1import { Database } from "bun:sqlite";2import { beforeAll, describe, expect, test } from "bun:test";3import { cp, mkdir, mkdtemp, readFile, writeFile } from "node:fs/promises";4import { tmpdir } from "node:os";5import { join } from "node:path";6import { deflateSync } from "node:zlib";7import { type Bucket, openBucket } from "../src/bucket/reader.ts";8import { readSave } from "../src/bucket/repo.ts";9import { syncAll, syncRepo } from "../src/bucket/sync.ts";10import { manifestTree } from "../src/mirror/manifest.ts";11import {12 fileAt,13 filesAt,14 flagReason,15 headId,16 history,17 objectBytes,18 repoStats,19 saveByPrefix,20 timeline,21} from "../src/mirror/queries.ts";22import { applyHidden, closeMirror, mirrorState, openMirror } from "../src/mirror/store.ts";23import { openKeprDb } from "../src/server/db.ts";24import { Browser, instance } from "./browser.ts";25import { type Fixture, KOH_BIN, makeKohBucket, writesFormat2 } from "./fixture.ts";2627const text = (bytes: Uint8Array | null) => new TextDecoder().decode(bytes ?? new Uint8Array());2829async function syncTarget(fx: Fixture) {30 const dataDir = await mkdtemp(join(tmpdir(), "kepr-data-"));31 const target = {32 bucket: openBucket({ kind: "folder", path: fx.bucketDir }),33 kepr: openKeprDb(dataDir),34 mirrorDir: join(dataDir, "mirror"),35 };36 return { ...target, mirror: () => openMirror(target.mirrorDir, fx.repo) };37}3839describe("a first sync of a koh bucket", () => {40 let fx: Fixture;41 let t: Awaited<ReturnType<typeof syncTarget>>;42 beforeAll(async () => {43 fx = await makeKohBucket();44 t = await syncTarget(fx);45 await syncAll(t);46 });47 const [head, checkpoint, second, first] = [0, 1, 2, 3].map((i) => () => fx.saveIds[i] as string);4849 test("registers the repo private, with a clean last sync", () => {50 const row = t.kepr.query("SELECT public, last_sync_at, last_sync_error FROM repos").get() as {51 public: number;52 last_sync_at: number;53 last_sync_error: string | null;54 };55 expect(row.public).toBe(0);56 expect(row.last_sync_error).toBeNull();57 expect(row.last_sync_at).toBeGreaterThan(0);58 });5960 test("history is newest first and leaves out the checkpoint", () => {61 expect(headId(t.mirror())).toBe(head());62 expect(history(t.mirror(), 10, 0).map((s) => s.id)).toEqual([head(), second(), first()]);63 expect(history(t.mirror(), 1, 1).map((s) => s.message)).toEqual(["add readme and entry point"]);64 expect(timeline(t.mirror()).map((s) => s.id)).toEqual([first(), second(), head()]);65 expect(saveByPrefix(t.mirror(), checkpoint())?.is_checkpoint).toBe(true);66 });6768 test("finds a save by a unique prefix of six or more characters", () => {69 const save = saveByPrefix(t.mirror(), second().slice(0, 6));70 expect([save?.id, save?.agent, save?.session]).toEqual([second(), "test-agent", "fixture"]);71 expect(saveByPrefix(t.mirror(), second().slice(0, 5))).toBeNull();72 expect(saveByPrefix(t.mirror(), "zzzzzz")).toBeNull();73 });7475 test("reads files and their bytes at any save", () => {76 const paths = filesAt(t.mirror(), head()).map((f) => f.path);77 expect(paths).toContain("src/lib/deep/util.ts");78 const now = fileAt(t.mirror(), head(), "src/main.ts");79 const then = fileAt(t.mirror(), second(), "src/main.ts");80 expect(text(objectBytes(t.mirror(), now?.hash as string))).toContain("hello");81 expect(text(objectBytes(t.mirror(), then?.hash as string))).toContain("'hi'");82 expect(fileAt(t.mirror(), first(), "src/main.ts")).toBeNull();83 expect(fileAt(t.mirror(), head(), "docs/logo.png")?.size).toBe(70);84 });8586 test("counts saves without checkpoints, and lines and language at head", () => {87 const stats = repoStats(t.mirror());88 expect(stats.saves).toBe(3);89 expect(stats.language).toBe("TypeScript");90 91 92 expect(stats.lines).toBe(4);93 expect(stats.updated).toBe(saveByPrefix(t.mirror(), head())?.created_at ?? -1);94 });9596 test("stores the flag event", () => {97 const flag = t.mirror().query("SELECT kind, save_id, reason FROM events").get();98 expect(flag).toEqual({ kind: "flag", save_id: first(), reason: "holds a secret" });99 });100101 test("a save's flag state is its newest flag or clear event, by time and then ID", async () => {102 expect(flagReason(t.mirror(), first())).toBe("holds a secret");103 expect(flagReason(t.mirror(), head())).toBeNull();104 const mirror = openMirror(await mkdtemp(join(tmpdir(), "kepr-flags-")), "flags");105 const event = mirror.query(106 "INSERT INTO events (id, kind, save_id, reason, created_at, machine) VALUES (?, ?, 'aaaaaaaaaaaa', ?, ?, 'm')",107 );108 event.run("000000000001", "flag", "first", 10);109 expect(flagReason(mirror, "aaaaaaaaaaaa")).toBe("first");110 event.run("000000000002", "clear", null, 20);111 expect(flagReason(mirror, "aaaaaaaaaaaa")).toBeNull();112 113 event.run("000000000003", "flag", "again", 20);114 expect(flagReason(mirror, "aaaaaaaaaaaa")).toBe("again");115 event.run("000000000000", "clear", null, 20);116 expect(flagReason(mirror, "aaaaaaaaaaaa")).toBe("again");117 });118119 test("a strip reaches the mirror and drops the object", async () => {120 const secret = fileAt(t.mirror(), head(), "secret.txt")?.hash as string;121 expect(objectBytes(t.mirror(), secret)).not.toBeNull();122 await fx.strip("secret.txt");123 await syncAll(t);124 for (const id of fx.saveIds) expect(fileAt(t.mirror(), id, "secret.txt")).toBeNull();125 expect(objectBytes(t.mirror(), secret)).toBeNull();126 expect(fileAt(t.mirror(), head(), "src/main.ts")).not.toBeNull();127 });128});129130test("a hidden path that is then stripped stays gone when it is unhidden", async () => {131 const fx = await makeKohBucket("hidden-strip");132 const t = await syncTarget(fx);133 await syncAll(t);134 const secret = fileAt(t.mirror(), fx.saveIds[0] as string, "secret.txt")?.hash as string;135 t.kepr.query("UPDATE repos SET hidden_paths = 'secret.txt' WHERE name = ?").run(fx.repo);136 await syncAll(t);137 for (const id of fx.saveIds) expect(fileAt(t.mirror(), id, "secret.txt")).toBeNull();138 expect(objectBytes(t.mirror(), secret)).not.toBeNull();139140 await fx.strip("secret.txt");141 await syncAll(t);142 applyHidden(t.mirror(), []);143 for (const id of fx.saveIds) expect(fileAt(t.mirror(), id, "secret.txt")).toBeNull();144 expect(objectBytes(t.mirror(), secret)).toBeNull();145 expect(fileAt(t.mirror(), fx.saveIds[0] as string, "src/main.ts")).not.toBeNull();146});147148test("a whole six-character ID finds its own save, not a longer one it begins", async () => {149 const mirror = openMirror(await mkdtemp(join(tmpdir(), "kepr-mirror-")), "ids");150 const empty = manifestTree([], () => null);151 mirror152 .query("INSERT INTO manifests (hash, body) VALUES (?, ?)")153 .run(empty.root, empty.bodies.get(empty.root) as string);154 const add = mirror.query(155 "INSERT INTO saves (id, parent, manifest, message, created_at, machine) VALUES (?, NULL, ?, ?, 1, 'm')",156 );157 add.run("af96c8", empty.root, "migrated from Koh 2");158 add.run("af96c8123456", empty.root, "made by Koh 3");159 expect(saveByPrefix(mirror, "af96c8")?.message).toBe("migrated from Koh 2");160 expect(saveByPrefix(mirror, "af96c81")?.message).toBe("made by Koh 3");161});162163test("a sync lands history in batches, so one cut short resumes where it stopped", async () => {164 const fx = await makeKohBucket("batched");165 const bucket = openBucket({ kind: "folder", path: fx.bucketDir });166 const mirror = openMirror(await mkdtemp(join(tmpdir(), "kepr-mirror-")), fx.repo);167 168 const failing: Bucket = {169 ...bucket,170 get: (key) =>171 key.includes("/objects/") && mirrorState(mirror, "head") !== null172 ? Promise.reject(new Error("connection reset"))173 : bucket.get(key),174 };175 await expect(syncRepo(failing, mirror, fx.repo, [], 1)).rejects.toThrow("connection reset");176 const first = fx.saveIds[3] as string;177 expect(mirrorState(mirror, "head")).toBe(first);178 expect(history(mirror, 10, 0).map((s) => s.id)).toEqual([first]);179180 await syncRepo(bucket, mirror, fx.repo, [], 1);181 expect(headId(mirror)).toBe(fx.saveIds[0] as string);182 expect(history(mirror, 10, 0)).toHaveLength(3);183 expect(flagReason(mirror, first)).toBe("holds a secret");184});185186test("a save larger than a batch is stored ahead of itself, and a sync cut short within it resumes", async () => {187 const fx = await makeKohBucket("ahead");188 const bucket = openBucket({ kind: "folder", path: fx.bucketDir });189 const mirror = openMirror(await mkdtemp(join(tmpdir(), "kepr-mirror-")), fx.repo);190 191 const first = await readSave(bucket, fx.repo, fx.saveIds.at(-1) as string);192 const firstObjects = new Set(first.files.map((file) => file.hash)).size;193 let objectGets = 0;194 const failing: Bucket = {195 ...bucket,196 get: (key) =>197 key.includes("/objects/") && ++objectGets > firstObjects198 ? Promise.reject(new Error("connection reset"))199 : bucket.get(key),200 };201 await expect(syncRepo(failing, mirror, fx.repo, [], 1)).rejects.toThrow("connection reset");202 const stored = () =>203 mirror.query<{ n: number }, []>("SELECT COUNT(*) AS n FROM objects").get()?.n;204 expect(mirrorState(mirror, "head")).toBeNull();205 expect(stored()).toBe(firstObjects);206207 await syncRepo(bucket, mirror, fx.repo, [], 1);208 expect(headId(mirror)).toBe(fx.saveIds[0] as string);209 expect(history(mirror, 10, 0)).toHaveLength(3);210 const guide = fileAt(mirror, fx.saveIds[0] as string, "docs/guide.md");211 expect(text(objectBytes(mirror, guide?.hash as string))).toBe(212 "# Guide\n\nRead me. It is short.\n",213 );214});215216test("object reads overlap, but never past the bytes allowed in flight", async () => {217 const fx = await makeKohBucket("in-flight");218 const bucket = openBucket({ kind: "folder", path: fx.bucketDir });219 const peak = async (readBytes?: number) => {220 let reading = 0;221 let most = 0;222 const counting: Bucket = {223 ...bucket,224 get: async (key) => {225 if (!key.includes("/objects/")) return bucket.get(key);226 most = Math.max(most, ++reading);227 await Bun.sleep(5);228 reading--;229 return bucket.get(key);230 },231 };232 const mirror = openMirror(await mkdtemp(join(tmpdir(), "kepr-mirror-")), fx.repo);233 await syncRepo(counting, mirror, fx.repo, [], undefined, readBytes);234 expect(headId(mirror)).toBe(fx.saveIds[0] as string);235 return most;236 };237 expect(await peak()).toBeGreaterThan(1);238 239 expect(await peak(1)).toBe(1);240});241242test("a read the gate admits after the batch filled waits for the next batch", async () => {243 const fx = await makeKohBucket("deferred");244 const bucket = openBucket({ kind: "folder", path: fx.bucketDir });245 const mirror = openMirror(await mkdtemp(join(tmpdir(), "kepr-mirror-")), fx.repo);246 const stored = () =>247 mirror.query<{ n: number }, []>("SELECT COUNT(*) AS n FROM objects").get()?.n ?? 0;248 let read = 0;249 const unstored: number[] = [];250 const counting: Bucket = {251 ...bucket,252 get: async (key) => {253 254 if (key.includes("/objects/")) unstored.push(read++ - stored());255 return bucket.get(key);256 },257 };258 await syncRepo(counting, mirror, fx.repo, [], 1, 1);259 expect(read).toBeGreaterThan(2);260 expect(new Set(unstored)).toEqual(new Set([0]));261});262263test("a failed read reports only once every other read has settled", async () => {264 const fx = await makeKohBucket("settled");265 const bucket = openBucket({ kind: "folder", path: fx.bucketDir });266 const mirror = openMirror(await mkdtemp(join(tmpdir(), "kepr-mirror-")), fx.repo);267 let reading = 0;268 let reads = 0;269 const failing: Bucket = {270 ...bucket,271 get: async (key) => {272 if (!key.includes("/objects/")) return bucket.get(key);273 if (reads++ === 0) throw new Error("connection reset");274 reading++;275 await Bun.sleep(30);276 reading--;277 return bucket.get(key);278 },279 };280 await expect(syncRepo(failing, mirror, fx.repo)).rejects.toThrow("connection reset");281 expect(reading).toBe(0);282});283284test("a new save syncs incrementally and a bad format is recorded as the last sync error", async () => {285 const fx = await makeKohBucket("growing");286 const t = await syncTarget(fx);287 await syncAll(t);288 await writeFile(join(fx.repoDir, "new.txt"), "new\n");289 Bun.spawnSync([KOH_BIN, "save", "add new"], {290 cwd: fx.repoDir,291 env: { PATH: process.env.PATH, HOME: join(fx.repoDir, "../../home"), NO_COLOR: "1" },292 });293 await syncAll(t);294 expect(history(t.mirror(), 1, 0)[0]?.message).toBe("add new");295296 await writeFile(join(fx.bucketDir, fx.repo, "format"), "koh-remote 3");297 298 299 await writeFile(join(fx.bucketDir, fx.repo, "head"), fx.saveIds[1] as string);300 await syncAll(t);301 const row = t.kepr.query("SELECT last_sync_error FROM repos").get() as {302 last_sync_error: string;303 };304 expect(row.last_sync_error).toContain('remote format "koh-remote 3"');305});306307test("a whole-history strip reaches every save, those arriving after it too, whatever their time (§10.2)", async () => {308 const fx = await makeKohBucket("late");309 const view = await mkdtemp(join(tmpdir(), "kepr-view-"));310 const viewRepo = join(view, fx.repo);311 await cp(join(fx.bucketDir, fx.repo), viewRepo, { recursive: true });312 313 314 await mkdir(join(viewRepo, "events"), { recursive: true });315 await writeFile(316 join(viewRepo, "events", "0000000000bb"),317 JSON.stringify({318 id: "0000000000bb",319 kind: "strip",320 save_id: "",321 path: "secret.txt",322 reason: "a secret got saved",323 created_at: 1,324 machine: "elsewhere",325 }),326 );327 const oldest = fx.saveIds.at(-1) as string;328 const newest = fx.saveIds[0] as string;329 330 await writeFile(join(viewRepo, "head"), oldest);331 const t = await syncTarget({ ...fx, bucketDir: view });332 await syncAll(t);333 expect(fileAt(t.mirror(), oldest, "secret.txt")).toBeNull();334 335 await writeFile(join(viewRepo, "head"), newest);336 await syncAll(t);337 expect(headId(t.mirror())).toBe(newest);338 for (const id of fx.saveIds) expect(fileAt(t.mirror(), id, "secret.txt")).toBeNull();339 expect(fileAt(t.mirror(), newest, "src/main.ts")).not.toBeNull();340});341342describe("the mirror's schema version", () => {343 test("a current mirror reopens, and one of another schema is rebuilt empty", async () => {344 const dir = await mkdtemp(join(tmpdir(), "kepr-mirror-"));345 const created = openMirror(dir, "one");346 created.run("PRAGMA wal_checkpoint(TRUNCATE)");347 await Bun.write(join(dir, "copy.db"), Bun.file(join(dir, "one.db")));348 expect(openMirror(dir, "copy").query("PRAGMA user_version").get()).toEqual({349 user_version: 5,350 });351352 353 354 for (const version of [1, 4, 6]) {355 const older = new Database(join(dir, `v${version}.db`));356 older.run("CREATE TABLE stale (x)");357 older.run(`PRAGMA user_version = ${version}`);358 older.close();359 const db = openMirror(dir, `v${version}`);360 expect(db.query("PRAGMA user_version").get()).toEqual({ user_version: 5 });361 expect(db.query("SELECT 1 FROM sqlite_schema WHERE name = 'stale'").get()).toBeNull();362 expect(mirrorState(db, "head")).toBeNull();363 expect(mirrorState(db, "epoch")).not.toBeNull();364 }365 });366367 test("an old schema is emptied even when it holds history", async () => {368 const fx = await makeKohBucket("rebuild");369 const t = await syncTarget(fx);370 await syncAll(t);371 expect(history(t.mirror(), 10, 0).length).toBe(3);372 373 t.mirror().run("PRAGMA user_version = 4");374 closeMirror(t.mirrorDir, fx.repo);375 const rebuilt = openMirror(t.mirrorDir, fx.repo);376 expect(history(rebuilt, 10, 0)).toEqual([]);377 expect(mirrorState(rebuilt, "head")).toBeNull();378 379 await syncAll(t);380 expect(headId(t.mirror())).toBe(fx.saveIds[0] as string);381 expect(history(t.mirror(), 10, 0)).toHaveLength(3);382 });383384 test("touches and facts recorded save by save match a mirror synced in one go", async () => {385 const fx = await makeKohBucket("stepwise");386 const t = await syncTarget(fx);387 await syncAll(t);388 await writeFile(join(fx.repoDir, "src/main.ts"), "// Entry point.\nconsole.log('again');\n");389 await writeFile(join(fx.repoDir, "added.txt"), "new\n");390 Bun.spawnSync([KOH_BIN, "save", "change main, add a file"], {391 cwd: fx.repoDir,392 env: { PATH: process.env.PATH, HOME: join(fx.repoDir, "../../home"), NO_COLOR: "1" },393 });394 Bun.spawnSync([KOH_BIN, "offer"], {395 cwd: fx.repoDir,396 env: { PATH: process.env.PATH, HOME: join(fx.repoDir, "../../home"), NO_COLOR: "1" },397 });398 await syncAll(t);399400 401 const whole = openMirror(await mkdtemp(join(tmpdir(), "kepr-mirror-")), fx.repo);402 await syncRepo(openBucket({ kind: "folder", path: fx.bucketDir }), whole, fx.repo);403 const derived = (db: Database) => [404 db.query("SELECT path, n FROM touches ORDER BY n, path").all(),405 db.query("SELECT * FROM facts ORDER BY path, hash").all(),406 db.query("SELECT hash FROM known_objects ORDER BY hash").all(),407 ];408 const incremental = derived(t.mirror());409 expect(incremental[0]).toContainEqual(expect.objectContaining({ path: "added.txt" }));410 expect(incremental).toEqual(derived(whole));411 });412413 test("a recount cut short is done when the mirror next opens", async () => {414 const fx = await makeKohBucket("recount");415 const t = await syncTarget(fx);416 await syncAll(t);417 const counted = repoStats(t.mirror()).lines;418 expect(counted).toBeGreaterThan(0);419 420 t.mirror().query("INSERT OR REPLACE INTO state (key, value) VALUES ('lines', '0')").run();421 t.mirror().run("DELETE FROM state WHERE key = 'stats_rule'");422 closeMirror(t.mirrorDir, fx.repo);423 expect(repoStats(t.mirror()).lines).toBe(counted);424 });425});426427428429const KOH_V2 = process.env.KOH_BIN ?? join(import.meta.dir, "..", "..", "koh", "build", "koh3");430const FORMAT_2 = await writesFormat2(KOH_V2);431if (!FORMAT_2) {432 console.warn(433 `format-2 sync tests skipped: ${KOH_V2} is absent or writes koh-remote 1 — ` +434 "set KOH_BIN to a format-2 koh (../koh/build/koh3)",435 );436}437438describe.serial("a format-2 repo", () => {439 test.skipIf(!FORMAT_2)(440 "syncs its manifest trees and serves every page",441 async () => {442 const fx = await makeKohBucket("trees", { format: 2, bin: KOH_V2 });443 expect(fx.format).toBe(2);444 const inst = await instance(fx.bucketDir);445 inst.kepr.run("UPDATE repos SET public = 1");446 const mirror = openMirror(join(inst.dataDir, "mirror"), fx.repo);447 const head = fx.saveIds[0] as string;448449 450 451 const tracked = [...new Bun.Glob("**/*").scanSync({ cwd: fx.repoDir }), ".kohignore"].filter(452 (path) => path !== "LOG.md" && !/^\.koh($|-|\/)/.test(path),453 );454 const paths = filesAt(mirror, head).map((file) => file.path);455 expect(new Set(paths)).toEqual(new Set(tracked));456 expect(paths).toContain("src/main.ts");457 expect(paths).toContain("secret.txt");458459 460 const missing = mirror461 .query<{ n: number }, []>(462 `SELECT COUNT(*) AS n FROM saves s463 WHERE s.manifest = '' OR NOT EXISTS (SELECT 1 FROM manifests m WHERE m.hash = s.manifest)`,464 )465 .get();466 expect(missing).toEqual({ n: 0 });467 const page = await (await inst.app.request(`/${fx.repo}`)).text();468 expect(page).toContain('data-path="src/main.ts"');469 expect(page).not.toContain('data-path=".koh"');470 expect(await (await inst.app.request(`/${fx.repo}/files/src/main.ts`)).text()).toContain(471 "hello",472 );473 const served = (await (await inst.app.request(`/${fx.repo}/koh/saves/${head}`)).json()) as {474 files: { path: string }[];475 };476 expect(served.files.map((file) => file.path)).toEqual(paths);477478 479 let reads = 0;480 const bucket = openBucket({ kind: "folder", path: fx.bucketDir });481 const counting: Bucket = {482 ...bucket,483 get: (key) => {484 if (key.includes("/objects/") || key.includes("/manifests/")) reads++;485 return bucket.get(key);486 },487 };488 await syncRepo(counting, mirror, fx.repo);489 expect(reads).toBe(0);490491 492 const trees = mirror.query("SELECT hash, body FROM manifests ORDER BY hash").all();493 await fx.strip("secret.txt");494 await syncRepo(bucket, mirror, fx.repo);495 expect(fileAt(mirror, head, "secret.txt")).toBeNull();496 expect(filesAt(mirror, head).map((file) => file.path)).toContain("src/main.ts");497 expect(mirror.query("SELECT hash, body FROM manifests ORDER BY hash").all()).toEqual(trees);498 const stripped = await (await inst.app.request(`/${fx.repo}`)).text();499 expect(stripped).not.toContain("secret.txt");500 },501 20_000,502 );503});504505test("a strip that arrives older than the saves already mirrored still strips them (§10.2, R6)", async () => {506 const fx = await makeKohBucket("older-strip");507 const t = await syncTarget(fx);508 await syncAll(t);509 510 for (const id of fx.saveIds) expect(fileAt(t.mirror(), id, "secret.txt")).not.toBeNull();511512 513 514 515 const events = join(fx.bucketDir, fx.repo, "events");516 await mkdir(events, { recursive: true });517 await writeFile(518 join(events, "0000000000aa"),519 JSON.stringify({520 id: "0000000000aa",521 kind: "strip",522 save_id: "",523 path: "secret.txt",524 reason: "a secret got saved",525 created_at: 1,526 machine: "elsewhere",527 }),528 );529 await syncAll(t);530531 for (const id of fx.saveIds) expect(fileAt(t.mirror(), id, "secret.txt")).toBeNull();532 expect(fileAt(t.mirror(), fx.saveIds[0] as string, "src/main.ts")).not.toBeNull();533});534535test("a save with an unsafe path lands without it, keeps syncing, and the admin status names it (A3)", async () => {536 const fx = await makeKohBucket("quarantine");537 const head = fx.saveIds[0] as string;538 const key = join(fx.bucketDir, fx.repo, "saves", head);539 const record = JSON.parse(await readFile(key, "utf8"));540 record.files.push({ ...record.files[0], path: "Icon\r" });541 await writeFile(key, JSON.stringify(record));542 const inst = await instance(fx.bucketDir);543 const mirror = openMirror(join(inst.dataDir, "mirror"), fx.repo);544 expect(inst.kepr.query("SELECT last_sync_error FROM repos").get()).toEqual({545 last_sync_error: null,546 });547 expect(filesAt(mirror, head).map((file) => file.path)).toContain("README.md");548 expect(filesAt(mirror, head).map((file) => file.path)).not.toContain("Icon\r");549550 await writeFile(join(fx.repoDir, "later.txt"), "later\n");551 const env = { PATH: process.env.PATH, HOME: join(fx.repoDir, "../../home"), NO_COLOR: "1" };552 Bun.spawnSync([KOH_BIN, "save", "a later save"], { cwd: fx.repoDir, env });553 Bun.spawnSync([KOH_BIN, "offer"], { cwd: fx.repoDir, env });554 await syncAll({555 bucket: openBucket({ kind: "folder", path: fx.bucketDir }),556 kepr: inst.kepr,557 mirrorDir: join(inst.dataDir, "mirror"),558 });559 expect(history(mirror, 1, 0)[0]?.message).toBe("a later save");560561 const browser = new Browser(inst.app);562 await browser.signIn();563 const page = await (await browser.get("/admin/repos")).text();564 expect(page).toContain("1 path quarantined: Icon\\x0d");565});566567test("a strip event with an illegal path is ignored, as Koh ignores it (§5.5)", async () => {568 const fx = await makeKohBucket("illegal-strip");569 for (const [id, path] of [570 ["aaaaaaaaaaaa", "src//"],571 ["bbbbbbbbbbbb", ""],572 ["cccccccccccc", "src\ud800"],573 ]) {574 const event = { id, kind: "strip", save_id: "", path, reason: "", created_at: 1, machine: "x" };575 await writeFile(join(fx.bucketDir, fx.repo, "events", id as string), JSON.stringify(event));576 }577 const t = await syncTarget(fx);578 await syncAll(t);579 expect(t.kepr.query("SELECT last_sync_error FROM repos").get()).toEqual({580 last_sync_error: null,581 });582 expect(filesAt(t.mirror(), fx.saveIds[0] as string).map((file) => file.path)).toContain(583 "src/main.ts",584 );585});586587test("an object that inflates past 512 MiB is quarantined without stopping the sync (A3)", async () => {588 const fx = await makeKohBucket("oversized");589 const head = fx.saveIds[0] as string;590 const key = join(fx.bucketDir, fx.repo, "saves", head);591 const record = JSON.parse(await readFile(key, "utf8"));592 const hash = "ab".repeat(32);593 record.files.push({ path: "huge.bin", hash, executable: false });594 await writeFile(key, JSON.stringify(record));595 await writeFile(596 join(fx.bucketDir, fx.repo, "objects", hash),597 deflateSync(new Uint8Array(512 * 1024 * 1024 + 1)),598 );599 const t = await syncTarget(fx);600 await syncAll(t);601 expect(t.kepr.query("SELECT last_sync_error FROM repos").get()).toEqual({602 last_sync_error: null,603 });604 expect(filesAt(t.mirror(), head).map((file) => file.path)).not.toContain("huge.bin");605 expect(JSON.parse(mirrorState(t.mirror(), "quarantined") ?? "[]")).toEqual(["huge.bin"]);606});607608test("the line count and the Atlas's facts skip a file over 8 MiB (A3)", async () => {609 const fx = await makeKohBucket("large-text");610 const t = await syncTarget(fx);611 await syncAll(t);612 const before = repoStats(t.mirror()).lines;613 await writeFile(join(fx.repoDir, "big.txt"), "x\n".repeat(4.5 * 1024 * 1024));614 const env = { PATH: process.env.PATH, HOME: join(fx.repoDir, "../../home"), NO_COLOR: "1" };615 Bun.spawnSync([KOH_BIN, "save", "add a big text file"], { cwd: fx.repoDir, env });616 Bun.spawnSync([KOH_BIN, "offer"], { cwd: fx.repoDir, env });617 await syncAll(t);618 expect(history(t.mirror(), 1, 0)[0]?.message).toBe("add a big text file");619 expect(repoStats(t.mirror()).lines).toBe(before);620 expect(621 t.mirror().query("SELECT lines, description FROM facts WHERE path = 'big.txt'").get(),622 ).toEqual({ lines: null, description: null });623});