import assert from "node:assert/strict"; import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync, } from "node:fs"; import { tmpdir } from "node:os"; import path from "node:path"; import { afterEach, describe, it } from "vitest"; import { discoverProjectRoot, indexDocuments, parseDocumentId, parseDocumentMetadata, parseSystemConfig, resolveGovernedPath, SystemDocumentError, validateAuthoredHtml, validateFilename, } from "../documents.ts"; const temporary: string[] = []; const tree = () => { const root = mkdtempSync(path.join(tmpdir(), "the-system-documents-")); temporary.push(root); return root; }; const dir = (...parts: string[]) => { const result = path.join(...parts); mkdirSync(result, { recursive: true }); return result; }; afterEach(() => { for (const root of temporary.splice(0)) rmSync(root, { recursive: true, force: true }); }); describe("project root", () => { it.each([ ["simple Git", [".git"], "directory"], ["Git worktree", [".git"], "file"], ["JJ workspace", [".jj"], "directory"], ["colocated JJ/Git", [".jj", ".git"], "directory"], ] as const)("resolves %s", (_name, markers, markerKind) => { const root = tree(); const cwd = dir(root, "packages", "app"); for (const marker of markers) { const target = path.join(root, marker); if (markerKind === "file" && marker === ".git") writeFileSync(target, "gitdir: ../shared\n"); else mkdirSync(target); } assert.equal(discoverProjectRoot(cwd), root); }); it("uses cwd when no VCS marker exists", () => { const cwd = dir(tree(), "plain"); assert.equal(discoverProjectRoot(cwd), path.resolve(cwd)); }); it("fails when nearest JJ and Git roots differ", () => { const gitRoot = tree(); mkdirSync(path.join(gitRoot, ".git")); const jjRoot = dir(gitRoot, "nested"); mkdirSync(path.join(jjRoot, ".jj")); const cwd = dir(jjRoot, "src"); assert.throws( () => discoverProjectRoot(cwd), (error: unknown) => error instanceof SystemDocumentError && error.code === "root.conflict" && error.message === `Conflicting project roots: Git ${gitRoot}; JJ ${jjRoot}`, ); }); }); describe("governed path containment", () => { it("normalizes a contained relative path", () => { const root = path.resolve("project"); assert.equal( resolveGovernedPath(root, ".system/specs/../plans/a.html"), path.join(root, ".system", "plans", "a.html"), ); }); it.each([ "../outside", path.resolve("outside"), ])("rejects %s", (candidate) => { assert.throws( () => resolveGovernedPath(path.resolve("project"), candidate), (error: unknown) => error instanceof SystemDocumentError && error.code === "path.outside-root", ); }); it("does not confuse a sibling sharing the root prefix for a child", () => { const root = path.resolve("project"); assert.throws( () => resolveGovernedPath(root, path.resolve("project-other/file")), /outside project root/, ); }); }); describe("system config", () => { it("accepts only the exact versioned shape", () => { assert.deepEqual( parseSystemConfig('{"prefix":"PX","schemaVersion":1,"styleVersion":1}'), { prefix: "PX", schemaVersion: 1, styleVersion: 1, }, ); }); it("rejects duplicate config keys", () => assert.throws( () => parseSystemConfig( '{"prefix":"PX","prefix":"AB","schemaVersion":1,"styleVersion":1}', ), (error: unknown) => error instanceof SystemDocumentError && error.code === "config.duplicate-key", )); it.each([ ["malformed JSON", "{"], [ "unknown key", '{"prefix":"PX","schemaVersion":1,"styleVersion":1,"extra":true}', ], ["missing key", '{"prefix":"PX","schemaVersion":1}'], ["short prefix", '{"prefix":"P","schemaVersion":1,"styleVersion":1}'], ["lowercase prefix", '{"prefix":"px","schemaVersion":1,"styleVersion":1}'], ["zero schema", '{"prefix":"PX","schemaVersion":0,"styleVersion":1}'], [ "fractional style", '{"prefix":"PX","schemaVersion":1,"styleVersion":1.5}', ], ])("rejects %s", (_name, source) => assert.throws(() => parseSystemConfig(source), SystemDocumentError)); }); describe("document IDs and filenames", () => { it.each([ ["PX-SPEC-001", "spec", 1], ["PX-ROADMAP-999", "roadmap", 999], ["PX-PLAN-1000", "plan", 1000], ["PX-ISSUE-042", "issue", 42], ["PX-RESEARCH-007", "research", 7], ] as const)("parses %s", (id, type, sequence) => { assert.deepEqual(parseDocumentId(id, "PX"), { id, prefix: "PX", type, sequence, }); }); it.each([ "P-SPEC-001", "px-SPEC-001", "PX-spec-001", "PX-SPEC-01", "PX-SPEC-000", "PX-SPEC-0001", "PX-TEST-001", "PX-SPEC-001-slug", ])("rejects invalid ID %s", (id) => assert.throws(() => parseDocumentId(id), /Invalid document ID/)); it("rejects a foreign configured prefix", () => assert.throws(() => parseDocumentId("AB-SPEC-001", "PX"), /prefix PX/)); it("accepts a matching type directory, ID, and slug", () => { assert.doesNotThrow(() => validateFilename( "/project/.system/specs/PX-SPEC-001-login-flow.html", { id: "PX-SPEC-001", type: "spec" }, "PX", ), ); }); it.each([ "/project/.system/specs/PX-SPEC-002-login-flow.html", "/project/.system/specs/PX-SPEC-001-Login.html", "/project/.system/plans/PX-SPEC-001-login-flow.html", "/project/.system/specs/PX-SPEC-001-login_flow.html", ])("rejects mismatched filename %s", (filename) => { assert.throws( () => validateFilename(filename, { id: "PX-SPEC-001", type: "spec" }, "PX"), /Filename mismatch/, ); }); }); const shell = ( metadata: string, body = "

Title

Contract

Readable.

", ) => ` Title ${body}`; describe("document metadata", () => { it.each([ ['{"id":"PX-SPEC-001","type":"spec"}', { id: "PX-SPEC-001", type: "spec" }], [ '{"id":"PX-ROADMAP-001","type":"roadmap","spec":"PX-SPEC-001"}', { id: "PX-ROADMAP-001", type: "roadmap", spec: "PX-SPEC-001" }, ], [ '{"id":"PX-PLAN-001","type":"plan","spec":"PX-SPEC-001"}', { id: "PX-PLAN-001", type: "plan", spec: "PX-SPEC-001" }, ], [ '{"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, }, ], [ '{"id":"PX-ISSUE-001","type":"issue","status":"open","specs":[]}', { id: "PX-ISSUE-001", type: "issue", status: "open", specs: [] }, ], [ '{"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"], }, ], ] as const)("parses exact metadata %s", (json, expected) => assert.deepEqual(parseDocumentMetadata(shell(json), "PX"), expected)); it("wraps malformed metadata JSON", () => { assert.throws( () => parseDocumentMetadata( shell('{"id":"PX-SPEC-001","type":"spec","\\uZZZZ":true}'), "PX", ), (error: unknown) => error instanceof SystemDocumentError && error.code === "metadata.invalid-json", ); }); it("ignores metadata blocks inside HTML comments", () => { const html = `${shell('{"id":"PX-SPEC-001","type":"spec"}')}`; assert.deepEqual(parseDocumentMetadata(html, "PX"), { id: "PX-SPEC-001", type: "spec", }); }); it.each([ ["missing block", ''], [ "duplicate blocks", shell('{"id":"PX-SPEC-001","type":"spec"}') + '', ], [ "duplicate JSON key", shell('{"id":"PX-SPEC-001","id":"PX-SPEC-002","type":"spec"}'), ], [ "unknown key", shell('{"id":"PX-SPEC-001","type":"spec","status":"open"}'), ], ["own ID/type mismatch", shell('{"id":"PX-PLAN-001","type":"spec"}')], [ "one-sided roadmap", shell( '{"id":"PX-PLAN-001","type":"plan","spec":"PX-SPEC-001","roadmap":"PX-ROADMAP-001"}', ), ], [ "duplicate issue specs", shell( '{"id":"PX-ISSUE-001","type":"issue","status":"fixed","specs":["PX-SPEC-001","PX-SPEC-001"]}', ), ], [ "invalid date", shell( '{"id":"PX-RESEARCH-001","type":"research","capturedAt":"2026-02-30"}', ), ], [ "non-HTTPS source", shell( '{"id":"PX-RESEARCH-001","type":"research","capturedAt":"2026-07-11","sources":["http://example.com"]}', ), ], ])("rejects %s", (_name, html) => assert.throws( () => parseDocumentMetadata(html, "PX"), SystemDocumentError, )); }); describe("authored HTML", () => { it("accepts the complete semantic shell and inert progressive enhancement", () => { const html = shell( '{"id":"PX-SPEC-001","type":"spec"}', "

Title

Contract

More

Text.

", ); assert.deepEqual( validateAuthoredHtml("specs/PX-SPEC-001-title.html", html), [], ); }); it.each([ [ "document.doctype", shell('{"id":"PX-SPEC-001","type":"spec"}').replace( "", "", ), ], [ "document.language", shell('{"id":"PX-SPEC-001","type":"spec"}').replace( 'lang="en"', 'lang="fr"', ), ], [ "document.charset", shell('{"id":"PX-SPEC-001","type":"spec"}').replace( '', "", ), ], [ "document.viewport", shell('{"id":"PX-SPEC-001","type":"spec"}').replace( /]+>/, "", ), ], [ "document.title", shell('{"id":"PX-SPEC-001","type":"spec"}').replace( "Title", "", ), ], [ "document.stylesheet", shell('{"id":"PX-SPEC-001","type":"spec"}').replace( "../system.css", "./local.css", ), ], [ "document.semantic-shell", shell('{"id":"PX-SPEC-001","type":"spec"}').replace( /
|<\/main>/g, "", ), ], [ "document.forbidden-tag", shell( '{"id":"PX-SPEC-001","type":"spec"}', '

X

', ), ], [ "document.event-handler", shell( '{"id":"PX-SPEC-001","type":"spec"}', '

X

X
', ), ], [ "document.executable-url", shell( '{"id":"PX-SPEC-001","type":"spec"}', '

X

X
', ), ], [ "document.external-script", shell( '{"id":"PX-SPEC-001","type":"spec"}', '

X

X
', ), ], [ "document.active-api", shell( '{"id":"PX-SPEC-001","type":"spec"}', "

X

X
", ), ], [ "document.css-resource", shell( '{"id":"PX-SPEC-001","type":"spec"}', "

X

X
", ), ], [ "document.meta-refresh", shell('{"id":"PX-SPEC-001","type":"spec"}').replace( "", '', ), ], ])("reports %s", (code, html) => assert.ok( validateAuthoredHtml("doc.html", html).some((item) => item.code === code), )); it("ignores shell and forbidden tags inside HTML comments", () => { const html = shell( '{"id":"PX-SPEC-001","type":"spec"}', "", ); const codes = validateAuthoredHtml("doc.html", html).map( ({ code }) => code, ); assert.ok(codes.includes("document.semantic-shell")); assert.ok(!codes.includes("document.forbidden-tag")); }); it.each([ ["missing head close", ""], ["missing body close", ""], ["missing html close", ""], ["missing header close", ""], ["missing main close", "
"], ["missing section close", ""], ] as const)("requires a complete shell: %s", (_name, removed) => { const findings = validateAuthoredHtml( "doc.html", shell('{"id":"PX-SPEC-001","type":"spec"}').replace(removed, ""), ); assert.ok( findings.some( ({ code }) => code === "document.structure" || code === "document.semantic-shell", ), ); }); it.each([ [ "unquoted executable URL", "X", "document.executable-url", ], [ "encoded executable URL with control whitespace", 'X', "document.executable-url", ], [ "unquoted remote src", "", "document.remote-resource", ], [ "encoded remote srcset", '', "document.remote-resource", ], [ "remote poster", '', "document.remote-resource", ], [ "resource-bearing href", '', "document.remote-resource", ], ] as const)("rejects %s", (_name, markup, code) => { const html = shell( '{"id":"PX-SPEC-001","type":"spec"}', `

X

${markup}
`, ); assert.ok( validateAuthoredHtml("doc.html", html).some( (finding) => finding.code === code, ), ); }); it("allows quoted and unquoted remote HTTPS navigation anchors", () => { for (const anchor of [ 'Reference', "Reference", ]) { const html = shell( '{"id":"PX-SPEC-001","type":"spec"}', `

X

${anchor}
`, ); assert.deepEqual(validateAuthoredHtml("doc.html", html), []); } }); }); const source = ( folder: string, id: string, slug: string, metadata: string, ) => ({ path: `/project/.system/${folder}/${id}-${slug}.html`, html: shell(metadata), }); describe("document index", () => { it("indexes a valid complete graph without diagnostics", () => { const result = indexDocuments( [ source( "specs", "PX-SPEC-001", "login", '{"id":"PX-SPEC-001","type":"spec"}', ), source( "roadmaps", "PX-ROADMAP-001", "login", '{"id":"PX-ROADMAP-001","type":"roadmap","spec":"PX-SPEC-001"}', ), source( "plans", "PX-PLAN-001", "login-phase-2", '{"id":"PX-PLAN-001","type":"plan","spec":"PX-SPEC-001","roadmap":"PX-ROADMAP-001","phase":2}', ), source( "issues", "PX-ISSUE-001", "login-error", '{"id":"PX-ISSUE-001","type":"issue","status":"open","specs":["PX-SPEC-001"]}', ), source( "research", "PX-RESEARCH-001", "login", '{"id":"PX-RESEARCH-001","type":"research","capturedAt":"2026-07-11"}', ), ], "PX", ); assert.equal(result.documents.length, 5); assert.deepEqual(result.diagnostics, []); }); it("excludes HTML- and filename-invalid documents from graph edges", () => { const invalidSpec = source( "specs", "PX-SPEC-009", "bad-html", '{"id":"PX-SPEC-009","type":"spec"}', ); invalidSpec.html = invalidSpec.html.replace( "
", "", ); const invalidPlan = source( "plans", "PX-PLAN-002", "invalid-source", '{"id":"PX-PLAN-002","type":"plan","spec":"PX-SPEC-404"}', ); invalidPlan.html = invalidPlan.html.replace("
", ""); const invalidFilenamePlan = source( "plans", "PX-PLAN-004", "invalid-filename-source", '{"id":"PX-PLAN-003","type":"plan","spec":"PX-SPEC-405"}', ); const result = indexDocuments( [ invalidSpec, source( "specs", "PX-SPEC-002", "wrong-name", '{"id":"PX-SPEC-010","type":"spec"}', ), source( "plans", "PX-PLAN-001", "references-invalid-html", '{"id":"PX-PLAN-001","type":"plan","spec":"PX-SPEC-009"}', ), source( "plans", "PX-PLAN-005", "references-invalid-filename", '{"id":"PX-PLAN-005","type":"plan","spec":"PX-SPEC-010"}', ), invalidPlan, invalidFilenamePlan, ], "PX", ); const invalidSourcePaths = new Set( result.documents .filter(({ metadata }) => ["PX-PLAN-002", "PX-PLAN-003"].includes(metadata.id), ) .map(({ path }) => path), ); assert.ok( result.diagnostics.some( ({ code, path }) => code === "document.filename" && path.includes("PX-SPEC-002"), ), ); assert.ok( result.diagnostics.some( ({ code, path }) => code === "document.semantic-shell" && path.includes("PX-SPEC-009"), ), ); for (const planId of ["PX-PLAN-001", "PX-PLAN-005"]) assert.ok( result.diagnostics.some( ({ code, path }) => code === "graph.dangling-reference" && path.includes(planId), ), ); for (const path of invalidSourcePaths) assert.ok( result.diagnostics.some( (item) => item.path === path && item.code.startsWith("document."), ), ); assert.ok( !result.diagnostics.some( ({ code, path }) => code.startsWith("graph.") && invalidSourcePaths.has(path), ), ); }); it("sorts stable filename, dangling, and forbidden-edge diagnostics", () => { const result = indexDocuments( [ source( "specs", "PX-SPEC-001", "one", '{"id":"PX-SPEC-001","type":"spec"}', ), source( "specs", "PX-SPEC-002", "two", '{"id":"PX-SPEC-001","type":"spec"}', ), source( "roadmaps", "PX-ROADMAP-001", "wrong-target", '{"id":"PX-ROADMAP-001","type":"roadmap","spec":"PX-PLAN-009"}', ), source( "plans", "PX-PLAN-001", "dangling", '{"id":"PX-PLAN-001","type":"plan","spec":"PX-SPEC-404"}', ), source( "plans", "PX-PLAN-002", "crossed", '{"id":"PX-PLAN-002","type":"plan","spec":"PX-SPEC-001","roadmap":"PX-ROADMAP-002","phase":1}', ), source( "roadmaps", "PX-ROADMAP-002", "other", '{"id":"PX-ROADMAP-002","type":"roadmap","spec":"PX-SPEC-003"}', ), source( "issues", "PX-ISSUE-001", "unknown", '{"id":"PX-ISSUE-001","type":"issue","status":"open","specs":[]}', ), ], "PX", ); 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), ); assert.ok( !result.diagnostics.some((item) => item.code === "graph.duplicate-id"), ); assert.ok( result.diagnostics.some((item) => item.code === "document.filename"), ); assert.ok( result.diagnostics.some( (item) => item.code === "graph.dangling-reference" && item.message.includes("PX-SPEC-404"), ), ); assert.ok( result.diagnostics.some( (item) => item.code === "graph.forbidden-edge" && item.message.includes("must reference spec"), ), ); assert.ok( result.diagnostics.some( (item) => item.code === "graph.forbidden-edge" && item.message.includes("belongs to PX-SPEC-003"), ), ); assert.ok( !result.diagnostics.some( (item) => item.path.includes("PX-ISSUE-001") && item.code.startsWith("graph."), ), ); }); }); describe("bundled system.css", () => { it("contains exact Nugu tokens, version, components, and responsive contracts", () => { const css = readFileSync( path.resolve(import.meta.dirname, "../assets/system.css"), "utf8", ); for (const token of [ "The System styleVersion: 1", "--fg: #121212", "--page: #ededed", "--panel: #dbdbdb", "--accent: #ae2eae", "--ui-accent: #922792", "--minor: #3b3b3b", "--focus: #184e5b", "--important: #4f3c69", "--error: #bd172e", "--warning: #6e6c10", "--info: #116477", "--fg: #ededed", "--page: #121212", "--panel: #242424", "--accent: #d151d1", "--ui-accent: #d86dd8", "--minor: #8b8b8b", "--focus: #7ba1aa", "--important: #dfd3f3", "--error: #ec6376", "--warning: #f0ee69", "--info: #3ec5e3", ".doc", ".mast", ".grid", ".section", ".contract", ".callout", ".flow", ".metadata", ".status", ".document-nav", "table", "pre", "overflow-wrap: anywhere", "@media (max-width: 560px)", ]) assert.ok(css.includes(token), `missing CSS contract: ${token}`); assert.doesNotMatch(css, /@import|url\s*\(|https?:\/\//i); }); });