repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by bugabinga

docs(the-system): plan guided initialization

35cebc22c5f4a965d93f0f80f5338b12da02c5d4

Oliver Jan Krylow <oliver@bugabinga.net> ·

unsigned

Browse filesCompare with HEAD

Changed files (1)

docs/super/plans/2026-07-13-the-system-phase-4-guided-init.html

Added
new file mode 100644
1 +<!doctype html>
2 +<html lang="en">
3 +<head>
4 +<meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">
5 +<title>The System Phase 4 guided initialization implementation plan</title>
6 +<style>
7 +:root{color-scheme:light dark;--fg:#121212;--bg:#ededed;--panel:#dbdbdb;--accent:#ae2eae;--ui:#922792;--focus:#184e5b;--error:#bd172e}@media(prefers-color-scheme:dark){:root{--fg:#ededed;--bg:#121212;--panel:#242424;--accent:#d151d1;--ui:#d86dd8;--focus:#7ba1aa;--error:#ec6376}}*{box-sizing:border-box}body{margin:0;padding:1rem;background:var(--bg);color:var(--fg);font:14px/1.55 ui-monospace,SFMono-Regular,Consolas,monospace}article{width:min(100%,1100px);margin:auto;border:3px solid var(--fg);box-shadow:10px 10px 0 var(--ui)}header,section{padding:clamp(1rem,3vw,1.5rem);border-bottom:2px solid var(--fg)}header{background:var(--panel);border-bottom-width:3px}h1{margin:.2rem 0;font:900 clamp(1.8rem,6vw,3.7rem)/.92 system-ui;text-transform:uppercase}h2{margin:0 0 1rem;color:var(--accent);font:900 1rem/1 system-ui;letter-spacing:.12em;text-transform:uppercase}h3{font-size:.92rem;text-transform:uppercase}p,li{max-width:96ch}li{margin:.4rem 0}a{color:var(--focus);font-weight:900}code{background:var(--panel);padding:.1rem .3rem;overflow-wrap:anywhere}pre{overflow:auto;padding:1rem;border:2px solid var(--fg);border-left:8px solid var(--ui);background:var(--panel);font-size:.82rem}pre code{padding:0;background:transparent;overflow-wrap:normal}table{width:100%;border-collapse:collapse}th,td{padding:.65rem;border:2px solid var(--fg);text-align:left;vertical-align:top}th{background:var(--panel)}.contract{padding:.9rem;border:3px solid var(--fg);border-left:9px solid var(--accent);background:var(--panel)}.stop{border-left-color:var(--error)}@media(max-width:620px){body{padding:.5rem}article{box-shadow:5px 5px 0 var(--ui)}table,tbody,tr,th,td{display:block;width:100%}}
8 +</style>
9 +</head>
10 +<body><article>
11 +<header>
12 +<p><strong>Implementation plan · 2026-07-13</strong></p>
13 +<h1>Phase 4 · Guided initialization</h1>
14 +<p><strong>For agentic workers:</strong> REQUIRED SUB-SKILL: use <code>/skill:executing-plans</code> task-by-task; checkboxes track execution.</p>
15 +<p><strong>Goal:</strong> make <code>/system-init [PROJECT-PREFIX]</code> create or upgrade a doctor-valid project system through explicit human decisions.</p>
16 +<p><strong>Architecture:</strong> human truth stays in <code>the-system-init</code>, which inspects context, asks one question at a time, and obtains separate core approvals. A narrow Node helper reuses the Phase 2 root/config kernel for fixed machine state, preserves cores, separates inspection from upgrades, and leaves final validity to the Phase 3 doctor.</p>
17 +<p><strong>Tech stack:</strong> TypeScript, Node 26 standard library/native type stripping, Vitest, Pi skills/prompts, bundled Nugu CSS, Biome/dprint, mise monorepo tasks.</p>
18 +<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>
19 +<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>
20 +<p><strong>Phase:</strong> Phase 4: Guided initialization.</p>
21 +</header><main>
22 +<section>
23 +<h2>Boundary and file map</h2>
24 +<div class="contract"><strong>Deliver only:</strong> on-demand init prompt/skill, deterministic machine-state helper, approval-bound core creation/upgrades, resource discovery, and doctor validation.</div>
25 +<ul>
26 +<li>Reuse current <code>discoverProjectRoot</code>, <code>resolveGovernedPath</code>, <code>parseSystemConfig</code>, version constants, bundled CSS, and doctor script.</li>
27 +<li>No <code>system.ts</code>, runtime registration, startup notice, injection, write gate, browser opener, lifecycle migration, or normal-turn behavior.</li>
28 +<li>The helper never writes core Markdown. Existing cores remain byte-for-byte unchanged; each missing core is written by the skill only after its displayed draft receives named approval.</li>
29 +<li>Missing machine assets may follow prefix approval. Existing config/CSS changes require an inspect report and separate approval.</li>
30 +<li>The prompt argument is a proposal, never approval. Malformed config, prefix conflict, newer project version, wrong path kind, and machine-path symlinks fail.</li>
31 +<li>Use root tasks as <code>mise //:task</code> and extension tasks as <code>mise //extensions/the-system:task</code>.</li>
32 +</ul>
33 +<table>
34 +<tr><th>Path</th><th>Action and responsibility</th></tr>
35 +<tr><td><code>extensions/the-system/init.ts</code></td><td>Create: inspect/apply directories, strict config, and exact bundled CSS without core writes.</td></tr>
36 +<tr><td><code>extensions/the-system/scripts/init.mjs</code></td><td>Create: stable <code>inspect|apply|upgrade</code> CLI.</td></tr>
37 +<tr><td><code>extensions/the-system/__tests__/init.test.ts</code></td><td>Create: root, copy, doctor, rerun, core, upgrade, prefix, version, and path fixtures.</td></tr>
38 +<tr><td><code>extensions/the-system/skills/the-system-init/SKILL.md</code></td><td>Create: trust warning, inspection, interview, drafting, approvals, reruns, doctor.</td></tr>
39 +<tr><td><code>extensions/the-system/prompts/system-init.md</code></td><td>Create: thin optional-prefix delegation.</td></tr>
40 +<tr><td><code>extensions/the-system/__tests__/workflow-skills.test.ts</code></td><td>Modify: contracts and real root/extension resource discovery.</td></tr>
41 +</table>
42 +<p>Do not modify kernel/doctor/CSS files, manifests, static checks, runtime entrypoints, mise files, TypeScript config, or lockfile.</p>
43 +</section>
44 +<section>
45 +<h2>Task 1 · Machine-state vertical slice</h2>
46 +<p><strong>Files:</strong> create <code>init.test.ts</code>, <code>init.ts</code>, and <code>scripts/init.mjs</code>.</p>
47 +<ol>
48 +<li><strong>☐ Write RED tests.</strong> Create <code>extensions/the-system/__tests__/init.test.ts</code> exactly:</li>
49 +</ol>
50 +<pre><code>import assert from "node:assert/strict";
51 +import { spawnSync } from "node:child_process";
52 +import { lstatSync, mkdirSync, mkdtempSync, readFileSync, rmSync, symlinkSync, writeFileSync } from "node:fs";
53 +import { tmpdir } from "node:os";
54 +import path from "node:path";
55 +import { afterEach, describe, it } from "vitest";
56 +import { runDoctor } from "../doctor.ts";
57 +import { SystemDocumentError } from "../documents.ts";
58 +import { applyInitialization, DEFAULT_MACHINE_ASSETS, inspectInitialization, type MachineAssets } from "../init.ts";
60 +const roots: string[] = [];
61 +const root = () =&gt; {
62 + const value = mkdtempSync(path.join(tmpdir(), "the-system-init-"));
63 + roots.push(value);
64 + mkdirSync(path.join(value, ".git"));
65 + return value;
66 +};
67 +const write = (root: string, relative: string, content: string) =&gt; {
68 + const target = path.join(root, relative);
69 + mkdirSync(path.dirname(target), { recursive: true });
70 + writeFileSync(target, content, "utf8");
71 +};
72 +const cores = (root: string) =&gt; {
73 + write(root, ".system/SYSTEM.md", "# System\n\nApproved topology.\n");
74 + write(root, ".system/MISSION.md", "# Mission\n\nApproved purpose.\n");
75 + write(root, ".system/RULES.md", "# Rules\n\nApproved constraints.\n");
76 +};
77 +const future: MachineAssets = {
78 + schemaVersion: 2,
79 + styleVersion: 2,
80 + css: "/* The System styleVersion: 2 */\n.future {}\n",
81 +};
82 +afterEach(() =&gt; {
83 + for (const value of roots.splice(0)) rmSync(value, { recursive: true, force: true });
84 +});
86 +describe("guided initialization machine state", () =&gt; {
87 + it("copies current machine assets to the discovered root", () =&gt; {
88 + const project = root();
89 + const cwd = path.join(project, "packages", "app");
90 + mkdirSync(cwd, { recursive: true });
91 + const script = path.resolve(import.meta.dirname, "../scripts/init.mjs");
92 + const child = spawnSync(process.execPath, ["--experimental-strip-types", script, "apply", cwd, "PX"], {
93 + encoding: "utf8",
94 + env: { ...process.env, NODE_NO_WARNINGS: "1" },
95 + });
96 + assert.equal(child.status, 0);
97 + assert.equal(child.stderr, "");
98 + assert.equal(
99 + child.stdout,
101 + `ROOT ${project}`, "PREFIX PX", "WROTE .system", "WROTE .system/specs",
102 + "WROTE .system/roadmaps", "WROTE .system/plans", "WROTE .system/issues",
103 + "WROTE .system/research", "WROTE .system/config.json", "WROTE .system/system.css",
104 + "OK machine state applied", "",
105 + ].join("\n"),
106 + );
107 + assert.equal(
108 + readFileSync(path.join(project, ".system/config.json"), "utf8"),
109 + '{\n\t"prefix": "PX",\n\t"schemaVersion": 1,\n\t"styleVersion": 1\n}\n',
110 + );
111 + assert.equal(readFileSync(path.join(project, ".system/system.css"), "utf8"), DEFAULT_MACHINE_ASSETS.css);
112 + assert.deepEqual(inspectInitialization(project, "PX").cores.map((item) =&gt; item.state), ["missing", "missing", "missing"]);
113 + });
115 + it("becomes doctor-green and preserves all bytes and mtimes on rerun", () =&gt; {
116 + const project = root();
117 + applyInitialization(project, "PX");
118 + cores(project);
119 + const paths = ["config.json", "system.css", "SYSTEM.md", "MISSION.md", "RULES.md"];
120 + const before = new Map(paths.map((name) =&gt; {
121 + const target = path.join(project, ".system", name);
122 + return [name, [readFileSync(target, "utf8"), lstatSync(target).mtimeMs] as const];
123 + }));
124 + const repeated = applyInitialization(project, "PX");
125 + assert.deepEqual(repeated, { root: project, prefix: "PX", changed: [], pending: [] });
126 + assert.deepEqual(inspectInitialization(project, "PX").cores.map((item) =&gt; item.state), ["preserve", "preserve", "preserve"]);
127 + for (const name of paths) {
128 + const target = path.join(project, ".system", name);
129 + assert.deepEqual([readFileSync(target, "utf8"), lstatSync(target).mtimeMs], before.get(name));
131 + assert.equal(runDoctor(project).exitCode, 0);
132 + });
134 + it("reports machine upgrades and applies them only with approval", () =&gt; {
135 + const project = root();
136 + applyInitialization(project, "PX");
137 + cores(project);
138 + const oldConfig = readFileSync(path.join(project, ".system/config.json"), "utf8");
139 + const oldCss = readFileSync(path.join(project, ".system/system.css"), "utf8");
140 + const upgrades = [
141 + ".system/config.json schemaVersion 1 -&gt; 2, styleVersion 1 -&gt; 2",
142 + ".system/system.css bundled styleVersion 2",
143 + ];
144 + assert.deepEqual(inspectInitialization(project, undefined, future).upgrades, upgrades);
145 + assert.deepEqual(applyInitialization(project, undefined, false, future).pending, upgrades);
146 + assert.equal(readFileSync(path.join(project, ".system/config.json"), "utf8"), oldConfig);
147 + assert.equal(readFileSync(path.join(project, ".system/system.css"), "utf8"), oldCss);
148 + assert.deepEqual(applyInitialization(project, undefined, true, future).changed, [
149 + ".system/config.json", ".system/system.css",
150 + ]);
151 + assert.equal(readFileSync(path.join(project, ".system/system.css"), "utf8"), future.css);
152 + for (const name of ["SYSTEM.md", "MISSION.md", "RULES.md"])
153 + assert.match(readFileSync(path.join(project, ".system", name), "utf8"), /Approved/);
154 + });
156 + it("fails on missing/invalid/conflicting prefixes, newer versions, and symlinks", () =&gt; {
157 + const project = root();
158 + assert.throws(() =&gt; applyInitialization(project), (error: unknown) =&gt;
159 + error instanceof SystemDocumentError &amp;&amp; error.code === "init.prefix-required");
160 + assert.throws(() =&gt; applyInitialization(project, "x"), SystemDocumentError);
161 + applyInitialization(project, "PX");
162 + assert.throws(() =&gt; inspectInitialization(project, "AB"), (error: unknown) =&gt;
163 + error instanceof SystemDocumentError &amp;&amp; error.code === "init.prefix-conflict");
164 + write(project, ".system/config.json", '{"prefix":"PX","schemaVersion":3,"styleVersion":1}');
165 + assert.throws(() =&gt; inspectInitialization(project, undefined, future), (error: unknown) =&gt;
166 + error instanceof SystemDocumentError &amp;&amp; error.code === "init.version-newer");
168 + const linked = root();
169 + const outside = mkdtempSync(path.join(tmpdir(), "the-system-init-outside-"));
170 + roots.push(outside);
171 + symlinkSync(outside, path.join(linked, ".system"), "dir");
172 + assert.throws(() =&gt; inspectInitialization(linked, "PX"), (error: unknown) =&gt;
173 + error instanceof SystemDocumentError &amp;&amp; error.code === "init.unsafe-path");
174 + });
175 +});</code></pre>
176 +<ol start="2">
177 +<li><strong>☐ Run RED.</strong><br>Run: <code>mise //:test -- extensions/the-system/__tests__/init.test.ts</code><br>Expected: FAIL because init module/script are absent.</li>
178 +<li><strong>☐ Implement the minimal module.</strong> Create <code>extensions/the-system/init.ts</code> exactly:</li>
179 +</ol>
180 +<pre><code>import { lstatSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
181 +import path from "node:path";
182 +import {
183 + discoverProjectRoot, parseSystemConfig, resolveGovernedPath,
184 + SCHEMA_VERSION, STYLE_VERSION, SystemDocumentError,
185 +} from "./documents.ts";
187 +export type MachineAssets = Readonly&lt;{ schemaVersion: number; styleVersion: number; css: string }&gt;;
188 +export type InitializationInspection = Readonly&lt;{
189 + root: string;
190 + prefix?: string;
191 + cores: readonly Readonly&lt;{ path: string; state: "missing" | "preserve" }&gt;[];
192 + creates: readonly string[];
193 + upgrades: readonly string[];
194 +}&gt;;
195 +export type InitializationResult = Readonly&lt;{
196 + root: string; prefix: string; changed: readonly string[]; pending: readonly string[];
197 +}&gt;;
198 +const DIRECTORIES = [
199 + ".system", ".system/specs", ".system/roadmaps", ".system/plans", ".system/issues", ".system/research",
200 +] as const;
201 +const CORES = [".system/SYSTEM.md", ".system/MISSION.md", ".system/RULES.md"] as const;
202 +const CONFIG = ".system/config.json";
203 +const CSS = ".system/system.css";
204 +export const DEFAULT_MACHINE_ASSETS: MachineAssets = Object.freeze({
205 + schemaVersion: SCHEMA_VERSION,
206 + styleVersion: STYLE_VERSION,
207 + css: readFileSync(path.join(import.meta.dirname, "assets/system.css"), "utf8"),
208 +});
209 +const target = (root: string, relative: string) =&gt; resolveGovernedPath(root, relative);
210 +const kind = (file: string) =&gt; {
211 + const stats = lstatSync(file, { throwIfNoEntry: false });
212 + if (!stats) return "missing" as const;
213 + if (stats.isSymbolicLink()) return "link" as const;
214 + if (stats.isDirectory()) return "directory" as const;
215 + if (stats.isFile()) return "file" as const;
216 + return "other" as const;
218 +const requireKind = (root: string, relative: string, expected: "directory" | "file") =&gt; {
219 + const actual = kind(target(root, relative));
220 + if (actual !== "missing" &amp;&amp; actual !== expected)
221 + throw new SystemDocumentError("init.unsafe-path", `${relative} must be a regular ${expected}; found ${actual}`);
222 + return actual;
224 +const validatePrefix = (prefix: string, assets: MachineAssets) =&gt; {
225 + parseSystemConfig(JSON.stringify({ prefix, schemaVersion: assets.schemaVersion, styleVersion: assets.styleVersion }));
226 + return prefix;
228 +const configSource = (prefix: string, assets: MachineAssets) =&gt;
229 + `${JSON.stringify({ prefix, schemaVersion: assets.schemaVersion, styleVersion: assets.styleVersion }, null, "\t")}\n`;
231 +export function inspectInitialization(
232 + cwd: string,
233 + requestedPrefix?: string,
234 + assets: MachineAssets = DEFAULT_MACHINE_ASSETS,
235 +): InitializationInspection {
236 + const root = discoverProjectRoot(cwd);
237 + for (const relative of DIRECTORIES) requireKind(root, relative, "directory");
238 + const configKind = requireKind(root, CONFIG, "file");
239 + const cssKind = requireKind(root, CSS, "file");
240 + const requested = requestedPrefix ? validatePrefix(requestedPrefix, assets) : undefined;
241 + const config = configKind === "file"
242 + ? parseSystemConfig(readFileSync(target(root, CONFIG), "utf8"))
243 + : undefined;
244 + if (config &amp;&amp; requested &amp;&amp; config.prefix !== requested)
245 + throw new SystemDocumentError("init.prefix-conflict", `Existing prefix ${config.prefix} does not match requested ${requested}`);
246 + if (config &amp;&amp; (config.schemaVersion &gt; assets.schemaVersion || config.styleVersion &gt; assets.styleVersion))
247 + throw new SystemDocumentError(
248 + "init.version-newer",
249 + `Project versions schema ${config.schemaVersion}, style ${config.styleVersion} are newer than installed schema ${assets.schemaVersion}, style ${assets.styleVersion}`,
250 + );
251 + const creates: string[] = [];
252 + for (const relative of DIRECTORIES)
253 + if (kind(target(root, relative)) === "missing") creates.push(relative);
254 + if (configKind === "missing") creates.push(CONFIG);
255 + if (cssKind === "missing") creates.push(CSS);
256 + const upgrades: string[] = [];
257 + if (config &amp;&amp; (config.schemaVersion !== assets.schemaVersion || config.styleVersion !== assets.styleVersion))
258 + upgrades.push(`${CONFIG} schemaVersion ${config.schemaVersion} -&gt; ${assets.schemaVersion}, styleVersion ${config.styleVersion} -&gt; ${assets.styleVersion}`);
259 + if (cssKind === "file" &amp;&amp; readFileSync(target(root, CSS), "utf8") !== assets.css)
260 + upgrades.push(`${CSS} bundled styleVersion ${assets.styleVersion}`);
261 + return {
262 + root,
263 + prefix: config?.prefix ?? requested,
264 + cores: CORES.map((relative) =&gt; ({
265 + path: relative,
266 + state: kind(target(root, relative)) === "missing" ? "missing" : "preserve",
267 + })),
268 + creates,
269 + upgrades,
270 + };
273 +export function applyInitialization(
274 + cwd: string,
275 + requestedPrefix?: string,
276 + approveUpgrades = false,
277 + assets: MachineAssets = DEFAULT_MACHINE_ASSETS,
278 +): InitializationResult {
279 + const inspection = inspectInitialization(cwd, requestedPrefix, assets);
280 + if (!inspection.prefix)
281 + throw new SystemDocumentError("init.prefix-required", "An approved project prefix is required before initialization");
282 + const changed: string[] = [];
283 + for (const relative of DIRECTORIES) {
284 + if (kind(target(inspection.root, relative)) !== "missing") continue;
285 + mkdirSync(target(inspection.root, relative));
286 + changed.push(relative);
288 + const configUpgrade = inspection.upgrades.some((item) =&gt; item.startsWith(`${CONFIG} `));
289 + if (kind(target(inspection.root, CONFIG)) === "missing" || (approveUpgrades &amp;&amp; configUpgrade)) {
290 + writeFileSync(target(inspection.root, CONFIG), configSource(inspection.prefix, assets),
291 + kind(target(inspection.root, CONFIG)) === "missing" ? { encoding: "utf8", flag: "wx" } : "utf8");
292 + changed.push(CONFIG);
294 + const cssUpgrade = inspection.upgrades.some((item) =&gt; item.startsWith(`${CSS} `));
295 + if (kind(target(inspection.root, CSS)) === "missing" || (approveUpgrades &amp;&amp; cssUpgrade)) {
296 + writeFileSync(target(inspection.root, CSS), assets.css,
297 + kind(target(inspection.root, CSS)) === "missing" ? { encoding: "utf8", flag: "wx" } : "utf8");
298 + changed.push(CSS);
300 + return {
301 + root: inspection.root,
302 + prefix: inspection.prefix,
303 + changed,
304 + pending: approveUpgrades ? [] : inspection.upgrades,
305 + };
306 +}</code></pre>
307 +<ol start="4">
308 +<li><strong>☐ Add the thin CLI.</strong> Create <code>extensions/the-system/scripts/init.mjs</code> exactly:</li>
309 +</ol>
310 +<pre><code>#!/usr/bin/env node
311 +import { applyInitialization, inspectInitialization } from "../init.ts";
313 +const [command = "inspect", cwd = process.cwd(), rawPrefix] = process.argv.slice(2);
314 +const prefix = rawPrefix || undefined;
315 +try {
316 + if (command === "inspect") {
317 + const result = inspectInitialization(cwd, prefix);
318 + console.log(`ROOT ${result.root}`);
319 + console.log(`PREFIX ${result.prefix ?? "required"}`);
320 + for (const core of result.cores) console.log(`CORE ${core.state} ${core.path}`);
321 + for (const item of result.creates) console.log(`CREATE ${item}`);
322 + for (const item of result.upgrades) console.log(`UPGRADE ${item}`);
323 + if (result.creates.length === 0 &amp;&amp; result.upgrades.length === 0) console.log("OK machine state current");
324 + } else if (command === "apply" || command === "upgrade") {
325 + const result = applyInitialization(cwd, prefix, command === "upgrade");
326 + console.log(`ROOT ${result.root}`);
327 + console.log(`PREFIX ${result.prefix}`);
328 + for (const item of result.changed) console.log(`WROTE ${item}`);
329 + for (const item of result.pending) console.log(`PENDING ${item}`);
330 + if (result.pending.length === 0) console.log("OK machine state applied");
331 + } else throw new Error(`Unknown command ${command}; expected inspect, apply, or upgrade`);
332 +} catch (error) {
333 + const value = error instanceof Error ? error : new Error(String(error));
334 + const code = "code" in value &amp;&amp; typeof value.code === "string" ? value.code : "init.failed";
335 + console.error(`ERROR ${code}: ${value.message}`);
336 + process.exitCode = 1;
337 +}</code></pre>
338 +<ol start="5">
339 +<li><strong>☐ Run GREEN.</strong><br>Run: <code>mise //:test -- extensions/the-system/__tests__/init.test.ts</code><br>Expected: four tests PASS.</li>
340 +<li><strong>☐ Run Phase 2/3 regressions.</strong><br>Run: <code>mise //:test -- extensions/the-system/__tests__/documents.test.ts extensions/the-system/__tests__/doctor.test.ts extensions/the-system/__tests__/init.test.ts</code><br>Expected: PASS.</li>
341 +<li><strong>☐ Checkpoint.</strong><br>Run: <code>git add extensions/the-system/init.ts extensions/the-system/scripts/init.mjs extensions/the-system/__tests__/init.test.ts &amp;&amp; git commit -m "feat(the-system): add guided init machine state"</code><br>Expected: helper/CLI/fixture commit only.</li>
342 +</ol>
343 +</section>
344 +<section>
345 +<h2>Task 2 · Guided workflow and discoverable prompt</h2>
346 +<p><strong>Files:</strong> modify <code>workflow-skills.test.ts</code>; create the init skill/prompt. Update discovery before GREEN because Phase 3 pins the exact prompt list.</p>
347 +<ol>
348 +<li><strong>☐ Add RED contract tests.</strong> Insert before the doctor test in <code>extensions/the-system/__tests__/workflow-skills.test.ts</code>:</li>
349 +</ol>
350 +<pre><code> it("keeps system-init prompt thin and its argument unapproved", () =&gt; {
351 + const template = prompt("system-init");
352 + assert.match(template, /^---\ndescription: Initialize or upgrade The System through guided approval\nargument-hint: "\[PROJECT-PREFIX\]"\n---/);
353 + assert.match(template, /the-system-init skill/);
354 + assert.match(template, /\$ARGUMENTS/);
355 + assert.match(template, /proposal, not approval/);
356 + assert.doesNotMatch(template, /config\.json|system\.css|SYSTEM\.md|MISSION\.md|RULES\.md|mkdir|writeFile/);
357 + });
359 + it("defines root-aware approval-bound core-preserving initialization", () =&gt; {
360 + const init = skill("the-system-init");
361 + for (const contract of [
362 + "privileged instructions", "README", "agent instructions", "build files",
363 + "one focused question at a time", "purpose", "audience", "non-goals",
364 + "engineering constraints", "security", "data", "tests", "release expectations",
365 + "[A-Z][A-Z0-9]{1,7}", "scripts/init.mjs inspect", "scripts/init.mjs apply",
366 + "scripts/init.mjs upgrade", "Never overwrite an existing core file",
367 + "Approve writing .system/MISSION.md?", "Approve writing .system/RULES.md?",
368 + "Approve writing .system/SYSTEM.md?", "scripts/doctor.mjs",
369 + ]) assert.ok(init.includes(contract), `missing init contract: ${contract}`);
370 + for (const file of ["MISSION.md", "RULES.md", "SYSTEM.md"])
371 + assert.ok(init.indexOf(`Approve writing .system/${file}?`) &lt; init.indexOf(`Write .system/${file}`));
372 + assert.match(init, /Never launch a browser or editor/);
373 + });</code></pre>
374 +<ol start="2">
375 +<li><strong>☐ Run RED.</strong><br>Run: <code>mise //:test -- extensions/the-system/__tests__/workflow-skills.test.ts</code><br>Expected: FAIL with missing init files.</li>
376 +<li><strong>☐ Create the skill.</strong> Create <code>extensions/the-system/skills/the-system-init/SKILL.md</code> exactly:</li>
377 +</ol>
378 +<pre><code>---
379 +name: the-system-init
380 +description: Create or upgrade a project-local .system through focused questions and explicit human approvals
381 +---
383 +# The System Init
385 +Use only for an explicit initialization or upgrade request; never during normal turns.
387 +## Safety
389 +Before any write, explain that `.system/SYSTEM.md`, `.system/MISSION.md`, and `.system/RULES.md` are privileged instructions future agents may receive as authority.
390 +Tell the user not to place secrets, credentials, raw private data, or binary bytes in them.
391 +Preserve unrelated dirty work.
392 +Never overwrite an existing core file.
393 +Never silently repair malformed config, root conflict, prefix conflict, newer project version, or unsafe path.
394 +Resolve `../../scripts/init.mjs` and `../../scripts/doctor.mjs` against this skill directory.
395 +Use absolute paths with `node --no-warnings --experimental-strip-types`.
397 +## Inspect
399 +Use `scripts/init.mjs inspect`:
400 +`node --no-warnings --experimental-strip-types &lt;absolute-init-path&gt; inspect &lt;current-cwd&gt;`.
401 +Pass a command prefix only as a proposal, not approval.
402 +Report every `ROOT`, `PREFIX`, `CORE`, `CREATE`, and `UPGRADE` line; stop on `ERROR`.
403 +Read existing `.system`, README/purpose docs, agent instructions, package/language manifests, build files, task config, conventional tests, top-level structure, and security/data/release config without mutation.
404 +Summarize facts, conflicts, and unknowns; never ask the user to repeat a consistent inspected fact.
406 +## Interview
408 +For first initialization or missing core truth, ask one focused question at a time and wait.
409 +Cover unresolved topics in order: purpose/outcome; audience/operators; non-goals/boundaries; engineering constraints/environments; security/trust; data ownership/retention/privacy/migration; tests/verification; release expectations/compatibility/rollout/rollback.
410 +Challenge vagueness or conflict with one follow-up at a time.
411 +When all cores exist on rerun, preserve settled truth and ask only about a machine upgrade or explicit requested gap.
413 +## Prefix and machine assets
415 +Propose one prefix from prompt argument, repository name, package name, or title, in that order.
416 +Require `[A-Z][A-Z0-9]{1,7}` and ask `Approve project prefix PREFIX?`.
417 +Only explicit yes approves; otherwise request one replacement, validate, and ask again.
418 +Existing config prefix is authoritative; stop rather than change a conflict.
419 +After approval, use `scripts/init.mjs apply`:
420 +`node --no-warnings --experimental-strip-types &lt;absolute-init-path&gt; apply &lt;root&gt; &lt;approved-prefix&gt;`.
421 +Relay every `WROTE` and `PENDING` line.
422 +If pending, display every config transition and CSS replacement, then ask `Approve the reported machine-owned config/CSS upgrade?`.
423 +On yes, use `scripts/init.mjs upgrade`:
424 +`node --no-warnings --experimental-strip-types &lt;absolute-init-path&gt; upgrade &lt;root&gt; &lt;approved-prefix&gt;`.
425 +On no, preserve assets, state doctor remains non-green, and do not claim completion.
427 +## Separate core approvals
429 +Use inspected facts and answers; never invent an unanswered rule.
430 +Do not modify, reformat, or seek blanket reapproval for a `preserve` core.
431 +For missing mission, show the whole project-specific draft with `# Mission`, `## Purpose`, `## Audience`, `## Outcomes`, and `## Non-goals`.
432 +Ask exactly: `Approve writing .system/MISSION.md?`
433 +Revise and redisplay when requested.
434 +Write .system/MISSION.md only after explicit approval of that displayed draft.
435 +For missing rules, show the whole project-specific draft with `# Rules`, `## Engineering constraints`, `## Security and data`, `## Testing`, and `## Release`.
436 +Ask exactly: `Approve writing .system/RULES.md?`
437 +Revise and redisplay when requested.
438 +Write .system/RULES.md only after explicit approval of that displayed draft.
439 +For missing topology, show this complete canonical draft without project facts:
441 +```markdown
442 +# The System
444 +## Authority
446 +MISSION.md defines why this project exists.
447 +RULES.md defines how work must be done.
448 +Approved specs define what behavior must exist.
449 +Metadata is the authority for system-document relationships.
451 +## Ownership
453 +Humans own SYSTEM.md, MISSION.md, RULES.md, specs, and accepted spec-owned mockups.
454 +Agents may draft roadmaps and plans for human review and maintain issues and research.
455 +Machine-owned config.json and system.css change only through initialization.
457 +## Documents
459 +Authored documents are editable HTML in matching .system directories.
460 +Each uses ../system.css and exactly one system-meta JSON block.
461 +Specs are leaf truth.
462 +Roadmaps reference one spec; plans reference one spec and optionally one matching roadmap phase; issues reference violated specs.
463 +Tests use SYSTEM-SPEC comments.
464 +Accepted mockups live beside and belong to their spec.
466 +## Safety
468 +System documents contain no secrets, credentials, raw private data, or binary asset bytes.
469 +Invalid or outdated state is reported and never silently repaired.
470 +```
472 +Ask exactly: `Approve writing .system/SYSTEM.md?`
473 +Revise and redisplay when requested.
474 +Write .system/SYSTEM.md only after explicit approval of that displayed draft.
475 +Denied approval leaves the core absent and initialization incomplete.
477 +## Validate
479 +Use `scripts/doctor.mjs` after approved writes:
480 +`node --no-warnings --experimental-strip-types &lt;absolute-doctor-path&gt; &lt;root&gt;`.
481 +Preserve report order; never hide or automatically repair findings.
482 +Exit 0 with `OK The System is valid` means completion; exit 1 means incomplete or invalid.
483 +Report root, prefix, created machine paths, preserved/new cores, upgrade decision, and doctor status.
484 +Never launch a browser or editor.
485 +Do not commit unless separately asked.</code></pre>
486 +<ol start="4">
487 +<li><strong>☐ Create the prompt.</strong> Create <code>extensions/the-system/prompts/system-init.md</code> exactly:</li>
488 +</ol>
489 +<pre><code>---
490 +description: Initialize or upgrade The System through guided approval
491 +argument-hint: "[PROJECT-PREFIX]"
492 +---
494 +Use the the-system-init skill for the current project.
495 +Treat optional prefix `$ARGUMENTS` as a proposal, not approval, and follow every focused question and separate write decision in the skill.</code></pre>
496 +<ol start="5">
497 +<li><strong>☐ Update real resource expectations before GREEN.</strong> In the existing package-discovery test, rename it to <code>"discovers phase resources from both package manifests"</code>. Replace the extension prompt assertion with:</li>
498 +</ol>
499 +<pre><code> assert.deepEqual(relativeResources(root, extension.prompts), [
500 + "prompts/system-doctor.md",
501 + "prompts/system-init.md",
502 + ]);
503 + for (const expected of ["skills/system-doctor/SKILL.md", "skills/the-system-init/SKILL.md"])
504 + assert.ok(relativeResources(root, extension.skills).includes(expected));</code></pre>
505 +<p>Replace its final repository prompt assertion with:</p>
506 +<pre><code> const repositoryPrompts = relativeResources(path.resolve(root, "../.."), repository.prompts);
507 + for (const expected of [
508 + "extensions/the-system/prompts/system-doctor.md",
509 + "extensions/the-system/prompts/system-init.md",
510 + ]) assert.ok(repositoryPrompts.includes(expected));</code></pre>
511 +<ol start="6">
512 +<li><strong>☐ Run GREEN.</strong><br>Run: <code>mise //:test -- extensions/the-system/__tests__/workflow-skills.test.ts</code><br>Expected: contracts and real root/extension discovery PASS; no manifest change is needed.</li>
513 +<li><strong>☐ Run both Phase 4 suites and checks.</strong><br>Run: <code>mise //:test -- extensions/the-system/__tests__/init.test.ts extensions/the-system/__tests__/workflow-skills.test.ts &amp;&amp; mise //:check</code><br>Expected: tests, typecheck, skills, static checks, and packages PASS.</li>
514 +<li><strong>☐ Checkpoint.</strong><br>Run: <code>git add extensions/the-system/skills/the-system-init/SKILL.md extensions/the-system/prompts/system-init.md extensions/the-system/__tests__/workflow-skills.test.ts &amp;&amp; git commit -m "feat(the-system): add guided init workflow"</code><br>Expected: one resource/workflow commit.</li>
515 +</ol>
516 +</section>
517 +<section>
518 +<h2>Task 3 · Independent-green gate</h2>
519 +<ol>
520 +<li><strong>☐ Record dirty work.</strong><br>Run: <code>git status --short</code><br>Expected: record and preserve every unrelated entry.</li>
521 +<li><strong>☐ Format planned files.</strong><br>Run: <code>mise //:fmt</code><br>Expected: retain changes only in the six planned paths; undo only formatter changes to unrelated clean-at-start files.</li>
522 +<li><strong>☐ Focused governance gate.</strong><br>Run: <code>mise //:test -- extensions/the-system/__tests__/documents.test.ts extensions/the-system/__tests__/doctor.test.ts extensions/the-system/__tests__/init.test.ts extensions/the-system/__tests__/workflow-skills.test.ts</code><br>Expected: PASS.</li>
523 +<li><strong>☐ Extension regression gate.</strong><br>Run: <code>mise //:test -- extensions/the-system/__tests__ &amp;&amp; mise //extensions/the-system:e2e</code><br>Expected: all extension tests and existing Chromium/Firefox mockup smoke tests PASS.</li>
524 +<li><strong>☐ Static/lint gate.</strong><br>Run: <code>mise //:check &amp;&amp; mise //:lint</code><br>Expected: typecheck, skills, static/package checks, formatting, and lint PASS.</li>
525 +<li><strong>☐ Real loading gate.</strong><br>Run: <code>mise //:test -- extensions/the-system/__tests__/harness.test.ts</code><br>Expected: existing single runtime entry loads; init remains resource/script-only.</li>
526 +<li><strong>☐ Full release gate.</strong><br>Run: <code>mise //:ci</code><br>Expected: check, lint, centralized tests, and all E2E PASS in documented order.</li>
527 +<li><strong>☐ Scope audit.</strong><br>Run: <code>git status --short &amp;&amp; git diff --name-only HEAD~2..HEAD</code><br>Expected: only the six file-map paths occur; original unrelated dirty work remains unchanged.</li>
528 +<li><strong>☐ Formatting checkpoint only if needed.</strong><br>Run: <code>git add extensions/the-system/init.ts extensions/the-system/scripts/init.mjs extensions/the-system/__tests__/init.test.ts extensions/the-system/skills/the-system-init/SKILL.md extensions/the-system/prompts/system-init.md extensions/the-system/__tests__/workflow-skills.test.ts &amp;&amp; git diff --cached --quiet || git commit -m "test(the-system): complete guided init phase gate"</code><br>Expected: no commit when clean; otherwise only formatted Phase 4 files.</li>
529 +</ol>
530 +</section>
531 +<section>
532 +<h2>Acceptance and self-review</h2>
533 +<table>
534 +<tr><th>Contract</th><th>Proof</th></tr>
535 +<tr><td>Thin prompt; optional prefix remains unapproved.</td><td>Prompt contract and real package discovery.</td></tr>
536 +<tr><td>Root/config/version rules reuse Phase 2.</td><td>Nested-root, strict prefix/version fixtures, unchanged kernel tests.</td></tr>
537 +<tr><td>Context inspection and eight focused topics precede drafting.</td><td>Exact skill workflow and contract tokens.</td></tr>
538 +<tr><td>Missing cores receive separate whole-draft approvals; existing cores survive.</td><td>Approval-order assertions, no helper core writes, byte/mtime rerun proof.</td></tr>
539 +<tr><td>Directories/config/exact CSS are idempotent; upgrades require consent.</td><td>Fresh, repeat, future-assets decline/approve fixtures.</td></tr>
540 +<tr><td>Completion is doctor-valid and on-demand.</td><td>Doctor-green fixture, harness, extension tests/E2E, <code>mise //:ci</code>.</td></tr>
541 +</table>
542 +<ul>
543 +<li>Every Phase 4 roadmap bullet maps to Tasks 1–2; Task 3 leaves the repository independently green.</li>
544 +<li>All APIs, paths, versions, script flags, discovery behavior, and mise syntax match the current Phase 2/3 implementation.</li>
545 +<li>Each implementation starts RED, receives literal minimal code, then runs focused GREEN and regression gates.</li>
546 +<li>Runtime governance, startup notices, browser review, lifecycle migrations, and issues remain outside this plan.</li>
547 +<li>No deferred implementation instruction remains; project-specific prose comes only from inspected facts and human answers.</li>
548 +</ul>
549 +<div class="contract stop"><strong>Stop here.</strong> This plan intentionally stops at Phase 4. Phase 5 owns injection, startup notification, runtime orchestration, and write gates; later phases own browser review and lifecycle migrations.</div>
550 +</section>
551 +</main></article></body></html>