repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by bugabinga

the-system: new board and better concept for phases

14ba3e383210a770961a0ab130b1d6b8a1d0a678

Oliver Krylow <o.krylow@isp-insoft.de> ·

SSH signature · not checked

Browse filesCompare with HEAD

Changed files (33)

+2708 / −511 text lines · all files grouped into 32 bars

Diff layout

CHANGELOG.md

Modified

+7 / −2 text lines

6363- Add Continuity to automatically resume the current task after context compaction while yielding to queued messages and active Goal or Tune runs
6464- Fix Continuity so it resumes user intent only when actionable work remains and stops instead of rerunning completed checks, retrying known blockers, or inventing follow-up work
6565- Make cmprss retrieval use bounded exact UTF-8 ranges, capped at 8192 bytes per call, with continuation offsets and replay-persistent savings accounting; preserve structurally rare JSON items and short search outliers during compression
66- Shorten the cmprss footer status with the Nerd Font compress icon
6667- Fix The System README artifact path docs to show plural directories
67- Make `/system init` deterministic with confirmation; it creates schema v3 config, plural artifact directories, and core files directly
68- Make `/system init` deterministic with confirmation; it creates schema 0 config, board state, plural artifact directories, and core files directly
6869- Add an optional project title to The System config; `/system init` writes it from the project directory name and rendered books use it
6970- Remove The System advisory shell mutation guard; governed confirmation remains on `write` and `edit`
7071- Seed `/system init` core files with concise SYSTEM, MISSION, and RULES role guidance while preserving existing core content on rerun
101102- Add terse artifact detail budgets for System docs; plans stay at module/interface/package/class level and avoid real code snippets
102103- Fix The System runtime warning so it stays quiet until a project opts into `.system`
103104- Improve The System startup performance in projects without `.system` by skipping governance loading
105- Redefine The System phases as selectable project-wide operating epochs, inject the current phase, show it in Pi status, foreground it in the book, and reset the unreleased schema to version 0
106- Make `/system init` update config and board schema markers mechanically, then offer agent-led bundle migration after config schema changes
107- Fix rejected System config edits so errors no longer mislabel them as phase changes
108- Add `/system board` for persistent spec, plan, and issue status tracking, plus reviewable `/system assess` proposals and consistency diagnostics
104109- Keep one mockup page open across iterations with live Pi-backed progress, authenticated agent cancellation, and best-effort closing on acceptance
105110- Fix mockups on Windows so the browser opens in the foreground through the native URL handler
106111- Fix mockup edge annotations so they stay contained without horizontal scrolling
131136- Fix RTK rewriting so `find` commands keep exact path semantics unless RTK passes a path capability probe, and notify users when rewrites are disabled or the compatibility guard can be removed
132137- Replace the tmux-only terminal skill with a terminal harness for observable TUI testing through tmux or WezTerm
133138- Harden git-safe against hook-skipping Git options through aliases, shell indirection, nested Bash, `xargs`, and child-process PATH lookup, including Git Bash on Windows
134- Fix git-safe startup on Windows when commands clear or replace `PATH`
139- Fix git-safe startup on Windows when commands clear or replace `PATH`, or disable MSYS argument conversion; give actionable errors without exposing launcher internals when Git cannot start
135140- Fix git-safe cloning on Windows so valid deep destination paths are accepted
137142## 0.0.3

extensions/cmprss/__tests__/cmprss.test.ts

Modified

+2 / −1 text lines

