Luigit
repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by admin

extensions/the-system/__e2e__/renderer.spec.ts

Raw
import { createHash } from "node:crypto";
import {
	mkdirSync,
	mkdtempSync,
	readdirSync,
	readFileSync,
	rmSync,
	statSync,
	writeFileSync,
} from "node:fs";
import { readFile } from "node:fs/promises";
import { createServer } from "node:http";
import { tmpdir } from "node:os";
import path from "node:path";
import { fileURLToPath } from "node:url";
import {
	expect,
	type Page,
	type Request,
	type Response,
	test,
} from "@playwright/test";
import { parseSync } from "oxc-parser";
import { observeDocumentDepartures } from "../../../test/browser-departures.ts";
import {
	type BrowserDiagnostics,
	emitBrowserFailureDiagnostics,
	observeBrowserDiagnostics,
} from "../../../test/browser-diagnostics.ts";

const boardRuntime: typeof import("../board-runtime.ts") = await import(
	new URL("../../../dist/the-system/board-runtime.ts", import.meta.url).href
);
const systemCommand: typeof import("../system-command.ts") = await import(
	new URL("../../../dist/the-system/system-command.ts", import.meta.url).href
);
const { createBoardRuntime } = boardRuntime;
const { createSystemCommand } = systemCommand;

const roots: string[] = [];
const runtimes: ReturnType<typeof createBoardRuntime>[] = [];
const health = new Map<
	Page,
	{
		errors: string[];
		requestErrors: Map<Request, string>;
		nativeMediaHandoffs: WeakSet<Request>;
		expected: Map<string, number>;
		expectedPageErrors: RegExp[];
		resourceResponses: Map<string, number>;
		resourceErrors: string[];
		diagnostics: BrowserDiagnostics;
		finalizeDepartures: () => Promise<void>;
	}
>();

test.beforeEach(({ page }) => observeHealth(page));

function observeHealth(page: Page) {
	const state = {
		errors: [] as string[],
		requestErrors: new Map<Request, string>(),
		nativeMediaHandoffs: new WeakSet<Request>(),
		expected: new Map<string, number>(),
		expectedPageErrors: [] as RegExp[],
		resourceResponses: new Map<string, number>(),
		resourceErrors: [] as string[],
		diagnostics: observeBrowserDiagnostics(page),
		finalizeDepartures: async () => {},
	};
	health.set(page, state);
	page.on("pageerror", (error) => {
		const index = state.expectedPageErrors.findIndex((pattern) =>
			pattern.test(error.message),
		);
		if (index >= 0) state.expectedPageErrors.splice(index, 1);
		else state.errors.push(`pageerror: ${error.message}`);
	});
	page.on("console", (message) => {
		if (message.type() !== "error") return;
		if (!message.text().startsWith("Failed to load resource:")) {
			state.errors.push(`console: ${message.text()}`);
			return;
		}
		const source = message.location().url;
		const path = source ? new URL(source).pathname : "";
		const remaining = state.resourceResponses.get(path) ?? 0;
		if (remaining > 0) state.resourceResponses.set(path, remaining - 1);
		else state.resourceErrors.push(`${message.text()} ${source}`);
	});
	page.on("response", (response) => {
		if (response.status() < 400) return;
		const pathname = new URL(response.url()).pathname;
		const key = `${pathname}:${response.status()}`;
		if (consumeExpected(state, key))
			state.resourceResponses.set(
				pathname,
				(state.resourceResponses.get(pathname) ?? 0) + 1,
			);
		else state.errors.push(`HTTP ${response.status()}: ${response.url()}`);
	});
	state.finalizeDepartures = observeDocumentDepartures(page, (request) => {
		const key = `${new URL(request.url()).pathname}:failed`;
		if (consumeExpected(state, key)) {
			const pathname = new URL(request.url()).pathname;
			state.resourceResponses.set(
				pathname,
				(state.resourceResponses.get(pathname) ?? 0) + 1,
			);
		} else {
			if (state.requestErrors.size >= 512)
				throw new Error("Browser request-failure limit exceeded");
			state.requestErrors.set(
				request,
				`requestfailed: ${request.url()} ${request.failure()?.errorText}`,
			);
		}
	});
}

test.afterEach(async ({ context: _context }, info) => {
	let healthy = false;
	try {
		for (const state of health.values()) {
			await state.finalizeDepartures();
			expect(
				[...state.requestErrors]
					.filter(([request]) => !state.nativeMediaHandoffs.has(request))
					.map(([, error]) => error),
			).toEqual([]);
			expect(state.errors).toEqual([]);
			expect(state.resourceErrors).toEqual([]);
			expect(
				[...state.expected.entries()].filter(([, count]) => count > 0),
			).toEqual([]);
			expect(state.expectedPageErrors).toEqual([]);
		}
		healthy = true;
	} finally {
		if (!healthy || info.status !== info.expectedStatus)
			await emitBrowserFailureDiagnostics(
				"the-system",
				info,
				[...health.values()].map((state) => state.diagnostics),
			);
		health.clear();
	}
});

test.afterEach(() => {
	for (const runtime of runtimes.splice(0)) runtime.shutdown();
	for (const root of roots.splice(0))
		rmSync(root, { recursive: true, force: true });
});

