// Session lifecycle composites (CV22.DS7.US10 slice D). // // Ports `session_start`, `session_start_fast`, `session_maintenance`, // `close_stale_orphans`, `retitle_pending_conversations`, and // `_reset_session_orientation` from `src/memory/cli/conversation_logger.py`. // // These are the composites Pi runs at session boundaries, and their REPORT is // the user-visible surface: Pi prints it. Parity is therefore string-exact in // grammar, labels, order, and the warning tails — everything except the // elapsed seconds, which are wall-clock and cannot be byte-stable across runs // or cores. // // The clock is injected rather than read (Navigator decision 2, 2026-09-03): // tests pin durations, and cross-core comparison normalizes the timing token // only after validating its exact grammar, so a re-worded or re-punctuated // report still fails. Freezing real timings would have faked the evidence // instead of isolating it. import { finishDeferredCloseTails } from "#conversation/deferredCloseTail.ts"; import { countCarriedOverConversations, countConversationsWithExtractionStatus, countQuarantinedConversations, extractPending, } from "#conversation/extractionDriver.ts"; import { setMute } from "#conversation/logger.ts"; import { sessionOutlivesTui } from "#conversation/runtimePolicy.ts"; import type { WritableDatabase } from "#db/database.ts"; import { GLOBAL_STICKY_DEFAULTS_SESSION_ID } from "#mirror/runtimeSession.ts"; import { deactivateOperatingMode } from "#mode/operatingMode.ts"; import { nowIso } from "#util/pyGenerators.ts"; /** Python's `close_stale_orphans` default. */ export const STALE_ORPHAN_THRESHOLD_MINUTES = 30; /** Python's `retitle_pending_conversations` default. */ export const RETITLE_LIMIT = 5; export interface MaintenanceDeps { /** Close one conversation through the full close tail. Throwing is isolated. */ closeConversation: (db: WritableDatabase, conversationId: string) => Promise | void; /** Improve one ended conversation's title; returns true when it changed. */ retitleConversation: (db: WritableDatabase, conversationId: string) => Promise | boolean; /** The DS5 orchestration behind replay with its accounting, as the driver injects it. */ runExtraction: (db: WritableDatabase, conversationId: string) => Promise | void; /** * The close-time finalization (title, summary, tags) for a conversation a * bounded runtime's SessionEnd closed without it (CV21.DS4.TS2). Optional * only for callers written before the step existed; the front door wires it. */ finalizeCloseTail?: (db: WritableDatabase, conversationId: string) => Promise | void; /** Python's `MEMORY_MAINTENANCE_MAX_EXTRACTIONS` (AI-05); defaults to the released budget. */ extractionLimit?: number; /** `MIRROR_STALE_ORPHAN_MINUTES` (CV21.DS4.US4); defaults to the 30-minute threshold. */ staleOrphanMinutes?: number; /** Monotonic seconds, injected so report timings are pinnable. */ monotonic?: () => number; now?: () => string; } /** * Python's `_reset_session_orientation`: a new runtime session starts from * intention, not stale mode or journey context. */ export function resetSessionOrientation(db: WritableDatabase, now: () => string = nowIso): void { deactivateOperatingMode(db, null, now()); db.prepare("DELETE FROM runtime_sessions WHERE session_id = ?").run( GLOBAL_STICKY_DEFAULTS_SESSION_ID, ); } /** * Conversation ids bound to an ATTENDED active runtime session: one whose * runtime ends the session with its TUI, so `active = 1` means a person may * still be typing. A runtime whose session outlives the TUI (Codex 0.163.0, * `runtimePolicy.ts`) is left out: there `active` means resumable, and an idle * conversation is an orphan like any other (CV21.DS4.US4). */ function attendedConversationIds(db: WritableDatabase): Set { const rows = db .prepare( "SELECT conversation_id, interface FROM runtime_sessions WHERE active = 1 AND conversation_id IS NOT NULL", ) .all() as Record[]; return new Set( rows .filter( (row) => !sessionOutlivesTui(typeof row.interface === "string" ? row.interface : null), ) .map((row) => String(row.conversation_id)), ); } /** * The runtime sessions still active on a conversation just closed as an orphan: * marked inactive with `closed_at`, so `guessRuntimeSessionId` stops reading * them as "the session" (DS12.TS2 L9's class), and a later prompt on the same * id binds a new conversation. */ function deactivateSessionsOf(db: WritableDatabase, conversationId: string, now: string): void { db.prepare( "UPDATE runtime_sessions SET active = 0, closed_at = ?, updated_at = ? WHERE conversation_id = ? AND active = 1", ).run(now, now, conversationId); } /** Python's `get_open_conversations_idle_since`. */ function openConversationsIdleSince(db: WritableDatabase, threshold: string): string[] { const rows = db .prepare( `SELECT c.id FROM conversations c WHERE c.ended_at IS NULL AND ( (SELECT MAX(m.created_at) FROM messages m WHERE m.conversation_id = c.id) < ? OR NOT EXISTS (SELECT 1 FROM messages m WHERE m.conversation_id = c.id) )`, ) .all(threshold) as Record[]; return rows.map((row) => String(row.id)); } /** * Python's `close_stale_orphans`: end open conversations idle longer than the * threshold, skipping any still bound to an attended active runtime session * (`attendedConversationIds`). Since CV21.DS4.US4 a session on a runtime that * outlives its TUI does not protect its conversation, and the close * deactivates every session the orphan was bound to. * * The count increments even when closing raises: `ended_at` is written before * the tail, so the orphan IS closed and an extraction failure must not stop the * loop or under-report the work. That asymmetry is deliberate in Python. * * KNOWN UNBOUNDED SPEND (registered for Debt Review): AI-05 caps extraction per * maintenance run, but this loop has no cap on orphan count and each orphan * runs the full close tail. Ported as-is; naming it here so DS8 prices it. */ export async function closeStaleOrphans( db: WritableDatabase, deps: Pick & { thresholdMinutes?: number }, ): Promise { const thresholdMinutes = deps.thresholdMinutes ?? STALE_ORPHAN_THRESHOLD_MINUTES; const now = deps.now ?? nowIso; const threshold = new Date(Date.parse(now()) - thresholdMinutes * 60_000).toISOString(); const attended = attendedConversationIds(db); let count = 0; for (const conversationId of openConversationsIdleSince(db, threshold)) { if (attended.has(conversationId)) continue; try { await deps.closeConversation(db, conversationId); } catch { // The orphan is closed regardless; a failed tail must not stop the loop. } deactivateSessionsOf(db, conversationId, now()); count += 1; } return count; } /** * Python's `retitle_pending_conversations`: opportunistically improve a small * batch of ended conversation titles at startup. */ export async function retitlePendingConversations( db: WritableDatabase, deps: Pick & { limit?: number }, ): Promise { const limit = deps.limit ?? RETITLE_LIMIT; if (limit <= 0) return 0; let candidates: string[]; try { const scanLimit = Math.max(limit * 10, 50); const rows = db .prepare( `SELECT c.id FROM conversations c WHERE c.ended_at IS NOT NULL -- Owed its deferred finalization, which titles it later this run (CV21.DS4.US4). AND (c.metadata IS NULL OR json_extract(c.metadata, '$.close_tail_pending') IS NOT 1) AND EXISTS (SELECT 1 FROM messages m WHERE m.conversation_id = c.id AND m.role = 'user') AND EXISTS (SELECT 1 FROM messages m WHERE m.conversation_id = c.id AND m.role = 'assistant') ORDER BY c.ended_at DESC, c.started_at DESC LIMIT ?`, ) .all(scanLimit) as Record[]; candidates = rows.map((row) => String(row.id)); } catch { return 0; } let changed = 0; for (const conversationId of candidates) { if (changed >= limit) break; try { if (await deps.retitleConversation(db, conversationId)) changed += 1; } catch { // Python swallows per-conversation failures and continues the batch. } } return changed; } interface TimedStep { label: string; count: number; elapsed: number; } async function timedStep( label: string, monotonic: () => number, run: () => Promise | number, ): Promise { const started = monotonic(); const count = await run(); return { label, count, elapsed: monotonic() - started }; } /** Python's `%.1f` seconds rendering inside the report. */ function formatElapsed(elapsed: number): string { return elapsed.toFixed(1); } /** * Python's `session_maintenance`: four timed steps in a fixed order, then the * warning tails. The step order is behavior, not presentation — closing stale * orphans first is what makes their conversations eligible for the extraction * step in the same run. * * CR153: there is no Pi backfill step. Python's walked Pi's session directory * and imported every file this home did not track, which on a machine with two * homes meant each other's sessions; a home's Pi conversations are the ones the * Pi extension logged into it, and maintenance reads no Pi session file. */ export async function sessionMaintenance( db: WritableDatabase, deps: MaintenanceDeps, ): Promise { const monotonic = deps.monotonic ?? (() => performance.now() / 1000); const steps: TimedStep[] = [ await timedStep("Closed stale conversations", monotonic, () => closeStaleOrphans(db, { closeConversation: deps.closeConversation, now: deps.now, thresholdMinutes: deps.staleOrphanMinutes ?? STALE_ORPHAN_THRESHOLD_MINUTES, }), ), await timedStep("Retitled pending conversations", monotonic, () => retitlePendingConversations(db, { retitleConversation: deps.retitleConversation }), ), await timedStep("Extracted pending conversations", monotonic, () => extractPending(db, { runExtraction: deps.runExtraction, limit: deps.extractionLimit }), ), // After extraction, so a stored summary is kept rather than generated twice. await timedStep("Finished deferred close tails", monotonic, () => deps.finalizeCloseTail ? finishDeferredCloseTails(db, { finalizeCloseTail: deps.finalizeCloseTail }) : 0, ), ]; const parts = ["Conversation maintenance complete."]; for (const step of steps) { parts.push(`${step.label}: ${step.count} (${formatElapsed(step.elapsed)}s)`); } const quarantined = countQuarantinedConversations(db); if (quarantined) { parts.push(`⚠ ${quarantined} conversation(s) quarantined after repeated extraction failure`); } const parseFailed = countConversationsWithExtractionStatus(db, "parse_failed"); if (parseFailed) { parts.push(`⚠ ${parseFailed} conversation(s) with unreadable model output (parse_failed)`); } const carriedOver = countCarriedOverConversations(db); if (carriedOver) { parts.push( `${carriedOver} conversation(s) carried over to the next run ` + "(maintenance extraction budget)", ); } return parts.join("\n"); } /** Python's `session_start_fast`: unmute and reorient, defer the expensive work. */ export function sessionStartFast(db: WritableDatabase, mirrorHome: string, now = nowIso): string { setMute(false, mirrorHome); resetSessionOrientation(db, now); return "Conversation logging ACTIVE. Maintenance deferred."; } /** Python's `session_start`: unmute, reorient, then run full maintenance. */ export async function sessionStart( db: WritableDatabase, mirrorHome: string, deps: MaintenanceDeps, ): Promise { setMute(false, mirrorHome); resetSessionOrientation(db, deps.now ?? nowIso); const maintenance = await sessionMaintenance(db, deps); return ["Conversation logging ACTIVE.", maintenance].join("\n"); }