repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by admin

feat(the-system): synchronize live boards and verified execution

dfb29b6ac23ac43851ec0779e8b0857000ff2ad5

Oliver Jan Krylow <oliver@bugabinga.net> ·

SSH signature · not checked

Browse filesCompare with HEAD

Changed files (23)

extensions/the-system/CHANGELOG.md

Modified
15 15 - Align bundle-slot and board-proposal prompt metadata and tool rendering with Pi defaults.
16 16 - Keep board proposals and repeatable bundle slots available across clarification turns and compaction.
17 17 - Add a generally invocable vertical-slicing skill and require it for `/system exec`.
18 +- Treat plans as required outcome rather than implementation order, and remove slice boundaries as human approval points.
19 +- Make visual models the System Markdown default, require visuals in specs and plans, and decompose plans by behavior instead of architectural layer.
20 +- Let `/system exec` apply verified board states directly through `system_board_update` with `source: agent` and an evidence note, keeping `/system assess` proposal-only.
21 +- Inject a board state block with counts and unfinished items into every `/system` lifecycle prompt.
22 +- Compact the injected document contract without dropping rules.
18 23 - Replace unconditional core-document blocking with validated one-shot human approval.
19 24 - Let completed `/system exec` runs propose evidence-backed board updates for human review.
25 +- Serve `/system board` pages from a live snapshot that re-renders when `.system` changes, so refreshes show persisted state and open boards follow disk edits.
26 +- Toggle plan `status` and spec board state directly from the rendered metadata box.
21 28 ## 0.0.3

extensions/the-system/README.md

Modified
24 24 The agent calls it for each new bundle after choosing a semantic title, then uses the returned ID and path exactly.
25 25 Context determines which bundles, if any, the command creates.
27 -Assessment and exec temporarily enable `system_board_propose` through clarification until one proposal submission completes.
28 -Exec proposes evidence-backed updates for referenced bundles after fresh verification.
27 +Assessment temporarily enables `system_board_propose` through clarification until one proposal submission completes.
29 28 Proposals remain ephemeral until a human applies selected changes through `/system board`.
29 +Exec temporarily enables `system_board_update`, which writes verified states directly to `.system/board.json` with `source: agent` and a terse evidence note.
30 +Board invariants reject unsupported claims, and the human overrides any entry in `/system board`.
31 32 ## Board
33 34 Tracked operational state lives in `.system/board.json`; bundle content remains stateless about implementation progress.
34 35 Specs and plans use `todo|done`; issues use `open|done`.
35 36 Absent entries default to `todo` or `open`.
36 -Each explicit entry records `state`, `updatedAt`, and `source: manual|assess` without duplicating bundle content.
37 +Each explicit entry records `state`, `updatedAt`, and `source: manual|assess|agent`, plus an optional `note` of at most 200 characters, without duplicating bundle content.
38 +Later writes without a note clear it, so a manual override drops the agent claim.
39 +Lifecycle prompts carry a board state block listing counts and up to 20 unfinished items; it is omitted when the board is unreadable.
40 +The board serves every page from a live snapshot: a request for an HTML page re-renders it whenever any `.system` file changed, and the open page polls `GET /api/state` once per second.
41 +Board state changes patch the page in place; document changes reload it and restore the disclosures that were open.
42 +A plan's metadata box toggles `status` between `draft` and `approved` on disk, and a spec's metadata box toggles its board state.
37 43 A spec can be done without plans, but cannot be done while any linked plan is todo.
38 44 Spec toggles never change plan states.
39 45 Reopening a plan demotes its spec; issues never change spec state.

extensions/the-system/__e2e__/renderer.spec.ts

