fixture.ts

10.5 KB · raw

1import { existsSync } from "node:fs";2import { mkdir, mkdtemp, writeFile } from "node:fs/promises";3import { tmpdir } from "node:os";4import { join } from "node:path";5import { blake3 } from "@noble/hashes/blake3.js";6import { bytesToHex } from "@noble/hashes/utils.js";7import type { ReleaseFile } from "../src/bucket/repo.ts";89/**10 * §4.3 of the resolutions: these tests are pinned to one koh, so a stale binary cannot make a pass11 * look real. The version is checked before any fixture runs; the message says how to fix it.12 * `KOH_BIN` names another binary (a build of the format-2 koh, say) for every fixture it makes.13 */14export const KOH_BIN = process.env.KOH_BIN ?? "koh";1516const PINNED_KOH = (await Bun.file(join(import.meta.dir, "koh-version.txt")).text()).trim();17const RUNNING_KOH = (() => {18	try {19		return Bun.spawnSync([KOH_BIN, "--version"]).stdout.toString().trim();20	} catch {21		return "";22	}23})();24if (RUNNING_KOH !== `koh ${PINNED_KOH}`) {25	throw new Error(26		`these tests are pinned to koh ${PINNED_KOH}, but ${KOH_BIN} reports "${RUNNING_KOH}" — ` +27			"install the matching koh (see koh's AGENTS.md), or update tests/koh-version.txt " +28			"once you have verified the new one",29	);30}3132export type Fixture = {33	bucketDir: string;34	repo: string;35	repoDir: string;36	/** The remote layout the fixture's bucket came out as (§9.2). */37	format: 1 | 2;38	/** Every save, newest first, checkpoint included. */39	saveIds: string[];40	/** Strips a path from every save with koh, so tests can sync before and after. */41	strip(path: string): Promise<void>;42};4344// The smallest valid PNG (1×1), so the fixture has a real binary file.45const PNG = Uint8Array.from(46	atob(47		"iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==",48	),49	(c) => c.charCodeAt(0),50);5152const README = `<!-- a leading comment and a centred title are not the intro -->5354<p align="center">DEMO</p>5556# Demo5758A small repo for **Kepr's** tests.5960See [the guide](docs/guide.md), [the site](https://example.com) and [a trap](javascript:alert(1)).6162![logo](docs/logo.png)6364<script>alert("raw html")</script>65`;6667/**68 * Builds a genuine Koh 3 folder remote with koh itself, under a throwaway HOME. The line is:69 * "add docs, a secret and a deep helper" (flagged) → a second later "add readme and entry point"70 * (agent and session) → a checkpoint holding an edit to the guide → "say hello" (head).71 *72 * The bucket is pinned to `koh-remote 1` unless `format: 2` is asked for: a fresh bucket made by a73 * format-2 koh is version 2, and §9.2 lets an existing repo keep version 1, which is what the tests74 * that edit a real record's file list read.75 */76export async function makeKohBucket(77	repo = "demo",78	options: { format?: 1 | 2; bin?: string } = {},79): Promise<Fixture> {80	const root = await mkdtemp(join(tmpdir(), "kepr-fixture-"));81	const home = join(root, "home");82	const bucketDir = join(root, "bucket");83	const repoDir = join(root, "work", repo);84	await mkdir(home);85	await mkdir(join(repoDir, "src/lib/deep"), { recursive: true });86	await mkdir(join(repoDir, "docs"));87	await mkdir(join(repoDir, "vendor"));88	const koh = (...args: string[]) => run(repoDir, home, args, options.bin);8990	koh("init");91	koh("remote", "folder", bucketDir);92	if (options.format !== 2) {93		await mkdir(join(bucketDir, repo), { recursive: true });94		await writeFile(join(bucketDir, repo, "format"), "koh-remote 1");95	}96	await writeFile(join(repoDir, "docs/guide.md"), "# Guide\n\nRead me.\n");97	await writeFile(join(repoDir, "docs/logo.png"), PNG);98	await writeFile(join(repoDir, "secret.txt"), "hunter2\n");99	await writeFile(100		join(repoDir, "src/lib/deep/util.ts"),101		"// The *one* helper. Deep down.\nexport const one = 1;\n",102	);103	await writeFile(join(repoDir, "vendor/big.c"), "int x;\n".repeat(100));104	koh("save", "add docs, a secret and a deep helper");105	const first = JSON.parse(koh("view", "--json")).head_id as string;106	koh("flag", first, "--reason", "holds a secret");107	// Saves a second apart, so the timeline has time to spread over.108	Bun.sleepSync(1100);109	await writeFile(join(repoDir, "README.md"), README);110	await writeFile(join(repoDir, "src/main.ts"), "// Entry point.\nconsole.log('hi');\n");111	koh("save", "add readme and entry point", "--agent", "test-agent", "--session", "fixture");112	// The guide's edit is first recorded by the checkpoint; the Atlas must credit it to "say hello".113	await writeFile(join(repoDir, "docs/guide.md"), "# Guide\n\nRead me. It is short.\n");114	koh("checkpoint", "before the second change");115	await writeFile(join(repoDir, "src/main.ts"), "// Entry point.\nconsole.log('hello');\n");116	koh("save", "say hello");117	koh("offer");118119	const log = JSON.parse(koh("view", "--json")) as { saves: { id: string }[] };120	const format = (await Bun.file(join(bucketDir, repo, "format")).text()).trim();121	return {122		bucketDir,123		repo,124		repoDir,125		format: format === "koh-remote 2" ? 2 : 1,126		saveIds: log.saves.map((save) => save.id),127		strip: (path) => stripPath(repoDir, home, path, options.bin),128	};129}130131/**132 * Whether `bin` writes a format-2 repo: false when it is absent, or writes `koh-remote 1`, in133 * which case the format-2 tests say how to run themselves and skip.134 */135export async function writesFormat2(bin: string): Promise<boolean> {136	if (!existsSync(bin)) return false;137	const space = await kohWorkspace("format-probe");138	const probe = (...args: string[]) => run(space.repoDir, space.home, args, bin);139	try {140		probe("init");141		probe("remote", "folder", space.bucketDir);142		await writeFile(join(space.repoDir, "probe.txt"), "probe\n");143		probe("save", "probe the format");144		probe("offer");145		return (146			(await Bun.file(join(space.bucketDir, "format-probe", "format")).text()).trim() ===147			"koh-remote 2"148		);149	} catch {150		return false;151	}152}153154function run(cwd: string, home: string, args: string[], bin = KOH_BIN): string {155	const result = Bun.spawnSync([bin, ...args], { cwd, env: env(home) });156	if (result.exitCode !== 0) {157		throw new Error(158			`koh ${args.join(" ")} failed: ${result.stderr.toString()}${result.stdout.toString()}`,159		);160	}161	return result.stdout.toString();162}163164function env(home: string) {165	return { PATH: process.env.PATH, HOME: home, NO_COLOR: "1" };166}167168/** `koh strip` insists on a terminal and a typed confirmation, so it runs under a Bun PTY. */169export async function stripPath(170	cwd: string,171	home: string,172	path: string,173	bin = KOH_BIN,174): Promise<void> {175	let output = "";176	const proc = Bun.spawn([bin, "strip", path], {177		cwd,178		env: env(home),179		terminal: { cols: 120, rows: 24, data: (_term, data) => (output += data.toString()) },180	});181	proc.terminal?.write(`y\n${path}\n`);182	const code = await proc.exited;183	proc.terminal?.close();184	if (code !== 0) throw new Error(`koh strip ${path} failed: ${output}`);185}186187/** What `makeRepos` hands back: the folder remote, its saves, and a way to run koh in a repo. */188export type FixtureRepos = {189	bucketDir: string;190	saves: Record<string, string>;191	/** Runs koh in one of the repos, under the fixture's HOME. */192	koh(repo: string, ...args: string[]): string;193};194195/** Repos with one koh save each, all offered to one folder remote: enough history for releases. */196export async function makeRepos(names: string[]): Promise<FixtureRepos> {197	const root = await mkdtemp(join(tmpdir(), "kepr-repos-"));198	const home = join(root, "home");199	const bucketDir = join(root, "bucket");200	await mkdir(home);201	const saves: Record<string, string> = {};202	for (const [i, name] of names.entries()) {203		const repoDir = join(root, "work", name);204		await mkdir(repoDir, { recursive: true });205		run(repoDir, home, ["init"]);206		if (i === 0) run(repoDir, home, ["remote", "folder", bucketDir]);207		await writeFile(join(repoDir, "README.md"), `# ${name}\n\nThe ${name} project.\n`);208		run(repoDir, home, ["save", `release ${name}`]);209		saves[name] = JSON.parse(run(repoDir, home, ["view", "--json"])).head_id;210	}211	return {212		bucketDir,213		saves,214		koh: (repo, ...args) => run(join(root, "work", repo), home, args),215	};216}217218/** A throwaway HOME, a repo folder and a bucket, with koh runnable inside (§4.3's pinned binary). */219export async function kohWorkspace(repo = "shipped"): Promise<{220	root: string;221	home: string;222	repoDir: string;223	bucketDir: string;224	run(...args: string[]): string;225}> {226	const root = await mkdtemp(join(tmpdir(), "kepr-workspace-"));227	const home = join(root, "home");228	const repoDir = join(root, "work", repo);229	const bucketDir = join(root, "bucket");230	await mkdir(home);231	await mkdir(repoDir, { recursive: true });232	return { root, home, repoDir, bucketDir, run: (...args) => run(repoDir, home, args) };233}234235/** A release file with its bytes, or only as a record declares it (the bytes are then a stand-in). */236export type FixtureFile = { platform: string; name: string; bytes: Uint8Array } | ReleaseFile;237238export type FixtureRelease = {239	version: string;240	save: string;241	notes?: string;242	publishedAt?: number;243	files: FixtureFile[];244};245246/**247 * Publishes a release straight into a folder remote, in §11.2's order: the files, then release.json,248 * then `releases/latest`. `kohWorkspace` plus `koh offer --builds` is the real thing249 * (tests/kohrelease.test.ts); this writes them by hand for fixtures that need several versions, an250 * old release, or hashes that no build produced.251 */252export async function writeRelease(253	bucketDir: string,254	repo: string,255	release: FixtureRelease,256	latest = true,257): Promise<void> {258	const dir = join(bucketDir, repo, "releases", release.version);259	const files: ReleaseFile[] = [];260	for (const file of release.files) {261		const bytes = "bytes" in file ? file.bytes : new TextEncoder().encode(`stand-in ${file.name}`);262		await mkdir(join(dir, file.platform), { recursive: true });263		await writeFile(join(dir, file.platform, file.name), bytes);264		files.push(265			"bytes" in file266				? {267						platform: file.platform,268						name: file.name,269						size: bytes.length,270						blake3: bytesToHex(blake3(bytes)),271						sha256: new Bun.CryptoHasher("sha256").update(bytes).digest("hex"),272					}273				: file,274		);275	}276	const record = {277		format: 1,278		repo,279		version: release.version,280		save: release.save,281		published_at: release.publishedAt ?? 1790000000,282		machine: "fixture",283		notes: release.notes ?? "",284		files,285	};286	await writeFile(join(dir, "release.json"), JSON.stringify(record, null, 2));287	if (latest) await writeFile(join(bucketDir, repo, "releases", "latest"), release.version);288}289290/** This machine's platform, which is what `koh build` builds for with no flags. */291export function platform(): string {292	const os = process.platform === "darwin" ? "macos" : "linux";293	const arch = process.arch === "arm64" ? "aarch64" : "x86_64";294	return `${os}-${arch}`;295}