test("health scopes aborts to confirmed document departures, not active, hash, or rejected navigations", async ({
	context,
	browserName,
}) => {
	test.skip(
		browserName !== "chromium",
		"Chromium ERR_ABORTED ownership contract",
	);
	for (const mode of ["depart", "active", "hash", "rejected"] as const) {
		const held = Promise.withResolvers<void>();
		const server = createServer((request, response) => {
			if (request.url === "/held.js") {
				response.writeHead(200, { "content-type": "text/javascript" });
				response.write("/* held module body */");
				held.resolve();
			} else {
				response.setHeader("content-type", "text/html");
				response.end(
					request.url === "/replacement"
						? "<!doctype html><p>Replacement</p>"
						: '<!doctype html><script async src="/held.js"></script><p>Original</p>',
				);
			}
		});
		await new Promise<void>((resolve) =>
			server.listen(0, "127.0.0.1", resolve),
		);
		const address = server.address();
		if (!address || typeof address === "string")
			throw new Error("No fixture port");
		const url = `http://127.0.0.1:${address.port}`;
		const current = await context.newPage();
		const failures: string[] = [];
		const finalize = observeDocumentDepartures(current, (request) =>
			failures.push(new URL(request.url()).pathname),
		);
		const abort = Promise.withResolvers<void>();
		const intercepted = Promise.withResolvers<void>();
		try {
			if (mode !== "depart")
				await current.route("**/held.js", async (route) => {
					intercepted.resolve();
					await abort.promise;
					await route.abort("aborted");
				});
			await current.goto(url, { waitUntil: "domcontentloaded" });
			await (mode === "depart" ? held.promise : intercepted.promise);
			const failed = current.waitForEvent("requestfailed", (request) =>
				request.url().endsWith("/held.js"),
			);
			if (mode === "depart") await current.goto(`${url}/replacement`);
			else {
				if (mode === "hash") {
					await current.evaluate(() => {
						location.hash = "still-here";
					});
					await expect(current).toHaveURL(/#still-here$/);
				}
				if (mode === "rejected") {
					await current.route("**/blocked", (route) => route.abort("failed"));
					await expect(current.goto(`${url}/blocked`)).rejects.toThrow();
				}
				abort.resolve();
			}
			expect((await failed).failure()?.errorText).toBe("net::ERR_ABORTED");
			await finalize();
			if (mode === "depart") expect(failures).toEqual([]);
			else expect(failures).toContain("/held.js");
		} finally {
			abort.resolve();
			await current.close();
			server.closeAllConnections();
			await new Promise<void>((resolve) => server.close(() => resolve()));
		}
	}
});

test("/system view and book render rich System docs without source mutation", async ({
	page,
}, testInfo) => {
	const root = systemFixture();
	const before = hashTree(path.join(root, ".system"));
	const runtime = createBoardRuntime();
	const command = createSystemCommand({ sendUserMessage() {} } as never, {
		openBook: (cwd, page) => runtime.open(cwd, undefined, page),
	});
	runtimes.push(runtime);
	const notices: string[] = [];
	const previousNodeEnv = process.env["NODE_ENV"];
	process.env["NODE_ENV"] = "test";
	try {
		await command.handler("view PX-SPEC-SPEC0001", ctx(root, notices));
		await command.handler("view PX-PHASE-PHASE002", ctx(root, notices));
		await command.handler("book", ctx(root, notices));
	} finally {
		process.env["NODE_ENV"] = previousNodeEnv;
	}
	const view = urlFromNotice(notices[0] ?? "");
	const phaseView = urlFromNotice(notices[1] ?? "");
	const book = urlFromNotice(notices[2] ?? "");
	expect(new URL(view).origin).toBe(new URL(book).origin);
	expect(new URL(phaseView).origin).toBe(new URL(book).origin);
	await page.goto(view);
	await expect(
		page.getByRole("heading", { name: "Contract" }).first(),
	).toBeVisible();
	await expect(
		page.locator("#PX-SPEC-SPEC0001").getByText("Metadata"),
	).toBeVisible();
	await expect(page.locator(".mermaid svg")).toBeVisible();
	await expect(page.locator("math").first()).toBeVisible();
	await expect(page.locator(".mermaid")).toBeVisible();
	await expect(page.locator("iframe")).toHaveAttribute(
		"src",
		/\/\.system\/.*mockup-card\.html/,
	);
	await expect(page.getByText("raw html works")).toBeVisible();
	await page.goto(phaseView);
	await expect(page.locator(".phase-current")).toHaveText("Current phase");
	await expect(
		page.getByRole("heading", { name: "Pre-v1" }).first(),
	).toBeVisible();
	await page.goto(book);
	await expect(
		page.getByRole("heading", { name: /the-system-render-e2e-.* Dossier/ }),
	).toBeVisible();
	await expect(page.getByRole("link", { name: "CORE-SYSTEM" })).toBeVisible();
	await expect(page.locator("#PX-PHASE-PHASE002")).toBeVisible();
	await expect(page.locator(".book-top .active-phase")).toHaveText(
		"Current phase pre-v1",
	);
	await expect(page.locator('.book-nav a[aria-current="true"]')).toContainText(
		"PX-PHASE-PHASE002",
	);
	const related = page
		.locator("#PX-SPEC-SPEC0001")
		.locator("details")
		.filter({ has: page.getByText("Referenced by", { exact: true }) });
	await expect(related).toHaveCount(1);
	await related.locator("summary").click();
	const buildBacklink = related.getByRole("link", { name: /Build/ });
	await expect(buildBacklink).toBeVisible();
	await expect(related.getByRole("link", { name: /Bug/ })).toBeVisible();
	await buildBacklink.click();
	await expect(page.locator("#PX-PLAN-PLAN0001")).toBeInViewport();
	await expect(
		page.locator('a[href^="file:"][href*="PX-"][href$="index.html"]'),
	).toHaveCount(0);
	await expect(
		page.locator('#PX-SPEC-SPEC0001 .ledger a[href="/#PX-RESEARCH-RSCH0001"]'),
	).toHaveCount(1);
	const readingOrder = [
		"CORE-MISSION",
		"PX-PHASE-PHASE002",
		"CORE-RULES",
		"PX-PHASE-PHASE001",
		"PX-SPEC-SPEC0001",
		"PX-PLAN-PLAN0001",
		"PX-PLAN-PLAN0002",
		"PX-ISSUE-ISSUE001",
		"PX-RESEARCH-RSCH0001",
	];
	const renderedOrder = await page
		.locator(".book-section")
		.evaluateAll((sections) => sections.map((section) => section.id));
	expect(renderedOrder.filter((id) => readingOrder.includes(id))).toEqual(
		readingOrder,
	);
	await assertSidebarConnected(page);
	await page.screenshot({ path: testInfo.outputPath("book-desktop.png") });
	const graph = page.locator("[data-graph-svg]");
	await expect(graph).toBeVisible();
	await expect(graph.locator("a")).toHaveCount(5);
	await expect(graph.locator('a[href="#PX-PHASE-PHASE002"]')).toHaveCount(0);
	const initialViewBox = await graph.getAttribute("viewBox");
	await graph.hover();
	await page.mouse.wheel(0, -240);
	await expect(graph).not.toHaveAttribute("viewBox", initialViewBox ?? "");
	await page.locator('[data-graph-zoom="reset"]').click();
	await expect(graph).toHaveAttribute("viewBox", initialViewBox ?? "");
	await page.locator('.book-nav a[href="/#PX-PHASE-PHASE002"]').click();
	await expect(page.locator("#PX-PHASE-PHASE002")).toBeInViewport();
	await expect(page).toHaveURL(/#PX-PHASE-PHASE002$/);
	await expect.poll(() => page.evaluate(() => scrollX)).toBe(0);
	await assertSidebarConnected(page);
	await page.locator('.book-nav a[href="/#PX-SPEC-SPEC0001"]').click();
	await expect(page.locator("#PX-SPEC-SPEC0001")).toBeInViewport();
	await expect.poll(() => page.evaluate(() => scrollX)).toBe(0);
	const ledger = page.locator("#PX-SPEC-SPEC0001 .ledger");
	await expect(ledger).not.toHaveAttribute("open", "");
	await ledger
		.locator("summary")
		.evaluate((element) => (element as HTMLElement).click());
	await expect(ledger).toHaveAttribute("open", "");
	const researchLink = ledger.locator('a[href="/#PX-RESEARCH-RSCH0001"]');
	await researchLink.evaluate((element) =>
		element.scrollIntoView({ behavior: "instant", block: "center" }),
	);
	await expect(researchLink).toBeVisible();
	await researchLink.click();
	await expect(page.locator("#PX-RESEARCH-RSCH0001")).toBeInViewport();
	await expect.poll(() => page.evaluate(() => scrollX)).toBe(0);
	await page.mouse.wheel(0, 1200);
	await assertSidebarConnected(page);
	await page.goto(book);
	await page.setViewportSize({ width: 390, height: 844 });
	await expect(page.locator(".book-nav")).toBeHidden();
	await expect(page.locator(".mobile-nav")).toBeVisible();
	await expect(page.locator(".mobile-nav > details")).not.toHaveAttribute(
		"open",
		"",
	);
	await expect(page.locator(".graph-frame")).toBeVisible();
	await page.screenshot({ path: testInfo.outputPath("book-mobile.png") });
	await page.locator('[data-graph-zoom="in"]').click();
	await expect(graph).not.toHaveAttribute("viewBox", initialViewBox ?? "");
	await expect.poll(() => page.evaluate(() => scrollX)).toBe(0);
	await page.locator("#search").fill("body-only-term");
	await expect(page.locator("#results")).toContainText("PX-SPEC-SPEC0001");
	await expect(page.locator("#results")).toContainText("body-only-term");
	expect(
		(
			await page.request.get(
				new URL(
					"/.system/specs/PX-SPEC-SPEC0001-contract/mockup-card.html",
					book,
				).href,
			)
		).ok(),
	).toBe(true);
	expect(hashTree(path.join(root, ".system"))).toBe(before);
});

test("book serves one self-contained patched Mermaid bundle and sanitizes diagram labels", async ({
	page,
}) => {
	const root = systemFixture();
	expectHealth(page, "/x:404", 2);
	const spec = ".system/specs/PX-SPEC-SPEC0001-contract/index.md";
	write(
		root,
		spec,
		readFileSync(path.join(root, spec), "utf8") +
			'\n\n```mermaid\nflowchart TD\n A["<img src=x onerror=window.diagramAttack=1>"]\n```\n',
	);
	const runtime = createBoardRuntime();
	runtimes.push(runtime);
	const url = urlFromNotice(await runtime.open(root, undefined, "/"));
	const external: string[] = [];
	page.on("request", (request) => {
		if (
			!request.url().startsWith(new URL(url).origin) &&
			!request.url().startsWith("data:")
		)
			external.push(request.url());
	});
	await page.goto(url);
	await expect(page.locator(".mermaid svg")).toHaveCount(2);
	await expect(page.locator(".mermaid [onerror], .mermaid script")).toHaveCount(
		0,
	);
	expect(await page.evaluate("window.diagramAttack")).toBeUndefined();
	expect(external).toEqual([]);
	const pending = [new URL("/browser/book.js", url).href];
	const seen = new Set<string>();
	let sanitizer = false;
	while (pending.length) {
		const file = pending.pop() as string;
		if (seen.has(file)) continue;
		seen.add(file);
		expect(seen.size).toBeLessThan(256);
		const response = await page.request.get(file);
		expect(response.ok(), file).toBe(true);
		expect(response.headers()["content-type"]).toContain("javascript");
		const source = await response.text();
		expect(source).not.toMatch(
			/DOMPurify(?:\.version\s*=\s*|\s+)['"]?3\.4\.12/,
		);
		if (/DOMPurify\.version\s*=\s*['"]3\.4\.17/.test(source)) sanitizer = true;
		for (const dependency of moduleDependencies(source)) {
			expect(dependency.startsWith("."), dependency).toBe(true);
			pending.push(new URL(dependency, file).href);
		}
	}
	expect(sanitizer).toBe(true);
	expect(seen.size).toBe(1);
});

for (const release of [false, true]) {
	test(
		"book renders multiple diagram families without fetching implementation chunks (release: " +
			release +
			")",
		async ({ page }) => {
			const root = systemFixture();
			const spec = ".system/specs/PX-SPEC-SPEC0001-contract/index.md";
			const diagrams = [
				"sequenceDiagram\n Alice->>Bob: Hello",
				"classDiagram\n class Widget",
				"stateDiagram-v2\n [*] --> Ready",
				'pie title Shares\n "A": 2\n "B": 1',
			];
			write(
				root,
				spec,
				readFileSync(path.join(root, spec), "utf8") +
					diagrams
						.map(
							(diagram) => '\n\n<pre class="mermaid">' + diagram + "</pre>\n",
						)
						.join(""),
			);
			const runtime = createBoardRuntime();
			runtimes.push(runtime);
			if (release) {
				// Build tooling stays outside the extension's composite TS project.
				const { bundleBrowserEntries } = await import(
					new URL("../../../scripts/build/bundle.ts", import.meta.url).href
				);
				const { readBuildSpec } = await import(
					new URL("../../../scripts/build/spec.ts", import.meta.url).href
				);
				const artifact = mkdtempSync(
					path.join(tmpdir(), "system-release-browser-"),
				);
				roots.push(artifact);
				await bundleBrowserEntries(
					readBuildSpec(fileURLToPath(new URL("../", import.meta.url))),
					artifact,
					{ release: true },
				);
				const directory = path.join(artifact, "browser");
				expect(
					readdirSync(directory).filter((file) => file.endsWith(".js")),
				).toEqual(["book.js"]);
				const body = await readFile(path.join(directory, "book.js"));
				await page.route("**/browser/book.js", (route) =>
					route.fulfill({
						status: 200,
						contentType: "text/javascript",
						body,
					}),
				);
			}
			const scripts = new Set<string>();
			page.on("request", (request) => {
				if (
					request.resourceType() === "script" &&
					request.frame() === page.mainFrame()
				)
					scripts.add(new URL(request.url()).pathname);
			});
			await page.goto(urlFromNotice(await runtime.open(root, undefined, "/")));
			await expect(
				page.locator('.mermaid[data-processed="true"] > svg'),
			).toHaveCount(5);
			for (const label of ["Alice", "Widget", "Ready", "Shares"])
				await expect(
					page.locator(".mermaid").filter({ hasText: label }),
				).toHaveCount(1);
			expect([...scripts]).toEqual(["/browser/book.js"]);
			await page.locator("#search").fill("body-only-term");
			await page.locator("#search-button").click();
			await expect(page).toHaveURL(/#PX-SPEC-SPEC0001$/);
		},
	);
}

test("book refresh retains location/search and keeps the last good page after invalid config", async ({
	page,
}) => {
	const root = systemFixture();
	const runtime = createBoardRuntime();
	runtimes.push(runtime);
	await page.goto(
		urlFromNotice(await runtime.open(root, undefined, "/#PX-SPEC-SPEC0001")),
	);
	await page.locator("#search").fill("body-only-term");
	const spec = ".system/specs/PX-SPEC-SPEC0001-contract/index.md";
	const source = readFileSync(path.join(root, spec), "utf8");
	const navigation = page
		.locator(".book-nav details")
		.filter({ has: page.locator('a[href="/#PX-PLAN-PLAN0001"]') });
	await navigation.locator("summary").click();
	await expect(navigation).toHaveAttribute("open", "");
	await expect(page.locator(".mermaid svg")).toHaveCount(1);
	await page.evaluate(() => scrollBy({ top: 120, behavior: "instant" }));
	const before = await page.evaluate(() => scrollY);
	write(root, spec, source + "\n\nBook changed on disk.\n");
	await expect(
		page.getByText("Book changed on disk.", { exact: true }),
	).toBeVisible({ timeout: 15000 });
	await expect(page).toHaveURL(/#PX-SPEC-SPEC0001$/);
	await expect(page.locator("#search")).toHaveValue("body-only-term");
	await expect(navigation).toHaveAttribute("open", "");
	await expect(page.locator("#results")).toContainText("body-only-term");
	await expect(page.locator("#results")).toContainText("PX-SPEC-SPEC0001");
	await expect(page.locator(".mermaid svg")).toHaveCount(1);
	await expect
		.poll(async () => Math.abs((await page.evaluate(() => scrollY)) - before))
		.toBeLessThan(60);
	const revision = await page.locator("body").getAttribute("data-revision");
	const config = readFileSync(path.join(root, ".system/config.json"), "utf8");
	write(root, ".system/config.json", "{");
	await expect(page.locator("[data-board-notice]")).toHaveClass(/is-error/, {
		timeout: 15000,
	});
	await expect(page.locator("body")).toHaveAttribute(
		"data-revision",
		revision as string,
	);
	await expect(
		page.getByText("Book changed on disk.", { exact: true }),
	).toBeVisible();
	write(root, ".system/config.json", config);
	write(root, spec, source + "\n\nBook recovered.\n");
	await expect(page.getByText("Book recovered.", { exact: true })).toBeVisible({
		timeout: 15000,
	});
});

test("/system board persists independent spec, plan, and issue assessments", async ({
	page,
}) => {
	const root = systemFixture();
	const runtime = createBoardRuntime();
	try {
		await runtime.tool.execute(
			"assessment",
			{
				items: [
					{
						id: "PX-ISSUE-ISSUE001",
						state: "done",
						rationale: "The reproduction no longer fails.",
					},
				],
			},
			new AbortController().signal,
			undefined,
			{ cwd: root } as never,
		);
		const notice = await runtime.open(root);
		expect(notice).toContain("Browser: Browser opener disabled");
		const url = notice.match(
			/http:\/\/127\.0\.0\.1:\d+\/board\.html\?k=[^\s]+/,
		)?.[0];
		expect(url).toBeTruthy();
		await page.goto(url ?? "");

		const spec = page.locator('[data-board-item][data-id="PX-SPEC-SPEC0001"]');
		const planA = page.locator('[data-board-item][data-id="PX-PLAN-PLAN0001"]');
		const planB = page.locator('[data-board-item][data-id="PX-PLAN-PLAN0002"]');
		const issue = page.locator(
			'[data-board-item][data-id="PX-ISSUE-ISSUE001"]',
		);
		await expect(spec).toBeVisible();
		await expect(planA).toBeVisible();
		await expect(planB).toBeVisible();
		await expect(issue.locator("[data-proposal]")).toContainText(
			"The reproduction no longer fails.",
		);
		await issue.locator("[data-apply-proposal]").click();
		await expect(issue).toHaveClass(/is-done/);
		await expect(issue.locator("[data-assessment]")).toContainText("assess");

		await spec.locator(":scope > .board-row > .board-bundle > summary").click();
		const specDetails = spec.locator(
			":scope > .board-row > .board-bundle > .board-details",
		);
		await expect(specDetails).toContainText("body-only-term");
		await expect(specDetails.locator(".ledger")).toContainText("Metadata");
		await expect(
			spec.locator(":scope > .board-row > .board-actions > .board-state"),
		).toBeDisabled();
		await planA.locator(".board-state").click();
		await expect(planA).toHaveClass(/is-done/);
		await planB.locator(".board-state").click();
		await expect(planB).toHaveClass(/is-done/);
		await expect(
			spec.locator(":scope > .board-row > .board-actions > .board-state"),
		).toBeEnabled();
		await spec
			.locator(":scope > .board-row > .board-actions > .board-state")
			.click();
		await expect(spec).toHaveClass(/is-done/);

		await spec
			.locator(":scope > .board-row > .board-actions > .board-state")
			.click();
		await expect(spec).not.toHaveClass(/is-done/);
		await expect(planA).toHaveClass(/is-done/);
		await expect(planB).toHaveClass(/is-done/);
		await spec
			.locator(":scope > .board-row > .board-actions > .board-state")
			.click();
		await planA.locator(".board-state").click();
		await expect(spec).not.toHaveClass(/is-done/);
		await expect(planA).not.toHaveClass(/is-done/);
		await expect(planB).toHaveClass(/is-done/);

		const board = JSON.parse(
			readFileSync(path.join(root, ".system/board.json"), "utf8"),
		);
		expect(board.items["PX-ISSUE-ISSUE001"].source).toBe("assess");
		expect(board.items["PX-SPEC-SPEC0001"].state).toBe("todo");
		expect(board.items["PX-PLAN-PLAN0001"].state).toBe("todo");
		expect(board.items["PX-PLAN-PLAN0002"].state).toBe("done");

		await page.setViewportSize({ width: 390, height: 844 });
		const specsBox = await page.locator(".board-spec-list").boundingBox();
		const issuesBox = await page.locator(".board-issue-list").boundingBox();
		if (!specsBox || !issuesBox)
			throw new Error("Board lists must remain visible");
		expect(issuesBox.y).toBeGreaterThanOrEqual(specsBox.y + specsBox.height);
		await expect.poll(() => page.evaluate(() => scrollX)).toBe(0);
	} finally {
		runtime.shutdown();
	}
});

test("/system board keeps controls disabled until live state initializes", async ({
	page,
}) => {
	const root = systemFixture();
	const runtime = createBoardRuntime();
	await runtime.tool.execute(
		"proposal",
		{
			items: [
				{
					id: "PX-ISSUE-ISSUE001",
					state: "done",
					rationale: "Delayed readiness regression",
				},
			],
		},
		new AbortController().signal,
		undefined,
		{ cwd: root } as never,
	);
	const initialPoll = Promise.withResolvers<void>();
	await page.route("**/api/state", async (route) => {
		if (route.request().method() === "GET") await initialPoll.promise;
		await route.continue();
	});
	try {
		const notice = await runtime.open(root);
		const url = notice.match(
			/http:\/\/127\.0\.0\.1:\d+\/board\.html\?k=[^\s]+/,
		)?.[0];
		expect(url).toBeTruthy();
		await page.goto(url ?? "");
		const plan = page.locator('[data-board-item][data-id="PX-PLAN-PLAN0001"]');
		const state = plan.locator(
			":scope > .board-row > .board-actions > .board-state",
		);
		const status = plan.locator(
			":scope > .board-row .ledger [data-status-toggle]",
		);
		const assessment = page
			.locator('[data-board-item][data-id="PX-SPEC-SPEC0001"]')
			.locator(":scope > .board-row .ledger [data-board-toggle]");
		await expect(state).toBeDisabled();
		await expect(status).toBeDisabled();
		await expect(assessment).toBeDisabled();
		const apply = page.locator("[data-apply-proposal]");
		await expect(apply).toBeDisabled();
		// A mutation response can establish known state before the delayed poll.
		await page.evaluate(() => {
			const book = globalThis as typeof globalThis & {
				systemBoardSeen(items: Record<string, unknown>): void;
			};
			book.systemBoardSeen({});
		});
		initialPoll.resolve();
		await expect(state).toBeEnabled();
		await expect(status).toBeEnabled();
		await expect(assessment).toBeEnabled();
		await expect(apply).toBeEnabled();
		await expect(page.locator("body")).toHaveAttribute(
			"data-live-ready",
			"true",
		);
		await state.click();
		await expect(state).toHaveText("DONE");
	} finally {
		initialPoll.resolve();
		await runtime.shutdown();
	}
});

test("/system board keeps terminal exec disabled and drop in metadata", async ({
	page,
}, testInfo) => {
	const runtime = createBoardRuntime();
	try {
		const notice = await runtime.open(systemFixture());
		await page.goto(
			notice.match(/http:\/\/127\.0\.0\.1:\d+\/board\.html\?k=[^\s]+/)?.[0] ??
				"",
		);
		const plan = page.locator('[data-board-item][data-id="PX-PLAN-PLAN0001"]');
		const exec = plan.locator("[data-exec]");
		const drop = plan.locator(":scope > .board-metadata > [data-drop]");
		await expect(exec).toBeEnabled();
		await expect(drop).toHaveText("DROP");
		await expect(page.locator(".mermaid svg.flowchart")).toHaveCount(1);
		await plan.locator(".board-state").click();
		await expect(exec).toBeDisabled();
		await page.reload();
		await expect(exec).toBeDisabled();
		await expect(page.locator(".mermaid svg.flowchart")).toHaveCount(1);
		await expect(drop).toBeEnabled();
		await plan.locator(".board-state").click();
		await expect(exec).toBeEnabled();
		await drop.click();
		await expect(exec).toBeDisabled();
		await expect(drop).toHaveText("RESTORE");
		await drop.click();
		await expect(exec).toBeEnabled();
		await expect(drop).toHaveText("DROP");
		await page.screenshot({
			path: testInfo.outputPath("board.png"),
			fullPage: true,
		});
	} finally {
		await runtime.shutdown();
	}
});

test("/system board survives refresh, follows disk changes, and toggles metadata", async ({
	page,
}) => {
	const root = systemFixture();
	const runtime = createBoardRuntime();
	runtimes.push(runtime);
	const notice = await runtime.open(root);
	const url = notice.match(
		/http:\/\/127\.0\.0\.1:\d+\/board\.html\?k=[^\s]+/,
	)?.[0];
	await page.goto(url ?? "");
	// Explicit refresh must follow observable renderer completion, not load alone.
	await expect(page.locator(".mermaid svg .node")).toHaveCount(2);

	const spec = page.locator('[data-board-item][data-id="PX-SPEC-SPEC0001"]');
	const planA = page.locator('[data-board-item][data-id="PX-PLAN-PLAN0001"]');
	const planB = page.locator('[data-board-item][data-id="PX-PLAN-PLAN0002"]');
	await planA.locator(".board-state").click();
	await expect(planA).toHaveClass(/is-done/);

	await page.reload();
	await expect(page.locator(".mermaid svg .node")).toHaveCount(2);
	await expect(planA).toHaveClass(/is-done/);
	await expect(planB).not.toHaveClass(/is-done/);

	const planLedger = planB.locator(":scope > .board-row .ledger");
	await planB.locator(":scope > .board-row > .board-bundle > summary").click();
	await planLedger.locator("summary").click();
	await spec.locator(":scope > .board-row > .board-bundle > summary").click();
	const specLedger = spec.locator(":scope > .board-row .ledger");
	await specLedger.locator("summary").click();

	write(
		root,
		".system/issues/PX-ISSUE-ISSUE002-later/index.md",
		"---\nid: PX-ISSUE-ISSUE002\ntype: issue\ntitle: Later\nspecs: [PX-SPEC-SPEC0001]\n---\n\n# Later\n",
	);
	const late = page.locator('[data-board-item][data-id="PX-ISSUE-ISSUE002"]');
	await expect(late).toBeVisible({ timeout: 15000 });
	// Polling reloads the whole document; visibility may precede script binding.
	await page.waitForLoadState("load");
	await expect
		.poll(() => page.evaluate("typeof globalThis.systemBoardSeen"))
		.toBe("function");

	await expect(
		planB.locator(":scope > .board-row > .board-bundle"),
	).toHaveAttribute("open", "");
	await expect(planLedger).toHaveAttribute("open", "");
	await expect(
		spec.locator(":scope > .board-row > .board-bundle"),
	).toHaveAttribute("open", "");
	await expect(specLedger).toHaveAttribute("open", "");
	const [statusResponse] = await Promise.all([
		page.waitForResponse(
			(response) =>
				response.url().endsWith("/api/status") &&
				response.request().method() === "POST",
		),
		planLedger.locator("[data-status-toggle]").click(),
	]);
	expect(statusResponse.ok(), await statusResponse.text()).toBe(true);
	expect(
		readFileSync(
			path.join(root, ".system/plans/PX-PLAN-PLAN0002-test/index.md"),
			"utf8",
		),
	).toContain("status: approved");
	const snapshot = await page.request.get(
		new URL("/api/state", page.url()).href,
	);
	expect((await snapshot.json()).problem).toBeUndefined();
	await expect(
		planB.locator(":scope > .board-row > .board-bundle > summary"),
	).toContainText("approved", { timeout: 15000 });

	await planB.locator(".board-state").click();
	await expect(planB).toHaveClass(/is-done/);
	const boardToggle = specLedger.locator("[data-board-toggle]");
	await expect(boardToggle).toHaveText("todo");
	await boardToggle.click();
	await expect(boardToggle).toHaveText("done");
	await expect(spec).toHaveClass(/is-done/);
	const board = JSON.parse(
		readFileSync(path.join(root, ".system/board.json"), "utf8"),
	);
	expect(board.items["PX-SPEC-SPEC0001"].state).toBe("done");
});

test("keyboard search, heading links, encoded previews, and mobile navigation", async ({
	page,
}, testInfo) => {
	const root = systemFixture();
	const bundle = ".system/specs/PX-SPEC-SPEC0001-contract/";
	write(
		root,
		`${bundle}space card.htm`,
		"<!doctype html><title>Encoded card</title><h1>Encoded preview</h1>",
	);
	write(
		root,
		`${bundle}space image.svg`,
		'<svg xmlns="http://www.w3.org/2000/svg" width="80" height="40"><rect width="80" height="40" fill="purple"/></svg>',
	);
	write(
		root,
		`${bundle}index.md`,
		readFileSync(path.join(root, bundle, "index.md"), "utf8") +
			"\n\n## Local heading\n\n[Local anchor](#local-heading)\n\n[Build heading](../../plans/PX-PLAN-PLAN0001-build/index.md#build)\n\n[Encoded card](./space%20card.htm)\n\n[Encoded image](./space%20image.svg)\n",
	);
	const runtime = createBoardRuntime();
	runtimes.push(runtime);
	await page.goto(urlFromNotice(await runtime.open(root, undefined, "/")));
	await expect(
		page.getByRole("searchbox", { name: "Search", exact: true }),
	).toBeVisible();
	await page.locator("#search").fill("body-only-term");
	await page.screenshot({ path: testInfo.outputPath("search-desktop.png") });
	await expect(page.locator("#results li").first()).toBeInViewport({
		ratio: 1,
	});
	await expect(page.locator("#results mark")).toContainText(["body-only-term"]);
	await page.locator("#search").press("Enter");
	await expect(page).toHaveURL(/#PX-SPEC-SPEC0001$/);
	await expect(
		page.locator("#PX-SPEC-SPEC0001 mark[data-search-hit]"),
	).toHaveText("body-only-term");
	await expect(page.locator("#results li")).toHaveCount(0);
	await page.locator("#search").fill("Build");
	await page.locator('#results a[href="/#PX-PLAN-PLAN0001"]').click();
	await expect(page.locator("#PX-PLAN-PLAN0001")).toBeInViewport();
	await page.locator("#search").fill("zzzznevermatcheszzzz");
	await expect(page.locator("#results li")).toHaveCount(0);
	const unchanged = page.url();
	await page.locator("#search").press("Enter");
	await expect(page).toHaveURL(unchanged);
	await page.locator("#search").fill("");
	await page.locator("#search").press("Enter");
	await expect(page).toHaveURL(unchanged);
	await expect(page.locator("mark[data-search-hit]")).toHaveCount(0);
	await page.locator("#search").fill("body-only-term");
	await page.locator("#search").press("Enter");
	await expect(
		page.locator("#PX-SPEC-SPEC0001 mark[data-search-hit]"),
	).toHaveText("body-only-term");
	const spec = page.locator("#PX-SPEC-SPEC0001");
	await spec.getByRole("link", { name: "Local anchor", exact: true }).click();
	await expect(page).toHaveURL(/#PX-SPEC-SPEC0001-local-heading$/);
	await expect(
		page.locator("#PX-SPEC-SPEC0001-local-heading"),
	).toBeInViewport();
	await expectUnoccludedByBookHeader(page, "#PX-SPEC-SPEC0001-local-heading");
	await spec.getByRole("link", { name: "Build heading", exact: true }).focus();
	await page.keyboard.press("Enter");
	await expect(page).toHaveURL(/#PX-PLAN-PLAN0001-build$/);
	await expect(page.locator("#PX-PLAN-PLAN0001-build")).toBeInViewport();
	await expectUnoccludedByBookHeader(page, "#PX-PLAN-PLAN0001-build");
	await page.goBack();
	await expect(page).toHaveURL(/#PX-SPEC-SPEC0001-local-heading$/);
	const preview = spec.locator('iframe[title="Encoded card"]');
	await expect(preview).toHaveCount(1);
	await expect(
		page
			.frameLocator('iframe[title="Encoded card"]')
			.getByRole("heading", { name: "Encoded preview" }),
	).toBeVisible();
	const image = spec.locator('img[alt="Encoded image"]');
	await expect(image).toBeVisible();
	await expect
		.poll(() => image.evaluate((img) => (img as HTMLImageElement).naturalWidth))
		.toBe(80);
	const full = spec
		.locator(".visual-asset-html")
		.filter({ has: page.locator('iframe[title="Encoded card"]') })
		.getByRole("link", { name: "Open full-size" });
	await full.focus();
	await page.keyboard.press("Enter");
	await expect(
		page.getByRole("heading", { name: "Encoded preview" }),
	).toBeVisible();
	await page.goBack();
	await spec
		.locator(".visual-asset-image")
		.getByRole("link", { name: "Open full-size" })
		.focus();
	await page.keyboard.press("Enter");
	await expect(page).toHaveURL(/space%20image\.svg$/);
	await expect(page.locator("svg")).toHaveAttribute("width", "80");
	await page.goBack();
	await page.setViewportSize({ width: 390, height: 844 });
	const navigation = page.locator(".mobile-nav > details");
	await navigation.locator(":scope > summary").focus();
	await page.keyboard.press("Enter");
	await expect(navigation).toHaveAttribute("open", "");
	const plansSummary = navigation
		.locator("details > summary")
		.filter({ hasText: "Plans" });
	await plansSummary.focus();
	await page.keyboard.press("Enter");
	const destination = navigation.locator('a[href="/#PX-PLAN-PLAN0002"]');
	await expect(destination).toBeVisible();
	await destination.focus();
	await page.keyboard.press("Enter");
	await expect(page.locator("#PX-PLAN-PLAN0002")).toBeInViewport();
	await page.locator("#search").fill("body-only-term");
	await page.locator("#search-button").click();
	await expect(page.locator("#PX-SPEC-SPEC0001")).toBeInViewport();
	await expect(page).toHaveURL(/#PX-SPEC-SPEC0001$/);
	await expect.poll(() => page.evaluate(() => scrollX)).toBe(0);
});

for (const mode of ["active", "cancelled", "hash-only"] as const) {
	test(
		"book reports active rendering failures after " + mode + " navigation",
		async ({ context }) => {
			const root = systemFixture();
			const spec = ".system/specs/PX-SPEC-SPEC0001-contract/index.md";
			write(
				root,
				spec,
				readFileSync(path.join(root, spec), "utf8") +
					'\n\n<a id="departure" href="/?departed">Leave</a>\n<a id="hash-only" href="#still-here">Stay</a>\n\n<pre class="mermaid">flowchart TD; this is invalid</pre>\n',
			);
			const runtime = createBoardRuntime();
			runtimes.push(runtime);
			const url = urlFromNotice(await runtime.open(root, undefined, "/"));
			const current = await context.newPage();
			observeHealth(current);
			const requested = Promise.withResolvers<void>();
			const release = Promise.withResolvers<void>();
			const diagnostics: string[] = [];
			current.on("pageerror", (error) => diagnostics.push(error.message));
			await current.route("**/browser/book.js", async (route) => {
				requested.resolve();
				await release.promise;
				await route.continue().catch(() => {});
			});
			if (mode === "cancelled")
				await current.addInitScript(() => {
					addEventListener("beforeunload", (event) => {
						event.preventDefault();
						event.returnValue = "";
					});
				});
			try {
				await current.goto(url, { waitUntil: "commit" });
				await requested.promise;
				await expect(current.locator("#departure")).toBeVisible();
				const origin = await current.evaluate(() => performance.timeOrigin);
				if (mode === "cancelled") {
					const dialog = current.waitForEvent("dialog");
					const navigation = current
						.locator("#departure")
						.click({ noWaitAfter: true });
					await (await dialog).dismiss();
					await navigation;
				} else if (mode === "hash-only") {
					await current.locator("#hash-only").click();
					await expect(current).toHaveURL(/#still-here$/);
				}
				expectPageError(current, /Parse error on line 1:/);
				const diagnostic = current.waitForEvent("pageerror");
				release.resolve();
				expect((await diagnostic).message).toContain("Parse error on line 1:");
				expect(await current.evaluate(() => performance.timeOrigin)).toBe(
					origin,
				);
				expect(diagnostics).toHaveLength(1);
				await expect(current.locator("#departure")).toBeVisible();
			} finally {
				release.resolve();
			}
		},
	);
}

test("book entry cancellation after confirmed document departure emits no runtime exception", async ({
	context,
}) => {
	const root = systemFixture();
	const spec = ".system/specs/PX-SPEC-SPEC0001-contract/index.md";
	write(
		root,
		spec,
		readFileSync(path.join(root, spec), "utf8") +
			'\n\n<a id="departure" href="about:blank">Leave</a>\n',
	);
	const runtime = createBoardRuntime();
	runtimes.push(runtime);
	const url = urlFromNotice(await runtime.open(root, undefined, "/"));
	const current = await context.newPage();
	observeHealth(current);
	expectHealth(current, "/browser/book.js:failed");
	const requested = Promise.withResolvers<Request>();
	const release = Promise.withResolvers<void>();
	const diagnostics: string[] = [];
	current.on("pageerror", (error) => diagnostics.push(error.message));
	await current.route("**/browser/book.js", async (route) => {
		requested.resolve(route.request());
		await release.promise;
		await route.continue().catch(() => {});
	});
	try {
		await current.goto(url, { waitUntil: "commit" });
		const entry = await requested.promise;
		await expect(current.locator("#departure")).toBeVisible();
		const origin = await current.evaluate(() => performance.timeOrigin);
		const failed = current.waitForEvent(
			"requestfailed",
			(request) => request === entry,
		);
		// about: is not an authored link scheme; set the native test target after rendering.
		await current.locator("#departure").evaluate((anchor) => {
			anchor.setAttribute("href", "about:blank");
		});
		await current.locator("#departure").click();
		await expect(current).toHaveURL("about:blank");
		expect(await current.evaluate(() => performance.timeOrigin)).not.toBe(
			origin,
		);
		release.resolve();
		expect((await failed).failure()?.errorText).toBeTruthy();
		expect(diagnostics).toEqual([]);
	} finally {
		release.resolve();
		await current.close();
	}
});

for (const mode of ["active", "stopped"] as const) {
	test(
		"book exposes initial entry failure on " + mode + " document",
		async ({ context, browserName }) => {
			const browserDirectory = fileURLToPath(
				new URL("../../../dist/the-system/browser/", import.meta.url),
			);
			const navigating = Promise.withResolvers<void>();
			const navigationClosed = Promise.withResolvers<void>();
			let closed = false;
			const server = createServer((request, response) => {
				const pathname = new URL(request.url ?? "/", "http://localhost")
					.pathname;
				if (pathname === "/pending-navigation") {
					response.on("close", () => {
						closed = true;
						navigationClosed.resolve();
					});
					navigating.resolve();
				} else if (pathname === "/browser/book.js") {
					response.setHeader("content-type", "text/javascript");
					void readFile(path.join(browserDirectory, "book.js")).then(
						(body) => {
							if (!response.destroyed) response.end(body);
						},
						() => {
							if (!response.destroyed) {
								response.statusCode = 404;
								response.end();
							}
						},
					);
				} else {
					response.setHeader("content-type", "text/html");
					response.end(
						pathname === "/frame"
							? "<!doctype html><body>child</body>"
							: '<!doctype html><script type="module" src="/browser/book.js"></script><pre class="mermaid">flowchart TD; A-->B</pre><iframe src="/frame"></iframe>',
					);
				}
			});
			await new Promise<void>((resolve) =>
				server.listen(0, "127.0.0.1", resolve),
			);
			const address = server.address();
			if (!address || typeof address === "string")
				throw new Error("No fixture port");
			const url = "http://127.0.0.1:" + address.port;
			const current = await context.newPage();
			observeHealth(current);
			expectHealth(current, "/browser/book.js:failed");
			const requested = Promise.withResolvers<Request>();
			const failEntry = Promise.withResolvers<void>();
			const diagnostics: string[] = [];
			current.on("pageerror", (error) => diagnostics.push(error.message));
			await current.addInitScript(() => {
				const failures: string[] = [];
				Object.defineProperty(window, "__entryFailures", { value: failures });
				addEventListener(
					"error",
					(event) => {
						const target = event.target;
						if (
							target instanceof HTMLScriptElement &&
							target.src &&
							new URL(target.src).pathname === "/browser/book.js"
						)
							failures.push("entry");
					},
					true,
				);
			});
			await current.route("**/browser/book.js", async (route) => {
				requested.resolve(route.request());
				await failEntry.promise;
				await route.abort("failed").catch(() => {});
			});
			try {
				await current.goto(url, { waitUntil: "commit" });
				const entry = await requested.promise;
				await expect(current.frameLocator("iframe").locator("body")).toHaveText(
					"child",
				);
				const origin = await current.evaluate(() => performance.timeOrigin);
				const failed = current.waitForEvent(
					"requestfailed",
					(request) => request === entry,
				);
				if (mode === "stopped") {
					expectHealth(current, "/pending-navigation:failed");
					await current.evaluate((destination) => {
						location.href = destination;
					}, url + "/pending-navigation");
					await navigating.promise;
					expect(closed).toBe(false);
					if (browserName === "chromium") {
						// Page.evaluate waits for the pending navigation; native Stop must not.
						const cdp = await context.newCDPSession(current);
						try {
							await cdp.send("Page.stopLoading");
						} finally {
							await cdp.detach();
						}
					} else await current.evaluate(() => stop());
					await navigationClosed.promise;
				}
				failEntry.resolve();
				expect((await failed).failure()?.errorText).toBeTruthy();
				// Explicit Stop cancels loading; Chromium does not emit a script error for that cancellation.
				// A genuine active load failure must still emit one in both engines.
				const entryErrors =
					mode === "stopped" && browserName === "chromium" ? [] : ["entry"];
				await expect
					.poll(() =>
						current.evaluate(() => Reflect.get(window, "__entryFailures")),
					)
					.toEqual(entryErrors);
				expect(await current.evaluate(() => performance.timeOrigin)).toBe(
					origin,
				);
				expect(diagnostics).toEqual([]);
				await expect(current.locator(".mermaid svg")).toHaveCount(0);
			} finally {
				failEntry.resolve();
				await current.close();
				server.closeAllConnections();
				await new Promise<void>((resolve) => server.close(() => resolve()));
			}
		},
	);
}

test("book scopes generated fragments without taking ownership of active raw HTML", async ({
	page,
}) => {
	const root = systemFixture();
	write(
		root,
		".system/SYSTEM.md",
		'<div id="core-custom">Core authored HTML.</div>\n\n# Core law\n\n[Core heading](#core-law)\n',
	);
	const spec = ".system/specs/PX-SPEC-SPEC0001-contract/index.md";
	write(
		root,
		spec,
		readFileSync(path.join(root, spec), "utf8") +
			[
				"",
				"Footnote reference[^1].",
				"",
				"[^1]: Document-local note.",
				"",
				'<div id="custom-fragment"><button id="increment" onclick="document.getElementById(\'counter\').textContent=String(Number(document.getElementById(\'counter\').textContent)+1)">increment</button><span id="counter">0</span><a id="custom-nav" href="#custom-fragment">custom fragment</a><svg id="icon" viewBox="0 0 10 10"><defs><linearGradient id="paint"><stop offset="0" stop-color="red"/></linearGradient></defs><rect id="painted" width="10" height="10" fill="url(#paint)"/><use id="paint-copy" href="#painted"/></svg></div>',
			].join("\n"),
	);
	for (const relative of [
		".system/specs/PX-SPEC-SPEC0001-contract/index.md",
		".system/plans/PX-PLAN-PLAN0001-build/index.md",
	])
		write(
			root,
			relative,
			readFileSync(path.join(root, relative), "utf8") +
				"\n\nFootnote reference[^2].\n\n[^2]: Document-local note.\n",
		);
	const runtime = createBoardRuntime();
	runtimes.push(runtime);
	await page.goto(urlFromNotice(await runtime.open(root, undefined, "/")));
	const coreArticle = page.locator(".book-section#CORE-SYSTEM");
	await expect(coreArticle.locator("#core-custom")).toHaveCount(1);
	await coreArticle
		.getByRole("link", { name: "Core heading", exact: true })
		.click();
	await expect(page).toHaveURL(/#CORE-SYSTEM-core-law$/);
	await expectUnoccludedByBookHeader(page, "#CORE-SYSTEM-core-law");
	const specArticle = page.locator(".book-section#PX-SPEC-SPEC0001");
	await specArticle.getByRole("button", { name: "increment" }).click();
	await expect(specArticle.locator("#counter")).toHaveText("1");
	expect(
		await specArticle.evaluate(() => ({
			counter: document.getElementById("counter")?.id,
			paint: document.getElementById("paint")?.id,
			fill: document.getElementById("painted")?.getAttribute("fill"),
			use: document.getElementById("paint-copy")?.getAttribute("href"),
			fragment: document.getElementById("custom-nav")?.getAttribute("href"),
		})),
	).toEqual({
		counter: "counter",
		paint: "paint",
		fill: "url(#paint)",
		use: "#painted",
		fragment: "#custom-fragment",
	});
	for (const id of ["PX-SPEC-SPEC0001", "PX-PLAN-PLAN0001"]) {
		const article = page.locator(`.book-section#${id}`);
		const reference = article.locator('sup a[href*="fn-"]');
		const target = await reference.first().getAttribute("href");
		expect(target).toMatch(new RegExp(`^#${id}-`));
		await expect(article.locator(target ?? "#missing")).toContainText(
			"Document-local note",
		);
		await expect(reference.first()).toHaveAttribute(
			"aria-describedby",
			`${id}-footnote-label`,
		);
		await expect(article.locator(`#${id}-footnote-label`)).toHaveCount(1);
		const backlink = article.locator(
			`${target ?? "#missing"} a[href*="fnref-"]`,
		);
		await expect(backlink).toHaveCount(1);
		await expect(backlink).toHaveAttribute("href", new RegExp(`^#${id}-`));
		await reference.first().click();
		expect(new URL(page.url()).hash).toBe(target);
		await expectUnoccludedByBookHeader(page, target ?? "#missing");
		const referenceTarget = await backlink.getAttribute("href");
		await backlink.click();
		expect(new URL(page.url()).hash).toBe(referenceTarget);
		await expectUnoccludedByBookHeader(page, referenceTarget ?? "#missing");
	}
});

test("graph controls, bounded pan and zoom, and light/dark desktop/mobile renderings", async ({
	page,
	browserName,
}, testInfo) => {
	const root = systemFixture();
	const video = await page.evaluate(async () => {
		const canvas = document.createElement("canvas");
		canvas.width = 80;
		canvas.height = 40;
		const ctx = canvas.getContext("2d");
		const stream = canvas.captureStream(10);
		const recorder = new MediaRecorder(stream, {
			mimeType: "video/webm;codecs=vp8",
		});
		const chunks: Blob[] = [];
		const stopped = new Promise<Blob>((resolve) => {
			recorder.ondataavailable = (event) => chunks.push(event.data);
			recorder.onstop = () => resolve(new Blob(chunks));
		});
		recorder.start();
		for (let i = 0; i < 4; i++) {
			if (ctx) {
				ctx.fillStyle = i % 2 ? "purple" : "teal";
				ctx.fillRect(0, 0, 80, 40);
			}
			await new Promise((resolve) => setTimeout(resolve, 100));
		}
		recorder.stop();
		const bytes = [...new Uint8Array(await (await stopped).arrayBuffer())];
		for (const track of stream.getTracks()) track.stop();
		return bytes;
	});
	const bundle = ".system/specs/PX-SPEC-SPEC0001-contract/";
	writeFileSync(testInfo.outputPath("clip.webm"), Buffer.from(video));
	writeFileSync(path.join(root, bundle, "clip.webm"), Buffer.from(video));
	write(
		root,
		`${bundle}index.md`,
		readFileSync(path.join(root, bundle, "index.md"), "utf8") +
			"\n\n[Clip](./clip.webm)\n\n```ts\nconst answer = 42;\n```\n\n| Key | Value |\n| --- | --- |\n| rich | Markdown |\n",
	);
	const runtime = createBoardRuntime();
	runtimes.push(runtime);
	const url = urlFromNotice(await runtime.open(root, undefined, "/"));
	let clipResponse: Response | undefined;
	page.on("response", (response) => {
		if (new URL(response.url()).pathname.endsWith("/clip.webm"))
			clipResponse = response;
	});
	await page.addInitScript(() => {
		const observe = (video: HTMLVideoElement) => {
			const observed = video as HTMLVideoElement & {
				__mediaEvents?: unknown[];
			};
			if (observed.__mediaEvents) return;
			observed.__mediaEvents = [];
			for (const type of [
				"loadstart",
				"loadedmetadata",
				"loadeddata",
				"canplay",
				"error",
			])
				video.addEventListener(type, () =>
					observed.__mediaEvents?.push({
						type,
						readyState: video.readyState,
						networkState: video.networkState,
					}),
				);
		};
		new MutationObserver((mutations) => {
			for (const mutation of mutations)
				for (const node of mutation.addedNodes)
					if (node instanceof HTMLVideoElement) observe(node);
		}).observe(document, { childList: true, subtree: true });
	});
	await page.goto(url);
	const graph = page.locator("[data-graph-svg]");
	const initial = await graph.getAttribute("viewBox");
	await page.locator('[data-graph-zoom="in"]').click();
	await expect(graph).not.toHaveAttribute("viewBox", initial ?? "");
	const zoomed = await graph.getAttribute("viewBox");
	const box = await graph.boundingBox();
	expect(box).not.toBeNull();
	if (!box) throw new Error("Graph bounds unavailable");
	await page.mouse.move(box.x + box.width - 4, box.y + box.height - 4);
	await page.mouse.down();
	await page.mouse.move(box.x + box.width - 90, box.y + box.height - 90, {
		steps: 5,
	});
	await page.mouse.up();
	await expect(graph).not.toHaveAttribute("viewBox", zoomed ?? "");
	await page.locator('[data-graph-zoom="out"]').click();
	await page.locator('[data-graph-zoom="reset"]').click();
	await expect(graph).toHaveAttribute("viewBox", initial ?? "");
	await graph.hover();
	await page.mouse.wheel(0, -200);
	await expect(graph).not.toHaveAttribute("viewBox", initial ?? "");
	for (let i = 0; i < 20; i++)
		await page.locator('[data-graph-zoom="in"]').click();
	const bounds = await graph.evaluate((svg) => ({
		box: svg.getAttribute("viewBox")?.split(" ").map(Number) ?? [],
		w: Number((svg as SVGElement).dataset["worldWidth"]),
		h: Number((svg as SVGElement).dataset["worldHeight"]),
	}));
	const [x = -1, y = -1, w = 0, h = 0] = bounds.box;
	expect(x).toBeGreaterThanOrEqual(0);
	expect(y).toBeGreaterThanOrEqual(0);
	expect(w).toBeGreaterThanOrEqual(180);
	expect(h).toBeGreaterThanOrEqual(120);
	expect(x + w).toBeLessThanOrEqual(bounds.w + 0.01);
	expect(y + h).toBeLessThanOrEqual(bounds.h + 0.01);
	for (let i = 0; i < 20; i++)
		await page.locator('[data-graph-zoom="out"]').click();
	await expect(graph).toHaveAttribute("viewBox", `0 0 ${bounds.w} ${bounds.h}`);
	await page.locator('[data-graph-zoom="reset"]').click();
	if (browserName === "chromium") {
		const cdp = await page.context().newCDPSession(page);
		const cx = box.x + box.width / 2,
			cy = box.y + box.height - 8;
		await cdp.send("Input.dispatchTouchEvent", {
			type: "touchStart",
			touchPoints: [
				{ x: cx - 20, y: cy },
				{ x: cx + 20, y: cy },
			],
		});
		await cdp.send("Input.dispatchTouchEvent", {
			type: "touchMove",
			touchPoints: [
				{ x: cx - 70, y: cy },
				{ x: cx + 70, y: cy },
			],
		});
		await cdp.send("Input.dispatchTouchEvent", {
			type: "touchEnd",
			touchPoints: [],
		});
		await expect(graph).not.toHaveAttribute("viewBox", initial ?? "");
		const pinched = await graph.getAttribute("viewBox");
		await cdp.send("Input.dispatchTouchEvent", {
			type: "touchStart",
			touchPoints: [{ x: cx, y: cy }],
		});
		await cdp.send("Input.dispatchTouchEvent", {
			type: "touchMove",
			touchPoints: [{ x: cx - 30, y: cy - 30 }],
		});
		await cdp.send("Input.dispatchTouchEvent", {
			type: "touchEnd",
			touchPoints: [],
		});
		await expect(graph).not.toHaveAttribute("viewBox", pinched ?? "");
		await cdp.detach();
	}
	await page.locator('[data-graph-zoom="reset"]').click();
	await graph.locator('a[href="#PX-SPEC-SPEC0001"]').click();
	await expect(page.locator("#PX-SPEC-SPEC0001")).toBeInViewport();
	const player = page.locator("video");
	await player.scrollIntoViewIfNeeded();
	const beforePlay = await player.evaluate((element) => {
		const video = element as HTMLVideoElement & { __mediaEvents?: unknown[] };
		return {
			currentSrc: video.currentSrc,
			events: video.__mediaEvents,
			networkState: video.networkState,
			readyState: video.readyState,
		};
	});
	try {
		await player.evaluate((element) => (element as HTMLVideoElement).play());
		await expect
			.poll(() =>
				player.evaluate((element) => (element as HTMLVideoElement).readyState),
			)
			.toBeGreaterThanOrEqual(2);
	} catch (cause) {
		try {
			const media = await player.evaluate((element) => {
				const video = element as HTMLVideoElement & {
					__mediaEvents?: unknown[];
				};
				return {
					currentSrc: video.currentSrc,
					error: video.error
						? { code: video.error.code, message: video.error.message }
						: undefined,
					events: video.__mediaEvents,
					networkState: video.networkState,
					readyState: video.readyState,
					source: video.querySelector("source")?.src,
				};
			});
			const response = clipResponse
				? {
						headers: await clipResponse.allHeaders(),
						status: clipResponse.status(),
						url: clipResponse.url(),
						bytes: (await clipResponse.body()).byteLength,
					}
				: undefined;
			writeFileSync(
				testInfo.outputPath("clip-diagnostics.json"),
				JSON.stringify({ beforePlay, media, response }, undefined, 2),
			);
		} catch {
			// Preserve the readiness assertion when its diagnostic collection fails.
		}
		throw cause;
	}
	await expect
		.poll(() =>
			player.evaluate((element) => (element as HTMLVideoElement).currentTime),
		)
		.toBeGreaterThan(0);
	await expect(page.locator("code.language-ts")).toContainText("answer");
	await expect(page.locator("math")).toBeVisible();
	await page
		.locator(".visual-asset-video")
		.getByRole("link", { name: "Open full-size" })
		.focus();
	let fullSizeRequest: Request | undefined;
	const fullSizeSettled = Promise.withResolvers<Request>();
	const captureFullSizeSettlement = (request: Request) => {
		if (request === fullSizeRequest) fullSizeSettled.resolve(request);
	};
	page.on("requestfinished", captureFullSizeSettlement);
	page.on("requestfailed", captureFullSizeSettlement);
	const clipUrl = new URL(`/${bundle}clip.webm`, url).href;
	const captureFullSizeRequest = (request: Request) => {
		if (
			request.isNavigationRequest() &&
			request.frame() === page.mainFrame() &&
			request.url() === clipUrl
		)
			fullSizeRequest ??= request;
	};
	page.on("request", captureFullSizeRequest);
	const embeddedOrigin = await page.evaluate(() => performance.timeOrigin);
	await page.keyboard.press("Enter");
	await expect(page).toHaveURL(/clip\.webm$/);
	await expect
		.poll(() =>
			page
				.locator("video")
				.evaluate((element) => (element as HTMLVideoElement).videoWidth),
		)
		.toBe(80);
	const nativeMediaOrigin = await page.evaluate(() => performance.timeOrigin);
	expect(nativeMediaOrigin).not.toBe(embeddedOrigin);
	await expect
		.poll(() =>
			page
				.locator("video")
				.evaluate((element) => (element as HTMLVideoElement).readyState),
		)
		.toBeGreaterThanOrEqual(2);
	expect(
		await page.locator("video").evaluate((element) => ({
			src: (element as HTMLVideoElement).currentSrc,
			error: (element as HTMLVideoElement).error?.code ?? null,
		})),
	).toEqual({ src: clipUrl, error: null });
	page.off("request", captureFullSizeRequest);
	for (const theme of ["light", "dark"] as const) {
		await page.emulateMedia({ colorScheme: theme });
		for (const size of ["desktop", "mobile"] as const) {
			await page.setViewportSize(
				size === "desktop"
					? { width: 1280, height: 900 }
					: { width: 390, height: 844 },
			);
			for (const mode of ["book", "board"] as const) {
				await page.goto(
					new URL(mode === "book" ? "/#PX-SPEC-SPEC0001" : "/board.html", url)
						.href,
				);
				if (mode === "board")
					await page
						.locator(
							'[data-id="PX-SPEC-SPEC0001"] > .board-row > .board-bundle > summary',
						)
						.click();
				await expect(page.locator(".mermaid svg .node")).toHaveCount(2);
				await expect
					.poll(() =>
						page.locator(".mermaid").evaluate((container) => {
							const bounds = container.getBoundingClientRect();
							return [...container.querySelectorAll(".node")].every((node) => {
								const rect = node.getBoundingClientRect();
								return (
									rect.width > 0 &&
									rect.height > 0 &&
									rect.left >= bounds.left &&
									rect.right <= bounds.right &&
									rect.top >= bounds.top &&
									rect.bottom <= bounds.bottom
								);
							});
						}),
					)
					.toBe(true);
				await page.screenshot({
					path: testInfo.outputPath(`${mode}-${theme}-${size}.png`),
					fullPage: mode === "board",
				});
				if (mode === "book" && size === "mobile") {
					await page.evaluate(() => scrollTo(0, 0));
					await page.screenshot({
						path: testInfo.outputPath(`book-${theme}-mobile-top.png`),
					});
				}
			}
		}
	}
	// The native media document's response stream can abort only when leaving it.
	// Inspect its terminal state after the successful return navigation, not before.
	expect(fullSizeRequest).toBeDefined();
	if (!fullSizeRequest)
		throw new Error("Native media navigation was not observed");
	const fullSizeResponse = await fullSizeRequest.response();
	expect(fullSizeResponse?.status()).toBe(200);
	expect(await fullSizeSettled.promise).toBe(fullSizeRequest);
	page.off("requestfinished", captureFullSizeSettlement);
	page.off("requestfailed", captureFullSizeSettlement);
	expect(await page.evaluate(() => performance.timeOrigin)).not.toBe(
		nativeMediaOrigin,
	);
	if (fullSizeRequest.failure()?.errorText === "net::ERR_ABORTED") {
		const state = health.get(page);
		if (!state) throw new Error("Health observer is not attached");
		expect(state.requestErrors.has(fullSizeRequest)).toBe(true);
		state.nativeMediaHandoffs.add(fullSizeRequest);
	}
});

test("board action dispatch, clipboard fixture, errors, and live proposal changes", async ({
	page,
}) => {
	const root = systemFixture();
	const runtime = createBoardRuntime();
	runtimes.push(runtime);
	const executions: string[] = [];
	let executionError = false;
	const url = urlFromNotice(
		await runtime.open(root, (id) => {
			if (executionError) throw new Error("Controlled execution failure");
			executions.push(id);
		}),
	);
	await page.addInitScript(() => {
		Object.defineProperty(navigator, "clipboard", {
			value: {
				writeText: async (value: string) => {
					if (sessionStorage.getItem("fixture-clipboard-denied"))
						throw new Error("Controlled clipboard denial");
					sessionStorage.setItem("fixture-clipboard", value);
				},
			},
		});
	});
	await page.goto(url);
	const plan = page.locator('[data-board-item][data-id="PX-PLAN-PLAN0001"]');
	const bundle = plan.locator(":scope > .board-row > .board-bundle");
	await expect(page.locator("body")).toHaveAttribute("data-live-ready", "true");
	const boardBefore = readFileSync(
		path.join(root, ".system/board.json"),
		"utf8",
	);
	await bundle.locator(":scope > summary").click();
	await expect(bundle).toHaveAttribute("open", "");
	expect(readFileSync(path.join(root, ".system/board.json"), "utf8")).toBe(
		boardBefore,
	);
	expect(executions).toEqual([]);
	await plan
		.getByRole("button", { name: "Copy PX-PLAN-PLAN0001", exact: true })
		.click();
	await expect(bundle).toHaveAttribute("open", "");
	expect(
		await page.evaluate(() => sessionStorage.getItem("fixture-clipboard")),
	).toBe("PX-PLAN-PLAN0001");
	await page.evaluate(() =>
		sessionStorage.setItem("fixture-clipboard-denied", "true"),
	);
	await plan
		.getByRole("button", { name: "Copy PX-PLAN-PLAN0001", exact: true })
		.click();
	await expect(page.locator("[data-board-notice]")).toContainText(
		"Controlled clipboard denial",
	);
	await expect(bundle).toHaveAttribute("open", "");
	await plan.locator("[data-exec]").click();
	await expect(page.locator("[data-board-notice]")).toContainText(
		"Exec requested",
	);
	expect(executions).toEqual(["PX-PLAN-PLAN0001"]);
	executionError = true;
	expectHealth(page, "/api/exec:400");
	await plan.locator("[data-exec]").click();
	await expect(page.locator("[data-board-notice]")).toContainText(
		"Controlled execution failure",
	);
	await expect(plan.locator("[data-exec]")).toBeEnabled();
	// Real server/editor dispatch, but isolated node process rather than user's editor.
	const editorScript = path.join(root, "editor.mjs");
	const editorLog = path.join(root, "edited.txt");
	writeFileSync(
		editorScript,
		`import { writeFileSync } from 'node:fs'; writeFileSync(${JSON.stringify(editorLog)}, process.argv[2]);`,
	);
	const previousVisual = process.env["VISUAL"];
	process.env["VISUAL"] =
		`${JSON.stringify(process.execPath)} ${JSON.stringify(editorScript)}`;
	try {
		await plan.locator("[data-edit]").click();
		await expect(page.locator("[data-board-notice]")).toContainText(
			"Document opened in editor",
		);
		expect(readFileSync(editorLog, "utf8")).toBe(
			path.join(root, ".system/plans/PX-PLAN-PLAN0001-build/index.md"),
		);
	} finally {
		if (previousVisual === undefined) delete process.env["VISUAL"];
		else process.env["VISUAL"] = previousVisual;
	}
	// Negative UI contract only; never fall through to native editor fallbacks.
	expectHealth(page, "/api/edit:400");
	await page.route("**/api/edit", (route) =>
		route.fulfill({
			status: 400,
			contentType: "application/json",
			body: JSON.stringify({ error: "Cannot open editor: controlled fixture" }),
		}),
	);
	await plan.locator("[data-edit]").click();
	await expect(page.locator("[data-board-notice]")).toContainText(
		"Cannot open editor",
	);
	await expect(plan.locator("[data-edit]")).toBeEnabled();
	await page.unroute("**/api/edit");
	await runtime.tool.execute(
		"proposal",
		{
			items: [
				{
					id: "PX-ISSUE-ISSUE001",
					state: "done",
					rationale: "Live verified proposal",
				},
			],
		},
		new AbortController().signal,
		undefined,
		{ cwd: root } as never,
	);
	const issue = page.locator('[data-board-item][data-id="PX-ISSUE-ISSUE001"]');
	await expect(issue.locator("[data-proposal]")).toContainText(
		"Live verified proposal",
		{ timeout: 15000 },
	);
	await expect(bundle).toHaveAttribute("open", "");
	// Replace proposal after display, then click stale button before next poll.
	await runtime.tool.execute(
		"proposal",
		{ items: [] },
		new AbortController().signal,
		undefined,
		{ cwd: root } as never,
	);
	expectHealth(page, "/api/proposal:400");
	await issue.locator("[data-apply-proposal]").click();
	await expect(page.locator("[data-board-notice]")).toContainText(
		"No matching assessment proposal",
	);
	await expect(issue).not.toHaveClass(/is-done/);
	await expect(issue.locator("[data-proposal]")).toHaveCount(0, {
		timeout: 15000,
	});
});

test("commands share authenticated server, isolate cookies, reject cross-origin, and reopen after shutdown", async ({
	page,
	playwright,
}) => {
	const root = systemFixture();
	const runtime = createBoardRuntime();
	runtimes.push(runtime);
	const notices: string[] = [];
	const command = createSystemCommand({ sendUserMessage() {} } as never, {
		openBook: (cwd, destination) => runtime.open(cwd, undefined, destination),
	});
	for (const args of [
		"book",
		"board",
		"view PX-SPEC-SPEC0001",
		"view contract",
		"view .system/specs/PX-SPEC-SPEC0001-contract/index.md",
	])
		await command.handler(args, ctx(root, notices));
	const urls = notices.map(urlFromNotice);
	expect(new Set(urls.map((url) => new URL(url).origin)).size).toBe(1);
	const url = urls[0] ?? "";
	const origin = new URL(url).origin;
	const anonymous = await playwright.request.newContext();
	try {
		expect((await anonymous.get(`${origin}/`)).status()).toBe(403);
		const handshake = await anonymous.get(url, { maxRedirects: 0 });
		expect(handshake.status()).toBe(303);
		expect(handshake.headers()["set-cookie"]).toContain(
			"HttpOnly; SameSite=Strict",
		);
		expect(handshake.headers()["location"]).toBe("/");
		expect((await anonymous.get(`${origin}/`)).ok()).toBe(true);
		const cross = await anonymous.post(`${origin}/api/state`, {
			headers: { origin: "https://attacker.invalid" },
			data: { id: "PX-PLAN-PLAN0001", state: "done" },
		});
		expect(cross.status()).toBe(403);
		expect(await cross.json()).toEqual({ error: "Invalid board origin" });
		const other = createBoardRuntime();
		runtimes.push(other);
		const otherUrl = urlFromNotice(await other.open(systemFixture()));
		expect(
			(await anonymous.get(new URL("/api/state", otherUrl).href)).status(),
		).toBe(403);
		for (const view of urls.slice(2)) {
			await page.goto(view);
			await expect(page).toHaveURL(/#PX-SPEC-SPEC0001$/);
			await expect(page.locator("#PX-SPEC-SPEC0001")).toBeInViewport();
		}
		await page.close();
		runtime.shutdown();
		await expect(
			anonymous.get(`${origin}/api/state`, { timeout: 2000 }),
		).rejects.toThrow();
		const reopened = urlFromNotice(await runtime.open(root));
		expect(new URL(reopened).searchParams.get("k")).not.toBe(
			new URL(url).searchParams.get("k"),
		);
		expect(
			(await anonymous.get(new URL("/api/state", reopened).href)).status(),
		).toBe(403);
		expect((await anonymous.get(reopened)).ok()).toBe(true);
	} finally {
		await anonymous.dispose();
	}
});

test("multiple tabs follow live state and recover malformed board while preserving reading context", async ({
	page,
	context,
}) => {
	const root = systemFixture();
	const runtime = createBoardRuntime();
	runtimes.push(runtime);
	const url = urlFromNotice(
		await runtime.open(root, undefined, "/#PX-SPEC-SPEC0001"),
	);
	await page.goto(url);
	const second = await context.newPage();
	observeHealth(second);
	await second.goto(new URL("/board.html", url).href);
	const ledger = page.locator("#PX-SPEC-SPEC0001 .ledger");
	await ledger.locator(":scope > summary").click();
	await page.locator("#search").fill("body-only-term");
	const plan = second.locator('[data-board-item][data-id="PX-PLAN-PLAN0001"]');
	await plan.locator(".board-state").click();
	await second
		.locator('[data-board-item][data-id="PX-PLAN-PLAN0002"] .board-state')
		.click();
	await second
		.locator(
			'[data-board-item][data-id="PX-SPEC-SPEC0001"] > .board-row > .board-actions > .board-state',
		)
		.click();
	await expect(
		page.locator("#PX-SPEC-SPEC0001 [data-board-toggle]"),
	).toHaveText("done", { timeout: 15000 });
	await expect(ledger).toHaveAttribute("open", "");
	await expect(page.locator("#results")).toContainText("body-only-term");
	const board = readFileSync(path.join(root, ".system/board.json"), "utf8");
	write(root, ".system/board.json", "{");
	await expect(page.locator("[data-board-notice]")).toContainText(
		"Invalid board JSON",
		{ timeout: 15000 },
	);
	await expect(second.locator("[data-board-notice]")).toContainText(
		"Invalid board JSON",
		{ timeout: 15000 },
	);
	const preview = new URL(
		"/.system/specs/PX-SPEC-SPEC0001-contract/mockup-card.html",
		url,
	).href;
	expect(await (await page.request.get(preview)).text()).toContain(
		"Mockup card",
	);
	await expect(plan).toHaveClass(/is-done/);
	write(root, ".system/board.json", board);
	const spec = ".system/specs/PX-SPEC-SPEC0001-contract/index.md";
	const goodSource = readFileSync(path.join(root, spec), "utf8");
	const malformed = ".system/issues/PX-ISSUE-ISSUE002-broken/index.md";
	write(root, malformed, "---\nid: [\n---\n");
	await expect(page.locator("#diagnostics")).toContainText(malformed, {
		timeout: 15000,
	});
	expect(await (await page.request.get(preview)).text()).toContain(
		"Mockup card",
	);
	await expect(page.locator("#PX-SPEC-SPEC0001")).toBeVisible();
	write(
		root,
		malformed,
		"---\nid: PX-ISSUE-ISSUE002\ntype: issue\ntitle: Repaired\nspecs: [PX-SPEC-SPEC0001]\n---\n\n# Repaired\n",
	);
	write(root, spec, goodSource + "\n\nRecovered across tabs.\n");
	await expect(
		page.getByText("Recovered across tabs.", { exact: true }),
	).toBeVisible({ timeout: 15000 });
	await expect(ledger).toHaveAttribute("open", "");
	await expect(page.locator("#search")).toHaveValue("body-only-term");
	await expect(page.locator("#results")).toContainText("body-only-term");
	await expect(page).toHaveURL(/#PX-SPEC-SPEC0001$/);
	await plan.locator(":scope > .board-row > .board-bundle > summary").click();
	await expect(plan.getByText("Build", { exact: true }).first()).toBeVisible();
	expectHealth(second, "/api/exec:failed");
	await second.route("**/api/exec", (route) => route.abort("failed"));
	await plan.locator(".board-state").click();
	await expect(plan.locator("[data-exec]")).toBeEnabled();
	await plan.locator("[data-exec]").click();
	await expect(second.locator("[data-board-notice]")).toContainText(
		"Reopen it with /system board",
	);
	await expect(plan.locator("[data-exec]")).toBeEnabled();
	await second.close();
});

function expectHealth(page: Page, key: string, count = 1): void {
	const state = health.get(page);
	if (!state) throw new Error("Health observer is not attached");
	state.expected.set(key, (state.expected.get(key) ?? 0) + count);
}

function expectPageError(page: Page, pattern: RegExp): void {
	const state = health.get(page);
	if (!state) throw new Error("Health observer is not attached");
	state.expectedPageErrors.push(pattern);
}

function consumeExpected(
	state: NonNullable<ReturnType<typeof health.get>>,
	key: string,
): boolean {
	const remaining = state.expected.get(key) ?? 0;
	if (!remaining) return false;
	state.expected.set(key, remaining - 1);
	return true;
}

function moduleDependencies(source: string): string[] {
	const parsed = parseSync("browser.js", source);
	expect(parsed.errors).toEqual([]);
	const module = parsed.module;
	return [
		...module.staticImports.map((item) => item.moduleRequest.value),
		...module.staticExports.flatMap((item) =>
			item.entries.flatMap((entry) =>
				entry.moduleRequest ? [entry.moduleRequest.value] : [],
			),
		),
		...module.dynamicImports.map((item) => {
			const expression = source.slice(
				item.moduleRequest.start,
				item.moduleRequest.end,
			);
			const literal = /^["'`]([\w./-]+)["'`]$/.exec(expression);
			expect(literal, expression).not.toBeNull();
			return literal?.[1] ?? "";
		}),
	];
}

async function expectUnoccludedByBookHeader(page: Page, selector: string) {
	await expect
		.poll(() =>
			page.locator(selector).evaluate((heading) => {
				const header = document.querySelector(".book-top");
				return !header || getComputedStyle(header).position !== "fixed"
					? true
					: heading.getBoundingClientRect().top >=
							header.getBoundingClientRect().bottom;
			}),
		)
		.toBe(true);
}

async function assertSidebarConnected(page: Page) {
	await expect(page.locator(".book-nav")).toBeVisible();
	await expect(page.locator(".book-nav")).toBeInViewport();
	const layout = await page.evaluate(() => {
		const top = document.querySelector(".book-top")?.getBoundingClientRect();
		const nav = document.querySelector(".book-nav")?.getBoundingClientRect();
		const main = document.querySelector(".book-main")?.getBoundingClientRect();
		return {
			scrollX,
			top: top
				? { bottom: top.bottom, left: top.left, right: top.right }
				: null,
			nav: nav ? { top: nav.top, left: nav.left, right: nav.right } : null,
			main: main ? { left: main.left } : null,
		};
	});
	expect(layout.scrollX).toBe(0);
	expect(layout.top?.left).toBe(0);
	expect(layout.nav?.top).toBe(layout.top?.bottom);
	expect(layout.nav?.left).toBeGreaterThanOrEqual(0);
	expect(layout.nav?.right ?? 0).toBeLessThan(layout.main?.left ?? 0);
}

function ctx(root: string, notices: string[]) {
	return {
		cwd: root,
		waitForIdle: async () => {},
		ui: { notify: (message: string) => notices.push(message) },
	} as never;
}

function systemFixture(): string {
	const root = mkdtempSync(path.join(tmpdir(), "the-system-render-e2e-"));
	roots.push(root);
	for (const directory of ["specs", "phases", "plans", "issues", "research"])
		mkdirSync(path.join(root, ".system", directory), { recursive: true });
	write(
		root,
		".system/config.json",
		'{"prefix":"PX","schemaVersion":0,"currentPhase":"PX-PHASE-PHASE002"}',
	);
	write(root, ".system/board.json", '{"schemaVersion":0,"items":{}}');
	write(root, ".system/SYSTEM.md", "# SYSTEM\n");
	write(root, ".system/MISSION.md", "# MISSION\n");
	write(root, ".system/RULES.md", "# RULES\n");
	write(
		root,
		".system/research/PX-RESEARCH-RSCH0001-notes/index.md",
		"---\nid: PX-RESEARCH-RSCH0001\ntype: research\ntitle: Notes\n---\n\n# Notes\n",
	);
	write(
		root,
		".system/specs/PX-SPEC-SPEC0001-contract/index.md",
		[
			"---",
			"id: PX-SPEC-SPEC0001",
			"type: spec",
			"title: Contract",
			"research: [PX-RESEARCH-RSCH0001]",
			"---",
			"",
			"# Contract",
			"",
			"body-only-term",
			"",
			"```mermaid",
			"flowchart TD; A-->B;",
			"```",
			"",
			"$x+1$",
			"",
			"[Mockup](./mockup-card.html)",
			"",
			"<p>raw html works</p>",
		].join("\n"),
	);
	write(
		root,
		".system/specs/PX-SPEC-SPEC0001-contract/mockup-card.html",
		"<section>Mockup card</section>",
	);
	write(
		root,
		".system/phases/PX-PHASE-PHASE001-delivery/index.md",
		"---\nid: PX-PHASE-PHASE001\ntype: phase\ntitle: Prototype\nlabel: prototype\n---\n\n# Prototype\n",
	);
	write(
		root,
		".system/phases/PX-PHASE-PHASE002-after-delivery/index.md",
		"---\nid: PX-PHASE-PHASE002\ntype: phase\ntitle: Pre-v1\nlabel: pre-v1\n---\n\n# Pre-v1\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/plans/PX-PLAN-PLAN0002-test/index.md",
		"---\nid: PX-PLAN-PLAN0002\ntype: plan\ntitle: Test\nspec: PX-SPEC-SPEC0001\nstatus: draft\ndepends_on: [PX-PLAN-PLAN0001]\n---\n\n# Test\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) {
	const target = path.join(root, relative);
	mkdirSync(path.dirname(target), { recursive: true });
	writeFileSync(target, content, "utf8");
}

function urlFromNotice(notice: string): string {
	const match = notice.match(/(?:opened|running): (http:\/\/\S+)$/m);
	expect(match?.[1]).toBeTruthy();
	return match?.[1] ?? "";
}

function hashTree(root: string): string {
	const hash = createHash("sha256");
	for (const file of files(root).sort()) {
		hash.update(path.relative(root, file));
		hash.update(readFileSync(file));
	}
	return hash.digest("hex");
}

function files(root: string): string[] {
	return readdirSync(root).flatMap((name) => {
		const file = path.join(root, name);
		return statSync(file).isDirectory() ? files(file) : [file];
	});
}