repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by bugabinga

extensions/the-system/__tests__/documents.test.ts

Raw
File outline
import assert from "node:assert/strict";
import {
	mkdirSync,
	mkdtempSync,
	rmSync,
	symlinkSync,
	writeFileSync,
} from "node:fs";
import { tmpdir } from "node:os";
import path from "node:path";
import { afterEach, describe, it } from "vitest";
import {
	discoverDocumentBundles,
	discoverProjectRoot,
	indexBundleDocuments,
	inspectSystemConfig,
	parseAuthoredDocument,
	parseSystemConfig,
	resolveGovernedPath,
	SystemDocumentError,
	validateBundleCandidate,
	validateDocumentPath,
} from "../documents.ts";

const roots: string[] = [];
const tree = () => {
	const root = mkdtempSync(path.join(tmpdir(), "the-system-documents-"));
	roots.push(root);
	return root;
};
const dir = (root: string, ...parts: string[]) => {
	const target = path.join(root, ...parts);
	mkdirSync(target, { recursive: true });
	return target;
};
const write = (root: string, relative: string, content: string) => {
	const target = path.join(root, relative);
	dir(path.dirname(target));
	writeFileSync(target, content);
};
const markdownSource = (
	directory: string,
	id: string,
	slug: string,
	frontmatter: string,
) => ({
	path: `.system/${directory}/${id}-${slug}/index.md`,
	markdown: `---\n${frontmatter}\n---\n\n# ${id}\n`,
});
const specMarkdown = (id: string) =>
	`---\nid: ${id}\ntype: spec\n---\n\n# ${id}\n`;
afterEach(() => {
	for (const root of roots.splice(0))
		rmSync(root, { recursive: true, force: true });
});

describe("project root and schema-v2 config", () => {
	it("contains paths and resolves nearest marker", () => {
		const root = tree();
		mkdirSync(path.join(root, ".git"));
		assert.equal(discoverProjectRoot(path.join(root, "nested")), root);
		assert.equal(resolveGovernedPath(root, "x/../x"), path.join(root, "x"));
		assert.throws(
			() => resolveGovernedPath(root, "../outside"),
			SystemDocumentError,
		);
	});
	it("accepts current config and inspects only narrow v1 config", () => {
		assert.deepEqual(parseSystemConfig('{"prefix":"PX","schemaVersion":2}'), {
			prefix: "PX",
			schemaVersion: 2,
		});
		assert.throws(
			() =>
				parseSystemConfig('{"prefix":"PX","schemaVersion":1,"styleVersion":1}'),
			SystemDocumentError,
		);
		assert.deepEqual(
			inspectSystemConfig('{"prefix":"PX","schemaVersion":1,"styleVersion":1}'),
			{ config: { prefix: "PX", schemaVersion: 1 }, legacyStyleVersion: 1 },
		);
	});
});

describe("Markdown bundle metadata", () => {
	it("projects known graph fields while preserving unknown frontmatter", () => {
		const parsed = parseAuthoredDocument(
			`---\nid: PX-PLAN-001\ntype: plan\nspec: PX-SPEC-001\nroadmap: PX-ROADMAP-001\nphase: 2\ntitle: Delivery\nreview:\n  owner: human\n---\n\n# Delivery\n`,
			"PX",
		);
		assert.deepEqual(parsed.metadata, {
			id: "PX-PLAN-001",
			type: "plan",
			spec: "PX-SPEC-001",
			roadmap: "PX-ROADMAP-001",
			phase: 2,
		});
		assert.deepEqual(
			[...parsed.frontmatter.keys()],
			["id", "type", "spec", "roadmap", "phase", "title", "review"],
		);
		assert.deepEqual(
			parseAuthoredDocument(
				"---\nid: PX-RESEARCH-001\ntype: research\ncapturedAt: 2026-07-15\nsources: [notes/local.txt, http://example.test]\n---\n",
				"PX",
			).metadata,
			{
				id: "PX-RESEARCH-001",
				type: "research",
				capturedAt: "2026-07-15",
				sources: ["notes/local.txt", "http://example.test"],
			},
		);
	});
	it("accepts only canonical index paths", () => {
		const metadata = { id: "PX-SPEC-001", type: "spec" } as const;
		assert.doesNotThrow(() =>
			validateDocumentPath(
				".system/specs/PX-SPEC-001-login-flow/index.md",
				metadata,
				"PX",
			),
		);
		for (const item of [
			".system/specs/PX-SPEC-001-login-flow.md",
			".system/plans/PX-SPEC-001-login-flow/index.md",
			".system/specs/PX-SPEC-001-Login/index.md",
			".system/specs/PX-SPEC-001-login-flow/other/index.md",
		])
			assert.throws(
				() => validateDocumentPath(item, metadata, "PX"),
				SystemDocumentError,
			);
	});
});

