import assert from "node:assert/strict"; import { chmodSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync, } from "node:fs"; import { tmpdir } from "node:os"; import path from "node:path"; import type { AutocompleteItem } from "@earendil-works/pi-tui"; import { afterEach, describe, it } from "vitest"; import registerTheSystem from "../index.ts"; import { editorCandidates, parseEditorCommand } from "../open-editor.ts"; import { loadProjectIndex } from "../project-index.ts"; import { composeSystemSection, runtimeState } from "../system.ts"; import { createSystemCommand } from "../system-command.ts"; import { systemPromptFor } from "../system-prompts.ts"; import { renderSystemBookSite } from "../system-renderer.ts"; const roots: string[] = []; const temp = () => { const root = mkdtempSync(path.join(tmpdir(), "the-system-command-")); roots.push(root); return root; }; const write = (root: string, relative: string, content: string) => { const target = path.join(root, relative); mkdirSync(path.dirname(target), { recursive: true }); writeFileSync(target, content, "utf8"); }; type CapturedTool = { execute: ( toolCallId: string, params: unknown, signal: undefined, onUpdate: undefined, ctx: unknown, ) => Promise; }; const validSystem = (root: string) => { for (const directory of ["specs", "phases", "plans", "issues", "research"]) mkdirSync(path.join(root, ".system", directory), { recursive: true }); for (const file of ["SYSTEM.md", "MISSION.md", "RULES.md"]) write(root, `.system/${file}`, `# ${file}\n`); write(root, ".system/config.json", '{"prefix":"PX","schemaVersion":0}'); write(root, ".system/board.json", '{"schemaVersion":0,"items":{}}'); write( root, ".system/specs/PX-SPEC-SPEC0001-contract/index.md", [ "---", "id: PX-SPEC-SPEC0001", "type: spec", "title: Contract", "extra:", " nested: yes", "---", "", "# Contract", "", "[Local details](#details)", "", "## Details", "", "> [!NOTE]", "> Alert body.", "", "Term", ": Definition", "", "```mermaid", "flowchart TD; A-->B;", "```", "", "Math $x+1$.", "", "```ts", "const ok = true;", "```", "", "[Interactive prototype](./mockup-card.html)", "", "[Architecture diagram](./architecture.svg)", "", "![Screen](./screen%20shot.png)", "", "[Walkthrough](./walkthrough.webm)", "", "[Supporting notes](./notes.md)", "", "An inline [prototype link](./mockup-card.html) stays inline.", "", "raw", ].join("\n"), ); write( root, ".system/specs/PX-SPEC-SPEC0001-contract/mockup-card.html", "
Mockup card
", ); write( root, ".system/specs/PX-SPEC-SPEC0001-contract/architecture.svg", '', ); write(root, ".system/specs/PX-SPEC-SPEC0001-contract/screen shot.png", "png"); write( root, ".system/specs/PX-SPEC-SPEC0001-contract/walkthrough.webm", "video", ); write( root, ".system/specs/PX-SPEC-SPEC0001-contract/notes.md", "# Supporting notes\n", ); write( root, ".system/phases/PX-PHASE-PHASE001-delivery/index.md", "---\nid: PX-PHASE-PHASE001\ntype: phase\ntitle: Delivery\nlabel: delivery\n---\n\n# Delivery\n", ); write( root, ".system/phases/PX-PHASE-PHASE002-alpha/index.md", "---\nid: PX-PHASE-PHASE002\ntype: phase\ntitle: Alpha\nlabel: alpha\n---\n\n# Alpha\n", ); write( root, ".system/plans/PX-PLAN-PLAN0001-build/index.md", "---\nid: PX-PLAN-PLAN0001\ntype: plan\ntitle: Build\nspec: PX-SPEC-SPEC0001\nstatus: draft\n---\n\n# Build\n", ); write( root, ".system/plans/PX-PLAN-PLAN0002-alpha/index.md", "---\nid: PX-PLAN-PLAN0002\ntype: plan\ntitle: Alpha\nspec: PX-SPEC-SPEC0001\nstatus: draft\ndepends_on: [PX-PLAN-PLAN0001]\n---\n\n# Alpha\n", ); }; afterEach(() => { for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true }); }); describe("/system command", () => { it("delivers stage content after human instructions and board state", () => { const heading = "# /system plan\n\n"; const bare = systemPromptFor("plan", ""); assert.ok(bare.startsWith(heading)); const stage = bare.slice(heading.length); assert.ok(stage.trim().length > 0); const full = systemPromptFor("plan", "login flow", "# Board\n- x"); assert.equal( full, `# /system plan: login flow\n\n# Board\n- x\n\n${stage}`, ); }); it("registers /system and deferred scoped tools upfront", () => { const commands: string[] = []; const tools: string[] = []; registerTheSystem({ registerCommand: (name: string) => commands.push(name), registerTool: (tool: { name: string }) => tools.push(tool.name), on() {}, } as never); assert.deepEqual(commands, ["system"]); assert.deepEqual(tools, [ "system_bundle_slot", "system_board_propose", "system_board_update", ]); }); it("runs deferred tools outside System stages without changing model tool membership", async () => { const project = temp(); validSystem(project); let boardTool: CapturedTool | undefined; let boardUpdateTool: CapturedTool | undefined; let bundleSlotTool: CapturedTool | undefined; registerTheSystem({ registerCommand() {}, registerTool(definition: { name: string }) { if (definition.name === "system_board_propose") boardTool = definition as unknown as CapturedTool; if (definition.name === "system_board_update") boardUpdateTool = definition as unknown as CapturedTool; if (definition.name === "system_bundle_slot") bundleSlotTool = definition as unknown as CapturedTool; }, on() {}, sendUserMessage() {}, } as never); const ctx = { cwd: project, mode: "interactive", hasUI: false, isIdle: () => true, abort() {}, sessionManager: { getSessionId: () => project, getBranch: () => [], }, ui: { notify() {}, setStatus() {}, theme: { fg: (_color: string, text: string) => text }, }, }; assert.ok(boardTool); await boardTool.execute( "proposal", { items: [ { id: "PX-SPEC-SPEC0001", state: "todo", rationale: "Implementation remains incomplete.", }, ], }, undefined, undefined, ctx, ); assert.deepEqual( JSON.parse( readFileSync(path.join(project, ".system/board.json"), "utf8"), ), { schemaVersion: 0, items: {} }, ); const cleared = await boardTool.execute( "assessment-no-changes", { items: [] }, undefined, undefined, ctx, ); assert.ok(cleared && typeof cleared === "object" && "details" in cleared); assert.deepEqual(cleared.details, { items: [] }); assert.ok(boardUpdateTool); const updateItems = ( items: { id: string; state: string; note: string }[], ) => ({ items }); await assert.rejects( boardUpdateTool.execute( "exec-invalid", updateItems([ { id: "PX-SPEC-SPEC0001", state: "done", note: "Claimed without finished plans.", }, ]), undefined, undefined, ctx, ), /cannot be done while plans remain todo/, ); assert.deepEqual( JSON.parse( readFileSync(path.join(project, ".system/board.json"), "utf8"), ), { schemaVersion: 0, items: {} }, ); await boardUpdateTool.execute( "exec-update", updateItems([ { id: "PX-PLAN-PLAN0001", state: "done", note: "Slice one verified.", }, { id: "PX-PLAN-PLAN0002", state: "done", note: "Slice two verified.", }, { id: "PX-SPEC-SPEC0001", state: "done", note: "Fresh verification passed.", }, ]), undefined, undefined, ctx, ); const applied = JSON.parse( readFileSync(path.join(project, ".system/board.json"), "utf8"), ); assert.equal(applied.items["PX-SPEC-SPEC0001"].state, "done"); assert.equal(applied.items["PX-SPEC-SPEC0001"].source, "agent"); assert.equal( applied.items["PX-SPEC-SPEC0001"].note, "Fresh verification passed.", ); assert.ok(bundleSlotTool); await bundleSlotTool.execute( "slot-one", { type: "spec", title: "First contract" }, undefined, undefined, ctx, ); await bundleSlotTool.execute( "slot-two", { type: "issue", title: "Second concern" }, undefined, undefined, ctx, ); }); it("discovers vertical slicing generally and format skills only in valid projects", async () => { let discover: ((event: { cwd: string }) => Promise) | undefined; registerTheSystem({ registerCommand() {}, registerTool() {}, on(event: string, handler: (...args: never[]) => unknown) { if (event === "resources_discover") discover = handler as never; }, } as never); const skills = path.resolve(import.meta.dirname, "../skills"); const genericSkills = [path.join(skills, "vertical-slices")]; const inactive = temp(); assert.deepEqual(await discover?.({ cwd: inactive }), { skillPaths: genericSkills, }); mkdirSync(path.join(inactive, ".system")); assert.deepEqual(await discover?.({ cwd: inactive }), { skillPaths: genericSkills, }); const active = temp(); validSystem(active); assert.deepEqual(await discover?.({ cwd: active }), { skillPaths: [ ...genericSkills, path.join(skills, "the-system-documents"), path.join(skills, "the-system-markdown"), path.join(skills, "the-system-board"), path.join(skills, "the-system-exec"), path.join(skills, "the-system-gfm"), path.join(skills, "the-system-tex"), path.join(skills, "the-system-mermaid"), ], }); write(active, ".system/config.json", '{"prefix":"PX","schemaVersion":4}'); assert.deepEqual(await discover?.({ cwd: active }), { skillPaths: genericSkills, }); }); 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( composeSystemSection(project) ?? "", /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((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; systemPromptOptions: { forceSystemPrompt?: string; sections: Record; }; }, ctx: unknown, ) => Promise) | 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((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"}', ); const systemPromptOptions = { sections: {} as Record }; await beforeAgentStart?.( { systemPrompt: "BASE", systemPromptOptions }, ctx, ); assert.match( systemPromptOptions.sections["the_system"]!, /# The System project law/, ); await waitForStatus("accent: PX · delivery"); }); it("offers subcommand completions and help", async () => { const command = createSystemCommand({ sendUserMessage() {} } as never); assert.deepEqual( ( command.getArgumentCompletions?.("sp") as AutocompleteItem[] | null )?.map((item) => item.value), ["spec", "spec-verify"], ); assert.deepEqual( ( command.getArgumentCompletions?.("ed") as AutocompleteItem[] | null )?.map((item) => item.value), ["edit"], ); assert.deepEqual( ( command.getArgumentCompletions?.("bo") as AutocompleteItem[] | null )?.map((item) => item.value), ["book", "board"], ); assert.equal(command.getArgumentCompletions?.("doctor"), null); const notices: string[] = []; await command.handler("", { cwd: temp(), waitForIdle: async () => {}, ui: { notify: (message: string) => notices.push(message) }, } as never); assert.match(notices[0] ?? "", /\/system /); }); it("opens the board directly through its runtime", async () => { const project = temp(); validSystem(project); const notices: string[] = []; const command = createSystemCommand({ sendUserMessage() {} } as never, { openBook: async (cwd, page) => { assert.equal(page, "/board.html"); 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/); }); it("runs init directly after confirmation", async () => { const project = temp(); const command = createSystemCommand({ sendUserMessage() {} } as never); const notices: string[] = []; await command.handler("init PX", { cwd: project, waitForIdle: async () => {}, ui: { confirm: async () => true, notify: (message: string) => notices.push(message), }, } as never); assert.match(notices[0] ?? "", /Initialized The System/); assert.match(notices[0] ?? "", /\/reload to activate System format skills/); assert.deepEqual( JSON.parse( readFileSync(path.join(project, ".system/config.json"), "utf8"), ), { prefix: "PX", schemaVersion: 0, title: path.basename(project) }, ); assert.match( readFileSync(path.join(project, ".system/SYSTEM.md"), "utf8"), /Stable project identity/, ); }); 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, ); }); it("reuses existing prefix on init rerun", async () => { const project = temp(); validSystem(project); const notices: string[] = []; const command = createSystemCommand({ sendUserMessage() {} } as never); await command.handler("init", { cwd: project, waitForIdle: async () => {}, ui: { input: async () => assert.fail("must not ask for prefix"), confirm: async (_title: string, summary: string) => { assert.match(summary, /Prefix: PX/); return true; }, notify: (message: string) => notices.push(message), }, } as never); assert.match(notices[0] ?? "", /Initialized The System/); assert.doesNotMatch(notices[0] ?? "", /\/reload/); }); it("injects lifecycle prompts without tool activation", async () => { const project = temp(); validSystem(project); const sent: string[] = []; const command = createSystemCommand({ sendUserMessage: (message: string) => sent.push(message), } as never); for (const subcommand of [ "research", "spec", "spec-verify", "assess", "phase", "plan", "issue", "exec", ]) for (const instruction of ["", "login flow"]) await command.handler(`${subcommand} ${instruction}`, { cwd: project, waitForIdle: async () => assert.fail("lifecycle command must not wait"), ui: { notify() {} }, } as never); for (const message of sent) { assert.match( message, /^# \/system (?:research|spec|spec-verify|assess|phase|plan|issue|exec)(?:: login flow)?\n\n# The System board state/, ); assert.match(message, /PX-SPEC-SPEC0001 · Contract · todo · default/); } }); it("warns instead of dispatching a stage while the agent is busy", async () => { const sent: string[] = []; const notices: Array<{ message: string; severity: string }> = []; const command = createSystemCommand({ sendUserMessage: (message: string) => sent.push(message), } as never); await command.handler("exec", { cwd: temp(), isIdle: () => false, waitForIdle: async () => assert.fail("must not wait while busy"), ui: { notify: (message: string, severity: string) => notices.push({ message, severity }), }, } as never); assert.equal(sent.length, 0); assert.equal(notices.length, 1); assert.equal(notices[0]?.severity, "warning"); assert.match(notices[0]?.message ?? "", /needs the agent idle/); }); it("keeps print-mode lifecycle commands alive through the generated turn", async () => { const order: string[] = []; const command = createSystemCommand({ sendUserMessage: () => order.push("send"), } as never); await command.handler("spec explain only", { cwd: temp(), mode: "json", waitForIdle: async () => { order.push("settled"); }, ui: { notify() {} }, } as never); assert.deepEqual(order, ["send", "settled"]); }); it("routes view/book into the shared book and renders rich HTTP content", async () => { const project = temp(); validSystem(project); const output = renderSystemBookSite(loadProjectIndex(project)); roots.push(output.directory); const pages: string[] = []; const command = createSystemCommand({ sendUserMessage() {} } as never, { openBook: async (cwd, page) => { assert.equal(cwd, project); pages.push(page); return `System book running: http://127.0.0.1:12345${page}`; }, }); const notices: string[] = []; const severities: string[] = []; let prompts = 0; let widgets = 0; const ctx = { cwd: project, hasUI: true, waitForIdle: async () => {}, ui: { confirm: async () => { prompts += 1; return true; }, notify: (message: string, severity: string) => { notices.push(message); severities.push(severity); }, setWidget: () => { widgets += 1; }, }, } as never; await command.handler("doctor", ctx); await command.handler("view PX-SPEC-SPEC0001", ctx); await command.handler("book", ctx); await command.handler("view PX-SPEC-SPEC0001 extra", ctx); await command.handler("edit PX-SPEC-SPEC0001 extra", ctx); assert.match(notices[0] ?? "", /OK/); assert.equal(severities[0], "info"); assert.equal(prompts, 0); assert.equal(widgets, 0); assert.deepEqual(pages, ["/#PX-SPEC-SPEC0001", "/"]); assert.match(notices[1] ?? "", /System book running: http:/); assert.match(notices[2] ?? "", /System book running: http:/); assert.match(notices[3] ?? "", /Usage: \/system view/); assert.match(notices[4] ?? "", /Usage: \/system edit/); const view = readFileSync(output.file, "utf8"); const docs = view; assert.match(view, /class="system-article"/); assert.match( view, /

Contract<\/a><\/h1>/, ); assert.match(view, /Metadata<\/summary>/); assert.match(view, /nested/); assert.doesNotMatch(view, /On this page/); assert.match(view, /class="mermaid"/); assert.match(view, /<\/iframe>/, ); assert.doesNotMatch(view, /]+sandbox/); assert.match( view, /Architecture diagram/, ); assert.match( view, /prototype link<\/a> stays inline\./, ); assert.match(view, /href="#PX-SPEC-SPEC0001-details">Local details<\/a>/); assert.match(view, /id="PX-SPEC-SPEC0001-details"/); assert.match( view, /src="\/\.system\/specs\/PX-SPEC-SPEC0001-contract\/screen%20shot\.png"/, ); assert.doesNotMatch(view, /screen%2520shot/); assert.match(view, /class="visual-asset-preview visual-asset-html"/); assert.match(view, /class="visual-asset-preview visual-asset-image"/); assert.match(view, /class="visual-asset-preview visual-asset-video"/); assert.match(view, /raw<\/mark>/); assert.match(docs, /the-system-command-.* Dossier/); assert.match(docs, /
/); assert.match(docs, /class="book-top"/); assert.match(docs, /class="book-nav"/); assert.match(docs, /class="mobile-nav"/); assert.match(docs, /class="nav-utils"/); assert.doesNotMatch(docs, /