import { Database } from "bun:sqlite"; import { existsSync, mkdirSync, readdirSync } from "node:fs"; import { join } from "node:path"; import { inflateSync } from "node:zlib"; import type { EventRecord, ReleaseRecord, SaveRecord } from "../bucket/repo.ts"; import { fileFacts } from "../describe/describe.ts"; import { isTestPath } from "../describe/links.ts"; import { declaredVersion } from "../describe/version.ts"; import { hashBody, manifestBody, manifestTree } from "./manifest.ts"; import { fileAt, filesAt, storedFilesAt } from "./queries.ts"; // Koh 3's schema (§5.1, `src/storage/storage.v`) minus `file_cache`, which only a working tree needs, // plus `releases`: each version's release.json (§11.2) as read from the bucket, since that is bucket // data too and pages and feeds need it on every request, and what the Atlas reads. const SCHEMA_VERSION = 5; // What pages read, worked out as each save lands rather than on every view (2026-10-02): which // real saves touched each path (added, changed or removed against the real save before; `n` is the // touching save's rowid), what each file says about itself, and the objects real saves refer to. const SCHEMA = ` CREATE TABLE objects ( hash TEXT PRIMARY KEY, size INTEGER NOT NULL, data BLOB NOT NULL ); CREATE TABLE saves ( id TEXT PRIMARY KEY, parent TEXT REFERENCES saves(id), manifest TEXT NOT NULL, message TEXT NOT NULL, created_at INTEGER NOT NULL, machine TEXT NOT NULL, is_checkpoint INTEGER NOT NULL DEFAULT 0, size_bytes INTEGER NOT NULL DEFAULT 0, agent TEXT, session TEXT, restores TEXT, replayed_from TEXT ); CREATE TABLE manifests ( hash TEXT PRIMARY KEY, body TEXT NOT NULL ) WITHOUT ROWID; CREATE TABLE events ( id TEXT PRIMARY KEY, kind TEXT NOT NULL, save_id TEXT, path TEXT, reason TEXT, created_at INTEGER NOT NULL, machine TEXT NOT NULL ); CREATE TABLE state ( key TEXT PRIMARY KEY, value TEXT NOT NULL ); CREATE TABLE releases ( version TEXT PRIMARY KEY, record TEXT NOT NULL ); CREATE TABLE known_objects (hash TEXT PRIMARY KEY) WITHOUT ROWID; CREATE TABLE touches ( path TEXT NOT NULL, n INTEGER NOT NULL ); CREATE INDEX touches_n ON touches(n); CREATE INDEX touches_path ON touches(path, n); CREATE TABLE facts ( hash TEXT NOT NULL, path TEXT NOT NULL, lines INTEGER, description TEXT, outline TEXT, PRIMARY KEY (hash, path) ); CREATE INDEX saves_parent ON saves(parent); `; /** * Creates a mirror, or rebuilds a disposable one: a mirror of another schema is emptied and the * next sync lands the repo again. Run under the write lock, since the request thread and the * sync's both open mirrors and must not both create or rebuild one. */ function upgrade(db: Database): void { db.transaction(() => { if (schemaVersion(db) !== 0) { for (const { name } of db .query<{ name: string }, []>( "SELECT name FROM sqlite_schema WHERE type = 'table' AND name NOT LIKE 'sqlite_%'", ) .all()) { db.run(`DROP TABLE "${name.replaceAll('"', '""')}"`); } } db.run(SCHEMA); // A new epoch keeps tarballs made before the rebuild from ever being looked up again. db.query("INSERT OR IGNORE INTO state (key, value) VALUES ('epoch', ?)").run( crypto.randomUUID(), ); db.run(`PRAGMA user_version = ${SCHEMA_VERSION}`); }).immediate(); } /** An object as the bucket stores it: zlib bytes, already checked against its hash. */ export type StoredObject = { compressed: Uint8Array; size: number }; /** One batch of a sync, landed in one transaction. Saves are oldest first. */ export type Landing = { head: string; releasesLatest: string; saves: SaveRecord[]; /** Folder bodies the saves' trees name, as fetched from the bucket (§9.2, format 2). */ manifests: Map; objects: Map; events: EventRecord[]; releases: ReleaseRecord[]; /** Escaped names of the paths these saves arrived without (§5.5, A3). */ quarantined: string[]; }; /** Marks a hidden entry as a name matched at any depth rather than a path from the root. */ export const ANY_DEPTH = "**/"; // No project declares its version in a file larger than this. const MAX_MANIFEST = 1024 * 1024; // A recount inflates every file at the newest save; a file this large is data, not lines of code. const MAX_COUNTED = 8 * 1024 * 1024; // Display names for the header's language, by extension; data and docs formats never count. const LANGUAGES: Record = { ts: "TypeScript", tsx: "TypeScript", js: "JavaScript", mjs: "JavaScript", zig: "Zig", v: "V", rs: "Rust", go: "Go", py: "Python", c: "C", h: "C", cpp: "C++", cc: "C++", hpp: "C++", swift: "Swift", kt: "Kotlin", java: "Java", rb: "Ruby", lua: "Lua", sh: "Shell", nix: "Nix", css: "CSS", html: "HTML", }; // Vendored code is someone else's: counting Koh 3's bundled SQLite made it read as 290k lines of C. const VENDORED = /(^|\/)(vendor|third_party|node_modules)\//; // Bumped when what the recount records changes, so every mirror recounts once when it opens. const STATS_RULE = "source-only, known objects, declared version (ASCII whitespace, BOM)"; const open = new Map(); /** Closes a repo's mirror, so a rename can move its file. */ export function closeMirror(dir: string, repo: string): void { const path = join(dir, `${repo}.db`); open.get(path)?.close(); open.delete(path); } /** * Opens every mirror in `dir`, bringing each to this Kepr's schema: run at start, before Kepr * listens, so no request waits on a migration. */ export function openMirrors(dir: string): void { if (!existsSync(dir)) return; for (const name of readdirSync(dir)) if (name.endsWith(".db")) openMirror(dir, name.slice(0, -3)); } /** Closes every mirror this thread holds open; the next use of each opens it again. */ export function closeMirrors(): void { for (const db of open.values()) db.close(); open.clear(); } /** The mirror of one repo at `/.db`, created on first use and kept open. */ export function openMirror(dir: string, repo: string): Database { const path = join(dir, `${repo}.db`); const cached = open.get(path); if (cached) return cached; mkdirSync(dir, { recursive: true }); const db = new Database(path, { strict: true }); db.run("PRAGMA journal_mode = WAL"); db.run("PRAGMA busy_timeout = 5000"); // A current mirror needs no lock; only creating or rebuilding one takes the write lock. if (schemaVersion(db) !== SCHEMA_VERSION) upgrade(db); // Only now: a rebuild drops tables other rows still reference, which foreign keys would refuse. db.run("PRAGMA foreign_keys = ON"); // Mirrors counted under an older rule are recounted now, not at the next save. if (mirrorState(db, "head") && mirrorState(db, "stats_rule") !== STATS_RULE) refreshStats(db); open.set(path, db); return db; } function schemaVersion(db: Database): number { return db.query<{ user_version: number }, []>("PRAGMA user_version").get()?.user_version ?? 0; } export function mirrorState(db: Database, key: string): string | null { const row = db .query<{ value: string }, [string]>("SELECT value FROM state WHERE key = ?") .get(key); return row?.value ?? null; } export function knownSave(db: Database, id: string): boolean { return db.query("SELECT 1 FROM saves WHERE id = ?").get(id) !== null; } export function knownObject(db: Database, hash: string): boolean { return db.query("SELECT 1 FROM objects WHERE hash = ?").get(hash) !== null; } /** Whether a save's tree can be flattened without fetching anything. */ export function knownManifest(db: Database, hash: string): boolean { return db.query("SELECT 1 FROM manifests WHERE hash = ?").get(hash) !== null; } export function knownEventIds(db: Database): Set { const rows = db.query<{ id: string }, []>("SELECT id FROM events").all(); return new Set(rows.map((row) => row.id)); } /** Drops a version deleted from the bucket; a sync only ever adds releases. */ export function forgetRelease(db: Database, version: string): void { db.query("DELETE FROM releases WHERE version = ?").run(version); } /** Replaces a version's record after Kepr rewrote it in the bucket. */ export function replaceRelease(db: Database, record: ReleaseRecord): void { db.query("UPDATE releases SET record = ? WHERE version = ?").run( JSON.stringify(record), record.version, ); } export function knownReleases(db: Database): Set { const rows = db.query<{ version: string }, []>("SELECT version FROM releases").all(); return new Set(rows.map((row) => row.version)); } /** Stores objects on their own, ahead of the save that refers to them. */ export function storeObjects(db: Database, objects: Map): void { const put = db.query("INSERT OR IGNORE INTO objects (hash, size, data) VALUES (?, ?, ?)"); db.transaction(() => { for (const [hash, object] of objects) put.run(hash, object.size, object.compressed); })(); } /** Stores folder manifests on their own, ahead of the save that names them. */ export function storeManifests(db: Database, manifests: Map): void { const put = db.query("INSERT OR IGNORE INTO manifests (hash, body) VALUES (?, ?)"); db.transaction(() => { for (const [hash, body] of manifests) { if (hashBody(body) !== hash) throw new Error(`manifest ${hash} does not match its body`); put.run(hash, body); } })(); } /** * Lands a sync like Koh's steal: objects, events, manifests, saves, then the strips the batch * names. A version-2 save keeps the tree the bucket fetched; a version-1 record is converted once, * so every later read is the same. Trees are never rewritten: a strip is read-time, which is why a * strip landing walks the saves once (for touches and unreferenced objects) and no other landing does. */ export function land(db: Database, landing: Landing): void { const putEvent = db.query( "INSERT OR IGNORE INTO events (id, kind, save_id, path, reason, created_at, machine) VALUES " + "(?, ?, ?, ?, ?, ?, ?)", ); const putSave = db.query( `INSERT OR IGNORE INTO saves (id, parent, manifest, message, created_at, machine, is_checkpoint, size_bytes, agent, session, restores, replayed_from) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, ); const putManifest = db.query("INSERT OR IGNORE INTO manifests (hash, body) VALUES (?, ?)"); const putRelease = db.query("INSERT OR IGNORE INTO releases (version, record) VALUES (?, ?)"); const setState = db.query("INSERT OR REPLACE INTO state (key, value) VALUES (?, ?)"); const sizeOf = db.query<{ size: number }, [string]>("SELECT size FROM objects WHERE hash = ?"); const stripped = landing.events.some((event) => event.kind === "strip"); // Immediate: a landing with nothing new reads before it writes, and the request thread writes // mirrors too (a deleted release). db.transaction(() => { storeObjects(db, landing.objects); for (const e of landing.events) { putEvent.run(e.id, e.kind, e.save_id, e.path, e.reason, e.created_at, e.machine); } storeManifests(db, landing.manifests); for (const s of landing.saves) { let root = s.manifest ?? ""; if (root === "") { const tree = manifestTree(s.files, (hash) => sizeOf.get(hash)?.size ?? null); for (const [hash, body] of tree.bodies) putManifest.run(hash, body); root = tree.root; } else if (manifestBody(db, root) === null) { throw new Error(`save ${s.id} names manifest ${root}, which did not land`); } putSave.run( s.id, s.parent === "" ? null : s.parent, root, s.message, s.created_at, s.machine, s.is_checkpoint ? 1 : 0, s.size_bytes, s.agent, s.session, s.restores, s.replayed_from, ); } const landed = landing.saves.map((save) => save.id); for (const r of landing.releases) putRelease.run(r.version, JSON.stringify(r)); if (stripped) dropStripped(db); else addKnownObjects(db, landing.saves); // A strip can reach any save, so every save's touches are worked out again after one. recordTouches(db, stripped ? 0 : Number(mirrorState(db, "touches_to") ?? 0)); recordFacts(db, landed); setState.run("head", landing.head); setState.run("releases_latest", landing.releasesLatest); const quarantined = new Set([...quarantinedPaths(db), ...landing.quarantined]); setState.run("quarantined", JSON.stringify([...quarantined].sort())); const newest = newestRealSave(db); if (stripped || newest !== mirrorState(db, "stats_save")) staleStats(db); }).immediate(); // Outside the transaction: the recount can inflate megabytes and needs no lock to be correct. if (mirrorState(db, "stats_rule") !== STATS_RULE) refreshStats(db); } /** * Makes `hidden` the mirror's hidden list: the operator's hidden paths (June, 2026-09-30) and the * names ignored in every repo (June, 2026-10-01), each as `ANY_DEPTH` + name. Trees are never * rewritten, so the list lands at once and takes effect on the next read. */ export function applyHidden(db: Database, hidden: string[]): void { if (hiddenList(db).join("\n") === hidden.join("\n")) return; db.transaction(() => { db.query("INSERT OR REPLACE INTO state (key, value) VALUES ('hidden', ?)").run( hidden.join("\n"), ); recordTouches(db, 0); recordFacts(db, null); rebuildKnownObjects(db); staleStats(db); })(); refreshStats(db); } // Marks the counts out of date in the change's own transaction: if Kepr stops before the recount // that follows, the mirror's next open does it. function staleStats(db: Database): void { db.run("DELETE FROM state WHERE key = 'stats_rule'"); } function newestRealSave(db: Database): string { return ( db .query<{ id: string }, []>( "SELECT id FROM saves WHERE is_checkpoint = 0 ORDER BY rowid DESC LIMIT 1", ) .get()?.id ?? "" ); } /** * Records which real saves touched each path, for the saves after rowid `from`; 0 starts again. * A save touched a path when it was added, changed or removed against the real save before it; * checkpoints are skipped, so a change first recorded by a checkpoint counts at the next real save. */ function recordTouches(db: Database, from: number): void { if (from === 0) db.run("DELETE FROM touches"); const previous = new Map(); const seed = from === 0 ? undefined : db .query<{ id: string }, [number]>( `SELECT id FROM saves WHERE is_checkpoint = 0 AND rowid <= ? ORDER BY rowid DESC LIMIT 1`, ) .get(from)?.id; if (seed !== undefined) { for (const file of filesAt(db, seed)) previous.set(file.path, file); } const put = db.query("INSERT INTO touches (path, n) VALUES (?, ?)"); const line = db .query<{ id: string; n: number }, [number]>( `SELECT id, rowid AS n FROM saves WHERE is_checkpoint = 0 AND rowid > ? ORDER BY rowid`, ) .all(from); for (const save of line) { const current = new Map(filesAt(db, save.id).map((file) => [file.path, file])); for (const [path, file] of current) { const before = previous.get(path); if (!before || before.hash !== file.hash || before.executable !== file.executable) { put.run(path, save.n); } } for (const path of previous.keys()) if (!current.has(path)) put.run(path, save.n); previous.clear(); for (const [path, file] of current) previous.set(path, file); } const last = db.query<{ n: number | null }, []>("SELECT MAX(rowid) AS n FROM saves").get()?.n; db.query("INSERT OR REPLACE INTO state (key, value) VALUES ('touches_to', ?)").run( String(last ?? 0), ); } /** * Records what each file of the given saves (or, with null, every save) says about itself, once per * version and path. Only a pair the mirror has never described is inflated, so an ordinary landing * that re-lists unchanged files reads none of them. */ function recordFacts(db: Database, saves: string[] | null): void { const ids = saves ?? db .query<{ id: string }, []>("SELECT id FROM saves ORDER BY rowid") .all() .map((r) => r.id); const has = db.query<{ one: number }, [string, string]>( "SELECT 1 AS one FROM facts WHERE hash = ? AND path = ?", ); const dataOf = db.query<{ data: Uint8Array }, [string]>( "SELECT data FROM objects WHERE hash = ?", ); const put = db.query( "INSERT OR IGNORE INTO facts (hash, path, lines, description, outline) VALUES (?, ?, ?, ?, ?)", ); const seen = new Set(); for (const id of ids) { for (const file of filesAt(db, id)) { const key = `${file.hash}\n${file.path}`; if (seen.has(key)) continue; seen.add(key); if (has.get(file.hash, file.path)) continue; // The stored bytes are read only for a file small enough to describe. const facts = fileFacts(file.path, file.size, () => { const stored = dataOf.get(file.hash); if (stored === null) throw new Error(`object ${file.hash} is missing`); return inflateSync(stored.data); }); put.run( file.hash, file.path, facts.lines, facts.description, facts.outline && JSON.stringify(facts.outline), ); } } } /** The objects real saves show, for the front page's "the library knows N things". */ function addKnownObjects(db: Database, saves: SaveRecord[]): void { const put = db.query("INSERT OR IGNORE INTO known_objects (hash) VALUES (?)"); for (const save of saves) { // Checkpoints are working marks, not history (§21.4), as in the recount. if (save.is_checkpoint) continue; for (const file of filesAt(db, save.id)) put.run(file.hash); } } function rebuildKnownObjects(db: Database): void { db.run("DELETE FROM known_objects"); const put = db.query("INSERT OR IGNORE INTO known_objects (hash) VALUES (?)"); const saves = db.query<{ id: string }, []>("SELECT id FROM saves WHERE is_checkpoint = 0").all(); for (const save of saves) for (const file of filesAt(db, save.id)) put.run(file.hash); } /** * Deletes the objects no save shows and no hidden path keeps, and recounts the objects real saves * show, so a strip erases what it removed. Only a landing that carries a strip event does this; * it is the one landing that walks the trees (for touches as well), and it rewrites no save's rows. */ function dropStripped(db: Database): void { const kept = new Set(); const saves = db.query<{ id: string }, []>("SELECT id FROM saves").all(); for (const save of saves) for (const file of storedFilesAt(db, save.id)) kept.add(file.hash); const drop = db.query("DELETE FROM objects WHERE hash = ?"); for (const row of db.query<{ hash: string }, []>("SELECT hash FROM objects").all()) { if (!kept.has(row.hash)) drop.run(row.hash); } db.run("DELETE FROM facts WHERE hash NOT IN (SELECT hash FROM objects)"); rebuildKnownObjects(db); } function hiddenList(db: Database): string[] { return mirrorState(db, "hidden")?.split("\n").filter(Boolean) ?? []; } /** Escaped names of every path this mirror's saves arrived without. */ export function quarantinedPaths(db: Database): string[] { return JSON.parse(mirrorState(db, "quarantined") ?? "[]"); } // A file at a save as text, if it is there and small enough to be a manifest. function smallFileText(db: Database, save: string, path: string): string | null { const file = fileAt(db, save, path); if (!file || file.size > MAX_MANIFEST) return null; const row = db .query<{ data: Uint8Array }, [string]>("SELECT data FROM objects WHERE hash = ?") .get(file.hash); return row ? new TextDecoder("utf-8", { ignoreBOM: true }).decode(inflateSync(row.data)) : null; } // Lines and languages never change between syncs, so they are counted once here, not per view. They // come from the newest real save, not `head`: a checkpoint's files are not public history (§21.4). // Lines are source lines: files in a known language, tests left out; docs and data never count. // Read and written under one write lock: both threads recount, and a recount must never publish // what it read before another thread's newer one. function refreshStats(db: Database): void { db.transaction(() => recount(db)).immediate(); } function recount(db: Database): void { const save = newestRealSave(db); const files = save === "" ? [] : filesAt(db, save); const dataOf = db.query<{ data: Uint8Array }, [string]>( "SELECT data FROM objects WHERE hash = ?", ); let lines = 0; const byLanguage = new Map(); for (const file of files) { const language = LANGUAGES[file.path.split(".").pop() ?? ""]; // Tests are not the program: counted, Koh 3's read as 18k lines of V where it has 11k. if (!language || VENDORED.test(file.path) || isTestPath(file.path)) continue; if (file.size > MAX_COUNTED) continue; const stored = dataOf.get(file.hash); if (stored === null) continue; const bytes = inflateSync(stored.data); if (bytes.includes(0)) continue; let count = 0; for (const byte of bytes) if (byte === 10) count++; if (bytes.length > 0 && bytes[bytes.length - 1] !== 10) count++; lines += count; byLanguage.set(language, (byLanguage.get(language) ?? 0) + count); } const languages = [...byLanguage].sort((a, b) => b[1] - a[1]); const setState = db.query("INSERT OR REPLACE INTO state (key, value) VALUES (?, ?)"); setState.run("lines", String(lines)); setState.run("language", languages[0]?.[0] ?? ""); setState.run("languages", JSON.stringify(languages)); setState.run("stats_save", save); setState.run("declared_version", declaredVersion((path) => smallFileText(db, save, path)) ?? ""); // Last, with the recount it names, so one cut short is done again at the next open. setState.run("stats_rule", STATS_RULE); }