import type { Database } from "bun:sqlite"; import { createHash } from "node:crypto"; import { inflateSync } from "node:zlib"; import type { ReleaseRecord } from "../bucket/repo.ts"; import type { FileFacts } from "../describe/describe.ts"; import type { Outline } from "../describe/links.ts"; import { flattenManifest } from "./manifest.ts"; import { mirrorState } from "./store.ts"; export type Save = { id: string; parent: string; message: string; created_at: number; machine: string; agent: string; session: string; is_checkpoint: boolean; }; export type FileEntry = { path: string; hash: string; executable: boolean; size: number }; /** The saves that touched each path up to one save, oldest first; `line` is every one of * them in line order. */ export type Touches = { line: Save[]; byPath: Map }; export type RepoStats = { saves: number; lines: number; language: string; updated: number | null }; const SAVE_COLUMNS = `id, COALESCE(parent, '') AS parent, message, created_at, machine, COALESCE(agent, '') AS agent, COALESCE(session, '') AS session, is_checkpoint = 1 AS is_checkpoint`; const ID_PREFIX = /^[0-9a-f]{6,12}$/; // Checkpoints are working marks, not history (§21.4): every list and count below leaves them out. const NOT_CHECKPOINT = "is_checkpoint = 0"; export function headId(db: Database): string | null { return mirrorState(db, "head"); } /** A page of saves, newest first. Rows land oldest first, so rowid is the order of the line. */ export function history(db: Database, limit: number, offset: number): Save[] { return db .query( `SELECT ${SAVE_COLUMNS} FROM saves WHERE ${NOT_CHECKPOINT} ORDER BY rowid DESC LIMIT ? OFFSET ?`, ) .all(limit, offset) .map(asSave); } /** Every save, oldest first, for the timeline. */ export function timeline(db: Database): Save[] { return db .query(`SELECT ${SAVE_COLUMNS} FROM saves WHERE ${NOT_CHECKPOINT} ORDER BY rowid`) .all() .map(asSave); } /** The save a unique prefix of 6–12 hex characters names (§6.1), or null when none or * several do. */ export function saveByPrefix(db: Database, prefix: string): Save | null { if (!ID_PREFIX.test(prefix)) return null; // A migrated save's whole six-character ID can also begin a twelve-character one. const exact = db .query(`SELECT ${SAVE_COLUMNS} FROM saves WHERE id = ?`) .get(prefix); if (exact) return asSave(exact); const rows = db .query(`SELECT ${SAVE_COLUMNS} FROM saves WHERE id GLOB ? LIMIT 2`) .all(`${prefix}*`); return rows.length === 1 ? asSave(rows[0] as Save) : null; } /** The nearest ancestor that is not a checkpoint: the parent a visitor can see (§21.4). */ export function visibleParent(db: Database, save: Save): Save | null { for (let id = save.parent; id !== ""; ) { const parent = saveByPrefix(db, id); if (!parent?.is_checkpoint) return parent; id = parent.parent; } return null; } /** The reason a save is flagged, or null when it isn't: its newest flag or clear event wins (§10.1). */ export function flagReason(db: Database, saveId: string): string | null { const row = db .query<{ kind: string; reason: string }, [string]>( `SELECT kind, COALESCE(reason, '') AS reason FROM events WHERE save_id = ? AND kind IN ('flag', 'clear') ORDER BY created_at DESC, id DESC LIMIT 1`, ) .get(saveId); return row?.kind === "flag" ? row.reason : null; } /** How many strip events have landed: events are append-only, so this only ever grows. */ /** * What a save's tarball depends on besides the save: the strips landed, and the hidden paths and * epoch the mirror was built with. A change to any of them names a new key, so an old tarball is * never looked up again, whatever a late write or a failed cleanup leaves behind. */ export function tarballGeneration(db: Database): string { const built = `${mirrorState(db, "hidden") ?? ""}\n${mirrorState(db, "epoch") ?? ""}`; return `${stripCount(db)}-${createHash("sha256").update(built).digest("hex").slice(0, 12)}`; } function stripCount(db: Database): number { return db.query<{ n: number }, []>("SELECT COUNT(*) AS n FROM events WHERE kind = 'strip'").get() ?.n as number; } type Strip = { save_id: string | null; path: string }; type Filters = { generation: string; hidden: string[]; strips: Strip[] }; // Which paths the operator hides and which strips cover, read once per strip/hidden generation. // A save's tree is never rewritten: the filter is applied as a save's files are read. const filters = new WeakMap(); function filtersAt(db: Database): Filters { const generation = tarballGeneration(db); const cached = filters.get(db); if (cached?.generation === generation) return cached; const fresh: Filters = { generation, hidden: (mirrorState(db, "hidden") ?? "").split("\n").filter(Boolean), strips: db.query("SELECT save_id, path FROM events WHERE kind = 'strip'").all(), }; filters.set(db, fresh); return fresh; } // §10.2's path rule: a file or folder, or an `ANY_DEPTH` name at any depth. function covers(entry: string, path: string): boolean { if (entry.startsWith("**/")) return `/${path}/`.includes(`/${entry.slice(3)}/`); return path === entry || path.startsWith(`${entry.replace(/\/+$/, "")}/`); } function filesAtSave(db: Database, saveId: string, keepHidden: boolean): FileEntry[] { const root = db .query<{ manifest: string }, [string]>("SELECT manifest FROM saves WHERE id = ?") .get(saveId)?.manifest; if (root === undefined) return []; const current = filtersAt(db); // A path whose object the mirror never stored — an oversized one, a quarantined one — is not // served, as the join on `objects` used to leave it out. const exists = db.query<{ one: number }, [string]>("SELECT 1 AS one FROM objects WHERE hash = ?"); return flattenManifest(db, root).filter( (file) => (keepHidden || !current.hidden.some((entry) => covers(entry, file.path))) && !current.strips.some( (strip) => (strip.save_id === "" || strip.save_id === saveId) && covers(strip.path, file.path), ) && exists.get(file.hash) !== null, ); } /** The files at a save, sorted: what its manifest tree flattens to, less hidden and stripped paths. */ export function filesAt(db: Database, saveId: string): FileEntry[] { return filesAtSave(db, saveId, false); } /** The files a strip leaves, hidden paths included: the objects unhiding must still find. */ export function storedFilesAt(db: Database, saveId: string): FileEntry[] { return filesAtSave(db, saveId, true); } export function fileAt(db: Database, saveId: string, path: string): FileEntry | null { return filesAt(db, saveId).find((file) => file.path === path) ?? null; } // A steal asks for the object list and then one object at a time; the set is the same for every // request until a landing, a strip or a hidden list changes, which the generation and head name. const visible = new WeakMap }>(); /** Every object a visible file at some save refers to: the Koh routes serve only these. */ export function visibleObjects(db: Database): Set { const key = `${tarballGeneration(db)}\n${mirrorState(db, "head") ?? ""}`; const cached = visible.get(db); if (cached?.key === key) return cached.hashes; const hashes = new Set(); const saves = db.query<{ id: string }, []>("SELECT id FROM saves").all(); for (const save of saves) for (const file of filesAt(db, save.id)) hashes.add(file.hash); visible.set(db, { key, hashes }); return hashes; } export function objectBytes(db: Database, hash: string): Uint8Array | null { const row = db .query<{ data: Uint8Array }, [string]>("SELECT data FROM objects WHERE hash = ?") .get(hash); return row ? new Uint8Array(inflateSync(row.data)) : null; } export function repoStats(db: Database): RepoStats { const row = db .query<{ saves: number; updated: number | null }, []>( `SELECT COUNT(*) AS saves, MAX(created_at) AS updated FROM saves WHERE ${NOT_CHECKPOINT}`, ) .get() ?? { saves: 0, updated: null }; return { saves: row.saves, updated: row.updated, lines: Number(mirrorState(db, "lines") ?? 0), language: mirrorState(db, "language") ?? "", }; } /** * Which saves touched each path on the line up to `saveId` (§21.5's detail panel), as recorded when * each save landed (`touches` in the mirror). */ export function fileTouches(db: Database, saveId: string): Touches { const at = { at: saveId }; // The saves once, the touches as bare pairs: every touch row carrying its save's columns was // most of the Atlas's cost. const byRowid = new Map( db .query( `SELECT rowid AS n, ${SAVE_COLUMNS} FROM saves WHERE ${NOT_CHECKPOINT} AND rowid <= (SELECT rowid FROM saves WHERE id = $at)`, ) .all(at) .map(({ n, ...row }) => [n, asSave(row)]), ); const touched = db .query<{ path: string; n: number }, { at: string }>( `SELECT path, n FROM touches WHERE n <= (SELECT rowid FROM saves WHERE id = $at) ORDER BY n`, ) .all(at); const line = new Set(); const byPath = new Map(); for (const { path, n } of touched) { const save = byRowid.get(n) as Save; line.add(save); const saves = byPath.get(path); if (saves) saves.push(save); else byPath.set(path, [save]); } return { line: [...line], byPath }; } type FactsRow = { lines: number | null; description: string | null; outline: string | null; }; function factsAt(db: Database, hash: string, path: string): FactsRow | null { return ( db .query( "SELECT lines, description, outline FROM facts WHERE hash = ? AND path = ?", ) .get(hash, path) ?? null ); } /** The files at a save with what each says about itself, as recorded when it landed. */ export function filesWithFacts(db: Database, saveId: string): (FileEntry & FileFacts)[] { return filesAt(db, saveId).map((file) => { const facts = factsAt(db, file.hash, file.path); return { ...file, lines: facts?.lines ?? null, description: facts?.description ?? null, outline: facts?.outline == null ? null : (JSON.parse(facts.outline) as Outline), }; }); } /** One file's Atlas panel row, or null when the save shows no such file. */ export function panelFile( db: Database, saveId: string, path: string, ): | (FileEntry & { lines: number | null; description: string | null; outline: string | null }) | null { if (path === ".kohignore") return null; const file = fileAt(db, saveId, path); if (!file) return null; const facts = factsAt(db, file.hash, file.path); return { ...file, ...(facts ?? { lines: null, description: null, outline: null }) }; } /** A folder's Atlas panel rows: every file under it at that save, sorted, less Koh's ignore file. */ export function panelFolder( db: Database, saveId: string, dir: string, ): { path: string; size: number; lines: number | null; description: string | null }[] { return filesAt(db, saveId) .filter((file) => file.path !== ".kohignore" && file.path.startsWith(`${dir}/`)) .map((file) => { const facts = factsAt(db, file.hash, file.path); return { path: file.path, size: file.size, lines: facts?.lines ?? null, description: facts?.description ?? null, }; }); } /** The file contents this repo's real saves refer to, as recounted when its saves land. */ export function knownObjects(db: Database): string[] { return db .query<{ hash: string }, []>("SELECT hash FROM known_objects") .all() .map((row) => row.hash); } /** The newest real saves, newest first. */ export function newestSaves(db: Database, limit: number): Save[] { return db .query( `SELECT ${SAVE_COLUMNS} FROM saves WHERE ${NOT_CHECKPOINT} ORDER BY rowid DESC LIMIT ?`, ) .all(limit) .map(asSave); } /** Lines per language at the newest real save, most first, vendored code left out as in the header's language. */ export function languageLines(db: Database): [string, number][] { return JSON.parse(mirrorState(db, "languages") ?? "[]") as [string, number][]; } /** Every release record the bucket holds, in no particular order. */ export function releaseRecords(db: Database): ReleaseRecord[] { return db .query<{ record: string }, []>("SELECT record FROM releases") .all() .map((row) => JSON.parse(row.record) as ReleaseRecord); } function asSave(row: Save): Save { return { ...row, is_checkpoint: Boolean(row.is_checkpoint) }; }