import { createRequire } from 'node:module'; import { closeSync, createReadStream, existsSync, mkdirSync, openSync, readdirSync, rmSync, writeFileSync, writeSync, } from 'node:fs'; import { basename, dirname, join, resolve } from 'node:path'; import { createInterface } from 'node:readline'; import { loadNodeSqliteModule } from '../framework/load-node-sqlite.js'; interface StatementLike { all(...params: unknown[]): Array>; iterate(...params: unknown[]): Iterable>; } interface DatabaseLike { prepare(sql: string): StatementLike; close(): void; } interface SqliteModuleLike { DatabaseSync: new (path: string, options?: { readOnly?: boolean }) => DatabaseLike; } export interface RuntimeDataExportPaths { readonly eventLedger: string; readonly stateHistory: string; readonly inputJournal: string; readonly observability: string; readonly rawWs?: string; readonly detailCapture?: string; } export type RuntimeDataExportSelection = | { readonly kind: 'all' } | { readonly kind: 'game'; readonly gameId: string }; export interface RuntimeDataExportOptions { readonly paths: RuntimeDataExportPaths; readonly selection: RuntimeDataExportSelection; readonly outputDir: string; readonly now?: () => Date; } export interface RuntimeDataExportResult { readonly path: string; readonly selection: RuntimeDataExportSelection; readonly sessionIds: readonly string[]; readonly segmentIds: readonly string[]; readonly rowCounts: Readonly>; readonly diagnosticCount: number; readonly rawWsFrameCount: number; readonly detailCaptureCount?: number; } interface GameScopeSelection { readonly sessionIds: readonly string[]; readonly segmentIds: readonly string[]; readonly segments: readonly Record[]; } interface TableQuery { readonly sql: string; readonly params: readonly unknown[]; } const localRequire = createRequire(import.meta.url); function sqliteModule(): SqliteModuleLike { const loaded = loadNodeSqliteModule>(localRequire); if (typeof loaded.DatabaseSync !== 'function') { throw new Error('Runtime data export requires node:sqlite DatabaseSync.'); } return loaded as SqliteModuleLike; } function openDatabase(path: string): DatabaseLike | null { if (!existsSync(path)) return null; return new (sqliteModule().DatabaseSync)(path, { readOnly: true }); } function quoteIdentifier(value: string): string { if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(value)) throw new Error(`Unsafe SQLite identifier: ${value}`); return `"${value}"`; } function placeholders(values: readonly unknown[]): string { if (values.length === 0) throw new Error('SQLite export filter must not be empty.'); return values.map(() => '?').join(', '); } function jsonValue(_key: string, value: unknown): unknown { if (typeof value !== 'bigint') return value; const number = Number(value); return Number.isSafeInteger(number) ? number : value.toString(); } function listTables(db: DatabaseLike): string[] { return db.prepare(` SELECT name FROM sqlite_schema WHERE type = 'table' AND name NOT LIKE 'sqlite_%' ORDER BY name `).all().map((row) => String(row.name)); } function databaseSchema(db: DatabaseLike): string { return db.prepare(` SELECT sql FROM sqlite_schema WHERE sql IS NOT NULL AND name NOT LIKE 'sqlite_%' ORDER BY type, name `).all().map((row) => `${String(row.sql).trim()};`).join('\n\n'); } function writeRows( db: DatabaseLike, query: TableQuery, path: string, ): number { const fd = openSync(path, 'wx'); let count = 0; try { for (const row of db.prepare(query.sql).iterate(...query.params)) { writeSync(fd, `${JSON.stringify(row, jsonValue)}\n`, undefined, 'utf8'); count += 1; } } finally { closeSync(fd); } return count; } function allRows(table: string): TableQuery { return { sql: `SELECT * FROM ${quoteIdentifier(table)} ORDER BY rowid`, params: [] }; } function gameTableQuery( database: 'event-ledger' | 'state-history' | 'runtime-epochs', table: string, scope: GameScopeSelection, ): TableQuery | null { const segments = placeholders(scope.segmentIds); const sessions = placeholders(scope.sessionIds); if (table === 'schema_migrations') return allRows(table); if (database === 'event-ledger') { if (table === 'play_sessions') { return { sql: `SELECT * FROM play_sessions WHERE session_id IN (${sessions}) ORDER BY rowid`, params: scope.sessionIds }; } if (table === 'event_segments') { return { sql: `SELECT * FROM event_segments WHERE segment_id IN (${segments}) ORDER BY rowid`, params: scope.segmentIds }; } if (table === 'events' || table === 'mailbox_items') { return { sql: `SELECT * FROM ${quoteIdentifier(table)} WHERE segment_id IN (${segments}) ORDER BY rowid`, params: scope.segmentIds }; } if (table === 'event_deliveries') { return { sql: `SELECT * FROM event_deliveries WHERE event_id IN (SELECT event_id FROM events WHERE segment_id IN (${segments})) ORDER BY rowid`, params: scope.segmentIds, }; } if (table === 'source_checkpoints') { return { sql: `SELECT * FROM source_checkpoints WHERE event_id IN (SELECT event_id FROM events WHERE segment_id IN (${segments})) ORDER BY rowid`, params: scope.segmentIds, }; } return null; } if (database === 'state-history') { if (table === 'history_scopes' || table === 'trajectory_records' || table === 'state_frames') { return { sql: `SELECT * FROM ${quoteIdentifier(table)} WHERE segment_id IN (${segments}) ORDER BY rowid`, params: scope.segmentIds, }; } return null; } if (table === 'runtime_epochs' || table === 'runtime_plugin_progress') { return { sql: `SELECT * FROM ${quoteIdentifier(table)} WHERE segment_id IN (${segments}) ORDER BY rowid`, params: scope.segmentIds, }; } if (table === 'runtime_plugin_outcomes' || table === 'runtime_plugin_states') { return { sql: `SELECT * FROM ${quoteIdentifier(table)} WHERE epoch_seq IN (SELECT epoch_seq FROM runtime_epochs WHERE segment_id IN (${segments})) ORDER BY rowid`, params: scope.segmentIds, }; } return null; } function gameScope(eventLedger: DatabaseLike, gameId: string): GameScopeSelection { const segments = eventLedger.prepare(` SELECT * FROM event_segments WHERE kind = 'game' AND scope_ref = ? ORDER BY opened_at, segment_seq `).all(gameId); if (segments.length === 0) throw new Error(`No local Runtime data found for game_id '${gameId}'.`); return { sessionIds: [...new Set(segments.map((row) => String(row.session_id)))], segmentIds: [...new Set(segments.map((row) => String(row.segment_id)))], segments, }; } function recordSegmentId(value: unknown): string | undefined { if (!value || typeof value !== 'object' || Array.isArray(value)) return undefined; const record = value as Record; return typeof record.scope?.segmentId === 'string' ? record.scope.segmentId : typeof record.scope?.segment_id === 'string' ? record.scope.segment_id : undefined; } async function exportDiagnostics( source: string, destination: string, segmentIds: ReadonlySet | null, ): Promise { const fd = openSync(destination, 'wx'); let count = 0; try { for (const path of rotatedJsonlSources(source)) { const input = createInterface({ input: createReadStream(path, { encoding: 'utf8' }), crlfDelay: Infinity, }); for await (const line of input) { if (!line.trim()) continue; if (segmentIds !== null) { let parsed: unknown; try { parsed = JSON.parse(line); } catch { continue; } const segmentId = recordSegmentId(parsed); if (!segmentId || !segmentIds.has(segmentId)) continue; } writeSync(fd, `${line}\n`, undefined, 'utf8'); count += 1; } } } finally { closeSync(fd); } return count; } function rotatedJsonlSources(path: string): string[] { const directory = dirname(path); if (!existsSync(directory)) return []; const activeName = basename(path); const rotated = readdirSync(directory) .map((entry) => { const match = new RegExp(`^${activeName.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}\\.(\\d+)$`).exec(entry); return match ? { path: join(directory, entry), generation: Number(match[1]) } : null; }) .filter((entry): entry is { path: string; generation: number } => entry !== null) .sort((left, right) => right.generation - left.generation) .map((entry) => entry.path); return [...rotated, ...(existsSync(path) ? [path] : [])]; } function rawFrameGameId(value: unknown): string | undefined { if (!value || typeof value !== 'object' || Array.isArray(value)) return undefined; const raw = (value as Record).raw; if (typeof raw !== 'string') return undefined; try { const frame = JSON.parse(raw) as Record; return typeof frame?.data?.game_id === 'string' ? frame.data.game_id : undefined; } catch { return undefined; } } async function exportRawWs( source: string | undefined, destination: string, gameId: string | null, ): Promise { const fd = openSync(destination, 'wx'); let count = 0; try { for (const path of source ? rotatedJsonlSources(source) : []) { const input = createInterface({ input: createReadStream(path, { encoding: 'utf8' }), crlfDelay: Infinity, }); for await (const line of input) { if (!line.trim()) continue; let parsed: unknown; try { parsed = JSON.parse(line); } catch { continue; } if (gameId !== null && rawFrameGameId(parsed) !== gameId) continue; writeSync(fd, `${line}\n`, undefined, 'utf8'); count += 1; } } } finally { closeSync(fd); } return count; } function prepareOutputDirectory(path: string): string { const output = resolve(path); if (existsSync(output)) throw new Error(`Export output already exists: ${output}`); mkdirSync(dirname(output), { recursive: true }); mkdirSync(output); return output; } /** Exports a bounded game segment or every local Runtime row without loading the dataset into memory. */ export async function exportRuntimeData(options: RuntimeDataExportOptions): Promise { const output = prepareOutputDirectory(options.outputDir); const opened: DatabaseLike[] = []; let completed = false; try { const eventLedger = openDatabase(options.paths.eventLedger); const stateHistory = openDatabase(options.paths.stateHistory); const inputJournal = openDatabase(options.paths.inputJournal); for (const database of [eventLedger, stateHistory, inputJournal]) if (database) opened.push(database); if (opened.length === 0) throw new Error('No local Runtime databases are available for export.'); let scope: GameScopeSelection | null = null; if (options.selection.kind === 'game') { if (!eventLedger) throw new Error('The Event Ledger is required to resolve a game_id.'); scope = gameScope(eventLedger, options.selection.gameId); } const rowCounts: Record = {}; const skippedTables: string[] = []; const databases = [ { name: 'event-ledger' as const, database: eventLedger }, { name: 'state-history' as const, database: stateHistory }, { name: 'runtime-epochs' as const, database: inputJournal }, ]; for (const entry of databases) { if (!entry.database) continue; const directory = join(output, entry.name); mkdirSync(directory); writeFileSync(join(directory, 'schema.sql'), `${databaseSchema(entry.database)}\n`, { flag: 'wx' }); for (const table of listTables(entry.database)) { const query = scope ? gameTableQuery(entry.name, table, scope) : allRows(table); if (!query) { skippedTables.push(`${entry.name}.${table}`); continue; } rowCounts[`${entry.name}.${table}`] = writeRows( entry.database, query, join(directory, `${table}.jsonl`), ); } } const diagnosticsDirectory = join(output, 'observability'); mkdirSync(diagnosticsDirectory); const diagnosticCount = await exportDiagnostics( options.paths.observability, join(diagnosticsDirectory, 'owner-runtime.jsonl'), scope ? new Set(scope.segmentIds) : null, ); const rawWsFrameCount = await exportRawWs( options.paths.rawWs, join(diagnosticsDirectory, 'game-sync.raw-ws.jsonl'), options.selection.kind === 'game' ? options.selection.gameId : null, ); const detailCaptureCount = await exportDiagnostics( options.paths.detailCapture ?? join(dirname(options.paths.observability), 'owner-detail.jsonl'), join(diagnosticsDirectory, 'owner-detail.jsonl'), scope ? new Set(scope.segmentIds) : null, ); const now = (options.now ?? (() => new Date()))().toISOString(); const manifest = { schema: 'clawclaw.runtime-data-export.v1', exported_at: now, selection: options.selection, sessions: scope?.sessionIds ?? [], segments: scope?.segments ?? [], row_counts: rowCounts, diagnostic_count: diagnosticCount, detail_capture_count: detailCaptureCount, raw_ws_frame_count: rawWsFrameCount, skipped_game_scoped_tables: skippedTables, format: 'One JSON object per line; schema.sql preserves the source table definitions.', }; writeFileSync(join(output, 'manifest.json'), `${JSON.stringify(manifest, null, 2)}\n`, { flag: 'wx' }); const result = { path: output, selection: options.selection, sessionIds: scope?.sessionIds ?? [], segmentIds: scope?.segmentIds ?? [], rowCounts, diagnosticCount, detailCaptureCount, rawWsFrameCount, }; completed = true; return result; } finally { for (const database of opened.reverse()) database.close(); if (!completed) rmSync(output, { recursive: true, force: true }); } }