repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by admin

feat(the-system): add scoped authoring tools

0e3fdea3301faefa736e63b16aa612279c417030

Oliver Jan Krylow <oliver@bugabinga.net> ·

SSH signature · not checked

Browse filesCompare with HEAD

Changed files (17)

extensions/the-system/CHANGELOG.md

Modified
10 10 - Add turn-scoped `system_slot` allocation with title-derived slugs and repeatable ID reservation.
11 11 - Redefine phases as project-wide operating epochs selected through config, injected into agent context, and shown in Pi and book navigation.
12 12 - Reset the unreleased config schema to version 0; `/system init` updates machine schema markers mechanically, then offers agent-led bundle migration.
13 +- Add initialized-project-only GFM, TeX, and Mermaid skills for already-selected System document formats.
14 +- Keep generated `/system` lifecycle turns alive in print and JSON modes.
15 +- Align mockup, artifact-slot, and board-proposal prompt metadata and tool rendering with Pi defaults.
16 +- Keep board proposals and repeatable artifact slots available across clarification turns and compaction.
14 18 ## 0.0.3

extensions/the-system/README.md

Modified
20 20 ## Tool
22 22 Artifact-authoring commands temporarily enable `system_slot`.
23 +It remains available through clarification, supports repeated reservations in the authoring run, then deactivates after that run settles.
23 24 The agent calls it for each new bundle after choosing a semantic title, then uses the returned ID and path exactly.
24 25 Context determines which bundles, if any, the command creates.
26 -Assessment temporarily enables `system_board_propose`.
27 +Assessment temporarily enables `system_board_propose` through clarification until one assessment submission completes.
27 28 Its proposals remain ephemeral until a human applies selected changes through `/system board`.
29 30 ## Board
68 69 ## Resources
70 -The extension exports no System skills and no top-level System prompt templates.
71 -`/system` uses internal prompt includes so System workflow guidance cannot spill into unrelated projects.
71 +The extension exports no System skills or prompt templates statically.
72 +For valid initialized projects, resource discovery exposes `the-system-gfm`, `the-system-tex`, and `the-system-mermaid`.
73 +Each skill requires the injected System Markdown contract and an already-selected format, so syntax guidance cannot select a format, create bundles, or spill into unrelated projects.
74 +Projects initialized during a live session require `/reload` before those skills become available.
73 76 The generic `mockup` tool remains available.

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

