the-system: new board and better concept for phases
14ba3e383210a770961a0ab130b1d6b8a1d0a678
Oliver Krylow <o.krylow@isp-insoft.de> ·
SSH signature · not checked
- Parent 1: 444451a8846c
bugabingas pi extensions
14ba3e383210a770961a0ab130b1d6b8a1d0a678
Oliver Krylow <o.krylow@isp-insoft.de> ·
SSH signature · not checked
+2708 / −511 text lines · all files grouped into 32 bars
+7 / −2 text lines
- Add Continuity to automatically resume the current task after context compaction while yielding to queued messages and active Goal or Tune runs- 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- 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- Shorten the cmprss footer status with the Nerd Font compress icon- Make `/system init` deterministic with confirmation; it creates schema v3 config, plural artifact directories, and core files directly- Make `/system init` deterministic with confirmation; it creates schema 0 config, board state, plural artifact directories, and core files directly- Add an optional project title to The System config; `/system init` writes it from the project directory name and rendered books use it- Remove The System advisory shell mutation guard; governed confirmation remains on `write` and `edit`- Seed `/system init` core files with concise SYSTEM, MISSION, and RULES role guidance while preserving existing core content on rerun- Add terse artifact detail budgets for System docs; plans stay at module/interface/package/class level and avoid real code snippets- Improve The System startup performance in projects without `.system` by skipping governance loading- 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- Make `/system init` update config and board schema markers mechanically, then offer agent-led bundle migration after config schema changes- Fix rejected System config edits so errors no longer mislabel them as phase changes- Add `/system board` for persistent spec, plan, and issue status tracking, plus reviewable `/system assess` proposals and consistency diagnostics- Keep one mockup page open across iterations with live Pi-backed progress, authenticated agent cancellation, and best-effort closing on acceptance- Fix mockups on Windows so the browser opens in the foreground through the native URL handler- 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- Replace the tmux-only terminal skill with a terminal harness for observable TUI testing through tmux or WezTerm- 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+2 / −1 text lines
+4 / −3 text lines
const STATUS_ICON = ""; /\b(error|fail|fatal|warn|exception|denied|timeout|missing|deprecated|critical|traceback|panic)\b/i; return `cmprss: ${percent === 0 ? "0" : `-${percent}`}%`; return `${STATUS_ICON} ${percent === 0 ? "0" : `-${percent}`}%`;+1 / −1 text lines
- Reject hook-skipping `--no-verify` options through normal Git, aliases, shell indirection, nested Bash, `xargs`, child-process PATH lookup, and literal bypasses+38 / −0 text lines
import { spawnSync } from "node:child_process"; it.runIf(process.platform === "win32")( "launches when callers disable MSYS argument conversion", async () => { const bin = mkdtempSync(path.join(tmpdir(), "pi-git-policy-bin-")); testDirs.push(bin); copyFileSync(process.execPath, path.join(bin, "git.exe")); const runtime = await createGitPolicyRuntime({ PATH: bin }, "win32"); const launcher = path .join(runtime.wrapperDir, "git") .replaceAll("\\", "/") .replace( /^([A-Za-z]):\//u, (_match, drive: string) => `/${drive.toLowerCase()}/`, ); const result = spawnSync( "bash", ["-lc", `MSYS2_ARG_CONV_EXCL='*' '${launcher}' --version`], { encoding: "utf8" }, ); expect(result.status, result.stderr).toBe(0); expect(result.stdout.trim()).toBe(process.version); rmSync(path.join(runtime.wrapperDir, "git-wrapper.cjs")); const unavailable = spawnSync( "bash", ["-lc", `'${launcher}' --version`], { encoding: "utf8", }, ); expect(unavailable.status).toBe(127); expect(unavailable.stderr.trim()).toBe( "git: command unavailable; ask the user to restart Pi", ); }, );+9 / −1 text lines
`#!/bin/sh\nexec ${shellQuote(bashPath(process.execPath))} ${shellQuote(bashPath(wrapperScript))} "$@"\n`,new file mode 100644+1 / −0 text lines
Until The System’s first release, keep config and board schema versions `0`; reject mismatches via `/system init`; never add compatibility or migration code.+6 / −3 text lines
- Migrate The System documents to rich Markdown bundles with YAML graph metadata, config-only machine state, doctor validation, and file-level spec ownership.- Rename phase and plan status `done` to `approved`; remove issue status.- Use rich Markdown bundles with YAML graph metadata, config-only machine state, doctor validation, and file-level spec ownership.- Add `/system board` with tracked schema-0 operational state, nested plan cards, independent issues, responsive accordions, and human-reviewed `/system assess` proposals.- Rename plan status `done` to `approved`; remove issue status.- Add turn-scoped `system_slot` allocation with title-derived slugs and repeatable ID reservation.+25 / −5 text lines
- `/system init [PROJECT-PREFIX]` initializes or upgrades `.system` after confirmation.- `/system init [PROJECT-PREFIX]` initializes `.system`, updates machine schema markers, then offers agent-led bundle migration after config schema changes.- `/system research|spec|spec-verify|phase|plan|issue|exec [instructions]` injects stage prompts.The agent calls it for each new bundle after choosing a semantic title, then uses the returned ID and path exactly.Assessment temporarily enables `system_board_propose`.Its proposals remain ephemeral until a human applies selected changes through `/system board`.## BoardTracked operational state lives in `.system/board.json`; bundle content remains stateless about implementation progress.Specs and plans use `todo|done`; issues use `open|done`.Absent entries default to `todo` or `open`.Each explicit entry records `state`, `updatedAt`, and `source: manual|assess` without duplicating bundle content.A spec can be done without plans, but cannot be done while any linked plan is todo.Spec toggles never change plan states.Reopening a plan demotes its spec; issues never change spec state.The board schema version is `0`; `/system init` updates mismatches mechanically before board or assessment can continue.Phases are project-wide operating epochs, not spec decomposition.The optional config `currentPhase` selects one phase for prompt injection and the Pi footer.Existing phase amendments and current-phase transitions require human approval.Approved plans are immutable.Create a new plan instead.The config schema version is `0`; a mismatch fails with instructions to run `/system init`.+139 / −18 text lines
import { createBoardRuntime } from "../board-runtime.ts"; await command.handler("view PX-PHASE-PHASE002", ctx(root, notices)); const book = pathFromNotice(notices[1] ?? ""); await expect(page.locator("#PX-PHASE-PHASE001")).toBeVisible(); expect(orderedSections.indexOf("PX-SPEC-SPEC0001")).toBeLessThan( orderedSections.indexOf("PX-PHASE-PHASE001"), ); expect(orderedSections.indexOf("PX-PHASE-PHASE001")).toBeLessThan( expect(orderedSections.indexOf("CORE-MISSION")).toBeLessThan( orderedSections.indexOf("CORE-RULES"), ); expect(orderedSections.indexOf("CORE-RULES")).toBeLessThan( orderedSections.indexOf("PX-PHASE-PHASE001"), ); expect(orderedSections.indexOf("PX-PHASE-PHASE001")).toBeLessThan( orderedSections.indexOf("PX-SPEC-SPEC0001"), ); expect(orderedSections.indexOf("PX-SPEC-SPEC0001")).toBeLessThan( await expect(graph.locator("a")).toHaveCount(7);test("/system board persists independent spec, plan, and issue assessments", async ({ page,}) => { const root = systemFixture(); const runtime = createBoardRuntime(); try { runtime.beginAssessment(root); await runtime.tool.execute( "assessment", { items: [ { id: "PX-ISSUE-ISSUE001", state: "done", rationale: "The reproduction no longer fails.", }, ], }, new AbortController().signal, undefined, { cwd: root } as never, ); runtime.endAssessment(); const notice = await runtime.open(root); const url = notice.match(/http:\/\/127\.0\.0\.1:\d+\/\?k=[^\s]+/)?.[0]; expect(url).toBeTruthy(); await page.goto(url ?? ""); const spec = page.locator('[data-board-item][data-id="PX-SPEC-SPEC0001"]'); const planA = page.locator('[data-board-item][data-id="PX-PLAN-PLAN0001"]'); const planB = page.locator('[data-board-item][data-id="PX-PLAN-PLAN0002"]'); const issue = page.locator( '[data-board-item][data-id="PX-ISSUE-ISSUE001"]', ); await expect(spec).toBeVisible(); await expect(planA).toBeVisible(); await expect(planB).toBeVisible(); await expect(issue.locator("[data-proposal]")).toContainText( "The reproduction no longer fails.", ); await issue.locator("[data-apply-proposal]").click(); await expect(issue).toHaveClass(/is-done/); await expect(issue.locator("[data-assessment]")).toContainText("assess"); await spec.locator(":scope > .board-row > .board-bundle > summary").click(); const specDetails = spec.locator( ":scope > .board-row > .board-bundle > .board-details", ); await expect(specDetails).toContainText("body-only-term"); await expect(specDetails.locator(".ledger")).toContainText("Metadata"); await expect( spec.locator(":scope > .board-row > .board-state"), ).toBeDisabled(); await planA.locator(".board-state").click(); await expect(planA).toHaveClass(/is-done/); await planB.locator(".board-state").click(); await expect(planB).toHaveClass(/is-done/); await expect( spec.locator(":scope > .board-row > .board-state"), ).toBeEnabled(); await spec.locator(":scope > .board-row > .board-state").click(); await expect(spec).toHaveClass(/is-done/); await spec.locator(":scope > .board-row > .board-state").click(); await expect(spec).not.toHaveClass(/is-done/); await expect(planA).toHaveClass(/is-done/); await expect(planB).toHaveClass(/is-done/); await spec.locator(":scope > .board-row > .board-state").click(); await planA.locator(".board-state").click(); await expect(spec).not.toHaveClass(/is-done/); await expect(planA).not.toHaveClass(/is-done/); await expect(planB).toHaveClass(/is-done/); const board = JSON.parse( readFileSync(path.join(root, ".system/board.json"), "utf8"), ); expect(board.items["PX-ISSUE-ISSUE001"].source).toBe("assess"); expect(board.items["PX-SPEC-SPEC0001"].state).toBe("todo"); expect(board.items["PX-PLAN-PLAN0001"].state).toBe("todo"); expect(board.items["PX-PLAN-PLAN0002"].state).toBe("done"); await page.setViewportSize({ width: 390, height: 844 }); const positions = await page.evaluate(() => { const specs = document .querySelector(".board-spec-list") ?.getBoundingClientRect(); const issues = document .querySelector(".board-issue-list") ?.getBoundingClientRect(); return { specsBottom: specs?.bottom ?? 0, issuesTop: issues?.top ?? 0 }; }); expect(positions.issuesTop).toBeGreaterThanOrEqual(positions.specsBottom); await expect.poll(() => page.evaluate(() => scrollX)).toBe(0); } finally { runtime.shutdown(); }}); write(root, ".system/config.json", '{"prefix":"PX","schemaVersion":3}'); "---\nid: PX-PHASE-PHASE001\ntype: phase\ntitle: Delivery\nspec: PX-SPEC-SPEC0001\nstatus: draft\n---\n\n# Delivery\n", "---\nid: PX-PHASE-PHASE001\ntype: phase\ntitle: Prototype\nlabel: prototype\n---\n\n# Prototype\n", "---\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", "---\nid: PX-PHASE-PHASE002\ntype: phase\ntitle: Pre-v1\nlabel: pre-v1\n---\n\n# Pre-v1\n", "---\nid: PX-PLAN-PLAN0001\ntype: plan\ntitle: Build\nspec: PX-SPEC-SPEC0001\nphase: PX-PHASE-PHASE002\nstatus: draft\n---\n\n# Build\n", "---\nid: PX-PLAN-PLAN0001\ntype: plan\ntitle: Build\nspec: PX-SPEC-SPEC0001\nstatus: draft\n---\n\n# Build\n", "---\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", "---\nid: PX-PLAN-PLAN0002\ntype: plan\ntitle: Test\nspec: PX-SPEC-SPEC0001\nstatus: draft\ndepends_on: [PX-PLAN-PLAN0001]\n---\n\n# Test\n",+1 / −1 text lines
new file mode 100644+159 / −0 text lines
import assert from "node:assert/strict";import { describe, it } from "vitest";import { boardStateFor, boardStateForInitialization, boardStateSource, emptyBoardState, parseBoardState, updateBoardState,} from "../board-state.ts";import type { BundleDocumentRecord, DocumentMetadata } from "../documents.ts";import { SystemDocumentError } from "../documents.ts";const document = (metadata: DocumentMetadata): BundleDocumentRecord => ({ path: `.system/${metadata.type}s/${metadata.id}-fixture/index.md`, metadata, frontmatter: new Map(),});const spec = document({ id: "PX-SPEC-SPEC0001", type: "spec", title: "Contract",});const planA = document({ id: "PX-PLAN-PLAN0001", type: "plan", title: "Build", spec: spec.metadata.id, status: "approved",});const planB = document({ id: "PX-PLAN-PLAN0002", type: "plan", title: "Test", spec: spec.metadata.id, status: "approved",});const issue = document({ id: "PX-ISSUE-ISSUE001", type: "issue", title: "Bug", specs: [spec.metadata.id],});const documents = [spec, planA, planB, issue];const at = "2026-03-20T12:00:00.000Z";describe("board state", () => { it("defaults specs and plans to todo and issues to open", () => { const board = emptyBoardState(); assert.equal(boardStateFor(board, spec.metadata), "todo"); assert.equal(boardStateFor(board, planA.metadata), "todo"); assert.equal(boardStateFor(board, issue.metadata), "open"); }); it("keeps spec state manual while requiring every existing plan done", () => { let board = emptyBoardState(); assert.throws( () => updateBoardState( board, documents, spec.metadata.id, "done", "manual", at, ), (error: unknown) => error instanceof SystemDocumentError && error.code === "board.spec-plans", ); board = updateBoardState( board, documents, planA.metadata.id, "done", "manual", at, ); board = updateBoardState( board, documents, planB.metadata.id, "done", "manual", at, ); assert.equal(boardStateFor(board, spec.metadata), "todo"); board = updateBoardState( board, documents, spec.metadata.id, "done", "manual", at, ); assert.equal(boardStateFor(board, spec.metadata), "done"); }); it("allows a planless spec done and never lets issues demote it", () => { let board = updateBoardState( emptyBoardState(), [spec, issue], spec.metadata.id, "done", "manual", at, ); board = updateBoardState( board, [spec, issue], issue.metadata.id, "open", "manual", at, ); assert.equal(boardStateFor(board, spec.metadata), "done"); }); it("reopening one plan demotes its spec without changing sibling plans", () => { let board = emptyBoardState(); for (const id of [planA.metadata.id, planB.metadata.id, spec.metadata.id]) board = updateBoardState(board, documents, id, "done", "manual", at); board = updateBoardState( board, documents, planA.metadata.id, "todo", "manual", at, ); assert.equal(boardStateFor(board, spec.metadata), "todo"); assert.equal(boardStateFor(board, planB.metadata), "done"); }); it("parses strict schema 0 and directly rewrites version mismatches", () => { const current = updateBoardState( emptyBoardState(), documents, issue.metadata.id, "done", "assess", at, ); assert.deepEqual(parseBoardState(boardStateSource(current), "PX"), current); const mismatched = boardStateSource(current).replace( '"schemaVersion": 0', '"schemaVersion": 9', ); assert.equal( boardStateForInitialization(mismatched, "PX").sourceSchemaVersion, 9, ); assert.throws( () => parseBoardState(mismatched, "PX"), (error: unknown) => error instanceof SystemDocumentError && error.code === "board.version", ); });});+38 / −4 text lines
write(root, ".system/config.json", '{"prefix":"PX","schemaVersion":3}'); ".system/board.json filesystem.missing", it("combines shared bundle, graph, obsolete CSS, and test diagnostics", () => { it("combines shared bundle, graph, and test diagnostics", () => { write(root, ".system/system.css", "legacy\n"); ".system/system.css filesystem.obsolete", it("reports invalid and dangling board state", () => { const root = temporaryRoot(); validSystem(root); write( root, ".system/board.json", '{"schemaVersion":0,"items":{"PX-SPEC-MISSING1":{"state":"done","updatedAt":"2026-03-20T12:00:00.000Z","source":"manual"}}}', ); assert.deepEqual( runDoctor(root).diagnostics.map(({ code }) => code), ["board.dangling-item"], ); write(root, ".system/board.json", '{"schemaVersion":4,"items":{}}'); assert.deepEqual( runDoctor(root).diagnostics.map(({ code }) => code), ["board.version"], ); }); write( root, ".system/config.json", '{"prefix":"PX","schemaVersion":0,"currentPhase":"PX-PHASE-PHASE001"}', ); assert.deepEqual( runDoctor(root).diagnostics.map(({ code, path }) => `${path} ${code}`), [".system/config.json config.current-phase"], ); write( root, ".system/phases/PX-PHASE-PHASE001-pre-v1/index.md", markdown("PX-PHASE-PHASE001", "phase", "\nlabel: pre-v1"), ); assert.deepEqual(runDoctor(root).diagnostics, []);+81 / −48 text lines
systemConfigForInitialization,describe("project root and schema-v3 config", () => {describe("project root and schema-0 config", () => { it("accepts minimal config and inspects narrow v1 config", () => { it("accepts schema 0 and prepares mismatched config for initialization", () => { '{"prefix":"PX","schemaVersion":3,"title":"Project X"}', '{"prefix":"PX","schemaVersion":0,"title":"Project X","currentPhase":"PX-PHASE-PHASE001"}', { prefix: "PX", schemaVersion: 3, title: "Project X" }, assert.deepEqual(parseSystemConfig('{"prefix":"PX","schemaVersion":3}'), { assert.deepEqual(parseSystemConfig('{"prefix":"PX","schemaVersion":0}'), { `---\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`, `---\nid: PX-PLAN-PL4N0001\ntype: plan\ntitle: Delivery\nspec: PX-SPEC-SPEC0001\nstatus: draft\ndepends_on: [PX-PLAN-PL4N0000]\nreview: human\n---\n`, phase: "PX-PHASE-PH4S0001", [ "id", "type", "title", "spec", "phase", "status", "depends_on", "review", ], ["id", "type", "title", "spec", "status", "depends_on", "review"], ); }); it("parses operating phases and validates their labels and size", () => { assert.deepEqual( parseAuthoredDocument( "---\nid: PX-PHASE-PHASE001\ntype: phase\ntitle: Pre-v1\nlabel: pre-v1\n---\n", "PX", ).metadata, { id: "PX-PHASE-PHASE001", type: "phase", title: "Pre-v1", label: "pre-v1", }, ); assert.throws( () => parseAuthoredDocument( "---\nid: PX-PHASE-PHASE001\ntype: phase\ntitle: Pre-v1\nlabel: label-is-too-long\n---\n", "PX", ), /1-12 ASCII/, ); assert.throws( () => parseAuthoredDocument( `---\nid: PX-PHASE-PHASE001\ntype: phase\ntitle: Pre-v1\nlabel: pre-v1\n---\n\n${"x".repeat(PHASE_BYTE_LIMIT)}`, "PX", ), /byte limit/, it("validates references, duplicates, and phase/spec consistency", () => { it("keeps phases separate from the spec-plan graph", () => { "id: PX-PHASE-PHASE001\ntype: phase\ntitle: Delivery\nspec: PX-SPEC-SPEC0001\nstatus: approved", "id: PX-PHASE-PHASE001\ntype: phase\ntitle: Delivery\nlabel: delivery", "id: PX-PLAN-PLAN0001\ntype: plan\ntitle: Build\nspec: PX-SPEC-SPEC0002\nphase: PX-PHASE-PHASE001\nstatus: draft", "id: PX-PLAN-PLAN0001\ntype: plan\ntitle: Build\nspec: PX-SPEC-SPEC0002\nstatus: draft", assert.deepEqual(indexed.diagnostics, []); source( "phases", "PX-PHASE-PHASE001", "one", "id: PX-PHASE-PHASE001\ntype: phase\ntitle: One\nspec: PX-SPEC-SPEC0001\nstatus: draft\ndepends_on: [PX-PHASE-PHASE002]", ), source( "phases", "PX-PHASE-PHASE002", "two", "id: PX-PHASE-PHASE002\ntype: phase\ntitle: Two\nspec: PX-SPEC-SPEC0001\nstatus: draft\ndepends_on: [PX-PHASE-PHASE001]", ), "id: PX-PLAN-PLAN0003\ntype: plan\ntitle: Three\nspec: PX-SPEC-SPEC0002\nstatus: draft", "id: PX-PLAN-PLAN0003\ntype: plan\ntitle: Three\nspec: PX-SPEC-SPEC0001\nstatus: draft\ndepends_on: [PX-PLAN-PLAN0002]", ), source( "plans", "PX-PLAN-PLAN0004", "four", "id: PX-PLAN-PLAN0004\ntype: plan\ntitle: Four\nspec: PX-SPEC-SPEC0002\nstatus: draft\ndepends_on: [PX-PLAN-PLAN0002]",+90 / −46 text lines
import { applyInitialization, inspectInitialization, type MachineState,} from "../init.ts";import { applyInitialization, inspectInitialization } from "../init.ts"; it("creates schema-v3 config and core files, then preserves cores on rerun", () => { it("creates schema-0 config and core files, then preserves cores on rerun", () => { assert.match(child.stdout, /WROTE \.system\/board\.json/); assert.doesNotMatch(child.stdout, /system\.css/); { prefix: "PX", schemaVersion: 3, title: path.basename(project) }, { prefix: "PX", schemaVersion: 0, title: path.basename(project) }, removed: [], it("holds legacy config and CSS pending, then upgrades only when approved", () => { it("holds a mismatched config pending, then rewrites it when approved", () => { const upgrades = [ ".system/config.json schemaVersion 1 -> 3; remove styleVersion", `.system/config.json add title "${path.basename(project)}"`, ".system/system.css remove obsolete machine-owned asset", ]; assert.deepEqual(inspectInitialization(project).upgrades, upgrades); assert.deepEqual(applyInitialization(project).pending, upgrades); legacy, ); assert.equal( readFileSync(path.join(project, ".system/system.css"), "utf8"), "legacy css\n", mismatched, it("rejects invalid prefixes, newer configs, and unsafe obsolete CSS paths", () => { it("rewrites a mismatched board directly to schema 0", () => { const project = root(); applyInitialization(project, "PX"); write( project, ".system/board.json", JSON.stringify({ schemaVersion: 7, items: { "PX-SPEC-SPEC0001": { state: "done", updatedAt: "2026-03-20T12:00:00.000Z", source: "manual", }, }, }), ); assert.deepEqual(inspectInitialization(project).rewrites, [ ".system/board.json schemaVersion 7 -> 0", ]); const configBefore = readFileSync( path.join(project, ".system/config.json"), "utf8", ); const result = applyInitialization(project, undefined, true); assert.deepEqual(result.changed, [".system/board.json"]); assert.equal( readFileSync(path.join(project, ".system/config.json"), "utf8"), configBefore, ); assert.equal( JSON.parse(readFileSync(path.join(project, ".system/board.json"), "utf8")) .schemaVersion, 0, ); }); it("preserves selected phase and title while resetting the schema", () => { const project = root(); applyInitialization(project, "PX"); write( project, ".system/config.json", JSON.stringify({ prefix: "PX", schemaVersion: 4, title: "Custom title", currentPhase: "PX-PHASE-PHASE001", }), ); applyInitialization(project, undefined, true); assert.deepEqual( JSON.parse( readFileSync(path.join(project, ".system/config.json"), "utf8"), ), { prefix: "PX", schemaVersion: 0, title: "Custom title", currentPhase: "PX-PHASE-PHASE001", }, ); }); it("rejects invalid prefixes, prefix conflicts, and unsafe config paths", () => {+261 / −20 text lines
readFileSync,import { startupRuntimeNotice } from "../startup-notice.ts"; runtimeState, it("injects the current phase after MISSION without mutating it", () => { const project = root(); const phase = ".system/phases/PX-PHASE-PHASE001-pre-v1/index.md"; write( project, phase, documentSource({ id: "PX-PHASE-PHASE001", type: "phase", title: "Pre-v1", label: "pre-v1", }), ); const configPath = path.join(project, ".system/config.json"); const config = JSON.parse(readFileSync(configPath, "utf8")); writeFileSync( configPath, `${JSON.stringify({ ...config, currentPhase: "PX-PHASE-PHASE001" })}\n`, ); const missionPath = path.join(project, ".system/MISSION.md"); const mission = readFileSync(missionPath, "utf8"); const prompt = composeSystemPrompt(project, "BASE"); assert.match( prompt, /SYSTEM\.md[\s\S]*MISSION\.md[\s\S]*Current phase: Pre-v1 · pre-v1[\s\S]*RULES\.md/, ); assert.equal(readFileSync(missionPath, "utf8"), mission); assert.deepEqual(runtimeState(project), { active: true, prefix: "PX", phaseLabel: "pre-v1", }); rmSync(path.join(project, path.dirname(phase)), { recursive: true, force: true, }); assert.match(composeSystemPrompt(project, "BASE"), /governance error/); }); it("activates an existing phase only after confirmation", async () => { const project = root(); write( project, ".system/phases/PX-PHASE-PHASE001-pre-v1/index.md", documentSource({ id: "PX-PHASE-PHASE001", type: "phase", title: "Pre-v1", label: "pre-v1", }), ); const configPath = path.join(project, ".system/config.json"); const config = JSON.parse(readFileSync(configPath, "utf8")); const candidate = `${JSON.stringify({ ...config, currentPhase: "PX-PHASE-PHASE001" })}\n`; let approvals = 0; const result = await preflightFileMutation( project, "write", { path: ".system/config.json", content: candidate }, { hasUI: true, select: async (_title, items) => { approvals += 1; assert.match(items[0] ?? "", /pre-v1 · Pre-v1/); return items[0]; }, }, ); assert.equal(result?.block, undefined); assert.equal(approvals, 1); const unavailable = await preflightFileMutation( project, "write", { path: ".system/config.json", content: candidate }, approval(false), ); assert.equal(unavailable?.block, true); assert.match(unavailable?.reason ?? "", /interactive UI/); for (const [decision, message] of [ ["deny", /denied/], ["cancel", /cancelled/], ] as const) { const rejected = await preflightFileMutation( project, "write", { path: ".system/config.json", content: candidate }, { hasUI: true, select: async (_title, items) => decision === "deny" ? items[1] : undefined, }, ); assert.equal(rejected?.block, true); assert.match(rejected?.reason ?? "", message); } writeFileSync(configPath, candidate); let deactivations = 0; const deactivated = await preflightFileMutation( project, "write", { path: ".system/config.json", content: `${JSON.stringify(config)}\n`, }, { hasUI: true, select: async (_title, items) => { deactivations += 1; assert.equal(items[0], "Deactivate current phase"); return items[0]; }, }, ); assert.equal(deactivated?.block, undefined); assert.equal(deactivations, 1); const unrelated = await preflightFileMutation( project, "write", { path: ".system/config.json", content: `${JSON.stringify({ ...config, title: "Changed", currentPhase: "PX-PHASE-PHASE001" })}\n`, }, approval(), ); assert.equal(unrelated?.block, true); assert.match(unrelated?.reason ?? "", /only change currentPhase/); }); it("reports rejected schema edits as config changes", async () => { const project = root(); const config = ".system/config.json"; write(project, config, '{"prefix":"PX","schemaVersion":1}\n'); const result = await preflightFileMutation( project, "edit", { path: config, edits: [{ oldText: '"schemaVersion":1', newText: '"schemaVersion":0' }], }, approval(), ); assert.equal(result?.block, true); assert.match(result?.reason ?? "", /rejected the config change/); assert.doesNotMatch(result?.reason ?? "", /phase change/); }); it("allows approved repair of invalid phase metadata", async () => { const project = root(); const phase = ".system/phases/PX-PHASE-PHASE001-pre-v1/index.md"; write( project, phase, "---\nid: PX-PHASE-PHASE001\ntype: phase\ntitle: Pre-v1\nspec: PX-SPEC-SPEC0001\nstatus: approved\n---\n", ); let approvals = 0; const result = await preflightFileMutation( project, "write", { path: phase, content: "---\nid: PX-PHASE-PHASE001\ntype: phase\ntitle: Pre-v1\nlabel: pre-v1\n---\n", }, { hasUI: true, select: async (_title, items) => { approvals += 1; return items[0]; }, }, ); assert.equal(result?.block, undefined); assert.equal(approvals, 1); }); it("allows scoped bundle migration without per-bundle approval", async () => { const project = root(); const phase = ".system/phases/PX-PHASE-PHASE001-pre-v1/index.md"; write( project, phase, "---\nid: PX-PHASE-PHASE001\ntype: phase\ntitle: Pre-v1\nspec: PX-SPEC-SPEC0001\nstatus: approved\n---\n", ); const migrated = await preflightFileMutation( project, "write", { path: phase, content: "---\nid: PX-PHASE-PHASE001\ntype: phase\ntitle: Pre-v1\nlabel: pre-v1\n---\n", }, approval(false), { bundleMigration: true }, ); assert.equal(migrated?.block, undefined); const invalid = await preflightFileMutation( project, "write", { path: phase, content: "---\nid: wrong\n---\n" }, approval(false), { bundleMigration: true }, ); assert.equal(invalid?.block, true); assert.match(invalid?.reason ?? "", /candidate validation failed/); }); it("validates editable non-spec indexes and blocks approved phase and plan bundles", async () => { it("approves phase amendments and keeps approved plans immutable", async () => { phase: "PX-PHASE-PHASE001", for (const relative of [phase, plan]) { let phaseApprovals = 0; const phaseResult = await preflightFileMutation( project, "edit", { path: phase, edits: [{ oldText: "Approved.", newText: "Reviewed." }], }, { hasUI: true, select: async (_title, items) => { phaseApprovals += 1; return items[0]; }, }, ); assert.equal(phaseResult?.block, undefined); assert.equal(phaseApprovals, 1); for (const target of [plan, plan.replace("index.md", "evidence.txt")]) {+269 / −13 text lines
import { composeSystemPrompt, runtimeState } from "../system.ts";import { systemPromptFor } from "../system-prompts.ts"; write(root, ".system/config.json", '{"prefix":"PX","schemaVersion":3}'); "---\nid: PX-PHASE-PHASE001\ntype: phase\ntitle: Delivery\nspec: PX-SPEC-SPEC0001\nstatus: draft\n---\n\n# Delivery\n", "---\nid: PX-PHASE-PHASE001\ntype: phase\ntitle: Delivery\nlabel: delivery\n---\n\n# Delivery\n", "---\nid: PX-PHASE-PHASE002\ntype: phase\ntitle: Alpha\nspec: PX-SPEC-SPEC0001\nstatus: draft\ndepends_on: [PX-PHASE-PHASE001]\n---\n\n# Alpha\n", "---\nid: PX-PHASE-PHASE002\ntype: phase\ntitle: Alpha\nlabel: alpha\n---\n\n# Alpha\n", "---\nid: PX-PLAN-PLAN0001\ntype: plan\ntitle: Build\nspec: PX-SPEC-SPEC0001\nphase: PX-PHASE-PHASE001\nstatus: draft\n---\n\n# Build\n", "---\nid: PX-PLAN-PLAN0001\ntype: plan\ntitle: Build\nspec: PX-SPEC-SPEC0001\nstatus: draft\n---\n\n# Build\n", "---\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", "---\nid: PX-PLAN-PLAN0002\ntype: plan\ntitle: Alpha\nspec: PX-SPEC-SPEC0001\nstatus: draft\ndepends_on: [PX-PLAN-PLAN0001]\n---\n\n# Alpha\n", it("registers /system, mockup, and the scoped artifact slot tool", () => { it("assigns bundle migration, not machine schema updates, to the agent", () => { const prompt = systemPromptFor("init", ""); assert.match(prompt, /config and board schema markers mechanically/); assert.match(prompt, /migrate existing bundles to schema 0/); }); it("registers /system and scoped extension tools", () => { assert.deepEqual(tools, ["mockup", "system_slot"]); assert.deepEqual(tools, ["mockup", "system_slot", "system_board_propose"]); }); it("reports schema mismatches with schema-0 init instructions", () => { const project = temp(); validSystem(project); write(project, ".system/config.json", '{"prefix":"PX","schemaVersion":4}'); assert.deepEqual(runtimeState(project), { active: true, notice: "The System schema does not match 0; run /system init to update it.", }); assert.match( composeSystemPrompt(project, "BASE"), /Schema version 4 does not match 0; run \/system init/, ); }); it("shows an accent System status for initialized and incomplete projects", async () => { for (const [project, expected] of [ [temp(), undefined], [temp(), "accent: ?"], [temp(), "accent: PX"], [temp(), "accent: PX · delivery"], ] as const) { if (expected === "accent: ?") mkdirSync(path.join(project, ".system")); if (expected?.startsWith("accent: PX")) validSystem(project); if (expected === "accent: PX · delivery") write( project, ".system/config.json", '{"prefix":"PX","schemaVersion":0,"currentPhase":"PX-PHASE-PHASE001"}', ); let sessionStart: ((event: unknown, ctx: unknown) => void) | undefined; let resolveStatus: (value: string | undefined) => void = () => {}; const status = new Promise<string | undefined>((resolve) => { resolveStatus = resolve; }); registerTheSystem({ registerCommand() {}, registerTool() {}, getActiveTools: () => [], setActiveTools() {}, on(event: string, handler: (event: unknown, ctx: unknown) => void) { if (event === "session_start") sessionStart = handler; }, } as never); sessionStart?.( {}, { cwd: project, hasUI: true, isIdle: () => true, abort() {}, sessionManager: { getSessionId: () => project }, ui: { notify() {}, setStatus(_key: string, text: string | undefined) { resolveStatus(text); }, theme: { fg: (color: string, text: string) => `${color}:${text}`, }, }, }, ); assert.equal(await status, expected); } }); it("refreshes the footer phase before later agent turns", async () => { const project = temp(); validSystem(project); let sessionStart: ((event: unknown, ctx: unknown) => void) | undefined; let beforeAgentStart: | ((event: { systemPrompt: string }, ctx: unknown) => Promise<unknown>) | undefined; const statuses: (string | undefined)[] = []; const waiters: Array<{ expected: string | undefined; resolve: () => void; }> = []; const waitForStatus = (expected: string | undefined) => { if (statuses.includes(expected)) return Promise.resolve(); return new Promise<void>((resolve) => waiters.push({ expected, resolve }), ); }; registerTheSystem({ registerCommand() {}, registerTool() {}, getActiveTools: () => [], setActiveTools() {}, on(event: string, handler: (...args: never[]) => unknown) { if (event === "session_start") sessionStart = handler as never; if (event === "before_agent_start") beforeAgentStart = handler as never; }, } as never); const ctx = { cwd: project, hasUI: true, isIdle: () => true, abort() {}, sessionManager: { getSessionId: () => project, getBranch: () => [], }, ui: { notify() {}, setStatus(_key: string, text: string | undefined) { statuses.push(text); for (const waiter of waiters) if (waiter.expected === text) waiter.resolve(); }, theme: { fg: (color: string, text: string) => `${color}:${text}`, }, }, }; sessionStart?.({}, ctx); await waitForStatus("accent: PX"); write( project, ".system/config.json", '{"prefix":"PX","schemaVersion":0,"currentPhase":"PX-PHASE-PHASE001"}', ); await beforeAgentStart?.({ systemPrompt: "BASE" }, ctx); await waitForStatus("accent: PX · delivery"); it("opens the board directly through its runtime", async () => { const project = temp(); validSystem(project); const notices: string[] = []; const command = createSystemCommand({ sendUserMessage() {} } as never, { openBoard: async (cwd) => { assert.equal(cwd, project); return "System board running: http://127.0.0.1:1234"; }, }); await command.handler("board", { cwd: project, waitForIdle: async () => {}, ui: { notify: (message: string) => notices.push(message) }, } as never); assert.match(notices[0] ?? "", /System board running/); }); { prefix: "PX", schemaVersion: 3, title: path.basename(project) }, { prefix: "PX", schemaVersion: 0, title: path.basename(project) }, it("updates machine schema mechanically, then offers agent bundle migration", async () => { const project = temp(); validSystem(project); write( project, ".system/config.json", '{"prefix":"PX","schemaVersion":4,"title":"Project"}', ); const sent: string[] = []; const confirmations: string[] = []; let idle = false; let migrations = 0; const command = createSystemCommand( { sendUserMessage: (message: string) => sent.push(message) } as never, { activateBundleMigration: () => migrations++ }, ); await command.handler("init", { cwd: project, waitForIdle: async () => { idle = true; }, ui: { confirm: async (title: string, summary: string) => { confirmations.push(title); if (title === "Initialize The System?") assert.match( summary, /Update: \.system\/config\.json schemaVersion 4 -> 0/, ); else assert.match(summary, /Machine schema updated mechanically/); return true; }, notify() {}, }, } as never); assert.deepEqual(confirmations, [ "Initialize The System?", "Should System bundles be migrated by agent?", ]); assert.equal(idle, true); assert.equal(migrations, 1); assert.match(sent[0] ?? "", /# \/system init/); assert.match( sent[0] ?? "", /Source: \.system\/config\.json schemaVersion 4 -> 0/, ); assert.equal( JSON.parse( readFileSync(path.join(project, ".system/config.json"), "utf8"), ).schemaVersion, 0, ); }); it("updates board schema without offering bundle migration", async () => { const project = temp(); validSystem(project); write(project, ".system/board.json", '{"schemaVersion":4,"items":{}}'); const sent: string[] = []; const confirmations: string[] = []; const command = createSystemCommand({ sendUserMessage: (message: string) => sent.push(message), } as never); await command.handler("init", { cwd: project, waitForIdle: async () => {}, ui: { confirm: async (title: string) => { confirmations.push(title); return true; }, notify() {}, }, } as never); assert.deepEqual(confirmations, ["Initialize The System?"]); assert.deepEqual(sent, []); assert.equal( JSON.parse(readFileSync(path.join(project, ".system/board.json"), "utf8")) .schemaVersion, 0, ); }); let assessments = 0; () => activations++, "assess", assert.equal(assessments, 2); assert.match( sent.find((item) => item.includes("# /system assess")) ?? "", /system_board_propose/, ); const phasePrompt = sent.find((item) => item.includes("# /system phase\n")) ?? ""; assert.match(phasePrompt, /project-wide operating phase/); assert.match(phasePrompt, /config currentPhase/); assert.doesNotMatch(phasePrompt, /large specs/); docs.indexOf('<section id="PX-SPEC-SPEC0001"') < docs.indexOf('<section id="PX-PHASE-PHASE002"') <new file mode 100644+157 / −0 text lines
import { StringEnum } from "@earendil-works/pi-ai";import { defineTool, keyHint } from "@earendil-works/pi-coding-agent";import { Text } from "@earendil-works/pi-tui";import { Type } from "typebox";import type { BoardServer } from "./board-server.ts";import { type BoardProposal, readBoardState } from "./board-state.ts";import { discoverProjectRoot } from "./documents.ts";import { loadProjectIndex } from "./project-index.ts";const STATES = ["todo", "done", "open"] as const;const proposalParameters = Type.Object({ items: Type.Array( Type.Object({ id: Type.String({ description: "Existing spec, plan, or issue ID." }), state: StringEnum(STATES, { description: "Proposed board state for the item type.", }), rationale: Type.String({ minLength: 1, maxLength: 1000, description: "Terse evidence supporting this proposed state.", }), }), { minItems: 1, maxItems: 100 }, ),});export function createBoardRuntime() { let assessmentRoot: string | undefined; const proposals = new Map<string, Map<string, BoardProposal>>(); const servers = new Set<BoardServer>(); const tool = defineTool({ name: "system_board_propose", label: "System Board Proposal", description: "Propose evidence-backed System board state changes for human review.", parameters: proposalParameters, renderCall(args, theme) { return new Text( theme.fg( "toolTitle", theme.bold( `system_board_propose ${Array.isArray(args.items) ? args.items.length : 0}`, ), ), 0, 0, ); }, renderResult(result, { expanded }, theme) { const items = (result.details as { items?: BoardProposal[] } | undefined) ?.items; if (!items) return new Text("", 0, 0); if (!expanded) return new Text( `${theme.fg("success", `${items.length} proposed`)} · ${theme.fg("dim", keyHint("app.tools.expand", "to expand"))}`, 0, 0, ); return new Text( items .map( (item) => `${theme.fg("accent", item.state.toUpperCase())} ${item.id}\n${theme.fg("dim", item.rationale)}`, ) .join("\n"), 0, 0, ); }, async execute(_toolCallId, params, _signal, _onUpdate, ctx) { const root = discoverProjectRoot(ctx.cwd); if (root !== assessmentRoot) throw new Error( "system_board_propose is only available during /system assess", ); const index = loadProjectIndex(root); const byId = new Map( index.documents.map((document) => [document.metadata.id, document]), ); const proposed = proposals.get(root) ?? new Map<string, BoardProposal>(); for (const raw of params.items) { const document = byId.get(raw.id); if (!document) throw new Error(`No System board item: ${raw.id}`); const valid = document.metadata.type === "issue" ? raw.state === "open" || raw.state === "done" : (document.metadata.type === "spec" || document.metadata.type === "plan") && (raw.state === "todo" || raw.state === "done"); if (!valid) throw new Error( `Invalid ${document.metadata.type} board state ${raw.state}: ${raw.id}`, ); proposed.set(raw.id, { id: raw.id, state: raw.state, rationale: raw.rationale.trim(), }); } proposals.set(root, proposed); const items = [...proposed.values()].sort((left, right) => left.id.localeCompare(right.id), ); return { content: [ { type: "text" as const, text: `${params.items.length} board state proposal(s) recorded for human review. Run /system board to inspect and apply them.`, }, ], details: { items }, }; }, }); return { tool, beginAssessment(cwd: string) { const root = discoverProjectRoot(cwd); const index = loadProjectIndex(root); readBoardState(root, index.prefix); assessmentRoot = root; proposals.set(root, new Map()); }, endAssessment() { assessmentRoot = undefined; }, async open(cwd: string): Promise<string> { const index = loadProjectIndex(cwd); const state = readBoardState(index.root, index.prefix); const current = [...(proposals.get(index.root)?.values() ?? [])]; const [{ renderSystemBoardSite }, { startBoardServer }, { openUrl }] = await Promise.all([ import("./system-renderer.ts"), import("./board-server.ts"), import("./open-browser.ts"), ]); const output = renderSystemBoardSite(index, state, current); const server = await startBoardServer( output.directory, index, proposals.get(index.root) ?? new Map(), ); servers.add(server); const opened = await openUrl(server.url); return opened.ok ? `System board opened: ${server.url}\nBrowser: ${opened.command}` : `System board running: ${server.url}\nBrowser: ${opened.error}`; }, shutdown() { assessmentRoot = undefined; for (const server of servers) server.close(); servers.clear(); }, };}new file mode 100644+281 / −0 text lines
import { randomUUID } from "node:crypto";import { createReadStream, lstatSync, realpathSync, rmSync } from "node:fs";import { createServer, type IncomingMessage, type Server, type ServerResponse,} from "node:http";import path from "node:path";import { type BoardItemState, type BoardProposal, readBoardState, updateBoardState, writeBoardState,} from "./board-state.ts";import type { ProjectIndex } from "./project-index.ts";const BODY_LIMIT = 64 * 1024;const COOKIE = "the_system_board";const STATES = ["todo", "done", "open"] as const;export type BoardServer = Readonly<{ url: string; close(): void }>;export async function startBoardServer( directory: string, index: ProjectIndex, proposals: Map<string, BoardProposal>,): Promise<BoardServer> { const token = `${randomUUID()}-${randomUUID()}`; const cookieName = `${COOKIE}_${token.slice(0, 8)}`; let server!: Server; let mutation = Promise.resolve(); const enqueue = <T>(work: () => T): Promise<T> => { const result = mutation.then(work, work); mutation = result.then( () => undefined, () => undefined, ); return result; }; server = createServer((request, response) => { void dispatch(request, response, { directory, index, proposals, token, cookieName, enqueue, }); }); await new Promise<void>((resolve, reject) => { server.once("error", reject); server.listen(0, "127.0.0.1", () => { server.off("error", reject); resolve(); }); }); const address = server.address(); if (!address || typeof address === "string") throw new Error("Failed to bind System board server"); return { url: `http://127.0.0.1:${address.port}/?k=${token}`, close() { server.close(); rmSync(directory, { recursive: true, force: true }); }, };}type DispatchState = Readonly<{ directory: string; index: ProjectIndex; proposals: Map<string, BoardProposal>; token: string; cookieName: string; enqueue<T>(work: () => T): Promise<T>;}>;async function dispatch( request: IncomingMessage, response: ServerResponse, state: DispatchState,): Promise<void> { try { const url = new URL(request.url ?? "/", "http://127.0.0.1"); const queryToken = url.searchParams.get("k"); const cookieToken = cookie(request.headers.cookie ?? "", state.cookieName); if (queryToken === state.token) { response.statusCode = 303; response.setHeader("Location", url.pathname); response.setHeader( "Set-Cookie", `${state.cookieName}=${state.token}; HttpOnly; SameSite=Strict; Path=/`, ); response.end(); return; } if (cookieToken !== state.token) { respondJson(response, 403, { error: "Forbidden" }); return; } if ( request.method === "POST" && request.headers.origin !== `http://${request.headers.host}` ) { respondJson(response, 403, { error: "Invalid board origin" }); return; } if (request.method === "POST" && url.pathname === "/api/state") { const input = await readJsonBody(request); const result = await state.enqueue(() => applyState(state.index, input, "manual"), ); respondJson(response, 200, result); return; } if (request.method === "POST" && url.pathname === "/api/proposal") { const input = await readJsonBody(request); if (typeof input.id !== "string" || typeof input.state !== "string") throw new Error("Expected assessment proposal with id and state"); const proposal = state.proposals.get(input.id); if (!proposal || proposal.state !== input.state) throw new Error(`No matching assessment proposal: ${input.id}`); const result = await state.enqueue(() => applyState(state.index, input, "assess"), ); state.proposals.delete(input.id); respondJson(response, 200, result); return; } if (request.method !== "GET") { respondJson(response, 405, { error: "Method not allowed" }); return; } serveFile(response, state.directory, url.pathname); } catch (error) { respondJson(response, 400, { error: error instanceof Error ? error.message : String(error), }); }}function applyState( index: ProjectIndex, input: Record<string, unknown>, source: "manual" | "assess",) { if ( Object.keys(input).some((key) => key !== "id" && key !== "state") || typeof input.id !== "string" || typeof input.state !== "string" || !STATES.includes(input.state as (typeof STATES)[number]) ) throw new Error("Expected board update with id and state"); const current = readBoardState(index.root, index.prefix); const updated = updateBoardState( current, index.documents, input.id, input.state as BoardItemState, source, ); writeBoardState(index.root, updated); return { items: updated.items };}function readJsonBody( request: IncomingMessage,): Promise<Record<string, unknown>> { return new Promise((resolve, reject) => { let source = ""; request.setEncoding("utf8"); request.on("data", (chunk: string) => { source += chunk; if (Buffer.byteLength(source) > BODY_LIMIT) { request.destroy(); reject(new Error("Board request body is too large")); } }); request.on("end", () => { try { const parsed = JSON.parse(source); if ( typeof parsed !== "object" || parsed === null || Array.isArray(parsed) ) throw new Error("Board request body must be an object"); resolve(parsed as Record<string, unknown>); } catch (error) { reject(error); } }); request.on("error", reject); });}function serveFile( response: ServerResponse, directory: string, pathname: string,): void { const relative = decodeURIComponent( pathname === "/" ? "index.html" : pathname.slice(1), ); const target = path.resolve(directory, relative); const inside = path.relative(directory, target); if ( inside === ".." || inside.startsWith(`..${path.sep}`) || path.isAbsolute(inside) ) { respondJson(response, 404, { error: "Not found" }); return; } const stats = lstatSync(target, { throwIfNoEntry: false }); if (!stats?.isFile() || stats.isSymbolicLink()) { respondJson(response, 404, { error: "Not found" }); return; } const realRoot = realpathSync(directory); const realTarget = realpathSync(target); const realInside = path.relative(realRoot, realTarget); if ( realInside === ".." || realInside.startsWith(`..${path.sep}`) || path.isAbsolute(realInside) ) { respondJson(response, 404, { error: "Not found" }); return; } response.statusCode = 200; response.setHeader("Content-Type", contentType(target)); response.setHeader("Cache-Control", "no-store"); createReadStream(target).pipe(response);}function contentType(file: string): string { switch (path.extname(file).toLowerCase()) { case ".html": return "text/html; charset=utf-8"; case ".js": return "text/javascript; charset=utf-8"; case ".css": return "text/css; charset=utf-8"; case ".svg": return "image/svg+xml"; case ".png": return "image/png"; case ".jpg": case ".jpeg": return "image/jpeg"; case ".gif": return "image/gif"; case ".webp": return "image/webp"; default: return "application/octet-stream"; }}function respondJson( response: ServerResponse, status: number, value: unknown,): void { if (response.headersSent) return; response.statusCode = status; response.setHeader("Content-Type", "application/json; charset=utf-8"); response.setHeader("Cache-Control", "no-store"); response.end(JSON.stringify(value));}function cookie(source: string, name: string): string | undefined { for (const part of source.split(";")) { const [key, ...value] = part.trim().split("="); if (key === name) return value.join("="); } return undefined;}new file mode 100644+257 / −0 text lines
import { readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";import path from "node:path";import { type BundleDocumentRecord, type DocumentMetadata, parseDocumentId, resolveGovernedPath, SystemDocumentError,} from "./documents.ts";export const BOARD_SCHEMA_VERSION = 0;export const BOARD_PATH = ".system/board.json";export type BoardItemState = "todo" | "done" | "open";export type BoardItemSource = "manual" | "assess";export type BoardEntry = Readonly<{ state: BoardItemState; updatedAt: string; source: BoardItemSource;}>;export type BoardProposal = Readonly<{ id: string; state: BoardItemState; rationale: string;}>;export type BoardState = Readonly<{ schemaVersion: number; items: Readonly<Record<string, BoardEntry>>;}>;const objectValue = ( value: unknown, label: string,): Record<string, unknown> => { if (typeof value !== "object" || value === null || Array.isArray(value)) throw new SystemDocumentError( "board.shape", `${label} must be a JSON object`, ); return value as Record<string, unknown>;};const exactKeys = ( value: Record<string, unknown>, required: readonly string[], label: string,) => { const actual = Object.keys(value).sort(); if ( required.some((key) => !(key in value)) || actual.some((key) => !required.includes(key)) ) throw new SystemDocumentError( "board.keys", `${label} expected keys ${[...required].sort().join(", ")}; received ${actual.join(", ")}`, );};const validState = (type: DocumentMetadata["type"], state: string): boolean => { switch (type) { case "spec": case "plan": return state === "todo" || state === "done"; case "issue": return state === "open" || state === "done"; default: return false; }};export function parseBoardState(source: string, prefix: string): BoardState { let parsed: unknown; try { parsed = JSON.parse(source); } catch { throw new SystemDocumentError("board.invalid-json", "Invalid board JSON"); } const value = objectValue(parsed, "Board"); if (value.schemaVersion !== BOARD_SCHEMA_VERSION) throw new SystemDocumentError( "board.version", `Board schema version ${String(value.schemaVersion)} does not match ${BOARD_SCHEMA_VERSION}; run /system init`, ); exactKeys(value, ["items", "schemaVersion"], "Board"); const rawItems = objectValue(value.items, "Board items"); const items: Record<string, BoardEntry> = {}; for (const [id, rawEntry] of Object.entries(rawItems)) { const parsedId = parseDocumentId(id, prefix); if (!["spec", "plan", "issue"].includes(parsedId.type)) throw new SystemDocumentError( "board.item-type", `Board item must reference a spec, plan, or issue: ${id}`, ); const entry = objectValue(rawEntry, `Board item ${id}`); exactKeys(entry, ["source", "state", "updatedAt"], `Board item ${id}`); if (typeof entry.state !== "string") throw new SystemDocumentError( "board.state", `Board item state must be a string: ${id}`, ); if (!validState(parsedId.type, entry.state)) throw new SystemDocumentError( "board.state", `Invalid ${parsedId.type} board state ${entry.state}: ${id}`, ); if (entry.source !== "manual" && entry.source !== "assess") throw new SystemDocumentError( "board.source", `Invalid board source for ${id}`, ); if ( typeof entry.updatedAt !== "string" || Number.isNaN(Date.parse(entry.updatedAt)) || new Date(entry.updatedAt).toISOString() !== entry.updatedAt ) throw new SystemDocumentError( "board.updated-at", `Board updatedAt must be a canonical ISO timestamp: ${id}`, ); items[id] = { state: entry.state as BoardItemState, updatedAt: entry.updatedAt, source: entry.source, }; } return { schemaVersion: BOARD_SCHEMA_VERSION, items };}export function boardStateForInitialization( source: string, prefix: string,): { state: BoardState; sourceSchemaVersion?: number } { try { return { state: parseBoardState(source, prefix) }; } catch (error) { if ( !(error instanceof SystemDocumentError) || error.code !== "board.version" ) throw error; const parsed = objectValue(JSON.parse(source), "Board"); if ( typeof parsed.schemaVersion !== "number" || !Number.isInteger(parsed.schemaVersion) ) throw error; const state = parseBoardState( JSON.stringify({ schemaVersion: BOARD_SCHEMA_VERSION, items: parsed.items, }), prefix, ); return { state, sourceSchemaVersion: parsed.schemaVersion }; }}export const emptyBoardState = (): BoardState => ({ schemaVersion: BOARD_SCHEMA_VERSION, items: {},});export function boardStateSource(state: BoardState): string { return `${JSON.stringify( { schemaVersion: BOARD_SCHEMA_VERSION, items: Object.fromEntries( Object.entries(state.items).sort(([left], [right]) => left.localeCompare(right), ), ), }, null, "\t", )}\n`;}export function readBoardState(root: string, prefix: string): BoardState { return parseBoardState( readFileSync(resolveGovernedPath(root, BOARD_PATH), "utf8"), prefix, );}export function defaultBoardState(metadata: DocumentMetadata): BoardItemState { return metadata.type === "issue" ? "open" : "todo";}export function boardStateFor( board: BoardState, metadata: DocumentMetadata,): BoardItemState { return board.items[metadata.id]?.state ?? defaultBoardState(metadata);}export function updateBoardState( board: BoardState, documents: readonly BundleDocumentRecord[], id: string, state: BoardItemState, source: BoardItemSource, updatedAt = new Date().toISOString(),): BoardState { const document = documents.find((candidate) => candidate.metadata.id === id); if (!document) throw new SystemDocumentError( "board.missing-item", `No System board item: ${id}`, ); if (!validState(document.metadata.type, state)) throw new SystemDocumentError( "board.state", `Invalid ${document.metadata.type} board state ${state}: ${id}`, ); const items: Record<string, BoardEntry> = { ...board.items }; items[id] = { state, source, updatedAt }; if (document.metadata.type === "spec" && state === "done") { const unfinished = documents.filter( (candidate) => candidate.metadata.type === "plan" && candidate.metadata.spec === id && (items[candidate.metadata.id]?.state ?? "todo") !== "done", ); if (unfinished.length) throw new SystemDocumentError( "board.spec-plans", `Spec ${id} cannot be done while plans remain todo: ${unfinished.map((item) => item.metadata.id).join(", ")}`, ); } if (document.metadata.type === "plan" && state === "todo") { const specId = document.metadata.spec; const spec = documents.find( (candidate) => candidate.metadata.type === "spec" && candidate.metadata.id === specId, ); if (spec && (items[spec.metadata.id]?.state ?? "todo") === "done") items[spec.metadata.id] = { state: "todo", source, updatedAt }; } return { schemaVersion: BOARD_SCHEMA_VERSION, items };}export function writeBoardState(root: string, state: BoardState): void { const target = resolveGovernedPath(root, BOARD_PATH); const temporary = path.join( path.dirname(target), `.board-${process.pid}-${Date.now()}.json`, ); writeFileSync(temporary, boardStateSource(state), { encoding: "utf8", flag: "wx", }); try { renameSync(temporary, target); } finally { rmSync(temporary, { force: true }); }}+59 / −34 text lines
import { BOARD_PATH, boardStateFor, readBoardState } from "./board-state.ts"; BOARD_PATH, const cssPath = path.join(root, ".system/system.css"); const css = lstatSync(cssPath, { throwIfNoEntry: false }); if (css?.isFile()) diagnostics.push( diagnostic( "filesystem.obsolete", ".system/system.css", "Remove obsolete machine-owned asset .system/system.css", ), ); else if (css) diagnostics.push( diagnostic( "filesystem.unsafe", ".system/system.css", ".system/system.css must be a regular file or absent", ), ); let prefix: string | undefined; let config: SystemConfig | undefined; const inspected = inspectSystemConfig(readFileSync(configPath, "utf8")); prefix = inspected.config.prefix; if (inspected.config.schemaVersion !== 3) diagnostics.push( diagnostic( "config.schema-outdated", ".system/config.json", `Schema version ${inspected.config.schemaVersion}; installed 3`, ), ); config = parseSystemConfig(readFileSync(configPath, "utf8")); if (isFile(path.join(root, BOARD_PATH))) { try { const board = readBoardState(root, config.prefix); const documentIds = new Set( index.documents.map((document) => document.metadata.id), ); for (const id of Object.keys(board.items)) if (!documentIds.has(id)) diagnostics.push( diagnostic( "board.dangling-item", BOARD_PATH, `Board references missing ${id}`, ), ); for (const spec of index.documents) { if ( spec.metadata.type !== "spec" || boardStateFor(board, spec.metadata) !== "done" ) continue; const unfinished = index.documents.filter( (document) => document.metadata.type === "plan" && document.metadata.spec === spec.metadata.id && boardStateFor(board, document.metadata) !== "done", ); if (unfinished.length) diagnostics.push( diagnostic( "board.spec-plans", BOARD_PATH, `Spec ${spec.metadata.id} is done while plans remain todo: ${unfinished.map((document) => document.metadata.id).join(", ")}`, ), ); } } catch (error) { const value = error as SystemDocumentError; diagnostics.push(diagnostic(value.code, BOARD_PATH, value.message)); } } try { readCurrentPhase(root, config); } catch (error) { const value = error as SystemDocumentError; diagnostics.push( diagnostic(value.code, ".system/config.json", value.message), ); }+136 / −105 text lines
export const SCHEMA_VERSION = 3; currentPhase?: string;export type InspectedSystemConfig = Readonly<{export type InitializationSystemConfig = Readonly<{ phase?: string;const exactKeys = ( value: Record<string, unknown>, required: readonly string[],) => { const actual = Object.keys(value).sort(); if ( required.some((key) => !(key in value)) || actual.some((key) => !required.includes(key)) ) throw new SystemDocumentError( "json.keys", `Expected keys ${[...required].sort().join(", ")}; received ${actual.join(", ")}`, );};const positiveInteger = (value: unknown) => typeof value === "number" && Number.isInteger(value) && value > 0; const validKeys = ["prefix", "schemaVersion", "title"]; const validKeys = ["currentPhase", "prefix", "schemaVersion", "title"]; `Expected keys prefix, schemaVersion[, title]; received ${keys.join(", ")}`, `Expected keys prefix, schemaVersion[, title, currentPhase]; received ${keys.join(", ")}`, if ("currentPhase" in value) { if (typeof value.currentPhase !== "string") throw new SystemDocumentError( "config.current-phase", "Current phase must be a phase ID", ); const current = parseDocumentId(value.currentPhase, value.prefix); if (current.type !== "phase") throw new SystemDocumentError( "config.current-phase", "Current phase must be a phase ID", ); }export function inspectSystemConfig(source: string): InspectedSystemConfig { } catch (currentError) { let parsed: unknown; try { parsed = JSON.parse(source); } catch { throw currentError; } if (duplicateTopLevelKeys(source).length > 0) throw currentError; let value: Record<string, unknown>; try { value = objectValue(parsed, "Legacy config"); exactKeys(value, ["prefix", "schemaVersion", "styleVersion"]); } catch { throw currentError; } if (value.schemaVersion !== 1 || !positiveInteger(value.styleVersion)) throw currentError; } catch (error) { if ( !(error instanceof SystemDocumentError) || error.code !== "config.version" ) throw error; const parsed = objectValue(JSON.parse(source), "Config"); if ( duplicateTopLevelKeys(source).length > 0 || typeof parsed.schemaVersion !== "number" || !Number.isInteger(parsed.schemaVersion) ) throw error; return { config, legacyStyleVersion: value.styleVersion as number }; return { config, sourceSchemaVersion: parsed.schemaVersion }; const dependencies = (expected: "phase" | "plan") => { const dependencies = (expected: "plan") => { const phase = fields.get("phase"); ...(typeof phase === "string" ? { phase } : {}), return { metadata: projectMetadata(parsed.frontmatter, prefix), frontmatter: parsed.frontmatter, }; const metadata = projectMetadata(parsed.frontmatter, prefix); if ( metadata.type === "phase" && Buffer.byteLength(source, "utf8") > PHASE_BYTE_LIMIT ) throw new SystemDocumentError( "document.phase-size", `Phase exceeds the ${PHASE_BYTE_LIMIT}-byte limit`, ); return { metadata, frontmatter: parsed.frontmatter };}export type CurrentPhaseDocument = Readonly<{ path: string; metadata: PhaseMetadata; markdown: string;}>;export function readCurrentPhase( root: string, config: SystemConfig,): CurrentPhaseDocument | undefined { if (!config.currentPhase) return undefined; const directory = path.join(root, ".system/phases"); let matches: string[]; try { matches = readdirSync(directory).filter((name) => name.startsWith(`${config.currentPhase}-`), ); } catch { throw new SystemDocumentError( "config.current-phase", `Current phase does not exist: ${config.currentPhase}`, ); } if (matches.length !== 1) throw new SystemDocumentError( "config.current-phase", matches.length === 0 ? `Current phase does not exist: ${config.currentPhase}` : `Current phase is ambiguous: ${config.currentPhase}`, ); const relative = `.system/phases/${matches[0]}/index.md`; const bundle = path.join(directory, matches[0] as string); const target = path.join(bundle, "index.md"); const targetStats = lstatSync(target, { throwIfNoEntry: false }); if ( lstatSync(bundle, { throwIfNoEntry: false })?.isSymbolicLink() || !targetStats?.isFile() || targetStats.isSymbolicLink() ) throw new SystemDocumentError( "config.current-phase", `Current phase is not a regular document: ${config.currentPhase}`, ); if (targetStats.size > PHASE_BYTE_LIMIT) throw new SystemDocumentError( "document.phase-size", `Current phase exceeds the ${PHASE_BYTE_LIMIT}-byte limit`, ); const markdown = readFileSync(target, "utf8"); const authored = parseAuthoredDocument(markdown, config.prefix); validateDocumentPath(relative, authored.metadata, config.prefix); if ( authored.metadata.type !== "phase" || authored.metadata.id !== config.currentPhase ) throw new SystemDocumentError( "config.current-phase", `Current phase document does not match ${config.currentPhase}`, ); return { path: relative, metadata: authored.metadata, markdown }; return [ [metadata.spec, "spec"], ...(metadata.depends_on ?? []).map((id) => [id, "phase"] as const), ]; return []; ...(metadata.phase ? ([[metadata.phase, "phase"]] as const) : []), metadata.type === "plan" ? (metadata.depends_on ?? []) : []; if (document.metadata.type === "plan" && document.metadata.phase) { const phase = unique.get(document.metadata.phase); if ( phase?.metadata.type === "phase" && phase.metadata.spec !== document.metadata.spec ) diagnostics.push( diagnostic( "graph.forbidden-edge", document.path, `${document.metadata.phase} belongs to ${phase.metadata.spec}, not ${document.metadata.spec}`, ), ); } if ( document.metadata.type === "phase" || document.metadata.type === "plan" ) { if (document.metadata.type === "plan") {+73 / −16 text lines
import { createBoardRuntime } from "./board-runtime.js"; const board = createBoardRuntime(); const activateBoardAssessment = (cwd: string) => { board.beginAssessment(cwd); const active = pi.getActiveTools(); if (!active.includes(board.tool.name)) pi.setActiveTools([...active, board.tool.name]); boardAssessmentRunActive = true; }; const deactivateBoardAssessment = () => { const active = pi.getActiveTools(); if (active.includes(board.tool.name)) pi.setActiveTools(active.filter((name) => name !== board.tool.name)); board.endAssessment(); boardAssessmentRunActive = false; }; const activateBundleMigration = () => { bundleMigrationRunActive = true; }; const { startupRuntimeNotice } = await import("./startup-notice.js"); if (notified || ticket !== generation) return; const message = await startupRuntimeNotice(ctx.cwd); if (!message) return; if (ctx.hasUI) ctx.ui.notify(message, "warning"); notified = true; const { startupRuntimeState } = await import("./startup-notice.js"); if (ticket !== generation) return; const runtime = await startupRuntimeState(ctx.cwd); if (ticket !== generation) return; if (ctx.hasUI) { ctx.ui.setStatus( "the-system", runtime.active ? ctx.ui.theme.fg( "accent", ` ${runtime.prefix ?? "?"}${runtime.phaseLabel ? ` · ${runtime.phaseLabel}` : ""}`, ) : undefined, ); if (runtime.notice && !warningNotified) { warningNotified = true; ctx.ui.notify(runtime.notice, "warning"); } } void notifyOnce(ctx, ticket).catch((error) => void syncRuntimeIndicator(ctx, ticket).catch((error) => void notifyOnce(ctx, generation).catch((error) => void syncRuntimeIndicator(ctx, generation).catch((error) => return preflightFileMutation(ctx.cwd, "write", event.input, ui); return preflightFileMutation(ctx.cwd, "edit", event.input, ui); pi.registerTool(board.tool); await createSystemCommand(pi, activateArtifactSlot).handler(args, ctx);+83 / −59 text lines
import { lstatSync, mkdirSync, readFileSync, writeFileSync } from "node:fs"; inspectSystemConfig, systemConfigForInitialization,export type MachineState = Readonly<{ schemaVersion: number }>; removed: readonly string[];const CSS = ".system/system.css"; "# SYSTEM\n\nStable project identity, domain truths, architecture invariants, and non-negotiable conventions.\nKeep durable; do not put current tasks here.\n", "# MISSION\n\nCurrent objective and why it matters now.\nUpdate when project direction changes.\n", "# 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", "# RULES\n\nConcrete operating constraints: commands, safety, style, boundaries, and do/don't rules.\nKeep executable; avoid goals and rationale unless needed.\n",const validatePrefix = (prefix: string, state: MachineState) => {const validatePrefix = (prefix: string) => {const configSource = (root: string, prefix: string, state: MachineState) =>const configSource = (prefix: string, title: string, currentPhase?: string) => { prefix, schemaVersion: state.schemaVersion, title: projectTitle(root) }, state: MachineState = DEFAULT_MACHINE_STATE, const cssKind = requireKind(root, CSS, "file"); const boardKind = requireKind(root, BOARD_PATH, "file"); ? inspectSystemConfig(readFileSync(target(root, CONFIG), "utf8")) const upgrades: string[] = []; if (config && config.schemaVersion !== state.schemaVersion) upgrades.push( `${CONFIG} schemaVersion ${config.schemaVersion} -> ${state.schemaVersion}${inspected?.legacyStyleVersion ? "; remove styleVersion" : ""}`, ); if (config && !config.title) upgrades.push(`${CONFIG} add title "${projectTitle(root)}"`); if (cssKind === "file") upgrades.push(`${CSS} remove obsolete machine-owned asset`); if (boardKind === "missing") creates.push(BOARD_PATH); const rewrites = [ ...(inspected?.sourceSchemaVersion === undefined ? [] : [ `${CONFIG} schemaVersion ${inspected.sourceSchemaVersion} -> ${SCHEMA_VERSION}`, ]), ...(board?.sourceSchemaVersion === undefined ? [] : [ `${BOARD_PATH} schemaVersion ${board.sourceSchemaVersion} -> ${BOARD_SCHEMA_VERSION}`, ]), ]; prefix: config?.prefix ?? requested, approveRewrite = false, const inspection = inspectInitialization(cwd, requestedPrefix, state); const inspection = inspectInitialization(cwd, requestedPrefix); const removed: string[] = []; (approveUpgrades && configUpgrade) configSource(inspection.root, inspection.prefix, state), if ( kind(target(inspection.root, BOARD_PATH)) === "missing" || (approveRewrite && inspection.rewrites.some((item) => item.startsWith(`${BOARD_PATH} `))) ) { const current = kind(target(inspection.root, BOARD_PATH)) === "file" ? boardStateForInitialization( readFileSync(target(inspection.root, BOARD_PATH), "utf8"), inspection.prefix, ).state : emptyBoardState(); writeFileSync( target(inspection.root, BOARD_PATH), boardStateSource(current), kind(target(inspection.root, BOARD_PATH)) === "missing" ? { encoding: "utf8", flag: "wx" } : "utf8", ); changed.push(BOARD_PATH); } pending: approveRewrite ? [] : inspection.rewrites,+7 / −1 text lines
const url = pathToFileURL(file).href;new file mode 100644+47 / −0 text lines
import { readFileSync } from "node:fs";import path from "node:path";import { type Diagnostic, discoverDocumentBundles, discoverProjectRoot, indexBundleDocuments, parseSystemConfig, readCurrentPhase,} from "./documents.ts";export function loadProjectIndex(cwd: string) { const root = discoverProjectRoot(cwd); const config = parseSystemConfig( readFileSync(path.join(root, ".system/config.json"), "utf8"), ); const discovery = discoverDocumentBundles(root); const indexed = indexBundleDocuments(discovery.sources, config.prefix); const phaseDiagnostics: Diagnostic[] = []; try { readCurrentPhase(root, config); } catch (error) { phaseDiagnostics.push({ code: "config.current-phase", path: ".system/config.json", message: error instanceof Error ? error.message : String(error), }); } return { root, prefix: config.prefix, ...(config.currentPhase ? { currentPhase: config.currentPhase } : {}), documents: indexed.documents.map((document) => ({ ...document, markdown: discovery.sources.find((source) => source.path === document.path) ?.markdown ?? "", })), diagnostics: [ ...discovery.diagnostics, ...indexed.diagnostics, ...phaseDiagnostics, ], };}export type ProjectIndex = ReturnType<typeof loadProjectIndex>;+5 / −6 text lines
for (const item of result.upgrades) console.log(`UPGRADE ${item}`); for (const item of result.rewrites) console.log(`REWRITE ${item}`); for (const item of result.removed) console.log(`REMOVED ${item}`);+13 / −6 text lines
import type { SystemRuntimeState } from "./system.ts"; if (!existsSync(path.join(root, ".system"))) return undefined; const { runtimeNotice } = await import("./system.ts"); return runtimeNotice(cwd); if (!existsSync(path.join(root, ".system"))) return { active: false }; const { runtimeState } = await import("./system.ts"); return runtimeState(cwd);}export async function startupRuntimeNotice( cwd: string,): Promise<string | undefined> { return (await startupRuntimeState(cwd)).notice;+2 / −0 text lines
+72 / −37 text lines
import { loadProjectIndex } from "./project-index.ts"; "assess",const NON_LIFECYCLE = new Set(["init", "doctor", "view", "book", "edit"]); await runSystemInit(parsed.rest, ctx); if (ARTIFACT_SUBCOMMANDS.has(parsed.subcommand)) activateArtifactTool(); "board", "assess [instructions]", ...inspection.upgrades.map((item) => `Upgrade: ${item}`), ...inspection.rewrites.map((item) => `Update: ${item}`), ...result.removed.map((item) => `Removed: ${item}`), if ( !configMigration || !(await ctx.ui.confirm( "Should System bundles be migrated by agent?", `Machine schema updated mechanically.\n${configMigration}`, )) ) return; await ctx.waitForIdle(); activateBundleMigration?.(); pi.sendUserMessage( systemPromptFor( "init", [ "The human approved agent-led bundle migration.", "Machine config and board schema markers are already current; do not edit them.", `Source: ${configMigration}`, "Inspect existing bundles and migrate obsolete structure and content to the current contracts.", ].join("\n"), ), );function projectIndex(cwd: string) { const root = discoverProjectRoot(cwd); const config = parseSystemConfig( readFileSync(path.join(root, ".system/config.json"), "utf8"), ); const discovery = discoverDocumentBundles(root); const indexed = indexBundleDocuments(discovery.sources, config.prefix); return { root, documents: indexed.documents.map((document) => ({ ...document, markdown: discovery.sources.find((source) => source.path === document.path) ?.markdown ?? "", })), diagnostics: [...discovery.diagnostics, ...indexed.diagnostics], };} return renderSystemBookSite(projectIndex(cwd)).file; return renderSystemBookSite(loadProjectIndex(cwd)).file; documents: ReturnType<typeof projectIndex>["documents"], documents: ReturnType<typeof loadProjectIndex>["documents"],+43 / −15 text lines
Config schemaVersion is 0.Approved phases and plans are immutable; create a new artifact instead.const BOARD_CONTRACT = `# The System board contractBoard state lives only in .system/board.json at schema version 0.Specs and plans use todo|done; issues use open|done.A spec may be done without plans, but cannot be done while any linked plan is todo.Issues never change spec state.Assessment proposes board changes for human review; it never applies them.`; init: `Initialize or upgrade .system only after explicit human approval. init: `Initialize .system only after explicit human approval.Schema upgrades are init-owned and must be reported before mutation.`,The /system init command updates config and board schema markers mechanically.When it reports a prior config schema, migrate existing bundles to schema 0 and the current contracts.Preserve current meaning where compatible; do not preserve obsolete bundle fields or add runtime migration code.`,Do not initialize, repair, rename, delete, or upgrade files.`,Do not initialize, repair, rename, delete, or rewrite files.`, phase: `Create or amend terse phase artifacts for large specs as context requires.Break specs into high-level steps, dependencies, risks, and completion criteria.Use status: draft until approval.Status: approved requires human approval and makes each phase immutable.`, plan: `Create or amend terse implementation plans for specs or phases as context requires. assess: `${BOARD_CONTRACT}Assess current implementation progress for the requested specs, plans, and issues.Inspect current code and tests deeply enough to justify each proposed state.Do not edit bundles or .system/board.json.Call system_board_propose with evidence-backed changes only.Omit items whose state cannot be assessed responsibly.`, phase: `Inspect MISSION and the current phase first.Create, amend, or transition one terse project-wide operating phase as context requires.A phase is a sub-mission and decision posture for an epoch, never a work breakdown or delivery milestone.Capture its sub-mission, ranked priorities, decision defaults, explicit non-goals, and observable exit criteria.Decision defaults cover concerns such as compatibility, migrations, stability, quality, speed, experimentation, and debt only when relevant.If it contains implementation steps, move those steps to a plan.Use a short label suitable for the Pi footer.When transitioning, create or amend the phase first, then update config currentPhase only after explicit human confirmation.Do not mutate MISSION.`, plan: `Create or amend terse implementation plans for specs as context requires.+200 / −40 text lines
currentPhase?: string; label?: string;const GROUPS = ["law", "spec", "phase", "plan", "issue", "research"] as const;const GROUPS = ["law", "phase", "spec", "plan", "issue", "research"] as const; "spec", "spec", bookBody(title, rendered, diagnostics, directory), bookBody(title, rendered, diagnostics, directory, input.currentPhase),export function renderSystemBoardSite( input: RenderInput, board: BoardState, proposals: readonly BoardProposal[],): RenderOutput { const directory = createOutput(input); const rendered = renderAll(input, directory); const diagnostics = [...input.diagnostics, ...referenceDiagnostics(input)]; writePages(directory, rendered, diagnostics, "book"); const title = `${projectName(input.root)} Board`; const body = boardBody(title, input, rendered, board, proposals).replaceAll( pathToFileURL(`${directory}${path.sep}`).href, "/", ); writeFileSync( path.join(directory, "index.html"), htmlPage( title, body, "board", "assets/mermaid.min.js", "assets/minisearch.js", ), "utf8", ); return { file: path.join(directory, "index.html"), directory };} ); const current = authored.find( (document) => document.id === input.currentPhase, ); return [ ...cores.filter( (document) => document.id === "CORE-SYSTEM" || document.id === "CORE-MISSION", ), ...(current ? [current] : []), ...cores.filter((document) => document.id === "CORE-RULES"), ...authored.filter((document) => document !== current), ];}; current: document.metadata.id === input.currentPhase, current?: boolean; 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>`; 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>`; 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>`; 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>`; return [ metadata.spec, ...(metadata.phase ? [metadata.phase] : []), ...dependencyIds(metadata), ]; return [metadata.spec, ...dependencyIds(metadata)]; metadata.type === "plan" ? (metadata.depends_on ?? []) : [];const boardBody = ( title: string, input: RenderInput, rendered: readonly RenderedDocument[], board: BoardState, proposals: readonly BoardProposal[],): string => { const authored = new Map( input.documents.map((document) => [document.metadata.id, document]), ); const pages = new Map(rendered.map((document) => [document.id, document])); const specs = input.documents .filter((document) => document.metadata.type === "spec") .sort((left, right) => compareBoardItems(left, right, board)); const issues = input.documents .filter((document) => document.metadata.type === "issue") .sort((left, right) => compareBoardItems(left, right, board)); const plansBySpec = new Map<string, RenderDocumentInput[]>(); for (const document of input.documents) { if (document.metadata.type !== "plan") continue; const plans = plansBySpec.get(document.metadata.spec) ?? []; plans.push(document); plansBySpec.set(document.metadata.spec, plans); } for (const plans of plansBySpec.values()) plans.sort((left, right) => compareBoardItems(left, right, board)); const proposalById = new Map( proposals.map((proposal) => [proposal.id, proposal]), ); const todo = specs.filter( (document) => boardStateFor(board, document.metadata) !== "done", ).length; const open = issues.filter( (document) => boardStateFor(board, document.metadata) !== "done", ).length; const specCards = specs .map((spec) => { const plans = plansBySpec.get(spec.metadata.id) ?? []; const donePlans = plans.filter( (plan) => boardStateFor(board, plan.metadata) === "done", ).length; const planSummary = plans.length ? ` · ${donePlans}/${plans.length} ${plans.length === 1 ? "plan" : "plans"} done` : ""; 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>`; }) .join(""); const issueCards = issues .map((issue) => { const refs = issue.metadata.type === "issue" ? issue.metadata.specs : []; const links = refs .map((id) => { const target = authored.get(id); return `<a href="#${esc(id)}">→ ${esc(target?.metadata.title ?? id)}</a>`; }) .join(""); 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>`; }) .join(""); 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>`;};const compareBoardItems = ( left: RenderDocumentInput, right: RenderDocumentInput, board: BoardState,) => Number(boardStateFor(board, left.metadata) === "done") - Number(boardStateFor(board, right.metadata) === "done") || compareDocuments(left, right);const boardDisclosure = ( document: RenderDocumentInput, rendered: RenderedDocument | undefined, suffix: string,) => `<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>`;const boardStateButton = (id: string, state: string) => `<button class="board-state" type="button" data-board-state="${esc(state)}" aria-label="Toggle ${esc(id)} state">${esc(state.toUpperCase())}</button>`;const boardPlan = ( plan: RenderDocumentInput, rendered: RenderedDocument | undefined, board: BoardState, proposal?: BoardProposal,) => { const state = boardStateFor(board, plan.metadata); 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>`;};const boardAssessment = (entry: BoardState["items"][string] | undefined) => entry ? `<span class="board-assessment" data-assessment data-source="${esc(entry.source)}" data-updated-at="${esc(entry.updatedAt)}">${esc(entry.source)} · ${esc(entry.updatedAt)}</span>` : '<span class="board-assessment" data-assessment>default</span>';const boardProposal = (proposal?: BoardProposal) => proposal ? `<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>` : "";const boardCss = () => String.raw`body[data-mode=board]{padding:10px;background:var(--bg);font:12px/1.35 ui-monospace,SFMono-Regular,Menlo,monospace}.board-top{display:grid;grid-template-columns:1fr auto;gap:10px;align-items:end;border-bottom:2px solid var(--text);padding-bottom:7px;margin-bottom:7px}.board-brand{color:var(--text);font-size:17px;font-weight:900;text-decoration:none;text-transform:uppercase}.board-top p{margin:2px 0 0;color:var(--muted);font-size:10px}.board-top>span{color:var(--muted)}.board-grid{display:grid;grid-template-columns:minmax(0,3fr) minmax(240px,1fr);gap:7px;align-items:start}.board-region{border:1px solid var(--line);background:var(--panel);min-width:0}.board-region>h1{font-size:11px;letter-spacing:.1em;text-transform:uppercase;margin:0;padding:6px 7px;border-bottom:1px solid var(--line)}.board-region>h1 span{float:right;color:var(--muted);font-weight:400}.board-spec-list{display:grid;grid-template-columns:repeat(auto-fit,minmax(290px,1fr));gap:6px;padding:6px;align-items:start}.board-issue-list{display:grid;gap:5px;padding:6px}.board-spec{border:2px solid var(--accent);background:var(--page);min-width:0}.board-spec.is-done{border-color:var(--line);background:var(--bg)}.board-row{display:grid;grid-template-columns:minmax(0,1fr) auto;gap:6px;align-items:start;padding:6px 7px}.board-bundle{min-width:0}.board-bundle>summary{cursor:pointer;list-style:none;display:grid;grid-template-columns:minmax(0,1fr);padding-left:14px;position:relative}.board-bundle>summary::-webkit-details-marker{display:none}.board-bundle>summary::before{content:'▸';position:absolute;left:0;color:var(--accent)}.board-bundle[open]>summary::before{content:'▾'}.board-kind{display:block;font-size:9px;color:var(--muted);text-transform:uppercase}.board-bundle>summary strong{display:block;font:700 13px/1.15 system-ui,sans-serif;margin-top:1px;overflow-wrap:anywhere}.is-done>.board-row .board-bundle>summary strong{color:var(--muted);text-decoration:line-through}.board-details{grid-column:1/-1;margin:6px 0 0 14px;border-top:1px solid var(--line);padding-top:6px;font-family:system-ui,sans-serif}.board-details>.system-article{border:0;padding:0;background:transparent}.board-details .mast{display:none}.board-details .ledger{margin:.35rem 0}.board-details h1{font-size:19px}.board-details h2{font-size:16px}.board-details h3{font-size:14px}.board-details pre{padding:.6rem}.board-plans{display:grid;gap:4px;border-top:1px solid var(--line);background:var(--bg);padding:4px}.board-plan{border-left:3px solid var(--accent);background:var(--page)}.board-plan.is-done{border-left-color:var(--line);background:var(--bg)}.board-plan .board-row{padding:4px 5px}.board-issue{border-left:3px solid var(--warn);background:var(--page)}.board-issue.is-done{border-left-color:var(--line);background:var(--bg)}.board-issue .board-bundle>summary::before{color:var(--warn)}.board-links{display:grid;gap:2px;padding:0 7px 6px 21px;font-size:10px}.board-state{border:1px solid var(--accent);background:var(--bg);color:var(--accent);font:9px ui-monospace,monospace;padding:3px 5px;cursor:pointer;min-width:43px}.board-issue .board-state{border-color:var(--warn);color:var(--warn)}.is-done>.board-row>.board-state,.board-plan.is-done .board-state,.board-issue.is-done .board-state{border-color:var(--line);color:var(--text)}.board-state:disabled{cursor:not-allowed;border-color:var(--line);color:var(--muted)}.board-assessment{display:block;color:var(--muted);font-size:9px;padding:0 7px 5px 21px}.board-proposal{display:grid;grid-template-columns:minmax(0,1fr) auto;gap:6px;border-top:1px solid var(--info);padding:5px 7px;color:var(--muted)}.board-proposal b{display:block;color:var(--info);font-size:9px}.board-proposal button{border:1px solid var(--info);background:var(--bg);color:var(--info);font:9px ui-monospace,monospace;padding:3px 6px}.board-empty{color:var(--muted);margin:6px}.board-notice{position:fixed;right:10px;bottom:10px;max-width:min(34rem,calc(100vw - 20px));background:var(--panel);border:1px solid var(--line);padding:7px;display:none}.board-notice.is-visible{display:block}.board-notice.is-error{border-color:var(--error);color:var(--error)}@media(max-width:760px){.board-top,.board-grid{grid-template-columns:1fr}.board-spec-list{grid-template-columns:1fr}.board-top>span{text-align:left}}`;const boardScript = () => String.raw`const root=document.body;const notice=document.querySelector('[data-board-notice]');const direct=(node,selector)=>[...node.children].filter(child=>child.matches(selector));const sort=(node,selector)=>direct(node,selector).sort((a,b)=>Number(a.classList.contains('is-done'))-Number(b.classList.contains('is-done'))||(a.dataset.id||'').localeCompare(b.dataset.id||'')).forEach(item=>node.append(item));const message=(text,error=false)=>{notice.textContent=text;notice.className='board-notice is-visible'+(error?' is-error':'');setTimeout(()=>notice.className='board-notice',3000)};const stateOf=card=>card.dataset.state||card.dataset.defaultState;const age=value=>{if(!value)return'default';const days=Math.max(0,Math.floor((Date.now()-Date.parse(value))/86400000));return days===0?'today':days===1?'1 day ago':days+' days ago'};function refresh(snapshot){for(const card of document.querySelectorAll('[data-board-item]')){const entry=snapshot.items[card.dataset.id];const state=entry?.state||card.dataset.defaultState;card.dataset.state=state;card.classList.toggle('is-done',state==='done');const button=card.querySelector(':scope > .board-row > .board-state');button.textContent=state.toUpperCase();const assessment=card.querySelector(':scope > [data-assessment]');assessment.textContent=entry?entry.source+' · '+age(entry.updatedAt):'default';assessment.title=entry?.updatedAt||''}for(const spec of document.querySelectorAll('[data-kind="spec"]')){const button=spec.querySelector(':scope > .board-row > .board-state');const unfinished=spec.querySelector('[data-kind="plan"]:not(.is-done)');button.disabled=!spec.classList.contains('is-done')&&Boolean(unfinished);button.title=button.disabled?'Finish every plan first':'No plan states will change'}document.querySelectorAll('[data-plan-list]').forEach(list=>sort(list,'[data-kind="plan"]'));sort(document.querySelector('[data-spec-list]'),'[data-kind="spec"]');sort(document.querySelector('[data-issue-list]'),'[data-kind="issue"]');document.querySelector('[data-spec-count]').textContent=String(document.querySelectorAll('[data-kind="spec"]:not(.is-done)').length);document.querySelector('[data-issue-count]').textContent=String(document.querySelectorAll('[data-kind="issue"]:not(.is-done)').length)}async function post(path,payload){const response=await fetch(path,{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify(payload)});const result=await response.json();if(!response.ok)throw new Error(result.error||'Board update failed');return result}root.addEventListener('click',async event=>{const proposal=event.target.closest('[data-apply-proposal]');const button=event.target.closest('.board-state');if(!proposal&&!button)return;event.preventDefault();const card=(proposal||button).closest('[data-board-item]');try{if(proposal){const result=await post('/api/proposal',{id:card.dataset.id,state:proposal.dataset.applyProposal});proposal.closest('[data-proposal]').remove();refresh(result);message('Assessment applied.')}else{const state=stateOf(card);const target=state==='done'?card.dataset.defaultState:'done';const result=await post('/api/state',{id:card.dataset.id,state:target});refresh(result);message('Board updated.')}}catch(error){message(error.message,true)}});for(const assessment of document.querySelectorAll('[data-assessment]'))if(assessment.dataset.updatedAt)assessment.textContent=assessment.dataset.source+' · '+age(assessment.dataset.updatedAt);`; currentPhase?: string, const utilities = `<div class="nav-utils"><a href="#book-overview">Top</a><a href="#reference-graph">Reference graph</a>${diagnosticNav}</div>`; const nav = bookNav(documents, utilities); const nav = bookNav(documents, utilities, currentPhase); const diagnosticStat = diagnostics.length ? `<p class="stats"><span class="bad">${diagnostics.length} diagnostics</span></p>` : ""; 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 const current = documents.find((document) => document.id === currentPhase); const stats = [ ...(current ? [ `<span class="active-phase">Current phase <a href="#${esc(current.id)}">${esc(current.label ?? current.title)}</a></span>`, ] : []), ...(diagnostics.length ? [`<span class="bad">${diagnostics.length} diagnostics</span>`] : []), ]; const status = stats.length ? `<p class="stats">${stats.join("")}</p>` : ""; 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 `<section id="${esc(document.id)}" class="book-section">${bookArticle(document.article, documents, outputRoot)}</section>`, `<section id="${esc(document.id)}" class="book-section${document.id === currentPhase ? " current-phase-section" : ""}">${bookArticle(document.article, documents, outputRoot)}</section>`, currentPhase?: string,const navItem = (item: RenderedDocument): string => {const navItem = (item: RenderedDocument, current = false): string => { return `<a href="#${esc(item.id)}">${esc(label)}</a>`; return `<a href="#${esc(item.id)}"${current ? ' class="current-phase-link" aria-current="true"' : ""}>${current ? "● " : ""}${esc(label)}</a>`; node.type === "phase" || node.type === "plan" ? node.refs.filter((id) => id.includes(`-${node.type.toUpperCase()}-`)) : []; node.type === "plan" ? node.refs.filter((id) => id.includes("-PLAN-")) : [];: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}@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}}body[data-mode=book]{overflow-x:hidden;--book-gutter:26px;--book-nav-width:15rem;--book-top-height:76px}*{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}}*{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}}+142 / −26 text lines
readCurrentPhase, SCHEMA_VERSION,const CONFIG_PATH = ".system/config.json"; `${systemPrompt}\n\n# The System governance error\n\n${message}\n\nDo not mutate .system until /system doctor resolves this governance error.`; `${systemPrompt}\n\n# The System governance error\n\n${message}\n\nDo not mutate .system until this governance error is resolved.`; const blocks = CORES.map((name) => coreBlock(root, name)).filter( const [system, mission, rules] = CORES.map((name) => coreBlock(root, name)); let phase: string | undefined; const configFile = path.join(root, CONFIG_PATH); if (existsSync(configFile)) { const config = parseSystemConfig(readFileSync(configFile, "utf8")); const current = readCurrentPhase(root, config); if (current) phase = `## Current phase: ${current.metadata.title} · ${current.metadata.label}\n\n${current.markdown}`; } const blocks = [system, mission, phase, rules].filter(export function runtimeNotice(cwd: string): string | undefined {export type SystemRuntimeState = Readonly<{ active: boolean; prefix?: string; phaseLabel?: string; notice?: string;}>;const INCOMPLETE_NOTICE = "The System is incomplete or invalid; run /system init before governed work.";const SCHEMA_NOTICE = `The System schema does not match ${SCHEMA_VERSION}; run /system init to update it.`;export function runtimeState(cwd: string): SystemRuntimeState { if (!existsSync(path.join(root, ".system"))) return undefined; if (!existsSync(path.join(root, ".system"))) return { active: false }; if ( inspection.cores.some(({ state }) => state === "missing") ) return "The System is incomplete or invalid; run /system init before governed work."; if (inspection.upgrades.length > 0) return "The System schema refresh is available; run /system init to inspect and approve it."; return undefined; inspection.cores.some(({ state }) => state === "missing"); let phaseLabel: string | undefined; if (inspection.prefix) { const config = parseSystemConfig( readFileSync(path.join(root, CONFIG_PATH), "utf8"), ); phaseLabel = readCurrentPhase(root, config)?.metadata.label; } const notice = incomplete ? INCOMPLETE_NOTICE : undefined; return { active: true, ...(inspection.prefix ? { prefix: inspection.prefix } : {}), ...(phaseLabel ? { phaseLabel } : {}), ...(notice ? { notice } : {}), }; return "The System is incomplete or invalid; run /system init before governed work."; return { active: true, notice: INCOMPLETE_NOTICE };type MutationOptions = Readonly<{ bundleMigration?: boolean }>; parseSystemConfig( readFileSync(path.join(root, ".system/config.json"), "utf8"), ).prefix; parseSystemConfig(readFileSync(path.join(root, CONFIG_PATH), "utf8")).prefix;const preflightCurrentPhase = async ( root: string, target: string, kind: MutationKind, input: MutationInput, ui: GovernanceUI,): Promise<GateResult> => { const stats = lstatSync(target, { throwIfNoEntry: false }); if (!stats?.isFile()) return blocked( "The System config must be initialized before selecting a phase.", ); try { const current = parseSystemConfig(readFileSync(target, "utf8")); const candidate = parseSystemConfig(candidateContent(target, kind, input)); if ( candidate.prefix !== current.prefix || candidate.schemaVersion !== current.schemaVersion || candidate.title !== current.title ) return blocked( "The System config mutation may only change currentPhase.", ); if (candidate.schemaVersion !== SCHEMA_VERSION) return blocked( `The System schema must be ${SCHEMA_VERSION} before selecting a phase.`, ); if (candidate.currentPhase === current.currentPhase) return blocked( candidate.currentPhase ? `The System phase is already ${candidate.currentPhase}.` : "The System already has no current phase.", ); const phase = readCurrentPhase(root, candidate); if (!ui.hasUI) return blocked( `The System blocked phase ${candidate.currentPhase ? "activation" : "deactivation"}: interactive UI is unavailable.`, ); const approve = phase ? `Activate: ${phase.metadata.label} · ${phase.metadata.title}` : "Deactivate current phase"; const deny = `Deny: keep ${current.currentPhase ?? "no current phase"}`; const decision = await ui.select("The System phase transition", [ approve, deny, ]); if (decision === approve) return undefined; return blocked( decision === deny ? "The System phase transition was denied." : "The System phase transition was cancelled.", ); } catch (error) { return blocked( `The System rejected the config change: ${error instanceof Error ? error.message : String(error)}`, ); }}; options: MutationOptions = {}, relative !== CONFIG_PATH && `The System requires document bundles at .system/<type-plural>/<ID>-<slug>/<file>: ${relative}.`, if (options.bundleMigration) { if (!location.index || !targetStats?.isFile()) return blocked( `The System bundle migration may only update an existing index.md: ${relative}.`, ); try { const content = candidateContent(target, kind, input); const discovery = discoverDocumentBundles(root); const findings = validateBundleCandidate( discovery.sources, { path: relative, markdown: content }, projectPrefix(root), ); if (findings.length > 0) return blocked(diagnosticsReason(findings)); return undefined; } catch (error) { return blocked( `The System candidate validation failed: ${error instanceof Error ? error.message : String(error)}`, ); } } if ( (current?.type === "phase" || current?.type === "plan") && current.status === "approved" ) if (current?.type === "plan" && current.status === "approved") `The System blocked mutation of approved ${current.type} ${current.id}; create a new artifact instead.`, (resolved.metadata.type === "phase" || resolved.metadata.type === "plan") && resolved.metadata.type === "plan" && if (current?.type === "plan" && current.status !== "approved") { `The System blocked approval of ${resolved.metadata.type} ${resolved.metadata.id}: interactive UI is unavailable.`, if (resolved.metadata.type !== "spec") return undefined;