6262 };
6464 expect(formatStatusText(runtime, { contextWindow: 200_000 })).toBe(
65 "cmprss: -25%",
65 " -25%",
6666 );
67 expect(formatStatusText(runtime)).toBe(" 50000t");
6768 });
6970 test("leaves small output unchanged", () => {

extensions/cmprss/index.ts

Modified

+4 / −3 text lines

1212const ENTRY_TYPE = "cmprss-state";
1313const STATUS_KEY = "cmprss";
14const STATUS_ICON = "";
1516const ERROR_RE =
1617 /\b(error|fail|fatal|warn|exception|denied|timeout|missing|deprecated|critical|traceback|panic)\b/i;
664665 !Number.isFinite(contextWindow) ||
665666 contextWindow <= 0
666667 )
667 return `cmprss: ${saved}t`;
668 return `${STATUS_ICON} ${saved}t`;
668669 const percent = Math.round((saved / contextWindow) * 100);
669 return `cmprss: ${percent === 0 ? "0" : `-${percent}`}%`;
670 return `${STATUS_ICON} ${percent === 0 ? "0" : `-${percent}`}%`;
672673function updateStatus(
679680): void {
680681 if (!ctx.hasUI || !runtime.config.status) return;
681682 if (!runtime.enabled) {
682 ctx.ui?.setStatus?.(STATUS_KEY, "cmprss: off");
683 ctx.ui?.setStatus?.(STATUS_KEY, `${STATUS_ICON} off`);
683684 return;
684685 }
685686 ctx.ui?.setStatus?.(

extensions/git-safe/CHANGELOG.md

Modified

+1 / −1 text lines

55- Prevent agent-issued Git commands from opening interactive editors
66- Reject hook-skipping `--no-verify` options through normal Git, aliases, shell indirection, nested Bash, `xargs`, child-process PATH lookup, and literal bypasses
7- Convert temporary wrapper paths for Git Bash on Windows
7- Launch through Git Bash even when callers disable MSYS argument conversion, and hide launcher internals when Git cannot start
88- Document explicit `git.exe` child-process and unrestricted-Bash residual bypasses
99- Keep safe-clone behavior unchanged

extensions/git-safe/__tests__/git-policy.test.ts

Modified

+38 / −0 text lines

1import { spawnSync } from "node:child_process";
12import {
23 chmodSync,
34 copyFileSync,
7273 expect(wrapper).not.toContain("__PI_GIT_SAFE_REAL_GIT__");
7374 });
76 it.runIf(process.platform === "win32")(
77 "launches when callers disable MSYS argument conversion",
78 async () => {
79 const bin = mkdtempSync(path.join(tmpdir(), "pi-git-policy-bin-"));
80 testDirs.push(bin);
81 copyFileSync(process.execPath, path.join(bin, "git.exe"));
82 const runtime = await createGitPolicyRuntime({ PATH: bin }, "win32");
83 const launcher = path
84 .join(runtime.wrapperDir, "git")
85 .replaceAll("\\", "/")
86 .replace(
87 /^([A-Za-z]):\//u,
88 (_match, drive: string) => `/${drive.toLowerCase()}/`,
89 );
90 const result = spawnSync(
91 "bash",
92 ["-lc", `MSYS2_ARG_CONV_EXCL='*' '${launcher}' --version`],
93 { encoding: "utf8" },
94 );
95 expect(result.status, result.stderr).toBe(0);
96 expect(result.stdout.trim()).toBe(process.version);
98 rmSync(path.join(runtime.wrapperDir, "git-wrapper.cjs"));
99 const unavailable = spawnSync(
100 "bash",
101 ["-lc", `'${launcher}' --version`],
102 {
103 encoding: "utf8",
104 },
105 );
106 expect(unavailable.status).toBe(127);
107 expect(unavailable.stderr.trim()).toBe(
108 "git: command unavailable; ask the user to restart Pi",
109 );
110 },
111 );
75113 it("routes Git, command, and env through the executable wrapper", () => {
76114 const runtime = { wrapperDir: "/tmp/git policy", realGit: "/usr/bin/git" };
77115 const wrapped = applyGitPolicy("git status", runtime);

extensions/git-safe/git-policy.ts

Modified

+9 / −1 text lines

8484 const wrapperDir = await mkdtemp(join(tmpdir(), "pi-git-safe-policy-"));
8585 const wrapperScript = join(wrapperDir, "git-wrapper.cjs");
8686 const launcher = join(wrapperDir, "git");
87 const wrapperScriptArgument =
88 platform === "win32" ? wrapperScript : bashPath(wrapperScript);
8789 try {
8890 const template = await readFile(
8991 new URL("./git-wrapper.cjs", import.meta.url),
9799 ),
98100 writeFile(
99101 launcher,
100 `#!/bin/sh\nexec ${shellQuote(bashPath(process.execPath))} ${shellQuote(bashPath(wrapperScript))} "$@"\n`,
102 `#!/bin/sh
103if [ ! -f ${shellQuote(bashPath(wrapperScript))} ]; then
104 printf '%s\\n' 'git: command unavailable; ask the user to restart Pi' >&2
105 exit 127
106fi
107exec ${shellQuote(bashPath(process.execPath))} ${shellQuote(wrapperScriptArgument)} "$@"
108`,
101109 { encoding: "utf8", mode: 0o500 },
102110 ),
103111 writeFile(

extensions/the-system/AGENTS.md

Added
new file mode 100644

+1 / −0 text lines

1Until The System’s first release, keep config and board schema versions `0`; reject mismatches via `/system init`; never add compatibility or migration code.

extensions/the-system/CHANGELOG.md

Modified

+6 / −3 text lines

33## Unreleased
5- Migrate The System documents to rich Markdown bundles with YAML graph metadata,
6 config-only machine state, doctor validation, and file-level spec ownership.
7- Rename phase and plan status `done` to `approved`; remove issue status.
5- Use rich Markdown bundles with YAML graph metadata, config-only machine state,
6 doctor validation, and file-level spec ownership.
7- Add `/system board` with tracked schema-0 operational state, nested plan cards, independent issues, responsive accordions, and human-reviewed `/system assess` proposals.
8- Rename plan status `done` to `approved`; remove issue status.
89- Open rendered pages through the native Win32 URL handler without flashing a command window.
910- Add turn-scoped `system_slot` allocation with title-derived slugs and repeatable ID reservation.
11- Redefine phases as project-wide operating epochs selected through config, injected into agent context, and shown in Pi and book navigation.
12- Reset the unreleased config schema to version 0; `/system init` updates machine schema markers mechanically, then offers agent-led bundle migration.
1114## 0.0.3

extensions/the-system/README.md

Modified

+25 / −5 text lines

55## Commands
77- `/system` shows help.
8- `/system init [PROJECT-PREFIX]` initializes or upgrades `.system` after confirmation.
8- `/system init [PROJECT-PREFIX]` initializes `.system`, updates machine schema markers, then offers agent-led bundle migration after config schema changes.
99- `/system doctor` runs read-only validation.
1010- `/system view <path|id|slug>` renders one document to temporary HTML.
1111- `/system edit <path|id|slug>` opens one document in `VISUAL`, `EDITOR`, or a platform editor.
1212- `/system book` renders the full dossier to temporary HTML.
13- `/system board` opens the interactive project board.
14- `/system assess [instructions]` assesses implementation progress and proposes board changes.
1315- `/system research|spec|spec-verify|phase|plan|issue|exec [instructions]` injects stage prompts.
1517Lifecycle stages never auto-chain.
2123The agent calls it for each new bundle after choosing a semantic title, then uses the returned ID and path exactly.
2224Context determines which bundles, if any, the command creates.
26Assessment temporarily enables `system_board_propose`.
27Its proposals remain ephemeral until a human applies selected changes through `/system board`.
29## Board
31Tracked operational state lives in `.system/board.json`; bundle content remains stateless about implementation progress.
32Specs and plans use `todo|done`; issues use `open|done`.
33Absent entries default to `todo` or `open`.
34Each explicit entry records `state`, `updatedAt`, and `source: manual|assess` without duplicating bundle content.
35A spec can be done without plans, but cannot be done while any linked plan is todo.
36Spec toggles never change plan states.
37Reopening a plan demotes its spec; issues never change spec state.
38The board schema version is `0`; `/system init` updates mismatches mechanically before board or assessment can continue.
2440## Documents
2642Canonical artifacts live at:
3854- research: `id`, `type: research`, `title`
3955- spec: `id`, `type: spec`, `title`, optional `research`
40- phase: `id`, `type: phase`, `title`, `spec`, `status: draft|approved`
41- plan: `id`, `type: plan`, `title`, `spec`, optional `phase`, `status: draft|approved`
56- phase: `id`, `type: phase`, `title`, `label`
57- plan: `id`, `type: plan`, `title`, `spec`, `status: draft|approved`
4258- issue: `id`, `type: issue`, `title`, `specs`
4460Issues intentionally have no status field.
45Approved phases and plans are immutable.
46Create a new artifact instead.
61Phases are project-wide operating epochs, not spec decomposition.
62The optional config `currentPhase` selects one phase for prompt injection and the Pi footer.
63Existing phase amendments and current-phase transitions require human approval.
64Approved plans are immutable.
65Create a new plan instead.
66The config schema version is `0`; a mismatch fails with instructions to run `/system init`.
4868## Resources

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

Modified

+139 / −18 text lines

1313import path from "node:path";
1414import { pathToFileURL } from "node:url";
1515import { expect, test } from "@playwright/test";
16import { createBoardRuntime } from "../board-runtime.ts";
1617import { createSystemCommand } from "../system-command.ts";
1819const roots: string[] = [];
3334 process.env.NODE_ENV = "test";
3435 try {
3536 await command.handler("view PX-SPEC-SPEC0001", ctx(root, notices));
37 await command.handler("view PX-PHASE-PHASE002", ctx(root, notices));
3638 await command.handler("book", ctx(root, notices));
3739 } finally {
3840 process.env.NODE_ENV = previousNodeEnv;
3941 }
4042 const view = pathFromNotice(notices[0] ?? "");
41 const book = pathFromNotice(notices[1] ?? "");
43 const phaseView = pathFromNotice(notices[1] ?? "");
44 const book = pathFromNotice(notices[2] ?? "");
4245 await page.goto(pathToFileURL(view).href);
4346 await expect(
4447 page.getByRole("heading", { name: "Contract" }).first(),
5154 /file:\/\/.*mockup-card\.html/,
5255 );
5356 await expect(page.getByText("raw html works")).toBeVisible();
57 await page.goto(pathToFileURL(phaseView).href);
58 await expect(page.locator(".phase-current")).toHaveText("Current phase");
59 await expect(
60 page.getByRole("heading", { name: "Pre-v1" }).first(),
61 ).toBeVisible();
5462 await page.goto(pathToFileURL(book).href);
5563 await expect(
5664 page.getByRole("heading", { name: /the-system-render-e2e-.* Dossier/ }),
5765 ).toBeVisible();
5866 await expect(page.getByRole("link", { name: "CORE-SYSTEM" })).toBeVisible();
59 await expect(page.locator("#PX-PHASE-PHASE001")).toBeVisible();
67 await expect(page.locator("#PX-PHASE-PHASE002")).toBeVisible();
68 await expect(page.locator(".book-top .active-phase")).toHaveText(
69 "Current phase pre-v1",
70 );
71 await expect(page.locator('.book-nav a[aria-current="true"]')).toContainText(
72 "PX-PHASE-PHASE002",
73 );
6074 await expect(page.locator(".book-toc")).toHaveCount(0);
6175 await expect(page.getByText("On this page")).toHaveCount(0);
6276 await expect(page.locator(".book-nav .nav-utils")).toBeVisible();
7185 await expect(
7286 page.locator("#PX-SPEC-SPEC0001 article > :last-child"),
7387 ).toHaveClass(/doc-related/);
74 await expect(page.locator("#PX-SPEC-SPEC0001 .doc-related")).toContainText(
75 "Delivery",
76 );
7788 await expect(page.locator("#PX-SPEC-SPEC0001 .doc-related")).toContainText(
7889 "Build",
7990 );
89100 const orderedSections = await page
90101 .locator(".book-section")
91102 .evaluateAll((sections) => sections.map((section) => section.id));
92 expect(orderedSections.indexOf("PX-SPEC-SPEC0001")).toBeLessThan(
93 orderedSections.indexOf("PX-PHASE-PHASE001"),
94 );
95 expect(orderedSections.indexOf("PX-PHASE-PHASE001")).toBeLessThan(
103 expect(orderedSections.indexOf("CORE-MISSION")).toBeLessThan(
96104 orderedSections.indexOf("PX-PHASE-PHASE002"),
97105 );
98106 expect(orderedSections.indexOf("PX-PHASE-PHASE002")).toBeLessThan(
107 orderedSections.indexOf("CORE-RULES"),
108 );
109 expect(orderedSections.indexOf("CORE-RULES")).toBeLessThan(
110 orderedSections.indexOf("PX-PHASE-PHASE001"),
111 );
112 expect(orderedSections.indexOf("PX-PHASE-PHASE001")).toBeLessThan(
113 orderedSections.indexOf("PX-SPEC-SPEC0001"),
114 );
115 expect(orderedSections.indexOf("PX-SPEC-SPEC0001")).toBeLessThan(
99116 orderedSections.indexOf("PX-PLAN-PLAN0001"),
100117 );
101118 expect(orderedSections.indexOf("PX-PLAN-PLAN0001")).toBeLessThan(
110127 await assertSidebarConnected(page);
111128 const graph = page.locator("[data-graph-svg]");
112129 await expect(graph).toBeVisible();
113 await expect(graph.locator("a")).toHaveCount(7);
130 await expect(graph.locator("a")).toHaveCount(5);
131 await expect(graph.locator('a[href="#PX-PHASE-PHASE002"]')).toHaveCount(0);
114132 const initialViewBox = await graph.getAttribute("viewBox");
115133 await graph.hover();
116134 await page.mouse.wheel(0, -240);
117135 await expect(graph).not.toHaveAttribute("viewBox", initialViewBox ?? "");
118136 await page.locator('[data-graph-zoom="reset"]').click();
119137 await expect(graph).toHaveAttribute("viewBox", initialViewBox ?? "");
120 await graph.locator('a[href="#PX-PHASE-PHASE001"]').click();
121 await expect(page.locator("#PX-PHASE-PHASE001")).toBeInViewport();
122 await expect(page).toHaveURL(/#PX-PHASE-PHASE001$/);
138 await page.locator('.book-nav a[href="#PX-PHASE-PHASE002"]').click();
139 await expect(page.locator("#PX-PHASE-PHASE002")).toBeInViewport();
140 await expect(page).toHaveURL(/#PX-PHASE-PHASE002$/);
123141 await expect.poll(() => page.evaluate(() => scrollX)).toBe(0);
124142 await assertSidebarConnected(page);
125143 await page.locator('.book-nav a[href="#PX-SPEC-SPEC0001"]').click();
162180 expect(hashTree(path.join(root, ".system"))).toBe(before);
163181});
183test("/system board persists independent spec, plan, and issue assessments", async ({
184 page,
185}) => {
186 const root = systemFixture();
187 const runtime = createBoardRuntime();
188 try {
189 runtime.beginAssessment(root);
190 await runtime.tool.execute(
191 "assessment",
192 {
193 items: [
194 {
195 id: "PX-ISSUE-ISSUE001",
196 state: "done",
197 rationale: "The reproduction no longer fails.",
198 },
199 ],
200 },
201 new AbortController().signal,
202 undefined,
203 { cwd: root } as never,
204 );
205 runtime.endAssessment();
206 const notice = await runtime.open(root);
207 const url = notice.match(/http:\/\/127\.0\.0\.1:\d+\/\?k=[^\s]+/)?.[0];
208 expect(url).toBeTruthy();
209 await page.goto(url ?? "");
211 const spec = page.locator('[data-board-item][data-id="PX-SPEC-SPEC0001"]');
212 const planA = page.locator('[data-board-item][data-id="PX-PLAN-PLAN0001"]');
213 const planB = page.locator('[data-board-item][data-id="PX-PLAN-PLAN0002"]');
214 const issue = page.locator(
215 '[data-board-item][data-id="PX-ISSUE-ISSUE001"]',
216 );
217 await expect(spec).toBeVisible();
218 await expect(planA).toBeVisible();
219 await expect(planB).toBeVisible();
220 await expect(issue.locator("[data-proposal]")).toContainText(
221 "The reproduction no longer fails.",
222 );
223 await issue.locator("[data-apply-proposal]").click();
224 await expect(issue).toHaveClass(/is-done/);
225 await expect(issue.locator("[data-assessment]")).toContainText("assess");
227 await spec.locator(":scope > .board-row > .board-bundle > summary").click();
228 const specDetails = spec.locator(
229 ":scope > .board-row > .board-bundle > .board-details",
230 );
231 await expect(specDetails).toContainText("body-only-term");
232 await expect(specDetails.locator(".ledger")).toContainText("Metadata");
233 await expect(
234 spec.locator(":scope > .board-row > .board-state"),
235 ).toBeDisabled();
236 await planA.locator(".board-state").click();
237 await expect(planA).toHaveClass(/is-done/);
238 await planB.locator(".board-state").click();
239 await expect(planB).toHaveClass(/is-done/);
240 await expect(
241 spec.locator(":scope > .board-row > .board-state"),
242 ).toBeEnabled();
243 await spec.locator(":scope > .board-row > .board-state").click();
244 await expect(spec).toHaveClass(/is-done/);
246 await spec.locator(":scope > .board-row > .board-state").click();
247 await expect(spec).not.toHaveClass(/is-done/);
248 await expect(planA).toHaveClass(/is-done/);
249 await expect(planB).toHaveClass(/is-done/);
250 await spec.locator(":scope > .board-row > .board-state").click();
251 await planA.locator(".board-state").click();
252 await expect(spec).not.toHaveClass(/is-done/);
253 await expect(planA).not.toHaveClass(/is-done/);
254 await expect(planB).toHaveClass(/is-done/);
256 const board = JSON.parse(
257 readFileSync(path.join(root, ".system/board.json"), "utf8"),
258 );
259 expect(board.items["PX-ISSUE-ISSUE001"].source).toBe("assess");
260 expect(board.items["PX-SPEC-SPEC0001"].state).toBe("todo");
261 expect(board.items["PX-PLAN-PLAN0001"].state).toBe("todo");
262 expect(board.items["PX-PLAN-PLAN0002"].state).toBe("done");
264 await page.setViewportSize({ width: 390, height: 844 });
265 const positions = await page.evaluate(() => {
266 const specs = document
267 .querySelector(".board-spec-list")
268 ?.getBoundingClientRect();
269 const issues = document
270 .querySelector(".board-issue-list")
271 ?.getBoundingClientRect();
272 return { specsBottom: specs?.bottom ?? 0, issuesTop: issues?.top ?? 0 };
273 });
274 expect(positions.issuesTop).toBeGreaterThanOrEqual(positions.specsBottom);
275 await expect.poll(() => page.evaluate(() => scrollX)).toBe(0);
276 } finally {
277 runtime.shutdown();
278 }
279});
165281async function assertSidebarConnected(page: {
166282 evaluate: <T>(fn: () => T) => Promise<T>;
167283}) {
199315 mkdirSync(path.join(root, ".git"));
200316 for (const directory of ["specs", "phases", "plans", "issues", "research"])
201317 mkdirSync(path.join(root, ".system", directory), { recursive: true });
202 write(root, ".system/config.json", '{"prefix":"PX","schemaVersion":3}');
318 write(
319 root,
320 ".system/config.json",
321 '{"prefix":"PX","schemaVersion":0,"currentPhase":"PX-PHASE-PHASE002"}',
322 );
323 write(root, ".system/board.json", '{"schemaVersion":0,"items":{}}');
203324 write(root, ".system/SYSTEM.md", "# SYSTEM\n");
204325 write(root, ".system/MISSION.md", "# MISSION\n");
205326 write(root, ".system/RULES.md", "# RULES\n");
242363 write(
243364 root,
244365 ".system/phases/PX-PHASE-PHASE001-delivery/index.md",
245 "---\nid: PX-PHASE-PHASE001\ntype: phase\ntitle: Delivery\nspec: PX-SPEC-SPEC0001\nstatus: draft\n---\n\n# Delivery\n",
366 "---\nid: PX-PHASE-PHASE001\ntype: phase\ntitle: Prototype\nlabel: prototype\n---\n\n# Prototype\n",
246367 );
247368 write(
248369 root,
249370 ".system/phases/PX-PHASE-PHASE002-after-delivery/index.md",
250 "---\nid: PX-PHASE-PHASE002\ntype: phase\ntitle: After Delivery\nspec: PX-SPEC-SPEC0001\nstatus: draft\ndepends_on: [PX-PHASE-PHASE001]\n---\n\n# After Delivery\n",
371 "---\nid: PX-PHASE-PHASE002\ntype: phase\ntitle: Pre-v1\nlabel: pre-v1\n---\n\n# Pre-v1\n",
251372 );
252373 write(
253374 root,
254375 ".system/plans/PX-PLAN-PLAN0001-build/index.md",
255 "---\nid: PX-PLAN-PLAN0001\ntype: plan\ntitle: Build\nspec: PX-SPEC-SPEC0001\nphase: PX-PHASE-PHASE002\nstatus: draft\n---\n\n# Build\n",
376 "---\nid: PX-PLAN-PLAN0001\ntype: plan\ntitle: Build\nspec: PX-SPEC-SPEC0001\nstatus: draft\n---\n\n# Build\n",
256377 );
257378 write(
258379 root,
259380 ".system/plans/PX-PLAN-PLAN0002-test/index.md",
260 "---\nid: PX-PLAN-PLAN0002\ntype: plan\ntitle: Test\nspec: PX-SPEC-SPEC0001\nphase: PX-PHASE-PHASE002\nstatus: draft\ndepends_on: [PX-PLAN-PLAN0001]\n---\n\n# Test\n",
381 "---\nid: PX-PLAN-PLAN0002\ntype: plan\ntitle: Test\nspec: PX-SPEC-SPEC0001\nstatus: draft\ndepends_on: [PX-PLAN-PLAN0001]\n---\n\n# Test\n",
261382 );
262383 write(
263384 root,

extensions/the-system/__tests__/artifact-slot-tool.test.ts

Modified

+1 / −1 text lines

1616 mkdirSync(path.join(root, ".system", directory), { recursive: true });
1717 writeFileSync(
1818 path.join(root, ".system/config.json"),
19 '{"prefix":"PX","schemaVersion":3}',
19 '{"prefix":"PX","schemaVersion":0}',
2020 );
2121 return root;
2222};

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

Added
new file mode 100644

+159 / −0 text lines

1import assert from "node:assert/strict";
2import { describe, it } from "vitest";
3import {
4 boardStateFor,
5 boardStateForInitialization,
6 boardStateSource,
7 emptyBoardState,
8 parseBoardState,
9 updateBoardState,
10} from "../board-state.ts";
11import type { BundleDocumentRecord, DocumentMetadata } from "../documents.ts";
12import { SystemDocumentError } from "../documents.ts";
14const document = (metadata: DocumentMetadata): BundleDocumentRecord => ({
15 path: `.system/${metadata.type}s/${metadata.id}-fixture/index.md`,
16 metadata,
17 frontmatter: new Map(),
18});
19const spec = document({
20 id: "PX-SPEC-SPEC0001",
21 type: "spec",
22 title: "Contract",
23});
24const planA = document({
25 id: "PX-PLAN-PLAN0001",
26 type: "plan",
27 title: "Build",
28 spec: spec.metadata.id,
29 status: "approved",
30});
31const planB = document({
32 id: "PX-PLAN-PLAN0002",
33 type: "plan",
34 title: "Test",
35 spec: spec.metadata.id,
36 status: "approved",
37});
38const issue = document({
39 id: "PX-ISSUE-ISSUE001",
40 type: "issue",
41 title: "Bug",
42 specs: [spec.metadata.id],
43});
44const documents = [spec, planA, planB, issue];
45const at = "2026-03-20T12:00:00.000Z";
47describe("board state", () => {
48 it("defaults specs and plans to todo and issues to open", () => {
49 const board = emptyBoardState();
50 assert.equal(boardStateFor(board, spec.metadata), "todo");
51 assert.equal(boardStateFor(board, planA.metadata), "todo");
52 assert.equal(boardStateFor(board, issue.metadata), "open");
53 });
55 it("keeps spec state manual while requiring every existing plan done", () => {
56 let board = emptyBoardState();
57 assert.throws(
58 () =>
59 updateBoardState(
60 board,
61 documents,
62 spec.metadata.id,
63 "done",
64 "manual",
65 at,
66 ),
67 (error: unknown) =>
68 error instanceof SystemDocumentError &&
69 error.code === "board.spec-plans",
70 );
71 board = updateBoardState(
72 board,
73 documents,
74 planA.metadata.id,
75 "done",
76 "manual",
77 at,
78 );
79 board = updateBoardState(
80 board,
81 documents,
82 planB.metadata.id,
83 "done",
84 "manual",
85 at,
86 );
87 assert.equal(boardStateFor(board, spec.metadata), "todo");
88 board = updateBoardState(
89 board,
90 documents,
91 spec.metadata.id,
92 "done",
93 "manual",
94 at,
95 );
96 assert.equal(boardStateFor(board, spec.metadata), "done");
97 });
99 it("allows a planless spec done and never lets issues demote it", () => {
100 let board = updateBoardState(
101 emptyBoardState(),
102 [spec, issue],
103 spec.metadata.id,
104 "done",
105 "manual",
106 at,
107 );
108 board = updateBoardState(
109 board,
110 [spec, issue],
111 issue.metadata.id,
112 "open",
113 "manual",
114 at,
115 );
116 assert.equal(boardStateFor(board, spec.metadata), "done");
117 });
119 it("reopening one plan demotes its spec without changing sibling plans", () => {
120 let board = emptyBoardState();
121 for (const id of [planA.metadata.id, planB.metadata.id, spec.metadata.id])
122 board = updateBoardState(board, documents, id, "done", "manual", at);
123 board = updateBoardState(
124 board,
125 documents,
126 planA.metadata.id,
127 "todo",
128 "manual",
129 at,
130 );
131 assert.equal(boardStateFor(board, spec.metadata), "todo");
132 assert.equal(boardStateFor(board, planB.metadata), "done");
133 });
135 it("parses strict schema 0 and directly rewrites version mismatches", () => {
136 const current = updateBoardState(
137 emptyBoardState(),
138 documents,
139 issue.metadata.id,
140 "done",
141 "assess",
142 at,
143 );
144 assert.deepEqual(parseBoardState(boardStateSource(current), "PX"), current);
145 const mismatched = boardStateSource(current).replace(
146 '"schemaVersion": 0',
147 '"schemaVersion": 9',
148 );
149 assert.equal(
150 boardStateForInitialization(mismatched, "PX").sourceSchemaVersion,
151 9,
152 );
153 assert.throws(
154 () => parseBoardState(mismatched, "PX"),
155 (error: unknown) =>
156 error instanceof SystemDocumentError && error.code === "board.version",
157 );
158 });
159});

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

Modified

+38 / −4 text lines

3434 mkdirSync(path.join(root, ".system", directory), { recursive: true });
3535 for (const file of ["SYSTEM.md", "MISSION.md", "RULES.md"])
3636 write(root, `.system/${file}`, `# ${file}\n`);
37 write(root, ".system/config.json", '{"prefix":"PX","schemaVersion":3}');
37 write(root, ".system/config.json", '{"prefix":"PX","schemaVersion":0}');
38 write(root, ".system/board.json", '{"schemaVersion":0,"items":{}}');
3839};
3940const snapshot = (root: string) => {
4041 const entries: {
8283 ".system/MISSION.md filesystem.missing",
8384 ".system/RULES.md filesystem.missing",
8485 ".system/SYSTEM.md filesystem.missing",
86 ".system/board.json filesystem.missing",
8587 ".system/config.json filesystem.missing",
8688 ".system/issues filesystem.missing",
8789 ".system/phases filesystem.missing",
9294 );
9395 });
95 it("combines shared bundle, graph, obsolete CSS, and test diagnostics", () => {
97 it("combines shared bundle, graph, and test diagnostics", () => {
9698 const root = temporaryRoot();
9799 validSystem(root);
98 write(root, ".system/system.css", "legacy\n");
99100 write(
100101 root,
101102 ".system/specs/PX-SPEC-SPEC0001-contract/index.md",
118119 [
119120 ".system/plans/PX-PLAN-PLAN0001-work/index.md graph.dangling-reference",
120121 ".system/specs/PX-SPEC-SPEC0002-empty bundle.missing-index",
121 ".system/system.css filesystem.obsolete",
122122 "tests/contract.test.ts test.dangling-reference",
123123 ],
124124 );
125125 });
127 it("reports invalid and dangling board state", () => {
128 const root = temporaryRoot();
129 validSystem(root);
130 write(
131 root,
132 ".system/board.json",
133 '{"schemaVersion":0,"items":{"PX-SPEC-MISSING1":{"state":"done","updatedAt":"2026-03-20T12:00:00.000Z","source":"manual"}}}',
134 );
135 assert.deepEqual(
136 runDoctor(root).diagnostics.map(({ code }) => code),
137 ["board.dangling-item"],
138 );
139 write(root, ".system/board.json", '{"schemaVersion":4,"items":{}}');
140 assert.deepEqual(
141 runDoctor(root).diagnostics.map(({ code }) => code),
142 ["board.version"],
143 );
144 });
127146 it("does not follow bundle symlinks and is green for a complete bundled system", () => {
128147 const root = temporaryRoot();
129148 const outside = temporaryRoot();
134153 markdown("PX-SPEC-SPEC0001"),
135154 );
136155 assert.deepEqual(runDoctor(root).diagnostics, []);
156 write(
157 root,
158 ".system/config.json",
159 '{"prefix":"PX","schemaVersion":0,"currentPhase":"PX-PHASE-PHASE001"}',
160 );
161 assert.deepEqual(
162 runDoctor(root).diagnostics.map(({ code, path }) => `${path} ${code}`),
163 [".system/config.json config.current-phase"],
164 );
165 write(
166 root,
167 ".system/phases/PX-PHASE-PHASE001-pre-v1/index.md",
168 markdown("PX-PHASE-PHASE001", "phase", "\nlabel: pre-v1"),
169 );
170 assert.deepEqual(runDoctor(root).diagnostics, []);
137171 symlinkSync(
138172 outside,
139173 path.join(root, ".system/specs/PX-SPEC-SPEC0002-link"),

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

Modified

+81 / −48 text lines

1313 discoverDocumentBundles,
1414 discoverProjectRoot,
1515 indexBundleDocuments,
16 inspectSystemConfig,
16 PHASE_BYTE_LIMIT,
1717 parseAuthoredDocument,
1818 parseDocumentId,
1919 parseSystemConfig,
2020 resolveGovernedPath,
2121 SystemDocumentError,
22 systemConfigForInitialization,
2223 validateBundleCandidate,
2324 validateDocumentPath,
2425} from "../documents.ts";
5657 rmSync(root, { recursive: true, force: true });
5758});
59describe("project root and schema-v3 config", () => {
60describe("project root and schema-0 config", () => {
6061 it("contains paths and resolves nearest marker", () => {
6162 const root = tree();
6263 mkdirSync(path.join(root, ".git"));
6869 );
6970 });
71 it("accepts minimal config and inspects narrow v1 config", () => {
72 it("accepts schema 0 and prepares mismatched config for initialization", () => {
7273 assert.deepEqual(
7374 parseSystemConfig(
74 '{"prefix":"PX","schemaVersion":3,"title":"Project X"}',
75 '{"prefix":"PX","schemaVersion":0,"title":"Project X","currentPhase":"PX-PHASE-PHASE001"}',
7576 ),
76 { prefix: "PX", schemaVersion: 3, title: "Project X" },
77 {
78 prefix: "PX",
79 schemaVersion: 0,
80 title: "Project X",
81 currentPhase: "PX-PHASE-PHASE001",
82 },
7783 );
78 assert.deepEqual(parseSystemConfig('{"prefix":"PX","schemaVersion":3}'), {
84 assert.deepEqual(parseSystemConfig('{"prefix":"PX","schemaVersion":0}'), {
7985 prefix: "PX",
80 schemaVersion: 3,
86 schemaVersion: 0,
8187 });
88 assert.throws(
89 () => parseSystemConfig('{"prefix":"PX","schemaVersion":4}'),
90 /does not match 0; run \/system init/,
91 );
8292 assert.deepEqual(
83 inspectSystemConfig('{"prefix":"PX","schemaVersion":1,"styleVersion":1}'),
84 { config: { prefix: "PX", schemaVersion: 1 }, legacyStyleVersion: 1 },
93 systemConfigForInitialization(
94 '{"prefix":"PX","schemaVersion":4,"title":"Project X"}',
95 ),
96 {
97 config: { prefix: "PX", schemaVersion: 0, title: "Project X" },
98 sourceSchemaVersion: 4,
99 },
85100 );
86101 });
87102});
89describe("schema-v3 identity and metadata", () => {
90 it("parses uppercase token IDs and rejects numeric legacy IDs", () => {
104describe("schema-0 identity and metadata", () => {
105 it("parses uppercase token IDs and rejects short numeric IDs", () => {
91106 assert.deepEqual(parseDocumentId("PX-SPEC-AZ3_P9QK", "PX"), {
92107 id: "PX-SPEC-AZ3_P9QK",
93108 prefix: "PX",
107122 it("projects known graph fields while preserving unknown frontmatter", () => {
108123 const parsed = parseAuthoredDocument(
109 `---\nid: PX-PLAN-PL4N0001\ntype: plan\ntitle: Delivery\nspec: PX-SPEC-SPEC0001\nphase: PX-PHASE-PH4S0001\nstatus: draft\ndepends_on: [PX-PLAN-PL4N0000]\nreview:\n owner: human\n---\n`,
124 `---\nid: PX-PLAN-PL4N0001\ntype: plan\ntitle: Delivery\nspec: PX-SPEC-SPEC0001\nstatus: draft\ndepends_on: [PX-PLAN-PL4N0000]\nreview: human\n---\n`,
110125 "PX",
111126 );
112127 assert.deepEqual(parsed.metadata, {
114129 type: "plan",
115130 title: "Delivery",
116131 spec: "PX-SPEC-SPEC0001",
117 phase: "PX-PHASE-PH4S0001",
118132 status: "draft",
119133 depends_on: ["PX-PLAN-PL4N0000"],
120134 });
121135 assert.deepEqual(
122136 [...parsed.frontmatter.keys()],
123 [
124 "id",
125 "type",
126 "title",
127 "spec",
128 "phase",
129 "status",
130 "depends_on",
131 "review",
132 ],
137 ["id", "type", "title", "spec", "status", "depends_on", "review"],
138 );
139 });
141 it("parses operating phases and validates their labels and size", () => {
142 assert.deepEqual(
143 parseAuthoredDocument(
144 "---\nid: PX-PHASE-PHASE001\ntype: phase\ntitle: Pre-v1\nlabel: pre-v1\n---\n",
145 "PX",
146 ).metadata,
147 {
148 id: "PX-PHASE-PHASE001",
149 type: "phase",
150 title: "Pre-v1",
151 label: "pre-v1",
152 },
153 );
154 assert.throws(
155 () =>
156 parseAuthoredDocument(
157 "---\nid: PX-PHASE-PHASE001\ntype: phase\ntitle: Pre-v1\nlabel: label-is-too-long\n---\n",
158 "PX",
159 ),
160 /1-12 ASCII/,
161 );
162 assert.throws(
163 () =>
164 parseAuthoredDocument(
165 `---\nid: PX-PHASE-PHASE001\ntype: phase\ntitle: Pre-v1\nlabel: pre-v1\n---\n\n${"x".repeat(PHASE_BYTE_LIMIT)}`,
166 "PX",
167 ),
168 /byte limit/,
133169 );
134170 });
240276 );
241277 });
243 it("validates references, duplicates, and phase/spec consistency", () => {
279 it("keeps phases separate from the spec-plan graph", () => {
244280 const indexed = indexBundleDocuments(
245281 [
246282 source(
265301 "phases",
266302 "PX-PHASE-PHASE001",
267303 "delivery",
268 "id: PX-PHASE-PHASE001\ntype: phase\ntitle: Delivery\nspec: PX-SPEC-SPEC0001\nstatus: approved",
304 "id: PX-PHASE-PHASE001\ntype: phase\ntitle: Delivery\nlabel: delivery",
269305 ),
270306 source(
271307 "plans",
272308 "PX-PLAN-PLAN0001",
273309 "build",
274 "id: PX-PLAN-PLAN0001\ntype: plan\ntitle: Build\nspec: PX-SPEC-SPEC0002\nphase: PX-PHASE-PHASE001\nstatus: draft",
310 "id: PX-PLAN-PLAN0001\ntype: plan\ntitle: Build\nspec: PX-SPEC-SPEC0002\nstatus: draft",
275311 ),
276312 ],
277313 "PX",
278314 );
315 assert.deepEqual(indexed.diagnostics, []);
279316 assert.deepEqual(
280 indexed.diagnostics.map(
281 (item) => `${item.path} ${item.code}: ${item.message}`,
282 ),
283 [
284 ".system/plans/PX-PLAN-PLAN0001-build/index.md graph.forbidden-edge: PX-PHASE-PHASE001 belongs to PX-SPEC-SPEC0001, not PX-SPEC-SPEC0002",
285 ],
317 indexed.documents.find((document) => document.metadata.type === "phase")
318 ?.metadata,
319 {
320 id: "PX-PHASE-PHASE001",
321 type: "phase",
322 title: "Delivery",
323 label: "delivery",
324 },
286325 );
287326 });
301340 "two",
302341 "id: PX-SPEC-SPEC0002\ntype: spec\ntitle: Two",
303342 ),
304 source(
305 "phases",
306 "PX-PHASE-PHASE001",
307 "one",
308 "id: PX-PHASE-PHASE001\ntype: phase\ntitle: One\nspec: PX-SPEC-SPEC0001\nstatus: draft\ndepends_on: [PX-PHASE-PHASE002]",
309 ),
310 source(
311 "phases",
312 "PX-PHASE-PHASE002",
313 "two",
314 "id: PX-PHASE-PHASE002\ntype: phase\ntitle: Two\nspec: PX-SPEC-SPEC0001\nstatus: draft\ndepends_on: [PX-PHASE-PHASE001]",
315 ),
316343 source(
317344 "plans",
318345 "PX-PLAN-PLAN0001",
329356 "plans",
330357 "PX-PLAN-PLAN0003",
331358 "three",
332 "id: PX-PLAN-PLAN0003\ntype: plan\ntitle: Three\nspec: PX-SPEC-SPEC0002\nstatus: draft",
359 "id: PX-PLAN-PLAN0003\ntype: plan\ntitle: Three\nspec: PX-SPEC-SPEC0001\nstatus: draft\ndepends_on: [PX-PLAN-PLAN0002]",
360 ),
361 source(
362 "plans",
363 "PX-PLAN-PLAN0004",
364 "four",
365 "id: PX-PLAN-PLAN0004\ntype: plan\ntitle: Four\nspec: PX-SPEC-SPEC0002\nstatus: draft\ndepends_on: [PX-PLAN-PLAN0002]",
333366 ),
334367 ],
335368 "PX",
352385 ),
353386 ],
354387 source(
355 "phases",
356 "PX-PHASE-PHASE001",
388 "plans",
389 "PX-PLAN-PLAN0001",
357390 "delivery",
358 "id: PX-PHASE-PHASE001\ntype: phase\ntitle: Delivery\nspec: PX-SPEC-MISSING1\nstatus: approved",
391 "id: PX-PLAN-PLAN0001\ntype: plan\ntitle: Delivery\nspec: PX-SPEC-MISSING1\nstatus: draft",
359392 ),
360393 "PX",
361394 );

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

Modified

+90 / −46 text lines

1414import { afterEach, describe, it } from "vitest";
1515import { runDoctor } from "../doctor.ts";
1616import { SystemDocumentError } from "../documents.ts";
17import {
18 applyInitialization,
19 inspectInitialization,
20 type MachineState,
21} from "../init.ts";
17import { applyInitialization, inspectInitialization } from "../init.ts";
2319const roots: string[] = [];
2420const root = () => {
3632 for (const name of ["SYSTEM.md", "MISSION.md", "RULES.md"])
3733 write(project, `.system/${name}`, `# ${name}\n\nApproved.\n`);
3834};
39const legacy = '{ "prefix": "PX", "schemaVersion": 1, "styleVersion": 1 }\n';
40const future: MachineState = { schemaVersion: 3 };
4135afterEach(() => {
4236 for (const value of roots.splice(0))
4337 rmSync(value, { recursive: true, force: true });
4438});
4640describe("guided initialization machine state", () => {
47 it("creates schema-v3 config and core files, then preserves cores on rerun", () => {
41 it("creates schema-0 config and core files, then preserves cores on rerun", () => {
4842 const project = root();
4943 const cwd = path.join(project, "packages", "app");
5044 mkdirSync(cwd, { recursive: true });
5650 );
5751 assert.equal(child.status, 0);
5852 assert.match(child.stdout, /WROTE \.system\/config\.json/);
53 assert.match(child.stdout, /WROTE \.system\/board\.json/);
5954 assert.match(child.stdout, /WROTE \.system\/SYSTEM\.md/);
60 assert.doesNotMatch(child.stdout, /system\.css/);
6155 assert.deepEqual(
6256 JSON.parse(
6357 readFileSync(path.join(project, ".system/config.json"), "utf8"),
6458 ),
65 { prefix: "PX", schemaVersion: 3, title: path.basename(project) },
59 { prefix: "PX", schemaVersion: 0, title: path.basename(project) },
6660 );
67 assert.equal(
68 lstatSync(path.join(project, ".system/system.css"), {
69 throwIfNoEntry: false,
70 }),
71 undefined,
61 assert.deepEqual(
62 JSON.parse(
63 readFileSync(path.join(project, ".system/board.json"), "utf8"),
64 ),
65 { schemaVersion: 0, items: {} },
7266 );
7367 assert.match(
7468 readFileSync(path.join(project, ".system/SYSTEM.md"), "utf8"),
7670 );
7771 assert.match(
7872 readFileSync(path.join(project, ".system/MISSION.md"), "utf8"),
79 /Current objective/,
73 /Enduring high-level project objective/,
8074 );
8175 assert.match(
8276 readFileSync(path.join(project, ".system/RULES.md"), "utf8"),
9084 root: project,
9185 prefix: "PX",
9286 changed: [],
93 removed: [],
9487 pending: [],
9588 });
9689 for (const [name, source, mtime] of before) {
10396 assert.equal(runDoctor(project).exitCode, 0);
10497 });
106 it("holds legacy config and CSS pending, then upgrades only when approved", () => {
99 it("holds a mismatched config pending, then rewrites it when approved", () => {
107100 const project = root();
108 write(project, ".system/config.json", legacy);
109 write(project, ".system/system.css", "legacy css\n");
101 const mismatched =
102 '{"prefix":"PX","schemaVersion":4,"title":"Project","obsolete":true}\n';
103 write(project, ".system/config.json", mismatched);
110104 cores(project);
111 const upgrades = [
112 ".system/config.json schemaVersion 1 -> 3; remove styleVersion",
113 `.system/config.json add title "${path.basename(project)}"`,
114 ".system/system.css remove obsolete machine-owned asset",
115 ];
116 assert.deepEqual(inspectInitialization(project).upgrades, upgrades);
117 assert.deepEqual(applyInitialization(project).pending, upgrades);
105 const rewrites = [".system/config.json schemaVersion 4 -> 0"];
106 assert.deepEqual(inspectInitialization(project).rewrites, rewrites);
107 assert.deepEqual(applyInitialization(project).pending, rewrites);
118108 assert.equal(
119109 readFileSync(path.join(project, ".system/config.json"), "utf8"),
120 legacy,
121 );
122 assert.equal(
123 readFileSync(path.join(project, ".system/system.css"), "utf8"),
124 "legacy css\n",
110 mismatched,
125111 );
126112 const result = applyInitialization(project, undefined, true);
127113 assert.deepEqual(result.changed, [".system/config.json"]);
128 assert.deepEqual(result.removed, [".system/system.css"]);
129 assert.equal(
130 lstatSync(path.join(project, ".system/system.css"), {
131 throwIfNoEntry: false,
132 }),
133 undefined,
114 assert.deepEqual(
115 JSON.parse(
116 readFileSync(path.join(project, ".system/config.json"), "utf8"),
117 ),
118 { prefix: "PX", schemaVersion: 0, title: "Project" },
134119 );
135120 });
137 it("rejects invalid prefixes, newer configs, and unsafe obsolete CSS paths", () => {
122 it("rewrites a mismatched board directly to schema 0", () => {
123 const project = root();
124 applyInitialization(project, "PX");
125 write(
126 project,
127 ".system/board.json",
128 JSON.stringify({
129 schemaVersion: 7,
130 items: {
131 "PX-SPEC-SPEC0001": {
132 state: "done",
133 updatedAt: "2026-03-20T12:00:00.000Z",
134 source: "manual",
135 },
136 },
137 }),
138 );
139 assert.deepEqual(inspectInitialization(project).rewrites, [
140 ".system/board.json schemaVersion 7 -> 0",
141 ]);
142 const configBefore = readFileSync(
143 path.join(project, ".system/config.json"),
144 "utf8",
145 );
146 const result = applyInitialization(project, undefined, true);
147 assert.deepEqual(result.changed, [".system/board.json"]);
148 assert.equal(
149 readFileSync(path.join(project, ".system/config.json"), "utf8"),
150 configBefore,
151 );
152 assert.equal(
153 JSON.parse(readFileSync(path.join(project, ".system/board.json"), "utf8"))
154 .schemaVersion,
155 0,
156 );
157 });
159 it("preserves selected phase and title while resetting the schema", () => {
160 const project = root();
161 applyInitialization(project, "PX");
162 write(
163 project,
164 ".system/config.json",
165 JSON.stringify({
166 prefix: "PX",
167 schemaVersion: 4,
168 title: "Custom title",
169 currentPhase: "PX-PHASE-PHASE001",
170 }),
171 );
172 applyInitialization(project, undefined, true);
173 assert.deepEqual(
174 JSON.parse(
175 readFileSync(path.join(project, ".system/config.json"), "utf8"),
176 ),
177 {
178 prefix: "PX",
179 schemaVersion: 0,
180 title: "Custom title",
181 currentPhase: "PX-PHASE-PHASE001",
182 },
183 );
184 });
186 it("rejects invalid prefixes, prefix conflicts, and unsafe config paths", () => {
138187 const project = root();
139188 assert.throws(() => applyInitialization(project), /prefix is required/i);
140189 assert.throws(() => applyInitialization(project, "x"), SystemDocumentError);
143192 () => inspectInitialization(project, "AB"),
144193 /prefix.*does not match/i,
145194 );
146 write(project, ".system/config.json", '{"prefix":"PX","schemaVersion":4}');
147 assert.throws(
148 () => inspectInitialization(project, undefined, future),
149 /newer/i,
150 );
152196 const linked = root();
153 write(linked, ".system/config.json", legacy);
154 symlinkSync("elsewhere.css", path.join(linked, ".system/system.css"));
197 mkdirSync(path.join(linked, ".system"));
198 symlinkSync("elsewhere.json", path.join(linked, ".system/config.json"));
155199 assert.throws(
156200 () => inspectInitialization(linked),
157201 (error: unknown) =>

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

Modified

+261 / −20 text lines

22import {
33 mkdirSync,
44 mkdtempSync,
5 readFileSync,
56 rmSync,
67 symlinkSync,
78 writeFileSync,
1011import path from "node:path";
1112import { afterEach, describe, it } from "vitest";
1213import { applyInitialization } from "../init.ts";
13import { startupRuntimeNotice } from "../startup-notice.ts";
14import {
15 startupRuntimeNotice,
16 startupRuntimeState,
17} from "../startup-notice.ts";
1418import {
1519 CORE_BYTE_LIMIT,
1620 composeSystemPrompt,
1721 preflightFileMutation,
1822 runtimeNotice,
23 runtimeState,
1924} from "../system.ts";
2126const roots: string[] = [];
6570 const project = mkdtempSync(path.join(tmpdir(), "the-system-runtime-"));
6671 roots.push(project);
6772 mkdirSync(path.join(project, ".git"));
73 assert.deepEqual(runtimeState(project), { active: false });
74 assert.deepEqual(await startupRuntimeState(project), { active: false });
6875 assert.equal(runtimeNotice(project), undefined);
6976 assert.equal(await startupRuntimeNotice(project), undefined);
7077 mkdirSync(path.join(project, ".system"));
78 assert.deepEqual(runtimeState(project), {
79 active: true,
80 notice:
81 "The System is incomplete or invalid; run /system init before governed work.",
82 });
83 assert.match(
84 (await startupRuntimeState(project)).notice ?? "",
85 /incomplete or invalid/,
86 );
7187 assert.match(runtimeNotice(project) ?? "", /incomplete or invalid/);
7288 assert.match(
7389 (await startupRuntimeNotice(project)) ?? "",
7490 /incomplete or invalid/,
7591 );
7692 });
94 it("reports the active project prefix", async () => {
95 const project = root();
96 assert.deepEqual(runtimeState(project), { active: true, prefix: "PX" });
97 assert.deepEqual(await startupRuntimeState(project), {
98 active: true,
99 prefix: "PX",
100 });
101 });
77102});
79104describe("runtime core injection", () => {
105 it("injects the current phase after MISSION without mutating it", () => {
106 const project = root();
107 const phase = ".system/phases/PX-PHASE-PHASE001-pre-v1/index.md";
108 write(
109 project,
110 phase,
111 documentSource({
112 id: "PX-PHASE-PHASE001",
113 type: "phase",
114 title: "Pre-v1",
115 label: "pre-v1",
116 }),
117 );
118 const configPath = path.join(project, ".system/config.json");
119 const config = JSON.parse(readFileSync(configPath, "utf8"));
120 writeFileSync(
121 configPath,
122 `${JSON.stringify({ ...config, currentPhase: "PX-PHASE-PHASE001" })}\n`,
123 );
124 const missionPath = path.join(project, ".system/MISSION.md");
125 const mission = readFileSync(missionPath, "utf8");
126 const prompt = composeSystemPrompt(project, "BASE");
127 assert.match(
128 prompt,
129 /SYSTEM\.md[\s\S]*MISSION\.md[\s\S]*Current phase: Pre-v1 · pre-v1[\s\S]*RULES\.md/,
130 );
131 assert.equal(readFileSync(missionPath, "utf8"), mission);
132 assert.deepEqual(runtimeState(project), {
133 active: true,
134 prefix: "PX",
135 phaseLabel: "pre-v1",
136 });
137 rmSync(path.join(project, path.dirname(phase)), {
138 recursive: true,
139 force: true,
140 });
141 assert.match(composeSystemPrompt(project, "BASE"), /governance error/);
142 });
80144 it("injects cores and reports malformed core paths", () => {
81145 const project = root();
82146 write(project, ".system/MISSION.md", "x".repeat(CORE_BYTE_LIMIT + 1));
88152});
90154describe("runtime bundle governance", () => {
155 it("activates an existing phase only after confirmation", async () => {
156 const project = root();
157 write(
158 project,
159 ".system/phases/PX-PHASE-PHASE001-pre-v1/index.md",
160 documentSource({
161 id: "PX-PHASE-PHASE001",
162 type: "phase",
163 title: "Pre-v1",
164 label: "pre-v1",
165 }),
166 );
167 const configPath = path.join(project, ".system/config.json");
168 const config = JSON.parse(readFileSync(configPath, "utf8"));
169 const candidate = `${JSON.stringify({ ...config, currentPhase: "PX-PHASE-PHASE001" })}\n`;
170 let approvals = 0;
171 const result = await preflightFileMutation(
172 project,
173 "write",
174 { path: ".system/config.json", content: candidate },
175 {
176 hasUI: true,
177 select: async (_title, items) => {
178 approvals += 1;
179 assert.match(items[0] ?? "", /pre-v1 · Pre-v1/);
180 return items[0];
181 },
182 },
183 );
184 assert.equal(result?.block, undefined);
185 assert.equal(approvals, 1);
186 const unavailable = await preflightFileMutation(
187 project,
188 "write",
189 { path: ".system/config.json", content: candidate },
190 approval(false),
191 );
192 assert.equal(unavailable?.block, true);
193 assert.match(unavailable?.reason ?? "", /interactive UI/);
194 for (const [decision, message] of [
195 ["deny", /denied/],
196 ["cancel", /cancelled/],
197 ] as const) {
198 const rejected = await preflightFileMutation(
199 project,
200 "write",
201 { path: ".system/config.json", content: candidate },
202 {
203 hasUI: true,
204 select: async (_title, items) =>
205 decision === "deny" ? items[1] : undefined,
206 },
207 );
208 assert.equal(rejected?.block, true);
209 assert.match(rejected?.reason ?? "", message);
210 }
211 writeFileSync(configPath, candidate);
212 let deactivations = 0;
213 const deactivated = await preflightFileMutation(
214 project,
215 "write",
216 {
217 path: ".system/config.json",
218 content: `${JSON.stringify(config)}\n`,
219 },
220 {
221 hasUI: true,
222 select: async (_title, items) => {
223 deactivations += 1;
224 assert.equal(items[0], "Deactivate current phase");
225 return items[0];
226 },
227 },
228 );
229 assert.equal(deactivated?.block, undefined);
230 assert.equal(deactivations, 1);
231 const unrelated = await preflightFileMutation(
232 project,
233 "write",
234 {
235 path: ".system/config.json",
236 content: `${JSON.stringify({ ...config, title: "Changed", currentPhase: "PX-PHASE-PHASE001" })}\n`,
237 },
238 approval(),
239 );
240 assert.equal(unrelated?.block, true);
241 assert.match(unrelated?.reason ?? "", /only change currentPhase/);
242 });
244 it("reports rejected schema edits as config changes", async () => {
245 const project = root();
246 const config = ".system/config.json";
247 write(project, config, '{"prefix":"PX","schemaVersion":1}\n');
248 const result = await preflightFileMutation(
249 project,
250 "edit",
251 {
252 path: config,
253 edits: [{ oldText: '"schemaVersion":1', newText: '"schemaVersion":0' }],
254 },
255 approval(),
256 );
257 assert.equal(result?.block, true);
258 assert.match(result?.reason ?? "", /rejected the config change/);
259 assert.doesNotMatch(result?.reason ?? "", /phase change/);
260 });
262 it("allows approved repair of invalid phase metadata", async () => {
263 const project = root();
264 const phase = ".system/phases/PX-PHASE-PHASE001-pre-v1/index.md";
265 write(
266 project,
267 phase,
268 "---\nid: PX-PHASE-PHASE001\ntype: phase\ntitle: Pre-v1\nspec: PX-SPEC-SPEC0001\nstatus: approved\n---\n",
269 );
270 let approvals = 0;
271 const result = await preflightFileMutation(
272 project,
273 "write",
274 {
275 path: phase,
276 content:
277 "---\nid: PX-PHASE-PHASE001\ntype: phase\ntitle: Pre-v1\nlabel: pre-v1\n---\n",
278 },
279 {
280 hasUI: true,
281 select: async (_title, items) => {
282 approvals += 1;
283 return items[0];
284 },
285 },
286 );
287 assert.equal(result?.block, undefined);
288 assert.equal(approvals, 1);
289 });
291 it("allows scoped bundle migration without per-bundle approval", async () => {
292 const project = root();
293 const phase = ".system/phases/PX-PHASE-PHASE001-pre-v1/index.md";
294 write(
295 project,
296 phase,
297 "---\nid: PX-PHASE-PHASE001\ntype: phase\ntitle: Pre-v1\nspec: PX-SPEC-SPEC0001\nstatus: approved\n---\n",
298 );
299 const migrated = await preflightFileMutation(
300 project,
301 "write",
302 {
303 path: phase,
304 content:
305 "---\nid: PX-PHASE-PHASE001\ntype: phase\ntitle: Pre-v1\nlabel: pre-v1\n---\n",
306 },
307 approval(false),
308 { bundleMigration: true },
309 );
310 assert.equal(migrated?.block, undefined);
311 const invalid = await preflightFileMutation(
312 project,
313 "write",
314 { path: phase, content: "---\nid: wrong\n---\n" },
315 approval(false),
316 { bundleMigration: true },
317 );
318 assert.equal(invalid?.block, true);
319 assert.match(invalid?.reason ?? "", /candidate validation failed/);
320 });
91322 it("does not govern mutations outside the detected project root", async () => {
92323 const project = root();
93324 const outside = path.join(path.dirname(project), "outside.md");
221452 assert.match(closed?.reason ?? "", /interactive UI/);
222453 });
224 it("validates editable non-spec indexes and blocks approved phase and plan bundles", async () => {
455 it("approves phase amendments and keeps approved plans immutable", async () => {
225456 const project = root();
226457 writeSpec(project);
227458 const phase = ".system/phases/PX-PHASE-PHASE001-delivery/index.md";
234465 id: "PX-PHASE-PHASE001",
235466 type: "phase",
236467 title: "Delivery",
237 spec: "PX-SPEC-SPEC0001",
238 status: "approved",
468 label: "delivery",
239469 }),
240470 );
241471 write(
246476 type: "plan",
247477 title: "Build",
248478 spec: "PX-SPEC-SPEC0001",
249 phase: "PX-PHASE-PHASE001",
250479 status: "approved",
251480 }),
252481 );
260489 specs: ["PX-SPEC-SPEC0001"],
261490 }),
262491 );
263 for (const relative of [phase, plan]) {
492 let phaseApprovals = 0;
493 const phaseResult = await preflightFileMutation(
494 project,
495 "edit",
496 {
497 path: phase,
498 edits: [{ oldText: "Approved.", newText: "Reviewed." }],
499 },
500 {
501 hasUI: true,
502 select: async (_title, items) => {
503 phaseApprovals += 1;
504 return items[0];
505 },
506 },
507 );
508 assert.equal(phaseResult?.block, undefined);
509 assert.equal(phaseApprovals, 1);
510 for (const target of [plan, plan.replace("index.md", "evidence.txt")]) {
264511 const result = await preflightFileMutation(
265512 project,
266 "edit",
267 {
268 path: relative,
269 edits: [{ oldText: "Approved.", newText: "Reviewed." }],
270 },
513 target === plan ? "edit" : "write",
514 target === plan
515 ? {
516 path: target,
517 edits: [{ oldText: "Approved.", newText: "Reviewed." }],
518 }
519 : { path: target, content: "new" },
271520 approval(),
272521 );
273 assert.equal(result?.block, true, relative);
522 assert.equal(result?.block, true, target);
274523 assert.match(result?.reason ?? "", /approved/);
275 const asset = await preflightFileMutation(
276 project,
277 "write",
278 { path: relative.replace("index.md", "evidence.txt"), content: "new" },
279 approval(),
280 );
281 assert.equal(asset?.block, true, relative);
282 assert.match(asset?.reason ?? "", /approved/);
283524 }
284525 const draftPlan = ".system/plans/PX-PLAN-PLAN0002-draft/index.md";
285526 write(

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

Modified

+269 / −13 text lines

1212import { afterEach, describe, it } from "vitest";
1313import registerTheSystem from "../index.ts";
1414import { editorCandidates, parseEditorCommand } from "../open-editor.ts";
15import { composeSystemPrompt, runtimeState } from "../system.ts";
1516import { createSystemCommand } from "../system-command.ts";
17import { systemPromptFor } from "../system-prompts.ts";
1719const roots: string[] = [];
1820const temp = () => {
3133 mkdirSync(path.join(root, ".system", directory), { recursive: true });
3234 for (const file of ["SYSTEM.md", "MISSION.md", "RULES.md"])
3335 write(root, `.system/${file}`, `# ${file}\n`);
34 write(root, ".system/config.json", '{"prefix":"PX","schemaVersion":3}');
36 write(root, ".system/config.json", '{"prefix":"PX","schemaVersion":0}');
37 write(root, ".system/board.json", '{"schemaVersion":0,"items":{}}');
3538 write(
3639 root,
3740 ".system/specs/PX-SPEC-SPEC0001-contract/index.md",
7578 write(
7679 root,
7780 ".system/phases/PX-PHASE-PHASE001-delivery/index.md",
78 "---\nid: PX-PHASE-PHASE001\ntype: phase\ntitle: Delivery\nspec: PX-SPEC-SPEC0001\nstatus: draft\n---\n\n# Delivery\n",
81 "---\nid: PX-PHASE-PHASE001\ntype: phase\ntitle: Delivery\nlabel: delivery\n---\n\n# Delivery\n",
7982 );
8083 write(
8184 root,
8285 ".system/phases/PX-PHASE-PHASE002-alpha/index.md",
83 "---\nid: PX-PHASE-PHASE002\ntype: phase\ntitle: Alpha\nspec: PX-SPEC-SPEC0001\nstatus: draft\ndepends_on: [PX-PHASE-PHASE001]\n---\n\n# Alpha\n",
86 "---\nid: PX-PHASE-PHASE002\ntype: phase\ntitle: Alpha\nlabel: alpha\n---\n\n# Alpha\n",
8487 );
8588 write(
8689 root,
8790 ".system/plans/PX-PLAN-PLAN0001-build/index.md",
88 "---\nid: PX-PLAN-PLAN0001\ntype: plan\ntitle: Build\nspec: PX-SPEC-SPEC0001\nphase: PX-PHASE-PHASE001\nstatus: draft\n---\n\n# Build\n",
91 "---\nid: PX-PLAN-PLAN0001\ntype: plan\ntitle: Build\nspec: PX-SPEC-SPEC0001\nstatus: draft\n---\n\n# Build\n",
8992 );
9093 write(
9194 root,
9295 ".system/plans/PX-PLAN-PLAN0002-alpha/index.md",
93 "---\nid: PX-PLAN-PLAN0002\ntype: plan\ntitle: Alpha\nspec: PX-SPEC-SPEC0001\nphase: PX-PHASE-PHASE001\nstatus: draft\ndepends_on: [PX-PLAN-PLAN0001]\n---\n\n# Alpha\n",
96 "---\nid: PX-PLAN-PLAN0002\ntype: plan\ntitle: Alpha\nspec: PX-SPEC-SPEC0001\nstatus: draft\ndepends_on: [PX-PLAN-PLAN0001]\n---\n\n# Alpha\n",
9497 );
9598};
100103});
102105describe("/system command", () => {
103 it("registers /system, mockup, and the scoped artifact slot tool", () => {
106 it("assigns bundle migration, not machine schema updates, to the agent", () => {
107 const prompt = systemPromptFor("init", "");
108 assert.match(prompt, /config and board schema markers mechanically/);
109 assert.match(prompt, /migrate existing bundles to schema 0/);
110 });
112 it("registers /system and scoped extension tools", () => {
104113 const commands: string[] = [];
105114 const tools: string[] = [];
106115 registerTheSystem({
109118 on() {},
110119 } as never);
111120 assert.deepEqual(commands, ["system"]);
112 assert.deepEqual(tools, ["mockup", "system_slot"]);
121 assert.deepEqual(tools, ["mockup", "system_slot", "system_board_propose"]);
122 });
124 it("reports schema mismatches with schema-0 init instructions", () => {
125 const project = temp();
126 validSystem(project);
127 write(project, ".system/config.json", '{"prefix":"PX","schemaVersion":4}');
128 assert.deepEqual(runtimeState(project), {
129 active: true,
130 notice:
131 "The System schema does not match 0; run /system init to update it.",
132 });
133 assert.match(
134 composeSystemPrompt(project, "BASE"),
135 /Schema version 4 does not match 0; run \/system init/,
136 );
137 });
139 it("shows an accent System status for initialized and incomplete projects", async () => {
140 for (const [project, expected] of [
141 [temp(), undefined],
142 [temp(), "accent: ?"],
143 [temp(), "accent: PX"],
144 [temp(), "accent: PX · delivery"],
145 ] as const) {
146 if (expected === "accent: ?") mkdirSync(path.join(project, ".system"));
147 if (expected?.startsWith("accent: PX")) validSystem(project);
148 if (expected === "accent: PX · delivery")
149 write(
150 project,
151 ".system/config.json",
152 '{"prefix":"PX","schemaVersion":0,"currentPhase":"PX-PHASE-PHASE001"}',
153 );
154 let sessionStart: ((event: unknown, ctx: unknown) => void) | undefined;
155 let resolveStatus: (value: string | undefined) => void = () => {};
156 const status = new Promise<string | undefined>((resolve) => {
157 resolveStatus = resolve;
158 });
159 registerTheSystem({
160 registerCommand() {},
161 registerTool() {},
162 getActiveTools: () => [],
163 setActiveTools() {},
164 on(event: string, handler: (event: unknown, ctx: unknown) => void) {
165 if (event === "session_start") sessionStart = handler;
166 },
167 } as never);
168 sessionStart?.(
169 {},
170 {
171 cwd: project,
172 hasUI: true,
173 isIdle: () => true,
174 abort() {},
175 sessionManager: { getSessionId: () => project },
176 ui: {
177 notify() {},
178 setStatus(_key: string, text: string | undefined) {
179 resolveStatus(text);
180 },
181 theme: {
182 fg: (color: string, text: string) => `${color}:${text}`,
183 },
184 },
185 },
186 );
187 assert.equal(await status, expected);
188 }
189 });
191 it("refreshes the footer phase before later agent turns", async () => {
192 const project = temp();
193 validSystem(project);
194 let sessionStart: ((event: unknown, ctx: unknown) => void) | undefined;
195 let beforeAgentStart:
196 | ((event: { systemPrompt: string }, ctx: unknown) => Promise<unknown>)
197 | undefined;
198 const statuses: (string | undefined)[] = [];
199 const waiters: Array<{
200 expected: string | undefined;
201 resolve: () => void;
202 }> = [];
203 const waitForStatus = (expected: string | undefined) => {
204 if (statuses.includes(expected)) return Promise.resolve();
205 return new Promise<void>((resolve) =>
206 waiters.push({ expected, resolve }),
207 );
208 };
209 registerTheSystem({
210 registerCommand() {},
211 registerTool() {},
212 getActiveTools: () => [],
213 setActiveTools() {},
214 on(event: string, handler: (...args: never[]) => unknown) {
215 if (event === "session_start") sessionStart = handler as never;
216 if (event === "before_agent_start") beforeAgentStart = handler as never;
217 },
218 } as never);
219 const ctx = {
220 cwd: project,
221 hasUI: true,
222 isIdle: () => true,
223 abort() {},
224 sessionManager: {
225 getSessionId: () => project,
226 getBranch: () => [],
227 },
228 ui: {
229 notify() {},
230 setStatus(_key: string, text: string | undefined) {
231 statuses.push(text);
232 for (const waiter of waiters)
233 if (waiter.expected === text) waiter.resolve();
234 },
235 theme: {
236 fg: (color: string, text: string) => `${color}:${text}`,
237 },
238 },
239 };
240 sessionStart?.({}, ctx);
241 await waitForStatus("accent: PX");
242 write(
243 project,
244 ".system/config.json",
245 '{"prefix":"PX","schemaVersion":0,"currentPhase":"PX-PHASE-PHASE001"}',
246 );
247 await beforeAgentStart?.({ systemPrompt: "BASE" }, ctx);
248 await waitForStatus("accent: PX · delivery");
113249 });
115251 it("offers subcommand completions and help", async () => {
122258 command.getArgumentCompletions?.("ed")?.map((item) => item.value),
123259 ["edit"],
124260 );
261 assert.deepEqual(
262 command.getArgumentCompletions?.("bo")?.map((item) => item.value),
263 ["book", "board"],
264 );
125265 assert.equal(command.getArgumentCompletions?.("doctor"), null);
126266 const notices: string[] = [];
127267 await command.handler("", {
132272 assert.match(notices[0] ?? "", /\/system <subcommand>/);
133273 });
275 it("opens the board directly through its runtime", async () => {
276 const project = temp();
277 validSystem(project);
278 const notices: string[] = [];
279 const command = createSystemCommand({ sendUserMessage() {} } as never, {
280 openBoard: async (cwd) => {
281 assert.equal(cwd, project);
282 return "System board running: http://127.0.0.1:1234";
283 },
284 });
285 await command.handler("board", {
286 cwd: project,
287 waitForIdle: async () => {},
288 ui: { notify: (message: string) => notices.push(message) },
289 } as never);
290 assert.match(notices[0] ?? "", /System board running/);
291 });
135293 it("runs init directly after confirmation", async () => {
136294 const project = temp();
137295 const command = createSystemCommand({ sendUserMessage() {} } as never);
149307 JSON.parse(
150308 readFileSync(path.join(project, ".system/config.json"), "utf8"),
151309 ),
152 { prefix: "PX", schemaVersion: 3, title: path.basename(project) },
310 { prefix: "PX", schemaVersion: 0, title: path.basename(project) },
153311 );
154312 assert.match(
155313 readFileSync(path.join(project, ".system/SYSTEM.md"), "utf8"),
157315 );
158316 });
318 it("updates machine schema mechanically, then offers agent bundle migration", async () => {
319 const project = temp();
320 validSystem(project);
321 write(
322 project,
323 ".system/config.json",
324 '{"prefix":"PX","schemaVersion":4,"title":"Project"}',
325 );
326 const sent: string[] = [];
327 const confirmations: string[] = [];
328 let idle = false;
329 let migrations = 0;
330 const command = createSystemCommand(
331 { sendUserMessage: (message: string) => sent.push(message) } as never,
332 { activateBundleMigration: () => migrations++ },
333 );
334 await command.handler("init", {
335 cwd: project,
336 waitForIdle: async () => {
337 idle = true;
338 },
339 ui: {
340 confirm: async (title: string, summary: string) => {
341 confirmations.push(title);
342 if (title === "Initialize The System?")
343 assert.match(
344 summary,
345 /Update: \.system\/config\.json schemaVersion 4 -> 0/,
346 );
347 else assert.match(summary, /Machine schema updated mechanically/);
348 return true;
349 },
350 notify() {},
351 },
352 } as never);
353 assert.deepEqual(confirmations, [
354 "Initialize The System?",
355 "Should System bundles be migrated by agent?",
356 ]);
357 assert.equal(idle, true);
358 assert.equal(migrations, 1);
359 assert.match(sent[0] ?? "", /# \/system init/);
360 assert.match(
361 sent[0] ?? "",
362 /Source: \.system\/config\.json schemaVersion 4 -> 0/,
363 );
364 assert.equal(
365 JSON.parse(
366 readFileSync(path.join(project, ".system/config.json"), "utf8"),
367 ).schemaVersion,
368 0,
369 );
370 });
372 it("updates board schema without offering bundle migration", async () => {
373 const project = temp();
374 validSystem(project);
375 write(project, ".system/board.json", '{"schemaVersion":4,"items":{}}');
376 const sent: string[] = [];
377 const confirmations: string[] = [];
378 const command = createSystemCommand({
379 sendUserMessage: (message: string) => sent.push(message),
380 } as never);
381 await command.handler("init", {
382 cwd: project,
383 waitForIdle: async () => {},
384 ui: {
385 confirm: async (title: string) => {
386 confirmations.push(title);
387 return true;
388 },
389 notify() {},
390 },
391 } as never);
392 assert.deepEqual(confirmations, ["Initialize The System?"]);
393 assert.deepEqual(sent, []);
394 assert.equal(
395 JSON.parse(readFileSync(path.join(project, ".system/board.json"), "utf8"))
396 .schemaVersion,
397 0,
398 );
399 });
160401 it("reuses existing prefix on init rerun", async () => {
161402 const project = temp();
162403 validSystem(project);
182423 validSystem(project);
183424 const sent: string[] = [];
184425 let activations = 0;
426 let assessments = 0;
185427 const command = createSystemCommand(
186428 {
187429 sendUserMessage: (message: string) => sent.push(message),
188430 } as never,
189 () => activations++,
431 {
432 activateArtifactTool: () => activations++,
433 activateAssessmentTool: () => assessments++,
434 },
190435 );
191436 for (const subcommand of [
192437 "research",
193438 "spec",
194439 "spec-verify",
440 "assess",
195441 "phase",
196442 "plan",
197443 "issue",
206452 for (const message of sent)
207453 assert.match(message, /The System document contract/);
208454 assert.equal(activations, 10);
455 assert.equal(assessments, 2);
209456 assert.doesNotMatch(sent.join("\n"), /Extension-generated artifact slot/);
210457 assert.match(
211458 sent.find((item) => item.includes("# /system exec")) ?? "",
212 /spec\+phase\+plan/,
459 /spec\+plan/,
213460 );
461 assert.match(
462 sent.find((item) => item.includes("# /system assess")) ?? "",
463 /system_board_propose/,
464 );
465 const phasePrompt =
466 sent.find((item) => item.includes("# /system phase\n")) ?? "";
467 assert.match(phasePrompt, /project-wide operating phase/);
468 assert.match(phasePrompt, /config currentPhase/);
469 assert.doesNotMatch(phasePrompt, /large specs/);
214470 assert.match(
215471 sent.find(
216472 (item) =>
293549 assert.match(docs, /#121212/);
294550 assert.match(docs, /prefers-color-scheme:dark/);
295551 assert.match(docs, /PX-PHASE-PHASE001/);
296 assert.match(docs, /after PX-PHASE-PHASE001/);
552 assert.doesNotMatch(docs, /after PX-PHASE/);
297553 assert.ok(
298 docs.indexOf('<section id="PX-SPEC-SPEC0001"') <
554 docs.indexOf('<section id="PX-PHASE-PHASE002"') <
299555 docs.indexOf('<section id="PX-PHASE-PHASE001"'),
300556 );
301557 assert.ok(
302558 docs.indexOf('<section id="PX-PHASE-PHASE001"') <
303 docs.indexOf('<section id="PX-PHASE-PHASE002"'),
559 docs.indexOf('<section id="PX-SPEC-SPEC0001"'),
304560 );
305561 assert.ok(
306562 docs.indexOf('<section id="PX-PLAN-PLAN0001"') <

extensions/the-system/board-runtime.ts

Added
new file mode 100644

+157 / −0 text lines

1import { StringEnum } from "@earendil-works/pi-ai";
2import { defineTool, keyHint } from "@earendil-works/pi-coding-agent";
3import { Text } from "@earendil-works/pi-tui";
4import { Type } from "typebox";
5import type { BoardServer } from "./board-server.ts";
6import { type BoardProposal, readBoardState } from "./board-state.ts";
7import { discoverProjectRoot } from "./documents.ts";
8import { loadProjectIndex } from "./project-index.ts";
9
10const STATES = ["todo", "done", "open"] as const;
11const proposalParameters = Type.Object({
12 items: Type.Array(
13 Type.Object({
14 id: Type.String({ description: "Existing spec, plan, or issue ID." }),
15 state: StringEnum(STATES, {
16 description: "Proposed board state for the item type.",
17 }),
18 rationale: Type.String({
19 minLength: 1,
20 maxLength: 1000,
21 description: "Terse evidence supporting this proposed state.",
22 }),
23 }),
24 { minItems: 1, maxItems: 100 },
25 ),
26});
28export function createBoardRuntime() {
29 let assessmentRoot: string | undefined;
30 const proposals = new Map<string, Map<string, BoardProposal>>();
31 const servers = new Set<BoardServer>();
32 const tool = defineTool({
33 name: "system_board_propose",
34 label: "System Board Proposal",
35 description:
36 "Propose evidence-backed System board state changes for human review.",
37 parameters: proposalParameters,
38 renderCall(args, theme) {
39 return new Text(
40 theme.fg(
41 "toolTitle",
42 theme.bold(
43 `system_board_propose ${Array.isArray(args.items) ? args.items.length : 0}`,
44 ),
45 ),
46 0,
47 0,
48 );
49 },
50 renderResult(result, { expanded }, theme) {
51 const items = (result.details as { items?: BoardProposal[] } | undefined)
52 ?.items;
53 if (!items) return new Text("", 0, 0);
54 if (!expanded)
55 return new Text(
56 `${theme.fg("success", `${items.length} proposed`)} · ${theme.fg("dim", keyHint("app.tools.expand", "to expand"))}`,
57 0,
58 0,
59 );
60 return new Text(
61 items
62 .map(
63 (item) =>
64 `${theme.fg("accent", item.state.toUpperCase())} ${item.id}\n${theme.fg("dim", item.rationale)}`,
65 )
66 .join("\n"),
67 0,
68 0,
69 );
70 },
71 async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
72 const root = discoverProjectRoot(ctx.cwd);
73 if (root !== assessmentRoot)
74 throw new Error(
75 "system_board_propose is only available during /system assess",
76 );
77 const index = loadProjectIndex(root);
78 const byId = new Map(
79 index.documents.map((document) => [document.metadata.id, document]),
80 );
81 const proposed = proposals.get(root) ?? new Map<string, BoardProposal>();
82 for (const raw of params.items) {
83 const document = byId.get(raw.id);
84 if (!document) throw new Error(`No System board item: ${raw.id}`);
85 const valid =
86 document.metadata.type === "issue"
87 ? raw.state === "open" || raw.state === "done"
88 : (document.metadata.type === "spec" ||
89 document.metadata.type === "plan") &&
90 (raw.state === "todo" || raw.state === "done");
91 if (!valid)
92 throw new Error(
93 `Invalid ${document.metadata.type} board state ${raw.state}: ${raw.id}`,
94 );
95 proposed.set(raw.id, {
96 id: raw.id,
97 state: raw.state,
98 rationale: raw.rationale.trim(),
99 });
100 }
101 proposals.set(root, proposed);
102 const items = [...proposed.values()].sort((left, right) =>
103 left.id.localeCompare(right.id),
104 );
105 return {
106 content: [
107 {
108 type: "text" as const,
109 text: `${params.items.length} board state proposal(s) recorded for human review. Run /system board to inspect and apply them.`,
110 },
111 ],
112 details: { items },
113 };
114 },
115 });
117 return {
118 tool,
119 beginAssessment(cwd: string) {
120 const root = discoverProjectRoot(cwd);
121 const index = loadProjectIndex(root);
122 readBoardState(root, index.prefix);
123 assessmentRoot = root;
124 proposals.set(root, new Map());
125 },
126 endAssessment() {
127 assessmentRoot = undefined;
128 },
129 async open(cwd: string): Promise<string> {
130 const index = loadProjectIndex(cwd);
131 const state = readBoardState(index.root, index.prefix);
132 const current = [...(proposals.get(index.root)?.values() ?? [])];
133 const [{ renderSystemBoardSite }, { startBoardServer }, { openUrl }] =
134 await Promise.all([
135 import("./system-renderer.ts"),
136 import("./board-server.ts"),
137 import("./open-browser.ts"),
138 ]);
139 const output = renderSystemBoardSite(index, state, current);
140 const server = await startBoardServer(
141 output.directory,
142 index,
143 proposals.get(index.root) ?? new Map(),
144 );
145 servers.add(server);
146 const opened = await openUrl(server.url);
147 return opened.ok
148 ? `System board opened: ${server.url}\nBrowser: ${opened.command}`
149 : `System board running: ${server.url}\nBrowser: ${opened.error}`;
150 },
151 shutdown() {
152 assessmentRoot = undefined;
153 for (const server of servers) server.close();
154 servers.clear();
155 },
156 };
157}

extensions/the-system/board-server.ts

Added
new file mode 100644

+281 / −0 text lines

1import { randomUUID } from "node:crypto";
2import { createReadStream, lstatSync, realpathSync, rmSync } from "node:fs";
3import {
4 createServer,
5 type IncomingMessage,
6 type Server,
7 type ServerResponse,
8} from "node:http";
9import path from "node:path";
10import {
11 type BoardItemState,
12 type BoardProposal,
13 readBoardState,
14 updateBoardState,
15 writeBoardState,
16} from "./board-state.ts";
17import type { ProjectIndex } from "./project-index.ts";
19const BODY_LIMIT = 64 * 1024;
20const COOKIE = "the_system_board";
21const STATES = ["todo", "done", "open"] as const;
23export type BoardServer = Readonly<{ url: string; close(): void }>;
25export async function startBoardServer(
26 directory: string,
27 index: ProjectIndex,
28 proposals: Map<string, BoardProposal>,
29): Promise<BoardServer> {
30 const token = `${randomUUID()}-${randomUUID()}`;
31 const cookieName = `${COOKIE}_${token.slice(0, 8)}`;
32 let server!: Server;
33 let mutation = Promise.resolve();
34 const enqueue = <T>(work: () => T): Promise<T> => {
35 const result = mutation.then(work, work);
36 mutation = result.then(
37 () => undefined,
38 () => undefined,
39 );
40 return result;
41 };
42 server = createServer((request, response) => {
43 void dispatch(request, response, {
44 directory,
45 index,
46 proposals,
47 token,
48 cookieName,
49 enqueue,
50 });
51 });
52 await new Promise<void>((resolve, reject) => {
53 server.once("error", reject);
54 server.listen(0, "127.0.0.1", () => {
55 server.off("error", reject);
56 resolve();
57 });
58 });
59 const address = server.address();
60 if (!address || typeof address === "string")
61 throw new Error("Failed to bind System board server");
62 return {
63 url: `http://127.0.0.1:${address.port}/?k=${token}`,
64 close() {
65 server.close();
66 rmSync(directory, { recursive: true, force: true });
67 },
68 };
69}
71type DispatchState = Readonly<{
72 directory: string;
73 index: ProjectIndex;
74 proposals: Map<string, BoardProposal>;
75 token: string;
76 cookieName: string;
77 enqueue<T>(work: () => T): Promise<T>;
78}>;
80async function dispatch(
81 request: IncomingMessage,
82 response: ServerResponse,
83 state: DispatchState,
84): Promise<void> {
85 try {
86 const url = new URL(request.url ?? "/", "http://127.0.0.1");
87 const queryToken = url.searchParams.get("k");
88 const cookieToken = cookie(request.headers.cookie ?? "", state.cookieName);
89 if (queryToken === state.token) {
90 response.statusCode = 303;
91 response.setHeader("Location", url.pathname);
92 response.setHeader(
93 "Set-Cookie",
94 `${state.cookieName}=${state.token}; HttpOnly; SameSite=Strict; Path=/`,
95 );
96 response.end();
97 return;
98 }
99 if (cookieToken !== state.token) {
100 respondJson(response, 403, { error: "Forbidden" });
101 return;
102 }
103 if (
104 request.method === "POST" &&
105 request.headers.origin !== `http://${request.headers.host}`
106 ) {
107 respondJson(response, 403, { error: "Invalid board origin" });
108 return;
109 }
110 if (request.method === "POST" && url.pathname === "/api/state") {
111 const input = await readJsonBody(request);
112 const result = await state.enqueue(() =>
113 applyState(state.index, input, "manual"),
114 );
115 respondJson(response, 200, result);
116 return;
117 }
118 if (request.method === "POST" && url.pathname === "/api/proposal") {
119 const input = await readJsonBody(request);
120 if (typeof input.id !== "string" || typeof input.state !== "string")
121 throw new Error("Expected assessment proposal with id and state");
122 const proposal = state.proposals.get(input.id);
123 if (!proposal || proposal.state !== input.state)
124 throw new Error(`No matching assessment proposal: ${input.id}`);
125 const result = await state.enqueue(() =>
126 applyState(state.index, input, "assess"),
127 );
128 state.proposals.delete(input.id);
129 respondJson(response, 200, result);
130 return;
131 }
132 if (request.method !== "GET") {
133 respondJson(response, 405, { error: "Method not allowed" });
134 return;
135 }
136 serveFile(response, state.directory, url.pathname);
137 } catch (error) {
138 respondJson(response, 400, {
139 error: error instanceof Error ? error.message : String(error),
140 });
141 }
142}
144function applyState(
145 index: ProjectIndex,
146 input: Record<string, unknown>,
147 source: "manual" | "assess",
148) {
149 if (
150 Object.keys(input).some((key) => key !== "id" && key !== "state") ||
151 typeof input.id !== "string" ||
152 typeof input.state !== "string" ||
153 !STATES.includes(input.state as (typeof STATES)[number])
154 )
155 throw new Error("Expected board update with id and state");
156 const current = readBoardState(index.root, index.prefix);
157 const updated = updateBoardState(
158 current,
159 index.documents,
160 input.id,
161 input.state as BoardItemState,
162 source,
163 );
164 writeBoardState(index.root, updated);
165 return { items: updated.items };
166}
168function readJsonBody(
169 request: IncomingMessage,
170): Promise<Record<string, unknown>> {
171 return new Promise((resolve, reject) => {
172 let source = "";
173 request.setEncoding("utf8");
174 request.on("data", (chunk: string) => {
175 source += chunk;
176 if (Buffer.byteLength(source) > BODY_LIMIT) {
177 request.destroy();
178 reject(new Error("Board request body is too large"));
179 }
180 });
181 request.on("end", () => {
182 try {
183 const parsed = JSON.parse(source);
184 if (
185 typeof parsed !== "object" ||
186 parsed === null ||
187 Array.isArray(parsed)
188 )
189 throw new Error("Board request body must be an object");
190 resolve(parsed as Record<string, unknown>);
191 } catch (error) {
192 reject(error);
193 }
194 });
195 request.on("error", reject);
196 });
197}
199function serveFile(
200 response: ServerResponse,
201 directory: string,
202 pathname: string,
203): void {
204 const relative = decodeURIComponent(
205 pathname === "/" ? "index.html" : pathname.slice(1),
206 );
207 const target = path.resolve(directory, relative);
208 const inside = path.relative(directory, target);
209 if (
210 inside === ".." ||
211 inside.startsWith(`..${path.sep}`) ||
212 path.isAbsolute(inside)
213 ) {
214 respondJson(response, 404, { error: "Not found" });
215 return;
216 }
217 const stats = lstatSync(target, { throwIfNoEntry: false });
218 if (!stats?.isFile() || stats.isSymbolicLink()) {
219 respondJson(response, 404, { error: "Not found" });
220 return;
221 }
222 const realRoot = realpathSync(directory);
223 const realTarget = realpathSync(target);
224 const realInside = path.relative(realRoot, realTarget);
225 if (
226 realInside === ".." ||
227 realInside.startsWith(`..${path.sep}`) ||
228 path.isAbsolute(realInside)
229 ) {
230 respondJson(response, 404, { error: "Not found" });
231 return;
232 }
233 response.statusCode = 200;
234 response.setHeader("Content-Type", contentType(target));
235 response.setHeader("Cache-Control", "no-store");
236 createReadStream(target).pipe(response);
237}
239function contentType(file: string): string {
240 switch (path.extname(file).toLowerCase()) {
241 case ".html":
242 return "text/html; charset=utf-8";
243 case ".js":
244 return "text/javascript; charset=utf-8";
245 case ".css":
246 return "text/css; charset=utf-8";
247 case ".svg":
248 return "image/svg+xml";
249 case ".png":
250 return "image/png";
251 case ".jpg":
252 case ".jpeg":
253 return "image/jpeg";
254 case ".gif":
255 return "image/gif";
256 case ".webp":
257 return "image/webp";
258 default:
259 return "application/octet-stream";
260 }
261}
263function respondJson(
264 response: ServerResponse,
265 status: number,
266 value: unknown,
267): void {
268 if (response.headersSent) return;
269 response.statusCode = status;
270 response.setHeader("Content-Type", "application/json; charset=utf-8");
271 response.setHeader("Cache-Control", "no-store");
272 response.end(JSON.stringify(value));
273}
275function cookie(source: string, name: string): string | undefined {
276 for (const part of source.split(";")) {
277 const [key, ...value] = part.trim().split("=");
278 if (key === name) return value.join("=");
279 }
280 return undefined;
281}

extensions/the-system/board-state.ts

Added
new file mode 100644

+257 / −0 text lines

1import { readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
2import path from "node:path";
3import {
4 type BundleDocumentRecord,
5 type DocumentMetadata,
6 parseDocumentId,
7 resolveGovernedPath,
8 SystemDocumentError,
9} from "./documents.ts";
11export const BOARD_SCHEMA_VERSION = 0;
12export const BOARD_PATH = ".system/board.json";
14export type BoardItemState = "todo" | "done" | "open";
15export type BoardItemSource = "manual" | "assess";
16export type BoardEntry = Readonly<{
17 state: BoardItemState;
18 updatedAt: string;
19 source: BoardItemSource;
20}>;
21export type BoardProposal = Readonly<{
22 id: string;
23 state: BoardItemState;
24 rationale: string;
25}>;
26export type BoardState = Readonly<{
27 schemaVersion: number;
28 items: Readonly<Record<string, BoardEntry>>;
29}>;
31const objectValue = (
32 value: unknown,
33 label: string,
34): Record<string, unknown> => {
35 if (typeof value !== "object" || value === null || Array.isArray(value))
36 throw new SystemDocumentError(
37 "board.shape",
38 `${label} must be a JSON object`,
39 );
40 return value as Record<string, unknown>;
41};
43const exactKeys = (
44 value: Record<string, unknown>,
45 required: readonly string[],
46 label: string,
47) => {
48 const actual = Object.keys(value).sort();
49 if (
50 required.some((key) => !(key in value)) ||
51 actual.some((key) => !required.includes(key))
52 )
53 throw new SystemDocumentError(
54 "board.keys",
55 `${label} expected keys ${[...required].sort().join(", ")}; received ${actual.join(", ")}`,
56 );
57};
59const validState = (type: DocumentMetadata["type"], state: string): boolean => {
60 switch (type) {
61 case "spec":
62 case "plan":
63 return state === "todo" || state === "done";
64 case "issue":
65 return state === "open" || state === "done";
66 default:
67 return false;
68 }
69};
71export function parseBoardState(source: string, prefix: string): BoardState {
72 let parsed: unknown;
73 try {
74 parsed = JSON.parse(source);
75 } catch {
76 throw new SystemDocumentError("board.invalid-json", "Invalid board JSON");
77 }
78 const value = objectValue(parsed, "Board");
79 if (value.schemaVersion !== BOARD_SCHEMA_VERSION)
80 throw new SystemDocumentError(
81 "board.version",
82 `Board schema version ${String(value.schemaVersion)} does not match ${BOARD_SCHEMA_VERSION}; run /system init`,
83 );
84 exactKeys(value, ["items", "schemaVersion"], "Board");
85 const rawItems = objectValue(value.items, "Board items");
86 const items: Record<string, BoardEntry> = {};
87 for (const [id, rawEntry] of Object.entries(rawItems)) {
88 const parsedId = parseDocumentId(id, prefix);
89 if (!["spec", "plan", "issue"].includes(parsedId.type))
90 throw new SystemDocumentError(
91 "board.item-type",
92 `Board item must reference a spec, plan, or issue: ${id}`,
93 );
94 const entry = objectValue(rawEntry, `Board item ${id}`);
95 exactKeys(entry, ["source", "state", "updatedAt"], `Board item ${id}`);
96 if (typeof entry.state !== "string")
97 throw new SystemDocumentError(
98 "board.state",
99 `Board item state must be a string: ${id}`,
100 );
101 if (!validState(parsedId.type, entry.state))
102 throw new SystemDocumentError(
103 "board.state",
104 `Invalid ${parsedId.type} board state ${entry.state}: ${id}`,
105 );
106 if (entry.source !== "manual" && entry.source !== "assess")
107 throw new SystemDocumentError(
108 "board.source",
109 `Invalid board source for ${id}`,
110 );
111 if (
112 typeof entry.updatedAt !== "string" ||
113 Number.isNaN(Date.parse(entry.updatedAt)) ||
114 new Date(entry.updatedAt).toISOString() !== entry.updatedAt
115 )
116 throw new SystemDocumentError(
117 "board.updated-at",
118 `Board updatedAt must be a canonical ISO timestamp: ${id}`,
119 );
120 items[id] = {
121 state: entry.state as BoardItemState,
122 updatedAt: entry.updatedAt,
123 source: entry.source,
124 };
125 }
126 return { schemaVersion: BOARD_SCHEMA_VERSION, items };
127}
129export function boardStateForInitialization(
130 source: string,
131 prefix: string,
132): { state: BoardState; sourceSchemaVersion?: number } {
133 try {
134 return { state: parseBoardState(source, prefix) };
135 } catch (error) {
136 if (
137 !(error instanceof SystemDocumentError) ||
138 error.code !== "board.version"
139 )
140 throw error;
141 const parsed = objectValue(JSON.parse(source), "Board");
142 if (
143 typeof parsed.schemaVersion !== "number" ||
144 !Number.isInteger(parsed.schemaVersion)
145 )
146 throw error;
147 const state = parseBoardState(
148 JSON.stringify({
149 schemaVersion: BOARD_SCHEMA_VERSION,
150 items: parsed.items,
151 }),
152 prefix,
153 );
154 return { state, sourceSchemaVersion: parsed.schemaVersion };
155 }
156}
158export const emptyBoardState = (): BoardState => ({
159 schemaVersion: BOARD_SCHEMA_VERSION,
160 items: {},
161});
163export function boardStateSource(state: BoardState): string {
164 return `${JSON.stringify(
165 {
166 schemaVersion: BOARD_SCHEMA_VERSION,
167 items: Object.fromEntries(
168 Object.entries(state.items).sort(([left], [right]) =>
169 left.localeCompare(right),
170 ),
171 ),
172 },
173 null,
174 "\t",
175 )}\n`;
176}
178export function readBoardState(root: string, prefix: string): BoardState {
179 return parseBoardState(
180 readFileSync(resolveGovernedPath(root, BOARD_PATH), "utf8"),
181 prefix,
182 );
183}
185export function defaultBoardState(metadata: DocumentMetadata): BoardItemState {
186 return metadata.type === "issue" ? "open" : "todo";
187}
189export function boardStateFor(
190 board: BoardState,
191 metadata: DocumentMetadata,
192): BoardItemState {
193 return board.items[metadata.id]?.state ?? defaultBoardState(metadata);
194}
196export function updateBoardState(
197 board: BoardState,
198 documents: readonly BundleDocumentRecord[],
199 id: string,
200 state: BoardItemState,
201 source: BoardItemSource,
202 updatedAt = new Date().toISOString(),
203): BoardState {
204 const document = documents.find((candidate) => candidate.metadata.id === id);
205 if (!document)
206 throw new SystemDocumentError(
207 "board.missing-item",
208 `No System board item: ${id}`,
209 );
210 if (!validState(document.metadata.type, state))
211 throw new SystemDocumentError(
212 "board.state",
213 `Invalid ${document.metadata.type} board state ${state}: ${id}`,
214 );
215 const items: Record<string, BoardEntry> = { ...board.items };
216 items[id] = { state, source, updatedAt };
217 if (document.metadata.type === "spec" && state === "done") {
218 const unfinished = documents.filter(
219 (candidate) =>
220 candidate.metadata.type === "plan" &&
221 candidate.metadata.spec === id &&
222 (items[candidate.metadata.id]?.state ?? "todo") !== "done",
223 );
224 if (unfinished.length)
225 throw new SystemDocumentError(
226 "board.spec-plans",
227 `Spec ${id} cannot be done while plans remain todo: ${unfinished.map((item) => item.metadata.id).join(", ")}`,
228 );
229 }
230 if (document.metadata.type === "plan" && state === "todo") {
231 const specId = document.metadata.spec;
232 const spec = documents.find(
233 (candidate) =>
234 candidate.metadata.type === "spec" && candidate.metadata.id === specId,
235 );
236 if (spec && (items[spec.metadata.id]?.state ?? "todo") === "done")
237 items[spec.metadata.id] = { state: "todo", source, updatedAt };
238 }
239 return { schemaVersion: BOARD_SCHEMA_VERSION, items };
240}
242export function writeBoardState(root: string, state: BoardState): void {
243 const target = resolveGovernedPath(root, BOARD_PATH);
244 const temporary = path.join(
245 path.dirname(target),
246 `.board-${process.pid}-${Date.now()}.json`,
247 );
248 writeFileSync(temporary, boardStateSource(state), {
249 encoding: "utf8",
250 flag: "wx",
251 });
252 try {
253 renameSync(temporary, target);
254 } finally {
255 rmSync(temporary, { force: true });
256 }
257}

extensions/the-system/doctor.ts

Modified

+59 / −34 text lines

11import { lstatSync, readdirSync, readFileSync } from "node:fs";
22import path from "node:path";
3import { BOARD_PATH, boardStateFor, readBoardState } from "./board-state.ts";
34import {
45 type Diagnostic,
56 discoverDocumentBundles,
67 discoverProjectRoot,
78 indexBundleDocuments,
8 inspectSystemConfig,
9 parseSystemConfig,
10 readCurrentPhase,
11 type SystemConfig,
912 type SystemDocumentError,
1013} from "./documents.ts";
2730] as const;
2831const SYSTEM_FILES = [
2932 ".system/config.json",
33 BOARD_PATH,
3034 ".system/SYSTEM.md",
3135 ".system/MISSION.md",
3236 ".system/RULES.md",
115119 diagnostics.push(
116120 diagnostic("filesystem.missing", relative, `Missing file ${relative}`),
117121 );
118 const cssPath = path.join(root, ".system/system.css");
119 const css = lstatSync(cssPath, { throwIfNoEntry: false });
120 if (css?.isFile())
121 diagnostics.push(
122 diagnostic(
123 "filesystem.obsolete",
124 ".system/system.css",
125 "Remove obsolete machine-owned asset .system/system.css",
126 ),
127 );
128 else if (css)
129 diagnostics.push(
130 diagnostic(
131 "filesystem.unsafe",
132 ".system/system.css",
133 ".system/system.css must be a regular file or absent",
134 ),
135 );
137 let prefix: string | undefined;
122 let config: SystemConfig | undefined;
138123 const configPath = path.join(root, ".system/config.json");
139124 if (isFile(configPath)) {
140125 try {
141 const inspected = inspectSystemConfig(readFileSync(configPath, "utf8"));
142 prefix = inspected.config.prefix;
143 if (inspected.config.schemaVersion !== 3)
144 diagnostics.push(
145 diagnostic(
146 "config.schema-outdated",
147 ".system/config.json",
148 `Schema version ${inspected.config.schemaVersion}; installed 3`,
149 ),
150 );
126 config = parseSystemConfig(readFileSync(configPath, "utf8"));
151127 } catch (error) {
152128 const value = error as SystemDocumentError;
153129 diagnostics.push(
158134 const discovery = discoverDocumentBundles(root);
159135 diagnostics.push(...discovery.diagnostics);
160136 let specIds = new Set<string>();
161 if (prefix) {
162 const index = indexBundleDocuments(discovery.sources, prefix);
137 if (config) {
138 const index = indexBundleDocuments(discovery.sources, config.prefix);
163139 diagnostics.push(...index.diagnostics);
140 if (isFile(path.join(root, BOARD_PATH))) {
141 try {
142 const board = readBoardState(root, config.prefix);
143 const documentIds = new Set(
144 index.documents.map((document) => document.metadata.id),
145 );
146 for (const id of Object.keys(board.items))
147 if (!documentIds.has(id))
148 diagnostics.push(
149 diagnostic(
150 "board.dangling-item",
151 BOARD_PATH,
152 `Board references missing ${id}`,
153 ),
154 );
155 for (const spec of index.documents) {
156 if (
157 spec.metadata.type !== "spec" ||
158 boardStateFor(board, spec.metadata) !== "done"
159 )
160 continue;
161 const unfinished = index.documents.filter(
162 (document) =>
163 document.metadata.type === "plan" &&
164 document.metadata.spec === spec.metadata.id &&
165 boardStateFor(board, document.metadata) !== "done",
166 );
167 if (unfinished.length)
168 diagnostics.push(
169 diagnostic(
170 "board.spec-plans",
171 BOARD_PATH,
172 `Spec ${spec.metadata.id} is done while plans remain todo: ${unfinished.map((document) => document.metadata.id).join(", ")}`,
173 ),
174 );
175 }
176 } catch (error) {
177 const value = error as SystemDocumentError;
178 diagnostics.push(diagnostic(value.code, BOARD_PATH, value.message));
179 }
180 }
181 try {
182 readCurrentPhase(root, config);
183 } catch (error) {
184 const value = error as SystemDocumentError;
185 diagnostics.push(
186 diagnostic(value.code, ".system/config.json", value.message),
187 );
188 }
164189 specIds = new Set(
165190 index.documents
166191 .filter((document) => document.metadata.type === "spec")
169194 }
170195 const references = collectTestReferences(root);
171196 for (const reference of references)
172 if (prefix && !specIds.has(reference.spec))
197 if (config && !specIds.has(reference.spec))
173198 diagnostics.push(
174199 diagnostic(
175200 "test.dangling-reference",

extensions/the-system/documents.ts

Modified

+136 / −105 text lines

1010export { discoverProjectRoot, SystemDocumentError } from "./project-root.ts";
12export const SCHEMA_VERSION = 3;
12export const SCHEMA_VERSION = 0;
13export const PHASE_BYTE_LIMIT = 32 * 1024;
1415export function resolveGovernedPath(root: string, candidate: string): string {
1516 const normalizedRoot = path.resolve(root);
3940 prefix: string;
4041 schemaVersion: number;
4142 title?: string;
43 currentPhase?: string;
4244}>;
43export type InspectedSystemConfig = Readonly<{
45export type InitializationSystemConfig = Readonly<{
4446 config: SystemConfig;
45 legacyStyleVersion?: number;
47 sourceSchemaVersion?: number;
4648}>;
4749export type ParsedDocumentId = Readonly<{
4850 id: string;
6567 id: string;
6668 type: "phase";
6769 title: string;
68 spec: string;
69 status: "draft" | "approved";
70 depends_on?: readonly string[];
70 label: string;
7171}>;
7272export type PlanMetadata = Readonly<{
7373 id: string;
7474 type: "plan";
7575 title: string;
7676 spec: string;
77 phase?: string;
7877 status: "draft" | "approved";
7978 depends_on?: readonly string[];
8079}>;
143142 );
144143 return value as Record<string, unknown>;
145144};
146const exactKeys = (
147 value: Record<string, unknown>,
148 required: readonly string[],
149) => {
150 const actual = Object.keys(value).sort();
151 if (
152 required.some((key) => !(key in value)) ||
153 actual.some((key) => !required.includes(key))
154 )
155 throw new SystemDocumentError(
156 "json.keys",
157 `Expected keys ${[...required].sort().join(", ")}; received ${actual.join(", ")}`,
158 );
159};
160const positiveInteger = (value: unknown) =>
161 typeof value === "number" && Number.isInteger(value) && value > 0;
162145const duplicateTopLevelKeys = (source: string): string[] => {
163146 const keys: string[] = [];
164147 const duplicates = new Set<string>();
213196 `Duplicate config keys: ${duplicates.join(", ")}`,
214197 );
215198 const value = objectValue(parsed, "Config");
199 if (value.schemaVersion !== SCHEMA_VERSION)
200 throw new SystemDocumentError(
201 "config.version",
202 `Schema version ${String(value.schemaVersion)} does not match ${SCHEMA_VERSION}; run /system init`,
203 );
216204 const keys = Object.keys(value).sort();
217 const validKeys = ["prefix", "schemaVersion", "title"];
205 const validKeys = ["currentPhase", "prefix", "schemaVersion", "title"];
218206 if (
219207 !("prefix" in value) ||
220208 !("schemaVersion" in value) ||
222210 )
223211 throw new SystemDocumentError(
224212 "json.keys",
225 `Expected keys prefix, schemaVersion[, title]; received ${keys.join(", ")}`,
213 `Expected keys prefix, schemaVersion[, title, currentPhase]; received ${keys.join(", ")}`,
226214 );
227215 if (typeof value.prefix !== "string" || !PREFIX.test(value.prefix))
228216 throw new SystemDocumentError("config.prefix", "Invalid project prefix");
229 if (!positiveInteger(value.schemaVersion))
230 throw new SystemDocumentError(
231 "config.version",
232 "Schema version must be a positive integer",
233 );
234217 if (
235218 "title" in value &&
236219 (typeof value.title !== "string" || value.title.trim() === "")
237220 )
238221 throw new SystemDocumentError("config.title", "Invalid project title");
222 if ("currentPhase" in value) {
223 if (typeof value.currentPhase !== "string")
224 throw new SystemDocumentError(
225 "config.current-phase",
226 "Current phase must be a phase ID",
227 );
228 const current = parseDocumentId(value.currentPhase, value.prefix);
229 if (current.type !== "phase")
230 throw new SystemDocumentError(
231 "config.current-phase",
232 "Current phase must be a phase ID",
233 );
234 }
239235 return {
240236 prefix: value.prefix,
241237 schemaVersion: value.schemaVersion as number,
242238 ...(typeof value.title === "string" ? { title: value.title } : {}),
239 ...(typeof value.currentPhase === "string"
240 ? { currentPhase: value.currentPhase }
241 : {}),
243242 };
246export function inspectSystemConfig(source: string): InspectedSystemConfig {
245export function systemConfigForInitialization(
246 source: string,
247): InitializationSystemConfig {
247248 try {
248249 return { config: parseSystemConfig(source) };
249 } catch (currentError) {
250 let parsed: unknown;
251 try {
252 parsed = JSON.parse(source);
253 } catch {
254 throw currentError;
255 }
256 if (duplicateTopLevelKeys(source).length > 0) throw currentError;
257 let value: Record<string, unknown>;
258 try {
259 value = objectValue(parsed, "Legacy config");
260 exactKeys(value, ["prefix", "schemaVersion", "styleVersion"]);
261 } catch {
262 throw currentError;
263 }
264 if (value.schemaVersion !== 1 || !positiveInteger(value.styleVersion))
265 throw currentError;
250 } catch (error) {
251 if (
252 !(error instanceof SystemDocumentError) ||
253 error.code !== "config.version"
254 )
255 throw error;
256 const parsed = objectValue(JSON.parse(source), "Config");
257 if (
258 duplicateTopLevelKeys(source).length > 0 ||
259 typeof parsed.schemaVersion !== "number" ||
260 !Number.isInteger(parsed.schemaVersion)
261 )
262 throw error;
266263 const config = parseSystemConfig(
267264 JSON.stringify({
268 prefix: value.prefix,
269 schemaVersion: value.schemaVersion,
265 prefix: parsed.prefix,
266 schemaVersion: SCHEMA_VERSION,
267 ...("title" in parsed ? { title: parsed.title } : {}),
268 ...("currentPhase" in parsed
269 ? { currentPhase: parsed.currentPhase }
270 : {}),
270271 }),
271272 );
272 return { config, legacyStyleVersion: value.styleVersion as number };
273 return { config, sourceSchemaVersion: parsed.schemaVersion };
273274 }
393394 );
394395 return value;
395396 };
396 const dependencies = (expected: "phase" | "plan") => {
397 const dependencies = (expected: "plan") => {
397398 const values = optionalUniqueStrings(fields, "depends_on");
398399 if (!values) return undefined;
399400 for (const value of values) {
415416 return research ? { id, type, title, research } : { id, type, title };
416417 }
417418 case "phase": {
418 const depends_on = dependencies("phase");
419 return {
420 id,
421 type,
422 title,
423 spec: reference("spec", "spec"),
424 status: statusField(
425 fields,
426 ["draft", "approved"],
427 "Phase status must be draft or approved",
428 ),
429 ...(depends_on ? { depends_on } : {}),
430 };
419 const label = requiredStringField(fields, "label");
420 if (!/^[A-Za-z0-9._-]{1,12}$/.test(label))
421 throw new SystemDocumentError(
422 "metadata.phase-label",
423 "Phase label must contain 1-12 ASCII letters, digits, dots, underscores, or hyphens",
424 );
425 return { id, type, title, label };
431426 }
432427 case "plan": {
433 const phase = fields.get("phase");
434428 const depends_on = dependencies("plan");
435 if (phase !== undefined && typeof phase !== "string")
436 throw new SystemDocumentError(
437 "metadata.value",
438 "phase must be a string",
439 );
440 if (typeof phase === "string") parseDocumentId(phase, prefix);
441429 return {
442430 id,
443431 type,
444432 title,
445433 spec: reference("spec", "spec"),
446 ...(typeof phase === "string" ? { phase } : {}),
447434 status: statusField(
448435 fields,
449436 ["draft", "approved"],
472459 prefix: string,
473460): AuthoredDocument {
474461 const parsed = parseRichMarkdown(source);
475 return {
476 metadata: projectMetadata(parsed.frontmatter, prefix),
477 frontmatter: parsed.frontmatter,
478 };
462 const metadata = projectMetadata(parsed.frontmatter, prefix);
463 if (
464 metadata.type === "phase" &&
465 Buffer.byteLength(source, "utf8") > PHASE_BYTE_LIMIT
466 )
467 throw new SystemDocumentError(
468 "document.phase-size",
469 `Phase exceeds the ${PHASE_BYTE_LIMIT}-byte limit`,
470 );
471 return { metadata, frontmatter: parsed.frontmatter };
472}
474export type CurrentPhaseDocument = Readonly<{
475 path: string;
476 metadata: PhaseMetadata;
477 markdown: string;
478}>;
480export function readCurrentPhase(
481 root: string,
482 config: SystemConfig,
483): CurrentPhaseDocument | undefined {
484 if (!config.currentPhase) return undefined;
485 const directory = path.join(root, ".system/phases");
486 let matches: string[];
487 try {
488 matches = readdirSync(directory).filter((name) =>
489 name.startsWith(`${config.currentPhase}-`),
490 );
491 } catch {
492 throw new SystemDocumentError(
493 "config.current-phase",
494 `Current phase does not exist: ${config.currentPhase}`,
495 );
496 }
497 if (matches.length !== 1)
498 throw new SystemDocumentError(
499 "config.current-phase",
500 matches.length === 0
501 ? `Current phase does not exist: ${config.currentPhase}`
502 : `Current phase is ambiguous: ${config.currentPhase}`,
503 );
504 const relative = `.system/phases/${matches[0]}/index.md`;
505 const bundle = path.join(directory, matches[0] as string);
506 const target = path.join(bundle, "index.md");
507 const targetStats = lstatSync(target, { throwIfNoEntry: false });
508 if (
509 lstatSync(bundle, { throwIfNoEntry: false })?.isSymbolicLink() ||
510 !targetStats?.isFile() ||
511 targetStats.isSymbolicLink()
512 )
513 throw new SystemDocumentError(
514 "config.current-phase",
515 `Current phase is not a regular document: ${config.currentPhase}`,
516 );
517 if (targetStats.size > PHASE_BYTE_LIMIT)
518 throw new SystemDocumentError(
519 "document.phase-size",
520 `Current phase exceeds the ${PHASE_BYTE_LIMIT}-byte limit`,
521 );
522 const markdown = readFileSync(target, "utf8");
523 const authored = parseAuthoredDocument(markdown, config.prefix);
524 validateDocumentPath(relative, authored.metadata, config.prefix);
525 if (
526 authored.metadata.type !== "phase" ||
527 authored.metadata.id !== config.currentPhase
528 )
529 throw new SystemDocumentError(
530 "config.current-phase",
531 `Current phase document does not match ${config.currentPhase}`,
532 );
533 return { path: relative, metadata: authored.metadata, markdown };
481536const diagnostic = (
610665 case "spec":
611666 return (metadata.research ?? []).map((id) => [id, "research"] as const);
612667 case "phase":
613 return [
614 [metadata.spec, "spec"],
615 ...(metadata.depends_on ?? []).map((id) => [id, "phase"] as const),
616 ];
668 return [];
617669 case "plan":
618670 return [
619671 [metadata.spec, "spec"],
620 ...(metadata.phase ? ([[metadata.phase, "phase"]] as const) : []),
621672 ...(metadata.depends_on ?? []).map((id) => [id, "plan"] as const),
622673 ];
623674 case "issue":
628679};
630681const dependencyReferences = (metadata: DocumentMetadata): readonly string[] =>
631 metadata.type === "phase" || metadata.type === "plan"
632 ? (metadata.depends_on ?? [])
633 : [];
682 metadata.type === "plan" ? (metadata.depends_on ?? []) : [];
634683const diagnosticIdentity = (item: Diagnostic) =>
635684 JSON.stringify([item.path, item.code, item.message]);
726775 ),
727776 );
728777 }
729 if (document.metadata.type === "plan" && document.metadata.phase) {
730 const phase = unique.get(document.metadata.phase);
731 if (
732 phase?.metadata.type === "phase" &&
733 phase.metadata.spec !== document.metadata.spec
734 )
735 diagnostics.push(
736 diagnostic(
737 "graph.forbidden-edge",
738 document.path,
739 `${document.metadata.phase} belongs to ${phase.metadata.spec}, not ${document.metadata.spec}`,
740 ),
741 );
742 }
743 if (
744 document.metadata.type === "phase" ||
745 document.metadata.type === "plan"
746 ) {
778 if (document.metadata.type === "plan") {
747779 for (const dependencyId of dependencyReferences(document.metadata)) {
748780 const dependency = unique.get(dependencyId);
749781 if (
788820 visited.add(id);
789821 };
790822 for (const document of graphEligible)
791 if (document.metadata.type === "phase" || document.metadata.type === "plan")
792 visit(document, []);
823 if (document.metadata.type === "plan") visit(document, []);
793824 return { documents, diagnostics: diagnostics.sort(compareDiagnostics) };

extensions/the-system/index.ts

Modified

+73 / −16 text lines

44 isToolCallEventType,
55} from "@earendil-works/pi-coding-agent";
66import { createArtifactSlotTool } from "./artifact-slot-tool.js";
7import { createBoardRuntime } from "./board-runtime.js";
78import { createMockupRuntime } from "./mockup-tool.js";
89import { systemArgumentCompletions } from "./system-command-meta.js";
1718export default function registerTheSystem(pi: ExtensionAPI): void {
1819 let generation = 0;
19 let notified = false;
20 let warningNotified = false;
2021 const mockup = createMockupRuntime();
2122 const artifactSlot = createArtifactSlotTool();
23 const board = createBoardRuntime();
2224 let artifactSlotRunActive = false;
25 let boardAssessmentRunActive = false;
26 let bundleMigrationRunActive = false;
2327 const activateArtifactSlot = () => {
2428 const active = pi.getActiveTools();
2529 if (!active.includes(artifactSlot.name))
3236 pi.setActiveTools(active.filter((name) => name !== artifactSlot.name));
3337 artifactSlotRunActive = false;
3438 };
39 const activateBoardAssessment = (cwd: string) => {
40 board.beginAssessment(cwd);
41 const active = pi.getActiveTools();
42 if (!active.includes(board.tool.name))
43 pi.setActiveTools([...active, board.tool.name]);
44 boardAssessmentRunActive = true;
45 };
46 const deactivateBoardAssessment = () => {
47 const active = pi.getActiveTools();
48 if (active.includes(board.tool.name))
49 pi.setActiveTools(active.filter((name) => name !== board.tool.name));
50 board.endAssessment();
51 boardAssessmentRunActive = false;
52 };
53 const activateBundleMigration = () => {
54 bundleMigrationRunActive = true;
55 };
36 const notifyOnce = async (ctx: ExtensionContext, ticket: number) => {
37 if (notified || ticket !== generation) return;
57 const syncRuntimeIndicator = async (
58 ctx: ExtensionContext,
59 ticket: number,
60 ) => {
61 if (ticket !== generation) return;
3862 try {
39 const { startupRuntimeNotice } = await import("./startup-notice.js");
40 if (notified || ticket !== generation) return;
41 const message = await startupRuntimeNotice(ctx.cwd);
42 if (!message) return;
43 if (ctx.hasUI) ctx.ui.notify(message, "warning");
44 notified = true;
63 const { startupRuntimeState } = await import("./startup-notice.js");
64 if (ticket !== generation) return;
65 const runtime = await startupRuntimeState(ctx.cwd);
66 if (ticket !== generation) return;
67 if (ctx.hasUI) {
68 ctx.ui.setStatus(
69 "the-system",
70 runtime.active
71 ? ctx.ui.theme.fg(
72 "accent",
73 ` ${runtime.prefix ?? "?"}${runtime.phaseLabel ? ` · ${runtime.phaseLabel}` : ""}`,
74 )
75 : undefined,
76 );
77 if (runtime.notice && !warningNotified) {
78 warningNotified = true;
79 ctx.ui.notify(runtime.notice, "warning");
80 }
81 }
4582 } catch (error) {
4683 if (!isStaleContextError(error)) throw error;
4784 }
5087 pi.on("session_start", (_event, ctx) => {
5188 deactivateArtifactSlot();
89 deactivateBoardAssessment();
90 bundleMigrationRunActive = false;
5291 const ticket = ++generation;
53 notified = false;
92 warningNotified = false;
5493 mockup.remember(ctx);
5594 const timer = setTimeout(() => {
5695 if (ticket === generation)
57 void notifyOnce(ctx, ticket).catch((error) =>
96 void syncRuntimeIndicator(ctx, ticket).catch((error) =>
5897 console.error("The System startup check failed:", error),
5998 );
6099 }, 0);
62101 });
63102 pi.on("session_shutdown", (_event, ctx) => {
64103 generation++;
65 notified = false;
104 warningNotified = false;
66105 artifactSlotRunActive = false;
106 boardAssessmentRunActive = false;
107 bundleMigrationRunActive = false;
108 board.shutdown();
67109 mockup.shutdown(ctx);
68110 });
69111 pi.on("before_agent_start", async (event, ctx) => {
70 void notifyOnce(ctx, generation).catch((error) =>
112 void syncRuntimeIndicator(ctx, generation).catch((error) =>
71113 console.error("The System startup check failed:", error),
72114 );
73115 mockup.agentWorking(ctx);
81123 };
82124 });
83125 pi.on("agent_settled", (_event, ctx) => {
126 void syncRuntimeIndicator(ctx, generation).catch((error) =>
127 console.error("The System status refresh failed:", error),
128 );
84129 mockup.agentSettled(ctx);
85130 if (artifactSlotRunActive) deactivateArtifactSlot();
131 if (boardAssessmentRunActive) deactivateBoardAssessment();
132 bundleMigrationRunActive = false;
86133 });
87134 pi.on("tool_call", async (event, ctx) => {
88135 if (
96143 select: (title: string, items: string[]) => ctx.ui.select(title, items),
97144 };
98145 if (isToolCallEventType("write", event))
99 return preflightFileMutation(ctx.cwd, "write", event.input, ui);
146 return preflightFileMutation(ctx.cwd, "write", event.input, ui, {
147 bundleMigration: bundleMigrationRunActive,
148 });
100149 if (isToolCallEventType("edit", event))
101 return preflightFileMutation(ctx.cwd, "edit", event.input, ui);
150 return preflightFileMutation(ctx.cwd, "edit", event.input, ui, {
151 bundleMigration: bundleMigrationRunActive,
152 });
102153 });
104155 pi.registerTool(mockup.tool);
105156 pi.registerTool(artifactSlot);
157 pi.registerTool(board.tool);
106158 pi.registerCommand("system", {
107159 description: "The System project governance",
108160 getArgumentCompletions: systemArgumentCompletions,
109161 handler: async (args, ctx) => {
110162 const { createSystemCommand } = await import("./system-command.js");
111 await createSystemCommand(pi, activateArtifactSlot).handler(args, ctx);
163 await createSystemCommand(pi, {
164 activateArtifactTool: activateArtifactSlot,
165 activateAssessmentTool: activateBoardAssessment,
166 activateBundleMigration,
167 openBoard: board.open,
168 }).handler(args, ctx);
112169 },
113170 });

extensions/the-system/init.ts

Modified

+83 / −59 text lines

1import {
2 lstatSync,
3 mkdirSync,
4 readFileSync,
5 unlinkSync,
6 writeFileSync,
7} from "node:fs";
1import { lstatSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
82import path from "node:path";
3import {
4 BOARD_PATH,
5 BOARD_SCHEMA_VERSION,
6 boardStateForInitialization,
7 boardStateSource,
8 emptyBoardState,
9} from "./board-state.ts";
910import {
1011 discoverProjectRoot,
11 inspectSystemConfig,
1212 parseSystemConfig,
1313 resolveGovernedPath,
1414 SCHEMA_VERSION,
1515 SystemDocumentError,
16 systemConfigForInitialization,
1617} from "./documents.ts";
18export type MachineState = Readonly<{ schemaVersion: number }>;
1919export type InitializationInspection = Readonly<{
2020 root: string;
2121 prefix?: string;
22 title?: string;
23 currentPhase?: string;
2224 cores: readonly Readonly<{ path: string; state: "missing" | "preserve" }>[];
2325 creates: readonly string[];
24 upgrades: readonly string[];
26 rewrites: readonly string[];
2527}>;
2628export type InitializationResult = Readonly<{
2729 root: string;
2830 prefix: string;
2931 changed: readonly string[];
30 removed: readonly string[];
3132 pending: readonly string[];
3233}>;
4546 ".system/RULES.md",
4647] as const;
4748const CONFIG = ".system/config.json";
48const CSS = ".system/system.css";
4949const CORE_CONTENT: Readonly<Record<(typeof CORES)[number], string>> = {
5050 ".system/SYSTEM.md":
5151 "# SYSTEM\n\nStable project identity, domain truths, architecture invariants, and non-negotiable conventions.\nKeep durable; do not put current tasks here.\n",
5252 ".system/MISSION.md":
53 "# MISSION\n\nCurrent objective and why it matters now.\nUpdate when project direction changes.\n",
53 "# MISSION\n\nEnduring high-level project objective and why it matters.\nUpdate only when the end goal changes; current operating priorities belong in a phase.\n",
5454 ".system/RULES.md":
5555 "# RULES\n\nConcrete operating constraints: commands, safety, style, boundaries, and do/don't rules.\nKeep executable; avoid goals and rationale unless needed.\n",
5656};
57export const DEFAULT_MACHINE_STATE: MachineState = Object.freeze({
58 schemaVersion: SCHEMA_VERSION,
59});
6158const target = (root: string, relative: string) =>
6259 resolveGovernedPath(root, relative);
8279 return actual;
8380};
8481const projectTitle = (root: string) => path.basename(root) || "Project";
85const validatePrefix = (prefix: string, state: MachineState) => {
82const validatePrefix = (prefix: string) => {
8683 parseSystemConfig(
8784 JSON.stringify({
8885 prefix,
89 schemaVersion: state.schemaVersion,
90 title: "Project",
86 schemaVersion: SCHEMA_VERSION,
9187 }),
9288 );
9389 return prefix;
9490};
95const configSource = (root: string, prefix: string, state: MachineState) =>
91const configSource = (prefix: string, title: string, currentPhase?: string) =>
9692 `${JSON.stringify(
97 { prefix, schemaVersion: state.schemaVersion, title: projectTitle(root) },
93 {
94 prefix,
95 schemaVersion: SCHEMA_VERSION,
96 title,
97 ...(currentPhase ? { currentPhase } : {}),
98 },
9899 null,
99100 "\t",
100101 )}\n`;
102103export function inspectInitialization(
103104 cwd: string,
104105 requestedPrefix?: string,
105 state: MachineState = DEFAULT_MACHINE_STATE,
106106): InitializationInspection {
107107 const root = discoverProjectRoot(cwd);
108108 for (const relative of DIRECTORIES) requireKind(root, relative, "directory");
109109 const configKind = requireKind(root, CONFIG, "file");
110 const cssKind = requireKind(root, CSS, "file");
110 const boardKind = requireKind(root, BOARD_PATH, "file");
111111 const requested = requestedPrefix
112 ? validatePrefix(requestedPrefix, state)
112 ? validatePrefix(requestedPrefix)
113113 : undefined;
114114 const inspected =
115115 configKind === "file"
116 ? inspectSystemConfig(readFileSync(target(root, CONFIG), "utf8"))
116 ? systemConfigForInitialization(
117 readFileSync(target(root, CONFIG), "utf8"),
118 )
117119 : undefined;
118120 const config = inspected?.config;
119121 if (config && requested && config.prefix !== requested)
121123 "init.prefix-conflict",
122124 `Existing prefix ${config.prefix} does not match requested ${requested}`,
123125 );
124 if (config && config.schemaVersion > state.schemaVersion)
125 throw new SystemDocumentError(
126 "init.version-newer",
127 `Project schema ${config.schemaVersion} is newer than installed schema ${state.schemaVersion}`,
128 );
126 const prefix = config?.prefix ?? requested;
127 const board =
128 boardKind === "file" && prefix
129 ? boardStateForInitialization(
130 readFileSync(target(root, BOARD_PATH), "utf8"),
131 prefix,
132 )
133 : undefined;
129134 const creates: string[] = [];
130135 for (const relative of DIRECTORIES)
131136 if (kind(target(root, relative)) === "missing") creates.push(relative);
132137 if (configKind === "missing") creates.push(CONFIG);
133 const upgrades: string[] = [];
134 if (config && config.schemaVersion !== state.schemaVersion)
135 upgrades.push(
136 `${CONFIG} schemaVersion ${config.schemaVersion} -> ${state.schemaVersion}${inspected?.legacyStyleVersion ? "; remove styleVersion" : ""}`,
137 );
138 if (config && !config.title)
139 upgrades.push(`${CONFIG} add title "${projectTitle(root)}"`);
140 if (cssKind === "file")
141 upgrades.push(`${CSS} remove obsolete machine-owned asset`);
138 if (boardKind === "missing") creates.push(BOARD_PATH);
139 const rewrites = [
140 ...(inspected?.sourceSchemaVersion === undefined
141 ? []
142 : [
143 `${CONFIG} schemaVersion ${inspected.sourceSchemaVersion} -> ${SCHEMA_VERSION}`,
144 ]),
145 ...(board?.sourceSchemaVersion === undefined
146 ? []
147 : [
148 `${BOARD_PATH} schemaVersion ${board.sourceSchemaVersion} -> ${BOARD_SCHEMA_VERSION}`,
149 ]),
150 ];
142151 return {
143152 root,
144 prefix: config?.prefix ?? requested,
153 prefix,
154 ...(config?.title ? { title: config.title } : {}),
155 ...(config?.currentPhase ? { currentPhase: config.currentPhase } : {}),
145156 cores: CORES.map((relative) => ({
146157 path: relative,
147158 state:
148159 kind(target(root, relative)) === "missing" ? "missing" : "preserve",
149160 })),
150161 creates,
151 upgrades,
162 rewrites,
152163 };
155166export function applyInitialization(
156167 cwd: string,
157168 requestedPrefix?: string,
158 approveUpgrades = false,
159 state: MachineState = DEFAULT_MACHINE_STATE,
169 approveRewrite = false,
160170): InitializationResult {
161 const inspection = inspectInitialization(cwd, requestedPrefix, state);
171 const inspection = inspectInitialization(cwd, requestedPrefix);
162172 if (!inspection.prefix)
163173 throw new SystemDocumentError(
164174 "init.prefix-required",
165175 "An approved project prefix is required before initialization",
166176 );
167177 const changed: string[] = [];
168 const removed: string[] = [];
169178 for (const relative of DIRECTORIES) {
170179 if (kind(target(inspection.root, relative)) !== "missing") continue;
171180 mkdirSync(target(inspection.root, relative));
172181 changed.push(relative);
173182 }
174 const configUpgrade = inspection.upgrades.some((item) =>
175 item.startsWith(`${CONFIG} `),
176 );
177183 if (
178184 kind(target(inspection.root, CONFIG)) === "missing" ||
179 (approveUpgrades && configUpgrade)
185 (approveRewrite &&
186 inspection.rewrites.some((item) => item.startsWith(`${CONFIG} `)))
180187 ) {
181188 writeFileSync(
182189 target(inspection.root, CONFIG),
183 configSource(inspection.root, inspection.prefix, state),
190 configSource(
191 inspection.prefix,
192 inspection.title ?? projectTitle(inspection.root),
193 inspection.currentPhase,
194 ),
184195 kind(target(inspection.root, CONFIG)) === "missing"
185196 ? { encoding: "utf8", flag: "wx" }
186197 : "utf8",
187198 );
188199 changed.push(CONFIG);
189200 }
201 if (
202 kind(target(inspection.root, BOARD_PATH)) === "missing" ||
203 (approveRewrite &&
204 inspection.rewrites.some((item) => item.startsWith(`${BOARD_PATH} `)))
205 ) {
206 const current =
207 kind(target(inspection.root, BOARD_PATH)) === "file"
208 ? boardStateForInitialization(
209 readFileSync(target(inspection.root, BOARD_PATH), "utf8"),
210 inspection.prefix,
211 ).state
212 : emptyBoardState();
213 writeFileSync(
214 target(inspection.root, BOARD_PATH),
215 boardStateSource(current),
216 kind(target(inspection.root, BOARD_PATH)) === "missing"
217 ? { encoding: "utf8", flag: "wx" }
218 : "utf8",
219 );
220 changed.push(BOARD_PATH);
221 }
190222 for (const core of inspection.cores) {
191223 if (core.state !== "missing") continue;
192224 writeFileSync(
199231 );
200232 changed.push(core.path);
201233 }
202 if (
203 approveUpgrades &&
204 inspection.upgrades.includes(`${CSS} remove obsolete machine-owned asset`)
205 ) {
206 unlinkSync(target(inspection.root, CSS));
207 removed.push(CSS);
208 }
209234 return {
210235 root: inspection.root,
211236 prefix: inspection.prefix,
212237 changed,
213 removed,
214 pending: approveUpgrades ? [] : inspection.upgrades,
238 pending: approveRewrite ? [] : inspection.rewrites,
215239 };

extensions/the-system/open-browser.ts

Modified

+7 / −1 text lines

99 file: string,
1010 options: { platform?: NodeJS.Platform; env?: NodeJS.ProcessEnv } = {},
1111): Promise<BrowserOpenResult> {
12 const url = pathToFileURL(file).href;
12 return openUrl(pathToFileURL(file).href, options);
13}
15export async function openUrl(
16 url: string,
17 options: { platform?: NodeJS.Platform; env?: NodeJS.ProcessEnv } = {},
18): Promise<BrowserOpenResult> {
1319 const env = options.env ?? process.env;
1420 if (env.NODE_ENV === "test" || env.VITEST)
1521 return { ok: false, url, error: "Browser opener disabled" };

extensions/the-system/project-index.ts

Added
new file mode 100644

+47 / −0 text lines

1import { readFileSync } from "node:fs";
2import path from "node:path";
3import {
4 type Diagnostic,
5 discoverDocumentBundles,
6 discoverProjectRoot,
7 indexBundleDocuments,
8 parseSystemConfig,
9 readCurrentPhase,
10} from "./documents.ts";
12export function loadProjectIndex(cwd: string) {
13 const root = discoverProjectRoot(cwd);
14 const config = parseSystemConfig(
15 readFileSync(path.join(root, ".system/config.json"), "utf8"),
16 );
17 const discovery = discoverDocumentBundles(root);
18 const indexed = indexBundleDocuments(discovery.sources, config.prefix);
19 const phaseDiagnostics: Diagnostic[] = [];
20 try {
21 readCurrentPhase(root, config);
22 } catch (error) {
23 phaseDiagnostics.push({
24 code: "config.current-phase",
25 path: ".system/config.json",
26 message: error instanceof Error ? error.message : String(error),
27 });
28 }
29 return {
30 root,
31 prefix: config.prefix,
32 ...(config.currentPhase ? { currentPhase: config.currentPhase } : {}),
33 documents: indexed.documents.map((document) => ({
34 ...document,
35 markdown:
36 discovery.sources.find((source) => source.path === document.path)
37 ?.markdown ?? "",
38 })),
39 diagnostics: [
40 ...discovery.diagnostics,
41 ...indexed.diagnostics,
42 ...phaseDiagnostics,
43 ],
44 };
45}
47export type ProjectIndex = ReturnType<typeof loadProjectIndex>;

extensions/the-system/scripts/init.mjs

Modified

+5 / −6 text lines

1212 for (const core of result.cores)
1313 console.log(`CORE ${core.state} ${core.path}`);
1414 for (const item of result.creates) console.log(`CREATE ${item}`);
15 for (const item of result.upgrades) console.log(`UPGRADE ${item}`);
15 for (const item of result.rewrites) console.log(`REWRITE ${item}`);
1616 if (
1717 result.creates.length === 0 &&
18 result.upgrades.length === 0 &&
18 result.rewrites.length === 0 &&
1919 result.cores.every((core) => core.state === "preserve")
2020 )
2121 console.log("OK machine state current");
22 } else if (command === "apply" || command === "upgrade") {
23 const result = applyInitialization(cwd, prefix, command === "upgrade");
22 } else if (command === "apply" || command === "rewrite") {
23 const result = applyInitialization(cwd, prefix, command === "rewrite");
2424 console.log(`ROOT ${result.root}`);
2525 console.log(`PREFIX ${result.prefix}`);
2626 for (const item of result.changed) console.log(`WROTE ${item}`);
27 for (const item of result.removed) console.log(`REMOVED ${item}`);
2827 for (const item of result.pending) console.log(`PENDING ${item}`);
2928 if (result.pending.length === 0) console.log("OK machine state applied");
3029 } else
3130 throw new Error(
32 `Unknown command ${command}; expected inspect, apply, or upgrade`,
31 `Unknown command ${command}; expected inspect, apply, or rewrite`,
3332 );
3433} catch (error) {
3534 const value = error instanceof Error ? error : new Error(String(error));

extensions/the-system/startup-notice.ts

Modified

+13 / −6 text lines

11import { existsSync } from "node:fs";
22import path from "node:path";
33import { discoverProjectRoot } from "./project-root.ts";
4import type { SystemRuntimeState } from "./system.ts";
5export async function startupRuntimeNotice(
6export async function startupRuntimeState(
67 cwd: string,
7): Promise<string | undefined> {
8): Promise<SystemRuntimeState> {
89 let root: string;
910 try {
1011 root = discoverProjectRoot(cwd);
1112 } catch {
12 return undefined;
13 return { active: false };
1314 }
14 if (!existsSync(path.join(root, ".system"))) return undefined;
15 const { runtimeNotice } = await import("./system.ts");
16 return runtimeNotice(cwd);
15 if (!existsSync(path.join(root, ".system"))) return { active: false };
16 const { runtimeState } = await import("./system.ts");
17 return runtimeState(cwd);
18}
20export async function startupRuntimeNotice(
21 cwd: string,
22): Promise<string | undefined> {
23 return (await startupRuntimeState(cwd)).notice;

extensions/the-system/system-command-meta.ts

Modified

+2 / −0 text lines

55 "doctor",
66 "view",
77 "book",
8 "board",
89 "edit",
910 "research",
1011 "spec",
1112 "spec-verify",
13 "assess",
1214 "phase",
1315 "plan",
1416 "issue",

extensions/the-system/system-command.ts

Modified

+72 / −37 text lines

1import { lstatSync, readFileSync } from "node:fs";
1import { lstatSync } from "node:fs";
22import path from "node:path";
33import type {
44 ExtensionAPI,
66 RegisteredCommand,
77} from "@earendil-works/pi-coding-agent";
88import { runDoctor } from "./doctor.ts";
9import {
10 discoverDocumentBundles,
11 discoverProjectRoot,
12 indexBundleDocuments,
13 parseSystemConfig,
14} from "./documents.ts";
159import { applyInitialization, inspectInitialization } from "./init.ts";
1610import { openHtmlFile } from "./open-browser.ts";
1711import { openEditableFile } from "./open-editor.ts";
12import { loadProjectIndex } from "./project-index.ts";
1813import { systemArgumentCompletions } from "./system-command-meta.ts";
1914import { systemPromptFor } from "./system-prompts.ts";
2217 "research",
2318 "spec",
2419 "spec-verify",
20 "assess",
2521 "phase",
2622 "plan",
2723 "issue",
3430 "plan",
3531 "issue",
3632]);
37const NON_LIFECYCLE = new Set(["init", "doctor", "view", "book", "edit"]);
33const NON_LIFECYCLE = new Set([
34 "init",
35 "doctor",
36 "view",
37 "book",
38 "board",
39 "edit",
40]);
3841type CommandOptions = Omit<RegisteredCommand, "name" | "sourceInfo">;
42type SystemCommandHooks = Readonly<{
43 activateArtifactTool?: () => void;
44 activateAssessmentTool?: (cwd: string) => void;
45 activateBundleMigration?: () => void;
46 openBoard?: (cwd: string) => Promise<string>;
47}>;
4049export function createSystemCommand(
4150 pi: ExtensionAPI,
42 activateArtifactTool: () => void = () => {},
51 hooks: SystemCommandHooks = {},
4352): CommandOptions {
4453 return {
4554 description: "The System project governance",
5160 return;
5261 }
5362 if (parsed.subcommand === "init") {
54 await runSystemInit(parsed.rest, ctx);
63 await runSystemInit(
64 pi,
65 hooks.activateBundleMigration,
66 parsed.rest,
67 ctx,
68 );
5569 return;
5670 }
5771 if (parsed.subcommand === "view") {
86100 ctx.ui.notify(await openNotice("System book", output), "info");
87101 return;
88102 }
103 if (parsed.subcommand === "board") {
104 if (parsed.rest.trim()) {
105 ctx.ui.notify("Usage: /system board", "error");
106 return;
107 }
108 if (!hooks.openBoard)
109 throw new Error("System board runtime is unavailable");
110 ctx.ui.notify(await hooks.openBoard(ctx.cwd), "info");
111 return;
112 }
89113 if (parsed.subcommand === "doctor") {
90114 const result = runDoctor(ctx.cwd);
91115 await showCommandResult(
96120 return;
97121 }
98122 await ctx.waitForIdle();
99 if (ARTIFACT_SUBCOMMANDS.has(parsed.subcommand)) activateArtifactTool();
123 if (ARTIFACT_SUBCOMMANDS.has(parsed.subcommand))
124 hooks.activateArtifactTool?.();
125 if (parsed.subcommand === "assess")
126 hooks.activateAssessmentTool?.(ctx.cwd);
100127 pi.sendUserMessage(systemPromptFor(parsed.subcommand, parsed.rest));
101128 },
102129 };
120147 "view <path|id|slug>",
121148 "edit <path|id|slug>",
122149 "book",
150 "board",
123151 "research [instructions]",
124152 "spec [instructions]",
125153 "spec-verify [instructions]",
154 "assess [instructions]",
126155 "phase [instructions]",
127156 "plan [instructions]",
128157 "issue [instructions]",
144173async function runSystemInit(
174 pi: ExtensionAPI,
175 activateBundleMigration: (() => void) | undefined,
145176 args: string,
146177 ctx: ExtensionCommandContext,
147178): Promise<void> {
156187 }
157188 inspection = inspectInitialization(ctx.cwd, requested);
158189 }
190 const configMigration = inspection.rewrites.find((item) =>
191 item.startsWith(".system/config.json "),
192 );
159193 const summary = [
160194 `Root: ${inspection.root}`,
161195 `Prefix: ${inspection.prefix}`,
163197 ...inspection.cores
164198 .filter((item) => item.state === "missing")
165199 .map((item) => `Create: ${item.path}`),
166 ...inspection.upgrades.map((item) => `Upgrade: ${item}`),
200 ...inspection.rewrites.map((item) => `Update: ${item}`),
167201 ].join("\n");
168202 if (!(await ctx.ui.confirm("Initialize The System?", summary))) {
169203 ctx.ui.notify("/system init cancelled", "info");
175209 `Initialized The System at ${result.root}`,
176210 `Prefix: ${result.prefix}`,
177211 ...result.changed.map((item) => `Wrote: ${item}`),
178 ...result.removed.map((item) => `Removed: ${item}`),
179212 ].join("\n"),
180213 "info",
181214 );
215 if (
216 !configMigration ||
217 !(await ctx.ui.confirm(
218 "Should System bundles be migrated by agent?",
219 `Machine schema updated mechanically.\n${configMigration}`,
220 ))
221 )
222 return;
223 await ctx.waitForIdle();
224 activateBundleMigration?.();
225 pi.sendUserMessage(
226 systemPromptFor(
227 "init",
228 [
229 "The human approved agent-led bundle migration.",
230 "Machine config and board schema markers are already current; do not edit them.",
231 `Source: ${configMigration}`,
232 "Inspect existing bundles and migrate obsolete structure and content to the current contracts.",
233 ].join("\n"),
234 ),
235 );
184238function formatDoctor(result: ReturnType<typeof runDoctor>): string {
193247 ].join("\n");
196function projectIndex(cwd: string) {
197 const root = discoverProjectRoot(cwd);
198 const config = parseSystemConfig(
199 readFileSync(path.join(root, ".system/config.json"), "utf8"),
200 );
201 const discovery = discoverDocumentBundles(root);
202 const indexed = indexBundleDocuments(discovery.sources, config.prefix);
203 return {
204 root,
205 documents: indexed.documents.map((document) => ({
206 ...document,
207 markdown:
208 discovery.sources.find((source) => source.path === document.path)
209 ?.markdown ?? "",
210 })),
211 diagnostics: [...discovery.diagnostics, ...indexed.diagnostics],
212 };
213}
215250async function renderSystemView(
216251 cwd: string,
217252 selector: string,
218253): Promise<string> {
219 const index = projectIndex(cwd);
254 const index = loadProjectIndex(cwd);
220255 const document = resolveDocument(index.root, index.documents, selector);
221256 const { renderSystemViewSite } = await import("./system-renderer.ts");
222257 return renderSystemViewSite(index, document).file;
225260async function renderSystemBook(cwd: string): Promise<string> {
226261 const { renderSystemBookSite } = await import("./system-renderer.ts");
227 return renderSystemBookSite(projectIndex(cwd)).file;
262 return renderSystemBookSite(loadProjectIndex(cwd)).file;
230265async function editSystemDocument(
231266 cwd: string,
232267 selector: string,
233268): Promise<string> {
234 const index = projectIndex(cwd);
269 const index = loadProjectIndex(cwd);
235270 const file = editableSystemPath(index.root, index.documents, selector);
236271 const opened = await openEditableFile(file);
237272 if (opened.ok)
242277function editableSystemPath(
243278 root: string,
244 documents: ReturnType<typeof projectIndex>["documents"],
279 documents: ReturnType<typeof loadProjectIndex>["documents"],
245280 selector: string,
246281): string {
247282 const normalized = selector.split(path.sep).join("/");
265300function resolveDocument(
266301 root: string,
267 documents: ReturnType<typeof projectIndex>["documents"],
302 documents: ReturnType<typeof loadProjectIndex>["documents"],
268303 selector: string,
269304) {
270305 const normalized = selector.split(path.sep).join("/");

extensions/the-system/system-prompts.ts

Modified

+43 / −15 text lines

99Use lowercase slugs.
1111Frontmatter refs store IDs only.
12Config schemaVersion is 0.
1314Type directories: research, specs, phases, plans, issues.
1516Required frontmatter:
1617- research: id, type: research, title
1718- spec: id, type: spec, title, optional research: string[]
18- phase: id, type: phase, title, spec, status: draft|approved, optional depends_on: phase ID[]
19- plan: id, type: plan, title, spec, optional phase, status: draft|approved, optional depends_on: plan ID[]
19- phase: id, type: phase, title, label
20- plan: id, type: plan, title, spec, status: draft|approved, optional depends_on: plan ID[]
2021- issue: id, type: issue, title, specs: string[]
2223Research references no System stage type.
2324Specs may reference research.
24Phases reference one spec and may depend on earlier phases for the same spec.
25Plans reference one spec, may reference one phase for the same spec, and may depend on earlier plans for the same spec.
25Phases are project-wide operating epochs related to MISSION, not spec decomposition or work breakdown.
26Phase labels contain 1-12 ASCII letters, digits, dots, underscores, or hyphens.
27Plans reference one spec and may depend on earlier plans for the same spec.
2628Issues may reference zero or more specs and have no status field.
27Approved phases and plans are immutable; create a new artifact instead.
29Approved plans are immutable; create a new artifact instead.
30Existing phases and specs require human approval before mutation.
31The optional config currentPhase ID selects the project-wide operating phase.
32Changing currentPhase requires explicit human confirmation.
2833Keep prose terse, minimal, and essential.
2934After creating or materially editing an artifact, end with:
4146Plans contain no real code snippets; terse pseudocode only for critical paths.
4247`;
49const BOARD_CONTRACT = `# The System board contract
51Board state lives only in .system/board.json at schema version 0.
52Specs and plans use todo|done; issues use open|done.
53A spec may be done without plans, but cannot be done while any linked plan is todo.
54Issues never change spec state.
55Assessment proposes board changes for human review; it never applies them.
56`;
4458const EXEC_CONTRACT = `# The System exec contract
4660Implement only what the referenced System artifacts require.
47Valid exec inputs: spec; spec+phase; spec+plan; spec+phase+plan; optional issue context.
48Phase and plan inputs must be status: approved.
61Valid exec inputs: spec; spec+plan; optional issue context.
62Plan inputs must be status: approved.
63The current phase is already project context; do not request or attach it as an exec input.
4964Use tests for nontrivial behavior.
5065Debug root cause before fixing bugs.
5166Before claiming implementation complete, run fresh verification and read the full result.
5469`;
5671const STAGE_PROMPTS: Readonly<Record<string, string>> = {
57 init: `Initialize or upgrade .system only after explicit human approval.
72 init: `Initialize .system only after explicit human approval.
5873Inspect current project docs and rules first.
5974Ask focused questions for missing project truth.
6075Never overwrite existing core law silently.
61Schema upgrades are init-owned and must be reported before mutation.`,
76The /system init command updates config and board schema markers mechanically.
77When it reports a prior config schema, migrate existing bundles to schema 0 and the current contracts.
78Preserve current meaning where compatible; do not preserve obsolete bundle fields or add runtime migration code.`,
6279 doctor: `Diagnose .system without mutation.
6380Run the deterministic doctor and explain each finding.
64Do not initialize, repair, rename, delete, or upgrade files.`,
81Do not initialize, repair, rename, delete, or rewrite files.`,
6582 research: `Develop terse research artifacts as context requires.
6683Collect technical or domain knowledge vital to the project.
6784Record facts, sources, conclusions, and unresolved questions only.
7491Find logical inconsistencies, holes, risky claims, or false assumptions.
7592Use ephemeral probes only.
7693Produce evidence and proposed spec amendments; do not create a canonical artifact.`,
77 phase: `Create or amend terse phase artifacts for large specs as context requires.
78Break specs into high-level steps, dependencies, risks, and completion criteria.
79Use status: draft until approval.
80Status: approved requires human approval and makes each phase immutable.`,
81 plan: `Create or amend terse implementation plans for specs or phases as context requires.
94 assess: `${BOARD_CONTRACT}
95Assess current implementation progress for the requested specs, plans, and issues.
96Inspect current code and tests deeply enough to justify each proposed state.
97Do not edit bundles or .system/board.json.
98Call system_board_propose with evidence-backed changes only.
99Omit items whose state cannot be assessed responsibly.`,
100 phase: `Inspect MISSION and the current phase first.
101Create, amend, or transition one terse project-wide operating phase as context requires.
102A phase is a sub-mission and decision posture for an epoch, never a work breakdown or delivery milestone.
103Capture its sub-mission, ranked priorities, decision defaults, explicit non-goals, and observable exit criteria.
104Decision defaults cover concerns such as compatibility, migrations, stability, quality, speed, experimentation, and debt only when relevant.
105If it contains implementation steps, move those steps to a plan.
106Use a short label suitable for the Pi footer.
107When transitioning, create or amend the phase first, then update config currentPhase only after explicit human confirmation.
108Do not mutate MISSION.`,
109 plan: `Create or amend terse implementation plans for specs as context requires.
82110Plan at module, interface, package, or class level.
83111Avoid function and line detail except critical paths.
84112Do not include real code snippets.

extensions/the-system/system-renderer.ts

Modified

+200 / −40 text lines

3333import remarkRehype from "remark-rehype";
3434import { unified } from "unified";
3535import { visit } from "unist-util-visit";
36import {
37 type BoardProposal,
38 type BoardState,
39 boardStateFor,
40} from "./board-state.ts";
3641import {
3742 type BundleDocumentRecord,
3843 type Diagnostic,
4651 Readonly<{ markdown: string }>;
4752export type RenderInput = Readonly<{
4853 root: string;
54 currentPhase?: string;
4955 documents: readonly RenderDocumentInput[];
5056 diagnostics: readonly Diagnostic[];
5157}>;
6672 article: string;
6773 text: string;
6874 refs: readonly string[];
75 label?: string;
6976}>;
7178type MarkdownNode = Readonly<{
7784type MarkdownRoot = MarkdownNode & Readonly<{ type: "root" }>;
7885type MarkdownText = MarkdownNode & Readonly<{ type: "text"; value: string }>;
80const GROUPS = ["law", "spec", "phase", "plan", "issue", "research"] as const;
87const GROUPS = ["law", "phase", "spec", "plan", "issue", "research"] as const;
8188const DOCUMENT_ORDER: readonly DocumentType[] = [
82 "spec",
8389 "phase",
90 "spec",
8491 "plan",
8592 "issue",
8693 "research",
125132 path.join(directory, "index.html"),
126133 htmlPage(
127134 title,
128 bookBody(title, rendered, diagnostics, directory),
135 bookBody(title, rendered, diagnostics, directory, input.currentPhase),
129136 "book",
130137 "assets/mermaid.min.js",
131138 "assets/minisearch.js",
135142 return { file: path.join(directory, "index.html"), directory };
145export function renderSystemBoardSite(
146 input: RenderInput,
147 board: BoardState,
148 proposals: readonly BoardProposal[],
149): RenderOutput {
150 const directory = createOutput(input);
151 const rendered = renderAll(input, directory);
152 const diagnostics = [...input.diagnostics, ...referenceDiagnostics(input)];
153 writePages(directory, rendered, diagnostics, "book");
154 const title = `${projectName(input.root)} Board`;
155 const body = boardBody(title, input, rendered, board, proposals).replaceAll(
156 pathToFileURL(`${directory}${path.sep}`).href,
157 "/",
158 );
159 writeFileSync(
160 path.join(directory, "index.html"),
161 htmlPage(
162 title,
163 body,
164 "board",
165 "assets/mermaid.min.js",
166 "assets/minisearch.js",
167 ),
168 "utf8",
169 );
170 return { file: path.join(directory, "index.html"), directory };
171}
138173const projectName = (root: string) => {
139174 try {
140175 return (
160195const renderAll = (
161196 input: RenderInput,
162197 outputRoot: string,
163): readonly RenderedDocument[] => [
164 ...coreDocuments(input.root).map((document) =>
198): readonly RenderedDocument[] => {
199 const cores = coreDocuments(input.root).map((document) =>
165200 renderCore(document, outputRoot),
166 ),
167 ...orderedSystemDocuments(input.documents).map((document) =>
201 );
202 const authored = orderedSystemDocuments(input.documents).map((document) =>
168203 renderDocument(input, document, outputRoot),
169 ),
170];
204 );
205 const current = authored.find(
206 (document) => document.id === input.currentPhase,
207 );
208 return [
209 ...cores.filter(
210 (document) =>
211 document.id === "CORE-SYSTEM" || document.id === "CORE-MISSION",
212 ),
213 ...(current ? [current] : []),
214 ...cores.filter((document) => document.id === "CORE-RULES"),
215 ...authored.filter((document) => document !== current),
216 ];
217};
172219const orderedSystemDocuments = (
173220 documents: readonly RenderDocumentInput[],
176223 const group = documents.filter(
177224 (document) => document.metadata.type === type,
178225 );
179 return type === "phase" || type === "plan"
226 return type === "plan"
180227 ? topoDocuments(group)
181228 : group.sort(compareDocuments);
182229 });
308355 markdown: document.markdown,
309356 outputRoot,
310357 documents: input.documents,
358 current: document.metadata.id === input.currentPhase,
311359 });
312360 return {
313361 id: document.metadata.id,
318366 article,
319367 text: `${frontmatterText(document.frontmatter)} ${textContent(document.markdown)}`,
320368 refs: refsFor(document.metadata),
369 ...(document.metadata.type === "phase"
370 ? { label: document.metadata.label }
371 : {}),
321372 };
322373};
331382 markdown: string;
332383 outputRoot: string;
333384 documents?: readonly RenderDocumentInput[];
385 current?: boolean;
334386}): string => {
335387 const metadata = input.frontmatter
336388 ? metadataHtml(input.frontmatter, input.documents ?? [], input.outputRoot)
348400 ),
349401 input.id,
350402 );
351 return `<article class="system-article" data-id="${esc(input.id)}"><header class="mast"><p class="eyebrow">${esc(input.type)} · <code>${esc(input.id)}</code></p><h1>${esc(input.title)}</h1><p class="source">${esc(input.sourcePath)}</p>${summaryHtml(input.metadata)}</header>${metadata}${body}${backlinks}</article>`;
403 return `<article class="system-article${input.current ? " current-phase" : ""}" data-id="${esc(input.id)}"><header class="mast"><p class="eyebrow">${esc(input.type)} · <code>${esc(input.id)}</code>${input.current ? '<strong class="phase-current">Current phase</strong>' : ""}</p><h1>${esc(input.title)}</h1><p class="source">${esc(input.sourcePath)}</p>${summaryHtml(input.metadata)}</header>${metadata}${body}${backlinks}</article>`;
352404};
354406const summaryHtml = (metadata?: DocumentMetadata): string => {
355407 if (!metadata) return "";
356408 const dependencies = dependencyIds(metadata);
357409 const refs = refsFor(metadata).filter((id) => !dependencies.includes(id));
358 return `<p class="summary">${esc(metadata.type)}${"status" in metadata ? ` · ${esc(metadata.status)}` : ""}${refs.length ? ` · refs ${refs.map(esc).join(", ")}` : ""}${dependencies.length ? ` · after ${dependencies.map(esc).join(", ")}` : ""}</p>`;
410 return `<p class="summary">${esc(metadata.type)}${metadata.type === "phase" ? ` · ${esc(metadata.label)}` : ""}${"status" in metadata ? ` · ${esc(metadata.status)}` : ""}${refs.length ? ` · refs ${refs.map(esc).join(", ")}` : ""}${dependencies.length ? ` · after ${dependencies.map(esc).join(", ")}` : ""}</p>`;
359411};
361413const backlinksHtml = (
426478 case "spec":
427479 return metadata.research ?? [];
428480 case "phase":
429 return [metadata.spec, ...dependencyIds(metadata)];
481 return [];
430482 case "plan":
431 return [
432 metadata.spec,
433 ...(metadata.phase ? [metadata.phase] : []),
434 ...dependencyIds(metadata),
435 ];
483 return [metadata.spec, ...dependencyIds(metadata)];
436484 case "issue":
437485 return metadata.specs;
438486 default:
441489};
443491const dependencyIds = (metadata: DocumentMetadata): readonly string[] =>
444 metadata.type === "phase" || metadata.type === "plan"
445 ? (metadata.depends_on ?? [])
446 : [];
492 metadata.type === "plan" ? (metadata.depends_on ?? []) : [];
448494const stripFrontmatter = (markdown: string) =>
449495 markdown.replace(/^---\n[\s\S]*?\n---\n?/, "");
526572 research: "Research",
527573};
575const boardBody = (
576 title: string,
577 input: RenderInput,
578 rendered: readonly RenderedDocument[],
579 board: BoardState,
580 proposals: readonly BoardProposal[],
581): string => {
582 const authored = new Map(
583 input.documents.map((document) => [document.metadata.id, document]),
584 );
585 const pages = new Map(rendered.map((document) => [document.id, document]));
586 const specs = input.documents
587 .filter((document) => document.metadata.type === "spec")
588 .sort((left, right) => compareBoardItems(left, right, board));
589 const issues = input.documents
590 .filter((document) => document.metadata.type === "issue")
591 .sort((left, right) => compareBoardItems(left, right, board));
592 const plansBySpec = new Map<string, RenderDocumentInput[]>();
593 for (const document of input.documents) {
594 if (document.metadata.type !== "plan") continue;
595 const plans = plansBySpec.get(document.metadata.spec) ?? [];
596 plans.push(document);
597 plansBySpec.set(document.metadata.spec, plans);
598 }
599 for (const plans of plansBySpec.values())
600 plans.sort((left, right) => compareBoardItems(left, right, board));
601 const proposalById = new Map(
602 proposals.map((proposal) => [proposal.id, proposal]),
603 );
604 const todo = specs.filter(
605 (document) => boardStateFor(board, document.metadata) !== "done",
606 ).length;
607 const open = issues.filter(
608 (document) => boardStateFor(board, document.metadata) !== "done",
609 ).length;
610 const specCards = specs
611 .map((spec) => {
612 const plans = plansBySpec.get(spec.metadata.id) ?? [];
613 const donePlans = plans.filter(
614 (plan) => boardStateFor(board, plan.metadata) === "done",
615 ).length;
616 const planSummary = plans.length
617 ? ` · ${donePlans}/${plans.length} ${plans.length === 1 ? "plan" : "plans"} done`
618 : "";
619 return `<article id="${esc(spec.metadata.id)}" class="board-spec${boardStateFor(board, spec.metadata) === "done" ? " is-done" : ""}" data-board-item data-kind="spec" data-id="${esc(spec.metadata.id)}" data-default-state="todo"><div class="board-row">${boardDisclosure(spec, pages.get(spec.metadata.id), planSummary)}${boardStateButton(spec.metadata.id, boardStateFor(board, spec.metadata))}</div>${plans.length ? `<div class="board-plans" data-plan-list>${plans.map((plan) => boardPlan(plan, pages.get(plan.metadata.id), board, proposalById.get(plan.metadata.id))).join("")}</div>` : ""}${boardAssessment(board.items[spec.metadata.id])}${boardProposal(proposalById.get(spec.metadata.id))}</article>`;
620 })
621 .join("");
622 const issueCards = issues
623 .map((issue) => {
624 const refs = issue.metadata.type === "issue" ? issue.metadata.specs : [];
625 const links = refs
626 .map((id) => {
627 const target = authored.get(id);
628 return `<a href="#${esc(id)}">→ ${esc(target?.metadata.title ?? id)}</a>`;
629 })
630 .join("");
631 return `<article class="board-issue${boardStateFor(board, issue.metadata) === "done" ? " is-done" : ""}" data-board-item data-kind="issue" data-id="${esc(issue.metadata.id)}" data-default-state="open"><div class="board-row">${boardDisclosure(issue, pages.get(issue.metadata.id), "")}${boardStateButton(issue.metadata.id, boardStateFor(board, issue.metadata))}</div>${links ? `<div class="board-links">${links}</div>` : ""}${boardAssessment(board.items[issue.metadata.id])}${boardProposal(proposalById.get(issue.metadata.id))}</article>`;
632 })
633 .join("");
634 return `<style>${boardCss()}</style><header class="board-top"><div><a class="board-brand" href="#">${esc(title)}</a><p>Spec toggles never change plan states. Reopening a plan demotes its spec.</p></div><span><b data-spec-count>${todo}</b> todo · <b data-issue-count>${open}</b> ${open === 1 ? "issue" : "issues"} open</span></header><main class="board-grid"><section class="board-region"><h1>Specs <span>${specs.length}</span></h1><div class="board-spec-list" data-spec-list>${specCards || '<p class="board-empty">No specs.</p>'}</div></section><aside class="board-region"><h1>Issues <span>${issues.length}</span></h1><div class="board-issue-list" data-issue-list>${issueCards || '<p class="board-empty">No issues.</p>'}</div></aside></main><output class="board-notice" data-board-notice aria-live="polite"></output><script>${boardScript()}</script>`;
635};
637const compareBoardItems = (
638 left: RenderDocumentInput,
639 right: RenderDocumentInput,
640 board: BoardState,
641) =>
642 Number(boardStateFor(board, left.metadata) === "done") -
643 Number(boardStateFor(board, right.metadata) === "done") ||
644 compareDocuments(left, right);
646const boardDisclosure = (
647 document: RenderDocumentInput,
648 rendered: RenderedDocument | undefined,
649 suffix: string,
650) =>
651 `<details class="board-bundle"><summary><span><span class="board-kind">${esc(document.metadata.id)}${esc(suffix)}</span><strong>${esc(document.metadata.title)}</strong></span></summary><div class="board-details">${rendered?.article ?? ""}</div></details>`;
653const boardStateButton = (id: string, state: string) =>
654 `<button class="board-state" type="button" data-board-state="${esc(state)}" aria-label="Toggle ${esc(id)} state">${esc(state.toUpperCase())}</button>`;
656const boardPlan = (
657 plan: RenderDocumentInput,
658 rendered: RenderedDocument | undefined,
659 board: BoardState,
660 proposal?: BoardProposal,
661) => {
662 const state = boardStateFor(board, plan.metadata);
663 return `<article class="board-plan${state === "done" ? " is-done" : ""}" data-board-item data-kind="plan" data-id="${esc(plan.metadata.id)}" data-default-state="todo"><div class="board-row">${boardDisclosure(plan, rendered, plan.metadata.type === "plan" ? ` · ${plan.metadata.status}` : "")}${boardStateButton(plan.metadata.id, state)}</div>${boardAssessment(board.items[plan.metadata.id])}${boardProposal(proposal)}</article>`;
664};
666const boardAssessment = (entry: BoardState["items"][string] | undefined) =>
667 entry
668 ? `<span class="board-assessment" data-assessment data-source="${esc(entry.source)}" data-updated-at="${esc(entry.updatedAt)}">${esc(entry.source)} · ${esc(entry.updatedAt)}</span>`
669 : '<span class="board-assessment" data-assessment>default</span>';
671const boardProposal = (proposal?: BoardProposal) =>
672 proposal
673 ? `<aside class="board-proposal" data-proposal><span><b>ASSESS → ${esc(proposal.state.toUpperCase())}</b>${esc(proposal.rationale)}</span><button type="button" data-apply-proposal="${esc(proposal.state)}">Apply</button></aside>`
674 : "";
676const boardCss = () => String.raw`
677body[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}}
678`;
680const boardScript = () => String.raw`
681const 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);
682`;
529684const bookBody = (
530685 title: string,
531686 documents: readonly RenderedDocument[],
532687 diagnostics: readonly Diagnostic[],
533688 outputRoot: string,
689 currentPhase?: string,
534690): string => {
535691 const diagnosticNav = diagnostics.length
536692 ? '<a href="#diagnostics">Diagnostics</a>'
537693 : "";
538694 const utilities = `<div class="nav-utils"><a href="#book-overview">Top</a><a href="#reference-graph">Reference graph</a>${diagnosticNav}</div>`;
539 const nav = bookNav(documents, utilities);
695 const nav = bookNav(documents, utilities, currentPhase);
540696 const diagnosticPanel = diagnostics.length
541697 ? `<section>${diagnosticsHtml(diagnostics, documents)}</section>`
542698 : "";
543 const diagnosticStat = diagnostics.length
544 ? `<p class="stats"><span class="bad">${diagnostics.length} diagnostics</span></p>`
545 : "";
546 return `<header class="book-top" id="book-overview"><a class="brand" href="#book-overview">${esc(title)}</a><label class="book-search"><span>Search</span><span class="search-row"><input id="search" type="search" autocomplete="off"><button type="button" id="search-button">Search</button></span><ol id="results" class="search-results" aria-live="polite"></ol></label>${diagnosticStat}</header><div class="book-shell"><nav class="mobile-nav"><details><summary>Book navigation</summary>${nav}</details></nav><aside class="book-nav">${nav}</aside><main class="book-main"><section class="book-head"><h1>${esc(title)}</h1><div class="overview-grid"><section>${graphHtml(documents)}</section>${diagnosticPanel}</div></section>${documents
699 const current = documents.find((document) => document.id === currentPhase);
700 const stats = [
701 ...(current
702 ? [
703 `<span class="active-phase">Current phase <a href="#${esc(current.id)}">${esc(current.label ?? current.title)}</a></span>`,
704 ]
705 : []),
706 ...(diagnostics.length
707 ? [`<span class="bad">${diagnostics.length} diagnostics</span>`]
708 : []),
709 ];
710 const status = stats.length ? `<p class="stats">${stats.join("")}</p>` : "";
711 return `<header class="book-top" id="book-overview"><a class="brand" href="#book-overview">${esc(title)}</a><label class="book-search"><span>Search</span><span class="search-row"><input id="search" type="search" autocomplete="off"><button type="button" id="search-button">Search</button></span><ol id="results" class="search-results" aria-live="polite"></ol></label>${status}</header><div class="book-shell"><nav class="mobile-nav"><details><summary>Book navigation</summary>${nav}</details></nav><aside class="book-nav">${nav}</aside><main class="book-main"><section class="book-head"><h1>${esc(title)}</h1><div class="overview-grid"><section>${graphHtml(documents)}</section>${diagnosticPanel}</div></section>${documents
547712 .map(
548713 (document) =>
549 `<section id="${esc(document.id)}" class="book-section">${bookArticle(document.article, documents, outputRoot)}</section>`,
714 `<section id="${esc(document.id)}" class="book-section${document.id === currentPhase ? " current-phase-section" : ""}">${bookArticle(document.article, documents, outputRoot)}</section>`,
550715 )
551716 .join(
552717 "\n",
569734const bookNav = (
570735 documents: readonly RenderedDocument[],
571736 utilities: string,
737 currentPhase?: string,
572738): string => {
573739 const byType = new Map(
574740 GROUPS.map((group) => [group, [] as RenderedDocument[]]),
578744 return `${utilities}${GROUPS.map((group) => {
579745 const items = byType.get(group) ?? [];
580746 if (!items.length) return "";
581 return `<details ${group === "law" || group === "spec" ? "open" : ""}><summary>${GROUP_LABELS[group]} <span class="count">${items.length}</span></summary>${items
582 .map((item) => navItem(item))
747 return `<details ${group === "law" || group === "phase" || group === "spec" ? "open" : ""}><summary>${GROUP_LABELS[group]} <span class="count">${items.length}</span></summary>${items
748 .map((item) => navItem(item, item.id === currentPhase))
583749 .join("")}</details>`;
584750 }).join("")}`;
585751};
587const navItem = (item: RenderedDocument): string => {
753const navItem = (item: RenderedDocument, current = false): string => {
588754 const label = item.type === "law" ? item.id : `${item.id} ${item.title}`;
589 return `<a href="#${esc(item.id)}">${esc(label)}</a>`;
755 return `<a href="#${esc(item.id)}"${current ? ' class="current-phase-link" aria-current="true"' : ""}>${current ? "● " : ""}${esc(label)}</a>`;
590756};
592758const graphHtml = (documents: readonly RenderedDocument[]) => {
697863});
699865const nodeDependencyIds = (node: RenderedDocument): readonly string[] =>
700 node.type === "phase" || node.type === "plan"
701 ? node.refs.filter((id) => id.includes(`-${node.type.toUpperCase()}-`))
702 : [];
866 node.type === "plan" ? node.refs.filter((id) => id.includes("-PLAN-")) : [];
704868const graphRefsForNode = (node: RenderedDocument): readonly string[] => {
705869 const dependencies = nodeDependencyIds(node);
706870 if (dependencies.length) return dependencies;
707 if (node.type === "plan") {
708 const phase = node.refs.find((id) => id.includes("-PHASE-"));
709 return phase ? [phase] : node.refs;
710 }
711871 return node.refs;
712872};
820980const htmlPage = (
821981 title: string,
822982 body: string,
823 mode: "single" | "book",
983 mode: "single" | "book" | "board",
824984 mermaidPath: string,
825985 miniSearchPath: string,
826986) => `<!doctype html>
8441004:root{color-scheme:light dark;--bg:#ededed;--panel:#dbdbdb;--page:#ededed;--text:#121212;--muted:#3b3b3b;--line:#5d5d5d;--accent:#922792;--link:#184e5b;--warn:#6e6c10;--error:#bd172e;--info:#116477;--code:#dbdbdb;--mark:#6e6c10}
8451005@media(prefers-color-scheme:dark){:root{--bg:#121212;--panel:#242424;--page:#121212;--text:#ededed;--muted:#8b8b8b;--line:#6f6f6f;--accent:#d86dd8;--link:#7ba1aa;--warn:#f0ee69;--error:#ec6376;--info:#3ec5e3;--code:#242424;--mark:#f0ee69}}
8461006body[data-mode=book]{overflow-x:hidden;--book-gutter:26px;--book-nav-width:15rem;--book-top-height:76px}
847*{box-sizing:border-box}html{scroll-behavior:smooth;max-width:100%;overflow-x:hidden}body{font-family:system-ui,sans-serif;line-height:1.55;margin:0;color:var(--text);background:var(--bg);max-width:100%;overflow-x:hidden}body[data-mode=single]{max-width:78rem;margin:2rem auto;padding:0 1rem}a{color:var(--link)}a:focus-visible,button:focus-visible,input:focus-visible,summary:focus-visible{outline:3px solid var(--accent);outline-offset:2px}button,input{font:inherit}button{cursor:pointer}.brand{font:900 12px ui-monospace,monospace;color:var(--accent);letter-spacing:.1em;text-transform:uppercase;text-decoration:none;align-self:end;padding-bottom:10px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.book-top{position:fixed;top:0;left:0;right:0;z-index:5;display:grid;grid-template-columns:var(--book-nav-width) minmax(0,1fr) max-content;gap:16px;align-items:end;height:var(--book-top-height);background:var(--panel);border-bottom:2px solid var(--line);padding:10px var(--book-gutter);overflow:hidden}.book-search{position:relative;display:grid;gap:4px;font:800 11px ui-monospace,monospace;color:var(--muted);text-transform:uppercase}.search-row{display:flex;gap:8px}.search-row input{width:100%;min-width:0;background:var(--bg);color:var(--text);border:2px solid var(--line);padding:8px;text-transform:none}.search-row button{background:var(--accent);color:var(--bg);border:0;padding:8px 12px;font-weight:900}.search-results{position:absolute;left:0;right:0;top:100%;z-index:8;display:grid;gap:6px;margin:6px 0 0;padding:0;list-style:none;background:var(--bg);border:2px solid var(--line);box-shadow:0 10px 24px color-mix(in srgb,var(--text),transparent 86%)}.search-results:empty{display:none}.search-results li{border-left:4px solid var(--accent);padding:7px 9px;background:var(--panel);text-transform:none}.search-results small{color:var(--muted)}mark{background:color-mix(in srgb,var(--mark),transparent 35%);color:var(--text);padding:0 .1em}.stats{display:flex;gap:8px;margin:0 0 10px;justify-content:end;font-variant-numeric:tabular-nums}.stats span{border:1px solid var(--line);background:var(--bg);padding:4px 7px;white-space:nowrap}.stats .bad{border-color:var(--error);color:var(--error)}.stats .ok{border-color:var(--info);color:var(--info)}.book-shell{display:block;width:100%;max-width:100vw;padding:var(--book-top-height) var(--book-gutter) 16px calc(var(--book-gutter) + var(--book-nav-width) + 16px)}.book-shell>*{min-width:0}.book-nav,.book-toc,.book-head,.system-article,.doc-move,.diagnostics,.graph{background:var(--panel);border:1px solid var(--line)}.book-nav{position:fixed;left:var(--book-gutter);top:var(--book-top-height);bottom:0;width:var(--book-nav-width);z-index:4;padding:10px;overflow:auto;border-top:0}.book-nav details{border-bottom:1px solid var(--line);padding:7px 0}.book-nav summary{font:900 11px ui-monospace,monospace;text-transform:uppercase;color:var(--muted);cursor:pointer}.book-nav a{display:block;text-decoration:none;padding:4px 6px 4px 12px;border-left:3px solid transparent;overflow-wrap:anywhere}.nav-utils{border-bottom:1px solid var(--line);margin-bottom:7px;padding-bottom:7px}.nav-utils a{font:800 11px ui-monospace,monospace;text-transform:uppercase;color:var(--muted)}.book-nav a:hover{border-color:var(--accent);background:color-mix(in srgb,var(--accent),transparent 88%)}.count{float:right;color:var(--muted);font-weight:400}.book-main{display:grid;gap:16px;min-width:0;max-width:100%;overflow:hidden}.book-head{padding:18px;overflow:hidden}.book-head h1{margin:0;font:900 clamp(26px,4vw,32px)/1.05 Georgia,serif;overflow-wrap:anywhere}.book-head p{color:var(--muted)}.overview-grid{display:grid;grid-template-columns:1fr;gap:12px}.overview-grid>section,.overview-grid aside{min-width:0}.book-toc{padding:12px;max-height:calc(100vh - 104px);overflow:auto;position:sticky;top:88px;font-size:13px;z-index:1}.book-toc h2{margin-top:0;color:var(--accent);font:800 12px ui-monospace,monospace;text-transform:uppercase}.book-toc a{display:block;color:var(--muted);margin:6px 0;text-decoration:none}.mobile-nav{display:none}.book-section{scroll-margin-top:72px}.system-article{display:block;min-width:0;max-width:100%;padding:28px 40px;background:var(--page);margin-block:0;overflow:hidden}.system-article+.diagnostics{margin-top:1rem}.mast h1{font:800 clamp(24px,4vw,34px)/1.1 Georgia,serif;margin:.2rem 0 1rem;overflow-wrap:anywhere}.eyebrow,.source,.summary{color:var(--muted)}.eyebrow{font:800 11px ui-monospace,monospace;text-transform:uppercase}.source{overflow-wrap:anywhere}.doc-move{display:flex;justify-content:space-between;gap:1rem;margin:1rem 0;padding:1rem}.ledger,.toc{border:1px solid var(--line);background:var(--panel);padding:.7rem;margin:1rem 0}.doc-related{clear:both;margin:1rem 0;padding:.8rem;background:var(--panel);border-left:4px solid var(--accent)}.doc-related summary{color:var(--accent);font:900 12px ui-monospace,monospace;text-transform:uppercase;cursor:pointer}.doc-related a{display:grid;gap:.1rem;padding:.45rem 0;border-top:1px solid var(--line);text-decoration:none}.doc-related span{color:var(--muted);font:800 10px ui-monospace,monospace;text-transform:uppercase}.doc-related code{font-size:11px;color:var(--muted)}.toc ol{margin:.5rem 0}.depth-3{margin-left:1rem}.depth-4,.depth-5,.depth-6{margin-left:2rem}code,pre{font-family:ui-monospace,SFMono-Regular,Menlo,monospace}pre{padding:1rem;overflow:auto;background:var(--code);border:1px solid var(--line)}table{border-collapse:collapse;width:100%;margin:.5rem 0;display:block;overflow:auto}th,td{border:1px solid var(--line);padding:.35rem;text-align:left;vertical-align:top}.ledger ol{margin:0}.diagnostics{border-color:var(--warn);padding:1rem}.diagnostics h2{margin-top:0}.diagnostics strong{color:var(--warn)}.diagnostics.ok{border-color:var(--info)}.diagnostics li{margin:.4rem 0}.graph{padding:1rem;overflow:hidden}.graph-head{display:grid;grid-template-columns:1fr auto;gap:.5rem;align-items:start}.graph h3{margin:0}.graph-head p{margin:.2rem 0 0;color:var(--muted)}.graph-controls{display:flex;gap:.35rem}.graph-controls button{background:var(--bg);color:var(--text);border:1px solid var(--line);padding:.35rem .55rem;font-weight:900}.graph-frame{height:min(62vh,520px);min-height:18rem;border:1px solid var(--line);background:var(--panel);overflow:hidden;touch-action:none;cursor:grab}.graph-frame:active{cursor:grabbing}.graph svg{display:block;width:100%;height:100%;touch-action:none}.graph path{fill:none;stroke:var(--line);stroke-width:1.6;stroke-opacity:.72}.graph a rect{fill:var(--bg);stroke:var(--accent);stroke-width:2}.graph a:hover rect{fill:color-mix(in srgb,var(--accent),transparent 86%)}.graph text{fill:var(--text);font:700 11px ui-monospace,monospace}.graph-node-type{fill:var(--muted);font:800 10px ui-monospace,monospace;text-transform:uppercase}.graph-list{margin-top:.7rem}.graph-list ol{max-height:16rem;overflow:auto}.mockup-preview iframe{width:100%;min-height:22rem;border:1px solid var(--line);background:white}.hljs{background:transparent}.math{overflow:auto}@media(max-width:1200px){.book-toc{display:none}}@media(max-width:980px){.book-top{grid-template-columns:1fr;position:static;height:auto}.search-results{position:static}.stats{justify-content:start;flex-wrap:wrap}.book-shell{display:block;padding:10px}.book-nav,.book-toc{display:none}.mobile-nav{display:grid;gap:8px;margin-bottom:10px}.mobile-nav details{background:var(--panel);border:1px solid var(--line);padding:8px}.mobile-nav a{display:block;margin:.35rem 0;overflow-wrap:anywhere}.mobile-nav .book-nav{display:block;position:static;height:auto;border:0;padding:0}.overview-grid{grid-template-columns:1fr}.system-article{padding:20px 18px}.mast h1{font-size:clamp(24px,8vw,28px)}.doc-move{flex-wrap:wrap}.doc-related{margin:1rem 0}}@media(max-width:620px){body{font-size:15px}.book-top{padding:10px}.brand{white-space:normal}.book-head h1{font-size:clamp(28px,10vw,38px)}.search-row{display:grid}.search-row button{width:100%}.book-shell{padding:8px}.book-head{padding:14px}.system-article{padding:18px 14px;border-left:0;border-right:0}.stats span{font-size:12px}.graph-head{grid-template-columns:1fr}.graph-controls button{flex:1}.graph-frame{height:12rem}.graph-list{display:block}}@media print{.book-top,.book-nav,.book-toc,.book-head,.doc-move,.mobile-nav{display:none}.book-shell{display:block;padding:0}.system-article{border:0;background:white;color:black;max-width:none;padding:0;font:12pt/1.55 Georgia,serif}.mast h1{break-before:page}.diagnostics{break-inside:avoid;border-color:#777;background:#eee}mark{background:#ddd}}
1007*{box-sizing:border-box}html{scroll-behavior:smooth;max-width:100%;overflow-x:hidden}body{font-family:system-ui,sans-serif;line-height:1.55;margin:0;color:var(--text);background:var(--bg);max-width:100%;overflow-x:hidden}body[data-mode=single]{max-width:78rem;margin:2rem auto;padding:0 1rem}a{color:var(--link)}a:focus-visible,button:focus-visible,input:focus-visible,summary:focus-visible{outline:3px solid var(--accent);outline-offset:2px}button,input{font:inherit}button{cursor:pointer}.brand{font:900 12px ui-monospace,monospace;color:var(--accent);letter-spacing:.1em;text-transform:uppercase;text-decoration:none;align-self:end;padding-bottom:10px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.book-top{position:fixed;top:0;left:0;right:0;z-index:5;display:grid;grid-template-columns:var(--book-nav-width) minmax(0,1fr) max-content;gap:16px;align-items:end;height:var(--book-top-height);background:var(--panel);border-bottom:2px solid var(--line);padding:10px var(--book-gutter);overflow:hidden}.book-search{position:relative;display:grid;gap:4px;font:800 11px ui-monospace,monospace;color:var(--muted);text-transform:uppercase}.search-row{display:flex;gap:8px}.search-row input{width:100%;min-width:0;background:var(--bg);color:var(--text);border:2px solid var(--line);padding:8px;text-transform:none}.search-row button{background:var(--accent);color:var(--bg);border:0;padding:8px 12px;font-weight:900}.search-results{position:absolute;left:0;right:0;top:100%;z-index:8;display:grid;gap:6px;margin:6px 0 0;padding:0;list-style:none;background:var(--bg);border:2px solid var(--line);box-shadow:0 10px 24px color-mix(in srgb,var(--text),transparent 86%)}.search-results:empty{display:none}.search-results li{border-left:4px solid var(--accent);padding:7px 9px;background:var(--panel);text-transform:none}.search-results small{color:var(--muted)}mark{background:color-mix(in srgb,var(--mark),transparent 35%);color:var(--text);padding:0 .1em}.stats{display:flex;gap:8px;margin:0 0 10px;justify-content:end;font-variant-numeric:tabular-nums}.stats span{border:1px solid var(--line);background:var(--bg);padding:4px 7px;white-space:nowrap}.stats .bad{border-color:var(--error);color:var(--error)}.stats .ok{border-color:var(--info);color:var(--info)}.stats .active-phase{border-color:var(--accent)}.stats .active-phase a{font-weight:900;text-decoration:none}.book-shell{display:block;width:100%;max-width:100vw;padding:var(--book-top-height) var(--book-gutter) 16px calc(var(--book-gutter) + var(--book-nav-width) + 16px)}.book-shell>*{min-width:0}.book-nav,.book-toc,.book-head,.system-article,.doc-move,.diagnostics,.graph{background:var(--panel);border:1px solid var(--line)}.book-nav{position:fixed;left:var(--book-gutter);top:var(--book-top-height);bottom:0;width:var(--book-nav-width);z-index:4;padding:10px;overflow:auto;border-top:0}.book-nav details{border-bottom:1px solid var(--line);padding:7px 0}.book-nav summary{font:900 11px ui-monospace,monospace;text-transform:uppercase;color:var(--muted);cursor:pointer}.book-nav a{display:block;text-decoration:none;padding:4px 6px 4px 12px;border-left:3px solid transparent;overflow-wrap:anywhere}.nav-utils{border-bottom:1px solid var(--line);margin-bottom:7px;padding-bottom:7px}.nav-utils a{font:800 11px ui-monospace,monospace;text-transform:uppercase;color:var(--muted)}.book-nav a:hover,.book-nav .current-phase-link{border-color:var(--accent);background:color-mix(in srgb,var(--accent),transparent 88%)}.book-nav .current-phase-link{color:var(--accent);font-weight:900}.count{float:right;color:var(--muted);font-weight:400}.book-main{display:grid;gap:16px;min-width:0;max-width:100%;overflow:hidden}.book-head{padding:18px;overflow:hidden}.book-head h1{margin:0;font:900 clamp(26px,4vw,32px)/1.05 Georgia,serif;overflow-wrap:anywhere}.book-head p{color:var(--muted)}.overview-grid{display:grid;grid-template-columns:1fr;gap:12px}.overview-grid>section,.overview-grid aside{min-width:0}.book-toc{padding:12px;max-height:calc(100vh - 104px);overflow:auto;position:sticky;top:88px;font-size:13px;z-index:1}.book-toc h2{margin-top:0;color:var(--accent);font:800 12px ui-monospace,monospace;text-transform:uppercase}.book-toc a{display:block;color:var(--muted);margin:6px 0;text-decoration:none}.mobile-nav{display:none}.book-section{scroll-margin-top:72px}.system-article{display:block;min-width:0;max-width:100%;padding:28px 40px;background:var(--page);margin-block:0;overflow:hidden}.system-article+.diagnostics{margin-top:1rem}.current-phase-section .system-article{border-left:5px solid var(--accent)}.phase-current{margin-left:.6rem;padding:.15rem .35rem;background:var(--accent);color:var(--bg);font-size:10px}.mast h1{font:800 clamp(24px,4vw,34px)/1.1 Georgia,serif;margin:.2rem 0 1rem;overflow-wrap:anywhere}.eyebrow,.source,.summary{color:var(--muted)}.eyebrow{font:800 11px ui-monospace,monospace;text-transform:uppercase}.source{overflow-wrap:anywhere}.doc-move{display:flex;justify-content:space-between;gap:1rem;margin:1rem 0;padding:1rem}.ledger,.toc{border:1px solid var(--line);background:var(--panel);padding:.7rem;margin:1rem 0}.doc-related{clear:both;margin:1rem 0;padding:.8rem;background:var(--panel);border-left:4px solid var(--accent)}.doc-related summary{color:var(--accent);font:900 12px ui-monospace,monospace;text-transform:uppercase;cursor:pointer}.doc-related a{display:grid;gap:.1rem;padding:.45rem 0;border-top:1px solid var(--line);text-decoration:none}.doc-related span{color:var(--muted);font:800 10px ui-monospace,monospace;text-transform:uppercase}.doc-related code{font-size:11px;color:var(--muted)}.toc ol{margin:.5rem 0}.depth-3{margin-left:1rem}.depth-4,.depth-5,.depth-6{margin-left:2rem}code,pre{font-family:ui-monospace,SFMono-Regular,Menlo,monospace}pre{padding:1rem;overflow:auto;background:var(--code);border:1px solid var(--line)}table{border-collapse:collapse;width:100%;margin:.5rem 0;display:block;overflow:auto}th,td{border:1px solid var(--line);padding:.35rem;text-align:left;vertical-align:top}.ledger ol{margin:0}.diagnostics{border-color:var(--warn);padding:1rem}.diagnostics h2{margin-top:0}.diagnostics strong{color:var(--warn)}.diagnostics.ok{border-color:var(--info)}.diagnostics li{margin:.4rem 0}.graph{padding:1rem;overflow:hidden}.graph-head{display:grid;grid-template-columns:1fr auto;gap:.5rem;align-items:start}.graph h3{margin:0}.graph-head p{margin:.2rem 0 0;color:var(--muted)}.graph-controls{display:flex;gap:.35rem}.graph-controls button{background:var(--bg);color:var(--text);border:1px solid var(--line);padding:.35rem .55rem;font-weight:900}.graph-frame{height:min(62vh,520px);min-height:18rem;border:1px solid var(--line);background:var(--panel);overflow:hidden;touch-action:none;cursor:grab}.graph-frame:active{cursor:grabbing}.graph svg{display:block;width:100%;height:100%;touch-action:none}.graph path{fill:none;stroke:var(--line);stroke-width:1.6;stroke-opacity:.72}.graph a rect{fill:var(--bg);stroke:var(--accent);stroke-width:2}.graph a:hover rect{fill:color-mix(in srgb,var(--accent),transparent 86%)}.graph text{fill:var(--text);font:700 11px ui-monospace,monospace}.graph-node-type{fill:var(--muted);font:800 10px ui-monospace,monospace;text-transform:uppercase}.graph-list{margin-top:.7rem}.graph-list ol{max-height:16rem;overflow:auto}.mockup-preview iframe{width:100%;min-height:22rem;border:1px solid var(--line);background:white}.hljs{background:transparent}.math{overflow:auto}@media(max-width:1200px){.book-toc{display:none}}@media(max-width:980px){.book-top{grid-template-columns:1fr;position:static;height:auto}.search-results{position:static}.stats{justify-content:start;flex-wrap:wrap}.book-shell{display:block;padding:10px}.book-nav,.book-toc{display:none}.mobile-nav{display:grid;gap:8px;margin-bottom:10px}.mobile-nav details{background:var(--panel);border:1px solid var(--line);padding:8px}.mobile-nav a{display:block;margin:.35rem 0;overflow-wrap:anywhere}.mobile-nav .book-nav{display:block;position:static;height:auto;border:0;padding:0}.overview-grid{grid-template-columns:1fr}.system-article{padding:20px 18px}.mast h1{font-size:clamp(24px,8vw,28px)}.doc-move{flex-wrap:wrap}.doc-related{margin:1rem 0}}@media(max-width:620px){body{font-size:15px}.book-top{padding:10px}.brand{white-space:normal}.book-head h1{font-size:clamp(28px,10vw,38px)}.search-row{display:grid}.search-row button{width:100%}.book-shell{padding:8px}.book-head{padding:14px}.system-article{padding:18px 14px;border-left:0;border-right:0}.stats span{font-size:12px}.graph-head{grid-template-columns:1fr}.graph-controls button{flex:1}.graph-frame{height:12rem}.graph-list{display:block}}@media print{.book-top,.book-nav,.book-toc,.book-head,.doc-move,.mobile-nav{display:none}.book-shell{display:block;padding:0}.system-article{border:0;background:white;color:black;max-width:none;padding:0;font:12pt/1.55 Georgia,serif}.mast h1{break-before:page}.diagnostics{break-inside:avoid;border-color:#777;background:#eee}mark{background:#ddd}}
8501010const jsonScript = (value: unknown) =>

extensions/the-system/system.ts

Modified

+142 / −26 text lines

1212 indexBundleDocuments,
1313 parseAuthoredDocument,
1414 parseSystemConfig,
15 readCurrentPhase,
1516 resolveGovernedPath,
17 SCHEMA_VERSION,
1618 validateBundleCandidate,
1719} from "./documents.ts";
1820import { inspectInitialization } from "./init.ts";
2022export const CORE_BYTE_LIMIT = 32 * 1024;
2123const CORES = ["SYSTEM.md", "MISSION.md", "RULES.md"] as const;
24const CONFIG_PATH = ".system/config.json";
2225const governanceError = (systemPrompt: string, message: string) =>
23 `${systemPrompt}\n\n# The System governance error\n\n${message}\n\nDo not mutate .system until /system doctor resolves this governance error.`;
26 `${systemPrompt}\n\n# The System governance error\n\n${message}\n\nDo not mutate .system until this governance error is resolved.`;
2427const coreBlock = (root: string, name: (typeof CORES)[number]) => {
2528 const relative = `.system/${name}`;
2629 const target = path.join(root, relative);
5255 );
5356 }
5457 try {
55 const blocks = CORES.map((name) => coreBlock(root, name)).filter(
58 const [system, mission, rules] = CORES.map((name) => coreBlock(root, name));
59 let phase: string | undefined;
60 const configFile = path.join(root, CONFIG_PATH);
61 if (existsSync(configFile)) {
62 const config = parseSystemConfig(readFileSync(configFile, "utf8"));
63 const current = readCurrentPhase(root, config);
64 if (current)
65 phase = `## Current phase: ${current.metadata.title} · ${current.metadata.label}\n\n${current.markdown}`;
66 }
67 const blocks = [system, mission, phase, rules].filter(
5668 (block): block is string => block !== undefined,
5769 );
5870 return blocks.length === 0
6678 }
69export function runtimeNotice(cwd: string): string | undefined {
81export type SystemRuntimeState = Readonly<{
82 active: boolean;
83 prefix?: string;
84 phaseLabel?: string;
85 notice?: string;
86}>;
88const INCOMPLETE_NOTICE =
89 "The System is incomplete or invalid; run /system init before governed work.";
90const SCHEMA_NOTICE = `The System schema does not match ${SCHEMA_VERSION}; run /system init to update it.`;
92export function runtimeState(cwd: string): SystemRuntimeState {
7093 let root: string;
7194 try {
7295 root = discoverProjectRoot(cwd);
7396 } catch {
74 return undefined;
97 return { active: false };
7598 }
76 if (!existsSync(path.join(root, ".system"))) return undefined;
99 if (!existsSync(path.join(root, ".system"))) return { active: false };
77100 try {
78101 const inspection = inspectInitialization(root);
79 if (
102 if (inspection.rewrites.length > 0)
103 return { active: true, notice: SCHEMA_NOTICE };
104 const incomplete =
80105 inspection.creates.length > 0 ||
81 inspection.cores.some(({ state }) => state === "missing")
82 )
83 return "The System is incomplete or invalid; run /system init before governed work.";
84 if (inspection.upgrades.length > 0)
85 return "The System schema refresh is available; run /system init to inspect and approve it.";
86 return undefined;
106 inspection.cores.some(({ state }) => state === "missing");
107 let phaseLabel: string | undefined;
108 if (inspection.prefix) {
109 const config = parseSystemConfig(
110 readFileSync(path.join(root, CONFIG_PATH), "utf8"),
111 );
112 phaseLabel = readCurrentPhase(root, config)?.metadata.label;
113 }
114 const notice = incomplete ? INCOMPLETE_NOTICE : undefined;
115 return {
116 active: true,
117 ...(inspection.prefix ? { prefix: inspection.prefix } : {}),
118 ...(phaseLabel ? { phaseLabel } : {}),
119 ...(notice ? { notice } : {}),
120 };
87121 } catch {
88 return "The System is incomplete or invalid; run /system init before governed work.";
122 return { active: true, notice: INCOMPLETE_NOTICE };
89123 }
126export function runtimeNotice(cwd: string): string | undefined {
127 return runtimeState(cwd).notice;
128}
92130type MutationKind = "write" | "edit";
93131type MutationInput = WriteToolInput | EditToolInput;
94132type GateResult = Readonly<{ block: true; reason: string }> | undefined;
96134 hasUI: boolean;
97135 select(title: string, items: string[]): Promise<string | undefined>;
98136}>;
137type MutationOptions = Readonly<{ bundleMigration?: boolean }>;
99138const CORE_PATHS = new Set([
100139 ".system/SYSTEM.md",
101140 ".system/MISSION.md",
149188 );
150189};
151190const projectPrefix = (root: string) =>
152 parseSystemConfig(
153 readFileSync(path.join(root, ".system/config.json"), "utf8"),
154 ).prefix;
191 parseSystemConfig(readFileSync(path.join(root, CONFIG_PATH), "utf8")).prefix;
193const preflightCurrentPhase = async (
194 root: string,
195 target: string,
196 kind: MutationKind,
197 input: MutationInput,
198 ui: GovernanceUI,
199): Promise<GateResult> => {
200 const stats = lstatSync(target, { throwIfNoEntry: false });
201 if (!stats?.isFile())
202 return blocked(
203 "The System config must be initialized before selecting a phase.",
204 );
205 try {
206 const current = parseSystemConfig(readFileSync(target, "utf8"));
207 const candidate = parseSystemConfig(candidateContent(target, kind, input));
208 if (
209 candidate.prefix !== current.prefix ||
210 candidate.schemaVersion !== current.schemaVersion ||
211 candidate.title !== current.title
212 )
213 return blocked(
214 "The System config mutation may only change currentPhase.",
215 );
216 if (candidate.schemaVersion !== SCHEMA_VERSION)
217 return blocked(
218 `The System schema must be ${SCHEMA_VERSION} before selecting a phase.`,
219 );
220 if (candidate.currentPhase === current.currentPhase)
221 return blocked(
222 candidate.currentPhase
223 ? `The System phase is already ${candidate.currentPhase}.`
224 : "The System already has no current phase.",
225 );
226 const phase = readCurrentPhase(root, candidate);
227 if (!ui.hasUI)
228 return blocked(
229 `The System blocked phase ${candidate.currentPhase ? "activation" : "deactivation"}: interactive UI is unavailable.`,
230 );
231 const approve = phase
232 ? `Activate: ${phase.metadata.label} · ${phase.metadata.title}`
233 : "Deactivate current phase";
234 const deny = `Deny: keep ${current.currentPhase ?? "no current phase"}`;
235 const decision = await ui.select("The System phase transition", [
236 approve,
237 deny,
238 ]);
239 if (decision === approve) return undefined;
240 return blocked(
241 decision === deny
242 ? "The System phase transition was denied."
243 : "The System phase transition was cancelled.",
244 );
245 } catch (error) {
246 return blocked(
247 `The System rejected the config change: ${error instanceof Error ? error.message : String(error)}`,
248 );
249 }
250};
156252type GovernedDocumentPath = Readonly<{
157253 directory: "specs" | "phases" | "plans" | "issues" | "research";
264360 kind: MutationKind,
265361 input: MutationInput,
266362 ui: GovernanceUI,
363 options: MutationOptions = {},
267364): Promise<GateResult> {
268365 let root: string;
269366 try {
291388 }
292389 const relative = posixRelative(root, target);
293390 if (
391 relative !== CONFIG_PATH &&
294392 !CORE_PATHS.has(relative) &&
295393 !/^\.system\/(specs|phases|plans|issues|research)(?:\/|$)/.test(relative)
296394 )
311409 );
312410 }
313411 const targetStats = lstatSync(target, { throwIfNoEntry: false });
412 if (relative === CONFIG_PATH)
413 return preflightCurrentPhase(root, target, kind, input, ui);
314414 if (CORE_PATHS.has(relative)) {
315415 if (targetStats)
316416 return blocked(
327427 return blocked(
328428 `The System requires document bundles at .system/<type-plural>/<ID>-<slug>/<file>: ${relative}.`,
329429 );
430 if (options.bundleMigration) {
431 if (!location.index || !targetStats?.isFile())
432 return blocked(
433 `The System bundle migration may only update an existing index.md: ${relative}.`,
434 );
435 try {
436 const content = candidateContent(target, kind, input);
437 const discovery = discoverDocumentBundles(root);
438 const findings = validateBundleCandidate(
439 discovery.sources,
440 { path: relative, markdown: content },
441 projectPrefix(root),
442 );
443 if (findings.length > 0) return blocked(diagnosticsReason(findings));
444 return undefined;
445 } catch (error) {
446 return blocked(
447 `The System candidate validation failed: ${error instanceof Error ? error.message : String(error)}`,
448 );
449 }
450 }
330451 try {
331452 const current = currentBundleMetadata(root, location);
332 if (
333 (current?.type === "phase" || current?.type === "plan") &&
334 current.status === "approved"
335 )
453 if (current?.type === "plan" && current.status === "approved")
336454 return blocked(
337455 `The System blocked mutation of approved ${current.type} ${current.id}; create a new artifact instead.`,
338456 );
369487 return blocked(`The System expected a regular owned file at ${relative}.`);
370488 if (
371489 location.index &&
372 (resolved.metadata.type === "phase" || resolved.metadata.type === "plan") &&
490 resolved.metadata.type === "plan" &&
373491 resolved.metadata.status === "approved"
374492 ) {
375493 const current = currentBundleMetadata(root, location);
376 if (
377 current?.type === resolved.metadata.type &&
378 current.status !== "approved"
379 ) {
494 if (current?.type === "plan" && current.status !== "approved") {
380495 if (!ui.hasUI)
381496 return blocked(
382497 `The System blocked approval of ${resolved.metadata.type} ${resolved.metadata.id}: interactive UI is unavailable.`,
395510 );
396511 }
397512 }
398 if (resolved.metadata.type !== "spec") return undefined;
513 if (resolved.metadata.type !== "spec" && resolved.metadata.type !== "phase")
514 return undefined;
399515 if (!ui.hasUI)
400516 return blocked(
401517 `The System blocked existing human-owned ${relative}: interactive UI is unavailable.`,