repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by bugabinga

docs(the-system): plan runtime governance

60ec65c0631fc785eeefa06ba5235872ad7216a9

Oliver Jan Krylow <oliver@bugabinga.net> ·

unsigned

Browse filesCompare with HEAD

Changed files (1)

docs/super/plans/2026-07-13-the-system-phase-5-runtime-governance.html

Added
new file mode 100644
1 +<!doctype html>
2 +<html lang="en">
3 +<head>
4 +<meta charset="utf-8">
5 +<meta name="viewport" content="width=device-width, initial-scale=1">
6 +<title>The System Phase 5 runtime governance implementation plan</title>
7 +<style>
8 +:root{color-scheme:light dark;--fg:#121212;--bg:#ededed;--panel:#dbdbdb;--accent:#ae2eae;--ui:#922792;--focus:#184e5b;--error:#bd172e;--ok:#116477}
9 +@media(prefers-color-scheme:dark){:root{--fg:#ededed;--bg:#121212;--panel:#242424;--accent:#d151d1;--ui:#d86dd8;--focus:#7ba1aa;--error:#ec6376;--ok:#3ec5e3}}
10 +*{box-sizing:border-box}body{margin:0;padding:1rem;background:var(--bg);color:var(--fg);font:14px/1.55 ui-monospace,SFMono-Regular,Consolas,monospace}article{width:min(100%,1120px);margin:auto;border:3px solid var(--fg);box-shadow:10px 10px 0 var(--ui)}header,section{padding:clamp(1rem,3vw,1.5rem);border-bottom:2px solid var(--fg)}header{background:var(--panel);border-bottom-width:3px}h1{margin:.2rem 0;font:900 clamp(1.8rem,6vw,3.7rem)/.92 system-ui;text-transform:uppercase}h2{margin:0 0 1rem;color:var(--accent);font:900 1rem/1 system-ui;letter-spacing:.12em;text-transform:uppercase}h3{margin:1.4rem 0 .5rem;font-size:.92rem;text-transform:uppercase}p,li{max-width:98ch}li{margin:.42rem 0}a{color:var(--focus);font-weight:900}code{background:var(--panel);padding:.1rem .3rem;overflow-wrap:anywhere}pre{overflow:auto;padding:1rem;border:2px solid var(--fg);border-left:8px solid var(--ui);background:var(--panel);font-size:.8rem;tab-size:2}pre code{padding:0;background:transparent;overflow-wrap:normal}table{width:100%;border-collapse:collapse}th,td{padding:.65rem;border:2px solid var(--fg);text-align:left;vertical-align:top}th{background:var(--panel)}.contract{padding:.9rem;border:3px solid var(--fg);border-left:9px solid var(--accent);background:var(--panel)}.stop{border-left-color:var(--error)}.green{border-left-color:var(--ok)}.checks{list-style:none;padding-left:0}.checks li{padding-left:1.7rem;position:relative}.checks li:before{content:"☐";position:absolute;left:0;color:var(--accent);font-weight:900}@media(max-width:650px){body{padding:.5rem}article{box-shadow:5px 5px 0 var(--ui)}table,tbody,tr,th,td{display:block;width:100%}}
11 +</style>
12 +</head>
13 +<body>
14 +<article>
15 +<header>
16 +<p><strong>Implementation plan · 2026-07-13 · Roadmap Phase 5 only</strong></p>
17 +<h1>Runtime governance</h1>
18 +<p><strong>Goal:</strong> initialized projects inject bounded human law every turn and receive advisory, validated ownership gates without changing task branches or browser mockups.</p>
19 +<p><strong>Architecture:</strong> keep document facts and candidate graph validation in <code>documents.ts</code>. Put all runtime state, core composition, startup notices, built-in write/edit preflight, approvals, and conservative shell recognition in one focused <code>system.ts</code>; <code>index.ts</code> performs one explicit registration call while retaining its current task/mockup implementation.</p>
20 +<p><strong>Tech stack:</strong> TypeScript, Node standard library, Pi <code>before_agent_start</code>/<code>session_start</code>/<code>tool_call</code> events, Vitest, real Pi test harness, mise monorepo tasks.</p>
21 +<p><strong>Roadmap:</strong> <a href="../roadmaps/2026-07-11-the-system-roadmap.html">docs/super/roadmaps/2026-07-11-the-system-roadmap.html</a></p>
22 +<p><strong>Phase:</strong> Phase 5: Runtime governance</p>
23 +</header>
24 +<main>
25 +<section>
26 +<h2>Execution contract</h2>
27 +<div class="contract">
28 +<p><strong>For agentic workers:</strong> REQUIRED SUB-SKILL: use <code>/skill:executing-plans</code> task-by-task. Check each checkbox only after its command produces the stated result.</p>
29 +</div>
30 +<ul>
31 +<li>Run from <code>/home/me/Workspace/dotfiles/pi-ext</code>.</li>
32 +<li>Use only <code>mise //:task</code> monorepo syntax shown below.</li>
33 +<li>Do not commit. Do not stage, stash, reset, clean, reformat unrelated files, or overwrite unrelated dirty work.</li>
34 +<li>Before each edit, inspect the named file as it exists then; preserve changes outside the exact blocks named here.</li>
35 +<li>Phase 5 does not migrate workflow output paths, alter the generic <code>mockup</code> tool, add browser opening, or add lifecycle prompts.</li>
36 +</ul>
37 +</section>
39 +<section>
40 +<h2>File map</h2>
41 +<table>
42 +<tr><th>Path</th><th>Action</th><th>Single responsibility</th></tr>
43 +<tr><td><code>extensions/the-system/documents.ts</code></td><td>Modify</td><td>Add one pure candidate-vs-current-index validator. Existing doctor/index behavior remains unchanged.</td></tr>
44 +<tr><td><code>extensions/the-system/__tests__/documents.test.ts</code></td><td>Modify</td><td>Prove candidate shell, metadata, filename, duplicate-ID, and downstream-reference failures.</td></tr>
45 +<tr><td><code>extensions/the-system/system.ts</code></td><td>Create</td><td>Compose cores, inspect runtime readiness, register notices, classify/preflight owned paths, request approval, and recognize shell writes.</td></tr>
46 +<tr><td><code>extensions/the-system/__tests__/system.test.ts</code></td><td>Create</td><td>Exercise pure composition plus real Pi event shapes, root changes, once-only notices, write/edit decisions, UI outcomes, and shell boundaries.</td></tr>
47 +<tr><td><code>extensions/the-system/index.ts</code></td><td>Modify</td><td>Import and invoke <code>registerSystemGovernance(pi)</code>; leave all existing task/mockup code byte-for-byte otherwise.</td></tr>
48 +</table>
49 +<div class="contract green">
50 +<strong>Minimal boundary:</strong> no policy class, registry, persistence layer, shell parser, alternate tool wrapper, or second runtime module. Session state is one closure boolean; project state is reread from the root resolved for the current event.
51 +</div>
52 +</section>
54 +<section>
55 +<h2>Task 1 · Shared candidate graph validation</h2>
56 +<p><strong>Files:</strong> modify <code>extensions/the-system/documents.ts</code>; test <code>extensions/the-system/__tests__/documents.test.ts</code>.</p>
57 +<ul class="checks">
58 +<li><strong>Step 1: add the failing import and tests.</strong> Add <code>validateDocumentCandidate</code> to the import from <code>../documents.ts</code>. Append this block after the existing document-index tests, reusing that file’s existing <code>shell</code> helper:</li>
59 +</ul>
60 +<pre><code>describe("document candidate validation", () =&gt; {
61 + const spec = (id: string, slug: string) =&gt; ({
62 + path: `.system/specs/${id}-${slug}.html`,
63 + html: shell(JSON.stringify({ id, type: "spec" })),
64 + });
65 + const roadmap = {
66 + path: ".system/roadmaps/PX-ROADMAP-001-delivery.html",
67 + html: shell(
68 + '{"id":"PX-ROADMAP-001","type":"roadmap","spec":"PX-SPEC-001"}',
69 + ),
70 + };
72 + it("accepts a valid new spec against a valid current index", () =&gt; {
73 + const current = [spec("PX-SPEC-001", "first")];
74 + assert.deepEqual(
75 + validateDocumentCandidate(
76 + current,
77 + spec("PX-SPEC-002", "second"),
78 + "PX",
79 + ),
80 + [],
81 + );
82 + });
84 + it("reports candidate failures and graph breakage caused by replacement", () =&gt; {
85 + const current = [spec("PX-SPEC-001", "first"), roadmap];
86 + const replacement = {
87 + path: ".system/specs/PX-SPEC-001-first.html",
88 + html: shell('{"id":"PX-SPEC-002","type":"spec"}'),
89 + };
90 + assert.deepEqual(
91 + validateDocumentCandidate(current, replacement, "PX").map(
92 + ({ code, path }) =&gt; `${path} ${code}`,
93 + ),
94 + [
95 + ".system/roadmaps/PX-ROADMAP-001-delivery.html graph.dangling-reference",
96 + ".system/specs/PX-SPEC-001-first.html document.filename",
97 + ],
98 + );
99 + });
101 + it("reports a duplicate ID on the candidate without replaying old findings", () =&gt; {
102 + const current = [
103 + spec("PX-SPEC-001", "first"),
105 + path: ".system/specs/broken.html",
106 + html: "not html",
107 + },
108 + ];
109 + const findings = validateDocumentCandidate(
110 + current,
112 + path: ".system/specs/PX-SPEC-001-copy.html",
113 + html: shell('{"id":"PX-SPEC-001","type":"spec"}'),
114 + },
115 + "PX",
116 + );
117 + assert.deepEqual(
118 + findings.map(({ code, path }) =&gt; `${path} ${code}`),
120 + ".system/specs/PX-SPEC-001-copy.html graph.duplicate-id",
121 + ],
122 + );
123 + });
124 +});</code></pre>
125 +<ul class="checks">
126 +<li><strong>Step 2: run RED.</strong><br>Run: <code>mise //:test -- extensions/the-system/__tests__/documents.test.ts</code><br>Expected: FAIL because <code>validateDocumentCandidate</code> is not exported.</li>
127 +<li><strong>Step 3: add the pure implementation.</strong> Insert immediately before <code>indexDocuments</code> in <code>documents.ts</code>:</li>
128 +</ul>
129 +<pre><code>const diagnosticIdentity = (item: Diagnostic) =&gt;
130 + JSON.stringify([item.path, item.code, item.message]);
132 +export function validateDocumentCandidate(
133 + current: readonly DocumentSource[],
134 + candidate: DocumentSource,
135 + prefix: string,
136 +): readonly Diagnostic[] {
137 + const baseline = new Set(
138 + indexDocuments(current, prefix).diagnostics.map(diagnosticIdentity),
139 + );
140 + const next = indexDocuments(
142 + ...current.filter((source) =&gt; source.path !== candidate.path),
143 + candidate,
144 + ],
145 + prefix,
146 + );
147 + return next.diagnostics.filter(
148 + (item) =&gt;
149 + item.path === candidate.path || !baseline.has(diagnosticIdentity(item)),
150 + );
151 +}</code></pre>
152 +<p>This intentionally uses the existing <code>indexDocuments</code> authority twice: all candidate-local errors block, newly introduced dependent errors block, and unrelated pre-existing diagnostics do not make every future repair impossible.</p>
153 +<ul class="checks">
154 +<li><strong>Step 4: run GREEN.</strong><br>Run: <code>mise //:test -- extensions/the-system/__tests__/documents.test.ts</code><br>Expected: PASS.</li>
155 +</ul>
156 +</section>
158 +<section>
159 +<h2>Task 2 · Per-turn core composition and once-only readiness notice</h2>
160 +<p><strong>Files:</strong> create <code>extensions/the-system/system.ts</code> and <code>extensions/the-system/__tests__/system.test.ts</code>; modify only the registration seam in <code>extensions/the-system/index.ts</code>.</p>
161 +<ul class="checks">
162 +<li><strong>Step 1: create the failing runtime tests.</strong> Create <code>extensions/the-system/__tests__/system.test.ts</code> with this initial content:</li>
163 +</ul>
164 +<pre><code>import assert from "node:assert/strict";
165 +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
166 +import { tmpdir } from "node:os";
167 +import path from "node:path";
168 +import { afterEach, describe, it } from "vitest";
169 +import { createTestSession, type TestSession } from "../../../test/harness.ts";
170 +import { applyInitialization } from "../init.ts";
171 +import { CORE_BYTE_LIMIT, composeSystemPrompt } from "../system.ts";
173 +const temporary: string[] = [];
174 +const sessions: TestSession[] = [];
175 +const extensionPath = path.resolve(import.meta.dirname, "../index.ts");
176 +const makeDirectory = (prefix: string) =&gt; {
177 + const value = mkdtempSync(path.join(tmpdir(), prefix));
178 + temporary.push(value);
179 + return value;
181 +const write = (root: string, relative: string, content: string) =&gt; {
182 + const target = path.join(root, relative);
183 + mkdirSync(path.dirname(target), { recursive: true });
184 + writeFileSync(target, content, "utf8");
186 +const writeCores = (root: string, label: string) =&gt; {
187 + write(root, ".system/SYSTEM.md", `# System\n\n${label} topology.\n`);
188 + write(root, ".system/MISSION.md", `# Mission\n\n${label} purpose.\n`);
189 + write(root, ".system/RULES.md", `# Rules\n\n${label} constraints.\n`);
191 +const initialized = () =&gt; {
192 + const root = makeDirectory("the-system-runtime-");
193 + mkdirSync(path.join(root, ".git"));
194 + applyInitialization(root, "PX");
195 + writeCores(root, "root");
196 + return root;
198 +afterEach(() =&gt; {
199 + for (const session of sessions.splice(0)) session.dispose();
200 + for (const root of temporary.splice(0))
201 + rmSync(root, { recursive: true, force: true });
202 +});
204 +describe("runtime core injection", () =&gt; {
205 + it("appends existing cores in stable order and marks an oversized core", () =&gt; {
206 + const root = initialized();
207 + write(root, ".system/MISSION.md", "x".repeat(CORE_BYTE_LIMIT + 1));
208 + const prompt = composeSystemPrompt(root, "BASE");
209 + assert.ok(prompt.startsWith("BASE\n\n# The System project law"));
210 + assert.ok(prompt.indexOf("## SYSTEM.md") &lt; prompt.indexOf("## MISSION.md"));
211 + assert.ok(prompt.indexOf("## MISSION.md") &lt; prompt.indexOf("## RULES.md"));
212 + assert.match(prompt, /MISSION\.md exceeds the 32768-byte injection limit/);
213 + assert.match(prompt, /root topology/);
214 + assert.match(prompt, /root constraints/);
215 + });
217 + it("omits absent cores rather than inventing defaults", () =&gt; {
218 + const root = makeDirectory("the-system-runtime-empty-");
219 + write(root, ".system/RULES.md", "# Rules\n\nOnly existing truth.\n");
220 + const prompt = composeSystemPrompt(root, "BASE");
221 + assert.doesNotMatch(prompt, /## SYSTEM\.md|## MISSION\.md/);
222 + assert.match(prompt, /## RULES\.md[\s\S]*Only existing truth/);
223 + });
225 + it("resolves the root again for every before_agent_start event", async () =&gt; {
226 + const parent = makeDirectory("the-system-root-change-");
227 + const cwd = path.join(parent, "packages", "app");
228 + mkdirSync(cwd, { recursive: true });
229 + writeCores(cwd, "nested");
230 + const t = await createTestSession({ cwd, extensions: [extensionPath] });
231 + sessions.push(t);
232 + const first = await t.session.extensionRunner.emitBeforeAgentStart(
233 + "first",
234 + undefined,
235 + "BASE",
236 + {},
237 + );
238 + assert.match(first?.systemPrompt ?? "", /nested topology/);
239 + mkdirSync(path.join(parent, ".git"));
240 + writeCores(parent, "parent");
241 + const second = await t.session.extensionRunner.emitBeforeAgentStart(
242 + "second",
243 + undefined,
244 + "BASE",
245 + {},
246 + );
247 + assert.match(second?.systemPrompt ?? "", /parent topology/);
248 + assert.doesNotMatch(second?.systemPrompt ?? "", /nested topology/);
249 + });
250 +});
252 +describe("runtime readiness notice", () =&gt; {
253 + it("notifies once per session when initialization is incomplete", async () =&gt; {
254 + const root = makeDirectory("the-system-notice-");
255 + mkdirSync(path.join(root, ".git"));
256 + const t = await createTestSession({ cwd: root, extensions: [extensionPath] });
257 + sessions.push(t);
258 + await t.session.extensionRunner.emitBeforeAgentStart("one", undefined, "BASE", {});
259 + await t.session.extensionRunner.emitBeforeAgentStart("two", undefined, "BASE", {});
260 + const notices = t.events.uiCallsFor("notify").filter((call) =&gt;
261 + String(call.args[0]).includes("/system-init"),
262 + );
263 + assert.equal(notices.length, 1);
264 + assert.match(String(notices[0]?.args[0]), /incomplete or invalid/);
265 + });
267 + it("stays silent for a doctor-green initialized project", async () =&gt; {
268 + const root = initialized();
269 + const t = await createTestSession({ cwd: root, extensions: [extensionPath] });
270 + sessions.push(t);
271 + await t.session.extensionRunner.emitBeforeAgentStart("one", undefined, "BASE", {});
272 + assert.equal(
273 + t.events.uiCallsFor("notify").filter((call) =&gt;
274 + String(call.args[0]).includes("/system-init"),
275 + ).length,
276 + 0,
277 + );
278 + });
279 +});</code></pre>
280 +<ul class="checks">
281 +<li><strong>Step 2: run RED.</strong><br>Run: <code>mise //:test -- extensions/the-system/__tests__/system.test.ts</code><br>Expected: FAIL because <code>../system.ts</code> does not exist.</li>
282 +<li><strong>Step 3: create the injection/notice runtime.</strong> Create <code>extensions/the-system/system.ts</code> with:</li>
283 +</ul>
284 +<pre><code>import { lstatSync, readFileSync } from "node:fs";
285 +import path from "node:path";
286 +import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
287 +import { discoverProjectRoot } from "./documents.ts";
288 +import { inspectInitialization } from "./init.ts";
290 +export const CORE_BYTE_LIMIT = 32 * 1024;
291 +const CORES = ["SYSTEM.md", "MISSION.md", "RULES.md"] as const;
293 +const coreBlock = (root: string, name: (typeof CORES)[number]) =&gt; {
294 + const target = path.join(root, ".system", name);
295 + const stats = lstatSync(target, { throwIfNoEntry: false });
296 + if (!stats?.isFile()) return undefined;
297 + if (stats.size &gt; CORE_BYTE_LIMIT)
298 + return `## ${name}\n\n[Not injected: ${name} exceeds the ${CORE_BYTE_LIMIT}-byte injection limit.]`;
299 + return `## ${name}\n\n${readFileSync(target, "utf8")}`;
302 +export function composeSystemPrompt(cwd: string, systemPrompt: string): string {
303 + let root: string;
304 + try {
305 + root = discoverProjectRoot(cwd);
306 + } catch (error) {
307 + const message = error instanceof Error ? error.message : String(error);
308 + return `${systemPrompt}\n\n# The System governance error\n\n${message}\n\nDo not mutate .system until /system-doctor resolves this root error.`;
310 + const blocks = CORES.map((name) =&gt; coreBlock(root, name)).filter(
311 + (block): block is string =&gt; block !== undefined,
312 + );
313 + if (blocks.length === 0) return systemPrompt;
314 + return `${systemPrompt}\n\n# The System project law\n\n${blocks.join("\n\n")}`;
317 +export function runtimeNotice(cwd: string): string | undefined {
318 + try {
319 + const inspection = inspectInitialization(cwd);
320 + if (
321 + inspection.creates.length &gt; 0 ||
322 + inspection.cores.some(({ state }) =&gt; state === "missing")
324 + return "The System is incomplete or invalid; run /system-init before governed work.";
325 + if (inspection.upgrades.length &gt; 0)
326 + return "The System schema/style refresh is available; run /system-init to inspect and approve it.";
327 + return undefined;
328 + } catch {
329 + return "The System is incomplete or invalid; run /system-init before governed work.";
333 +export function registerSystemGovernance(pi: ExtensionAPI): void {
334 + let notified = false;
335 + const notifyOnce = (_event: unknown, ctx: ExtensionContext) =&gt; {
336 + if (notified || !ctx.hasUI) return;
337 + const message = runtimeNotice(ctx.cwd);
338 + if (!message) return;
339 + ctx.ui.notify(message, "warning");
340 + notified = true;
341 + };
342 + pi.on("session_start", async (event, ctx) =&gt; {
343 + notified = false;
344 + notifyOnce(event, ctx);
345 + });
346 + pi.on("before_agent_start", async (event, ctx) =&gt; {
347 + notifyOnce(event, ctx);
348 + return { systemPrompt: composeSystemPrompt(ctx.cwd, event.systemPrompt) };
349 + });
350 +}</code></pre>
351 +<ul class="checks">
352 +<li><strong>Step 4: register governance without restructuring existing behavior.</strong> In <code>index.ts</code>, add this import beside the current local import:</li>
353 +</ul>
354 +<pre><code>import { createMockupTool } from "./mockup.js";
355 +import { registerSystemGovernance } from "./system.js";</code></pre>
356 +<p>Then make the registration function begin exactly as follows; do not move or alter any existing registration beneath the added call:</p>
357 +<pre><code>export default function registerTaskCommands(pi: ExtensionAPI): void {
358 + registerSystemGovernance(pi);
359 + pi.registerTool(createPushTaskTool(pi));
360 + pi.registerTool(createMockupTool());</code></pre>
361 +<ul class="checks">
362 +<li><strong>Step 5: run GREEN.</strong><br>Run: <code>mise //:test -- extensions/the-system/__tests__/system.test.ts extensions/the-system/__tests__/harness.test.ts</code><br>Expected: PASS; the real runtime still loads one extension.</li>
363 +</ul>
364 +</section>
366 +<section>
367 +<h2>Task 3 · Built-in write/edit ownership and candidate preflight</h2>
368 +<p><strong>Files:</strong> modify <code>extensions/the-system/system.ts</code> and <code>extensions/the-system/__tests__/system.test.ts</code>.</p>
369 +<ul class="checks">
370 +<li><strong>Step 1: append real-event failing tests.</strong> Extend the fs import in <code>system.test.ts</code> with <code>readFileSync</code>. Add <code>shell</code> and <code>writeSpec</code> helpers immediately after <code>writeCores</code>:</li>
371 +</ul>
372 +<pre><code>const shell = (id: string) =&gt; `&lt;!doctype html&gt;
373 +&lt;html lang="en"&gt;&lt;head&gt;&lt;meta charset="utf-8"&gt;
374 +&lt;meta name="viewport" content="width=device-width, initial-scale=1"&gt;
375 +&lt;title&gt;${id}&lt;/title&gt;&lt;link rel="stylesheet" href="../system.css"&gt;&lt;/head&gt;
376 +&lt;body&gt;&lt;header&gt;&lt;h1&gt;${id}&lt;/h1&gt;&lt;/header&gt;&lt;main&gt;&lt;section&gt;&lt;h2&gt;Contract&lt;/h2&gt;&lt;p&gt;Approved.&lt;/p&gt;&lt;/section&gt;&lt;/main&gt;
377 +&lt;script type="application/json" id="system-meta"&gt;{"id":"${id}","type":"spec"}&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;`;
378 +const writeSpec = (root: string, id = "PX-SPEC-001", slug = "contract") =&gt; {
379 + const relative = `.system/specs/${id}-${slug}.html`;
380 + write(root, relative, shell(id));
381 + return relative;
382 +};</code></pre>
383 +<p>Append these tests:</p>
384 +<pre><code>describe("runtime write and edit governance", () =&gt; {
385 + it("blocks write/edit of existing cores and permits approved missing-core creation", async () =&gt; {
386 + const root = initialized();
387 + const t = await createTestSession({ cwd: root, extensions: [extensionPath] });
388 + sessions.push(t);
389 + for (const event of [
390 + { type: "tool_call", toolCallId: "w", toolName: "write", input: { path: ".system/RULES.md", content: "replacement" } },
391 + { type: "tool_call", toolCallId: "e", toolName: "edit", input: { path: ".system/MISSION.md", edits: [{ oldText: "root", newText: "agent" }] } },
392 + ] as const) {
393 + const result = await t.session.extensionRunner.emitToolCall(event);
394 + assert.equal(result?.block, true);
395 + assert.match(result?.reason ?? "", /human-owned core/);
397 + rmSync(path.join(root, ".system/SYSTEM.md"));
398 + const creation = await t.session.extensionRunner.emitToolCall({
399 + type: "tool_call", toolCallId: "new-core", toolName: "write",
400 + input: { path: ".system/SYSTEM.md", content: "# System\n\nHuman-approved.\n" },
401 + });
402 + assert.equal(creation?.block, undefined);
403 + });
405 + it("allows a valid new spec without a redundant UI gate and blocks an invalid candidate", async () =&gt; {
406 + const root = initialized();
407 + const t = await createTestSession({ cwd: root, extensions: [extensionPath] });
408 + sessions.push(t);
409 + const valid = await t.session.extensionRunner.emitToolCall({
410 + type: "tool_call", toolCallId: "valid", toolName: "write",
411 + input: { path: ".system/specs/PX-SPEC-001-contract.html", content: shell("PX-SPEC-001") },
412 + });
413 + assert.equal(valid?.block, undefined);
414 + assert.equal(t.events.uiCallsFor("select").length, 0);
415 + const invalid = await t.session.extensionRunner.emitToolCall({
416 + type: "tool_call", toolCallId: "invalid", toolName: "write",
417 + input: { path: ".system/specs/PX-SPEC-002-broken.html", content: "&lt;html&gt;broken&lt;/html&gt;" },
418 + });
419 + assert.equal(invalid?.block, true);
420 + assert.match(invalid?.reason ?? "", /candidate validation failed/);
421 + });
423 + it.each([
424 + ["approve", (items: string[]) =&gt; items[0], false, /./],
425 + ["deny", (items: string[]) =&gt; items[1], true, /denied/],
426 + ["cancel", () =&gt; undefined, true, /cancelled/],
427 + ] as const)("handles UI %s for an existing spec", async (_name, choose, blocked, reason) =&gt; {
428 + const root = initialized();
429 + const relative = writeSpec(root);
430 + const t = await createTestSession({
431 + cwd: root,
432 + extensions: [extensionPath],
433 + mockUI: { select: (_title, items) =&gt; choose(items) },
434 + });
435 + sessions.push(t);
436 + const result = await t.session.extensionRunner.emitToolCall({
437 + type: "tool_call", toolCallId: "edit", toolName: "edit",
438 + input: { path: relative, edits: [{ oldText: "Approved.", newText: "Approved and reviewed." }] },
439 + });
440 + assert.equal(result?.block === true, blocked);
441 + if (blocked) assert.match(result?.reason ?? "", reason);
442 + assert.equal(t.events.uiCallsFor("select").length, 1);
443 + });
445 + it("fails closed without UI and validates the computed edit candidate first", async () =&gt; {
446 + const root = initialized();
447 + const relative = writeSpec(root);
448 + const noUi = await import("../system.ts");
449 + const result = await noUi.preflightFileMutation(
450 + root,
451 + "edit",
452 + { path: relative, edits: [{ oldText: "Approved.", newText: "Reviewed." }] },
453 + { hasUI: false, select: async () =&gt; undefined },
454 + );
455 + assert.equal(result?.block, true);
456 + assert.match(result?.reason ?? "", /interactive UI is unavailable/);
457 + const invalid = await noUi.preflightFileMutation(
458 + root,
459 + "edit",
460 + { path: relative, edits: [{ oldText: "&lt;/main&gt;", newText: "" }] },
461 + { hasUI: true, select: async (_title, items) =&gt; items[0] },
462 + );
463 + assert.equal(invalid?.block, true);
464 + assert.match(invalid?.reason ?? "", /candidate validation failed/);
465 + });
467 + it("permits a valid new spec-owned mockup and gates an existing one", async () =&gt; {
468 + const root = initialized();
469 + const owner = writeSpec(root);
470 + assert.ok(readFileSync(path.join(root, owner), "utf8").includes("PX-SPEC-001"));
471 + const mockup = ".system/specs/PX-SPEC-001-contract-mockup-mobile.html";
472 + const t = await createTestSession({ cwd: root, extensions: [extensionPath] });
473 + sessions.push(t);
474 + const first = await t.session.extensionRunner.emitToolCall({
475 + type: "tool_call", toolCallId: "new-mockup", toolName: "write",
476 + input: { path: mockup, content: shell("PX-SPEC-001") },
477 + });
478 + assert.equal(first?.block, undefined);
479 + write(root, mockup, shell("PX-SPEC-001"));
480 + const second = await t.session.extensionRunner.emitToolCall({
481 + type: "tool_call", toolCallId: "old-mockup", toolName: "write",
482 + input: { path: mockup, content: shell("PX-SPEC-001").replace("Approved.", "Reviewed.") },
483 + });
484 + assert.equal(second?.block, true);
485 + assert.match(second?.reason ?? "", /cancelled/);
486 + });
487 +});</code></pre>
488 +<ul class="checks">
489 +<li><strong>Step 2: run RED.</strong><br>Run: <code>mise //:test -- extensions/the-system/__tests__/system.test.ts</code><br>Expected: FAIL because no <code>tool_call</code> hook or <code>preflightFileMutation</code> exists.</li>
490 +<li><strong>Step 3: expand imports in <code>system.ts</code>.</strong> Replace its current imports with:</li>
491 +</ul>
492 +<pre><code>import {
493 + existsSync,
494 + lstatSync,
495 + readdirSync,
496 + readFileSync,
497 +} from "node:fs";
498 +import path from "node:path";
499 +import {
500 + isToolCallEventType,
501 + type EditToolInput,
502 + type ExtensionAPI,
503 + type ExtensionContext,
504 + type WriteToolInput,
505 +} from "@earendil-works/pi-coding-agent";
506 +import {
507 + type Diagnostic,
508 + discoverProjectRoot,
509 + indexDocuments,
510 + parseSystemConfig,
511 + resolveGovernedPath,
512 + validateAuthoredHtml,
513 + validateDocumentCandidate,
514 +} from "./documents.ts";
515 +import { inspectInitialization } from "./init.ts";</code></pre>
516 +<ul class="checks">
517 +<li><strong>Step 4: add the direct preflight implementation.</strong> Insert this block immediately before <code>registerSystemGovernance</code>:</li>
518 +</ul>
519 +<pre><code>type MutationKind = "write" | "edit";
520 +type MutationInput = WriteToolInput | EditToolInput;
521 +type GateResult = Readonly&lt;{ block: true; reason: string }&gt; | undefined;
522 +export type GovernanceUI = Readonly&lt;{
523 + hasUI: boolean;
524 + select(title: string, items: string[]): Promise&lt;string | undefined&gt;;
525 +}&gt;;
526 +const DOCUMENT_DIRECTORIES = ["specs", "roadmaps", "plans", "issues", "research"] as const;
527 +const CORE_PATHS = new Set([
528 + ".system/SYSTEM.md",
529 + ".system/MISSION.md",
530 + ".system/RULES.md",
531 +]);
532 +const MOCKUP_NAME = /^(.*)-mockup-[a-z0-9]+(?:-[a-z0-9]+)*\.html$/;
533 +const posixRelative = (root: string, target: string) =&gt;
534 + path.relative(root, target).split(path.sep).join("/");
535 +const blocked = (reason: string): GateResult =&gt; ({ block: true, reason });
536 +const diagnosticsReason = (diagnostics: readonly Diagnostic[]) =&gt; {
537 + const shown = diagnostics.slice(0, 3).map(
538 + (item) =&gt; `${item.path} ${item.code}: ${item.message}`,
539 + );
540 + if (diagnostics.length &gt; shown.length)
541 + shown.push(`+${diagnostics.length - shown.length} more finding(s)`);
542 + return `The System candidate validation failed: ${shown.join("; ")}`;
544 +const collectDocumentSources = (root: string) =&gt; {
545 + const sources: { path: string; html: string }[] = [];
546 + for (const directory of DOCUMENT_DIRECTORIES) {
547 + const absolute = path.join(root, ".system", directory);
548 + const stats = lstatSync(absolute, { throwIfNoEntry: false });
549 + if (!stats?.isDirectory()) continue;
550 + for (const entry of readdirSync(absolute, { withFileTypes: true })) {
551 + if (!entry.isFile() || !entry.name.endsWith(".html")) continue;
552 + if (directory === "specs" &amp;&amp; MOCKUP_NAME.test(entry.name)) continue;
553 + const sourcePath = `.system/${directory}/${entry.name}`;
554 + sources.push({
555 + path: sourcePath,
556 + html: readFileSync(path.join(absolute, entry.name), "utf8"),
557 + });
560 + return sources.sort((left, right) =&gt; left.path.localeCompare(right.path));
562 +const applyExactEdits = (source: string, edits: EditToolInput["edits"]) =&gt; {
563 + const replacements = edits.map((edit) =&gt; {
564 + const start = source.indexOf(edit.oldText);
565 + if (start &lt; 0 || source.indexOf(edit.oldText, start + 1) &gt;= 0)
566 + throw new Error("each governed edit oldText must match exactly once");
567 + return { start, end: start + edit.oldText.length, newText: edit.newText };
568 + }).sort((left, right) =&gt; left.start - right.start);
569 + for (let index = 1; index &lt; replacements.length; index++)
570 + if (replacements[index - 1]!.end &gt; replacements[index]!.start)
571 + throw new Error("governed edits must not overlap");
572 + let candidate = source;
573 + for (const replacement of replacements.reverse())
574 + candidate =
575 + candidate.slice(0, replacement.start) +
576 + replacement.newText +
577 + candidate.slice(replacement.end);
578 + return candidate;
580 +const candidateContent = (
581 + target: string,
582 + kind: MutationKind,
583 + input: MutationInput,
584 +) =&gt; {
585 + if (kind === "write") return (input as WriteToolInput).content;
586 + if (!existsSync(target)) throw new Error("edit cannot create a governed file; use write");
587 + return applyExactEdits(
588 + readFileSync(target, "utf8"),
589 + (input as EditToolInput).edits,
590 + );
592 +const projectPrefix = (root: string) =&gt;
593 + parseSystemConfig(readFileSync(path.join(root, ".system/config.json"), "utf8")).prefix;
594 +const validateSpec = (
595 + root: string,
596 + relative: string,
597 + content: string,
598 +) =&gt; validateDocumentCandidate(
599 + collectDocumentSources(root),
600 + { path: relative, html: content },
601 + projectPrefix(root),
603 +const validateMockup = (
604 + root: string,
605 + relative: string,
606 + content: string,
607 +): readonly Diagnostic[] =&gt; {
608 + const findings = [...validateAuthoredHtml(relative, content)];
609 + const filename = path.posix.basename(relative);
610 + const owner = MOCKUP_NAME.exec(filename)?.[1];
611 + const ownerPath = owner ? `.system/specs/${owner}.html` : undefined;
612 + if (!ownerPath || !existsSync(path.join(root, ownerPath)))
613 + findings.push({
614 + code: "mockup.orphaned",
615 + path: relative,
616 + message: `Mockup owner is missing: ${ownerPath ?? "unrecognized filename"}`,
617 + });
618 + return findings.sort(
619 + (left, right) =&gt;
620 + left.path.localeCompare(right.path) ||
621 + left.code.localeCompare(right.code) ||
622 + left.message.localeCompare(right.message),
623 + );
626 +export async function preflightFileMutation(
627 + cwd: string,
628 + kind: MutationKind,
629 + input: MutationInput,
630 + ui: GovernanceUI,
631 +): Promise&lt;GateResult&gt; {
632 + let root: string;
633 + try {
634 + root = discoverProjectRoot(cwd);
635 + } catch (error) {
636 + return blocked(`The System cannot resolve project ownership: ${error instanceof Error ? error.message : String(error)}`);
638 + let target: string;
639 + try {
640 + target = resolveGovernedPath(root, path.resolve(cwd, input.path));
641 + } catch (error) {
642 + return blocked(`The System rejected the governed path: ${error instanceof Error ? error.message : String(error)}`);
644 + const relative = posixRelative(root, target);
645 + if (CORE_PATHS.has(relative)) {
646 + if (existsSync(target))
647 + return blocked(`The System blocked mutation of human-owned core ${relative}.`);
648 + if (kind === "edit")
649 + return blocked(`The System requires write, not edit, to create approved missing core ${relative}.`);
650 + return undefined;
652 + if (!relative.startsWith(".system/specs/") || !relative.endsWith(".html"))
653 + return undefined;
654 + const targetStats = lstatSync(target, { throwIfNoEntry: false });
655 + if (targetStats?.isSymbolicLink())
656 + return blocked(`The System rejected symbolic-link target ${relative}.`);
657 + let content: string;
658 + let findings: readonly Diagnostic[];
659 + try {
660 + content = candidateContent(target, kind, input);
661 + findings = MOCKUP_NAME.test(path.posix.basename(relative))
662 + ? validateMockup(root, relative, content)
663 + : validateSpec(root, relative, content);
664 + } catch (error) {
665 + return blocked(`The System candidate validation failed: ${error instanceof Error ? error.message : String(error)}`);
667 + if (findings.length &gt; 0) return blocked(diagnosticsReason(findings));
668 + if (!targetStats) return undefined;
669 + if (!targetStats.isFile())
670 + return blocked(`The System expected a regular owned file at ${relative}.`);
671 + if (!ui.hasUI)
672 + return blocked(`The System blocked existing human-owned ${relative}: interactive UI is unavailable.`);
673 + const approve = `Approve once: ${kind} ${relative}`;
674 + const deny = `Deny: keep ${relative} unchanged`;
675 + const decision = await ui.select("The System ownership approval", [approve, deny]);
676 + if (decision === approve) return undefined;
677 + return blocked(
678 + decision === deny
679 + ? `The System ownership approval was denied for ${relative}.`
680 + : `The System ownership approval was cancelled for ${relative}.`,
681 + );
682 +}</code></pre>
683 +<ul class="checks">
684 +<li><strong>Step 5: register the real built-in tool event shapes.</strong> Add this handler as the final statement inside <code>registerSystemGovernance</code>:</li>
685 +</ul>
686 +<pre><code> pi.on("tool_call", async (event, ctx) =&gt; {
687 + const ui: GovernanceUI = {
688 + hasUI: ctx.hasUI,
689 + select: (title, items) =&gt; ctx.ui.select(title, items),
690 + };
691 + if (isToolCallEventType("write", event))
692 + return preflightFileMutation(ctx.cwd, "write", event.input, ui);
693 + if (isToolCallEventType("edit", event))
694 + return preflightFileMutation(ctx.cwd, "edit", event.input, ui);
695 + });</code></pre>
696 +<ul class="checks">
697 +<li><strong>Step 6: run GREEN.</strong><br>Run: <code>mise //:test -- extensions/the-system/__tests__/documents.test.ts extensions/the-system/__tests__/system.test.ts</code><br>Expected: PASS, including approve, deny, cancel, no-UI, candidate, missing-core, spec, and mockup cases.</li>
698 +</ul>
699 +</section>
701 +<section>
702 +<h2>Task 4 · Conservative recognizable shell mutation guard</h2>
703 +<p><strong>Files:</strong> modify <code>extensions/the-system/system.ts</code> and <code>extensions/the-system/__tests__/system.test.ts</code>.</p>
704 +<ul class="checks">
705 +<li><strong>Step 1: append failing shell tests.</strong> Append:</li>
706 +</ul>
707 +<pre><code>describe("runtime shell advisory guard", () =&gt; {
708 + it.each([
709 + "printf replacement &gt; .system/RULES.md",
710 + "sed -i 's/Approved/Changed/' .system/specs/PX-SPEC-001-contract.html",
711 + "rm .system/specs/PX-SPEC-001-contract-mockup-mobile.html",
712 + ])("blocks recognizable owned mutation: %s", async (command) =&gt; {
713 + const root = initialized();
714 + writeSpec(root);
715 + const t = await createTestSession({ cwd: root, extensions: [extensionPath] });
716 + sessions.push(t);
717 + const result = await t.session.extensionRunner.emitToolCall({
718 + type: "tool_call", toolCallId: "bash", toolName: "bash", input: { command },
719 + });
720 + assert.equal(result?.block, true);
721 + assert.match(result?.reason ?? "", /advisory shell guard/);
722 + assert.match(result?.reason ?? "", /not a sandbox/);
723 + assert.match(result?.reason ?? "", /use write or edit/i);
724 + });
726 + it.each([
727 + "cat .system/RULES.md",
728 + "printf report &gt; build/report.txt",
729 + "git status --short",
730 + ])("allows a command without a recognizable owned mutation: %s", async (command) =&gt; {
731 + const root = initialized();
732 + const t = await createTestSession({ cwd: root, extensions: [extensionPath] });
733 + sessions.push(t);
734 + const result = await t.session.extensionRunner.emitToolCall({
735 + type: "tool_call", toolCallId: "bash-safe", toolName: "bash", input: { command },
736 + });
737 + assert.equal(result?.block, undefined);
738 + });
739 +});</code></pre>
740 +<ul class="checks">
741 +<li><strong>Step 2: run RED.</strong><br>Run: <code>mise //:test -- extensions/the-system/__tests__/system.test.ts</code><br>Expected: FAIL because recognizable bash writes are not blocked.</li>
742 +<li><strong>Step 3: add narrow recognition, not a shell parser.</strong> Insert before <code>preflightFileMutation</code>:</li>
743 +</ul>
744 +<pre><code>const SHELL_MUTATOR = /(?:^|[;&amp;|]\s*)(?:rm|mv|cp|install|truncate|touch|tee|sed\s+-[^\n]*i|perl\s+-[^\n]*i)\b|(?:^|[^&lt;])&gt;&gt;?/i;
745 +const OWNED_SHELL_PATH = /(?:^|[\s"'`])([^\s"'`;&amp;|]*\.system\/(?:SYSTEM\.md|MISSION\.md|RULES\.md|specs\/[^\s"'`;&amp;|]+\.html))(?=$|[\s"'`;&amp;|])/i;
747 +export function preflightShellMutation(command: string): GateResult {
748 + if (!SHELL_MUTATOR.test(command)) return undefined;
749 + const owned = OWNED_SHELL_PATH.exec(command)?.[1];
750 + if (!owned) return undefined;
751 + return blocked(
752 + `The System advisory shell guard blocked recognizable mutation of ${owned}; use write or edit for candidate validation and ownership approval. Shell recognition is not a sandbox or security boundary.`,
753 + );
754 +}</code></pre>
755 +<ul class="checks">
756 +<li><strong>Step 4: add bash to the existing <code>tool_call</code> handler.</strong> Insert before its write branch:</li>
757 +</ul>
758 +<pre><code> if (isToolCallEventType("bash", event))
759 + return preflightShellMutation(event.input.command);</code></pre>
760 +<ul class="checks">
761 +<li><strong>Step 5: run GREEN.</strong><br>Run: <code>mise //:test -- extensions/the-system/__tests__/system.test.ts</code><br>Expected: PASS. The tests deliberately prove obvious redirection/in-place/removal forms and deliberately do not claim complete shell interpretation.</li>
762 +</ul>
763 +</section>
765 +<section>
766 +<h2>Task 5 · Independent Phase 5 release gate</h2>
767 +<p><strong>Files:</strong> no production expansion; only fix defects in the five Phase 5 files named by this plan.</p>
768 +<ul class="checks">
769 +<li><strong>Step 1: format only touched TypeScript files.</strong><br>Run: <code>npx biome check --write extensions/the-system/documents.ts extensions/the-system/system.ts extensions/the-system/index.ts extensions/the-system/__tests__/documents.test.ts extensions/the-system/__tests__/system.test.ts</code><br>Expected: exits 0 and does not touch other paths.</li>
770 +<li><strong>Step 2: run the complete The System unit suite.</strong><br>Run: <code>mise //:test -- extensions/the-system/__tests__/*.test.ts</code><br>Expected: PASS.</li>
771 +<li><strong>Step 3: run explicit retained behavior regressions.</strong><br>Run: <code>mise //:test -- extensions/the-system/__tests__/the-system.test.ts extensions/the-system/__tests__/mockup.test.ts extensions/the-system/__tests__/harness.test.ts extensions/the-system/__tests__/init.test.ts extensions/the-system/__tests__/doctor.test.ts</code><br>Expected: PASS; task branches, push-task, auto, renderer, mockup server/tool, init, doctor, and real Pi loading remain unchanged.</li>
772 +<li><strong>Step 4: run repository checks.</strong><br>Run: <code>mise //:check</code><br>Expected: typecheck, skills, static extension checks, and extension package checks PASS.</li>
773 +<li><strong>Step 5: run formatting/lint verification.</strong><br>Run: <code>mise //:lint</code><br>Expected: PASS without writing files.</li>
774 +<li><strong>Step 6: run the independent-green release gate.</strong><br>Run: <code>mise //:ci</code><br>Expected: PASS, including browser E2E owned by existing extensions.</li>
775 +<li><strong>Step 7: inspect the worktree without changing it.</strong><br>Run: <code>git status --short</code><br>Expected: only the five planned implementation paths plus pre-existing unrelated dirty paths are listed; no generated report, cache, lockfile, README, changelog, prompt, skill, or mockup file was added by Phase 5.</li>
776 +</ul>
777 +</section>
779 +<section>
780 +<h2>Behavior matrix</h2>
781 +<table>
782 +<tr><th>Input/state</th><th>Decision</th><th>Proof</th></tr>
783 +<tr><td>Existing SYSTEM/MISSION/RULES</td><td>Append under stable headings each agent turn; oversize is explicitly bounded, never silently truncated.</td><td><code>system.test.ts</code> composition and root-change tests.</td></tr>
784 +<tr><td>Missing core</td><td>No invented prompt text; <code>write</code> creation passes because Phase 4’s skill owns human approval.</td><td>Missing-core tests.</td></tr>
785 +<tr><td>Incomplete, malformed, or stale machine state</td><td>One warning per session directs to <code>/system-init</code>; no repair occurs.</td><td>Notice tests plus unchanged init/doctor tests.</td></tr>
786 +<tr><td>Existing core via write/edit</td><td>Always block.</td><td>Real <code>ToolCallEvent</code> tests.</td></tr>
787 +<tr><td>New valid spec/mockup</td><td>Pass after shared validation, no redundant UI.</td><td>Candidate and ownership tests.</td></tr>
788 +<tr><td>Invalid candidate</td><td>Block before UI with stable diagnostics.</td><td>Invalid write/edit tests.</td></tr>
789 +<tr><td>Existing spec/mockup</td><td>Validate candidate, then approve once; deny/cancel/no-UI block.</td><td>UI matrix.</td></tr>
790 +<tr><td>Recognizable shell mutation</td><td>Block and direct to write/edit while stating advisory, non-sandbox boundary.</td><td>Shell matrix.</td></tr>
791 +<tr><td>Unrelated writes, commands, task branches, generic mockup tool</td><td>Pass unchanged.</td><td>Safe shell tests and retained suites.</td></tr>
792 +</table>
793 +</section>
795 +<section>
796 +<h2>Self-review and phase boundary</h2>
797 +<ul>
798 +<li>Every Phase 5 roadmap bullet maps to Tasks 1–4; Task 5 proves the repository independently green.</li>
799 +<li>Root discovery, containment, strict config, HTML, metadata, graph, init versions, and doctor authority are reused from implemented Phases 2–4 rather than duplicated.</li>
800 +<li>Pi handlers use actual <code>session_start</code>, <code>before_agent_start</code>, and narrowed built-in <code>tool_call</code> event shapes.</li>
801 +<li>Approval order is validation first, then UI. Parallel sibling calls receive independent preflight; no unsafe assumption is made about sibling results.</li>
802 +<li>Shell matching is intentionally conservative and explicitly advisory. It does not claim to recognize generated paths, embedded interpreters, environment expansion, or every shell grammar form.</li>
803 +<li>No prompt, skill, package resource, CSS, doctor protocol, initialization behavior, task implementation, mockup implementation, workflow output, README, changelog, or lockfile changes belong here.</li>
804 +<li>No implementation placeholder or deferred Phase 5 behavior remains.</li>
805 +</ul>
806 +<div class="contract stop"><strong>Stop here.</strong> This plan intentionally stops at Phase 5: Runtime governance. Phase 6 owns spec authoring, accepted mockup persistence, and browser review; Phases 7–8 own lifecycle migration and issue memory.</div>
807 +</section>
808 +</main>
809 +</article>
810 +</body>
811 +</html>