repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by bugabinga

feat(the-system): refine governed bundle workflow

444451a8846cc9468e1b2082ab22991a0d1a2eb6

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

SSH signature · not checked

Browse filesCompare with HEAD

Rename approval states, remove issue status, and allocate title-derived bundle IDs through a turn-scoped tool. Open rendered pages on Win32 without flashing a command window.

Changed files (19)

CHANGELOG.md

Modified
75 75 - Fix `/system edit` fallback selection so `termux-open` is used only on Termux/Android and other platforms keep their native editor fallback
76 76 - Fix The System document prompt and governance to require plural artifact directories and block unknown `.system` paths such as `.system/spec`
77 77 - Fix `/system view` and `/system book` HTML output so rendered pages include document bodies and open in the browser
78 +- Fix `/system view` and `/system book` on Windows to use the native URL handler without flashing a command window
78 79 - Fix rich System doc rendering so heading anchors are document-scoped and iframe embeds use browser-loadable file URLs
79 80 - Fix `/system book` Mermaid diagrams so they load from local file output in browsers
80 81 - Fix `/system book` layout so the On this page sidebar and referenced-by panels no longer overlap content, referenced-by panels are collapsible at the end of pages, the dossier uses full width, header elements align, empty diagnostics are hidden, law navigation avoids duplicate labels, project metadata is used for titles and favicons, and graph labels no longer overflow boxes
89 90 - Update The System lifecycle design around one `/system` command with subcommands for init, doctor, view, book, research, spec, spec-verify, phase, plan, issue, and exec
90 91 - Update The System lifecycle stages: the small path is `spec -> exec`; the larger path is `research -> spec -> spec-verify -> phase -> plan -> exec`; optional stages never auto-chain
91 92 - Update The System lifecycle IDs to schema v3 token IDs and rename roadmap terminology to phase terminology
92 -- Update The System lifecycle design so phase and plan status is `draft` or `done`; `done` means human-approved, immutable, and exec-eligible, while supersession happens by creating a new artifact with prose references
93 -- Require interactive approval before changing a phase or plan from `draft` to `done`
94 -- Update The System lifecycle metadata: specs have `id`, `type`, `title`, and optional `research`; phases have `spec`, `status: draft|done`, and optional `depends_on`; plans have `spec`, optional `phase`, `status: draft|done`, and optional `depends_on`; issues have `specs` and `status: open|done`; `spec-verify` creates no canonical document
93 +- Update The System lifecycle design so phase and plan status is `draft` or `approved`; `approved` means human-approved, immutable, and exec-eligible, while supersession happens by creating a new artifact with prose references
94 +- Require interactive approval before changing a phase or plan from `draft` to `approved`
95 +- Add turn-scoped `system_slot` allocation so semantic titles produce slugs and one command can reserve multiple unique bundle IDs
96 +- Update The System lifecycle metadata: specs have `id`, `type`, `title`, and optional `research`; phases have `spec`, `status: draft|approved`, and optional `depends_on`; plans have `spec`, optional `phase`, `status: draft|approved`, and optional `depends_on`; issues have `specs` without status; `spec-verify` creates no canonical document
95 97 - Add The System dependency validation and rendering for phase and plan `depends_on`, including same-spec checks, dangling-reference and cycle diagnostics, reference graph edges, and dependency-aware book ordering
96 98 - Update The System rich-Markdown design to use phases instead of roadmaps in the lifecycle model
97 99 - Remove The System exported skills and top-level prompt templates; `/system` subcommands use internal prompt includes for document and Markdown knowledge

docs/super/specs/2026-07-15-the-system-rich-markdown-design.md

