repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by bugabinga

test(the-system): complete document kernel phase

40e8cd7e9a4d5bfb9be9f0b43d140df4496d60aa

Oliver Jan Krylow <oliver@bugabinga.net> ·

unsigned

Browse filesCompare with HEAD

Changed files (4)

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

Modified
1 1 import assert from "node:assert/strict";
2 -import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
2 +import {
3 + mkdirSync,
4 + mkdtempSync,
5 + readFileSync,
6 + rmSync,
7 + writeFileSync,
8 +} from "node:fs";
3 9 import { tmpdir } from "node:os";
4 10 import path from "node:path";
5 11 import { afterEach, describe, it } from "vitest";
6 12 import {
7 - discoverProjectRoot,
8 - indexDocuments,
9 - parseDocumentId,
10 - parseDocumentMetadata,
11 - parseSystemConfig,
12 - resolveGovernedPath,
13 - SystemDocumentError,
14 - validateAuthoredHtml,
15 - validateFilename,
13 + discoverProjectRoot,
14 + indexDocuments,
15 + parseDocumentId,
16 + parseDocumentMetadata,
17 + parseSystemConfig,
18 + resolveGovernedPath,
19 + SystemDocumentError,
20 + validateAuthoredHtml,
21 + validateFilename,
16 22 } from "../documents.ts";
18 24 const temporary: string[] = [];
19 25 const tree = () => {
20 - const root = mkdtempSync(path.join(tmpdir(), "the-system-documents-"));
21 - temporary.push(root);
22 - return root;
26 + const root = mkdtempSync(path.join(tmpdir(), "the-system-documents-"));
27 + temporary.push(root);
28 + return root;
24 30 const dir = (...parts: string[]) => {
25 - const result = path.join(...parts);
26 - mkdirSync(result, { recursive: true });
27 - return result;
31 + const result = path.join(...parts);
32 + mkdirSync(result, { recursive: true });
33 + return result;
29 35 afterEach(() => {
30 - for (const root of temporary.splice(0)) rmSync(root, { recursive: true, force: true });
36 + for (const root of temporary.splice(0))
37 + rmSync(root, { recursive: true, force: true });
33 40 describe("project root", () => {
34 - it.each([
35 - ["simple Git", [".git"], "directory"],
36 - ["Git worktree", [".git"], "file"],
37 - ["JJ workspace", [".jj"], "directory"],
38 - ["colocated JJ/Git", [".jj", ".git"], "directory"],
39 - ] as const)("resolves %s", (_name, markers, markerKind) => {
40 - const root = tree();
41 - const cwd = dir(root, "packages", "app");
42 - for (const marker of markers) {
43 - const target = path.join(root, marker);
44 - if (markerKind === "file" && marker === ".git") writeFileSync(target, "gitdir: ../shared\n");
45 - else mkdirSync(target);
46 - }
47 - assert.equal(discoverProjectRoot(cwd), root);
48 - });
41 + it.each([
42 + ["simple Git", [".git"], "directory"],
43 + ["Git worktree", [".git"], "file"],
44 + ["JJ workspace", [".jj"], "directory"],
45 + ["colocated JJ/Git", [".jj", ".git"], "directory"],
46 + ] as const)("resolves %s", (_name, markers, markerKind) => {
47 + const root = tree();
48 + const cwd = dir(root, "packages", "app");
49 + for (const marker of markers) {
50 + const target = path.join(root, marker);
51 + if (markerKind === "file" && marker === ".git")
52 + writeFileSync(target, "gitdir: ../shared\n");
53 + else mkdirSync(target);
54 + }
55 + assert.equal(discoverProjectRoot(cwd), root);
56 + });
50 - it("uses cwd when no VCS marker exists", () => {
51 - const cwd = dir(tree(), "plain");
52 - assert.equal(discoverProjectRoot(cwd), path.resolve(cwd));
53 - });
58 + it("uses cwd when no VCS marker exists", () => {
59 + const cwd = dir(tree(), "plain");
60 + assert.equal(discoverProjectRoot(cwd), path.resolve(cwd));
61 + });
55 - it("fails when nearest JJ and Git roots differ", () => {
56 - const gitRoot = tree();
57 - mkdirSync(path.join(gitRoot, ".git"));
58 - const jjRoot = dir(gitRoot, "nested");
59 - mkdirSync(path.join(jjRoot, ".jj"));
60 - const cwd = dir(jjRoot, "src");
61 - assert.throws(
62 - () => discoverProjectRoot(cwd),
63 - (error: unknown) =>
64 - error instanceof SystemDocumentError &&
65 - error.code === "root.conflict" &&
66 - error.message === `Conflicting project roots: Git ${gitRoot}; JJ ${jjRoot}`,
67 - );
68 - });
63 + it("fails when nearest JJ and Git roots differ", () => {
64 + const gitRoot = tree();
65 + mkdirSync(path.join(gitRoot, ".git"));
66 + const jjRoot = dir(gitRoot, "nested");
67 + mkdirSync(path.join(jjRoot, ".jj"));
68 + const cwd = dir(jjRoot, "src");
69 + assert.throws(
70 + () => discoverProjectRoot(cwd),
71 + (error: unknown) =>
72 + error instanceof SystemDocumentError &&
73 + error.code === "root.conflict" &&
74 + error.message ===
75 + `Conflicting project roots: Git ${gitRoot}; JJ ${jjRoot}`,
76 + );
77 + });
71 80 describe("governed path containment", () => {
72 - it("normalizes a contained relative path", () => {
73 - const root = path.resolve("project");
74 - assert.equal(
75 - resolveGovernedPath(root, ".system/specs/../plans/a.html"),
76 - path.join(root, ".system", "plans", "a.html"),
77 - );
78 - });
81 + it("normalizes a contained relative path", () => {
82 + const root = path.resolve("project");
83 + assert.equal(
84 + resolveGovernedPath(root, ".system/specs/../plans/a.html"),
85 + path.join(root, ".system", "plans", "a.html"),
86 + );
87 + });
80 - it.each(["../outside", path.resolve("outside")])("rejects %s", (candidate) => {
81 - assert.throws(
82 - () => resolveGovernedPath(path.resolve("project"), candidate),
83 - (error: unknown) => error instanceof SystemDocumentError && error.code === "path.outside-root",
84 - );
85 - });
89 + it.each([
90 + "../outside",
91 + path.resolve("outside"),
92 + ])("rejects %s", (candidate) => {
93 + assert.throws(
94 + () => resolveGovernedPath(path.resolve("project"), candidate),
95 + (error: unknown) =>
96 + error instanceof SystemDocumentError &&
97 + error.code === "path.outside-root",
98 + );
99 + });
87 - it("does not confuse a sibling sharing the root prefix for a child", () => {
88 - const root = path.resolve("project");
89 - assert.throws(
90 - () => resolveGovernedPath(root, path.resolve("project-other/file")),
91 - /outside project root/,
92 - );
93 - });
101 + it("does not confuse a sibling sharing the root prefix for a child", () => {
102 + const root = path.resolve("project");
103 + assert.throws(
104 + () => resolveGovernedPath(root, path.resolve("project-other/file")),
105 + /outside project root/,
106 + );
107 + });
96 110 describe("system config", () => {
97 - it("accepts only the exact versioned shape", () => {
98 - assert.deepEqual(parseSystemConfig('{"prefix":"PX","schemaVersion":1,"styleVersion":1}'), {
99 - prefix: "PX",
100 - schemaVersion: 1,
101 - styleVersion: 1,
102 - });
103 - });
111 + it("accepts only the exact versioned shape", () => {
112 + assert.deepEqual(
113 + parseSystemConfig('{"prefix":"PX","schemaVersion":1,"styleVersion":1}'),
115 + prefix: "PX",
116 + schemaVersion: 1,
117 + styleVersion: 1,
118 + },
119 + );
120 + });
105 - it.each([
106 - ["malformed JSON", "{"],
107 - ["unknown key", '{"prefix":"PX","schemaVersion":1,"styleVersion":1,"extra":true}'],
108 - ["missing key", '{"prefix":"PX","schemaVersion":1}'],
109 - ["short prefix", '{"prefix":"P","schemaVersion":1,"styleVersion":1}'],
110 - ["lowercase prefix", '{"prefix":"px","schemaVersion":1,"styleVersion":1}'],
111 - ["zero schema", '{"prefix":"PX","schemaVersion":0,"styleVersion":1}'],
112 - ["fractional style", '{"prefix":"PX","schemaVersion":1,"styleVersion":1.5}'],
113 - ])("rejects %s", (_name, source) =>
114 - assert.throws(() => parseSystemConfig(source), SystemDocumentError),
115 - );
122 + it.each([
123 + ["malformed JSON", "{"],
125 + "unknown key",
126 + '{"prefix":"PX","schemaVersion":1,"styleVersion":1,"extra":true}',
127 + ],
128 + ["missing key", '{"prefix":"PX","schemaVersion":1}'],
129 + ["short prefix", '{"prefix":"P","schemaVersion":1,"styleVersion":1}'],
130 + ["lowercase prefix", '{"prefix":"px","schemaVersion":1,"styleVersion":1}'],
131 + ["zero schema", '{"prefix":"PX","schemaVersion":0,"styleVersion":1}'],
133 + "fractional style",
134 + '{"prefix":"PX","schemaVersion":1,"styleVersion":1.5}',
135 + ],
136 + ])("rejects %s", (_name, source) =>
137 + assert.throws(() => parseSystemConfig(source), SystemDocumentError));
118 140 describe("document IDs and filenames", () => {
119 - it.each([
120 - ["PX-SPEC-001", "spec", 1],
121 - ["PX-ROADMAP-999", "roadmap", 999],
122 - ["PX-PLAN-1000", "plan", 1000],
123 - ["PX-ISSUE-042", "issue", 42],
124 - ["PX-RESEARCH-007", "research", 7],
125 - ] as const)("parses %s", (id, type, sequence) => {
126 - assert.deepEqual(parseDocumentId(id, "PX"), { id, prefix: "PX", type, sequence });
127 - });
141 + it.each([
142 + ["PX-SPEC-001", "spec", 1],
143 + ["PX-ROADMAP-999", "roadmap", 999],
144 + ["PX-PLAN-1000", "plan", 1000],
145 + ["PX-ISSUE-042", "issue", 42],
146 + ["PX-RESEARCH-007", "research", 7],
147 + ] as const)("parses %s", (id, type, sequence) => {
148 + assert.deepEqual(parseDocumentId(id, "PX"), {
149 + id,
150 + prefix: "PX",
151 + type,
152 + sequence,
153 + });
154 + });
129 - it.each([
130 - "P-SPEC-001",
131 - "px-SPEC-001",
132 - "PX-spec-001",
133 - "PX-SPEC-01",
134 - "PX-SPEC-000",
135 - "PX-SPEC-0001",
136 - "PX-TEST-001",
137 - "PX-SPEC-001-slug",
138 - ])("rejects invalid ID %s", (id) =>
139 - assert.throws(() => parseDocumentId(id), /Invalid document ID/),
140 - );
156 + it.each([
157 + "P-SPEC-001",
158 + "px-SPEC-001",
159 + "PX-spec-001",
160 + "PX-SPEC-01",
161 + "PX-SPEC-000",
162 + "PX-SPEC-0001",
163 + "PX-TEST-001",
164 + "PX-SPEC-001-slug",
165 + ])("rejects invalid ID %s", (id) =>
166 + assert.throws(() => parseDocumentId(id), /Invalid document ID/));
142 - it("rejects a foreign configured prefix", () =>
143 - assert.throws(() => parseDocumentId("AB-SPEC-001", "PX"), /prefix PX/));
168 + it("rejects a foreign configured prefix", () =>
169 + assert.throws(() => parseDocumentId("AB-SPEC-001", "PX"), /prefix PX/));
145 - it("accepts a matching type directory, ID, and slug", () => {
146 - assert.doesNotThrow(() =>
147 - validateFilename(
148 - "/project/.system/specs/PX-SPEC-001-login-flow.html",
149 - { id: "PX-SPEC-001", type: "spec" },
150 - "PX",
151 - ),
152 - );
153 - });
171 + it("accepts a matching type directory, ID, and slug", () => {
172 + assert.doesNotThrow(() =>
173 + validateFilename(
174 + "/project/.system/specs/PX-SPEC-001-login-flow.html",
175 + { id: "PX-SPEC-001", type: "spec" },
176 + "PX",
177 + ),
178 + );
179 + });
155 - it.each([
156 - "/project/.system/specs/PX-SPEC-002-login-flow.html",
157 - "/project/.system/specs/PX-SPEC-001-Login.html",
158 - "/project/.system/plans/PX-SPEC-001-login-flow.html",
159 - "/project/.system/specs/PX-SPEC-001-login_flow.html",
160 - ])("rejects mismatched filename %s", (filename) => {
161 - assert.throws(
162 - () => validateFilename(filename, { id: "PX-SPEC-001", type: "spec" }, "PX"),
163 - /Filename mismatch/,
164 - );
165 - });
181 + it.each([
182 + "/project/.system/specs/PX-SPEC-002-login-flow.html",
183 + "/project/.system/specs/PX-SPEC-001-Login.html",
184 + "/project/.system/plans/PX-SPEC-001-login-flow.html",
185 + "/project/.system/specs/PX-SPEC-001-login_flow.html",
186 + ])("rejects mismatched filename %s", (filename) => {
187 + assert.throws(
188 + () =>
189 + validateFilename(filename, { id: "PX-SPEC-001", type: "spec" }, "PX"),
190 + /Filename mismatch/,
191 + );
192 + });
168 -const shell = (metadata: string, body = "<header><h1>Title</h1></header><main><section><h2>Contract</h2><p>Readable.</p></section></main>") => `<!doctype html>
195 +const shell = (
196 + metadata: string,
197 + body = "<header><h1>Title</h1></header><main><section><h2>Contract</h2><p>Readable.</p></section></main>",
198 +) => `<!doctype html>
169 199 <html lang="en"><head><meta charset="utf-8">
170 200 <meta name="viewport" content="width=device-width, initial-scale=1">
171 201 <title>Title</title><link rel="stylesheet" href="../system.css"></head>
172 202 <body>${body}<script type="application/json" id="system-meta">${metadata}</script></body></html>`;
174 204 describe("document metadata", () => {
175 - it.each([
176 - ['{"id":"PX-SPEC-001","type":"spec"}', { id: "PX-SPEC-001", type: "spec" }],
177 - ['{"id":"PX-ROADMAP-001","type":"roadmap","spec":"PX-SPEC-001"}', { id: "PX-ROADMAP-001", type: "roadmap", spec: "PX-SPEC-001" }],
178 - ['{"id":"PX-PLAN-001","type":"plan","spec":"PX-SPEC-001"}', { id: "PX-PLAN-001", type: "plan", spec: "PX-SPEC-001" }],
179 - ['{"id":"PX-PLAN-002","type":"plan","spec":"PX-SPEC-001","roadmap":"PX-ROADMAP-001","phase":2}', { id: "PX-PLAN-002", type: "plan", spec: "PX-SPEC-001", roadmap: "PX-ROADMAP-001", phase: 2 }],
180 - ['{"id":"PX-ISSUE-001","type":"issue","status":"open","specs":[]}', { id: "PX-ISSUE-001", type: "issue", status: "open", specs: [] }],
181 - ['{"id":"PX-RESEARCH-001","type":"research","capturedAt":"2026-07-11","sources":["https://example.com/a"]}', { id: "PX-RESEARCH-001", type: "research", capturedAt: "2026-07-11", sources: ["https://example.com/a"] }],
182 - ] as const)("parses exact metadata %s", (json, expected) => assert.deepEqual(parseDocumentMetadata(shell(json), "PX"), expected));
205 + it.each([
206 + ['{"id":"PX-SPEC-001","type":"spec"}', { id: "PX-SPEC-001", type: "spec" }],
208 + '{"id":"PX-ROADMAP-001","type":"roadmap","spec":"PX-SPEC-001"}',
209 + { id: "PX-ROADMAP-001", type: "roadmap", spec: "PX-SPEC-001" },
210 + ],
212 + '{"id":"PX-PLAN-001","type":"plan","spec":"PX-SPEC-001"}',
213 + { id: "PX-PLAN-001", type: "plan", spec: "PX-SPEC-001" },
214 + ],
216 + '{"id":"PX-PLAN-002","type":"plan","spec":"PX-SPEC-001","roadmap":"PX-ROADMAP-001","phase":2}',
218 + id: "PX-PLAN-002",
219 + type: "plan",
220 + spec: "PX-SPEC-001",
221 + roadmap: "PX-ROADMAP-001",
222 + phase: 2,
223 + },
224 + ],
226 + '{"id":"PX-ISSUE-001","type":"issue","status":"open","specs":[]}',
227 + { id: "PX-ISSUE-001", type: "issue", status: "open", specs: [] },
228 + ],
230 + '{"id":"PX-RESEARCH-001","type":"research","capturedAt":"2026-07-11","sources":["https://example.com/a"]}',
232 + id: "PX-RESEARCH-001",
233 + type: "research",
234 + capturedAt: "2026-07-11",
235 + sources: ["https://example.com/a"],
236 + },
237 + ],
238 + ] as const)("parses exact metadata %s", (json, expected) =>
239 + assert.deepEqual(parseDocumentMetadata(shell(json), "PX"), expected));
184 - it.each([
185 - ["missing block", "<!doctype html><html lang=\"en\"></html>"],
186 - ["duplicate blocks", shell('{"id":"PX-SPEC-001","type":"spec"}') + '<script type="application/json" id="system-meta">{}</script>'],
187 - ["duplicate JSON key", shell('{"id":"PX-SPEC-001","id":"PX-SPEC-002","type":"spec"}')],
188 - ["unknown key", shell('{"id":"PX-SPEC-001","type":"spec","status":"open"}')],
189 - ["own ID/type mismatch", shell('{"id":"PX-PLAN-001","type":"spec"}')],
190 - ["one-sided roadmap", shell('{"id":"PX-PLAN-001","type":"plan","spec":"PX-SPEC-001","roadmap":"PX-ROADMAP-001"}')],
191 - ["duplicate issue specs", shell('{"id":"PX-ISSUE-001","type":"issue","status":"fixed","specs":["PX-SPEC-001","PX-SPEC-001"]}')],
192 - ["invalid date", shell('{"id":"PX-RESEARCH-001","type":"research","capturedAt":"2026-02-30"}')],
193 - ["non-HTTPS source", shell('{"id":"PX-RESEARCH-001","type":"research","capturedAt":"2026-07-11","sources":["http://example.com"]}')],
194 - ])("rejects %s", (_name, html) => assert.throws(() => parseDocumentMetadata(html, "PX"), SystemDocumentError));
241 + it.each([
242 + ["missing block", '<!doctype html><html lang="en"></html>'],
244 + "duplicate blocks",
245 + shell('{"id":"PX-SPEC-001","type":"spec"}') +
246 + '<script type="application/json" id="system-meta">{}</script>',
247 + ],
249 + "duplicate JSON key",
250 + shell('{"id":"PX-SPEC-001","id":"PX-SPEC-002","type":"spec"}'),
251 + ],
253 + "unknown key",
254 + shell('{"id":"PX-SPEC-001","type":"spec","status":"open"}'),
255 + ],
256 + ["own ID/type mismatch", shell('{"id":"PX-PLAN-001","type":"spec"}')],
258 + "one-sided roadmap",
259 + shell(
260 + '{"id":"PX-PLAN-001","type":"plan","spec":"PX-SPEC-001","roadmap":"PX-ROADMAP-001"}',
261 + ),
262 + ],
264 + "duplicate issue specs",
265 + shell(
266 + '{"id":"PX-ISSUE-001","type":"issue","status":"fixed","specs":["PX-SPEC-001","PX-SPEC-001"]}',
267 + ),
268 + ],
270 + "invalid date",
271 + shell(
272 + '{"id":"PX-RESEARCH-001","type":"research","capturedAt":"2026-02-30"}',
273 + ),
274 + ],
276 + "non-HTTPS source",
277 + shell(
278 + '{"id":"PX-RESEARCH-001","type":"research","capturedAt":"2026-07-11","sources":["http://example.com"]}',
279 + ),
280 + ],
281 + ])("rejects %s", (_name, html) =>
282 + assert.throws(
283 + () => parseDocumentMetadata(html, "PX"),
284 + SystemDocumentError,
285 + ));
197 288 describe("authored HTML", () => {
198 - it("accepts the complete semantic shell and inert progressive enhancement", () => {
199 - const html = shell('{"id":"PX-SPEC-001","type":"spec"}', "<header><h1>Title</h1></header><main><section><h2>Contract</h2><details><summary>More</summary><p>Text.</p></details></section></main><script>document.querySelector('details');</script>");
200 - assert.deepEqual(validateAuthoredHtml("specs/PX-SPEC-001-title.html", html), []);
201 - });
289 + it("accepts the complete semantic shell and inert progressive enhancement", () => {
290 + const html = shell(
291 + '{"id":"PX-SPEC-001","type":"spec"}',
292 + "<header><h1>Title</h1></header><main><section><h2>Contract</h2><details><summary>More</summary><p>Text.</p></details></section></main><script>document.querySelector('details');</script>",
293 + );
294 + assert.deepEqual(
295 + validateAuthoredHtml("specs/PX-SPEC-001-title.html", html),
296 + [],
297 + );
298 + });
203 - it.each([
204 - ["document.doctype", shell('{"id":"PX-SPEC-001","type":"spec"}').replace("<!doctype html>", "")],
205 - ["document.language", shell('{"id":"PX-SPEC-001","type":"spec"}').replace('lang="en"', 'lang="fr"')],
206 - ["document.charset", shell('{"id":"PX-SPEC-001","type":"spec"}').replace('<meta charset="utf-8">', "")],
207 - ["document.viewport", shell('{"id":"PX-SPEC-001","type":"spec"}').replace(/<meta name="viewport"[^>]+>/, "")],
208 - ["document.title", shell('{"id":"PX-SPEC-001","type":"spec"}').replace("<title>Title</title>", "<title></title>")],
209 - ["document.stylesheet", shell('{"id":"PX-SPEC-001","type":"spec"}').replace("../system.css", "./local.css")],
210 - ["document.semantic-shell", shell('{"id":"PX-SPEC-001","type":"spec"}').replace(/<main>|<\/main>/g, "")],
211 - ["document.forbidden-tag", shell('{"id":"PX-SPEC-001","type":"spec"}', "<header><h1>X</h1></header><main><section><iframe src=\"x\"></iframe></section></main>")],
212 - ["document.event-handler", shell('{"id":"PX-SPEC-001","type":"spec"}', "<header><h1>X</h1></header><main><section onclick=\"x()\">X</section></main>")],
213 - ["document.executable-url", shell('{"id":"PX-SPEC-001","type":"spec"}', "<header><h1>X</h1></header><main><section><a href=\"javascript:x()\">X</a></section></main>")],
214 - ["document.external-script", shell('{"id":"PX-SPEC-001","type":"spec"}', "<header><h1>X</h1></header><main><section>X</section></main><script src=\"https://example.com/x.js\"></script>")],
215 - ["document.active-api", shell('{"id":"PX-SPEC-001","type":"spec"}', "<header><h1>X</h1></header><main><section>X</section></main><script>fetch('https://example.com')</script>")],
216 - ["document.css-resource", shell('{"id":"PX-SPEC-001","type":"spec"}', "<header><h1>X</h1></header><main><section>X</section></main><style>@import url('https://example.com/x.css');</style>")],
217 - ["document.meta-refresh", shell('{"id":"PX-SPEC-001","type":"spec"}').replace("</head>", '<meta http-equiv="refresh" content="0; url=x"></head>')],
218 - ])("reports %s", (code, html) => assert.ok(validateAuthoredHtml("doc.html", html).some((item) => item.code === code)));
300 + it.each([
302 + "document.doctype",
303 + shell('{"id":"PX-SPEC-001","type":"spec"}').replace(
304 + "<!doctype html>",
305 + "",
306 + ),
307 + ],
309 + "document.language",
310 + shell('{"id":"PX-SPEC-001","type":"spec"}').replace(
311 + 'lang="en"',
312 + 'lang="fr"',
313 + ),
314 + ],
316 + "document.charset",
317 + shell('{"id":"PX-SPEC-001","type":"spec"}').replace(
318 + '<meta charset="utf-8">',
319 + "",
320 + ),
321 + ],
323 + "document.viewport",
324 + shell('{"id":"PX-SPEC-001","type":"spec"}').replace(
325 + /<meta name="viewport"[^>]+>/,
326 + "",
327 + ),
328 + ],
330 + "document.title",
331 + shell('{"id":"PX-SPEC-001","type":"spec"}').replace(
332 + "<title>Title</title>",
333 + "<title></title>",
334 + ),
335 + ],
337 + "document.stylesheet",
338 + shell('{"id":"PX-SPEC-001","type":"spec"}').replace(
339 + "../system.css",
340 + "./local.css",
341 + ),
342 + ],
344 + "document.semantic-shell",
345 + shell('{"id":"PX-SPEC-001","type":"spec"}').replace(
346 + /<main>|<\/main>/g,
347 + "",
348 + ),
349 + ],
351 + "document.forbidden-tag",
352 + shell(
353 + '{"id":"PX-SPEC-001","type":"spec"}',
354 + '<header><h1>X</h1></header><main><section><iframe src="x"></iframe></section></main>',
355 + ),
356 + ],
358 + "document.event-handler",
359 + shell(
360 + '{"id":"PX-SPEC-001","type":"spec"}',
361 + '<header><h1>X</h1></header><main><section onclick="x()">X</section></main>',
362 + ),
363 + ],
365 + "document.executable-url",
366 + shell(
367 + '{"id":"PX-SPEC-001","type":"spec"}',
368 + '<header><h1>X</h1></header><main><section><a href="javascript:x()">X</a></section></main>',
369 + ),
370 + ],
372 + "document.external-script",
373 + shell(
374 + '{"id":"PX-SPEC-001","type":"spec"}',
375 + '<header><h1>X</h1></header><main><section>X</section></main><script src="https://example.com/x.js"></script>',
376 + ),
377 + ],
379 + "document.active-api",
380 + shell(
381 + '{"id":"PX-SPEC-001","type":"spec"}',
382 + "<header><h1>X</h1></header><main><section>X</section></main><script>fetch('https://example.com')</script>",
383 + ),
384 + ],
386 + "document.css-resource",
387 + shell(
388 + '{"id":"PX-SPEC-001","type":"spec"}',
389 + "<header><h1>X</h1></header><main><section>X</section></main><style>@import url('https://example.com/x.css');</style>",
390 + ),
391 + ],
393 + "document.meta-refresh",
394 + shell('{"id":"PX-SPEC-001","type":"spec"}').replace(
395 + "</head>",
396 + '<meta http-equiv="refresh" content="0; url=x"></head>',
397 + ),
398 + ],
399 + ])("reports %s", (code, html) =>
400 + assert.ok(
401 + validateAuthoredHtml("doc.html", html).some((item) => item.code === code),
402 + ));
220 - it("allows remote HTTPS navigation anchors", () => {
221 - const html = shell('{"id":"PX-SPEC-001","type":"spec"}', "<header><h1>X</h1></header><main><section><a href=\"https://example.com/reference\">Reference</a></section></main>");
222 - assert.deepEqual(validateAuthoredHtml("doc.html", html), []);
223 - });
404 + it("allows remote HTTPS navigation anchors", () => {
405 + const html = shell(
406 + '{"id":"PX-SPEC-001","type":"spec"}',
407 + '<header><h1>X</h1></header><main><section><a href="https://example.com/reference">Reference</a></section></main>',
408 + );
409 + assert.deepEqual(validateAuthoredHtml("doc.html", html), []);
410 + });
226 -const source = (folder: string, id: string, slug: string, metadata: string) => ({
227 - path: `/project/.system/${folder}/${id}-${slug}.html`, html: shell(metadata),
413 +const source = (
414 + folder: string,
415 + id: string,
416 + slug: string,
417 + metadata: string,
418 +) => ({
419 + path: `/project/.system/${folder}/${id}-${slug}.html`,
420 + html: shell(metadata),
230 423 describe("document index", () => {
231 - it("indexes a valid complete graph without diagnostics", () => {
232 - const result = indexDocuments([
233 - source("specs", "PX-SPEC-001", "login", '{"id":"PX-SPEC-001","type":"spec"}'),
234 - source("roadmaps", "PX-ROADMAP-001", "login", '{"id":"PX-ROADMAP-001","type":"roadmap","spec":"PX-SPEC-001"}'),
235 - source("plans", "PX-PLAN-001", "login-phase-2", '{"id":"PX-PLAN-001","type":"plan","spec":"PX-SPEC-001","roadmap":"PX-ROADMAP-001","phase":2}'),
236 - source("issues", "PX-ISSUE-001", "login-error", '{"id":"PX-ISSUE-001","type":"issue","status":"open","specs":["PX-SPEC-001"]}'),
237 - source("research", "PX-RESEARCH-001", "login", '{"id":"PX-RESEARCH-001","type":"research","capturedAt":"2026-07-11"}'),
238 - ], "PX");
239 - assert.equal(result.documents.length, 5);
240 - assert.deepEqual(result.diagnostics, []);
241 - });
424 + it("indexes a valid complete graph without diagnostics", () => {
425 + const result = indexDocuments(
427 + source(
428 + "specs",
429 + "PX-SPEC-001",
430 + "login",
431 + '{"id":"PX-SPEC-001","type":"spec"}',
432 + ),
433 + source(
434 + "roadmaps",
435 + "PX-ROADMAP-001",
436 + "login",
437 + '{"id":"PX-ROADMAP-001","type":"roadmap","spec":"PX-SPEC-001"}',
438 + ),
439 + source(
440 + "plans",
441 + "PX-PLAN-001",
442 + "login-phase-2",
443 + '{"id":"PX-PLAN-001","type":"plan","spec":"PX-SPEC-001","roadmap":"PX-ROADMAP-001","phase":2}',
444 + ),
445 + source(
446 + "issues",
447 + "PX-ISSUE-001",
448 + "login-error",
449 + '{"id":"PX-ISSUE-001","type":"issue","status":"open","specs":["PX-SPEC-001"]}',
450 + ),
451 + source(
452 + "research",
453 + "PX-RESEARCH-001",
454 + "login",
455 + '{"id":"PX-RESEARCH-001","type":"research","capturedAt":"2026-07-11"}',
456 + ),
457 + ],
458 + "PX",
459 + );
460 + assert.equal(result.documents.length, 5);
461 + assert.deepEqual(result.diagnostics, []);
462 + });
243 - it("sorts stable duplicate, filename, dangling, and forbidden-edge diagnostics", () => {
244 - const result = indexDocuments([
245 - source("specs", "PX-SPEC-001", "one", '{"id":"PX-SPEC-001","type":"spec"}'),
246 - source("specs", "PX-SPEC-002", "two", '{"id":"PX-SPEC-001","type":"spec"}'),
247 - source("roadmaps", "PX-ROADMAP-001", "wrong-target", '{"id":"PX-ROADMAP-001","type":"roadmap","spec":"PX-PLAN-009"}'),
248 - source("plans", "PX-PLAN-001", "dangling", '{"id":"PX-PLAN-001","type":"plan","spec":"PX-SPEC-404"}'),
249 - source("plans", "PX-PLAN-002", "crossed", '{"id":"PX-PLAN-002","type":"plan","spec":"PX-SPEC-001","roadmap":"PX-ROADMAP-002","phase":1}'),
250 - source("roadmaps", "PX-ROADMAP-002", "other", '{"id":"PX-ROADMAP-002","type":"roadmap","spec":"PX-SPEC-003"}'),
251 - source("issues", "PX-ISSUE-001", "unknown", '{"id":"PX-ISSUE-001","type":"issue","status":"open","specs":[]}'),
252 - ], "PX");
253 - assert.deepEqual(result.diagnostics.map(({ code }) => code), [...result.diagnostics].sort((a, b) => a.path.localeCompare(b.path) || a.code.localeCompare(b.code) || a.message.localeCompare(b.message)).map(({ code }) => code));
254 - assert.ok(result.diagnostics.some((item) => item.code === "graph.duplicate-id" && item.message.includes("PX-SPEC-001")));
255 - assert.ok(result.diagnostics.some((item) => item.code === "document.filename"));
256 - assert.ok(result.diagnostics.some((item) => item.code === "graph.dangling-reference" && item.message.includes("PX-SPEC-404")));
257 - assert.ok(result.diagnostics.some((item) => item.code === "graph.forbidden-edge" && item.message.includes("must reference spec")));
258 - assert.ok(result.diagnostics.some((item) => item.code === "graph.forbidden-edge" && item.message.includes("belongs to PX-SPEC-003")));
259 - assert.ok(!result.diagnostics.some((item) => item.path.includes("PX-ISSUE-001") && item.code.startsWith("graph.")));
260 - });
464 + it("sorts stable duplicate, filename, dangling, and forbidden-edge diagnostics", () => {
465 + const result = indexDocuments(
467 + source(
468 + "specs",
469 + "PX-SPEC-001",
470 + "one",
471 + '{"id":"PX-SPEC-001","type":"spec"}',
472 + ),
473 + source(
474 + "specs",
475 + "PX-SPEC-002",
476 + "two",
477 + '{"id":"PX-SPEC-001","type":"spec"}',
478 + ),
479 + source(
480 + "roadmaps",
481 + "PX-ROADMAP-001",
482 + "wrong-target",
483 + '{"id":"PX-ROADMAP-001","type":"roadmap","spec":"PX-PLAN-009"}',
484 + ),
485 + source(
486 + "plans",
487 + "PX-PLAN-001",
488 + "dangling",
489 + '{"id":"PX-PLAN-001","type":"plan","spec":"PX-SPEC-404"}',
490 + ),
491 + source(
492 + "plans",
493 + "PX-PLAN-002",
494 + "crossed",
495 + '{"id":"PX-PLAN-002","type":"plan","spec":"PX-SPEC-001","roadmap":"PX-ROADMAP-002","phase":1}',
496 + ),
497 + source(
498 + "roadmaps",
499 + "PX-ROADMAP-002",
500 + "other",
501 + '{"id":"PX-ROADMAP-002","type":"roadmap","spec":"PX-SPEC-003"}',
502 + ),
503 + source(
504 + "issues",
505 + "PX-ISSUE-001",
506 + "unknown",
507 + '{"id":"PX-ISSUE-001","type":"issue","status":"open","specs":[]}',
508 + ),
509 + ],
510 + "PX",
511 + );
512 + assert.deepEqual(
513 + result.diagnostics.map(({ code }) => code),
514 + [...result.diagnostics]
515 + .sort(
516 + (a, b) =>
517 + a.path.localeCompare(b.path) ||
518 + a.code.localeCompare(b.code) ||
519 + a.message.localeCompare(b.message),
521 + .map(({ code }) => code),
522 + );
523 + assert.ok(
524 + result.diagnostics.some(
525 + (item) =>
526 + item.code === "graph.duplicate-id" &&
527 + item.message.includes("PX-SPEC-001"),
528 + ),
529 + );
530 + assert.ok(
531 + result.diagnostics.some((item) => item.code === "document.filename"),
532 + );
533 + assert.ok(
534 + result.diagnostics.some(
535 + (item) =>
536 + item.code === "graph.dangling-reference" &&
537 + item.message.includes("PX-SPEC-404"),
538 + ),
539 + );
540 + assert.ok(
541 + result.diagnostics.some(
542 + (item) =>
543 + item.code === "graph.forbidden-edge" &&
544 + item.message.includes("must reference spec"),
545 + ),
546 + );
547 + assert.ok(
548 + result.diagnostics.some(
549 + (item) =>
550 + item.code === "graph.forbidden-edge" &&
551 + item.message.includes("belongs to PX-SPEC-003"),
552 + ),
553 + );
554 + assert.ok(
555 + !result.diagnostics.some(
556 + (item) =>
557 + item.path.includes("PX-ISSUE-001") && item.code.startsWith("graph."),
558 + ),
559 + );
560 + });
263 563 describe("bundled system.css", () => {
264 - it("contains exact Nugu tokens, version, components, and responsive contracts", () => {
265 - const css = readFileSync(path.resolve(import.meta.dirname, "../assets/system.css"), "utf8");
266 - for (const token of [
267 - "The System styleVersion: 1", "--fg: #121212", "--page: #ededed", "--panel: #dbdbdb",
268 - "--accent: #ae2eae", "--ui-accent: #922792", "--minor: #3b3b3b", "--focus: #184e5b",
269 - "--important: #4f3c69", "--error: #bd172e", "--warning: #6e6c10", "--info: #116477",
270 - "--fg: #ededed", "--page: #121212", "--panel: #242424", "--accent: #d151d1",
271 - "--ui-accent: #d86dd8", "--minor: #8b8b8b", "--focus: #7ba1aa", "--important: #dfd3f3",
272 - "--error: #ec6376", "--warning: #f0ee69", "--info: #3ec5e3",
273 - ".doc", ".mast", ".grid", ".section", ".contract", ".callout", ".flow", ".metadata",
274 - ".status", ".document-nav", "table", "pre", "overflow-wrap: anywhere", "@media (max-width: 560px)",
275 - ]) assert.ok(css.includes(token), `missing CSS contract: ${token}`);
276 - assert.doesNotMatch(css, /@import|url\s*\(|https?:\/\//i);
277 - });
564 + it("contains exact Nugu tokens, version, components, and responsive contracts", () => {
565 + const css = readFileSync(
566 + path.resolve(import.meta.dirname, "../assets/system.css"),
567 + "utf8",
568 + );
569 + for (const token of [
570 + "The System styleVersion: 1",
571 + "--fg: #121212",
572 + "--page: #ededed",
573 + "--panel: #dbdbdb",
574 + "--accent: #ae2eae",
575 + "--ui-accent: #922792",
576 + "--minor: #3b3b3b",
577 + "--focus: #184e5b",
578 + "--important: #4f3c69",
579 + "--error: #bd172e",
580 + "--warning: #6e6c10",
581 + "--info: #116477",
582 + "--fg: #ededed",
583 + "--page: #121212",
584 + "--panel: #242424",
585 + "--accent: #d151d1",
586 + "--ui-accent: #d86dd8",
587 + "--minor: #8b8b8b",
588 + "--focus: #7ba1aa",
589 + "--important: #dfd3f3",
590 + "--error: #ec6376",
591 + "--warning: #f0ee69",
592 + "--info: #3ec5e3",
593 + ".doc",
594 + ".mast",
595 + ".grid",
596 + ".section",
597 + ".contract",
598 + ".callout",
599 + ".flow",
600 + ".metadata",
601 + ".status",
602 + ".document-nav",
603 + "table",
604 + "pre",
605 + "overflow-wrap: anywhere",
606 + "@media (max-width: 560px)",
607 + ])
608 + assert.ok(css.includes(token), `missing CSS contract: ${token}`);
609 + assert.doesNotMatch(css, /@import|url\s*\(|https?:\/\//i);
610 + });

extensions/the-system/assets/system.css

Modified
1 1 /* The System styleVersion: 1 */
2 2 :root {
3 - color-scheme: light dark;
4 - --fg: #121212;
5 - --page: #ededed;
6 - --panel: #dbdbdb;
7 - --accent: #ae2eae;
8 - --ui-accent: #922792;
9 - --minor: #3b3b3b;
10 - --focus: #184e5b;
11 - --important: #4f3c69;
12 - --error: #bd172e;
13 - --warning: #6e6c10;
14 - --info: #116477;
15 - font-family: ui-monospace, SFMono-Regular, Consolas, monospace;
16 - color: var(--fg);
17 - background: var(--page);
3 + color-scheme: light dark;
4 + --fg: #121212;
5 + --page: #ededed;
6 + --panel: #dbdbdb;
7 + --accent: #ae2eae;
8 + --ui-accent: #922792;
9 + --minor: #3b3b3b;
10 + --focus: #184e5b;
11 + --important: #4f3c69;
12 + --error: #bd172e;
13 + --warning: #6e6c10;
14 + --info: #116477;
15 + font-family: ui-monospace, SFMono-Regular, Consolas, monospace;
16 + color: var(--fg);
17 + background: var(--page);
19 19 @media (prefers-color-scheme: dark) {
20 - :root {
21 - --fg: #ededed;
22 - --page: #121212;
23 - --panel: #242424;
24 - --accent: #d151d1;
25 - --ui-accent: #d86dd8;
26 - --minor: #8b8b8b;
27 - --focus: #7ba1aa;
28 - --important: #dfd3f3;
29 - --error: #ec6376;
30 - --warning: #f0ee69;
31 - --info: #3ec5e3;
32 - }
20 + :root {
21 + --fg: #ededed;
22 + --page: #121212;
23 + --panel: #242424;
24 + --accent: #d151d1;
25 + --ui-accent: #d86dd8;
26 + --minor: #8b8b8b;
27 + --focus: #7ba1aa;
28 + --important: #dfd3f3;
29 + --error: #ec6376;
30 + --warning: #f0ee69;
31 + --info: #3ec5e3;
32 + }
34 +* {
35 + box-sizing: border-box;
37 +body {
38 + margin: 0;
39 + padding: 1rem;
34 -* { box-sizing: border-box; }
35 -body { margin: 0; padding: 1rem; }
36 41 .doc {
37 - background: var(--page);
38 - border: 3px solid var(--fg);
39 - box-shadow: 9px 9px 0 var(--ui-accent);
40 - max-width: 780px;
41 - margin: 0 auto;
42 + background: var(--page);
43 + border: 3px solid var(--fg);
44 + box-shadow: 9px 9px 0 var(--ui-accent);
45 + max-width: 780px;
46 + margin: 0 auto;
43 48 .mast {
44 - display: grid;
45 - grid-template-columns: minmax(0, 1fr) auto;
46 - gap: 1rem;
47 - padding: clamp(.85rem, 3vw, 1.3rem);
48 - border-bottom: 3px solid var(--fg);
49 - background: var(--panel);
49 + display: grid;
50 + grid-template-columns: minmax(0, 1fr) auto;
51 + gap: 1rem;
52 + padding: clamp(0.85rem, 3vw, 1.3rem);
53 + border-bottom: 3px solid var(--fg);
54 + background: var(--panel);
52 - font-size: .7rem;
53 - font-weight: 900;
54 - letter-spacing: .16em;
55 - text-transform: uppercase;
56 - color: var(--accent);
57 + font-size: 0.7rem;
58 + font-weight: 900;
59 + letter-spacing: 0.16em;
60 + text-transform: uppercase;
61 + color: var(--accent);
58 63 .mast h1 {
59 - margin: .2rem 0 0;
60 - font: 900 clamp(1.35rem, 5vw, 2.25rem)/.96 system-ui;
61 - text-transform: uppercase;
62 - overflow-wrap: anywhere;
64 + margin: 0.2rem 0 0;
65 + font: 900 clamp(1.35rem, 5vw, 2.25rem) / 0.96 system-ui;
66 + text-transform: uppercase;
67 + overflow-wrap: anywhere;
64 69 .id {
65 - border: 2px solid var(--fg);
66 - padding: .45rem;
67 - font-weight: 900;
68 - align-self: start;
69 - background: var(--page);
70 + border: 2px solid var(--fg);
71 + padding: 0.45rem;
72 + font-weight: 900;
73 + align-self: start;
74 + background: var(--page);
76 +.grid {
77 + display: grid;
78 + grid-template-columns: minmax(0, 1.15fr) minmax(0, 0.85fr);
71 -.grid { display: grid; grid-template-columns: minmax(0, 1.15fr) minmax(0, .85fr); }
72 80 .section {
73 - padding: clamp(.8rem, 2vw, 1.1rem);
74 - border-bottom: 2px solid var(--fg);
75 - min-width: 0;
81 + padding: clamp(0.8rem, 2vw, 1.1rem);
82 + border-bottom: 2px solid var(--fg);
83 + min-width: 0;
85 +.section:nth-child(odd) {
86 + border-right: 2px solid var(--fg);
77 -.section:nth-child(odd) { border-right: 2px solid var(--fg); }
78 88 .section h2 {
79 - font: 900 .76rem/1 system-ui;
80 - text-transform: uppercase;
81 - letter-spacing: .11em;
82 - margin: 0 0 .75rem;
83 - color: var(--accent);
89 + font: 900 0.76rem / 1 system-ui;
90 + text-transform: uppercase;
91 + letter-spacing: 0.11em;
92 + margin: 0 0 0.75rem;
93 + color: var(--accent);
95 +.section p,
96 +.section li {
97 + font-size: 0.82rem;
98 + line-height: 1.55;
85 -.section p, .section li { font-size: .82rem; line-height: 1.55; }
86 100 .contract {
87 - background: var(--panel);
88 - color: var(--fg);
89 - padding: .8rem;
90 - border: 2px solid var(--fg);
91 - border-left: 7px solid var(--ui-accent);
92 - font-weight: 800;
101 + background: var(--panel);
102 + color: var(--fg);
103 + padding: 0.8rem;
104 + border: 2px solid var(--fg);
105 + border-left: 7px solid var(--ui-accent);
106 + font-weight: 800;
108 +.flow {
109 + display: flex;
110 + align-items: center;
111 + gap: 0.35rem;
112 + flex-wrap: wrap;
94 -.flow { display: flex; align-items: center; gap: .35rem; flex-wrap: wrap; }
95 114 .node {
96 - border: 2px solid var(--fg);
97 - padding: .35rem .5rem;
98 - background: var(--panel);
99 - font-weight: 900;
115 + border: 2px solid var(--fg);
116 + padding: 0.35rem 0.5rem;
117 + background: var(--panel);
118 + font-weight: 900;
120 +.arrow {
121 + font-size: 1.2rem;
122 + color: var(--accent);
101 -.arrow { font-size: 1.2rem; color: var(--accent); }
102 124 .note {
103 - border: 2px dashed var(--focus);
104 - padding: .65rem;
105 - color: var(--focus);
106 - background: var(--panel);
125 + border: 2px dashed var(--focus);
126 + padding: 0.65rem;
127 + color: var(--focus);
128 + background: var(--panel);
108 130 @media (max-width: 560px) {
109 - body { padding: .5rem; }
110 - .doc { box-shadow: 5px 5px 0 var(--ui-accent); }
111 - .mast { grid-template-columns: 1fr; }
112 - .id { justify-self: start; }
113 - .grid { grid-template-columns: 1fr; }
114 - .section:nth-child(odd) { border-right: 0; }
115 - .flow { align-items: stretch; }
116 - .node { flex: 1; text-align: center; }
117 - .arrow { align-self: center; }
131 + body {
132 + padding: 0.5rem;
134 + .doc {
135 + box-shadow: 5px 5px 0 var(--ui-accent);
137 + .mast {
138 + grid-template-columns: 1fr;
140 + .id {
141 + justify-self: start;
143 + .grid {
144 + grid-template-columns: 1fr;
146 + .section:nth-child(odd) {
147 + border-right: 0;
149 + .flow {
150 + align-items: stretch;
152 + .node {
153 + flex: 1;
154 + text-align: center;
156 + .arrow {
157 + align-self: center;
120 161 /* Shared authored-document primitives. */
121 -a { color: var(--focus); font-weight: 800; overflow-wrap: anywhere; }
122 -.document-nav { display: flex; flex-wrap: wrap; gap: .5rem; padding: .8rem; border-bottom: 2px solid var(--fg); }
123 -.metadata { display: grid; grid-template-columns: repeat(auto-fit, minmax(9rem, 1fr)); gap: .5rem; margin: 0; padding: .8rem; background: var(--panel); border: 2px solid var(--fg); }
124 -.metadata dt { color: var(--accent); font-size: .7rem; font-weight: 900; letter-spacing: .12em; text-transform: uppercase; }
125 -.metadata dd { margin: .2rem 0 0; overflow-wrap: anywhere; }
126 -.callout { padding: .75rem; border: 2px solid var(--fg); border-left: 7px solid var(--info); background: var(--panel); }
127 -.callout.important { border-left-color: var(--important); }
128 -.callout.warning { border-left-color: var(--warning); }
129 -.callout.error { border-left-color: var(--error); }
130 -.status { display: inline-block; padding: .15rem .45rem; border: 2px solid currentColor; color: var(--info); font-size: .7rem; font-weight: 900; text-transform: uppercase; }
131 -.status.open, .status.error { color: var(--error); }
132 -.status.fixed { color: var(--focus); }
133 -table { width: 100%; border-collapse: collapse; }
134 -th, td { padding: .6rem; border: 2px solid var(--fg); text-align: left; vertical-align: top; overflow-wrap: anywhere; }
135 -th { background: var(--panel); }
136 -pre, code { background: var(--panel); }
137 -code { padding: .1rem .3rem; overflow-wrap: anywhere; }
138 -pre { max-width: 100%; padding: .8rem; overflow: auto; border-left: 7px solid var(--ui-accent); }
139 -pre code { padding: 0; }
140 -figure { max-width: 100%; margin: 1rem 0; overflow: auto; }
141 -details { border: 2px solid var(--fg); padding: .65rem; }
142 -summary { min-height: 2.75rem; cursor: pointer; font-weight: 900; }
162 +a {
163 + color: var(--focus);
164 + font-weight: 800;
165 + overflow-wrap: anywhere;
167 +.document-nav {
168 + display: flex;
169 + flex-wrap: wrap;
170 + gap: 0.5rem;
171 + padding: 0.8rem;
172 + border-bottom: 2px solid var(--fg);
174 +.metadata {
175 + display: grid;
176 + grid-template-columns: repeat(auto-fit, minmax(9rem, 1fr));
177 + gap: 0.5rem;
178 + margin: 0;
179 + padding: 0.8rem;
180 + background: var(--panel);
181 + border: 2px solid var(--fg);
183 +.metadata dt {
184 + color: var(--accent);
185 + font-size: 0.7rem;
186 + font-weight: 900;
187 + letter-spacing: 0.12em;
188 + text-transform: uppercase;
190 +.metadata dd {
191 + margin: 0.2rem 0 0;
192 + overflow-wrap: anywhere;
194 +.callout {
195 + padding: 0.75rem;
196 + border: 2px solid var(--fg);
197 + border-left: 7px solid var(--info);
198 + background: var(--panel);
200 +.callout.important {
201 + border-left-color: var(--important);
203 +.callout.warning {
204 + border-left-color: var(--warning);
206 +.callout.error {
207 + border-left-color: var(--error);
209 +.status {
210 + display: inline-block;
211 + padding: 0.15rem 0.45rem;
212 + border: 2px solid currentColor;
213 + color: var(--info);
214 + font-size: 0.7rem;
215 + font-weight: 900;
216 + text-transform: uppercase;
218 +.status.open,
219 +.status.error {
220 + color: var(--error);
222 +.status.fixed {
223 + color: var(--focus);
225 +table {
226 + width: 100%;
227 + border-collapse: collapse;
229 +th,
230 +td {
231 + padding: 0.6rem;
232 + border: 2px solid var(--fg);
233 + text-align: left;
234 + vertical-align: top;
235 + overflow-wrap: anywhere;
237 +th {
238 + background: var(--panel);
240 +pre,
241 +code {
242 + background: var(--panel);
244 +code {
245 + padding: 0.1rem 0.3rem;
246 + overflow-wrap: anywhere;
248 +pre {
249 + max-width: 100%;
250 + padding: 0.8rem;
251 + overflow: auto;
252 + border-left: 7px solid var(--ui-accent);
254 +pre code {
255 + padding: 0;
257 +figure {
258 + max-width: 100%;
259 + margin: 1rem 0;
260 + overflow: auto;
262 +details {
263 + border: 2px solid var(--fg);
264 + padding: 0.65rem;
266 +summary {
267 + min-height: 2.75rem;
268 + cursor: pointer;
269 + font-weight: 900;
143 271 @media (max-width: 560px) {
144 - .document-nav a { min-height: 2.75rem; display: inline-flex; align-items: center; }
145 - table, tbody, tr, th, td { display: block; width: 100%; }
146 - th { border-bottom: 0; }
147 - .metadata { grid-template-columns: 1fr; }
272 + .document-nav a {
273 + min-height: 2.75rem;
274 + display: inline-flex;
275 + align-items: center;
277 + table,
278 + tbody,
279 + tr,
280 + th,
281 + td {
282 + display: block;
283 + width: 100%;
285 + th {
286 + border-bottom: 0;
288 + .metadata {
289 + grid-template-columns: 1fr;

extensions/the-system/documents.ts

Modified
5 5 export const STYLE_VERSION = 1;
7 7 export class SystemDocumentError extends Error {
8 - constructor(
9 - readonly code: string,
10 - message: string,
11 - ) {
12 - super(message);
13 - this.name = "SystemDocumentError";
14 - }
8 + constructor(
9 + readonly code: string,
10 + message: string,
11 + ) {
12 + super(message);
13 + this.name = "SystemDocumentError";
14 + }
17 -const nearestMarker = (cwd: string, marker: string, markerExists: (path: string) => boolean) => {
18 - let current = path.resolve(cwd);
19 - while (true) {
20 - if (markerExists(path.join(current, marker))) return current;
21 - const parent = path.dirname(current);
22 - if (parent === current) return undefined;
23 - current = parent;
24 - }
17 +const nearestMarker = (
18 + cwd: string,
19 + marker: string,
20 + markerExists: (path: string) => boolean,
21 +) => {
22 + let current = path.resolve(cwd);
23 + while (true) {
24 + if (markerExists(path.join(current, marker))) return current;
25 + const parent = path.dirname(current);
26 + if (parent === current) return undefined;
27 + current = parent;
28 + }
27 -export function discoverProjectRoot(cwd: string, markerExists = existsSync): string {
28 - const resolvedCwd = path.resolve(cwd);
29 - const jj = nearestMarker(resolvedCwd, ".jj", markerExists);
30 - const git = nearestMarker(resolvedCwd, ".git", markerExists);
31 - if (jj && git && jj !== git) {
32 - throw new SystemDocumentError("root.conflict", `Conflicting project roots: Git ${git}; JJ ${jj}`);
33 - }
34 - return jj ?? git ?? resolvedCwd;
31 +export function discoverProjectRoot(
32 + cwd: string,
33 + markerExists = existsSync,
34 +): string {
35 + const resolvedCwd = path.resolve(cwd);
36 + const jj = nearestMarker(resolvedCwd, ".jj", markerExists);
37 + const git = nearestMarker(resolvedCwd, ".git", markerExists);
38 + if (jj && git && jj !== git) {
39 + throw new SystemDocumentError(
40 + "root.conflict",
41 + `Conflicting project roots: Git ${git}; JJ ${jj}`,
42 + );
43 + }
44 + return jj ?? git ?? resolvedCwd;
37 47 export function resolveGovernedPath(root: string, candidate: string): string {
38 - const normalizedRoot = path.resolve(root);
39 - const target = path.resolve(normalizedRoot, candidate);
40 - const relative = path.relative(normalizedRoot, target);
41 - if (relative === ".." || relative.startsWith(`..${path.sep}`) || path.isAbsolute(relative)) {
42 - throw new SystemDocumentError("path.outside-root", `Path is outside project root: ${candidate}`);
43 - }
44 - return target;
48 + const normalizedRoot = path.resolve(root);
49 + const target = path.resolve(normalizedRoot, candidate);
50 + const relative = path.relative(normalizedRoot, target);
51 + if (
52 + relative === ".." ||
53 + relative.startsWith(`..${path.sep}`) ||
54 + path.isAbsolute(relative)
55 + ) {
56 + throw new SystemDocumentError(
57 + "path.outside-root",
58 + `Path is outside project root: ${candidate}`,
59 + );
60 + }
61 + return target;
47 -export const DOCUMENT_TYPES = ["spec", "roadmap", "plan", "issue", "research"] as const;
64 +export const DOCUMENT_TYPES = [
65 + "spec",
66 + "roadmap",
67 + "plan",
68 + "issue",
69 + "research",
70 +] as const;
48 71 export type DocumentType = (typeof DOCUMENT_TYPES)[number];
49 -export type SystemConfig = Readonly<{ prefix: string; schemaVersion: number; styleVersion: number }>;
72 +export type SystemConfig = Readonly<{
73 + prefix: string;
74 + schemaVersion: number;
75 + styleVersion: number;
76 +}>;
50 77 export type ParsedDocumentId = Readonly<{
51 - id: string;
52 - prefix: string;
53 - type: DocumentType;
54 - sequence: number;
78 + id: string;
79 + prefix: string;
80 + type: DocumentType;
81 + sequence: number;
56 83 export type SpecMetadata = Readonly<{ id: string; type: "spec" }>;
57 -export type RoadmapMetadata = Readonly<{ id: string; type: "roadmap"; spec: string }>;
84 +export type RoadmapMetadata = Readonly<{
85 + id: string;
86 + type: "roadmap";
87 + spec: string;
88 +}>;
58 89 export type PlanMetadata = Readonly<{
59 - id: string;
60 - type: "plan";
61 - spec: string;
62 - roadmap?: string;
63 - phase?: number;
90 + id: string;
91 + type: "plan";
92 + spec: string;
93 + roadmap?: string;
94 + phase?: number;
65 96 export type IssueMetadata = Readonly<{
66 - id: string;
67 - type: "issue";
68 - status: "open" | "fixed";
69 - specs: readonly string[];
97 + id: string;
98 + type: "issue";
99 + status: "open" | "fixed";
100 + specs: readonly string[];
71 102 export type ResearchMetadata = Readonly<{
72 - id: string;
73 - type: "research";
74 - capturedAt: string;
75 - sources?: readonly string[];
103 + id: string;
104 + type: "research";
105 + capturedAt: string;
106 + sources?: readonly string[];
77 108 export type DocumentMetadata =
78 - | SpecMetadata
79 - | RoadmapMetadata
80 - | PlanMetadata
81 - | IssueMetadata
82 - | ResearchMetadata;
109 + | SpecMetadata
110 + | RoadmapMetadata
111 + | PlanMetadata
112 + | IssueMetadata
113 + | ResearchMetadata;
84 115 const PREFIX = /^[A-Z][A-Z0-9]{1,7}$/;
85 116 const SLUG = "[a-z0-9]+(?:-[a-z0-9]+)*";
86 -const TYPE_BY_TOKEN = new Map(DOCUMENT_TYPES.map((type) => [type.toUpperCase(), type]));
117 +const TYPE_BY_TOKEN = new Map(
118 + DOCUMENT_TYPES.map((type) => [type.toUpperCase(), type]),
87 120 const DIRECTORY_BY_TYPE: Readonly<Record<DocumentType, string>> = {
88 - spec: "specs",
89 - roadmap: "roadmaps",
90 - plan: "plans",
91 - issue: "issues",
92 - research: "research",
121 + spec: "specs",
122 + roadmap: "roadmaps",
123 + plan: "plans",
124 + issue: "issues",
125 + research: "research",
95 -const objectValue = (value: unknown, label: string): Record<string, unknown> => {
96 - if (typeof value !== "object" || value === null || Array.isArray(value)) {
97 - throw new SystemDocumentError("json.shape", `${label} must be a JSON object`);
98 - }
99 - return value as Record<string, unknown>;
128 +const objectValue = (
129 + value: unknown,
130 + label: string,
131 +): Record<string, unknown> => {
132 + if (typeof value !== "object" || value === null || Array.isArray(value)) {
133 + throw new SystemDocumentError(
134 + "json.shape",
135 + `${label} must be a JSON object`,
136 + );
138 + return value as Record<string, unknown>;
101 140 const exactKeys = (
102 - value: Record<string, unknown>,
103 - required: readonly string[],
104 - optional: readonly string[] = [],
141 + value: Record<string, unknown>,
142 + required: readonly string[],
143 + optional: readonly string[] = [],
105 144 ) => {
106 - const actual = Object.keys(value).sort();
107 - const allowed = new Set([...required, ...optional]);
108 - if (required.some((key) => !(key in value)) || actual.some((key) => !allowed.has(key))) {
109 - throw new SystemDocumentError(
110 - "json.keys",
111 - `Expected keys ${[...required, ...optional].sort().join(", ")}; received ${actual.join(", ")}`,
112 - );
113 - }
145 + const actual = Object.keys(value).sort();
146 + const allowed = new Set([...required, ...optional]);
147 + if (
148 + required.some((key) => !(key in value)) ||
149 + actual.some((key) => !allowed.has(key))
150 + ) {
151 + throw new SystemDocumentError(
152 + "json.keys",
153 + `Expected keys ${[...required, ...optional].sort().join(", ")}; received ${actual.join(", ")}`,
154 + );
115 157 const positiveInteger = (value: unknown) =>
116 - typeof value === "number" && Number.isInteger(value) && value > 0;
158 + typeof value === "number" && Number.isInteger(value) && value > 0;
118 160 export function parseSystemConfig(source: string): SystemConfig {
119 - let parsed: unknown;
120 - try {
121 - parsed = JSON.parse(source);
122 - } catch {
123 - throw new SystemDocumentError("config.invalid-json", "Invalid config JSON");
124 - }
125 - const value = objectValue(parsed, "Config");
126 - exactKeys(value, ["prefix", "schemaVersion", "styleVersion"]);
127 - if (typeof value.prefix !== "string" || !PREFIX.test(value.prefix)) {
128 - throw new SystemDocumentError("config.prefix", "Invalid project prefix");
129 - }
130 - if (!positiveInteger(value.schemaVersion) || !positiveInteger(value.styleVersion)) {
131 - throw new SystemDocumentError(
132 - "config.version",
133 - "Schema and style versions must be positive integers",
134 - );
135 - }
136 - return {
137 - prefix: value.prefix,
138 - schemaVersion: value.schemaVersion as number,
139 - styleVersion: value.styleVersion as number,
140 - };
161 + let parsed: unknown;
162 + try {
163 + parsed = JSON.parse(source);
164 + } catch {
165 + throw new SystemDocumentError("config.invalid-json", "Invalid config JSON");
167 + const value = objectValue(parsed, "Config");
168 + exactKeys(value, ["prefix", "schemaVersion", "styleVersion"]);
169 + if (typeof value.prefix !== "string" || !PREFIX.test(value.prefix)) {
170 + throw new SystemDocumentError("config.prefix", "Invalid project prefix");
172 + if (
173 + !positiveInteger(value.schemaVersion) ||
174 + !positiveInteger(value.styleVersion)
175 + ) {
176 + throw new SystemDocumentError(
177 + "config.version",
178 + "Schema and style versions must be positive integers",
179 + );
181 + return {
182 + prefix: value.prefix,
183 + schemaVersion: value.schemaVersion as number,
184 + styleVersion: value.styleVersion as number,
185 + };
143 -export function parseDocumentId(source: string, expectedPrefix?: string): ParsedDocumentId {
144 - const match = /^([A-Z][A-Z0-9]{1,7})-(SPEC|ROADMAP|PLAN|ISSUE|RESEARCH)-([0-9]{3,})$/.exec(
145 - source,
146 - );
147 - const sequence = match ? Number(match[3]) : 0;
148 - const canonical = sequence > 0 ? String(sequence).padStart(3, "0") : "";
149 - if (!match || match[3] !== canonical) {
150 - throw new SystemDocumentError("id.invalid", `Invalid document ID: ${source}`);
151 - }
152 - if (expectedPrefix && match[1] !== expectedPrefix) {
153 - throw new SystemDocumentError(
154 - "id.prefix",
155 - `Document ID must use prefix ${expectedPrefix}: ${source}`,
156 - );
157 - }
158 - return {
159 - id: source,
160 - prefix: match[1],
161 - type: TYPE_BY_TOKEN.get(match[2]) as DocumentType,
162 - sequence,
163 - };
188 +export function parseDocumentId(
189 + source: string,
190 + expectedPrefix?: string,
191 +): ParsedDocumentId {
192 + const match =
193 + /^([A-Z][A-Z0-9]{1,7})-(SPEC|ROADMAP|PLAN|ISSUE|RESEARCH)-([0-9]{3,})$/.exec(
194 + source,
195 + );
196 + const sequence = match ? Number(match[3]) : 0;
197 + const canonical = sequence > 0 ? String(sequence).padStart(3, "0") : "";
198 + if (!match || match[3] !== canonical) {
199 + throw new SystemDocumentError(
200 + "id.invalid",
201 + `Invalid document ID: ${source}`,
202 + );
204 + if (expectedPrefix && match[1] !== expectedPrefix) {
205 + throw new SystemDocumentError(
206 + "id.prefix",
207 + `Document ID must use prefix ${expectedPrefix}: ${source}`,
208 + );
210 + return {
211 + id: source,
212 + prefix: match[1],
213 + type: TYPE_BY_TOKEN.get(match[2]) as DocumentType,
214 + sequence,
215 + };
166 218 export function validateFilename(
167 - filename: string,
168 - metadata: DocumentMetadata,
169 - prefix: string,
219 + filename: string,
220 + metadata: DocumentMetadata,
221 + prefix: string,
170 222 ): void {
171 - const parsed = parseDocumentId(metadata.id, prefix);
172 - const expectedDirectory = DIRECTORY_BY_TYPE[metadata.type];
173 - const directory = path.basename(path.dirname(filename));
174 - const pattern = new RegExp(`^${metadata.id}-${SLUG}\\.html$`);
175 - if (
176 - parsed.type !== metadata.type ||
177 - directory !== expectedDirectory ||
178 - !pattern.test(path.basename(filename))
179 - ) {
180 - throw new SystemDocumentError(
181 - "document.filename",
182 - `Filename mismatch for ${metadata.id}: ${filename}`,
183 - );
184 - }
223 + const parsed = parseDocumentId(metadata.id, prefix);
224 + const expectedDirectory = DIRECTORY_BY_TYPE[metadata.type];
225 + const directory = path.basename(path.dirname(filename));
226 + const pattern = new RegExp(`^${metadata.id}-${SLUG}\\.html$`);
227 + if (
228 + parsed.type !== metadata.type ||
229 + directory !== expectedDirectory ||
230 + !pattern.test(path.basename(filename))
231 + ) {
232 + throw new SystemDocumentError(
233 + "document.filename",
234 + `Filename mismatch for ${metadata.id}: ${filename}`,
235 + );
187 239 const duplicateTopLevelKeys = (source: string): string[] => {
188 - const keys: string[] = [];
189 - const duplicates = new Set<string>();
190 - let depth = 0;
191 - let index = 0;
192 - while (index < source.length) {
193 - const character = source[index];
194 - if (character === "{") { depth += 1; index += 1; continue; }
195 - if (character === "}") { depth -= 1; index += 1; continue; }
196 - if (character !== '"') { index += 1; continue; }
197 - const start = index;
198 - index += 1;
199 - let escaped = false;
200 - while (index < source.length) {
201 - const current = source[index++];
202 - if (!escaped && current === '"') break;
203 - escaped = !escaped && current === "\\";
204 - if (current !== "\\") escaped = false;
205 - }
206 - if (depth !== 1) continue;
207 - let cursor = index;
208 - while (/\s/.test(source[cursor] ?? "")) cursor += 1;
209 - if (source[cursor] !== ":") continue;
210 - const key = JSON.parse(source.slice(start, index)) as string;
211 - if (keys.includes(key)) duplicates.add(key);
212 - keys.push(key);
213 - }
214 - return [...duplicates].sort();
240 + const keys: string[] = [];
241 + const duplicates = new Set<string>();
242 + let depth = 0;
243 + let index = 0;
244 + while (index < source.length) {
245 + const character = source[index];
246 + if (character === "{") {
247 + depth += 1;
248 + index += 1;
249 + continue;
251 + if (character === "}") {
252 + depth -= 1;
253 + index += 1;
254 + continue;
256 + if (character !== '"') {
257 + index += 1;
258 + continue;
260 + const start = index;
261 + index += 1;
262 + let escaped = false;
263 + while (index < source.length) {
264 + const current = source[index++];
265 + if (!escaped && current === '"') break;
266 + escaped = !escaped && current === "\\";
267 + if (current !== "\\") escaped = false;
269 + if (depth !== 1) continue;
270 + let cursor = index;
271 + while (/\s/.test(source[cursor] ?? "")) cursor += 1;
272 + if (source[cursor] !== ":") continue;
273 + const key = JSON.parse(source.slice(start, index)) as string;
274 + if (keys.includes(key)) duplicates.add(key);
275 + keys.push(key);
277 + return [...duplicates].sort();
217 280 const stringArray = (value: unknown, label: string): string[] => {
218 - if (!Array.isArray(value) || value.some((item) => typeof item !== "string")) throw new SystemDocumentError("metadata.value", `${label} must be a string array`);
219 - if (new Set(value).size !== value.length) throw new SystemDocumentError("metadata.duplicate", `${label} must contain unique values`);
220 - return value;
281 + if (!Array.isArray(value) || value.some((item) => typeof item !== "string"))
282 + throw new SystemDocumentError(
283 + "metadata.value",
284 + `${label} must be a string array`,
285 + );
286 + if (new Set(value).size !== value.length)
287 + throw new SystemDocumentError(
288 + "metadata.duplicate",
289 + `${label} must contain unique values`,
290 + );
291 + return value;
222 293 const validDate = (value: unknown) => {
223 - if (typeof value !== "string" || !/^\d{4}-\d{2}-\d{2}$/.test(value)) return false;
224 - const date = new Date(`${value}T00:00:00Z`);
225 - return !Number.isNaN(date.valueOf()) && date.toISOString().slice(0, 10) === value;
294 + if (typeof value !== "string" || !/^\d{4}-\d{2}-\d{2}$/.test(value))
295 + return false;
296 + const date = new Date(`${value}T00:00:00Z`);
297 + return (
298 + !Number.isNaN(date.valueOf()) && date.toISOString().slice(0, 10) === value
299 + );
227 301 const httpsUrl = (value: string) => {
228 - try { return new URL(value).protocol === "https:"; } catch { return false; }
302 + try {
303 + return new URL(value).protocol === "https:";
304 + } catch {
305 + return false;
230 -const metadataScripts = (html: string) => [...html.matchAll(/<script\b([^>]*)>([\s\S]*?)<\/script\s*>/gi)]
231 - .filter((match) => /\bid\s*=\s*(["'])system-meta\1/i.test(match[1]) && /\btype\s*=\s*(["'])application\/json\1/i.test(match[1]));
308 +const metadataScripts = (html: string) =>
309 + [...html.matchAll(/<script\b([^>]*)>([\s\S]*?)<\/script\s*>/gi)].filter(
310 + (match) =>
311 + /\bid\s*=\s*(["'])system-meta\1/i.test(match[1]) &&
312 + /\btype\s*=\s*(["'])application\/json\1/i.test(match[1]),
313 + );
233 -export function parseDocumentMetadata(html: string, prefix: string): DocumentMetadata {
234 - const blocks = metadataScripts(html);
235 - if (blocks.length !== 1) throw new SystemDocumentError("metadata.block", `Expected exactly one system-meta block; received ${blocks.length}`);
236 - const json = blocks[0][2].trim();
237 - const duplicates = duplicateTopLevelKeys(json);
238 - if (duplicates.length) throw new SystemDocumentError("metadata.duplicate-key", `Duplicate metadata keys: ${duplicates.join(", ")}`);
239 - let parsed: unknown;
240 - try { parsed = JSON.parse(json); } catch { throw new SystemDocumentError("metadata.invalid-json", "Invalid system metadata JSON"); }
241 - const value = objectValue(parsed, "Metadata");
242 - if (typeof value.id !== "string" || typeof value.type !== "string") throw new SystemDocumentError("metadata.identity", "Metadata requires string id and type");
243 - const ownId = parseDocumentId(value.id, prefix);
244 - if (ownId.type !== value.type) throw new SystemDocumentError("metadata.identity", `Metadata ID/type mismatch: ${value.id} / ${value.type}`);
245 - const reference = (key: string) => {
246 - if (typeof value[key] !== "string") throw new SystemDocumentError("metadata.value", `${key} must be a document ID`);
247 - parseDocumentId(value[key] as string, prefix);
248 - return value[key] as string;
249 - };
250 - switch (value.type) {
251 - case "spec":
252 - exactKeys(value, ["id", "type"]);
253 - return { id: value.id, type: "spec" };
254 - case "roadmap":
255 - exactKeys(value, ["id", "type", "spec"]);
256 - return { id: value.id, type: "roadmap", spec: reference("spec") };
257 - case "plan": {
258 - exactKeys(value, ["id", "type", "spec"], ["roadmap", "phase"]);
259 - const hasRoadmap = "roadmap" in value;
260 - const hasPhase = "phase" in value;
261 - if (hasRoadmap !== hasPhase || (hasPhase && !positiveInteger(value.phase))) throw new SystemDocumentError("metadata.plan-phase", "Plan roadmap and positive phase must appear together");
262 - return hasRoadmap ? { id: value.id, type: "plan", spec: reference("spec"), roadmap: reference("roadmap"), phase: value.phase as number } : { id: value.id, type: "plan", spec: reference("spec") };
263 - }
264 - case "issue": {
265 - exactKeys(value, ["id", "type", "status", "specs"]);
266 - if (value.status !== "open" && value.status !== "fixed") throw new SystemDocumentError("metadata.status", "Issue status must be open or fixed");
267 - const specs = stringArray(value.specs, "specs");
268 - for (const id of specs) parseDocumentId(id, prefix);
269 - return { id: value.id, type: "issue", status: value.status, specs };
270 - }
271 - case "research": {
272 - exactKeys(value, ["id", "type", "capturedAt"], ["sources"]);
273 - if (!validDate(value.capturedAt)) throw new SystemDocumentError("metadata.date", "capturedAt must be a valid ISO date");
274 - const sources = "sources" in value ? stringArray(value.sources, "sources") : undefined;
275 - if (sources?.some((source) => !httpsUrl(source))) throw new SystemDocumentError("metadata.source", "Research sources must use HTTPS");
276 - return sources ? { id: value.id, type: "research", capturedAt: value.capturedAt as string, sources } : { id: value.id, type: "research", capturedAt: value.capturedAt as string };
277 - }
278 - default:
279 - throw new SystemDocumentError("metadata.type", `Unsupported metadata type: ${value.type}`);
280 - }
315 +export function parseDocumentMetadata(
316 + html: string,
317 + prefix: string,
318 +): DocumentMetadata {
319 + const blocks = metadataScripts(html);
320 + if (blocks.length !== 1)
321 + throw new SystemDocumentError(
322 + "metadata.block",
323 + `Expected exactly one system-meta block; received ${blocks.length}`,
324 + );
325 + const json = blocks[0][2].trim();
326 + const duplicates = duplicateTopLevelKeys(json);
327 + if (duplicates.length)
328 + throw new SystemDocumentError(
329 + "metadata.duplicate-key",
330 + `Duplicate metadata keys: ${duplicates.join(", ")}`,
331 + );
332 + let parsed: unknown;
333 + try {
334 + parsed = JSON.parse(json);
335 + } catch {
336 + throw new SystemDocumentError(
337 + "metadata.invalid-json",
338 + "Invalid system metadata JSON",
339 + );
341 + const value = objectValue(parsed, "Metadata");
342 + if (typeof value.id !== "string" || typeof value.type !== "string")
343 + throw new SystemDocumentError(
344 + "metadata.identity",
345 + "Metadata requires string id and type",
346 + );
347 + const ownId = parseDocumentId(value.id, prefix);
348 + if (ownId.type !== value.type)
349 + throw new SystemDocumentError(
350 + "metadata.identity",
351 + `Metadata ID/type mismatch: ${value.id} / ${value.type}`,
352 + );
353 + const reference = (key: string) => {
354 + if (typeof value[key] !== "string")
355 + throw new SystemDocumentError(
356 + "metadata.value",
357 + `${key} must be a document ID`,
358 + );
359 + parseDocumentId(value[key] as string, prefix);
360 + return value[key] as string;
361 + };
362 + switch (value.type) {
363 + case "spec":
364 + exactKeys(value, ["id", "type"]);
365 + return { id: value.id, type: "spec" };
366 + case "roadmap":
367 + exactKeys(value, ["id", "type", "spec"]);
368 + return { id: value.id, type: "roadmap", spec: reference("spec") };
369 + case "plan": {
370 + exactKeys(value, ["id", "type", "spec"], ["roadmap", "phase"]);
371 + const hasRoadmap = "roadmap" in value;
372 + const hasPhase = "phase" in value;
373 + if (
374 + hasRoadmap !== hasPhase ||
375 + (hasPhase && !positiveInteger(value.phase))
377 + throw new SystemDocumentError(
378 + "metadata.plan-phase",
379 + "Plan roadmap and positive phase must appear together",
380 + );
381 + return hasRoadmap
382 + ? {
383 + id: value.id,
384 + type: "plan",
385 + spec: reference("spec"),
386 + roadmap: reference("roadmap"),
387 + phase: value.phase as number,
389 + : { id: value.id, type: "plan", spec: reference("spec") };
391 + case "issue": {
392 + exactKeys(value, ["id", "type", "status", "specs"]);
393 + if (value.status !== "open" && value.status !== "fixed")
394 + throw new SystemDocumentError(
395 + "metadata.status",
396 + "Issue status must be open or fixed",
397 + );
398 + const specs = stringArray(value.specs, "specs");
399 + for (const id of specs) parseDocumentId(id, prefix);
400 + return { id: value.id, type: "issue", status: value.status, specs };
402 + case "research": {
403 + exactKeys(value, ["id", "type", "capturedAt"], ["sources"]);
404 + if (!validDate(value.capturedAt))
405 + throw new SystemDocumentError(
406 + "metadata.date",
407 + "capturedAt must be a valid ISO date",
408 + );
409 + const sources =
410 + "sources" in value ? stringArray(value.sources, "sources") : undefined;
411 + if (sources?.some((source) => !httpsUrl(source)))
412 + throw new SystemDocumentError(
413 + "metadata.source",
414 + "Research sources must use HTTPS",
415 + );
416 + return sources
417 + ? {
418 + id: value.id,
419 + type: "research",
420 + capturedAt: value.capturedAt as string,
421 + sources,
423 + : {
424 + id: value.id,
425 + type: "research",
426 + capturedAt: value.capturedAt as string,
427 + };
429 + default:
430 + throw new SystemDocumentError(
431 + "metadata.type",
432 + `Unsupported metadata type: ${value.type}`,
433 + );
283 -export type Diagnostic = Readonly<{ code: string; path: string; message: string }>;
284 -const diagnostic = (code: string, path: string, message: string): Diagnostic => ({ code, path, message });
285 -const count = (source: string, expression: RegExp) => [...source.matchAll(expression)].length;
437 +export type Diagnostic = Readonly<{
438 + code: string;
439 + path: string;
440 + message: string;
441 +}>;
442 +const diagnostic = (
443 + code: string,
444 + path: string,
445 + message: string,
446 +): Diagnostic => ({ code, path, message });
447 +const count = (source: string, expression: RegExp) =>
448 + [...source.matchAll(expression)].length;
287 -export function validateAuthoredHtml(filename: string, html: string): readonly Diagnostic[] {
288 - const findings: Diagnostic[] = [];
289 - const requireOne = (code: string, expression: RegExp, message: string) => {
290 - if (count(html, expression) !== 1) findings.push(diagnostic(code, filename, message));
291 - };
292 - if (!/^<!doctype html>/i.test(html.trimStart())) findings.push(diagnostic("document.doctype", filename, "Document must begin with HTML doctype"));
293 - requireOne("document.language", /<html\b[^>]*\blang\s*=\s*(["'])en\1[^>]*>/gi, "Document requires one html lang=en root");
294 - requireOne("document.charset", /<meta\b[^>]*\bcharset\s*=\s*(["'])?utf-8\1[^>]*>/gi, "Document requires one UTF-8 charset meta");
295 - requireOne("document.viewport", /<meta\b[^>]*\bname\s*=\s*(["'])viewport\1[^>]*\bcontent\s*=\s*(["'])width=device-width,\s*initial-scale=1\2[^>]*>/gi, "Document requires one viewport meta");
296 - requireOne("document.title", /<title>\s*[^<\s][^<]*<\/title>/gi, "Document requires one nonempty title");
297 - requireOne("document.stylesheet", /<link\b(?=[^>]*\brel\s*=\s*(["'])stylesheet\1)(?=[^>]*\bhref\s*=\s*(["'])\.\.\/system\.css\2)[^>]*>/gi, "Document requires exactly ../system.css");
298 - if (count(html, /<link\b[^>]*\brel\s*=\s*(["'])stylesheet\1[^>]*>/gi) !== 1) findings.push(diagnostic("document.stylesheet", filename, "Additional or missing stylesheets are forbidden"));
299 - for (const tag of ["header", "main", "section"] as const) requireOne("document.semantic-shell", new RegExp(`<${tag}\\b`, "gi"), `Document requires one ${tag} element`);
300 - if (/<\/?(?:iframe|object|embed)\b/i.test(html)) findings.push(diagnostic("document.forbidden-tag", filename, "iframe, object, and embed are forbidden"));
301 - if (/<meta\b[^>]*\bhttp-equiv\s*=\s*(["'])refresh\1/i.test(html)) findings.push(diagnostic("document.meta-refresh", filename, "Meta refresh is forbidden"));
302 - if (/\son[a-z]+\s*=/i.test(html)) findings.push(diagnostic("document.event-handler", filename, "Event-handler attributes are forbidden"));
303 - if (/\b(?:href|src|action|formaction|xlink:href)\s*=\s*(["'])\s*(?:javascript|vbscript|data):/i.test(html)) findings.push(diagnostic("document.executable-url", filename, "Executable URL schemes are forbidden"));
304 - if (/<script\b[^>]*\bsrc\s*=/i.test(html)) findings.push(diagnostic("document.external-script", filename, "External script sources are forbidden"));
305 - if (/<(?:img|audio|video|source|track)\b[^>]*\bsrc\s*=\s*(["'])https?:/i.test(html)) findings.push(diagnostic("document.remote-resource", filename, "Remote media resources are forbidden"));
306 - if (/(?:@import|url\s*\(\s*["']?\s*(?:https?:|data:))/i.test(html)) findings.push(diagnostic("document.css-resource", filename, "CSS imports and remote/data URLs are forbidden"));
307 - const executable = [...html.matchAll(/<script\b([^>]*)>([\s\S]*?)<\/script\s*>/gi)]
308 - .filter((match) => !/\btype\s*=\s*(["'])application\/json\1/i.test(match[1]))
309 - .map((match) => match[2]).join("\n");
310 - if (/\b(?:fetch|XMLHttpRequest|WebSocket|EventSource|importScripts|localStorage|sessionStorage|indexedDB)\b/.test(executable) || /\bimport\s*\(/.test(executable)) findings.push(diagnostic("document.active-api", filename, "Network, import, and browser storage APIs are forbidden"));
311 - return findings.sort(compareDiagnostics);
450 +export function validateAuthoredHtml(
451 + filename: string,
452 + html: string,
453 +): readonly Diagnostic[] {
454 + const findings: Diagnostic[] = [];
455 + const requireOne = (code: string, expression: RegExp, message: string) => {
456 + if (count(html, expression) !== 1)
457 + findings.push(diagnostic(code, filename, message));
458 + };
459 + if (!/^<!doctype html>/i.test(html.trimStart()))
460 + findings.push(
461 + diagnostic(
462 + "document.doctype",
463 + filename,
464 + "Document must begin with HTML doctype",
465 + ),
466 + );
467 + requireOne(
468 + "document.language",
469 + /<html\b[^>]*\blang\s*=\s*(["'])en\1[^>]*>/gi,
470 + "Document requires one html lang=en root",
471 + );
472 + requireOne(
473 + "document.charset",
474 + /<meta\b[^>]*\bcharset\s*=\s*(["'])?utf-8\1[^>]*>/gi,
475 + "Document requires one UTF-8 charset meta",
476 + );
477 + requireOne(
478 + "document.viewport",
479 + /<meta\b[^>]*\bname\s*=\s*(["'])viewport\1[^>]*\bcontent\s*=\s*(["'])width=device-width,\s*initial-scale=1\2[^>]*>/gi,
480 + "Document requires one viewport meta",
481 + );
482 + requireOne(
483 + "document.title",
484 + /<title>\s*[^<\s][^<]*<\/title>/gi,
485 + "Document requires one nonempty title",
486 + );
487 + requireOne(
488 + "document.stylesheet",
489 + /<link\b(?=[^>]*\brel\s*=\s*(["'])stylesheet\1)(?=[^>]*\bhref\s*=\s*(["'])\.\.\/system\.css\2)[^>]*>/gi,
490 + "Document requires exactly ../system.css",
491 + );
492 + if (count(html, /<link\b[^>]*\brel\s*=\s*(["'])stylesheet\1[^>]*>/gi) !== 1)
493 + findings.push(
494 + diagnostic(
495 + "document.stylesheet",
496 + filename,
497 + "Additional or missing stylesheets are forbidden",
498 + ),
499 + );
500 + for (const tag of ["header", "main", "section"] as const)
501 + requireOne(
502 + "document.semantic-shell",
503 + new RegExp(`<${tag}\\b`, "gi"),
504 + `Document requires one ${tag} element`,
505 + );
506 + if (/<\/?(?:iframe|object|embed)\b/i.test(html))
507 + findings.push(
508 + diagnostic(
509 + "document.forbidden-tag",
510 + filename,
511 + "iframe, object, and embed are forbidden",
512 + ),
513 + );
514 + if (/<meta\b[^>]*\bhttp-equiv\s*=\s*(["'])refresh\1/i.test(html))
515 + findings.push(
516 + diagnostic(
517 + "document.meta-refresh",
518 + filename,
519 + "Meta refresh is forbidden",
520 + ),
521 + );
522 + if (/\son[a-z]+\s*=/i.test(html))
523 + findings.push(
524 + diagnostic(
525 + "document.event-handler",
526 + filename,
527 + "Event-handler attributes are forbidden",
528 + ),
529 + );
530 + if (
531 + /\b(?:href|src|action|formaction|xlink:href)\s*=\s*(["'])\s*(?:javascript|vbscript|data):/i.test(
532 + html,
535 + findings.push(
536 + diagnostic(
537 + "document.executable-url",
538 + filename,
539 + "Executable URL schemes are forbidden",
540 + ),
541 + );
542 + if (/<script\b[^>]*\bsrc\s*=/i.test(html))
543 + findings.push(
544 + diagnostic(
545 + "document.external-script",
546 + filename,
547 + "External script sources are forbidden",
548 + ),
549 + );
550 + if (
551 + /<(?:img|audio|video|source|track)\b[^>]*\bsrc\s*=\s*(["'])https?:/i.test(
552 + html,
555 + findings.push(
556 + diagnostic(
557 + "document.remote-resource",
558 + filename,
559 + "Remote media resources are forbidden",
560 + ),
561 + );
562 + if (/(?:@import|url\s*\(\s*["']?\s*(?:https?:|data:))/i.test(html))
563 + findings.push(
564 + diagnostic(
565 + "document.css-resource",
566 + filename,
567 + "CSS imports and remote/data URLs are forbidden",
568 + ),
569 + );
570 + const executable = [
571 + ...html.matchAll(/<script\b([^>]*)>([\s\S]*?)<\/script\s*>/gi),
573 + .filter(
574 + (match) => !/\btype\s*=\s*(["'])application\/json\1/i.test(match[1]),
576 + .map((match) => match[2])
577 + .join("\n");
578 + if (
579 + /\b(?:fetch|XMLHttpRequest|WebSocket|EventSource|importScripts|localStorage|sessionStorage|indexedDB)\b/.test(
580 + executable,
581 + ) ||
582 + /\bimport\s*\(/.test(executable)
584 + findings.push(
585 + diagnostic(
586 + "document.active-api",
587 + filename,
588 + "Network, import, and browser storage APIs are forbidden",
589 + ),
590 + );
591 + return findings.sort(compareDiagnostics);
314 594 const compareDiagnostics = (left: Diagnostic, right: Diagnostic) =>
315 - left.path.localeCompare(right.path) || left.code.localeCompare(right.code) || left.message.localeCompare(right.message);
595 + left.path.localeCompare(right.path) ||
596 + left.code.localeCompare(right.code) ||
597 + left.message.localeCompare(right.message);
317 599 export type DocumentSource = Readonly<{ path: string; html: string }>;
318 -export type DocumentRecord = Readonly<{ path: string; metadata: DocumentMetadata }>;
319 -export type DocumentIndex = Readonly<{ documents: readonly DocumentRecord[]; diagnostics: readonly Diagnostic[] }>;
600 +export type DocumentRecord = Readonly<{
601 + path: string;
602 + metadata: DocumentMetadata;
603 +}>;
604 +export type DocumentIndex = Readonly<{
605 + documents: readonly DocumentRecord[];
606 + diagnostics: readonly Diagnostic[];
607 +}>;
321 -const references = (metadata: DocumentMetadata): readonly [string, "spec" | "roadmap"][] => {
322 - switch (metadata.type) {
323 - case "roadmap": return [[metadata.spec, "spec"]];
324 - case "plan": return [[metadata.spec, "spec"], ...(metadata.roadmap ? [[metadata.roadmap, "roadmap"] as const] : [])];
325 - case "issue": return metadata.specs.map((id) => [id, "spec"] as const);
326 - default: return [];
327 - }
609 +const references = (
610 + metadata: DocumentMetadata,
611 +): readonly (readonly [string, "spec" | "roadmap"])[] => {
612 + switch (metadata.type) {
613 + case "roadmap":
614 + return [[metadata.spec, "spec"]];
615 + case "plan":
616 + return [
617 + [metadata.spec, "spec"],
618 + ...(metadata.roadmap ? [[metadata.roadmap, "roadmap"] as const] : []),
619 + ];
620 + case "issue":
621 + return metadata.specs.map((id) => [id, "spec"] as const);
622 + default:
623 + return [];
330 -export function indexDocuments(sources: readonly DocumentSource[], prefix: string): DocumentIndex {
331 - const documents: DocumentRecord[] = [];
332 - const diagnostics: Diagnostic[] = [];
333 - for (const item of [...sources].sort((left, right) => left.path.localeCompare(right.path))) {
334 - diagnostics.push(...validateAuthoredHtml(item.path, item.html));
335 - try {
336 - const metadata = parseDocumentMetadata(item.html, prefix);
337 - try { validateFilename(item.path, metadata, prefix); }
338 - catch (error) { diagnostics.push(diagnostic("document.filename", item.path, (error as Error).message)); }
339 - documents.push({ path: item.path, metadata });
340 - } catch (error) {
341 - const value = error as SystemDocumentError;
342 - diagnostics.push(diagnostic("document.metadata", item.path, `${value.code}: ${value.message}`));
343 - }
344 - }
345 - const groups = new Map<string, DocumentRecord[]>();
346 - for (const document of documents) groups.set(document.metadata.id, [...(groups.get(document.metadata.id) ?? []), document]);
347 - for (const [id, records] of groups) {
348 - if (records.length > 1) {
349 - const paths = records.map((record) => record.path).sort();
350 - for (const record of records) diagnostics.push(diagnostic("graph.duplicate-id", record.path, `Duplicate ID ${id}: ${paths.join(", ")}`));
351 - }
352 - }
353 - const unique = new Map([...groups].filter(([, records]) => records.length === 1).map(([id, records]) => [id, records[0]]));
354 - for (const document of documents) {
355 - for (const [targetId, expectedType] of references(document.metadata)) {
356 - const referencedType = parseDocumentId(targetId, prefix).type;
357 - const target = unique.get(targetId);
358 - if (referencedType !== expectedType) {
359 - diagnostics.push(
360 - diagnostic(
361 - "graph.forbidden-edge",
362 - document.path,
363 - `${document.metadata.id} must reference ${expectedType}; ${targetId} is ${referencedType}`,
364 - ),
365 - );
366 - } else if (!target) {
367 - diagnostics.push(
368 - diagnostic(
369 - "graph.dangling-reference",
370 - document.path,
371 - `${document.metadata.id} references missing ${targetId}`,
372 - ),
373 - );
374 - } else if (target.metadata.type !== expectedType) {
375 - diagnostics.push(
376 - diagnostic(
377 - "graph.forbidden-edge",
378 - document.path,
379 - `${document.metadata.id} must reference ${expectedType}; ${targetId} is ${target.metadata.type}`,
380 - ),
381 - );
382 - }
383 - }
384 - if (document.metadata.type === "plan" && document.metadata.roadmap) {
385 - const roadmap = unique.get(document.metadata.roadmap);
386 - if (roadmap?.metadata.type === "roadmap" && roadmap.metadata.spec !== document.metadata.spec) {
387 - diagnostics.push(diagnostic("graph.forbidden-edge", document.path, `${document.metadata.roadmap} belongs to ${roadmap.metadata.spec}, not ${document.metadata.spec}`));
388 - }
389 - }
390 - }
391 - return { documents, diagnostics: diagnostics.sort(compareDiagnostics) };
627 +export function indexDocuments(
628 + sources: readonly DocumentSource[],
629 + prefix: string,
630 +): DocumentIndex {
631 + const documents: DocumentRecord[] = [];
632 + const diagnostics: Diagnostic[] = [];
633 + for (const item of [...sources].sort((left, right) =>
634 + left.path.localeCompare(right.path),
635 + )) {
636 + diagnostics.push(...validateAuthoredHtml(item.path, item.html));
637 + try {
638 + const metadata = parseDocumentMetadata(item.html, prefix);
639 + try {
640 + validateFilename(item.path, metadata, prefix);
641 + } catch (error) {
642 + diagnostics.push(
643 + diagnostic("document.filename", item.path, (error as Error).message),
644 + );
646 + documents.push({ path: item.path, metadata });
647 + } catch (error) {
648 + const value = error as SystemDocumentError;
649 + diagnostics.push(
650 + diagnostic(
651 + "document.metadata",
652 + item.path,
653 + `${value.code}: ${value.message}`,
654 + ),
655 + );
658 + const groups = new Map<string, DocumentRecord[]>();
659 + for (const document of documents)
660 + groups.set(document.metadata.id, [
661 + ...(groups.get(document.metadata.id) ?? []),
662 + document,
663 + ]);
664 + for (const [id, records] of groups) {
665 + if (records.length > 1) {
666 + const paths = records.map((record) => record.path).sort();
667 + for (const record of records)
668 + diagnostics.push(
669 + diagnostic(
670 + "graph.duplicate-id",
671 + record.path,
672 + `Duplicate ID ${id}: ${paths.join(", ")}`,
673 + ),
674 + );
677 + const unique = new Map(
678 + [...groups]
679 + .filter(([, records]) => records.length === 1)
680 + .map(([id, records]) => [id, records[0]]),
681 + );
682 + for (const document of documents) {
683 + for (const [targetId, expectedType] of references(document.metadata)) {
684 + const referencedType = parseDocumentId(targetId, prefix).type;
685 + const target = unique.get(targetId);
686 + if (referencedType !== expectedType) {
687 + diagnostics.push(
688 + diagnostic(
689 + "graph.forbidden-edge",
690 + document.path,
691 + `${document.metadata.id} must reference ${expectedType}; ${targetId} is ${referencedType}`,
692 + ),
693 + );
694 + } else if (!target) {
695 + diagnostics.push(
696 + diagnostic(
697 + "graph.dangling-reference",
698 + document.path,
699 + `${document.metadata.id} references missing ${targetId}`,
700 + ),
701 + );
702 + } else if (target.metadata.type !== expectedType) {
703 + diagnostics.push(
704 + diagnostic(
705 + "graph.forbidden-edge",
706 + document.path,
707 + `${document.metadata.id} must reference ${expectedType}; ${targetId} is ${target.metadata.type}`,
708 + ),
709 + );
712 + if (document.metadata.type === "plan" && document.metadata.roadmap) {
713 + const roadmap = unique.get(document.metadata.roadmap);
714 + if (
715 + roadmap?.metadata.type === "roadmap" &&
716 + roadmap.metadata.spec !== document.metadata.spec
717 + ) {
718 + diagnostics.push(
719 + diagnostic(
720 + "graph.forbidden-edge",
721 + document.path,
722 + `${document.metadata.roadmap} belongs to ${roadmap.metadata.spec}, not ${document.metadata.spec}`,
723 + ),
724 + );
728 + return { documents, diagnostics: diagnostics.sort(compareDiagnostics) };

tsconfig.json

Modified
24 24 "extensions/**/*.test.ts",
25 25 "extensions/**/*.bench.ts",
26 26 "extensions/**/scripts/**",
27 - "extensions/the-system"
27 + "extensions/the-system/index.ts",
28 + "extensions/the-system/mockup.ts",
29 + "extensions/the-system/skills/systematic-debugging/condition-based-waiting-example.ts"