1 +import assert
from "node:assert/strict";
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);
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");
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`);
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));
48 +const initialized = ()
=> {
49 + const root
= makeDirectory(
"the-system-runtime-");
50 + mkdirSync(path.
join(
root,
".git"));
51 + applyInitialization(
root,
"PX");
52 + writeCores(
root,
"root");
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 });
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/);
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/);
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/);
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] });
99 + const first
= await t.session.extensionRunner.
emitBeforeAgentStart(
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(
114 + assert.
match(second?.systemPrompt
?? "",
/parent topology/);
115 + assert.
doesNotMatch(second?.systemPrompt
?? "",
/nested topology/);
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] });
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"),
130 + assert.
equal(notices.
length,
1);
131 + assert.
match(
String(notices[
0]?.args[
0]),
/incomplete or invalid/);
134 + it(
"stays silent for a doctor-green initialized project",
async ()
=> {
135 + const root
= initialized();
136 + const t
= await createTestSession({ cwd:
root, extensions: [extensionPath] });
138 + await t.session.extensionRunner.
emitBeforeAgentStart(
"one",
undefined,
"BASE", {});
140 + t.events.
uiCallsFor(
"notify").
filter((call)
=> 141 + String(call.args[
0]).
includes(
"/system-init"),
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] });
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" }] } },
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" },
166 + assert.
equal(creation?.block,
undefined);
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(
177 + { path:
".system/SYSTEM.md", content:
"replacement" },
178 + { hasUI:
true,
select:
async ()
=> undefined },
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(
190 + path:
".system/specs/PX-SPEC-001-contract.html",
191 + content:
shell(
"PX-SPEC-001"),
193 + { hasUI:
true,
select:
async ()
=> undefined },
195 + assert.
equal(linkedDirectory?.block,
true);
196 + assert.
match(linkedDirectory?.reason
?? "",
/symbolic link/i);
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] });
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") },
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>" },
213 + assert.
equal(invalid?.block,
true);
214 + assert.
match(invalid?.reason
?? "",
/candidate validation failed/);
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(
224 + path:
".system/specs/nested/PX-SPEC-001-contract.html",
225 + content:
shell(
"PX-SPEC-001"),
227 + { hasUI:
true,
select:
async ()
=> undefined },
229 + assert.
equal(result?.block,
true);
230 + assert.
match(result?.reason
?? "",
/directly inside/);
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({
242 + extensions: [extensionPath],
243 + mockUI: {
select: (_title, items)
=> choose(items) },
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." }] },
250 + assert.
equal(result?.block
=== true, blocked);
251 + if (blocked) assert.
match(result?.reason
?? "", reason);
252 + assert.
equal(t.events.
uiCallsFor(
"select").
length,
1);
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(
262 + { path: relative, edits: [{ oldText:
"Approved.", newText:
"Reviewed." }] },
263 + { hasUI:
false,
select:
async ()
=> undefined },
265 + assert.
equal(result?.block,
true);
266 + assert.
match(result?.reason
?? "",
/interactive UI is unavailable/);
267 + const invalid
= await system.
preflightFileMutation(
270 + { path: relative, edits: [{ oldText:
"</main>", newText:
"" }] },
271 + { hasUI:
true,
select:
async (_title, items)
=> items[
0] },
273 + assert.
equal(invalid?.block,
true);
274 + assert.
match(invalid?.reason
?? "",
/candidate validation failed/);
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(
284 + path:
".system/specs/PX-SPEC-002-contract-mockup-mobile.html",
285 + content:
shell(
"PX-SPEC-002"),
287 + { hasUI:
true,
select:
async ()
=> undefined },
289 + assert.
equal(specNamedLikeMockup?.block,
undefined);
292 + const mockup
= ".system/specs/PX-SPEC-001-contract-mockup-mobile.html";
293 + write(
root, mockup,
documentShell(
"mockup"));
295 + const metadataFreeMockup
= await system.
preflightFileMutation(
298 + { path: mockup, content:
documentShell(
"mockup") },
301 + select:
async (_title, items)
=> {
307 + assert.
equal(metadataFreeMockup?.block,
undefined);
308 + assert.
equal(approvals,
1);
311 + it(
"preflights every document type but only requests ownership approval for specs and mockups",
async ()
=> {
312 + const root
= initialized();
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"}'],
321 + const relative
= `.system/${directory}/${id}-delivery.html`;
322 + const invalid
= await system.
preflightFileMutation(
325 + { path: relative, content:
"<html>broken</html>" },
326 + { hasUI:
true,
select:
async ()
=> {
throw new Error(
"unexpected approval"); } },
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(
335 + { path: relative, edits: [{ oldText:
"Approved.", newText:
"Reviewed." }] },
336 + { hasUI:
true,
select:
async ()
=> {
throw new Error(
"unexpected approval"); } },
338 + assert.
equal(existing?.block,
undefined, directory);
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({
349 + extensions: [extensionPath],
350 + mockUI: {
select: ()
=> undefined },
353 + const first
= await t.session.extensionRunner.
emitToolCall({
354 + type:
"tool_call", toolCallId:
"new-mockup", toolName:
"write",
355 + input: { path: mockup, content:
documentShell(
"mockup") },
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.") },
363 + assert.
equal(second?.block,
true);
364 + assert.
match(second?.reason
?? "",
/cancelled/);
368 +describe(
"runtime shell advisory guard", ()
=> {
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();
376 + const t
= await createTestSession({ cwd:
root, extensions: [extensionPath] });
378 + const result
= await t.session.extensionRunner.
emitToolCall({
379 + type:
"tool_call", toolCallId:
"bash", toolName:
"bash", input: { command },
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);
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] });
395 + const result
= await t.session.extensionRunner.
emitToolCall({
396 + type:
"tool_call", toolCallId:
"bash-safe", toolName:
"bash", input: { command },
398 + assert.
equal(result?.block,
undefined);