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

A test lists the doors that exist only as a tool or a Talk press; make a machine and mail setup get their pages #18480

opened this

Merged 5h 5m ago, live in production

torque/forge:torque/18479-a-test-lists-the-doors-that-exist-only-a → main 0 commits fork

  • Merged. torque/18479-a-test-lists-the-doors-that-exist-only-a was merged into main as be45257.

Review

Sign in to review this change.
4 files changed +271 −0
docs/features/pageless-doors.md added +11
@@ -0,0 +1,11 @@
1 ---
2 topic: Agents: MCP, git, or the terminal
3 row: Doors with no page: the tools an agent has that a person cannot press
4 ---
5 # Doors with no page
6
7 An MCP tool that writes, or a Talk press (a key of `ASKING` in `src/crew/conversation_confirm.ts`), is a door for an agent. A person should reach the same write on a page that posts through the same `src/actions/` function.
8
9 `bun scripts/pageless.ts` lists the doors with none; `test/pageless-doors.test.ts` fails on one not named in `scripts/pageless-allow.json`, and on a listed one that gained a page (`--write` prunes). The list only shrinks.
10
11 Make a machine is the compose form on `/infra/build` (`src/web/pages/infra.ts`, posting to `/infra/apply`, which calls `startBuild` as the `infra` tool does). Mail setup is the card on `/settings/secrets` (`src/web/render/mail_aws_card.ts`, posting to `/settings/mail-aws`, which calls `setUpMailAws`). Terminal: `src/tui/screens/infra.ts`, `src/tui/screens/secrets.ts`.
scripts/pageless-allow.json added +38
@@ -0,0 +1,38 @@
1 [
2 "app_data_import",
3 "app_registry",
4 "archive",
5 "atlas",
6 "attach_look",
7 "board_write",
8 "bring",
9 "changes",
10 "claim_link",
11 "cloud_accounts",
12 "decider_shadow",
13 "decisions_by",
14 "estimate",
15 "feed_dismiss",
16 "feed_like",
17 "flag_set",
18 "invite",
19 "keep_plan",
20 "land_past_gate",
21 "maintenance",
22 "notify",
23 "outsiders",
24 "parent_unlink",
25 "registry_install",
26 "release_hold",
27 "release_now",
28 "restore_drill",
29 "rollback",
30 "share",
31 "spawn",
32 "subscription_add",
33 "subscription_budget",
34 "subscription_delete",
35 "subscription_headroom",
36 "subscription_wake",
37 "talk_watch"
38 ]
scripts/pageless.ts added +57
@@ -0,0 +1,57 @@
1 /**
2 * Doors with no page (#18479, P18 of #334). A write the forge offers as an MCP tool or holds as a
3 * Talk press (a key of `ASKING`, `src/crew/conversation_confirm.ts`) is reachable by an agent; a
4 * person should reach the same write on a page that posts to the same function. This reads the
5 * tree: a door is the tool's `name`; it has a page when a module a page posts through (under
6 * `src/web/`, or a route module `src/http/**` outside the JSON API and MCP) imports a name the tool
7 * imports from `src/actions/`. A door with none is listed in `scripts/pageless-allow.json`, and the
8 * list only shrinks: `--write` prunes the doors that gained a page.
9 */
10
11 import { readFileSync, writeFileSync } from "node:fs";
12 import { join } from "node:path";
13
14 const files = (root: string, glob: string) => [...new Bun.Glob(glob).scanSync({ cwd: root })].sort();
15
16 /** The names a module imports (not types) from `src/actions/`, whatever the depth of its path. */
17 export function actionNames(text: string): string[] {
18 const out: string[] = [];
19 for (const m of text.matchAll(/import\s+(?!type\b)\{([^}]*)\}\s+from\s+["'][./]*\/actions\/[\w./-]+["']/g))
20 for (const part of m[1]!.split(",")) {
21 const n = part.trim();
22 if (n !== "" && !n.startsWith("type ")) out.push((n.split(/\s+as\s+/)[0] ?? n).trim());
23 }
24 return out;
25 }
26
27 /** The tool names that are doors: a tool that writes, or one `ASKING` holds. */
28 export function pagelessDoors(root: string): string[] {
29 const read = (f: string) => readFileSync(join(root, f), "utf8");
30 const asking = read("src/crew/conversation_confirm.ts");
31 const held = new Set([...(asking.split("export const ASKING")[1] ?? "").split("\n};")[0]!.matchAll(/^ {2}(\w+): /gm)].map((m) => m[1]!));
32 const paged = new Set<string>();
33 const pageFiles = [...files(root, "src/web/**/*.ts"), ...files(root, "src/http/**/*.ts").filter((f) => !/\/(api|mcp)\//.test(f) && !f.includes("/contract/"))];
34 for (const f of pageFiles) for (const n of actionNames(read(f))) paged.add(n);
35 const out: string[] = [];
36 for (const f of files(root, "src/http/mcp/tools/*.ts")) {
37 const text = read(f);
38 const name = /^ {2}name: "([\w-]+)"/m.exec(text)?.[1];
39 if (name === undefined || !(held.has(name) || /^ {2}writes: true/m.test(text))) continue;
40 if (!actionNames(text).some((n) => paged.has(n))) out.push(name);
41 }
42 return out.sort();
43 }
44
45 if (import.meta.main) {
46 const root = join(import.meta.dir, "..");
47 const path = join(root, "scripts/pageless-allow.json");
48 const found = pagelessDoors(root);
49 if (process.argv.includes("--write")) {
50 const kept = (JSON.parse(readFileSync(path, "utf8")) as string[]).filter((p) => found.includes(p));
51 writeFileSync(path, JSON.stringify(kept, null, 2) + "\n");
52 console.log(`kept ${kept.length}`);
53 } else if (process.argv.includes("--init")) {
54 writeFileSync(path, JSON.stringify(found, null, 2) + "\n");
55 console.log(`wrote ${found.length}`);
56 } else console.log(found.join("\n"));
57 }
test/pageless-doors.test.ts added +165
@@ -0,0 +1,165 @@
1 /**
2 * Doors with no page (#18479, P18 of #334): every MCP tool that writes, or that Talk holds as a
3 * press, is reached by a person on a page that posts through the same `src/actions/` function, or
4 * is listed in `scripts/pageless-allow.json`, and the list only shrinks. "Make a machine" (/infra)
5 * and "mail setup" (/settings/secrets) have their controls, and these tests press them.
6 */
7 import { afterAll, beforeAll, expect, test } from "bun:test";
8 import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
9 import { mkdtemp, rm } from "node:fs/promises";
10 import { tmpdir } from "node:os";
11 import { dirname, join } from "node:path";
12 import { actionNames, pagelessDoors } from "../scripts/pageless.ts";
13 import allowed from "../scripts/pageless-allow.json";
14 import { createApp, type App } from "../src/app.ts";
15 import { addAccount, allowWrite, net as cloudNet } from "../src/actions/cloud.ts";
16 import { createSession } from "../src/core/sessions.ts";
17 import { createUser, type User } from "../src/core/users.ts";
18 import { getMailAws } from "../src/core/mail_aws.ts";
19 import { forgeHttp } from "../src/http/server.ts";
20 import { quietLogs } from "./helpers/globals.ts";
21 import { promote } from "./helpers/members.ts";
22 import { seedPlaces } from "./helpers/places-fixture.ts";
23
24 quietLogs();
25
26 const root = new URL("..", import.meta.url).pathname;
27 const found = pagelessDoors(root);
28
29 test("every write door has a page, or is allowed", () => {
30 const fresh = found.filter((d) => !allowed.includes(d));
31 expect(fresh, `these MCP tools or Talk presses have no page that posts through their actions function; add the control (a page or a form on one) or, only if truly intended, list the tool in scripts/pageless-allow.json: ${fresh.join(", ")}`).toEqual([]);
32 });
33
34 test("a listed door that gained a page fails: prune the list", () => {
35 const stale = allowed.filter((d) => !found.includes(d));
36 expect(stale, `these doors now have a page; run \`bun scripts/pageless.ts --write\`: ${stale.join(", ")}`).toEqual([]);
37 });
38
39 /**
40 * Lower this when the list shrinks; raising it is adding a door with no page, which review refuses.
41 */
42 const CEILING = 36;
43
44 test("the allow list cannot gain a door", () => {
45 expect(allowed.length).toBeLessThanOrEqual(CEILING);
46 });
47
48 test("make a machine and mail setup are not on the list: each has a control", () => {
49 expect(allowed).not.toContain("infra");
50 expect(allowed).not.toContain("secrets");
51 expect(found).not.toContain("infra");
52 expect(found).not.toContain("secrets");
53 });
54
55 test("actionNames reads the functions a module takes from actions/, never types or other layers", () => {
56 const text = 'import { a, type B, c as d } from "../../../actions/x.ts";\nimport type { E } from "../../actions/y.ts";\nimport { f } from "../core/z.ts";\n';
57 expect(actionNames(text)).toEqual(["a", "c"]);
58 });
59
60 test("pagelessDoors() names a write tool no page posts through, and a shared function clears it", () => {
61 const dir = mkdtempSync(join(process.env.TMPDIR ?? tmpdir(), "pageless-"));
62 const put = (path: string, text: string) => {
63 const at = join(dir, path);
64 mkdirSync(dirname(at), { recursive: true });
65 writeFileSync(at, text, "utf8");
66 };
67 try {
68 put("src/crew/conversation_confirm.ts", "export const ASKING = {\n held: {},\n};\n");
69 const tool = (name: string, fn: string, writes: boolean) => put(`src/http/mcp/tools/${name}.ts`, `import { ${fn} } from "../../../actions/${name}.ts";\nexport const tool = {\n name: "${name}",\n${writes ? " writes: true,\n" : ""}};\n`);
70 tool("alone", "doAlone", true);
71 tool("shared", "doShared", true);
72 tool("held", "doHeld", false);
73 tool("reads", "doReads", false);
74 put("src/web/pages/shared.ts", 'import { doShared } from "../../actions/shared.ts";\n');
75 put("src/http/api/held.ts", 'import { doHeld } from "../../actions/held.ts";\n');
76 expect(pagelessDoors(dir)).toEqual(["alone", "held"]);
77 } finally {
78 rmSync(dir, { recursive: true, force: true });
79 }
80 });
81
82 test("the infra tool and the /infra page start a build through the same function", () => {
83 const tool = readFileSync(join(root, "src/http/mcp/tools/infra.ts"), "utf8");
84 const routes = readFileSync(join(root, "src/http/infra_routes.ts"), "utf8");
85 expect(tool).toContain("startBuild(ctx.app, user, p)");
86 expect(routes).toContain("startBuild(ctx.app, ctx.auth.user, p");
87 expect(routes).toContain('may(ctx.app.db, principalOfUser(ctx.auth.user), "forge.administer")');
88 });
89
90 const HOST = "forge.test";
91 let dataDir = "";
92 let app: App;
93 let http: ReturnType<typeof forgeHttp>;
94 const users = {} as Record<"boss" | "gina", User>;
95 const cookie = (u: User) => ({ cookie: `forge_session=${createSession(app.db, u.id).token}` });
96 const send = (path: string, who: User | undefined, form?: Record<string, string>) =>
97 http.handle(new Request(`http://${HOST}${path}`, {
98 method: form === undefined ? "GET" : "POST",
99 headers: { ...(who === undefined ? {} : cookie(who)), origin: `http://${HOST}`, ...(form === undefined ? {} : { "content-type": "application/x-www-form-urlencoded" }) },
100 ...(form === undefined ? {} : { body: new URLSearchParams(form).toString() }),
101 }));
102
103 beforeAll(async () => {
104 process.env["FORGE_CELLS"] = "off";
105 dataDir = await mkdtemp(join(tmpdir(), "forge-pageless-"));
106 app = createApp({ dataDir, port: 0, host: HOST });
107 await seedPlaces(app.db);
108 for (const name of ["boss", "gina"] as const) {
109 const made = await createUser(app.db, { origin: "seed", trusted: true, username: name, email: `${name}@forge.local`, password: "a-good-passphrase", adminIfFirst: name === "boss" });
110 if (!made.ok) throw new Error(String(made.error));
111 users[name] = made.value;
112 }
113 promote(app.db, users.boss, users.gina);
114 cloudNet.fetch = async () => new Response(JSON.stringify({ account: { email: "[email protected]", status: "active" } }), { status: 200 });
115 const added = await addAccount(app, users.boss, "digitalocean", "main", "dop_v1_9Zq4TxLm7Kp2Vb8nWcR5");
116 if (!added.ok) throw new Error(String(added.error));
117 allowWrite(app, users.boss, "digitalocean", "main", true);
118 http = forgeHttp(app);
119 });
120
121 afterAll(async () => {
122 delete process.env["FORGE_CELLS"];
123 app.close();
124 await rm(dataDir, { recursive: true, force: true });
125 });
126
127 test("make a machine: /infra/build draws the compose form that posts to /infra/apply", async () => {
128 const res = await send("/infra/build", users.boss);
129 expect(res.status).toBe(200);
130 const page = await res.text();
131 expect(page).toContain('action="/infra/apply"');
132 expect(page).toContain("data-compose");
133 expect(page).toContain("digitalocean");
134 });
135
136 test("make a machine: pressing it asks may(forge.administer) first, and builds nothing from an empty form", async () => {
137 expect((await send("/infra/apply", users.gina, {})).status).toBe(403);
138 expect((await send("/infra/apply", undefined, {})).status).toBe(303);
139 const asked = await send("/infra/apply", users.boss, {});
140 expect(asked.status).toBeGreaterThanOrEqual(400);
141 expect(asked.headers.get("location")).toBeNull();
142 expect(app.db.query("SELECT count(*) AS n FROM event WHERE kind LIKE 'infra.%'").get()).toEqual({ n: 0 });
143 });
144
145 test("mail setup: Secrets draws the card, and without an AWS and a DNS account says what to attach", async () => {
146 const res = await send("/settings/secrets", users.boss);
147 expect(res.status).toBe(200);
148 const page = await res.text();
149 expect(page).toContain('id="mail-aws"');
150 expect(page).toContain("attach an AWS account");
151 });
152
153 test("mail setup: the control posts to /settings/mail-aws, and only an admin who ticked the box makes anything", async () => {
154 const set = { step: "set_up", aws: "main", dns: "edge", domain: "mail.example.com", region: "us-east-1" };
155 expect((await send("/settings/mail-aws", users.gina, set)).status).toBe(403);
156 expect((await send("/settings/mail-aws", undefined, set)).status).toBe(303);
157 const unticked = await send("/settings/mail-aws", users.boss, set);
158 expect(unticked.status).toBe(303);
159 expect(unticked.headers.get("location")).toContain("/settings/secrets");
160 expect(getMailAws(app.db)).toBeUndefined();
161 // Ticked, it reaches setUpMailAws, which refuses the accounts this forge does not hold.
162 const ticked = await send("/settings/mail-aws", users.boss, { ...set, confirm: "1" });
163 expect(ticked.status).toBe(303);
164 expect(getMailAws(app.db)).toBeUndefined();
165 });

Search
↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs