1import { Database } from "bun:sqlite";2import { beforeAll, describe, expect, test } from "bun:test";3import { mkdtemp, writeFile } from "node:fs/promises";4import { tmpdir } from "node:os";5import { join } from "node:path";6import { openBucket } from "../src/bucket/reader.ts";7import { syncAll } from "../src/bucket/sync.ts";8import {9 fileAt,10 filesAt,11 flagReason,12 headId,13 history,14 objectBytes,15 repoStats,16 saveByPrefix,17 timeline,18} from "../src/mirror/queries.ts";19import { openMirror } from "../src/mirror/store.ts";20import { openKeprDb } from "../src/server/db.ts";21import { type Fixture, makeKohBucket } from "./fixture.ts";2223const text = (bytes: Uint8Array | null) => new TextDecoder().decode(bytes ?? new Uint8Array());2425async function syncTarget(fx: Fixture) {26 const dataDir = await mkdtemp(join(tmpdir(), "kepr-data-"));27 const target = {28 bucket: openBucket({ kind: "folder", path: fx.bucketDir }),29 kepr: openKeprDb(dataDir),30 mirrorDir: join(dataDir, "mirror"),31 };32 return { ...target, mirror: () => openMirror(target.mirrorDir, fx.repo) };33}3435describe("a first sync of a koh3 bucket", () => {36 let fx: Fixture;37 let t: Awaited<ReturnType<typeof syncTarget>>;38 beforeAll(async () => {39 fx = await makeKohBucket();40 t = await syncTarget(fx);41 await syncAll(t);42 });43 const [head, checkpoint, second, first] = [0, 1, 2, 3].map((i) => () => fx.saveIds[i] as string);4445 test("registers the repo private, with a clean last sync", () => {46 const row = t.kepr.query("SELECT public, last_sync_at, last_sync_error FROM repos").get() as {47 public: number;48 last_sync_at: number;49 last_sync_error: string | null;50 };51 expect(row.public).toBe(0);52 expect(row.last_sync_error).toBeNull();53 expect(row.last_sync_at).toBeGreaterThan(0);54 });5556 test("history is newest first and leaves out the checkpoint", () => {57 expect(headId(t.mirror())).toBe(head());58 expect(history(t.mirror(), 10, 0).map((s) => s.id)).toEqual([head(), second(), first()]);59 expect(history(t.mirror(), 1, 1).map((s) => s.message)).toEqual(["add readme and entry point"]);60 expect(timeline(t.mirror()).map((s) => s.id)).toEqual([first(), second(), head()]);61 expect(saveByPrefix(t.mirror(), checkpoint())?.is_checkpoint).toBe(true);62 });6364 test("finds a save by a unique prefix of six or more characters", () => {65 const save = saveByPrefix(t.mirror(), second().slice(0, 6));66 expect([save?.id, save?.agent, save?.session]).toEqual([second(), "test-agent", "fixture"]);67 expect(saveByPrefix(t.mirror(), second().slice(0, 5))).toBeNull();68 expect(saveByPrefix(t.mirror(), "zzzzzz")).toBeNull();69 });7071 test("reads files and their bytes at any save", () => {72 const paths = filesAt(t.mirror(), head()).map((f) => f.path);73 expect(paths).toContain("src/lib/deep/util.ts");74 const now = fileAt(t.mirror(), head(), "src/main.ts");75 const then = fileAt(t.mirror(), second(), "src/main.ts");76 expect(text(objectBytes(t.mirror(), now?.hash as string))).toContain("hello");77 expect(text(objectBytes(t.mirror(), then?.hash as string))).toContain("'hi'");78 expect(fileAt(t.mirror(), first(), "src/main.ts")).toBeNull();79 expect(fileAt(t.mirror(), head(), "docs/logo.png")?.size).toBe(70);80 });8182 test("counts saves without checkpoints, and lines and language at head", () => {83 const stats = repoStats(t.mirror());84 expect(stats.saves).toBe(3);85 expect(stats.language).toBe("TypeScript");86 87 expect(stats.lines).toBeGreaterThan(16);88 89 expect(stats.lines).toBeLessThan(100);90 expect(stats.updated).toBe(saveByPrefix(t.mirror(), head())?.created_at ?? -1);91 });9293 test("stores the flag event", () => {94 const flag = t.mirror().query("SELECT kind, save_id, reason FROM events").get();95 expect(flag).toEqual({ kind: "flag", save_id: first(), reason: "holds a secret" });96 });9798 test("a save's flag state is its newest flag or clear event, by time and then ID", async () => {99 expect(flagReason(t.mirror(), first())).toBe("holds a secret");100 expect(flagReason(t.mirror(), head())).toBeNull();101 const mirror = openMirror(await mkdtemp(join(tmpdir(), "kepr-flags-")), "flags");102 const event = mirror.query(103 "INSERT INTO events (id, kind, save_id, reason, created_at, machine) VALUES (?, ?, 'aaaaaaaaaaaa', ?, ?, 'm')",104 );105 event.run("000000000001", "flag", "first", 10);106 expect(flagReason(mirror, "aaaaaaaaaaaa")).toBe("first");107 event.run("000000000002", "clear", null, 20);108 expect(flagReason(mirror, "aaaaaaaaaaaa")).toBeNull();109 110 event.run("000000000003", "flag", "again", 20);111 expect(flagReason(mirror, "aaaaaaaaaaaa")).toBe("again");112 event.run("000000000000", "clear", null, 20);113 expect(flagReason(mirror, "aaaaaaaaaaaa")).toBe("again");114 });115116 test("a strip reaches the mirror and drops the object", async () => {117 const secret = fileAt(t.mirror(), head(), "secret.txt")?.hash as string;118 expect(objectBytes(t.mirror(), secret)).not.toBeNull();119 await fx.strip("secret.txt");120 await syncAll(t);121 for (const id of fx.saveIds) expect(fileAt(t.mirror(), id, "secret.txt")).toBeNull();122 expect(objectBytes(t.mirror(), secret)).toBeNull();123 expect(fileAt(t.mirror(), head(), "src/main.ts")).not.toBeNull();124 });125});126127test("a new save syncs incrementally and a bad format is recorded as the last sync error", async () => {128 const fx = await makeKohBucket("growing");129 const t = await syncTarget(fx);130 await syncAll(t);131 await writeFile(join(fx.repoDir, "new.txt"), "new\n");132 Bun.spawnSync(["koh3", "save", "add new"], {133 cwd: fx.repoDir,134 env: { PATH: process.env.PATH, HOME: join(fx.repoDir, "../../home"), NO_COLOR: "1" },135 });136 await syncAll(t);137 expect(history(t.mirror(), 1, 0)[0]?.message).toBe("add new");138139 await writeFile(join(fx.bucketDir, fx.repo, "format"), "koh-remote 2");140 await syncAll(t);141 const row = t.kepr.query("SELECT last_sync_error FROM repos").get() as {142 last_sync_error: string;143 };144 expect(row.last_sync_error).toContain('remote format "koh-remote 2"');145});146147describe("the mirror's schema version", () => {148 test("a version 1 mirror reopens and any other version is refused as disposable", async () => {149 const dir = await mkdtemp(join(tmpdir(), "kepr-mirror-"));150 const created = openMirror(dir, "one");151 created.run("PRAGMA wal_checkpoint(TRUNCATE)");152 await Bun.write(join(dir, "copy.db"), Bun.file(join(dir, "one.db")));153 expect(openMirror(dir, "copy").query("PRAGMA user_version").get()).toEqual({154 user_version: 1,155 });156157 const future = new Database(join(dir, "future.db"));158 future.run("PRAGMA user_version = 2");159 future.close();160 expect(() => openMirror(dir, "future")).toThrow("disposable");161 });162});