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";891011121314export 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 37 format: 1 | 2;38 39 saveIds: string[];40 41 strip(path: string): Promise<void>;42};434445const 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)).61626364<script>alert("raw html")</script>65`;6667686970717273747576export 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 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 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}130131132133134135export 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}167168169export 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}186187188export type FixtureRepos = {189 bucketDir: string;190 saves: Record<string, string>;191 192 koh(repo: string, ...args: string[]): string;193};194195196export 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}217218219export 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}234235236export 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};245246247248249250251252export 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}289290291export 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}