pi-ext bugabingas pi extensions
owned by admin
README Source History Refs Compare Notes Search feat(the-system): improve book renderer
2c402ed0b00175218262cd539bc99d51ffb74c9f
Oliver Jan Krylow <oliver@bugabinga.net > · 11 Aug 2026
unsigned
Browse files Compare with HEAD
Changed files (10) 6 6 - Modernize extensions for Pi 0.84 API changes around agent sessions, provider headers, auth, and RPC message updates
7 7 - Fix The System README artifact path docs to show plural directories
8 8 - Make `/system init` deterministic with confirmation; it creates schema v3 config, plural artifact directories, and core files directly
9 + - Seed `/system init` core files with concise SYSTEM, MISSION, and RULES role guidance while preserving existing core content on rerun
10 + - Fix `/system init` so rerunning in an initialized project reuses the existing prefix instead of asking again
9 11 - Fix exact `/system` subcommands such as `doctor` and `book` so autocomplete does not consume Enter
10 12 - Fix The System document prompt and governance to require plural artifact directories and block unknown `.system` paths such as `.system/spec`
11 13 - Fix `/system view` and `/system book` HTML output so rendered pages include document bodies and open in the browser
12 14 - Fix rich System doc rendering so heading anchors are document-scoped and iframe embeds use browser-loadable file URLs
15 + - Fix `/system book` Mermaid diagrams so they load from local file output in browsers
16 + - Fix `/system book` layout so the On this page sidebar no longer overlaps content, the dossier uses full width, header elements align, empty diagnostics are hidden, law navigation avoids duplicate labels, project metadata is used for titles and favicons, and graph labels no longer overflow boxes
17 + - Improve `/system book` with a responsive dossier reader, collapsible navigation, attached search results with highlights, diagnostic links, reference graph, Nugu colors, and print CSS
13 18 - Update The System lifecycle design around one `/system` command with subcommands for init, doctor, view, book, research, spec, spec-verify, phase, plan, issue, and exec
14 19 - Update The System lifecycle stages: the small path is `spec -> exec`; the larger path is `research -> spec -> spec-verify -> phase -> plan -> exec`; optional stages never auto-chain
15 20 - Update The System lifecycle IDs to schema v3 token IDs and rename roadmap terminology to phase terminology
extensions/the-system/__e2e__/renderer.spec.ts Modified 53 53 await expect (page.
getByText (
"raw html works" )).
toBeVisible ();
54 54 await page.
goto (
pathToFileURL (book).
href );
56 - page.
getByRole (
"heading" , { name:
"The System Docs" }),
56 + page.
getByRole (
"heading" , { name:
/the-system-render-e2e-. * Dossier/ }),
58 58 await expect (page.
getByRole (
"link" , { name:
"CORE-SYSTEM" })).
toBeVisible ();
59 59 await expect (page.
getByText (
"PX-PHASE-PHASE001" ).
first ()).
toBeVisible ();
extensions/the-system/__tests__/documents.test.ts Modified 71 71 it (
"accepts minimal config and inspects narrow v1 config" , ()
=> {
74 + '{"prefix":"PX","schemaVersion":3,"title":"Project X"}' ,
76 + { prefix:
"PX" , schemaVersion:
3 , title:
"Project X" },
72 78 assert.
deepEqual (
parseSystemConfig (
'{"prefix":"PX","schemaVersion":3}' ), {
extensions/the-system/__tests__/init.test.ts Modified 58 58 assert.
match (child.stdout,
/WROTE \.system\/config\.json/ );
59 59 assert.
match (child.stdout,
/WROTE \.system\/SYSTEM\.md/ );
60 60 assert.
doesNotMatch (child.stdout,
/system\.css/ );
62 - readFileSync (path.
join (project,
".system/config.json" ),
"utf8" ),
63 - '{\n\t"prefix": "PX",\n\t"schemaVersion": 3\n}\n' ,
63 + readFileSync (path.
join (project,
".system/config.json" ),
"utf8" ),
65 + { prefix:
"PX" , schemaVersion:
3 , title: path.
basename (project) },
66 68 lstatSync (path.
join (project,
".system/system.css" ), {
74 + readFileSync (path.
join (project,
".system/SYSTEM.md" ),
"utf8" ),
75 + /Stable project identity/ ,
78 + readFileSync (path.
join (project,
".system/MISSION.md" ),
"utf8" ),
79 + /Current objective/ ,
82 + readFileSync (path.
join (project,
".system/RULES.md" ),
"utf8" ),
83 + /Concrete operating constraints/ ,
71 85 const before
= [
"SYSTEM.md" ,
"MISSION.md" ,
"RULES.md" ].
map ((name)
=> {
72 86 const target
= path.
join (project,
".system" , name);
73 87 return [name,
readFileSync (target,
"utf8" ),
lstatSync (target).mtimeMs];
97 111 const upgrades
= [
98 112 ".system/config.json schemaVersion 1 -> 3; remove styleVersion" ,
113 + `.system/config.json add title "${path. basename (project)}"` ,
99 114 ".system/system.css remove obsolete machine-owned asset" ,
101 116 assert.
deepEqual (
inspectInitialization (project).upgrades, upgrades);
extensions/the-system/__tests__/the-system.test.ts Modified 126 126 assert.
match (notices[
0 ]
?? "" ,
/Initialized The System/ );
128 - readFileSync (path.
join (project,
".system/config.json" ),
"utf8" ),
129 - '{\n\t"prefix": "PX",\n\t"schemaVersion": 3\n}\n' ,
129 + readFileSync (path.
join (project,
".system/config.json" ),
"utf8" ),
131 + { prefix:
"PX" , schemaVersion:
3 , title: path.
basename (project) },
132 134 readFileSync (path.
join (project,
".system/SYSTEM.md" ),
"utf8" ),
135 + /Stable project identity/ ,
139 + it (
"reuses existing prefix on init rerun" ,
async ()
=> {
140 + const project
= temp ();
141 + validSystem (project);
142 + const notices
: string []
= [];
143 + const command
= createSystemCommand ({
sendUserMessage () {} }
as never );
144 + await command.
handler (
"init" , {
146 + waitForIdle :
async ()
=> {},
148 + input :
async ()
=> assert.
fail (
"must not ask for prefix" ),
149 + confirm :
async (_title
: string , summary
: string )
=> {
150 + assert.
match (summary,
/Prefix: PX/ );
153 + notify : (message
: string )
=> notices.
push (message),
156 + assert.
match (notices[
0 ]
?? "" ,
/Initialized The System/ );
137 159 it (
"injects lifecycle prompts with shared contracts and generated artifact slots" ,
async ()
=> {
138 160 const project
= temp ();
139 161 validSystem (project);
220 242 assert.
match (view,
/hljs/ );
221 243 assert.
match (view,
/<iframe src="file:\/\/. * mockup-card\.html"/ );
222 244 assert.
match (view,
/<mark>raw<\/mark>/ );
223 - assert.
match (docs,
/The System Docs/ );
224 - assert.
match (docs,
/<section id="PX-SPEC-SPEC0001">/ );
245 + assert.
match (docs,
/the-system-command-. * Dossier/ );
246 + assert.
match (docs,
/<section id="PX-SPEC-SPEC0001" class="book-section">/ );
247 + assert.
match (docs,
/class="book-top"/ );
248 + assert.
match (docs,
/class="book-nav"/ );
249 + assert.
match (docs,
/class="mobile-nav"/ );
225 250 assert.
match (docs,
/id="search"/ );
251 + assert.
doesNotMatch (docs,
/0 diagnostics/ );
252 + assert.
match (docs,
/rel="icon"/ );
253 + assert.
match (docs,
/data-search-hit/ );
226 254 assert.
match (docs,
/MiniSearch/ );
227 255 assert.
doesNotMatch (view,
/<nav class="doc-move"/ );
228 256 assert.
match (docs,
/CORE-SYSTEM/ );
229 - assert.
match (docs,
/Graph/ );
257 + assert.
match (docs,
/Reference graph/ );
258 + assert.
match (docs,
/System reference graph/ );
230 259 assert.
match (docs,
/Backlinks/ );
260 + assert.
match (docs,
/#ededed/ );
261 + assert.
match (docs,
/#121212/ );
262 + assert.
match (docs,
/prefers-color-scheme:dark/ );
231 263 assert.
match (docs,
/PX-PHASE-PHASE001/ );
232 264 assert.
match (docs,
/spec/ );
233 265 assert.
match (docs,
/class="system-article"/ );
extensions/the-system/documents.ts Modified 73 73 export type DocumentType = (
typeof DOCUMENT_TYPES)[
number ];
74 - export type SystemConfig = Readonly <{ prefix
: string ; schemaVersion
: number }>;
74 + export type SystemConfig = Readonly <{
76 + schemaVersion
: number ;
75 79 export type InspectedSystemConfig = Readonly <{
76 80 config
: SystemConfig ;
77 81 legacyStyleVersion
?: number ;
244 248 `Duplicate config keys: ${duplicates. join (", ")}` ,
246 250 const value
= objectValue (parsed,
"Config" );
247 - exactKeys (value, [
"prefix" ,
"schemaVersion" ]);
251 + const keys
= Object .
keys (value).
sort ();
252 + const validKeys
= [
"prefix" ,
"schemaVersion" ,
"title" ];
254 + ! (
"prefix" in value)
|| 255 + ! (
"schemaVersion" in value)
|| 256 + keys.
some ((key)
=> ! validKeys.
includes (key))
258 + throw new SystemDocumentError (
260 + `Expected keys prefix, schemaVersion[, title]; received ${keys. join (", ")}` ,
248 262 if (
typeof value.
prefix !== "string" || ! PREFIX.
test (value.
prefix ))
249 263 throw new SystemDocumentError (
"config.prefix" ,
"Invalid project prefix" );
250 264 if (
! positiveInteger (value.schemaVersion))
252 266 "config.version" ,
253 267 "Schema version must be a positive integer" ,
255 - return { prefix: value.
prefix , schemaVersion: value.schemaVersion
as number };
270 + "title" in value
&& 271 + (
typeof value.
title !== "string" || value.
title .
trim ()
=== "" )
273 + throw new SystemDocumentError (
"config.title" ,
"Invalid project title" );
275 + prefix: value.
prefix ,
276 + schemaVersion: value.schemaVersion
as number ,
277 + ... (
typeof value.
title === "string" ? { title: value.
title }
: {}),
258 281 export function inspectSystemConfig (source
: string )
: InspectedSystemConfig {
extensions/the-system/init.ts Modified 8 + import path
from "node:path" ;
9 10 discoverProjectRoot,
10 11 inspectSystemConfig,
46 47 const CONFIG
= ".system/config.json" ;
47 48 const CSS
= ".system/system.css" ;
49 + const CORE_CONTENT
: Readonly <
Record <(
typeof CORES)[
number ],
string >>
= {
50 + ".system/SYSTEM.md" :
51 + "# SYSTEM\n\nStable project identity, domain truths, architecture invariants, and non-negotiable conventions.\nKeep durable; do not put current tasks here.\n" ,
52 + ".system/MISSION.md" :
53 + "# MISSION\n\nCurrent objective and why it matters now.\nUpdate when project direction changes.\n" ,
55 + "# RULES\n\nConcrete operating constraints: commands, safety, style, boundaries, and do/don't rules.\nKeep executable; avoid goals and rationale unless needed.\n" ,
48 57 export const DEFAULT_MACHINE_STATE
: MachineState = Object .
freeze ({
49 58 schemaVersion: SCHEMA_VERSION,
84 + const projectTitle = (root
: string )
=> path.
basename (
root )
|| "Project" ;
75 85 const validatePrefix = (prefix
: string , state
: MachineState )
=> {
77 - JSON .
stringify ({ prefix, schemaVersion: state.schemaVersion }),
89 + schemaVersion: state.schemaVersion,
81 - const configSource = (prefix
: string , state
: MachineState )
=> 82 - `${ JSON . stringify ({ prefix, schemaVersion: state.schemaVersion }, null, "\t")}\n` ;
95 + const configSource = (root
: string , prefix
: string , state
: MachineState )
=> 97 + { prefix, schemaVersion: state.schemaVersion, title: projectTitle ( root ) }, 84 102 export function inspectInitialization (
118 136 `${CONFIG} schemaVersion ${config.schemaVersion} -> ${state.schemaVersion}${inspected?.legacyStyleVersion ? "; remove styleVersion" : ""}` ,
138 + if (config
&& ! config.
title )
139 + upgrades.
push (
`${CONFIG} add title "${ projectTitle ( root )}"` );
120 140 if (cssKind
=== "file" )
121 141 upgrades.
push (
`${ CSS } remove obsolete machine-owned asset` );
162 182 target (inspection.root, CONFIG),
163 - configSource (inspection.
prefix , state),
183 + configSource (inspection.root, inspection.
prefix , state),
164 184 kind (
target (inspection.root, CONFIG))
=== "missing" 165 185 ? { encoding:
"utf8" , flag:
"wx" }
170 190 for (
const core
of inspection.cores) {
171 191 if (core.state
!== "missing" )
continue ;
172 - writeFileSync (
target (inspection.root, core.path),
"" , {
192 + writeFileSync (
target (inspection.root, core.path), CORE_CONTENT[core.path], {
173 193 encoding:
"utf8" ,
extensions/the-system/system-command.ts Modified 155 155 ctx : ExtensionCommandContext,
156 156 ):
Promise <void> {
158 - args.trim() || (await ctx.ui.input(
"Project prefix" ,
"SYS" ));
157 + let requested
= args.
trim ()
|| undefined ;
158 + let inspection
= inspectInitialization (ctx.cwd, requested);
159 + requested ??= inspection.prefix;
159 160 if (!requested) {
160 - ctx.ui.notify(
"/system init cancelled" ,
"info" );
161 + requested
= await ctx.ui.
input (
"Project prefix" ,
"SYS" );
163 + ctx.ui.
notify (
"/system init cancelled" ,
"info" );
166 + inspection
= inspectInitialization (ctx.cwd, requested);
163 - const inspection = inspectInitialization(ctx.cwd, requested);
164 168 const summary
= [
165 169 `Root: ${inspection.root}` ,
166 170 `Prefix: ${inspection. prefix }` ,
extensions/the-system/system-prompts.ts Modified 19 19 - plan : id,
type : plan, title, spec, optional phase,
status : draft
| done
20 20 - issue : id,
type : issue, title,
specs : string[],
status : open
| done
22 - Research references no System stage.
22 + Research references no System stage type.
23 23 Specs may reference research.
24 24 Phases reference one spec.
25 25 Plans reference one spec and may reference one phase for the same spec.
extensions/the-system/system-renderer.ts Modified 26 26 import remarkRehype
from "remark-rehype" ;
27 27 import { unified }
from "unified" ;
28 28 import { visit }
from "unist-util-visit" ;
30 - BundleDocumentRecord,
30 + type BundleDocumentRecord,
32 + type DocumentMetadata,
33 34 }
from "./documents.ts" ;
34 35 import type { FrontmatterMap, FrontmatterValue }
from "./markdown.ts" ;
106 107 const rendered
= renderAll (input, directory);
107 108 const diagnostics
= [
... input.diagnostics,
... referenceDiagnostics (input)];
108 109 writePages (directory, rendered, diagnostics,
"book" );
110 + const title
= `${ projectName (input.root)} Dossier` ;
110 112 path.
join (directory,
"index.html" ),
113 - bookBody (rendered, diagnostics),
115 + bookBody (title, rendered, diagnostics),
115 - "assets/mermaid.esm.min.mjs" ,
117 + "assets/mermaid.min.js" ,
116 118 "assets/minisearch.js" ,
120 122 return { file: path.
join (directory,
"index.html" ), directory };
125 + const projectName = (root
: string )
=> {
129 + readFileSync (path.
join (
root ,
".system/config.json" ),
"utf8" ),
131 + path.
basename (
root )
?? 135 + return path.
basename (
root )
|| "Project" ;
123 139 const createOutput = (input
: RenderInput )
: string => {
124 140 const directory
= mkdtempSync (path.
join (
tmpdir (),
"system-render-" ));
125 141 copyBundles (input.root, input.documents, directory);
169 185 `${controls ? `<nav class="doc-move">${controls}</nav>` : ""}${ document .article}${ diagnosticsHtml (diagnostics)}` ,
171 - rel (
document .outputPath,
"assets/mermaid.esm.min.mjs" ),
187 + rel (
document .outputPath,
"assets/mermaid.min.js" ),
172 188 rel (
document .outputPath,
"assets/minisearch.js" ),
442 458 return value.
trim ();
461 + const GROUP_LABELS
: Readonly <
Record <(
typeof GROUPS)[
number ],
string >>
= {
467 + research:
"Research" ,
445 470 const bookBody = (
446 472 documents
: readonly RenderedDocument [],
447 473 diagnostics
: readonly Diagnostic [],
475 + const nav
= bookNav (documents);
476 + const diagnosticNav
= diagnostics.
length 477 + ? '<a href="#diagnostics">Diagnostics</a>' 479 + const diagnosticPanel
= diagnostics.
length 480 + ? `<section>${ diagnosticsHtml (diagnostics, documents)}</section>` 482 + const diagnosticStat
= diagnostics.
length 483 + ? `<p class="stats"><span class="bad">${diagnostics. length } diagnostics</span></p>` 485 + return `<header class="book-top" id="book-overview"><a class="brand" href="#book-overview">${ esc (title)}</a><label class="book-search"><span>Search</span><span class="search-row"><input id="search" type="search" autocomplete="off"><button type="button" id="search-button">Search</button></span><ol id="results" class="search-results" aria-live="polite"></ol></label>${diagnosticStat}</header><div class="book-shell"><nav class="mobile-nav"><details open><summary>Book navigation</summary>${nav}</details><details><summary>On this page</summary><a href="#book-overview">Overview</a><a href="#reference-graph">Reference graph</a>${diagnosticNav}</details></nav><aside class="book-nav">${nav}</aside><main class="book-main"><section class="book-head"><h1>${ esc (title)}</h1><div class="overview-grid"><section>${ graphHtml (documents)}</section>${diagnosticPanel}</div></section>${documents 488 + `<section id="${ esc ( document . id )}" class="book-section">${ document .article}</section>`, 492 + )}</main><aside class="book-toc"><h2>On this page</h2><a href="#book-overview">Overview</a><a href="#reference-graph">Reference graph</a>${diagnosticNav}</aside></div><script type="application/json" id="search-data">${ jsonScript (documents. map (({ id, title, type, text }) => ({ id, title, type, text, href: `#${id}` })))}</script><script>${ searchScript ()}</script>` ;
495 + const bookNav = (documents
: readonly RenderedDocument [])
: string => {
449 496 const byType
= new Map (
450 497 GROUPS.
map ((group)
=> [group, []
as RenderedDocument []]),
452 499 for (
const document
of documents)
453 500 byType.
get (
document .
type as (
typeof GROUPS)[
number ])?.
push (
document );
454 - const nav
= GROUPS.
map ((group)
=> {
501 + return GROUPS.
map ((group)
=> {
455 502 const items
= byType.
get (group)
?? [];
456 503 if (
! items.
length )
return "" ;
457 - return `<section><h2>${ esc (group)}</h2><ol>${items 460 - `<li><a href="#${ esc (item. id )}">${ esc (item. id )}</a> <a href="${ esc (item.outputPath)}">${ esc (item. title )}</a></li>`, 462 - . join ("")}</ol></section>` ;
504 + return `<details ${group === "law" || group === "spec" ? "open" : ""}><summary>${GROUP_LABELS[group]} <span class="count">${items. length }</span></summary>${items 505 + . map ((item) => navItem (item)) 506 + . join ("")}</details>` ;
464 - return `<header class="book-head"><h1>The System Docs</h1><p>Ephemeral rendered dossier.</p></header><label class="search">Search <input id="search" type="search" autocomplete="off"></label><ol id="results"></ol><nav class="book-nav">${nav}</nav>${ graphHtml (documents)}${ diagnosticsHtml (diagnostics)}${documents 467 - `<section id="${ esc ( document . id )}">${ document .article}</section>`, 471 - )}<script type="application/json" id="search-data">${ jsonScript (documents. map (({ id, title, type, text, outputPath }) => ({ id, title, type, text, outputPath })))}</script><script>${ searchScript ()}</script>` ;
510 + const navItem = (item
: RenderedDocument )
: string => {
511 + const label
= item.
type === "law" ? item.
id : `${item. id } ${item. title }` ;
512 + return `<a href="#${ esc (item. id )}">${ esc (label)}</a>` ;
474 515 const graphHtml = (documents
: readonly RenderedDocument [])
=> {
475 516 const byId
= new Map (documents.
map ((document)
=> [
document .
id ,
document ]));
476 - const rows
= documents.
flatMap ((document)
=> {
517 + const linked
= documents.
filter ((document)
=> {
518 + const backlinks
= documents.
some ((candidate)
=> 519 + candidate.refs.
includes (
document .
id ),
521 + return document .refs.
some ((id)
=> byId.
has (id))
|| backlinks;
523 + if (
! linked.
length )
524 + return `<section id="reference-graph" class="graph"><h3>Reference graph</h3><p>No references yet.</p></section>` ;
525 + const nodes
= linked.
slice (
0 ,
24 );
526 + const columns
= new Map (GROUPS.
map ((group, index)
=> [group, index]));
527 + const rowByType
= new Map <
string ,
number >();
528 + const positions
= new Map (
529 + nodes.
map ((document)
=> {
530 + const type
= document .
type as (
typeof GROUPS)[
number ];
531 + const row
= rowByType.
get (type)
?? 0 ;
532 + rowByType.
set (type, row
+ 1 );
535 + { x:
24 + (columns.
get (type)
?? 0 )
* 180 , y:
28 + row
* 64 },
539 + const height
= Math .
max (
180 ,
Math .
max (
... rowByType.
values ())
* 64 + 50 );
540 + const lines
= nodes.
flatMap ((document)
=> {
541 + const from
= positions.
get (
document .
id );
542 + if (
! from)
return [];
543 + return document .refs.
flatMap ((id)
=> {
544 + const to
= positions.
get (id);
545 + if (
! to)
return [];
546 + return `<line x1="${from. x + 152}" y1="${from. y + 20}" x2="${to. x }" y2="${to. y + 20}"></line>` ;
549 + const boxes
= nodes
550 + .
map ((document)
=> {
551 + const position
= positions.
get (
document .
id );
552 + if (
! position)
return "" ;
553 + return `<a href="#${ esc ( document . id )}"><title>${ esc ( document . id )} ${ esc ( document . title )}</title><rect x="${position. x }" y="${position. y }" width="152" height="40" rx="2"></rect><text x="${position. x + 8}" y="${position. y + 24}">${ esc ( shortLabel ( document ))}</text></a>` ;
556 + const rows
= linked.
map ((document)
=> {
477 557 const backlinks
= documents
478 558 .
filter ((candidate)
=> candidate.refs.
includes (
document .
id ))
479 559 .
map ((candidate)
=> candidate.
id );
480 - if (
! document .refs.
length && ! backlinks.
length )
return [];
482 - `<tr><th>${ esc ( document . id )}</th><td>${ document .refs. map ((id) => graphLink (id, byId)). join (", ")}</td><td>${backlinks. map ((id) => graphLink (id, byId)). join (", ")}</td></tr>` ,
560 + return `<li><a href="#${ esc ( document . id )}">${ esc ( document . id )}</a><br>References: ${ document .refs. map ((id) => graphLink (id, byId)). join (", ") || "none"}<br>Backlinks: ${backlinks. map ((id) => graphLink (id, byId)). join (", ") || "none"}</li>` ;
485 - if (
! rows.
length )
return "" ;
486 - return `<section class="graph"><h2>Graph</h2><table><tr><th>Document</th><th>References</th><th>Backlinks</th></tr>${rows. join ("")}</table></section>` ;
562 + return `<section id="reference-graph" class="graph"><h3>Reference graph</h3><svg viewBox="0 0 1100 ${height}" role="img" aria-label="System reference graph">${lines. join ("")}${boxes}</svg><ol class="graph-list">${rows. join ("")}</ol></section>` ;
565 + const shortLabel = (document
: RenderedDocument )
=> {
566 + if (
document .
type === "law" )
return document .
title ;
567 + const [prefix, type, token]
= document .
id .
split (
"-" );
568 + return `${type ?? prefix}-${token ?? ""}` .
slice (
0 ,
18 );
489 571 const graphLink = (id
: string , byId
: ReadonlyMap <
string ,
RenderedDocument >)
=> {
523 - const diagnosticsHtml = (diagnostics
: readonly Diagnostic [])
=> {
524 - if (
! diagnostics.
length )
return "" ;
525 - return `<aside class="diagnostics"><h2>Diagnostics</h2><ol>${diagnostics 528 - `<li><code>${ esc (item.path)}</code> <strong>${ esc (item. code )}</strong> ${ esc (item.message)}</li>`, 605 + const diagnosticsHtml = (
606 + diagnostics
: readonly Diagnostic [],
607 + documents
: readonly RenderedDocument []
= [],
609 + if (
! diagnostics.
length && documents.
length === 0 )
return "" ;
610 + if (
! diagnostics.
length )
611 + return `<aside class="diagnostics ok" id="diagnostics"><h2>Diagnostics</h2><p>No diagnostics.</p></aside>` ;
612 + return `<aside class="diagnostics" id="diagnostics"><h2>Diagnostics</h2><ol>${diagnostics 614 + const href = diagnosticHref (item, documents); 615 + const target = href 616 + ? `<a href="${href}"><code>${ esc (item.path)}</code></a>` 617 + : `<code>${ esc (item.path)}</code>`; 618 + return `<li>${target} <strong>${ esc (item. code )}</strong> ${ esc (item.message)}</li>`; 530 620 . join ("")}</ol></aside>` ;
623 + const diagnosticHref = (
624 + diagnostic
: Diagnostic ,
625 + documents
: readonly RenderedDocument [],
627 + const source
= diagnostic.path.
split (
":" ,
1 )[
0 ];
628 + const document
= documents.
find ((item)
=> item.sourcePath
=== source);
629 + return document ? `#${ esc ( document . id )}` : undefined ;
533 632 const copyBundles = (
535 634 documents
: readonly RenderDocumentInput [],
549 648 const copyMermaid = (outputRoot
: string )
=> {
550 649 const mermaid
= path.
join (
551 650 path.
dirname (
fileURLToPath (
import .
meta .
resolve (
"mermaid/package.json" ))),
552 - "dist/mermaid.esm.min.mjs" ,
651 + "dist/mermaid.min.js" ,
554 653 if (
! existsSync (mermaid))
return ;
555 654 mkdirSync (path.
join (outputRoot,
"assets" ), { recursive:
true });
556 - copyFileSync (mermaid, path.
join (outputRoot,
"assets/mermaid.esm.min.mjs" ));
655 + copyFileSync (mermaid, path.
join (outputRoot,
"assets/mermaid.min.js" ));
559 658 const copyMiniSearch = (outputRoot
: string )
=> {
576 675 mermaidPath : string,
577 676 miniSearchPath : string,
578 677 )
=> `<!doctype html> 579 679 <meta charset="utf-8"> 580 680 <meta name="viewport" content="width=device-width,initial-scale=1"> 681 + <meta name="description" content="${ esc (title)}"> 682 + <link rel="icon" href="${ favicon (title)}"> 581 683 <title>${ esc (title)}</title> 582 684 <style>${ css ()}</style> 583 - <body data-mode="${mode}"><script src="${ esc (miniSearchPath)}"></script>${body}<script type="module">const mermaid=(await Function('p','return import(p)')('${ esc (mermaidPath)}')).default;mermaid.initialize({startOnLoad:true,theme:matchMedia('(prefers-color-scheme: dark)').matches?'dark':'default'});</script></body>` ;
685 + <body data-mode="${mode}"><script src="${ esc (miniSearchPath)}"></script>${body}<script src="${ esc (mermaidPath)}"></script><script>if(globalThis.mermaid){const theme=matchMedia('(prefers-color-scheme: dark)').matches?'dark':'default';globalThis.mermaid.initialize({startOnLoad:true,theme})}</script></body> 586 - `:root{color-scheme:light dark;--bg:#f6f2ef;--panel:#fffaf7;--text:#16100d;--muted:#6f625d;--line:#d8ccc6;--accent:#b0177a;--link:#006d80;--warn:#9a5b00;--error:#b00020;--code:#eee5df}@media(prefers-color-scheme:dark){:root{--bg:#151112;--panel:#21191b;--text:#f3e8e3;--muted:#b9aaa4;--line:#3a2d30;--accent:#ff6fca;--link:#5dd7e8;--warn:#ffc464;--error:#ff6f80;--code:#2f2527}}body{font-family:system-ui,sans-serif;line-height:1.55;margin:0;color:var(--text);background:var(--bg)}body[data-mode=single]{max-width:78rem;margin:2rem auto;padding:0 1rem}.book-head,.book-nav,.search,.diagnostics,.graph,.system-article,.doc-move{display:block;max-width:78rem;margin:1rem auto;padding:1rem;background:var(--panel);border:1px solid var(--line);border-radius:.5rem}.system-article{margin-block:2rem}a{color:var(--link)}.eyebrow,.source,.summary{color:var(--muted)}code,pre{font-family:ui-monospace,SFMono-Regular,Menlo,monospace}pre{padding:1rem;overflow:auto;background:var(--code);border:1px solid var(--line)}table{border-collapse:collapse;width:100%;margin:.5rem 0}th,td{border:1px solid var(--line);padding:.35rem;text-align:left;vertical-align:top}.ledger ol{margin:0}.toc ol,.book-nav ol,#results{margin:.5rem 0}.depth-3{margin-left:1rem}.depth-4,.depth-5,.depth-6{margin-left:2rem}.diagnostics{border-color:var(--warn)}.diagnostics strong{color:var(--warn)}.mockup-preview iframe{width:100%;min-height:22rem;border:1px solid var(--line);background:white}.hljs{background:transparent}.math{overflow:auto}.search input{margin-left:.5rem;max-width:32rem;width:60%}` ;
688 + const favicon = (title
: string )
=> {
689 + const initial
= esc ((title.
trim ()[
0 ]
?? "P" ).
toUpperCase ());
690 + const svg
= `<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 64 64'><rect width='64' height='64' fill='%23ededed'/><text x='32' y='42' text-anchor='middle' font-family='monospace' font-size='34' font-weight='900' fill='%23922792'>${initial}</text></svg>` ;
691 + return `data:image/svg+xml,${svg}` ;
694 + const css = ()
=> String . raw ` 695 + :root{color-scheme:light dark;--bg:#ededed;--panel:#dbdbdb;--page:#ededed;--text:#121212;--muted:#3b3b3b;--line:#5d5d5d;--accent:#922792;--link:#184e5b;--warn:#6e6c10;--error:#bd172e;--info:#116477;--code:#dbdbdb;--mark:#6e6c10} 696 + @media(prefers-color-scheme:dark){:root{--bg:#121212;--panel:#242424;--page:#121212;--text:#ededed;--muted:#8b8b8b;--line:#6f6f6f;--accent:#d86dd8;--link:#7ba1aa;--warn:#f0ee69;--error:#ec6376;--info:#3ec5e3;--code:#242424;--mark:#f0ee69}} 697 + body[data-mode=book]{overflow-x:hidden} 698 + *{box-sizing:border-box}html{scroll-behavior:smooth}body{font-family:system-ui,sans-serif;line-height:1.55;margin:0;color:var(--text);background:var(--bg)}body[data-mode=single]{max-width:78rem;margin:2rem auto;padding:0 1rem}a{color:var(--link)}a:focus-visible,button:focus-visible,input:focus-visible,summary:focus-visible{outline:3px solid var(--accent);outline-offset:2px}button,input{font:inherit}button{cursor:pointer}.brand{font:900 12px ui-monospace,monospace;color:var(--accent);letter-spacing:.1em;text-transform:uppercase;text-decoration:none;align-self:end;padding-bottom:10px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.book-top{position:sticky;top:0;z-index:5;display:grid;grid-template-columns:minmax(180px,220px) minmax(260px,1fr) max-content;gap:14px;align-items:end;background:var(--panel);border-bottom:2px solid var(--line);padding:10px 26px}.book-search{position:relative;display:grid;gap:4px;font:800 11px ui-monospace,monospace;color:var(--muted);text-transform:uppercase}.search-row{display:flex;gap:8px}.search-row input{width:100%;min-width:0;background:var(--bg);color:var(--text);border:2px solid var(--line);padding:8px;text-transform:none}.search-row button{background:var(--accent);color:var(--bg);border:0;padding:8px 12px;font-weight:900}.search-results{position:absolute;left:0;right:0;top:100%;z-index:8;display:grid;gap:6px;margin:6px 0 0;padding:0;list-style:none;background:var(--bg);border:2px solid var(--line);box-shadow:0 10px 24px color-mix(in srgb,var(--text),transparent 86%)}.search-results:empty{display:none}.search-results li{border-left:4px solid var(--accent);padding:7px 9px;background:var(--panel);text-transform:none}.search-results small{color:var(--muted)}mark{background:color-mix(in srgb,var(--mark),transparent 35%);color:var(--text);padding:0 .1em}.stats{display:flex;gap:8px;margin:0 0 10px;justify-content:end;font-variant-numeric:tabular-nums}.stats span{border:1px solid var(--line);background:var(--bg);padding:4px 7px;white-space:nowrap}.stats .bad{border-color:var(--error);color:var(--error)}.stats .ok{border-color:var(--info);color:var(--info)}.book-shell{display:grid;grid-template-columns:220px minmax(0,1fr) 160px;gap:16px;padding:16px 26px;align-items:start}.book-shell>*{min-width:0}.book-nav,.book-toc,.book-head,.system-article,.doc-move,.diagnostics,.graph{background:var(--panel);border:1px solid var(--line)}.book-nav{padding:10px;position:sticky;top:64px;height:calc(100vh - 88px);overflow:auto}.book-nav details{border-bottom:1px solid var(--line);padding:7px 0}.book-nav summary{font:900 11px ui-monospace,monospace;text-transform:uppercase;color:var(--muted);cursor:pointer}.book-nav a{display:block;text-decoration:none;padding:4px 6px 4px 12px;border-left:3px solid transparent;overflow-wrap:anywhere}.book-nav a:hover{border-color:var(--accent);background:color-mix(in srgb,var(--accent),transparent 88%)}.count{float:right;color:var(--muted);font-weight:400}.book-main{display:grid;gap:16px;min-width:0}.book-head{padding:18px;overflow:hidden}.book-head h1{margin:0;font:900 32px/1.05 Georgia,serif}.book-head p{color:var(--muted)}.overview-grid{display:grid;grid-template-columns:1fr;gap:12px}.overview-grid>section,.overview-grid aside{min-width:0}.book-toc{padding:12px;max-height:calc(100vh - 104px);overflow:auto;position:sticky;top:88px;font-size:13px;z-index:1}.book-toc h2{margin-top:0;color:var(--accent);font:800 12px ui-monospace,monospace;text-transform:uppercase}.book-toc a{display:block;color:var(--muted);margin:6px 0;text-decoration:none}.mobile-nav{display:none}.book-section{scroll-margin-top:72px}.system-article{display:block;padding:28px 40px;background:var(--page);margin-block:0;overflow:hidden}.system-article+.diagnostics{margin-top:1rem}.mast h1{font:800 34px/1.1 Georgia,serif;margin:.2rem 0 1rem}.eyebrow,.source,.summary{color:var(--muted)}.eyebrow{font:800 11px ui-monospace,monospace;text-transform:uppercase}.source{overflow-wrap:anywhere}.doc-move{display:flex;justify-content:space-between;gap:1rem;margin:1rem 0;padding:1rem}.ledger,.toc{border:1px solid var(--line);background:var(--panel);padding:.7rem;margin:1rem 0}.toc ol{margin:.5rem 0}.depth-3{margin-left:1rem}.depth-4,.depth-5,.depth-6{margin-left:2rem}code,pre{font-family:ui-monospace,SFMono-Regular,Menlo,monospace}pre{padding:1rem;overflow:auto;background:var(--code);border:1px solid var(--line)}table{border-collapse:collapse;width:100%;margin:.5rem 0;display:block;overflow:auto}th,td{border:1px solid var(--line);padding:.35rem;text-align:left;vertical-align:top}.ledger ol{margin:0}.diagnostics{border-color:var(--warn);padding:1rem}.diagnostics h2{margin-top:0}.diagnostics strong{color:var(--warn)}.diagnostics.ok{border-color:var(--info)}.diagnostics li{margin:.4rem 0}.graph{padding:1rem;overflow:hidden}.graph h3{margin-top:0}.graph svg{display:block;width:100%;height:auto;max-height:520px;border:1px solid var(--line);background:var(--panel)}.graph line{stroke:var(--line);stroke-width:2}.graph a rect{fill:var(--bg);stroke:var(--accent);stroke-width:2}.graph a:hover rect{fill:color-mix(in srgb,var(--accent),transparent 86%)}.graph text{fill:var(--text);font:700 11px ui-monospace,monospace}.graph-list{display:none}.mockup-preview iframe{width:100%;min-height:22rem;border:1px solid var(--line);background:white}.hljs{background:transparent}.math{overflow:auto}@media(max-width:980px){.book-top{grid-template-columns:1fr;position:static}.search-results{position:static}.stats{justify-content:start;flex-wrap:wrap}.book-shell{display:block;padding:10px}.book-nav,.book-toc{display:none}.mobile-nav{display:grid;gap:8px;margin-bottom:10px}.mobile-nav details{background:var(--panel);border:1px solid var(--line);padding:8px}.mobile-nav .book-nav{display:block;position:static;height:auto;border:0;padding:0}.overview-grid{grid-template-columns:1fr}.system-article{padding:20px 18px}.mast h1{font-size:28px}.doc-move{flex-wrap:wrap}}@media(max-width:620px){body{font-size:15px}.book-top{padding:10px}.search-row{display:grid}.search-row button{width:100%}.book-shell{padding:8px}.book-head{padding:14px}.system-article{padding:18px 14px;border-left:0;border-right:0}.stats span{font-size:12px}.graph svg{display:none}.graph-list{display:block}}@media print{.book-top,.book-nav,.book-toc,.book-head,.doc-move,.mobile-nav{display:none}.book-shell{display:block;padding:0}.system-article{border:0;background:white;color:black;max-width:none;padding:0;font:12pt/1.55 Georgia,serif}.mast h1{break-before:page}.diagnostics{break-inside:avoid;border-color:#777;background:#eee}mark{background:#ddd}} 588 701 const jsonScript = (value
: unknown )
=> 589 702 JSON .
stringify (value).
replaceAll (
"<" ,
"\\u003c" ).
replaceAll (
"&" ,
"\\u0026" );
591 704 const searchScript = ()
=> 592 - `const data=JSON.parse(document.getElementById('search-data').textContent);const index=new MiniSearch({fields:['id','title','type','text'],storeFields:['id','title','type','text','outputPath']});index.addAll(data);const input=document.getElementById('search');const out=document.getElementById('results');input.addEventListener('input',()=>{const q=input.value.trim();out.textContent='';if(!q)return;for(const item of index.search(q,{prefix:true,fuzzy:.2}).slice(0,20)){const li=document.createElement('li');const a=document.createElement('a');const body=item.text||'';const at=body.toLowerCase().indexOf(q.toLowerCase());const start=Math.max(0,at-40);const context=at<0?'':body.slice(start,at+q.length+80);a.href=item.outputPath;a.textContent=item.id+' '+item.title;li.append(a,' — '+item.type+(context?' — '+context:''));out.append(li)}});` ;
705 + `const data=JSON.parse(document.getElementById('search-data').textContent);const index=new MiniSearch({fields:['id','title','type','text'],storeFields:['id','title','type','text','href']});index.addAll(data);const input=document.getElementById('search');const button=document.getElementById('search-button');const out=document.getElementById('results');const terms=()=>input.value.trim().toLowerCase().split(/\\s+/).filter(Boolean);function appendHits(node,text,parts){let i=0;const lower=text.toLowerCase();while(i<text.length){let hit=-1,term='';for(const part of parts){const at=lower.indexOf(part,i);if(at>=0&&(hit<0||at<hit)){hit=at;term=part}}if(hit<0){node.append(document.createTextNode(text.slice(i)));break}node.append(document.createTextNode(text.slice(i,hit)));const mark=document.createElement('mark');mark.dataset.searchHit='';mark.textContent=text.slice(hit,hit+term.length);node.append(mark);i=hit+term.length}}function clearArticleHits(){for(const mark of document.querySelectorAll('mark[data-search-hit]'))mark.replaceWith(document.createTextNode(mark.textContent||''))}function highlightArticle(id,parts){clearArticleHits();const root=document.getElementById(id);if(!root||!parts.length)return;const walker=document.createTreeWalker(root,NodeFilter.SHOW_TEXT,{acceptNode(node){const parent=node.parentElement;if(!parent||['SCRIPT','STYLE','TEXTAREA','INPUT','MARK'].includes(parent.tagName))return NodeFilter.FILTER_REJECT;return parts.some(part=>(node.nodeValue||'').toLowerCase().includes(part))?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_REJECT}});const hits=[];while(hits.length<80){const node=walker.nextNode();if(!node)break;hits.push(node)}for(const node of hits){const span=document.createDocumentFragment();appendHits(span,node.nodeValue||'',parts);node.replaceWith(span)}}function render(){const q=input.value.trim();const parts=terms();out.textContent='';if(!q)return;for(const item of index.search(q,{prefix:true,fuzzy:.2}).slice(0,20)){const li=document.createElement('li');const a=document.createElement('a');const body=item.text||'';const lower=body.toLowerCase();const at=Math.min(...parts.map(part=>{const found=lower.indexOf(part);return found<0?Number.POSITIVE_INFINITY:found}));const start=Number.isFinite(at)?Math.max(0,at-40):0;const context=body.slice(start,Number.isFinite(at)?at+120:120);a.href=item.href;a.textContent=item.id+' '+item.title;const small=document.createElement('small');appendHits(small,context,parts);a.addEventListener('click',()=>{highlightArticle(item.id,parts);out.textContent=''});li.append(a,document.createElement('br'),small);out.append(li)}}input.addEventListener('input',render);button?.addEventListener('click',()=>{render();out.querySelector('a')?.click()});` ;
594 707 const esc = (value
: string )
=>