repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by bugabinga

feat(the-system): complete runtime governance

84a043b32131be522a6e9127558e26374e291aa8

Oliver Jan Krylow <oliver@bugabinga.net> ·

unsigned

Browse filesCompare with HEAD

Changed files (5)

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

Modified
18 18 resolveGovernedPath,
19 19 SystemDocumentError,
20 20 validateAuthoredHtml,
21 + validateDocumentCandidate,
21 22 validateFilename,
22 23 } from "../documents.ts";
762 +describe("document candidate validation", () => {
763 + const spec = (id: string, slug: string) => ({
764 + path: `.system/specs/${id}-${slug}.html`,
765 + html: shell(JSON.stringify({ id, type: "spec" })),
766 + });
767 + const roadmap = {
768 + path: ".system/roadmaps/PX-ROADMAP-001-delivery.html",
769 + html: shell(
770 + '{"id":"PX-ROADMAP-001","type":"roadmap","spec":"PX-SPEC-001"}',
771 + ),
772 + };
774 + it("accepts a valid new spec against a valid current index", () => {
775 + const current = [spec("PX-SPEC-001", "first")];
776 + assert.deepEqual(
777 + validateDocumentCandidate(current, spec("PX-SPEC-002", "second"), "PX"),
778 + [],
779 + );
780 + });
782 + it("reports candidate failures and graph breakage caused by replacement", () => {
783 + const current = [spec("PX-SPEC-001", "first"), roadmap];
784 + const replacement = {
785 + path: ".system/specs/PX-SPEC-001-first.html",
786 + html: shell('{"id":"PX-SPEC-002","type":"spec"}'),
787 + };
788 + assert.deepEqual(
789 + validateDocumentCandidate(current, replacement, "PX").map(
790 + ({ code, path }) => `${path} ${code}`,
791 + ),
793 + ".system/roadmaps/PX-ROADMAP-001-delivery.html graph.dangling-reference",
794 + ".system/specs/PX-SPEC-001-first.html document.filename",
795 + ],
796 + );
797 + });
799 + it("reports a duplicate ID on the candidate without replaying old findings", () => {
800 + const current = [
801 + spec("PX-SPEC-001", "first"),
802 + { path: ".system/specs/broken.html", html: "not html" },
803 + ];
804 + const findings = validateDocumentCandidate(
805 + current,
807 + path: ".system/specs/PX-SPEC-001-copy.html",
808 + html: shell('{"id":"PX-SPEC-001","type":"spec"}'),
809 + },
810 + "PX",
811 + );
812 + assert.deepEqual(
813 + findings.map(({ code, path }) => `${path} ${code}`),
814 + [".system/specs/PX-SPEC-001-copy.html graph.duplicate-id"],
815 + );
816 + });
817 +});
761 819 describe("bundled system.css", () => {
762 820 it("contains exact Nugu tokens, version, components, and responsive contracts", () => {
763 821 const css = readFileSync(

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

Added
new file mode 100644
1 +import assert from "node:assert/strict";
2 +import {
3 + mkdirSync,
4 + mkdtempSync,
5 + readFileSync,
6 + rmSync,
7 + symlinkSync,
8 + writeFileSync,
9 +} from "node:fs";
10 +import { tmpdir } from "node:os";
11 +import path from "node:path";
12 +import { afterEach, describe, it } from "vitest";
13 +import { createTestSession, type TestSession } from "../../../test/harness.ts";
14 +import { applyInitialization } from "../init.ts";
15 +import { CORE_BYTE_LIMIT, composeSystemPrompt } from "../system.ts";
17 +const temporary: string[] = [];
18 +const sessions: TestSession[] = [];
19 +const extensionPath = path.resolve(import.meta.dirname, "../index.ts");
20 +const makeDirectory = (prefix: string) => {
21 + const value = mkdtempSync(path.join(tmpdir(), prefix));
22 + temporary.push(value);
23 + return value;
24 +};
25 +const write = (root: string, relative: string, content: string) => {
26 + const target = path.join(root, relative);
27 + mkdirSync(path.dirname(target), { recursive: true });
28 + writeFileSync(target, content, "utf8");
29 +};
30 +const writeCores = (root: string, label: string) => {
31 + write(root, ".system/SYSTEM.md", `# System\n\n${label} topology.\n`);
32 + write(root, ".system/MISSION.md", `# Mission\n\n${label} purpose.\n`);
33 + write(root, ".system/RULES.md", `# Rules\n\n${label} constraints.\n`);
34 +};
35 +const documentShell = (id: string, metadata?: string) => `<!doctype html>
36 +<html lang="en"><head><meta charset="utf-8">
37 +<meta name="viewport" content="width=device-width, initial-scale=1">
38 +<title>${id}</title><link rel="stylesheet" href="../system.css"></head>
39 +<body><header><h1>${id}</h1></header><main><section><h2>Contract</h2><p>Approved.</p></section></main>${metadata ? `
40 +<script type="application/json" id="system-meta">${metadata}</script>` : ""}</body></html>`;
41 +const shell = (id: string) =>
42 + documentShell(id, `{"id":"${id}","type":"spec"}`);
43 +const writeSpec = (root: string, id = "PX-SPEC-001", slug = "contract") => {
44 + const relative = `.system/specs/${id}-${slug}.html`;
45 + write(root, relative, shell(id));
46 + return relative;
47 +};
48 +const initialized = () => {
49 + const root = makeDirectory("the-system-runtime-");
50 + mkdirSync(path.join(root, ".git"));
51 + applyInitialization(root, "PX");
52 + writeCores(root, "root");
53 + return root;
54 +};
55 +afterEach(() => {
56 + for (const session of sessions.splice(0)) session.dispose();
57 + for (const root of temporary.splice(0))
58 + rmSync(root, { recursive: true, force: true });
59 +});
61 +describe("runtime core injection", () => {
62 + it("appends existing cores in stable order and marks an oversized core", () => {
63 + const root = initialized();
64 + write(root, ".system/MISSION.md", "x".repeat(CORE_BYTE_LIMIT + 1));
65 + const prompt = composeSystemPrompt(root, "BASE");
66 + assert.ok(prompt.startsWith("BASE\n\n# The System project law"));
67 + assert.ok(prompt.indexOf("## SYSTEM.md") < prompt.indexOf("## MISSION.md"));
68 + assert.ok(prompt.indexOf("## MISSION.md") < prompt.indexOf("## RULES.md"));
69 + assert.match(prompt, /MISSION\.md exceeds the 32768-byte injection limit/);
70 + assert.match(prompt, /root topology/);
71 + assert.match(prompt, /root constraints/);
72 + });
74 + it("omits absent cores rather than inventing defaults", () => {
75 + const root = makeDirectory("the-system-runtime-empty-");
76 + write(root, ".system/RULES.md", "# Rules\n\nOnly existing truth.\n");
77 + const prompt = composeSystemPrompt(root, "BASE");
78 + assert.doesNotMatch(prompt, /## SYSTEM\.md|## MISSION\.md/);
79 + assert.match(prompt, /## RULES\.md[\s\S]*Only existing truth/);
80 + });
82 + it("returns a governance error block for malformed core paths", () => {
83 + const root = initialized();
84 + rmSync(path.join(root, ".system/SYSTEM.md"));
85 + mkdirSync(path.join(root, ".system/SYSTEM.md"));
86 + const prompt = composeSystemPrompt(root, "BASE");
87 + assert.match(prompt, /# The System governance error/);
88 + assert.match(prompt, /Malformed core path \.system\/SYSTEM\.md/);
89 + assert.match(prompt, /Do not mutate \.system/);
90 + });
92 + it("resolves the root again for every before_agent_start event", async () => {
93 + const parent = makeDirectory("the-system-root-change-");
94 + const cwd = path.join(parent, "packages", "app");
95 + mkdirSync(cwd, { recursive: true });
96 + writeCores(cwd, "nested");
97 + const t = await createTestSession({ cwd, extensions: [extensionPath] });
98 + sessions.push(t);
99 + const first = await t.session.extensionRunner.emitBeforeAgentStart(
100 + "first",
101 + undefined,
102 + "BASE",
103 + {},
104 + );
105 + assert.match(first?.systemPrompt ?? "", /nested topology/);
106 + mkdirSync(path.join(parent, ".git"));
107 + writeCores(parent, "parent");
108 + const second = await t.session.extensionRunner.emitBeforeAgentStart(
109 + "second",
110 + undefined,
111 + "BASE",
112 + {},
113 + );
114 + assert.match(second?.systemPrompt ?? "", /parent topology/);
115 + assert.doesNotMatch(second?.systemPrompt ?? "", /nested topology/);
116 + });
117 +});
119 +describe("runtime readiness notice", () => {
120 + it("notifies once per session when initialization is incomplete", async () => {
121 + const root = makeDirectory("the-system-notice-");
122 + mkdirSync(path.join(root, ".git"));
123 + const t = await createTestSession({ cwd: root, extensions: [extensionPath] });
124 + sessions.push(t);
125 + await t.session.extensionRunner.emitBeforeAgentStart("one", undefined, "BASE", {});
126 + await t.session.extensionRunner.emitBeforeAgentStart("two", undefined, "BASE", {});
127 + const notices = t.events.uiCallsFor("notify").filter((call) =>
128 + String(call.args[0]).includes("/system-init"),
129 + );
130 + assert.equal(notices.length, 1);
131 + assert.match(String(notices[0]?.args[0]), /incomplete or invalid/);
132 + });
134 + it("stays silent for a doctor-green initialized project", async () => {
135 + const root = initialized();
136 + const t = await createTestSession({ cwd: root, extensions: [extensionPath] });
137 + sessions.push(t);
138 + await t.session.extensionRunner.emitBeforeAgentStart("one", undefined, "BASE", {});
139 + assert.equal(
140 + t.events.uiCallsFor("notify").filter((call) =>
141 + String(call.args[0]).includes("/system-init"),
142 + ).length,
143 + 0,
144 + );
145 + });
146 +});
148 +describe("runtime write and edit governance", () => {
149 + it("blocks write/edit of existing cores and permits approved missing-core creation", async () => {
150 + const root = initialized();
151 + const t = await createTestSession({ cwd: root, extensions: [extensionPath] });
152 + sessions.push(t);
153 + for (const event of [
154 + { type: "tool_call", toolCallId: "w", toolName: "write", input: { path: ".system/RULES.md", content: "replacement" } },
155 + { type: "tool_call", toolCallId: "e", toolName: "edit", input: { path: ".system/MISSION.md", edits: [{ oldText: "root", newText: "agent" }] } },
156 + ] as const) {
157 + const result = await t.session.extensionRunner.emitToolCall(event);
158 + assert.equal(result?.block, true);
159 + assert.match(result?.reason ?? "", /human-owned core/);
161 + rmSync(path.join(root, ".system/SYSTEM.md"));
162 + const creation = await t.session.extensionRunner.emitToolCall({
163 + type: "tool_call", toolCallId: "new-core", toolName: "write",
164 + input: { path: ".system/SYSTEM.md", content: "# System\n\nHuman-approved.\n" },
165 + });
166 + assert.equal(creation?.block, undefined);
167 + });
169 + it("rejects symbolic-link governed targets and ancestors before allowing a write", async () => {
170 + const root = initialized();
171 + const system = await import("../system.ts");
172 + rmSync(path.join(root, ".system/SYSTEM.md"));
173 + symlinkSync("missing-core.md", path.join(root, ".system/SYSTEM.md"));
174 + const danglingCore = await system.preflightFileMutation(
175 + root,
176 + "write",
177 + { path: ".system/SYSTEM.md", content: "replacement" },
178 + { hasUI: true, select: async () => undefined },
179 + );
180 + assert.equal(danglingCore?.block, true);
181 + assert.match(danglingCore?.reason ?? "", /symbolic link/i);
183 + rmSync(path.join(root, ".system/specs"), { recursive: true });
184 + const outside = makeDirectory("the-system-linked-specs-");
185 + symlinkSync(outside, path.join(root, ".system/specs"), "dir");
186 + const linkedDirectory = await system.preflightFileMutation(
187 + root,
188 + "write",
190 + path: ".system/specs/PX-SPEC-001-contract.html",
191 + content: shell("PX-SPEC-001"),
192 + },
193 + { hasUI: true, select: async () => undefined },
194 + );
195 + assert.equal(linkedDirectory?.block, true);
196 + assert.match(linkedDirectory?.reason ?? "", /symbolic link/i);
197 + });
199 + it("allows a valid new spec without a redundant UI gate and blocks an invalid candidate", async () => {
200 + const root = initialized();
201 + const t = await createTestSession({ cwd: root, extensions: [extensionPath] });
202 + sessions.push(t);
203 + const valid = await t.session.extensionRunner.emitToolCall({
204 + type: "tool_call", toolCallId: "valid", toolName: "write",
205 + input: { path: ".system/specs/PX-SPEC-001-contract.html", content: shell("PX-SPEC-001") },
206 + });
207 + assert.equal(valid?.block, undefined);
208 + assert.equal(t.events.uiCallsFor("select").length, 0);
209 + const invalid = await t.session.extensionRunner.emitToolCall({
210 + type: "tool_call", toolCallId: "invalid", toolName: "write",
211 + input: { path: ".system/specs/PX-SPEC-002-broken.html", content: "<html>broken</html>" },
212 + });
213 + assert.equal(invalid?.block, true);
214 + assert.match(invalid?.reason ?? "", /candidate validation failed/);
215 + });
217 + it("requires authored documents directly inside their matching directory", async () => {
218 + const root = initialized();
219 + const system = await import("../system.ts");
220 + const result = await system.preflightFileMutation(
221 + root,
222 + "write",
224 + path: ".system/specs/nested/PX-SPEC-001-contract.html",
225 + content: shell("PX-SPEC-001"),
226 + },
227 + { hasUI: true, select: async () => undefined },
228 + );
229 + assert.equal(result?.block, true);
230 + assert.match(result?.reason ?? "", /directly inside/);
231 + });
233 + it.each([
234 + ["approve", (items: string[]) => items[0], false, /./],
235 + ["deny", (items: string[]) => items[1], true, /denied/],
236 + ["cancel", () => undefined, true, /cancelled/],
237 + ] as const)("handles UI %s for an existing spec", async (_name, choose, blocked, reason) => {
238 + const root = initialized();
239 + const relative = writeSpec(root);
240 + const t = await createTestSession({
241 + cwd: root,
242 + extensions: [extensionPath],
243 + mockUI: { select: (_title, items) => choose(items) },
244 + });
245 + sessions.push(t);
246 + const result = await t.session.extensionRunner.emitToolCall({
247 + type: "tool_call", toolCallId: "edit", toolName: "edit",
248 + input: { path: relative, edits: [{ oldText: "Approved.", newText: "Approved and reviewed." }] },
249 + });
250 + assert.equal(result?.block === true, blocked);
251 + if (blocked) assert.match(result?.reason ?? "", reason);
252 + assert.equal(t.events.uiCallsFor("select").length, 1);
253 + });
255 + it("fails closed without UI and validates the computed edit candidate first", async () => {
256 + const root = initialized();
257 + const relative = writeSpec(root);
258 + const system = await import("../system.ts");
259 + const result = await system.preflightFileMutation(
260 + root,
261 + "edit",
262 + { path: relative, edits: [{ oldText: "Approved.", newText: "Reviewed." }] },
263 + { hasUI: false, select: async () => undefined },
264 + );
265 + assert.equal(result?.block, true);
266 + assert.match(result?.reason ?? "", /interactive UI is unavailable/);
267 + const invalid = await system.preflightFileMutation(
268 + root,
269 + "edit",
270 + { path: relative, edits: [{ oldText: "</main>", newText: "" }] },
271 + { hasUI: true, select: async (_title, items) => items[0] },
272 + );
273 + assert.equal(invalid?.block, true);
274 + assert.match(invalid?.reason ?? "", /candidate validation failed/);
275 + });
277 + it("classifies metadata-bearing mockup slugs as specs and metadata-free files as mockups", async () => {
278 + const root = initialized();
279 + const system = await import("../system.ts");
280 + const specNamedLikeMockup = await system.preflightFileMutation(
281 + root,
282 + "write",
284 + path: ".system/specs/PX-SPEC-002-contract-mockup-mobile.html",
285 + content: shell("PX-SPEC-002"),
286 + },
287 + { hasUI: true, select: async () => undefined },
288 + );
289 + assert.equal(specNamedLikeMockup?.block, undefined);
291 + writeSpec(root);
292 + const mockup = ".system/specs/PX-SPEC-001-contract-mockup-mobile.html";
293 + write(root, mockup, documentShell("mockup"));
294 + let approvals = 0;
295 + const metadataFreeMockup = await system.preflightFileMutation(
296 + root,
297 + "write",
298 + { path: mockup, content: documentShell("mockup") },
300 + hasUI: true,
301 + select: async (_title, items) => {
302 + approvals += 1;
303 + return items[0];
304 + },
305 + },
306 + );
307 + assert.equal(metadataFreeMockup?.block, undefined);
308 + assert.equal(approvals, 1);
309 + });
311 + it("preflights every document type but only requests ownership approval for specs and mockups", async () => {
312 + const root = initialized();
313 + writeSpec(root);
314 + const system = await import("../system.ts");
315 + for (const [directory, id, metadata] of [
316 + ["roadmaps", "PX-ROADMAP-001", '{"id":"PX-ROADMAP-001","type":"roadmap","spec":"PX-SPEC-001"}'],
317 + ["plans", "PX-PLAN-001", '{"id":"PX-PLAN-001","type":"plan","spec":"PX-SPEC-001"}'],
318 + ["issues", "PX-ISSUE-001", '{"id":"PX-ISSUE-001","type":"issue","status":"open","specs":[]}'],
319 + ["research", "PX-RESEARCH-001", '{"id":"PX-RESEARCH-001","type":"research","capturedAt":"2026-07-15"}'],
320 + ] as const) {
321 + const relative = `.system/${directory}/${id}-delivery.html`;
322 + const invalid = await system.preflightFileMutation(
323 + root,
324 + "write",
325 + { path: relative, content: "<html>broken</html>" },
326 + { hasUI: true, select: async () => { throw new Error("unexpected approval"); } },
327 + );
328 + assert.equal(invalid?.block, true, directory);
329 + assert.match(invalid?.reason ?? "", /candidate validation failed/);
331 + write(root, relative, documentShell(id, metadata));
332 + const existing = await system.preflightFileMutation(
333 + root,
334 + "edit",
335 + { path: relative, edits: [{ oldText: "Approved.", newText: "Reviewed." }] },
336 + { hasUI: true, select: async () => { throw new Error("unexpected approval"); } },
337 + );
338 + assert.equal(existing?.block, undefined, directory);
340 + });
342 + it("permits a valid new spec-owned mockup and gates an existing one", async () => {
343 + const root = initialized();
344 + const owner = writeSpec(root);
345 + assert.ok(readFileSync(path.join(root, owner), "utf8").includes("PX-SPEC-001"));
346 + const mockup = ".system/specs/PX-SPEC-001-contract-mockup-mobile.html";
347 + const t = await createTestSession({
348 + cwd: root,
349 + extensions: [extensionPath],
350 + mockUI: { select: () => undefined },
351 + });
352 + sessions.push(t);
353 + const first = await t.session.extensionRunner.emitToolCall({
354 + type: "tool_call", toolCallId: "new-mockup", toolName: "write",
355 + input: { path: mockup, content: documentShell("mockup") },
356 + });
357 + assert.equal(first?.block, undefined);
358 + write(root, mockup, documentShell("mockup"));
359 + const second = await t.session.extensionRunner.emitToolCall({
360 + type: "tool_call", toolCallId: "old-mockup", toolName: "write",
361 + input: { path: mockup, content: documentShell("mockup").replace("Approved.", "Reviewed.") },
362 + });
363 + assert.equal(second?.block, true);
364 + assert.match(second?.reason ?? "", /cancelled/);
365 + });
366 +});
368 +describe("runtime shell advisory guard", () => {
369 + it.each([
370 + "printf replacement > .system/RULES.md",
371 + "sed -i 's/Approved/Changed/' .system/specs/PX-SPEC-001-contract.html",
372 + "rm .system/specs/PX-SPEC-001-contract-mockup-mobile.html",
373 + ])("blocks recognizable owned mutation: %s", async (command) => {
374 + const root = initialized();
375 + writeSpec(root);
376 + const t = await createTestSession({ cwd: root, extensions: [extensionPath] });
377 + sessions.push(t);
378 + const result = await t.session.extensionRunner.emitToolCall({
379 + type: "tool_call", toolCallId: "bash", toolName: "bash", input: { command },
380 + });
381 + assert.equal(result?.block, true);
382 + assert.match(result?.reason ?? "", /advisory shell guard/);
383 + assert.match(result?.reason ?? "", /not a sandbox/);
384 + assert.match(result?.reason ?? "", /use write or edit/i);
385 + });
387 + it.each([
388 + "cat .system/RULES.md",
389 + "printf report > build/report.txt",
390 + "git status --short",
391 + ])("allows a command without a recognizable owned mutation: %s", async (command) => {
392 + const root = initialized();
393 + const t = await createTestSession({ cwd: root, extensions: [extensionPath] });
394 + sessions.push(t);
395 + const result = await t.session.extensionRunner.emitToolCall({
396 + type: "tool_call", toolCallId: "bash-safe", toolName: "bash", input: { command },
397 + });
398 + assert.equal(result?.block, undefined);
399 + });
400 +});

extensions/the-system/documents.ts

Modified
841 +const diagnosticIdentity = (item: Diagnostic) =>
842 + JSON.stringify([item.path, item.code, item.message]);
844 +export function validateDocumentCandidate(
845 + current: readonly DocumentSource[],
846 + candidate: DocumentSource,
847 + prefix: string,
848 +): readonly Diagnostic[] {
849 + const baseline = new Set(
850 + indexDocuments(current, prefix).diagnostics.map(diagnosticIdentity),
851 + );
852 + const next = indexDocuments(
854 + ...current.filter((source) => source.path !== candidate.path),
855 + candidate,
856 + ],
857 + prefix,
858 + );
859 + return next.diagnostics.filter(
860 + (item) =>
861 + item.path === candidate.path ||
862 + (!baseline.has(diagnosticIdentity(item)) &&
863 + item.code !== "graph.duplicate-id"),
864 + );
841 867 export function indexDocuments(
842 868 sources: readonly DocumentSource[],
843 869 prefix: string,

extensions/the-system/index.ts

Modified
15 15 import { Type } from "typebox";
16 16 import { createMockupTool } from "./mockup.js";
17 +import { registerSystemGovernance } from "./system.js";
18 19 export default function registerTaskCommands(pi: ExtensionAPI): void {
20 + registerSystemGovernance(pi);
19 21 pi.registerTool(createPushTaskTool(pi));
20 22 pi.registerTool(createMockupTool());
21 23 pi.registerCommand("start-task", createStartTaskCommand(pi));

extensions/the-system/system.ts

Added
new file mode 100644
1 +import {
2 + existsSync,
3 + lstatSync,
4 + readdirSync,
5 + readFileSync,
6 +} from "node:fs";
7 +import path from "node:path";
8 +import {
9 + isToolCallEventType,
10 + type EditToolInput,
11 + type ExtensionAPI,
12 + type ExtensionContext,
13 + type WriteToolInput,
14 +} from "@earendil-works/pi-coding-agent";
15 +import {
16 + type Diagnostic,
17 + discoverProjectRoot,
18 + parseDocumentMetadata,
19 + parseSystemConfig,
20 + resolveGovernedPath,
21 + validateAuthoredHtml,
22 + validateDocumentCandidate,
23 +} from "./documents.ts";
24 +import { inspectInitialization } from "./init.ts";
26 +export const CORE_BYTE_LIMIT = 32 * 1024;
27 +const CORES = ["SYSTEM.md", "MISSION.md", "RULES.md"] as const;
29 +const governanceError = (systemPrompt: string, message: string) =>
30 + `${systemPrompt}\n\n# The System governance error\n\n${message}\n\nDo not mutate .system until /system-doctor resolves this governance error.`;
32 +const coreBlock = (root: string, name: (typeof CORES)[number]) => {
33 + const relative = `.system/${name}`;
34 + const target = path.join(root, relative);
35 + try {
36 + const stats = lstatSync(target, { throwIfNoEntry: false });
37 + if (!stats) return undefined;
38 + if (!stats.isFile())
39 + throw new Error(`Malformed core path ${relative}: expected a regular file.`);
40 + if (stats.size > CORE_BYTE_LIMIT)
41 + return `## ${name}\n\n[Not injected: ${name} exceeds the ${CORE_BYTE_LIMIT}-byte injection limit.]`;
42 + return `## ${name}\n\n${readFileSync(target, "utf8")}`;
43 + } catch (error) {
44 + const message = error instanceof Error ? error.message : String(error);
45 + throw new Error(`Unable to read core path ${relative}: ${message}`);
46 + }
47 +};
49 +export function composeSystemPrompt(cwd: string, systemPrompt: string): string {
50 + let root: string;
51 + try {
52 + root = discoverProjectRoot(cwd);
53 + } catch (error) {
54 + return governanceError(
55 + systemPrompt,
56 + error instanceof Error ? error.message : String(error),
57 + );
58 + }
59 + try {
60 + const blocks = CORES.map((name) => coreBlock(root, name)).filter(
61 + (block): block is string => block !== undefined,
62 + );
63 + if (blocks.length === 0) return systemPrompt;
64 + return `${systemPrompt}\n\n# The System project law\n\n${blocks.join("\n\n")}`;
65 + } catch (error) {
66 + return governanceError(
67 + systemPrompt,
68 + error instanceof Error ? error.message : String(error),
69 + );
70 + }
73 +export function runtimeNotice(cwd: string): string | undefined {
74 + try {
75 + const inspection = inspectInitialization(cwd);
76 + if (
77 + inspection.creates.length > 0 ||
78 + inspection.cores.some(({ state }) => state === "missing")
79 + )
80 + return "The System is incomplete or invalid; run /system-init before governed work.";
81 + if (inspection.upgrades.length > 0)
82 + return "The System schema/style refresh is available; run /system-init to inspect and approve it.";
83 + return undefined;
84 + } catch {
85 + return "The System is incomplete or invalid; run /system-init before governed work.";
86 + }
89 +type MutationKind = "write" | "edit";
90 +type MutationInput = WriteToolInput | EditToolInput;
91 +type GateResult = Readonly<{ block: true; reason: string }> | undefined;
92 +export type GovernanceUI = Readonly<{
93 + hasUI: boolean;
94 + select(title: string, items: string[]): Promise<string | undefined>;
95 +}>;
96 +const DOCUMENT_DIRECTORIES = [
97 + "specs",
98 + "roadmaps",
99 + "plans",
100 + "issues",
101 + "research",
102 +] as const;
103 +const CORE_PATHS = new Set([
104 + ".system/SYSTEM.md",
105 + ".system/MISSION.md",
106 + ".system/RULES.md",
107 +]);
108 +const MOCKUP_NAME = /^(.*)-mockup-[a-z0-9]+(?:-[a-z0-9]+)*\.html$/;
109 +const posixRelative = (root: string, target: string) =>
110 + path.relative(root, target).split(path.sep).join("/");
111 +const blocked = (reason: string): GateResult => ({ block: true, reason });
112 +const diagnosticsReason = (diagnostics: readonly Diagnostic[]) => {
113 + const shown = diagnostics
114 + .slice(0, 3)
115 + .map((item) => `${item.path} ${item.code}: ${item.message}`);
116 + if (diagnostics.length > shown.length)
117 + shown.push(`+${diagnostics.length - shown.length} more finding(s)`);
118 + return `The System candidate validation failed: ${shown.join("; ")}`;
120 +const collectDocumentSources = (root: string, prefix: string) => {
121 + const sources: { path: string; html: string }[] = [];
122 + for (const directory of DOCUMENT_DIRECTORIES) {
123 + const absolute = path.join(root, ".system", directory);
124 + const stats = lstatSync(absolute, { throwIfNoEntry: false });
125 + if (!stats?.isDirectory()) continue;
126 + for (const entry of readdirSync(absolute, { withFileTypes: true })) {
127 + if (!entry.isFile() || !entry.name.endsWith(".html")) continue;
128 + const sourcePath = `.system/${directory}/${entry.name}`;
129 + const html = readFileSync(path.join(absolute, entry.name), "utf8");
130 + if (directory === "specs" && MOCKUP_NAME.test(entry.name)) {
131 + try {
132 + if (parseDocumentMetadata(html, prefix).type !== "spec") continue;
133 + } catch {
134 + continue;
137 + sources.push({ path: sourcePath, html });
140 + return sources.sort((left, right) => left.path.localeCompare(right.path));
142 +const applyExactEdits = (source: string, edits: EditToolInput["edits"]) => {
143 + const replacements = edits
144 + .map((edit) => {
145 + const start = source.indexOf(edit.oldText);
146 + if (start < 0 || source.indexOf(edit.oldText, start + 1) >= 0)
147 + throw new Error("each governed edit oldText must match exactly once");
148 + return { start, end: start + edit.oldText.length, newText: edit.newText };
149 + })
150 + .sort((left, right) => left.start - right.start);
151 + for (let index = 1; index < replacements.length; index++) {
152 + const previous = replacements[index - 1];
153 + const next = replacements[index];
154 + if (previous && next && previous.end > next.start)
155 + throw new Error("governed edits must not overlap");
157 + let candidate = source;
158 + for (const replacement of replacements.reverse())
159 + candidate =
160 + candidate.slice(0, replacement.start) +
161 + replacement.newText +
162 + candidate.slice(replacement.end);
163 + return candidate;
165 +const candidateContent = (
166 + target: string,
167 + kind: MutationKind,
168 + input: MutationInput,
169 +) => {
170 + if (kind === "write") return (input as WriteToolInput).content;
171 + if (!existsSync(target))
172 + throw new Error("edit cannot create a governed file; use write");
173 + return applyExactEdits(
174 + readFileSync(target, "utf8"),
175 + (input as EditToolInput).edits,
176 + );
178 +const projectPrefix = (root: string) =>
179 + parseSystemConfig(readFileSync(path.join(root, ".system/config.json"), "utf8"))
180 + .prefix;
181 +const validateDocument = (root: string, relative: string, content: string) => {
182 + const prefix = projectPrefix(root);
183 + return validateDocumentCandidate(
184 + collectDocumentSources(root, prefix),
185 + { path: relative, html: content },
186 + prefix,
187 + );
189 +const isSpecCandidate = (root: string, content: string) => {
190 + try {
191 + return parseDocumentMetadata(content, projectPrefix(root)).type === "spec";
192 + } catch {
193 + return false;
196 +const validateMockup = (
197 + root: string,
198 + relative: string,
199 + content: string,
200 +): readonly Diagnostic[] => {
201 + const findings = [...validateAuthoredHtml(relative, content)];
202 + const filename = path.posix.basename(relative);
203 + const owner = MOCKUP_NAME.exec(filename)?.[1];
204 + const ownerPath = owner ? `.system/specs/${owner}.html` : undefined;
205 + if (!ownerPath || !existsSync(path.join(root, ownerPath)))
206 + findings.push({
207 + code: "mockup.orphaned",
208 + path: relative,
209 + message: `Mockup owner is missing: ${ownerPath ?? "unrecognized filename"}`,
210 + });
211 + return findings.sort(
212 + (left, right) =>
213 + left.path.localeCompare(right.path) ||
214 + left.code.localeCompare(right.code) ||
215 + left.message.localeCompare(right.message),
216 + );
219 +const directDocumentPath = (relative: string) =>
220 + /^\.system\/(specs|roadmaps|plans|issues|research)\/[^/]+\.html$/.test(
221 + relative,
222 + );
223 +const nestedDocumentPath = (relative: string) =>
224 + /^\.system\/(specs|roadmaps|plans|issues|research)\/.+\/[^/]+\.html$/.test(
225 + relative,
226 + );
227 +const symbolicLinkInPath = (root: string, target: string) => {
228 + const relative = path.relative(root, target);
229 + let current = root;
230 + for (const part of relative.split(path.sep)) {
231 + if (!part) continue;
232 + current = path.join(current, part);
233 + const stats = lstatSync(current, { throwIfNoEntry: false });
234 + if (stats?.isSymbolicLink()) return posixRelative(root, current);
236 + return undefined;
239 +const SHELL_MUTATOR =
240 + /(?:^|[;&|]\s*)(?:rm|mv|cp|install|truncate|touch|tee|sed\s+-[^\n]*i|perl\s+-[^\n]*i)\b|(?:^|[^<])>>?/i;
241 +const OWNED_SHELL_PATH =
242 + /(?:^|[\s"'`])([^\s"'`;&|]*\.system\/(?:SYSTEM\.md|MISSION\.md|RULES\.md|specs\/[^\s"'`;&|]+\.html))(?=$|[\s"'`;&|])/i;
244 +export function preflightShellMutation(command: string): GateResult {
245 + if (!SHELL_MUTATOR.test(command)) return undefined;
246 + const owned = OWNED_SHELL_PATH.exec(command)?.[1];
247 + if (!owned) return undefined;
248 + return blocked(
249 + `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.`,
250 + );
253 +export async function preflightFileMutation(
254 + cwd: string,
255 + kind: MutationKind,
256 + input: MutationInput,
257 + ui: GovernanceUI,
258 +): Promise<GateResult> {
259 + let root: string;
260 + try {
261 + root = discoverProjectRoot(cwd);
262 + } catch (error) {
263 + return blocked(
264 + `The System cannot resolve project ownership: ${error instanceof Error ? error.message : String(error)}`,
265 + );
267 + let target: string;
268 + try {
269 + target = resolveGovernedPath(root, path.resolve(cwd, input.path));
270 + } catch (error) {
271 + return blocked(
272 + `The System rejected the governed path: ${error instanceof Error ? error.message : String(error)}`,
273 + );
275 + const relative = posixRelative(root, target);
276 + if (nestedDocumentPath(relative))
277 + return blocked(
278 + `The System requires authored documents directly inside their matching .system directory: ${relative}.`,
279 + );
280 + const documentPath = directDocumentPath(relative);
281 + if (!CORE_PATHS.has(relative) && !documentPath) return undefined;
282 + try {
283 + const link = symbolicLinkInPath(root, target);
284 + if (link)
285 + return blocked(`The System rejected symbolic link in governed path: ${link}.`);
286 + } catch (error) {
287 + return blocked(
288 + `The System rejected unsafe governed path: ${error instanceof Error ? error.message : String(error)}`,
289 + );
291 + const targetStats = lstatSync(target, { throwIfNoEntry: false });
292 + if (CORE_PATHS.has(relative)) {
293 + if (targetStats)
294 + return blocked(`The System blocked mutation of human-owned core ${relative}.`);
295 + if (kind === "edit")
296 + return blocked(
297 + `The System requires write, not edit, to create approved missing core ${relative}.`,
298 + );
299 + return undefined;
301 + let content: string;
302 + let findings: readonly Diagnostic[];
303 + let mockup: boolean;
304 + let spec: boolean;
305 + try {
306 + content = candidateContent(target, kind, input);
307 + spec = isSpecCandidate(root, content);
308 + mockup = MOCKUP_NAME.test(path.posix.basename(relative)) && !spec;
309 + findings = mockup
310 + ? validateMockup(root, relative, content)
311 + : validateDocument(root, relative, content);
312 + } catch (error) {
313 + return blocked(
314 + `The System candidate validation failed: ${error instanceof Error ? error.message : String(error)}`,
315 + );
317 + if (findings.length > 0) return blocked(diagnosticsReason(findings));
318 + if (!targetStats) return undefined;
319 + if (!targetStats.isFile())
320 + return blocked(`The System expected a regular owned file at ${relative}.`);
321 + if (!spec && !mockup) return undefined;
322 + if (!ui.hasUI)
323 + return blocked(
324 + `The System blocked existing human-owned ${relative}: interactive UI is unavailable.`,
325 + );
326 + const approve = `Approve once: ${kind} ${relative}`;
327 + const deny = `Deny: keep ${relative} unchanged`;
328 + const decision = await ui.select("The System ownership approval", [approve, deny]);
329 + if (decision === approve) return undefined;
330 + return blocked(
331 + decision === deny
332 + ? `The System ownership approval was denied for ${relative}.`
333 + : `The System ownership approval was cancelled for ${relative}.`,
334 + );
337 +export function registerSystemGovernance(pi: ExtensionAPI): void {
338 + let notified = false;
339 + const notifyOnce = (_event: unknown, ctx: ExtensionContext) => {
340 + if (notified || !ctx.hasUI) return;
341 + const message = runtimeNotice(ctx.cwd);
342 + if (!message) return;
343 + ctx.ui.notify(message, "warning");
344 + notified = true;
345 + };
346 + pi.on("session_start", async (event, ctx) => {
347 + notified = false;
348 + notifyOnce(event, ctx);
349 + });
350 + pi.on("before_agent_start", async (event, ctx) => {
351 + notifyOnce(event, ctx);
352 + return { systemPrompt: composeSystemPrompt(ctx.cwd, event.systemPrompt) };
353 + });
354 + pi.on("tool_call", async (event, ctx) => {
355 + const ui: GovernanceUI = {
356 + hasUI: ctx.hasUI,
357 + select: (title, items) => ctx.ui.select(title, items),
358 + };
359 + if (isToolCallEventType("bash", event))
360 + return preflightShellMutation(event.input.command);
361 + if (isToolCallEventType("write", event))
362 + return preflightFileMutation(ctx.cwd, "write", event.input, ui);
363 + if (isToolCallEventType("edit", event))
364 + return preflightFileMutation(ctx.cwd, "edit", event.input, ui);
365 + });