Public: anyone can read this; the crew can change it.

Thought intake: a forge-level tell, from the composer, the API and the MCP, kept verbatim in an append-only ledger #805

Closed opened this in answer to
Closed without merging

mason/forge:mason/651-thought-intake-a-forge-level-tell-from-t → main 4 commits fork

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
19 files changed +664 −12
.scratch/forge-thoughts-COBx4h/forge.db added
Binary file not shown.
.scratch/forge-thoughts-COBx4h/forge.db-shm added
Binary file not shown.
.scratch/forge-thoughts-COBx4h/forge.db-wal added
Binary file not shown.
docs/FEED.md +20
@@ -50,6 +50,26 @@ client (etag, 304). A card: the reason as a link into the thing, Steer (run
5050 cards, posts to the run's `steer`) or Tell the crew (everything else, posts to
5151 the app's `tell`), Dismiss and Mute app (the interactions API, same-origin).
5252 Keys: `j`/`k`/Enter are the shell's, `x` dismisses the focused card.
53
54 Above the cards sits the composer: one box, a "To" picker and Send. "The
55 forge" is the default choice; every app the viewer can write follows, and
56 choosing one is that app's tell. A thought for the forge posts to
57 `/thoughts` and lands back on `/`, where the viewer's last three thoughts sit
58 on top of the feed as their own posts, verbatim and marked *received*.
59
60 ## Thoughts (`src/core/thoughts.ts`, `src/actions/thoughts.ts`)
61
62 A thought is what a person tells the forge itself, not one app. It is kept
63 exactly as typed (no trim, no cleaning; empty and repeated text are kept,
64 each its own row) in the `thought` table: author, text, source (`composer`,
65 `api`, `mcp`, `share`) and `received_at`. The table is append-only: there is
66 no update or delete in code, and its triggers refuse one from anywhere
67 (`test/thoughts.test.ts` proves both). It rides the database snapshot like
68 every other table. Each thought appends `thought.received { thought, source }`
69 to the outbox — the id, never the words — for triage to read.
70 Three doors: the composer, `POST /api/v1/thoughts { text }` (rw token or
71 same-origin session; 201 `{ id, received_at }`), and the MCP `tell` with no
72 `repo`. Agents are refused; a thought is a person's.
5373 Not yet: the `choose` deck card (nothing in the feed produces one), stop from
5474 a card, and paging past the first 20.
5575
docs/MCP.md +1 −1
@@ -28,7 +28,7 @@ for a tunnel and a forge that sleeps.
2828 | tool | does | writes |
2929 | -------------- | ------------------------------------------------------------------------------------------------- | ------ |
3030 | `apps` | the apps you can see: live or not, where served, how each runs itself, what is working | |
31 | `tell` | a sentence becomes an issue, a builder is picked, a run starts on the crew's next tick | yes |
31 | `tell` | a sentence becomes an issue, a builder is picked, a run starts on the crew's next tick; with no `repo`, a thought for the forge, kept verbatim (returns its id) | yes |
3232 | `say` | speak on an issue or a pull; a working builder hears it as its next step | yes |
3333 | `now` | what the crew is doing right now: who, on what, since when, at what cost; a planner that declined the direction and waits for you comes first (`run: null`, its words in `says`) | |
3434 | `stop` | stop one run by its id from `now` | yes |
scripts/gate.ts +1
@@ -123,6 +123,7 @@ export const GATE: readonly string[] = [
123123 "test/data-home.test.ts",
124124 "test/tree.test.ts",
125125 "test/reports.test.ts",
126 "test/thoughts.test.ts",
126127 "test/report-discovery.test.ts",
127128 "test/apps-report.test.ts",
128129 ];
src/actions/thoughts.ts added +43
@@ -0,0 +1,43 @@
1 /**
2 * A thought told to the forge (`core/thoughts.ts`): the composer with "the
3 * forge" chosen, `POST /api/v1/thoughts`, and the MCP `tell` with no
4 * repository all land here. Nothing typed is refused for what it says —
5 * empty and repeated text are kept — only for who says it (a person, never
6 * an agent) and for being past the bound. The thought and its
7 * `thought.received` event are written together; the event carries the id
8 * and the door, never the words, so the outbox's readers fetch the text
9 * through the table.
10 */
11
12 import type { App } from "../app.ts";
13 import {
14 insertThought,
15 THOUGHT_MAX,
16 type Thought,
17 type ThoughtSource,
18 } from "../core/thoughts.ts";
19 import type { User } from "../core/users.ts";
20 import { err, ok, type Result } from "../kernel/result.ts";
21
22 export type ThinkError = "unauthorized" | "forbidden" | "too_long";
23
24 export function tellForge(
25 app: App,
26 actor: User | undefined,
27 text: string,
28 source: ThoughtSource,
29 ): Result<Thought, ThinkError> {
30 if (!actor) return err("unauthorized");
31 if (actor.kind !== "user") return err("forbidden");
32 if (text.length > THOUGHT_MAX) return err("too_long");
33 const thought = app.db.transaction(() => {
34 const made = insertThought(app.db, { authorId: actor.id, text, source });
35 app.bus.append({
36 kind: "thought.received",
37 actorId: actor.id,
38 payload: { thought: made.id, source },
39 });
40 return made;
41 })();
42 return ok(thought);
43 }
src/core/reserved.ts +1
@@ -92,6 +92,7 @@ export const SYSTEM_NAMES: readonly string[] = [
9292 "theme",
9393 "www",
9494 "asked",
95 "thoughts",
9596 // the forge's own nouns, and the platform's name
9697 "user",
9798 "users",
src/core/schema.ts +18
@@ -1215,4 +1215,22 @@ export const migrations: readonly string[] = [
12151215 );
12161216 CREATE INDEX IF NOT EXISTS report_waiting ON report(repo_id, state, id);
12171217 `,
1218 // 48 — a thought (`core/thoughts.ts`): what a person said to the forge
1219 // itself, kept exactly as typed, forever. Append-only by trigger, so no
1220 // code path — present or future — can rewrite or drop one. No foreign
1221 // key on the author: a thought outlives whoever said it.
1222 `
1223 CREATE TABLE IF NOT EXISTS thought (
1224 id TEXT PRIMARY KEY,
1225 author_id TEXT NOT NULL,
1226 text TEXT NOT NULL,
1227 source TEXT NOT NULL CHECK (source IN ('composer','api','mcp','share')),
1228 received_at TEXT NOT NULL
1229 );
1230 CREATE INDEX IF NOT EXISTS thought_by_author ON thought(author_id, id);
1231 CREATE TRIGGER IF NOT EXISTS thought_never_updated BEFORE UPDATE ON thought
1232 BEGIN SELECT RAISE(ABORT, 'thoughts are append-only'); END;
1233 CREATE TRIGGER IF NOT EXISTS thought_never_deleted BEFORE DELETE ON thought
1234 BEGIN SELECT RAISE(ABORT, 'thoughts are append-only'); END;
1235 `,
12181236 ];
src/core/thoughts.ts added +86
@@ -0,0 +1,86 @@
1 /**
2 * Thoughts: what a person said to the forge itself, not to one app's crew.
3 * A thought is kept exactly as typed — no trim, no cleaning, empty and
4 * repeated text included — with who said it, through which door, and when.
5 * The table is append-only: this module has no update or delete, and the
6 * schema's triggers refuse one from anywhere else. Pure data, no authz, no
7 * events.
8 */
9
10 import type { Database } from "bun:sqlite";
11 import { id } from "../kernel/id.ts";
12
13 /** The doors a thought comes in by. */
14 export const THOUGHT_SOURCES = ["composer", "api", "mcp", "share"] as const;
15 export type ThoughtSource = (typeof THOUGHT_SOURCES)[number];
16
17 /** A bound on one thought, in characters: generous, never silent. */
18 export const THOUGHT_MAX = 20_000;
19
20 export interface Thought {
21 readonly id: string;
22 readonly authorId: string;
23 readonly text: string;
24 readonly source: ThoughtSource;
25 readonly receivedAt: string;
26 }
27
28 interface ThoughtRow {
29 id: string;
30 author_id: string;
31 text: string;
32 source: ThoughtSource;
33 received_at: string;
34 }
35
36 const fromRow = (row: ThoughtRow): Thought => ({
37 id: row.id,
38 authorId: row.author_id,
39 text: row.text,
40 source: row.source,
41 receivedAt: row.received_at,
42 });
43
44 export function insertThought(
45 db: Database,
46 input: { authorId: string; text: string; source: ThoughtSource },
47 ): Thought {
48 const thought: Thought = {
49 id: id(),
50 authorId: input.authorId,
51 text: input.text,
52 source: input.source,
53 receivedAt: new Date().toISOString(),
54 };
55 db.query(
56 "INSERT INTO thought (id, author_id, text, source, received_at) VALUES (?1, ?2, ?3, ?4, ?5)",
57 ).run(
58 thought.id,
59 thought.authorId,
60 thought.text,
61 thought.source,
62 thought.receivedAt,
63 );
64 return thought;
65 }
66
67 export function getThought(db: Database, thoughtId: string): Thought | undefined {
68 const row = db
69 .query<ThoughtRow, [string]>("SELECT * FROM thought WHERE id = ?1")
70 .get(thoughtId);
71 return row ? fromRow(row) : undefined;
72 }
73
74 /** One person's thoughts, newest first. */
75 export function listThoughtsBy(
76 db: Database,
77 authorId: string,
78 limit = 20,
79 ): Thought[] {
80 return db
81 .query<ThoughtRow, [string, number]>(
82 "SELECT * FROM thought WHERE author_id = ?1 ORDER BY id DESC LIMIT ?2",
83 )
84 .all(authorId, limit)
85 .map(fromRow);
86 }
src/http/feed.ts +26
@@ -4,6 +4,8 @@
44 */
55
66 import { tellCrew } from "../actions/crew.ts";
7 import { tellForge } from "../actions/thoughts.ts";
8 import { THOUGHT_MAX } from "../core/thoughts.ts";
79 import { audienceFilter } from "../core/event_audience.ts";
810 import { getEvent } from "../core/events.ts";
911 import {
@@ -121,6 +123,30 @@ export function feedRoutes(router: Router<Handler>): void {
121123 return json({ issue: told.value.issue.number }, 201);
122124 });
123125
126 // A thought for the forge itself, kept verbatim: empty and repeated text
127 // are stored like any other; only a text that is not a string is refused.
128 router.add("POST", "/api/v1/thoughts", async (ctx) => {
129 const denied = requireScope(ctx, "rw");
130 if (denied) return denied;
131 const input = await body(ctx.request);
132 const text = input.text ?? "";
133 if (typeof text !== "string" || text.length > THOUGHT_MAX)
134 return apiError(
135 "invalid_text",
136 422,
137 `text is a string of at most ${THOUGHT_MAX} characters`,
138 );
139 const kept = tellForge(ctx.app, ctx.auth.user, text, "api");
140 if (!kept.ok)
141 return kept.error === "forbidden"
142 ? apiError("forbidden", 403, "a thought is a person's")
143 : apiError("invalid_text", 422, "that could not be kept");
144 return json(
145 { id: kept.value.id, received_at: kept.value.receivedAt },
146 201,
147 );
148 });
149
124150 router.add("POST", "/api/v1/share", async (ctx) => {
125151 const denied = requireScope(ctx, "rw");
126152 if (denied) return denied;
src/http/mcp.ts +29 −3
@@ -28,6 +28,8 @@ import { openPlan, parsePlan, PLAN_MAX } from "../actions/plan.ts";
2828 import { cancelRepoRun } from "../actions/runs.ts";
2929 import { spawnDoor } from "../spawn/door.ts";
3030 import { tell, toldWords } from "../actions/tell.ts";
31 import { tellForge } from "../actions/thoughts.ts";
32 import { THOUGHT_MAX } from "../core/thoughts.ts";
3133 import {
3234 readUsage,
3335 usageDays,
@@ -174,14 +176,38 @@ const TOOLS: readonly Tool[] = [
174176 {
175177 name: "tell",
176178 description:
177 "Tell an app's crew what should change. One sentence or several; the first line becomes the title. A builder is picked and starts on the crew's next tick.",
179 "Tell an app's crew what should change, or — with no repo — tell the forge itself a thought, kept exactly as written. With a repo, the first line becomes the title and a builder is picked and starts on the crew's next tick.",
178180 inputSchema: {
179181 type: "object",
180 properties: { repo: REPO_ARG, text: { type: "string", maxLength: 8000 } },
181 required: ["repo", "text"],
182 properties: {
183 repo: {
184 ...REPO_ARG,
185 description:
186 "The app or repository, as owner/name. Leave it out to tell the forge.",
187 },
188 text: { type: "string", maxLength: THOUGHT_MAX },
189 },
190 required: ["text"],
182191 },
183192 writes: true,
184193 async run(ctx, user, args) {
194 if (args["repo"] === undefined || args["repo"] === "") {
195 const text = args["text"] ?? "";
196 if (typeof text !== "string") return bad("invalid_text", "text is a string");
197 const kept = tellForge(ctx.app, user, text, "mcp");
198 if (!kept.ok)
199 return bad(
200 kept.error,
201 kept.error === "too_long"
202 ? `a thought is at most ${THOUGHT_MAX} characters`
203 : "a thought is a person's",
204 );
205 return good({
206 says: "Received.",
207 thought: kept.value.id,
208 received_at: kept.value.receivedAt,
209 });
210 }
185211 const repo = repoArg(ctx, user, args);
186212 if (isAnswer(repo)) return repo;
187213 const told = await tell(ctx.app, user, repo, str(args["text"]));
src/http/server.ts +3
@@ -125,6 +125,7 @@ import {
125125 shipSubmit,
126126 takeBackSubmit,
127127 tellSubmit,
128 thoughtSubmit,
128129 } from "../web/studio/actions.ts";
129130 import { askedPage } from "../web/studio/asked_page.ts";
130131 import { asksPage } from "../web/studio/asks_page.ts";
@@ -448,6 +449,8 @@ export function buildRouter(): Router<Handler> {
448449 router.add("GET", "/asks", asksPage);
449450 // What people asked of the crew, and what became of it (core/asked.ts).
450451 router.add("GET", "/asked", askedPage);
452 // The home's composer: a thought for the forge, or a tell for one app.
453 router.add("POST", "/thoughts", thoughtSubmit);
451454 // The big view, folded into the board: every old address lands on its wall mode.
452455 router.add("GET", "/big", bigRedirect);
453456 router.add("GET", "/search", searchPage);
src/web/studio/actions.ts +56 −4
@@ -10,6 +10,9 @@
1010
1111 import { addComment, setIssueStateThrough } from "../../actions/issues.ts";
1212 import { tellCrew } from "../../actions/crew.ts";
13 import { tellForge } from "../../actions/thoughts.ts";
14 import { canRead, getRepo, type Repo } from "../../core/repos.ts";
15 import { THOUGHT_MAX } from "../../core/thoughts.ts";
1316 import { mergePull } from "../../actions/pulls.ts";
1417 import { revertPull, type RevertPullError } from "../../actions/revert.ts";
1518 import { getPull } from "../../core/pulls.ts";
@@ -45,23 +48,72 @@ export async function tellSubmit(ctx: Ctx): Promise<Response> {
4548 tone: "danger",
4649 message: "Say something first.",
4750 });
51 return tellAndSay(ctx, repo, text, base);
52 }
53
54 /** Tell an app's crew and land on `to` with what happened, in one sentence. */
55 async function tellAndSay(
56 ctx: Ctx,
57 repo: Repo,
58 text: string,
59 to: string,
60 ): Promise<Response> {
4861 const told = await tellCrew(ctx.app, ctx.auth.user, repo, text);
4962 if (!told.ok)
50 return flashTo(ctx, base, {
63 return flashTo(ctx, to, {
5164 tone: "danger",
5265 message: "That could not be told.",
5366 });
5467 const { routed } = told.value;
5568 if (routed === undefined)
56 return flashTo(ctx, base, {
69 return flashTo(ctx, to, {
5770 message: `Told. Nobody is on the crew to take it yet — add someone under Settings → Crew.`,
5871 });
5972 const builder = routed.builder;
60 return flashTo(ctx, base, {
61 message: `${builder.user.username} is on it — ${routed.size} ${routed.kind}${routed.by === "rule" ? "" : `, ${routed.by} decided in ${routed.ms} ms`}. Watch it work below.`,
73 return flashTo(ctx, to, {
74 message: `${builder.user.username} is on it — ${routed.size} ${routed.kind}${routed.by === "rule" ? "" : `, ${routed.by} decided in ${routed.ms} ms`}.${to === "/" ? "" : " Watch it work below."}`,
6275 });
6376 }
6477
78 /**
79 * POST /thoughts { text, app } — the home's composer. With "the forge"
80 * chosen (`app` empty) the text is a thought, kept exactly as typed, empty
81 * or repeated included; with an app chosen it is that app's tell, the same
82 * act as the app's own box.
83 */
84 export async function thoughtSubmit(ctx: Ctx): Promise<Response> {
85 if (!ctx.auth.user) return signInFirst(ctx);
86 const form = await readForm(ctx, "rw");
87 if (form instanceof Response) return form;
88 const text = field(form, "text");
89 const app = field(form, "app");
90 if (app !== "") {
91 const [owner, name, extra] = app.split("/");
92 const repo =
93 owner && name && extra === undefined
94 ? getRepo(ctx.app.db, owner, name)
95 : undefined;
96 if (!repo || !canRead(ctx.app.db, repo, ctx.auth.user))
97 return notFoundPage(ctx);
98 if (text.trim() === "")
99 return flashTo(ctx, "/", {
100 tone: "danger",
101 message: "Say something first.",
102 });
103 return tellAndSay(ctx, repo, text, "/");
104 }
105 const kept = tellForge(ctx.app, ctx.auth.user, text, "composer");
106 if (!kept.ok)
107 return flashTo(ctx, "/", {
108 tone: "danger",
109 message:
110 kept.error === "too_long"
111 ? `That is past ${THOUGHT_MAX} characters; nothing was kept. Split it in two.`
112 : "Only a person can tell the forge a thought.",
113 });
114 return flashTo(ctx, "/", { message: "Received." });
115 }
116
65117 /** POST /:owner/:name/pulls/:number/ship — land a green change. */
66118 export async function shipSubmit(ctx: Ctx): Promise<Response> {
67119 const repo = loadRepo(ctx);
src/web/studio/feed.ts +63 −2
@@ -7,6 +7,8 @@
77 * Every string on a card is plain text and is escaped here, once.
88 */
99
10 import type { Repo } from "../../core/repos.ts";
11 import { listThoughtsBy, THOUGHT_MAX, type Thought } from "../../core/thoughts.ts";
1012 import type { User } from "../../core/users.ts";
1113 import type { Ctx } from "../../http/context.ts";
1214 import { readFeed } from "../../feed/feed.ts";
@@ -14,7 +16,7 @@ import type { FeedItem } from "../../feed/rank.ts";
1416 import { html, type Html } from "../html.ts";
1517 import { fragment } from "../layout.ts";
1618 import { outboxJs } from "../outbox.ts";
17 import { btn, empty } from "../ui.ts";
19 import { badge, btn, empty, time } from "../ui.ts";
1820
1921 /** Events that can change what the feed says. */
2022 export const FEED_LIVE =
@@ -22,6 +24,9 @@ export const FEED_LIVE =
2224
2325 export const FEED_FIRST_PAGE = 20;
2426
27 /** How many of the viewer's own thoughts sit on top of the feed. */
28 export const FEED_THOUGHTS = 3;
29
2530 const RUN_LINK = /^\/[^/]+\/[^/]+\/runs\/[A-Za-z0-9_-]+$/;
2631
2732 const KIND_LABEL: Record<FeedItem["kind"], string> = {
@@ -63,6 +68,60 @@ export function feedCard(item: FeedItem): Html {
6368 </article>`;
6469 }
6570
71 /**
72 * The composer above the feed: one box, one choice of where it goes, one
73 * send. "The forge" is the default — a thought kept verbatim — and every
74 * app the viewer can write is the same tell as that app's own box. A plain
75 * form: it works with no script, and the page it lands on shows the post.
76 */
77 export function feedComposer(apps: readonly Repo[]): Html {
78 return html`<form method="post" action="/thoughts" class="fcard fcompose">
79 <textarea
80 name="text"
81 rows="2"
82 maxlength="${String(THOUGHT_MAX)}"
83 aria-label="What you are thinking"
84 placeholder="What are you thinking?"
85 ></textarea>
86 <div class="fcompose-bar">
87 <label class="small muted"
88 >To
89 <select name="app" aria-label="Where it goes">
90 <option value="" selected>the forge</option>
91 ${apps.map(
92 (r) =>
93 html`<option value="${r.ownerName}/${r.name}">
94 ${r.ownerName}/${r.name}
95 </option>`,
96 )}
97 </select></label
98 >
99 <span class="spacer"></span>
100 ${btn("Send", { size: "sm", variant: "primary" })}
101 </div>
102 </form>`;
103 }
104
105 /** One of the viewer's own thoughts, as it was typed, marked received. */
106 export function thoughtPost(thought: Thought, author: string): Html {
107 return html`<article
108 class="fcard fpost"
109 data-item="thought:${thought.id}"
110 data-kind="thought"
111 >
112 <div class="fcard-head">
113 <span class="badge">You</span>
114 <span class="fcard-app muted small">to the forge · ${author}</span>
115 <span class="spacer"></span>
116 ${badge("received", { tone: "success" })}
117 <span class="muted small">${time(thought.receivedAt)}</span>
118 </div>
119 ${thought.text === ""
120 ? html`<p class="fpost-text muted">(nothing typed)</p>`
121 : html`<p class="fpost-text">${thought.text}</p>`}
122 </article>`;
123 }
124
66125 /**
67126 * One line above the feed, empty unless there is something to say: the feed
68127 * on screen is old (the service worker served it with no network), or acts
@@ -82,6 +141,7 @@ export function feedNote(): Html {
82141 /** The region: cards, or one line saying there is nothing to do. */
83142 export function feedRegion(user: User, ctx: Ctx): Html {
84143 const { items } = readFeed(ctx.app.db, user, { limit: FEED_FIRST_PAGE });
144 const thoughts = listThoughtsBy(ctx.app.db, user.id, FEED_THOUGHTS);
85145 return html`<section
86146 id="live-feed"
87147 class="feed"
@@ -89,7 +149,8 @@ export function feedRegion(user: User, ctx: Ctx): Html {
89149 data-live="${FEED_LIVE}"
90150 data-live-src="/live/feed"
91151 >
92 ${items.length === 0
152 ${thoughts.map((t) => thoughtPost(t, user.username))}
153 ${items.length === 0 && thoughts.length === 0
93154 ? empty({
94155 icon: "activity",
95156 title: "Nothing new",
src/web/studio/feed_style.ts +5
@@ -10,6 +10,11 @@ export const feedCss = /* css */ `
1010 .fcard-say summary { cursor: pointer; color: var(--muted-fg, inherit); padding: 4px 0; }
1111 .fcard-form { display: grid; gap: 8px; margin-top: 6px; }
1212 .fcard-form textarea { width: 100%; min-height: 56px; resize: vertical; }
13 .fcompose { display: grid; gap: 8px; }
14 .fcompose textarea { width: 100%; min-height: 56px; resize: vertical; }
15 .fcompose-bar { display: flex; align-items: center; gap: 8px; flex-wrap: wrap; }
16 .fcompose select { max-width: 60vw; }
17 .fpost-text { margin: 8px 0 4px; white-space: pre-wrap; overflow-wrap: anywhere; }
1318 @media (max-width: 600px) {
1419 .fcard { padding: 12px; }
1520 .fcard-head .btn { padding: 8px 10px; }
src/web/studio/home.ts +2 −1
@@ -28,7 +28,7 @@ import { lookUrl, pictured } from "../pages/looks.ts";
2828 import { writableAppsOf } from "./asks.ts";
2929 import { productionFactsForRepos, shelfRows } from "./shelf.ts";
3030 import { servingHistory } from "./words.ts";
31 import { feedJs, feedNote, feedRegion } from "./feed.ts";
31 import { feedComposer, feedJs, feedNote, feedRegion } from "./feed.ts";
3232
3333 /** The events that can change a row on the shelf. */
3434 const APPS_LIVE =
@@ -157,6 +157,7 @@ export async function studioHome(ctx: Ctx, user: User): Promise<Response> {
157157 <span class="spacer"></span>
158158 <a class="small muted" href="/asked">What you asked for</a>
159159 </div>
160 ${feedComposer(appRepos)}
160161 ${feedNote()}
161162 ${feedRegion(user, ctx)}
162163 ${appsRegion(apps)}
test/mcp.test.ts +2 −1
@@ -178,7 +178,8 @@ describe("the forge over MCP", () => {
178178 listed.body.result.tools.map((t: any) => [t.name, t]),
179179 );
180180 expect(byName.get("tell").annotations.readOnlyHint).toBe(false);
181 expect(byName.get("tell").inputSchema.required).toEqual(["repo", "text"]);
181 // With no repo, `tell` is a thought for the forge (#651): only the text is required.
182 expect(byName.get("tell").inputSchema.required).toEqual(["text"]);
182183
183184 expect((await call(rw, "nothing/here")).body.error.code).toBe(-32601);
184185 expect(
test/thoughts.test.ts added +308
@@ -0,0 +1,308 @@
1 /**
2 * Thoughts: what a person tells the forge itself, through the composer, the
3 * API and the MCP, kept exactly as typed in a ledger nothing can rewrite.
4 * Proven at the protocol level: each door stores the text byte for byte
5 * with its source, empty and repeated text are kept, the table refuses an
6 * update or a delete from anywhere, and the thought reaches the feed and
7 * the outbox.
8 */
9 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
10 import { readdir, readFile, mkdtemp, rm } from "node:fs/promises";
11 import { tmpdir } from "node:os";
12 import { join } from "node:path";
13 import { Database } from "bun:sqlite";
14 import { createAgent } from "../src/actions/crew.ts";
15 import { createRepo } from "../src/actions/repos.ts";
16 import { tellForge } from "../src/actions/thoughts.ts";
17 import { createApp, type App } from "../src/app.ts";
18 import { createApp as insertApp } from "../src/core/apps.ts";
19 import { listEvents } from "../src/core/events.ts";
20 import {
21 getThought,
22 listThoughtsBy,
23 THOUGHT_MAX,
24 THOUGHT_SOURCES,
25 } from "../src/core/thoughts.ts";
26 import { createToken } from "../src/core/tokens.ts";
27 import { createUser, type User } from "../src/core/users.ts";
28 import { serve, type Servers } from "../src/http/server.ts";
29
30 /** Text a cleaner would mangle: edges, CRLF, tabs, a bidi mark, emoji, markup. */
31 const AWKWARD =
32 " leading and trailing \r\nline two\twith a tab\n‮bidi‬ 🧵 <b>&amp;</b> `code` *not markdown*\n\n";
33
34 describe("thoughts", () => {
35 let dataDir: string;
36 let app: App;
37 let servers: Servers;
38 let base: string;
39 let alice: User;
40 let aliceRw: string;
41 let aliceRo: string;
42 let botRw: string;
43 let nextId = 1;
44
45 beforeAll(async () => {
46 dataDir = await mkdtemp(join(tmpdir(), "forge-thoughts-"));
47 app = createApp({ dataDir, port: 0 });
48 servers = await serve(app);
49 base = servers.url;
50 const a = await createUser(app.db, {
51 username: "alice",
52 email: "[email protected]",
53 password: "a-good-passphrase",
54 adminIfFirst: true,
55 });
56 if (!a.ok) throw new Error(a.error);
57 alice = a.value;
58 const made = await createRepo(app, alice, { name: "garden" });
59 if (!made.ok) throw new Error(String(made.error));
60 const garden = insertApp(app.db, {
61 repoId: made.value.id,
62 slug: "garden",
63 access: "private",
64 });
65 if (!garden.ok) throw new Error(garden.error);
66 const bot = await createAgent(app, alice, { username: "bot" });
67 if (!bot.ok) throw new Error(String(bot.error));
68 aliceRw = createToken(app.db, alice.id, "t", "rw").token;
69 aliceRo = createToken(app.db, alice.id, "r", "ro").token;
70 botRw = createToken(app.db, bot.value.user.id, "run", "rw").token;
71 });
72 afterAll(async () => {
73 servers.stop();
74 app.close();
75 await rm(dataDir, { recursive: true, force: true });
76 });
77
78 const api = (token: string, payload: unknown) =>
79 fetch(`${base}/api/v1/thoughts`, {
80 method: "POST",
81 headers: {
82 "content-type": "application/json",
83 authorization: `Bearer ${token}`,
84 },
85 body: JSON.stringify(payload),
86 });
87
88 const mcpTell = async (token: string, args: unknown) => {
89 const res = await fetch(`${base}/mcp`, {
90 method: "POST",
91 headers: {
92 "content-type": "application/json",
93 accept: "application/json, text/event-stream",
94 authorization: `Bearer ${token}`,
95 },
96 body: JSON.stringify({
97 jsonrpc: "2.0",
98 id: nextId++,
99 method: "tools/call",
100 params: { name: "tell", arguments: args },
101 }),
102 });
103 const body = (await res.json()) as any;
104 const text: string = body.result.content[0].text;
105 return body.result.isError === true
106 ? { error: text }
107 : { value: JSON.parse(text) };
108 };
109
110 let cookie = "";
111 const signIn = async () => {
112 if (cookie !== "") return cookie;
113 const res = await fetch(`${base}/signin`, {
114 method: "POST",
115 body: new URLSearchParams({
116 username: "alice",
117 password: "a-good-passphrase",
118 }),
119 redirect: "manual",
120 });
121 cookie = (res.headers.get("set-cookie") ?? "").split(";")[0]!;
122 return cookie;
123 };
124 const compose = async (fields: Record<string, string>, origin = base) =>
125 fetch(`${base}/thoughts`, {
126 method: "POST",
127 headers: { cookie: await signIn(), origin },
128 body: new URLSearchParams(fields),
129 redirect: "manual",
130 });
131
132 const count = (): number =>
133 (app.db.query("SELECT count(*) AS n FROM thought").get() as { n: number })
134 .n;
135
136 test("the API keeps the text byte for byte, with its source", async () => {
137 const res = await api(aliceRw, { text: AWKWARD });
138 expect(res.status).toBe(201);
139 const { id } = (await res.json()) as { id: string };
140 const kept = getThought(app.db, id)!;
141 expect(kept.text).toBe(AWKWARD);
142 expect(kept.source).toBe("api");
143 expect(kept.authorId).toBe(alice.id);
144 expect(Number.isNaN(Date.parse(kept.receivedAt))).toBe(false);
145 });
146
147 test("empty and repeated text are kept, each as its own thought", async () => {
148 const before = count();
149 for (const payload of [{ text: "" }, {}, { text: "again" }, { text: "again" }]) {
150 expect((await api(aliceRw, payload)).status).toBe(201);
151 }
152 expect(count()).toBe(before + 4);
153 const [last, prev, empty1, empty2] = listThoughtsBy(app.db, alice.id, 4);
154 expect([last!.text, prev!.text, empty1!.text, empty2!.text]).toEqual([
155 "again",
156 "again",
157 "",
158 "",
159 ]);
160 expect(last!.id).not.toBe(prev!.id);
161 });
162
163 test("the API refuses what is not a string, past the bound, read-only, an agent, a stranger", async () => {
164 const before = count();
165 expect((await api(aliceRw, { text: 42 })).status).toBe(422);
166 expect((await api(aliceRw, { text: "x".repeat(THOUGHT_MAX + 1) })).status).toBe(422);
167 expect((await api(aliceRo, { text: "hi" })).status).toBe(403);
168 expect((await api(botRw, { text: "hi" })).status).toBe(403);
169 const stranger = await fetch(`${base}/api/v1/thoughts`, {
170 method: "POST",
171 headers: { "content-type": "application/json" },
172 body: JSON.stringify({ text: "hi" }),
173 });
174 expect(stranger.status).toBe(401);
175 expect(count()).toBe(before);
176 // At the bound exactly is kept.
177 expect((await api(aliceRw, { text: "y".repeat(THOUGHT_MAX) })).status).toBe(201);
178 });
179
180 test("the MCP tell with no repo writes a thought and returns its id", async () => {
181 const told = await mcpTell(aliceRw, { text: AWKWARD });
182 expect(told.value.thought).toBeString();
183 const kept = getThought(app.db, told.value.thought)!;
184 expect(kept.text).toBe(AWKWARD);
185 expect(kept.source).toBe("mcp");
186 const blank = await mcpTell(aliceRw, { text: "" });
187 expect(getThought(app.db, blank.value.thought)!.text).toBe("");
188 // An agent's tell to the forge is refused; nothing is kept.
189 const before = count();
190 expect((await mcpTell(botRw, { text: "hi" })).error).toBeDefined();
191 expect((await mcpTell(aliceRo, { text: "hi" })).error).toContain("forbidden");
192 expect(count()).toBe(before);
193 // With a repo, it is still that app's tell, not a thought.
194 const issue = await mcpTell(aliceRw, { repo: "alice/garden", text: "Plant beans" });
195 expect(issue.value.issue).toBe(1);
196 expect(count()).toBe(before);
197 });
198
199 test("the composer with the forge chosen keeps the thought and shows it on the feed", async () => {
200 const res = await compose({ app: "", text: AWKWARD });
201 expect(res.status).toBe(303);
202 expect(res.headers.get("location")).toStartWith("/");
203 const [kept] = listThoughtsBy(app.db, alice.id, 1);
204 expect(kept!.text).toBe(AWKWARD);
205 expect(kept!.source).toBe("composer");
206
207 const home = await (
208 await fetch(`${base}/`, { headers: { cookie: await signIn() } })
209 ).text();
210 // The composer: "the forge" first and chosen, then the apps she writes.
211 expect(home).toContain('action="/thoughts"');
212 expect(home).toMatch(/<option value="" selected>the forge<\/option>/);
213 expect(home).toContain('value="alice/garden"');
214 // The post, verbatim and escaped, marked received, above the feed's cards.
215 const post = home.indexOf(`data-item="thought:${kept!.id}"`);
216 expect(post).toBeGreaterThan(-1);
217 expect(home).toContain("received");
218 expect(home).toContain("&lt;b&gt;&amp;amp;&lt;/b&gt;");
219 expect(home).not.toContain("<b>&amp;</b>");
220 });
221
222 test("the composer with an app chosen tells that app; another origin is refused", async () => {
223 const before = count();
224 const res = await compose({ app: "alice/garden", text: "Water the beans" });
225 expect(res.status).toBe(303);
226 expect(count()).toBe(before);
227 const title = app.db
228 .query("SELECT title FROM issue WHERE title = 'Water the beans'")
229 .get() as { title: string } | null;
230 expect(title?.title).toBe("Water the beans");
231 const crossSite = await compose({ app: "", text: "hi" }, "https://evil.example");
232 expect(crossSite.status).toBe(403);
233 expect(count()).toBe(before);
234 const elsewhere = await compose({ app: "alice/nothing", text: "hi" });
235 expect(elsewhere.status).toBe(404);
236 });
237
238 test("each source is a source the table knows", () => {
239 for (const source of THOUGHT_SOURCES) {
240 const made = tellForge(app, alice, `from ${source}`, source);
241 expect(made.ok).toBe(true);
242 if (made.ok) expect(getThought(app.db, made.value.id)!.source).toBe(source);
243 }
244 expect(() =>
245 app.db
246 .query(
247 "INSERT INTO thought (id, author_id, text, source, received_at) VALUES ('x', ?1, 't', 'smoke', 'now')",
248 )
249 .run(alice.id),
250 ).toThrow();
251 });
252
253 test("every thought rides the outbox as thought.received, with its id and never its words", () => {
254 const made = tellForge(app, alice, "a secret plan", "api");
255 if (!made.ok) throw new Error(made.error);
256 const events = listEvents(app.db, { kind: "thought.received", limit: 500 });
257 const mine = events.find((e) => e.payload.thought === made.value.id);
258 expect(mine).toBeDefined();
259 expect(mine!.actorId).toBe(alice.id);
260 expect(mine!.repoId).toBeNull();
261 expect(mine!.payload.source).toBe("api");
262 expect(JSON.stringify(mine!.payload)).not.toContain("secret plan");
263 expect(events.length).toBe(count());
264 });
265
266 test("append-only: the table refuses an update and a delete, and no code writes one", async () => {
267 const [kept] = listThoughtsBy(app.db, alice.id, 1);
268 expect(() =>
269 app.db.query("UPDATE thought SET text = 'rewritten' WHERE id = ?1").run(kept!.id),
270 ).toThrow(/append-only/);
271 expect(() =>
272 app.db.query("DELETE FROM thought WHERE id = ?1").run(kept!.id),
273 ).toThrow(/append-only/);
274 expect(getThought(app.db, kept!.id)!.text).toBe(kept!.text);
275
276 // No path in the source names an update or a delete of the table.
277 const offenders: string[] = [];
278 const walk = async (dir: string): Promise<void> => {
279 for (const entry of await readdir(dir, { withFileTypes: true })) {
280 const path = join(dir, entry.name);
281 if (entry.isDirectory()) await walk(path);
282 else if (entry.name.endsWith(".ts")) {
283 const text = await readFile(path, "utf8");
284 if (/UPDATE\s+thought\b|DELETE\s+FROM\s+thought\b|DROP\s+TABLE\s+(IF\s+EXISTS\s+)?thought\b/i.test(text))
285 offenders.push(path);
286 }
287 }
288 };
289 await walk(join(import.meta.dir, "..", "src"));
290 expect(offenders).toEqual([]);
291 });
292
293 test("the backup copy of the database carries every thought", () => {
294 const copy = join(dataDir, "backup-check.db");
295 app.db.run("VACUUM INTO ?1", [copy]);
296 const restored = new Database(copy, { readonly: true });
297 try {
298 const n = (restored.query("SELECT count(*) AS n FROM thought").get() as { n: number }).n;
299 expect(n).toBe(count());
300 const row = restored
301 .query("SELECT text FROM thought WHERE source = 'mcp' ORDER BY id LIMIT 1")
302 .get() as { text: string };
303 expect(row.text).toBe(AWKWARD);
304 } finally {
305 restored.close();
306 }
307 });
308 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs