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>
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%}}
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>
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>
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>
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>
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.
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>
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>
60 +<
pre><
code>describe("document candidate validation", () =
> {
61 + const spec = (id: string, slug: string) =
> ({
62 + path: `.system/specs/${id}-${slug}.html`,
63 + html: shell(JSON.stringify({ id, type: "spec" })),
66 + path: ".system/roadmaps/PX-ROADMAP-001-delivery.html",
68 + '{"id":"PX-ROADMAP-001","type":"roadmap","spec":"PX-SPEC-001"}',
72 + it("accepts a valid new spec against a valid current index", () =
> {
73 + const current = [spec("PX-SPEC-001", "first")];
75 + validateDocumentCandidate(
77 + spec("PX-SPEC-002", "second"),
84 + it("reports candidate failures and graph breakage caused by replacement", () =
> {
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"}'),
91 + validateDocumentCandidate(current, replacement, "PX").map(
92 + ({ code, path }) =
> `${path} ${code}`,
95 + ".system/roadmaps/PX-ROADMAP-001-delivery.html graph.dangling-reference",
96 + ".system/specs/PX-SPEC-001-first.html document.filename",
101 + it("reports a duplicate ID on the candidate without replaying old findings", () =
> {
103 + spec("PX-SPEC-001", "first"),
105 + path: ".system/specs/broken.html",
109 + const findings = validateDocumentCandidate(
112 + path: ".system/specs/PX-SPEC-001-copy.html",
113 + html: shell('{"id":"PX-SPEC-001","type":"spec"}'),
118 + findings.map(({ code, path }) =
> `${path} ${code}`),
120 + ".system/specs/PX-SPEC-001-copy.html graph.duplicate-id",
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>
129 +<
pre><
code>const diagnosticIdentity = (item: Diagnostic) =
> 130 + JSON.stringify([item.path, item.code, item.message]);
132 +export function validateDocumentCandidate(
133 + current: readonly DocumentSource[],
134 + candidate: DocumentSource,
136 +): readonly Diagnostic[] {
137 + const baseline = new Set(
138 + indexDocuments(current, prefix).diagnostics.map(diagnosticIdentity),
140 + const next = indexDocuments(
142 + ...current.filter((source) =
> source.path !== candidate.path),
147 + return next.diagnostics.filter(
149 + item.path === candidate.path || !baseline.has(diagnosticIdentity(item)),
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>
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>
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>
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>
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) =
> {
177 + const value = mkdtempSync(path.join(tmpdir(), prefix));
178 + temporary.push(value);
181 +const write = (root: string, relative: string, content: string) =
> {
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) =
> {
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 = () =
> {
192 + const root = makeDirectory("the-system-runtime-");
193 + mkdirSync(path.join(root, ".git"));
194 + applyInitialization(root, "PX");
195 + writeCores(root, "root");
198 +afterEach(() =
> {
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 });
204 +describe("runtime core injection", () =
> {
205 + it("appends existing cores in stable order and marks an oversized core", () =
> {
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")
< prompt.indexOf("## MISSION.md"));
211 + assert.ok(prompt.indexOf("## MISSION.md")
< 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/);
217 + it("omits absent cores rather than inventing defaults", () =
> {
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/);
225 + it("resolves the root again for every before_agent_start event", async () =
> {
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] });
232 + const first = await t.session.extensionRunner.emitBeforeAgentStart(
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(
247 + assert.match(second?.systemPrompt ?? "", /parent topology/);
248 + assert.doesNotMatch(second?.systemPrompt ?? "", /nested topology/);
252 +describe("runtime readiness notice", () =
> {
253 + it("notifies once per session when initialization is incomplete", async () =
> {
254 + const root = makeDirectory("the-system-notice-");
255 + mkdirSync(path.join(root, ".git"));
256 + const t = await createTestSession({ cwd: root, extensions: [extensionPath] });
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) =
> 261 + String(call.args[0]).includes("/system-init"),
263 + assert.equal(notices.length, 1);
264 + assert.match(String(notices[0]?.args[0]), /incomplete or invalid/);
267 + it("stays silent for a doctor-green initialized project", async () =
> {
268 + const root = initialized();
269 + const t = await createTestSession({ cwd: root, extensions: [extensionPath] });
271 + await t.session.extensionRunner.emitBeforeAgentStart("one", undefined, "BASE", {});
273 + t.events.uiCallsFor("notify").filter((call) =
> 274 + String(call.args[0]).includes("/system-init"),
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>
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]) =
> {
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
> 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 {
305 + root = discoverProjectRoot(cwd);
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) =
> coreBlock(root, name)).filter(
311 + (block): block is string =
> block !== undefined,
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 {
319 + const inspection = inspectInitialization(cwd);
321 + inspection.creates.length
> 0 ||
322 + inspection.cores.some(({ state }) =
> state === "missing")
324 + return "The System is incomplete or invalid; run /system-init before governed work.";
325 + if (inspection.upgrades.length
> 0)
326 + return "The System schema/style refresh is available; run /system-init to inspect and approve it.";
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) =
> {
336 + if (notified || !ctx.hasUI) return;
337 + const message = runtimeNotice(ctx.cwd);
338 + if (!message) return;
339 + ctx.ui.notify(message, "warning");
342 + pi.on("session_start", async (event, ctx) =
> {
344 + notifyOnce(event, ctx);
346 + pi.on("before_agent_start", async (event, ctx) =
> {
347 + notifyOnce(event, ctx);
348 + return { systemPrompt: composeSystemPrompt(ctx.cwd, event.systemPrompt) };
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>
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>
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>
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>
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>
372 +<
pre><
code>const shell = (id: string) =
> `
<!doctype html
> 373 +<html lang="en"
><head
><meta charset="utf-8"
> 374 +<meta name="viewport" content="width=device-width, initial-scale=1"
> 375 +<title
>${id}
</title
><link rel="stylesheet" href="../system.css"
></head
> 376 +<body
><header
><h1
>${id}
</h1
></header
><main
><section
><h2
>Contract
</h2
><p
>Approved.
</p
></section
></main
> 377 +<script type="application/json" id="system-meta"
>{"id":"${id}","type":"spec"}
</script
></body
></html
>`;
378 +const writeSpec = (root: string, id = "PX-SPEC-001", slug = "contract") =
> {
379 + const relative = `.system/specs/${id}-${slug}.html`;
380 + write(root, relative, shell(id));
383 +<
p>Append these tests:</
p>
384 +<
pre><
code>describe("runtime write and edit governance", () =
> {
385 + it("blocks write/edit of existing cores and permits approved missing-core creation", async () =
> {
386 + const root = initialized();
387 + const t = await createTestSession({ cwd: root, extensions: [extensionPath] });
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" }] } },
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" },
402 + assert.equal(creation?.block, undefined);
405 + it("allows a valid new spec without a redundant UI gate and blocks an invalid candidate", async () =
> {
406 + const root = initialized();
407 + const t = await createTestSession({ cwd: root, extensions: [extensionPath] });
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") },
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: "
<html
>broken
</html
>" },
419 + assert.equal(invalid?.block, true);
420 + assert.match(invalid?.reason ?? "", /candidate validation failed/);
424 + ["approve", (items: string[]) =
> items[0], false, /./],
425 + ["deny", (items: string[]) =
> items[1], true, /denied/],
426 + ["cancel", () =
> undefined, true, /cancelled/],
427 + ] as const)("handles UI %s for an existing spec", async (_name, choose, blocked, reason) =
> {
428 + const root = initialized();
429 + const relative = writeSpec(root);
430 + const t = await createTestSession({
432 + extensions: [extensionPath],
433 + mockUI: { select: (_title, items) =
> choose(items) },
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." }] },
440 + assert.equal(result?.block === true, blocked);
441 + if (blocked) assert.match(result?.reason ?? "", reason);
442 + assert.equal(t.events.uiCallsFor("select").length, 1);
445 + it("fails closed without UI and validates the computed edit candidate first", async () =
> {
446 + const root = initialized();
447 + const relative = writeSpec(root);
448 + const noUi = await import("../system.ts");
449 + const result = await noUi.preflightFileMutation(
452 + { path: relative, edits: [{ oldText: "Approved.", newText: "Reviewed." }] },
453 + { hasUI: false, select: async () =
> undefined },
455 + assert.equal(result?.block, true);
456 + assert.match(result?.reason ?? "", /interactive UI is unavailable/);
457 + const invalid = await noUi.preflightFileMutation(
460 + { path: relative, edits: [{ oldText: "
</main
>", newText: "" }] },
461 + { hasUI: true, select: async (_title, items) =
> items[0] },
463 + assert.equal(invalid?.block, true);
464 + assert.match(invalid?.reason ?? "", /candidate validation failed/);
467 + it("permits a valid new spec-owned mockup and gates an existing one", async () =
> {
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] });
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") },
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.") },
484 + assert.equal(second?.block, true);
485 + assert.match(second?.reason ?? "", /cancelled/);
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>
498 +import path from "node:path";
500 + isToolCallEventType,
501 + type EditToolInput,
503 + type ExtensionContext,
504 + type WriteToolInput,
505 +} from "@earendil-works/pi-coding-agent";
508 + discoverProjectRoot,
511 + resolveGovernedPath,
512 + validateAuthoredHtml,
513 + validateDocumentCandidate,
514 +} from "./documents.ts";
515 +import { inspectInitialization } from "./init.ts";</
code></
pre>
517 +<
li><
strong>Step 4: add the direct preflight implementation.</
strong> Insert this block immediately before <
code>registerSystemGovernance</
code>:</
li>
519 +<
pre><
code>type MutationKind = "write" | "edit";
520 +type MutationInput = WriteToolInput | EditToolInput;
521 +type GateResult = Readonly
<{ block: true; reason: string }
> | undefined;
522 +export type GovernanceUI = Readonly
<{
524 + select(title: string, items: string[]): Promise
<string | undefined
>;
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",
532 +const MOCKUP_NAME = /^(.*)-mockup-[a-z0-9]+(?:-[a-z0-9]+)*\.html$/;
533 +const posixRelative = (root: string, target: string) =
> 534 + path.relative(root, target).split(path.sep).join("/");
535 +const blocked = (reason: string): GateResult =
> ({ block: true, reason });
536 +const diagnosticsReason = (diagnostics: readonly Diagnostic[]) =
> {
537 + const shown = diagnostics.slice(0, 3).map(
538 + (item) =
> `${item.path} ${item.code}: ${item.message}`,
540 + if (diagnostics.length
> 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) =
> {
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"
&& MOCKUP_NAME.test(entry.name)) continue;
553 + const sourcePath = `.system/${directory}/${entry.name}`;
556 + html: readFileSync(path.join(absolute, entry.name), "utf8"),
560 + return sources.sort((left, right) =
> left.path.localeCompare(right.path));
562 +const applyExactEdits = (source: string, edits: EditToolInput["edits"]) =
> {
563 + const replacements = edits.map((edit) =
> {
564 + const start = source.indexOf(edit.oldText);
565 + if (start
< 0 || source.indexOf(edit.oldText, start + 1)
>= 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) =
> left.start - right.start);
569 + for (let index = 1; index
< replacements.length; index++)
570 + if (replacements[index - 1]!.end
> replacements[index]!.start)
571 + throw new Error("governed edits must not overlap");
572 + let candidate = source;
573 + for (const replacement of replacements.reverse())
575 + candidate.slice(0, replacement.start) +
576 + replacement.newText +
577 + candidate.slice(replacement.end);
580 +const candidateContent = (
582 + kind: MutationKind,
583 + input: MutationInput,
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,
592 +const projectPrefix = (root: string) =
> 593 + parseSystemConfig(readFileSync(path.join(root, ".system/config.json"), "utf8")).prefix;
594 +const validateSpec = (
598 +) =
> validateDocumentCandidate(
599 + collectDocumentSources(root),
600 + { path: relative, html: content },
601 + projectPrefix(root),
603 +const validateMockup = (
607 +): readonly Diagnostic[] =
> {
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)))
614 + code: "mockup.orphaned",
616 + message: `Mockup owner is missing: ${ownerPath ?? "unrecognized filename"}`,
618 + return findings.sort(
619 + (left, right) =
> 620 + left.path.localeCompare(right.path) ||
621 + left.code.localeCompare(right.code) ||
622 + left.message.localeCompare(right.message),
626 +export async function preflightFileMutation(
628 + kind: MutationKind,
629 + input: MutationInput,
631 +): Promise
<GateResult
> {
634 + root = discoverProjectRoot(cwd);
636 + return blocked(`The System cannot resolve project ownership: ${error instanceof Error ? error.message : String(error)}`);
638 + let target: string;
640 + target = resolveGovernedPath(root, path.resolve(cwd, input.path));
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}.`);
652 + if (!relative.startsWith(".system/specs/") || !relative.endsWith(".html"))
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[];
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);
665 + return blocked(`The System candidate validation failed: ${error instanceof Error ? error.message : String(error)}`);
667 + if (findings.length
> 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}.`);
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;
679 + ? `The System ownership approval was denied for ${relative}.`
680 + : `The System ownership approval was cancelled for ${relative}.`,
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>
686 +<
pre><
code> pi.on("tool_call", async (event, ctx) =
> {
687 + const ui: GovernanceUI = {
689 + select: (title, items) =
> ctx.ui.select(title, items),
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);
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>
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>
705 +<
li><
strong>Step 1: append failing shell tests.</
strong> Append:</
li>
707 +<
pre><
code>describe("runtime shell advisory guard", () =
> {
709 + "printf replacement
> .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) =
> {
713 + const root = initialized();
715 + const t = await createTestSession({ cwd: root, extensions: [extensionPath] });
717 + const result = await t.session.extensionRunner.emitToolCall({
718 + type: "tool_call", toolCallId: "bash", toolName: "bash", input: { command },
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);
727 + "cat .system/RULES.md",
728 + "printf report
> build/report.txt",
729 + "git status --short",
730 + ])("allows a command without a recognizable owned mutation: %s", async (command) =
> {
731 + const root = initialized();
732 + const t = await createTestSession({ cwd: root, extensions: [extensionPath] });
734 + const result = await t.session.extensionRunner.emitToolCall({
735 + type: "tool_call", toolCallId: "bash-safe", toolName: "bash", input: { command },
737 + assert.equal(result?.block, undefined);
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>
744 +<
pre><
code>const SHELL_MUTATOR = /(?:^|[;
&|]\s*)(?:rm|mv|cp|install|truncate|touch|tee|sed\s+-[^\n]*i|perl\s+-[^\n]*i)\b|(?:^|[^
<])
>>?/i;
745 +const OWNED_SHELL_PATH = /(?:^|[\s"'`])([^\s"'`;
&|]*\.system\/(?:SYSTEM\.md|MISSION\.md|RULES\.md|specs\/[^\s"'`;
&|]+\.html))(?=$|[\s"'`;
&|])/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;
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.`,
756 +<
li><
strong>Step 4: add bash to the existing <
code>tool_call</
code> handler.</
strong> Insert before its write branch:</
li>
758 +<
pre><
code> if (isToolCallEventType("bash", event))
759 + return preflightShellMutation(event.input.command);</
code></
pre>
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>
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>
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>
780 +<
h2>Behavior matrix</
h2>
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>
796 +<
h2>Self-review and phase boundary</
h2>
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>
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>