1import type { Database } from "bun:sqlite";2import { inflateSync } from "node:zlib";3import { mirrorState } from "./store.ts";45export type Save = {6 id: string;7 parent: string;8 message: string;9 created_at: number;10 machine: string;11 agent: string;12 session: string;13 is_checkpoint: boolean;14};1516export type FileEntry = { path: string; hash: string; executable: boolean; size: number };171819export type Touches = { line: Save[]; byPath: Map<string, Save[]> };2021export type RepoStats = { saves: number; lines: number; language: string; updated: number | null };2223const SAVE_COLUMNS = `id, COALESCE(parent, '') AS parent, message, created_at, machine,24 COALESCE(agent, '') AS agent, COALESCE(session, '') AS session, is_checkpoint = 1 AS is_checkpoint`;25const LINE_COLUMNS =26 "line.id, line.parent, line.message, line.created_at, line.machine, line.agent, line.session, line.is_checkpoint, line.n";27const ID_PREFIX = /^[0-9a-f]{6,12}$/;282930const NOT_CHECKPOINT = "is_checkpoint = 0";3132export function headId(db: Database): string | null {33 return mirrorState(db, "head");34}353637export function history(db: Database, limit: number, offset: number): Save[] {38 return db39 .query<Save, [number, number]>(40 `SELECT ${SAVE_COLUMNS} FROM saves WHERE ${NOT_CHECKPOINT} ORDER BY rowid DESC LIMIT ? OFFSET ?`,41 )42 .all(limit, offset)43 .map(asSave);44}454647export function timeline(db: Database): Save[] {48 return db49 .query<Save, []>(`SELECT ${SAVE_COLUMNS} FROM saves WHERE ${NOT_CHECKPOINT} ORDER BY rowid`)50 .all()51 .map(asSave);52}535455export function saveByPrefix(db: Database, prefix: string): Save | null {56 if (!ID_PREFIX.test(prefix)) return null;57 const rows = db58 .query<Save, [string]>(`SELECT ${SAVE_COLUMNS} FROM saves WHERE id LIKE ? || '%' LIMIT 2`)59 .all(prefix);60 return rows.length === 1 ? asSave(rows[0] as Save) : null;61}626364export function visibleParent(db: Database, save: Save): Save | null {65 for (let id = save.parent; id !== ""; ) {66 const parent = saveByPrefix(db, id);67 if (!parent?.is_checkpoint) return parent;68 id = parent.parent;69 }70 return null;71}727374export function flagReason(db: Database, saveId: string): string | null {75 const row = db76 .query<{ kind: string; reason: string }, [string]>(77 `SELECT kind, COALESCE(reason, '') AS reason FROM events78 WHERE save_id = ? AND kind IN ('flag', 'clear') ORDER BY created_at DESC, id DESC LIMIT 1`,79 )80 .get(saveId);81 return row?.kind === "flag" ? row.reason : null;82}8384export function filesAt(db: Database, saveId: string): FileEntry[] {85 return db86 .query<FileEntry, [string]>(87 `SELECT f.path, f.hash, f.executable = 1 AS executable, o.size FROM save_files f88 JOIN objects o ON o.hash = f.hash WHERE f.save_id = ? ORDER BY f.path`,89 )90 .all(saveId)91 .map((file) => ({ ...file, executable: Boolean(file.executable) }));92}9394export function fileAt(db: Database, saveId: string, path: string): FileEntry | null {95 const file = db96 .query<FileEntry, [string, string]>(97 `SELECT f.path, f.hash, f.executable = 1 AS executable, o.size FROM save_files f98 JOIN objects o ON o.hash = f.hash WHERE f.save_id = ? AND f.path = ?`,99 )100 .get(saveId, path);101 return file ? { ...file, executable: Boolean(file.executable) } : null;102}103104export function objectBytes(db: Database, hash: string): Uint8Array<ArrayBuffer> | null {105 const row = db106 .query<{ data: Uint8Array }, [string]>("SELECT data FROM objects WHERE hash = ?")107 .get(hash);108 return row ? new Uint8Array(inflateSync(row.data)) : null;109}110111export function repoStats(db: Database): RepoStats {112 const row = db113 .query<{ saves: number; updated: number | null }, []>(114 `SELECT COUNT(*) AS saves, MAX(created_at) AS updated FROM saves WHERE ${NOT_CHECKPOINT}`,115 )116 .get() ?? { saves: 0, updated: null };117 return {118 saves: row.saves,119 updated: row.updated,120 lines: Number(mirrorState(db, "lines") ?? 0),121 language: mirrorState(db, "language") ?? "",122 };123}124125126127128129130export function fileTouches(db: Database, saveId: string): Touches {131 const rows = db132 .query<Save & { path: string; n: number }, { at: string }>(133 `WITH line AS (134 SELECT ${SAVE_COLUMNS}, LAG(id) OVER (ORDER BY rowid) AS prev, rowid AS n FROM saves135 WHERE ${NOT_CHECKPOINT} AND rowid <= (SELECT rowid FROM saves WHERE id = $at)136 )137 SELECT ${LINE_COLUMNS}, f.path FROM line JOIN save_files f ON f.save_id = line.id138 LEFT JOIN save_files p ON p.save_id = line.prev AND p.path = f.path139 WHERE p.hash IS NOT f.hash OR p.executable IS NOT f.executable140 UNION ALL141 SELECT ${LINE_COLUMNS}, p.path FROM line JOIN save_files p ON p.save_id = line.prev142 WHERE NOT EXISTS (SELECT 1 FROM save_files f WHERE f.save_id = line.id AND f.path = p.path)143 ORDER BY n`,144 )145 .all({ at: saveId });146 const saves = new Map<string, Save>();147 const byPath = new Map<string, Save[]>();148 for (const { path, n: _, ...row } of rows) {149 const save = saves.get(row.id) ?? asSave(row);150 saves.set(save.id, save);151 const touched = byPath.get(path);152 if (touched) touched.push(save);153 else byPath.set(path, [save]);154 }155 return { line: [...saves.values()], byPath };156}157158function asSave(row: Save): Save {159 return { ...row, is_checkpoint: Boolean(row.is_checkpoint) };160}