|
| 1 | +/** Read-only transcript detection; positive repairs retain exact snapshots. */ |
| 2 | +import fs from "node:fs"; |
| 3 | +import type { DatabaseSync } from "node:sqlite"; |
| 4 | +import { isRecord } from "@openclaw/normalization-core/record-coerce"; |
| 5 | +import type { SqliteTranscriptStorageRow } from "../config/sessions/session-accessor.sqlite-read.js"; |
| 6 | +import { openNodeSqliteDatabase } from "../infra/node-sqlite.js"; |
| 7 | +import { tableExists } from "../state/openclaw-state-db-schema-helpers.js"; |
| 8 | + |
| 9 | +// Schema-tolerant session enumeration for transcript-label migration (avoids post-ship columns). |
| 10 | +// Queries transcript_events table (schema-stable) instead of sessions table. |
| 11 | +// Returns read-only view of all distinct session IDs with events. |
| 12 | +export function readOnlySqliteTranscriptSessionIds(sqlitePath: string): string[] { |
| 13 | + if (!fs.existsSync(sqlitePath)) { |
| 14 | + return []; |
| 15 | + } |
| 16 | + let database: DatabaseSync | undefined; |
| 17 | + try { |
| 18 | + database = openNodeSqliteDatabase(sqlitePath, { readOnly: true }); |
| 19 | + if (!tableExists(database, "transcript_events")) { |
| 20 | + return []; |
| 21 | + } |
| 22 | + const rows = database |
| 23 | + .prepare("SELECT DISTINCT session_id FROM transcript_events ORDER BY session_id ASC") |
| 24 | + .all(); |
| 25 | + return rows.flatMap((row) => (typeof row.session_id === "string" ? [row.session_id] : [])); |
| 26 | + } finally { |
| 27 | + database?.close(); |
| 28 | + } |
| 29 | +} |
| 30 | + |
| 31 | +function iterateTranscriptRows(database: DatabaseSync, sessionId: string, firstRowOnly = false) { |
| 32 | + return database |
| 33 | + .prepare( |
| 34 | + `SELECT created_at, event_json, seq FROM transcript_events WHERE session_id = ? ORDER BY seq ASC${firstRowOnly ? " LIMIT 1" : ""}`, |
| 35 | + ) |
| 36 | + .iterate(sessionId); |
| 37 | +} |
| 38 | + |
| 39 | +// Read-only transcript snapshot reader for dry-run detection phase. |
| 40 | +// Avoids opening writable database lifecycle (lease/WAL/schema-ensure). |
| 41 | +// Returns rows only; migration parses per-row during repair. |
| 42 | +type ReadOnlyTranscriptSnapshot = |
| 43 | + | { |
| 44 | + ok: true; |
| 45 | + rows: Array<{ eventJson: string; seq: number }>; |
| 46 | + } |
| 47 | + | { ok: false; error: unknown }; |
| 48 | + |
| 49 | +export function readOnlySqliteTranscriptRepairSnapshot( |
| 50 | + sqlitePath: string, |
| 51 | + sessionId: string, |
| 52 | + needsRepair: (event: unknown) => boolean, |
| 53 | +): ReadOnlyTranscriptSnapshot { |
| 54 | + if (!fs.existsSync(sqlitePath)) { |
| 55 | + return { ok: false, error: new Error(`SQLite database not found: ${sqlitePath}`) }; |
| 56 | + } |
| 57 | + let database: DatabaseSync | undefined; |
| 58 | + try { |
| 59 | + database = openNodeSqliteDatabase(sqlitePath, { readOnly: true }); |
| 60 | + // Unchanged histories retain one payload. Re-read positive candidates in full so |
| 61 | + // malformed siblings and exact-snapshot guards still govern the surgical repair. |
| 62 | + for (const row of iterateTranscriptRows(database, sessionId)) { |
| 63 | + if (typeof row.event_json !== "string" || typeof row.seq !== "number") { |
| 64 | + continue; |
| 65 | + } |
| 66 | + let event: unknown; |
| 67 | + try { |
| 68 | + event = JSON.parse(row.event_json); |
| 69 | + } catch { |
| 70 | + continue; |
| 71 | + } |
| 72 | + if (!needsRepair(event)) { |
| 73 | + continue; |
| 74 | + } |
| 75 | + const rows: Array<{ eventJson: string; seq: number }> = []; |
| 76 | + for (const candidate of iterateTranscriptRows(database, sessionId)) { |
| 77 | + if (typeof candidate.event_json === "string" && typeof candidate.seq === "number") { |
| 78 | + rows.push({ eventJson: candidate.event_json, seq: candidate.seq }); |
| 79 | + } |
| 80 | + } |
| 81 | + return { ok: true, rows }; |
| 82 | + } |
| 83 | + return { ok: true, rows: [] }; |
| 84 | + } catch (error) { |
| 85 | + return { ok: false, error }; |
| 86 | + } finally { |
| 87 | + database?.close(); |
| 88 | + } |
| 89 | +} |
| 90 | + |
| 91 | +/** Reads exact row metadata for a guarded transcript replacement without opening a writer. */ |
| 92 | +export function readOnlySqliteHeaderlessTranscriptSnapshot( |
| 93 | + sqlitePath: string, |
| 94 | + sessionId: string, |
| 95 | +): |
| 96 | + | { ok: true; rows: SqliteTranscriptStorageRow[]; sessionKey?: string } |
| 97 | + | { ok: false; error: unknown } { |
| 98 | + if (!fs.existsSync(sqlitePath)) { |
| 99 | + return { ok: false, error: new Error(`SQLite database not found: ${sqlitePath}`) }; |
| 100 | + } |
| 101 | + let database: DatabaseSync | undefined; |
| 102 | + try { |
| 103 | + database = openNodeSqliteDatabase(sqlitePath, { readOnly: true }); |
| 104 | + // Headers can live at nonzero seq. A current header needs no whole-history read; |
| 105 | + // possible headerless repairs still take and validate the complete exact snapshot. |
| 106 | + for (const row of iterateTranscriptRows(database, sessionId, true)) { |
| 107 | + if (typeof row.event_json !== "string") { |
| 108 | + break; |
| 109 | + } |
| 110 | + let first: unknown; |
| 111 | + try { |
| 112 | + first = JSON.parse(row.event_json); |
| 113 | + } catch { |
| 114 | + return { ok: true, rows: [] }; |
| 115 | + } |
| 116 | + if (!isRecord(first) || first.type === "session") { |
| 117 | + return { ok: true, rows: [] }; |
| 118 | + } |
| 119 | + } |
| 120 | + const sessionKeyRow = database |
| 121 | + .prepare("SELECT session_key FROM session_windows WHERE session_id = ? LIMIT 1") |
| 122 | + .get(sessionId); |
| 123 | + const storageRows: SqliteTranscriptStorageRow[] = []; |
| 124 | + for (const row of iterateTranscriptRows(database, sessionId)) { |
| 125 | + if ( |
| 126 | + typeof row.created_at !== "number" || |
| 127 | + typeof row.event_json !== "string" || |
| 128 | + typeof row.seq !== "number" |
| 129 | + ) { |
| 130 | + return { |
| 131 | + ok: false, |
| 132 | + error: new Error(`Invalid transcript row metadata for session ${sessionId}`), |
| 133 | + }; |
| 134 | + } |
| 135 | + storageRows.push({ |
| 136 | + createdAt: row.created_at, |
| 137 | + eventJson: row.event_json, |
| 138 | + seq: row.seq, |
| 139 | + }); |
| 140 | + } |
| 141 | + return { |
| 142 | + ok: true, |
| 143 | + rows: storageRows, |
| 144 | + ...(typeof sessionKeyRow?.session_key === "string" |
| 145 | + ? { sessionKey: sessionKeyRow.session_key } |
| 146 | + : {}), |
| 147 | + }; |
| 148 | + } catch (error) { |
| 149 | + return { ok: false, error }; |
| 150 | + } finally { |
| 151 | + database?.close(); |
| 152 | + } |
| 153 | +} |
0 commit comments