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}838485export function stripCount(db: Database): number {86 return db.query<{ n: number }, []>("SELECT COUNT(*) AS n FROM events WHERE kind = 'strip'").get()87 ?.n as number;88}8990export function filesAt(db: Database, saveId: string): FileEntry[] {91 return db92 .query<FileEntry, [string]>(93 `SELECT f.path, f.hash, f.executable = 1 AS executable, o.size FROM save_files f94 JOIN objects o ON o.hash = f.hash WHERE f.save_id = ? ORDER BY f.path`,95 )96 .all(saveId)97 .map((file) => ({ ...file, executable: Boolean(file.executable) }));98}99100export function fileAt(db: Database, saveId: string, path: string): FileEntry | null {101 const file = db102 .query<FileEntry, [string, string]>(103 `SELECT f.path, f.hash, f.executable = 1 AS executable, o.size FROM save_files f104 JOIN objects o ON o.hash = f.hash WHERE f.save_id = ? AND f.path = ?`,105 )106 .get(saveId, path);107 return file ? { ...file, executable: Boolean(file.executable) } : null;108}109110export function objectBytes(db: Database, hash: string): Uint8Array<ArrayBuffer> | null {111 const row = db112 .query<{ data: Uint8Array }, [string]>("SELECT data FROM objects WHERE hash = ?")113 .get(hash);114 return row ? new Uint8Array(inflateSync(row.data)) : null;115}116117export function repoStats(db: Database): RepoStats {118 const row = db119 .query<{ saves: number; updated: number | null }, []>(120 `SELECT COUNT(*) AS saves, MAX(created_at) AS updated FROM saves WHERE ${NOT_CHECKPOINT}`,121 )122 .get() ?? { saves: 0, updated: null };123 return {124 saves: row.saves,125 updated: row.updated,126 lines: Number(mirrorState(db, "lines") ?? 0),127 language: mirrorState(db, "language") ?? "",128 };129}130131132133134135136export function fileTouches(db: Database, saveId: string): Touches {137 const rows = db138 .query<Save & { path: string; n: number }, { at: string }>(139 `WITH line AS (140 SELECT ${SAVE_COLUMNS}, LAG(id) OVER (ORDER BY rowid) AS prev, rowid AS n FROM saves141 WHERE ${NOT_CHECKPOINT} AND rowid <= (SELECT rowid FROM saves WHERE id = $at)142 )143 SELECT ${LINE_COLUMNS}, f.path FROM line JOIN save_files f ON f.save_id = line.id144 LEFT JOIN save_files p ON p.save_id = line.prev AND p.path = f.path145 WHERE p.hash IS NOT f.hash OR p.executable IS NOT f.executable146 UNION ALL147 SELECT ${LINE_COLUMNS}, p.path FROM line JOIN save_files p ON p.save_id = line.prev148 WHERE NOT EXISTS (SELECT 1 FROM save_files f WHERE f.save_id = line.id AND f.path = p.path)149 ORDER BY n`,150 )151 .all({ at: saveId });152 const saves = new Map<string, Save>();153 const byPath = new Map<string, Save[]>();154 for (const { path, n: _, ...row } of rows) {155 const save = saves.get(row.id) ?? asSave(row);156 saves.set(save.id, save);157 const touched = byPath.get(path);158 if (touched) touched.push(save);159 else byPath.set(path, [save]);160 }161 return { line: [...saves.values()], byPath };162}163164function asSave(row: Save): Save {165 return { ...row, is_checkpoint: Boolean(row.is_checkpoint) };166}