@@ -0,0 +1,406 @@
1+/**
2+ * Session persistence layer.
3+ *
4+ * Stores sessions and their message histories in a single SQLite database
5+ * via `bun:sqlite`. Messages are stored as JSON-serialized pi-ai {@link Message}
6+ * objects grouped by turn number. Cumulative token/cost stats are computed
7+ * from the message history rather than stored separately.
8+ *
9+ * @module
10+ */
11+
12+import { Database } from "bun:sqlite";
13+import type { AssistantMessage, Message } from "@mariozechner/pi-ai";
14+
15+// ---------------------------------------------------------------------------
16+// Types
17+// ---------------------------------------------------------------------------
18+
19+/**
20+ * A persisted session record.
21+ *
22+ * Represents a single conversation scoped to a working directory.
23+ * The `model` and `effort` fields reflect the values at session creation —
24+ * the user may switch models mid-session via `/model`, but the session
25+ * record is not updated (individual assistant messages carry their own model).
26+ */
27+export interface Session {
28+ /** Unique session identifier (UUID). */
29+ id: string;
30+ /** Working directory the session is scoped to. */
31+ cwd: string;
32+ /** Provider/model string at creation time, e.g. `"anthropic/claude-sonnet-4-20250514"`. */
33+ model: string | null;
34+ /** Thinking effort level at creation time. */
35+ effort: string | null;
36+ /** ID of the session this was forked from, or `null` if original. */
37+ forkedFrom: string | null;
38+ /** Unix timestamp in milliseconds when the session was created. */
39+ createdAt: number;
40+ /** Unix timestamp in milliseconds, updated on each new message. */
41+ updatedAt: number;
42+}
43+
44+/**
45+ * Cumulative token and cost statistics for a session.
46+ *
47+ * Computed by summing `usage` fields from all {@link AssistantMessage}s
48+ * in the session's history. Not stored — derived on load and maintained
49+ * in-memory during the session.
50+ */
51+export interface SessionStats {
52+ /** Total input tokens across all assistant messages. */
53+ totalInput: number;
54+ /** Total output tokens across all assistant messages. */
55+ totalOutput: number;
56+ /** Total cost in dollars across all assistant messages. */
57+ totalCost: number;
58+}
59+
60+/** Options for creating a new session. */
61+interface CreateSessionOpts {
62+ /** Working directory to scope the session to. */
63+ cwd: string;
64+ /** Provider/model identifier, e.g. `"anthropic/claude-sonnet-4-20250514"`. */
65+ model?: string;
66+ /** Thinking effort level, e.g. `"medium"`. */
67+ effort?: string;
68+}
69+
70+// ---------------------------------------------------------------------------
71+// Internal row types (map directly to SQLite column names)
72+// ---------------------------------------------------------------------------
73+
74+/** Row shape returned by `SELECT * FROM sessions`. */
75+type SessionRow = {
76+ id: string;
77+ cwd: string;
78+ model: string | null;
79+ effort: string | null;
80+ forked_from: string | null;
81+ created_at: number;
82+ updated_at: number;
83+};
84+
85+/** Row shape for `SELECT MAX(turn)` queries. */
86+type MaxTurnRow = { max_turn: number | null };
87+
88+/** Row shape for `SELECT data` queries. */
89+type DataRow = { data: string };
90+
91+// ---------------------------------------------------------------------------
92+// SQL
93+// ---------------------------------------------------------------------------
94+
95+const SQL = {
96+ listSessions: "SELECT * FROM sessions WHERE cwd = ? ORDER BY updated_at DESC",
97+ maxTurn: "SELECT MAX(turn) as max_turn FROM messages WHERE session_id = ?",
98+ loadMessages: "SELECT data FROM messages WHERE session_id = ? ORDER BY id",
99+} as const;
100+
101+const SCHEMA = `
102+CREATE TABLE IF NOT EXISTS sessions (
103+ id TEXT PRIMARY KEY,
104+ cwd TEXT NOT NULL,
105+ model TEXT,
106+ effort TEXT,
107+ forked_from TEXT,
108+ created_at INTEGER NOT NULL,
109+ updated_at INTEGER NOT NULL
110+);
111+
112+CREATE INDEX IF NOT EXISTS idx_sessions_cwd ON sessions(cwd);
113+
114+CREATE TABLE IF NOT EXISTS messages (
115+ id INTEGER PRIMARY KEY AUTOINCREMENT,
116+ session_id TEXT NOT NULL REFERENCES sessions(id) ON DELETE CASCADE,
117+ turn INTEGER NOT NULL,
118+ data TEXT NOT NULL,
119+ created_at INTEGER NOT NULL
120+);
121+
122+CREATE INDEX IF NOT EXISTS idx_messages_session ON messages(session_id, turn);
123+`;
124+
125+// ---------------------------------------------------------------------------
126+// Database
127+// ---------------------------------------------------------------------------
128+
129+/**
130+ * Open (or create) the SQLite database and ensure the schema exists.
131+ *
132+ * Enables WAL journal mode for concurrent read performance and foreign
133+ * keys for cascade deletes. Pass `":memory:"` for an in-memory database
134+ * (useful in tests).
135+ *
136+ * @param path - File path for the database, or `":memory:"` for in-memory.
137+ * @returns An open {@link Database} handle. The caller is responsible for
138+ * closing it when done.
139+ *
140+ * @example
141+ * ```ts
142+ * const db = openDatabase("~/.config/mini-coder/mini-coder.db");
143+ * // ... use db ...
144+ * db.close();
145+ * ```
146+ */
147+export function openDatabase(path: string): Database {
148+ const db = new Database(path);
149+ db.run("PRAGMA journal_mode = WAL");
150+ db.run("PRAGMA foreign_keys = ON");
151+ db.exec(SCHEMA);
152+ return db;
153+}
154+
155+// ---------------------------------------------------------------------------
156+// Session CRUD
157+// ---------------------------------------------------------------------------
158+
159+function generateId(): string {
160+ return crypto.randomUUID();
161+}
162+
163+/**
164+ * Create a new session record.
165+ *
166+ * @param db - Open database handle.
167+ * @param opts - Session options (cwd is required; model and effort are optional).
168+ * @returns The newly created {@link Session}.
169+ */
170+export function createSession(db: Database, opts: CreateSessionOpts): Session {
171+ const id = generateId();
172+ const now = Date.now();
173+ db.run(
174+ "INSERT INTO sessions (id, cwd, model, effort, forked_from, created_at, updated_at) VALUES (?, ?, ?, ?, NULL, ?, ?)",
175+ [id, opts.cwd, opts.model ?? null, opts.effort ?? null, now, now],
176+ );
177+ return {
178+ id,
179+ cwd: opts.cwd,
180+ model: opts.model ?? null,
181+ effort: opts.effort ?? null,
182+ forkedFrom: null,
183+ createdAt: now,
184+ updatedAt: now,
185+ };
186+}
187+
188+/**
189+ * Retrieve a session by its ID.
190+ *
191+ * @param db - Open database handle.
192+ * @param id - The session UUID.
193+ * @returns The {@link Session}, or `null` if not found.
194+ */
195+export function getSession(db: Database, id: string): Session | null {
196+ const row = db
197+ .query<SessionRow, [string]>("SELECT * FROM sessions WHERE id = ?")
198+ .get(id);
199+ if (!row) return null;
200+ return {
201+ id: row.id,
202+ cwd: row.cwd,
203+ model: row.model,
204+ effort: row.effort,
205+ forkedFrom: row.forked_from,
206+ createdAt: row.created_at,
207+ updatedAt: row.updated_at,
208+ };
209+}
210+
211+/**
212+ * List sessions for a working directory, most recently updated first.
213+ *
214+ * @param db - Open database handle.
215+ * @param cwd - Working directory to filter by.
216+ * @returns An array of {@link Session} records ordered by `updatedAt` descending.
217+ */
218+export function listSessions(db: Database, cwd: string): Session[] {
219+ const rows = db.query<SessionRow, [string]>(SQL.listSessions).all(cwd);
220+ return rows.map((row) => ({
221+ id: row.id,
222+ cwd: row.cwd,
223+ model: row.model,
224+ effort: row.effort,
225+ forkedFrom: row.forked_from,
226+ createdAt: row.created_at,
227+ updatedAt: row.updated_at,
228+ }));
229+}
230+
231+/**
232+ * Delete a session and all its messages (via foreign key cascade).
233+ *
234+ * @param db - Open database handle.
235+ * @param id - The session UUID to delete.
236+ */
237+export function deleteSession(db: Database, id: string): void {
238+ db.run("DELETE FROM sessions WHERE id = ?", [id]);
239+}
240+
241+// ---------------------------------------------------------------------------
242+// Messages
243+// ---------------------------------------------------------------------------
244+
245+/**
246+ * Append a message to a session's history.
247+ *
248+ * Turn numbering rules:
249+ * - When `turn` is **omitted**, a new turn is started with `MAX(turn) + 1`
250+ * (or `1` for the first message). This is used for user messages.
251+ * - When `turn` is **provided**, the message joins that existing turn.
252+ * This is used for assistant and tool-result messages that belong to
253+ * the same agent loop as the initiating user message.
254+ *
255+ * Also updates the session's `updatedAt` timestamp.
256+ *
257+ * @param db - Open database handle.
258+ * @param sessionId - The session to append to.
259+ * @param message - A pi-ai {@link Message} (UserMessage, AssistantMessage, or ToolResultMessage).
260+ * @param turn - Explicit turn number to join. Omit to start a new turn.
261+ * @returns The turn number the message was stored with.
262+ */
263+export function appendMessage(
264+ db: Database,
265+ sessionId: string,
266+ message: Message,
267+ turn?: number,
268+): number {
269+ const now = Date.now();
270+
271+ let effectiveTurn: number;
272+ if (turn !== undefined) {
273+ effectiveTurn = turn;
274+ } else {
275+ const row = db.query<MaxTurnRow, [string]>(SQL.maxTurn).get(sessionId);
276+ effectiveTurn = (row?.max_turn ?? 0) + 1;
277+ }
278+
279+ db.run(
280+ "INSERT INTO messages (session_id, turn, data, created_at) VALUES (?, ?, ?, ?)",
281+ [sessionId, effectiveTurn, JSON.stringify(message), now],
282+ );
283+ db.run("UPDATE sessions SET updated_at = ? WHERE id = ?", [now, sessionId]);
284+
285+ return effectiveTurn;
286+}
287+
288+/**
289+ * Load all messages for a session in insertion order.
290+ *
291+ * Messages are deserialized from their JSON representation back into
292+ * pi-ai {@link Message} objects. The ordering matches the original
293+ * append order (by autoincrement `id`), preserving the conversation flow.
294+ *
295+ * @param db - Open database handle.
296+ * @param sessionId - The session to load messages for.
297+ * @returns An array of {@link Message} objects, empty if the session has
298+ * no messages or does not exist.
299+ */
300+export function loadMessages(db: Database, sessionId: string): Message[] {
301+ const rows = db.query<DataRow, [string]>(SQL.loadMessages).all(sessionId);
302+ return rows.map((row) => JSON.parse(row.data) as Message);
303+}
304+
305+// ---------------------------------------------------------------------------
306+// Undo
307+// ---------------------------------------------------------------------------
308+
309+/**
310+ * Remove the last turn from a session's history.
311+ *
312+ * Deletes **all** messages with the highest turn number — the user message
313+ * and every assistant/tool-result message that followed in the same agent
314+ * loop. This is a context-only operation; filesystem changes are not reverted.
315+ *
316+ * @param db - Open database handle.
317+ * @param sessionId - The session to undo in.
318+ * @returns `true` if a turn was removed, `false` if the session had no messages.
319+ */
320+export function undoLastTurn(db: Database, sessionId: string): boolean {
321+ const row = db.query<MaxTurnRow, [string]>(SQL.maxTurn).get(sessionId);
322+ if (!row?.max_turn) return false;
323+
324+ db.run("DELETE FROM messages WHERE session_id = ? AND turn = ?", [
325+ sessionId,
326+ row.max_turn,
327+ ]);
328+ return true;
329+}
330+
331+// ---------------------------------------------------------------------------
332+// Fork
333+// ---------------------------------------------------------------------------
334+
335+/**
336+ * Fork a session into a new independent copy.
337+ *
338+ * Creates a new session with the same `cwd`, `model`, and `effort` as the
339+ * source, then copies all messages preserving their turn numbers. The new
340+ * session's `forkedFrom` field points back to the source. The original
341+ * session is not modified.
342+ *
343+ * @param db - Open database handle.
344+ * @param sourceId - The session to fork from.
345+ * @returns The newly created {@link Session}.
346+ * @throws If the source session does not exist.
347+ */
348+export function forkSession(db: Database, sourceId: string): Session {
349+ const source = getSession(db, sourceId);
350+ if (!source) throw new Error(`Session not found: ${sourceId}`);
351+
352+ const id = generateId();
353+ const now = Date.now();
354+
355+ db.run(
356+ "INSERT INTO sessions (id, cwd, model, effort, forked_from, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?)",
357+ [id, source.cwd, source.model, source.effort, sourceId, now, now],
358+ );
359+
360+ db.run(
361+ "INSERT INTO messages (session_id, turn, data, created_at) SELECT ?, turn, data, created_at FROM messages WHERE session_id = ? ORDER BY id",
362+ [id, sourceId],
363+ );
364+
365+ return {
366+ id,
367+ cwd: source.cwd,
368+ model: source.model,
369+ effort: source.effort,
370+ forkedFrom: sourceId,
371+ createdAt: now,
372+ updatedAt: now,
373+ };
374+}
375+
376+// ---------------------------------------------------------------------------
377+// Stats
378+// ---------------------------------------------------------------------------
379+
380+/**
381+ * Compute cumulative token and cost statistics from a message history.
382+ *
383+ * Iterates over the messages, summing `usage` fields from assistant messages
384+ * only (user and tool-result messages do not carry usage data). This is
385+ * designed to be called once on session load, with the result maintained
386+ * in-memory via a running accumulator during the session.
387+ *
388+ * @param messages - The full message history for a session.
389+ * @returns Aggregated {@link SessionStats}.
390+ */
391+export function computeStats(messages: Message[]): SessionStats {
392+ let totalInput = 0;
393+ let totalOutput = 0;
394+ let totalCost = 0;
395+
396+ for (const msg of messages) {
397+ if (msg.role === "assistant") {
398+ const am = msg as AssistantMessage;
399+ totalInput += am.usage.input;
400+ totalOutput += am.usage.output;
401+ totalCost += am.usage.cost.total;
402+ }
403+ }
404+
405+ return { totalInput, totalOutput, totalCost };
406+}