Modified
135 135 Stage prompts own lifecycle behavior, and `/system exec` owns code, test, debug, review, and git guidance only inside that command.
137 -Agents allocate IDs and paths from the System document contract, while extension write/edit gates block invalid documents and return actionable frontmatter or path errors.
137 +Artifact-authoring commands temporarily enable `system_slot` for their agent run.
139 +After choosing semantic titles, the agent calls `system_slot` for each new bundle and uses the returned IDs and paths exactly.
141 +Context determines which bundles, if any, the command creates.
143 +The extension derives each slug from its bundle title.
145 +Extension write/edit gates block invalid documents and return actionable frontmatter or path errors.
139 147 After creating or materially editing an artifact, the agent prints a copyable view line:
164 172 Issues amend or create specs only when the issue exposes a spec gap; normal bugs and security fixes do not force spec amendment.
166 -Finished phases and plans are immutable.
174 +Approved phases and plans are immutable.
168 -Create a new phase or plan instead of editing a finished one.
176 +Create a new phase or plan instead of editing an approved one.
170 178 The extension enforces immutability from frontmatter status.
181 -The extension owns lifecycle directories, type names, token generation, status enums, and metadata validation.
189 +The extension owns lifecycle directories, type names, token generation, the phase and plan status enum, and metadata validation.
183 191 Frontmatter references store IDs only; body links may use relative paths, slugs, or normal Markdown links that the renderer resolves.
185 193 Required known frontmatter fields are:
187 -| Type | Fields |
188 -| ---------- | --------------------------------------------------------------------- |
189 -| `research` | `id`, `type: research`, `title` |
190 -| `spec` | `id`, `type: spec`, `title`, optional `research: string[]` |
191 -| `phase` | `id`, `type: phase`, `title`, `spec`, `status: draft |
192 -| `plan` | `id`, `type: plan`, `title`, `spec`, optional `phase`, `status: draft |
193 -| `issue` | `id`, `type: issue`, `title`, `specs: string[]`, `status: open |
195 +| Type | Fields |
196 +| ---------- | ------------------------------------------------------------------------------- |
197 +| `research` | `id`, `type: research`, `title` |
198 +| `spec` | `id`, `type: spec`, `title`, optional `research: string[]` |
199 +| `phase` | `id`, `type: phase`, `title`, `spec`, `status: draft\|approved` |
200 +| `plan` | `id`, `type: plan`, `title`, `spec`, optional `phase`, `status: draft\|approved` |
201 +| `issue` | `id`, `type: issue`, `title`, `specs: string[]` |
195 203 Research references no System stage.
203 211 Issues may reference as many specs as make sense and may start with an empty array while the contract is unknown.
205 -Phase and plan `done` means human-approved, immutable, and eligible for exec.
213 +Phase and plan `approved` means human-approved, immutable, and eligible for exec.
207 -Specs and research have no status and remain editable under normal ownership gates.
215 +Specs, research, and issues have no status.
217 +Specs remain editable under ownership gates; research and issues remain editable.
209 219 Tests still use `SYSTEM-SPEC: <SPEC-ID>` comments when a test directly proves a spec contract.
221 231 Spec verification records claims checked, evidence, result, and proposed spec amendments; it does not become canonical project state.
223 -Phases record coarse milestones, ordering, dependencies, risks, and done criteria.
233 +Phases record coarse milestones, ordering, dependencies, risks, and completion criteria.
225 235 Plans record concrete implementation steps and checks at module, interface, package, or class level.
231 241 Terse pseudocode is allowed only when needed to explain an important change.
233 -Issues record symptom, impact, reproduction or evidence, related specs, and status.
243 +Issues record symptom, impact, reproduction or evidence, and related specs.
235 245 Exec logs record System refs, changed areas, verification evidence, and the copyable view line.

extensions/the-system/CHANGELOG.md

Modified
4 4 # Changelog
6 6 ## Unreleased
8 8 - Migrate The System documents to rich Markdown bundles with YAML graph metadata,
9 9 config-only machine state, doctor validation, and file-level spec ownership.
10 +- Rename phase and plan status `done` to `approved`; remove issue status.
11 +- Open rendered pages through the native Win32 URL handler without flashing a command window.
12 +- Add turn-scoped `system_slot` allocation with title-derived slugs and repeatable ID reservation.
11 14 ## 0.0.3

extensions/the-system/README.md

Modified
15 15 Lifecycle stages never auto-chain.
16 16 Agents may recommend the next stage, but humans invoke optional stages.
18 +## Tool
20 +Artifact-authoring commands temporarily enable `system_slot`.
21 +The agent calls it for each new bundle after choosing a semantic title, then uses the returned ID and path exactly.
22 +Context determines which bundles, if any, the command creates.
18 24 ## Documents
20 26 Canonical artifacts live at:
32 38 - research: `id`, `type: research`, `title`
33 39 - spec: `id`, `type: spec`, `title`, optional `research`
34 -- phase: `id`, `type: phase`, `title`, `spec`, `status: draft|done`
35 -- plan: `id`, `type: plan`, `title`, `spec`, optional `phase`, `status: draft|done`
36 -- issue: `id`, `type: issue`, `title`, `specs`, `status: open|done`
40 +- phase: `id`, `type: phase`, `title`, `spec`, `status: draft|approved`
41 +- plan: `id`, `type: plan`, `title`, `spec`, optional `phase`, `status: draft|approved`
42 +- issue: `id`, `type: issue`, `title`, `specs`
38 -Done phases and plans are immutable.
44 +Issues intentionally have no status field.
45 +Approved phases and plans are immutable.
39 46 Create a new artifact instead.
41 48 ## Resources

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

Modified
262 262 write(
264 264 ".system/issues/PX-ISSUE-ISSUE001-bug/index.md",
265 - "---\nid: PX-ISSUE-ISSUE001\ntype: issue\ntitle: Bug\nspecs: [PX-SPEC-SPEC0001]\nstatus: open\n---\n\n# Bug\n",
265 + "---\nid: PX-ISSUE-ISSUE001\ntype: issue\ntitle: Bug\nspecs: [PX-SPEC-SPEC0001]\n---\n\n# Bug\n",
267 267 return root;

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

Added
new file mode 100644
1 +import assert from "node:assert/strict";
2 +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
3 +import { tmpdir } from "node:os";
4 +import path from "node:path";
5 +import { initTheme } from "@earendil-works/pi-coding-agent";
6 +import { afterEach, describe, it } from "vitest";
7 +import { reserveArtifactSlot } from "../artifact-slot.ts";
8 +import { createArtifactSlotTool } from "../artifact-slot-tool.ts";
10 +const roots: string[] = [];
11 +const project = () => {
12 + const root = mkdtempSync(path.join(tmpdir(), "system-slot-"));
13 + roots.push(root);
14 + mkdirSync(path.join(root, ".git"));
15 + for (const directory of ["specs", "phases", "plans", "issues", "research"])
16 + mkdirSync(path.join(root, ".system", directory), { recursive: true });
17 + writeFileSync(
18 + path.join(root, ".system/config.json"),
19 + '{"prefix":"PX","schemaVersion":3}',
20 + );
21 + return root;
22 +};
24 +afterEach(() => {
25 + for (const root of roots.splice(0))
26 + rmSync(root, { recursive: true, force: true });
27 +});
29 +const theme = {
30 + fg: (_style: string, text: string) => text,
31 + bold: (text: string) => text,
32 +};
33 +const render = (component: { render(width: number): string[] }) =>
34 + component.render(120).join("\n");
36 +describe("system_slot", () => {
37 + it("derives semantic slugs and reserves unique IDs on demand", () => {
38 + const root = project();
39 + const reserved = new Set<string>();
40 + const first = reserveArtifactSlot(
41 + root,
42 + { type: "phase", title: "Service Übergang" },
43 + reserved,
44 + );
45 + const second = reserveArtifactSlot(
46 + root,
47 + { type: "phase", title: "Service Übergang" },
48 + reserved,
49 + );
50 + assert.equal(first.slug, "service-ubergang");
51 + assert.notEqual(first.id, second.id);
52 + assert.match(
53 + first.path,
54 + /^\.system\/phases\/PX-PHASE-[A-Z0-9_]{8}-service-ubergang\/index\.md$/,
55 + );
56 + });
58 + it("keeps prompting terse and renders human-useful mappings", () => {
59 + initTheme("default", false);
60 + const root = project();
61 + const slot = reserveArtifactSlot(root, {
62 + type: "plan",
63 + title: "Replace cache invalidation",
64 + });
65 + const tool = createArtifactSlotTool();
66 + assert.equal(
67 + tool.description,
68 + "Reserve an ID and canonical path for a new System bundle.",
69 + );
70 + 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.",
72 + ]);
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 + ),
81 + );
82 + assert.match(collapsed, new RegExp(slot.id));
83 + assert.match(collapsed, /replace-cache-invalidation/);
84 + assert.match(collapsed, /to expand/);
85 + const expanded = render(
86 + (tool.renderResult as Function)(
87 + result,
88 + { expanded: true, isPartial: false },
89 + theme,
90 + {},
91 + ),
92 + );
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}`));
96 + });
97 +});

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

