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 #1633

Closed opened this
Closed without merging

scout/forge:scout/1060-thought-intake-a-forge-level-tell-from-t → main 13 commits fork 2 threads · 2 unresolved

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
15 files changed +590 −25
README.md +13
@@ -322,6 +322,19 @@ agent yourself already does. `FORGE_APP_PLAN=0` turns it off; so does having
322322 no `claude` on `PATH` — either way **Pick for me** stops being offered and
323323 `New app` behaves exactly as it did before this existed.
324324
325 ## Thoughts
326
327 A thought is a tell to the forge itself, not to an app: kept exactly as typed
328 (whitespace and repeats included, up to 20,000 characters) in an append-only
329 ledger that triggers refuse to change or delete, with its time and source.
330 Only its author sees it. Four doors, one author each (the session or token):
331 the home composer's **the forge (no app)** choice, `POST /api/v1/thoughts`
332 with `{"text": "…"}` (a write token; answers `201` with the id), MCP
333 `tell` with no `repo`, and `t` on the terminal's launcher (signed in).
334 A token's requests, thoughts included, count against its per-minute
335 limit. Tells to an app are unchanged (the composer stops them at 2,000
336 characters). See `docs/FEED.md`.
337
325338 ## The crew
326339
327340 In a preview (`FORGE_APP_ENV=preview`, which the platform sets) the crew is
docs/FEED.md +20
@@ -135,3 +135,23 @@ one `POST /api/v1/asks/bulk` (`action`, `items`, `reason`, `preview: false`);
135135 swaps in place and the top bar's count follows. One undo link
136136 (`POST /api/v1/asks/bulk/<id>/undo`) is kept for a day. The MCP's `asks_act`
137137 takes the same set, verb and reason.
138
139 ## Thoughts (#1060)
140
141 A thought is what the owner says to the forge itself, belonging to no
142 repository. It is kept in the `thought` table (id, author, text, source,
143 `received_at`) exactly as typed: not trimmed, not deduplicated, an empty one
144 too, up to 20,000 characters. The table is append-only — triggers refuse an
145 `UPDATE` or `DELETE`, and no code path attempts one. It lives in `forge.db`,
146 so every backup carries it. Three doors, one function (`recordThought`):
147
148 - the composer's picker, "the forge (no app)" (value `-`), through the outbox
149 to `POST /api/v1/feed/tells { app: "-", text }`, or `POST /tell` without a
150 script — source `composer`;
151 - `POST /api/v1/thoughts { text }` (rw) — source `api`;
152 - the MCP `tell { text }` with no `repo` — source `mcp`, returns the id.
153
154 Each appends a `thought.received` event (the id and source, never the words)
155 for triage, and shows in the author's feed — theirs alone — as a "Received"
156 post in their own words, with no tell, mute or dismiss. `share` is reserved
157 as a source for a later door.
scripts/gate.ts +1
@@ -211,6 +211,7 @@ export const GATE: readonly string[] = [
211211 "test/reaches.test.ts",
212212 "test/milestones.test.ts",
213213 "test/mcp.test.ts",
214 "test/thoughts.test.ts",
214215 "test/name-marks.test.ts",
215216 "test/new-forge.test.ts",
216217 "test/notify.test.ts",
src/core/schema.ts +23
@@ -1631,6 +1631,29 @@ export const migrations: readonly string[] = [
16311631 scopes TEXT NOT NULL
16321632 );
16331633 `,
1634 // 78 — the thought ledger (#1060): what the owner said to the forge
1635 // itself, verbatim, with its source and time. Append-only: the database
1636 // refuses an UPDATE or a DELETE, so no code path can rewrite a thought.
1637 // `author_id` is not a foreign key: removing an account must not be able
1638 // to fail on, or erase, what it once said.
1639 `
1640 CREATE TABLE thought (
1641 id TEXT PRIMARY KEY,
1642 author_id TEXT NOT NULL,
1643 text TEXT NOT NULL,
1644 source TEXT NOT NULL CHECK (source IN ('composer', 'api', 'mcp', 'share', 'terminal')),
1645 received_at TEXT NOT NULL
1646 );
1647 CREATE INDEX thought_author ON thought (author_id, received_at DESC);
1648 CREATE TRIGGER thought_no_update BEFORE UPDATE ON thought
1649 BEGIN
1650 SELECT RAISE(ABORT, 'a thought is never changed');
1651 END;
1652 CREATE TRIGGER thought_no_delete BEFORE DELETE ON thought
1653 BEGIN
1654 SELECT RAISE(ABORT, 'a thought is never deleted');
1655 END;
1656 `,
16341657 ];
16351658
16361659 /**
src/core/thoughts.ts added +90
@@ -0,0 +1,90 @@
1 /**
2 * The thought ledger: what the owner said to the forge itself, kept exactly
3 * as typed with its source and time. Append-only — there is no function here
4 * that changes or removes a row, and the table refuses it too (migration 78).
5 * Nothing is trimmed, deduplicated or refused for being empty: a repeat is
6 * the repeats issue's to notice, never the ledger's to drop.
7 */
8
9 import type { Database } from "bun:sqlite";
10 import type { EventBus } from "./events.ts";
11 import { id } from "../kernel/id.ts";
12
13 export const THOUGHT_SOURCES = ["composer", "api", "mcp", "share", "terminal"] as const;
14 export type ThoughtSource = (typeof THOUGHT_SOURCES)[number];
15
16 /** The most one thought may hold; past it the door says so rather than cut it. */
17 export const THOUGHT_MAX = 20_000;
18
19 export interface Thought {
20 readonly id: string;
21 readonly authorId: string;
22 /** Verbatim: not trimmed, not normalised. */
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 toThought = (r: ThoughtRow): Thought => ({
37 id: r.id,
38 authorId: r.author_id,
39 text: r.text,
40 source: r.source,
41 receivedAt: r.received_at,
42 });
43
44 /** Whether `text` may be kept: a string within the ceiling (empty is fine). */
45 export const thoughtFits = (text: unknown): text is string =>
46 typeof text === "string" && text.length <= THOUGHT_MAX;
47
48 /** Keep one thought and announce it on the outbox for triage. */
49 export function recordThought(
50 db: Database,
51 bus: EventBus,
52 input: { authorId: string; text: string; source: ThoughtSource },
53 ): Thought {
54 const thought: Thought = {
55 id: id(),
56 authorId: input.authorId,
57 text: input.text,
58 source: input.source,
59 receivedAt: new Date().toISOString(),
60 };
61 db.query(
62 "INSERT INTO thought (id, author_id, text, source, received_at) VALUES (?1, ?2, ?3, ?4, ?5)",
63 ).run(
64 thought.id,
65 thought.authorId,
66 thought.text,
67 thought.source,
68 thought.receivedAt,
69 );
70 bus.append({
71 kind: "thought.received",
72 actorId: thought.authorId,
73 payload: { thoughtId: thought.id, source: thought.source },
74 });
75 return thought;
76 }
77
78 /** An author's newest thoughts first. */
79 export function listThoughts(
80 db: Database,
81 authorId: string,
82 limit = 20,
83 ): Thought[] {
84 return db
85 .query<ThoughtRow, [string, number]>(
86 "SELECT * FROM thought WHERE author_id = ?1 ORDER BY received_at DESC, id DESC LIMIT ?2",
87 )
88 .all(authorId, limit)
89 .map(toThought);
90 }
src/feed/items.ts +27
@@ -16,6 +16,7 @@ import {
1616 listOrigins,
1717 mirrorsByOrigin,
1818 } from "../core/origins.ts";
19 import { listThoughts } from "../core/thoughts.ts";
1920 import { getPull, toldBy } from "../core/pulls.ts";
2021 import {
2122 canSeeOwnerFacts,
@@ -39,6 +40,7 @@ export type FeedKind =
3940 | "tell"
4041 | "reply"
4142 | "look"
43 | "thought"
4244 | "milestone";
4345
4446 /** What a candidate is, before it is ranked and worded. */
@@ -88,6 +90,30 @@ const LANDED_URGENCY = 4;
8890 /** Something of the viewer's has stopped and only they can start it: a failure's weight. */
8991 const FROZEN_URGENCY = 4;
9092
93 /** A thought belongs to no repository: `repoId` is empty and `app` is the forge. */
94 export const FORGE_APP = "the forge";
95 const THOUGHT_URGENCY = 3;
96
97 /**
98 * The viewer's own thoughts, in their own words and whole: a post marked
99 * received, at the top while it is new. Only the author ever sees one.
100 */
101 function thoughtCandidates(db: Database, viewer: User): Candidate[] {
102 return listThoughts(db, viewer.id, 20).map((t) => ({
103 id: `thought:${t.id}`,
104 kind: "thought",
105 repoId: "",
106 app: FORGE_APP,
107 actorId: viewer.id,
108 actor: viewer.username,
109 at: t.receivedAt,
110 link: "/",
111 what: t.text,
112 said: t.text,
113 urgency: THOUGHT_URGENCY,
114 }));
115 }
116
91117 /**
92118 * What the viewer watches (`core/watches.ts`), one item for each milestone:
93119 * how far it is and what merged since they last opened it, or that it
@@ -254,6 +280,7 @@ export function candidatesFor(
254280 },
255281 });
256282 }
283 out.push(...thoughtCandidates(db, viewer));
257284 out.push(...watchedCandidates(db, viewer, now));
258285 out.push(...frozenCandidates(db, viewer, now));
259286 for (const d of decided) {
src/http/feed.ts +31
@@ -12,6 +12,8 @@ import {
1212 isInteractionKind,
1313 recordInteraction,
1414 } from "../core/interactions.ts";
15 import { recordThought, THOUGHT_MAX, thoughtFits } from "../core/thoughts.ts";
16 import { FORGE_CHOICE } from "../web/studio/feed.ts";
1517 import { share, RECIPIENTS_MAX } from "../feed/share.ts";
1618 import { canRead, getRepo, getRepoById } from "../core/repos.ts";
1719 import {
@@ -151,6 +153,17 @@ export function feedRoutes(router: Router<Handler>): void {
151153 if (denied) return denied;
152154 const viewer = ctx.auth.user!;
153155 const input = await body(ctx.request);
156 // "the forge" in the composer's picker: a thought, kept as typed.
157 if (input.app === FORGE_CHOICE) {
158 if (!thoughtFits(input.text))
159 return apiError("invalid_text", 422, `text is at most ${THOUGHT_MAX} characters`);
160 const kept = recordThought(ctx.app.db, ctx.app.bus, {
161 authorId: viewer.id,
162 text: input.text,
163 source: "composer",
164 });
165 return json({ thought: kept.id }, 201);
166 }
154167 const text = str(input.text).trim();
155168 if (text === "" || text.length > 2000)
156169 return apiError("invalid_text", 422, "text is 1 to 2000 characters");
@@ -170,6 +183,24 @@ export function feedRoutes(router: Router<Handler>): void {
170183 return json({ issue: told.value.issue.number }, 201);
171184 });
172185
186 // A thought to the forge itself: no repository, kept verbatim (#1060).
187 router.add("POST", "/api/v1/thoughts", async (ctx) => {
188 const denied = requireScope(ctx, "rw");
189 if (denied) return denied;
190 const input = await body(ctx.request);
191 if (!thoughtFits(input.text))
192 return apiError("invalid_text", 422, `text is a string of at most ${THOUGHT_MAX} characters`);
193 const kept = recordThought(ctx.app.db, ctx.app.bus, {
194 authorId: ctx.auth.user!.id,
195 text: input.text,
196 source: "api",
197 });
198 return json(
199 { id: kept.id, source: kept.source, received_at: kept.receivedAt },
200 201,
201 );
202 });
203
173204 router.add("POST", "/api/v1/share", async (ctx) => {
174205 const denied = requireScope(ctx, "rw");
175206 if (denied) return denied;
src/http/mcp.ts +18 −4
@@ -39,6 +39,8 @@ import { openPlan, parsePlan, PLAN_MAX } from "../actions/plan.ts";
3939 import { cancelRepoRun } from "../actions/runs.ts";
4040 import { clientRows } from "../spawn/clients.ts";
4141 import { reissueDoor, spawnDoor } from "../spawn/door.ts";
42 import { MAX_BODY } from "../core/issues.ts";
43 import { recordThought, THOUGHT_MAX, thoughtFits } from "../core/thoughts.ts";
4244 import { contextNote, parseContext } from "../actions/tell_context.ts";
4345 import {
4446 CARD_KINDS,
@@ -295,12 +297,12 @@ const TOOLS: readonly Tool[] = [
295297 {
296298 name: "tell",
297299 description:
298 "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.",
300 `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. With no repo it is a thought for the forge itself: kept exactly as given, with its time and source, and the answer is its id. A thought is at most ${THOUGHT_MAX} characters; a tell to an app, ${MAX_BODY}.`,
299301 inputSchema: {
300302 type: "object",
301303 properties: {
302304 repo: REPO_ARG,
303 text: { type: "string", maxLength: 8000 },
305 text: { type: "string" },
outdated

Low: this maxLength (MAX_BODY = 65,536) is wrong for a thought, which allows only THOUGHT_MAX = 20,000. A schema-driven client will send text this server then refuses.

304306 context: {
305307 type: "object",
306308 description:
@@ -313,10 +315,20 @@ const TOOLS: readonly Tool[] = [
313315 },
314316 },
315317 },
316 required: ["repo", "text"],
318 required: ["text"],
317319 },
318320 writes: true,
319321 async run(ctx, user, args) {
322 if (args["repo"] === undefined || args["repo"] === null) {
323 const text = args["text"];
324 if (!thoughtFits(text)) return bad("invalid_text", `text is a string of at most ${THOUGHT_MAX} characters`);
325 const kept = recordThought(ctx.app.db, ctx.app.bus, {
326 authorId: user.id,
327 text,
328 source: "mcp",
329 });
330 return good({ thought: kept.id, received_at: kept.receivedAt });
331 }
320332 const repo = repoArg(ctx, user, args);
321333 if (isAnswer(repo)) return repo;
322334 const where = parseContext(args["context"]);
@@ -338,7 +350,9 @@ const TOOLS: readonly Tool[] = [
338350 told.error,
339351 told.error === "empty"
340352 ? "say something first"
341 : told.error === "forbidden"
353 : told.error === "body_too_long"
354 ? `text is at most ${MAX_BODY} characters`
355 : told.error === "forbidden"
342356 ? DIRECTION_NOTE
343357 : told.error === "unverified"
344358 ? UNVERIFIED_WORDS
src/tui/screens/dashboard.ts +6
@@ -65,6 +65,7 @@ import {
6565 promptScreen,
6666 plural,
6767 } from "./common.ts";
68 import { tellForge } from "./thought.ts";
6869 import { issueScreen } from "./issue.ts";
6970 import { newRepoScreen } from "./newrepo.ts";
7071 import { pullScreen } from "./pull.ts";
@@ -397,6 +398,7 @@ export function dashboardScreen(f: Session, ctx: Ctx): Screen {
397398 disabled: focus !== "machine" || pins.length === 0,
398399 }),
399400 binding(["n"], "new repo", { disabled: !f.signedIn }),
401 binding(["t"], "tell the forge", { disabled: !f.signedIn }),
400402 binding(["A"], "account", { disabled: !f.signedIn }),
401403 binding(["s"], "sign in", { disabled: f.signedIn }),
402404 binding(["r"], "refresh"),
@@ -526,6 +528,10 @@ export function dashboardScreen(f: Session, ctx: Ctx): Screen {
526528 ctx.push(newRepoScreen(f, ctx));
527529 return true;
528530 }
531 if (e.key === "t" && !e.ctrl && !e.alt && f.user) {
532 tellForge(f, ctx, screen);
533 return true;
534 }
529535 if (e.key === "A" && f.user) {
530536 openOnWeb(f, ctx, "/settings", "Account settings");
531537 return true;
src/tui/screens/thought.ts added +34
@@ -0,0 +1,34 @@
1 /**
2 * `t` on the launcher: say something to the forge itself. The same
3 * `recordThought` the page, the API and the MCP use, with the identity the
4 * SSH connection proved; the words are kept exactly as typed.
5 */
6
7 import { recordThought, thoughtFits, THOUGHT_MAX } from "../../core/thoughts.ts";
8 import type { Ctx, Screen } from "../app/app.ts";
9 import type { Session } from "../session.ts";
10 import { promptScreen } from "./common.ts";
11
12 export function tellForge(f: Session, ctx: Ctx, parent: Screen): void {
13 ctx.push(
14 promptScreen(ctx, parent, {
15 title: "Tell the forge",
16 label: "Thought",
17 hint: "Kept exactly as typed; only you see it.",
18 onSubmit: (value) => {
19 const user = f.user;
20 if (user === undefined) return "sign in to tell the forge";
21 if (value === "") return "write something to tell the forge";
22 if (!thoughtFits(value))
23 return `at most ${THOUGHT_MAX} characters`;
24 recordThought(f.app.db, f.app.bus, {
25 authorId: user.id,
26 text: value,
27 source: "terminal",
28 });
29 ctx.toast("kept", "success");
30 return undefined;
31 },
32 }),
33 );
34 }
src/web/studio/actions.ts +17
@@ -22,6 +22,8 @@ import type { Ctx } from "../../http/context.ts";
2222 import { loadRepo, notFoundPage, repoBase, signInFirst } from "../chrome.ts";
2323 import { field, readForm, type Form } from "../form.ts";
2424 import { flashOrJson, flashTo } from "../layout.ts";
25 import { recordThought, THOUGHT_MAX, thoughtFits } from "../../core/thoughts.ts";
26 import { FORGE_CHOICE } from "./feed.ts";
2527 import { changeHref } from "./nouns.ts";
2628
2729 /** A merge refusal in a person's words. */
@@ -94,6 +96,21 @@ export async function composerSubmit(ctx: Ctx): Promise<Response> {
9496 if (!ctx.auth.user) return signInFirst(ctx);
9597 const form = await readForm(ctx, "rw");
9698 if (form instanceof Response) return form;
99 if (field(form, "app") === FORGE_CHOICE) {
100 // Verbatim: the box is not trimmed, and an empty one is still kept.
101 const text = form.get("text");
102 if (typeof text !== "string" || !thoughtFits(text))
103 return flashTo(ctx, "/", {
104 tone: "danger",
105 message: `A thought is at most ${THOUGHT_MAX} characters.`,
106 });
107 recordThought(ctx.app.db, ctx.app.bus, {
108 authorId: ctx.auth.user.id,
109 text,
110 source: "composer",
111 });
112 return flashTo(ctx, "/", { message: "Received." });
113 }
97114 const [owner = "", name = "", ...extra] = field(form, "app").split("/");
98115 const repo = extra.length === 0 ? getRepo(ctx.app.db, owner, name) : undefined;
99116 if (!repo || !canRead(ctx.app.db, repo, ctx.auth.user)) return notFoundPage(ctx);
src/web/studio/feed.ts +57 −19
@@ -17,11 +17,16 @@ import { html, type Html } from "../html.ts";
1717 import { fragment } from "../layout.ts";
1818 import { outboxJs } from "../outbox.ts";
1919 import { avatar, btn, empty, nameMark, timeAgo } from "../ui.ts";
20 import { FORGE_APP } from "../../feed/items.ts";
21 import { THOUGHT_MAX } from "../../core/thoughts.ts";
2022 import { writableAppsOf } from "./asks.ts";
2123
2224 /** Events that can change what the feed says. */
2325 export const FEED_LIVE =
24 "run.finished,issue.opened,issue.commented,pull.commented,pull.opened,pull.merged,pull.reviewed,pull.closed,look.taken,app.serving,issue.blocked,issue.unblocked,issue.closed,decision.*";
26 "run.finished,issue.opened,issue.commented,pull.commented,pull.opened,pull.merged,pull.reviewed,pull.closed,look.taken,app.serving,issue.blocked,issue.unblocked,issue.closed,thought.received,decision.*";
27
28 /** The picker's value for "no repository" — not a slug, so no app can be named it. */
29 export const FORGE_CHOICE = "-";
2530
2631 export const FEED_FIRST_PAGE = 20;
2732
@@ -36,6 +41,7 @@ const KIND_LABEL: Record<FeedItem["kind"], string> = {
3641 cost: "Cost",
3742 milestone: "Watching",
3843 tell: "Told",
44 thought: "Received",
3945 reply: "Reply",
4046 look: "Look",
4147 };
@@ -58,6 +64,7 @@ export function feedCard(
5864 item: FeedItem,
5965 marks: ReadonlyMap<string, Mark> = new Map(),
6066 ): Html {
67 if (item.kind === "thought") return thoughtCard(item, marks);
6168 const steer = item.kind === "run" || item.kind === "cost";
6269 const target = steer && RUN_LINK.test(item.link) ? `${item.link}/steer` : null;
6370 return html`<article
@@ -111,6 +118,27 @@ export function sharedDraft(params: URLSearchParams): string {
111118 return parts.join("\n").slice(0, TELL_MAX);
112119 }
113120
121 /**
122 * A thought, verbatim: the owner's own post, marked received. It belongs to
123 * no app, so it has no tell form, no mute and no dismiss — only its words.
124 */
125 function thoughtCard(
126 item: FeedItem,
127 marks: ReadonlyMap<string, Mark>,
128 ): Html {
129 return html`<article class="fcard" tabindex="0" data-item="${item.id}" data-kind="thought">
130 <div class="fcard-head">
131 ${avatar(item.actor ?? item.app)}
132 <strong class="fcard-who">${item.actor ?? item.app}</strong
133 >${nameMark(item.actor === null ? undefined : marks.get(item.actor))}
134 <span class="fcard-app muted small">${item.app} · ${timeAgo(item.at)}</span>
135 <span class="spacer"></span>
136 <span class="badge">${KIND_LABEL.thought}</span>
137 </div>
138 <p class="fcard-reason" style="white-space:pre-wrap">${item.what}</p>
139 </article>`;
140 }
141
114142 /**
115143 * The composer: say something to an app's crew, which opens a tell — the
116144 * home's one primary action. Without a script it posts to the chosen app's
@@ -120,28 +148,31 @@ export function sharedDraft(params: URLSearchParams): string {
120148 */
121149 export function composer(ctx: Ctx, user: User): Html {
122150 const { repos } = writableAppsOf(ctx, user);
123 if (repos.length === 0)
124 return empty({
125 icon: "rocket",
126 title: "No apps yet",
127 note: "Make one, tell the crew what it is, and watch it come up here.",
128 action: html`${btn("New app", { href: "/apps/new", variant: "primary" })}
129 ${btn("Repositories", { href: `/${user.username}` })}`,
130 });
131151 const slug = (r: { ownerName: string; name: string }) => `${r.ownerName}/${r.name}`;
132 const first = slug(repos[0]!);
133 return html`<form id="composer" class="composer" method="post" action="/tell">
134 <textarea class="input" name="text" rows="2" maxlength="2000" required placeholder="Tell the crew what should change" aria-label="Tell the crew">${sharedDraft(ctx.url.searchParams)}</textarea>
152 // "the forge" is a choice like any app: a thought that belongs to none.
153 const picker =
154 repos.length === 0
155 ? html`<input type="hidden" name="app" value="${FORGE_CHOICE}" /><span class="muted small">${FORGE_APP}</span>`
156 : html`<select name="app" class="input" aria-label="Which app">
157 ${repos.map((r) => html`<option value="${slug(r)}">${slug(r)}</option>`)}
158 <option value="${FORGE_CHOICE}">${FORGE_APP} (no app)</option>
159 </select>`;
160 const form = html`<form id="composer" class="composer" method="post" action="/tell">
161 <textarea class="input" name="text" rows="2" maxlength="${repos.length === 0 ? String(THOUGHT_MAX) : "2000"}" data-forge-max="${String(THOUGHT_MAX)}" required placeholder="${repos.length === 0 ? "Tell the forge what is on your mind" : "Tell the crew what should change"}" aria-label="Tell the crew">${sharedDraft(ctx.url.searchParams)}</textarea>
135162 <div class="composer-bar">
136 ${repos.length === 1
137 ? html`<input type="hidden" name="app" value="${first}" /><span class="muted small">${first}</span>`
138 : html`<select name="app" class="input" aria-label="Which app">
139 ${repos.map((r) => html`<option value="${slug(r)}">${slug(r)}</option>`)}
140 </select>`}
163 ${picker}
141164 <span class="spacer"></span>
142165 ${btn("Post", { variant: "primary" })}
143166 </div>
144167 </form>`;
168 if (repos.length > 0) return form;
169 return html`${empty({
170 icon: "rocket",
171 title: "No apps yet",
172 note: "Make one, tell the crew what it is, and watch it come up here.",
173 action: html`${btn("New app", { href: "/apps/new", variant: "primary" })}
174 ${btn("Repositories", { href: `/${user.username}` })}`,
175 })}${form}`;
145176 }
146177
147178 /**
@@ -273,11 +304,18 @@ ${outboxJs}
273304 // The composer is a tell too: kept and sent the same way; the box clears
274305 // at once, and the post arrives in the timeline when the forge says so.
275306 var composer = document.getElementById('composer');
307 var pick = composer && composer.elements.app;
308 if (pick && pick.tagName === 'SELECT') pick.addEventListener('change', function () {
309 var t = composer.elements.text;
310 t.maxLength = pick.value === '${FORGE_CHOICE}' ? Number(t.getAttribute('data-forge-max')) : 2000;
311 });
276312 if (composer) composer.addEventListener('submit', function (e) {

High: three lines below, the submit handler trims (box.value.trim()) before it queues to /api/v1/feed/tells, so a thought from the composer with JavaScript on loses its leading and trailing whitespace. When app.value === '-', send box.value as it is.

277313 var box = composer.elements.text;
278314 var app = composer.elements.app;
279 var text = box ? box.value.trim() : '';
280 if (!text || !app) return;
315 if (!box || !app) return;
316 // A thought for the forge is kept exactly as typed; an app tell is trimmed.
317 var text = app.value === '${FORGE_CHOICE}' ? box.value : box.value.trim();
318 if (!text.trim()) return;
281319 if (!queue('/api/v1/feed/tells', { app: app.value, text: text })) return;
282320 e.preventDefault();
283321 box.value = '';
test/mcp.test.ts +1 −1
@@ -205,7 +205,7 @@ describe("the forge over MCP", () => {
205205 listed.body.result.tools.map((t: any) => [t.name, t]),
206206 );
207207 expect(byName.get("tell").annotations.readOnlyHint).toBe(false);
208 expect(byName.get("tell").inputSchema.required).toEqual(["repo", "text"]);
208 expect(byName.get("tell").inputSchema.required).toEqual(["text"]);
209209
210210 expect((await call(rw, "nothing/here")).body.error.code).toBe(-32601);
211211 expect(
test/thoughts.test.ts added +250
@@ -0,0 +1,250 @@
1 /**
2 * The thought ledger (#1060): what is typed is kept exactly, from the
3 * composer, the API and the MCP, can never be changed or removed, and shows
4 * up in the owner's feed — and only theirs — with an event for triage.
5 */
6 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
7 import { mkdtemp, rm } from "node:fs/promises";
8 import { tmpdir } from "node:os";
9 import { join } from "node:path";
10 import { createApp, type App } from "../src/app.ts";
11 import { createRepo } from "../src/actions/repos.ts";
12 import { createApp as insertApp } from "../src/core/apps.ts";
13 import { listEvents } from "../src/core/events.ts";
14 import { createSession } from "../src/core/sessions.ts";
15 import { createToken } from "../src/core/tokens.ts";
16 import { listThoughts, THOUGHT_MAX } from "../src/core/thoughts.ts";
17 import { createUser, type User } from "../src/core/users.ts";
18 import { readFeed } from "../src/feed/feed.ts";
19 import { Session } from "../src/tui/forge.ts";
20 import { tellForge } from "../src/tui/screens/thought.ts";
21 import type { Ctx, Screen } from "../src/tui/app/app.ts";
22 import { serve, type Servers } from "../src/http/server.ts";
23
24 describe("thought intake", () => {
25 let dataDir: string;
26 let app: App;
27 let servers: Servers;
28 let alice: User;
29 let bob: User;
30 let cookie: string;
31 let rw: string;
32 let ro: string;
33
34 beforeAll(async () => {
35 dataDir = await mkdtemp(join(tmpdir(), "forge-thoughts-"));
36 app = createApp({ dataDir, port: 0 });
37 servers = await serve(app);
38 const mk = async (username: string, first = false) => {
39 const r = await createUser(app.db, {
40 trusted: true,
41 username,
42 email: `${username}@forge.local`,
43 password: "a-good-passphrase",
44 adminIfFirst: first,
45 });
46 if (!r.ok) throw new Error(r.error);
47 return r.value;
48 };
49 alice = await mk("alice", true);
50 bob = await mk("bob");
51 cookie = `forge_session=${createSession(app.db, alice.id).token}`;
52 rw = createToken(app.db, alice.id, "rw", "rw").token;
53 ro = createToken(app.db, alice.id, "ro", "ro").token;
54 });
55
56 afterAll(async () => {
57 servers.stop();
58 app.close();
59 await rm(dataDir, { recursive: true, force: true });
60 });
61
62 const api = (text: unknown, token = rw) =>
63 fetch(`${servers.url}/api/v1/thoughts`, {
64 method: "POST",
65 headers: { authorization: `Bearer ${token}`, "content-type": "application/json" },
66 body: JSON.stringify({ text }),
67 });
68 const mcp = async (args: unknown) => {
69 const res = await fetch(`${servers.url}/mcp`, {
70 method: "POST",
71 headers: {
72 authorization: `Bearer ${rw}`,
73 "content-type": "application/json",
74 accept: "application/json, text/event-stream",
75 },
76 body: JSON.stringify({
77 jsonrpc: "2.0",
78 id: 1,
79 method: "tools/call",
80 params: { name: "tell", arguments: args },
81 }),
82 });
83 const body: any = await res.json();
84 const text: string = body.result.content[0].text;
85 // An error is plain text ("code: message"), a success is JSON.
86 return body.result.isError ? { error: text } : JSON.parse(text);
87 };
88
89 test("the API keeps text verbatim, whitespace, markup and repeats included", async () => {
90 const odd = " <b>hi</b>\n\n\tтест 🙂 ";
91 const a = await api(odd);
92 expect(a.status).toBe(201);
93 const id = ((await a.json()) as { id: string }).id;
94 expect((await api(odd)).status).toBe(201);
95 expect((await api("")).status).toBe(201);
96 const kept = listThoughts(app.db, alice.id);
97 expect(kept.find((t) => t.id === id)).toMatchObject({
98 text: odd,
99 source: "api",
100 authorId: alice.id,
101 });
102 expect(kept.filter((t) => t.text === odd)).toHaveLength(2);
103 expect(kept.some((t) => t.text === "")).toBe(true);
104 });
105
106 test("a bad body is refused at the boundary; a read token cannot write", async () => {
107 expect((await api(42)).status).toBe(422);
108 expect((await api("x".repeat(THOUGHT_MAX + 1))).status).toBe(422);
109 expect((await api("nope", ro)).status).toBe(403);
110 const anon = await fetch(`${servers.url}/api/v1/thoughts`, {
111 method: "POST",
112 headers: { "content-type": "application/json" },
113 body: JSON.stringify({ text: "x" }),
114 });
115 expect([401, 403]).toContain(anon.status);
116 });
117
118 test("MCP tell with no repo returns the thought id", async () => {
119 const out = await mcp({ text: "from my phone" });
120 expect(typeof out.thought).toBe("string");
121 expect(listThoughts(app.db, alice.id).find((t) => t.id === out.thought)).toMatchObject({
122 text: "from my phone",
123 source: "mcp",
124 });
125 });
126
127 test("the composer's forge choice keeps a thought, with and without a script", async () => {
128 const js = await fetch(`${servers.url}/api/v1/feed/tells`, {
129 method: "POST",
130 headers: { cookie, origin: servers.url, "content-type": "application/json" },
131 body: JSON.stringify({ app: "-", text: " composer, json " }),
132 });
133 expect(js.status).toBe(201);
134 const form = await fetch(`${servers.url}/tell`, {
135 method: "POST",
136 redirect: "manual",
137 headers: { cookie, origin: servers.url, "content-type": "application/x-www-form-urlencoded" },
138 body: new URLSearchParams({ app: "-", text: " composer, form " }),
139 });
140 expect(form.status).toBeLessThan(400);
141 const texts = listThoughts(app.db, alice.id).filter((t) => t.source === "composer").map((t) => t.text);
142 expect(texts).toContain(" composer, json ");
143 expect(texts).toContain(" composer, form ");
144 });
145
146 test("every source is kept, and each thought rides the outbox", () => {
147 const sources = new Set(listThoughts(app.db, alice.id).map((t) => t.source));
148 expect([...sources].sort()).toEqual(["api", "composer", "mcp"]);
149 const events = listEvents(app.db, { kind: "thought.received", limit: 100 });
150 expect(events).toHaveLength(listThoughts(app.db, alice.id).length);
151 expect(events[0]!.payload["thoughtId"]).toBeString();
152 // The event names the thought; the words stay in the ledger.
153 expect(JSON.stringify(events)).not.toContain("from my phone");
154 });
155
156 test("append-only: the database refuses an update and a delete", () => {
157 const row = listThoughts(app.db, alice.id)[0]!;
158 expect(() => app.db.run("UPDATE thought SET text = 'x' WHERE id = ?1", [row.id])).toThrow();
159 expect(() => app.db.run("DELETE FROM thought WHERE id = ?1", [row.id])).toThrow();
160 expect(() => app.db.run("DELETE FROM thought")).toThrow();
161 expect(listThoughts(app.db, alice.id)[0]!.text).toBe(row.text);
162 });
163
164 test("no code path updates or deletes a thought", async () => {
165 const src = await Bun.file(join(import.meta.dir, "../src/core/thoughts.ts")).text();
166 expect(src).not.toMatch(/\b(UPDATE|DELETE)\b\s+(FROM\s+)?thought/i);
167 });
168
169 test("the thought is a post at the top of the owner's feed, whole and escaped", async () => {
170 await api("<script>alert(1)</script> newest");
171 const mine = readFeed(app.db, alice).items;
172 expect(mine[0]).toMatchObject({ kind: "thought", app: "the forge", what: "<script>alert(1)</script> newest" });
173 expect(readFeed(app.db, bob).items.filter((i) => i.kind === "thought")).toHaveLength(0);
174 const page = await (await fetch(`${servers.url}/`, { headers: { cookie } })).text();
175 expect(page).toContain("&lt;script&gt;alert(1)&lt;/script&gt; newest");
176 expect(page).not.toContain("<script>alert(1)</script>");
177 expect(page).toContain("Received");
178 expect(page).toContain('name="app" value="-"');
179 });
180
181 test("with apps the picker offers the forge beside them", async () => {
182 const made = await createRepo(app, alice, { name: "game", visibility: "private" });
183 if (!made.ok) throw new Error("repo");
184 insertApp(app.db, { repoId: made.value.id, slug: "game", access: "private" });
185 const page = await (await fetch(`${servers.url}/`, { headers: { cookie } })).text();
186 expect(page).toContain('<option value="alice/game">');
187 expect(page).toContain('<option value="-">the forge (no app)</option>');
188 // An app tell still stops at 2000 in the browser; only the forge choice
189 // (switched on picker change) may type more.
190 expect(page).toContain('name="text" rows="2" maxlength="2000"');
191 expect(page).toContain(`data-forge-max="${THOUGHT_MAX}"`);
192 });
193
194 test("MCP names the real limit when a thought is too long", async () => {
195 const out = await mcp({ text: "x".repeat(THOUGHT_MAX + 1) });
196 expect(out.error).toContain("invalid_text");
197 expect(out.error).toContain(`at most ${THOUGHT_MAX} characters`);
198 expect(await mcp({ text: 7 })).toHaveProperty("error");
199 });
200
201 test("the terminal keeps a thought as its ssh-verified user, and it shows in their feed", async () => {
202 const session = new Session(app, {
203 sshUsername: "alice",
204 remoteAddress: "127.0.0.1",
205 fingerprint: "SHA256:test",
206 user: alice,
207 });
208 let pushed: Screen | undefined;
209 const toasts: string[] = [];
210 const ctx = {
211 push: (s: Screen) => (pushed = s),
212 pop: () => {},
213 toast: (t: string) => toasts.push(t),
214 } as unknown as Ctx;
215 tellForge(session, ctx, {} as Screen);
216 const type = (text: string) => {
217 for (const ch of text) pushed!.key!({ key: ch } as never);
218 return pushed!.key!({ key: "enter" } as never);
219 };
220 // Empty is refused in the terminal (an accidental enter), nothing kept.
221 const before = listThoughts(app.db, alice.id).length;
222 pushed!.key!({ key: "enter" } as never);
223 expect(listThoughts(app.db, alice.id)).toHaveLength(before);
224 type("from <ssh>");
225 const kept = listThoughts(app.db, alice.id)[0]!;
226 expect(kept).toMatchObject({ text: "from <ssh>", source: "terminal", authorId: alice.id });
227 expect(toasts).toContain("kept");
228 expect(readFeed(app.db, alice).items[0]).toMatchObject({ kind: "thought", what: "from <ssh>" });
229 expect(readFeed(app.db, bob).items.filter((i) => i.kind === "thought")).toHaveLength(0);
230 const events = listEvents(app.db, { kind: "thought.received", limit: 1 });
231 expect(events[0]!.payload["source"]).toBe("terminal");
232 // The page refreshes live on this event.
233 const page = await (await fetch(`${servers.url}/`, { headers: { cookie } })).text();
234 expect(page).toContain("thought.received");
235 });
236
237 test("the composer script sends the forge choice untrimmed and trims app tells", async () => {
238 const page = await (await fetch(`${servers.url}/`, { headers: { cookie } })).text();
239 expect(page).toContain("app.value === '-' ? box.value : box.value.trim()");
240 expect(page).not.toContain("var text = box ? box.value.trim()");
241 });
242
243 test("the ledger refuses an unknown source and stays the ledger append-only", () => {
244 expect(() =>
245 app.db.run("INSERT INTO thought VALUES ('z', ?1, 't', 'bogus', 'now')", [alice.id]),
246 ).toThrow();
247 expect(() => app.db.run("UPDATE thought SET text = 'x'")).toThrow();
248 expect(() => app.db.run("DELETE FROM thought")).toThrow();
249 });
250 });
test/tui-apps.test.ts +2 −1
@@ -466,7 +466,8 @@ describe("terminal: apps, runs and the crew", () => {
466466
467467 const before = h.text();
468468 expect(before).not.toContain("new app");
469 for (const key of ["a", "N", "t"]) {
469 // `t` was the removed runs key; it now tells the forge (#1060).
470 for (const key of ["a", "N"]) {
470471 await h.press(key);
471472 expect(h.text()).toBe(before);
472473 }

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs