Luigit
repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by admin

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

Raw
import assert from "node:assert/strict";
import {
	mkdirSync,
	mkdtempSync,
	readFileSync,
	rmSync,
	utimesSync,
	writeFileSync,
} from "node:fs";
import { tmpdir } from "node:os";
import path from "node:path";
import { runInNewContext } from "node:vm";
import { afterEach, describe, it, vi } from "vitest";
import { loadProjectIndex } from "../project-index.ts";
import { renderSystemBookSite } from "../system-renderer.ts";

const roots: string[] = [];
const outputs: string[] = [];

afterEach(() => {
	for (const directory of outputs.splice(0))
		rmSync(directory, { recursive: true, force: true });
	for (const root of roots.splice(0))
		rmSync(root, { recursive: true, force: true });
});

describe("System board renderer", () => {
	it("renders one spec column with copy and exec controls for board documents", () => {
		const root = fixture();
		const index = loadProjectIndex(root);
		const output = renderSystemBookSite(
			index,
			{ schemaVersion: 0, items: {} },
			[],
			"revision",
		);
		outputs.push(output.directory);
		const html = readFileSync(
			path.join(output.directory, "board.html"),
			"utf8",
		);

		assert.match(
			html,
			/\.board-spec-list\{display:grid;grid-template-columns:1fr;/,
		);
		for (const id of [
			"PX-SPEC-SPEC0001",
			"PX-PLAN-PLAN0001",
			"PX-ISSUE-ISSUE001",
		]) {
			assert.match(html, new RegExp(`data-copy-id="${id}"`));
			assert.match(html, new RegExp(`data-exec aria-label="Execute ${id}"`));
			assert.match(
				html,
				new RegExp(`data-edit aria-label="Edit ${id} in editor"`),
			);
			assert.match(
				html,
				new RegExp(`data-drop aria-label="Drop or restore ${id}"`),
			);
		}
	});

	it("orders specs active, done, dropped with modification order and stable ID ties", () => {
		const root = fixture();
		for (const [number, modified] of [
			[1, 1],
			[2, 2],
			[3, 3],
			[4, 2],
			[5, 5],
		] as const) {
			const relative = `.system/specs/PX-SPEC-SPEC000${number}-contract/index.md`;
			if (number !== 1)
				write(
					root,
					relative,
					`---\nid: PX-SPEC-SPEC000${number}\ntype: spec\ntitle: Contract ${number}\n---\n\n# Contract ${number}\n`,
				);
			utimesSync(path.join(root, relative), modified, modified);
		}
		const output = renderSystemBookSite(
			loadProjectIndex(root),
			{
				schemaVersion: 0,
				items: {
					"PX-SPEC-SPEC0005": {
						state: "dropped",
						source: "manual",
						updatedAt: "2026-01-01T00:00:00.000Z",
					},
					"PX-SPEC-SPEC0003": {
						state: "done",
						source: "manual",
						updatedAt: "2026-01-01T00:00:00.000Z",
					},
				},
			},
			[],
			"revision",
		);
		outputs.push(output.directory);
		const html = readFileSync(
			path.join(output.directory, "board.html"),
			"utf8",
		);
		assert.deepEqual(
			[
				...html.matchAll(
					/data-kind="spec" data-modified-at="(\d+)" data-id="([^"]+)"/g,
				),
			].map((match) => [match[2], Number(match[1])]),
			[
				["PX-SPEC-SPEC0002", 2000],
				["PX-SPEC-SPEC0004", 2000],
				["PX-SPEC-SPEC0001", 1000],
				["PX-SPEC-SPEC0003", 3000],
				["PX-SPEC-SPEC0005", 5000],
			],
		);
		assert.match(html, /data-spec-count>3<\/b>/);
		assert.match(html, /class="board-spec is-dropped"/);
		assert.match(
			html,
			/data-drop aria-label="Drop or restore PX-SPEC-SPEC0005" disabled>RESTORE<\/button>/,
		);
		assert.doesNotMatch(
			html,
			/Spec toggles never change plan states|Reopening a plan demotes its spec/,
		);
	});

	it.each(["during response", "after response"])(
		"ignores pre-approval polls arriving %s",
		async (arrival) => {
			const c = ledger(ledgerSource());
			await c.initialized;
			const snapshot = Promise.withResolvers<unknown>();
			c.fetch.mockResolvedValueOnce({ ok: true, json: () => snapshot.promise });
			const pendingPoll = c.poll();
			const response = Promise.withResolvers<unknown>();
			c.fetch.mockResolvedValueOnce({ ok: true, json: () => response.promise });
			const pendingWrite = c.click();
			assert.equal(c.button.disabled, true);
			assert.equal(c.fetch.mock.calls.at(-1)?.[0], "/api/status");
			const calls = c.fetch.mock.calls.length;
			await c.poll();
			assert.equal(
				c.fetch.mock.calls.length,
				calls,
				"no polling during response body",
			);
			if (arrival === "after response") {
				response.resolve({});
				await pendingWrite;
			}
			snapshot.resolve({ revision: "approved-revision", items: {} });
			await pendingPoll;
			assert.equal(c.reloads, 0, "old poll cannot interrupt approval");
			response.resolve({});
			await pendingWrite;
			assert.equal(c.button.textContent, "approved");
			assert.equal(c.button.disabled, false);
			c.fetch.mockResolvedValueOnce(
				jsonResponse({ revision: "approved-revision", items: {} }),
			);
			await c.poll();
			assert.equal(c.reloads, 1, "fresh poll refreshes approved document");
		},
	);

	it("recovers controls and polling after approval failure", async () => {
		const c = ledger(ledgerSource());
		await c.initialized;
		c.fetch.mockResolvedValueOnce(
			jsonResponse({ error: "Approval failed" }, false),
		);
		await c.click();
		assert.equal(c.button.disabled, false);
		assert.equal(c.button.textContent, "draft");
		assert.equal(c.notice.textContent, "Approval failed");
		const calls = c.fetch.mock.calls.length;
		await c.poll();
		assert.equal(c.fetch.mock.calls.length, calls + 1);
	});
});

function ledgerSource(): string {
	const output = renderSystemBookSite(
		loadProjectIndex(fixture()),
		{ schemaVersion: 0, items: {} },
		[],
		"revision",
	);
	outputs.push(output.directory);
	const html = readFileSync(path.join(output.directory, "board.html"), "utf8");
	const start = html.indexOf("const element=");
	const end = html.indexOf("</script>", start);
	assert.ok(start >= 0 && end > start, "emitted ledger script exists");
	return html.slice(start, end);
}

function jsonResponse(value: unknown, ok = true) {
	return { ok, json: async () => value };
}

function ledger(script: string) {
	const initialized = Promise.withResolvers<void>();
	const button = {
		disabled: false,
		dataset: { status: "draft", id: "PX-PLAN-PLAN0001" },
		textContent: "draft",
		hasAttribute: (name: string) => name === "data-status-toggle",
	};
	type Click = (event: {
		target: { closest(): typeof button };
		preventDefault(): void;
	}) => Promise<void>;
	let click!: Click;
	const fetch = vi.fn<
		(
			path: string,
			options?: unknown,
		) => Promise<{ ok: boolean; json(): Promise<unknown> }>
	>(async () => jsonResponse({ revision: "revision", items: {} }));
	let poll!: () => Promise<void>;
	let reloads = 0;
	const notice = { textContent: "", className: "" };
	runInNewContext(script, {
		document: {
			body: {
				dataset: { revision: "revision" },
				addEventListener: (_: string, fn: Click) => {
					click = fn;
				},
				hasAttribute: () => false,
				append() {},
			},
			querySelector: () => notice,
			querySelectorAll: () => [],
			addEventListener() {},
			hidden: false,
		},
		globalThis: { systemBoardRefresh: () => initialized.resolve() },
		fetch,
		setTimeout() {},
		setInterval: (fn: () => Promise<void>) => {
			poll = fn;
		},
		sessionStorage: { setItem() {}, getItem: () => "[]" },
		location: { reload: () => reloads++ },
	});
	return {
		initialized: initialized.promise,
		button,
		notice,
		fetch,
		poll,
		click: () =>
			click({ target: { closest: () => button }, preventDefault() {} }),
		get reloads() {
			return reloads;
		},
	};
}

function fixture(): string {
	const root = mkdtempSync(path.join(tmpdir(), "system-renderer-"));
	roots.push(root);
	write(root, ".system/config.json", '{"prefix":"PX","schemaVersion":0}');
	write(root, ".system/SYSTEM.md", "# SYSTEM\n");
	write(
		root,
		".system/specs/PX-SPEC-SPEC0001-contract/index.md",
		"---\nid: PX-SPEC-SPEC0001\ntype: spec\ntitle: Contract\n---\n\n# Contract\n",
	);
	write(
		root,
		".system/plans/PX-PLAN-PLAN0001-build/index.md",
		"---\nid: PX-PLAN-PLAN0001\ntype: plan\ntitle: Build\nspec: PX-SPEC-SPEC0001\nstatus: draft\n---\n\n# Build\n",
	);
	write(
		root,
		".system/issues/PX-ISSUE-ISSUE001-bug/index.md",
		"---\nid: PX-ISSUE-ISSUE001\ntype: issue\ntitle: Bug\nspecs: [PX-SPEC-SPEC0001]\n---\n\n# Bug\n",
	);
	return root;
}

function write(root: string, relative: string, content: string): void {
	const target = path.join(root, relative);
	mkdirSync(path.dirname(target), { recursive: true });
	writeFileSync(target, content, "utf8");
}