Modified
136 - it("validates minimal status fields", () => {
136 + it("parses issue metadata without status and validates approval status", () => {
137 137 assert.deepEqual(
138 138 parseAuthoredDocument(
139 - "---\nid: PX-ISSUE-ISSUE001\ntype: issue\ntitle: Bug\nstatus: done\nspecs: []\n---\n",
139 + "---\nid: PX-ISSUE-ISSUE001\ntype: issue\ntitle: Bug\nspecs: []\n---\n",
141 141 ).metadata,
143 143 id: "PX-ISSUE-ISSUE001",
144 144 type: "issue",
145 145 title: "Bug",
146 - status: "done",
147 146 specs: [],
149 + assert.equal(
150 + parseAuthoredDocument(
151 + "---\nid: PX-PLAN-PLAN0001\ntype: plan\ntitle: Build\nspec: PX-SPEC-SPEC0001\nstatus: approved\n---\n",
152 + "PX",
153 + ).metadata.status,
154 + "approved",
155 + );
150 156 assert.throws(
152 158 parseAuthoredDocument(
153 - "---\nid: PX-ISSUE-ISSUE001\ntype: issue\ntitle: Bug\nstatus: fixed\nspecs: []\n---\n",
159 + "---\nid: PX-PLAN-PLAN0001\ntype: plan\ntitle: Build\nspec: PX-SPEC-SPEC0001\nstatus: done\n---\n",
156 - SystemDocumentError,
162 + /status must be draft or approved/,
259 265 "phases",
260 266 "PX-PHASE-PHASE001",
261 267 "delivery",
262 - "id: PX-PHASE-PHASE001\ntype: phase\ntitle: Delivery\nspec: PX-SPEC-SPEC0001\nstatus: done",
268 + "id: PX-PHASE-PHASE001\ntype: phase\ntitle: Delivery\nspec: PX-SPEC-SPEC0001\nstatus: approved",
264 270 source(
265 271 "plans",
349 355 "phases",
350 356 "PX-PHASE-PHASE001",
351 357 "delivery",
352 - "id: PX-PHASE-PHASE001\ntype: phase\ntitle: Delivery\nspec: PX-SPEC-MISSING1\nstatus: done",
358 + "id: PX-PHASE-PHASE001\ntype: phase\ntitle: Delivery\nspec: PX-SPEC-MISSING1\nstatus: approved",

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

Modified
1 1 import path from "node:path";
2 -import { afterEach, describe, expect, it } from "vitest";
2 +import { afterEach, describe, expect, it, vi } from "vitest";
3 3 import { createTestSession, type TestSession } from "../../../test/harness";
5 5 describe("the-system pi-test-harness", () => {
17 17 expect(t.session.extensionRunner.extensions).toHaveLength(1);
18 18 expect(t.session.extensionRunner.extensions[0].path).toBe(extensionPath);
21 + it("scopes system_slot to artifact command runs", async () => {
22 + const extensionPath = path.resolve(import.meta.dirname, "../index.ts");
23 + t = await createTestSession({ extensions: [extensionPath] });
24 + const [extension] = t.session.extensionRunner.extensions;
25 + const sendUserMessage = vi
26 + .spyOn(t.session, "sendUserMessage")
27 + .mockResolvedValue();
28 + expect(extension.tools.has("system_slot")).toBe(true);
29 + expect(t.session.getActiveToolNames()).not.toContain("system_slot");
30 + await extension.commands
31 + .get("system")
32 + .handler(
33 + "spec let us discuss caching",
34 + t.session.extensionRunner.createCommandContext(),
35 + );
36 + expect(sendUserMessage).toHaveBeenCalledOnce();
37 + expect(t.session.getActiveToolNames()).toContain("system_slot");
38 + expect(t.session.systemPrompt).toContain(
39 + "- system_slot: Reserve an ID and canonical path for a new System bundle.",
40 + );
41 + expect(t.session.systemPrompt).toContain(
42 + "- When context requires new bundles, call system_slot for each after choosing its title; use returned IDs and paths exactly.",
43 + );
44 + for (const handler of extension.handlers.get("agent_settled"))
45 + await handler(
46 + { type: "agent_settled", messages: [] },
47 + t.session.extensionRunner.createCommandContext(),
48 + );
49 + expect(t.session.getActiveToolNames()).not.toContain("system_slot");
50 + expect(t.session.systemPrompt).not.toContain("- system_slot:");
51 + });

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

Added
new file mode 100644
1 +import assert from "node:assert/strict";
2 +import {
3 + chmodSync,
4 + copyFileSync,
5 + existsSync,
6 + mkdtempSync,
7 + readFileSync,
8 + rmSync,
9 + writeFileSync,
10 +} from "node:fs";
11 +import { tmpdir } from "node:os";
12 +import path from "node:path";
13 +import { afterEach, describe, it } from "vitest";
14 +import { openHtmlFile } from "../open-browser.ts";
16 +const roots: string[] = [];
18 +afterEach(() => {
19 + for (const root of roots.splice(0))
20 + rmSync(root, { recursive: true, force: true });
21 +});
23 +describe("System browser opener", () => {
24 + it("opens through the native win32 URL handler without cmd", async () => {
25 + const root = mkdtempSync(path.join(tmpdir(), "system-browser-"));
26 + roots.push(root);
27 + const executable = path.join(root, "rundll32.exe");
28 + const preload = path.join(root, "record.cjs");
29 + const record = path.join(root, "args.json");
30 + const html = path.join(root, "system.html");
31 + copyFileSync(process.execPath, executable);
32 + chmodSync(executable, 0o755);
33 + writeFileSync(
34 + preload,
35 + `require("node:fs").writeFileSync(${JSON.stringify(record)}, JSON.stringify(process.argv.slice(1)));`,
36 + );
37 + writeFileSync(html, "<!doctype html><title>System</title>");
38 + const opened = await openHtmlFile(html, {
39 + platform: "win32",
40 + env: {
41 + ...process.env,
42 + PATH: root,
43 + NODE_ENV: "",
44 + VITEST: "",
45 + NODE_OPTIONS: `--require=${preload}`,
46 + },
47 + });
48 + assert.equal(opened.ok, true);
49 + if (!opened.ok) return;
50 + assert.equal(opened.command, "rundll32.exe");
51 + for (let attempt = 0; attempt < 100 && !existsSync(record); attempt++)
52 + await new Promise((resolve) => setTimeout(resolve, 10));
53 + const args = JSON.parse(readFileSync(record, "utf8")) as string[];
54 + assert.equal(path.basename(args[0] ?? ""), "url.dll,FileProtocolHandler");
55 + assert.equal(args[1], opened.url);
56 + });
57 +});

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

Modified
221 221 assert.match(closed?.reason ?? "", /interactive UI/);
224 - it("validates editable non-spec indexes and blocks done phase and plan bundles", async () => {
224 + it("validates editable non-spec indexes and blocks approved phase and plan bundles", async () => {
225 225 const project = root();
226 226 writeSpec(project);
227 227 const phase = ".system/phases/PX-PHASE-PHASE001-delivery/index.md";
235 235 type: "phase",
236 236 title: "Delivery",
237 237 spec: "PX-SPEC-SPEC0001",
238 - status: "done",
238 + status: "approved",
241 241 write(
247 247 title: "Build",
248 248 spec: "PX-SPEC-SPEC0001",
249 249 phase: "PX-PHASE-PHASE001",
250 - status: "done",
250 + status: "approved",
253 253 write(
257 257 id: "PX-ISSUE-ISSUE001",
258 258 type: "issue",
259 259 title: "Bug",
260 - status: "open",
261 260 specs: ["PX-SPEC-SPEC0001"],
272 271 approval(),
274 273 assert.equal(result?.block, true, relative);
275 - assert.match(result?.reason ?? "", /done/);
274 + assert.match(result?.reason ?? "", /approved/);
276 275 const asset = await preflightFileMutation(
277 276 project,
278 277 "write",
280 279 approval(),
282 281 assert.equal(asset?.block, true, relative);
283 - assert.match(asset?.reason ?? "", /done/);
282 + assert.match(asset?.reason ?? "", /approved/);
285 284 const draftPlan = ".system/plans/PX-PLAN-PLAN0002-draft/index.md";
286 285 write(
294 293 status: "draft",
297 - let doneApprovals = 0;
298 - const doneResult = await preflightFileMutation(
296 + let approvals = 0;
297 + const approvalResult = await preflightFileMutation(
299 298 project,
300 299 "edit",
302 301 path: draftPlan,
303 - edits: [{ oldText: "status: draft", newText: "status: done" }],
302 + edits: [{ oldText: "status: draft", newText: "status: approved" }],
306 305 hasUI: true,
307 306 select: async (_title, items) => {
308 - doneApprovals += 1;
307 + approvals += 1;
309 308 return items[0];
313 - assert.equal(doneResult?.block, undefined);
314 - assert.equal(doneApprovals, 1);
312 + assert.equal(approvalResult?.block, undefined);
313 + assert.equal(approvals, 1);
315 314 const issueResult = await preflightFileMutation(
316 315 project,
317 316 "edit",

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

Modified
102 102 describe("/system command", () => {
103 - it("registers only /system plus the generic mockup tool", () => {
103 + it("registers /system, mockup, and the scoped artifact slot tool", () => {
104 104 const commands: string[] = [];
105 105 const tools: string[] = [];
106 106 registerTheSystem({
109 109 on() {},
110 110 } as never);
111 111 assert.deepEqual(commands, ["system"]);
112 - assert.deepEqual(tools, ["mockup"]);
112 + assert.deepEqual(tools, ["mockup", "system_slot"]);
115 115 it("offers subcommand completions and help", async () => {
177 177 assert.match(notices[0] ?? "", /Initialized The System/);
180 - it("injects lifecycle prompts with shared contracts and generated artifact slots", async () => {
180 + it("injects lifecycle prompts and activates artifact allocation", async () => {
181 181 const project = temp();
182 182 validSystem(project);
183 183 const sent: string[] = [];
184 - const command = createSystemCommand({
185 - sendUserMessage: (message: string) => sent.push(message),
186 - } as never);
184 + let activations = 0;
185 + const command = createSystemCommand(
187 + sendUserMessage: (message: string) => sent.push(message),
188 + } as never,
189 + () => activations++,
190 + );
187 191 for (const subcommand of [
188 192 "research",
189 193 "spec",
201 205 } as never);
202 206 for (const message of sent)
203 207 assert.match(message, /The System document contract/);
204 - assert.match(
205 - sent.find(
206 - (item) =>
207 - item.includes("# /system spec\n") && item.includes("login flow"),
208 - ) ?? "",
209 - /Path: \.system\/specs\/PX-SPEC-[A-Z0-9_]{8}-login-flow\/index\.md/,
210 - );
211 - assert.doesNotMatch(
212 - sent.find((item) => item.includes("# /system spec-verify")) ?? "",
213 - /Extension-generated artifact slot/,
214 - );
208 + assert.equal(activations, 10);
209 + assert.doesNotMatch(sent.join("\n"), /Extension-generated artifact slot/);
215 210 assert.match(
216 211 sent.find((item) => item.includes("# /system exec")) ?? "",
217 212 /spec\+phase\+plan/,

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

Added
new file mode 100644
1 +import { StringEnum } from "@earendil-works/pi-ai";
2 +import { defineTool, keyHint } from "@earendil-works/pi-coding-agent";
3 +import { Text } from "@earendil-works/pi-tui";
4 +import { Type } from "typebox";
5 +import type { ArtifactSlot } from "./artifact-slot.js";
7 +const DESCRIPTION = "Reserve an ID and canonical path for a new System bundle.";
8 +const GUIDANCE =
9 + "When context requires new bundles, call system_slot for each after choosing its title; use returned IDs and paths exactly.";
10 +const ARTIFACT_TYPES = ["research", "spec", "phase", "plan", "issue"] as const;
12 +export function createArtifactSlotTool() {
13 + const reserved = new Set<string>();
14 + return defineTool({
15 + name: "system_slot",
16 + label: "System Slot",
17 + description: DESCRIPTION,
18 + promptSnippet: DESCRIPTION,
19 + promptGuidelines: [GUIDANCE],
20 + parameters: Type.Object({
21 + type: StringEnum(ARTIFACT_TYPES, {
22 + description: "System bundle type.",
23 + }),
24 + title: Type.String({
25 + minLength: 1,
26 + description: "Final semantic bundle title used to derive the slug.",
27 + }),
28 + }),
29 + 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,
63 + );
64 + },
65 + async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
66 + const { reserveArtifactSlot } = await import("./artifact-slot.js");
67 + const slot = reserveArtifactSlot(ctx.cwd, params, reserved);
68 + return {
69 + content: [
70 + {
71 + type: "text" as const,
72 + text: [
73 + `Reserved ${slot.type} bundle.`,
74 + `Title: ${slot.title}`,
75 + `ID: ${slot.id}`,
76 + `Path: ${slot.path}`,
77 + "Use the ID and path exactly.",
78 + ].join("\n"),
79 + },
80 + ],
81 + details: slot,
82 + };
83 + },
84 + });
87 +function bounded(value: string, limit: number): string {
88 + return value.length <= limit ? value : `${value.slice(0, limit - 1)}…`;

extensions/the-system/artifact-slot.ts

Added
new file mode 100644
1 +import { randomBytes } from "node:crypto";
2 +import { readFileSync } from "node:fs";
3 +import path from "node:path";
4 +import {
5 + directoryForType,
6 + discoverDocumentBundles,
7 + discoverProjectRoot,
8 + indexBundleDocuments,
9 + parseSystemConfig,
10 +} from "./documents.js";
12 +export type ArtifactType = "research" | "spec" | "phase" | "plan" | "issue";
13 +export type ArtifactSlot = Readonly<{
14 + type: ArtifactType;
15 + title: string;
16 + id: string;
17 + slug: string;
18 + path: string;
19 +}>;
21 +export function reserveArtifactSlot(
22 + cwd: string,
23 + input: { type: ArtifactType; title: string },
24 + reserved: Set<string> = new Set(),
25 +): ArtifactSlot {
26 + const root = discoverProjectRoot(cwd);
27 + const config = parseSystemConfig(
28 + readFileSync(path.join(root, ".system/config.json"), "utf8"),
29 + );
30 + const discovery = discoverDocumentBundles(root);
31 + const indexed = indexBundleDocuments(discovery.sources, config.prefix);
32 + const existing = new Set([
33 + ...indexed.documents.map((document) => document.metadata.id),
34 + ...reserved,
35 + ]);
36 + const title = input.title.trim();
37 + if (!title) throw new Error("System bundle title must not be empty");
38 + const id = generateDocumentId(config.prefix, input.type, existing);
39 + reserved.add(id);
40 + const slug = slugForTitle(title);
41 + return {
42 + type: input.type,
43 + title,
44 + id,
45 + slug,
46 + path: `.system/${directoryForType(input.type)}/${id}-${slug}/index.md`,
47 + };
50 +function generateDocumentId(
51 + prefix: string,
52 + type: ArtifactType,
53 + existing: ReadonlySet<string>,
54 +): string {
55 + while (true) {
56 + const token = randomBytes(6)
57 + .toString("base64url")
58 + .toUpperCase()
59 + .replaceAll("-", "_");
60 + const id = `${prefix}-${type.toUpperCase()}-${token}`;
61 + if (!existing.has(id)) return id;
62 + }
65 +function slugForTitle(title: string): string {
66 + const slug = title
67 + .normalize("NFKD")
68 + .replace(/\p{Mark}/gu, "")
69 + .toLowerCase()
70 + .replace(/[^a-z0-9]+/g, "-")
71 + .replace(/^-|-$/g, "")
72 + .slice(0, 48)
73 + .replace(/-$/g, "");
74 + return slug || "artifact";

extensions/the-system/documents.ts

Modified
66 66 type: "phase";
67 67 title: string;
68 68 spec: string;
69 - status: "draft" | "done";
69 + status: "draft" | "approved";
70 70 depends_on?: readonly string[];
72 72 export type PlanMetadata = Readonly<{
75 75 title: string;
76 76 spec: string;
77 77 phase?: string;
78 - status: "draft" | "done";
78 + status: "draft" | "approved";
79 79 depends_on?: readonly string[];
81 81 export type IssueMetadata = Readonly<{
82 82 id: string;
83 83 type: "issue";
84 84 title: string;
85 - status: "open" | "done";
86 85 specs: readonly string[];
88 87 export type DocumentMetadata =
424 423 spec: reference("spec", "spec"),
425 424 status: statusField(
426 425 fields,
427 - ["draft", "done"],
428 - "Phase status must be draft or done",
426 + ["draft", "approved"],
427 + "Phase status must be draft or approved",
430 429 ...(depends_on ? { depends_on } : {}),
447 446 ...(typeof phase === "string" ? { phase } : {}),
448 447 status: statusField(
449 448 fields,
450 - ["draft", "done"],
451 - "Plan status must be draft or done",
449 + ["draft", "approved"],
450 + "Plan status must be draft or approved",
453 452 ...(depends_on ? { depends_on } : {}),
460 459 title,
461 - status: statusField(
462 - fields,
463 - ["open", "done"],
464 - "Issue status must be open or done",
465 - ),
466 460 specs: requiredUniqueStrings(fields, "specs"),
468 462 default:

extensions/the-system/index.ts

Modified
3 3 import {
4 4 type ExtensionAPI,
5 5 type ExtensionContext,
6 6 isToolCallEventType,
7 7 } from "@earendil-works/pi-coding-agent";
8 +import { createArtifactSlotTool } from "./artifact-slot-tool.js";
8 9 import { createMockupRuntime } from "./mockup-tool.js";
9 10 import { systemArgumentCompletions } from "./system-command-meta.js";
17 18 let generation = 0;
18 19 let notified = false;
19 20 const mockup = createMockupRuntime();
21 + const artifactSlot = createArtifactSlotTool();
22 + let artifactSlotRunActive = false;
23 + const activateArtifactSlot = () => {
24 + const active = pi.getActiveTools();
25 + if (!active.includes(artifactSlot.name))
26 + pi.setActiveTools([...active, artifactSlot.name]);
27 + artifactSlotRunActive = true;
28 + };
29 + const deactivateArtifactSlot = () => {
30 + const active = pi.getActiveTools();
31 + if (active.includes(artifactSlot.name))
32 + pi.setActiveTools(active.filter((name) => name !== artifactSlot.name));
33 + artifactSlotRunActive = false;
34 + };
21 36 const notifyOnce = async (ctx: ExtensionContext, ticket: number) => {
22 37 if (notified || ticket !== generation) return;
35 50 pi.on("session_start", (_event, ctx) => {
51 + deactivateArtifactSlot();
36 52 const ticket = ++generation;
37 53 notified = false;
38 54 mockup.remember(ctx);
47 63 pi.on("session_shutdown", (_event, ctx) => {
48 64 generation++;
49 65 notified = false;
66 + artifactSlotRunActive = false;
50 67 mockup.shutdown(ctx);
52 69 pi.on("before_agent_start", async (event, ctx) => {
63 80 : systemPrompt,
66 - pi.on("agent_settled", (_event, ctx) => mockup.agentSettled(ctx));
83 + pi.on("agent_settled", (_event, ctx) => {
84 + mockup.agentSettled(ctx);
85 + if (artifactSlotRunActive) deactivateArtifactSlot();
86 + });
67 87 pi.on("tool_call", async (event, ctx) => {
68 88 if (
69 89 !isToolCallEventType("write", event) &&
84 104 pi.registerTool(mockup.tool);
105 + pi.registerTool(artifactSlot);
85 106 pi.registerCommand("system", {
86 107 description: "The System project governance",
87 108 getArgumentCompletions: systemArgumentCompletions,
88 109 handler: async (args, ctx) => {
89 110 const { createSystemCommand } = await import("./system-command.js");
90 - await createSystemCommand(pi).handler(args, ctx);
111 + await createSystemCommand(pi, activateArtifactSlot).handler(args, ctx);

extensions/the-system/open-browser.ts

Modified
5 5 | { ok: true; url: string; command: string }
6 6 | { ok: false; url: string; error: string };
8 -export async function openHtmlFile(file: string): Promise<BrowserOpenResult> {
8 +export async function openHtmlFile(
9 + file: string,
10 + options: { platform?: NodeJS.Platform; env?: NodeJS.ProcessEnv } = {},
11 +): Promise<BrowserOpenResult> {
9 12 const url = pathToFileURL(file).href;
10 - if (process.env.NODE_ENV === "test" || process.env.VITEST)
13 + const env = options.env ?? process.env;
14 + if (env.NODE_ENV === "test" || env.VITEST)
11 15 return { ok: false, url, error: "Browser opener disabled" };
12 - for (const candidate of openerCandidates(url)) {
13 - const ok = await trySpawn(candidate.command, candidate.args);
16 + for (const candidate of openerCandidates(url, options)) {
17 + const ok = await trySpawn(candidate.command, candidate.args, env);
14 18 if (ok) return { ok: true, url, command: candidate.command };
16 20 return { ok: false, url, error: "No browser opener found" };
19 -function openerCandidates(
23 +export type BrowserOpenerCandidate = {
24 + command: string;
25 + args: string[];
26 +};
28 +export function openerCandidates(
20 29 url: string,
21 -): Array<{ command: string; args: string[] }> {
22 - if (process.env.TERMUX_VERSION)
23 - return [{ command: "termux-open-url", args: [url] }];
24 - if (process.platform === "darwin") return [{ command: "open", args: [url] }];
25 - if (process.platform === "win32")
26 - return [{ command: "cmd.exe", args: ["/c", "start", "", url] }];
30 + options: { platform?: NodeJS.Platform; env?: NodeJS.ProcessEnv } = {},
31 +): BrowserOpenerCandidate[] {
32 + const platform = options.platform ?? process.platform;
33 + const env = options.env ?? process.env;
34 + if (env.TERMUX_VERSION) return [{ command: "termux-open-url", args: [url] }];
35 + if (platform === "darwin") return [{ command: "open", args: [url] }];
36 + if (platform === "win32")
37 + return [
38 + {
39 + command: "rundll32.exe",
40 + args: ["url.dll,FileProtocolHandler", url],
41 + },
42 + ];
27 43 return [
28 44 { command: "xdg-open", args: [url] },
29 45 { command: "wslview", args: [url] },
34 -function trySpawn(command: string, args: string[]): Promise<boolean> {
50 +function trySpawn(
51 + command: string,
52 + args: string[],
53 + env: NodeJS.ProcessEnv,
54 +): Promise<boolean> {
35 55 return new Promise((resolve) => {
36 - const child = spawn(command, args, { detached: true, stdio: "ignore" });
56 + const child = spawn(command, args, {
57 + detached: true,
58 + stdio: "ignore",
59 + windowsHide: true,
60 + env,
61 + });
37 62 let settled = false;
38 63 const done = (ok: boolean) => {
39 64 if (settled) return;

extensions/the-system/system-command.ts

Modified
1 -import { randomBytes } from "node:crypto";
2 1 import { lstatSync, readFileSync } from "node:fs";
3 2 import path from "node:path";
4 3 import type {
8 7 } from "@earendil-works/pi-coding-agent";
9 8 import { runDoctor } from "./doctor.ts";
10 9 import {
11 - type DocumentType,
12 - directoryForType,
13 10 discoverDocumentBundles,
14 11 discoverProjectRoot,
15 12 indexBundleDocuments,
30 27 "issue",
31 28 "exec",
30 +const ARTIFACT_SUBCOMMANDS = new Set([
31 + "research",
32 + "spec",
33 + "phase",
34 + "plan",
35 + "issue",
36 +]);
33 37 const NON_LIFECYCLE = new Set(["init", "doctor", "view", "book", "edit"]);
34 38 type CommandOptions = Omit<RegisteredCommand, "name" | "sourceInfo">;
36 -export function createSystemCommand(pi: ExtensionAPI): CommandOptions {
40 +export function createSystemCommand(
41 + pi: ExtensionAPI,
42 + activateArtifactTool: () => void = () => {},
43 +): CommandOptions {
37 44 return {
38 45 description: "The System project governance",
39 46 getArgumentCompletions: systemArgumentCompletions,
89 96 return;
91 98 await ctx.waitForIdle();
92 - pi.sendUserMessage(
93 - systemPromptFor(
94 - parsed.subcommand,
95 - parsed.rest,
96 - generatedArtifactSlot(ctx.cwd, parsed.subcommand, parsed.rest),
97 - ),
98 - );
99 + if (ARTIFACT_SUBCOMMANDS.has(parsed.subcommand)) activateArtifactTool();
100 + pi.sendUserMessage(systemPromptFor(parsed.subcommand, parsed.rest));
286 288 throw new Error(`No System document: ${selector}`);
289 -function generatedArtifactSlot(
290 - cwd: string,
291 - subcommand: string,
292 - instructions: string,
293 -): string | undefined {
294 - const type = stageDocumentType(subcommand);
295 - if (!type) return undefined;
296 - let index: ReturnType<typeof projectIndex>;
297 - try {
298 - index = projectIndex(cwd);
299 - } catch {
300 - return undefined;
301 - }
302 - const id = generateDocumentId(
303 - parseSystemConfig(
304 - readFileSync(path.join(index.root, ".system/config.json"), "utf8"),
305 - ).prefix,
306 - type,
307 - new Set(index.documents.map((document) => document.metadata.id)),
308 - );
309 - const slug = slugFor(instructions || type);
310 - return [
311 - `For a new ${type} artifact, use this extension-generated ID and path exactly:`,
312 - `ID: ${id}`,
313 - `Path: .system/${directoryForType(type)}/${id}-${slug}/index.md`,
314 - "If amending an existing artifact, do not create this path.",
315 - ].join("\n");
318 -function stageDocumentType(subcommand: string): DocumentType | undefined {
319 - if (["research", "spec", "phase", "plan", "issue"].includes(subcommand))
320 - return subcommand as DocumentType;
321 - return undefined;
324 -function generateDocumentId(
325 - prefix: string,
326 - type: DocumentType,
327 - existing: ReadonlySet<string>,
328 -): string {
329 - while (true) {
330 - const token = randomBytes(6)
331 - .toString("base64url")
332 - .toUpperCase()
333 - .replaceAll("-", "_");
334 - const id = `${prefix}-${type.toUpperCase()}-${token}`;
335 - if (!existing.has(id)) return id;
336 - }
339 -function slugFor(source: string): string {
340 - const slug = source
341 - .toLowerCase()
342 - .replace(/[^a-z0-9]+/g, "-")
343 - .replace(/^-|-$/g, "")
344 - .slice(0, 48)
345 - .replace(/-$/g, "");
346 - return slug || "artifact";
349 291 async function openNotice(label: string, output: string): Promise<string> {
350 292 const opened = await openHtmlFile(output);
351 293 if (opened.ok)

extensions/the-system/system-prompts.ts

Modified
15 15 Required frontmatter:
16 16 - research: id, type: research, title
17 17 - spec: id, type: spec, title, optional research: string[]
18 -- phase: id, type: phase, title, spec, status: draft|done, optional depends_on: phase ID[]
19 -- plan: id, type: plan, title, spec, optional phase, status: draft|done, optional depends_on: plan ID[]
20 -- issue: id, type: issue, title, specs: string[], status: open|done
18 +- phase: id, type: phase, title, spec, status: draft|approved, optional depends_on: phase ID[]
19 +- plan: id, type: plan, title, spec, optional phase, status: draft|approved, optional depends_on: plan ID[]
20 +- issue: id, type: issue, title, specs: string[]
22 22 Research references no System stage type.
23 23 Specs may reference research.
24 24 Phases reference one spec and may depend on earlier phases for the same spec.
25 25 Plans reference one spec, may reference one phase for the same spec, and may depend on earlier plans for the same spec.
26 -Issues may reference zero or more specs.
27 -Done phases and plans are immutable; create a new artifact instead.
26 +Issues may reference zero or more specs and have no status field.
27 +Approved phases and plans are immutable; create a new artifact instead.
28 28 Keep prose terse, minimal, and essential.
29 29 After creating or materially editing an artifact, end with:
46 46 Implement only what the referenced System artifacts require.
47 47 Valid exec inputs: spec; spec+phase; spec+plan; spec+phase+plan; optional issue context.
48 -Phase and plan inputs must be status: done.
48 +Phase and plan inputs must be status: approved.
49 49 Use tests for nontrivial behavior.
50 50 Debug root cause before fixing bugs.
51 -Before claiming done, run fresh verification and read the full result.
51 +Before claiming implementation complete, run fresh verification and read the full result.
52 52 Final log includes refs, changed areas, verification, and a copyable View block.
53 53 Commit messages tell the document-linked story, not file/test inventory.
62 62 doctor: `Diagnose .system without mutation.
63 63 Run the deterministic doctor and explain each finding.
64 64 Do not initialize, repair, rename, delete, or upgrade files.`,
65 - research: `Create or amend terse research.
65 + research: `Develop terse research artifacts as context requires.
66 66 Collect technical or domain knowledge vital to the project.
67 67 Record facts, sources, conclusions, and unresolved questions only.
68 -If relevant specs exist, ask whether a later spec should reference this research; research itself never links to stages.`,
69 - spec: `Create or amend a terse spec.
68 +If relevant specs exist, ask whether later specs should reference the research; research artifacts never link to stages.`,
69 + spec: `Create or amend terse specs as context requires.
70 70 Capture high-level intent, scope, behavior, constraints, and acceptance criteria.
71 71 Do not prescribe implementation.
72 72 Specs may reference research.`,
74 74 Find logical inconsistencies, holes, risky claims, or false assumptions.
75 75 Use ephemeral probes only.
76 76 Produce evidence and proposed spec amendments; do not create a canonical artifact.`,
77 - phase: `Create a terse phase artifact for a large spec.
78 -Break the spec into high-level steps, dependencies, risks, and done criteria.
79 -Set status: draft until human approval; status: done means approved and immutable.`,
80 - plan: `Create a terse implementation plan for a spec or phase.
77 + phase: `Create or amend terse phase artifacts for large specs as context requires.
78 +Break specs into high-level steps, dependencies, risks, and completion criteria.
79 +Use status: draft until approval.
80 +Status: approved requires human approval and makes each phase immutable.`,
81 + plan: `Create or amend terse implementation plans for specs or phases as context requires.
81 82 Plan at module, interface, package, or class level.
82 83 Avoid function and line detail except critical paths.
83 84 Do not include real code snippets.
84 85 Use terse pseudocode only when necessary.
85 -Set status: draft until human approval; status: done means approved and immutable.`,
86 - issue: `Create or amend a terse issue.
87 -Record symptom, impact, reproduction or evidence, related specs, and status.
86 +Use status: draft until approval.
87 +Status: approved requires human approval and makes each plan immutable.`,
88 + issue: `Create or amend terse issues as context requires.
89 +Record symptom, impact, reproduction or evidence, and related specs.
88 90 Use specs: [] while the violated contract is unknown.
89 -Amend or create a spec only when the issue exposes a spec gap.`,
91 +Amend or create specs only when issues expose spec gaps.`,
90 92 exec: EXEC_CONTRACT,
103 105 export function systemPromptFor(
104 106 subcommand: string,
105 107 instructions: string,
106 - generatedArtifact?: string,
107 108 ): string {
108 109 const stage = STAGE_PROMPTS[subcommand];
109 110 if (!stage) throw new Error(`Unknown /system subcommand: ${subcommand}`);
112 113 ...(NEEDS_MARKDOWN.has(subcommand) ? [MARKDOWN_CONTRACT] : []),
113 114 `# /system ${subcommand}`,
114 115 stage,
115 - ...(generatedArtifact
116 - ? [`# Extension-generated artifact slot\n\n${generatedArtifact}`]
117 - : []),
118 116 instructions.trim()
119 117 ? `# Human instructions\n\n${instructions.trim()}`
120 118 : "# Human instructions\n\nNo instructions were supplied. Infer intent with focused questions or selection before writing.",

extensions/the-system/system.ts

Modified
319 319 if (kind === "edit")
320 320 return blocked(
321 - `The System requires write, not edit, to create approved missing core ${relative}.`,
321 + `The System requires write, not edit, to create missing core ${relative}.`,
323 323 return undefined;
331 331 const current = currentBundleMetadata(root, location);
333 333 (current?.type === "phase" || current?.type === "plan") &&
334 - current.status === "done"
334 + current.status === "approved"
336 336 return blocked(
337 - `The System blocked mutation of done ${current.type} ${current.id}; create a new artifact instead.`,
337 + `The System blocked mutation of approved ${current.type} ${current.id}; create a new artifact instead.`,
339 339 } catch (error) {
340 340 return blocked(
371 371 location.index &&
372 372 (resolved.metadata.type === "phase" || resolved.metadata.type === "plan") &&
373 - resolved.metadata.status === "done"
373 + resolved.metadata.status === "approved"
375 375 const current = currentBundleMetadata(root, location);
376 - if (current?.type === resolved.metadata.type && current.status !== "done") {
376 + if (
377 + current?.type === resolved.metadata.type &&
378 + current.status !== "approved"
379 + ) {
377 380 if (!ui.hasUI)
378 381 return blocked(
379 - `The System blocked finishing ${resolved.metadata.type} ${resolved.metadata.id}: interactive UI is unavailable.`,
382 + `The System blocked approval of ${resolved.metadata.type} ${resolved.metadata.id}: interactive UI is unavailable.`,
381 - const approve = `Approve done: ${resolved.metadata.id}`;
384 + const approve = `Approve: ${resolved.metadata.id}`;
382 385 const deny = `Deny: keep ${resolved.metadata.id} draft`;
383 - const decision = await ui.select("The System done approval", [
386 + const decision = await ui.select("The System artifact approval", [
384 387 approve,
387 390 if (decision !== approve)
388 391 return blocked(
389 392 decision === deny
390 - ? `The System done approval was denied for ${resolved.metadata.id}.`
391 - : `The System done approval was cancelled for ${resolved.metadata.id}.`,
393 + ? `The System approval was denied for ${resolved.metadata.id}.`
394 + : `The System approval was cancelled for ${resolved.metadata.id}.`,