pi-ext bugabingas pi extensions
owned by bugabinga
README Source History Refs Compare Notes Search test(the-system): complete document kernel phase
40e8cd7e9a4d5bfb9be9f0b43d140df4496d60aa
Oliver Jan Krylow <oliver@bugabinga.net > · 12 Jul 2026
unsigned
Browse files Compare 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" ;
3 9 import { tmpdir }
from "node:os" ;
4 10 import path
from "node:path" ;
5 11 import { afterEach, describe, it }
from "vitest" ;
10 - parseDocumentMetadata,
12 - resolveGovernedPath,
13 - SystemDocumentError,
14 - validateAuthoredHtml,
13 + discoverProjectRoot,
16 + parseDocumentMetadata,
18 + resolveGovernedPath,
19 + SystemDocumentError,
20 + validateAuthoredHtml,
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 );
26 + const root
= mkdtempSync (path.
join (
tmpdir (),
"the-system-documents-" ));
27 + temporary.
push (
root );
24 30 const dir = (
... parts
: string [])
=> {
25 - const result
= path.
join (
... parts);
26 - mkdirSync (result, { recursive:
true });
31 + const result
= path.
join (
... parts);
32 + mkdirSync (result, { recursive:
true });
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" , ()
=> {
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);
47 - assert.
equal (
discoverProjectRoot (cwd),
root );
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);
55 + assert.
equal (
discoverProjectRoot (cwd),
root );
50 - it (
"uses cwd when no VCS marker exists" , ()
=> {
51 - const cwd
= dir (
tree (),
"plain" );
52 - assert.
equal (
discoverProjectRoot (cwd), path.
resolve (cwd));
58 + it (
"uses cwd when no VCS marker exists" , ()
=> {
59 + const cwd
= dir (
tree (),
"plain" );
60 + assert.
equal (
discoverProjectRoot (cwd), path.
resolve (cwd));
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" );
62 - ()
=> discoverProjectRoot (cwd),
64 - error
instanceof SystemDocumentError && 65 - error.
code === "root.conflict" && 66 - error.message
=== `Conflicting project roots: Git ${gitRoot}; JJ ${jjRoot}` ,
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" );
70 + ()
=> discoverProjectRoot (cwd),
72 + error
instanceof SystemDocumentError && 73 + error.
code === "root.conflict" && 75 + `Conflicting project roots: Git ${gitRoot}; JJ ${jjRoot}` ,
71 80 describe (
"governed path containment" , ()
=> {
72 - it (
"normalizes a contained relative path" , ()
=> {
73 - const root
= path.
resolve (
"project" );
75 - resolveGovernedPath (
root ,
".system/specs/../plans/a.html" ),
76 - path.
join (
root ,
".system" ,
"plans" ,
"a.html" ),
81 + it (
"normalizes a contained relative path" , ()
=> {
82 + const root
= path.
resolve (
"project" );
84 + resolveGovernedPath (
root ,
".system/specs/../plans/a.html" ),
85 + path.
join (
root ,
".system" ,
"plans" ,
"a.html" ),
80 - it.
each ([
"../outside" , path.
resolve (
"outside" )])(
"rejects %s" , (candidate)
=> {
82 - ()
=> resolveGovernedPath (path.
resolve (
"project" ), candidate),
83 - (error
: unknown )
=> error
instanceof SystemDocumentError && error.
code === "path.outside-root" ,
91 + path.
resolve (
"outside" ),
92 + ])(
"rejects %s" , (candidate)
=> {
94 + ()
=> resolveGovernedPath (path.
resolve (
"project" ), candidate),
96 + error
instanceof SystemDocumentError && 97 + error.
code === "path.outside-root" ,
87 - it (
"does not confuse a sibling sharing the root prefix for a child" , ()
=> {
88 - const root
= path.
resolve (
"project" );
90 - ()
=> resolveGovernedPath (
root , path.
resolve (
"project-other/file" )),
91 - /outside project root/ ,
101 + it (
"does not confuse a sibling sharing the root prefix for a child" , ()
=> {
102 + const root
= path.
resolve (
"project" );
104 + ()
=> resolveGovernedPath (
root , path.
resolve (
"project-other/file" )),
105 + /outside project root/ ,
96 110 describe (
"system config" , ()
=> {
97 - it (
"accepts only the exact versioned shape" , ()
=> {
98 - assert.
deepEqual (
parseSystemConfig (
'{"prefix":"PX","schemaVersion":1,"styleVersion":1}' ), {
111 + it (
"accepts only the exact versioned shape" , ()
=> {
113 + parseSystemConfig (
'{"prefix":"PX","schemaVersion":1,"styleVersion":1}' ),
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),
123 + [
"malformed JSON" ,
"{" ],
126 + '{"prefix":"PX","schemaVersion":1,"styleVersion":1,"extra":true}' ,
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}' ,
136 + ])(
"rejects %s" , (_name, source)
=> 137 + assert.
throws (()
=> parseSystemConfig (source), SystemDocumentError));
118 140 describe (
"document IDs and filenames" , ()
=> {
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 });
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" ), {
137 - "PX-SPEC-001-slug" ,
138 - ])(
"rejects invalid ID %s" , (id)
=> 139 - assert.
throws (()
=> parseDocumentId (id),
/Invalid document ID/ ),
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 (()
=> 148 - "/project/.system/specs/PX-SPEC-001-login-flow.html" ,
149 - { id:
"PX-SPEC-001" , type:
"spec" },
171 + it (
"accepts a matching type directory, ID, and slug" , ()
=> {
172 + assert.
doesNotThrow (()
=> 174 + "/project/.system/specs/PX-SPEC-001-login-flow.html" ,
175 + { id:
"PX-SPEC-001" , type:
"spec" },
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)
=> {
162 - ()
=> validateFilename (filename, { id:
"PX-SPEC-001" , type:
"spec" },
"PX" ),
163 - /Filename mismatch/ ,
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)
=> {
189 + validateFilename (filename, { id:
"PX-SPEC-001" , type:
"spec" },
"PX" ),
190 + /Filename mismatch/ ,
168 - const shell = (metadata
: string , body
= "<header><h1>Title</h1></header><main><section><h2>Contract</h2><p>Readable.</p></section></main>" )
=> `<!doctype html> 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" , ()
=> {
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));
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" },
212 + '{"id":"PX-PLAN-001","type":"plan","spec":"PX-SPEC-001"}' ,
213 + { id:
"PX-PLAN-001" , type:
"plan" , spec:
"PX-SPEC-001" },
216 + '{"id":"PX-PLAN-002","type":"plan","spec":"PX-SPEC-001","roadmap":"PX-ROADMAP-001","phase":2}' ,
220 + spec:
"PX-SPEC-001" ,
221 + roadmap:
"PX-ROADMAP-001" ,
226 + '{"id":"PX-ISSUE-001","type":"issue","status":"open","specs":[]}' ,
227 + { id:
"PX-ISSUE-001" , type:
"issue" , status:
"open" , specs: [] },
230 + '{"id":"PX-RESEARCH-001","type":"research","capturedAt":"2026-07-11","sources":["https://example.com/a"]}' ,
232 + id:
"PX-RESEARCH-001" ,
234 + capturedAt:
"2026-07-11" ,
235 + sources: [
"https://example.com/a" ],
238 + ]
as const )(
"parses exact metadata %s" , (json, expected)
=> 239 + assert.
deepEqual (
parseDocumentMetadata (
shell (json),
"PX" ), expected));
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));
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>' ,
249 + "duplicate JSON key" ,
250 + shell (
'{"id":"PX-SPEC-001","id":"PX-SPEC-002","type":"spec"}' ),
254 + shell (
'{"id":"PX-SPEC-001","type":"spec","status":"open"}' ),
256 + [
"own ID/type mismatch" ,
shell (
'{"id":"PX-PLAN-001","type":"spec"}' )],
258 + "one-sided roadmap" ,
260 + '{"id":"PX-PLAN-001","type":"plan","spec":"PX-SPEC-001","roadmap":"PX-ROADMAP-001"}' ,
264 + "duplicate issue specs" ,
266 + '{"id":"PX-ISSUE-001","type":"issue","status":"fixed","specs":["PX-SPEC-001","PX-SPEC-001"]}' ,
272 + '{"id":"PX-RESEARCH-001","type":"research","capturedAt":"2026-02-30"}' ,
276 + "non-HTTPS source" ,
278 + '{"id":"PX-RESEARCH-001","type":"research","capturedAt":"2026-07-11","sources":["http://example.com"]}' ,
281 + ])(
"rejects %s" , (_name, html)
=> 283 + ()
=> parseDocumentMetadata (html,
"PX" ),
284 + SystemDocumentError,
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), []);
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>" ,
295 + validateAuthoredHtml (
"specs/PX-SPEC-001-title.html" , html),
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)));
302 + "document.doctype" ,
303 + shell (
'{"id":"PX-SPEC-001","type":"spec"}' ).
replace (
309 + "document.language" ,
310 + shell (
'{"id":"PX-SPEC-001","type":"spec"}' ).
replace (
316 + "document.charset" ,
317 + shell (
'{"id":"PX-SPEC-001","type":"spec"}' ).
replace (
318 + '<meta charset="utf-8">' ,
323 + "document.viewport" ,
324 + shell (
'{"id":"PX-SPEC-001","type":"spec"}' ).
replace (
325 + /<meta name="viewport"[ ^ >] + >/ ,
331 + shell (
'{"id":"PX-SPEC-001","type":"spec"}' ).
replace (
332 + "<title>Title</title>" ,
337 + "document.stylesheet" ,
338 + shell (
'{"id":"PX-SPEC-001","type":"spec"}' ).
replace (
344 + "document.semantic-shell" ,
345 + shell (
'{"id":"PX-SPEC-001","type":"spec"}' ).
replace (
346 + /<main> | <\/main>/ g ,
351 + "document.forbidden-tag" ,
353 + '{"id":"PX-SPEC-001","type":"spec"}' ,
354 + '<header><h1>X</h1></header><main><section><iframe src="x"></iframe></section></main>' ,
358 + "document.event-handler" ,
360 + '{"id":"PX-SPEC-001","type":"spec"}' ,
361 + '<header><h1>X</h1></header><main><section onclick="x()">X</section></main>' ,
365 + "document.executable-url" ,
367 + '{"id":"PX-SPEC-001","type":"spec"}' ,
368 + '<header><h1>X</h1></header><main><section><a href="javascript:x()">X</a></section></main>' ,
372 + "document.external-script" ,
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>' ,
379 + "document.active-api" ,
381 + '{"id":"PX-SPEC-001","type":"spec"}' ,
382 + "<header><h1>X</h1></header><main><section>X</section></main><script>fetch('https://example.com')</script>" ,
386 + "document.css-resource" ,
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>" ,
393 + "document.meta-refresh" ,
394 + shell (
'{"id":"PX-SPEC-001","type":"spec"}' ).
replace (
396 + '<meta http-equiv="refresh" content="0; url=x"></head>' ,
399 + ])(
"reports %s" , (code, html)
=> 401 + validateAuthoredHtml (
"doc.html" , html).
some ((item)
=> item.
code === code),
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), []);
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>' ,
409 + assert.
deepEqual (
validateAuthoredHtml (
"doc.html" , html), []);
226 - const source = (folder
: string , id
: string , slug
: string , metadata
: string )
=> ({
227 - path:
`/project/.system/${folder}/${id}-${slug}.html` , html:
shell (metadata),
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"}' ),
239 - assert.
equal (result.documents.
length ,
5 );
240 - assert.
deepEqual (result.diagnostics, []);
424 + it (
"indexes a valid complete graph without diagnostics" , ()
=> {
425 + const result
= indexDocuments (
431 + '{"id":"PX-SPEC-001","type":"spec"}' ,
437 + '{"id":"PX-ROADMAP-001","type":"roadmap","spec":"PX-SPEC-001"}' ,
443 + '{"id":"PX-PLAN-001","type":"plan","spec":"PX-SPEC-001","roadmap":"PX-ROADMAP-001","phase":2}' ,
449 + '{"id":"PX-ISSUE-001","type":"issue","status":"open","specs":["PX-SPEC-001"]}' ,
455 + '{"id":"PX-RESEARCH-001","type":"research","capturedAt":"2026-07-11"}' ,
460 + assert.
equal (result.documents.
length ,
5 );
461 + assert.
deepEqual (result.diagnostics, []);
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":[]}' ),
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." )));
464 + it (
"sorts stable duplicate, filename, dangling, and forbidden-edge diagnostics" , ()
=> {
465 + const result
= indexDocuments (
471 + '{"id":"PX-SPEC-001","type":"spec"}' ,
477 + '{"id":"PX-SPEC-001","type":"spec"}' ,
483 + '{"id":"PX-ROADMAP-001","type":"roadmap","spec":"PX-PLAN-009"}' ,
489 + '{"id":"PX-PLAN-001","type":"plan","spec":"PX-SPEC-404"}' ,
495 + '{"id":"PX-PLAN-002","type":"plan","spec":"PX-SPEC-001","roadmap":"PX-ROADMAP-002","phase":1}' ,
501 + '{"id":"PX-ROADMAP-002","type":"roadmap","spec":"PX-SPEC-003"}' ,
507 + '{"id":"PX-ISSUE-001","type":"issue","status":"open","specs":[]}' ,
513 + result.diagnostics.
map (({ code })
=> code),
514 + [
... result.diagnostics]
517 + a.path.
localeCompare (b.path)
|| 518 + a.
code .
localeCompare (b.
code )
|| 519 + a.message.
localeCompare (b.message),
521 + .
map (({ code })
=> code),
524 + result.diagnostics.
some (
526 + item.
code === "graph.duplicate-id" && 527 + item.message.
includes (
"PX-SPEC-001" ),
531 + result.diagnostics.
some ((item)
=> item.
code === "document.filename" ),
534 + result.diagnostics.
some (
536 + item.
code === "graph.dangling-reference" && 537 + item.message.
includes (
"PX-SPEC-404" ),
541 + result.diagnostics.
some (
543 + item.
code === "graph.forbidden-edge" && 544 + item.message.
includes (
"must reference spec" ),
548 + result.diagnostics.
some (
550 + item.
code === "graph.forbidden-edge" && 551 + item.message.
includes (
"belongs to PX-SPEC-003" ),
555 + ! result.diagnostics.
some (
557 + item.path.
includes (
"PX-ISSUE-001" )
&& item.
code .
startsWith (
"graph." ),
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 );
564 + it (
"contains exact Nugu tokens, version, components, and responsive contracts" , ()
=> {
565 + const css
= readFileSync (
566 + path.
resolve (
import .
meta .dirname,
"../assets/system.css" ),
569 + for (
const token
of [
570 + "The System styleVersion: 1" ,
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" ,
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" ,
605 + "overflow-wrap: anywhere" ,
606 + "@media (max-width: 560px)" ,
608 + assert.
ok (css.
includes (token),
`missing CSS contract: ${token}` );
609 + assert.
doesNotMatch (css,
/@import | url\s * \( | https ? :\/\// i );
extensions/the-system/assets/system.css Modified 3 - color -scheme: light dark;
8 - --ui-accent :
#922792 ;
11 - --important :
#4f3c69 ;
15 - font-family :
ui-monospace ,
SFMono-Regular ,
Consolas ,
monospace ;
17 - background :
var (
--page );
3 + color -scheme: light dark;
8 + --ui-accent :
#922792 ;
11 + --important :
#4f3c69 ;
15 + font-family :
ui-monospace ,
SFMono-Regular ,
Consolas ,
monospace ;
17 + background :
var (
--page );
19 19 @media (prefers-
color -scheme: dark) {
25 - --ui-accent :
#d86dd8 ;
28 - --important :
#dfd3f3 ;
25 + --ui-accent :
#d86dd8 ;
28 + --important :
#dfd3f3 ;
35 + box-sizing :
border-box ;
34 - * {
box-sizing :
border-box ; }
35 - body {
margin :
0 ;
padding :
1 rem ; }
37 - background :
var (
--page );
38 - border :
3 px solid var (
--fg );
39 - box-shadow :
9 px 9 px 0 var (
--ui-accent );
42 + background :
var (
--page );
43 + border :
3 px solid var (
--fg );
44 + box-shadow :
9 px 9 px 0 var (
--ui-accent );
45 - grid-template-columns :
minmax (
0 ,
1 fr )
auto ;
47 - padding : clamp(
.85 rem ,
3 vw ,
1.3 rem );
48 - border-bottom :
3 px solid var (
--fg );
49 - background :
var (
--panel );
50 + grid-template-columns :
minmax (
0 ,
1 fr )
auto ;
52 + padding : clamp(
0.85 rem ,
3 vw ,
1.3 rem );
53 + border-bottom :
3 px solid var (
--fg );
54 + background :
var (
--panel );
54 - letter-spacing :
.16 em ;
55 - text-transform :
uppercase ;
56 - color :
var (
--accent );
59 + letter-spacing :
0.16 em ;
60 + text-transform :
uppercase ;
61 + color :
var (
--accent );
60 - font :
900 clamp (
1.35 rem ,
5 vw ,
2.25 rem )/.96
system -ui;
61 - text-transform :
uppercase ;
62 - overflow-wrap : anywhere;
65 + font :
900 clamp (
1.35 rem ,
5 vw ,
2.25 rem ) / 0.96
system -ui;
66 + text-transform :
uppercase ;
67 + overflow-wrap : anywhere;
65 - border :
2 px solid var (
--fg );
69 - background :
var (
--page );
70 + border :
2 px solid var (
--fg );
74 + background :
var (
--page );
78 + grid-template-columns :
minmax (
0 ,
1.15 fr )
minmax (
0 ,
0.85 fr );
71 - .grid {
display :
grid ;
grid-template-columns :
minmax (
0 ,
1.15 fr )
minmax (
0 ,
.85 fr ); }
73 - padding : clamp(
.8 rem ,
2 vw ,
1.1 rem );
74 - border-bottom :
2 px solid var (
--fg );
81 + padding : clamp(
0.8 rem ,
2 vw ,
1.1 rem );
82 + border-bottom :
2 px solid var (
--fg );
85 + .section:nth-child(
odd ) {
86 + border-right :
2 px solid var (
--fg );
77 - .section:nth-child(
odd ) {
border-right :
2 px solid var (
--fg ); }
79 - font :
900 .76 rem /
1 system-ui ;
80 - text-transform :
uppercase ;
81 - letter-spacing :
.11 em ;
83 - color :
var (
--accent );
89 + font :
900 0.76 rem /
1 system-ui ;
90 + text-transform :
uppercase ;
91 + letter-spacing :
0.11 em ;
92 + margin :
0 0 0.75 rem ;
93 + color :
var (
--accent );
85 - .section
p , .section
li {
font-size :
.82 rem ;
line-height :
1.55 ; }
87 - background :
var (
--panel );
90 - border :
2 px solid var (
--fg );
91 - border-left :
7 px solid var (
--ui-accent );
101 + background :
var (
--panel );
104 + border :
2 px solid var (
--fg );
105 + border-left :
7 px solid var (
--ui-accent );
110 + align-items :
center ;
94 - .flow {
display :
flex ;
align-items :
center ; gap:
.35 rem ;
flex-wrap :
wrap ; }
96 - border :
2 px solid var (
--fg );
97 - padding :
.35 rem .5 rem ;
98 - background :
var (
--panel );
115 + border :
2 px solid var (
--fg );
116 + padding :
0.35 rem 0.5 rem ;
117 + background :
var (
--panel );
122 + color :
var (
--accent );
101 - .arrow {
font-size :
1.2 rem ;
color :
var (
--accent ); }
103 - border :
2 px dashed var (
--focus );
105 - color :
var (
--focus );
106 - background :
var (
--panel );
125 + border :
2 px dashed var (
--focus );
127 + color :
var (
--focus );
128 + background :
var (
--panel );
108 130 @media (
max-width :
560 px ) {
109 - body {
padding :
.5 rem ; }
110 - .doc {
box-shadow :
5 px 5 px 0 var (
--ui-accent ); }
111 - .mast {
grid-template-columns :
1 fr ; }
112 - .id { justify-self:
start ; }
113 - .grid {
grid-template-columns :
1 fr ; }
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 ; }
135 + box-shadow :
5 px 5 px 0 var (
--ui-accent );
138 + grid-template-columns :
1 fr ;
141 + justify-self:
start ;
144 + grid-template-columns :
1 fr ;
146 + .section:nth-child(
odd ) {
150 + align-items :
stretch ;
154 + text-align :
center ;
157 + align-self :
center ;
121 - a {
color :
var (
--focus );
font-weight :
800 ;
overflow-wrap : anywhere; }
122 - .document-nav {
display :
flex ;
flex-wrap :
wrap ; gap:
.5 rem ;
padding :
.8 rem ;
border-bottom :
2 px solid var (
--fg ); }
123 - .metadata {
display :
grid ;
grid-template-columns :
repeat (
auto-fit ,
minmax (
9 rem ,
1 fr )); gap:
.5 rem ;
margin :
0 ;
padding :
.8 rem ;
background :
var (
--panel );
border :
2 px solid var (
--fg ); }
124 - .metadata
dt {
color :
var (
--accent );
font-size :
.7 rem ;
font-weight :
900 ;
letter-spacing :
.12 em ;
text-transform :
uppercase ; }
125 - .metadata
dd {
margin :
.2 rem 0 0 ;
overflow-wrap : anywhere; }
126 - .callout {
padding :
.75 rem ;
border :
2 px solid var (
--fg );
border-left :
7 px 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 :
.15 rem .45 rem ;
border :
2 px solid currentColor ;
color :
var (
--info );
font-size :
.7 rem ;
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 :
.6 rem ;
border :
2 px 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 :
.1 rem .3 rem ;
overflow-wrap : anywhere; }
138 - pre {
max-width :
100 % ;
padding :
.8 rem ;
overflow :
auto ;
border-left :
7 px solid var (
--ui-accent ); }
139 - pre code {
padding :
0 ; }
140 - figure {
max-width :
100 % ;
margin :
1 rem 0 ;
overflow :
auto ; }
141 - details {
border :
2 px solid var (
--fg );
padding :
.65 rem ; }
142 - summary {
min-height :
2.75 rem ;
cursor :
pointer ;
font-weight :
900 ; }
163 + color :
var (
--focus );
165 + overflow-wrap : anywhere;
172 + border-bottom :
2 px solid var (
--fg );
176 + grid-template-columns :
repeat (
auto-fit ,
minmax (
9 rem ,
1 fr ));
180 + background :
var (
--panel );
181 + border :
2 px solid var (
--fg );
184 + color :
var (
--accent );
187 + letter-spacing :
0.12 em ;
188 + text-transform :
uppercase ;
191 + margin :
0.2 rem 0 0 ;
192 + overflow-wrap : anywhere;
196 + border :
2 px solid var (
--fg );
197 + border-left :
7 px solid var (
--info );
198 + background :
var (
--panel );
200 + .callout.important {
201 + border-left-color :
var (
--important );
204 + border-left-color :
var (
--warning );
207 + border-left-color :
var (
--error );
210 + display :
inline-block ;
211 + padding :
0.15 rem 0.45 rem ;
212 + border :
2 px solid currentColor ;
213 + color :
var (
--info );
216 + text-transform :
uppercase ;
220 + color :
var (
--error );
223 + color :
var (
--focus );
227 + border-collapse :
collapse ;
232 + border :
2 px solid var (
--fg );
234 + vertical-align :
top ;
235 + overflow-wrap : anywhere;
238 + background :
var (
--panel );
242 + background :
var (
--panel );
245 + padding :
0.1 rem 0.3 rem ;
246 + overflow-wrap : anywhere;
252 + border-left :
7 px solid var (
--ui-accent );
263 + border :
2 px solid var (
--fg );
267 + min-height :
2.75 rem ;
143 271 @media (
max-width :
560 px ) {
144 - .document-nav
a {
min-height :
2.75 rem ;
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 :
1 fr ; }
273 + min-height :
2.75 rem ;
274 + display :
inline-flex ;
275 + align-items :
center ;
289 + grid-template-columns :
1 fr ;
extensions/the-system/documents.ts Modified 5 5 export const STYLE_VERSION
= 1 ;
7 7 export class SystemDocumentError extends Error {
9 - readonly code
: string ,
13 - this.
name = "SystemDocumentError" ;
9 + readonly code
: string ,
13 + this.
name = "SystemDocumentError" ;
17 - const nearestMarker = (cwd
: string , marker
: string ,
markerExists : (path
: string )
=> boolean )
=> {
18 - let current
= path.
resolve (cwd);
20 - if (
markerExists (path.
join (current, marker)))
return current;
21 - const parent
= path.
dirname (current);
22 - if (parent
=== current)
return undefined ;
17 + const nearestMarker = (
20 + markerExists : (path
: string )
=> boolean ,
22 + let current
= path.
resolve (cwd);
24 + if (
markerExists (path.
join (current, marker)))
return current;
25 + const parent
= path.
dirname (current);
26 + if (parent
=== current)
return undefined ;
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}` );
34 - return jj
?? git
?? resolvedCwd;
31 + export function discoverProjectRoot (
33 + markerExists
= existsSync,
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 (
41 + `Conflicting project roots: Git ${git}; JJ ${jj}` ,
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}` );
48 + const normalizedRoot
= path.
resolve (
root );
49 + const target
= path.
resolve (normalizedRoot, candidate);
50 + const relative
= path.
relative (normalizedRoot, target);
52 + relative
=== ".." || 53 + relative.
startsWith (
`..${path.sep}` )
|| 54 + path.
isAbsolute (relative)
56 + throw new SystemDocumentError (
57 + "path.outside-root" ,
58 + `Path is outside project root: ${candidate}` ,
47 - export const DOCUMENT_TYPES
= [
"spec" ,
"roadmap" ,
"plan" ,
"issue" ,
"research" ]
as const ;
64 + export const DOCUMENT_TYPES
= [
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 <{
74 + schemaVersion
: number ;
75 + styleVersion
: number ;
50 77 export type ParsedDocumentId = Readonly <{
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 <{
58 89 export type PlanMetadata = Readonly <{
65 96 export type IssueMetadata = Readonly <{
68 - status
: "open" | "fixed" ;
69 - specs
: readonly string [];
99 + status
: "open" | "fixed" ;
100 + specs
: readonly string [];
71 102 export type ResearchMetadata = Readonly <{
75 - sources
?: readonly string [];
105 + capturedAt
: string ;
106 + sources
?: readonly string [];
77 108 export type DocumentMetadata = 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 >>
= {
89 - roadmap:
"roadmaps" ,
92 - research:
"research" ,
122 + roadmap:
"roadmaps" ,
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` );
99 - return value
as Record <
string ,
unknown >;
128 + const objectValue = (
131 + )
: Record <
string ,
unknown >
=> {
132 + if (
typeof value
!== "object" || value
=== null || Array .
isArray (value)) {
133 + throw new SystemDocumentError (
135 + `${label} must be a JSON object` ,
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 []
= [],
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 (
111 - `Expected keys ${[ ... required, ... optional]. sort (). join (", ")}; received ${actual. join (", ")}` ,
145 + const actual
= Object .
keys (value).
sort ();
146 + const allowed
= new Set ([
... required,
... optional]);
148 + required.
some ((key)
=> ! (key
in value))
|| 149 + actual.
some ((key)
=> ! allowed.
has (key))
151 + throw new SystemDocumentError (
153 + `Expected keys ${[ ... required, ... optional]. sort (). join (", ")}; received ${actual. join (", ")}` ,
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 ;
121 - parsed
= JSON .
parse (source);
123 - throw new SystemDocumentError (
"config.invalid-json" ,
"Invalid config JSON" );
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" );
130 - if (
! positiveInteger (value.schemaVersion)
|| ! positiveInteger (value.styleVersion)) {
131 - throw new SystemDocumentError (
133 - "Schema and style versions must be positive integers" ,
137 - prefix: value.
prefix ,
138 - schemaVersion: value.schemaVersion
as number ,
139 - styleVersion: value.styleVersion
as number ,
161 + let parsed
: unknown ;
163 + parsed
= JSON .
parse (source);
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" );
173 + ! positiveInteger (value.schemaVersion)
|| 174 + ! positiveInteger (value.styleVersion)
176 + throw new SystemDocumentError (
178 + "Schema and style versions must be positive integers" ,
182 + prefix: value.
prefix ,
183 + schemaVersion: value.schemaVersion
as number ,
184 + styleVersion: value.styleVersion
as number ,
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 (
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}` );
152 - if (expectedPrefix
&& match[
1 ]
!== expectedPrefix) {
153 - throw new SystemDocumentError (
155 - `Document ID must use prefix ${expectedPrefix}: ${source}` ,
161 - type: TYPE_BY_TOKEN.
get (match[
2 ])
as DocumentType ,
188 + export function parseDocumentId (
190 + expectedPrefix
?: string ,
191 + )
: ParsedDocumentId {
193 + / ^ ([A-Z][A-Z0-9] {1,7} )-(SPEC | ROADMAP | PLAN | ISSUE | RESEARCH)-([0-9] {3,} ) $ / .
exec (
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 (
201 + `Invalid document ID: ${source}` ,
204 + if (expectedPrefix
&& match[
1 ]
!== expectedPrefix) {
205 + throw new SystemDocumentError (
207 + `Document ID must use prefix ${expectedPrefix}: ${source}` ,
213 + type: TYPE_BY_TOKEN.
get (match[
2 ])
as DocumentType ,
166 218 export function validateFilename (
168 - metadata
: DocumentMetadata ,
220 + metadata
: DocumentMetadata ,
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$` );
176 - parsed.
type !== metadata.
type || 177 - directory
!== expectedDirectory
|| 178 - ! pattern.
test (path.
basename (filename))
180 - throw new SystemDocumentError (
181 - "document.filename" ,
182 - `Filename mismatch for ${metadata. id }: ${filename}` ,
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$` );
228 + parsed.
type !== metadata.
type || 229 + directory
!== expectedDirectory
|| 230 + ! pattern.
test (path.
basename (filename))
232 + throw new SystemDocumentError (
233 + "document.filename" ,
234 + `Filename mismatch for ${metadata. id }: ${filename}` ,
187 239 const duplicateTopLevelKeys = (source
: string )
: string []
=> {
188 - const keys
: string []
= [];
189 - const duplicates
= new Set <
string >();
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;
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 ;
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);
214 - return [
... duplicates].
sort ();
240 + const keys
: string []
= [];
241 + const duplicates
= new Set <
string >();
244 + while (index
< source.
length ) {
245 + const character
= source[index];
246 + if (character
=== "{" ) {
251 + if (character
=== "}" ) {
256 + if (character
!== '"' ) {
260 + const start
= index;
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);
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` );
281 + if (
! Array .
isArray (value)
|| value.
some ((item)
=> typeof item
!== "string" ))
282 + throw new SystemDocumentError (
284 + `${label} must be a string array` ,
286 + if (
new Set (value).
size !== value.
length )
287 + throw new SystemDocumentError (
288 + "metadata.duplicate" ,
289 + `${label} must contain unique values` ,
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))
296 + const date
= new Date (
`${value}T00:00:00Z` );
298 + ! Number .
isNaN (date.
valueOf ())
&& date.
toISOString ().
slice (
0 ,
10 )
=== value
227 301 const httpsUrl = (value
: string )
=> {
228 - try {
return new URL (value).
protocol === "https:" ; }
catch {
return false ; }
303 + return new URL (value).
protocol === "https:" ;
230 - const metadataScripts = (html
: string )
=> [
... html.
matchAll (
/<script \b ([ ^ >] * )>([\s\S] *? )<\/script\s * >/ gi )]
231 - .
filter ((match)
=> / \b id\s * =\s * (["'])system-meta \1 / i .
test (match[
1 ])
&& / \b type\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 (
311 + / \b id\s * =\s * (["'])system-meta \1 / i .
test (match[
1 ])
&& 312 + / \b type\s * =\s * (["'])application\/json \1 / i .
test (match[
1 ]),
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 ;
250 - switch (value.
type ) {
252 - exactKeys (value, [
"id" ,
"type" ]);
253 - return { id: value.
id , type:
"spec" };
255 - exactKeys (value, [
"id" ,
"type" ,
"spec" ]);
256 - return { id: value.
id , type:
"roadmap" , spec:
reference (
"spec" ) };
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" ) };
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 };
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 };
279 - throw new SystemDocumentError (
"metadata.type" ,
`Unsupported metadata type: ${value. type }` );
315 + export function parseDocumentMetadata (
318 + )
: DocumentMetadata {
319 + const blocks
= metadataScripts (html);
320 + if (blocks.
length !== 1 )
321 + throw new SystemDocumentError (
323 + `Expected exactly one system-meta block; received ${blocks. length }` ,
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 (", ")}` ,
332 + let parsed
: unknown ;
334 + parsed
= JSON .
parse (json);
336 + throw new SystemDocumentError (
337 + "metadata.invalid-json" ,
338 + "Invalid system metadata JSON" ,
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" ,
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 }` ,
353 + const reference = (key
: string )
=> {
354 + if (
typeof value[key]
!== "string" )
355 + throw new SystemDocumentError (
357 + `${key} must be a document ID` ,
359 + parseDocumentId (value[key]
as string , prefix);
360 + return value[key]
as string ;
362 + switch (value.
type ) {
364 + exactKeys (value, [
"id" ,
"type" ]);
365 + return { id: value.
id , type:
"spec" };
367 + exactKeys (value, [
"id" ,
"type" ,
"spec" ]);
368 + return { id: value.
id , type:
"roadmap" , spec:
reference (
"spec" ) };
370 + exactKeys (value, [
"id" ,
"type" ,
"spec" ], [
"roadmap" ,
"phase" ]);
371 + const hasRoadmap
= "roadmap" in value;
372 + const hasPhase
= "phase" in value;
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" ,
385 + spec:
reference (
"spec" ),
386 + roadmap:
reference (
"roadmap" ),
387 + phase: value.phase
as number ,
389 + : { id: value.
id , type:
"plan" , spec:
reference (
"spec" ) };
392 + exactKeys (value, [
"id" ,
"type" ,
"status" ,
"specs" ]);
393 + if (value.
status !== "open" && value.
status !== "fixed" )
394 + throw new SystemDocumentError (
396 + "Issue status must be open or fixed" ,
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 };
403 + exactKeys (value, [
"id" ,
"type" ,
"capturedAt" ], [
"sources" ]);
404 + if (
! validDate (value.capturedAt))
405 + throw new SystemDocumentError (
407 + "capturedAt must be a valid ISO date" ,
410 + "sources" in value
? stringArray (value.sources,
"sources" )
: undefined ;
411 + if (sources?.
some ((source)
=> ! httpsUrl (source)))
412 + throw new SystemDocumentError (
414 + "Research sources must use HTTPS" ,
420 + capturedAt: value.capturedAt
as string ,
426 + capturedAt: value.capturedAt
as string ,
430 + throw new SystemDocumentError (
432 + `Unsupported metadata type: ${value. type }` ,
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 <{
442 + const diagnostic = (
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));
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 [ ^ >] *\b lang\s * =\s * (["'])en \1 [ ^ >] * >/ gi ,
"Document requires one html lang=en root" );
294 - requireOne (
"document.charset" ,
/<meta \b [ ^ >] *\b charset\s * =\s * (["']) ? utf-8 \1 [ ^ >] * >/ gi ,
"Document requires one UTF-8 charset meta" );
295 - requireOne (
"document.viewport" ,
/<meta \b [ ^ >] *\b name\s * =\s * (["'])viewport \1 [ ^ >] *\b content\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 (?=[ ^ >] *\b rel\s * =\s * (["'])stylesheet \1 )(?=[ ^ >] *\b href\s * =\s * (["'])\.\.\/system\.css \2 )[ ^ >] * >/ gi ,
"Document requires exactly ../system.css" );
298 - if (
count (html,
/<link \b [ ^ >] *\b rel\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 [ ^ >] *\b http-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 [ ^ >] *\b src\s * =/ i .
test (html)) findings.
push (
diagnostic (
"document.external-script" , filename,
"External script sources are forbidden" ));
305 - if (
/<(?:img | audio | video | source | track) \b [ ^ >] *\b src\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)
=> ! / \b type\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)
|| / \b import\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 (
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));
459 + if (
! / ^ <!doctype html>/ i .
test (html.
trimStart ()))
462 + "document.doctype" ,
464 + "Document must begin with HTML doctype" ,
468 + "document.language" ,
469 + /<html \b [ ^ >] *\b lang\s * =\s * (["'])en \1 [ ^ >] * >/ gi ,
470 + "Document requires one html lang=en root" ,
473 + "document.charset" ,
474 + /<meta \b [ ^ >] *\b charset\s * =\s * (["']) ? utf-8 \1 [ ^ >] * >/ gi ,
475 + "Document requires one UTF-8 charset meta" ,
478 + "document.viewport" ,
479 + /<meta \b [ ^ >] *\b name\s * =\s * (["'])viewport \1 [ ^ >] *\b content\s * =\s * (["'])width=device-width,\s * initial-scale=1 \2 [ ^ >] * >/ gi ,
480 + "Document requires one viewport meta" ,
484 + /<title>\s * [ ^ <\s][ ^ <] * <\/title>/ gi ,
485 + "Document requires one nonempty title" ,
488 + "document.stylesheet" ,
489 + /<link \b (?=[ ^ >] *\b rel\s * =\s * (["'])stylesheet \1 )(?=[ ^ >] *\b href\s * =\s * (["'])\.\.\/system\.css \2 )[ ^ >] * >/ gi ,
490 + "Document requires exactly ../system.css" ,
492 + if (
count (html,
/<link \b [ ^ >] *\b rel\s * =\s * (["'])stylesheet \1 [ ^ >] * >/ gi )
!== 1 )
495 + "document.stylesheet" ,
497 + "Additional or missing stylesheets are forbidden" ,
500 + for (
const tag
of [
"header" ,
"main" ,
"section" ]
as const )
502 + "document.semantic-shell" ,
503 + new RegExp (
`<${tag}\\b` ,
"gi" ),
504 + `Document requires one ${tag} element` ,
506 + if (
/<\/ ? (?:iframe | object | embed) \b / i .
test (html))
509 + "document.forbidden-tag" ,
511 + "iframe, object, and embed are forbidden" ,
514 + if (
/<meta \b [ ^ >] *\b http-equiv\s * =\s * (["'])refresh \1 / i .
test (html))
517 + "document.meta-refresh" ,
519 + "Meta refresh is forbidden" ,
522 + if (
/\son[a-z] + \s * =/ i .
test (html))
525 + "document.event-handler" ,
527 + "Event-handler attributes are forbidden" ,
531 + / \b (?:href | src | action | formaction | xlink:href)\s * =\s * (["'])\s * (?:javascript | vbscript | data):/ i .
test (
537 + "document.executable-url" ,
539 + "Executable URL schemes are forbidden" ,
542 + if (
/<script \b [ ^ >] *\b src\s * =/ i .
test (html))
545 + "document.external-script" ,
547 + "External script sources are forbidden" ,
551 + /<(?:img | audio | video | source | track) \b [ ^ >] *\b src\s * =\s * (["'])https ? :/ i .
test (
557 + "document.remote-resource" ,
559 + "Remote media resources are forbidden" ,
562 + if (
/(?:@import | url\s * \(\s * ["'] ? \s * (?:https ? : | data:))/ i .
test (html))
565 + "document.css-resource" ,
567 + "CSS imports and remote/data URLs are forbidden" ,
570 + const executable
= [
571 + ... html.
matchAll (
/<script \b ([ ^ >] * )>([\s\S] *? )<\/script\s * >/ gi ),
574 + (match)
=> ! / \b type\s * =\s * (["'])application\/json \1 / i .
test (match[
1 ]),
576 + .
map ((match)
=> match[
2 ])
579 + / \b (?:fetch | XMLHttpRequest | WebSocket | EventSource | importScripts | localStorage | sessionStorage | indexedDB) \b / .
test (
582 + / \b import\s * \(/ .
test (executable)
586 + "document.active-api" ,
588 + "Network, import, and browser storage APIs are forbidden" ,
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 <{
602 + metadata
: DocumentMetadata ;
604 + export type DocumentIndex = Readonly <{
605 + documents
: readonly DocumentRecord [];
606 + diagnostics
: readonly Diagnostic [];
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 [];
609 + const references = (
610 + metadata
: DocumentMetadata ,
611 + )
: readonly (
readonly [
string ,
"spec" | "roadmap" ])[]
=> {
612 + switch (metadata.
type ) {
614 + return [[metadata.spec,
"spec" ]];
617 + [metadata.spec,
"spec" ],
618 + ... (metadata.roadmap
? [[metadata.roadmap,
"roadmap" ]
as const ]
: []),
621 + return metadata.specs.
map ((id)
=> [id,
"spec" ]
as const );
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));
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 });
341 - const value
= error
as SystemDocumentError ;
342 - diagnostics.
push (
diagnostic (
"document.metadata" , item.path,
`${value. code }: ${value.message}` ));
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 (", ")}` ));
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) {
361 - "graph.forbidden-edge" ,
363 - `${ document .metadata. id } must reference ${expectedType}; ${targetId} is ${referencedType}` ,
366 - }
else if (
! target) {
369 - "graph.dangling-reference" ,
371 - `${ document .metadata. id } references missing ${targetId}` ,
374 - }
else if (target.metadata.
type !== expectedType) {
377 - "graph.forbidden-edge" ,
379 - `${ document .metadata. id } must reference ${expectedType}; ${targetId} is ${target.metadata. type }` ,
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}` ));
391 - return { documents, diagnostics: diagnostics.
sort (compareDiagnostics) };
627 + export function indexDocuments (
628 + sources
: readonly DocumentSource [],
631 + const documents
: DocumentRecord []
= [];
632 + const diagnostics
: Diagnostic []
= [];
633 + for (
const item
of [
... sources].
sort ((left, right)
=> 634 + left.path.
localeCompare (right.path),
636 + diagnostics.
push (
... validateAuthoredHtml (item.path, item.html));
638 + const metadata
= parseDocumentMetadata (item.html, prefix);
640 + validateFilename (item.path, metadata, prefix);
643 + diagnostic (
"document.filename" , item.path, (error
as Error ).message),
646 + documents.
push ({ path: item.path, metadata });
648 + const value
= error
as SystemDocumentError ;
651 + "document.metadata" ,
653 + `${value. code }: ${value.message}` ,
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 )
?? []),
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)
670 + "graph.duplicate-id" ,
672 + `Duplicate ID ${id}: ${paths. join (", ")}` ,
677 + const unique
= new Map (
679 + .
filter (([, records])
=> records.
length === 1 )
680 + .
map (([id, records])
=> [id, records[
0 ]]),
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) {
689 + "graph.forbidden-edge" ,
691 + `${ document .metadata. id } must reference ${expectedType}; ${targetId} is ${referencedType}` ,
694 + }
else if (
! target) {
697 + "graph.dangling-reference" ,
699 + `${ document .metadata. id } references missing ${targetId}` ,
702 + }
else if (target.metadata.
type !== expectedType) {
705 + "graph.forbidden-edge" ,
707 + `${ document .metadata. id } must reference ${expectedType}; ${targetId} is ${target.metadata. type }` ,
712 + if (
document .metadata.
type === "plan" && document .metadata.roadmap) {
713 + const roadmap
= unique.
get (
document .metadata.roadmap);
715 + roadmap?.metadata.
type === "roadmap" && 716 + roadmap.metadata.spec
!== document .metadata.spec
720 + "graph.forbidden-edge" ,
722 + `${ document .metadata.roadmap} belongs to ${roadmap.metadata.spec}, not ${ document .metadata.spec}` ,
728 + return { documents, diagnostics: diagnostics.
sort (compareDiagnostics) };
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"