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

Closed opened this in answer to
Closed without merging

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

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
10 files changed +418 −22
src/actions/thoughts.ts added +34
@@ -0,0 +1,34 @@
1 /**
2 * Receive a thought: keep it verbatim in the ledger, then say so on the
3 * outbox for triage. Every door (the composer, the API, the MCP `tell`
4 * without an app) comes through here.
5 */
6
7 import type { App } from "../app.ts";
8 import {
9 addThought,
10 THOUGHT_MAX,
11 type Thought,
12 type ThoughtSource,
13 } from "../core/thoughts.ts";
14 import type { User } from "../core/users.ts";
15 import { err, ok, type Result } from "../kernel/result.ts";
16
17 export type ThoughtError = "unauthorized" | "too_long";
18
19 export function receiveThought(
20 app: App,
21 actor: User | undefined,
22 text: string,
23 source: ThoughtSource,
24 ): Result<Thought, ThoughtError> {
25 if (!actor) return err("unauthorized");
26 if (text.length > THOUGHT_MAX) return err("too_long");
27 const thought = addThought(app.db, { authorId: actor.id, text, source });
28 app.bus.append({
29 kind: "thought.received",
30 actorId: actor.id,
31 payload: { thoughtId: thought.id, source },
32 });
33 return ok(thought);
34 }
src/core/schema.ts +17
@@ -1540,4 +1540,21 @@ export const migrations: readonly string[] = [
15401540 SELECT RAISE(ABORT, 'a sealed repository is never public');
15411541 END;
15421542 `,
1543 // 71 — thoughts (#651): what the owner says to the forge itself, verbatim,
1544 // with who, when and by which door. Append-only: the database refuses an
1545 // UPDATE or DELETE, whoever writes.
1546 `
1547 CREATE TABLE thought (
1548 id TEXT PRIMARY KEY,
1549 author_id TEXT NOT NULL,
1550 text TEXT NOT NULL,
1551 source TEXT NOT NULL CHECK (source IN ('composer', 'api', 'mcp', 'share')),
1552 received_at TEXT NOT NULL
1553 );
1554 CREATE INDEX thought_author ON thought(author_id, id);
1555 CREATE TRIGGER thought_no_update BEFORE UPDATE ON thought
1556 BEGIN SELECT RAISE(ABORT, 'thoughts are append-only'); END;
1557 CREATE TRIGGER thought_no_delete BEFORE DELETE ON thought
1558 BEGIN SELECT RAISE(ABORT, 'thoughts are append-only'); END;
1559 `,
15431560 ];
src/core/thoughts.ts added +75
@@ -0,0 +1,75 @@
1 /**
2 * Thoughts: what the owner said to the forge itself, kept exactly as typed.
3 * The ledger is append-only — this module has an insert and reads, and the
4 * table refuses an UPDATE or DELETE (migration 71) — so a thought later
5 * repeated or reversed is a new row, never an edit of the old one.
6 */
7
8 import type { Database } from "bun:sqlite";
9 import { id } from "../kernel/id.ts";
10
11 export const THOUGHT_SOURCES = ["composer", "api", "mcp", "share"] as const;
12 export type ThoughtSource = (typeof THOUGHT_SOURCES)[number];
13
14 /** The longest thought taken; the MCP `tell` allows the same. */
15 export const THOUGHT_MAX = 8000;
16
17 export interface Thought {
18 readonly id: string;
19 readonly authorId: string;
20 /** Verbatim: not trimmed, not normalised, possibly empty. */
21 readonly text: string;
22 readonly source: ThoughtSource;
23 readonly receivedAt: string;
24 }
25
26 interface Row {
27 id: string;
28 author_id: string;
29 text: string;
30 source: string;
31 received_at: string;
32 }
33
34 const toThought = (r: Row): Thought => ({
35 id: r.id,
36 authorId: r.author_id,
37 text: r.text,
38 source: r.source as ThoughtSource,
39 receivedAt: r.received_at,
40 });
41
42 export function addThought(
43 db: Database,
44 input: { authorId: string; text: string; source: ThoughtSource },
45 ): Thought {
46 const thought: Thought = {
47 id: id(),
48 authorId: input.authorId,
49 text: input.text,
50 source: input.source,
51 receivedAt: new Date().toISOString(),
52 };
53 db.query(
54 "INSERT INTO thought (id, author_id, text, source, received_at) VALUES (?1, ?2, ?3, ?4, ?5)",
55 ).run(thought.id, thought.authorId, thought.text, thought.source, thought.receivedAt);
56 return thought;
57 }
58
59 export function getThought(db: Database, thoughtId: string): Thought | undefined {
60 const row = db.query("SELECT * FROM thought WHERE id = ?1").get(thoughtId) as Row | null;
61 return row ? toThought(row) : undefined;
62 }
63
64 /** One author's thoughts, newest first. */
65 export function listThoughts(
66 db: Database,
67 authorId: string,
68 limit = 20,
69 ): Thought[] {
70 return (
71 db
72 .query("SELECT * FROM thought WHERE author_id = ?1 ORDER BY id DESC LIMIT ?2")
73 .all(authorId, limit) as Row[]
74 ).map(toThought);
75 }
src/feed/items.ts +29 −1
@@ -18,6 +18,7 @@ import {
1818 listReposWritableTo,
1919 type Repo,
2020 } from "../core/repos.ts";
21 import { listThoughts } from "../core/thoughts.ts";
2122 import { getUserById, type User } from "../core/users.ts";
2223 import { watchedBy } from "../core/watches.ts";
2324 import { askLinesFor } from "../web/studio/asks.ts";
@@ -34,7 +35,9 @@ export type FeedKind =
3435 | "tell"
3536 | "reply"
3637 | "look"
37 | "milestone";
38 | "milestone"
39 // The viewer's own words to the forge, kept verbatim (`core/thoughts.ts`).
40 | "thought";
3841
3942 /** What a candidate is, before it is ranked and worded. */
4043 export interface Candidate {
@@ -117,6 +120,30 @@ function watchedCandidates(db: Database, viewer: User, now: number): Candidate[]
117120 return out;
118121 }
119122
123 /** Where a thought belongs to no repository: the feed's name for the forge itself. */
124 export const FORGE_APP = "the forge";
125 const THOUGHT_URGENCY = 3;
126
127 /**
128 * The viewer's own recent thoughts, each a post in their words exactly as
129 * typed (never clipped here), above plain news until something answers.
130 */
131 function thoughtCandidates(db: Database, viewer: User): Candidate[] {
132 return listThoughts(db, viewer.id, 20).map((t) => ({
133 id: `thought:${t.id}`,
134 kind: "thought",
135 repoId: "",
136 app: FORGE_APP,
137 actorId: viewer.id,
138 actor: viewer.username,
139 at: t.receivedAt,
140 link: "/",
141 what: t.text,
142 urgency: THOUGHT_URGENCY,
143 said: t.text,
144 }));
145 }
146
120147 export function candidatesFor(
121148 db: Database,
122149 viewer: User,
@@ -182,6 +209,7 @@ export function candidatesFor(
182209 });
183210 }
184211 out.push(...watchedCandidates(db, viewer, now));
212 out.push(...thoughtCandidates(db, viewer));
185213 for (const d of decided) {
186214 const repo = repos.get(d.repoId);
187215 if (!repo) continue;
src/http/feed.ts +21
@@ -3,6 +3,8 @@
33 * are the signed-in viewer's own — there is no way to ask for another's.
44 */
55
6 import { receiveThought } from "../actions/thoughts.ts";
7 import { THOUGHT_MAX } from "../core/thoughts.ts";
68 import { tell, UNVERIFIED_WORDS } from "../actions/tell.ts";
79 import { DIRECTION_NOTE } from "../crew/direct.ts";
810 import { audienceFilter } from "../core/event_audience.ts";
@@ -170,6 +172,25 @@ export function feedRoutes(router: Router<Handler>): void {
170172 return json({ issue: told.value.issue.number }, 201);
171173 });
172174
175 // A thought that belongs to no app, kept as typed (`core/thoughts.ts`).
176 // Not trimmed and not refused for being empty or said before; only a
177 // non-string or an over-long text is turned away, so it is never cut.
178 router.add("POST", "/api/v1/thoughts", async (ctx) => {
179 const denied = requireScope(ctx, "rw");
180 if (denied) return denied;
181 const input = await body(ctx.request);
182 if (typeof input.text !== "string" || input.text.length > THOUGHT_MAX)
183 return apiError("invalid_text", 422, `text is a string of up to ${THOUGHT_MAX} characters`);
184 const made = receiveThought(
185 ctx.app,
186 ctx.auth.user,
187 input.text,
188 input.source === "composer" ? "composer" : "api",
189 );
190 if (!made.ok) return unauthorized();
191 return json({ id: made.value.id, received_at: made.value.receivedAt }, 201);
192 });
193
173194 router.add("POST", "/api/v1/share", async (ctx) => {
174195 const denied = requireScope(ctx, "rw");
175196 if (denied) return denied;
src/http/mcp.ts +17 −3
@@ -37,6 +37,8 @@ import { openPlan, parsePlan, PLAN_MAX } from "../actions/plan.ts";
3737 import { cancelRepoRun } from "../actions/runs.ts";
3838 import { clientRows } from "../spawn/clients.ts";
3939 import { reissueDoor, spawnDoor } from "../spawn/door.ts";
40 import { receiveThought } from "../actions/thoughts.ts";
41 import { THOUGHT_MAX } from "../core/thoughts.ts";
4042 import { tell, toldWords, UNVERIFIED_WORDS } from "../actions/tell.ts";
4143 import { readReturns, reportSpend } from "../actions/returns.ts";
4244 import {
@@ -269,14 +271,26 @@ const TOOLS: readonly Tool[] = [
269271 {
270272 name: "tell",
271273 description:
272 "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.",
274 "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 said, and the answer is its id.",
273275 inputSchema: {
274276 type: "object",
275 properties: { repo: REPO_ARG, text: { type: "string", maxLength: 8000 } },
276 required: ["repo", "text"],
277 properties: { repo: REPO_ARG, text: { type: "string", maxLength: THOUGHT_MAX } },
278 required: ["text"],
277279 },
278280 writes: true,
279281 async run(ctx, user, args) {
282 if (args["repo"] === undefined) {
283 const said = args["text"];
284 if (typeof said !== "string")
285 return bad("invalid_text", "text is a string");
286 const made = receiveThought(ctx.app, user, said, "mcp");
287 return made.ok
288 ? good({
289 says: "Received. It is kept as you said it.",
290 thought: made.value.id,
291 })
292 : bad(made.error, "that could not be kept (too long?)");
293 }
280294 const repo = repoArg(ctx, user, args);
281295 if (isAnswer(repo)) return repo;
282296 const told = await tell(ctx.app, user, repo, str(args["text"]));
src/web/studio/actions.ts +9
@@ -11,6 +11,7 @@
1111 import { mayView } from "../../core/sealed.ts";
1212 import { holdPull, releasePull } from "../../actions/holds.ts";
1313 import { addComment } from "../../actions/issues.ts";
14 import { receiveThought } from "../../actions/thoughts.ts";
1415 import { tell } from "../../actions/tell.ts";
1516 import { DIRECTION_NOTE } from "../../crew/direct.ts";
1617 import { mergePull } from "../../actions/pulls.ts";
@@ -20,6 +21,7 @@ import { canRead, getRepo, type Repo } from "../../core/repos.ts";
2021 import { bringUpToDate } from "../../crew/autonomy.ts";
2122 import type { Ctx } from "../../http/context.ts";
2223 import { loadRepo, notFoundPage, repoBase, signInFirst } from "../chrome.ts";
24 import { FORGE_CHOICE } from "./feed.ts";
2325 import { field, readForm, type Form } from "../form.ts";
2426 import { flashOrJson, flashTo } from "../layout.ts";
2527 import { changeHref } from "./nouns.ts";
@@ -94,6 +96,13 @@ 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 // "the forge" is no repository: the words are kept as typed.
100 if (field(form, "app") === FORGE_CHOICE) {
101 const made = receiveThought(ctx.app, ctx.auth.user, field(form, "text"), "composer");
102 return flashTo(ctx, "/", made.ok
103 ? { message: "Received." }
104 : { tone: "danger", message: "That is too long to keep." });
105 }
97106 const [owner = "", name = "", ...extra] = field(form, "app").split("/");
98107 const repo = extra.length === 0 ? getRepo(ctx.app.db, owner, name) : undefined;
99108 if (!repo || !canRead(ctx.app.db, repo, ctx.auth.user)) return notFoundPage(ctx);
src/web/studio/feed.ts +47 −17
@@ -25,6 +25,9 @@ export const FEED_LIVE =
2525
2626 export const FEED_FIRST_PAGE = 20;
2727
28 /** The composer's "the forge": the app field's value for a thought, no repository. */
29 export const FORGE_CHOICE = "forge";
30
2831 const RUN_LINK = /^\/[^/]+\/[^/]+\/runs\/[A-Za-z0-9_-]+$/;
2932
3033 const KIND_LABEL: Record<FeedItem["kind"], string> = {
@@ -36,6 +39,7 @@ const KIND_LABEL: Record<FeedItem["kind"], string> = {
3639 cost: "Cost",
3740 milestone: "Watching",
3841 tell: "Told",
42 thought: "Received",
3943 reply: "Reply",
4044 look: "Look",
4145 };
@@ -58,6 +62,19 @@ export function feedCard(
5862 item: FeedItem,
5963 marks: ReadonlyMap<string, Mark> = new Map(),
6064 ): Html {
65 // A thought is the viewer's own words, shown whole and as typed; it has no
66 // page to open and nothing to dismiss, since the ledger keeps it.
67 if (item.kind === "thought")
68 return html`<article class="fcard" data-nav tabindex="0" data-item="${item.id}" data-kind="thought">
69 <div class="fcard-head">
70 ${avatar(item.actor ?? item.app)}
71 <strong class="fcard-who">${item.actor ?? item.app}</strong>
72 <span class="fcard-app muted small">${item.app} · ${timeAgo(item.at)}</span>
73 <span class="spacer"></span>
74 <span class="badge">${KIND_LABEL.thought}</span>
75 </div>
76 <p class="fcard-reason" style="white-space: pre-wrap; overflow-wrap: anywhere">${item.what}</p>
77 </article>`;
6178 const steer = item.kind === "run" || item.kind === "cost";
6279 const target = steer && RUN_LINK.test(item.link) ? `${item.link}/steer` : null;
6380 return html`<article
@@ -101,24 +118,24 @@ export function feedCard(
101118 */
102119 export function composer(ctx: Ctx, user: User): Html {
103120 const { repos } = writableAppsOf(ctx, user);
104 if (repos.length === 0)
105 return empty({
106 icon: "rocket",
107 title: "No apps yet",
108 note: "Make one, tell the crew what it is, and watch it come up here.",
109 action: html`${btn("New app", { href: "/apps/new", variant: "primary" })}
110 ${btn("Repositories", { href: `/${user.username}` })}`,
111 });
112121 const slug = (r: { ownerName: string; name: string }) => `${r.ownerName}/${r.name}`;
113 const first = slug(repos[0]!);
114 return html`<form id="composer" class="composer" method="post" action="/tell">
115 <textarea name="text" rows="2" maxlength="2000" required placeholder="Tell the crew what should change" aria-label="Tell the crew"></textarea>
122 const nudge =
123 repos.length === 0
124 ? 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 })
131 : null;
132 return html`${nudge}<form id="composer" class="composer" method="post" action="/tell">
133 <textarea name="text" rows="2" maxlength="2000" required placeholder="${repos.length === 0 ? "Tell the forge anything" : "Tell the crew what should change"}" aria-label="Tell the crew"></textarea>
116134 <div class="composer-bar">
117 ${repos.length === 1
118 ? html`<input type="hidden" name="app" value="${first}" /><span class="muted small">${first}</span>`
119 : html`<select name="app" class="input" aria-label="Which app">
120 ${repos.map((r) => html`<option value="${slug(r)}">${slug(r)}</option>`)}
121 </select>`}
135 <select name="app" class="input" aria-label="Which app">
136 ${repos.map((r) => html`<option value="${slug(r)}">${slug(r)}</option>`)}
137 <option value="${FORGE_CHOICE}">the forge</option>
138 </select>
122139 <span class="spacer"></span>
123140 ${btn("Post", { variant: "primary" })}
124141 </div>
@@ -259,7 +276,20 @@ ${outboxJs}
259276 var app = composer.elements.app;
260277 var text = box ? box.value.trim() : '';
261278 if (!text || !app) return;
262 if (!queue('/api/v1/feed/tells', { app: app.value, text: text })) return;
279 // A thought is kept as typed: the box's value, not the trimmed text.
280 var sent = app.value === ${JSON.stringify(FORGE_CHOICE)}
281 ? queue('/api/v1/thoughts', { text: box.value, source: 'composer' })
282 : queue('/api/v1/feed/tells', { app: app.value, text: text });
283 if (!sent) return;
284 // A thought has no app to stream from: show it in the timeline once it is kept.
285 if (app.value === ${JSON.stringify(FORGE_CHOICE)}) outbox.flush().then(function () {
286 return fetch('/live/feed', { credentials: 'same-origin' }).then(function (r) { return r.ok ? r.text() : ''; }).then(function (t) {
287 var d = document.createElement('div');
288 d.innerHTML = t;
289 var n = d.querySelector('#live-feed');
290 if (n) feed.innerHTML = n.innerHTML;
291 });
292 }).catch(function () {});
263293 e.preventDefault();
264294 box.value = '';
265295 box.focus();
test/mcp.test.ts +1 −1
@@ -200,7 +200,7 @@ describe("the forge over MCP", () => {
200200 listed.body.result.tools.map((t: any) => [t.name, t]),
201201 );
202202 expect(byName.get("tell").annotations.readOnlyHint).toBe(false);
203 expect(byName.get("tell").inputSchema.required).toEqual(["repo", "text"]);
203 expect(byName.get("tell").inputSchema.required).toEqual(["text"]);
204204
205205 expect((await call(rw, "nothing/here")).body.error.code).toBe(-32601);
206206 expect(
test/thoughts.test.ts added +168
@@ -0,0 +1,168 @@
1 /**
2 * Thoughts (#651): what the owner says to the forge itself is kept exactly
3 * as typed, in a ledger that only grows, whichever door it came through.
4 */
5 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
6 import { mkdtemp, readdir, readFile, rm } from "node:fs/promises";
7 import { tmpdir } from "node:os";
8 import { join } from "node:path";
9 import { createApp, type App } from "../src/app.ts";
10 import { listEvents } from "../src/core/events.ts";
11 import { createSession } from "../src/core/sessions.ts";
12 import { createToken } from "../src/core/tokens.ts";
13 import { getThought, listThoughts } from "../src/core/thoughts.ts";
14 import { createUser, type User } from "../src/core/users.ts";
15 import { readFeed } from "../src/feed/feed.ts";
16 import { serve, type Servers } from "../src/http/server.ts";
17
18 describe("thoughts", () => {
19 let dir: string;
20 let app: App;
21 let servers: Servers;
22 let alice: User;
23 let rw: string;
24 let ro: string;
25 let cookie: string;
26
27 const post = (path: string, body: unknown, token = rw) =>
28 fetch(`${servers.url}${path}`, {
29 method: "POST",
30 headers: { authorization: `Bearer ${token}`, "content-type": "application/json" },
31 body: JSON.stringify(body),
32 });
33 const mcp = async (args: unknown) => {
34 const res = await fetch(`${servers.url}/mcp`, {
35 method: "POST",
36 headers: {
37 authorization: `Bearer ${rw}`,
38 "content-type": "application/json",
39 accept: "application/json, text/event-stream",
40 },
41 body: JSON.stringify({
42 jsonrpc: "2.0",
43 id: 1,
44 method: "tools/call",
45 params: { name: "tell", arguments: args },
46 }),
47 });
48 const body = (await res.json()) as any;
49 return { error: body.result.isError === true, text: body.result.content[0].text as string };
50 };
51
52 beforeAll(async () => {
53 dir = await mkdtemp(join(tmpdir(), "forge-thoughts-"));
54 app = createApp({ dataDir: dir, port: 0 });
55 servers = await serve(app);
56 const r = await createUser(app.db, {
57 trusted: true,
58 username: "alice",
59 email: "[email protected]",
60 password: "a-good-passphrase",
61 adminIfFirst: true,
62 });
63 if (!r.ok) throw new Error(r.error);
64 alice = r.value;
65 rw = createToken(app.db, alice.id, "rw", "rw").token;
66 ro = createToken(app.db, alice.id, "ro", "ro").token;
67 cookie = `forge_session=${createSession(app.db, alice.id).token}`;
68 });
69 afterAll(async () => {
70 await servers.stop();
71 await rm(dir, { recursive: true, force: true });
72 });
73
74 test("the API keeps the text byte for byte, empty and repeated included", async () => {
75 const odd = " two\r\nlines <b>& “quotes” 🚀\t \n";
76 for (const text of [odd, odd, "", " "]) {
77 const res = await post("/api/v1/thoughts", { text });
78 expect(res.status).toBe(201);
79 const { id } = (await res.json()) as { id: string };
80 const kept = getThought(app.db, id)!;
81 expect(kept.text).toBe(text);
82 expect(kept.source).toBe("api");
83 expect(kept.authorId).toBe(alice.id);
84 expect(Date.parse(kept.receivedAt)).toBeGreaterThan(0);
85 }
86 });
87
88 test("a read credential cannot, and a non-string or over-long text is refused, not cut", async () => {
89 expect((await post("/api/v1/thoughts", { text: "x" }, ro)).status).toBe(403);
90 expect((await post("/api/v1/thoughts", { text: 5 })).status).toBe(422);
91 expect((await post("/api/v1/thoughts", {})).status).toBe(422);
92 expect((await post("/api/v1/thoughts", { text: "x".repeat(8001) })).status).toBe(422);
93 });
94
95 test("MCP tell with no repo writes a thought and answers its id", async () => {
96 const said = " keep this exactly\n";
97 const got = await mcp({ text: said });
98 expect(got.error).toBe(false);
99 const { thought } = JSON.parse(got.text);
100 expect(getThought(app.db, thought)).toMatchObject({ text: said, source: "mcp" });
101 expect((await mcp({ text: 3 })).error).toBe(true);
102 // A repo that is not there is still not found, never a thought.
103 const before = listThoughts(app.db, alice.id, 100).length;
104 expect((await mcp({ repo: "alice/none", text: "hi" })).error).toBe(true);
105 expect(listThoughts(app.db, alice.id, 100).length).toBe(before);
106 });
107
108 test("the composer's 'the forge' keeps the words, same-origin only", async () => {
109 const send = (origin: string) =>
110 fetch(`${servers.url}/tell`, {
111 method: "POST",
112 headers: { cookie, origin },
113 body: new URLSearchParams({ app: "forge", text: "from the composer" }),
114 redirect: "manual",
115 });
116 expect((await send("https://evil.example")).status).toBe(403);
117 expect((await send(servers.url)).status).toBe(303);
118 const mine = listThoughts(app.db, alice.id, 100).filter((t) => t.source === "composer");
119 expect(mine.map((t) => t.text)).toEqual(["from the composer"]);
120 const page = await fetch(`${servers.url}/`, {
121 headers: { cookie: `${cookie}; forge_mode=studio` },
122 });
123 expect(await page.text()).toContain('<option value="forge">the forge</option>');
124 });
125
126 test("each thought rides the outbox and is a post in the author's feed alone", async () => {
127 const events = listEvents(app.db, { kind: "thought.received", limit: 100 });
128 const kept = listThoughts(app.db, alice.id, 100);
129 expect(events.length).toBe(kept.length);
130 expect(events.every((e) => e.repoId === null && e.actorId === alice.id)).toBe(true);
131 expect(new Set(events.map((e) => e.payload["thoughtId"]))).toEqual(new Set(kept.map((t) => t.id)));
132 const items = readFeed(app.db, alice).items.filter((i) => i.kind === "thought");
133 expect(items.length).toBeGreaterThan(0);
134 const top = items.find((i) => i.what === "from the composer")!;
135 expect(top).toMatchObject({ app: "the forge", actor: "alice" });
136 const other = await createUser(app.db, {
137 trusted: true,
138 username: "bob",
139 email: "[email protected]",
140 password: "a-good-passphrase",
141 });
142 if (!other.ok) throw new Error(other.error);
143 expect(readFeed(app.db, other.value).items.filter((i) => i.kind === "thought")).toEqual([]);
144 });
145
146 test("the ledger only grows: the database refuses UPDATE and DELETE", () => {
147 const t = listThoughts(app.db, alice.id, 1)[0]!;
148 expect(() => app.db.query("UPDATE thought SET text = 'x' WHERE id = ?1").run(t.id)).toThrow(/append-only/);
149 expect(() => app.db.query("DELETE FROM thought WHERE id = ?1").run(t.id)).toThrow(/append-only/);
150 expect(getThought(app.db, t.id)).toEqual(t);
151 });
152
153 test("no code path updates or deletes a thought", async () => {
154 const hits: string[] = [];
155 const walk = async (d: string) => {
156 for (const e of await readdir(d, { withFileTypes: true })) {
157 const p = join(d, e.name);
158 if (e.isDirectory()) await walk(p);
159 else if (p.endsWith(".ts") && !p.endsWith("core/schema.ts")) {
160 const src = await readFile(p, "utf8");
161 if (/(UPDATE|DELETE\s+FROM)\s+thought\b/i.test(src)) hits.push(p);
162 }
163 }
164 };
165 await walk(join(import.meta.dir, "../src"));
166 expect(hits).toEqual([]);
167 });
168 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs