4 +<
meta charset=
"utf-8">
5 +<
meta name=
"viewport" content=
"width=device-width, initial-scale=1">
6 +<
title>The System Phase 3 doctor implementation plan</
title>
8 +:root {
color-scheme:light dark;
--fg:
#121212;
--page:
#ededed;
--panel:
#dbdbdb;
--accent:
#ae2eae;
--ui:
#922792;
--focus:
#184e5b;
--error:
#bd172e; }
9 +@media(prefers-
color-scheme:dark) { :root {
--fg:
#ededed;
--page:
#121212;
--panel:
#242424;
--accent:
#d151d1;
--ui:
#d86dd8;
--focus:
#7ba1aa;
--error:
#ec6376; } }
10 +* {
box-sizing:
border-box; }
11 +body {
margin:
0;
padding:
1rem;
background:
var(
--page);
color:
var(
--fg);
font:
14px/
1.55 ui-monospace,
SFMono-Regular,
Consolas,
monospace; }
12 +article {
width:min(
100%,
1080px);
margin:
0 auto 3rem;
border:
3px solid var(
--fg);
box-shadow:
10px 10px 0 var(
--ui); }
13 +header,
section {
padding:clamp(
1rem,
3vw,
1.5rem);
border-bottom:
2px solid var(
--fg); }
14 +header {
background:
var(
--panel);
border-bottom-width:
3px; }
15 +h1 {
margin:
.25rem 0;
font:
900 clamp(
1.8rem,
6vw,
3.7rem)/.92
system-ui;
text-transform:
uppercase; }
16 +h2 {
margin:
0 0 1rem;
color:
var(
--accent);
font:
900 1rem/
1 system-ui;
letter-spacing:
.12em;
text-transform:
uppercase; }
17 +h3 {
margin:
1.4rem 0 .5rem;
font-size:
.92rem;
text-transform:
uppercase; }
18 +p,
li {
max-width:
94ch; }
19 +li {
margin:
.38rem 0; }
20 +a {
color:
var(
--focus);
font-weight:
900; }
21 +code {
background:
var(
--panel);
padding:
.1rem .3rem;
overflow-wrap:anywhere; }
22 +pre {
max-width:
100%;
overflow:
auto;
padding:
1rem;
border:
2px solid var(
--fg);
border-left:
8px solid var(
--ui);
background:
var(
--panel); }
23 +pre code {
padding:
0;
background:
transparent; }
24 +table {
width:
100%;
border-collapse:
collapse; }
25 +th,
td {
padding:
.65rem;
border:
2px solid var(
--fg);
text-align:
left;
vertical-align:
top; }
26 +th {
background:
var(
--panel); }
27 +.contract {
padding:
.8rem;
border:
3px solid var(
--fg);
border-left:
9px solid var(
--accent);
background:
var(
--panel); }
28 +.stop {
border-left-color:
var(
--error); }
29 +.checks {
padding-left:
1.35rem; }
30 +@media(
max-width:
600px) {
body {
padding:
.5rem; }
article {
box-shadow:
5px 5px 0 var(
--ui); }
table,
tbody,
tr,
th,
td {
display:
block;
width:
100%; }
th {
border-bottom:
0; } }
36 +<
p><
strong>Implementation plan · 2026-07-11</
strong></
p>
37 +<
h1>Phase 3 · Doctor vertical slice</
h1>
38 +<
p><
strong>For agentic workers:</
strong> REQUIRED SUB-SKILL: use <
code>/skill:executing-plans</
code> task-by-task. Checkbox steps are tracking state.</
p>
39 +<
p><
strong>Goal:</
strong> ship a deterministic, read-only project doctor, its focused workflow skill and prompt, and the shared document-authoring authority.</
p>
40 +<
p><
strong>Architecture:</
strong> add a filesystem adapter in <
code>doctor.ts</
code> over the pure Phase 2 <
code>documents.ts</
code> kernel, then keep <
code>scripts/doctor.mjs</
code> limited to text rendering and exit status. Pi behavior remains resource-only: one thin prompt delegates to one doctor skill; <
code>system-documents</
code> centralizes authoring law without changing existing workflows.</
p>
41 +<
p><
strong>Tech stack:</
strong> TypeScript, Node 26 standard library/native type transformation, Vitest, Pi package resources, Markdown skills/prompts, Biome/dprint, mise.</
p>
42 +<
p><
strong>Roadmap:</
strong> <
a href=
"../roadmaps/2026-07-11-the-system-roadmap.html"><
code>docs/super/roadmaps/2026-07-11-the-system-roadmap.html</
code></
a></
p>
43 +<
p><
strong>Design:</
strong> <
a href=
"../specs/2026-07-11-the-system-design.html"><
code>docs/super/specs/2026-07-11-the-system-design.html</
code></
a></
p>
44 +<
p><
strong>Phase:</
strong> Phase 3: Doctor vertical slice.</
p>
49 +<
div class=
"contract"><
strong>Deliver only:</
strong> read-only doctor traversal/reporting, <
code>system-doctor</
code>, <
code>/system-doctor</
code>, initial <
code>system-documents</
code>, prompt exports, exact resource checks, and independent CI proof.</
div>
51 +<
li>No <
code>system.ts</
code>, runtime hook, startup notice, prompt injection, ownership gate, initialization, config/CSS copy, browser opener, lifecycle migration, or filesystem write.</
li>
52 +<
li>The doctor may read only regular files and directories below the discovered project root. It does not follow symbolic links, execute authored JavaScript, fetch URLs, or repair findings.</
li>
53 +<
li>Existing task branches, mockup behavior, extension registration, and workflow skills remain unchanged.</
li>
54 +<
li>Historical <
code>docs/super/**</
code> remains the approved plan location and is excluded from the live-name assertion.</
li>
60 +<
tr><
th>Path</
th><
th>Action</
th><
th>Responsibility</
th></
tr>
61 +<
tr><
td><
code>extensions/the-system/doctor.ts</
code></
td><
td>Create</
td><
td>Read-only filesystem traversal, config/CSS checks, authored-source collection, mockup ownership, test-reference discovery, stable result.</
td></
tr>
62 +<
tr><
td><
code>extensions/the-system/scripts/doctor.mjs</
code></
td><
td>Create</
td><
td>CLI argument, stable line protocol, and exit status only.</
td></
tr>
63 +<
tr><
td><
code>extensions/the-system/__tests__/doctor.test.ts</
code></
td><
td>Create</
td><
td>Fixture diagnostics, ordering, CLI status, and byte/metadata no-mutation proof.</
td></
tr>
64 +<
tr><
td><
code>extensions/the-system/skills/system-doctor/SKILL.md</
code></
td><
td>Create</
td><
td>Doctor invocation and explanation workflow; explicitly forbids repair.</
td></
tr>
65 +<
tr><
td><
code>extensions/the-system/skills/system-documents/SKILL.md</
code></
td><
td>Create</
td><
td>Single authority for authored HTML, metadata, IDs, references, mockups, validation, and browser-review consent.</
td></
tr>
66 +<
tr><
td><
code>extensions/the-system/prompts/system-doctor.md</
code></
td><
td>Create</
td><
td>Thin <
code>/system-doctor</
code> delegation.</
td></
tr>
67 +<
tr><
td><
code>extensions/the-system/__tests__/workflow-skills.test.ts</
code></
td><
td>Modify</
td><
td>Exact skill/prompt contracts and real package resource discovery.</
td></
tr>
68 +<
tr><
td><
code>extensions/the-system/package.json</
code></
td><
td>Modify</
td><
td>Export package-local <
code>prompts</
code> beside existing extension and skills resources.</
td></
tr>
69 +<
tr><
td><
code>package.json</
code></
td><
td>Modify</
td><
td>Export The System prompts from the repository package.</
td></
tr>
70 +<
tr><
td><
code>scripts/test_extensions_static_check.mjs</
code></
td><
td>Modify</
td><
td>Pin exact root and extension resource manifests.</
td></
tr>
72 +<
p><
code>documents.ts</
code>, <
code>index.ts</
code>, <
code>mockup.ts</
code>, <
code>tsconfig.json</
code>, and the lockfile do not change. <
code>doctor.ts</
code> imports the Phase 2 public kernel; scripts remain excluded from root typecheck while <
code>doctor.ts</
code> is included automatically.</
p>
75 +<
h2>Task 1 · Read-only doctor model and fixture traversal</
h2>
76 +<
p><
strong>Files:</
strong> create <
code>extensions/the-system/doctor.ts</
code> and <
code>extensions/the-system/__tests__/doctor.test.ts</
code>.</
p>
78 +<
li><
strong>☐ Step 1: write the failing fixture tests.</
strong> Create <
code>extensions/the-system/__tests__/doctor.test.ts</
code> exactly:</
li>
80 +<
pre><
code>import assert from "node:assert/strict";
90 +import { tmpdir } from "node:os";
91 +import path from "node:path";
92 +import { afterEach, describe, it } from "vitest";
93 +import { runDoctor } from "../doctor.ts";
95 +const roots: string[] = [];
96 +const temporaryRoot = () =
> {
97 + const root = mkdtempSync(path.join(tmpdir(), "the-system-doctor-"));
99 + mkdirSync(path.join(root, ".git"));
102 +const write = (root: string, relative: string, content = "") =
> {
103 + const target = path.join(root, relative);
104 + mkdirSync(path.dirname(target), { recursive: true });
105 + writeFileSync(target, content, "utf8");
107 +const metadata = (value: object) =
> 108 + `
<script type="application/json" id="system-meta"
>${JSON.stringify(value)}
</script
>`;
109 +const html = (meta: object, body = "
<p
>contract
</p
>") =
> `
<!doctype html
> 110 +<html lang="en"
> 112 +<meta charset="utf-8"
> 113 +<meta name="viewport" content="width=device-width, initial-scale=1"
> 114 +<title
>Fixture
</title
> 115 +<link rel="stylesheet" href="../system.css"
> 118 +<body
><header
><h1
>Fixture
</h1
></header
><main
><section
>${body}
</section
></main
></body
> 120 +const validSystem = (root: string) =
> {
121 + for (const directory of ["specs", "roadmaps", "plans", "issues", "research"])
122 + mkdirSync(path.join(root, ".system", directory), { recursive: true });
123 + for (const file of ["SYSTEM.md", "MISSION.md", "RULES.md"])
124 + write(root, `.system/${file}`, `# ${file}\n`);
127 + ".system/config.json",
128 + '{"prefix":"PX","schemaVersion":1,"styleVersion":1}',
130 + write(root, ".system/system.css", "/* The System styleVersion: 1 */\n");
133 +afterEach(() =
> {
134 + for (const root of roots.splice(0))
135 + rmSync(root, { recursive: true, force: true });
138 +describe("system doctor", () =
> {
139 + it("reports every required path in stable path/code order", () =
> {
140 + const root = temporaryRoot();
141 + const result = runDoctor(path.join(root, "nested"));
143 + assert.equal(result.root, root);
144 + assert.equal(result.exitCode, 1);
146 + result.diagnostics.map(({ code, path }) =
> `${path} ${code}`),
148 + ".system filesystem.missing",
149 + ".system/MISSION.md filesystem.missing",
150 + ".system/RULES.md filesystem.missing",
151 + ".system/SYSTEM.md filesystem.missing",
152 + ".system/config.json filesystem.missing",
153 + ".system/issues filesystem.missing",
154 + ".system/plans filesystem.missing",
155 + ".system/research filesystem.missing",
156 + ".system/roadmaps filesystem.missing",
157 + ".system/specs filesystem.missing",
158 + ".system/system.css filesystem.missing",
163 + it("combines machine-state, kernel, mockup, and test-reference findings", () =
> {
164 + const root = temporaryRoot();
168 + ".system/config.json",
169 + '{"prefix":"PX","schemaVersion":2,"styleVersion":2}',
171 + write(root, ".system/system.css", "/* The System styleVersion: 1 */\n");
174 + ".system/specs/PX-SPEC-001-contract.html",
175 + html({ id: "PX-SPEC-001", type: "spec" }),
179 + ".system/plans/PX-PLAN-001-work.html",
180 + html({ id: "PX-PLAN-001", type: "plan", spec: "PX-SPEC-999" }),
184 + ".system/specs/PX-SPEC-404-gone-mockup-empty.html",
185 + "
<!doctype html
><title
>asset
</title
>",
189 + "tests/contract.test.ts",
190 + "// SYSTEM-SPEC: PX-SPEC-001\n// SYSTEM-SPEC: PX-SPEC-999\n",
193 + const result = runDoctor(root);
195 + assert.deepEqual(result.references, [
196 + { path: "tests/contract.test.ts", spec: "PX-SPEC-001" },
197 + { path: "tests/contract.test.ts", spec: "PX-SPEC-999" },
200 + result.diagnostics.map(({ code, path }) =
> `${path} ${code}`),
202 + ".system/config.json config.schema-outdated",
203 + ".system/config.json config.style-outdated",
204 + ".system/plans/PX-PLAN-001-work.html graph.dangling-reference",
205 + ".system/specs/PX-SPEC-404-gone-mockup-empty.html mockup.orphaned",
206 + ".system/system.css css.version-mismatch",
207 + "tests/contract.test.ts test.dangling-reference",
210 + assert.equal(result.exitCode, 1);
213 + it("returns green for a complete system and ignores symlinks and non-HTML files", () =
> {
214 + const root = temporaryRoot();
218 + ".system/specs/PX-SPEC-001-contract.html",
219 + html({ id: "PX-SPEC-001", type: "spec" }),
221 + write(root, ".system/specs/notes.txt", "not authored HTML");
222 + write(root, "src/value.ts", "export const value = 1;\n");
224 + const result = runDoctor(root);
226 + assert.deepEqual(result.diagnostics, []);
227 + assert.deepEqual(result.references, []);
228 + assert.equal(result.exitCode, 0);
231 +<
ol class=
"checks" start=
"2">
232 +<
li><
strong>☐ Step 2: run RED.</
strong><
br>Run: <
code>mise run test -- extensions/the-system/__tests__/doctor.test.ts</
code><
br>Expected: FAIL because <
code>../doctor.ts</
code> cannot be resolved.</
li>
233 +<
li><
strong>☐ Step 3: implement the minimal read-only adapter.</
strong> Create <
code>extensions/the-system/doctor.ts</
code> exactly:</
li>
241 +import path from "node:path";
244 + discoverProjectRoot,
249 + SystemDocumentError,
250 + validateAuthoredHtml,
251 +} from "./documents.ts";
253 +export type TestReference = Readonly
<{ path: string; spec: string }
>;
254 +export type DoctorResult = Readonly
<{
256 + diagnostics: readonly Diagnostic[];
257 + references: readonly TestReference[];
261 +const SYSTEM_DIRECTORIES = [
264 + ".system/roadmaps",
267 + ".system/research",
269 +const SYSTEM_FILES = [
270 + ".system/config.json",
271 + ".system/system.css",
272 + ".system/SYSTEM.md",
273 + ".system/MISSION.md",
274 + ".system/RULES.md",
276 +const DOCUMENT_DIRECTORIES = [
283 +const TEST_DIRECTORIES = ["test", "tests", "__tests__"] as const;
284 +const TEST_REFERENCE = /SYSTEM-SPEC:\s*([A-Z][A-Z0-9]{1,7}-SPEC-[0-9]{3,})/g;
285 +const MOCKUP = /^(.*)-mockup-[a-z0-9]+(?:-[a-z0-9]+)*\.html$/;
287 +const diagnostic = (code: string, path: string, message: string): Diagnostic =
> ({
292 +const compareDiagnostics = (left: Diagnostic, right: Diagnostic) =
> 293 + left.path.localeCompare(right.path) ||
294 + left.code.localeCompare(right.code) ||
295 + left.message.localeCompare(right.message);
296 +const relativePath = (root: string, target: string) =
> 297 + path.relative(root, target).split(path.sep).join("/");
298 +const isDirectory = (target: string) =
> {
300 + return statSync(target, { throwIfNoEntry: false })?.isDirectory() === true;
305 +const isFile = (target: string) =
> {
307 + return statSync(target, { throwIfNoEntry: false })?.isFile() === true;
313 +const collectDocumentSources = (root: string) =
> {
314 + const sources: { path: string; html: string }[] = [];
315 + const mockups: string[] = [];
316 + for (const directory of DOCUMENT_DIRECTORIES) {
317 + const absoluteDirectory = path.join(root, ".system", directory);
318 + if (!isDirectory(absoluteDirectory)) continue;
319 + for (const entry of readdirSync(absoluteDirectory, { withFileTypes: true })) {
320 + if (!entry.isFile() || !entry.name.endsWith(".html")) continue;
321 + const relative = `.system/${directory}/${entry.name}`;
322 + if (directory === "specs"
&& MOCKUP.test(entry.name)) {
323 + mockups.push(relative);
328 + html: readFileSync(path.join(absoluteDirectory, entry.name), "utf8"),
333 + sources: sources.sort((left, right) =
> left.path.localeCompare(right.path)),
334 + mockups: mockups.sort(),
338 +const collectTestReferences = (root: string): TestReference[] =
> {
339 + const references: TestReference[] = [];
340 + const visited = new Set
<string
>();
341 + const scan = (directory: string) =
> {
342 + const resolved = path.resolve(directory);
343 + if (visited.has(resolved) || !isDirectory(resolved)) return;
344 + visited.add(resolved);
345 + for (const entry of readdirSync(resolved, { withFileTypes: true }).sort(
346 + (left, right) =
> left.name.localeCompare(right.name),
348 + if ([".git", ".jj", ".system", "node_modules"].includes(entry.name))
350 + const target = path.join(resolved, entry.name);
351 + if (entry.isDirectory()) {
355 + if (!entry.isFile()) continue;
356 + const source = readFileSync(target, "utf8");
357 + for (const match of source.matchAll(TEST_REFERENCE))
358 + references.push({ path: relativePath(root, target), spec: match[1] });
361 + for (const directory of TEST_DIRECTORIES) scan(path.join(root, directory));
362 + return references.sort(
363 + (left, right) =
> 364 + left.path.localeCompare(right.path) || left.spec.localeCompare(right.spec),
368 +export function runDoctor(cwd: string): DoctorResult {
371 + root = discoverProjectRoot(cwd);
373 + const value = error as SystemDocumentError;
374 + const diagnostics = [diagnostic(value.code, path.resolve(cwd), value.message)];
375 + return { root: path.resolve(cwd), diagnostics, references: [], exitCode: 1 };
378 + const diagnostics: Diagnostic[] = [];
379 + for (const relative of SYSTEM_DIRECTORIES) {
380 + const target = path.join(root, relative);
381 + if (!isDirectory(target))
383 + diagnostic("filesystem.missing", relative, `Missing directory ${relative}`),
386 + for (const relative of SYSTEM_FILES) {
387 + const target = path.join(root, relative);
388 + if (!isFile(target))
390 + diagnostic("filesystem.missing", relative, `Missing file ${relative}`),
394 + let prefix: string | undefined;
395 + const configPath = path.join(root, ".system/config.json");
396 + if (isFile(configPath)) {
398 + const config = parseSystemConfig(readFileSync(configPath, "utf8"));
399 + prefix = config.prefix;
400 + if (config.schemaVersion !== SCHEMA_VERSION)
403 + "config.schema-outdated",
404 + ".system/config.json",
405 + `Schema version ${config.schemaVersion}; installed ${SCHEMA_VERSION}`,
408 + if (config.styleVersion !== STYLE_VERSION)
411 + "config.style-outdated",
412 + ".system/config.json",
413 + `Style version ${config.styleVersion}; installed ${STYLE_VERSION}`,
417 + const value = error as SystemDocumentError;
419 + diagnostic(value.code, ".system/config.json", value.message),
424 + const cssPath = path.join(root, ".system/system.css");
425 + if (isFile(cssPath)) {
426 + const css = readFileSync(cssPath, "utf8");
427 + const version = /The System styleVersion:\s*([0-9]+)/.exec(css)?.[1];
432 + ".system/system.css",
433 + "Missing The System styleVersion marker",
436 + else if (Number(version) !== STYLE_VERSION)
439 + "css.version-mismatch",
440 + ".system/system.css",
441 + `Stylesheet version ${version}; installed ${STYLE_VERSION}`,
446 + const { sources, mockups } = collectDocumentSources(root);
447 + let specIds = new Set
<string
>();
449 + const index = indexDocuments(sources, prefix);
450 + diagnostics.push(...index.diagnostics);
453 + .filter((document) =
> document.metadata.type === "spec")
454 + .map((document) =
> document.metadata.id),
457 + for (const source of sources)
458 + diagnostics.push(...validateAuthoredHtml(source.path, source.html));
461 + const sourcePaths = new Set(sources.map((source) =
> source.path));
462 + for (const mockup of mockups) {
463 + const filename = path.posix.basename(mockup);
464 + const owner = MOCKUP.exec(filename)?.[1];
465 + const ownerPath = `.system/specs/${owner}.html`;
466 + if (!owner || !sourcePaths.has(ownerPath))
471 + `Mockup owner is missing: ${ownerPath}`,
476 + const references = collectTestReferences(root);
477 + for (const reference of references)
478 + if (prefix
&& !specIds.has(reference.spec))
481 + "test.dangling-reference",
483 + `Test references missing ${reference.spec}`,
487 + diagnostics.sort(compareDiagnostics);
492 + exitCode: diagnostics.length === 0 ? 0 : 1,
495 +<
ol class=
"checks" start=
"4">
496 +<
li><
strong>☐ Step 4: run GREEN.</
strong><
br>Run: <
code>mise run test -- extensions/the-system/__tests__/doctor.test.ts</
code><
br>Expected: PASS; output order is path, code, message regardless of directory enumeration order.</
li>
497 +<
li><
strong>☐ Step 5: typecheck the new adapter.</
strong><
br>Run: <
code>npm run typecheck</
code><
br>Expected: exit 0; <
code>doctor.ts</
code> is covered by <
code>extensions/**/*.ts</
code>.</
li>
498 +<
li><
strong>☐ Step 6: checkpoint.</
strong><
br>Run: <
code>git add extensions/the-system/doctor.ts extensions/the-system/__tests__/doctor.test.ts
&& git commit -m "feat(the-system): add read-only project doctor"</
code><
br>Expected: one focused adapter/test commit; unrelated dirty paths remain unstaged.</
li>
502 +<
h2>Task 2 · Deterministic CLI, status, and no-mutation proof</
h2>
503 +<
p><
strong>Files:</
strong> modify <
code>extensions/the-system/__tests__/doctor.test.ts</
code>; create <
code>extensions/the-system/scripts/doctor.mjs</
code>.</
p>
505 +<
li><
strong>☐ Step 1: add CLI dependencies and snapshot helper.</
strong> In <
code>extensions/the-system/__tests__/doctor.test.ts</
code>, add <
code>spawnSync</
code> from <
code>node:child_process</
code>. Add <
code>mode</
code> and <
code>mtimeMs</
code> to the existing <
code>node:fs</
code> imports only through the helper below; no additional imports are required. Insert before <
code>afterEach</
code>:</
li>
507 +<
pre><
code>const snapshot = (root: string) =
> {
508 + const entries: { path: string; content?: string; mode: number; mtimeMs: number }[] = [];
509 + const visit = (directory: string) =
> {
510 + for (const entry of readdirSync(directory, { withFileTypes: true }).sort(
511 + (left, right) =
> left.name.localeCompare(right.name),
513 + const target = path.join(directory, entry.name);
514 + const stats = statSync(target);
516 + path: path.relative(root, target).split(path.sep).join("/"),
518 + mtimeMs: stats.mtimeMs,
522 + ? { ...record, content: readFileSync(target, "utf8") }
525 + if (entry.isDirectory()) visit(target);
531 +<
p>Append inside <
code>describe("system doctor", ...)</
code>:</
p>
532 +<
pre><
code> it("renders stable CLI output, returns status, and does not mutate the tree", () =
> {
533 + const root = temporaryRoot();
537 + ".system/specs/PX-SPEC-001-contract.html",
538 + html({ id: "PX-SPEC-001", type: "spec" }),
540 + write(root, "tests/contract.test.ts", "// SYSTEM-SPEC: PX-SPEC-001\n");
541 + const before = snapshot(root);
542 + const script = path.resolve(import.meta.dirname, "../scripts/doctor.mjs");
544 + const green = spawnSync(
546 + ["--experimental-transform-types", script, root],
547 + { encoding: "utf8", env: { ...process.env, NODE_NO_WARNINGS: "1" } },
550 + assert.equal(green.status, 0);
553 + `ROOT ${root}\nREF tests/contract.test.ts PX-SPEC-001\nOK The System is valid\n`,
555 + assert.equal(green.stderr, "");
556 + assert.deepEqual(snapshot(root), before);
558 + write(root, ".system/system.css", "unversioned\n");
559 + const brokenBefore = snapshot(root);
560 + const red = spawnSync(
562 + ["--experimental-transform-types", script, root],
563 + { encoding: "utf8", env: { ...process.env, NODE_NO_WARNINGS: "1" } },
566 + assert.equal(red.status, 1);
569 + `ROOT ${root}\nREF tests/contract.test.ts PX-SPEC-001\nERROR css.version .system/system.css: Missing The System styleVersion marker\n`,
571 + assert.equal(red.stderr, "");
572 + assert.deepEqual(snapshot(root), brokenBefore);
574 +<
ol class=
"checks" start=
"2">
575 +<
li><
strong>☐ Step 2: run RED.</
strong><
br>Run: <
code>mise run test -- extensions/the-system/__tests__/doctor.test.ts</
code><
br>Expected: FAIL because <
code>scripts/doctor.mjs</
code> is absent and the child exits nonzero without the line protocol.</
li>
576 +<
li><
strong>☐ Step 3: add the thin executable.</
strong> Create <
code>extensions/the-system/scripts/doctor.mjs</
code> exactly:</
li>
578 +<
pre><
code>#!/usr/bin/env node
579 +import { runDoctor } from "../doctor.ts";
581 +const result = runDoctor(process.argv[2] ?? process.cwd());
582 +console.log(`ROOT ${result.root}`);
583 +for (const reference of result.references)
584 + console.log(`REF ${reference.path} ${reference.spec}`);
585 +for (const finding of result.diagnostics)
586 + console.log(`ERROR ${finding.code} ${finding.path}: ${finding.message}`);
587 +if (result.exitCode === 0) console.log("OK The System is valid");
588 +process.exitCode = result.exitCode;</
code></
pre>
589 +<
ol class=
"checks" start=
"4">
590 +<
li><
strong>☐ Step 4: run GREEN.</
strong><
br>Run: <
code>mise run test -- extensions/the-system/__tests__/doctor.test.ts</
code><
br>Expected: PASS, including exact stdout, exit 0/1, empty stderr, and unchanged names/content/mode/mtime.</
li>
591 +<
li><
strong>☐ Step 5: prove direct invocation against an uninitialized disposable directory.</
strong><
br>Run: <
code>tmp=$(mktemp -d); node --no-warnings --experimental-transform-types extensions/the-system/scripts/doctor.mjs "$tmp"; status=$?; rm -rf "$tmp"; test "$status" -eq 1</
code><
br>Expected: one <
code>ROOT</
code> line followed by eleven sorted <
code>ERROR filesystem.missing</
code> lines; final shell status 0 confirms doctor status was 1 and cleanup was external.</
li>
592 +<
li><
strong>☐ Step 6: checkpoint.</
strong><
br>Run: <
code>git add extensions/the-system/scripts/doctor.mjs extensions/the-system/__tests__/doctor.test.ts
&& git commit -m "feat(the-system): expose doctor CLI"</
code><
br>Expected: one CLI/test commit.</
li>
596 +<
h2>Task 3 · Doctor and document-authority skill contracts</
h2>
597 +<
p><
strong>Files:</
strong> modify <
code>extensions/the-system/__tests__/workflow-skills.test.ts</
code>; create both skill files and <
code>extensions/the-system/prompts/system-doctor.md</
code>.</
p>
599 +<
li><
strong>☐ Step 1: write failing contract tests.</
strong> Add this helper below <
code>skill</
code> in <
code>extensions/the-system/__tests__/workflow-skills.test.ts</
code>:</
li>
601 +<
pre><
code>const prompt = (name: string) =
> 602 + readFileSync(path.join(root, "prompts", `${name}.md`), "utf8");</
code></
pre>
603 +<
p>Append inside the existing <
code>describe</
code>:</
p>
604 +<
pre><
code> it("keeps system-doctor prompt thin and delegates without repair", () =
> {
605 + const template = prompt("system-doctor");
606 + const doctor = skill("system-doctor");
608 + assert.match(template, /^---\ndescription: Diagnose The System without mutation\n---/);
609 + assert.match(template, /system-doctor skill/);
610 + assert.doesNotMatch(template, /config\.json|system\.css|readdir|writeFile/);
611 + assert.match(doctor, /\.\.\/\.\.\/scripts\/doctor\.mjs/);
612 + assert.match(doctor, /--experimental-transform-types/);
613 + assert.match(doctor, /Exit 0/);
614 + assert.match(doctor, /Exit 1/);
615 + assert.match(doctor, /Never edit, initialize, upgrade, copy, or delete/);
618 + it("makes system-documents the single authored-document authority", () =
> {
619 + const documents = skill("system-documents");
621 + for (const contract of [
622 + "single document-authoring authority",
625 + "SPEC|ROADMAP|PLAN|ISSUE|RESEARCH",
626 + "Metadata is the reference authority",
627 + "spec-owned mockup",
628 + "Never open a browser or editor automatically",
629 + "scripts/doctor.mjs",
631 + assert.ok(documents.includes(contract), `missing document contract: ${contract}`);
632 + assert.doesNotMatch(documents, /initialize|SYSTEM\.md|MISSION\.md|RULES\.md/i);
634 +<
ol class=
"checks" start=
"2">
635 +<
li><
strong>☐ Step 2: run RED.</
strong><
br>Run: <
code>mise run test -- extensions/the-system/__tests__/workflow-skills.test.ts</
code><
br>Expected: FAIL with <
code>ENOENT</
code> for <
code>prompts/system-doctor.md</
code>.</
li>
636 +<
li><
strong>☐ Step 3: create the focused doctor skill.</
strong> Create <
code>extensions/the-system/skills/system-doctor/SKILL.md</
code> exactly:</
li>
640 +description: Diagnose a project's .system tree deterministically without changing files
645 +Use this skill when a user asks to inspect, validate, or explain a project system.
649 +1. Resolve `../../scripts/doctor.mjs` against this skill directory and use that absolute path.
650 +2. Run `node --no-warnings --experimental-transform-types
<absolute-doctor-path
> <project-cwd
>`.
651 +3. Treat `ROOT`, `REF`, `ERROR`, and `OK` as the complete machine report.
653 +Exit 0 means the project system is valid.
654 +Exit 1 means one or more findings were reported.
658 +- Preserve report order.
659 +- Explain each code, path, observed state, and required human action.
660 +- State that discovered `REF` lines are informational unless a matching dangling-reference error exists.
661 +- State that active-markup checks are structural lint, not browser sandboxing.
662 +- Never edit, initialize, upgrade, copy, or delete project files.
663 +- Never rerun with a repair flag; no repair mode exists.
665 +<
ol class=
"checks" start=
"4">
666 +<
li><
strong>☐ Step 4: create the shared authoring authority.</
strong> Create <
code>extensions/the-system/skills/system-documents/SKILL.md</
code> exactly:</
li>
669 +name: system-documents
670 +description: Apply The System HTML, metadata, ID, reference, mockup, validation, and browser-review contracts
675 +This is the single document-authoring authority for `.system` authored documents.
676 +Other lifecycle skills must delegate these rules instead of copying or weakening them.
680 +- Discover the project root from the nearest `.jj` and `.git` markers; stop when they disagree.
681 +- Read `.system/config.json`; require its approved prefix and current schema/style versions.
682 +- Resolve every target below the project root and reject traversal.
683 +- Inspect existing filenames and metadata before allocating an ID.
687 +Use `<
PREFIX>-(SPEC|ROADMAP|PLAN|ISSUE|RESEARCH)-<
SEQUENCE>`.
688 +Start sequence text at three digits, permit growth past 999, and use the next unused value for that type.
689 +Use lowercase ASCII slugs matching `[a-z0-9]+(?:-[a-z0-9]+)*`.
690 +Write `<
ID>-<
slug>.html` only in its matching `.system/specs|roadmaps|plans|issues|research` directory.
694 +Every authored document is complete, formatted, directly editable HTML with:
696 +- `
<!doctype html
>`, `
<html lang="en"
>`, UTF-8 charset, viewport, and a nonempty title;
697 +- exactly one `
<link rel="stylesheet" href="../system.css"
>`;
698 +- header followed by main containing one section;
699 +- semantic headings, paragraphs, lists, tables, asides, figures, and details where appropriate;
700 +- one readable `
<script type="application/json" id="system-meta"
>` block.
702 +Inline CSS may express document-specific layout but may not redefine shared Nugu colors, typography, breakpoints, or components.
703 +Inline JavaScript must be optional, dependency-free progressive disclosure, filtering, or a tiny explanation.
704 +Forbid network APIs, browser storage, dynamic import, external scripts, event-handler attributes, executable URL schemes, iframes, objects, embeds, meta refresh, remote runtime assets, generated SVG sludge, and diagram libraries.
705 +HTTPS anchors remain allowed navigation.
707 +## Metadata and graph
709 +Metadata is the reference authority; prose links never create graph edges.
710 +Use exact keys only:
712 +- spec: `id`, `type`;
713 +- roadmap: `id`, `type`, one `spec`;
714 +- plan: `id`, `type`, one `spec`, plus `roadmap` and positive `phase` together when phase-scoped;
715 +- issue: `id`, `type`, `open|fixed` status, unique `specs` array;
716 +- research: `id`, `type`, ISO `capturedAt`, optional unique HTTPS `sources`.
718 +Specs are leaf truth and have no outgoing system-document metadata.
719 +Roadmaps point to one spec.
720 +Plans point to one spec and optionally one phase of a roadmap for that same spec.
721 +Issues point only to specs; an empty array is allowed while the violated contract is unknown.
722 +Tests use a language-appropriate `SYSTEM-SPEC:
<SPEC-ID
>` comment.
724 +## Spec-owned mockups
726 +Persist only a human-accepted spec-owned mockup.
727 +Place it beside its owner as `<
spec-stem>-mockup-<
option-slug>.html` and link it relatively from the spec.
728 +A mockup is a constituent asset, not an authored graph node: do not add `system-meta`.
729 +Keep it standalone, editable, dependency-free, and subject to the same active-resource prohibitions.
731 +## Validate and review
733 +After writing or materially editing a document, run the bundled `../../scripts/doctor.mjs` through Node with `--experimental-transform-types`.
734 +Do not hide, reorder, or silently repair findings.
735 +Print the exact source path and ask whether browser review is wanted.
736 +Never open a browser or editor automatically.
737 +Only use an explicitly approved, shell-free local-file opener when one is available; otherwise leave the source path as the review interface.
739 +<
ol class=
"checks" start=
"5">
740 +<
li><
strong>☐ Step 5: create the thin prompt.</
strong> Create <
code>extensions/the-system/prompts/system-doctor.md</
code> exactly:</
li>
743 +description: Diagnose The System without mutation
745 +Use the system-doctor skill to run deterministic validation for the current project and explain every reported line without changing files.
747 +<
ol class=
"checks" start=
"6">
748 +<
li><
strong>☐ Step 6: run GREEN.</
strong><
br>Run: <
code>mise run test -- extensions/the-system/__tests__/workflow-skills.test.ts</
code><
br>Expected: PASS; prompt contains delegation only, doctor skill owns execution/explanation, document skill owns all authoring contracts.</
li>
749 +<
li><
strong>☐ Step 7: run skill validation.</
strong><
br>Run: <
code>node scripts/check_skills.mjs</
code><
br>Expected: exit 0; both new directory names equal frontmatter names.</
li>
750 +<
li><
strong>☐ Step 8: checkpoint.</
strong><
br>Run: <
code>git add extensions/the-system/skills/system-doctor/SKILL.md extensions/the-system/skills/system-documents/SKILL.md extensions/the-system/prompts/system-doctor.md extensions/the-system/__tests__/workflow-skills.test.ts
&& git commit -m "feat(the-system): add doctor and document skills"</
code><
br>Expected: one resource-contract commit.</
li>
754 +<
h2>Task 4 · Package prompt exports and real discovery</
h2>
755 +<
p><
strong>Files:</
strong> modify both package manifests, <
code>workflow-skills.test.ts</
code>, and <
code>scripts/test_extensions_static_check.mjs</
code>.</
p>
757 +<
li><
strong>☐ Step 1: write the real package-discovery test.</
strong> In <
code>extensions/the-system/__tests__/workflow-skills.test.ts</
code>, replace the <
code>node:fs</
code> import with:</
li>
759 +<
pre><
code>import { mkdtempSync, readFileSync, rmSync } from "node:fs";
760 +import { tmpdir } from "node:os";
762 + DefaultPackageManager,
764 +} from "@earendil-works/pi-coding-agent";</
code></
pre>
765 +<
p>Append inside the existing <
code>describe</
code>:</
p>
766 +<
pre><
code> it("discovers doctor resources from both package manifests", async () =
> {
767 + const sandbox = mkdtempSync(path.join(tmpdir(), "the-system-resources-"));
769 + const settings = SettingsManager.create(
771 + path.join(sandbox, ".agent"),
773 + const manager = new DefaultPackageManager({
775 + agentDir: path.join(sandbox, ".agent"),
776 + settingsManager: settings,
778 + const repository = await manager.resolveExtensionSources(
779 + [path.resolve(root, "../../..")],
780 + { temporary: true },
782 + const extension = await manager.resolveExtensionSources([root], {
785 + const relativeResources = (
787 + resources: readonly { path: string }[],
790 + .map((resource) =
> 791 + path.relative(base, resource.path).split(path.sep).join("/"),
795 + assert.deepEqual(relativeResources(root, extension.prompts), [
796 + "prompts/system-doctor.md",
799 + relativeResources(root, extension.skills).includes(
800 + "skills/system-doctor/SKILL.md",
804 + relativeResources(path.resolve(root, "../../.."), repository.prompts).includes(
805 + "extensions/the-system/prompts/system-doctor.md",
809 + rmSync(sandbox, { recursive: true, force: true });
812 +<
ol class=
"checks" start=
"2">
813 +<
li><
strong>☐ Step 2: run RED.</
strong><
br>Run: <
code>mise run test -- extensions/the-system/__tests__/workflow-skills.test.ts</
code><
br>Expected: FAIL because neither manifest exports prompts.</
li>
814 +<
li><
strong>☐ Step 3: export extension-package prompts.</
strong> In <
code>extensions/the-system/package.json</
code>, replace the complete <
code>pi</
code> object with:</
li>
827 +<
ol class=
"checks" start=
"4">
828 +<
li><
strong>☐ Step 4: export repository-package prompts.</
strong> In root <
code>package.json</
code>, add after the existing <
code>skills</
code> array inside <
code>pi</
code>:</
li>
832 + "extensions/the-system/prompts"
834 +<
ol class=
"checks" start=
"5">
835 +<
li><
strong>☐ Step 5: update exact static assertions.</
strong> In <
code>scripts/test_extensions_static_check.mjs</
code>, replace the current root skills-only assertion and extension-manifest assertion with:</
li>
837 +<
pre><
code>assert.deepEqual(rootPkg().pi, {
838 + extensions: ["extensions/*/index.ts"],
840 + "extensions/the-system/skills",
841 + "extensions/ultra/skills",
842 + "extensions/lazy/skills",
844 + prompts: ["extensions/the-system/prompts"],
848 + readFileSync(join(ROOT, "extensions/the-system/package.json"), "utf8"),
851 + extensions: ["index.ts"],
852 + skills: ["skills"],
853 + prompts: ["prompts"],
856 +<
ol class=
"checks" start=
"6">
857 +<
li><
strong>☐ Step 6: run GREEN resource tests.</
strong><
br>Run: <
code>mise run test -- extensions/the-system/__tests__/workflow-skills.test.ts</
code><
br>Expected: PASS; <
code>DefaultPackageManager</
code> discovers the actual prompt and doctor skill through extension and repository manifests.</
li>
858 +<
li><
strong>☐ Step 7: run exact static checks.</
strong><
br>Run: <
code>node scripts/test_extensions_static_check.mjs</
code><
br>Expected: prints <
code>OK static-check tests</
code>.</
li>
859 +<
li><
strong>☐ Step 8: verify no lockfile churn.</
strong><
br>Run: <
code>npm install --package-lock-only --ignore-scripts
&& git diff --exit-code -- package-lock.json</
code><
br>Expected: exit 0; Pi resource metadata does not alter workspace lock entries. If the local npm version reformats unrelated lock data, restore only <
code>package-lock.json</
code> from the task-start snapshot and rerun the diff command.</
li>
860 +<
li><
strong>☐ Step 9: checkpoint.</
strong><
br>Run: <
code>git add package.json extensions/the-system/package.json extensions/the-system/__tests__/workflow-skills.test.ts scripts/test_extensions_static_check.mjs
&& git commit -m "feat(the-system): export doctor prompt resources"</
code><
br>Expected: one manifest/discovery commit; <
code>package-lock.json</
code> remains unchanged.</
li>
864 +<
h2>Task 5 · Independent-green phase gate</
h2>
865 +<
p><
strong>Files:</
strong> no new files; verify only the Phase 3 paths above.</
p>
867 +<
li><
strong>☐ Step 1: format through repository tooling.</
strong><
br>Run: <
code>mise run fmt</
code><
br>Expected: Biome and dprint complete. Inspect <
code>git status --short</
code>, retain formatting only in planned Phase 3 files, and restore tool changes to unrelated pre-existing dirty files from the task-start snapshot.</
li>
868 +<
li><
strong>☐ Step 2: rerun focused doctor and resource suites.</
strong><
br>Run: <
code>mise run test -- extensions/the-system/__tests__/doctor.test.ts extensions/the-system/__tests__/workflow-skills.test.ts</
code><
br>Expected: PASS.</
li>
869 +<
li><
strong>☐ Step 3: run all renamed-extension regressions.</
strong><
br>Run: <
code>mise run test -- extensions/the-system/__tests__</
code><
br>Expected: PASS for doctor, documents, harness, tasks, mockup, and workflow skills.</
li>
870 +<
li><
strong>☐ Step 4: typecheck.</
strong><
br>Run: <
code>npm run typecheck</
code><
br>Expected: exit 0; runtime entrypoints retain their existing exclusions and <
code>doctor.ts</
code> typechecks.</
li>
871 +<
li><
strong>☐ Step 5: run package/static checks.</
strong><
br>Run: <
code>mise run check</
code><
br>Expected: skill validation, <
code>OK static-check tests</
code>, and all extension package checks pass.</
li>
872 +<
li><
strong>☐ Step 6: prove real extension loading remains intact.</
strong><
br>Run: <
code>mise run test -- extensions/the-system/__tests__/harness.test.ts</
code><
br>Expected: PASS with exactly one loaded <
code>index.ts</
code>; doctor remains an on-demand script/resource slice.</
li>
873 +<
li><
strong>☐ Step 7: run full CI.</
strong><
br>Run: <
code>mise run ci</
code><
br>Expected: lint, all repository tests, skill checks, static checks, and extension checks pass.</
li>
874 +<
li><
strong>☐ Step 8: audit phase boundary and dirty-work preservation.</
strong><
br>Run: <
code>git status --short
&& git diff --name-only HEAD~4..HEAD</
code><
br>Expected: committed phase paths are exactly the ten paths in the file map; no <
code>system.ts</
code>, <
code>index.ts</
code>, <
code>mockup.ts</
code>, <
code>documents.ts</
code>, <
code>tsconfig.json</
code>, or lockfile change. Pre-existing unrelated dirty paths remain present and unmodified.</
li>
875 +<
li><
strong>☐ Step 9: final formatting checkpoint only if needed.</
strong><
br>Run: <
code>git add extensions/the-system/doctor.ts extensions/the-system/scripts/doctor.mjs extensions/the-system/__tests__/doctor.test.ts extensions/the-system/__tests__/workflow-skills.test.ts extensions/the-system/skills/system-doctor/SKILL.md extensions/the-system/skills/system-documents/SKILL.md extensions/the-system/prompts/system-doctor.md extensions/the-system/package.json package.json scripts/test_extensions_static_check.mjs
&& git diff --cached --quiet || git commit -m "test(the-system): complete doctor phase gate"</
code><
br>Expected: formatting-only planned changes commit when present; otherwise no commit is created.</
li>
879 +<
h2>Acceptance matrix</
h2>
881 +<
tr><
th>Phase 3 contract</
th><
th>Proof</
th></
tr>
882 +<
tr><
td>Any cwd resolves through Phase 2 JJ/Git rules; conflicts fail.</
td><
td><
code>runDoctor</
code> delegates to <
code>discoverProjectRoot</
code>; Phase 2 root matrix remains green.</
td></
tr>
883 +<
tr><
td>Missing core files/directories and malformed/outdated machine state report deterministically.</
td><
td>Doctor fixture tests and sorted line protocol.</
td></
tr>
884 +<
tr><
td>HTML shell, metadata, filename, duplicate ID, dangling graph, forbidden resource, and stylesheet findings reuse one kernel.</
td><
td><
code>collectDocumentSources → indexDocuments</
code>; no duplicate validator implementation.</
td></
tr>
885 +<
tr><
td>Orphaned spec-owned mockups report without treating mockups as graph documents.</
td><
td><
code>MOCKUP</
code> owner-stem check and fixture.</
td></
tr>
886 +<
tr><
td>Conventional test roots report discovered <
code>SYSTEM-SPEC</
code> references and dangling targets.</
td><
td>Sorted <
code>REF</
code> lines plus <
code>test.dangling-reference</
code>.</
td></
tr>
887 +<
tr><
td>Doctor never mutates or escapes/follows links.</
td><
td>Only read/stat/readdir APIs, <
code>Dirent.isFile/isDirectory</
code>, and before/after content/mode/mtime snapshot.</
td></
tr>
888 +<
tr><
td>Exit status is automation-safe.</
td><
td>Exact child-process tests: valid 0, findings 1.</
td></
tr>
889 +<
tr><
td><
code>/system-doctor</
code> is thin; workflow lives in <
code>system-doctor</
code>.</
td><
td>Prompt/skill contract test.</
td></
tr>
890 +<
tr><
td><
code>system-documents</
code> is one authoring authority.</
td><
td>Exact HTML, metadata, graph, mockup, validation, and consent contract assertions.</
td></
tr>
891 +<
tr><
td>Root and extension packages export prompts and skills discoverably.</
td><
td>Real <
code>DefaultPackageManager.resolveExtensionSources</
code> test and exact static assertions.</
td></
tr>
892 +<
tr><
td>Existing runtime behavior remains intact and CI-green.</
td><
td>Extension suite, real harness, typecheck, checks, full <
code>mise run ci</
code>.</
td></
tr>
896 +<
h2>Plan self-review</
h2>
898 +<
li>Coverage: every Phase 3 roadmap bullet maps to Tasks 1–4; Task 5 proves independent green status.</
li>
899 +<
li>Design alignment: doctor reports every specified class available in Phase 2, keeps test-reference absence advisory, never executes/fetches/writes, and shares the kernel.</
li>
900 +<
li>Scope: initialization, injection, write gates, browser opener implementation, and later lifecycle prompts are absent.</
li>
901 +<
li>Consistency: diagnostic/result names, CLI lines, manifest paths, skill-relative script path, and tests match exactly across tasks.</
li>
902 +<
li>Buildability: each behavior has RED, exact implementation, GREEN, and focused checkpoint commands.</
li>
903 +<
li>Placeholder scan: every code/file mutation is literal; no deferred implementation instruction remains.</
li>
904 +<
li>Phase health: doctor is useful from its script and prompt while <
code>index.ts</
code> and all prior behavior remain unchanged.</
li>
906 +<
div class=
"contract stop"><
strong>Stop here.</
strong> This plan intentionally stops at Phase 3: Doctor vertical slice. Phase 4 owns initialization and all writes; Phase 5 owns runtime injection and gates; later phases own browser opening and lifecycle migrations.</
div>
907 +<
p><
strong>Execution handoff:</
strong> execute with <
code>/skill:executing-plans</
code>.</
p>