describe("bundle discovery", () => {
	it("returns authored indexes and structural diagnostics separately", () => {
		const root = tree();
		write(
			root,
			".system/specs/PX-SPEC-001-contract/index.md",
			specMarkdown("PX-SPEC-001"),
		);
		write(root, ".system/specs/PX-SPEC-001-contract/assets/data.csv", "a,b");
		write(root, ".system/plans/loose.md", "bad");
		dir(root, ".system", "specs", "PX-SPEC-002-empty");
		assert.deepEqual(discoverDocumentBundles(root).sources, [
			{
				path: ".system/specs/PX-SPEC-001-contract/index.md",
				markdown: specMarkdown("PX-SPEC-001"),
			},
		]);
		assert.deepEqual(
			discoverDocumentBundles(root).diagnostics.map(
				(item) => `${item.path} ${item.code}`,
			),
			[
				".system/plans/loose.md bundle.expected-directory",
				".system/specs/PX-SPEC-002-empty bundle.missing-index",
			],
		);
	});
	it("rejects a symlinked .system root without following it", () => {
		const root = tree();
		const outside = tree();
		write(
			outside,
			".system/specs/PX-SPEC-001-contract/index.md",
			specMarkdown("PX-SPEC-001"),
		);
		symlinkSync(
			path.join(outside, ".system"),
			path.join(root, ".system"),
			"dir",
		);
		assert.deepEqual(discoverDocumentBundles(root), {
			sources: [],
			diagnostics: [
				{
					code: "bundle.symbolic-link",
					path: ".system",
					message: "Bundle path is a symbolic link: .system",
				},
			],
		});
	});

	it("reports symlinks without following them", () => {
		const root = tree();
		const outside = tree();
		write(
			root,
			".system/specs/PX-SPEC-001-contract/index.md",
			specMarkdown("PX-SPEC-001"),
		);
		symlinkSync(
			outside,
			path.join(root, ".system/specs/PX-SPEC-002-link"),
			"dir",
		);
		symlinkSync(
			outside,
			path.join(root, ".system/specs/PX-SPEC-001-contract/assets-link"),
			"dir",
		);
		assert.deepEqual(
			discoverDocumentBundles(root).diagnostics.map((item) => item.code),
			["bundle.symbolic-link", "bundle.symbolic-link"],
		);
	});
});

describe("bundle graph and candidate validation", () => {
	it("excludes duplicate IDs from reference targets", () => {
		const duplicatePaths = [
			".system/specs/PX-SPEC-001-alpha/index.md",
			".system/specs/PX-SPEC-001-beta/index.md",
		];
		const indexed = indexBundleDocuments(
			[
				markdownSource(
					"specs",
					"PX-SPEC-001",
					"alpha",
					"id: PX-SPEC-001\ntype: spec",
				),
				markdownSource(
					"specs",
					"PX-SPEC-001",
					"beta",
					"id: PX-SPEC-001\ntype: spec",
				),
				markdownSource(
					"roadmaps",
					"PX-ROADMAP-001",
					"delivery",
					"id: PX-ROADMAP-001\ntype: roadmap\nspec: PX-SPEC-001",
				),
			],
			"PX",
		);
		assert.deepEqual(
			indexed.diagnostics.map(
				(item) => `${item.path} ${item.code}: ${item.message}`,
			),
			[
				".system/roadmaps/PX-ROADMAP-001-delivery/index.md graph.dangling-reference: PX-ROADMAP-001 references missing PX-SPEC-001",
				`.system/specs/PX-SPEC-001-alpha/index.md graph.duplicate-id: Duplicate ID PX-SPEC-001: ${duplicatePaths.join(", ")}`,
				`.system/specs/PX-SPEC-001-beta/index.md graph.duplicate-id: Duplicate ID PX-SPEC-001: ${duplicatePaths.join(", ")}`,
			],
		);
	});

	it("indexes references, ignores unknown fields, and suppresses baseline findings", () => {
		const current = [
			markdownSource(
				"specs",
				"PX-SPEC-001",
				"one",
				"id: PX-SPEC-001\ntype: spec\nrelated: PX-SPEC-404",
			),
			markdownSource(
				"roadmaps",
				"PX-ROADMAP-001",
				"delivery",
				"id: PX-ROADMAP-001\ntype: roadmap\nspec: PX-SPEC-001",
			),
		];
		assert.deepEqual(indexBundleDocuments(current, "PX").diagnostics, []);
		const candidate = markdownSource(
			"specs",
			"PX-SPEC-001",
			"one",
			"id: PX-SPEC-002\ntype: spec",
		);
		assert.deepEqual(
			validateBundleCandidate(current, candidate, "PX").map(
				(item) => `${item.path} ${item.code}`,
			),
			[
				".system/roadmaps/PX-ROADMAP-001-delivery/index.md graph.dangling-reference",
				".system/specs/PX-SPEC-001-one/index.md document.path",
			],
		);
	});
});