repositories / pi-ext
pi-ext
bugabingas pi extensions
owned by bugabinga
extensions/the-system/__tests__/documents.test.ts
RawFile outline
- temporary line 24
- tree line 25
- dir line 30
- afterEach line 35
- project root line 40
- uses cwd when no VCS marker exists line 58
- fails when nearest JJ and Git roots differ line 63
- governed path containment line 80
- normalizes a contained relative path line 81
- does not confuse a sibling sharing the root prefix for a child line 101
- system config line 110
- accepts only the exact versioned shape line 111
- rejects duplicate config keys line 122
- document IDs and filenames line 151
- rejects a foreign configured prefix line 179
- accepts a matching type directory, ID, and slug line 182
- shell line 206
- document metadata line 215
- wraps malformed metadata JSON line 252
- ignores metadata blocks inside HTML comments line 265
- authored HTML line 320
- accepts the complete semantic shell and inert progressive enhancement line 321
- ignores shell and forbidden tags inside HTML comments line 436
- allows quoted and unquoted remote HTTPS navigation anchors line 511
- source line 525
- document index line 535
- indexes a valid complete graph without diagnostics line 536
- excludes HTML- and filename-invalid documents from graph edges line 576
- sorts stable filename, dangling, and forbidden-edge diagnostics line 666
- bundled system.css line 761
- contains exact Nugu tokens, version, components, and responsive contracts line 762
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 = "<header><h1>Title</h1></header><main><section><h2>Contract</h2><p>Readable.</p></section></main>",
) => `<!doctype html>
<html lang="en"><head><meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Title</title><link rel="stylesheet" href="../system.css"></head>
<body>${body}<script type="application/json" id="system-meta">${metadata}</script></body></html>`;
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"}')}<!-- <script type="application/json" id="system-meta">{}</script> -->`;
assert.deepEqual(parseDocumentMetadata(html, "PX"), {
id: "PX-SPEC-001",
type: "spec",
});
});
it.each([
["missing block", '<!doctype html><html lang="en"></html>'],
[
"duplicate blocks",
shell('{"id":"PX-SPEC-001","type":"spec"}') +
'<script type="application/json" id="system-meta">{}</script>',
],
[
"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"}',
"<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>",
);
assert.deepEqual(
validateAuthoredHtml("specs/PX-SPEC-001-title.html", html),
[],
);
});
it.each([
[
"document.doctype",
shell('{"id":"PX-SPEC-001","type":"spec"}').replace(
"<!doctype html>",
"",
),
],
[
"document.language",
shell('{"id":"PX-SPEC-001","type":"spec"}').replace(
'lang="en"',
'lang="fr"',
),
],
[
"document.charset",
shell('{"id":"PX-SPEC-001","type":"spec"}').replace(
'<meta charset="utf-8">',
"",
),
],
[
"document.viewport",
shell('{"id":"PX-SPEC-001","type":"spec"}').replace(
/<meta name="viewport"[^>]+>/,
"",
),
],
[
"document.title",
shell('{"id":"PX-SPEC-001","type":"spec"}').replace(
"<title>Title</title>",
"<title></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>|<\/main>/g,
"",
),
],
[
"document.forbidden-tag",
shell(
'{"id":"PX-SPEC-001","type":"spec"}',
'<header><h1>X</h1></header><main><section><iframe src="x"></iframe></section></main>',
),
],
[
"document.event-handler",
shell(
'{"id":"PX-SPEC-001","type":"spec"}',
'<header><h1>X</h1></header><main><section onclick="x()">X</section></main>',
),
],
[
"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>',
),
],
[
"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>',
),
],
[
"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>",
),
],
[
"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>",
),
],
[
"document.meta-refresh",
shell('{"id":"PX-SPEC-001","type":"spec"}').replace(
"</head>",
'<meta http-equiv="refresh" content="0; url=x"></head>',
),
],
])("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"}',
"<!-- <header><main><section><iframe></iframe></section></main></header> -->",
);
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", "</head>"],
["missing body close", "</body>"],
["missing html close", "</html>"],
["missing header close", "</header>"],
["missing main close", "</main>"],
["missing section close", "</section>"],
] 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",
"<a href=javascript:alert(1)>X</a>",
"document.executable-url",
],
[
"encoded executable URL with control whitespace",
'<a href="java	script:alert(1)">X</a>',
"document.executable-url",
],
[
"unquoted remote src",
"<img src=https://example.com/a.png>",
"document.remote-resource",
],
[
"encoded remote srcset",
'<img srcset="/local.png 1x, https://example.com/a.png 2x">',
"document.remote-resource",
],
[
"remote poster",
'<video poster="//example.com/poster.png"></video>',
"document.remote-resource",
],
[
"resource-bearing href",
'<link rel="preload" href="https://example.com/font.woff2">',
"document.remote-resource",
],
] as const)("rejects %s", (_name, markup, code) => {
const html = shell(
'{"id":"PX-SPEC-001","type":"spec"}',
`<header><h1>X</h1></header><main><section>${markup}</section></main>`,
);
assert.ok(
validateAuthoredHtml("doc.html", html).some(
(finding) => finding.code === code,
),
);
});
it("allows quoted and unquoted remote HTTPS navigation anchors", () => {
for (const anchor of [
'<a href="https://example.com/reference">Reference</a>',
"<a href=https://example.com/reference>Reference</a>",
]) {
const html = shell(
'{"id":"PX-SPEC-001","type":"spec"}',
`<header><h1>X</h1></header><main><section>${anchor}</section></main>`,
);
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(
"<header>",
"<!-- <header> -->",
);
const invalidPlan = source(
"plans",
"PX-PLAN-002",
"invalid-source",
'{"id":"PX-PLAN-002","type":"plan","spec":"PX-SPEC-404"}',
);
invalidPlan.html = invalidPlan.html.replace("<main>", "");
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);
});
});