Modified
282 +test("/system board survives refresh, follows disk changes, and toggles metadata", async ({
283 + page,
284 +}) => {
285 + const root = systemFixture();
286 + const runtime = createBoardRuntime();
287 + try {
288 + const notice = await runtime.open(root);
289 + const url = notice.match(/http:\/\/127\.0\.0\.1:\d+\/\?k=[^\s]+/)?.[0];
290 + await page.goto(url ?? "");
292 + const spec = page.locator('[data-board-item][data-id="PX-SPEC-SPEC0001"]');
293 + const planA = page.locator('[data-board-item][data-id="PX-PLAN-PLAN0001"]');
294 + const planB = page.locator('[data-board-item][data-id="PX-PLAN-PLAN0002"]');
295 + await planA.locator(".board-state").click();
296 + await expect(planA).toHaveClass(/is-done/);
298 + await page.reload();
299 + await expect(planA).toHaveClass(/is-done/);
300 + await expect(planB).not.toHaveClass(/is-done/);
302 + write(
303 + root,
304 + ".system/issues/PX-ISSUE-ISSUE002-later/index.md",
305 + "---\nid: PX-ISSUE-ISSUE002\ntype: issue\ntitle: Later\nspecs: [PX-SPEC-SPEC0001]\n---\n\n# Later\n",
306 + );
307 + const late = page.locator('[data-board-item][data-id="PX-ISSUE-ISSUE002"]');
308 + await expect(late).toBeVisible({ timeout: 15000 });
310 + const planLedger = planB.locator(":scope > .board-row .ledger");
311 + await planB
312 + .locator(":scope > .board-row > .board-bundle > summary")
313 + .click();
314 + await planLedger.locator("summary").click();
315 + await planLedger.locator("[data-status-toggle]").click();
316 + await expect(
317 + planB.locator(":scope > .board-row > .board-bundle > summary"),
318 + ).toContainText("approved", { timeout: 15000 });
319 + expect(
320 + readFileSync(
321 + path.join(root, ".system/plans/PX-PLAN-PLAN0002-test/index.md"),
322 + "utf8",
323 + ),
324 + ).toContain("status: approved");
326 + await planB.locator(".board-state").click();
327 + await expect(planB).toHaveClass(/is-done/);
328 + await spec.locator(":scope > .board-row > .board-bundle > summary").click();
329 + const specLedger = spec.locator(":scope > .board-row .ledger");
330 + await specLedger.locator("summary").click();
331 + const boardToggle = specLedger.locator("[data-board-toggle]");
332 + await expect(boardToggle).toHaveText("todo");
333 + await boardToggle.click();
334 + await expect(boardToggle).toHaveText("done");
335 + await expect(spec).toHaveClass(/is-done/);
336 + const board = JSON.parse(
337 + readFileSync(path.join(root, ".system/board.json"), "utf8"),
338 + );
339 + expect(board.items["PX-SPEC-SPEC0001"].state).toBe("done");
340 + } finally {
341 + runtime.shutdown();
343 +});
282 345 async function assertSidebarConnected(page: {
283 346 evaluate: <T>(fn: () => T) => Promise<T>;

extensions/the-system/__tests__/board-runtime.test.ts

Modified
38 38 assert.notEqual(tool.promptSnippet, tool.description);
39 39 assert.match(tool.description, /does not modify \.system\/board\.json/);
40 40 assert.deepEqual(tool.promptGuidelines, [
41 - "During /system assess or after completing /system exec, call system_board_propose exactly once with evidence-backed state changes; use an empty items list when no changes are justified.",
41 + "During /system assess, call system_board_propose exactly once with evidence-backed state changes; use an empty items list when no changes are justified.",
45 + it("describes the exec update tool as an applying board writer", () => {
46 + const tool = createBoardRuntime().updateTool;
48 + assert.equal(tool.label, "system_board_update");
49 + assert.equal(
50 + tool.promptSnippet,
51 + "Update System board states from verified work",
52 + );
53 + assert.match(tool.description, /Apply verified board states/);
54 + assert.deepEqual(tool.promptGuidelines, [
55 + "After fresh verification in /system exec, call system_board_update exactly once with the states your work proves; use an empty items list when no change is justified.",
56 + ]);
57 + assert.ok(tool.renderCall);
58 + const call = render(
59 + tool.renderCall(
60 + {
61 + items: [
62 + {
63 + id: "PX-PLAN-PLAN0001",
64 + state: "done",
65 + note: "Slice verified by test run.",
66 + },
67 + ],
68 + },
69 + theme,
70 + renderContext(true),
71 + ),
72 + );
73 + assert.match(call, /^system_board_update 1 item/);
74 + assert.match(call, /DONE PX-PLAN-PLAN0001/);
75 + assert.match(call, /Slice verified by test run\./);
76 + assert.ok(tool.renderResult);
77 + assert.equal(
78 + render(
79 + tool.renderResult(
80 + { content: [], details: { items: [] } },
81 + { expanded: false, isPartial: false },
82 + theme,
83 + renderContext(false),
84 + ),
85 + ).trimEnd(),
86 + "✓ no board changes",
87 + );
88 + assert.equal(
89 + render(
90 + tool.renderResult(
91 + { content: [], details: { items } },
92 + { expanded: false, isPartial: false },
93 + theme,
94 + renderContext(false),
95 + ),
96 + ).trimEnd(),
97 + "✓ 2 board changes applied",
98 + );
99 + });
45 101 it("keeps proposal details behind expansion and renders errors", () => {
46 102 const tool = createBoardRuntime().tool;
47 103 assert.ok(tool.renderCall);

extensions/the-system/__tests__/board-server.test.ts

Added
new file mode 100644
1 +import assert from "node:assert/strict";
2 +import {
3 + mkdirSync,
4 + mkdtempSync,
5 + readFileSync,
6 + rmSync,
7 + writeFileSync,
8 +} from "node:fs";
9 +import { tmpdir } from "node:os";
10 +import path from "node:path";
11 +import { afterEach, describe, it } from "vitest";
12 +import {
13 + type BoardRenderer,
14 + type BoardServer,
15 + boardSignature,
16 + startBoardServer,
17 +} from "../board-server.ts";
18 +import { planStatusSource } from "../plan-status.ts";
20 +const roots: string[] = [];
21 +const servers: BoardServer[] = [];
23 +afterEach(() => {
24 + for (const server of servers.splice(0)) server.close();
25 + for (const root of roots.splice(0))
26 + rmSync(root, { recursive: true, force: true });
27 +});
29 +describe("board signature", () => {
30 + it("separates document changes from board state changes", () => {
31 + const root = fixture();
32 + const initial = boardSignature(root);
34 + write(root, ".system/board.json", boardJson({}));
35 + const afterBoard = boardSignature(root);
36 + assert.equal(afterBoard.documents, initial.documents);
37 + assert.notEqual(afterBoard.board, initial.board);
39 + write(
40 + root,
41 + ".system/specs/PX-SPEC-SPEC0001-contract/index.md",
42 + `${spec()}\nmore\n`,
43 + );
44 + const afterDocument = boardSignature(root);
45 + assert.notEqual(afterDocument.documents, afterBoard.documents);
46 + assert.equal(afterDocument.board, afterBoard.board);
47 + });
48 +});
50 +describe("plan status source", () => {
51 + it("rewrites exactly one status line and preserves the body", () => {
52 + const updated = planStatusSource(plan("draft"), "approved");
53 + assert.equal(updated, plan("approved"));
54 + });
56 + it("preserves CRLF frontmatter", () => {
57 + const source = plan("draft").replaceAll("\n", "\r\n");
58 + assert.equal(
59 + planStatusSource(source, "approved"),
60 + plan("approved").replaceAll("\n", "\r\n"),
61 + );
62 + });
64 + it("rejects documents without a single status line", () => {
65 + assert.throws(
66 + () => planStatusSource("# Plan\n", "approved"),
67 + /frontmatter/,
68 + );
69 + assert.throws(
70 + () =>
71 + planStatusSource(
72 + plan("draft").replace(
73 + "status: draft",
74 + "status: draft\nstatus: draft",
75 + ),
76 + "approved",
77 + ),
78 + /exactly one status line/,
79 + );
80 + });
81 +});
83 +describe("board server", () => {
84 + it("re-renders stale pages and serves live board state", async () => {
85 + const root = fixture();
86 + let renders = 0;
87 + const client = await open(root, (_index, board, _proposals, revision) => {
88 + renders += 1;
89 + const directory = mkdtempSync(path.join(tmpdir(), "board-site-"));
90 + roots.push(directory);
91 + writeFileSync(
92 + path.join(directory, "index.html"),
93 + `<body data-revision="${revision}" data-renders="${renders}" data-items="${
94 + Object.keys(board.items).length
95 + }">`,
96 + "utf8",
97 + );
98 + return { directory };
99 + });
101 + assert.equal(renders, 1);
102 + assert.match(await client.text("/"), /data-renders="1"/);
103 + assert.match(await client.text("/"), /data-renders="1"/);
105 + const before = await client.json("/api/state");
106 + assert.deepEqual(before.items, {});
107 + assert.equal(typeof before.revision, "string");
109 + const applied = await client.post("/api/state", {
110 + id: "PX-PLAN-PLAN0001",
111 + state: "done",
112 + });
113 + assert.equal(applied.items["PX-PLAN-PLAN0001"].state, "done");
114 + const after = await client.json("/api/state");
115 + assert.equal(after.items["PX-PLAN-PLAN0001"].state, "done");
116 + assert.equal(after.revision, before.revision);
118 + const reloaded = await client.text("/");
119 + assert.match(reloaded, /data-renders="2"/);
120 + assert.match(reloaded, /data-items="1"/);
122 + write(
123 + root,
124 + ".system/issues/PX-ISSUE-ISSUE002-later/index.md",
125 + "---\nid: PX-ISSUE-ISSUE002\ntype: issue\ntitle: Later\nspecs: [PX-SPEC-SPEC0001]\n---\n\n# Later\n",
126 + );
127 + const changed = await client.json("/api/state");
128 + assert.notEqual(changed.revision, before.revision);
129 + assert.match(await client.text("/"), /data-renders="3"/);
130 + const late = await client.post("/api/state", {
131 + id: "PX-ISSUE-ISSUE002",
132 + state: "done",
133 + });
134 + assert.equal(late.items["PX-ISSUE-ISSUE002"].state, "done");
135 + });
137 + it("toggles plan status on disk and rejects other documents", async () => {
138 + const root = fixture();
139 + const client = await open(root);
140 + const planPath = ".system/plans/PX-PLAN-PLAN0001-build/index.md";
142 + const result = await client.post("/api/status", {
143 + id: "PX-PLAN-PLAN0001",
144 + status: "approved",
145 + });
146 + assert.deepEqual(result, { id: "PX-PLAN-PLAN0001", status: "approved" });
147 + assert.match(read(root, planPath), /^status: approved$/m);
149 + await client.post("/api/status", {
150 + id: "PX-PLAN-PLAN0001",
151 + status: "draft",
152 + });
153 + assert.equal(read(root, planPath), plan("draft"));
155 + assert.match(
157 + await client.failing("/api/status", {
158 + id: "PX-SPEC-SPEC0001",
159 + status: "approved",
160 + })
161 + ).error,
162 + /Only plans carry a status/,
163 + );
164 + assert.match(
166 + await client.failing("/api/status", {
167 + id: "PX-PLAN-PLAN0001",
168 + status: "shipped",
169 + })
170 + ).error,
171 + /Expected plan update with id and status/,
172 + );
173 + });
174 +});
176 +const stubRenderer: BoardRenderer = (_index, _board, _proposals, revision) => {
177 + const directory = mkdtempSync(path.join(tmpdir(), "board-site-"));
178 + roots.push(directory);
179 + writeFileSync(
180 + path.join(directory, "index.html"),
181 + `<body data-revision="${revision}">`,
182 + "utf8",
183 + );
184 + return { directory };
187 +async function open(root: string, render: BoardRenderer = stubRenderer) {
188 + const server = await startBoardServer(root, new Map(), render);
189 + servers.push(server);
190 + const url = new URL(server.url);
191 + const handshake = await fetch(server.url, { redirect: "manual" });
192 + const cookie = (handshake.headers.get("set-cookie") ?? "").split(";")[0];
193 + assert.equal(handshake.status, 303);
194 + assert.ok(cookie);
195 + const origin = `${url.protocol}//${url.host}`;
196 + const request = (target: string, init?: RequestInit) =>
197 + fetch(`${origin}${target}`, {
198 + ...init,
199 + headers: { ...(init?.headers ?? {}), cookie: cookie ?? "" },
200 + });
201 + const send = (target: string, payload: unknown) =>
202 + request(target, {
203 + method: "POST",
204 + headers: { "content-type": "application/json", origin },
205 + body: JSON.stringify(payload),
206 + });
207 + return {
208 + async text(target: string) {
209 + const response = await request(target);
210 + assert.equal(response.status, 200);
211 + return response.text();
212 + },
213 + async json(target: string) {
214 + const response = await request(target);
215 + assert.equal(response.status, 200);
216 + return (await response.json()) as never;
217 + },
218 + async post(target: string, payload: unknown) {
219 + const response = await send(target, payload);
220 + assert.equal(response.status, 200);
221 + return (await response.json()) as never;
222 + },
223 + async failing(target: string, payload: unknown) {
224 + const response = await send(target, payload);
225 + assert.equal(response.status, 400);
226 + return (await response.json()) as { error: string };
227 + },
228 + };
231 +const boardJson = (items: Record<string, unknown>) =>
232 + `${JSON.stringify({ schemaVersion: 0, items }, null, "\t")}\n`;
234 +const spec = () =>
235 + "---\nid: PX-SPEC-SPEC0001\ntype: spec\ntitle: Contract\n---\n\n# Contract\n";
237 +const plan = (status: string) =>
238 + `---\nid: PX-PLAN-PLAN0001\ntype: plan\ntitle: Build\nspec: PX-SPEC-SPEC0001\nstatus: ${status}\n---\n\n# Build\n`;
240 +function fixture(): string {
241 + const root = mkdtempSync(path.join(tmpdir(), "board-server-"));
242 + roots.push(root);
243 + mkdirSync(path.join(root, ".git"));
244 + for (const directory of ["specs", "phases", "plans", "issues", "research"])
245 + mkdirSync(path.join(root, ".system", directory), { recursive: true });
246 + write(root, ".system/config.json", '{"prefix":"PX","schemaVersion":0}');
247 + write(root, ".system/board.json", '{"schemaVersion":0,"items":{}}');
248 + write(root, ".system/SYSTEM.md", "# SYSTEM\n");
249 + write(root, ".system/specs/PX-SPEC-SPEC0001-contract/index.md", spec());
250 + write(root, ".system/plans/PX-PLAN-PLAN0001-build/index.md", plan("draft"));
251 + return root;
254 +function write(root: string, relative: string, content: string) {
255 + const target = path.join(root, relative);
256 + mkdirSync(path.dirname(target), { recursive: true });
257 + writeFileSync(target, content, "utf8");
260 +const read = (root: string, relative: string) =>
261 + readFileSync(path.join(root, relative), "utf8");

extensions/the-system/__tests__/board-state.test.ts

Modified
132 132 assert.equal(boardStateFor(board, planB.metadata), "done");
135 + it("round-trips agent entries with notes and clears them on later writes", () => {
136 + let board = updateBoardState(
137 + emptyBoardState(),
138 + documents,
139 + planA.metadata.id,
140 + "done",
141 + "agent",
142 + at,
143 + " exec verified: 12 tests pass ",
144 + );
145 + assert.deepEqual(board.items[planA.metadata.id], {
146 + state: "done",
147 + source: "agent",
148 + updatedAt: at,
149 + note: "exec verified: 12 tests pass",
150 + });
151 + assert.deepEqual(parseBoardState(boardStateSource(board), "PX"), board);
152 + board = updateBoardState(
153 + board,
154 + documents,
155 + planA.metadata.id,
156 + "todo",
157 + "manual",
158 + at,
159 + );
160 + assert.deepEqual(board.items[planA.metadata.id], {
161 + state: "todo",
162 + source: "manual",
163 + updatedAt: at,
164 + });
165 + });
167 + it("rejects unknown sources and oversized notes", () => {
168 + const entry = (extra: string) =>
169 + `{"schemaVersion":0,"items":{"${planA.metadata.id}":{"state":"done","source":${extra}}}}`;
170 + assert.throws(
171 + () => parseBoardState(entry(`"robot","updatedAt":"${at}"`), "PX"),
172 + (error: unknown) =>
173 + error instanceof SystemDocumentError && error.code === "board.source",
174 + );
175 + assert.throws(
176 + () =>
177 + parseBoardState(
178 + entry(`"agent","updatedAt":"${at}","note":"${"x".repeat(201)}"`),
179 + "PX",
180 + ),
181 + (error: unknown) =>
182 + error instanceof SystemDocumentError && error.code === "board.note",
183 + );
184 + assert.throws(
185 + () =>
186 + parseBoardState(entry(`"agent","updatedAt":"${at}","why":"x"`), "PX"),
187 + (error: unknown) =>
188 + error instanceof SystemDocumentError && error.code === "board.keys",
189 + );
190 + });
135 192 it("parses strict schema 0 and directly rewrites version mismatches", () => {
136 193 const current = updateBoardState(
137 194 emptyBoardState(),

extensions/the-system/__tests__/board-summary.test.ts

Added
new file mode 100644
1 +import assert from "node:assert/strict";
2 +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
3 +import { tmpdir } from "node:os";
4 +import path from "node:path";
5 +import { afterEach, describe, it } from "vitest";
6 +import { boardSummaryBlock } from "../board-summary.ts";
8 +const roots: string[] = [];
9 +const write = (root: string, relative: string, content: string) => {
10 + const target = path.join(root, relative);
11 + mkdirSync(path.dirname(target), { recursive: true });
12 + writeFileSync(target, content);
13 +};
15 +const project = (board: string): string => {
16 + const root = mkdtempSync(path.join(tmpdir(), "system-board-summary-"));
17 + roots.push(root);
18 + mkdirSync(path.join(root, ".git"));
19 + for (const file of ["SYSTEM.md", "MISSION.md", "RULES.md"])
20 + write(root, `.system/${file}`, `# ${file}\n`);
21 + write(root, ".system/config.json", '{"prefix":"PX","schemaVersion":0}');
22 + write(root, ".system/board.json", board);
23 + write(
24 + root,
25 + ".system/specs/PX-SPEC-SPEC0001-contract/index.md",
26 + "---\nid: PX-SPEC-SPEC0001\ntype: spec\ntitle: Contract\n---\n\n# Contract\n",
27 + );
28 + write(
29 + root,
30 + ".system/plans/PX-PLAN-PLAN0001-build/index.md",
31 + "---\nid: PX-PLAN-PLAN0001\ntype: plan\ntitle: Build\nspec: PX-SPEC-SPEC0001\nstatus: approved\n---\n\n# Build\n",
32 + );
33 + write(
34 + root,
35 + ".system/issues/PX-ISSUE-ISSUE001-bug/index.md",
36 + "---\nid: PX-ISSUE-ISSUE001\ntype: issue\ntitle: Bug\nspecs:\n - PX-SPEC-SPEC0001\n---\n\n# Bug\n",
37 + );
38 + return root;
39 +};
41 +afterEach(() => {
42 + for (const root of roots.splice(0))
43 + rmSync(root, { recursive: true, force: true });
44 +});
46 +describe("board summary block", () => {
47 + it("counts tracked items and lists unfinished work with provenance", () => {
48 + const now = Date.parse("2026-03-22T12:00:00.000Z");
49 + const root = project(
50 + JSON.stringify({
51 + schemaVersion: 0,
52 + items: {
53 + "PX-PLAN-PLAN0001": {
54 + state: "done",
55 + updatedAt: "2026-03-20T12:00:00.000Z",
56 + source: "agent",
57 + note: "exec verified",
58 + },
59 + },
60 + }),
61 + );
62 + const block = boardSummaryBlock(root, now) ?? "";
63 + assert.match(block, /# The System board state/);
64 + assert.match(
65 + block,
66 + /specs 1 todo, 0 done\. plans 0 todo, 1 done\. issues 1 open, 0 done\./,
67 + );
68 + assert.match(block, /- PX-SPEC-SPEC0001 · Contract · todo · default/);
69 + assert.match(block, /- PX-ISSUE-ISSUE001 · Bug · open · default/);
70 + assert.doesNotMatch(block, /PX-PLAN-PLAN0001/);
71 + });
73 + it("shows entry source, age, and note for unfinished items", () => {
74 + const now = Date.parse("2026-03-22T12:00:00.000Z");
75 + const root = project(
76 + JSON.stringify({
77 + schemaVersion: 0,
78 + items: {
79 + "PX-SPEC-SPEC0001": {
80 + state: "todo",
81 + updatedAt: "2026-03-21T12:00:00.000Z",
82 + source: "agent",
83 + note: "slice one only",
84 + },
85 + },
86 + }),
87 + );
88 + assert.match(
89 + boardSummaryBlock(root, now) ?? "",
90 + /- PX-SPEC-SPEC0001 · Contract · todo · agent 1 day ago · slice one only/,
91 + );
92 + });
94 + it("stays silent when the board is unreadable", () => {
95 + const root = project('{"schemaVersion":9,"items":{}}');
96 + assert.equal(boardSummaryBlock(root), undefined);
97 + rmSync(path.join(root, ".system/board.json"));
98 + assert.equal(boardSummaryBlock(root), undefined);
99 + });
100 +});

extensions/the-system/__tests__/the-system.test.ts

Modified
152 152 assert.match(prompt, /complete, observable behavior/);
153 153 assert.match(prompt, /Do not batch work horizontally/);
154 154 assert.match(prompt, /freshly verify each slice before starting the next/);
155 + assert.match(prompt, /define required outcome, not implementation order/);
156 + assert.match(
157 + prompt,
158 + /Re-sequence layered plan content into vertical slices/,
159 + );
160 + assert.match(prompt, /Do not pause for human approval between slices/);
161 + });
163 + it("plans behavior decomposition with visual models", () => {
164 + const prompt = systemPromptFor("plan", "");
165 + assert.match(
166 + prompt,
167 + /Decompose by observable behavior, not by architectural layer/,
168 + );
169 + assert.match(prompt, /without a layer-by-layer build order/);
170 + assert.match(
171 + prompt,
172 + /Model the module and interface structure, or the behavior sequence, as a diagram/,
173 + );
174 + });
176 + it("defaults System Markdown to visual models", () => {
177 + const prompt = systemPromptFor("spec", "");
178 + assert.match(
179 + prompt,
180 + /Model structure, sequence, state, entities, and decisions visually by default/,
181 + );
182 + assert.match(prompt, /select a format first/);
183 + assert.match(prompt, /Terse governs prose, not models/);
157 186 it("registers /system and scoped extension tools", () => {
163 192 on() {},
164 193 } as never);
165 194 assert.deepEqual(commands, ["system"]);
166 - assert.deepEqual(tools, ["system_bundle_slot", "system_board_propose"]);
195 + assert.deepEqual(tools, [
196 + "system_bundle_slot",
197 + "system_board_propose",
198 + "system_board_update",
199 + ]);
169 202 it("keeps scoped tools through clarification until their existing completion signal", async () => {
174 207 | { handler: (args: string, ctx: unknown) => Promise<void> }
175 208 | undefined;
176 209 let boardTool: CapturedTool | undefined;
210 + let boardUpdateTool: CapturedTool | undefined;
177 211 let bundleSlotTool: CapturedTool | undefined;
178 212 let agentSettled: ((event: unknown, ctx: unknown) => void) | undefined;
179 213 registerTheSystem({
183 217 registerTool(definition: { name: string }) {
184 218 if (definition.name === "system_board_propose")
185 219 boardTool = definition as CapturedTool;
220 + if (definition.name === "system_board_update")
221 + boardUpdateTool = definition as CapturedTool;
186 222 if (definition.name === "system_bundle_slot")
187 223 bundleSlotTool = definition as CapturedTool;
238 274 agentSettled?.({}, ctx);
239 275 assert.ok(!activeTools.includes("system_board_propose"));
241 - await command.handler("exec PX-SPEC-SPEC0001", ctx);
242 - assert.ok(activeTools.includes("system_board_propose"));
243 - agentSettled?.({}, ctx);
244 - assert.ok(activeTools.includes("system_board_propose"));
245 - await boardTool.execute(
246 - "exec-proposal",
247 - {
248 - items: [
249 - {
250 - id: "PX-SPEC-SPEC0001",
251 - state: "done",
252 - rationale: "Fresh verification passed.",
253 - },
254 - ],
255 - },
256 - undefined,
257 - undefined,
258 - ctx,
259 - );
260 - agentSettled?.({}, ctx);
261 - assert.ok(!activeTools.includes("system_board_propose"));
262 277 assert.deepEqual(
263 278 JSON.parse(
264 279 readFileSync(path.join(project, ".system/board.json"), "utf8"),
266 281 { schemaVersion: 0, items: {} },
284 + await command.handler("exec PX-SPEC-SPEC0001", ctx);
285 + assert.ok(activeTools.includes("system_board_update"));
286 + assert.ok(!activeTools.includes("system_board_propose"));
287 + agentSettled?.({}, ctx);
288 + assert.ok(activeTools.includes("system_board_update"));
289 + assert.ok(boardUpdateTool);
290 + const updateItems = (
291 + items: { id: string; state: string; note: string }[],
292 + ) => ({ items });
293 + await assert.rejects(
294 + boardUpdateTool.execute(
295 + "exec-invalid",
296 + updateItems([
298 + id: "PX-SPEC-SPEC0001",
299 + state: "done",
300 + note: "Claimed without finished plans.",
301 + },
302 + ]),
303 + undefined,
304 + undefined,
305 + ctx,
306 + ),
307 + /cannot be done while plans remain todo/,
308 + );
309 + assert.deepEqual(
310 + JSON.parse(
311 + readFileSync(path.join(project, ".system/board.json"), "utf8"),
312 + ),
313 + { schemaVersion: 0, items: {} },
314 + );
315 + agentSettled?.({}, ctx);
316 + assert.ok(activeTools.includes("system_board_update"));
317 + await boardUpdateTool.execute(
318 + "exec-update",
319 + updateItems([
321 + id: "PX-PLAN-PLAN0001",
322 + state: "done",
323 + note: "Slice one verified.",
324 + },
326 + id: "PX-PLAN-PLAN0002",
327 + state: "done",
328 + note: "Slice two verified.",
329 + },
331 + id: "PX-SPEC-SPEC0001",
332 + state: "done",
333 + note: "Fresh verification passed.",
334 + },
335 + ]),
336 + undefined,
337 + undefined,
338 + ctx,
339 + );
340 + agentSettled?.({}, ctx);
341 + assert.ok(!activeTools.includes("system_board_update"));
342 + const applied = JSON.parse(
343 + readFileSync(path.join(project, ".system/board.json"), "utf8"),
344 + );
345 + assert.equal(applied.items["PX-SPEC-SPEC0001"].state, "done");
346 + assert.equal(applied.items["PX-SPEC-SPEC0001"].source, "agent");
347 + assert.equal(
348 + applied.items["PX-SPEC-SPEC0001"].note,
349 + "Fresh verification passed.",
350 + );
269 352 await command.handler("spec", ctx);
270 353 assert.ok(activeTools.includes("system_bundle_slot"));
271 354 agentSettled?.({}, ctx);
630 713 validSystem(project);
631 714 const sent: string[] = [];
632 715 let activations = 0;
633 - let boardRuns = 0;
716 + let proposalRuns = 0;
717 + let updateRuns = 0;
634 718 const command = createSystemCommand(
636 720 sendUserMessage: (message: string) => sent.push(message),
637 721 } as never,
639 723 activateBundleTool: () => activations++,
640 - activateBoardTool: () => boardRuns++,
724 + activateBoardProposal: () => proposalRuns++,
725 + activateBoardUpdate: () => updateRuns++,
643 728 for (const subcommand of [
657 742 assert.fail("lifecycle command must not wait"),
658 743 ui: { notify() {} },
659 744 } as never);
660 - for (const message of sent)
745 + for (const message of sent) {
661 746 assert.match(message, /The System document contract/);
747 + assert.match(message, /# The System board state/);
748 + assert.match(message, /PX-SPEC-SPEC0001 · Contract · todo · default/);
662 750 assert.equal(activations, 10);
663 - assert.equal(boardRuns, 4);
751 + assert.equal(proposalRuns, 2);
752 + assert.equal(updateRuns, 2);
664 753 assert.doesNotMatch(sent.join("\n"), /Extension-generated bundle slot/);
665 754 const execPrompt =
666 755 sent.find((item) => item.includes("# /system exec")) ?? "";
667 756 assert.match(execPrompt, /spec\+plan/);
668 - assert.match(execPrompt, /call system_board_propose exactly once/);
669 - assert.match(execPrompt, /never apply automatically/);
757 + assert.match(execPrompt, /call system_board_update exactly once/);
758 + assert.match(execPrompt, /The System board contract/);
759 + assert.match(execPrompt, /recorded with source agent/);
670 760 const assessPrompt =
671 761 sent.find((item) => item.includes("# /system assess")) ?? "";
672 762 assert.match(
685 775 item.includes("# /system spec\n") && item.includes("login flow"),
686 776 ) ?? "";
687 777 assert.match(specPrompt, /login flow/);
688 - assert.match(specPrompt, /Use mockups and diagrams when they clarify/);
778 + assert.match(specPrompt, /a prose-only spec is incomplete/);
779 + assert.match(specPrompt, /Use mockups for visual elements/);
689 780 assert.match(specPrompt, /Persist accepted visual assets/);
690 781 assert.match(
691 782 specPrompt,

extensions/the-system/__tests__/workflow-skills.test.ts

Modified
60 60 skill,
61 61 /A slice is complete only when its behavior is integrated, observable, tested, and freshly verified/,
63 + assert.match(
64 + skill,
65 + /A plan defines the required outcome, not the implementation order/,
66 + );
67 + assert.match(skill, /slice boundaries are not human approval points/);
63 68 assert.doesNotMatch(skill, /The System|\.system/);

extensions/the-system/board-runtime.ts

Modified
3 3 import { StringEnum } from "@earendil-works/pi-ai";
4 4 import { defineTool, keyHint } from "@earendil-works/pi-coding-agent";
5 5 import { Text } from "@earendil-works/pi-tui";
6 6 import { Type } from "typebox";
7 7 import type { BoardServer } from "./board-server.ts";
8 -import { type BoardProposal, readBoardState } from "./board-state.ts";
8 +import {
9 + BOARD_NOTE_LIMIT,
10 + type BoardProposal,
11 + readBoardState,
12 + updateBoardState,
13 + writeBoardState,
14 +} from "./board-state.ts";
9 15 import { discoverProjectRoot } from "./documents.ts";
16 +import {
17 + loadBoardServer,
18 + loadOpenBrowser,
19 + loadSystemRenderer,
20 +} from "./loaders.js";
10 21 import { loadProjectIndex } from "./project-index.ts";
11 22 import { expandableFallback } from "./tool-rendering.ts";
25 36 { minItems: 0, maxItems: 100 },
39 +const updateParameters = Type.Object({
40 + items: Type.Array(
41 + Type.Object({
42 + id: Type.String({ description: "Existing spec, plan, or issue ID." }),
43 + state: StringEnum(STATES, {
44 + description: "Board state for the item type.",
45 + }),
46 + note: Type.String({
47 + minLength: 1,
48 + maxLength: BOARD_NOTE_LIMIT,
49 + description: "Terse verified evidence stored with the board entry.",
50 + }),
51 + }),
52 + { minItems: 0, maxItems: 100 },
53 + ),
54 +});
56 +interface CallTheme {
57 + fg(style: string, text: string): string;
58 + bold(text: string): string;
61 +function renderBoardItems(
62 + name: string,
63 + args: { items?: unknown },
64 + theme: CallTheme,
65 + context: { expanded: boolean; lastComponent?: unknown },
66 +): Text {
67 + const text =
68 + (context.lastComponent as Text | undefined) ?? new Text("", 0, 0);
69 + const items = Array.isArray(args.items)
70 + ? (args.items as Record<string, unknown>[])
71 + : [];
72 + const count = items.length;
73 + let output = `${theme.fg("toolTitle", theme.bold(name))} ${theme.fg("toolOutput", `${count} item${count === 1 ? "" : "s"}`)}`;
74 + if (!context.expanded && count > 0) {
75 + output += theme.fg("dim", ` (${keyHint("app.tools.expand", "to expand")})`);
76 + } else {
77 + for (const item of items) {
78 + output += `\n${theme.fg("accent", String(item.state).toUpperCase())} ${theme.fg("toolOutput", String(item.id))}`;
79 + const evidence = item.rationale ?? item.note;
80 + if (evidence) output += `\n${theme.fg("dim", String(evidence))}`;
81 + }
82 + }
83 + text.setText(output);
84 + return text;
29 87 export function createBoardRuntime() {
30 88 let proposalRoot: string | undefined;
31 89 let proposalFinished = false;
90 + let updateRoot: string | undefined;
91 + let updateFinished = false;
32 92 const proposals = new Map<string, Map<string, BoardProposal>>();
33 93 const servers = new Set<BoardServer>();
34 94 const tool = defineTool({
38 98 "Record evidence-backed proposed board states for human review. Accepts existing spec, plan, or issue IDs and does not modify .system/board.json.",
39 99 promptSnippet: "Propose System board states for human review",
40 100 promptGuidelines: [
41 - "During /system assess or after completing /system exec, call system_board_propose exactly once with evidence-backed state changes; use an empty items list when no changes are justified.",
101 + "During /system assess, call system_board_propose exactly once with evidence-backed state changes; use an empty items list when no changes are justified.",
43 103 parameters: proposalParameters,
44 104 renderCall(args, theme, context) {
45 - const text =
46 - (context.lastComponent as Text | undefined) ?? new Text("", 0, 0);
47 - const items = Array.isArray(args.items) ? args.items : [];
48 - const count = items.length;
49 - let output = `${theme.fg("toolTitle", theme.bold("system_board_propose"))} ${theme.fg("toolOutput", `${count} item${count === 1 ? "" : "s"}`)}`;
50 - if (!context.expanded && count > 0) {
51 - output += theme.fg(
52 - "dim",
53 - ` (${keyHint("app.tools.expand", "to expand")})`,
54 - );
55 - } else {
56 - for (const item of items) {
57 - output += `\n${theme.fg("accent", String(item.state).toUpperCase())} ${theme.fg("toolOutput", String(item.id))}`;
58 - if (item.rationale)
59 - output += `\n${theme.fg("dim", String(item.rationale))}`;
60 - }
61 - }
62 - text.setText(output);
63 - return text;
105 + return renderBoardItems("system_board_propose", args, theme, context);
65 107 renderResult(result, { expanded }, theme, context) {
66 108 const text =
181 + const updateTool = defineTool({
182 + name: "system_board_update",
183 + label: "system_board_update",
184 + description:
185 + "Apply verified board states to .system/board.json with source agent. Accepts existing spec, plan, or issue IDs and rejects states that violate board invariants.",
186 + promptSnippet: "Update System board states from verified work",
187 + promptGuidelines: [
188 + "After fresh verification in /system exec, call system_board_update exactly once with the states your work proves; use an empty items list when no change is justified.",
189 + ],
190 + parameters: updateParameters,
191 + renderCall(args, theme, context) {
192 + return renderBoardItems("system_board_update", args, theme, context);
193 + },
194 + renderResult(result, { expanded }, theme, context) {
195 + const text =
196 + (context.lastComponent as Text | undefined) ?? new Text("", 0, 0);
197 + const items = (result.details as { items?: BoardProposal[] } | undefined)
198 + ?.items;
199 + if (!items) {
200 + text.setText(
201 + expandableFallback(
202 + result.content,
203 + expanded,
204 + theme,
205 + context.isError ? "error" : "muted",
206 + ),
207 + );
208 + return text;
210 + const count = items.length;
211 + text.setText(
212 + theme.fg(
213 + "success",
214 + count === 0
215 + ? "✓ no board changes"
216 + : `✓ ${count} board change${count === 1 ? "" : "s"} applied`,
217 + ),
218 + );
219 + return text;
220 + },
221 + async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
222 + const root = discoverProjectRoot(ctx.cwd);
223 + if (root !== updateRoot)
224 + throw new Error(
225 + "system_board_update is only available during /system exec",
226 + );
227 + const index = loadProjectIndex(root);
228 + let state = readBoardState(root, index.prefix);
229 + const updatedAt = new Date().toISOString();
230 + const applied: BoardProposal[] = [];
231 + for (const raw of params.items) {
232 + state = updateBoardState(
233 + state,
234 + index.documents,
235 + raw.id,
236 + raw.state,
237 + "agent",
238 + updatedAt,
239 + raw.note,
240 + );
241 + applied.push({
242 + id: raw.id,
243 + state: raw.state,
244 + rationale: raw.note.trim(),
245 + });
247 + if (applied.length > 0) writeBoardState(root, state);
248 + updateFinished = true;
249 + const items = [...applied].sort((left, right) =>
250 + left.id.localeCompare(right.id),
251 + );
252 + return {
253 + content: [
255 + type: "text" as const,
256 + text:
257 + applied.length === 0
258 + ? "No board states changed."
259 + : `${applied.length} board state(s) applied. Run /system board to review or override them.`,
260 + },
261 + ],
262 + details: { items },
263 + };
264 + },
265 + });
139 267 return {
269 + updateTool,
270 + beginUpdate(cwd: string) {
271 + const root = discoverProjectRoot(cwd);
272 + const index = loadProjectIndex(root);
273 + readBoardState(root, index.prefix);
274 + updateRoot = root;
275 + updateFinished = false;
276 + },
277 + updateComplete() {
278 + return updateRoot !== undefined && updateFinished;
279 + },
280 + endUpdate() {
281 + updateRoot = undefined;
282 + updateFinished = false;
283 + },
141 284 beginProposal(cwd: string) {
142 285 const root = discoverProjectRoot(cwd);
143 286 const index = loadProjectIndex(root);
156 299 async open(cwd: string): Promise<string> {
157 300 const index = loadProjectIndex(cwd);
158 - const state = readBoardState(index.root, index.prefix);
159 - const current = [...(proposals.get(index.root)?.values() ?? [])];
301 + readBoardState(index.root, index.prefix);
160 302 const [{ renderSystemBoardSite }, { startBoardServer }, { openUrl }] =
161 303 await Promise.all([
162 - import("./system-renderer.ts"),
163 - import("./board-server.ts"),
164 - import("./open-browser.ts"),
304 + loadSystemRenderer(),
305 + loadBoardServer(),
306 + loadOpenBrowser(),
166 - const output = renderSystemBoardSite(index, state, current);
308 + const current = proposals.get(index.root) ?? new Map();
309 + proposals.set(index.root, current);
167 310 const server = await startBoardServer(
168 - output.directory,
169 - index,
170 - proposals.get(index.root) ?? new Map(),
311 + index.root,
312 + current,
313 + (site, state, pending, revision) =>
314 + renderSystemBoardSite(site, state, pending, revision),
172 316 servers.add(server);
173 317 const opened = await openUrl(server.url);
178 322 shutdown() {
179 323 proposalRoot = undefined;
180 324 proposalFinished = false;
325 + updateRoot = undefined;
326 + updateFinished = false;
181 327 for (const server of servers) server.close();
182 328 servers.clear();

extensions/the-system/board-server.ts

Modified
1 -import { randomUUID } from "node:crypto";
2 -import { createReadStream, lstatSync, realpathSync, rmSync } from "node:fs";
1 +import { createHash, randomUUID } from "node:crypto";
2 +import {
3 + createReadStream,
4 + type Dirent,
5 + lstatSync,
6 + readdirSync,
7 + readFileSync,
8 + realpathSync,
9 + rmSync,
10 +} from "node:fs";
3 11 import {
4 12 createServer,
5 13 type IncomingMessage,
10 18 import {
11 19 type BoardItemState,
12 20 type BoardProposal,
21 + type BoardState,
13 22 readBoardState,
14 23 updateBoardState,
15 24 writeBoardState,
16 25 } from "./board-state.ts";
17 -import type { ProjectIndex } from "./project-index.ts";
26 +import { parseSystemConfig } from "./documents.ts";
27 +import { writePlanStatus } from "./plan-status.ts";
28 +import { loadProjectIndex, type ProjectIndex } from "./project-index.ts";
19 30 const BODY_LIMIT = 64 * 1024;
31 +const SIGNATURE_BYTE_LIMIT = 1024 * 1024;
20 32 const COOKIE = "the_system_board";
21 33 const STATES = ["todo", "done", "open"] as const;
34 +const STATUSES = ["draft", "approved"] as const;
23 36 export type BoardServer = Readonly<{ url: string; close(): void }>;
37 +export type BoardSignature = Readonly<{ documents: string; board: string }>;
38 +export type BoardRenderer = (
39 + index: ProjectIndex,
40 + board: BoardState,
41 + proposals: readonly BoardProposal[],
42 + revision: string,
43 +) => Readonly<{ directory: string }>;
45 +export function boardSignature(root: string): BoardSignature {
46 + const documents = createHash("sha256");
47 + const board = createHash("sha256");
48 + const systemRoot = path.join(root, ".system");
49 + for (const file of governedFiles(systemRoot)) {
50 + const relative = path.relative(systemRoot, file).split(path.sep).join("/");
51 + const digest = relative === "board.json" ? board : documents;
52 + digest.update(`${relative}\u0000`);
53 + const stats = lstatSync(file, { throwIfNoEntry: false });
54 + if (!stats?.isFile()) continue;
55 + if (stats.size > SIGNATURE_BYTE_LIMIT) {
56 + digest.update(`${stats.size}:${stats.mtimeMs}`);
57 + continue;
58 + }
59 + digest.update(readFileSync(file));
60 + }
61 + return { documents: documents.digest("hex"), board: board.digest("hex") };
64 +function governedFiles(directory: string): readonly string[] {
65 + let entries: Dirent[];
66 + try {
67 + entries = readdirSync(directory, { withFileTypes: true });
68 + } catch {
69 + return [];
70 + }
71 + return entries
72 + .sort((left, right) => left.name.localeCompare(right.name))
73 + .flatMap((entry) => {
74 + const target = path.join(directory, entry.name);
75 + if (entry.isSymbolicLink()) return [];
76 + if (entry.isDirectory()) return governedFiles(target);
77 + return entry.isFile() ? [target] : [];
78 + });
81 +type BoardSite = Readonly<{ signature: BoardSignature; directory: string }>;
25 83 export async function startBoardServer(
26 - directory: string,
27 - index: ProjectIndex,
84 + root: string,
28 85 proposals: Map<string, BoardProposal>,
86 + render: BoardRenderer,
29 87 ): Promise<BoardServer> {
30 88 const token = `${randomUUID()}-${randomUUID()}`;
31 89 const cookieName = `${COOKIE}_${token.slice(0, 8)}`;
32 - let server!: Server;
90 + const stale = new Set<string>();
91 + let site = renderSite(root, proposals, render);
92 + let renderError: string | undefined;
93 + const ensureSite = (): BoardSite => {
94 + const signature = boardSignature(root);
95 + if (
96 + signature.documents === site.signature.documents &&
97 + signature.board === site.signature.board
98 + )
99 + return site;
100 + const previous = site;
101 + try {
102 + site = renderSite(root, proposals, render, signature);
103 + renderError = undefined;
104 + } catch (error) {
105 + renderError = error instanceof Error ? error.message : String(error);
106 + return previous;
108 + discard(previous.directory, stale);
109 + return site;
110 + };
33 111 let mutation = Promise.resolve();
34 112 const enqueue = <T>(work: () => T): Promise<T> => {
35 113 const result = mutation.then(work, work);
40 118 return result;
42 - server = createServer((request, response) => {
120 + const server: Server = createServer((request, response) => {
43 121 void dispatch(request, response, {
44 - directory,
45 - index,
122 + root,
46 123 proposals,
47 124 token,
48 125 cookieName,
49 126 enqueue,
127 + ensureSite,
128 + currentSite: () => site,
129 + renderProblem: () => renderError,
52 132 await new Promise<void>((resolve, reject) => {
62 142 return {
63 143 url: `http://127.0.0.1:${address.port}/?k=${token}`,
64 144 close() {
145 + server.closeAllConnections();
65 146 server.close();
66 - rmSync(directory, { recursive: true, force: true });
147 + discard(site.directory, stale);
148 + for (const directory of [...stale]) discard(directory, stale);
153 +function renderSite(
154 + root: string,
155 + proposals: Map<string, BoardProposal>,
156 + render: BoardRenderer,
157 + signature = boardSignature(root),
158 +): BoardSite {
159 + const index = loadProjectIndex(root);
160 + const board = readBoardState(index.root, index.prefix);
161 + const output = render(
162 + index,
163 + board,
164 + [...proposals.values()].sort((left, right) =>
165 + left.id.localeCompare(right.id),
166 + ),
167 + signature.documents,
168 + );
169 + return { signature, directory: output.directory };
172 +function discard(directory: string, stale: Set<string>): void {
173 + try {
174 + rmSync(directory, { recursive: true, force: true });
175 + stale.delete(directory);
176 + } catch {
177 + stale.add(directory);
71 181 type DispatchState = Readonly<{
72 - directory: string;
73 - index: ProjectIndex;
182 + root: string;
74 183 proposals: Map<string, BoardProposal>;
75 184 token: string;
76 185 cookieName: string;
77 186 enqueue<T>(work: () => T): Promise<T>;
187 + ensureSite(): BoardSite;
188 + currentSite(): BoardSite;
189 + renderProblem(): string | undefined;
80 192 async function dispatch(
110 222 if (request.method === "POST" && url.pathname === "/api/state") {
111 223 const input = await readJsonBody(request);
112 224 const result = await state.enqueue(() =>
113 - applyState(state.index, input, "manual"),
225 + applyState(state.root, input, "manual"),
115 227 respondJson(response, 200, result);
116 228 return;
230 + if (request.method === "POST" && url.pathname === "/api/status") {
231 + const input = await readJsonBody(request);
232 + const result = await state.enqueue(() => applyStatus(state.root, input));
233 + respondJson(response, 200, result);
234 + return;
118 236 if (request.method === "POST" && url.pathname === "/api/proposal") {
119 237 const input = await readJsonBody(request);
120 238 if (typeof input.id !== "string" || typeof input.state !== "string")
123 241 if (!proposal || proposal.state !== input.state)
124 242 throw new Error(`No matching assessment proposal: ${input.id}`);
125 243 const result = await state.enqueue(() =>
126 - applyState(state.index, input, "assess"),
244 + applyState(state.root, input, "assess"),
128 246 state.proposals.delete(input.id);
129 247 respondJson(response, 200, result);
133 251 respondJson(response, 405, { error: "Method not allowed" });
134 252 return;
136 - serveFile(response, state.directory, url.pathname);
254 + if (url.pathname === "/api/state") {
255 + respondJson(response, 200, snapshot(state));
256 + return;
258 + const site = isDocument(url.pathname)
259 + ? state.ensureSite()
260 + : state.currentSite();
261 + serveFile(response, site.directory, url.pathname);
137 262 } catch (error) {
138 263 respondJson(response, 400, {
139 264 error: error instanceof Error ? error.message : String(error),
269 +const isDocument = (pathname: string) =>
270 + pathname === "/" || pathname.endsWith(".html");
272 +function snapshot(state: DispatchState) {
273 + const prefix = parseSystemConfig(
274 + readFileSync(path.join(state.root, ".system/config.json"), "utf8"),
275 + ).prefix;
276 + const board = readBoardState(state.root, prefix);
277 + const problem = state.renderProblem();
278 + return {
279 + revision: boardSignature(state.root).documents,
280 + items: board.items,
281 + ...(problem ? { problem } : {}),
282 + };
144 285 function applyState(
145 - index: ProjectIndex,
286 + root: string,
146 287 input: Record<string, unknown>,
147 288 source: "manual" | "assess",
153 294 !STATES.includes(input.state as (typeof STATES)[number])
155 296 throw new Error("Expected board update with id and state");
297 + const index = loadProjectIndex(root);
156 298 const current = readBoardState(index.root, index.prefix);
157 299 const updated = updateBoardState(
158 300 current,
165 307 return { items: updated.items };
310 +function applyStatus(root: string, input: Record<string, unknown>) {
311 + if (
312 + Object.keys(input).some((key) => key !== "id" && key !== "status") ||
313 + typeof input.id !== "string" ||
314 + typeof input.status !== "string" ||
315 + !STATUSES.includes(input.status as (typeof STATUSES)[number])
317 + throw new Error("Expected plan update with id and status");
318 + const index = loadProjectIndex(root);
319 + writePlanStatus(index, input.id, input.status as (typeof STATUSES)[number]);
320 + return { id: input.id, status: input.status };
168 323 function readJsonBody(
169 324 request: IncomingMessage,
170 325 ): Promise<Record<string, unknown>> {

extensions/the-system/board-state.ts

Modified
11 11 export const BOARD_SCHEMA_VERSION = 0;
12 12 export const BOARD_PATH = ".system/board.json";
14 +export const BOARD_NOTE_LIMIT = 200;
14 15 export type BoardItemState = "todo" | "done" | "open";
15 -export type BoardItemSource = "manual" | "assess";
16 +export type BoardItemSource = "manual" | "assess" | "agent";
16 17 export type BoardEntry = Readonly<{
17 18 state: BoardItemState;
18 19 updatedAt: string;
19 20 source: BoardItemSource;
21 + note?: string;
21 23 export type BoardProposal = Readonly<{
22 24 id: string;
44 46 value: Record<string, unknown>,
45 47 required: readonly string[],
46 48 label: string,
49 + optional: readonly string[] = [],
47 50 ) => {
48 51 const actual = Object.keys(value).sort();
50 53 required.some((key) => !(key in value)) ||
51 - actual.some((key) => !required.includes(key))
54 + actual.some((key) => !required.includes(key) && !optional.includes(key))
53 56 throw new SystemDocumentError(
54 57 "board.keys",
92 95 `Board item must reference a spec, plan, or issue: ${id}`,
94 97 const entry = objectValue(rawEntry, `Board item ${id}`);
95 - exactKeys(entry, ["source", "state", "updatedAt"], `Board item ${id}`);
98 + exactKeys(entry, ["source", "state", "updatedAt"], `Board item ${id}`, [
99 + "note",
100 + ]);
96 101 if (typeof entry.state !== "string")
97 102 throw new SystemDocumentError(
98 103 "board.state",
103 108 "board.state",
104 109 `Invalid ${parsedId.type} board state ${entry.state}: ${id}`,
106 - if (entry.source !== "manual" && entry.source !== "assess")
111 + if (
112 + entry.source !== "manual" &&
113 + entry.source !== "assess" &&
114 + entry.source !== "agent"
107 116 throw new SystemDocumentError(
108 117 "board.source",
109 118 `Invalid board source for ${id}`,
120 + if (
121 + entry.note !== undefined &&
122 + (typeof entry.note !== "string" ||
123 + entry.note.trim().length === 0 ||
124 + entry.note.length > BOARD_NOTE_LIMIT)
126 + throw new SystemDocumentError(
127 + "board.note",
128 + `Board note must be 1-${BOARD_NOTE_LIMIT} characters: ${id}`,
129 + );
112 131 typeof entry.updatedAt !== "string" ||
113 132 Number.isNaN(Date.parse(entry.updatedAt)) ||
121 140 state: entry.state as BoardItemState,
122 141 updatedAt: entry.updatedAt,
123 142 source: entry.source,
143 + ...(entry.note === undefined ? {} : { note: entry.note as string }),
126 146 return { schemaVersion: BOARD_SCHEMA_VERSION, items };
200 220 state: BoardItemState,
201 221 source: BoardItemSource,
202 222 updatedAt = new Date().toISOString(),
223 + note?: string,
203 224 ): BoardState {
204 225 const document = documents.find((candidate) => candidate.metadata.id === id);
205 226 if (!document)
212 233 "board.state",
213 234 `Invalid ${document.metadata.type} board state ${state}: ${id}`,
236 + const trimmedNote = note?.trim();
237 + if (trimmedNote !== undefined && trimmedNote.length > BOARD_NOTE_LIMIT)
238 + throw new SystemDocumentError(
239 + "board.note",
240 + `Board note must be 1-${BOARD_NOTE_LIMIT} characters: ${id}`,
241 + );
215 242 const items: Record<string, BoardEntry> = { ...board.items };
216 - items[id] = { state, source, updatedAt };
243 + items[id] = {
244 + state,
245 + source,
246 + updatedAt,
247 + ...(trimmedNote ? { note: trimmedNote } : {}),
248 + };
217 249 if (document.metadata.type === "spec" && state === "done") {
218 250 const unfinished = documents.filter(
219 251 (candidate) =>

extensions/the-system/board-summary.ts

Added
new file mode 100644
1 +import {
2 + type BoardEntry,
3 + boardStateFor,
4 + defaultBoardState,
5 + readBoardState,
6 +} from "./board-state.ts";
7 +import type { DocumentMetadata } from "./documents.ts";
8 +import { loadProjectIndex } from "./project-index.ts";
10 +const LISTED_ITEMS = 20;
11 +const TRACKED = ["spec", "plan", "issue"] as const;
12 +type TrackedType = (typeof TRACKED)[number];
14 +const age = (updatedAt: string, now: number): string => {
15 + const days = Math.max(
16 + 0,
17 + Math.floor((now - Date.parse(updatedAt)) / 86_400_000),
18 + );
19 + if (days === 0) return "today";
20 + return days === 1 ? "1 day ago" : `${days} days ago`;
21 +};
23 +const describe = (
24 + metadata: DocumentMetadata,
25 + entry: BoardEntry | undefined,
26 + now: number,
27 +): string => {
28 + const state = entry?.state ?? defaultBoardState(metadata);
29 + const origin = entry
30 + ? `${entry.source} ${age(entry.updatedAt, now)}`
31 + : "default";
32 + const note = entry?.note ? ` · ${entry.note}` : "";
33 + return `- ${metadata.id} · ${metadata.title} · ${state} · ${origin}${note}`;
34 +};
36 +export function boardSummaryBlock(
37 + cwd: string,
38 + now = Date.now(),
39 +): string | undefined {
40 + let documents: { metadata: DocumentMetadata }[];
41 + let items: Readonly<Record<string, BoardEntry>>;
42 + try {
43 + const index = loadProjectIndex(cwd);
44 + items = readBoardState(index.root, index.prefix).items;
45 + documents = index.documents;
46 + } catch {
47 + return undefined;
48 + }
49 + const tracked = documents.filter(
50 + (
51 + document,
52 + ): document is {
53 + metadata: DocumentMetadata & { type: TrackedType };
54 + } => TRACKED.includes(document.metadata.type as TrackedType),
55 + );
56 + if (tracked.length === 0) return undefined;
57 + const counts = new Map<TrackedType, { open: number; done: number }>(
58 + TRACKED.map((type) => [type, { open: 0, done: 0 }]),
59 + );
60 + const unfinished: { metadata: DocumentMetadata; type: TrackedType }[] = [];
61 + for (const document of tracked) {
62 + const type = document.metadata.type;
63 + const state = boardStateFor({ schemaVersion: 0, items }, document.metadata);
64 + const count = counts.get(type) as { open: number; done: number };
65 + if (state === "done") count.done += 1;
66 + else {
67 + count.open += 1;
68 + unfinished.push({ metadata: document.metadata, type });
69 + }
70 + }
71 + const totals = TRACKED.map((type) => {
72 + const count = counts.get(type) as { open: number; done: number };
73 + const label = type === "issue" ? "open" : "todo";
74 + return `${type}s ${count.open} ${label}, ${count.done} done`;
75 + }).join(". ");
76 + unfinished.sort(
77 + (left, right) =>
78 + TRACKED.indexOf(left.type) - TRACKED.indexOf(right.type) ||
79 + left.metadata.id.localeCompare(right.metadata.id),
80 + );
81 + const listed = unfinished
82 + .slice(0, LISTED_ITEMS)
83 + .map((item) => describe(item.metadata, items[item.metadata.id], now));
84 + const overflow = unfinished.length - listed.length;
85 + return [
86 + "# The System board state",
87 + "",
88 + `${totals}.`,
89 + ...(listed.length === 0
90 + ? ["", "No unfinished items."]
91 + : [
92 + "",
93 + "Unfinished:",
94 + ...listed,
95 + ...(overflow > 0 ? [`+${overflow} more`] : []),
96 + ]),
97 + ].join("\n");

extensions/the-system/bundle-slot-tool.ts

Modified
3 3 import { StringEnum } from "@earendil-works/pi-ai";
4 4 import { defineTool, keyHint } from "@earendil-works/pi-coding-agent";
5 5 import { Text } from "@earendil-works/pi-tui";
6 6 import { Type } from "typebox";
7 7 import type { BundleSlot } from "./bundle-slot.js";
8 +import { loadBundleSlot } from "./loaders.js";
8 9 import { expandableFallback } from "./tool-rendering.js";
10 11 const DESCRIPTION =
76 77 return text;
78 79 async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
79 - const { reserveBundleSlot } = await import("./bundle-slot.js");
80 + const { reserveBundleSlot } = await loadBundleSlot();
80 81 const slot = reserveBundleSlot(ctx.cwd, params, reserved);
81 82 onReserved?.();
82 83 return {

extensions/the-system/index.ts

Modified
6 6 } from "@earendil-works/pi-coding-agent";
7 7 import { createBoardRuntime } from "./board-runtime.js";
8 8 import { createBundleSlotTool } from "./bundle-slot-tool.js";
9 +import { loadStartupNotice, loadSystem, loadSystemCommand } from "./loaders.js";
9 10 import { systemArgumentCompletions } from "./system-command-meta.js";
11 12 function isStaleContextError(error: unknown): boolean {
21 22 let bundleSlotRunActive = false;
22 23 let bundleSlotUsed = false;
23 24 let boardProposalRunActive = false;
25 + let boardUpdateRunActive = false;
24 26 let bundleMigrationRunActive = false;
25 27 const bundleSlot = createBundleSlotTool(() => {
26 28 bundleSlotUsed = true;
54 56 board.endProposal();
55 57 boardProposalRunActive = false;
59 + const activateBoardUpdate = (cwd: string) => {
60 + board.beginUpdate(cwd);
61 + const active = pi.getActiveTools();
62 + if (!active.includes(board.updateTool.name))
63 + pi.setActiveTools([...active, board.updateTool.name]);
64 + boardUpdateRunActive = true;
65 + };
66 + const deactivateBoardUpdate = () => {
67 + const active = pi.getActiveTools();
68 + if (active.includes(board.updateTool.name))
69 + pi.setActiveTools(
70 + active.filter((name) => name !== board.updateTool.name),
71 + );
72 + board.endUpdate();
73 + boardUpdateRunActive = false;
74 + };
57 75 const activateBundleMigration = () => {
58 76 bundleMigrationRunActive = true;
60 78 const beginLifecycle = () => {
61 79 if (bundleSlotRunActive) deactivateBundleSlot();
62 80 if (boardProposalRunActive) deactivateBoardProposal();
81 + if (boardUpdateRunActive) deactivateBoardUpdate();
64 83 const notifyFailure = (
65 84 ctx: ExtensionContext,
79 98 ) => {
80 99 if (ticket !== generation) return;
82 - const { startupRuntimeState } = await import("./startup-notice.js");
101 + const { startupRuntimeState } = await loadStartupNotice();
83 102 if (ticket !== generation) return;
84 103 const runtime = await startupRuntimeState(ctx.cwd);
85 104 if (ticket !== generation) return;
106 125 pi.on("resources_discover", async (event) => {
107 126 const root = path.join(import.meta.dirname, "skills");
108 127 const skillPaths = [path.join(root, "vertical-slices")];
109 - const { startupRuntimeState } = await import("./startup-notice.js");
128 + const { startupRuntimeState } = await loadStartupNotice();
110 129 const runtime = await startupRuntimeState(event.cwd);
111 130 if (runtime.active && !runtime.notice)
112 131 skillPaths.push(
119 138 pi.on("session_start", (_event, ctx) => {
120 139 deactivateBundleSlot();
121 140 deactivateBoardProposal();
141 + deactivateBoardUpdate();
122 142 bundleMigrationRunActive = false;
123 143 const ticket = ++generation;
124 144 warningNotified = false;
136 156 bundleSlotRunActive = false;
137 157 bundleSlotUsed = false;
138 158 boardProposalRunActive = false;
159 + boardUpdateRunActive = false;
139 160 bundleMigrationRunActive = false;
140 161 board.shutdown();
143 164 void syncRuntimeIndicator(ctx, generation).catch((error) =>
144 165 notifyFailure(ctx, "The System startup check failed", error),
146 - const { composeSystemPrompt } = await import("./system.js");
167 + const { composeSystemPrompt } = await loadSystem();
147 168 return { systemPrompt: composeSystemPrompt(ctx.cwd, event.systemPrompt) };
149 170 pi.on("agent_settled", (_event, ctx) => {
153 174 if (bundleSlotRunActive && bundleSlotUsed) deactivateBundleSlot();
154 175 if (boardProposalRunActive && board.proposalComplete())
155 176 deactivateBoardProposal();
177 + if (boardUpdateRunActive && board.updateComplete()) deactivateBoardUpdate();
156 178 bundleMigrationRunActive = false;
158 180 pi.on("tool_call", async (event, ctx) => {
161 183 !isToolCallEventType("edit", event)
163 185 return;
164 - const { preflightFileMutation } = await import("./system.js");
186 + const { preflightFileMutation } = await loadSystem();
165 187 const ui = {
166 188 hasUI: ctx.hasUI,
167 189 select: (title: string, items: string[]) => ctx.ui.select(title, items),
176 198 pi.registerTool(bundleSlot);
177 199 pi.registerTool(board.tool);
200 + pi.registerTool(board.updateTool);
178 201 pi.registerCommand("system", {
179 202 description: "The System project governance",
180 203 getArgumentCompletions: systemArgumentCompletions,
181 204 handler: async (args, ctx) => {
182 - const { createSystemCommand } = await import("./system-command.js");
205 + const { createSystemCommand } = await loadSystemCommand();
183 206 await createSystemCommand(pi, {
184 207 beginLifecycle,
185 208 activateBundleTool: activateBundleSlot,
186 - activateBoardTool: activateBoardProposal,
209 + activateBoardProposal,
210 + activateBoardUpdate,
187 211 activateBundleMigration,
188 212 openBoard: board.open,
189 213 }).handler(args, ctx);

extensions/the-system/lazy.ts

Added
new file mode 100644
1 +/**
2 + * Memoize a dynamic import so concurrent callers share one evaluation.
3 + *
4 + * Pi loads extensions through jiti with the module cache disabled.
5 + * Two concurrent imports of the same module can then race: the second
6 + * caller receives a partially initialized module whose top-level awaits
7 + * have not finished and whose imported bindings are still `undefined`.
8 + *
9 + * Routing every lazy import through one shared promise closes that window.
10 + * A rejected load clears the memo so the next call retries.
11 + */
12 +export function lazy<T>(load: () => Promise<T>): () => Promise<T> {
13 + let promise: Promise<T> | undefined;
14 + return () =>
15 + (promise ??= load().catch((error: unknown) => {
16 + promise = undefined;
17 + throw error;
18 + }));

extensions/the-system/loaders.ts

Added
new file mode 100644
1 +/**
2 + * Centralized lazy loaders for The System implementation modules.
3 + *
4 + * Keeping every loader here means one shared promise per target module
5 + * across all importing files, so no two concurrent entry points can race
6 + * jiti's module-cache-free loader into a partially initialized module.
7 + */
8 +import { lazy } from "./lazy.js";
10 +export const loadSystem = lazy(() => import("./system.js"));
11 +export const loadStartupNotice = lazy(() => import("./startup-notice.js"));
12 +export const loadSystemCommand = lazy(() => import("./system-command.js"));
13 +export const loadSystemRenderer = lazy(() => import("./system-renderer.ts"));
14 +export const loadBoardServer = lazy(() => import("./board-server.ts"));
15 +export const loadOpenBrowser = lazy(() => import("./open-browser.ts"));
16 +export const loadBundleSlot = lazy(() => import("./bundle-slot.js"));

extensions/the-system/plan-status.ts

Added
new file mode 100644
1 +import { readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
2 +import path from "node:path";
3 +import {
4 + parseAuthoredDocument,
5 + resolveGovernedPath,
6 + SystemDocumentError,
7 + validateBundleCandidate,
8 +} from "./documents.ts";
9 +import type { ProjectIndex } from "./project-index.ts";
11 +export type PlanStatus = "draft" | "approved";
13 +const FRONTMATTER = /^(---\r?\n)([\s\S]*?)(\r?\n---(?:\r?\n|$))/;
14 +const STATUS_LINE = /^status:[^\r\n]*$/gm;
16 +export function planStatusSource(source: string, status: PlanStatus): string {
17 + const block = FRONTMATTER.exec(source);
18 + if (!block)
19 + throw new SystemDocumentError(
20 + "status.frontmatter",
21 + "Plan requires one leading YAML frontmatter block",
22 + );
23 + const open = block[1] ?? "";
24 + const body = block[2] ?? "";
25 + const close = block[3] ?? "";
26 + const matches = body.match(STATUS_LINE) ?? [];
27 + if (matches.length !== 1)
28 + throw new SystemDocumentError(
29 + "status.line",
30 + `Plan frontmatter requires exactly one status line; found ${matches.length}`,
31 + );
32 + const updated = body.replace(STATUS_LINE, `status: ${status}`);
33 + return `${open}${updated}${close}${source.slice(block[0].length)}`;
36 +export function writePlanStatus(
37 + index: ProjectIndex,
38 + id: string,
39 + status: PlanStatus,
40 +): void {
41 + const document = index.documents.find(
42 + (candidate) => candidate.metadata.id === id,
43 + );
44 + if (!document)
45 + throw new SystemDocumentError(
46 + "status.missing-item",
47 + `No System document: ${id}`,
48 + );
49 + if (document.metadata.type !== "plan")
50 + throw new SystemDocumentError(
51 + "status.item-type",
52 + `Only plans carry a status: ${id}`,
53 + );
54 + if (document.metadata.status === status) return;
55 + const target = resolveGovernedPath(index.root, document.path);
56 + const markdown = planStatusSource(readFileSync(target, "utf8"), status);
57 + const diagnostics = validateBundleCandidate(
58 + index.documents.map((candidate) => ({
59 + path: candidate.path,
60 + markdown: candidate.markdown,
61 + })),
62 + { path: document.path, markdown },
63 + index.prefix,
64 + );
65 + if (diagnostics.length > 0)
66 + throw new SystemDocumentError(
67 + "status.invalid",
68 + `Plan would become invalid: ${diagnostics.map((item) => item.message).join("; ")}`,
69 + );
70 + const written = parseAuthoredDocument(markdown, index.prefix).metadata;
71 + if (written.type !== "plan" || written.status !== status)
72 + throw new SystemDocumentError(
73 + "status.invalid",
74 + `Plan status did not change to ${status}: ${id}`,
75 + );
76 + const temporary = path.join(
77 + path.dirname(target),
78 + `.status-${process.pid}-${Date.now()}.md`,
79 + );
80 + writeFileSync(temporary, markdown, { encoding: "utf8", flag: "wx" });
81 + try {
82 + renameSync(temporary, target);
83 + } finally {
84 + rmSync(temporary, { force: true });
85 + }

extensions/the-system/skills/vertical-slices/SKILL.md

Modified
19 19 When no end-to-end path exists, make the first slice the thinnest working path through the critical components.
20 20 Include only the minimum prerequisite work that slice needs.
22 +## Slicing a given plan
24 +A plan defines the required outcome, not the implementation order.
25 +Re-sequence its content into vertical slices, including when it is written as layers, phases, or components.
26 +Implement every part the plan requires; slicing narrows each step, never the delivered scope.
27 +Continue directly into the next slice until the plan is fully implemented.
28 +Verification means verification you run and read yourself, so slice boundaries are not human approval points.
29 +Report once at the end, unless the plan is wrong, blocked, or contradicted by evidence.
22 31 ## Boundaries
24 33 A slice is complete only when its behavior is integrated, observable, tested, and freshly verified.

extensions/the-system/startup-notice.ts

Modified
1 1 import { existsSync } from "node:fs";
2 2 import path from "node:path";
3 +import { loadSystem } from "./loaders.js";
3 4 import { discoverProjectRoot } from "./project-root.ts";
4 5 import type { SystemRuntimeState } from "./system.ts";
13 14 return { active: false };
15 16 if (!existsSync(path.join(root, ".system"))) return { active: false };
16 - const { runtimeState } = await import("./system.ts");
17 + const { runtimeState } = await loadSystem();
17 18 return runtimeState(cwd);

extensions/the-system/system-command.ts

Modified
5 5 ExtensionCommandContext,
6 6 RegisteredCommand,
7 7 } from "@earendil-works/pi-coding-agent";
8 +import { boardSummaryBlock } from "./board-summary.ts";
8 9 import { runDoctor } from "./doctor.ts";
9 10 import { applyInitialization, inspectInitialization } from "./init.ts";
11 +import { loadSystemRenderer } from "./loaders.js";
10 12 import { openHtmlFile } from "./open-browser.ts";
11 13 import { openEditableFile } from "./open-editor.ts";
12 14 import { loadProjectIndex } from "./project-index.ts";
42 44 type SystemCommandHooks = Readonly<{
43 45 beginLifecycle?: () => void;
44 46 activateBundleTool?: () => void;
45 - activateBoardTool?: (cwd: string) => void;
47 + activateBoardProposal?: (cwd: string) => void;
48 + activateBoardUpdate?: (cwd: string) => void;
46 49 activateBundleMigration?: () => void;
47 50 openBoard?: (cwd: string) => Promise<string>;
122 125 hooks.beginLifecycle?.();
123 126 if (BUNDLE_SUBCOMMANDS.has(parsed.subcommand))
124 127 hooks.activateBundleTool?.();
125 - if (parsed.subcommand === "assess" || parsed.subcommand === "exec")
126 - hooks.activateBoardTool?.(ctx.cwd);
127 - pi.sendUserMessage(systemPromptFor(parsed.subcommand, parsed.rest));
128 + if (parsed.subcommand === "assess")
129 + hooks.activateBoardProposal?.(ctx.cwd);
130 + if (parsed.subcommand === "exec") hooks.activateBoardUpdate?.(ctx.cwd);
131 + pi.sendUserMessage(
132 + systemPromptFor(
133 + parsed.subcommand,
134 + parsed.rest,
135 + boardSummaryBlock(ctx.cwd),
136 + ),
137 + );
128 138 if (ctx.mode === "print" || ctx.mode === "json") {
129 139 await new Promise((resolve) => setTimeout(resolve, 0));
130 140 await ctx.waitForIdle();
253 263 ): Promise<string> {
254 264 const index = loadProjectIndex(cwd);
255 265 const document = resolveDocument(index.root, index.documents, selector);
256 - const { renderSystemViewSite } = await import("./system-renderer.ts");
266 + const { renderSystemViewSite } = await loadSystemRenderer();
257 267 return renderSystemViewSite(index, document).file;
260 270 async function renderSystemBook(cwd: string): Promise<string> {
261 - const { renderSystemBookSite } = await import("./system-renderer.ts");
271 + const { renderSystemBookSite } = await loadSystemRenderer();
262 272 return renderSystemBookSite(loadProjectIndex(cwd)).file;

extensions/the-system/system-prompts.ts

Modified
1 1 export const DOCUMENT_CONTRACT = `# The System document contract
3 3 Use .system bundles only.
5 -Every authored document lives at .system/<type-plural>/<ID>-<slug>/index.md.
7 -ID shape: <PREFIX>-<TYPE>-<8 chars from A-Z0-9_->.
9 -Use lowercase slugs.
11 -Frontmatter refs store IDs only.
12 -Config schemaVersion is 0.
4 +Authored documents live at .system/<type-plural>/<ID>-<slug>/index.md with lowercase slugs.
14 5 Type directories: research, specs, phases, plans, issues.
6 +ID shape: <PREFIX>-<TYPE>-<8 chars from A-Z0-9_->.
7 +Frontmatter refs store IDs only; config schemaVersion is 0.
16 9 Required frontmatter:
17 10 - research: id, type: research, title
20 13 - plan: id, type: plan, title, spec, status: draft|approved, optional depends_on: plan ID[]
21 14 - issue: id, type: issue, title, specs: string[]
23 -Research references no System stage type.
24 -Specs may reference research.
25 -Operate only the explicitly invoked /system lifecycle stage.
26 -Never auto-chain stages or create bundles for another stage.
27 -You may recommend another stage; wait for explicit human invocation.
16 +Research links to no stage; specs may reference research; issues have no status field.
17 +Plan depends_on targets earlier plans for the same spec.
28 18 Phases are project-wide operating epochs related to MISSION, not spec decomposition or work breakdown.
29 19 Phase labels contain 1-12 ASCII letters, digits, dots, underscores, or hyphens.
30 -Plans reference one spec and may depend on earlier plans for the same spec.
31 -Issues may reference zero or more specs and have no status field.
32 -Approved plans are immutable outside an explicitly approved /system init bundle migration; otherwise create a new plan bundle.
20 +Config currentPhase selects the operating phase; changing it requires explicit human confirmation.
21 +Operate only the invoked /system stage; never auto-chain or create bundles for another stage.
22 +Recommend the next stage, then wait for explicit human invocation.
23 +Approved plans are immutable outside an approved /system init bundle migration; otherwise create a new plan bundle.
33 24 Mutating existing core files or files in phase and spec bundles requires one-shot human approval.
34 -The optional config currentPhase ID selects the project-wide operating phase.
35 -Changing currentPhase requires explicit human confirmation.
36 25 Keep prose terse, minimal, and essential.
37 26 After creating or materially editing a System document, end with:
43 32 export const MARKDOWN_CONTRACT = `# The System Markdown contract
45 34 Use readable Markdown.
46 -Prefer visual explanations and diagrams when they clarify structure or relationships.
47 -Use GFM tables/task lists only when they clarify.
48 -Use Mermaid, TeX, raw HTML, and assets only when prose is worse.
49 -After choosing GFM, TeX, or Mermaid, load its matching the-system-* skill.
35 +Model structure, sequence, state, entities, and decisions visually by default.
36 +Use prose for intent, judgment, and constraints.
37 +When content is a structure, flow, state machine, relation, comparison, or branch, select a format first, then load its matching the-system-* skill.
38 +Mermaid models systems, GFM tables enumerate comparisons, TeX states formal relations, raw HTML mockups show visual or interactive surfaces.
39 +Terse governs prose, not models; a diagram that replaces a paragraph is the terse form.
50 40 Keep local Markdown links relative so /system view and /system book can resolve them.
51 41 System documents contain no real code snippets; use terse pseudocode only when essential.
54 -const BOARD_CONTRACT = `# The System board contract
44 +export const BOARD_CONTRACT = `# The System board contract
56 46 Board state lives only in .system/board.json at schema version 0.
57 47 Specs and plans use todo|done; issues use open|done.
58 48 A spec may be done without plans, but cannot be done while any linked plan is todo.
59 49 Issues never change spec state.
60 50 Assessment proposes board changes for human review; it never applies them.
51 +Exec applies verified states directly through system_board_update, recorded with source agent and a terse evidence note.
52 +Claim a state only from verification you ran and read; the human overrides any entry in /system board.
63 55 const EXEC_CONTRACT = `# The System exec contract
68 60 The current phase is already project context; do not request or attach it as an exec input.
69 61 Load the vertical-slices skill before implementation.
70 62 Execute in thin vertical slices of behavior required by the referenced documents.
63 +Referenced documents define required outcome, not implementation order.
64 +Re-sequence layered plan content into vertical slices and implement all of it.
65 +Do not pause for human approval between slices.
71 66 Each slice delivers one complete, observable behavior through the system's user-facing or public interface, crossing every layer that behavior requires.
72 67 Do not batch work horizontally by architectural layer or component.
73 68 Integrate, test, and freshly verify each slice before starting the next; leave the repository working after every slice.
74 69 Use tests for nontrivial behavior.
75 70 Debug root cause before fixing bugs.
76 71 Before claiming implementation complete, run fresh verification and read the full result.
77 -After fresh verification, call system_board_propose exactly once with evidence-backed state changes for referenced bundles; use an empty items list when no changes are justified.
78 -Board proposals require human review and never apply automatically.
72 +After fresh verification, call system_board_update exactly once with the states your work proves for referenced bundles; use an empty items list when no change is justified.
73 +Each update carries a terse note naming the evidence; a rejected update means the claimed state violates a board invariant.
79 74 Final log includes refs, changed areas, verification, and a copyable View block.
80 75 Commit messages tell the document-linked story, not file/test inventory.
97 92 If relevant specs exist, ask whether later specs should reference the research; research bundles never link to stages.`,
98 93 spec: `Create or amend terse specs as context requires.
99 94 Capture high-level intent, scope, behavior, constraints, and acceptance criteria.
100 -Use mockups and diagrams when they clarify visual elements, UI, layout, interactions, or relationships.
95 +Every spec models its behavior visually with at least one diagram, mockup, or state model; a prose-only spec is incomplete.
96 +Use mockups for visual elements, UI, layout, and interactions, and diagrams for structure, flow, states, and relationships.
101 97 Persist accepted visual assets and their required local dependencies inside the spec bundle.
102 98 Link or embed them from index.md, and encode accepted feedback as behavior and constraints.
103 99 Do not prescribe implementation.
122 118 When transitioning, create or amend the phase first, then update config currentPhase only after explicit human confirmation.
123 119 Do not mutate MISSION.`,
124 120 plan: `Create or amend terse implementation plans for specs as context requires.
125 -Plan at module, interface, package, or class level.
121 +Decompose by observable behavior, not by architectural layer, and order behaviors by delivery value.
122 +Name the modules, interfaces, packages, or classes each behavior touches, without a layer-by-layer build order.
123 +Model the module and interface structure, or the behavior sequence, as a diagram.
124 +Show dependencies between plans and between behaviors visually.
126 125 Avoid function and line detail except critical paths.
127 126 Do not include real code snippets.
128 127 Use terse pseudocode only when necessary.
130 129 Status: approved requires human approval and makes each plan immutable.`,
131 130 issue: `Create or amend terse issues as context requires.
132 131 Record symptom, impact, reproduction or evidence, and related specs.
132 +Use a sequence diagram for reproduction when the failure crosses components.
133 133 Use specs: [] while the violated contract is unknown.
134 134 Amend or create specs only when issues expose spec gaps.`,
135 - exec: EXEC_CONTRACT,
135 + exec: `${BOARD_CONTRACT}
136 +${EXEC_CONTRACT}`,
138 139 const NEEDS_MARKDOWN = new Set([
148 149 export function systemPromptFor(
149 150 subcommand: string,
150 151 instructions: string,
152 + boardState?: string,
151 153 ): string {
152 154 const stage = STAGE_PROMPTS[subcommand];
153 155 if (!stage) throw new Error(`Unknown /system subcommand: ${subcommand}`);
156 158 ...(NEEDS_MARKDOWN.has(subcommand) ? [MARKDOWN_CONTRACT] : []),
157 159 `# /system ${subcommand}`,
158 160 stage,
161 + ...(boardState?.trim() ? [boardState.trim()] : []),
159 162 instructions.trim()
160 163 ? `# Human instructions\n\n${instructions.trim()}`
161 164 : "# Human instructions\n\nNo instructions were supplied. Infer intent with focused questions or selection before writing.",

extensions/the-system/system-renderer.ts

Modified
56 56 diagnostics: readonly Diagnostic[];
58 58 export type RenderOutput = Readonly<{ file: string; directory: string }>;
59 +type LiveContext = Readonly<{ board: BoardState; revision: string }>;
60 61 type CoreDocument = Readonly<{
61 62 id: string;
130 131 const title = `${projectName(input.root)} Dossier`;
131 132 writeFileSync(
132 133 path.join(directory, "index.html"),
133 - htmlPage(
134 + htmlPage({
134 135 title,
135 - bookBody(title, rendered, diagnostics, directory, input.currentPhase),
136 - "book",
137 - "assets/mermaid.min.js",
138 - "assets/minisearch.js",
139 - ),
136 + body: bookBody(
137 + title,
138 + rendered,
139 + diagnostics,
140 + directory,
141 + input.currentPhase,
142 + ),
143 + mode: "book",
144 + mermaidPath: "assets/mermaid.min.js",
145 + miniSearchPath: "assets/minisearch.js",
146 + }),
140 147 "utf8",
142 149 return { file: path.join(directory, "index.html"), directory };
146 153 input: RenderInput,
147 154 board: BoardState,
148 155 proposals: readonly BoardProposal[],
156 + revision = "",
149 157 ): RenderOutput {
158 + const live: LiveContext = { board, revision };
150 159 const directory = createOutput(input);
151 - const rendered = renderAll(input, directory);
160 + const rendered = renderAll(input, directory, live);
152 161 const diagnostics = [...input.diagnostics, ...referenceDiagnostics(input)];
153 - writePages(directory, rendered, diagnostics, "book");
162 + writePages(directory, rendered, diagnostics, "book", live);
154 163 const title = `${projectName(input.root)} Board`;
155 164 const body = boardBody(title, input, rendered, board, proposals).replaceAll(
156 165 pathToFileURL(`${directory}${path.sep}`).href,
159 168 writeFileSync(
160 169 path.join(directory, "index.html"),
161 - htmlPage(
170 + htmlPage({
162 171 title,
164 - "board",
165 - "assets/mermaid.min.js",
166 - "assets/minisearch.js",
167 - ),
173 + mode: "board",
174 + mermaidPath: "assets/mermaid.min.js",
175 + miniSearchPath: "assets/minisearch.js",
176 + live,
177 + }),
168 178 "utf8",
170 180 return { file: path.join(directory, "index.html"), directory };
195 205 const renderAll = (
196 206 input: RenderInput,
197 207 outputRoot: string,
208 + live?: LiveContext,
198 209 ): readonly RenderedDocument[] => {
199 210 const coreSources = coreDocuments(input.root);
200 211 const renderedSources = new Set([
205 216 renderCore(document, outputRoot, renderedSources),
207 218 const authored = orderedSystemDocuments(input.documents).map((document) =>
208 - renderDocument(input, document, outputRoot, renderedSources),
219 + renderDocument(input, document, outputRoot, renderedSources, live),
210 221 const current = authored.find(
211 222 (document) => document.id === input.currentPhase,
272 283 documents: readonly RenderedDocument[],
273 284 diagnostics: readonly Diagnostic[],
274 285 mode: "single" | "book",
286 + live?: LiveContext,
275 287 ) => {
276 288 for (const [index, document] of documents.entries()) {
277 289 const previous = documents[index - 1];
292 304 writeFileSync(
293 305 path.join(outputRoot, document.outputPath),
294 - htmlPage(
295 - document.title,
296 - `${controls ? `<nav class="doc-move">${controls}</nav>` : ""}${document.article}${diagnosticsHtml(diagnostics)}`,
306 + htmlPage({
307 + title: document.title,
308 + body: `${controls ? `<nav class="doc-move">${controls}</nav>` : ""}${document.article}${diagnosticsHtml(diagnostics)}`,
298 - rel(document.outputPath, "assets/mermaid.min.js"),
299 - rel(document.outputPath, "assets/minisearch.js"),
300 - ),
310 + mermaidPath: rel(document.outputPath, "assets/mermaid.min.js"),
311 + miniSearchPath: rel(document.outputPath, "assets/minisearch.js"),
312 + ...(live ? { live } : {}),
313 + }),
301 314 "utf8",
351 364 document: RenderDocumentInput,
352 365 outputRoot: string,
353 366 renderedSources: ReadonlySet<string>,
367 + live?: LiveContext,
354 368 ): RenderedDocument => {
355 369 const outputPath = document.path.replace(/index\.md$/, "index.html");
356 370 const article = articleHtml({
371 + ...(live ? { live } : {}),
357 372 id: document.metadata.id,
358 373 title: document.metadata.title,
359 374 type: document.metadata.type,
393 408 documents?: readonly RenderDocumentInput[];
394 409 current?: boolean;
395 410 renderedSources: ReadonlySet<string>;
411 + live?: LiveContext;
396 412 }): string => {
397 413 const metadata = input.frontmatter
398 - ? metadataHtml(input.frontmatter, input.documents ?? [], input.outputRoot)
414 + ? metadataHtml(
415 + input.frontmatter,
416 + input.documents ?? [],
417 + input.outputRoot,
418 + input.metadata,
419 + input.live,
400 422 const backlinks = input.documents
401 423 ? backlinksHtml(input.id, input.documents, input.outputRoot)
447 469 frontmatter: FrontmatterMap,
448 470 documents: readonly RenderDocumentInput[],
449 471 outputRoot: string,
472 + metadata?: DocumentMetadata,
473 + live?: LiveContext,
450 474 ): string => {
451 475 const rows = [...frontmatter.entries()]
452 - .map(
453 - ([key, value]) =>
454 - `<tr><th>${esc(key)}</th><td>${valueHtml(value, documents, outputRoot)}</td></tr>`,
476 + .map(([key, value]) => {
477 + const toggle =
478 + live && metadata?.type === "plan" && key === "status"
479 + ? statusToggle(metadata.id, metadata.status)
480 + : undefined;
481 + return `<tr><th>${esc(key)}</th><td>${toggle ?? valueHtml(value, documents, outputRoot)}</td></tr>`;
482 + })
456 483 .join("");
457 - return `<details class="ledger"><summary>Metadata</summary><table>${rows}</table></details>`;
484 + const boardRow =
485 + live && metadata?.type === "spec"
486 + ? `<tr><th>board</th><td>${boardStateToggle(metadata.id, boardStateFor(live.board, metadata))}</td></tr>`
487 + : "";
488 + return `<details class="ledger"><summary>Metadata</summary><table>${rows}${boardRow}</table></details>`;
491 +const statusToggle = (id: string, status: string) =>
492 + `<button class="ledger-toggle" type="button" data-status-toggle data-id="${esc(id)}" data-status="${esc(status)}" title="Toggle plan status">${esc(status)}</button>`;
494 +const boardStateToggle = (id: string, state: string) =>
495 + `<button class="ledger-toggle" type="button" data-board-toggle data-id="${esc(id)}" data-state="${esc(state)}" data-default-state="todo" title="Toggle board state">${esc(state)}</button>`;
460 497 const valueHtml = (
461 498 value: FrontmatterValue,
462 499 documents: readonly RenderDocumentInput[],
721 758 const boardAssessment = (entry: BoardState["items"][string] | undefined) =>
723 - ? `<span class="board-assessment" data-assessment data-source="${esc(entry.source)}" data-updated-at="${esc(entry.updatedAt)}">${esc(entry.source)} · ${esc(entry.updatedAt)}</span>`
760 + ? `<span class="board-assessment" data-assessment data-source="${esc(entry.source)}" data-updated-at="${esc(entry.updatedAt)}"${entry.note ? ` data-note="${esc(entry.note)}"` : ""}>${esc(entry.source)} · ${esc(entry.updatedAt)}${entry.note ? ` · ${esc(entry.note)}` : ""}</span>`
724 761 : '<span class="board-assessment" data-assessment>default</span>';
726 763 const boardProposal = (proposal?: BoardProposal) =>
731 768 const boardCss = () => String.raw`
732 -body[data-mode=board]{padding:10px;background:var(--bg);font:12px/1.35 ui-monospace,SFMono-Regular,Menlo,monospace}.board-top{display:grid;grid-template-columns:1fr auto;gap:10px;align-items:end;border-bottom:2px solid var(--text);padding-bottom:7px;margin-bottom:7px}.board-brand{color:var(--text);font-size:17px;font-weight:900;text-decoration:none;text-transform:uppercase}.board-top p{margin:2px 0 0;color:var(--muted);font-size:10px}.board-top>span{color:var(--muted)}.board-grid{display:grid;grid-template-columns:minmax(0,3fr) minmax(240px,1fr);gap:7px;align-items:start}.board-region{border:1px solid var(--line);background:var(--panel);min-width:0}.board-region>h1{font-size:11px;letter-spacing:.1em;text-transform:uppercase;margin:0;padding:6px 7px;border-bottom:1px solid var(--line)}.board-region>h1 span{float:right;color:var(--muted);font-weight:400}.board-spec-list{display:grid;grid-template-columns:repeat(auto-fit,minmax(290px,1fr));gap:6px;padding:6px;align-items:start}.board-issue-list{display:grid;gap:5px;padding:6px}.board-spec{border:2px solid var(--accent);background:var(--page);min-width:0}.board-spec.is-done{border-color:var(--line);background:var(--bg)}.board-row{display:grid;grid-template-columns:minmax(0,1fr) auto;gap:6px;align-items:start;padding:6px 7px}.board-bundle{min-width:0}.board-bundle>summary{cursor:pointer;list-style:none;display:grid;grid-template-columns:minmax(0,1fr);padding-left:14px;position:relative}.board-bundle>summary::-webkit-details-marker{display:none}.board-bundle>summary::before{content:'▸';position:absolute;left:0;color:var(--accent)}.board-bundle[open]>summary::before{content:'▾'}.board-kind{display:block;font-size:9px;color:var(--muted);text-transform:uppercase}.board-bundle>summary strong{display:block;font:700 13px/1.15 system-ui,sans-serif;margin-top:1px;overflow-wrap:anywhere}.is-done>.board-row .board-bundle>summary strong{color:var(--muted);text-decoration:line-through}.board-details{grid-column:1/-1;margin:6px 0 0 14px;border-top:1px solid var(--line);padding-top:6px;font-family:system-ui,sans-serif}.board-details>.system-article{border:0;padding:0;background:transparent}.board-details .mast{display:none}.board-details .ledger{margin:.35rem 0}.board-details h1{font-size:19px}.board-details h2{font-size:16px}.board-details h3{font-size:14px}.board-details pre{padding:.6rem}.board-plans{display:grid;gap:4px;border-top:1px solid var(--line);background:var(--bg);padding:4px}.board-plan{border-left:3px solid var(--accent);background:var(--page)}.board-plan.is-done{border-left-color:var(--line);background:var(--bg)}.board-plan .board-row{padding:4px 5px}.board-issue{border-left:3px solid var(--warn);background:var(--page)}.board-issue.is-done{border-left-color:var(--line);background:var(--bg)}.board-issue .board-bundle>summary::before{color:var(--warn)}.board-links{display:grid;gap:2px;padding:0 7px 6px 21px;font-size:10px}.board-state{border:1px solid var(--accent);background:var(--bg);color:var(--accent);font:9px ui-monospace,monospace;padding:3px 5px;cursor:pointer;min-width:43px}.board-issue .board-state{border-color:var(--warn);color:var(--warn)}.is-done>.board-row>.board-state,.board-plan.is-done .board-state,.board-issue.is-done .board-state{border-color:var(--line);color:var(--text)}.board-state:disabled{cursor:not-allowed;border-color:var(--line);color:var(--muted)}.board-assessment{display:block;color:var(--muted);font-size:9px;padding:0 7px 5px 21px}.board-proposal{display:grid;grid-template-columns:minmax(0,1fr) auto;gap:6px;border-top:1px solid var(--info);padding:5px 7px;color:var(--muted)}.board-proposal b{display:block;color:var(--info);font-size:9px}.board-proposal button{border:1px solid var(--info);background:var(--bg);color:var(--info);font:9px ui-monospace,monospace;padding:3px 6px}.board-empty{color:var(--muted);margin:6px}.board-notice{position:fixed;right:10px;bottom:10px;max-width:min(34rem,calc(100vw - 20px));background:var(--panel);border:1px solid var(--line);padding:7px;display:none}.board-notice.is-visible{display:block}.board-notice.is-error{border-color:var(--error);color:var(--error)}@media(max-width:760px){.board-top,.board-grid{grid-template-columns:1fr}.board-spec-list{grid-template-columns:1fr}.board-top>span{text-align:left}}
769 +body[data-mode=board]{padding:10px;background:var(--bg);font:12px/1.35 ui-monospace,SFMono-Regular,Menlo,monospace}.board-top{display:grid;grid-template-columns:1fr auto;gap:10px;align-items:end;border-bottom:2px solid var(--text);padding-bottom:7px;margin-bottom:7px}.board-brand{color:var(--text);font-size:17px;font-weight:900;text-decoration:none;text-transform:uppercase}.board-top p{margin:2px 0 0;color:var(--muted);font-size:10px}.board-top>span{color:var(--muted)}.board-grid{display:grid;grid-template-columns:minmax(0,3fr) minmax(240px,1fr);gap:7px;align-items:start}.board-region{border:1px solid var(--line);background:var(--panel);min-width:0}.board-region>h1{font-size:11px;letter-spacing:.1em;text-transform:uppercase;margin:0;padding:6px 7px;border-bottom:1px solid var(--line)}.board-region>h1 span{float:right;color:var(--muted);font-weight:400}.board-spec-list{display:grid;grid-template-columns:repeat(auto-fit,minmax(290px,1fr));gap:6px;padding:6px;align-items:start}.board-issue-list{display:grid;gap:5px;padding:6px}.board-spec{border:2px solid var(--accent);background:var(--page);min-width:0}.board-spec.is-done{border-color:var(--line);background:var(--bg)}.board-row{display:grid;grid-template-columns:minmax(0,1fr) auto;gap:6px;align-items:start;padding:6px 7px}.board-bundle{min-width:0}.board-bundle>summary{cursor:pointer;list-style:none;display:grid;grid-template-columns:minmax(0,1fr);padding-left:14px;position:relative}.board-bundle>summary::-webkit-details-marker{display:none}.board-bundle>summary::before{content:'▸';position:absolute;left:0;color:var(--accent)}.board-bundle[open]>summary::before{content:'▾'}.board-kind{display:block;font-size:9px;color:var(--muted);text-transform:uppercase}.board-bundle>summary strong{display:block;font:700 13px/1.15 system-ui,sans-serif;margin-top:1px;overflow-wrap:anywhere}.is-done>.board-row .board-bundle>summary strong{color:var(--muted);text-decoration:line-through}.board-details{grid-column:1/-1;margin:6px 0 0 14px;border-top:1px solid var(--line);padding-top:6px;font-family:system-ui,sans-serif}.board-details>.system-article{border:0;padding:0;background:transparent}.board-details .mast{display:none}.board-details .ledger{margin:.35rem 0}.board-details h1{font-size:19px}.board-details h2{font-size:16px}.board-details h3{font-size:14px}.board-details pre{padding:.6rem}.board-plans{display:grid;gap:4px;border-top:1px solid var(--line);background:var(--bg);padding:4px}.board-plan{border-left:3px solid var(--accent);background:var(--page)}.board-plan.is-done{border-left-color:var(--line);background:var(--bg)}.board-plan .board-row{padding:4px 5px}.board-issue{border-left:3px solid var(--warn);background:var(--page)}.board-issue.is-done{border-left-color:var(--line);background:var(--bg)}.board-issue .board-bundle>summary::before{color:var(--warn)}.board-links{display:grid;gap:2px;padding:0 7px 6px 21px;font-size:10px}.board-state{border:1px solid var(--accent);background:var(--bg);color:var(--accent);font:9px ui-monospace,monospace;padding:3px 5px;cursor:pointer;min-width:43px}.board-issue .board-state{border-color:var(--warn);color:var(--warn)}.is-done>.board-row>.board-state,.board-plan.is-done .board-state,.board-issue.is-done .board-state{border-color:var(--line);color:var(--text)}.board-state:disabled{cursor:not-allowed;border-color:var(--line);color:var(--muted)}.board-assessment{display:block;color:var(--muted);font-size:9px;padding:0 7px 5px 21px}.board-proposal{display:grid;grid-template-columns:minmax(0,1fr) auto;gap:6px;border-top:1px solid var(--info);padding:5px 7px;color:var(--muted)}.board-proposal b{display:block;color:var(--info);font-size:9px}.board-proposal button{border:1px solid var(--info);background:var(--bg);color:var(--info);font:9px ui-monospace,monospace;padding:3px 6px}.board-empty{color:var(--muted);margin:6px}@media(max-width:760px){.board-top,.board-grid{grid-template-columns:1fr}.board-spec-list{grid-template-columns:1fr}.board-top>span{text-align:left}}
735 772 const boardScript = () => String.raw`
736 -const root=document.body;const notice=document.querySelector('[data-board-notice]');const direct=(node,selector)=>[...node.children].filter(child=>child.matches(selector));const sort=(node,selector)=>direct(node,selector).sort((a,b)=>Number(a.classList.contains('is-done'))-Number(b.classList.contains('is-done'))||(a.dataset.id||'').localeCompare(b.dataset.id||'')).forEach(item=>node.append(item));const message=(text,error=false)=>{notice.textContent=text;notice.className='board-notice is-visible'+(error?' is-error':'');setTimeout(()=>notice.className='board-notice',3000)};const stateOf=card=>card.dataset.state||card.dataset.defaultState;const age=value=>{if(!value)return'default';const days=Math.max(0,Math.floor((Date.now()-Date.parse(value))/86400000));return days===0?'today':days===1?'1 day ago':days+' days ago'};function refresh(snapshot){for(const card of document.querySelectorAll('[data-board-item]')){const entry=snapshot.items[card.dataset.id];const state=entry?.state||card.dataset.defaultState;card.dataset.state=state;card.classList.toggle('is-done',state==='done');const button=card.querySelector(':scope > .board-row > .board-state');button.textContent=state.toUpperCase();const assessment=card.querySelector(':scope > [data-assessment]');assessment.textContent=entry?entry.source+' · '+age(entry.updatedAt):'default';assessment.title=entry?.updatedAt||''}for(const spec of document.querySelectorAll('[data-kind="spec"]')){const button=spec.querySelector(':scope > .board-row > .board-state');const unfinished=spec.querySelector('[data-kind="plan"]:not(.is-done)');button.disabled=!spec.classList.contains('is-done')&&Boolean(unfinished);button.title=button.disabled?'Finish every plan first':'No plan states will change'}document.querySelectorAll('[data-plan-list]').forEach(list=>sort(list,'[data-kind="plan"]'));sort(document.querySelector('[data-spec-list]'),'[data-kind="spec"]');sort(document.querySelector('[data-issue-list]'),'[data-kind="issue"]');document.querySelector('[data-spec-count]').textContent=String(document.querySelectorAll('[data-kind="spec"]:not(.is-done)').length);document.querySelector('[data-issue-count]').textContent=String(document.querySelectorAll('[data-kind="issue"]:not(.is-done)').length)}async function post(path,payload){const response=await fetch(path,{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify(payload)});const result=await response.json();if(!response.ok)throw new Error(result.error||'Board update failed');return result}root.addEventListener('click',async event=>{const proposal=event.target.closest('[data-apply-proposal]');const button=event.target.closest('.board-state');if(!proposal&&!button)return;event.preventDefault();const card=(proposal||button).closest('[data-board-item]');try{if(proposal){const result=await post('/api/proposal',{id:card.dataset.id,state:proposal.dataset.applyProposal});proposal.closest('[data-proposal]').remove();refresh(result);message('Assessment applied.')}else{const state=stateOf(card);const target=state==='done'?card.dataset.defaultState:'done';const result=await post('/api/state',{id:card.dataset.id,state:target});refresh(result);message('Board updated.')}}catch(error){message(error.message,true)}});for(const assessment of document.querySelectorAll('[data-assessment]'))if(assessment.dataset.updatedAt)assessment.textContent=assessment.dataset.source+' · '+age(assessment.dataset.updatedAt);
773 +const root=document.body;const direct=(node,selector)=>[...node.children].filter(child=>child.matches(selector));const sort=(node,selector)=>{const items=direct(node,selector);const ordered=[...items].sort((a,b)=>Number(a.classList.contains('is-done'))-Number(b.classList.contains('is-done'))||(a.dataset.id||'').localeCompare(b.dataset.id||''));if(ordered.some((item,at)=>item!==items[at]))for(const item of ordered)node.append(item)};const notice=document.querySelector('[data-board-notice]');const message=(text,error=false)=>{notice.textContent=text;notice.className='board-notice is-visible'+(error?' is-error':'');setTimeout(()=>{notice.className='board-notice'},3000)};const stateOf=card=>card.dataset.state||card.dataset.defaultState;const age=value=>{if(!value)return'default';const days=Math.max(0,Math.floor((Date.now()-Date.parse(value))/86400000));return days===0?'today':days===1?'1 day ago':days+' days ago'};function refresh(snapshot){for(const card of document.querySelectorAll('[data-board-item]')){const entry=snapshot.items[card.dataset.id];const state=entry?.state||card.dataset.defaultState;card.dataset.state=state;card.classList.toggle('is-done',state==='done');const button=card.querySelector(':scope > .board-row > .board-state');button.textContent=state.toUpperCase();const assessment=card.querySelector(':scope > [data-assessment]');assessment.textContent=entry?entry.source+' · '+age(entry.updatedAt)+(entry.note?' · '+entry.note:''):'default';assessment.title=entry?.updatedAt||''}for(const spec of document.querySelectorAll('[data-kind="spec"]')){const button=spec.querySelector(':scope > .board-row > .board-state');const unfinished=spec.querySelector('[data-kind="plan"]:not(.is-done)');button.disabled=!spec.classList.contains('is-done')&&Boolean(unfinished);button.title=button.disabled?'Finish every plan first':'No plan states will change'}document.querySelectorAll('[data-plan-list]').forEach(list=>sort(list,'[data-kind="plan"]'));sort(document.querySelector('[data-spec-list]'),'[data-kind="spec"]');sort(document.querySelector('[data-issue-list]'),'[data-kind="issue"]');document.querySelector('[data-spec-count]').textContent=String(document.querySelectorAll('[data-kind="spec"]:not(.is-done)').length);document.querySelector('[data-issue-count]').textContent=String(document.querySelectorAll('[data-kind="issue"]:not(.is-done)').length)}globalThis.systemBoardRefresh=refresh;async function post(path,payload){const response=await fetch(path,{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify(payload)});const result=await response.json();if(!response.ok)throw new Error(result.error||'Board update failed');globalThis.systemBoardSeen?.(result.items);return result}root.addEventListener('click',async event=>{const proposal=event.target.closest('[data-apply-proposal]');const button=event.target.closest('.board-state');if(!proposal&&!button)return;event.preventDefault();const card=(proposal||button).closest('[data-board-item]');try{if(proposal){const result=await post('/api/proposal',{id:card.dataset.id,state:proposal.dataset.applyProposal});proposal.closest('[data-proposal]').remove();refresh(result);message('Assessment applied.')}else{const state=stateOf(card);const target=state==='done'?card.dataset.defaultState:'done';const result=await post('/api/state',{id:card.dataset.id,state:target});refresh(result);message('Board updated.')}}catch(error){message(error.message,true)}});for(const assessment of document.querySelectorAll('[data-assessment]'))if(assessment.dataset.updatedAt)assessment.textContent=assessment.dataset.source+' · '+age(assessment.dataset.updatedAt)+(assessment.dataset.note?' · '+assessment.dataset.note:'');
776 +const ledgerCss = () => String.raw`
777 +.ledger-toggle{border:1px solid var(--accent);background:var(--bg);color:var(--accent);font:700 11px ui-monospace,monospace;padding:2px 8px;text-transform:uppercase}.ledger-toggle:disabled{cursor:progress;opacity:.55}.board-notice{position:fixed;right:10px;bottom:10px;z-index:9;max-width:min(34rem,calc(100vw - 20px));background:var(--panel);border:1px solid var(--line);padding:7px;font:12px ui-monospace,monospace;display:none}.board-notice.is-visible{display:block}.board-notice.is-error{border-color:var(--error);color:var(--error)}
780 +const ledgerScript = () => String.raw`
781 +const element=()=>{let node=document.querySelector('[data-board-notice]');if(!node){node=document.createElement('output');node.className='board-notice';node.setAttribute('data-board-notice','');node.setAttribute('aria-live','polite');document.body.append(node)}return node};const notify=(text,isError=false)=>{const node=element();node.textContent=text;node.className='board-notice is-visible'+(isError?' is-error':'');setTimeout(()=>{node.className='board-notice'},3000)};let known=null;let reloading=false;const request=async(path,payload)=>{const response=await fetch(path,{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify(payload)});const result=await response.json();if(!response.ok)throw new Error(result.error||'Board request failed');if(result&&result.items)known=JSON.stringify(result.items);return result};globalThis.systemBoardSeen=items=>{known=JSON.stringify(items)};const syncLedger=items=>{for(const button of document.querySelectorAll('[data-board-toggle]')){const state=items[button.dataset.id]?.state||button.dataset.defaultState;button.dataset.state=state;button.textContent=state}};const OPEN='system-board-open';const remember=()=>{try{sessionStorage.setItem(OPEN,JSON.stringify([...document.querySelectorAll('.board-bundle[open]')].map(node=>node.closest('[data-board-item]')?.dataset.id).filter(Boolean)))}catch{}};const restore=()=>{try{for(const id of JSON.parse(sessionStorage.getItem(OPEN)||'[]'))document.querySelector('[data-board-item][data-id="'+id+'"] > .board-row > .board-bundle')?.setAttribute('open','')}catch{}};document.body.addEventListener('click',async event=>{const button=event.target.closest?.('.ledger-toggle');if(!button)return;event.preventDefault();button.disabled=true;try{if(button.hasAttribute('data-status-toggle')){const next=button.dataset.status==='approved'?'draft':'approved';await request('/api/status',{id:button.dataset.id,status:next});button.dataset.status=next;button.textContent=next;notify('Plan status is now '+next+'.')}else{const next=button.dataset.state==='done'?button.dataset.defaultState:'done';const result=await request('/api/state',{id:button.dataset.id,state:next});syncLedger(result.items);globalThis.systemBoardRefresh?.(result);notify('Board updated.')}}catch(error){notify(error.message,true)}finally{button.disabled=false}});const poll=async()=>{if(reloading)return;try{const response=await fetch('/api/state');const snapshot=await response.json();if(!response.ok||typeof snapshot.revision!=='string')return;if(snapshot.revision!==document.body.dataset.revision){reloading=true;remember();location.reload();return}const encoded=JSON.stringify(snapshot.items);if(encoded===known)return;known=encoded;syncLedger(snapshot.items);globalThis.systemBoardRefresh?.(snapshot);if(snapshot.problem)notify(snapshot.problem,true)}catch{}};restore();void poll();setInterval(poll,1000);document.addEventListener('visibilitychange',()=>{if(!document.hidden)void poll()});
739 784 const bookBody = (
1032 1077 const rel = (from: string, to: string) =>
1033 1078 path.relative(path.dirname(from), to).split(path.sep).join("/") || ".";
1035 -const htmlPage = (
1036 - title: string,
1037 - body: string,
1038 - mode: "single" | "book" | "board",
1039 - mermaidPath: string,
1040 - miniSearchPath: string,
1041 -) => `<!doctype html>
1080 +const htmlPage = ({
1081 + title,
1082 + body,
1083 + mode,
1084 + mermaidPath,
1085 + miniSearchPath,
1086 + live,
1087 +}: Readonly<{
1088 + title: string;
1089 + body: string;
1090 + mode: "single" | "book" | "board";
1091 + mermaidPath: string;
1092 + miniSearchPath: string;
1093 + live?: LiveContext;
1094 +}>) => `<!doctype html>
1042 1095 <html lang="en">
1043 1096 <meta charset="utf-8">
1044 1097 <meta name="viewport" content="width=device-width,initial-scale=1">
1045 1098 <meta name="description" content="${esc(title)}">
1046 1099 <link rel="icon" href="${favicon(title)}">
1047 1100 <title>${esc(title)}</title>
1048 -<style>${css()}</style>
1049 -<body data-mode="${mode}"><script src="${esc(miniSearchPath)}"></script>${body}<script src="${esc(mermaidPath)}"></script><script>if(globalThis.mermaid){const theme=matchMedia('(prefers-color-scheme: dark)').matches?'dark':'default';globalThis.mermaid.initialize({startOnLoad:true,theme})}</script></body>
1101 +<style>${css()}</style>${live ? `<style>${ledgerCss()}</style>` : ""}
1102 +<body data-mode="${mode}"${live ? ` data-revision="${esc(live.revision)}"` : ""}><script src="${esc(miniSearchPath)}"></script>${body}<script src="${esc(mermaidPath)}"></script><script>if(globalThis.mermaid){const theme=matchMedia('(prefers-color-scheme: dark)').matches?'dark':'default';globalThis.mermaid.initialize({startOnLoad:true,theme})}</script>${live ? `<script>${ledgerScript()}</script>` : ""}</body>
1050 1103 </html>`;
1052 1105 const favicon = (title: string) => {