Modified
29 29 const theme = {
30 30 fg: (_style: string, text: string) => text,
31 31 bold: (text: string) => text,
32 -};
32 +} as never;
33 33 const render = (component: { render(width: number): string[] }) =>
34 34 component.render(120).join("\n");
35 +const renderContext = (expanded: boolean, lastComponent?: unknown) =>
36 + ({ expanded, lastComponent, isError: false } as never);
36 38 describe("system_slot", () => {
37 39 it("derives semantic slugs and reserves unique IDs on demand", () => {
58 - it("keeps prompting terse and renders human-useful mappings", () => {
60 + it("uses concise prompt metadata and Pi-style tool rendering", () => {
59 61 initTheme("default", false);
60 62 const root = project();
61 63 const slot = reserveArtifactSlot(root, {
63 65 title: "Replace cache invalidation",
65 67 const tool = createArtifactSlotTool();
68 + assert.equal(tool.label, "system_slot");
66 69 assert.equal(
67 70 tool.description,
68 - "Reserve an ID and canonical path for a new System bundle.",
71 + "Reserve a unique System document ID and canonical bundle path from its type and semantic title.",
73 + assert.equal(
74 + tool.promptSnippet,
75 + "Reserve an ID and path for a System bundle",
76 + );
77 + assert.notEqual(tool.promptSnippet, tool.description);
70 78 assert.deepEqual(tool.promptGuidelines, [
71 - "When context requires new bundles, call system_slot for each after choosing its title; use returned IDs and paths exactly.",
79 + "Resolve needed clarifications before reserving slots.",
80 + "Call system_slot once per required bundle after choosing its final type and title; use each returned ID and path exactly.",
73 - const result = { content: [], details: slot };
74 - const collapsed = render(
75 - (tool.renderResult as Function)(
76 - result,
77 - { expanded: false, isPartial: false },
78 - theme,
79 - {},
80 - ),
83 + assert.ok(tool.renderCall);
84 + const callComponent = tool.renderCall(
85 + { type: "plan", title: slot.title },
86 + theme,
87 + renderContext(false),
82 - assert.match(collapsed, new RegExp(slot.id));
89 + assert.match(
90 + render(callComponent),
91 + /^system_slot plan · Replace cache invalidation/,
92 + );
94 + assert.ok(tool.renderResult);
95 + const result = { content: [], details: slot };
96 + const collapsedComponent = tool.renderResult(
97 + result,
98 + { expanded: false, isPartial: false },
99 + theme,
100 + renderContext(false),
101 + );
102 + const collapsed = render(collapsedComponent);
103 + const expandedComponent = tool.renderResult(
104 + result,
105 + { expanded: true, isPartial: false },
106 + theme,
107 + renderContext(true, collapsedComponent),
108 + );
109 + const expanded = render(expandedComponent);
110 + assert.equal(expandedComponent, collapsedComponent);
111 + assert.match(collapsed, new RegExp(`^✓ reserved ${slot.id}`));
83 112 assert.match(collapsed, /replace-cache-invalidation/);
84 113 assert.match(collapsed, /to expand/);
85 - const expanded = render(
86 - (tool.renderResult as Function)(
87 - result,
88 - { expanded: true, isPartial: false },
114 + assert.doesNotMatch(collapsed, new RegExp(slot.path));
115 + assert.match(expanded, /type plan/);
116 + assert.match(expanded, /title Replace cache invalidation/);
117 + assert.ok(expanded.includes(`path ${slot.path}`));
119 + const error = render(
120 + tool.renderResult(
121 + { content: [{ type: "text", text: "reservation failed" }] },
122 + { expanded: false, isPartial: false },
89 123 theme,
90 - {},
124 + { ...renderContext(false), isError: true } as never,
93 - assert.match(expanded, /title {2}Replace cache invalidation/);
94 - assert.match(expanded, new RegExp(`id ${slot.id}`));
95 - assert.ok(expanded.includes(`path ${slot.path}`));
127 + assert.equal(error.trimEnd(), "reservation failed");

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

Added
new file mode 100644
1 +import assert from "node:assert/strict";
2 +import { initTheme } from "@earendil-works/pi-coding-agent";
3 +import { beforeAll, describe, it } from "vitest";
4 +import { createBoardRuntime } from "../board-runtime.ts";
6 +const theme = {
7 + fg: (_style: string, text: string) => text,
8 + bold: (text: string) => text,
9 +} as never;
10 +const render = (component: { render(width: number): string[] }) =>
11 + component.render(120).join("\n");
12 +const renderContext = (expanded: boolean, lastComponent?: unknown) =>
13 + ({ expanded, lastComponent, isError: false } as never);
14 +const items = [
15 + {
16 + id: "PX-SPEC-SPEC0001",
17 + state: "todo" as const,
18 + rationale: "Acceptance remains incomplete.",
19 + },
20 + {
21 + id: "PX-ISSUE-ISSUE001",
22 + state: "done" as const,
23 + rationale: "Regression coverage proves closure.",
24 + },
25 +];
27 +beforeAll(() => initTheme("default", false));
29 +describe("system_board_propose", () => {
30 + it("uses concise prompt metadata", () => {
31 + const tool = createBoardRuntime().tool;
33 + assert.equal(tool.label, "system_board_propose");
34 + assert.equal(
35 + tool.promptSnippet,
36 + "Propose System board states for human review",
37 + );
38 + assert.notEqual(tool.promptSnippet, tool.description);
39 + assert.match(tool.description, /does not modify \.system\/board\.json/);
40 + assert.deepEqual(tool.promptGuidelines, [
41 + "During /system assess, call system_board_propose exactly once after inspection; use an empty items list when no state changes are justified.",
42 + ]);
43 + });
45 + it("keeps proposal details behind expansion and renders errors", () => {
46 + const tool = createBoardRuntime().tool;
47 + assert.ok(tool.renderCall);
48 + const collapsedCallComponent = tool.renderCall(
49 + { items },
50 + theme,
51 + renderContext(false),
52 + );
53 + const collapsedCall = render(collapsedCallComponent);
54 + const expandedCallComponent = tool.renderCall(
55 + { items },
56 + theme,
57 + renderContext(true, collapsedCallComponent),
58 + );
59 + const expandedCall = render(expandedCallComponent);
60 + assert.equal(expandedCallComponent, collapsedCallComponent);
61 + assert.match(collapsedCall, /^system_board_propose 2 items/);
62 + assert.match(collapsedCall, /to expand/);
63 + assert.doesNotMatch(collapsedCall, /Acceptance remains incomplete/);
64 + assert.match(expandedCall, /TODO PX-SPEC-SPEC0001/);
65 + assert.match(expandedCall, /Acceptance remains incomplete/);
67 + assert.ok(tool.renderResult);
68 + const result = { content: [], details: { items } };
69 + const collapsedResultComponent = tool.renderResult(
70 + result,
71 + { expanded: false, isPartial: false },
72 + theme,
73 + renderContext(false),
74 + );
75 + const collapsedResult = render(collapsedResultComponent);
76 + const expandedResultComponent = tool.renderResult(
77 + result,
78 + { expanded: true, isPartial: false },
79 + theme,
80 + renderContext(true, collapsedResultComponent),
81 + );
82 + const expandedResult = render(expandedResultComponent);
83 + assert.equal(expandedResultComponent, collapsedResultComponent);
84 + assert.match(collapsedResult, /^✓ 2 changes proposed/);
85 + assert.match(collapsedResult, /to expand/);
86 + assert.doesNotMatch(collapsedResult, /PX-SPEC-SPEC0001/);
87 + assert.match(expandedResult, /TODO PX-SPEC-SPEC0001/);
88 + assert.match(expandedResult, /Regression coverage proves closure/);
90 + const empty = render(
91 + tool.renderResult(
92 + { content: [], details: { items: [] } },
93 + { expanded: false, isPartial: false },
94 + theme,
95 + renderContext(false),
96 + ),
97 + );
98 + assert.equal(empty.trimEnd(), "✓ no changes proposed");
100 + const error = render(
101 + tool.renderResult(
102 + { content: [{ type: "text", text: "proposal failed" }] },
103 + { expanded: false, isPartial: false },
104 + theme,
105 + { ...renderContext(false), isError: true } as never,
106 + ),
107 + );
108 + assert.equal(error.trimEnd(), "proposal failed");
109 + });
110 +});

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

Modified
19 19 expect(t.session.extensionRunner.extensions[0].path).toBe(extensionPath);
22 - it("scopes system_slot to artifact command runs", async () => {
22 + it("keeps system_slot through clarification and cancels it on the next lifecycle", async () => {
23 23 const extensionPath = path.resolve(import.meta.dirname, "../index.ts");
24 24 t = await createTestSession({ extensions: [extensionPath] });
25 25 const [extension] = t.session.extensionRunner.extensions;
37 37 expect(sendUserMessage).toHaveBeenCalledOnce();
38 38 expect(t.session.getActiveToolNames()).toContain("system_slot");
39 39 expect(t.session.systemPrompt).toContain(
40 - "- system_slot: Reserve an ID and canonical path for a new System bundle.",
40 + "- system_slot: Reserve an ID and path for a System bundle",
42 42 expect(t.session.systemPrompt).toContain(
43 - "- When context requires new bundles, call system_slot for each after choosing its title; use returned IDs and paths exactly.",
43 + "- Resolve needed clarifications before reserving slots.",
44 + );
45 + expect(t.session.systemPrompt).toContain(
46 + "- Call system_slot once per required bundle after choosing its final type and title; use each returned ID and path exactly.",
45 48 for (const handler of extension.handlers.get("agent_settled"))
46 49 await handler(
47 50 { type: "agent_settled", messages: [] },
48 51 t.session.extensionRunner.createCommandContext(),
53 + expect(t.session.getActiveToolNames()).toContain("system_slot");
54 + await extension.commands
55 + .get("system")
56 + .handler("exec continue", t.session.extensionRunner.createCommandContext());
50 57 expect(t.session.getActiveToolNames()).not.toContain("system_slot");
51 58 expect(t.session.systemPrompt).not.toContain("- system_slot:");

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

Modified
11 11 } from "node:fs/promises";
12 12 import { tmpdir } from "node:os";
13 13 import path from "node:path";
14 -import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
15 -import { afterEach, describe, it } from "vitest";
14 +import {
15 + type ExtensionContext,
16 + initTheme,
17 +} from "@earendil-works/pi-coding-agent";
18 +import { afterEach, beforeAll, describe, it } from "vitest";
16 19 import type { MockupRequest, MockupResult } from "../mockup.ts";
17 20 import {
18 21 createMockupRuntime,
45 48 const roots: string[] = [];
49 +beforeAll(() => initTheme("default", false));
46 50 afterEach(async () => {
47 51 await Promise.all(
48 52 roots.splice(0).map((root) => rm(root, { recursive: true })),
74 78 return bytes;
81 +function plainTheme() {
82 + return {
83 + fg: (_style: string, text: string) => text,
84 + bold: (text: string) => text,
85 + } as never;
88 +function rendered(component: { render(width: number): string[] }): string {
89 + return component.render(120).join("\n");
92 +function renderContext(expanded: boolean, lastComponent?: unknown) {
93 + return {
94 + expanded,
95 + lastComponent,
96 + isError: false,
97 + } as never;
100 +describe("mockup tool contract", () => {
101 + it("uses concise prompt metadata without duplicating its description", () => {
102 + const tool = createMockupRuntime({ openBrowser: false }).tool;
104 + assert.strictEqual(tool.label, "mockup");
105 + assert.strictEqual(tool.promptSnippet, "Review HTML mockups in a browser");
106 + assert.notStrictEqual(tool.promptSnippet, tool.description);
107 + assert.deepStrictEqual(tool.promptGuidelines, [
108 + "Use mockup when visual comparison beats prose for UI, layout, styling, or interaction decisions.",
109 + "Pass HTML fragments only; never include <!doctype>, <html>, <head>, or <body>.",
110 + "Provide 1-4 options; one option is valid when reviewing a single design.",
111 + "The tool owns browser review and feedback. Do not ask the user to repeat its result in chat.",
112 + "On iterate, revise the fragments and call mockup again. On accept, continue the design unless feedback requires another iteration.",
113 + ]);
114 + });
116 + it("renders a compact call and reserves option details for expansion", () => {
117 + const tool = createMockupRuntime({ openBrowser: false }).tool;
118 + assert.ok(tool.renderCall);
119 + const collapsedComponent = tool.renderCall(
120 + request,
121 + plainTheme(),
122 + renderContext(false),
123 + );
124 + const collapsed = rendered(collapsedComponent);
125 + const expandedComponent = tool.renderCall(
126 + request,
127 + plainTheme(),
128 + renderContext(true, collapsedComponent),
129 + );
130 + const expanded = rendered(expandedComponent);
132 + assert.strictEqual(expandedComponent, collapsedComponent);
133 + assert.match(collapsed, /^mockup Layout · 2 options/);
134 + assert.match(collapsed, /to expand/);
135 + assert.doesNotMatch(collapsed, /Which layout\?/);
136 + assert.match(expanded, /Which layout\?/);
137 + assert.match(expanded, /dense Dense/);
138 + assert.match(expanded, /calm Calm/);
139 + assert.doesNotMatch(expanded, /<section>/);
140 + });
142 + it("keeps feedback compact until expanded and renders errors", () => {
143 + const tool = createMockupRuntime({ openBrowser: false }).tool;
144 + assert.ok(tool.renderResult);
145 + const toolResult = {
146 + content: [{ type: "text" as const, text: "structured result" }],
147 + details: {
148 + ...result,
149 + sessionId: "session",
150 + chainId: "chain",
151 + iteration: 1,
152 + cacheManifest: "/cache/manifest.json",
153 + history: [],
154 + contextCapsule: "capsule",
155 + },
156 + };
157 + const collapsedComponent = tool.renderResult(
158 + toolResult,
159 + { expanded: false, isPartial: false },
160 + plainTheme(),
161 + renderContext(false),
162 + );
163 + const collapsed = rendered(collapsedComponent);
164 + const expandedComponent = tool.renderResult(
165 + toolResult,
166 + { expanded: true, isPartial: false },
167 + plainTheme(),
168 + renderContext(true, collapsedComponent),
169 + );
170 + const expanded = rendered(expandedComponent);
172 + assert.strictEqual(expandedComponent, collapsedComponent);
173 + assert.match(collapsed, /^↻ iterate · selected dense · 1 annotation/);
174 + assert.match(collapsed, /to expand/);
175 + assert.doesNotMatch(collapsed, /keep density|tighten|cache/);
176 + assert.match(expanded, /notes: keep density/);
177 + assert.match(expanded, /dense @ 25%,50% tighten/);
178 + assert.match(expanded, /cache: \/cache\/manifest\.json/);
180 + const accepted = rendered(
181 + tool.renderResult(
183 + ...toolResult,
184 + details: {
185 + ...toolResult.details,
186 + action: "accept",
187 + selected: [],
188 + annotations: [],
189 + },
190 + },
191 + { expanded: false, isPartial: false },
192 + plainTheme(),
193 + renderContext(false),
194 + ),
195 + );
196 + assert.match(accepted, /^✓ accepted · selected none · 0 annotations/);
198 + const error = rendered(
199 + tool.renderResult(
200 + { content: [{ type: "text", text: "browser failed" }] },
201 + { expanded: false, isPartial: false },
202 + plainTheme(),
203 + { ...renderContext(false), isError: true } as never,
204 + ),
205 + );
206 + assert.strictEqual(error.trimEnd(), "browser failed");
207 + });
208 +});
77 210 describe("mockup context cache", () => {
78 211 it("uses the native OS cache location", () => {
79 212 assert.strictEqual(

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

Modified
28 28 mkdirSync(path.dirname(target), { recursive: true });
29 29 writeFileSync(target, content, "utf8");
31 +type CapturedTool = {
32 + execute: (
33 + toolCallId: string,
34 + params: unknown,
35 + signal: undefined,
36 + onUpdate: undefined,
37 + ctx: unknown,
38 + ) => Promise<unknown>;
39 +};
31 40 const validSystem = (root: string) => {
32 41 for (const directory of ["specs", "phases", "plans", "issues", "research"])
33 42 mkdirSync(path.join(root, ".system", directory), { recursive: true });
121 130 assert.deepEqual(tools, ["mockup", "system_slot", "system_board_propose"]);
133 + it("keeps scoped tools through clarification until their existing completion signal", async () => {
134 + const project = temp();
135 + validSystem(project);
136 + let activeTools = ["read"];
137 + let command:
138 + | { handler: (args: string, ctx: unknown) => Promise<void> }
139 + | undefined;
140 + let boardTool: CapturedTool | undefined;
141 + let slotTool: CapturedTool | undefined;
142 + let agentSettled: ((event: unknown, ctx: unknown) => void) | undefined;
143 + registerTheSystem({
144 + registerCommand(_name: string, definition: typeof command) {
145 + command = definition;
146 + },
147 + registerTool(definition: { name: string }) {
148 + if (definition.name === "system_board_propose")
149 + boardTool = definition as CapturedTool;
150 + if (definition.name === "system_slot")
151 + slotTool = definition as CapturedTool;
152 + },
153 + on(event: string, handler: (...args: never[]) => unknown) {
154 + if (event === "agent_settled") agentSettled = handler as never;
155 + },
156 + getActiveTools: () => activeTools,
157 + setActiveTools: (tools: string[]) => {
158 + activeTools = tools;
159 + },
160 + sendUserMessage() {},
161 + } as never);
162 + const ctx = {
163 + cwd: project,
164 + mode: "interactive",
165 + hasUI: false,
166 + isIdle: () => true,
167 + abort() {},
168 + sessionManager: {
169 + getSessionId: () => project,
170 + getBranch: () => [],
171 + },
172 + ui: {
173 + notify() {},
174 + setStatus() {},
175 + theme: { fg: (_color: string, text: string) => text },
176 + },
177 + };
179 + assert.ok(command);
180 + await command.handler("assess", ctx);
181 + assert.ok(activeTools.includes("system_board_propose"));
183 + agentSettled?.({}, ctx);
184 + assert.ok(activeTools.includes("system_board_propose"));
186 + assert.ok(boardTool);
187 + await boardTool.execute(
188 + "proposal",
190 + items: [
192 + id: "PX-SPEC-SPEC0001",
193 + state: "todo",
194 + rationale: "Implementation remains incomplete.",
195 + },
196 + ],
197 + },
198 + undefined,
199 + undefined,
200 + ctx,
201 + );
202 + agentSettled?.({}, ctx);
203 + assert.ok(!activeTools.includes("system_board_propose"));
204 + assert.deepEqual(
205 + JSON.parse(readFileSync(path.join(project, ".system/board.json"), "utf8")),
206 + { schemaVersion: 0, items: {} },
207 + );
209 + await command.handler("spec", ctx);
210 + assert.ok(activeTools.includes("system_slot"));
211 + agentSettled?.({}, ctx);
212 + assert.ok(activeTools.includes("system_slot"));
214 + assert.ok(slotTool);
215 + await slotTool.execute(
216 + "slot-one",
217 + { type: "spec", title: "First contract" },
218 + undefined,
219 + undefined,
220 + ctx,
221 + );
222 + assert.ok(activeTools.includes("system_slot"));
223 + await slotTool.execute(
224 + "slot-two",
225 + { type: "issue", title: "Second concern" },
226 + undefined,
227 + undefined,
228 + ctx,
229 + );
230 + agentSettled?.({}, ctx);
231 + assert.ok(!activeTools.includes("system_slot"));
232 + });
234 + it("discovers format skills only for valid initialized projects", async () => {
235 + let discover:
236 + | ((event: { cwd: string }) => Promise<unknown>)
237 + | undefined;
238 + registerTheSystem({
239 + registerCommand() {},
240 + registerTool() {},
241 + on(event: string, handler: (...args: never[]) => unknown) {
242 + if (event === "resources_discover") discover = handler as never;
243 + },
244 + } as never);
245 + const inactive = temp();
246 + assert.equal(await discover?.({ cwd: inactive }), undefined);
247 + mkdirSync(path.join(inactive, ".system"));
248 + assert.equal(await discover?.({ cwd: inactive }), undefined);
249 + const active = temp();
250 + validSystem(active);
251 + assert.deepEqual(await discover?.({ cwd: active }), {
252 + skillPaths: [path.resolve(import.meta.dirname, "../skills")],
253 + });
254 + write(active, ".system/config.json", '{"prefix":"PX","schemaVersion":4}');
255 + assert.equal(await discover?.({ cwd: active }), undefined);
256 + });
124 258 it("reports schema mismatches with schema-0 init instructions", () => {
125 259 const project = temp();
126 260 validSystem(project);
304 438 } as never);
305 439 assert.match(notices[0] ?? "", /Initialized The System/);
440 + assert.match(notices[0] ?? "", /\/reload to activate System format skills/);
306 441 assert.deepEqual(
307 442 JSON.parse(
308 443 readFileSync(path.join(project, ".system/config.json"), "utf8"),
417 552 } as never);
418 553 assert.match(notices[0] ?? "", /Initialized The System/);
554 + assert.doesNotMatch(notices[0] ?? "", /\/reload/);
421 557 it("injects lifecycle prompts and activates artifact allocation", async () => {
446 582 for (const instruction of ["", "login flow"])
447 583 await command.handler(`${subcommand} ${instruction}`, {
448 584 cwd: project,
449 - waitForIdle: async () => {},
585 + waitForIdle: async () => assert.fail("lifecycle command must not wait"),
450 586 ui: { notify() {} },
451 587 } as never);
452 588 for (const message of sent)
458 594 sent.find((item) => item.includes("# /system exec")) ?? "",
459 595 /spec\+plan/,
461 - assert.match(
462 - sent.find((item) => item.includes("# /system assess")) ?? "",
463 - /system_board_propose/,
464 - );
597 + const assessPrompt =
598 + sent.find((item) => item.includes("# /system assess")) ?? "";
599 + assert.match(assessPrompt, /Submit the assessment through system_board_propose/);
600 + assert.doesNotMatch(assessPrompt, /empty items list/);
465 601 const phasePrompt =
466 602 sent.find((item) => item.includes("# /system phase\n")) ?? "";
467 603 assert.match(phasePrompt, /project-wide operating phase/);
468 604 assert.match(phasePrompt, /config currentPhase/);
469 605 assert.doesNotMatch(phasePrompt, /large specs/);
470 - assert.match(
606 + const specPrompt =
471 607 sent.find(
472 608 (item) =>
473 609 item.includes("# /system spec\n") && item.includes("login flow"),
474 - ) ?? "",
475 - /login flow/,
476 - );
610 + ) ?? "";
611 + assert.match(specPrompt, /login flow/);
612 + assert.match(specPrompt, /Use mockup for visual elements, UI, layout/);
613 + assert.match(specPrompt, /save the selected HTML as a spec-bundle asset/);
614 + assert.match(specPrompt, /encode feedback as behavior and constraints/);
477 615 assert.match(
478 616 sent.find((item) => item.endsWith("before writing.")) ?? "",
479 617 /No instructions were supplied/,
621 + it("keeps print-mode lifecycle commands alive through the generated turn", async () => {
622 + const order: string[] = [];
623 + const command = createSystemCommand({
624 + sendUserMessage: () => order.push("send"),
625 + } as never);
626 + await command.handler("spec explain only", {
627 + cwd: temp(),
628 + mode: "json",
629 + waitForIdle: async () => {
630 + order.push("settled");
631 + },
632 + ui: { notify() {} },
633 + } as never);
634 + assert.deepEqual(order, ["send", "settled"]);
635 + });
483 637 it("runs doctor directly and renders rich browser view/book files", async () => {
484 638 const project = temp();
485 639 validSystem(project);

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

Modified
18 18 describe("the-system internal prompt model", () => {
19 - it("ships no System skills or top-level prompt templates", () => {
19 + it("ships System format skills without exporting them statically", () => {
20 20 const extension = packageJson();
21 21 assert.deepEqual(extension.pi, { extensions: ["index.ts"] });
22 22 const repository = repositoryPackage();
24 24 assert.ok(
25 25 !repository.pi?.prompts?.includes("extensions/the-system/prompts"),
27 + for (const name of [
28 + "the-system-gfm",
29 + "the-system-tex",
30 + "the-system-mermaid",
31 + ]) {
32 + const skill = readFileSync(
33 + path.join(root, "skills", name, "SKILL.md"),
34 + "utf8",
35 + );
36 + assert.match(skill, new RegExp(`name: ${name}`));
37 + assert.match(skill, /current instructions contain The System Markdown contract/);
38 + assert.match(skill, /already been selected/);
39 + assert.doesNotMatch(skill.split("---", 3)[1] ?? "", /bundle|create|author/);
40 + }
29 43 it("keeps System instructions internal to the /system command", () => {
30 44 const prompts = readFileSync(path.join(root, "system-prompts.ts"), "utf8");
31 45 assert.match(prompts, /The System document contract/);
32 46 assert.match(prompts, /The System Markdown contract/);
47 + assert.match(prompts, /load its matching the-system-\* skill/);
33 48 assert.match(prompts, /No instructions were supplied/);
34 49 assert.match(prompts, /\/system view <ID>/);

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

Modified
4 4 import { StringEnum } from "@earendil-works/pi-ai";
5 5 import { defineTool, keyHint } from "@earendil-works/pi-coding-agent";
6 6 import { Text } from "@earendil-works/pi-tui";
7 7 import { Type } from "typebox";
8 8 import type { ArtifactSlot } from "./artifact-slot.js";
10 -const DESCRIPTION = "Reserve an ID and canonical path for a new System bundle.";
11 -const GUIDANCE =
12 - "When context requires new bundles, call system_slot for each after choosing its title; use returned IDs and paths exactly.";
10 +const DESCRIPTION =
11 + "Reserve a unique System document ID and canonical bundle path from its type and semantic title.";
12 +const GUIDANCE = [
13 + "Resolve needed clarifications before reserving slots.",
14 + "Call system_slot once per required bundle after choosing its final type and title; use each returned ID and path exactly.",
15 +];
13 16 const ARTIFACT_TYPES = ["research", "spec", "phase", "plan", "issue"] as const;
15 -export function createArtifactSlotTool() {
18 +export function createArtifactSlotTool(onReserved?: () => void) {
16 19 const reserved = new Set<string>();
17 20 return defineTool({
18 21 name: "system_slot",
19 - label: "System Slot",
22 + label: "system_slot",
20 23 description: DESCRIPTION,
21 - promptSnippet: DESCRIPTION,
22 - promptGuidelines: [GUIDANCE],
24 + promptSnippet: "Reserve an ID and path for a System bundle",
25 + promptGuidelines: GUIDANCE,
23 26 parameters: Type.Object({
24 27 type: StringEnum(ARTIFACT_TYPES, {
25 28 description: "System bundle type.",
29 32 renderCall(args, theme, context) {
30 - const heading = theme.fg("toolTitle", theme.bold("system_slot"));
31 - const type = String(args.type ?? "bundle");
32 - const title = bounded(String(args.title ?? "untitled"), 56);
33 - const lines = [heading, theme.fg("dim", `${type} · ${title}`)];
34 - if (!context.expanded)
35 - lines.push(theme.fg("muted", keyHint("app.tools.expand", "to expand")));
36 - return new Text(lines.join("\n"), 0, 0);
37 - },
38 - renderResult(result, context, theme) {
39 - const slot = result.details as ArtifactSlot | undefined;
40 - if (!slot) return new Text("", 0, 0);
41 - if (!context.expanded)
42 - return new Text(
43 - [
44 - theme.fg("success", `reserved ${slot.id}`),
45 - theme.fg(
46 - "dim",
47 - `${bounded(slot.slug, 40)} · ${keyHint("app.tools.expand", "to expand")}`,
48 - ),
49 - ].join("\n"),
50 - 0,
51 - 0,
52 - );
53 - return new Text(
54 - [
55 - theme.fg("success", `reserved ${slot.type} bundle`),
56 - `title ${slot.title}`,
57 - `id ${slot.id}`,
58 - `slug ${slot.slug}`,
59 - `path ${slot.path}`,
60 - ].join("\n"),
61 - 0,
62 - 0,
33 + const text =
34 + (context.lastComponent as Text | undefined) ?? new Text("", 0, 0);
35 + text.setText(
36 + `${theme.fg("toolTitle", theme.bold("system_slot"))} ${theme.fg("accent", String(args.type ?? "bundle"))} ${theme.fg("toolOutput", `· ${bounded(String(args.title ?? "untitled"), 72)}`)}`,
38 + return text;
39 + },
40 + renderResult(result, { expanded }, theme, context) {
41 + const text =
42 + (context.lastComponent as Text | undefined) ?? new Text("", 0, 0);
43 + const slot = result.details as ArtifactSlot | undefined;
44 + if (!slot) {
45 + const output = result.content
46 + .filter(
47 + (item): item is { type: "text"; text: string } =>
48 + item.type === "text",
49 + )
50 + .map((item) => item.text)
51 + .join("\n");
52 + text.setText(theme.fg(context.isError ? "error" : "muted", output));
53 + return text;
54 + }
55 + let output = `${theme.fg("success", "✓ reserved")} ${theme.fg("accent", slot.id)}${theme.fg("dim", ` · ${bounded(slot.slug, 40)}`)}`;
56 + if (!expanded) {
57 + output += theme.fg(
58 + "dim",
59 + ` (${keyHint("app.tools.expand", "to expand")})`,
60 + );
61 + } else {
62 + output += [
63 + `\n${theme.fg("dim", "type ")}${theme.fg("toolOutput", slot.type)}`,
64 + `${theme.fg("dim", "title ")}${theme.fg("toolOutput", slot.title)}`,
65 + `${theme.fg("dim", "path ")}${theme.fg("toolOutput", slot.path)}`,
66 + ].join("\n");
67 + }
68 + text.setText(output);
69 + return text;
65 71 async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
66 72 const { reserveArtifactSlot } = await import("./artifact-slot.js");
67 73 const slot = reserveArtifactSlot(ctx.cwd, params, reserved);
74 + onReserved?.();
68 75 return {
69 76 content: [

extensions/the-system/board-runtime.ts

Modified
21 21 description: "Terse evidence supporting this proposed state.",
24 - { minItems: 1, maxItems: 100 },
24 + { minItems: 0, maxItems: 100 },
28 28 export function createBoardRuntime() {
29 29 let assessmentRoot: string | undefined;
30 + let assessmentFinished = false;
30 31 const proposals = new Map<string, Map<string, BoardProposal>>();
31 32 const servers = new Set<BoardServer>();
32 33 const tool = defineTool({
33 34 name: "system_board_propose",
34 - label: "System Board Proposal",
35 + label: "system_board_propose",
35 36 description:
36 - "Propose evidence-backed System board state changes for human review.",
37 + "Record evidence-backed proposed board states for human review. Accepts existing spec, plan, or issue IDs and does not modify .system/board.json.",
38 + promptSnippet: "Propose System board states for human review",
39 + promptGuidelines: [
40 + "During /system assess, call system_board_propose exactly once after inspection; use an empty items list when no state changes are justified.",
41 + ],
37 42 parameters: proposalParameters,
38 - renderCall(args, theme) {
39 - return new Text(
40 - theme.fg(
41 - "toolTitle",
42 - theme.bold(
43 - `system_board_propose ${Array.isArray(args.items) ? args.items.length : 0}`,
44 - ),
45 - ),
46 - 0,
47 - 0,
48 - );
43 + renderCall(args, theme, context) {
44 + const text =
45 + (context.lastComponent as Text | undefined) ?? new Text("", 0, 0);
46 + const items = Array.isArray(args.items) ? args.items : [];
47 + const count = items.length;
48 + let output = `${theme.fg("toolTitle", theme.bold("system_board_propose"))} ${theme.fg("toolOutput", `${count} item${count === 1 ? "" : "s"}`)}`;
49 + if (!context.expanded && count > 0) {
50 + output += theme.fg(
51 + "dim",
52 + ` (${keyHint("app.tools.expand", "to expand")})`,
53 + );
54 + } else {
55 + for (const item of items) {
56 + output += `\n${theme.fg("accent", String(item.state).toUpperCase())} ${theme.fg("toolOutput", String(item.id))}`;
57 + if (item.rationale)
58 + output += `\n${theme.fg("dim", String(item.rationale))}`;
59 + }
60 + }
61 + text.setText(output);
62 + return text;
50 - renderResult(result, { expanded }, theme) {
64 + renderResult(result, { expanded }, theme, context) {
65 + const text =
66 + (context.lastComponent as Text | undefined) ?? new Text("", 0, 0);
51 67 const items = (result.details as { items?: BoardProposal[] } | undefined)
52 68 ?.items;
53 - if (!items) return new Text("", 0, 0);
54 - if (!expanded)
55 - return new Text(
56 - `${theme.fg("success", `${items.length} proposed`)} · ${theme.fg("dim", keyHint("app.tools.expand", "to expand"))}`,
57 - 0,
58 - 0,
59 - );
60 - return new Text(
61 - items
62 - .map(
63 - (item) =>
64 - `${theme.fg("accent", item.state.toUpperCase())} ${item.id}\n${theme.fg("dim", item.rationale)}`,
69 + if (!items) {
70 + const output = result.content
71 + .filter(
72 + (item): item is { type: "text"; text: string } =>
73 + item.type === "text",
66 - .join("\n"),
67 - 0,
68 - 0,
75 + .map((item) => item.text)
76 + .join("\n");
77 + text.setText(theme.fg(context.isError ? "error" : "muted", output));
78 + return text;
79 + }
80 + const count = items.length;
81 + let output = theme.fg(
82 + "success",
83 + count === 0
84 + ? "✓ no changes proposed"
85 + : `✓ ${count} change${count === 1 ? "" : "s"} proposed`,
87 + if (!expanded && count > 0) {
88 + output += theme.fg(
89 + "dim",
90 + ` (${keyHint("app.tools.expand", "to expand")})`,
91 + );
92 + } else if (expanded) {
93 + for (const item of items)
94 + output += `\n${theme.fg("accent", item.state.toUpperCase())} ${theme.fg("toolOutput", item.id)}\n${theme.fg("dim", item.rationale)}`;
95 + }
96 + text.setText(output);
97 + return text;
71 99 async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
72 100 const root = discoverProjectRoot(ctx.cwd);
101 129 proposals.set(root, proposed);
130 + assessmentFinished = true;
102 131 const items = [...proposed.values()].sort((left, right) =>
103 132 left.id.localeCompare(right.id),
121 150 const index = loadProjectIndex(root);
122 151 readBoardState(root, index.prefix);
123 152 assessmentRoot = root;
153 + assessmentFinished = false;
124 154 proposals.set(root, new Map());
156 + assessmentComplete() {
157 + return assessmentRoot !== undefined && assessmentFinished;
158 + },
126 159 endAssessment() {
127 160 assessmentRoot = undefined;
161 + assessmentFinished = false;
129 163 async open(cwd: string): Promise<string> {
130 164 const index = loadProjectIndex(cwd);
151 185 shutdown() {
152 186 assessmentRoot = undefined;
187 + assessmentFinished = false;
153 188 for (const server of servers) server.close();
154 189 servers.clear();

extensions/the-system/index.ts

Modified
1 +import path from "node:path";
1 2 import {
2 3 type ExtensionAPI,
3 4 type ExtensionContext,
19 20 let generation = 0;
20 21 let warningNotified = false;
21 22 const agentBlockReasons = new Map<string, string>();
22 - const mockup = createMockupRuntime();
23 - const artifactSlot = createArtifactSlotTool();
24 - const board = createBoardRuntime();
25 23 let artifactSlotRunActive = false;
24 + let artifactSlotUsed = false;
26 25 let boardAssessmentRunActive = false;
27 26 let bundleMigrationRunActive = false;
27 + const mockup = createMockupRuntime();
28 + const artifactSlot = createArtifactSlotTool(() => {
29 + artifactSlotUsed = true;
30 + });
31 + const board = createBoardRuntime();
28 32 const activateArtifactSlot = () => {
29 33 const active = pi.getActiveTools();
30 34 if (!active.includes(artifactSlot.name))
31 35 pi.setActiveTools([...active, artifactSlot.name]);
32 36 artifactSlotRunActive = true;
37 + artifactSlotUsed = false;
34 39 const deactivateArtifactSlot = () => {
35 40 const active = pi.getActiveTools();
36 41 if (active.includes(artifactSlot.name))
37 42 pi.setActiveTools(active.filter((name) => name !== artifactSlot.name));
38 43 artifactSlotRunActive = false;
44 + artifactSlotUsed = false;
40 46 const activateBoardAssessment = (cwd: string) => {
41 47 board.beginAssessment(cwd);
54 60 const activateBundleMigration = () => {
55 61 bundleMigrationRunActive = true;
63 + const beginLifecycle = () => {
64 + if (artifactSlotRunActive) deactivateArtifactSlot();
65 + if (boardAssessmentRunActive) deactivateBoardAssessment();
66 + };
58 68 const syncRuntimeIndicator = async (
59 69 ctx: ExtensionContext,
98 + pi.on("resources_discover", async (event) => {
99 + const { startupRuntimeState } = await import("./startup-notice.js");
100 + const runtime = await startupRuntimeState(event.cwd);
101 + if (!runtime.active || runtime.notice) return;
102 + return { skillPaths: [path.join(import.meta.dirname, "skills")] };
103 + });
88 104 pi.on("session_start", (_event, ctx) => {
89 105 deactivateArtifactSlot();
90 106 deactivateBoardAssessment();
106 122 warningNotified = false;
107 123 agentBlockReasons.clear();
108 124 artifactSlotRunActive = false;
125 + artifactSlotUsed = false;
109 126 boardAssessmentRunActive = false;
110 127 bundleMigrationRunActive = false;
111 128 board.shutdown();
132 149 agentBlockReasons.clear();
133 150 mockup.agentSettled(ctx);
134 - if (artifactSlotRunActive) deactivateArtifactSlot();
135 - if (boardAssessmentRunActive) deactivateBoardAssessment();
151 + if (artifactSlotRunActive && artifactSlotUsed) deactivateArtifactSlot();
152 + if (boardAssessmentRunActive && board.assessmentComplete())
153 + deactivateBoardAssessment();
136 154 bundleMigrationRunActive = false;
138 156 pi.on("context", (event) => {
178 196 handler: async (args, ctx) => {
179 197 const { createSystemCommand } = await import("./system-command.js");
180 198 await createSystemCommand(pi, {
199 + beginLifecycle,
181 200 activateArtifactTool: activateArtifactSlot,
182 201 activateAssessmentTool: activateBoardAssessment,
183 202 activateBundleMigration,

extensions/the-system/mockup-tool.ts

Modified
26 26 } from "./mockup.js";
28 28 const DESCRIPTION =
29 - "Show HTML-fragment mockup options in a browser and return selected options, notes, annotations, and accept/iterate action.";
29 + "Show HTML-fragment mockups in a browser for visual review. Returns accept or iterate, selected option IDs, notes, and annotations.";
30 30 const CACHE_TTL_MS = 30 * 24 * 60 * 60 * 1000;
31 31 const CACHE_LIMIT_BYTES = 256 * 1024 * 1024;
132 132 const tool = defineTool({
133 133 name: "mockup",
134 - label: "Mockup",
134 + label: "mockup",
135 135 description: DESCRIPTION,
136 - promptSnippet: DESCRIPTION,
136 + promptSnippet: "Review HTML mockups in a browser",
137 137 promptGuidelines: [
138 - "Use mockup for visual UI/layout/style choices when seeing options beats reading descriptions.",
139 - "Pass only HTML fragments in options[].html; never pass <!doctype>, <html>, <head>, or <body>.",
140 - "Create 1-4 options. One option is valid for review of a single screen.",
141 - "The tool owns browser communication, selection, notes, annotations, Accept, and Iterate. Do not ask the user to repeat browser feedback in chat.",
142 - "After an iterate result, revise the fragments and call mockup again. After accept, continue the design unless notes require another iteration.",
138 + "Use mockup when visual comparison beats prose for UI, layout, styling, or interaction decisions.",
139 + "Pass HTML fragments only; never include <!doctype>, <html>, <head>, or <body>.",
140 + "Provide 1-4 options; one option is valid when reviewing a single design.",
141 + "The tool owns browser review and feedback. Do not ask the user to repeat its result in chat.",
142 + "On iterate, revise the fragments and call mockup again. On accept, continue the design unless feedback requires another iteration.",
144 144 parameters,
145 145 renderCall(args, theme, context) {
146 - const title = theme.fg("toolTitle", theme.bold("mockup"));
146 + const text =
147 + (context.lastComponent as Text | undefined) ?? new Text("", 0, 0);
147 148 const optionCount = Array.isArray(args.options) ? args.options.length : 0;
148 - const lines = [
149 - title,
150 - theme.fg(
149 + const optionWord = `option${optionCount === 1 ? "" : "s"}`;
150 + let output = `${theme.fg("toolTitle", theme.bold("mockup"))} ${theme.fg("accent", args.title ?? "untitled")} ${theme.fg("toolOutput", `· ${optionCount} ${optionWord}${args.multi ? " · multi-select" : ""}`)}`;
151 + if (!context.expanded) {
152 + output += theme.fg(
151 153 "dim",
152 - `${args.title ?? "untitled"} · ${optionCount} option${optionCount === 1 ? "" : "s"}`,
153 - ),
154 - ];
155 - if (context.expanded && Array.isArray(args.options)) {
156 - for (const option of args.options)
157 - lines.push(theme.fg("muted", `- ${String(option.id)}`));
154 + ` (${keyHint("app.tools.expand", "to expand")})`,
155 + );
158 156 } else {
159 - lines.push(theme.fg("muted", keyHint("app.tools.expand", "to expand")));
157 + if (args.question)
158 + output += `\n${theme.fg("toolOutput", args.question)}`;
159 + for (const option of args.options ?? []) {
160 + const description = option.description
161 + ? theme.fg("dim", ` · ${option.description}`)
162 + : "";
163 + output += `\n${theme.fg("accent", String(option.id))} ${theme.fg("toolOutput", option.label)}${description}`;
161 - return new Text(lines.join("\n"), 0, 0);
166 + text.setText(output);
167 + return text;
163 - renderResult(result, context, theme) {
169 + renderResult(result, { expanded }, theme, context) {
170 + const text =
171 + (context.lastComponent as Text | undefined) ?? new Text("", 0, 0);
164 172 const details = result.details as Partial<MockupToolDetails> | undefined;
165 - if (!details) return new Text("", 0, 0);
173 + if (!details) {
174 + const output = result.content
175 + .filter(
176 + (item): item is { type: "text"; text: string } =>
177 + item.type === "text",
179 + .map((item) => item.text)
180 + .join("\n");
181 + text.setText(theme.fg(context.isError ? "error" : "muted", output));
182 + return text;
184 + const action = details.action ?? "submitted";
185 + const status =
186 + action === "accept"
187 + ? theme.fg("success", "✓ accepted")
188 + : theme.fg("warning", "↻ iterate");
189 + const selected = (details.selected ?? []).join(", ") || "none";
166 190 const annotations = details.annotations ?? [];
167 - const summary = `${details.action ?? "submitted"} · ${(details.selected ?? []).join(", ") || "none"} · ${annotations.length} annotation${annotations.length === 1 ? "" : "s"}`;
168 - if (!context.expanded) return new Text(theme.fg("dim", summary), 0, 0);
169 - return new Text(
170 - [
171 - theme.fg("dim", summary),
172 - details.notes ? `notes: ${details.notes}` : "notes: ",
173 - details.cacheManifest
174 - ? `cache: ${details.cacheManifest}`
175 - : "cache: unavailable",
176 - ].join("\n"),
177 - 0,
178 - );
191 + let output = `${status}${theme.fg("dim", ` · selected ${selected} · ${annotations.length} annotation${annotations.length === 1 ? "" : "s"}`)}`;
192 + if (!expanded) {
193 + output += theme.fg(
194 + "dim",
195 + ` (${keyHint("app.tools.expand", "to expand")})`,
196 + );
197 + } else {
198 + if (details.notes)
199 + output += `\n${theme.fg("toolOutput", `notes: ${details.notes}`)}`;
200 + for (const annotation of annotations) {
201 + output += `\n${theme.fg("accent", annotation.optionId)} ${theme.fg("dim", `@ ${Math.round(annotation.x * 100)}%,${Math.round(annotation.y * 100)}%`)} ${theme.fg("toolOutput", annotation.note)}`;
203 + if (details.history && details.history.length > 1)
204 + output += `\n${theme.fg("dim", `iterations: ${details.history.length}`)}`;
205 + if (details.cacheManifest)
206 + output += `\n${theme.fg("dim", `cache: ${details.cacheManifest}`)}`;
207 + else if (details.cacheError)
208 + output += `\n${theme.fg("warning", `cache unavailable: ${details.cacheError}`)}`;
210 + text.setText(output);
211 + return text;
180 213 async execute(toolCallId, params, signal, _onUpdate, ctx) {
181 214 const request = validateMockupRequest(params);

extensions/the-system/skills/the-system-gfm/SKILL.md

Added
new file mode 100644
1 +---
2 +name: the-system-gfm
3 +description: "Use only when current instructions contain The System Markdown contract and a GitHub Flavored Markdown (GFM) table, task list, footnote, autolink, or strikethrough has already been selected for the System document."
4 +---
6 +# The System GFM
8 +Do not choose a rich format or create another artifact.
9 +Apply the active System contracts first.
11 +## Tables
13 +Use a table only for a compact comparison or matrix.
14 +Keep every cell to one line and escape a literal pipe as `\|`.
15 +Use alignment markers only when alignment carries meaning.
17 +```markdown
18 +| Condition | Required result |
19 +| --- | --- |
20 +| Valid input | Accept |
21 +| Invalid input | Reject |
22 +```
24 +## Task lists
26 +Use task lists only for static checkable criteria, never progress or completion state.
27 +Keep criteria unchecked because `.system/board.json` owns operational state.
29 +```markdown
30 +- [ ] The invalid input is rejected.
31 +- [ ] The rejection explains the violated rule.
32 +```
34 +## Footnotes
36 +Use a footnote only when source detail would interrupt the claim.
37 +Keep it short and place its definition after the containing section.
39 +```markdown
40 +The format follows the published specification.[^gfm]
42 +[^gfm]: [GitHub Flavored Markdown specification](https://github.github.com/gfm/)
43 +```
45 +## Links and strikethrough
47 +Use descriptive links instead of bare autolinks.
48 +Keep local document and asset links relative; external sources use absolute HTTPS links.
49 +Do not use strikethrough to retain obsolete canonical text; replace or remove that text.
51 +Prefer ordinary prose or lists when these extensions add no structure.

extensions/the-system/skills/the-system-mermaid/SKILL.md

Added
new file mode 100644
1 +---
2 +name: the-system-mermaid
3 +description: "Use only when current instructions contain The System Markdown contract and a Mermaid diagram has already been selected to explain structure, decisions, interactions, states, entities, cardinality, or conceptual type relationships in the System document."
4 +---
6 +# The System Mermaid
8 +Do not choose a diagram or create another artifact.
9 +Apply the active System contracts first.
10 +Use one model per `mermaid` fence and introduce its claim in prose.
11 +Never diagram `/system` stage progression or duplicate board state.
13 +## Select the narrowest model
15 +- `flowchart` for bounded structure, dependencies, or decisions.
16 +- `sequenceDiagram` for interactions ordered over time.
17 +- `stateDiagram-v2` for domain states and transitions.
18 +- `erDiagram` for conceptual entities and cardinality.
19 +- `classDiagram` for conceptual static type relationships.
21 +### Flowchart
23 +Use `LR` for a short chain and `TB` for hierarchy or branching.
24 +Separate stable identifiers from quoted human labels.
26 +```mermaid
27 +flowchart LR
28 + request["Request"] --> policy{"Valid?"}
29 + policy -->|yes| result["Result"]
30 + policy -->|no| rejection["Rejection"]
31 +```
33 +### Sequence
35 +Declare participants when their order matters.
36 +Use solid arrows for calls and dashed arrows for replies.
37 +Use `alt` only for a material branch.
39 +```mermaid
40 +sequenceDiagram
41 + participant C as Client
42 + participant S as Service
43 + C->>S: Request
44 + alt accepted
45 + S-->>C: Result
46 + else rejected
47 + S-->>C: Error
48 + end
49 +```
51 +### State
53 +Use `[*]` for start or terminal state and label meaningful transitions.
54 +Model domain behavior, never plan, spec, issue, or board progress.
56 +```mermaid
57 +stateDiagram-v2
58 + [*] --> Draft
59 + Draft --> Published: approve
60 + Published --> [*]: retire
61 +```
63 +### Entity relationship
65 +Use singular conceptual entities and label relationships from the first entity's perspective.
66 +Cardinality markers are `o|` zero-or-one, `||` exactly-one, `o{` zero-or-more, and `|{` one-or-more.
67 +Omit storage fields and keys unless the artifact explicitly defines a physical schema.
69 +```mermaid
70 +erDiagram
71 + ACCOUNT ||--o{ INVOICE : receives
72 +```
74 +### Class
76 +Show conceptual types and relationships only.
77 +Omit members, methods, visibility, generics, and implementation types.
79 +```mermaid
80 +classDiagram
81 + Client --> Service : uses
82 +```
84 +## Portability
86 +Keep identifiers short, stable, and ASCII; labels may contain human text.
87 +Do not use bare lowercase `end` as a flowchart node or label because Mermaid reserves it.
88 +Split dense diagrams instead of styling around poor structure.
90 +Do not add Mermaid directives, configuration, themes, custom styles, HTML labels, callbacks, clickable nodes, icons, images, or remote assets.

extensions/the-system/skills/the-system-tex/SKILL.md

Added
new file mode 100644
1 +---
2 +name: the-system-tex
3 +description: "Use only when current instructions contain The System Markdown contract and TeX or LaTeX math has already been selected for an equation, formula, logical relation, set relation, or mathematical notation in the System document."
4 +---
6 +# The System TeX
8 +Do not choose math or create another artifact.
9 +Apply the active System contracts first.
10 +The renderer accepts MathJax TeX input, not complete TeX or LaTeX documents.
12 +## Delimiters
14 +Use single dollars for short inline notation:
16 +```markdown
17 +The retry delay is $d_n = \min(d_{max}, d_0 2^n)$.
18 +```
20 +Use double dollars on separate lines for one displayed relation:
22 +```markdown
23 +$$
24 +P(A \mid B) = \frac{P(B \mid A)P(A)}{P(B)}
25 +$$
26 +```
28 +Escape a literal currency dollar as `\$`.
29 +Do not use `\(...\)` or `\[...\]`; the Markdown parser recognizes dollar delimiters.
31 +## Compact notation
33 +- Subscript and exponent: `x_i`, `x^2`
34 +- Fraction and root: `\frac{a}{b}`, `\sqrt{x}`
35 +- Sum and product: `\sum_{i=1}^{n}`, `\prod_{i=1}^{n}`
36 +- Logic: `\forall`, `\exists`, `\land`, `\lor`, `\neg`, `\Rightarrow`
37 +- Sets: `\in`, `\notin`, `\subseteq`, `\cup`, `\cap`, `\varnothing`
38 +- Short labels inside math: `\text{accepted}`
40 +Define every non-obvious symbol in adjacent prose.
41 +Keep units and explanatory sentences outside math.
43 +Do not add preambles, packages, custom macros, renderer configuration, TikZ, or text-heavy formulas.
44 +Prefer prose when notation does not shorten or clarify the claim.

extensions/the-system/system-command.ts

Modified
41 41 type CommandOptions = Omit<RegisteredCommand, "name" | "sourceInfo">;
42 42 type SystemCommandHooks = Readonly<{
43 + beginLifecycle?: () => void;
43 44 activateArtifactTool?: () => void;
44 45 activateAssessmentTool?: (cwd: string) => void;
45 46 activateBundleMigration?: () => void;
120 121 return;
122 - await ctx.waitForIdle();
123 + hooks.beginLifecycle?.();
123 124 if (ARTIFACT_SUBCOMMANDS.has(parsed.subcommand))
124 125 hooks.activateArtifactTool?.();
125 126 if (parsed.subcommand === "assess")
126 127 hooks.activateAssessmentTool?.(ctx.cwd);
127 128 pi.sendUserMessage(systemPromptFor(parsed.subcommand, parsed.rest));
129 + if (ctx.mode === "print" || ctx.mode === "json") {
130 + await new Promise((resolve) => setTimeout(resolve, 0));
131 + await ctx.waitForIdle();
203 208 ctx.ui.notify("/system init cancelled", "info");
204 209 return;
211 + const reloadRequired =
212 + inspection.creates.length > 0 ||
213 + inspection.rewrites.length > 0 ||
214 + inspection.cores.some((core) => core.state === "missing");
206 215 const result = applyInitialization(ctx.cwd, requested, true);
207 216 ctx.ui.notify(
209 218 `Initialized The System at ${result.root}`,
210 219 `Prefix: ${result.prefix}`,
211 220 ...result.changed.map((item) => `Wrote: ${item}`),
221 + ...(reloadRequired
222 + ? ["Run /reload to activate System format skills."]
223 + : []),
212 224 ].join("\n"),
213 225 "info",

extensions/the-system/system-prompts.ts

Modified
23 23 Research references no System stage type.
24 24 Specs may reference research.
25 +Operate only the explicitly invoked /system lifecycle stage.
26 +Never auto-chain stages or create artifacts for another stage.
27 +You may recommend another stage; wait for explicit human invocation.
25 28 Phases are project-wide operating epochs related to MISSION, not spec decomposition or work breakdown.
26 29 Phase labels contain 1-12 ASCII letters, digits, dots, underscores, or hyphens.
27 30 Plans reference one spec and may depend on earlier plans for the same spec.
28 31 Issues may reference zero or more specs and have no status field.
29 -Approved plans are immutable; create a new artifact instead.
30 -Existing phases and specs require human approval before mutation.
32 +Approved plans are immutable outside an explicitly approved /system init bundle migration; otherwise create a new artifact.
33 +Mutating existing files in phase and spec bundles requires human approval.
31 34 The optional config currentPhase ID selects the project-wide operating phase.
32 35 Changing currentPhase requires explicit human confirmation.
33 36 Keep prose terse, minimal, and essential.
40 43 export const MARKDOWN_CONTRACT = `# The System Markdown contract
42 45 Use readable Markdown.
46 +Prefer visual explanations and diagrams when they clarify structure or relationships.
43 47 Use GFM tables/task lists only when they clarify.
44 48 Use Mermaid, TeX, raw HTML, and assets only when prose is worse.
45 -Keep links relative or ID-clear so /system view and /system book can resolve them.
46 -Plans contain no real code snippets; terse pseudocode only for critical paths.
49 +After choosing GFM, TeX, or Mermaid, load its matching the-system-* skill.
50 +Keep local Markdown links relative so /system view and /system book can resolve them.
51 +System documents contain no real code snippets; use terse pseudocode only when essential.
49 54 const BOARD_CONTRACT = `# The System board contract
85 90 If relevant specs exist, ask whether later specs should reference the research; research artifacts never link to stages.`,
86 91 spec: `Create or amend terse specs as context requires.
87 92 Capture high-level intent, scope, behavior, constraints, and acceptance criteria.
93 +Use mockup for visual elements, UI, layout, and interaction choices.
94 +After acceptance, save the selected HTML as a spec-bundle asset, link it from index.md, and encode feedback as behavior and constraints.
88 95 Do not prescribe implementation.
89 96 Specs may reference research.`,
90 97 "spec-verify": `Verify a spec experimentally.
95 102 Assess current implementation progress for the requested specs, plans, and issues.
96 103 Inspect current code and tests deeply enough to justify each proposed state.
97 104 Do not edit bundles or .system/board.json.
98 -Call system_board_propose with evidence-backed changes only.
105 +Submit the assessment through system_board_propose.
99 106 Omit items whose state cannot be assessed responsibly.`,
100 107 phase: `Inspect MISSION and the current phase first.
101 108 Create, amend, or transition one terse project-wide operating phase as context requires.