28ac0b3567c7
store per-folder manifests and derive file lists in the mirror (v3.2.8)
- time
- 2026-11-17 01:46 UTC · 1 week ago
- machine
- Junes-MacBook-Pro.local
- agent
- deepseek/deepseek-flash
- session
- review findings
- parent
- 2ca58cd86939
↓ kepr-28ac0b35.tar.gzatlas at this save
files changed20 files
package.json+1 −1public/js/kepr.js+28 −10scripts/budget.ts+4 −4src/bucket/reader.ts+47 −0src/bucket/repo.ts+20 −3src/bucket/sync.ts+57 −0src/mirror/manifest.ts+220 −0src/mirror/queries.ts+130 −32src/mirror/remote.ts+19 −21src/mirror/store.ts+222 −261src/pages/atlas.ts+4 −26src/releases/releases.ts+35 −11tests/bucket.test.ts+20 −2tests/console.test.ts+47 −0tests/fixture.ts+56 −9tests/hidden.test.ts+5 −6tests/kohpaths.test.ts+48 −7tests/pages.test.ts+4 −4tests/sync.test.ts+141 −76tests/tarball.test.ts+3 −3package.json+1 −1
@@ -1,6 +1,6 @@11 {22 "name": "kepr",3- "version": "3.2.7",3+ "version": "3.2.8",44 "private": true,55 "type": "module",66 "scripts": {public/js/kepr.js+28 −10
@@ -77,21 +77,28 @@7777 strip = Math.max(x + spacing(Number.POSITIVE_INFINITY), width);7878 offset = x - width * 0.82;7979 };80- // Every visible copy of each x on the looping strip.81- const onScreen = (x, margin) => {82- const shift = ((offset % strip) + strip) % strip;83- const copies = [];84- for (let sx = x - shift - strip; sx < width + margin; sx += strip) {85- if (sx > -margin) copies.push(sx);80+ // The strip's shift this frame, and the first save at or past an x (x is sorted, see resize).81+ const shifted = () => ((offset % strip) + strip) % strip;82+ const firstAt = (x) => {83+ let [lo, hi] = [0, saves.length];84+ while (lo < hi) {85+ const mid = (lo + hi) >>> 1;86+ if (saves[mid].x <= x) lo = mid + 1;87+ else hi = mid;8688 }87- return copies;89+ return lo;8890 };8991 const hit = (event) => {9092 const box = canvas.getBoundingClientRect();9193 const [mx, my] = [event.clientX - box.left, event.clientY - box.top];9294 if (Math.abs(my - height / 2) > radius + 7) return null;95+ const shift = shifted();9396 return (94- saves.find((save) => onScreen(save.x, 0).some((x) => Math.abs(mx - x) < radius + 7)) ?? null97+ saves.find((save) => {98+ for (let sx = save.x - shift - strip; sx < width; sx += strip)99+ if (sx > 0 && Math.abs(mx - sx) < radius + 7) return true;100+ return false;101+ }) ?? null95102 );96103 };97104 let [hovered, drag, dragFrom, downX, lastX, velocity, resumeAt, lastFrame] = [@@ -144,8 +151,19 @@144151 ctx.setLineDash([]);145152 ctx.font = '10px "Martian Mono", monospace';146153 ctx.textAlign = "center";147- for (const save of saves) {148- for (const x of onScreen(save.x, 10)) {154+ const shift = shifted();155+ const margin = 10;156+ const last = saves[saves.length - 1].x;157+ // Saves are sorted by x, so only the copies inside the canvas' windows need visiting: one158+ // stripe per k, each holding the copies of a contiguous run of saves.159+ for (let k = Math.floor((-shift - width - margin) / strip); ; k++) {160+ const base = shift + k * strip;161+ if (base - margin > last) break;162+ const end = base + width + margin;163+ if (end <= 0) continue;164+ for (let i = firstAt(base - margin); i < saves.length && saves[i].x < end; i++) {165+ const save = saves[i];166+ const x = save.x - base;149167 ctx.globalAlpha = hovered === null ? save.alpha : hovered === save ? 1 : save.alpha * 0.6;150168 ctx.fillStyle = save.fill;151169 ctx.beginPath();scripts/budget.ts+4 −4
@@ -4,11 +4,11 @@44 55 // Prefixes are matched in order, so the specific files come before the directories.66 const TS_AREAS: [string, string[], number][] = [7- ["bucket", ["src/bucket/"], 1250],8- ["mirror", ["src/mirror/"], 1100],7+ ["bucket", ["src/bucket/"], 1380],8+ ["mirror", ["src/mirror/"], 1390],99 ["describe", ["src/describe/"], 530],10- ["pages", ["src/pages/"], 2565],11- ["releases", ["src/releases/"], 900],10+ ["pages", ["src/pages/"], 2540],11+ ["releases", ["src/releases/"], 800],1212 ["tarball", ["src/tarball/"], 300],1313 ["issues", ["src/issues/"], 1700],1414 ["admin", ["src/admin/"], 2800],src/bucket/reader.ts+47 −0
@@ -13,6 +13,8 @@1313 */1414 export type Bucket = {1515 get(key: string): Promise<Uint8Array | null>;16+ /** The tag naming the version of `key` stored now, as `If-Match` wants it; null when absent. */17+ tag(key: string): Promise<string | null>;1618 list(prefix: string): Promise<string[]>;1719 /** The top-level folders' names: one listing, however many keys they hold. */1820 folders(): Promise<string[]>;@@ -29,6 +31,12 @@2931 * one of its files is deleted; any other key is refused.3032 */3133 put(key: string, bytes: Uint8Array, type: string): Promise<void>;34+ /**35+ * Writes one of the keys `put` writes only while it still holds the version `tag` names, since a36+ * Koh publish can land at any moment (2026-11-16). False means another writer got there first and37+ * its value stands.38+ */39+ putIfTag(key: string, bytes: Uint8Array, type: string, tag: string): Promise<boolean>;3240 /** Deletes one of Kepr's own files, a release's file or `releases/latest`; nothing else. */3341 remove(key: string): Promise<void>;3442 /** Copies a key of one repo to another repo: a rename (June, 2026-10-01), and nothing else. */@@ -173,6 +181,15 @@173181 if (!response.ok) throw new Error(`S3 GET ${key} failed: HTTP ${response.status}`);174182 return new Uint8Array(await response.arrayBuffer());175183 },184+ async tag(key) {185+ // HEAD, not stat: a missing key is a 404 to check for, not an error Bun's reader types.186+ const response = await fetch(client.presign(key, { method: "HEAD", expiresIn: 60 }));187+ if (response.status === 404) return null;188+ if (!response.ok) throw new Error(`S3 HEAD ${key} failed: HTTP ${response.status}`);189+ const tag = response.headers.get("etag");190+ if (tag === null) throw new Error(`S3 HEAD ${key} named no version`);191+ return tag;192+ },176193 async list(prefix) {177194 const keys: string[] = [];178195 let continuationToken: string | undefined;@@ -220,6 +237,23 @@220237 requireWritable(key, RELEASE_WRITE);221238 await write(key, (file) => file.write(bytes, { type }));222239 },240+ async putIfTag(key, bytes, type, tag) {241+ requireWritable(key, RELEASE_WRITE);242+ // A presigned PUT signs the host alone, so `If-Match` is the bucket's own condition: 412 is243+ // another writer's value standing, and an S3 that can't do conditional writes refuses loudly.244+ const url = client.presign(key, { method: "PUT", expiresIn: 60 });245+ const response = await fetch(url, {246+ method: "PUT",247+ headers: { "If-Match": tag, "Content-Type": type },248+ body: bytes,249+ }).catch((error: unknown) => {250+ throw new BucketWriteError(`The bucket refused ${key}: ${error}`);251+ });252+ if (response.status === 412) return false;253+ if (!response.ok)254+ throw new BucketWriteError(`The bucket refused ${key}: HTTP ${response.status}`);255+ return true;256+ },223257 async remove(key) {224258 requireWritable(key, RELEASE_FILE);225259 await write(key, (file) => file.delete());@@ -262,6 +296,11 @@262296 const file = Bun.file(join(root, key));263297 return (await file.exists()) ? await file.bytes() : null;264298 },299+ async tag(key) {300+ const bytes = await this.get(key);301+ // A folder has no ETag: the hash of the content names the version it holds.302+ return bytes === null ? null : String(Bun.hash(bytes));303+ },265304 list,266305 async size(key) {267306 if (key.split("/").includes("..")) throw new Error(`bucket key escapes the folder: ${key}`);@@ -286,6 +325,14 @@286325 async put(key, bytes) {287326 requireWritable(key, RELEASE_WRITE);288327 await Bun.write(join(root, key), bytes);328+ },329+ async putIfTag(key, bytes, _type, tag) {330+ requireWritable(key, RELEASE_WRITE);331+ // ponytail: a folder has no atomic compare-and-write, so a local Koh can still land in the332+ // gap; the S3 reader is the one the race is about, and tests here are single-writer.333+ if ((await this.tag(key)) !== tag) return false;334+ await Bun.write(join(root, key), bytes);335+ return true;289336 },290337 async remove(key) {291338 requireWritable(key, RELEASE_FILE);src/bucket/repo.ts+20 −3
@@ -18,6 +18,8 @@1818 session: string;1919 restores: string;2020 replayed_from: string;21+ /** Root manifest of a format-2 record; absent on a version-1 record, whose `files` it replaces. */22+ manifest?: string;2123 files: SaveFile[];2224 };2325 @@ -126,13 +128,13 @@126128 if (!SAVE_ID.test(id)) throw new BucketError(`not a save ID: "${id}"`);127129 }128130 129-/** Applies §9.2's format rule: a missing key is version 1; anything but `koh-remote 1` is refused. */131+/** Applies §9.2's format rule: a missing key is version 1; a version Kepr doesn't read is refused. */130132 export async function checkFormat(bucket: Bucket, repo: string): Promise<void> {131133 requireRepo(repo);132134 const bytes = await bucket.get(`${repo}/format`);133135 if (bytes === null) return;134136 const format = decoder.decode(bytes).trim();135- if (format !== "koh-remote 1") {137+ if (format !== "koh-remote 1" && format !== "koh-remote 2") {136138 throw new BucketError(`${repo} uses remote format "${format}"; update Kepr to read it`);137139 }138140 }@@ -167,6 +169,18 @@167169 };168170 }169171 172+/** One folder body from a format-2 repo, checked against its key as steal checks it (§9.4). */173+export async function readManifest(bucket: Bucket, repo: string, hash: string): Promise<string> {174+ requireRepo(repo);175+ if (!HEX64.test(hash)) throw new BucketError(`not a manifest hash: "${hash}"`);176+ const bytes = await bucket.get(`${repo}/manifests/${hash}`);177+ if (bytes === null) throw new BucketError(`${repo}/manifests/${hash} is missing`);178+ if (bytesToHex(blake3(bytes)) !== hash) {179+ throw new BucketError(`${repo}/manifests/${hash} does not match its hash`);180+ }181+ return decoder.decode(bytes);182+}183+170184 /**171185 * A record's text, read as Koh reads it (\u00A75.5): an unpaired surrogate escape stands for its three172186 * bytes, and each byte outside a valid UTF-8 sequence becomes the lone surrogate U+DC00 + byte, so@@ -360,7 +374,10 @@360374 typeof r.is_checkpoint === "boolean" &&361375 Array.isArray(r.files) &&362376 r.files.every(isSaveFile) &&363- new Set(r.files.map((file) => file.path)).size === r.files.length;377+ new Set(r.files.map((file) => file.path)).size === r.files.length &&378+ // A format-2 record names its root manifest in place of a file list; one that names an379+ // invalid hash is refused, as Koh's steal refuses it (§9.2).380+ (r.manifest === undefined || (typeof r.manifest === "string" && HEX64.test(r.manifest)));364381 if (!valid) throw new BucketError("save record does not match the Koh 3 schema");365382 return value as SaveRecord;366383 }src/bucket/sync.ts+57 −0
@@ -1,7 +1,9 @@11 import type { Database } from "bun:sqlite";2+import { flattenTree, manifestBody, parseManifest } from "../mirror/manifest.ts";23 import {34 applyHidden,45 knownEventIds,6+ knownManifest,57 knownObject,68 knownReleases,79 knownSave,@@ -43,10 +45,12 @@4345 type ReleaseRecord,4446 readEvent,4547 readHead,48+ readManifest,4649 readObject,4750 readRelease,4851 readReleasesLatest,4952 readSave,53+ type SaveFile,5054 type SaveRecord,5155 } from "./repo.ts";5256 @@ -292,6 +296,7 @@292296 // resumes from the last batch.293297 let saves: SaveRecord[] = [];294298 let objects = new Map<string, StoredObject>();299+ let manifests = new Map<string, string>();295300 let quarantined: string[] = [];296301 let fetched = 0;297302 const oversized = new Set<string>();@@ -300,6 +305,7 @@300305 head: batchHead,301306 releasesLatest: mirrorState(mirror, "releases_latest") ?? "",302307 saves,308+ manifests,303309 objects,304310 events: [],305311 releases: [],@@ -307,6 +313,7 @@307313 });308314 saves = [];309315 objects = new Map();316+ manifests = new Map();310317 quarantined = [];311318 fetched = 0;312319 };@@ -333,6 +340,48 @@333340 }334341 };335342 const ids = [...unknown].reverse();343+ // A format-2 save names its root manifest instead of a file list: fetch the folders the mirror344+ // lacks, checking every body against its key (§9.4), and flatten the tree to the files the345+ // landing stores and counts. A manifest the mirror holds means its whole tree is held too.346+ const treeOf = async (save: SaveRecord): Promise<SaveFile[]> => {347+ if (save.manifest === undefined) return save.files;348+ const bodies = new Map<string, string>();349+ let pending = [save.manifest];350+ while (pending.length > 0) {351+ const wanted = pending.filter(352+ (hash) => !bodies.has(hash) && !manifests.has(hash) && !knownManifest(mirror, hash),353+ );354+ pending = [];355+ if (wanted.length === 0) break;356+ const read = await inTurn(wanted, READS_AT_ONCE, async (hash) => {357+ try {358+ const body = await readManifest(bucket, repo, hash);359+ return { hash, body, entries: parseManifest(body) };360+ } catch (cause) {361+ const reason = cause instanceof Error ? cause.message : String(cause);362+ throw new BucketError(363+ `${repo}: save ${save.id} names manifest ${hash}, which cannot be read: ${reason}`,364+ );365+ }366+ });367+ for (const { hash, body, entries } of read) {368+ bodies.set(hash, body);369+ for (const entry of entries) if (entry.kind === "folder") pending.push(entry.manifest);370+ }371+ }372+ const files = flattenTree((hash) => {373+ const body = bodies.get(hash) ?? manifests.get(hash) ?? manifestBody(mirror, hash);374+ if (body === null) {375+ throw new BucketError(`${repo}: save ${save.id} names manifest ${hash}, which is missing`);376+ }377+ return body;378+ }, save.manifest);379+ for (const [hash, body] of bodies) {380+ manifests.set(hash, body);381+ fetched += body.length;382+ }383+ return files;384+ };336385 for (let start = 0; start < ids.length; start += READS_AT_ONCE) {337386 const records = await inTurn(ids.slice(start, start + READS_AT_ONCE), READS_AT_ONCE, (id) => {338387 const read = walked.get(id);@@ -342,6 +391,13 @@342391 });343392 for (const save of records) {344393 quarantined.push(...save.quarantined);394+ if (save.manifest !== undefined) {395+ const files = await treeOf(save);396+ quarantined.push(397+ ...files.filter((file) => !isSafePath(file.path)).map((file) => escapePath(file.path)),398+ );399+ save.files = files.filter((file) => isSafePath(file.path));400+ }345401 // One save can hold more than a batch, as a first import does: its objects are stored346402 // ahead of it, after the saves before it have landed, so no landing's cleanup sees them347403 // unreferenced.@@ -397,6 +453,7 @@397453 head,398454 releasesLatest,399455 saves,456+ manifests,400457 objects,401458 events,402459 releases,src/mirror/manifest.ts+220 −0
@@ -0,0 +1,220 @@1+import type { Database } from "bun:sqlite";2+import { blake3 } from "@noble/hashes/blake3.js";3+import { bytesToHex } from "@noble/hashes/utils.js";4+import { isSafePath } from "../bucket/repo.ts";5+import type { FileEntry } from "./queries.ts";6+7+/** One immediate entry of a folder manifest (§5.1). Field order is the encoding, so it is the schema. */8+export type ManifestEntry = {9+ name: string;10+ kind: "file" | "folder";11+ hash: string;12+ size: number;13+ executable: boolean;14+ manifest: string;15+};16+17+const HEX64 = /^[0-9a-f]{64}$/;18+const encoder = new TextEncoder();19+20+export function hashBody(body: string): string {21+ return bytesToHex(blake3(encoder.encode(body)));22+}23+24+/** A manifest body, refusing a shape no reader could walk. Names are not checked, as in Koh. */25+export function parseManifest(body: string): ManifestEntry[] {26+ const value = JSON.parse(body) as { entries?: unknown };27+ if (typeof value !== "object" || value === null || !Array.isArray(value.entries)) {28+ throw new Error("it has no entries");29+ }30+ const entries: ManifestEntry[] = [];31+ for (const raw of value.entries) {32+ const e = raw as Record<string, unknown>;33+ if (typeof raw !== "object" || raw === null || typeof e.name !== "string" || e.name === "") {34+ throw new Error("it has an entry with no name");35+ }36+ if (e.kind === "file") {37+ if (typeof e.hash !== "string" || !HEX64.test(e.hash)) {38+ throw new Error(`its entry ${e.name} has an invalid object hash`);39+ }40+ if (!Number.isSafeInteger(e.size) || (e.size as number) < 0) {41+ throw new Error(`its entry ${e.name} has an invalid size`);42+ }43+ if (typeof e.executable !== "boolean") {44+ throw new Error(`its entry ${e.name} has no executable bit`);45+ }46+ entries.push({47+ name: e.name,48+ kind: "file",49+ hash: e.hash,50+ size: e.size as number,51+ executable: e.executable,52+ manifest: "",53+ });54+ } else if (e.kind === "folder") {55+ if (typeof e.manifest !== "string" || !HEX64.test(e.manifest)) {56+ throw new Error(`its entry ${e.name} has an invalid manifest hash`);57+ }58+ entries.push({59+ name: e.name,60+ kind: "folder",61+ hash: "",62+ size: 0,63+ executable: false,64+ manifest: e.manifest,65+ });66+ } else {67+ throw new Error(`its entry ${e.name} has an unknown kind`);68+ }69+ }70+ return entries;71+}72+73+/** Every file under a manifest, path-joined and sorted as SQLite's BINARY collation sorts paths. */74+export function flattenTree(read: (hash: string) => string, root: string): FileEntry[] {75+ const files: FileEntry[] = [];76+ walk(read, root, "", files, []);77+ return files.sort((a, b) => byPath(a.path, b.path));78+}79+80+function walk(81+ read: (hash: string) => string,82+ hash: string,83+ prefix: string,84+ out: FileEntry[],85+ ancestors: string[],86+): void {87+ if (ancestors.includes(hash)) throw new Error(`manifest ${hash} refers to itself`);88+ const deeper = [...ancestors, hash];89+ for (const entry of parseManifest(read(hash))) {90+ if (entry.kind === "file") {91+ out.push({92+ path: prefix + entry.name,93+ hash: entry.hash,94+ executable: entry.executable,95+ size: entry.size,96+ });97+ } else {98+ walk(read, entry.manifest, `${prefix}${entry.name}/`, out, deeper);99+ }100+ }101+}102+103+// Comparing code points is comparing UTF-8 bytes, which is what `ORDER BY path` did.104+function byPath(a: string, b: string): number {105+ for (let i = 0, j = 0; i < a.length && j < b.length; ) {106+ const x = a.codePointAt(i) as number;107+ const y = b.codePointAt(j) as number;108+ if (x !== y) return x - y;109+ i += x > 0xffff ? 2 : 1;110+ j += y > 0xffff ? 2 : 1;111+ }112+ return a.length - b.length;113+}114+115+/** A stored manifest body, or null when the mirror lacks it. */116+export function manifestBody(db: Database, hash: string): string | null {117+ return (118+ db.query<{ body: string }, [string]>("SELECT body FROM manifests WHERE hash = ?").get(hash)119+ ?.body ?? null120+ );121+}122+123+// A manifest never changes once stored, so a flattened tree can be kept for the whole process.124+// A damaged tree is refused rather than cached: the mirror is disposable, and the next sync's125+// landing is what rewrites it.126+const flat = new Map<string, FileEntry[]>();127+let flatEntries = 0;128+const MAX_FLAT = 50_000;129+130+/**131+ * The files under a stored manifest, cached by hash. An illegal path (§5.5) is never handed out:132+ * the body is kept verbatim, but no page, tarball or object listing may see the name.133+ */134+export function flattenManifest(db: Database, root: string): FileEntry[] {135+ const cached = flat.get(root);136+ if (cached) return cached;137+ const files = flattenTree((hash) => {138+ const body = manifestBody(db, hash);139+ if (body === null) throw new Error(`manifest ${hash} is missing from the mirror`);140+ return body;141+ }, root).filter((file) => isSafePath(file.path));142+ if (flatEntries + files.length > MAX_FLAT) {143+ flat.clear();144+ flatEntries = 0;145+ }146+ flat.set(root, files);147+ flatEntries += files.length;148+ return files;149+}150+151+type Trie = {152+ files: Map<string, { hash: string; executable: boolean }>;153+ folders: Map<string, Trie>;154+};155+156+/**157+ * Builds the folder manifests of a version-1 file list once, writing §5.1's canonical body, and158+ * returns the root hash with every body. The mirror's hashes need not equal Koh's: the list only159+ * has to land once, and identical lists must share a row.160+ */161+export function manifestTree(162+ files: { path: string; hash: string; executable: boolean }[],163+ sizeOf: (hash: string) => number | null,164+): { root: string; bodies: Map<string, string> } {165+ const top: Trie = { files: new Map(), folders: new Map() };166+ for (const file of files) {167+ const size = sizeOf(file.hash);168+ // The object is stored before the save; one that is not cannot be opened, described or169+ // tarred, so it is left out as an oversized object is.170+ if (size === null) continue;171+ const parts = file.path.split("/");172+ const name = parts.pop() as string;173+ let node = top;174+ for (const part of parts) {175+ let child = node.folders.get(part);176+ if (!child) {177+ child = { files: new Map(), folders: new Map() };178+ node.folders.set(part, child);179+ }180+ node = child;181+ }182+ node.files.set(name, { hash: file.hash, executable: file.executable });183+ }184+ const bodies = new Map<string, string>();185+ const write = (node: Trie): string => {186+ const entries: ManifestEntry[] = [];187+ for (const [name, child] of node.folders) {188+ entries.push({189+ name,190+ kind: "folder",191+ hash: "",192+ size: 0,193+ executable: false,194+ manifest: write(child),195+ });196+ }197+ if (node.files.size > 0) {198+ for (const [name, file] of node.files) {199+ entries.push({200+ name,201+ kind: "file",202+ hash: file.hash,203+ size: sizeOf(file.hash) as number,204+ executable: file.executable,205+ manifest: "",206+ });207+ }208+ }209+ // Entries are sorted by name, then kind: a file before a folder of the same name (§5.1).210+ entries.sort((a, b) => {211+ if (a.name !== b.name) return a.name < b.name ? -1 : 1;212+ return (a.kind === "file" ? 0 : 1) - (b.kind === "file" ? 0 : 1);213+ });214+ const body = JSON.stringify({ entries });215+ const hash = hashBody(body);216+ bodies.set(hash, body);217+ return hash;218+ };219+ return { root: write(top), bodies };220+}src/mirror/queries.ts+130 −32
@@ -4,6 +4,7 @@44 import type { ReleaseRecord } from "../bucket/repo.ts";55 import type { FileFacts } from "../describe/describe.ts";66 import type { Outline } from "../describe/links.ts";7+import { flattenManifest } from "./manifest.ts";78 import { mirrorState } from "./store.ts";89 910 export type Save = {@@ -106,26 +107,82 @@106107 ?.n as number;107108 }108109 110+type Strip = { save_id: string | null; path: string };111+type Filters = { generation: string; hidden: string[]; strips: Strip[] };112+113+// Which paths the operator hides and which strips cover, read once per strip/hidden generation.114+// A save's tree is never rewritten: the filter is applied as a save's files are read.115+const filters = new WeakMap<Database, Filters>();116+117+function filtersAt(db: Database): Filters {118+ const generation = tarballGeneration(db);119+ const cached = filters.get(db);120+ if (cached?.generation === generation) return cached;121+ const fresh: Filters = {122+ generation,123+ hidden: (mirrorState(db, "hidden") ?? "").split("\n").filter(Boolean),124+ strips: db.query<Strip, []>("SELECT save_id, path FROM events WHERE kind = 'strip'").all(),125+ };126+ filters.set(db, fresh);127+ return fresh;128+}129+130+// §10.2's path rule: a file or folder, or an `ANY_DEPTH` name at any depth.131+function covers(entry: string, path: string): boolean {132+ if (entry.startsWith("**/")) return `/${path}/`.includes(`/${entry.slice(3)}/`);133+ return path === entry || path.startsWith(`${entry.replace(/\/+$/, "")}/`);134+}135+136+function filesAtSave(db: Database, saveId: string, keepHidden: boolean): FileEntry[] {137+ const root = db138+ .query<{ manifest: string }, [string]>("SELECT manifest FROM saves WHERE id = ?")139+ .get(saveId)?.manifest;140+ if (root === undefined) return [];141+ const current = filtersAt(db);142+ // A path whose object the mirror never stored — an oversized one, a quarantined one — is not143+ // served, as the join on `objects` used to leave it out.144+ const exists = db.query<{ one: number }, [string]>("SELECT 1 AS one FROM objects WHERE hash = ?");145+ return flattenManifest(db, root).filter(146+ (file) =>147+ (keepHidden || !current.hidden.some((entry) => covers(entry, file.path))) &&148+ !current.strips.some(149+ (strip) =>150+ (strip.save_id === "" || strip.save_id === saveId) && covers(strip.path, file.path),151+ ) &&152+ exists.get(file.hash) !== null,153+ );154+}155+156+/** The files at a save, sorted: what its manifest tree flattens to, less hidden and stripped paths. */109157 export function filesAt(db: Database, saveId: string): FileEntry[] {110- return db111- .query<FileEntry, [string]>(112- `SELECT f.path, f.hash, f.executable = 1 AS executable, o.size FROM save_files f113- JOIN objects o ON o.hash = f.hash WHERE f.save_id = ? ORDER BY f.path`,114- )115- .all(saveId)116- .map((file) => ({ ...file, executable: Boolean(file.executable) }));158+ return filesAtSave(db, saveId, false);117159 }118160 161+/** The files a strip leaves, hidden paths included: the objects unhiding must still find. */162+export function storedFilesAt(db: Database, saveId: string): FileEntry[] {163+ return filesAtSave(db, saveId, true);164+}165+119166 export function fileAt(db: Database, saveId: string, path: string): FileEntry | null {120- const file = db121- .query<FileEntry, [string, string]>(122- `SELECT f.path, f.hash, f.executable = 1 AS executable, o.size FROM save_files f123- JOIN objects o ON o.hash = f.hash WHERE f.save_id = ? AND f.path = ?`,124- )125- .get(saveId, path);126- return file ? { ...file, executable: Boolean(file.executable) } : null;167+ return filesAt(db, saveId).find((file) => file.path === path) ?? null;127168 }128169 170+// A steal asks for the object list and then one object at a time; the set is the same for every171+// request until a landing, a strip or a hidden list changes, which the generation and head name.172+const visible = new WeakMap<Database, { key: string; hashes: Set<string> }>();173+174+/** Every object a visible file at some save refers to: the Koh routes serve only these. */175+export function visibleObjects(db: Database): Set<string> {176+ const key = `${tarballGeneration(db)}\n${mirrorState(db, "head") ?? ""}`;177+ const cached = visible.get(db);178+ if (cached?.key === key) return cached.hashes;179+ const hashes = new Set<string>();180+ const saves = db.query<{ id: string }, []>("SELECT id FROM saves").all();181+ for (const save of saves) for (const file of filesAt(db, save.id)) hashes.add(file.hash);182+ visible.set(db, { key, hashes });183+ return hashes;184+}185+129186 export function objectBytes(db: Database, hash: string): Uint8Array<ArrayBuffer> | null {130187 const row = db131188 .query<{ data: Uint8Array }, [string]>("SELECT data FROM objects WHERE hash = ?")@@ -186,26 +243,67 @@186243 return { line: [...line], byPath };187244 }188245 246+type FactsRow = {247+ lines: number | null;248+ description: string | null;249+ outline: string | null;250+};251+252+function factsAt(db: Database, hash: string, path: string): FactsRow | null {253+ return (254+ db255+ .query<FactsRow, [string, string]>(256+ "SELECT lines, description, outline FROM facts WHERE hash = ? AND path = ?",257+ )258+ .get(hash, path) ?? null259+ );260+}261+189262 /** The files at a save with what each says about itself, as recorded when it landed. */190263 export function filesWithFacts(db: Database, saveId: string): (FileEntry & FileFacts)[] {191- return db192- .query<193- FileEntry & { lines: number | null; description: string | null; outline: string | null },194- [string]195- >(196- `SELECT f.path, f.hash, f.executable = 1 AS executable, o.size, x.lines, x.description, x.outline197- FROM save_files f198- JOIN objects o ON o.hash = f.hash199- LEFT JOIN facts x ON x.hash = f.hash AND x.path = f.path200- WHERE f.save_id = ?201- ORDER BY f.path`,202- )203- .all(saveId)204- .map((row) => ({205- ...row,206- executable: Boolean(row.executable),207- outline: row.outline === null ? null : (JSON.parse(row.outline) as Outline),208- }));264+ return filesAt(db, saveId).map((file) => {265+ const facts = factsAt(db, file.hash, file.path);266+ return {267+ ...file,268+ lines: facts?.lines ?? null,269+ description: facts?.description ?? null,270+ outline: facts?.outline == null ? null : (JSON.parse(facts.outline) as Outline),271+ };272+ });273+}274+275+/** One file's Atlas panel row, or null when the save shows no such file. */276+export function panelFile(277+ db: Database,278+ saveId: string,279+ path: string,280+):281+ | (FileEntry & { lines: number | null; description: string | null; outline: string | null })282+ | null {283+ if (path === ".kohignore") return null;284+ const file = fileAt(db, saveId, path);285+ if (!file) return null;286+ const facts = factsAt(db, file.hash, file.path);287+ return { ...file, ...(facts ?? { lines: null, description: null, outline: null }) };288+}289+290+/** A folder's Atlas panel rows: every file under it at that save, sorted, less Koh's ignore file. */291+export function panelFolder(292+ db: Database,293+ saveId: string,294+ dir: string,295+): { path: string; size: number; lines: number | null; description: string | null }[] {296+ return filesAt(db, saveId)297+ .filter((file) => file.path !== ".kohignore" && file.path.startsWith(`${dir}/`))298+ .map((file) => {299+ const facts = factsAt(db, file.hash, file.path);300+ return {301+ path: file.path,302+ size: file.size,303+ lines: facts?.lines ?? null,304+ description: facts?.description ?? null,305+ };306+ });209307 }210308 211309 /** The file contents this repo's real saves refer to, as recounted when its saves land. */src/mirror/remote.ts+19 −21
@@ -2,7 +2,7 @@22 import type { Context, Hono } from "hono";33 import { type EventRecord, SAVE_ID, type SaveFile, type SaveRecord } from "../bucket/repo.ts";44 import { openPublicRepo, type PageContext } from "../pages/layout.ts";5-import { filesAt, headId } from "./queries.ts";5+import { type FileEntry, filesAt, headId, visibleObjects } from "./queries.ts";66 77 const JSON_TYPE = "application/json; charset=UTF-8";88 const TEXT_TYPE = "text/plain; charset=UTF-8";@@ -88,21 +88,20 @@8888 const row = mirror8989 .query<SaveRow, [string]>(`SELECT ${SAVE_COLUMNS} FROM saves WHERE id = ?`)9090 .get(id);91- return row ? json(c, saveRecord(mirror, row), SAVE_CACHE) : miss(c);91+ return row ? json(c, saveRecord(row, filesAt(mirror, row.id)), SAVE_CACHE) : miss(c);9292 }),9393 );9494 9595 // The object's stored bytes, zlib and all: `koh steal` inflates them itself and checks the hash.96- // Only objects a visible file refers to: the mirror keeps hidden files' objects for unhiding.96+ // Only objects a visible file refers to: a hidden or stripped path is never served, while its97+ // object is kept for unhiding.9798 app.get("/:repo/koh/objects/:hash", (c) =>9899 serve(c, c.req.param("repo"), (mirror) => {99100 const hash = c.req.param("hash");100- if (!OBJECT_HASH.test(hash)) return miss(c);101+ if (!OBJECT_HASH.test(hash) || !visibleObjects(mirror).has(hash)) return miss(c);101102 const row = mirror102103 .query<{ data: Uint8Array<ArrayBuffer> }, [string]>(103- `SELECT data FROM objects o104- WHERE hash = ?105- AND EXISTS (SELECT 1 FROM save_files f WHERE f.hash = o.hash)`,104+ "SELECT data FROM objects WHERE hash = ?",106105 )107106 .get(hash);108107 return row@@ -128,14 +127,7 @@128127 129128 app.get("/:repo/koh/objects", (c) =>130129 serve(c, c.req.param("repo"), (mirror) => {131- const hashes = mirror132- .query<{ hash: string }, []>(133- `SELECT hash FROM objects o134- WHERE EXISTS (SELECT 1 FROM save_files f WHERE f.hash = o.hash)135- ORDER BY hash`,136- )137- .all()138- .map((row) => row.hash);130+ const hashes = [...visibleObjects(mirror)].sort();139131 return text(c, hashes.length > 0 ? `${hashes.join("\n")}\n` : "", NO_CACHE);140132 }),141133 );@@ -194,18 +186,24 @@194186 const saves = reader.prepare<SaveRow, []>(`SELECT ${SAVE_COLUMNS} FROM saves`);195187 const events = reader.prepare<EventRow, []>(`SELECT ${EVENT_COLUMNS} FROM events`);196188 const objects = reader.prepare<{ hash: string; data: Uint8Array }, []>(197- `SELECT hash, data FROM objects o198- WHERE EXISTS (SELECT 1 FROM save_files f WHERE f.hash = o.hash)`,189+ "SELECT hash, data FROM objects",199190 );200191 try {201192 reader.run("BEGIN DEFERRED");193+ // The objects a visible file refers to, gathered as the save records that name them stream:194+ // a hidden or stripped path's object is left out, as it is left out of the record.195+ const visible = new Set<string>();202196 for (const row of saves.iterate()) {203- yield* entry(`saves/${row.id}`, encoder.encode(saveRecord(reader, row)));197+ const files = filesAt(reader, row.id);198+ for (const file of files) visible.add(file.hash);199+ yield* entry(`saves/${row.id}`, encoder.encode(saveRecord(row, files)));204200 }205201 for (const row of events.iterate()) {206202 yield* entry(`events/${row.id}`, encoder.encode(eventRecord(row)));207203 }208- for (const row of objects.iterate()) yield* entry(`objects/${row.hash}`, row.data);204+ for (const row of objects.iterate()) {205+ if (visible.has(row.hash)) yield* entry(`objects/${row.hash}`, row.data);206+ }209207 reader.run("COMMIT");210208 // A connection cut between two entries would otherwise pass for the whole repo.211209 yield encoder.encode("end 0\n");@@ -221,7 +219,7 @@221219 222220 // Field names and their order are Koh's, and every optional is an empty string, as `json2.encode`223221 // writes it: `koh steal` decodes this straight into its own record.224-function saveRecord(mirror: Database, row: SaveRow): string {222+function saveRecord(row: SaveRow, files: FileEntry[]): string {225223 const record: SaveRecord = {226224 id: row.id,227225 parent: row.parent ?? "",@@ -235,7 +233,7 @@235233 restores: row.restores ?? "",236234 replayed_from: row.replayed_from ?? "",237235 // Whatever the strips left: a path they removed is gone from the record too.238- files: filesAt(mirror, row.id).map(236+ files: files.map(239237 (file): SaveFile => ({ path: file.path, hash: file.hash, executable: file.executable }),240238 ),241239 };src/mirror/store.ts+222 −261
@@ -6,41 +6,16 @@66 import { fileFacts } from "../describe/describe.ts";77 import { isTestPath } from "../describe/links.ts";88 import { declaredVersion } from "../describe/version.ts";9+import { hashBody, manifestBody, manifestTree } from "./manifest.ts";10+import { fileAt, filesAt, storedFilesAt } from "./queries.ts";911 1012 // Koh 3's schema (§5.1, `src/storage/storage.v`) minus `file_cache`, which only a working tree needs,1113 // plus `releases`: each version's release.json (§11.2) as read from the bucket, since that is bucket12-// data too and pages and feeds need it on every request, `hidden_files`, and what the Atlas reads.13-const SCHEMA_VERSION = 4;14-// The operator's hidden rows, moved out of `save_files` rather than deleted, so a changed hidden15-// list is applied in place, with nothing fetched again (2026-10-02).16-const HIDDEN_FILES = `17-CREATE TABLE hidden_files (18- save_id TEXT NOT NULL REFERENCES saves(id),19- path TEXT NOT NULL,20- hash TEXT NOT NULL REFERENCES objects(hash),21- executable INTEGER NOT NULL DEFAULT 0,22- PRIMARY KEY (save_id, path)23-);24-`;14+// data too and pages and feeds need it on every request, and what the Atlas reads.15+const SCHEMA_VERSION = 5;2516 // What pages read, worked out as each save lands rather than on every view (2026-10-02): which2617 // real saves touched each path (added, changed or removed against the real save before; `n` is the2718 // touching save's rowid), what each file says about itself, and the objects real saves refer to.28-const DERIVED = `29-CREATE TABLE known_objects (hash TEXT PRIMARY KEY) WITHOUT ROWID;30-CREATE TABLE touches (31- path TEXT NOT NULL,32- n INTEGER NOT NULL33-);34-CREATE INDEX touches_n ON touches(n);35-CREATE TABLE facts (36- hash TEXT NOT NULL,37- path TEXT NOT NULL,38- lines INTEGER,39- description TEXT,40- outline TEXT,41- PRIMARY KEY (hash, path)42-);43-`;4419 const SCHEMA = `4520 CREATE TABLE objects (4621 hash TEXT PRIMARY KEY,@@ -50,6 +25,7 @@5025 CREATE TABLE saves (5126 id TEXT PRIMARY KEY,5227 parent TEXT REFERENCES saves(id),28+ manifest TEXT NOT NULL,5329 message TEXT NOT NULL,5430 created_at INTEGER NOT NULL,5531 machine TEXT NOT NULL,@@ -60,13 +36,10 @@6036 restores TEXT,6137 replayed_from TEXT6238 );63-CREATE TABLE save_files (64- save_id TEXT NOT NULL REFERENCES saves(id),65- path TEXT NOT NULL,66- hash TEXT NOT NULL REFERENCES objects(hash),67- executable INTEGER NOT NULL DEFAULT 0,68- PRIMARY KEY (save_id, path)69-);39+CREATE TABLE manifests (40+ hash TEXT PRIMARY KEY,41+ body TEXT NOT NULL42+) WITHOUT ROWID;7043 CREATE TABLE events (7144 id TEXT PRIMARY KEY,7245 kind TEXT NOT NULL,@@ -84,11 +57,49 @@8457 version TEXT PRIMARY KEY,8558 record TEXT NOT NULL8659 );60+CREATE TABLE known_objects (hash TEXT PRIMARY KEY) WITHOUT ROWID;61+CREATE TABLE touches (62+ path TEXT NOT NULL,63+ n INTEGER NOT NULL64+);65+CREATE INDEX touches_n ON touches(n);66+CREATE INDEX touches_path ON touches(path, n);67+CREATE TABLE facts (68+ hash TEXT NOT NULL,69+ path TEXT NOT NULL,70+ lines INTEGER,71+ description TEXT,72+ outline TEXT,73+ PRIMARY KEY (hash, path)74+);8775 CREATE INDEX saves_parent ON saves(parent);88-CREATE INDEX save_files_hash ON save_files(hash);89-${HIDDEN_FILES}90-${DERIVED}`;76+`;9177 78+/**79+ * Creates a mirror, or rebuilds a disposable one: a mirror of another schema is emptied and the80+ * next sync lands the repo again. Run under the write lock, since the request thread and the81+ * sync's both open mirrors and must not both create or rebuild one.82+ */83+function upgrade(db: Database): void {84+ db.transaction(() => {85+ if (schemaVersion(db) !== 0) {86+ for (const { name } of db87+ .query<{ name: string }, []>(88+ "SELECT name FROM sqlite_schema WHERE type = 'table' AND name NOT LIKE 'sqlite_%'",89+ )90+ .all()) {91+ db.run(`DROP TABLE "${name.replaceAll('"', '""')}"`);92+ }93+ }94+ db.run(SCHEMA);95+ // A new epoch keeps tarballs made before the rebuild from ever being looked up again.96+ db.query("INSERT OR IGNORE INTO state (key, value) VALUES ('epoch', ?)").run(97+ crypto.randomUUID(),98+ );99+ db.run(`PRAGMA user_version = ${SCHEMA_VERSION}`);100+ }).immediate();101+}102+92103 /** An object as the bucket stores it: zlib bytes, already checked against its hash. */93104 export type StoredObject = { compressed: Uint8Array; size: number };94105 @@ -97,6 +108,8 @@97108 head: string;98109 releasesLatest: string;99110 saves: SaveRecord[];111+ /** Folder bodies the saves' trees name, as fetched from the bucket (§9.2, format 2). */112+ manifests: Map<string, string>;100113 objects: Map<string, StoredObject>;101114 events: EventRecord[];102115 releases: ReleaseRecord[];@@ -179,17 +192,8 @@179192 db.run("PRAGMA journal_mode = WAL");180193 db.run("PRAGMA foreign_keys = ON");181194 db.run("PRAGMA busy_timeout = 5000");182- // A current mirror needs no lock; only creating or migrating one takes the write lock.183- const found = schemaVersion(db) === SCHEMA_VERSION ? SCHEMA_VERSION : upgrade(db);184- if (found !== 0 && found !== 2 && found !== 3 && found !== SCHEMA_VERSION) {185- db.close();186- throw new Error(187- `${path} has mirror schema version ${found}; this Kepr reads version ${SCHEMA_VERSION}. ` +188- "The mirror is disposable: delete it and the next sync rebuilds it from the bucket.",189- );190- }191- // A panel reads one path's touches; without this index every hover scans them (§21.5).192- db.run("CREATE INDEX IF NOT EXISTS touches_path ON touches(path, n)");195+ // A current mirror needs no lock; only creating or rebuilding one takes the write lock.196+ if (schemaVersion(db) !== SCHEMA_VERSION) upgrade(db);193197 // Mirrors counted under an older rule are recounted now, not at the next save.194198 if (mirrorState(db, "head") && mirrorState(db, "stats_rule") !== STATS_RULE) refreshStats(db);195199 open.set(path, db);@@ -200,30 +204,6 @@200204 return db.query<{ user_version: number }, []>("PRAGMA user_version").get()?.user_version ?? 0;201205 }202206 203-/**204- * Creates or migrates a mirror and returns the version it found, read again under the write lock:205- * the request thread and the sync's both open mirrors, and must not both create or migrate one.206- */207-function upgrade(db: Database): number {208- return db209- .transaction(() => {210- const found = schemaVersion(db);211- if (found === SCHEMA_VERSION || ![0, 2, 3].includes(found)) return found;212- if (found === 0) db.run(SCHEMA);213- if (found === 2) db.run(HIDDEN_FILES);214- if (found === 2 || found === 3) db.run(DERIVED);215- // Version 2 deleted hidden rows, so only the bucket can bring them back on unhide.216- if (found === 2 && mirrorState(db, "hidden")) clearMirror(db);217- else if (found !== 0) {218- recordTouches(db, 0);219- recordFacts(db, null);220- }221- db.run(`PRAGMA user_version = ${SCHEMA_VERSION}`);222- return found;223- })224- .immediate();225-}226-227207 export function mirrorState(db: Database, key: string): string | null {228208 const row = db229209 .query<{ value: string }, [string]>("SELECT value FROM state WHERE key = ?")@@ -239,6 +219,11 @@239219 return db.query("SELECT 1 FROM objects WHERE hash = ?").get(hash) !== null;240220 }241221 222+/** Whether a save's tree can be flattened without fetching anything. */223+export function knownManifest(db: Database, hash: string): boolean {224+ return db.query("SELECT 1 FROM manifests WHERE hash = ?").get(hash) !== null;225+}226+242227 export function knownEventIds(db: Database): Set<string> {243228 const rows = db.query<{ id: string }, []>("SELECT id FROM events").all();244229 return new Set(rows.map((row) => row.id));@@ -270,9 +255,22 @@270255 })();271256 }272257 258+/** Stores folder manifests on their own, ahead of the save that names them. */259+export function storeManifests(db: Database, manifests: Map<string, string>): void {260+ const put = db.query("INSERT OR IGNORE INTO manifests (hash, body) VALUES (?, ?)");261+ db.transaction(() => {262+ for (const [hash, body] of manifests) {263+ if (hashBody(body) !== hash) throw new Error(`manifest ${hash} does not match its body`);264+ put.run(hash, body);265+ }266+ })();267+}268+273269 /**274- * Lands a sync like Koh's steal: objects, events, saves, then every strip over every save. The new275- * saves are hidden by the list the mirror holds; `applyHidden` changes that list.270+ * Lands a sync like Koh's steal: objects, events, manifests, saves, then the strips the batch271+ * names. A version-2 save keeps the tree the bucket fetched; a version-1 record is converted once,272+ * so every later read is the same. Trees are never rewritten: a strip is read-time, which is why a273+ * strip landing walks the saves once (for touches and unreferenced objects) and no other landing does.276274 */277275 export function land(db: Database, landing: Landing): void {278276 const putEvent = db.query(@@ -280,14 +278,15 @@280278 "(?, ?, ?, ?, ?, ?, ?)",281279 );282280 const putSave = db.query(283- `INSERT OR IGNORE INTO saves (id, parent, message, created_at, machine, is_checkpoint, size_bytes,284- agent, session, restores, replayed_from) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,281+ `INSERT OR IGNORE INTO saves (id, parent, manifest, message, created_at, machine,282+ is_checkpoint, size_bytes, agent, session, restores, replayed_from)283+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,285284 );286- const putFile = db.query(287- "INSERT OR IGNORE INTO save_files (save_id, path, hash, executable) VALUES (?, ?, ?, ?)",288- );285+ const putManifest = db.query("INSERT OR IGNORE INTO manifests (hash, body) VALUES (?, ?)");289286 const putRelease = db.query("INSERT OR IGNORE INTO releases (version, record) VALUES (?, ?)");290287 const setState = db.query("INSERT OR REPLACE INTO state (key, value) VALUES (?, ?)");288+ const sizeOf = db.query<{ size: number }, [string]>("SELECT size FROM objects WHERE hash = ?");289+ const stripped = landing.events.some((event) => event.kind === "strip");291290 // Immediate: a landing with nothing new reads before it writes, and the request thread writes292291 // mirrors too (a deleted release).293292 db.transaction(() => {@@ -295,10 +294,20 @@295294 for (const e of landing.events) {296295 putEvent.run(e.id, e.kind, e.save_id, e.path, e.reason, e.created_at, e.machine);297296 }297+ storeManifests(db, landing.manifests);298298 for (const s of landing.saves) {299+ let root = s.manifest ?? "";300+ if (root === "") {301+ const tree = manifestTree(s.files, (hash) => sizeOf.get(hash)?.size ?? null);302+ for (const [hash, body] of tree.bodies) putManifest.run(hash, body);303+ root = tree.root;304+ } else if (manifestBody(db, root) === null) {305+ throw new Error(`save ${s.id} names manifest ${root}, which did not land`);306+ }299307 putSave.run(300308 s.id,301309 s.parent === "" ? null : s.parent,310+ root,302311 s.message,303312 s.created_at,304313 s.machine,@@ -309,12 +318,11 @@309318 s.restores,310319 s.replayed_from,311320 );312- for (const f of s.files) putFile.run(s.id, f.path, f.hash, f.executable ? 1 : 0);313321 }314- for (const r of landing.releases) putRelease.run(r.version, JSON.stringify(r));315- const stripped = applyStrips(db);316322 const landed = landing.saves.map((save) => save.id);317- hideRows(db, hiddenList(db), landed);323+ for (const r of landing.releases) putRelease.run(r.version, JSON.stringify(r));324+ if (stripped) dropStripped(db);325+ else addKnownObjects(db, landing.saves);318326 // A strip can reach any save, so every save's touches are worked out again after one.319327 recordTouches(db, stripped ? 0 : Number(mirrorState(db, "touches_to") ?? 0));320328 recordFacts(db, landed);@@ -322,28 +330,27 @@322330 setState.run("releases_latest", landing.releasesLatest);323331 const quarantined = new Set([...quarantinedPaths(db), ...landing.quarantined]);324332 setState.run("quarantined", JSON.stringify([...quarantined].sort()));325- staleStats(db);333+ const newest = newestRealSave(db);334+ if (stripped || newest !== mirrorState(db, "stats_save")) staleStats(db);326335 }).immediate();327336 // Outside the transaction: the recount can inflate megabytes and needs no lock to be correct.328- refreshStats(db);337+ if (mirrorState(db, "stats_rule") !== STATS_RULE) refreshStats(db);329338 }330339 331340 /**332341 * Makes `hidden` the mirror's hidden list: the operator's hidden paths (June, 2026-09-30) and the333- * names ignored in every repo (June, 2026-10-01), each as `ANY_DEPTH` + name. Rows move between334- * `save_files` and `hidden_files`, so it takes milliseconds and fetches nothing.342+ * names ignored in every repo (June, 2026-10-01), each as `ANY_DEPTH` + name. Trees are never343+ * rewritten, so the list lands at once and takes effect on the next read.335344 */336345 export function applyHidden(db: Database, hidden: string[]): void {337346 if (hiddenList(db).join("\n") === hidden.join("\n")) return;338347 db.transaction(() => {339- db.run(340- `INSERT OR IGNORE INTO save_files (save_id, path, hash, executable)341- SELECT save_id, path, hash, executable FROM hidden_files`,348+ db.query("INSERT OR REPLACE INTO state (key, value) VALUES ('hidden', ?)").run(349+ hidden.join("\n"),342350 );343- db.run("DELETE FROM hidden_files");344- hideRows(db, hidden, null);345351 recordTouches(db, 0);346352 recordFacts(db, null);353+ rebuildKnownObjects(db);347354 staleStats(db);348355 })();349356 refreshStats(db);@@ -355,6 +362,16 @@355362 db.run("DELETE FROM state WHERE key = 'stats_rule'");356363 }357364 365+function newestRealSave(db: Database): string {366+ return (367+ db368+ .query<{ id: string }, []>(369+ "SELECT id FROM saves WHERE is_checkpoint = 0 ORDER BY rowid DESC LIMIT 1",370+ )371+ .get()?.id ?? ""372+ );373+}374+358375 /**359376 * Records which real saves touched each path, for the saves after rowid `from`; 0 starts again.360377 * A save touched a path when it was added, changed or removed against the real save before it;@@ -362,178 +379,142 @@362379 */363380 function recordTouches(db: Database, from: number): void {364381 if (from === 0) db.run("DELETE FROM touches");365- db.query(366- `WITH line AS (367- SELECT id, rowid AS n, LAG(id) OVER (ORDER BY rowid) AS prev368- FROM saves369- WHERE is_checkpoint = 0382+ const previous = new Map<string, { hash: string; executable: boolean }>();383+ const seed =384+ from === 0385+ ? undefined386+ : db387+ .query<{ id: string }, [number]>(388+ `SELECT id FROM saves389+ WHERE is_checkpoint = 0 AND rowid <= ?390+ ORDER BY rowid DESC LIMIT 1`,391+ )392+ .get(from)?.id;393+ if (seed !== undefined) {394+ for (const file of filesAt(db, seed)) previous.set(file.path, file);395+ }396+ const put = db.query("INSERT INTO touches (path, n) VALUES (?, ?)");397+ const line = db398+ .query<{ id: string; n: number }, [number]>(399+ `SELECT id, rowid AS n FROM saves400+ WHERE is_checkpoint = 0 AND rowid > ?401+ ORDER BY rowid`,370402 )371- INSERT INTO touches (path, n)372- SELECT f.path, line.n373- FROM line374- JOIN save_files f ON f.save_id = line.id375- LEFT JOIN save_files p ON p.save_id = line.prev AND p.path = f.path376- WHERE line.n > $from377- AND (p.hash IS NOT f.hash OR p.executable IS NOT f.executable)378- UNION ALL379- SELECT p.path, line.n380- FROM line381- JOIN save_files p ON p.save_id = line.prev382- WHERE line.n > $from383- AND NOT EXISTS (SELECT 1 FROM save_files f WHERE f.save_id = line.id AND f.path = p.path)`,384- ).run({ from });403+ .all(from);404+ for (const save of line) {405+ const current = new Map(filesAt(db, save.id).map((file) => [file.path, file]));406+ for (const [path, file] of current) {407+ const before = previous.get(path);408+ if (!before || before.hash !== file.hash || before.executable !== file.executable) {409+ put.run(path, save.n);410+ }411+ }412+ for (const path of previous.keys()) if (!current.has(path)) put.run(path, save.n);413+ previous.clear();414+ for (const [path, file] of current) previous.set(path, file);415+ }385416 const last = db.query<{ n: number | null }, []>("SELECT MAX(rowid) AS n FROM saves").get()?.n;386417 db.query("INSERT OR REPLACE INTO state (key, value) VALUES ('touches_to', ?)").run(387418 String(last ?? 0),388419 );389420 }390421 391-/** Records what each file of the given saves, or (null) every save, says about itself, once per version and path. */422+/**423+ * Records what each file of the given saves (or, with null, every save) says about itself, once per424+ * version and path. Only a pair the mirror has never described is inflated, so an ordinary landing425+ * that re-lists unchanged files reads none of them.426+ */392427 function recordFacts(db: Database, saves: string[] | null): void {393- const wanted = db394- .query<{ hash: string; path: string }, { all: number; saves: string }>(395- `SELECT DISTINCT f.hash, f.path396- FROM save_files f397- WHERE ($all = 1 OR f.save_id IN (SELECT value FROM json_each($saves)))398- AND NOT EXISTS (SELECT 1 FROM facts x WHERE x.hash = f.hash AND x.path = f.path)`,399- )400- .all({ all: saves === null ? 1 : 0, saves: JSON.stringify(saves ?? []) });401- const sizeOf = db.query<{ size: number }, [string]>("SELECT size FROM objects WHERE hash = ?");428+ const ids =429+ saves ??430+ db431+ .query<{ id: string }, []>("SELECT id FROM saves ORDER BY rowid")432+ .all()433+ .map((r) => r.id);434+ const has = db.query<{ one: number }, [string, string]>(435+ "SELECT 1 AS one FROM facts WHERE hash = ? AND path = ?",436+ );402437 const dataOf = db.query<{ data: Uint8Array }, [string]>(403438 "SELECT data FROM objects WHERE hash = ?",404439 );405440 const put = db.query(406441 "INSERT OR IGNORE INTO facts (hash, path, lines, description, outline) VALUES (?, ?, ?, ?, ?)",407442 );408- for (const { hash, path } of wanted) {409- const size = sizeOf.get(hash)?.size;410- if (size === undefined) continue;411- // The stored bytes are read only for a file small enough to describe.412- const read = () => inflateSync((dataOf.get(hash) as { data: Uint8Array }).data);413- const facts = fileFacts(path, size, read);414- put.run(415- hash,416- path,417- facts.lines,418- facts.description,419- facts.outline && JSON.stringify(facts.outline),420- );443+ const seen = new Set<string>();444+ for (const id of ids) {445+ for (const file of filesAt(db, id)) {446+ const key = `${file.hash}\n${file.path}`;447+ if (seen.has(key)) continue;448+ seen.add(key);449+ if (has.get(file.hash, file.path)) continue;450+ // The stored bytes are read only for a file small enough to describe.451+ const facts = fileFacts(file.path, file.size, () => {452+ const stored = dataOf.get(file.hash);453+ if (stored === null) throw new Error(`object ${file.hash} is missing`);454+ return inflateSync(stored.data);455+ });456+ put.run(457+ file.hash,458+ file.path,459+ facts.lines,460+ facts.description,461+ facts.outline && JSON.stringify(facts.outline),462+ );463+ }421464 }422465 }423466 424-function hiddenList(db: Database): string[] {425- return mirrorState(db, "hidden")?.split("\n").filter(Boolean) ?? [];426-}427-428-// Moves the rows `hidden` matches, in the `saves` given or (null) every save, into `hidden_files`.429-// The list is recorded in the same transaction, so the tarball key never names a list the rows430-// don't reflect yet.431-function hideRows(db: Database, hidden: string[], saves: string[] | null): void {432- for (const entry of hidden) {433- const { where, params } = pathMatch(entry);434- const scope = { ...params, all: saves === null ? 1 : 0, saves: JSON.stringify(saves ?? []) };435- const chosen = `${where} AND ($all = 1 OR save_id IN (SELECT value FROM json_each($saves)))`;436- db.query(437- `INSERT OR IGNORE INTO hidden_files (save_id, path, hash, executable)438- SELECT save_id, path, hash, executable FROM save_files439- WHERE ${chosen}`,440- ).run(scope);441- db.query(`DELETE FROM save_files WHERE ${chosen}`).run(scope);467+/** The objects real saves show, for the front page's "the library knows N things". */468+function addKnownObjects(db: Database, saves: SaveRecord[]): void {469+ const put = db.query("INSERT OR IGNORE INTO known_objects (hash) VALUES (?)");470+ for (const save of saves) {471+ // Checkpoints are working marks, not history (§21.4), as in the recount.472+ if (save.is_checkpoint) continue;473+ for (const file of filesAt(db, save.id)) put.run(file.hash);442474 }443- db.query("INSERT OR REPLACE INTO state (key, value) VALUES ('hidden', ?)").run(hidden.join("\n"));444475 }445476 446-/** Escaped names of every path this mirror's saves arrived without. */447-export function quarantinedPaths(db: Database): string[] {448- return JSON.parse(mirrorState(db, "quarantined") ?? "[]");477+function rebuildKnownObjects(db: Database): void {478+ db.run("DELETE FROM known_objects");479+ const put = db.query("INSERT OR IGNORE INTO known_objects (hash) VALUES (?)");480+ const saves = db.query<{ id: string }, []>("SELECT id FROM saves WHERE is_checkpoint = 0").all();481+ for (const save of saves) for (const file of filesAt(db, save.id)) put.run(file.hash);449482 }450483 451-// §10.2: a strip of one save reaches that save; a strip of every save bans its path from all of452-// history, whenever a save was made or arrives. Re-applying every strip is harmless, which is how a453-// save that arrives after its strip event is covered too.454-// Returns whether any save lost a file.455-function applyStrips(db: Database): boolean {456- const strips = db457- .query<{ save_id: string; path: string }, []>(458- "SELECT save_id, path FROM events WHERE kind = 'strip'",459- )460- .all();461- if (strips.length === 0) return false;462- let removed = 0;463- for (const strip of strips) {464- const { where, params } = pathMatch(strip.path);465- // Hidden rows too, so unhiding never brings back what a strip removed.466- for (const table of ["save_files", "hidden_files"]) {467- removed += db468- .query(`DELETE FROM ${table} WHERE ${where} AND ($save = '' OR save_id = $save)`)469- .run({ ...params, save: strip.save_id }).changes;470- }484+/**485+ * Deletes the objects no save shows and no hidden path keeps, and recounts the objects real saves486+ * show, so a strip erases what it removed. Only a landing that carries a strip event does this;487+ * it is the one landing that walks the trees (for touches as well), and it rewrites no save's rows.488+ */489+function dropStripped(db: Database): void {490+ const kept = new Set<string>();491+ const saves = db.query<{ id: string }, []>("SELECT id FROM saves").all();492+ for (const save of saves) for (const file of storedFilesAt(db, save.id)) kept.add(file.hash);493+ const drop = db.query("DELETE FROM objects WHERE hash = ?");494+ for (const row of db.query<{ hash: string }, []>("SELECT hash FROM objects").all()) {495+ if (!kept.has(row.hash)) drop.run(row.hash);471496 }472- db.run(473- `DELETE FROM objects474- WHERE hash NOT IN (SELECT hash FROM save_files)475- AND hash NOT IN (SELECT hash FROM hidden_files)`,476- );477497 db.run("DELETE FROM facts WHERE hash NOT IN (SELECT hash FROM objects)");478- return removed > 0;498+ rebuildKnownObjects(db);479499 }480500 481-/** The SQL condition matching a path, file or folder, or an `ANY_DEPTH` name at any depth. */482-function pathMatch(path: string): { where: string; params: Record<string, string> } {483- if (path.startsWith(ANY_DEPTH)) {484- return {485- where: "instr('/' || path || '/', $segment) > 0",486- params: { segment: `/${path.slice(ANY_DEPTH.length)}/` },487- };488- }489- // Koh compares the prefix exactly, never with LIKE, so `_` and `%` in a path match only themselves.490- return {491- where: "(path = $path OR substr(path, 1, length($dir)) = $dir)",492- params: { path, dir: `${path.replace(/\/+$/, "")}/` },493- };501+function hiddenList(db: Database): string[] {502+ return mirrorState(db, "hidden")?.split("\n").filter(Boolean) ?? [];494503 }495504 496-/**497- * Empties a mirror in place so the next sync rebuilds it from the bucket, as the move to schema498- * version 3 needs when hidden rows were deleted. The file and its open handles stay, so a request holding one reads an empty499- * repo for a moment rather than failing. A new epoch keeps tarballs kept before it from matching.500- */501-export function clearMirror(db: Database): void {502- db.transaction(() => {503- // Children before parents, for the foreign keys; every name is a table of SCHEMA's.504- const tables = [505- "save_files",506- "hidden_files",507- "touches",508- "facts",509- "known_objects",510- "events",511- "saves",512- "objects",513- "releases",514- "state",515- ];516- for (const table of tables) {517- db.run(`DELETE FROM ${table}`);518- }519- db.query("INSERT INTO state (key, value) VALUES ('epoch', ?)").run(crypto.randomUUID());520- })();505+/** Escaped names of every path this mirror's saves arrived without. */506+export function quarantinedPaths(db: Database): string[] {507+ return JSON.parse(mirrorState(db, "quarantined") ?? "[]");521508 }522509 523510 // A file at a save as text, if it is there and small enough to be a manifest.524511 function smallFileText(db: Database, save: string, path: string): string | null {512+ const file = fileAt(db, save, path);513+ if (!file || file.size > MAX_MANIFEST) return null;525514 const row = db526- .query<{ size: number; data: Uint8Array }, [string, string]>(527- `SELECT o.size, o.data528- FROM save_files f529- JOIN objects o ON o.hash = f.hash530- WHERE f.save_id = ?531- AND f.path = ?`,532- )533- .get(save, path);534- return row && row.size <= MAX_MANIFEST535- ? new TextDecoder("utf-8", { ignoreBOM: true }).decode(inflateSync(row.data))536- : null;515+ .query<{ data: Uint8Array }, [string]>("SELECT data FROM objects WHERE hash = ?")516+ .get(file.hash);517+ return row ? new TextDecoder("utf-8", { ignoreBOM: true }).decode(inflateSync(row.data)) : null;537518 }538519 539520 // Lines and languages never change between syncs, so they are counted once here, not per view. They@@ -546,17 +527,11 @@546527 }547528 548529 function recount(db: Database): void {549- const save =550- db551- .query<{ id: string }, []>(552- "SELECT id FROM saves WHERE is_checkpoint = 0 ORDER BY rowid DESC LIMIT 1",553- )554- .get()?.id ?? "";555- const files = db556- .query<{ path: string; size: number; data: Uint8Array }, [string]>(557- "SELECT f.path, o.size, o.data FROM save_files f JOIN objects o ON o.hash = f.hash WHERE f.save_id = ?",558- )559- .all(save);530+ const save = newestRealSave(db);531+ const files = save === "" ? [] : filesAt(db, save);532+ const dataOf = db.query<{ data: Uint8Array }, [string]>(533+ "SELECT data FROM objects WHERE hash = ?",534+ );560535 let lines = 0;561536 const byLanguage = new Map<string, number>();562537 for (const file of files) {@@ -564,7 +539,9 @@564539 // Tests are not the program: counted, Koh 3's read as 18k lines of V where it has 11k.565540 if (!language || VENDORED.test(file.path) || isTestPath(file.path)) continue;566541 if (file.size > MAX_COUNTED) continue;567- const bytes = inflateSync(file.data);542+ const stored = dataOf.get(file.hash);543+ if (stored === null) continue;544+ const bytes = inflateSync(stored.data);568545 if (bytes.includes(0)) continue;569546 let count = 0;570547 for (const byte of bytes) if (byte === 10) count++;@@ -579,22 +556,6 @@579556 setState.run("languages", JSON.stringify(languages));580557 setState.run("stats_save", save);581558 setState.run("declared_version", declaredVersion((path) => smallFileText(db, save, path)) ?? "");582- // §21.1's "the library knows N things": the file contents any real save refers to, which the583- // front page unites across public repos. From `objects`, probing save_files_hash: a DISTINCT584- // over save_files reads saves × files rows.585- db.run("DELETE FROM known_objects");586- db.run(587- `INSERT INTO known_objects (hash)588- SELECT o.hash589- FROM objects o590- WHERE EXISTS (591- SELECT 1592- FROM save_files f593- JOIN saves s ON s.id = f.save_id594- WHERE f.hash = o.hash595- AND s.is_checkpoint = 0596- )`,597- );598559 // Last, with the recount it names, so one cut short is done again at the next open.599560 setState.run("stats_rule", STATS_RULE);600561 }src/pages/atlas.ts+4 −26
@@ -4,6 +4,8 @@44 import {55 filesWithFacts,66 fileTouches,7+ panelFile,8+ panelFolder,79 type Save,810 type Touches,911 tarballGeneration,@@ -132,22 +134,6 @@132134 </section>`;133135 }134136 135-type PanelRow = { path: string; size: number; lines: number | null; description: string | null };136-137-// A panel's own reads: one row's facts, and the saves that touched it or (for a folder) anything138-// under it. Everything else the panel needs comes from the links, which are kept (linksFor).139-const FILE_SQL = `SELECT f.path, o.size, x.lines, x.description, x.outline140- FROM save_files f141- JOIN objects o ON o.hash = f.hash142- LEFT JOIN facts x ON x.hash = f.hash AND x.path = f.path143- WHERE f.save_id = ? AND f.path = ? AND f.path != '.kohignore'`;144-const FOLDER_SQL = `SELECT f.path, o.size, x.lines, x.description145- FROM save_files f146- JOIN objects o ON o.hash = f.hash147- LEFT JOIN facts x ON x.hash = f.hash AND x.path = f.path148- WHERE f.save_id = ? AND f.path >= ? AND f.path < ? AND f.path != '.kohignore'149- ORDER BY f.path`;150-151137 // The saves that touched a path, or (with `under`) anything under a folder, oldest first.152138 function pathTouches(db: Database, saveId: string, path: string, under: boolean): Save[] {153139 const scope = under ? "path >= ? AND path < ?" : "path = ?";@@ -179,16 +165,8 @@179165 const folder = path.endsWith("/");180166 const dir = folder ? path.slice(0, -1) : path;181167 return repo.mirror.transaction((): Html | null => {182- const rows = folder183- ? repo.mirror184- .query<PanelRow, [string, string, string]>(FOLDER_SQL)185- .all(saveId, `${dir}/`, `${dir}0`)186- : [];187- const row = folder188- ? null189- : (repo.mirror190- .query<PanelRow & { outline: string | null }, [string, string]>(FILE_SQL)191- .get(saveId, dir) ?? null);168+ const rows = folder ? panelFolder(repo.mirror, saveId, dir) : [];169+ const row = folder ? null : panelFile(repo.mirror, saveId, dir);192170 if (folder ? rows.length === 0 : row === null) return null;193171 const view = {194172 repo: repo.settings.name,src/releases/releases.ts+35 −11
@@ -1,6 +1,6 @@11 import type { Database } from "bun:sqlite";22 import type { Context } from "hono";3-import type { Bucket } from "../bucket/reader.ts";3+import { type Bucket, BucketWriteError } from "../bucket/reader.ts";44 import {55 checkRelease,66 listReleaseVersions,@@ -297,16 +297,7 @@297297 repo: string,298298 version: string,299299 ): Promise<void> {300- if ((await readReleasesLatest(bucket, repo)) === version) {301- const newest = (await listReleaseVersions(bucket, repo))302- .filter((other) => other !== version)303- .sort((a, b) => compareVersions(b, a))[0];304- const latest = `${repo}/releases/latest`;305- // ponytail: an unconditional write, as the reader has no put_if_match; a Koh publish landing306- // between the read above and this write loses `latest` until it offers again.307- if (newest) await bucket.put(latest, new TextEncoder().encode(newest), "text/plain");308- else await bucket.remove(latest);309- }300+ await moveLatest(bucket, repo, version);310301 const prefix = `${repo}/releases/${version}/`;311302 const record = `${prefix}release.json`;312303 for (const key of await bucket.list(prefix)) {@@ -320,6 +311,39 @@320311 kepr.query(`DELETE FROM ${table} WHERE repo = ? AND version = ?`).run(repo, version);321312 }322313 })();314+}315+316+// A delete retries the conditional move a few times; only a publish in the same instant causes one.317+const LATEST_TRIES = 3;318+319+/**320+ * Moves `<repo>/releases/latest` off `version` to the newest build left, or removes it with the last321+ * (June, 2026-09-30). A Koh publish can land at any moment, so the write is conditional on the tag322+ * of the value it replaces (2026-11-16): a publish that got there first keeps its own newer version,323+ * and `latest` is never dragged back to an older build. Nothing is deleted when the tag keeps324+ * moving, so a retry finds the build whole.325+ */326+async function moveLatest(bucket: Bucket, repo: string, version: string): Promise<void> {327+ const key = `${repo}/releases/latest`;328+ for (let attempt = 0; attempt < LATEST_TRIES; attempt++) {329+ // The tag before the value: a publish landing between the two is then caught by the value330+ // reading newer than `version`, rather than being written over under a tag it never held.331+ const tag = await bucket.tag(key);332+ if (tag === null || (await readReleasesLatest(bucket, repo)) !== version) return;333+ const newest = (await listReleaseVersions(bucket, repo))334+ .filter((other) => other !== version)335+ .sort((a, b) => compareVersions(b, a))[0];336+ if (newest === undefined) {337+ // A delete names no version to match, so check the tag once more, just before removing it.338+ // ponytail: a publish in the gap after this check still loses `latest` until it offers.339+ if ((await bucket.tag(key)) === tag) await bucket.remove(key);340+ return;341+ }342+ if (await bucket.putIfTag(key, new TextEncoder().encode(newest), "text/plain", tag)) return;343+ }344+ throw new BucketWriteError(345+ `koh is publishing to ${repo}: ${key} kept changing, so nothing was deleted`,346+ );323347 }324348 325349 /** Why a single file can't be deleted: the last one goes with its version, never alone. */tests/bucket.test.ts+20 −2
@@ -127,13 +127,15 @@127127 });128128 129129 describe("the format rule", () => {130- test("accepts koh-remote 1 and refuses anything else", async () => {130+ test("accepts both remote formats and refuses anything else", async () => {131131 const { bucketDir, repo } = await makeKohBucket("formatted");132132 const b = openBucket({ kind: "folder", path: bucketDir });133133 await writeFile(join(bucketDir, repo, "format"), "koh-remote 1");134134 await checkFormat(b, repo);135135 await writeFile(join(bucketDir, repo, "format"), "koh-remote 2");136- await expect(checkFormat(b, repo)).rejects.toThrow('remote format "koh-remote 2"');136+ await checkFormat(b, repo);137+ await writeFile(join(bucketDir, repo, "format"), "koh-remote 3");138+ await expect(checkFormat(b, repo)).rejects.toThrow('remote format "koh-remote 3"');137139 });138140 });139141 @@ -170,6 +172,8 @@170172 downloadUrl: () => "",171173 viewUrl: () => null,172174 put: async () => {},175+ tag: async () => null,176+ putIfTag: async () => false,173177 remove: async () => {},174178 copy: async () => {},175179 removeRenamed: async () => {},@@ -229,6 +233,8 @@229233 downloadUrl: () => "",230234 viewUrl: () => null,231235 put: async () => {},236+ tag: async () => null,237+ putIfTag: async () => false,232238 remove: async () => {},233239 copy: async () => {},234240 removeRenamed: async () => {},@@ -261,6 +267,14 @@261267 await expect(readTampered(dupe)).rejects.toThrow("Koh 3 schema");262268 });263269 270+ test("refuses a record whose manifest is not a manifest hash", async () => {271+ for (const manifest of ["", "../../elsewhere", "A".repeat(64)]) {272+ await expect(readTampered((record) => (record.manifest = manifest))).rejects.toThrow(273+ "Koh 3 schema",274+ );275+ }276+ });277+264278 test("accepts the six-character IDs that Koh 2's early saves keep through migration", async () => {265279 expect((await readTampered((record) => (record.parent = "af96c8"))).parent).toBe("af96c8");266280 });@@ -314,6 +328,8 @@314328 downloadUrl: () => "",315329 viewUrl: () => null,316330 put: async () => {},331+ tag: async () => null,332+ putIfTag: async () => false,317333 remove: async () => {},318334 copy: async () => {},319335 removeRenamed: async () => {},@@ -341,6 +357,8 @@341357 downloadUrl: () => "",342358 viewUrl: () => null,343359 put: async () => {},360+ tag: async () => null,361+ putIfTag: async () => false,344362 remove: async () => {},345363 copy: async () => {},346364 removeRenamed: async () => {},tests/console.test.ts+47 −0
@@ -483,6 +483,53 @@483483 });484484 });485485 486+describe("a publish landing while a build is deleted", () => {487+ let inst: Instance;488+ let bucketDir: string;489+ let save: string;490+ const folder = () => openBucket({ kind: "folder", path: bucketDir });491+ const mirror = () => openMirror(join(inst.dataDir, "mirror"), "app");492+ const latest = () => Bun.file(join(bucketDir, "app/releases/latest")).text();493+ let moves = 0;494+495+ // A `koh offer` of 3.0.0 lands between the delete's read of `latest` and its write, as it can.496+ const publishing = (): Bucket => ({497+ ...folder(),498+ async putIfTag(key, bytes, type, tag) {499+ moves += 1;500+ await writeRelease(bucketDir, "app", {501+ version: "3.0.0",502+ save,503+ files: [{ platform: "linux-x86_64", name: "app", bytes: new Uint8Array([1]) }],504+ });505+ return folder().putIfTag(key, bytes, type, tag);506+ },507+ });508+509+ beforeAll(async () => {510+ const repos = await makeRepos(["app"]);511+ bucketDir = repos.bucketDir;512+ save = repos.saves.app as string;513+ for (const version of ["1.0.0", "2.0.0"]) {514+ await writeRelease(bucketDir, "app", {515+ version,516+ save,517+ files: [{ platform: "linux-x86_64", name: "app", bytes: new Uint8Array([1]) }],518+ });519+ }520+ inst = await instance(bucketDir);521+ });522+523+ test("the published version keeps latest, and the deleted build still goes", async () => {524+ await deleteRelease(publishing(), inst.kepr, mirror(), "app", "2.0.0");525+ expect(await latest()).toBe("3.0.0");526+ expect(await Bun.file(join(bucketDir, "app/releases/3.0.0/release.json")).exists()).toBe(true);527+ expect(await Bun.file(join(bucketDir, "app/releases/2.0.0/release.json")).exists()).toBe(false);528+ // One conditional write was refused; the retry read 3.0.0 and left it alone.529+ expect(moves).toBe(1);530+ });531+});532+486533 describe("site and profile settings, and the signature upload", () => {487534 let inst: Instance;488535 let operator: Browser;tests/fixture.ts+56 −9
@@ -1,3 +1,4 @@1+import { existsSync } from "node:fs";12 import { mkdir, mkdtemp, writeFile } from "node:fs/promises";23 import { tmpdir } from "node:os";34 import { join } from "node:path";@@ -8,18 +9,21 @@89 /**910 * §4.3 of the resolutions: these tests are pinned to one koh, so a stale binary cannot make a pass1011 * 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.1113 */14+export const KOH_BIN = process.env.KOH_BIN ?? "koh";15+1216 const PINNED_KOH = (await Bun.file(join(import.meta.dir, "koh-version.txt")).text()).trim();1317 const RUNNING_KOH = (() => {1418 try {15- return Bun.spawnSync(["koh", "--version"]).stdout.toString().trim();19+ return Bun.spawnSync([KOH_BIN, "--version"]).stdout.toString().trim();1620 } catch {1721 return "";1822 }1923 })();2024 if (RUNNING_KOH !== `koh ${PINNED_KOH}`) {2125 throw new Error(22- `these tests are pinned to koh ${PINNED_KOH}, but koh on PATH reports "${RUNNING_KOH}" — ` +26+ `these tests are pinned to koh ${PINNED_KOH}, but ${KOH_BIN} reports "${RUNNING_KOH}" — ` +2327 "install the matching koh (see koh's AGENTS.md), or update tests/koh-version.txt " +2428 "once you have verified the new one",2529 );@@ -29,6 +33,8 @@2933 bucketDir: string;3034 repo: string;3135 repoDir: string;36+ /** The remote layout the fixture's bucket came out as (§9.2). */37+ format: 1 | 2;3238 /** Every save, newest first, checkpoint included. */3339 saveIds: string[];3440 /** Strips a path from every save with koh, so tests can sync before and after. */@@ -62,8 +68,15 @@6268 * Builds a genuine Koh 3 folder remote with koh itself, under a throwaway HOME. The line is:6369 * "add docs, a secret and a deep helper" (flagged) → a second later "add readme and entry point"6470 * (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.6575 */66-export async function makeKohBucket(repo = "demo"): Promise<Fixture> {76+export async function makeKohBucket(77+ repo = "demo",78+ options: { format?: 1 | 2; bin?: string } = {},79+): Promise<Fixture> {6780 const root = await mkdtemp(join(tmpdir(), "kepr-fixture-"));6881 const home = join(root, "home");6982 const bucketDir = join(root, "bucket");@@ -72,10 +85,14 @@7285 await mkdir(join(repoDir, "src/lib/deep"), { recursive: true });7386 await mkdir(join(repoDir, "docs"));7487 await mkdir(join(repoDir, "vendor"));75- const koh = (...args: string[]) => run(repoDir, home, args);88+ const koh = (...args: string[]) => run(repoDir, home, args, options.bin);7689 7790 koh("init");7891 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+ }7996 await writeFile(join(repoDir, "docs/guide.md"), "# Guide\n\nRead me.\n");8097 await writeFile(join(repoDir, "docs/logo.png"), PNG);8198 await writeFile(join(repoDir, "secret.txt"), "hunter2\n");@@ -100,17 +117,42 @@100117 koh("offer");101118 102119 const log = JSON.parse(koh("view", "--json")) as { saves: { id: string }[] };120+ const format = (await Bun.file(join(bucketDir, repo, "format")).text()).trim();103121 return {104122 bucketDir,105123 repo,106124 repoDir,125+ format: format === "koh-remote 2" ? 2 : 1,107126 saveIds: log.saves.map((save) => save.id),108- strip: (path) => stripPath(repoDir, home, path),127+ strip: (path) => stripPath(repoDir, home, path, options.bin),109128 };110129 }111130 112-function run(cwd: string, home: string, args: string[]): string {113- const result = Bun.spawnSync(["koh", ...args], { cwd, env: env(home) });131+/**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+ */135+export 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+}153+154+function run(cwd: string, home: string, args: string[], bin = KOH_BIN): string {155+ const result = Bun.spawnSync([bin, ...args], { cwd, env: env(home) });114156 if (result.exitCode !== 0) {115157 throw new Error(116158 `koh ${args.join(" ")} failed: ${result.stderr.toString()}${result.stdout.toString()}`,@@ -124,9 +166,14 @@124166 }125167 126168 /** `koh strip` insists on a terminal and a typed confirmation, so it runs under a Bun PTY. */127-export async function stripPath(cwd: string, home: string, path: string): Promise<void> {169+export async function stripPath(170+ cwd: string,171+ home: string,172+ path: string,173+ bin = KOH_BIN,174+): Promise<void> {128175 let output = "";129- const proc = Bun.spawn(["koh", "strip", path], {176+ const proc = Bun.spawn([bin, "strip", path], {130177 cwd,131178 env: env(home),132179 terminal: { cols: 120, rows: 24, data: (_term, data) => (output += data.toString()) },tests/hidden.test.ts+5 −6
@@ -6,6 +6,7 @@66 import { join } from "node:path";77 import { openBucket } from "../src/bucket/reader.ts";88 import { syncAll } from "../src/bucket/sync.ts";9+import { fileAt, filesAt, headId, timeline } from "../src/mirror/queries.ts";910 import { openMirror } from "../src/mirror/store.ts";1011 import { Browser, type Instance, instance } from "./browser.ts";1112 import { makeRepos } from "./fixture.ts";@@ -133,9 +134,9 @@133134 134135 test("a hidden file's object is neither listed nor served on the Koh routes", async () => {135136 const mirror = openMirror(join(inst.dataDir, "mirror"), "app");136- const hash = mirror137- .query<{ hash: string }, []>("SELECT hash FROM save_files WHERE path = 'private/notes.md'")138- .get()?.hash as string;137+ const hash = filesAt(mirror, headId(mirror) as string).find(138+ (file) => file.path === "private/notes.md",139+ )?.hash as string;139140 await hide("private");140141 expect(await text("/app/koh/objects")).not.toContain(hash);141142 expect(await status(`/app/koh/objects/${hash}`)).toBe(404);@@ -147,9 +148,7 @@147148 test("rebuilding a mirror keeps handles that requests already hold usable", async () => {148149 const mirror = openMirror(join(inst.dataDir, "mirror"), "app");149150 const count = () =>150- mirror151- .query<{ n: number }, []>("SELECT COUNT(*) AS n FROM save_files WHERE path = 'tool.py'")152- .get()?.n;151+ timeline(mirror).filter((save) => fileAt(mirror, save.id, "tool.py") !== null).length;153152 await hide("tool.py");154153 expect(count()).toBe(0);155154 await hide("");tests/kohpaths.test.ts+48 −7
@@ -5,9 +5,11 @@55 import { dirname, join } from "node:path";66 import { openBucket } from "../src/bucket/reader.ts";77 import { syncAll } from "../src/bucket/sync.ts";8+import { flattenTree } from "../src/mirror/manifest.ts";9+import { filesAt } from "../src/mirror/queries.ts";810 import { openMirror, quarantinedPaths } from "../src/mirror/store.ts";911 import { openKeprDb } from "../src/server/db.ts";10-import { makeKohBucket } from "./fixture.ts";12+import { KOH_BIN, makeKohBucket } from "./fixture.ts";1113 1214 // §5.5 is a contract between the repos: every path either side drops, the other drops too.1315 const UNSAFE = [@@ -48,7 +50,7 @@4850 await mkdir(home);4951 await mkdir(work);5052 const runKoh = (cwd: string, args: string[]) =>51- Bun.spawnSync(["koh", ...args], {53+ Bun.spawnSync([KOH_BIN, ...args], {5254 cwd,5355 env: { PATH: process.env.PATH, HOME: home, NO_COLOR: "1" },5456 });@@ -66,17 +68,56 @@6668 });6769 expect(kepr.query("SELECT last_sync_error FROM repos").get()).toEqual({ last_sync_error: null });6870 69- const fileLists = (db: Database) =>70- db.query("SELECT save_id, path FROM save_files ORDER BY save_id, path").all();71+ // Koh's own store is version 1 (`save_files`) or version 2 (manifest trees); Kepr's mirror72+ // keeps trees either way, so its side is flattened through the same reader.73+ const sorted = (rows: { save_id: string; path: string }[]) =>74+ rows.sort((a, b) =>75+ a.save_id === b.save_id ? (a.path < b.path ? -1 : 1) : a.save_id < b.save_id ? -1 : 1,76+ );77+ const kohFiles = (db: Database) => {78+ if (db.query("SELECT 1 FROM sqlite_schema WHERE name = 'save_files'").get()) {79+ return sorted(80+ db81+ .query<{ save_id: string; path: string }, []>("SELECT save_id, path FROM save_files")82+ .all(),83+ );84+ }85+ const bodies = new Map(86+ db87+ .query<{ hash: string; body: string }, []>("SELECT hash, body FROM manifests")88+ .all()89+ .map((row) => [row.hash, row.body] as const),90+ );91+ return sorted(92+ db93+ .query<{ id: string; manifest: string }, []>("SELECT id, manifest FROM saves")94+ .all()95+ .flatMap((save) =>96+ flattenTree((hash) => bodies.get(hash) as string, save.manifest).map((file) => ({97+ save_id: save.id,98+ path: file.path,99+ })),100+ ),101+ );102+ };103+ const mirrorFiles = (db: Database) =>104+ sorted(105+ db106+ .query<{ id: string }, []>("SELECT id FROM saves")107+ .all()108+ .flatMap((save) =>109+ filesAt(db, save.id).map((file) => ({ save_id: save.id, path: file.path })),110+ ),111+ );71112 const koh = new Database(join(work, fx.repo, ".koh"));72113 const mirror = openMirror(join(dataDir, "mirror"), fx.repo);73- expect(fileLists(koh)).toEqual(fileLists(mirror));74- expect(fileLists(koh)).toContainEqual({ save_id: head, path: "src/main.ts" });114+ expect(kohFiles(koh)).toEqual(mirrorFiles(mirror));115+ expect(kohFiles(koh)).toContainEqual({ save_id: head, path: "src/main.ts" });75116 // Same verdict and the same escaped name on both sides, name for name.76117 expect(dropped.length).toBe(UNSAFE.length);77118 expect([...dropped].sort()).toEqual(quarantinedPaths(mirror));78119 for (const path of UNSAFE) {79- expect(fileLists(koh)).not.toContainEqual({ save_id: head, path });120+ expect(kohFiles(koh)).not.toContainEqual({ save_id: head, path });80121 }81122 koh.close();82123 tests/pages.test.ts+4 −4
@@ -11,7 +11,7 @@1111 import { timelineSaves, timelineSvg } from "../src/pages/timeline.ts";1212 import { createApp } from "../src/server/app.ts";1313 import { openKeprDb } from "../src/server/db.ts";14-import { type Fixture, makeKohBucket } from "./fixture.ts";14+import { type Fixture, KOH_BIN, makeKohBucket } from "./fixture.ts";1515 1616 let fx: Fixture;1717 let app: Hono;@@ -36,7 +36,7 @@3636 `${"a".repeat(1024 * 1024 - 1)}é${"b".repeat(1000)}\n`,3737 );3838 await writeFile(join(large.repoDir, "big.bin"), new Uint8Array(1024 * 1024 + 500).fill(0xff));39- Bun.spawnSync(["koh", "save", "add large files"], {39+ Bun.spawnSync([KOH_BIN, "save", "add large files"], {4040 cwd: large.repoDir,4141 env: { PATH: process.env.PATH, HOME: join(large.repoDir, "../../home"), NO_COLOR: "1" },4242 });@@ -49,10 +49,10 @@4949 ["a\nb", "drop the newline"],5050 ] as const) {5151 await writeFile(join(tail.repoDir, "tail.txt"), text);52- Bun.spawnSync(["koh", "save", message], { cwd: tail.repoDir, env: tailEnv });52+ Bun.spawnSync([KOH_BIN, "save", message], { cwd: tail.repoDir, env: tailEnv });5353 }5454 tailSaves = JSON.parse(55- Bun.spawnSync(["koh", "view", "--json"], {55+ Bun.spawnSync([KOH_BIN, "view", "--json"], {5656 cwd: tail.repoDir,5757 env: tailEnv,5858 }).stdout.toString(),tests/sync.test.ts+141 −76
@@ -7,6 +7,7 @@77 import { type Bucket, openBucket } from "../src/bucket/reader.ts";88 import { readSave } from "../src/bucket/repo.ts";99 import { syncAll, syncRepo } from "../src/bucket/sync.ts";10+import { manifestTree } from "../src/mirror/manifest.ts";1011 import {1112 fileAt,1213 filesAt,@@ -21,7 +22,7 @@2122 import { applyHidden, closeMirror, mirrorState, openMirror } from "../src/mirror/store.ts";2223 import { openKeprDb } from "../src/server/db.ts";2324 import { Browser, instance } from "./browser.ts";24-import { type Fixture, makeKohBucket } from "./fixture.ts";25+import { type Fixture, KOH_BIN, makeKohBucket, writesFormat2 } from "./fixture.ts";2526 2627 const text = (bytes: Uint8Array | null) => new TextDecoder().decode(bytes ?? new Uint8Array());2728 @@ -146,11 +147,15 @@146147 147148 test("a whole six-character ID finds its own save, not a longer one it begins", async () => {148149 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);149154 const add = mirror.query(150- "INSERT INTO saves (id, parent, message, created_at, machine) VALUES (?, NULL, ?, 1, 'm')",155+ "INSERT INTO saves (id, parent, manifest, message, created_at, machine) VALUES (?, NULL, ?, ?, 1, 'm')",151156 );152- add.run("af96c8", "migrated from Koh 2");153- add.run("af96c8123456", "made by Koh 3");157+ add.run("af96c8", empty.root, "migrated from Koh 2");158+ add.run("af96c8123456", empty.root, "made by Koh 3");154159 expect(saveByPrefix(mirror, "af96c8")?.message).toBe("migrated from Koh 2");155160 expect(saveByPrefix(mirror, "af96c81")?.message).toBe("made by Koh 3");156161 });@@ -281,14 +286,14 @@281286 const t = await syncTarget(fx);282287 await syncAll(t);283288 await writeFile(join(fx.repoDir, "new.txt"), "new\n");284- Bun.spawnSync(["koh", "save", "add new"], {289+ Bun.spawnSync([KOH_BIN, "save", "add new"], {285290 cwd: fx.repoDir,286291 env: { PATH: process.env.PATH, HOME: join(fx.repoDir, "../../home"), NO_COLOR: "1" },287292 });288293 await syncAll(t);289294 expect(history(t.mirror(), 1, 0)[0]?.message).toBe("add new");290295 291- await writeFile(join(fx.bucketDir, fx.repo, "format"), "koh-remote 2");296+ await writeFile(join(fx.bucketDir, fx.repo, "format"), "koh-remote 3");292297 // koh writes `format` only when it offers, which moves the head; a head at rest keeps the293298 // format the sync already checked.294299 await writeFile(join(fx.bucketDir, fx.repo, "head"), fx.saveIds[1] as string);@@ -296,7 +301,7 @@296301 const row = t.kepr.query("SELECT last_sync_error FROM repos").get() as {297302 last_sync_error: string;298303 };299- expect(row.last_sync_error).toContain('remote format "koh-remote 2"');304+ expect(row.last_sync_error).toContain('remote format "koh-remote 3"');300305 });301306 302307 test("a whole-history strip reaches every save, those arriving after it too, whatever their time (§10.2)", async () => {@@ -335,106 +340,166 @@335340 });336341 337342 describe("the mirror's schema version", () => {338- test("a version 4 mirror reopens and any other version is refused as disposable", async () => {343+ test("a current mirror reopens, and one of another schema is rebuilt empty", async () => {339344 const dir = await mkdtemp(join(tmpdir(), "kepr-mirror-"));340345 const created = openMirror(dir, "one");341346 created.run("PRAGMA wal_checkpoint(TRUNCATE)");342347 await Bun.write(join(dir, "copy.db"), Bun.file(join(dir, "one.db")));343348 expect(openMirror(dir, "copy").query("PRAGMA user_version").get()).toEqual({344- user_version: 4,349+ user_version: 5,345350 });346351 347- for (const version of [1, 5]) {348- const other = new Database(join(dir, `v${version}.db`));349- other.run(`PRAGMA user_version = ${version}`);350- other.close();351- expect(() => openMirror(dir, `v${version}`)).toThrow("disposable");352+ // Mirrors are disposable: an older or newer one is emptied at open and rebuilt from the353+ // bucket, never refused, so a schema change costs one sync rather than an operator's work.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();352364 }353365 });354366 355- test("a version 2 mirror moves to 4 in place, emptied only when it deleted hidden rows", async () => {356- const dir = await mkdtemp(join(tmpdir(), "kepr-mirror-"));357- for (const [name, hidden] of [358- ["plain", ""],359- ["hiding", "secret.txt"],360- ] as const) {361- const db = openMirror(dir, name);362- for (const table of ["hidden_files", "touches", "facts", "known_objects"]) {363- db.run(`DROP TABLE ${table}`);364- }365- db.run("PRAGMA user_version = 2");366- db.query("INSERT INTO state (key, value) VALUES ('head', 'abcdef123456'), ('hidden', ?)").run(367- hidden,368- );369- closeMirror(dir, name);370- }371- const head = (name: string) => mirrorState(openMirror(dir, name), "head");372- expect(head("plain")).toBe("abcdef123456");373- expect(head("hiding")).toBeNull();374- for (const name of ["plain", "hiding"]) {375- const db = openMirror(dir, name);376- expect(db.query("PRAGMA user_version").get()).toEqual({ user_version: 4 });377- expect(db.query("SELECT COUNT(*) AS n FROM hidden_files").get()).toEqual({ n: 0 });378- }367+ 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+ // What a mirror made by the previous Kepr looks like: the same file under an older number.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+ // The next sync lands it all again.379+ await syncAll(t);380+ expect(headId(t.mirror())).toBe(fx.saveIds[0] as string);381+ expect(history(t.mirror(), 10, 0)).toHaveLength(3);379382 });380383 381- test("touches recorded save by save match touches worked out all at once", async () => {384+ test("touches and facts recorded save by save match a mirror synced in one go", async () => {382385 const fx = await makeKohBucket("stepwise");383386 const t = await syncTarget(fx);384387 await syncAll(t);385388 await writeFile(join(fx.repoDir, "src/main.ts"), "// Entry point.\nconsole.log('again');\n");386389 await writeFile(join(fx.repoDir, "added.txt"), "new\n");387- Bun.spawnSync(["koh", "save", "change main, add a file"], {390+ Bun.spawnSync([KOH_BIN, "save", "change main, add a file"], {388391 cwd: fx.repoDir,389392 env: { PATH: process.env.PATH, HOME: join(fx.repoDir, "../../home"), NO_COLOR: "1" },390393 });391- Bun.spawnSync(["koh", "offer"], {394+ Bun.spawnSync([KOH_BIN, "offer"], {392395 cwd: fx.repoDir,393396 env: { PATH: process.env.PATH, HOME: join(fx.repoDir, "../../home"), NO_COLOR: "1" },394397 });395398 await syncAll(t);396- const touches = () => t.mirror().query("SELECT path, n FROM touches ORDER BY n, path").all();397- const stepwise = touches();398- expect(stepwise).toContainEqual(expect.objectContaining({ path: "added.txt" }));399- // Reopened as version 3, the mirror works every save's touches out again in one go.400- for (const table of ["touches", "facts", "known_objects"]) {401- t.mirror().run(`DROP TABLE ${table}`);402- }403- t.mirror().run("PRAGMA user_version = 3");404- closeMirror(t.mirrorDir, fx.repo);405- expect(touches()).toEqual(stepwise);399+400+ // A second mirror of the same bucket works everything out in one landing.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));406411 });407412 408413 test("a recount cut short is done when the mirror next opens", async () => {409414 const fx = await makeKohBucket("recount");410415 const t = await syncTarget(fx);411416 await syncAll(t);412- const known = () => t.mirror().query("SELECT COUNT(*) AS n FROM known_objects").get();413- const counted = known();417+ const counted = repoStats(t.mirror()).lines;418+ expect(counted).toBeGreaterThan(0);414419 // What a landing leaves if Kepr stops before its recount commits.415- t.mirror().run("DELETE FROM known_objects");420+ t.mirror().query("INSERT OR REPLACE INTO state (key, value) VALUES ('lines', '0')").run();416421 t.mirror().run("DELETE FROM state WHERE key = 'stats_rule'");417422 closeMirror(t.mirrorDir, fx.repo);418- expect(known()).toEqual(counted);423+ expect(repoStats(t.mirror()).lines).toBe(counted);419424 });425+});420426 421- test("a version 3 mirror gains the touches and facts a sync would have recorded", async () => {422- const fx = await makeKohBucket("derived");423- const t = await syncTarget(fx);424- await syncAll(t);425- const derived = () => [426- t.mirror().query("SELECT path, n FROM touches ORDER BY n, path").all(),427- t.mirror().query("SELECT * FROM facts ORDER BY path").all(),428- ];429- const recorded = derived();430- expect((recorded[0] as unknown[]).length).toBeGreaterThan(0);431- for (const table of ["touches", "facts", "known_objects"]) {432- t.mirror().run(`DROP TABLE ${table}`);433- }434- t.mirror().run("PRAGMA user_version = 3");435- closeMirror(t.mirrorDir, fx.repo);436- expect(derived()).toEqual(recorded);437- });427+// The suite's fixture is pinned to format 1; a format-2 repo needs the koh that writes trees. Its428+// build ships beside this repo, and `KOH_BIN` names another one.429+const KOH_V2 = process.env.KOH_BIN ?? join(import.meta.dir, "..", "..", "koh", "build", "koh3");430+const FORMAT_2 = await writesFormat2(KOH_V2);431+if (!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+}437+438+describe.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;448+449+ // What Koh saved is the working tree's tracked files; the mirror shows the same list.450+ // A dotfile glob leaves out `.kohignore`, and `LOG.md` is regenerated, never saved (§5.3).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");458+459+ // Every save names a stored tree, and the served record is still the flat one Koh reads.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);477+478+ // Nothing new: a second sync reads no object and no manifest.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);490+491+ // A strip arrives as an event: the path goes, and no tree is rewritten.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+ );438503 });439504 440505 test("a strip that arrives older than the saves already mirrored still strips them (§10.2, R6)", async () => {@@ -484,8 +549,8 @@484549 485550 await writeFile(join(fx.repoDir, "later.txt"), "later\n");486551 const env = { PATH: process.env.PATH, HOME: join(fx.repoDir, "../../home"), NO_COLOR: "1" };487- Bun.spawnSync(["koh", "save", "a later save"], { cwd: fx.repoDir, env });488- Bun.spawnSync(["koh", "offer"], { cwd: fx.repoDir, env });552+ Bun.spawnSync([KOH_BIN, "save", "a later save"], { cwd: fx.repoDir, env });553+ Bun.spawnSync([KOH_BIN, "offer"], { cwd: fx.repoDir, env });489554 await syncAll({490555 bucket: openBucket({ kind: "folder", path: fx.bucketDir }),491556 kepr: inst.kepr,@@ -547,8 +612,8 @@547612 const before = repoStats(t.mirror()).lines;548613 await writeFile(join(fx.repoDir, "big.txt"), "x\n".repeat(4.5 * 1024 * 1024));549614 const env = { PATH: process.env.PATH, HOME: join(fx.repoDir, "../../home"), NO_COLOR: "1" };550- Bun.spawnSync(["koh", "save", "add a big text file"], { cwd: fx.repoDir, env });551- Bun.spawnSync(["koh", "offer"], { cwd: fx.repoDir, env });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 });552617 await syncAll(t);553618 expect(history(t.mirror(), 1, 0)[0]?.message).toBe("add a big text file");554619 expect(repoStats(t.mirror()).lines).toBe(before);tests/tarball.test.ts+3 −3
@@ -11,7 +11,7 @@1111 import { openKeprDb } from "../src/server/db.ts";1212 import { cachedTarball } from "../src/tarball/cache.ts";1313 import { buildTarball, isStripped } from "../src/tarball/tar.ts";14-import { type Fixture, makeKohBucket } from "./fixture.ts";14+import { type Fixture, KOH_BIN, makeKohBucket } from "./fixture.ts";1515 1616 let fx: Fixture;1717 let app: Hono;@@ -53,9 +53,9 @@5353 await chmod(join(fx.repoDir, "run.sh"), 0o755);5454 const home = join(fx.repoDir, "../../home");5555 const env = { PATH: process.env.PATH, HOME: home, NO_COLOR: "1" };56- const save = Bun.spawnSync(["koh", "save", "add build files"], { cwd: fx.repoDir, env });56+ const save = Bun.spawnSync([KOH_BIN, "save", "add build files"], { cwd: fx.repoDir, env });5757 expect(save.exitCode).toBe(0);58- const log = Bun.spawnSync(["koh", "view", "--json"], { cwd: fx.repoDir, env });58+ const log = Bun.spawnSync([KOH_BIN, "view", "--json"], { cwd: fx.repoDir, env });5959 head = JSON.parse(log.stdout.toString()).head_id;6060 dataDir = await mkdtemp(join(tmpdir(), "kepr-tarball-"));6161 const kepr = openKeprDb(dataDir);