Contract
Readable.
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 = " Readable.Title
Contract
Text.