repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by bugabinga

docs(the-system): plan project doctor

b5ba6b31b9779706eb9c120b9770780d08f3a023

Oliver Jan Krylow <oliver@bugabinga.net> ·

unsigned

Browse filesCompare with HEAD

Changed files (1)

docs/super/plans/2026-07-11-the-system-phase-3-doctor.html

Added
new file mode 100644
1 +<!doctype html>
2 +<html lang="en">
3 +<head>
4 +<meta charset="utf-8">
5 +<meta name="viewport" content="width=device-width, initial-scale=1">
6 +<title>The System Phase 3 doctor implementation plan</title>
7 +<style>
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; } }
31 +</style>
32 +</head>
33 +<body>
34 +<article>
35 +<header>
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>
45 +</header>
46 +<main>
47 +<section>
48 +<h2>Scope lock</h2>
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>
50 +<ul>
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>
55 +</ul>
56 +</section>
57 +<section>
58 +<h2>File map</h2>
59 +<table>
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>
71 +</table>
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>
73 +</section>
74 +<section>
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>
77 +<ol class="checks">
78 +<li><strong>☐ Step 1: write the failing fixture tests.</strong> Create <code>extensions/the-system/__tests__/doctor.test.ts</code> exactly:</li>
79 +</ol>
80 +<pre><code>import assert from "node:assert/strict";
81 +import {
82 + mkdirSync,
83 + mkdtempSync,
84 + readFileSync,
85 + readdirSync,
86 + rmSync,
87 + statSync,
88 + writeFileSync,
89 +} from "node:fs";
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 = () =&gt; {
97 + const root = mkdtempSync(path.join(tmpdir(), "the-system-doctor-"));
98 + roots.push(root);
99 + mkdirSync(path.join(root, ".git"));
100 + return root;
102 +const write = (root: string, relative: string, content = "") =&gt; {
103 + const target = path.join(root, relative);
104 + mkdirSync(path.dirname(target), { recursive: true });
105 + writeFileSync(target, content, "utf8");
107 +const metadata = (value: object) =&gt;
108 + `&lt;script type="application/json" id="system-meta"&gt;${JSON.stringify(value)}&lt;/script&gt;`;
109 +const html = (meta: object, body = "&lt;p&gt;contract&lt;/p&gt;") =&gt; `&lt;!doctype html&gt;
110 +&lt;html lang="en"&gt;
111 +&lt;head&gt;
112 +&lt;meta charset="utf-8"&gt;
113 +&lt;meta name="viewport" content="width=device-width, initial-scale=1"&gt;
114 +&lt;title&gt;Fixture&lt;/title&gt;
115 +&lt;link rel="stylesheet" href="../system.css"&gt;
116 +${metadata(meta)}
117 +&lt;/head&gt;
118 +&lt;body&gt;&lt;header&gt;&lt;h1&gt;Fixture&lt;/h1&gt;&lt;/header&gt;&lt;main&gt;&lt;section&gt;${body}&lt;/section&gt;&lt;/main&gt;&lt;/body&gt;
119 +&lt;/html&gt;`;
120 +const validSystem = (root: string) =&gt; {
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`);
125 + write(
126 + root,
127 + ".system/config.json",
128 + '{"prefix":"PX","schemaVersion":1,"styleVersion":1}',
129 + );
130 + write(root, ".system/system.css", "/* The System styleVersion: 1 */\n");
133 +afterEach(() =&gt; {
134 + for (const root of roots.splice(0))
135 + rmSync(root, { recursive: true, force: true });
136 +});
138 +describe("system doctor", () =&gt; {
139 + it("reports every required path in stable path/code order", () =&gt; {
140 + const root = temporaryRoot();
141 + const result = runDoctor(path.join(root, "nested"));
143 + assert.equal(result.root, root);
144 + assert.equal(result.exitCode, 1);
145 + assert.deepEqual(
146 + result.diagnostics.map(({ code, path }) =&gt; `${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",
159 + ],
160 + );
161 + });
163 + it("combines machine-state, kernel, mockup, and test-reference findings", () =&gt; {
164 + const root = temporaryRoot();
165 + validSystem(root);
166 + write(
167 + root,
168 + ".system/config.json",
169 + '{"prefix":"PX","schemaVersion":2,"styleVersion":2}',
170 + );
171 + write(root, ".system/system.css", "/* The System styleVersion: 1 */\n");
172 + write(
173 + root,
174 + ".system/specs/PX-SPEC-001-contract.html",
175 + html({ id: "PX-SPEC-001", type: "spec" }),
176 + );
177 + write(
178 + root,
179 + ".system/plans/PX-PLAN-001-work.html",
180 + html({ id: "PX-PLAN-001", type: "plan", spec: "PX-SPEC-999" }),
181 + );
182 + write(
183 + root,
184 + ".system/specs/PX-SPEC-404-gone-mockup-empty.html",
185 + "&lt;!doctype html&gt;&lt;title&gt;asset&lt;/title&gt;",
186 + );
187 + write(
188 + root,
189 + "tests/contract.test.ts",
190 + "// SYSTEM-SPEC: PX-SPEC-001\n// SYSTEM-SPEC: PX-SPEC-999\n",
191 + );
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" },
198 + ]);
199 + assert.deepEqual(
200 + result.diagnostics.map(({ code, path }) =&gt; `${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",
208 + ],
209 + );
210 + assert.equal(result.exitCode, 1);
211 + });
213 + it("returns green for a complete system and ignores symlinks and non-HTML files", () =&gt; {
214 + const root = temporaryRoot();
215 + validSystem(root);
216 + write(
217 + root,
218 + ".system/specs/PX-SPEC-001-contract.html",
219 + html({ id: "PX-SPEC-001", type: "spec" }),
220 + );
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);
229 + });
230 +});</code></pre>
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>
234 +</ol>
235 +<pre><code>import {
236 + existsSync,
237 + readFileSync,
238 + readdirSync,
239 + statSync,
240 +} from "node:fs";
241 +import path from "node:path";
242 +import {
243 + type Diagnostic,
244 + discoverProjectRoot,
245 + indexDocuments,
246 + parseSystemConfig,
247 + SCHEMA_VERSION,
248 + STYLE_VERSION,
249 + SystemDocumentError,
250 + validateAuthoredHtml,
251 +} from "./documents.ts";
253 +export type TestReference = Readonly&lt;{ path: string; spec: string }&gt;;
254 +export type DoctorResult = Readonly&lt;{
255 + root: string;
256 + diagnostics: readonly Diagnostic[];
257 + references: readonly TestReference[];
258 + exitCode: 0 | 1;
259 +}&gt;;
261 +const SYSTEM_DIRECTORIES = [
262 + ".system",
263 + ".system/specs",
264 + ".system/roadmaps",
265 + ".system/plans",
266 + ".system/issues",
267 + ".system/research",
268 +] as const;
269 +const SYSTEM_FILES = [
270 + ".system/config.json",
271 + ".system/system.css",
272 + ".system/SYSTEM.md",
273 + ".system/MISSION.md",
274 + ".system/RULES.md",
275 +] as const;
276 +const DOCUMENT_DIRECTORIES = [
277 + "specs",
278 + "roadmaps",
279 + "plans",
280 + "issues",
281 + "research",
282 +] as const;
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 =&gt; ({
288 + code,
289 + path,
290 + message,
291 +});
292 +const compareDiagnostics = (left: Diagnostic, right: Diagnostic) =&gt;
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) =&gt;
297 + path.relative(root, target).split(path.sep).join("/");
298 +const isDirectory = (target: string) =&gt; {
299 + try {
300 + return statSync(target, { throwIfNoEntry: false })?.isDirectory() === true;
301 + } catch {
302 + return false;
305 +const isFile = (target: string) =&gt; {
306 + try {
307 + return statSync(target, { throwIfNoEntry: false })?.isFile() === true;
308 + } catch {
309 + return false;
313 +const collectDocumentSources = (root: string) =&gt; {
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" &amp;&amp; MOCKUP.test(entry.name)) {
323 + mockups.push(relative);
324 + continue;
326 + sources.push({
327 + path: relative,
328 + html: readFileSync(path.join(absoluteDirectory, entry.name), "utf8"),
329 + });
332 + return {
333 + sources: sources.sort((left, right) =&gt; left.path.localeCompare(right.path)),
334 + mockups: mockups.sort(),
335 + };
338 +const collectTestReferences = (root: string): TestReference[] =&gt; {
339 + const references: TestReference[] = [];
340 + const visited = new Set&lt;string&gt;();
341 + const scan = (directory: string) =&gt; {
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) =&gt; left.name.localeCompare(right.name),
347 + )) {
348 + if ([".git", ".jj", ".system", "node_modules"].includes(entry.name))
349 + continue;
350 + const target = path.join(resolved, entry.name);
351 + if (entry.isDirectory()) {
352 + scan(target);
353 + continue;
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] });
360 + };
361 + for (const directory of TEST_DIRECTORIES) scan(path.join(root, directory));
362 + return references.sort(
363 + (left, right) =&gt;
364 + left.path.localeCompare(right.path) || left.spec.localeCompare(right.spec),
365 + );
368 +export function runDoctor(cwd: string): DoctorResult {
369 + let root: string;
370 + try {
371 + root = discoverProjectRoot(cwd);
372 + } catch (error) {
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))
382 + diagnostics.push(
383 + diagnostic("filesystem.missing", relative, `Missing directory ${relative}`),
384 + );
386 + for (const relative of SYSTEM_FILES) {
387 + const target = path.join(root, relative);
388 + if (!isFile(target))
389 + diagnostics.push(
390 + diagnostic("filesystem.missing", relative, `Missing file ${relative}`),
391 + );
394 + let prefix: string | undefined;
395 + const configPath = path.join(root, ".system/config.json");
396 + if (isFile(configPath)) {
397 + try {
398 + const config = parseSystemConfig(readFileSync(configPath, "utf8"));
399 + prefix = config.prefix;
400 + if (config.schemaVersion !== SCHEMA_VERSION)
401 + diagnostics.push(
402 + diagnostic(
403 + "config.schema-outdated",
404 + ".system/config.json",
405 + `Schema version ${config.schemaVersion}; installed ${SCHEMA_VERSION}`,
406 + ),
407 + );
408 + if (config.styleVersion !== STYLE_VERSION)
409 + diagnostics.push(
410 + diagnostic(
411 + "config.style-outdated",
412 + ".system/config.json",
413 + `Style version ${config.styleVersion}; installed ${STYLE_VERSION}`,
414 + ),
415 + );
416 + } catch (error) {
417 + const value = error as SystemDocumentError;
418 + diagnostics.push(
419 + diagnostic(value.code, ".system/config.json", value.message),
420 + );
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];
428 + if (!version)
429 + diagnostics.push(
430 + diagnostic(
431 + "css.version",
432 + ".system/system.css",
433 + "Missing The System styleVersion marker",
434 + ),
435 + );
436 + else if (Number(version) !== STYLE_VERSION)
437 + diagnostics.push(
438 + diagnostic(
439 + "css.version-mismatch",
440 + ".system/system.css",
441 + `Stylesheet version ${version}; installed ${STYLE_VERSION}`,
442 + ),
443 + );
446 + const { sources, mockups } = collectDocumentSources(root);
447 + let specIds = new Set&lt;string&gt;();
448 + if (prefix) {
449 + const index = indexDocuments(sources, prefix);
450 + diagnostics.push(...index.diagnostics);
451 + specIds = new Set(
452 + index.documents
453 + .filter((document) =&gt; document.metadata.type === "spec")
454 + .map((document) =&gt; document.metadata.id),
455 + );
456 + } else {
457 + for (const source of sources)
458 + diagnostics.push(...validateAuthoredHtml(source.path, source.html));
461 + const sourcePaths = new Set(sources.map((source) =&gt; 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))
467 + diagnostics.push(
468 + diagnostic(
469 + "mockup.orphaned",
470 + mockup,
471 + `Mockup owner is missing: ${ownerPath}`,
472 + ),
473 + );
476 + const references = collectTestReferences(root);
477 + for (const reference of references)
478 + if (prefix &amp;&amp; !specIds.has(reference.spec))
479 + diagnostics.push(
480 + diagnostic(
481 + "test.dangling-reference",
482 + reference.path,
483 + `Test references missing ${reference.spec}`,
484 + ),
485 + );
487 + diagnostics.sort(compareDiagnostics);
488 + return {
489 + root,
490 + diagnostics,
491 + references,
492 + exitCode: diagnostics.length === 0 ? 0 : 1,
493 + };
494 +}</code></pre>
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 &amp;&amp; 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>
499 +</ol>
500 +</section>
501 +<section>
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>
504 +<ol class="checks">
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>
506 +</ol>
507 +<pre><code>const snapshot = (root: string) =&gt; {
508 + const entries: { path: string; content?: string; mode: number; mtimeMs: number }[] = [];
509 + const visit = (directory: string) =&gt; {
510 + for (const entry of readdirSync(directory, { withFileTypes: true }).sort(
511 + (left, right) =&gt; left.name.localeCompare(right.name),
512 + )) {
513 + const target = path.join(directory, entry.name);
514 + const stats = statSync(target);
515 + const record = {
516 + path: path.relative(root, target).split(path.sep).join("/"),
517 + mode: stats.mode,
518 + mtimeMs: stats.mtimeMs,
519 + };
520 + entries.push(
521 + entry.isFile()
522 + ? { ...record, content: readFileSync(target, "utf8") }
523 + : record,
524 + );
525 + if (entry.isDirectory()) visit(target);
527 + };
528 + visit(root);
529 + return entries;
530 +};</code></pre>
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", () =&gt; {
533 + const root = temporaryRoot();
534 + validSystem(root);
535 + write(
536 + root,
537 + ".system/specs/PX-SPEC-001-contract.html",
538 + html({ id: "PX-SPEC-001", type: "spec" }),
539 + );
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(
545 + process.execPath,
546 + ["--experimental-transform-types", script, root],
547 + { encoding: "utf8", env: { ...process.env, NODE_NO_WARNINGS: "1" } },
548 + );
550 + assert.equal(green.status, 0);
551 + assert.equal(
552 + green.stdout,
553 + `ROOT ${root}\nREF tests/contract.test.ts PX-SPEC-001\nOK The System is valid\n`,
554 + );
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(
561 + process.execPath,
562 + ["--experimental-transform-types", script, root],
563 + { encoding: "utf8", env: { ...process.env, NODE_NO_WARNINGS: "1" } },
564 + );
566 + assert.equal(red.status, 1);
567 + assert.equal(
568 + red.stdout,
569 + `ROOT ${root}\nREF tests/contract.test.ts PX-SPEC-001\nERROR css.version .system/system.css: Missing The System styleVersion marker\n`,
570 + );
571 + assert.equal(red.stderr, "");
572 + assert.deepEqual(snapshot(root), brokenBefore);
573 + });</code></pre>
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>
577 +</ol>
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 &amp;&amp; git commit -m "feat(the-system): expose doctor CLI"</code><br>Expected: one CLI/test commit.</li>
593 +</ol>
594 +</section>
595 +<section>
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>
598 +<ol class="checks">
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>
600 +</ol>
601 +<pre><code>const prompt = (name: string) =&gt;
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", () =&gt; {
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/);
616 + });
618 + it("makes system-documents the single authored-document authority", () =&gt; {
619 + const documents = skill("system-documents");
621 + for (const contract of [
622 + "single document-authoring authority",
623 + "../system.css",
624 + "system-meta",
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",
630 + ])
631 + assert.ok(documents.includes(contract), `missing document contract: ${contract}`);
632 + assert.doesNotMatch(documents, /initialize|SYSTEM\.md|MISSION\.md|RULES\.md/i);
633 + });</code></pre>
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>
637 +</ol>
638 +<pre><code>---
639 +name: system-doctor
640 +description: Diagnose a project's .system tree deterministically without changing files
641 +---
643 +# System Doctor
645 +Use this skill when a user asks to inspect, validate, or explain a project system.
647 +## Run
649 +1. Resolve `../../scripts/doctor.mjs` against this skill directory and use that absolute path.
650 +2. Run `node --no-warnings --experimental-transform-types &lt;absolute-doctor-path&gt; &lt;project-cwd&gt;`.
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.
656 +## Explain
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.
664 +</code></pre>
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>
667 +</ol>
668 +<pre><code>---
669 +name: system-documents
670 +description: Apply The System HTML, metadata, ID, reference, mockup, validation, and browser-review contracts
671 +---
673 +# System Documents
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.
678 +## Preconditions
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.
685 +## IDs and paths
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.
692 +## HTML source
694 +Every authored document is complete, formatted, directly editable HTML with:
696 +- `&lt;!doctype html&gt;`, `&lt;html lang="en"&gt;`, UTF-8 charset, viewport, and a nonempty title;
697 +- exactly one `&lt;link rel="stylesheet" href="../system.css"&gt;`;
698 +- header followed by main containing one section;
699 +- semantic headings, paragraphs, lists, tables, asides, figures, and details where appropriate;
700 +- one readable `&lt;script type="application/json" id="system-meta"&gt;` 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: &lt;SPEC-ID&gt;` 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.
738 +</code></pre>
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>
741 +</ol>
742 +<pre><code>---
743 +description: Diagnose The System without mutation
744 +---
745 +Use the system-doctor skill to run deterministic validation for the current project and explain every reported line without changing files.
746 +</code></pre>
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 &amp;&amp; git commit -m "feat(the-system): add doctor and document skills"</code><br>Expected: one resource-contract commit.</li>
751 +</ol>
752 +</section>
753 +<section>
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>
756 +<ol class="checks">
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>
758 +</ol>
759 +<pre><code>import { mkdtempSync, readFileSync, rmSync } from "node:fs";
760 +import { tmpdir } from "node:os";
761 +import {
762 + DefaultPackageManager,
763 + SettingsManager,
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 () =&gt; {
767 + const sandbox = mkdtempSync(path.join(tmpdir(), "the-system-resources-"));
768 + try {
769 + const settings = SettingsManager.create(
770 + sandbox,
771 + path.join(sandbox, ".agent"),
772 + );
773 + const manager = new DefaultPackageManager({
774 + cwd: sandbox,
775 + agentDir: path.join(sandbox, ".agent"),
776 + settingsManager: settings,
777 + });
778 + const repository = await manager.resolveExtensionSources(
779 + [path.resolve(root, "../../..")],
780 + { temporary: true },
781 + );
782 + const extension = await manager.resolveExtensionSources([root], {
783 + temporary: true,
784 + });
785 + const relativeResources = (
786 + base: string,
787 + resources: readonly { path: string }[],
788 + ) =&gt;
789 + resources
790 + .map((resource) =&gt;
791 + path.relative(base, resource.path).split(path.sep).join("/"),
793 + .sort();
795 + assert.deepEqual(relativeResources(root, extension.prompts), [
796 + "prompts/system-doctor.md",
797 + ]);
798 + assert.ok(
799 + relativeResources(root, extension.skills).includes(
800 + "skills/system-doctor/SKILL.md",
801 + ),
802 + );
803 + assert.ok(
804 + relativeResources(path.resolve(root, "../../.."), repository.prompts).includes(
805 + "extensions/the-system/prompts/system-doctor.md",
806 + ),
807 + );
808 + } finally {
809 + rmSync(sandbox, { recursive: true, force: true });
811 + });</code></pre>
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>
815 +</ol>
816 +<pre><code>"pi": {
817 + "extensions": [
818 + "index.ts"
819 + ],
820 + "skills": [
821 + "skills"
822 + ],
823 + "prompts": [
824 + "prompts"
826 +}</code></pre>
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>
829 +</ol>
830 +<pre><code>,
831 +"prompts": [
832 + "extensions/the-system/prompts"
833 +]</code></pre>
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>
836 +</ol>
837 +<pre><code>assert.deepEqual(rootPkg().pi, {
838 + extensions: ["extensions/*/index.ts"],
839 + skills: [
840 + "extensions/the-system/skills",
841 + "extensions/ultra/skills",
842 + "extensions/lazy/skills",
843 + ],
844 + prompts: ["extensions/the-system/prompts"],
845 +});
846 +assert.deepEqual(
847 + JSON.parse(
848 + readFileSync(join(ROOT, "extensions/the-system/package.json"), "utf8"),
849 + ).pi,
851 + extensions: ["index.ts"],
852 + skills: ["skills"],
853 + prompts: ["prompts"],
854 + },
855 +);</code></pre>
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 &amp;&amp; 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 &amp;&amp; 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>
861 +</ol>
862 +</section>
863 +<section>
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>
866 +<ol class="checks">
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 &amp;&amp; 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 &amp;&amp; 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>
876 +</ol>
877 +</section>
878 +<section>
879 +<h2>Acceptance matrix</h2>
880 +<table>
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>
893 +</table>
894 +</section>
895 +<section>
896 +<h2>Plan self-review</h2>
897 +<ul>
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>
905 +</ul>
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>
908 +</section>
909 +</main>
910 +</article>
911 +</body>
912 +</html>