@titan-design/session-graph 0.8.1 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -376,6 +376,9 @@ interface EpisodeRow {
376
376
  endOffset: number;
377
377
  /** `session_start`, `brief`, `channel_followup`, `idle_gap`, `pr_merge`, `spawn_wave_complete`, `task_wrap`, `context_reset`, or a newer heuristic's term. */
378
378
  openedBy: string;
379
+ /** The transcript `startOffset`/`endOffset` fall in; a session resumed across transcripts can differ between the two. */
380
+ startTranscriptId?: number | null;
381
+ endTranscriptId?: number | null;
379
382
  assignmentOffset?: number | null;
380
383
  firstDeliverableOffset?: number | null;
381
384
  firstDeliverableSignal?: string | null;
package/dist/index.js CHANGED
@@ -247,6 +247,13 @@ function applyOriginSchema(db) {
247
247
  for (const view of ORIGIN_VIEWS) db.exec(view);
248
248
  }
249
249
 
250
+ // src/audit-schema-v6.ts
251
+ var EPISODE_TRANSCRIPT_MIGRATION_NAME = "episode transcript ids";
252
+ function applyEpisodeTranscriptSchema(db) {
253
+ addColumnIfMissing(db, EPISODE_TABLE, "start_transcript_id", "INTEGER");
254
+ addColumnIfMissing(db, EPISODE_TABLE, "end_transcript_id", "INTEGER");
255
+ }
256
+
250
257
  // src/normalized-schema.ts
251
258
  import { conversationRef } from "@titan-design/agent-protocol";
252
259
  var NORMALIZED_DDL = `
@@ -457,7 +464,8 @@ var MIGRATIONS = [
457
464
  backfillClaudeAliases(db);
458
465
  } },
459
466
  { version: 4, name: AUDIT_MIGRATION_NAME, up: applyAuditSchema },
460
- { version: 5, name: ORIGIN_MIGRATION_NAME, up: applyOriginSchema }
467
+ { version: 5, name: ORIGIN_MIGRATION_NAME, up: applyOriginSchema },
468
+ { version: 6, name: EPISODE_TRANSCRIPT_MIGRATION_NAME, up: applyEpisodeTranscriptSchema }
461
469
  ];
462
470
 
463
471
  // src/graph.ts
@@ -1183,9 +1191,11 @@ async function exists(absolutePath) {
1183
1191
  var DELETE_EPISODES = `DELETE FROM ${EPISODE_TABLE} WHERE session_id = ? AND heuristic = ?`;
1184
1192
  var INSERT_EPISODE = `
1185
1193
  INSERT INTO ${EPISODE_TABLE} (session_id, episode_index, heuristic, heuristic_version, started_at, ended_at,
1186
- start_offset, end_offset, opened_by, assignment_offset, first_deliverable_offset, first_deliverable_signal, first_status_offset)
1194
+ start_offset, end_offset, start_transcript_id, end_transcript_id, opened_by, assignment_offset,
1195
+ first_deliverable_offset, first_deliverable_signal, first_status_offset)
1187
1196
  VALUES (@sessionId, @episodeIndex, @heuristic, @heuristicVersion, @startedAt, @endedAt,
1188
- @startOffset, @endOffset, @openedBy, @assignmentOffset, @firstDeliverableOffset, @firstDeliverableSignal, @firstStatusOffset)`;
1197
+ @startOffset, @endOffset, @startTranscriptId, @endTranscriptId, @openedBy, @assignmentOffset,
1198
+ @firstDeliverableOffset, @firstDeliverableSignal, @firstStatusOffset)`;
1189
1199
  function replaceEpisodes(graph, sessionId, heuristic, rows) {
1190
1200
  const remove = graph.db.prepare(DELETE_EPISODES);
1191
1201
  const insert = graph.db.prepare(INSERT_EPISODE);
@@ -1206,6 +1216,8 @@ function episodeParams(sessionId, heuristic, row) {
1206
1216
  startOffset: row.startOffset,
1207
1217
  endOffset: row.endOffset,
1208
1218
  openedBy: row.openedBy,
1219
+ startTranscriptId: row.startTranscriptId ?? null,
1220
+ endTranscriptId: row.endTranscriptId ?? null,
1209
1221
  assignmentOffset: row.assignmentOffset ?? null,
1210
1222
  firstDeliverableOffset: row.firstDeliverableOffset ?? null,
1211
1223
  firstDeliverableSignal: row.firstDeliverableSignal ?? null,
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/graph.ts","../src/audit-schema.ts","../src/audit-schema-v5.ts","../src/normalized-schema.ts","../src/schema.ts","../src/audit-apply.ts","../src/facet.ts","../src/apply.ts","../src/purge.ts","../src/audit-rollup.ts","../src/rollup.ts","../src/refresh.ts","../src/outcomes.ts","../src/origin.ts","../src/tasks.ts","../src/episodes.ts","../src/prices.ts","../src/normalized-index.ts","../src/normalized-project.ts","../src/normalized-query.ts"],"sourcesContent":["import { EdgeTable, SpanFtsTables, WatermarkTable, openDatabase, runMigrations, type Db } from \"@titan-design/store-sqlite\";\nimport { DERIVED_TABLES, KIT, MIGRATIONS } from \"./schema.js\";\n\n/** One open session graph: the connection plus the kit helpers bound to its tables. */\nexport interface SessionGraph {\n db: Db;\n transcripts: WatermarkTable;\n edges: EdgeTable;\n spans: SpanFtsTables;\n}\n\nexport interface OpenSessionGraphOptions {\n /**\n * The highest migration version the caller owns, checked before any migration runs.\n * A product layering its own tables on this graph passes its own top version, not this\n * package's: `MIGRATIONS` here is one band of a shared database, never the top of it.\n */\n schemaVersion?: number;\n}\n\nexport function openSessionGraph(dbPath: string, options: OpenSessionGraphOptions = {}): SessionGraph {\n const db = openDatabase(dbPath, { schemaVersion: options.schemaVersion });\n runMigrations(db, MIGRATIONS);\n return {\n db,\n transcripts: new WatermarkTable(db, { name: KIT.watermark }),\n edges: new EdgeTable(db, { name: KIT.edge }),\n spans: new SpanFtsTables(db, { name: KIT.spanFts }),\n };\n}\n\n/**\n * Clear every derived row and rewind all watermarks so the next refresh\n * rebuilds from byte 0. Rewinding alone is not enough: the accumulating\n * upserts would add a second copy of every count.\n */\nexport function resetIndex(graph: SessionGraph): void {\n graph.db.transaction(() => {\n for (const table of DERIVED_TABLES) graph.db.exec(`DELETE FROM \"${table}\"`);\n graph.spans.clearIndex();\n for (const row of graph.transcripts.list()) graph.transcripts.rewind(row.sourceKey);\n })();\n}\n\nexport function allSessionIds(graph: SessionGraph): string[] {\n return (graph.db.prepare(\"SELECT session_id FROM session\").all() as { session_id: string }[]).map((r) => r.session_id);\n}\n","import type { Db } from \"@titan-design/store-sqlite\";\n\n/** Recorded in `_migration`; store-sqlite refuses a database whose applied name differs, so never rename it. */\nexport const AUDIT_MIGRATION_NAME = \"audit tables\";\n\n/** Tables written per transcript by `applyAudit` and dropped by `purgeTranscript`. */\nexport const AUDIT_TABLES = [\n \"request\",\n \"tool_call\",\n \"inbound\",\n \"context_block\",\n \"compaction\",\n \"queue_op\",\n \"session_signal\",\n \"cost_state_observation\",\n] as const;\n\n/** Per-transcript read state for each audit facet; cleared with the audit rows so a re-read starts clean. */\nexport const FACET_TABLE = \"transcript_facet\";\n\nexport const AUDIT_DDL = `\n CREATE TABLE IF NOT EXISTS request (\n transcript_id INTEGER NOT NULL,\n request_id TEXT NOT NULL,\n byte_offset INTEGER NOT NULL, -- first line seen for this request\n session_id TEXT NOT NULL,\n message_id TEXT,\n ts TEXT NOT NULL,\n model TEXT NOT NULL,\n input_tokens INTEGER NOT NULL DEFAULT 0,\n cache_read_tokens INTEGER NOT NULL DEFAULT 0,\n cache_creation_tokens INTEGER NOT NULL DEFAULT 0,\n cache_creation_5m INTEGER NOT NULL DEFAULT 0,\n cache_creation_1h INTEGER NOT NULL DEFAULT 0,\n output_tokens INTEGER NOT NULL DEFAULT 0,\n thinking_tokens INTEGER NOT NULL DEFAULT 0,\n context_tokens INTEGER NOT NULL DEFAULT 0, -- input + cache_read + cache_creation\n service_tier TEXT,\n is_sidechain INTEGER NOT NULL DEFAULT 0,\n -- rollup-owned, recomputed for touched sessions:\n seq_in_session INTEGER,\n gap_ms INTEGER, -- since previous request in the session\n ctx_delta INTEGER, -- context_tokens - (prev.context_tokens + prev.output_tokens)\n wake_cause TEXT,\n wake_delivery TEXT,\n wake_detail TEXT, -- tool name, channel sender, or NULL\n wake_tool_family TEXT,\n wake_mcp_server TEXT,\n wake_offset INTEGER, -- byte_offset of the inbound row\n PRIMARY KEY (transcript_id, request_id)\n ) WITHOUT ROWID;\n CREATE INDEX IF NOT EXISTS idx_request_session_ts ON request(session_id, ts);\n CREATE INDEX IF NOT EXISTS idx_request_ts ON request(ts);\n CREATE INDEX IF NOT EXISTS idx_request_id ON request(request_id);\n\n CREATE TABLE IF NOT EXISTS tool_call (\n transcript_id INTEGER NOT NULL, byte_offset INTEGER NOT NULL, block_index INTEGER NOT NULL,\n session_id TEXT NOT NULL, ts TEXT NOT NULL, tool_use_id TEXT NOT NULL,\n name TEXT NOT NULL, family TEXT NOT NULL, mcp_server TEXT, input_chars INTEGER NOT NULL,\n PRIMARY KEY (transcript_id, byte_offset, block_index)\n ) WITHOUT ROWID;\n CREATE INDEX IF NOT EXISTS idx_tool_call_use ON tool_call(tool_use_id);\n\n CREATE TABLE IF NOT EXISTS inbound (\n transcript_id INTEGER NOT NULL, byte_offset INTEGER NOT NULL, block_index INTEGER NOT NULL,\n session_id TEXT NOT NULL, ts TEXT NOT NULL,\n cause TEXT NOT NULL, delivery TEXT NOT NULL, detail TEXT,\n origin_server TEXT, from_name TEXT, msg_id TEXT, tool_use_id TEXT,\n is_error INTEGER NOT NULL DEFAULT 0, content_hash TEXT NOT NULL, chars INTEGER NOT NULL,\n queued_ms INTEGER, -- rollup-owned\n PRIMARY KEY (transcript_id, byte_offset, block_index)\n ) WITHOUT ROWID;\n CREATE INDEX IF NOT EXISTS idx_inbound_session ON inbound(session_id, byte_offset);\n\n CREATE TABLE IF NOT EXISTS context_block (\n transcript_id INTEGER NOT NULL, byte_offset INTEGER NOT NULL, block_index INTEGER NOT NULL,\n session_id TEXT NOT NULL, ts TEXT NOT NULL, source TEXT NOT NULL,\n tool_use_id TEXT, attachment_type TEXT, chars INTEGER NOT NULL, is_media INTEGER NOT NULL DEFAULT 0,\n PRIMARY KEY (transcript_id, byte_offset, block_index)\n ) WITHOUT ROWID;\n CREATE INDEX IF NOT EXISTS idx_context_block_session ON context_block(session_id, source);\n\n CREATE TABLE IF NOT EXISTS compaction (\n transcript_id INTEGER NOT NULL, byte_offset INTEGER NOT NULL,\n session_id TEXT NOT NULL, ts TEXT NOT NULL, trigger TEXT,\n pre_tokens INTEGER, post_tokens INTEGER, dropped_tokens INTEGER, duration_ms INTEGER,\n mid_loop INTEGER, -- rollup-owned: previous inbound was a tool_result\n PRIMARY KEY (transcript_id, byte_offset)\n ) WITHOUT ROWID;\n\n CREATE TABLE IF NOT EXISTS queue_op (\n transcript_id INTEGER NOT NULL, byte_offset INTEGER NOT NULL,\n session_id TEXT NOT NULL, ts TEXT NOT NULL, operation TEXT NOT NULL,\n content_hash TEXT, origin_server TEXT,\n PRIMARY KEY (transcript_id, byte_offset)\n ) WITHOUT ROWID;\n CREATE INDEX IF NOT EXISTS idx_queue_op_hash ON queue_op(session_id, content_hash);\n\n CREATE TABLE IF NOT EXISTS session_signal (\n transcript_id INTEGER NOT NULL, byte_offset INTEGER NOT NULL, block_index INTEGER NOT NULL,\n session_id TEXT NOT NULL, ts TEXT NOT NULL, signal TEXT NOT NULL, detail TEXT, tool_use_id TEXT,\n -- one Bash block can emit up to three signals (commit, push, pr_create); the signal name disambiguates them\n PRIMARY KEY (transcript_id, byte_offset, block_index, signal)\n ) WITHOUT ROWID;\n CREATE INDEX IF NOT EXISTS idx_signal_session ON session_signal(session_id, ts);\n\n CREATE TABLE IF NOT EXISTS cost_state_observation (\n transcript_id INTEGER NOT NULL, byte_offset INTEGER NOT NULL,\n session_id TEXT NOT NULL, ts TEXT, total_cost_usd REAL NOT NULL, model_usage TEXT NOT NULL,\n PRIMARY KEY (transcript_id, byte_offset)\n ) WITHOUT ROWID;\n\n CREATE TABLE IF NOT EXISTS transcript_facet (\n transcript_id INTEGER NOT NULL, facet TEXT NOT NULL,\n version INTEGER NOT NULL, indexed_to INTEGER NOT NULL,\n PRIMARY KEY (transcript_id, facet)\n ) WITHOUT ROWID;\n`;\n\n/** `[table, column, type]`; `turn.wake_cause` is rollup-owned. */\nexport const AUDIT_COLUMNS = [\n [\"session\", \"account\", \"TEXT\"],\n [\"turn\", \"wake_cause\", \"TEXT\"],\n [\"task\", \"estimate\", \"REAL\"],\n [\"pr\", \"review_rounds\", \"INTEGER\"],\n [\"pr\", \"closed_at\", \"TEXT\"],\n [\"pr\", \"outcome_checked_at\", \"TEXT\"],\n] as const;\n\n/** The version 4 body. Safe to run twice: a database can reach version 4 after a partial manual repair. */\nexport function applyAuditSchema(db: Db): void {\n db.exec(AUDIT_DDL);\n for (const [table, column, type] of AUDIT_COLUMNS) addColumnIfMissing(db, table, column, type);\n}\n\n/** SQLite's `ADD COLUMN` has no `IF NOT EXISTS`, and a repeat throws \"duplicate column name\". */\nfunction addColumnIfMissing(db: Db, table: string, column: string, type: string): void {\n const present = db.prepare(\"SELECT 1 FROM pragma_table_info(?) WHERE name = ?\").get(table, column);\n if (!present) db.exec(`ALTER TABLE \"${table}\" ADD COLUMN \"${column}\" ${type}`);\n}\n","import type { Db } from \"@titan-design/store-sqlite\";\n\n/** Recorded in `_migration`; store-sqlite refuses a database whose applied name differs, so never rename it. */\nexport const ORIGIN_MIGRATION_NAME = \"origin, episodes, prices\";\n\n/** Re-derivable from their own sources rather than from transcripts, so `resetIndex` clears them and the next pass refills them. */\nexport const ORIGIN_TABLES = [\"session_origin\", \"session_external_event\"] as const;\n\n/** Written from transcript offsets by `replaceEpisodes`; a rewritten transcript invalidates them, so purge drops them by session. */\nexport const EPISODE_TABLE = \"episode\";\n\nexport const ORIGIN_DDL = `\n CREATE TABLE IF NOT EXISTS session_origin ( -- not derived from transcripts\n session_id TEXT PRIMARY KEY,\n origin_system TEXT NOT NULL, -- 'agent-chat'\n agent_id TEXT, agent_name TEXT, parent_name TEXT, parent_session_id TEXT,\n profile TEXT, model_alias TEXT, surface TEXT, isolation TEXT, depth INTEGER,\n origin_kind TEXT, -- spawned | adopted | inherited | human\n config_dir TEXT, spawn_cwd TEXT, spawned_at TEXT,\n brief_chars INTEGER, brief_excerpt TEXT, brief_path TEXT, launch_args TEXT,\n resolved_at TEXT NOT NULL\n );\n CREATE INDEX IF NOT EXISTS idx_origin_parent ON session_origin(parent_session_id);\n\n CREATE TABLE IF NOT EXISTS session_external_event ( -- teleport, handoff, retire, exit\n session_id TEXT NOT NULL, ts TEXT NOT NULL, origin_system TEXT NOT NULL,\n kind TEXT NOT NULL, detail TEXT,\n PRIMARY KEY (session_id, ts, kind)\n ) WITHOUT ROWID;\n\n CREATE TABLE IF NOT EXISTS episode ( -- provisional, see section 9\n session_id TEXT NOT NULL, episode_index INTEGER NOT NULL,\n heuristic TEXT NOT NULL, heuristic_version INTEGER NOT NULL,\n started_at TEXT NOT NULL, ended_at TEXT NOT NULL,\n start_offset INTEGER NOT NULL, end_offset INTEGER NOT NULL,\n opened_by TEXT NOT NULL, -- brief | channel_followup | idle_gap | compaction\n assignment_offset INTEGER, first_deliverable_offset INTEGER, first_deliverable_signal TEXT,\n first_status_offset INTEGER,\n PRIMARY KEY (session_id, heuristic, episode_index)\n ) WITHOUT ROWID;\n\n CREATE TABLE IF NOT EXISTS price (\n model TEXT NOT NULL, effective_from TEXT NOT NULL, table_version INTEGER NOT NULL,\n input_usd_mtok REAL NOT NULL, cache_read_usd_mtok REAL NOT NULL,\n cache_write_5m_usd_mtok REAL NOT NULL, cache_write_1h_usd_mtok REAL NOT NULL,\n output_usd_mtok REAL NOT NULL, source TEXT,\n PRIMARY KEY (model, effective_from)\n ) WITHOUT ROWID;\n`;\n\nconst REQUEST_COLUMNS = `transcript_id, request_id, byte_offset, session_id, message_id, ts, model,\n input_tokens, cache_read_tokens, cache_creation_tokens, cache_creation_5m, cache_creation_1h,\n output_tokens, thinking_tokens, context_tokens, service_tier, is_sidechain,\n seq_in_session, gap_ms, ctx_delta, wake_cause, wake_delivery, wake_detail,\n wake_tool_family, wake_mcp_server, wake_offset`;\n\n/** Fan-out copies of one request across transcripts collapse to the earliest `(ts, transcript_id)`. Every cost query reads this, never `request`. */\nconst REQUEST_DEDUP = `\n CREATE VIEW IF NOT EXISTS request_dedup AS\n SELECT ${REQUEST_COLUMNS} FROM (\n SELECT r.*, ROW_NUMBER() OVER (PARTITION BY r.request_id ORDER BY r.ts, r.transcript_id) AS copy_rank\n FROM request r\n ) WHERE copy_rank = 1;\n`;\n\n/**\n * Longest model prefix wins, so `claude-opus-5[1m]` prices as `claude-opus-5`; then the latest\n * `effective_from` at or before the request. An unmatched model reads `priced = 0` and costs 0,\n * never a guessed default. A split-less cache write (`5m + 1h = 0`) prices at the 5m rate.\n */\nconst REQUEST_COST = `\n CREATE VIEW IF NOT EXISTS request_cost AS\n WITH candidate AS (\n SELECT d.request_id, p.model AS price_model, p.effective_from AS price_effective_from,\n p.input_usd_mtok, p.cache_read_usd_mtok, p.cache_write_5m_usd_mtok, p.cache_write_1h_usd_mtok, p.output_usd_mtok,\n ROW_NUMBER() OVER (PARTITION BY d.request_id ORDER BY length(p.model) DESC, p.effective_from DESC) AS match_rank\n FROM request_dedup d\n JOIN price p ON substr(d.model, 1, length(p.model)) = p.model AND p.effective_from <= d.ts\n ), component AS (\n SELECT d.*, c.price_model, c.price_effective_from, c.price_model IS NOT NULL AS priced,\n COALESCE(d.input_tokens * c.input_usd_mtok, 0) / 1e6 AS input_cost_usd,\n COALESCE(d.cache_read_tokens * c.cache_read_usd_mtok, 0) / 1e6 AS cache_read_cost_usd,\n COALESCE(CASE WHEN d.cache_creation_5m + d.cache_creation_1h = 0 THEN d.cache_creation_tokens ELSE d.cache_creation_5m END\n * c.cache_write_5m_usd_mtok, 0) / 1e6 AS cache_write_5m_cost_usd,\n COALESCE(d.cache_creation_1h * c.cache_write_1h_usd_mtok, 0) / 1e6 AS cache_write_1h_cost_usd,\n COALESCE(d.output_tokens * c.output_usd_mtok, 0) / 1e6 AS output_cost_usd\n FROM request_dedup d\n LEFT JOIN candidate c ON c.request_id = d.request_id AND c.match_rank = 1\n )\n SELECT *,\n input_cost_usd + cache_read_cost_usd + cache_write_5m_cost_usd + cache_write_1h_cost_usd + output_cost_usd AS cost_usd,\n (cache_read_tokens < 0.2 * context_tokens AND cache_creation_tokens >= 20000) AS is_cold,\n CASE WHEN context_tokens < 50000 THEN '<50k' WHEN context_tokens < 100000 THEN '50-100k'\n WHEN context_tokens < 200000 THEN '100-200k' ELSE '200k+' END AS context_band,\n CASE WHEN gap_ms IS NULL THEN NULL WHEN gap_ms < 300000 THEN '<5m'\n WHEN gap_ms < 3600000 THEN '5-60m' ELSE '>60m' END AS gap_band\n FROM component;\n`;\n\nconst ASSISTANT_OUTPUT = \"'assistant_text', 'assistant_thinking', 'assistant_tool_input'\";\n\n/**\n * A block belongs to the first request after it in its transcript; a block on the request's own\n * line is that request's output and so feeds the next one. Blocks whose request is a fan-out copy\n * drop out with it, keeping estimates aligned with `request_dedup`. Assistant output is already\n * subtracted from `ctx_delta`, so those rows stay visible with a NULL `est_tokens` and no share.\n */\nconst CONTEXT_CONTRIBUTION = `\n CREATE VIEW IF NOT EXISTS context_contribution AS\n WITH stream AS (\n SELECT transcript_id, byte_offset, 0 AS lane, block_index, NULL AS request_id FROM context_block\n UNION ALL\n SELECT transcript_id, byte_offset, -1 AS lane, 0, request_id FROM request\n ), ordered AS (\n SELECT *, COUNT(request_id) OVER (PARTITION BY transcript_id ORDER BY byte_offset, lane, block_index ROWS UNBOUNDED PRECEDING) AS requests_before\n FROM stream\n ), owner AS (\n SELECT b.transcript_id, b.byte_offset, b.block_index, r.request_id\n FROM ordered b JOIN ordered r ON r.transcript_id = b.transcript_id AND r.lane = -1 AND r.requests_before = b.requests_before + 1\n WHERE b.lane = 0\n ), tool AS (\n SELECT tool_use_id, name, family, mcp_server,\n ROW_NUMBER() OVER (PARTITION BY tool_use_id ORDER BY transcript_id, byte_offset, block_index) AS copy_rank\n FROM tool_call\n )\n SELECT cb.transcript_id, cb.byte_offset, cb.block_index, cb.session_id, cb.ts, cb.source,\n cb.tool_use_id, cb.attachment_type, cb.chars, cb.is_media, o.request_id, d.ctx_delta,\n CASE WHEN cb.source IN (${ASSISTANT_OUTPUT}) THEN NULL\n ELSE d.ctx_delta * cb.chars * 1.0 / NULLIF(SUM(CASE WHEN cb.source IN (${ASSISTANT_OUTPUT}) THEN 0 ELSE cb.chars END)\n OVER (PARTITION BY o.transcript_id, o.request_id), 0) END AS est_tokens,\n t.name AS tool_name, t.family AS tool_family, t.mcp_server\n FROM context_block cb\n JOIN owner o USING (transcript_id, byte_offset, block_index)\n JOIN request_dedup d ON d.transcript_id = o.transcript_id AND d.request_id = o.request_id\n LEFT JOIN tool t ON t.tool_use_id = cb.tool_use_id AND t.copy_rank = 1;\n`;\n\nexport const ORIGIN_VIEWS = [REQUEST_DEDUP, REQUEST_COST, CONTEXT_CONTRIBUTION] as const;\n\n/** The version 5 body. Every statement is `IF NOT EXISTS`, so a repeat run is a no-op. */\nexport function applyOriginSchema(db: Db): void {\n db.exec(ORIGIN_DDL);\n for (const view of ORIGIN_VIEWS) db.exec(view);\n}\n","import { conversationRef } from \"@titan-design/agent-protocol\";\nimport type { Db } from \"@titan-design/store-sqlite\";\n\n/** Additive: legacy rows, aliases and original locators are never rewritten. */\nexport const NORMALIZED_DDL = `\nCREATE TABLE IF NOT EXISTS conversation (\n ref TEXT PRIMARY KEY, harness TEXT NOT NULL, namespace TEXT NOT NULL,\n native_id TEXT NOT NULL, legacy_session_id TEXT,\n UNIQUE(harness, namespace, native_id)\n);\nCREATE TABLE IF NOT EXISTS conversation_alias (\n legacy_ref TEXT NOT NULL, conversation_ref TEXT NOT NULL,\n PRIMARY KEY(legacy_ref, conversation_ref)\n);\nCREATE TABLE IF NOT EXISTS normalized_source (\n transcript_id INTEGER PRIMARY KEY, source_id TEXT NOT NULL UNIQUE,\n conversation_ref TEXT NOT NULL, descriptor TEXT NOT NULL\n);\nCREATE TABLE IF NOT EXISTS normalized_event (\n transcript_id INTEGER NOT NULL, byte_offset INTEGER NOT NULL,\n subrecord_index INTEGER NOT NULL, byte_length INTEGER NOT NULL,\n conversation_ref TEXT NOT NULL, kind TEXT NOT NULL, ts TEXT,\n turn_ref TEXT, call_ref TEXT, item_ref TEXT, phase TEXT, is_error INTEGER,\n usage TEXT, metadata TEXT, history_origin TEXT, related_ref TEXT, relationship TEXT,\n PRIMARY KEY(transcript_id, byte_offset, subrecord_index)\n);\nCREATE INDEX IF NOT EXISTS idx_normalized_event_conversation ON normalized_event(conversation_ref, ts);\nCREATE TABLE IF NOT EXISTS normalized_span (\n span_id INTEGER PRIMARY KEY, locators TEXT NOT NULL\n);\n`;\n\n/** Only the old transcript session table proves Claude provenance, never a ref prefix. */\nexport function backfillClaudeAliases(db: Db, sessionIds?: readonly string[]): void {\n const insert = db.prepare(\"INSERT OR IGNORE INTO conversation(ref,harness,namespace,native_id,legacy_session_id) VALUES (?,?,?,?,?)\");\n const alias = db.prepare(\"INSERT OR IGNORE INTO conversation_alias VALUES (?,?)\");\n const rows = sessionIds?.map(session_id => ({ session_id })) ?? db.prepare(\"SELECT session_id FROM session\").all() as Iterable<{ session_id: string }>;\n for (const row of rows) {\n const ref = conversationRef({ harness: \"claude-code\", namespace: \"legacy\", nativeId: row.session_id });\n insert.run(ref, \"claude-code\", \"legacy\", row.session_id, row.session_id);\n alias.run(`session:${row.session_id}`, ref);\n }\n}\n\n/** Ambiguity is explicit; workspace session bodies remain in their original namespace. */\nexport function resolveConversationAlias(db: Db, legacyRef: string): string | null {\n const rows = db.prepare(\"SELECT conversation_ref FROM conversation_alias WHERE legacy_ref = ?\").all(legacyRef) as { conversation_ref: string }[];\n if (rows.length > 1) throw new Error(`ambiguous conversation alias: ${legacyRef}`);\n return rows[0]?.conversation_ref ?? null;\n}\n","import { AUDIT_MIGRATION_NAME, AUDIT_TABLES, FACET_TABLE, applyAuditSchema } from \"./audit-schema.js\";\nimport { EPISODE_TABLE, ORIGIN_MIGRATION_NAME, ORIGIN_TABLES, applyOriginSchema } from \"./audit-schema-v5.js\";\nimport { NORMALIZED_DDL, backfillClaudeAliases } from \"./normalized-schema.js\";\nimport { SQL_NOW, kitMigration, type Migration } from \"@titan-design/store-sqlite\";\n\n/** Kit table names this graph uses. `watermark` rows are transcripts; `search_*` are the FTS spans. */\nexport const KIT = { watermark: \"transcript\", edge: \"edge\", spanFts: \"search\" } as const;\n\n/**\n * Legacy domain tables. Original sources can be pruned; schema migrations must\n * preserve these rows rather than assuming a replay is possible.\n * Locators are `(transcript_id, byte_offset, byte_length)`; `fact_id` rows\n * resolve through the facts table's unique `(transcript_id, byte_offset)`.\n */\nexport const DOMAIN_DDL = `\n CREATE TABLE IF NOT EXISTS fact (\n fact_id INTEGER PRIMARY KEY,\n transcript_id INTEGER NOT NULL,\n byte_offset INTEGER NOT NULL,\n byte_length INTEGER NOT NULL,\n event_type TEXT NOT NULL,\n ts TEXT NOT NULL,\n seq INTEGER NOT NULL,\n session_id TEXT NOT NULL,\n prompt_id TEXT,\n tool_use_id TEXT,\n t_indexed TEXT NOT NULL DEFAULT (${SQL_NOW}),\n UNIQUE (transcript_id, byte_offset)\n );\n CREATE INDEX IF NOT EXISTS idx_fact_session_ts ON fact(session_id, ts);\n CREATE INDEX IF NOT EXISTS idx_fact_prompt ON fact(prompt_id);\n CREATE INDEX IF NOT EXISTS idx_fact_tool_use ON fact(tool_use_id);\n\n CREATE TABLE IF NOT EXISTS session (\n session_id TEXT PRIMARY KEY,\n transcript_id INTEGER,\n started_at TEXT,\n ended_at TEXT,\n start_type TEXT,\n cwd TEXT,\n git_branch TEXT,\n ai_title TEXT,\n seed_prompt TEXT,\n cli_version TEXT,\n turn_count INTEGER NOT NULL DEFAULT 0,\n commit_count INTEGER NOT NULL DEFAULT 0,\n push_count INTEGER NOT NULL DEFAULT 0\n );\n CREATE INDEX IF NOT EXISTS idx_session_started ON session(started_at);\n\n CREATE TABLE IF NOT EXISTS session_model_usage (\n session_id TEXT NOT NULL,\n model TEXT NOT NULL,\n input_tokens INTEGER NOT NULL DEFAULT 0,\n output_tokens INTEGER NOT NULL DEFAULT 0,\n cache_read_tokens INTEGER NOT NULL DEFAULT 0,\n cache_creation_tokens INTEGER NOT NULL DEFAULT 0,\n thinking_tokens INTEGER NOT NULL DEFAULT 0,\n request_count INTEGER NOT NULL DEFAULT 0,\n PRIMARY KEY (session_id, model)\n );\n\n CREATE TABLE IF NOT EXISTS turn (\n prompt_id TEXT PRIMARY KEY,\n session_id TEXT NOT NULL,\n turn_index INTEGER NOT NULL,\n started_at TEXT NOT NULL,\n ended_at TEXT,\n duration_ms INTEGER,\n tool_call_count INTEGER NOT NULL DEFAULT 0,\n thinking_ms INTEGER NOT NULL DEFAULT 0,\n fact_id_start INTEGER\n );\n CREATE INDEX IF NOT EXISTS idx_turn_session ON turn(session_id, turn_index);\n\n CREATE TABLE IF NOT EXISTS permission_phase (\n phase_id INTEGER PRIMARY KEY,\n session_id TEXT NOT NULL,\n from_mode TEXT,\n to_mode TEXT NOT NULL,\n trigger TEXT NOT NULL,\n t_valid TEXT NOT NULL,\n t_invalid TEXT,\n fact_id INTEGER\n );\n CREATE INDEX IF NOT EXISTS idx_phase_session ON permission_phase(session_id, t_valid);\n\n CREATE TABLE IF NOT EXISTS human_edit (\n edit_id INTEGER PRIMARY KEY,\n session_id TEXT NOT NULL,\n file_path TEXT NOT NULL,\n ts TEXT NOT NULL,\n fact_id INTEGER,\n UNIQUE (session_id, file_path, ts)\n );\n\n CREATE TABLE IF NOT EXISTS file_checkpoint (\n checkpoint_id INTEGER PRIMARY KEY,\n session_id TEXT NOT NULL,\n file_path TEXT NOT NULL,\n backup_file_name TEXT NOT NULL,\n version INTEGER NOT NULL,\n backup_time TEXT NOT NULL,\n fact_id INTEGER,\n UNIQUE (session_id, file_path, backup_file_name)\n );\n\n CREATE TABLE IF NOT EXISTS pr (\n pr_ref TEXT PRIMARY KEY, number INTEGER, repo TEXT, title TEXT, state TEXT, url TEXT, merged_at TEXT\n );\n CREATE TABLE IF NOT EXISTS branch (\n branch_ref TEXT PRIMARY KEY, repo TEXT, name TEXT NOT NULL, base TEXT, created_at TEXT, deleted_at TEXT\n );\n CREATE TABLE IF NOT EXISTS file (\n file_ref TEXT PRIMARY KEY, repo TEXT, path TEXT NOT NULL\n );\n CREATE TABLE IF NOT EXISTS task (\n task_ref TEXT PRIMARY KEY, task_id TEXT NOT NULL, initiative TEXT, title TEXT, status TEXT\n );\n CREATE TABLE IF NOT EXISTS subagent (\n agent_ref TEXT PRIMARY KEY,\n session_id TEXT,\n child_session_id TEXT,\n parent_agent_ref TEXT,\n agent_type TEXT,\n label TEXT,\n started_at TEXT,\n ended_at TEXT,\n fact_id INTEGER\n );\n CREATE INDEX IF NOT EXISTS idx_subagent_child ON subagent(child_session_id);\n CREATE TABLE IF NOT EXISTS artifact (\n artifact_ref TEXT PRIMARY KEY, kind TEXT, title TEXT, url TEXT, path TEXT, created_at TEXT\n );\n CREATE TABLE IF NOT EXISTS pr_merge_observation (\n number INTEGER NOT NULL, repo_hint TEXT, merged_at TEXT NOT NULL,\n PRIMARY KEY (number, repo_hint, merged_at)\n );\n CREATE TABLE IF NOT EXISTS pr_create_observation (\n tool_use_id TEXT PRIMARY KEY, title TEXT, number INTEGER, repo TEXT, url TEXT\n );\n`;\n\n/** Every derived table, in an order safe to clear. The watermark table is not derived. */\nexport const DERIVED_TABLES = [\n \"normalized_span\",\n \"normalized_event\",\n \"normalized_source\",\n `${KIT.spanFts}_span`,\n KIT.edge,\n \"turn\",\n \"permission_phase\",\n \"human_edit\",\n \"file_checkpoint\",\n \"subagent\",\n ...AUDIT_TABLES,\n FACET_TABLE,\n ...ORIGIN_TABLES,\n EPISODE_TABLE,\n \"session_model_usage\",\n \"session\",\n \"fact\",\n \"pr\",\n \"pr_merge_observation\",\n \"pr_create_observation\",\n \"branch\",\n \"file\",\n \"task\",\n \"artifact\",\n] as const;\n\nexport const MIGRATIONS: Migration[] = [\n kitMigration(1, { watermark: KIT.watermark, edge: KIT.edge, spanFts: KIT.spanFts }, \"kit tables\"),\n { version: 2, name: \"session graph tables\", up: (db) => db.exec(DOMAIN_DDL) },\n { version: 3, name: \"normalized conversations and source evidence\", up: (db) => { db.exec(NORMALIZED_DDL); backfillClaudeAliases(db); } },\n { version: 4, name: AUDIT_MIGRATION_NAME, up: applyAuditSchema },\n { version: 5, name: ORIGIN_MIGRATION_NAME, up: applyOriginSchema },\n];\n","import type { TranscriptDelta } from \"@titan-design/session-read\";\nimport type { Db } from \"@titan-design/store-sqlite\";\n\ntype Row = Record<string, unknown>;\n\n/**\n * One API response is written as several assistant lines, each repeating its\n * usage. The row keeps the first line's identity and the largest count seen,\n * so a partial streaming copy never wins and chunk order cannot change it.\n */\nconst UPSERT_REQUEST = `\n INSERT INTO request (transcript_id, request_id, byte_offset, session_id, message_id, ts, model,\n input_tokens, cache_read_tokens, cache_creation_tokens, cache_creation_5m, cache_creation_1h,\n output_tokens, thinking_tokens, context_tokens, service_tier, is_sidechain)\n VALUES (@transcriptId, @requestId, @byteOffset, @sessionId, @messageId, @ts, @model,\n @inputTokens, @cacheReadTokens, @cacheCreationTokens, @cacheCreation5mTokens, @cacheCreation1hTokens,\n @outputTokens, @thinkingTokens, @inputTokens + @cacheReadTokens + @cacheCreationTokens, @serviceTier, @isSidechain)\n ON CONFLICT (transcript_id, request_id) DO UPDATE SET\n session_id = CASE WHEN excluded.byte_offset < byte_offset THEN excluded.session_id ELSE session_id END,\n message_id = CASE WHEN excluded.byte_offset < byte_offset THEN excluded.message_id ELSE message_id END,\n model = CASE WHEN excluded.byte_offset < byte_offset THEN excluded.model ELSE model END,\n service_tier = CASE WHEN excluded.byte_offset < byte_offset THEN excluded.service_tier ELSE service_tier END,\n is_sidechain = CASE WHEN excluded.byte_offset < byte_offset THEN excluded.is_sidechain ELSE is_sidechain END,\n byte_offset = MIN(byte_offset, excluded.byte_offset),\n ts = MIN(ts, excluded.ts),\n input_tokens = MAX(input_tokens, excluded.input_tokens),\n cache_read_tokens = MAX(cache_read_tokens, excluded.cache_read_tokens),\n cache_creation_tokens = MAX(cache_creation_tokens, excluded.cache_creation_tokens),\n cache_creation_5m = MAX(cache_creation_5m, excluded.cache_creation_5m),\n cache_creation_1h = MAX(cache_creation_1h, excluded.cache_creation_1h),\n output_tokens = MAX(output_tokens, excluded.output_tokens),\n thinking_tokens = MAX(thinking_tokens, excluded.thinking_tokens),\n context_tokens = MAX(input_tokens, excluded.input_tokens) + MAX(cache_read_tokens, excluded.cache_read_tokens)\n + MAX(cache_creation_tokens, excluded.cache_creation_tokens)`;\n\n/** Line-located rows are facts about one position in the file, so a re-read of the same bytes is a no-op. */\nconst INSERTS = {\n toolCalls: `INSERT INTO tool_call (transcript_id, byte_offset, block_index, session_id, ts, tool_use_id, name, family, mcp_server, input_chars)\n VALUES (@transcriptId, @byteOffset, @blockIndex, @sessionId, @ts, @toolUseId, @name, @family, @mcpServer, @inputChars)\n ON CONFLICT DO NOTHING`,\n inbound: `INSERT INTO inbound (transcript_id, byte_offset, block_index, session_id, ts, cause, delivery, detail, origin_server, from_name, msg_id, tool_use_id, is_error, content_hash, chars)\n VALUES (@transcriptId, @byteOffset, @blockIndex, @sessionId, @ts, @cause, @delivery, @detail, @originServer, @fromName, @msgId, @toolUseId, @isError, @contentHash, @chars)\n ON CONFLICT DO NOTHING`,\n contextBlocks: `INSERT INTO context_block (transcript_id, byte_offset, block_index, session_id, ts, source, tool_use_id, attachment_type, chars, is_media)\n VALUES (@transcriptId, @byteOffset, @blockIndex, @sessionId, @ts, @source, @toolUseId, @attachmentType, @chars, @isMedia)\n ON CONFLICT DO NOTHING`,\n compactions: `INSERT INTO compaction (transcript_id, byte_offset, session_id, ts, trigger, pre_tokens, post_tokens, dropped_tokens, duration_ms)\n VALUES (@transcriptId, @byteOffset, @sessionId, @ts, @trigger, @preTokens, @postTokens, @droppedTokens, @durationMs)\n ON CONFLICT DO NOTHING`,\n queueOps: `INSERT INTO queue_op (transcript_id, byte_offset, session_id, ts, operation, content_hash, origin_server)\n VALUES (@transcriptId, @byteOffset, @sessionId, @ts, @operation, @contentHash, @originServer)\n ON CONFLICT DO NOTHING`,\n signals: `INSERT INTO session_signal (transcript_id, byte_offset, block_index, session_id, ts, signal, detail, tool_use_id)\n VALUES (@transcriptId, @byteOffset, @blockIndex, @sessionId, @ts, @signal, @detail, @toolUseId)\n ON CONFLICT DO NOTHING`,\n costStates: `INSERT INTO cost_state_observation (transcript_id, byte_offset, session_id, ts, total_cost_usd, model_usage)\n VALUES (@transcriptId, @byteOffset, @sessionId, @ts, @totalCostUsd, @modelUsageJson)\n ON CONFLICT DO NOTHING`,\n} as const;\n\n/** Write one delta's audit events. Runs inside `applyDelta`'s transaction, so it opens none of its own. */\nexport function applyAudit(db: Db, transcriptId: number, delta: TranscriptDelta): void {\n run(db, UPSERT_REQUEST, transcriptId, delta.requests);\n for (const [list, sql] of Object.entries(INSERTS) as [keyof typeof INSERTS, string][]) {\n run(db, sql, transcriptId, delta[list]);\n }\n}\n\nfunction run(db: Db, sql: string, transcriptId: number, events: readonly object[]): void {\n if (events.length === 0) return;\n const statement = db.prepare(sql);\n const names = [...new Set([...sql.matchAll(/@(\\w+)/g)].map((m) => m[1]!))];\n for (const event of events) statement.run(bind(names, { ...(event as Row), transcriptId }));\n}\n\n/** better-sqlite3 rejects unused named parameters and cannot bind booleans. */\nfunction bind(names: readonly string[], row: Row): Row {\n return Object.fromEntries(names.map((name) => {\n const value = row[name] ?? null;\n return [name, typeof value === \"boolean\" ? Number(value) : value];\n }));\n}\n","import { EXTRACT_VERSION, TranscriptParseError, extractTranscript, type DiscoveredTranscript, type TranscriptDelta } from \"@titan-design/session-read\";\nimport type { Db, WatermarkRow } from \"@titan-design/store-sqlite\";\nimport { applyAudit } from \"./audit-apply.js\";\nimport { AUDIT_TABLES, FACET_TABLE } from \"./audit-schema.js\";\nimport type { SessionGraph } from \"./graph.js\";\n\n/** The one facet today: the eight audit tables, all written from the same extraction. */\nexport const AUDIT_FACET = \"audit\";\n\n/** Transcripts re-extracted per pass, so a daemon's pass stays short while the backlog drains. */\nexport const DEFAULT_FACET_LIMIT = 40;\n\nexport interface BackfillOptions {\n /** Transcripts visited this pass. `Infinity` clears the whole backlog. */\n limit?: number;\n /** The extraction version a facet must reach. Defaults to session-read's `EXTRACT_VERSION`. */\n version?: number;\n}\n\nexport interface BackfillSummary {\n backfilled: number;\n /** Stale transcripts left for later passes. */\n backlog: number;\n /** Sessions whose audit rows were rebuilt, for the caller's rollup. */\n sessionIds: string[];\n}\n\ninterface Candidate {\n row: WatermarkRow;\n transcript: DiscoveredTranscript;\n}\n\n/**\n * Bring the audit facet of already-indexed transcripts up to `version` without a\n * full rebuild: re-read each one up to its watermark and replace only its audit\n * rows. Legacy tables are never written, so their accumulating counts cannot double.\n */\nexport async function backfillFacets(graph: SessionGraph, transcripts: readonly DiscoveredTranscript[], options: BackfillOptions = {}): Promise<BackfillSummary> {\n const version = options.version ?? EXTRACT_VERSION;\n const stale = staleTranscripts(graph, transcripts, version);\n const visit = stale.slice(0, options.limit ?? DEFAULT_FACET_LIMIT);\n const sessionIds = new Set<string>();\n let backfilled = 0;\n for (const candidate of visit) {\n const touched = await backfillOne(graph, candidate, version);\n if (!touched) continue;\n backfilled += 1;\n for (const id of touched) sessionIds.add(id);\n }\n return { backfilled, backlog: stale.length - visit.length, sessionIds: [...sessionIds] };\n}\n\n/** Discovered, status `ok`, and below `version`; newest first so recent cost history lands first. */\nfunction staleTranscripts(graph: SessionGraph, transcripts: readonly DiscoveredTranscript[], version: number): Candidate[] {\n const byPath = new Map(transcripts.map((t) => [t.displayPath, t]));\n const versions = facetVersions(graph.db);\n const stale: Candidate[] = [];\n for (const row of graph.transcripts.list()) {\n const transcript = byPath.get(row.sourceKey);\n if (!transcript || row.status !== \"ok\" || (versions.get(row.sourceId) ?? -1) >= version) continue;\n stale.push({ row, transcript });\n }\n return stale.sort((a, b) => (b.row.fileMtime ?? \"\").localeCompare(a.row.fileMtime ?? \"\"));\n}\n\nfunction facetVersions(db: Db): Map<number, number> {\n const rows = db.prepare(`SELECT transcript_id, version FROM ${FACET_TABLE} WHERE facet = ?`).all(AUDIT_FACET) as { transcript_id: number; version: number }[];\n return new Map(rows.map((r) => [r.transcript_id, r.version]));\n}\n\n/** Returns the sessions touched, or `null` when the file could not be re-read and was marked instead. */\nasync function backfillOne(graph: SessionGraph, { row, transcript }: Candidate, version: number): Promise<string[] | null> {\n let delta: TranscriptDelta & { lastByteOffset: number };\n try {\n delta = await extractTranscript(transcript.absolutePath, { untilByteOffset: row.lastOffset, subagentId: transcript.subagentId });\n } catch (err) {\n // Mark rather than skip, or a broken file would hold a slot at the head of every pass.\n const status = unreadableStatus(err);\n if (!status) throw err;\n graph.transcripts.markStatus(row.sourceKey, status, err instanceof Error ? err.message : String(err));\n return null;\n }\n graph.db.transaction(() => {\n for (const table of AUDIT_TABLES) graph.db.prepare(`DELETE FROM \"${table}\" WHERE transcript_id = ?`).run(row.sourceId);\n applyAudit(graph.db, row.sourceId, delta);\n writeFacet(graph.db, row.sourceId, version, delta.lastByteOffset);\n })();\n return delta.sessions.map((s) => s.sessionId);\n}\n\nfunction unreadableStatus(err: unknown): \"missing\" | \"quarantined\" | null {\n if (err instanceof TranscriptParseError) return \"quarantined\";\n if ((err as NodeJS.ErrnoException | null)?.code === \"ENOENT\") return \"missing\";\n return null;\n}\n\nfunction writeFacet(db: Db, transcriptId: number, version: number, indexedTo: number): void {\n db.prepare(`\n INSERT INTO ${FACET_TABLE} (transcript_id, facet, version, indexed_to) VALUES (?, ?, ?, ?)\n ON CONFLICT (transcript_id, facet) DO UPDATE SET version = excluded.version, indexed_to = excluded.indexed_to`)\n .run(transcriptId, AUDIT_FACET, version, indexedTo);\n}\n\n/**\n * Record a forward read. A read from byte 0 covers the whole file, so it sets the\n * facet outright; a resumed read only extends a facet that is already current,\n * because the bytes before it may predate the audit tables.\n */\nexport function advanceFacet(db: Db, transcriptId: number, fromByteOffset: number, indexedTo: number, version: number = EXTRACT_VERSION): void {\n if (fromByteOffset === 0) {\n writeFacet(db, transcriptId, version, indexedTo);\n return;\n }\n db.prepare(`UPDATE ${FACET_TABLE} SET indexed_to = ? WHERE transcript_id = ? AND facet = ? AND version = ?`)\n .run(indexedTo, transcriptId, AUDIT_FACET, version);\n}\n","import { applyAudit } from \"./audit-apply.js\";\nimport { backfillClaudeAliases } from \"./normalized-schema.js\";\nimport { sessionRef, type TranscriptDelta } from \"@titan-design/session-read\";\nimport type { Db } from \"@titan-design/store-sqlite\";\nimport type { SessionGraph } from \"./graph.js\";\n\n/**\n * Apply one transcript chunk's delta in a single transaction, so a crash can\n * never leave rows committed behind a stale watermark or ahead of their rows.\n * Append-only tables are idempotent through unique indexes; session rows\n * accumulate; usage is left to the rollup, which recomputes it from `request`;\n * ref-keyed assets insert-if-absent with COALESCE merges that mirror\n * `EventFolder`'s rules.\n */\nexport function applyDelta(graph: SessionGraph, transcriptId: number, delta: TranscriptDelta, source: DeltaSource = {}): void {\n graph.db.transaction(() => {\n applyFacts(graph.db, transcriptId, delta);\n applySessions(graph.db, transcriptId, delta, source.account ?? null);\n backfillClaudeAliases(graph.db, delta.sessions.map(s => s.sessionId));\n applyAssets(graph.db, delta);\n applyPhases(graph.db, transcriptId, delta);\n applyLinkedRows(graph, transcriptId, delta);\n applyAudit(graph.db, transcriptId, delta);\n })();\n}\n\n/** What discovery knows about the file that the lines themselves do not carry. */\nexport interface DeltaSource {\n /** The Claude config dir the transcript was found under; `null` when discovery did not say. */\n account?: string | null;\n}\n\nconst INSERT_FACT = `\n INSERT INTO fact (transcript_id, byte_offset, byte_length, event_type, ts, seq, session_id, prompt_id, tool_use_id)\n VALUES (@transcriptId, @byteOffset, @byteLength, @eventType, @ts, @seq, @sessionId, @promptId, @toolUseId)\n ON CONFLICT (transcript_id, byte_offset) DO NOTHING`;\n\n/** Facts carry a per-transcript `seq` continuing from whatever is stored. */\nfunction applyFacts(db: Db, transcriptId: number, delta: TranscriptDelta): void {\n const next = db.prepare(\"SELECT COALESCE(MAX(seq), -1) + 1 AS next FROM fact WHERE transcript_id = ?\").get(transcriptId) as { next: number };\n const insert = db.prepare(INSERT_FACT);\n let seq = next.next;\n for (const f of delta.facts) {\n insert.run({ transcriptId, byteOffset: f.byteOffset, byteLength: f.byteLength, eventType: f.eventType, ts: f.ts, seq: seq++, sessionId: f.sessionId, promptId: f.promptId, toolUseId: f.toolUseId });\n }\n}\n\nconst UPSERT_SESSION = `\n INSERT INTO session (session_id, transcript_id, started_at, ended_at, start_type, cwd, git_branch, ai_title, seed_prompt, cli_version, account, turn_count, commit_count, push_count)\n VALUES (@sessionId, @transcriptId, @startedAt, @endedAt, @startType, @cwd, @gitBranch, @aiTitle, @seedPrompt, @cliVersion, @account, @turnDelta, @commitDelta, @pushDelta)\n ON CONFLICT (session_id) DO UPDATE SET\n started_at = MIN(COALESCE(started_at, excluded.started_at), COALESCE(excluded.started_at, started_at)),\n ended_at = MAX(COALESCE(ended_at, excluded.ended_at), COALESCE(excluded.ended_at, ended_at)),\n start_type = CASE\n WHEN excluded.start_type IS NULL THEN start_type\n WHEN start_type IS NULL THEN excluded.start_type\n WHEN COALESCE(excluded.started_at, started_at) < COALESCE(started_at, excluded.started_at) THEN excluded.start_type\n ELSE start_type END,\n cwd = COALESCE(excluded.cwd, cwd),\n git_branch = COALESCE(git_branch, excluded.git_branch),\n ai_title = COALESCE(excluded.ai_title, ai_title),\n seed_prompt = COALESCE(seed_prompt, excluded.seed_prompt),\n cli_version = COALESCE(excluded.cli_version, cli_version),\n account = COALESCE(excluded.account, account),\n turn_count = turn_count + excluded.turn_count,\n commit_count = commit_count + excluded.commit_count,\n push_count = push_count + excluded.push_count`;\n\nfunction applySessions(db: Db, transcriptId: number, delta: TranscriptDelta, account: string | null): void {\n const upsertSession = db.prepare(UPSERT_SESSION);\n for (const s of delta.sessions) upsertSession.run({ ...s, transcriptId, account });\n}\n\nconst ASSET_UPSERTS = {\n prs: `INSERT INTO pr (pr_ref, number, repo, title, url) VALUES (@prRef, @number, @repo, @title, @url)\n ON CONFLICT (pr_ref) DO UPDATE SET title = COALESCE(title, excluded.title), url = COALESCE(url, excluded.url)`,\n branches: `INSERT INTO branch (branch_ref, repo, name, base, created_at, deleted_at) VALUES (@branchRef, @repo, @name, @base, @createdAt, @deletedAt)\n ON CONFLICT (branch_ref) DO UPDATE SET base = COALESCE(base, excluded.base),\n created_at = MIN(COALESCE(created_at, excluded.created_at), COALESCE(excluded.created_at, created_at)),\n deleted_at = MAX(COALESCE(deleted_at, excluded.deleted_at), COALESCE(excluded.deleted_at, deleted_at))`,\n files: `INSERT INTO file (file_ref, repo, path) VALUES (@fileRef, @repo, @path) ON CONFLICT (file_ref) DO NOTHING`,\n tasks: `INSERT INTO task (task_ref, task_id, status) VALUES (@taskRef, @taskId, @status)\n ON CONFLICT (task_ref) DO UPDATE SET status = COALESCE(excluded.status, status)`,\n artifacts: `INSERT INTO artifact (artifact_ref, kind, title, url, path, created_at) VALUES (@artifactRef, @artifactKind, @title, @url, @path, @ts)\n ON CONFLICT (artifact_ref) DO NOTHING`,\n prMerges: `INSERT INTO pr_merge_observation (number, repo_hint, merged_at) VALUES (@number, @repoHint, @ts)\n ON CONFLICT (number, repo_hint, merged_at) DO NOTHING`,\n prCreates: `INSERT INTO pr_create_observation (tool_use_id, title, number, repo, url) VALUES (@toolUseId, @title, @number, @repo, @url)\n ON CONFLICT (tool_use_id) DO UPDATE SET title = COALESCE(title, excluded.title), number = COALESCE(number, excluded.number),\n repo = COALESCE(repo, excluded.repo), url = COALESCE(url, excluded.url)`,\n} as const;\n\nfunction applyAssets(db: Db, delta: TranscriptDelta): void {\n for (const [kind, sql] of Object.entries(ASSET_UPSERTS) as [keyof typeof ASSET_UPSERTS, string][]) {\n const statement = db.prepare(sql);\n for (const row of delta[kind] as unknown as Record<string, unknown>[]) statement.run(pick(row, sql));\n }\n}\n\n/** better-sqlite3 rejects unused named parameters, so pass only the ones the statement binds. */\nfunction pick(row: Record<string, unknown>, sql: string): Record<string, unknown> {\n const names = new Set([...sql.matchAll(/@(\\w+)/g)].map((m) => m[1]!));\n return Object.fromEntries([...names].map((name) => [name, row[name] ?? null]));\n}\n\n/**\n * Bi-temporal phase collapse: a candidate matching the session's open phase is a\n * no-op; otherwise the open phase closes at the new `t_valid` and a replacement\n * row is inserted. Done here so a chunk boundary mid-run cannot add a phase.\n */\nfunction applyPhases(db: Db, transcriptId: number, delta: TranscriptDelta): void {\n const current = db.prepare(\"SELECT phase_id, to_mode FROM permission_phase WHERE session_id = ? AND trigger = ? AND t_invalid IS NULL ORDER BY phase_id DESC LIMIT 1\");\n const close = db.prepare(\"UPDATE permission_phase SET t_invalid = ? WHERE phase_id = ?\");\n const insert = db.prepare(\"INSERT INTO permission_phase (session_id, from_mode, to_mode, trigger, t_valid, fact_id) VALUES (?, ?, ?, ?, ?, ?)\");\n for (const phase of delta.phases) {\n const open = current.get(phase.sessionId, phase.trigger) as { phase_id: number; to_mode: string } | undefined;\n if (open?.to_mode === phase.toMode) continue;\n if (open) close.run(phase.ts, open.phase_id);\n insert.run(phase.sessionId, open?.to_mode ?? null, phase.toMode, phase.trigger, phase.ts, factIdFor(db, transcriptId, phase.byteOffset));\n }\n}\n\nfunction applyLinkedRows(graph: SessionGraph, transcriptId: number, delta: TranscriptDelta): void {\n const { db } = graph;\n const factId = (byteOffset: number) => factIdFor(db, transcriptId, byteOffset);\n\n const upsertTurn = db.prepare(`\n INSERT INTO turn (prompt_id, session_id, turn_index, started_at, fact_id_start)\n VALUES (?, ?, (SELECT COALESCE(MAX(turn_index), -1) + 1 FROM turn WHERE session_id = ?), ?, ?)\n ON CONFLICT (prompt_id) DO UPDATE SET session_id = MIN(session_id, excluded.session_id)`);\n for (const t of delta.turns) upsertTurn.run(t.promptId, t.sessionId, t.sessionId, t.ts, factId(t.byteOffset));\n\n const insertEdit = db.prepare(\"INSERT INTO human_edit (session_id, file_path, ts, fact_id) VALUES (?, ?, ?, ?) ON CONFLICT (session_id, file_path, ts) DO NOTHING\");\n for (const e of delta.humanEdits) insertEdit.run(e.sessionId, e.filePath, e.ts, factId(e.byteOffset));\n\n const insertCheckpoint = db.prepare(`\n INSERT INTO file_checkpoint (session_id, file_path, backup_file_name, version, backup_time, fact_id) VALUES (?, ?, ?, ?, ?, ?)\n ON CONFLICT (session_id, file_path, backup_file_name) DO NOTHING`);\n for (const c of delta.fileCheckpoints) insertCheckpoint.run(c.sessionId, c.filePath, c.backupFileName, c.version, c.backupTime, factId(c.byteOffset));\n\n const upsertSubagent = db.prepare(`\n INSERT INTO subagent (agent_ref, session_id, agent_type, label, started_at, fact_id) VALUES (?, ?, ?, ?, ?, ?)\n ON CONFLICT (agent_ref) DO UPDATE SET session_id = COALESCE(session_id, excluded.session_id),\n agent_type = COALESCE(agent_type, excluded.agent_type), label = COALESCE(label, excluded.label), started_at = COALESCE(started_at, excluded.started_at)`);\n for (const s of delta.subagents) upsertSubagent.run(s.agentRef, s.sessionId, s.agentType, s.label, s.ts || null, factId(s.byteOffset));\n\n // The dispatch row and this bridge come from different lines; an upsert survives a chunk boundary between them.\n const linkTranscript = db.prepare(\"INSERT INTO subagent (agent_ref, child_session_id) VALUES (?, ?) ON CONFLICT (agent_ref) DO UPDATE SET child_session_id = excluded.child_session_id\");\n for (const l of delta.subagentTranscripts) linkTranscript.run(l.agentRef, l.childSessionId);\n\n for (const e of delta.edges) graph.edges.assert({ sourceRef: e.sourceRef, relation: e.relation, targetRef: e.targetRef, tValid: e.ts, factId: factId(e.byteOffset) });\n\n for (const span of delta.spans) {\n graph.spans.index({ ownerRef: sessionRef(span.sessionId), field: span.field, sourceId: transcriptId, byteOffset: span.byteOffset, byteLength: span.byteLength }, span.text);\n }\n}\n\nfunction factIdFor(db: Db, transcriptId: number, byteOffset: number): number | null {\n const row = db.prepare(\"SELECT fact_id FROM fact WHERE transcript_id = ? AND byte_offset = ?\").get(transcriptId, byteOffset) as { fact_id: number } | undefined;\n return row?.fact_id ?? null;\n}\n","import { sessionRef } from \"@titan-design/session-read\";\nimport type { SessionGraph } from \"./graph.js\";\nimport { AUDIT_TABLES, FACET_TABLE } from \"./audit-schema.js\";\nimport { EPISODE_TABLE } from \"./audit-schema-v5.js\";\nimport { KIT } from \"./schema.js\";\n\n/** Derived tables keyed by `session_id`, reachable from a transcript through `session`. */\nconst SESSION_SCOPED = [\"turn\", \"permission_phase\", \"human_edit\", \"file_checkpoint\", \"subagent\", \"session_model_usage\", EPISODE_TABLE] as const;\n\n/**\n * Drop every derived row one transcript produced, so re-reading it from byte 0\n * rebuilds those rows instead of doubling them.\n *\n * `resetIndex` already states the reason at corpus scale: rewinding alone is not\n * enough, because the accumulating upserts add a second copy of every count. A\n * rewritten single transcript has the same problem one file at a time.\n * `session.turn_count`, the `session_model_usage` token buckets and the\n * commit/push counts all sum into what is already there, and rows the rewrite\n * removed are never deleted — `fact` survives on its unique\n * `(transcript_id, byte_offset)` index, so stale facts simply persist.\n *\n * Shared identity rows survive on purpose. `pr`, `branch`, `file`, `task` and\n * `artifact` are keyed by ref, many transcripts assert the same one, and the\n * inserts are insert-if-absent; a single transcript cannot know whether it was\n * the only source. The two observation tables are left for the same reason —\n * `reconcile` folds them, and re-reading re-asserts the same rows.\n *\n * Audit rows and facet state carry `transcript_id` themselves, so they go by it\n * directly rather than through `session`.\n */\nexport function purgeTranscript(graph: SessionGraph, transcriptId: number): void {\n graph.db.transaction(() => {\n const owned = graph.db.prepare(\"SELECT session_id FROM session WHERE transcript_id = ?\").all(transcriptId) as { session_id: string }[];\n for (const { session_id } of owned) graph.spans.purgeOwner(sessionRef(session_id));\n\n // Children first: each subquery reads the `session` rows deleted last.\n for (const table of SESSION_SCOPED) {\n graph.db.prepare(`DELETE FROM \"${table}\" WHERE session_id IN (SELECT session_id FROM session WHERE transcript_id = ?)`).run(transcriptId);\n }\n graph.db.prepare(`DELETE FROM \"${KIT.edge}\" WHERE fact_id IN (SELECT fact_id FROM fact WHERE transcript_id = ?)`).run(transcriptId);\n for (const table of [...AUDIT_TABLES, FACET_TABLE]) {\n graph.db.prepare(`DELETE FROM \"${table}\" WHERE transcript_id = ?`).run(transcriptId);\n }\n graph.db.prepare(\"DELETE FROM fact WHERE transcript_id = ?\").run(transcriptId);\n graph.db.prepare(\"DELETE FROM session WHERE transcript_id = ?\").run(transcriptId);\n })();\n}\n","import type { Db } from \"@titan-design/store-sqlite\";\n\nconst IN_BATCH = \"SELECT value FROM json_each(@sessionIds)\";\n\n/** Order, gap and context growth by request position; `seq_in_session` is 0-based like `turn.turn_index`. */\nconst REQUEST_ORDER = `\n WITH ordered AS (\n SELECT transcript_id, request_id, ts, context_tokens,\n ROW_NUMBER() OVER w - 1 AS seq,\n LAG(ts) OVER w AS prev_ts,\n LAG(context_tokens) OVER w AS prev_context,\n LAG(output_tokens) OVER w AS prev_output\n FROM request WHERE session_id IN (${IN_BATCH})\n WINDOW w AS (PARTITION BY session_id ORDER BY ts, byte_offset, transcript_id, request_id)\n )\n UPDATE request SET seq_in_session = ordered.seq,\n gap_ms = CAST(ROUND((julianday(ordered.ts) - julianday(ordered.prev_ts)) * 86400000) AS INTEGER),\n ctx_delta = ordered.context_tokens - (ordered.prev_context + ordered.prev_output)\n FROM ordered WHERE request.transcript_id = ordered.transcript_id AND request.request_id = ordered.request_id`;\n\n/**\n * A request is woken by the last arrival before it in its own transcript and\n * session. A tool result names its tool through `tool_call`, and an\n * `AskUserQuestion` result is the human answering, not a tool reporting.\n */\nconst REQUEST_WAKE = `\n WITH hit AS (\n SELECT r.transcript_id, r.request_id,\n (SELECT MAX(i.byte_offset) FROM inbound i\n WHERE i.transcript_id = r.transcript_id AND i.session_id = r.session_id AND i.byte_offset < r.byte_offset) AS wake_offset\n FROM request r WHERE r.session_id IN (${IN_BATCH})\n ),\n tools AS (\n SELECT transcript_id, tool_use_id, name, family, mcp_server,\n ROW_NUMBER() OVER (PARTITION BY transcript_id, tool_use_id ORDER BY byte_offset, block_index) AS pick\n FROM tool_call WHERE session_id IN (${IN_BATCH})\n ),\n wake AS (\n SELECT hit.transcript_id, hit.request_id, hit.wake_offset, i.cause, i.delivery, i.detail, i.from_name,\n t.name AS tool_name, t.family, t.mcp_server\n FROM hit\n LEFT JOIN inbound i ON i.transcript_id = hit.transcript_id AND i.byte_offset = hit.wake_offset\n AND i.block_index = (SELECT MAX(block_index) FROM inbound j WHERE j.transcript_id = hit.transcript_id AND j.byte_offset = hit.wake_offset)\n LEFT JOIN tools t ON t.transcript_id = i.transcript_id AND t.tool_use_id = i.tool_use_id AND t.pick = 1\n )\n UPDATE request SET\n wake_cause = CASE WHEN wake.cause IS NULL THEN 'session_start'\n WHEN wake.tool_name = 'AskUserQuestion' THEN 'ask_user_answer' ELSE wake.cause END,\n wake_delivery = wake.delivery,\n wake_detail = COALESCE(wake.tool_name, wake.from_name, wake.detail),\n wake_tool_family = wake.family,\n wake_mcp_server = wake.mcp_server,\n wake_offset = wake.wake_offset\n FROM wake WHERE request.transcript_id = wake.transcript_id AND request.request_id = wake.request_id`;\n\n/** How long a message waited: its delivery paired with the latest earlier enqueue of the same content. */\nconst INBOUND_QUEUED = `\n UPDATE inbound SET queued_ms = (\n SELECT CAST(ROUND((julianday(inbound.ts) - julianday(q.ts)) * 86400000) AS INTEGER)\n FROM queue_op q\n WHERE q.transcript_id = inbound.transcript_id AND q.session_id = inbound.session_id\n AND q.operation = 'enqueue' AND q.content_hash = inbound.content_hash AND q.byte_offset < inbound.byte_offset\n ORDER BY q.byte_offset DESC LIMIT 1)\n WHERE session_id IN (${IN_BATCH})`;\n\n/** A compaction whose last arrival was a tool result fired inside a tool loop, not between turns. */\nconst COMPACTION_MID_LOOP = `\n UPDATE compaction SET mid_loop = COALESCE((\n SELECT i.delivery = 'tool_result' FROM inbound i\n WHERE i.transcript_id = compaction.transcript_id AND i.session_id = compaction.session_id AND i.byte_offset < compaction.byte_offset\n ORDER BY i.byte_offset DESC, i.block_index DESC LIMIT 1), 0)\n WHERE session_id IN (${IN_BATCH})`;\n\nconst TURN_WAKE = `\n UPDATE turn SET wake_cause = (\n SELECT i.cause FROM fact f JOIN inbound i ON i.transcript_id = f.transcript_id AND i.byte_offset = f.byte_offset\n WHERE f.fact_id = turn.fact_id_start ORDER BY i.block_index LIMIT 1)\n WHERE session_id IN (${IN_BATCH})`;\n\n/**\n * Usage is a sum over deduplicated requests, never an accumulation of lines.\n * A request copied into a second transcript counts once. Sessions with no\n * request rows keep what they have: their transcripts predate the table or are gone.\n */\nconst CLEAR_USAGE = `\n DELETE FROM session_model_usage\n WHERE session_id IN (${IN_BATCH}) AND session_id IN (SELECT session_id FROM request WHERE session_id IN (${IN_BATCH}))`;\n\nconst RECOMPUTE_USAGE = `\n WITH ranked AS (\n SELECT *, ROW_NUMBER() OVER (PARTITION BY session_id, request_id ORDER BY ts, transcript_id) AS pick\n FROM request WHERE session_id IN (${IN_BATCH})\n )\n INSERT INTO session_model_usage (session_id, model, input_tokens, output_tokens, cache_read_tokens, cache_creation_tokens, thinking_tokens, request_count)\n SELECT session_id, model, SUM(input_tokens), SUM(output_tokens), SUM(cache_read_tokens), SUM(cache_creation_tokens), SUM(thinking_tokens), COUNT(*)\n FROM ranked WHERE pick = 1 GROUP BY session_id, model`;\n\nconst STEPS = [REQUEST_ORDER, REQUEST_WAKE, INBOUND_QUEUED, COMPACTION_MID_LOOP, TURN_WAKE, CLEAR_USAGE, RECOMPUTE_USAGE] as const;\n\nexport type AuditRollup = (sessionIdsJson: string) => void;\n\n/** Prepare the audit recomputes once; the caller runs them per batch inside its own transaction. */\nexport function prepareAuditRollup(db: Db): AuditRollup {\n const statements = STEPS.map((sql) => db.prepare(sql));\n return (sessionIds) => {\n for (const statement of statements) statement.run({ sessionIds });\n };\n}\n","import { prepareAuditRollup } from \"./audit-rollup.js\";\nimport type { SessionGraph } from \"./graph.js\";\n\nconst BATCH = 400;\n\n/**\n * Turn aggregates that no single line can supply. Contract: recompute, never\n * accumulate. Every value is a pure function of the fact rows, so incremental\n * refreshes and full rebuilds converge regardless of chunk boundaries.\n */\nconst ROLLUP = `\n WITH ordered AS (\n SELECT fact_id, session_id, event_type, ts, prompt_id,\n COUNT(CASE WHEN event_type = 'user_prompt' THEN 1 END) OVER (\n PARTITION BY session_id ORDER BY ts, transcript_id, seq ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS turn_no,\n LAG(event_type) OVER (PARTITION BY session_id ORDER BY ts, transcript_id, seq) AS prev_type,\n LAG(ts) OVER (PARTITION BY session_id ORDER BY ts, transcript_id, seq) AS prev_ts\n FROM fact WHERE session_id IN (SELECT value FROM json_each(@sessionIds))\n ),\n owners AS (SELECT session_id, turn_no, prompt_id FROM ordered WHERE event_type = 'user_prompt'),\n agg AS (\n SELECT owners.prompt_id AS prompt_id, MAX(ordered.ts) AS ended_at,\n CAST(ROUND((julianday(MAX(ordered.ts)) - julianday(MIN(ordered.ts))) * 86400000) AS INTEGER) AS duration_ms,\n SUM(CASE WHEN ordered.event_type = 'tool_decision' THEN 1 ELSE 0 END) AS tool_call_count,\n CAST(COALESCE(SUM(CASE\n WHEN ordered.event_type IN ('assistant_response', 'tool_decision') AND ordered.prev_type IN ('user_prompt', 'tool_result', 'tool_result_error')\n THEN ROUND((julianday(ordered.ts) - julianday(ordered.prev_ts)) * 86400000) END), 0) AS INTEGER) AS thinking_ms\n FROM ordered JOIN owners ON owners.session_id = ordered.session_id AND owners.turn_no = ordered.turn_no\n GROUP BY owners.prompt_id\n )\n UPDATE turn SET ended_at = agg.ended_at, duration_ms = COALESCE(agg.duration_ms, 0),\n tool_call_count = agg.tool_call_count, thinking_ms = COALESCE(agg.thinking_ms, 0)\n FROM agg WHERE turn.prompt_id = agg.prompt_id`;\n\n/** `turn_index` is insert-order at write time; recomputing it from `started_at` makes it a property of the corpus. */\nconst RENUMBER_TURNS = `\n WITH ordered AS (\n SELECT prompt_id, ROW_NUMBER() OVER (PARTITION BY session_id ORDER BY started_at, prompt_id) - 1 AS idx\n FROM turn WHERE session_id IN (SELECT value FROM json_each(@sessionIds))\n )\n UPDATE turn SET turn_index = ordered.idx FROM ordered WHERE turn.prompt_id = ordered.prompt_id`;\n\n/** Recompute turn aggregates and the audit rollup for the given sessions in one transaction. */\nexport function rollupSessions(graph: SessionGraph, sessionIds: readonly string[]): number {\n const unique = [...new Set(sessionIds)];\n if (unique.length === 0) return 0;\n const aggregate = graph.db.prepare(ROLLUP);\n const renumber = graph.db.prepare(RENUMBER_TURNS);\n const audit = prepareAuditRollup(graph.db);\n return graph.db.transaction(() => {\n let updated = 0;\n for (let i = 0; i < unique.length; i += BATCH) {\n const batch = JSON.stringify(unique.slice(i, i + BATCH));\n renumber.run({ sessionIds: batch });\n updated += aggregate.run({ sessionIds: batch }).changes;\n audit(batch);\n }\n return updated;\n })();\n}\n\n/**\n * A merge sighting and the `pr-link` naming the same PR routinely live in different transcripts; fold at pass end.\n * Once the forge has checked a PR (`outcome_checked_at` set), its `merged_at` is forge-accurate and must not be\n * overwritten by a transcript sighting time on a later pass.\n */\nconst RECONCILE_PR_MERGES = `\n UPDATE pr SET state = 'merged',\n merged_at = (SELECT MIN(o.merged_at) FROM pr_merge_observation o WHERE o.number = pr.number AND (o.repo_hint IS NULL OR pr.repo LIKE '%/' || o.repo_hint))\n WHERE pr.outcome_checked_at IS NULL\n AND EXISTS (SELECT 1 FROM pr_merge_observation o WHERE o.number = pr.number AND (o.repo_hint IS NULL OR pr.repo LIKE '%/' || o.repo_hint))`;\n\n/** Both halves of a `gh pr create` make a real PR whether or not a `pr-link` ever mentioned it. */\nconst RECONCILE_PR_CREATES = `\n INSERT INTO pr (pr_ref, number, repo, title, url)\n SELECT 'pr:' || repo || '#' || number, number, repo, title, url FROM pr_create_observation\n WHERE number IS NOT NULL AND repo IS NOT NULL AND title IS NOT NULL\n ON CONFLICT (pr_ref) DO UPDATE SET title = COALESCE(pr.title, excluded.title), url = COALESCE(pr.url, excluded.url)`;\n\n/**\n * A subagent ends when its child session's last line does, not when the\n * dispatch's tool_result returns (most dispatches are async and return at\n * launch). Parentage comes from the dispatch that ran inside a child transcript.\n */\nconst RECONCILE_SUBAGENTS = `\n UPDATE subagent SET\n ended_at = COALESCE((SELECT s.ended_at FROM session s WHERE s.session_id = subagent.child_session_id), ended_at),\n parent_agent_ref = COALESCE((SELECT p.agent_ref FROM subagent p WHERE p.child_session_id = subagent.session_id), parent_agent_ref)`;\n\nexport interface ReconcileCounts {\n prMerges: number;\n prCreates: number;\n subagents: number;\n}\n\n/** Whole-table reconciliations, run once at the end of a refresh pass after the rollup. */\nexport function reconcile(graph: SessionGraph): ReconcileCounts {\n return {\n prCreates: graph.db.prepare(RECONCILE_PR_CREATES).run().changes,\n prMerges: graph.db.prepare(RECONCILE_PR_MERGES).run().changes,\n subagents: graph.db.prepare(RECONCILE_SUBAGENTS).run().changes,\n };\n}\n","import { promises as fs } from \"node:fs\";\nimport { contentHash, resumePoint } from \"@titan-design/locator\";\nimport { TranscriptParseError, extractTranscript, type DiscoveredTranscript } from \"@titan-design/session-read\";\nimport { applyDelta } from \"./apply.js\";\nimport { advanceFacet, backfillFacets } from \"./facet.js\";\nimport { allSessionIds, type SessionGraph } from \"./graph.js\";\nimport { enrichPrs, type PrEnrichment, type PrResolver } from \"./outcomes.js\";\nimport { resolveOrigins, type OriginEnrichment, type OriginResolver } from \"./origin.js\";\nimport { purgeTranscript } from \"./purge.js\";\nimport { reconcile, rollupSessions, type ReconcileCounts } from \"./rollup.js\";\nimport { allTaskIds, enrichTasks, NO_ENRICHMENT, type TaskEnrichment, type TaskResolver } from \"./tasks.js\";\n\nexport interface IndexOptions {\n /** Re-hash the already-read prefix to catch same-length rewrites. O(file), so opt in. */\n verifyHash?: boolean;\n /** Store a whole-file content hash for durability reporting. O(file), so opt in. */\n withContentHash?: boolean;\n /** Fill task title, initiative and present status from the caller's store. Absent means transcripts alone. */\n resolveTasks?: TaskResolver;\n /** Record who launched each session. Runs once per `refreshCorpus` pass, never per transcript. Absent means no origin rows. */\n resolveOrigins?: OriginResolver;\n /** Fill PR state, merge, close and review rounds from the caller's forge. Runs once per `refreshCorpus` pass. Absent means transcripts alone. */\n resolvePrs?: PrResolver;\n}\n\nexport interface RefreshOptions extends IndexOptions {\n /** Roll up every session, not just the ones this pass touched. */\n full?: boolean;\n /** Stale audit facets re-extracted per pass (default 40). `Infinity` clears the backlog. */\n facetLimit?: number;\n}\n\nexport type TranscriptOutcome =\n | { status: \"unchanged\" | \"indexed\" | \"rewound\"; transcriptId: number; sessionIds: string[]; facts: number; tasks: TaskEnrichment }\n | { status: \"missing\" | \"quarantined\"; transcriptId: number; sessionIds: string[]; facts: 0; tasks: TaskEnrichment; reason: string };\n\n/**\n * Bring one transcript up to date: read from its watermark (or byte 0 after a\n * rewrite), apply the delta, advance the watermark. A malformed line\n * quarantines the transcript instead of poisoning the pass.\n */\nexport async function indexTranscript(graph: SessionGraph, transcript: DiscoveredTranscript, options: IndexOptions = {}): Promise<TranscriptOutcome> {\n const row = graph.transcripts.ensure(transcript.displayPath);\n const entry = { path: transcript.displayPath, lastByteOffset: row.lastOffset, prefixHash: row.prefixHash, mtime: row.fileMtime };\n const point = await resumePoint(entry, transcript.absolutePath, { verifyHash: options.verifyHash });\n const base = { transcriptId: row.sourceId, sessionIds: [] as string[], tasks: NO_ENRICHMENT };\n if (point.state === \"missing\") {\n graph.transcripts.markStatus(transcript.displayPath, \"missing\", \"source file no longer exists\");\n return { ...base, status: \"missing\", facts: 0, reason: \"source file no longer exists\" };\n }\n if (point.state === \"unchanged\") {\n // A file that vanished and came back unchanged resumes at EOF, so there are no\n // bytes to read and `advance()` — the only writer of status 'ok' — never runs,\n // stranding the row on 'missing' forever. Clear it here rather than forcing a\n // re-read, which would rewrite the prefix hash from a zero-byte delta.\n // Quarantine is deliberately not cleared: the same bytes still will not parse.\n if (row.status === \"missing\") graph.transcripts.markStatus(transcript.displayPath, \"ok\", null);\n return { ...base, status: \"unchanged\", facts: 0 };\n }\n\n try {\n const delta = await extractTranscript(transcript.absolutePath, {\n fromByteOffset: point.start,\n priorPrefixHash: point.state === \"rewritten\" ? null : row.prefixHash,\n subagentId: transcript.subagentId,\n });\n // Two ways to learn a transcript was rewritten, and both must purge. `resumePoint`\n // catches a file that shrank; `extractTranscript` re-hashes the prefix it was asked\n // to skip and restarts from zero on its own when the bytes moved — a rotation that\n // left the file the same length or longer. Ignoring its answer replays the whole\n // file onto rows that were never removed, which is the accumulation purge exists\n // to prevent, reached by a different road.\n const rewound = point.state === \"rewritten\" || delta.restartedFromZero;\n // After extraction, never before: a parse failure quarantines the transcript,\n // and purging first would destroy rows we could then no longer rebuild.\n if (rewound) purgeTranscript(graph, row.sourceId);\n applyDelta(graph, row.sourceId, delta, { account: transcript.account });\n advanceFacet(graph.db, row.sourceId, rewound ? 0 : point.start, delta.lastByteOffset);\n const stat = await fs.stat(transcript.absolutePath);\n graph.transcripts.advance(transcript.displayPath, {\n lastOffset: delta.lastByteOffset,\n prefixHash: delta.prefixHash,\n fileSize: stat.size,\n fileMtime: stat.mtime.toISOString(),\n contentHash: options.withContentHash ? await contentHash(transcript.absolutePath) : null,\n });\n const sessionIds = delta.sessions.map((s) => s.sessionId);\n const taskIds = delta.tasks.map((t) => t.taskId);\n const tasks = taskIds.length > 0 ? await enrichTasks(graph, options.resolveTasks, taskIds) : NO_ENRICHMENT;\n return { ...base, sessionIds, tasks, status: rewound ? \"rewound\" : \"indexed\", facts: delta.facts.length };\n } catch (err) {\n if (!(err instanceof TranscriptParseError)) throw err;\n graph.transcripts.markStatus(transcript.displayPath, \"quarantined\", err.message);\n return { ...base, status: \"quarantined\", facts: 0, reason: err.message };\n }\n}\n\nexport interface RefreshSummary {\n transcripts: number;\n indexed: number;\n unchanged: number;\n rewound: number;\n missing: number;\n quarantined: number;\n facts: number;\n turnsRolledUp: number;\n reconciled: ReconcileCounts;\n tasks: TaskEnrichment;\n origins: OriginEnrichment;\n prs: PrEnrichment;\n markedMissing: number;\n facetsBackfilled: number;\n /** Transcripts whose audit facet is still stale after this pass. */\n facetBacklog: number;\n}\n\n/**\n * One pass over a corpus: index every transcript, re-extract a bounded batch of\n * stale audit facets, roll up the sessions that changed, resolve session\n * origins, reconcile cross-transcript observations, resolve PR outcomes,\n * enrich tasks, and mark rows whose source file is gone. Idempotent: a second pass over unchanged\n * files changes nothing.\n *\n * The resolver is hoisted out of the per-transcript loop and run once over the\n * whole task table, so a corpus of N transcripts costs one resolver call rather\n * than N, and a task whose store row changed refreshes even when no transcript\n * did. That bounds staleness to one pass.\n */\nexport async function refreshCorpus(graph: SessionGraph, transcripts: readonly DiscoveredTranscript[], options: RefreshOptions = {}): Promise<RefreshSummary> {\n const { resolveTasks, resolveOrigins: originResolver, resolvePrs, full, facetLimit, ...perTranscript } = options;\n const counts = { indexed: 0, unchanged: 0, rewound: 0, missing: 0, quarantined: 0 };\n const touched: string[] = [];\n let facts = 0;\n for (const transcript of transcripts) {\n const outcome = await indexTranscript(graph, transcript, perTranscript);\n counts[outcome.status] += 1;\n facts += outcome.facts;\n touched.push(...outcome.sessionIds);\n }\n const facets = await backfillFacets(graph, transcripts, { limit: facetLimit });\n touched.push(...facets.sessionIds);\n const turnsRolledUp = rollupSessions(graph, full ? allSessionIds(graph) : touched);\n // Before reconcile, so a worker's subagent row gets its ended_at in the same pass.\n const origins = await resolveOrigins(graph, originResolver);\n const reconciled = reconcile(graph);\n // After reconcile, so a merge a transcript witnessed is already sticky when the forge answers.\n const prs = await enrichPrs(graph, resolvePrs);\n const tasks = await enrichTasks(graph, resolveTasks, allTaskIds(graph));\n const markedMissing = await markMissing(graph, transcripts);\n const facetSummary = { facetsBackfilled: facets.backfilled, facetBacklog: facets.backlog };\n return { transcripts: transcripts.length, ...counts, facts, turnsRolledUp, reconciled, tasks, origins, prs, markedMissing, ...facetSummary };\n}\n\n/** Rows absent from discovery are only nominated; an `fs.stat` decides, so an empty scan cannot condemn the corpus. */\nasync function markMissing(graph: SessionGraph, discovered: readonly DiscoveredTranscript[]): Promise<number> {\n const present = new Set(discovered.map((t) => t.displayPath));\n const byPath = new Map(discovered.map((t) => [t.displayPath, t.absolutePath]));\n let marked = 0;\n for (const row of graph.transcripts.list()) {\n if (row.status === \"missing\" || present.has(row.sourceKey)) continue;\n const normalized = graph.db.prepare(\"SELECT descriptor FROM normalized_source WHERE transcript_id = ?\").get(row.sourceId) as { descriptor: string } | undefined;\n const absolute = normalized ? (JSON.parse(normalized.descriptor) as { path: string }).path : byPath.get(row.sourceKey) ?? row.sourceKey;\n if (await exists(absolute)) continue;\n graph.transcripts.markStatus(row.sourceKey, \"missing\", \"source file no longer exists\");\n marked += 1;\n }\n return marked;\n}\n\nasync function exists(absolutePath: string): Promise<boolean> {\n try {\n await fs.stat(absolutePath);\n return true;\n } catch {\n return false;\n }\n}\n","import type { SessionGraph } from \"./graph.js\";\n\n/** A PR the graph holds, as the resolver needs it to ask a forge. */\nexport interface PrKey {\n prRef: string;\n repo: string;\n number: number;\n}\n\n/**\n * What a forge knows and a transcript cannot state: a merge done by another\n * session or in the browser, a close, and the review history. Every field is\n * optional; an omitted or null field leaves whatever the transcripts derived.\n */\nexport interface ResolvedPr {\n /** `open`, `closed` or `merged`, in any case. */\n state?: string | null;\n mergedAt?: string | null;\n closedAt?: string | null;\n /** Stored as the resolver counts it; the round definition is open question Q6 in the TP-256 design. */\n reviewRounds?: number | null;\n}\n\n/** Resolutions keyed by `pr_ref` (`pr:acme/demo#7`). */\nexport type PrResolution = ReadonlyMap<string, ResolvedPr | null | undefined>;\n\n/**\n * Supplied by the caller, never by this package: session-graph is tier 2 and\n * must not learn which forge a product talks to. Called once per pass with every\n * PR whose outcome may still change.\n */\nexport type PrResolver = (prs: readonly PrKey[]) => PromiseLike<PrResolution> | PrResolution;\n\nexport interface PrEnrichment {\n /** PRs handed to the resolver. */\n requested: number;\n /** PR rows the resolver updated. */\n applied: number;\n /** The resolver threw; rows stand as the transcripts left them. */\n failed: boolean;\n /** Why it failed, for the caller to log. Absent unless `failed`. */\n error?: string;\n}\n\nexport const NO_PR_OUTCOMES: PrEnrichment = Object.freeze({ requested: 0, applied: 0, failed: false });\n\n/** A merge is final, so a merged PR is asked about once; open and closed PRs can still move. */\nconst PRS_NEEDING_OUTCOME = `\n SELECT pr_ref, repo, number FROM pr\n WHERE repo IS NOT NULL AND number IS NOT NULL AND (outcome_checked_at IS NULL OR state IS NOT 'merged')\n ORDER BY pr_ref`;\n\n/** A stale forge cache must not reopen a PR a transcript saw merged, so `merged` is sticky. */\nconst APPLY_OUTCOME = `\n UPDATE pr SET\n state = CASE WHEN state = 'merged' THEN state ELSE COALESCE(lower(@state), state) END,\n merged_at = COALESCE(@mergedAt, merged_at),\n closed_at = COALESCE(@closedAt, closed_at),\n review_rounds = COALESCE(@reviewRounds, review_rounds),\n outcome_checked_at = @checkedAt\n WHERE pr_ref = @prRef`;\n\nexport function prsNeedingOutcome(graph: SessionGraph): PrKey[] {\n const rows = graph.db.prepare(PRS_NEEDING_OUTCOME).all() as { pr_ref: string; repo: string; number: number }[];\n return rows.map((r) => ({ prRef: r.pr_ref, repo: r.repo, number: r.number }));\n}\n\n/**\n * Fill PR outcomes from a caller-supplied resolver. Runs after `reconcile`, so\n * it sees the merges the transcripts witnessed and only adds what they missed.\n * Updates rows and never inserts one: a PR enters the graph from a transcript.\n * A resolver that throws costs this pass its outcomes and nothing else.\n */\nexport async function enrichPrs(graph: SessionGraph, resolver: PrResolver | undefined): Promise<PrEnrichment> {\n if (!resolver) return NO_PR_OUTCOMES;\n const prs = prsNeedingOutcome(graph);\n if (prs.length === 0) return NO_PR_OUTCOMES;\n try {\n const resolved = await resolver(prs);\n return { requested: prs.length, applied: write(graph, resolved, new Date().toISOString()), failed: false };\n } catch (err) {\n return { requested: prs.length, applied: 0, failed: true, error: err instanceof Error ? err.message : String(err) };\n }\n}\n\nfunction write(graph: SessionGraph, resolved: PrResolution, checkedAt: string): number {\n const apply = graph.db.prepare(APPLY_OUTCOME);\n return graph.db.transaction(() => {\n let applied = 0;\n for (const [prRef, fields] of resolved) {\n if (!fields) continue;\n applied += apply.run({\n prRef,\n checkedAt,\n state: fields.state ?? null,\n mergedAt: fields.mergedAt ?? null,\n closedAt: fields.closedAt ?? null,\n reviewRounds: fields.reviewRounds ?? null,\n }).changes;\n }\n return applied;\n })();\n}\n","import { RELATIONS, sessionRef } from \"@titan-design/session-read\";\nimport type { SessionGraph } from \"./graph.js\";\n\n/**\n * Who started a session and why, as a launcher such as agent-chat recorded it.\n * A transcript cannot state this: a `claude -p` worker and a headless miner look\n * the same from inside. Every field but `originSystem` is optional.\n */\nexport interface ResolvedOrigin {\n originSystem: string;\n agentId?: string | null;\n agentName?: string | null;\n parentName?: string | null;\n parentSessionId?: string | null;\n profile?: string | null;\n modelAlias?: string | null;\n surface?: string | null;\n isolation?: string | null;\n depth?: number | null;\n /** `spawned`, `adopted`, `inherited` or `human`. */\n originKind?: string | null;\n configDir?: string | null;\n spawnCwd?: string | null;\n spawnedAt?: string | null;\n briefChars?: number | null;\n briefExcerpt?: string | null;\n briefPath?: string | null;\n launchArgs?: string | null;\n}\n\n/** A lifecycle event the launcher saw outside the transcript: `teleport`, `handoff`, `retired`, `exited`. */\nexport interface ExternalEvent {\n sessionId: string;\n ts: string;\n kind: string;\n detail?: string | null;\n /** Defaults to the session's resolved origin system. */\n originSystem?: string | null;\n}\n\nexport interface OriginResolution {\n /** Keyed by session id. */\n origins: Record<string, ResolvedOrigin>;\n externalEvents?: readonly ExternalEvent[];\n}\n\n/**\n * Supplied by the caller, never by this package: session-graph is tier 2 and\n * must not learn where a launcher keeps its records. Called once per pass with\n * every session that has no origin row or a stale one.\n */\nexport type OriginResolver = (sessionIds: readonly string[]) => PromiseLike<OriginResolution> | OriginResolution;\n\nexport interface OriginEnrichment {\n /** Session ids handed to the resolver. */\n requested: number;\n /** `session_origin` rows the resolver wrote. */\n applied: number;\n /** `session_external_event` rows the resolver wrote. */\n events: number;\n /** The resolver threw; origin rows stand as the last pass left them. */\n failed: boolean;\n /** Why it failed, for the caller to log. Absent unless `failed`. */\n error?: string;\n}\n\nexport const NO_ORIGINS: OriginEnrichment = Object.freeze({ requested: 0, applied: 0, events: 0, failed: false });\n\n/** A session whose transcript grew after its origin was resolved may have been retired or handed off since. */\nconst SESSIONS_NEEDING_ORIGIN = `\n SELECT s.session_id FROM session s LEFT JOIN session_origin o ON o.session_id = s.session_id\n WHERE o.session_id IS NULL OR o.resolved_at < s.ended_at\n ORDER BY s.session_id`;\n\nconst UPSERT_ORIGIN = `\n INSERT OR REPLACE INTO session_origin (session_id, origin_system, agent_id, agent_name, parent_name, parent_session_id,\n profile, model_alias, surface, isolation, depth, origin_kind, config_dir, spawn_cwd, spawned_at,\n brief_chars, brief_excerpt, brief_path, launch_args, resolved_at)\n VALUES (@sessionId, @originSystem, @agentId, @agentName, @parentName, @parentSessionId,\n @profile, @modelAlias, @surface, @isolation, @depth, @originKind, @configDir, @spawnCwd, @spawnedAt,\n @briefChars, @briefExcerpt, @briefPath, @launchArgs, @resolvedAt)`;\n\nconst UPSERT_EVENT = `\n INSERT INTO session_external_event (session_id, ts, origin_system, kind, detail)\n VALUES (@sessionId, @ts, COALESCE(@originSystem, (SELECT origin_system FROM session_origin WHERE session_id = @sessionId), 'unknown'), @kind, @detail)\n ON CONFLICT (session_id, ts, kind) DO UPDATE SET origin_system = excluded.origin_system, detail = excluded.detail`;\n\n/** Existing subagent queries then cover launcher-spawned workers unchanged; `reconcile` fills `ended_at` from the child session. */\nconst PROJECT_SUBAGENTS = `\n INSERT INTO subagent (agent_ref, session_id, child_session_id, agent_type, label, started_at)\n SELECT 'agent:' || origin_system || ':' || agent_id, parent_session_id, session_id, profile, agent_name, spawned_at\n FROM session_origin WHERE parent_session_id IS NOT NULL AND agent_id IS NOT NULL\n ON CONFLICT (agent_ref) DO UPDATE SET session_id = excluded.session_id, child_session_id = excluded.child_session_id,\n agent_type = excluded.agent_type, label = excluded.label, started_at = COALESCE(excluded.started_at, started_at)`;\n\nexport function sessionsNeedingOrigin(graph: SessionGraph): string[] {\n return (graph.db.prepare(SESSIONS_NEEDING_ORIGIN).all() as { session_id: string }[]).map((r) => r.session_id);\n}\n\n/**\n * Resolve origins for the sessions that lack a current one, then project every\n * stored origin into `spawned` edges and `subagent` rows. Projecting from the\n * table, not from this pass's answer, restores rows a parent transcript's purge\n * removed. A resolver that throws costs this pass its origins and nothing else.\n */\nexport async function resolveOrigins(graph: SessionGraph, resolver: OriginResolver | undefined): Promise<OriginEnrichment> {\n if (!resolver) return NO_ORIGINS;\n const sessionIds = sessionsNeedingOrigin(graph);\n try {\n const resolution = await resolver(sessionIds);\n const written = writeResolution(graph, resolution, new Date().toISOString());\n return { requested: sessionIds.length, ...written, failed: false };\n } catch (err) {\n return { requested: sessionIds.length, applied: 0, events: 0, failed: true, error: err instanceof Error ? err.message : String(err) };\n } finally {\n projectOrigins(graph);\n }\n}\n\nfunction writeResolution(graph: SessionGraph, resolution: OriginResolution, resolvedAt: string): { applied: number; events: number } {\n const upsertOrigin = graph.db.prepare(UPSERT_ORIGIN);\n const upsertEvent = graph.db.prepare(UPSERT_EVENT);\n return graph.db.transaction(() => {\n let applied = 0;\n for (const [sessionId, origin] of Object.entries(resolution.origins)) {\n applied += upsertOrigin.run(originRow(sessionId, origin, resolvedAt)).changes;\n }\n let events = 0;\n for (const e of resolution.externalEvents ?? []) {\n events += upsertEvent.run({ sessionId: e.sessionId, ts: e.ts, kind: e.kind, detail: e.detail ?? null, originSystem: e.originSystem ?? null }).changes;\n }\n return { applied, events };\n })();\n}\n\nfunction originRow(sessionId: string, o: ResolvedOrigin, resolvedAt: string): Record<string, string | number | null> {\n return {\n sessionId, originSystem: o.originSystem, resolvedAt,\n agentId: o.agentId ?? null, agentName: o.agentName ?? null, parentName: o.parentName ?? null, parentSessionId: o.parentSessionId ?? null,\n profile: o.profile ?? null, modelAlias: o.modelAlias ?? null, surface: o.surface ?? null, isolation: o.isolation ?? null,\n depth: o.depth ?? null, originKind: o.originKind ?? null, configDir: o.configDir ?? null, spawnCwd: o.spawnCwd ?? null,\n spawnedAt: o.spawnedAt ?? null, briefChars: o.briefChars ?? null, briefExcerpt: o.briefExcerpt ?? null,\n briefPath: o.briefPath ?? null, launchArgs: o.launchArgs ?? null,\n };\n}\n\nfunction projectOrigins(graph: SessionGraph): void {\n const spawned = graph.db.prepare(\"SELECT session_id, parent_session_id, spawned_at, resolved_at FROM session_origin WHERE parent_session_id IS NOT NULL\").all() as {\n session_id: string; parent_session_id: string; spawned_at: string | null; resolved_at: string;\n }[];\n graph.db.transaction(() => {\n graph.db.prepare(PROJECT_SUBAGENTS).run();\n for (const o of spawned) {\n graph.edges.assert({ sourceRef: sessionRef(o.parent_session_id), relation: RELATIONS.SPAWNED, targetRef: sessionRef(o.session_id), tValid: o.spawned_at ?? o.resolved_at });\n }\n })();\n}\n","import { taskRef } from \"@titan-design/session-read\";\nimport type { SessionGraph } from \"./graph.js\";\n\n/**\n * What a product's task store knows and a transcript cannot state: the task's\n * present title, its initiative, and the status it holds right now rather than\n * the one some command was observed to set. Every field is optional; an omitted\n * or null field leaves whatever the transcripts derived in place.\n */\nexport interface ResolvedTask {\n initiative?: string | null;\n title?: string | null;\n status?: string | null;\n /** The store's size estimate for the task, in whatever unit it keeps. */\n estimate?: number | null;\n}\n\n/** Resolutions keyed by bare task id (`AW-23`, not `task:AW-23`). */\nexport type TaskResolution = ReadonlyMap<string, ResolvedTask | null | undefined>;\n\n/**\n * Supplied by the caller, never by this package: session-graph is tier 2 and\n * must not learn where any product keeps its tasks. Called once per pass with\n * every task id at once, because a real resolver reads a store. Returning an id\n * that no transcript mentioned inserts that task; that is how a task nobody\n * worked on gets into the graph.\n */\nexport type TaskResolver = (taskIds: readonly string[]) => PromiseLike<TaskResolution> | TaskResolution;\n\nexport interface TaskEnrichment {\n /** Task ids handed to the resolver. */\n requested: number;\n /** Task rows the resolver wrote. */\n applied: number;\n /** The resolver threw; rows stand as the transcripts left them. */\n failed: boolean;\n /** Why it failed, for the caller to log. Absent unless `failed`. */\n error?: string;\n}\n\nexport const NO_ENRICHMENT: TaskEnrichment = Object.freeze({ requested: 0, applied: 0, failed: false });\n\n/**\n * COALESCE gives the resolver precedence over the transcripts on every field it\n * states, and none on the fields it omits: the store is the system of record for\n * a task's present status, while a transcript only witnesses a command that ran.\n */\nconst UPSERT_TASK = `\n INSERT INTO task (task_ref, task_id, initiative, title, status, estimate) VALUES (@taskRef, @taskId, @initiative, @title, @status, @estimate)\n ON CONFLICT (task_ref) DO UPDATE SET\n initiative = COALESCE(excluded.initiative, initiative),\n title = COALESCE(excluded.title, title),\n status = COALESCE(excluded.status, status),\n estimate = COALESCE(excluded.estimate, estimate)`;\n\nexport function allTaskIds(graph: SessionGraph): string[] {\n return (graph.db.prepare(\"SELECT task_id FROM task\").all() as { task_id: string }[]).map((r) => r.task_id);\n}\n\n/**\n * Enrich task rows from a caller-supplied resolver. Runs outside the delta's\n * transaction because a resolver is async; a crash between the two leaves rows\n * un-enriched, which the next pass corrects. A resolver that throws costs this\n * pass its enrichment and nothing else.\n */\nexport async function enrichTasks(graph: SessionGraph, resolver: TaskResolver | undefined, taskIds: readonly string[]): Promise<TaskEnrichment> {\n const unique = [...new Set(taskIds)];\n if (!resolver) return NO_ENRICHMENT;\n try {\n const resolved = await resolver(unique);\n return { requested: unique.length, applied: write(graph, resolved), failed: false };\n } catch (err) {\n return { requested: unique.length, applied: 0, failed: true, error: err instanceof Error ? err.message : String(err) };\n }\n}\n\nfunction write(graph: SessionGraph, resolved: TaskResolution): number {\n const upsert = graph.db.prepare(UPSERT_TASK);\n return graph.db.transaction(() => {\n let applied = 0;\n for (const [taskId, fields] of resolved) {\n if (!fields) continue;\n applied += upsert.run({\n taskRef: taskRef(taskId),\n taskId,\n initiative: fields.initiative ?? null,\n title: fields.title ?? null,\n status: fields.status ?? null,\n estimate: fields.estimate ?? null,\n }).changes;\n }\n return applied;\n })();\n}\n","import { EPISODE_TABLE } from \"./audit-schema-v5.js\";\nimport type { SessionGraph } from \"./graph.js\";\n\n/**\n * One stretch of a session as some segmentation heuristic cut it. The rule\n * lives above storage (session-analytics); this package only keeps its output.\n * Offsets are byte offsets into the session's transcript.\n */\nexport interface EpisodeRow {\n episodeIndex: number;\n heuristicVersion: number;\n startedAt: string;\n endedAt: string;\n startOffset: number;\n endOffset: number;\n /** `session_start`, `brief`, `channel_followup`, `idle_gap`, `pr_merge`, `spawn_wave_complete`, `task_wrap`, `context_reset`, or a newer heuristic's term. */\n openedBy: string;\n assignmentOffset?: number | null;\n firstDeliverableOffset?: number | null;\n firstDeliverableSignal?: string | null;\n firstStatusOffset?: number | null;\n}\n\nconst DELETE_EPISODES = `DELETE FROM ${EPISODE_TABLE} WHERE session_id = ? AND heuristic = ?`;\n\nconst INSERT_EPISODE = `\n INSERT INTO ${EPISODE_TABLE} (session_id, episode_index, heuristic, heuristic_version, started_at, ended_at,\n start_offset, end_offset, opened_by, assignment_offset, first_deliverable_offset, first_deliverable_signal, first_status_offset)\n VALUES (@sessionId, @episodeIndex, @heuristic, @heuristicVersion, @startedAt, @endedAt,\n @startOffset, @endOffset, @openedBy, @assignmentOffset, @firstDeliverableOffset, @firstDeliverableSignal, @firstStatusOffset)`;\n\n/**\n * The only writer of `episode`. Replaces one heuristic's segmentation of one\n * session atomically and leaves every other heuristic's rows alone, so two rule\n * sets can coexist while one is compared against the other. Returns rows written.\n */\nexport function replaceEpisodes(graph: SessionGraph, sessionId: string, heuristic: string, rows: readonly EpisodeRow[]): number {\n const remove = graph.db.prepare(DELETE_EPISODES);\n const insert = graph.db.prepare(INSERT_EPISODE);\n return graph.db.transaction(() => {\n remove.run(sessionId, heuristic);\n for (const row of rows) insert.run(episodeParams(sessionId, heuristic, row));\n return rows.length;\n })();\n}\n\nfunction episodeParams(sessionId: string, heuristic: string, row: EpisodeRow): Record<string, string | number | null> {\n return {\n sessionId, heuristic,\n episodeIndex: row.episodeIndex, heuristicVersion: row.heuristicVersion,\n startedAt: row.startedAt, endedAt: row.endedAt, startOffset: row.startOffset, endOffset: row.endOffset, openedBy: row.openedBy,\n assignmentOffset: row.assignmentOffset ?? null, firstDeliverableOffset: row.firstDeliverableOffset ?? null,\n firstDeliverableSignal: row.firstDeliverableSignal ?? null, firstStatusOffset: row.firstStatusOffset ?? null,\n };\n}\n","import type { SessionGraph } from \"./graph.js\";\n\n/** USD per million tokens for one model prefix from one date. Shaped so session-analytics' `PRICE_TABLE` passes straight through. */\nexport interface PriceInput {\n /** Matched against `request.model` by longest prefix in `request_cost`. */\n modelPrefix: string;\n /** ISO date or timestamp; compared as text against `request.ts`. */\n effectiveFrom: string;\n input: number;\n cacheRead: number;\n cacheWrite5m: number;\n cacheWrite1h: number;\n output: number;\n}\n\nexport interface SyncPricesOptions {\n /** Stamped on every row so a report can name the table it priced with. */\n tableVersion: number;\n source?: string;\n}\n\n/** Replace every `price` row with `rows` in one transaction, so `request_cost` never reads a half-written table. */\nexport function syncPrices(graph: SessionGraph, rows: readonly PriceInput[], options: SyncPricesOptions): number {\n const insert = graph.db.prepare(\n `INSERT INTO price (model, effective_from, table_version, input_usd_mtok, cache_read_usd_mtok,\n cache_write_5m_usd_mtok, cache_write_1h_usd_mtok, output_usd_mtok, source)\n VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,\n );\n const source = options.source ?? null;\n graph.db.transaction(() => {\n graph.db.exec(\"DELETE FROM price\");\n for (const r of rows) {\n insert.run(r.modelPrefix, r.effectiveFrom, options.tableVersion, r.input, r.cacheRead, r.cacheWrite5m, r.cacheWrite1h, r.output, source);\n }\n })();\n return rows.length;\n}\n","import { randomUUID } from \"node:crypto\";\nimport { stat } from \"node:fs/promises\";\nimport { contentHash } from \"@titan-design/locator\";\nimport { conversationRef } from \"@titan-design/agent-protocol\";\nimport { SPAN_TEXT_CAP, readCodexObservations, type CodexReadResult, type NormalizedSessionObservation, type SessionSourceDescriptor, type SourceTextLocator } from \"@titan-design/session-read\";\nimport type { SessionGraph } from \"./graph.js\";\nimport { insertObservation, observationText } from \"./normalized-project.js\";\n\nexport interface NormalizedIndexResult { status: \"indexed\" | \"unchanged\" | \"missing\" | \"quarantined\"; conversationRef: string; observations: number; reason?: string }\n\n/** Replay changed sources into temporary staging; swap rows and watermark atomically. */\nexport async function indexCodexSource(graph: SessionGraph, source: SessionSourceDescriptor): Promise<NormalizedIndexResult> {\n const ref = conversationRef(source.conversation);\n const base = { conversationRef: ref, observations: 0 };\n const row = graph.transcripts.ensure(source.sourceId);\n let info;\n try { info = await stat(source.path); } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== \"ENOENT\") throw error;\n graph.transcripts.markStatus(source.sourceId, \"missing\", \"source unavailable\");\n return { ...base, status: \"missing\" };\n }\n // Always replay: the decoder verifies bytes, detects projections that arrived later,\n // and avoids trusting mtime alone. Equality of the resulting prefix is the fast no-op.\n const stage = `stage_${randomUUID().replaceAll(\"-\", \"\")}`;\n graph.db.exec(`CREATE TEMP TABLE ${stage}(seq INTEGER PRIMARY KEY, observation TEXT NOT NULL)`);\n let result: CodexReadResult | undefined;\n try {\n const fingerprint = await contentHash(source.path);\n const insert = graph.db.prepare(`INSERT INTO ${stage}(observation) VALUES (?)`);\n for await (const observation of readCodexObservations(source, {}, done => { result = done; })) insert.run(JSON.stringify(observation));\n if (!result) throw new Error(\"decoder completed without a resume boundary\");\n const boundary = (result as CodexReadResult).resumeBoundary;\n const prior = graph.db.prepare(\"SELECT descriptor FROM normalized_source WHERE transcript_id = ?\").get(row.sourceId) as { descriptor: string } | undefined;\n if (prior && row.contentHash === fingerprint && row.prefixHash === boundary.prefixHash && row.lastOffset === boundary.byteOffset) {\n graph.db.prepare(\"UPDATE normalized_source SET descriptor = ? WHERE transcript_id = ?\").run(JSON.stringify(source), row.sourceId);\n graph.transcripts.markStatus(source.sourceId, \"ok\", null);\n return { ...base, status: \"unchanged\" };\n }\n const count = graph.db.transaction(() => {\n purgeNormalizedSource(graph, row.sourceId);\n graph.db.prepare(\"INSERT OR IGNORE INTO conversation(ref,harness,namespace,native_id) VALUES (?,?,?,?)\").run(ref, source.harness, source.namespace, source.conversation.nativeId);\n graph.db.prepare(\"INSERT OR REPLACE INTO normalized_source VALUES (?,?,?,?)\").run(row.sourceId, source.sourceId, ref, JSON.stringify(source));\n const n = applyStaged(graph, stage, row.sourceId, ref);\n graph.transcripts.advance(source.sourceId, { lastOffset: boundary.byteOffset, prefixHash: boundary.prefixHash, fileSize: info.size, fileMtime: info.mtime.toISOString(), contentHash: fingerprint });\n return n;\n })();\n return { ...base, status: \"indexed\", observations: count };\n } catch (error) {\n const reason = error instanceof Error ? error.message : String(error);\n graph.transcripts.markStatus(source.sourceId, \"quarantined\", reason);\n return { ...base, status: \"quarantined\", reason };\n } finally { graph.db.exec(`DROP TABLE ${stage}`); }\n}\n\nfunction applyStaged(graph: SessionGraph, stage: string, transcriptId: number, ref: string): number {\n const spans = `${stage}_spans`;\n graph.db.exec(`CREATE TEMP TABLE ${spans}(field TEXT, offset INTEGER, length INTEGER, text TEXT, locators TEXT, PRIMARY KEY(field,offset))`);\n let count = 0;\n try {\n for (const row of stagedRows<{ observation: string }>(graph, stage)) {\n const o = JSON.parse(row.observation) as NormalizedSessionObservation;\n insertObservation(graph, transcriptId, o);\n for (const p of observationText(o)) stageText(graph, spans, p.field, p.text, p.locator);\n count++;\n }\n for (const s of stagedRows<{ field: string; offset: number; length: number; text: string; locators: string }>(graph, spans)) {\n const id = graph.spans.index({ ownerRef: ref, sourceId: transcriptId, field: s.field, byteOffset: s.offset, byteLength: s.length }, s.text);\n graph.db.prepare(\"INSERT INTO normalized_span VALUES (?,?)\").run(id, s.locators);\n }\n } finally { graph.db.exec(`DROP TABLE ${spans}`); }\n return count;\n}\n\nfunction stageText(graph: SessionGraph, table: string, field: string, text: string, locator: SourceTextLocator): void {\n const line = locator.evidence.line;\n const prior = graph.db.prepare(`SELECT text,locators FROM ${table} WHERE field = ? AND offset = ?`).get(field, line.byteOffset) as { text: string; locators: string } | undefined;\n const locators = prior ? JSON.parse(prior.locators) as unknown[] : [];\n locators.push(locator);\n graph.db.prepare(`INSERT OR REPLACE INTO ${table} VALUES (?,?,?,?,?)`).run(field, line.byteOffset, line.byteLength, (prior ? `${prior.text}\\n${text}` : text).slice(0, SPAN_TEXT_CAP), JSON.stringify(locators));\n}\n\nfunction purgeNormalizedSource(graph: SessionGraph, transcriptId: number): void {\n graph.db.prepare(\"DELETE FROM normalized_span WHERE span_id IN (SELECT span_id FROM search_span WHERE source_id = ?)\").run(transcriptId);\n graph.db.prepare(\"DELETE FROM search_span WHERE source_id = ?\").run(transcriptId);\n graph.db.prepare(\"DELETE FROM normalized_event WHERE transcript_id = ?\").run(transcriptId);\n}\n\n\n/** Finish each SELECT before writing; SQLite forbids writes during an active iterator. */\nfunction* stagedRows<T>(graph: SessionGraph, table: string): Generator<T> {\n const select = graph.db.prepare(`SELECT rowid AS cursor, * FROM ${table} WHERE rowid > ? ORDER BY rowid LIMIT 128`);\n let cursor = 0;\n for (;;) {\n const rows = select.all(cursor) as (T & { cursor: number })[];\n if (!rows.length) return;\n for (const row of rows) { cursor = row.cursor; yield row; }\n }\n}\n","import { conversationRef } from \"@titan-design/agent-protocol\";\nimport { normalizedSearchText, SPAN_TEXT_CAP, scopedConversationItemRef, type NormalizedSessionObservation as Observation, type SourceTextLocator } from \"@titan-design/session-read\";\nimport type { SessionGraph } from \"./graph.js\";\n\n/** Persist structural evidence only; prose remains in the source and transient FTS input. */\nexport function insertObservation(graph: SessionGraph, transcriptId: number, o: Observation): void {\n graph.db.prepare(`INSERT INTO normalized_event VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`).run(\n transcriptId, o.evidence.line.byteOffset, o.evidence.subrecord.index, o.evidence.line.byteLength,\n conversationRef(o.conversation), o.kind, o.timestamp,\n \"turn\" in o && o.turn ? scopedConversationItemRef(o.turn) : null,\n \"call\" in o ? scopedConversationItemRef(o.call) : null,\n \"item\" in o && o.item ? scopedConversationItemRef(o.item) : null,\n o.kind === \"native_turn\" ? o.phase : null,\n o.kind === \"tool_result\" && o.isError !== null ? Number(o.isError) : null,\n o.kind === \"usage\" ? JSON.stringify(o.measurement) : null,\n o.kind === \"metadata\" ? JSON.stringify(o.entries.filter(e => [\"cwd\", \"model\", \"cli_version\", \"git_branch\", \"title\"].includes(e.name))) : null,\n o.historyOrigin ? conversationRef(o.historyOrigin) : null,\n o.kind === \"lineage\" ? conversationRef(o.relatedConversation) : null,\n o.kind === \"lineage\" ? o.relationship : null,\n );\n}\n\nexport interface ObservationText { field: string; text: string; locator: SourceTextLocator }\nexport function observationText(o: Observation): ObservationText[] {\n if (o.kind === \"message\") return o.content.map(p => ({ field: o.role === \"user\" ? \"prompt\" : \"assistant_response\", text: p.text.slice(0, SPAN_TEXT_CAP), locator: p.locator }));\n if (o.kind === \"tool_call\" && o.inputLocator) return [{ field: \"tool_input\", text: normalizedSearchText(o.input), locator: o.inputLocator }];\n if (o.kind === \"tool_result\" && o.outputLocator) return [{ field: \"tool_result\", text: normalizedSearchText(o.output), locator: o.outputLocator }];\n return [];\n}\n","import { contentHash, prefixHash } from \"@titan-design/locator\";\nimport type { UsageMeasurement } from \"@titan-design/agent-protocol\";\nimport { readSessionSourceText, readSessionText, SessionUsageAccumulator, type SessionUsageSummary, type SourceTextLocator, type SessionSourceDescriptor, type SpanField } from \"@titan-design/session-read\";\nimport type { SessionGraph } from \"./graph.js\";\n\nexport interface IndexedSpan { sourceId: number; byteOffset: number; byteLength: number; field: string; spanId?: number }\n/** One resolver for search and error clustering; never display a raw JSON line. */\nexport async function readIndexedText(graph: SessionGraph, span: IndexedSpan): Promise<string | null> {\n const row = graph.db.prepare(`SELECT n.locators FROM normalized_span n JOIN search_span s USING(span_id)\n WHERE s.source_id = ? AND s.byte_offset = ? AND s.field = ?`).get(span.sourceId, span.byteOffset, span.field) as { locators: string } | undefined;\n if (row) {\n const source = graph.db.prepare(\"SELECT descriptor FROM normalized_source WHERE transcript_id = ?\").get(span.sourceId) as { descriptor: string } | undefined;\n if (!source) return null;\n const descriptor = JSON.parse(source.descriptor) as SessionSourceDescriptor;\n const watermark = graph.transcripts.list().find(t => t.sourceId === span.sourceId);\n try { if (!watermark?.prefixHash || await prefixHash(descriptor.path, watermark.lastOffset) !== watermark.prefixHash) return null; }\n catch { return null; }\n if (span.byteOffset + span.byteLength + 1 > watermark.lastOffset) {\n try { if (!watermark.contentHash || await contentHash(descriptor.path) !== watermark.contentHash) return null; } catch { return null; }\n }\n const texts = await Promise.all((JSON.parse(row.locators) as SourceTextLocator[]).map(locator => readSessionSourceText(locator, { sources: [JSON.parse(source.descriptor) as SessionSourceDescriptor] })));\n return texts.some(text => text === null) ? null : texts.join(\"\\n\");\n }\n const normalized = graph.db.prepare(\"SELECT 1 FROM normalized_source WHERE transcript_id = ?\").get(span.sourceId);\n if (normalized) return null;\n const legacy = graph.transcripts.list().find(t => t.sourceId === span.sourceId);\n return legacy ? readSessionText({ path: legacy.sourceKey, byteOffset: span.byteOffset, byteLength: span.byteLength, field: span.field as SpanField }) : null;\n}\n\nexport interface ConversationSummary {\n sessionId: string; harness: string; nativeId: string; namespace: string;\n title: string | null; startedAt: string | null; endedAt: string | null;\n cwd: string | null; gitBranch: string | null; turnCount: number; commitCount: number | null; pushCount: number | null;\n}\nexport function normalizedSessions(graph: SessionGraph, options: { ref?: string; limit?: number; since?: string } = {}): ConversationSummary[] {\n const rows = graph.db.prepare(`SELECT c.ref,c.harness,c.native_id,c.namespace,MIN(e.ts) AS started,\n COUNT(DISTINCT CASE WHEN e.kind = 'native_turn' THEN e.turn_ref END) AS turns\n FROM conversation c JOIN (SELECT DISTINCT conversation_ref FROM normalized_source) s ON s.conversation_ref = c.ref\n LEFT JOIN normalized_event e ON e.conversation_ref = c.ref AND e.history_origin IS NULL\n WHERE c.legacy_session_id IS NULL AND (? IS NULL OR c.ref = ?)\n GROUP BY c.ref HAVING (? IS NULL OR MIN(e.ts) >= ?)\n ORDER BY started DESC LIMIT ?`).all(options.ref ?? null,options.ref ?? null,options.since ?? null,options.since ?? null,options.limit ?? -1) as\n { ref: string; harness: string; native_id: string; namespace: string; started: string | null; turns: number }[];\n const meta = graph.db.prepare(`SELECT json_extract(j.value,'$.value') AS value\n FROM normalized_event e,json_each(e.metadata) j WHERE e.conversation_ref = ?\n AND e.history_origin IS NULL AND json_extract(j.value,'$.name') = ? ORDER BY e.ts DESC,e.byte_offset DESC,e.subrecord_index DESC LIMIT 1`);\n return rows.map(c => {\n const text = (key: string) => { const value = (meta.get(c.ref,key) as { value: unknown } | undefined)?.value; return typeof value === \"string\" ? value : null; };\n return { sessionId:c.ref,harness:c.harness,nativeId:c.native_id,namespace:c.namespace,title:text(\"title\"),startedAt:c.started,\n endedAt:null,cwd:text(\"cwd\"),gitBranch:text(\"git_branch\"),turnCount:c.turns,commitCount:null,pushCount:null };\n });\n}\n\nexport type NormalizedUsageSummary = SessionUsageSummary;\n/** Shared storage-free usage policy keeps graph and direct readers consistent. */\nexport function normalizedUsage(graph: SessionGraph, ref: string): NormalizedUsageSummary[] {\n // Snapshot epochs are local to a physical source; never add copies from different files.\n // Pick the source with the latest native timestamp (then fullest coverage, then stable ID).\n const preferred = graph.db.prepare(`SELECT transcript_id FROM normalized_event\n WHERE conversation_ref = ? AND usage IS NOT NULL AND history_origin IS NULL\n GROUP BY transcript_id ORDER BY MAX(ts) DESC, COUNT(*) DESC, transcript_id ASC LIMIT 1`).get(ref) as { transcript_id: number } | undefined;\n const rows = graph.db.prepare(`SELECT usage FROM normalized_event WHERE conversation_ref = ?\n AND usage IS NOT NULL AND history_origin IS NULL\n AND (json_extract(usage,'$.kind') = 'delta' OR transcript_id = ?)\n ORDER BY byte_offset,subrecord_index`);\n const accumulator = new SessionUsageAccumulator();\n for (const row of rows.iterate(ref, preferred?.transcript_id ?? -1) as Iterable<{ usage: string }>) {\n accumulator.add(JSON.parse(row.usage) as UsageMeasurement);\n }\n return accumulator.summaries();\n}\n"],"mappings":";AAAA,SAAS,WAAW,eAAe,gBAAgB,cAAc,qBAA8B;;;ACGxF,IAAM,uBAAuB;AAG7B,IAAM,eAAe;AAAA,EAC1B;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAGO,IAAM,cAAc;AAEpB,IAAM,YAAY;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAA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,IAAI,KAAK,CAAqB;AAAA,EAC3D;AACA,SAAO,YAAY,UAAU;AAC/B;","names":["sessionRef","sessionRef","TranscriptParseError","extractTranscript","sessionRef","write","extractTranscript","stat","TranscriptParseError","contentHash","conversationRef","SPAN_TEXT_CAP","conversationRef","conversationRef","contentHash","SPAN_TEXT_CAP","contentHash"]}
1
+ {"version":3,"sources":["../src/graph.ts","../src/audit-schema.ts","../src/audit-schema-v5.ts","../src/audit-schema-v6.ts","../src/normalized-schema.ts","../src/schema.ts","../src/audit-apply.ts","../src/facet.ts","../src/apply.ts","../src/purge.ts","../src/audit-rollup.ts","../src/rollup.ts","../src/refresh.ts","../src/outcomes.ts","../src/origin.ts","../src/tasks.ts","../src/episodes.ts","../src/prices.ts","../src/normalized-index.ts","../src/normalized-project.ts","../src/normalized-query.ts"],"sourcesContent":["import { EdgeTable, SpanFtsTables, WatermarkTable, openDatabase, runMigrations, type Db } from \"@titan-design/store-sqlite\";\nimport { DERIVED_TABLES, KIT, MIGRATIONS } from \"./schema.js\";\n\n/** One open session graph: the connection plus the kit helpers bound to its tables. */\nexport interface SessionGraph {\n db: Db;\n transcripts: WatermarkTable;\n edges: EdgeTable;\n spans: SpanFtsTables;\n}\n\nexport interface OpenSessionGraphOptions {\n /**\n * The highest migration version the caller owns, checked before any migration runs.\n * A product layering its own tables on this graph passes its own top version, not this\n * package's: `MIGRATIONS` here is one band of a shared database, never the top of it.\n */\n schemaVersion?: number;\n}\n\nexport function openSessionGraph(dbPath: string, options: OpenSessionGraphOptions = {}): SessionGraph {\n const db = openDatabase(dbPath, { schemaVersion: options.schemaVersion });\n runMigrations(db, MIGRATIONS);\n return {\n db,\n transcripts: new WatermarkTable(db, { name: KIT.watermark }),\n edges: new EdgeTable(db, { name: KIT.edge }),\n spans: new SpanFtsTables(db, { name: KIT.spanFts }),\n };\n}\n\n/**\n * Clear every derived row and rewind all watermarks so the next refresh\n * rebuilds from byte 0. Rewinding alone is not enough: the accumulating\n * upserts would add a second copy of every count.\n */\nexport function resetIndex(graph: SessionGraph): void {\n graph.db.transaction(() => {\n for (const table of DERIVED_TABLES) graph.db.exec(`DELETE FROM \"${table}\"`);\n graph.spans.clearIndex();\n for (const row of graph.transcripts.list()) graph.transcripts.rewind(row.sourceKey);\n })();\n}\n\nexport function allSessionIds(graph: SessionGraph): string[] {\n return (graph.db.prepare(\"SELECT session_id FROM session\").all() as { session_id: string }[]).map((r) => r.session_id);\n}\n","import type { Db } from \"@titan-design/store-sqlite\";\n\n/** Recorded in `_migration`; store-sqlite refuses a database whose applied name differs, so never rename it. */\nexport const AUDIT_MIGRATION_NAME = \"audit tables\";\n\n/** Tables written per transcript by `applyAudit` and dropped by `purgeTranscript`. */\nexport const AUDIT_TABLES = [\n \"request\",\n \"tool_call\",\n \"inbound\",\n \"context_block\",\n \"compaction\",\n \"queue_op\",\n \"session_signal\",\n \"cost_state_observation\",\n] as const;\n\n/** Per-transcript read state for each audit facet; cleared with the audit rows so a re-read starts clean. */\nexport const FACET_TABLE = \"transcript_facet\";\n\nexport const AUDIT_DDL = `\n CREATE TABLE IF NOT EXISTS request (\n transcript_id INTEGER NOT NULL,\n request_id TEXT NOT NULL,\n byte_offset INTEGER NOT NULL, -- first line seen for this request\n session_id TEXT NOT NULL,\n message_id TEXT,\n ts TEXT NOT NULL,\n model TEXT NOT NULL,\n input_tokens INTEGER NOT NULL DEFAULT 0,\n cache_read_tokens INTEGER NOT NULL DEFAULT 0,\n cache_creation_tokens INTEGER NOT NULL DEFAULT 0,\n cache_creation_5m INTEGER NOT NULL DEFAULT 0,\n cache_creation_1h INTEGER NOT NULL DEFAULT 0,\n output_tokens INTEGER NOT NULL DEFAULT 0,\n thinking_tokens INTEGER NOT NULL DEFAULT 0,\n context_tokens INTEGER NOT NULL DEFAULT 0, -- input + cache_read + cache_creation\n service_tier TEXT,\n is_sidechain INTEGER NOT NULL DEFAULT 0,\n -- rollup-owned, recomputed for touched sessions:\n seq_in_session INTEGER,\n gap_ms INTEGER, -- since previous request in the session\n ctx_delta INTEGER, -- context_tokens - (prev.context_tokens + prev.output_tokens)\n wake_cause TEXT,\n wake_delivery TEXT,\n wake_detail TEXT, -- tool name, channel sender, or NULL\n wake_tool_family TEXT,\n wake_mcp_server TEXT,\n wake_offset INTEGER, -- byte_offset of the inbound row\n PRIMARY KEY (transcript_id, request_id)\n ) WITHOUT ROWID;\n CREATE INDEX IF NOT EXISTS idx_request_session_ts ON request(session_id, ts);\n CREATE INDEX IF NOT EXISTS idx_request_ts ON request(ts);\n CREATE INDEX IF NOT EXISTS idx_request_id ON request(request_id);\n\n CREATE TABLE IF NOT EXISTS tool_call (\n transcript_id INTEGER NOT NULL, byte_offset INTEGER NOT NULL, block_index INTEGER NOT NULL,\n session_id TEXT NOT NULL, ts TEXT NOT NULL, tool_use_id TEXT NOT NULL,\n name TEXT NOT NULL, family TEXT NOT NULL, mcp_server TEXT, input_chars INTEGER NOT NULL,\n PRIMARY KEY (transcript_id, byte_offset, block_index)\n ) WITHOUT ROWID;\n CREATE INDEX IF NOT EXISTS idx_tool_call_use ON tool_call(tool_use_id);\n\n CREATE TABLE IF NOT EXISTS inbound (\n transcript_id INTEGER NOT NULL, byte_offset INTEGER NOT NULL, block_index INTEGER NOT NULL,\n session_id TEXT NOT NULL, ts TEXT NOT NULL,\n cause TEXT NOT NULL, delivery TEXT NOT NULL, detail TEXT,\n origin_server TEXT, from_name TEXT, msg_id TEXT, tool_use_id TEXT,\n is_error INTEGER NOT NULL DEFAULT 0, content_hash TEXT NOT NULL, chars INTEGER NOT NULL,\n queued_ms INTEGER, -- rollup-owned\n PRIMARY KEY (transcript_id, byte_offset, block_index)\n ) WITHOUT ROWID;\n CREATE INDEX IF NOT EXISTS idx_inbound_session ON inbound(session_id, byte_offset);\n\n CREATE TABLE IF NOT EXISTS context_block (\n transcript_id INTEGER NOT NULL, byte_offset INTEGER NOT NULL, block_index INTEGER NOT NULL,\n session_id TEXT NOT NULL, ts TEXT NOT NULL, source TEXT NOT NULL,\n tool_use_id TEXT, attachment_type TEXT, chars INTEGER NOT NULL, is_media INTEGER NOT NULL DEFAULT 0,\n PRIMARY KEY (transcript_id, byte_offset, block_index)\n ) WITHOUT ROWID;\n CREATE INDEX IF NOT EXISTS idx_context_block_session ON context_block(session_id, source);\n\n CREATE TABLE IF NOT EXISTS compaction (\n transcript_id INTEGER NOT NULL, byte_offset INTEGER NOT NULL,\n session_id TEXT NOT NULL, ts TEXT NOT NULL, trigger TEXT,\n pre_tokens INTEGER, post_tokens INTEGER, dropped_tokens INTEGER, duration_ms INTEGER,\n mid_loop INTEGER, -- rollup-owned: previous inbound was a tool_result\n PRIMARY KEY (transcript_id, byte_offset)\n ) WITHOUT ROWID;\n\n CREATE TABLE IF NOT EXISTS queue_op (\n transcript_id INTEGER NOT NULL, byte_offset INTEGER NOT NULL,\n session_id TEXT NOT NULL, ts TEXT NOT NULL, operation TEXT NOT NULL,\n content_hash TEXT, origin_server TEXT,\n PRIMARY KEY (transcript_id, byte_offset)\n ) WITHOUT ROWID;\n CREATE INDEX IF NOT EXISTS idx_queue_op_hash ON queue_op(session_id, content_hash);\n\n CREATE TABLE IF NOT EXISTS session_signal (\n transcript_id INTEGER NOT NULL, byte_offset INTEGER NOT NULL, block_index INTEGER NOT NULL,\n session_id TEXT NOT NULL, ts TEXT NOT NULL, signal TEXT NOT NULL, detail TEXT, tool_use_id TEXT,\n -- one Bash block can emit up to three signals (commit, push, pr_create); the signal name disambiguates them\n PRIMARY KEY (transcript_id, byte_offset, block_index, signal)\n ) WITHOUT ROWID;\n CREATE INDEX IF NOT EXISTS idx_signal_session ON session_signal(session_id, ts);\n\n CREATE TABLE IF NOT EXISTS cost_state_observation (\n transcript_id INTEGER NOT NULL, byte_offset INTEGER NOT NULL,\n session_id TEXT NOT NULL, ts TEXT, total_cost_usd REAL NOT NULL, model_usage TEXT NOT NULL,\n PRIMARY KEY (transcript_id, byte_offset)\n ) WITHOUT ROWID;\n\n CREATE TABLE IF NOT EXISTS transcript_facet (\n transcript_id INTEGER NOT NULL, facet TEXT NOT NULL,\n version INTEGER NOT NULL, indexed_to INTEGER NOT NULL,\n PRIMARY KEY (transcript_id, facet)\n ) WITHOUT ROWID;\n`;\n\n/** `[table, column, type]`; `turn.wake_cause` is rollup-owned. */\nexport const AUDIT_COLUMNS = [\n [\"session\", \"account\", \"TEXT\"],\n [\"turn\", \"wake_cause\", \"TEXT\"],\n [\"task\", \"estimate\", \"REAL\"],\n [\"pr\", \"review_rounds\", \"INTEGER\"],\n [\"pr\", \"closed_at\", \"TEXT\"],\n [\"pr\", \"outcome_checked_at\", \"TEXT\"],\n] as const;\n\n/** The version 4 body. Safe to run twice: a database can reach version 4 after a partial manual repair. */\nexport function applyAuditSchema(db: Db): void {\n db.exec(AUDIT_DDL);\n for (const [table, column, type] of AUDIT_COLUMNS) addColumnIfMissing(db, table, column, type);\n}\n\n/** SQLite's `ADD COLUMN` has no `IF NOT EXISTS`, and a repeat throws \"duplicate column name\". */\nexport function addColumnIfMissing(db: Db, table: string, column: string, type: string): void {\n const present = db.prepare(\"SELECT 1 FROM pragma_table_info(?) WHERE name = ?\").get(table, column);\n if (!present) db.exec(`ALTER TABLE \"${table}\" ADD COLUMN \"${column}\" ${type}`);\n}\n","import type { Db } from \"@titan-design/store-sqlite\";\n\n/** Recorded in `_migration`; store-sqlite refuses a database whose applied name differs, so never rename it. */\nexport const ORIGIN_MIGRATION_NAME = \"origin, episodes, prices\";\n\n/** Re-derivable from their own sources rather than from transcripts, so `resetIndex` clears them and the next pass refills them. */\nexport const ORIGIN_TABLES = [\"session_origin\", \"session_external_event\"] as const;\n\n/** Written from transcript offsets by `replaceEpisodes`; a rewritten transcript invalidates them, so purge drops them by session. */\nexport const EPISODE_TABLE = \"episode\";\n\nexport const ORIGIN_DDL = `\n CREATE TABLE IF NOT EXISTS session_origin ( -- not derived from transcripts\n session_id TEXT PRIMARY KEY,\n origin_system TEXT NOT NULL, -- 'agent-chat'\n agent_id TEXT, agent_name TEXT, parent_name TEXT, parent_session_id TEXT,\n profile TEXT, model_alias TEXT, surface TEXT, isolation TEXT, depth INTEGER,\n origin_kind TEXT, -- spawned | adopted | inherited | human\n config_dir TEXT, spawn_cwd TEXT, spawned_at TEXT,\n brief_chars INTEGER, brief_excerpt TEXT, brief_path TEXT, launch_args TEXT,\n resolved_at TEXT NOT NULL\n );\n CREATE INDEX IF NOT EXISTS idx_origin_parent ON session_origin(parent_session_id);\n\n CREATE TABLE IF NOT EXISTS session_external_event ( -- teleport, handoff, retire, exit\n session_id TEXT NOT NULL, ts TEXT NOT NULL, origin_system TEXT NOT NULL,\n kind TEXT NOT NULL, detail TEXT,\n PRIMARY KEY (session_id, ts, kind)\n ) WITHOUT ROWID;\n\n CREATE TABLE IF NOT EXISTS episode ( -- provisional, see section 9\n session_id TEXT NOT NULL, episode_index INTEGER NOT NULL,\n heuristic TEXT NOT NULL, heuristic_version INTEGER NOT NULL,\n started_at TEXT NOT NULL, ended_at TEXT NOT NULL,\n start_offset INTEGER NOT NULL, end_offset INTEGER NOT NULL,\n opened_by TEXT NOT NULL, -- brief | channel_followup | idle_gap | compaction\n assignment_offset INTEGER, first_deliverable_offset INTEGER, first_deliverable_signal TEXT,\n first_status_offset INTEGER,\n PRIMARY KEY (session_id, heuristic, episode_index)\n ) WITHOUT ROWID;\n\n CREATE TABLE IF NOT EXISTS price (\n model TEXT NOT NULL, effective_from TEXT NOT NULL, table_version INTEGER NOT NULL,\n input_usd_mtok REAL NOT NULL, cache_read_usd_mtok REAL NOT NULL,\n cache_write_5m_usd_mtok REAL NOT NULL, cache_write_1h_usd_mtok REAL NOT NULL,\n output_usd_mtok REAL NOT NULL, source TEXT,\n PRIMARY KEY (model, effective_from)\n ) WITHOUT ROWID;\n`;\n\nconst REQUEST_COLUMNS = `transcript_id, request_id, byte_offset, session_id, message_id, ts, model,\n input_tokens, cache_read_tokens, cache_creation_tokens, cache_creation_5m, cache_creation_1h,\n output_tokens, thinking_tokens, context_tokens, service_tier, is_sidechain,\n seq_in_session, gap_ms, ctx_delta, wake_cause, wake_delivery, wake_detail,\n wake_tool_family, wake_mcp_server, wake_offset`;\n\n/** Fan-out copies of one request across transcripts collapse to the earliest `(ts, transcript_id)`. Every cost query reads this, never `request`. */\nconst REQUEST_DEDUP = `\n CREATE VIEW IF NOT EXISTS request_dedup AS\n SELECT ${REQUEST_COLUMNS} FROM (\n SELECT r.*, ROW_NUMBER() OVER (PARTITION BY r.request_id ORDER BY r.ts, r.transcript_id) AS copy_rank\n FROM request r\n ) WHERE copy_rank = 1;\n`;\n\n/**\n * Longest model prefix wins, so `claude-opus-5[1m]` prices as `claude-opus-5`; then the latest\n * `effective_from` at or before the request. An unmatched model reads `priced = 0` and costs 0,\n * never a guessed default. A split-less cache write (`5m + 1h = 0`) prices at the 5m rate.\n */\nconst REQUEST_COST = `\n CREATE VIEW IF NOT EXISTS request_cost AS\n WITH candidate AS (\n SELECT d.request_id, p.model AS price_model, p.effective_from AS price_effective_from,\n p.input_usd_mtok, p.cache_read_usd_mtok, p.cache_write_5m_usd_mtok, p.cache_write_1h_usd_mtok, p.output_usd_mtok,\n ROW_NUMBER() OVER (PARTITION BY d.request_id ORDER BY length(p.model) DESC, p.effective_from DESC) AS match_rank\n FROM request_dedup d\n JOIN price p ON substr(d.model, 1, length(p.model)) = p.model AND p.effective_from <= d.ts\n ), component AS (\n SELECT d.*, c.price_model, c.price_effective_from, c.price_model IS NOT NULL AS priced,\n COALESCE(d.input_tokens * c.input_usd_mtok, 0) / 1e6 AS input_cost_usd,\n COALESCE(d.cache_read_tokens * c.cache_read_usd_mtok, 0) / 1e6 AS cache_read_cost_usd,\n COALESCE(CASE WHEN d.cache_creation_5m + d.cache_creation_1h = 0 THEN d.cache_creation_tokens ELSE d.cache_creation_5m END\n * c.cache_write_5m_usd_mtok, 0) / 1e6 AS cache_write_5m_cost_usd,\n COALESCE(d.cache_creation_1h * c.cache_write_1h_usd_mtok, 0) / 1e6 AS cache_write_1h_cost_usd,\n COALESCE(d.output_tokens * c.output_usd_mtok, 0) / 1e6 AS output_cost_usd\n FROM request_dedup d\n LEFT JOIN candidate c ON c.request_id = d.request_id AND c.match_rank = 1\n )\n SELECT *,\n input_cost_usd + cache_read_cost_usd + cache_write_5m_cost_usd + cache_write_1h_cost_usd + output_cost_usd AS cost_usd,\n (cache_read_tokens < 0.2 * context_tokens AND cache_creation_tokens >= 20000) AS is_cold,\n CASE WHEN context_tokens < 50000 THEN '<50k' WHEN context_tokens < 100000 THEN '50-100k'\n WHEN context_tokens < 200000 THEN '100-200k' ELSE '200k+' END AS context_band,\n CASE WHEN gap_ms IS NULL THEN NULL WHEN gap_ms < 300000 THEN '<5m'\n WHEN gap_ms < 3600000 THEN '5-60m' ELSE '>60m' END AS gap_band\n FROM component;\n`;\n\nconst ASSISTANT_OUTPUT = \"'assistant_text', 'assistant_thinking', 'assistant_tool_input'\";\n\n/**\n * A block belongs to the first request after it in its transcript; a block on the request's own\n * line is that request's output and so feeds the next one. Blocks whose request is a fan-out copy\n * drop out with it, keeping estimates aligned with `request_dedup`. Assistant output is already\n * subtracted from `ctx_delta`, so those rows stay visible with a NULL `est_tokens` and no share.\n */\nconst CONTEXT_CONTRIBUTION = `\n CREATE VIEW IF NOT EXISTS context_contribution AS\n WITH stream AS (\n SELECT transcript_id, byte_offset, 0 AS lane, block_index, NULL AS request_id FROM context_block\n UNION ALL\n SELECT transcript_id, byte_offset, -1 AS lane, 0, request_id FROM request\n ), ordered AS (\n SELECT *, COUNT(request_id) OVER (PARTITION BY transcript_id ORDER BY byte_offset, lane, block_index ROWS UNBOUNDED PRECEDING) AS requests_before\n FROM stream\n ), owner AS (\n SELECT b.transcript_id, b.byte_offset, b.block_index, r.request_id\n FROM ordered b JOIN ordered r ON r.transcript_id = b.transcript_id AND r.lane = -1 AND r.requests_before = b.requests_before + 1\n WHERE b.lane = 0\n ), tool AS (\n SELECT tool_use_id, name, family, mcp_server,\n ROW_NUMBER() OVER (PARTITION BY tool_use_id ORDER BY transcript_id, byte_offset, block_index) AS copy_rank\n FROM tool_call\n )\n SELECT cb.transcript_id, cb.byte_offset, cb.block_index, cb.session_id, cb.ts, cb.source,\n cb.tool_use_id, cb.attachment_type, cb.chars, cb.is_media, o.request_id, d.ctx_delta,\n CASE WHEN cb.source IN (${ASSISTANT_OUTPUT}) THEN NULL\n ELSE d.ctx_delta * cb.chars * 1.0 / NULLIF(SUM(CASE WHEN cb.source IN (${ASSISTANT_OUTPUT}) THEN 0 ELSE cb.chars END)\n OVER (PARTITION BY o.transcript_id, o.request_id), 0) END AS est_tokens,\n t.name AS tool_name, t.family AS tool_family, t.mcp_server\n FROM context_block cb\n JOIN owner o USING (transcript_id, byte_offset, block_index)\n JOIN request_dedup d ON d.transcript_id = o.transcript_id AND d.request_id = o.request_id\n LEFT JOIN tool t ON t.tool_use_id = cb.tool_use_id AND t.copy_rank = 1;\n`;\n\nexport const ORIGIN_VIEWS = [REQUEST_DEDUP, REQUEST_COST, CONTEXT_CONTRIBUTION] as const;\n\n/** The version 5 body. Every statement is `IF NOT EXISTS`, so a repeat run is a no-op. */\nexport function applyOriginSchema(db: Db): void {\n db.exec(ORIGIN_DDL);\n for (const view of ORIGIN_VIEWS) db.exec(view);\n}\n","import type { Db } from \"@titan-design/store-sqlite\";\nimport { addColumnIfMissing } from \"./audit-schema.js\";\nimport { EPISODE_TABLE } from \"./audit-schema-v5.js\";\n\n/** Recorded in `_migration`; store-sqlite refuses a database whose applied name differs, so never rename it. */\nexport const EPISODE_TRANSCRIPT_MIGRATION_NAME = \"episode transcript ids\";\n\n/**\n * Nullable so existing episode rows survive; a rewritten transcript's episodes are\n * dropped and rebuilt by `replaceEpisodes` anyway. `transcript_id` is INTEGER\n * everywhere else in this schema (`request`, `inbound`, `session_signal`, ...), so\n * these match rather than introducing a TEXT id for the same concept.\n */\nexport function applyEpisodeTranscriptSchema(db: Db): void {\n addColumnIfMissing(db, EPISODE_TABLE, \"start_transcript_id\", \"INTEGER\");\n addColumnIfMissing(db, EPISODE_TABLE, \"end_transcript_id\", \"INTEGER\");\n}\n","import { conversationRef } from \"@titan-design/agent-protocol\";\nimport type { Db } from \"@titan-design/store-sqlite\";\n\n/** Additive: legacy rows, aliases and original locators are never rewritten. */\nexport const NORMALIZED_DDL = `\nCREATE TABLE IF NOT EXISTS conversation (\n ref TEXT PRIMARY KEY, harness TEXT NOT NULL, namespace TEXT NOT NULL,\n native_id TEXT NOT NULL, legacy_session_id TEXT,\n UNIQUE(harness, namespace, native_id)\n);\nCREATE TABLE IF NOT EXISTS conversation_alias (\n legacy_ref TEXT NOT NULL, conversation_ref TEXT NOT NULL,\n PRIMARY KEY(legacy_ref, conversation_ref)\n);\nCREATE TABLE IF NOT EXISTS normalized_source (\n transcript_id INTEGER PRIMARY KEY, source_id TEXT NOT NULL UNIQUE,\n conversation_ref TEXT NOT NULL, descriptor TEXT NOT NULL\n);\nCREATE TABLE IF NOT EXISTS normalized_event (\n transcript_id INTEGER NOT NULL, byte_offset INTEGER NOT NULL,\n subrecord_index INTEGER NOT NULL, byte_length INTEGER NOT NULL,\n conversation_ref TEXT NOT NULL, kind TEXT NOT NULL, ts TEXT,\n turn_ref TEXT, call_ref TEXT, item_ref TEXT, phase TEXT, is_error INTEGER,\n usage TEXT, metadata TEXT, history_origin TEXT, related_ref TEXT, relationship TEXT,\n PRIMARY KEY(transcript_id, byte_offset, subrecord_index)\n);\nCREATE INDEX IF NOT EXISTS idx_normalized_event_conversation ON normalized_event(conversation_ref, ts);\nCREATE TABLE IF NOT EXISTS normalized_span (\n span_id INTEGER PRIMARY KEY, locators TEXT NOT NULL\n);\n`;\n\n/** Only the old transcript session table proves Claude provenance, never a ref prefix. */\nexport function backfillClaudeAliases(db: Db, sessionIds?: readonly string[]): void {\n const insert = db.prepare(\"INSERT OR IGNORE INTO conversation(ref,harness,namespace,native_id,legacy_session_id) VALUES (?,?,?,?,?)\");\n const alias = db.prepare(\"INSERT OR IGNORE INTO conversation_alias VALUES (?,?)\");\n const rows = sessionIds?.map(session_id => ({ session_id })) ?? db.prepare(\"SELECT session_id FROM session\").all() as Iterable<{ session_id: string }>;\n for (const row of rows) {\n const ref = conversationRef({ harness: \"claude-code\", namespace: \"legacy\", nativeId: row.session_id });\n insert.run(ref, \"claude-code\", \"legacy\", row.session_id, row.session_id);\n alias.run(`session:${row.session_id}`, ref);\n }\n}\n\n/** Ambiguity is explicit; workspace session bodies remain in their original namespace. */\nexport function resolveConversationAlias(db: Db, legacyRef: string): string | null {\n const rows = db.prepare(\"SELECT conversation_ref FROM conversation_alias WHERE legacy_ref = ?\").all(legacyRef) as { conversation_ref: string }[];\n if (rows.length > 1) throw new Error(`ambiguous conversation alias: ${legacyRef}`);\n return rows[0]?.conversation_ref ?? null;\n}\n","import { AUDIT_MIGRATION_NAME, AUDIT_TABLES, FACET_TABLE, applyAuditSchema } from \"./audit-schema.js\";\nimport { EPISODE_TABLE, ORIGIN_MIGRATION_NAME, ORIGIN_TABLES, applyOriginSchema } from \"./audit-schema-v5.js\";\nimport { EPISODE_TRANSCRIPT_MIGRATION_NAME, applyEpisodeTranscriptSchema } from \"./audit-schema-v6.js\";\nimport { NORMALIZED_DDL, backfillClaudeAliases } from \"./normalized-schema.js\";\nimport { SQL_NOW, kitMigration, type Migration } from \"@titan-design/store-sqlite\";\n\n/** Kit table names this graph uses. `watermark` rows are transcripts; `search_*` are the FTS spans. */\nexport const KIT = { watermark: \"transcript\", edge: \"edge\", spanFts: \"search\" } as const;\n\n/**\n * Legacy domain tables. Original sources can be pruned; schema migrations must\n * preserve these rows rather than assuming a replay is possible.\n * Locators are `(transcript_id, byte_offset, byte_length)`; `fact_id` rows\n * resolve through the facts table's unique `(transcript_id, byte_offset)`.\n */\nexport const DOMAIN_DDL = `\n CREATE TABLE IF NOT EXISTS fact (\n fact_id INTEGER PRIMARY KEY,\n transcript_id INTEGER NOT NULL,\n byte_offset INTEGER NOT NULL,\n byte_length INTEGER NOT NULL,\n event_type TEXT NOT NULL,\n ts TEXT NOT NULL,\n seq INTEGER NOT NULL,\n session_id TEXT NOT NULL,\n prompt_id TEXT,\n tool_use_id TEXT,\n t_indexed TEXT NOT NULL DEFAULT (${SQL_NOW}),\n UNIQUE (transcript_id, byte_offset)\n );\n CREATE INDEX IF NOT EXISTS idx_fact_session_ts ON fact(session_id, ts);\n CREATE INDEX IF NOT EXISTS idx_fact_prompt ON fact(prompt_id);\n CREATE INDEX IF NOT EXISTS idx_fact_tool_use ON fact(tool_use_id);\n\n CREATE TABLE IF NOT EXISTS session (\n session_id TEXT PRIMARY KEY,\n transcript_id INTEGER,\n started_at TEXT,\n ended_at TEXT,\n start_type TEXT,\n cwd TEXT,\n git_branch TEXT,\n ai_title TEXT,\n seed_prompt TEXT,\n cli_version TEXT,\n turn_count INTEGER NOT NULL DEFAULT 0,\n commit_count INTEGER NOT NULL DEFAULT 0,\n push_count INTEGER NOT NULL DEFAULT 0\n );\n CREATE INDEX IF NOT EXISTS idx_session_started ON session(started_at);\n\n CREATE TABLE IF NOT EXISTS session_model_usage (\n session_id TEXT NOT NULL,\n model TEXT NOT NULL,\n input_tokens INTEGER NOT NULL DEFAULT 0,\n output_tokens INTEGER NOT NULL DEFAULT 0,\n cache_read_tokens INTEGER NOT NULL DEFAULT 0,\n cache_creation_tokens INTEGER NOT NULL DEFAULT 0,\n thinking_tokens INTEGER NOT NULL DEFAULT 0,\n request_count INTEGER NOT NULL DEFAULT 0,\n PRIMARY KEY (session_id, model)\n );\n\n CREATE TABLE IF NOT EXISTS turn (\n prompt_id TEXT PRIMARY KEY,\n session_id TEXT NOT NULL,\n turn_index INTEGER NOT NULL,\n started_at TEXT NOT NULL,\n ended_at TEXT,\n duration_ms INTEGER,\n tool_call_count INTEGER NOT NULL DEFAULT 0,\n thinking_ms INTEGER NOT NULL DEFAULT 0,\n fact_id_start INTEGER\n );\n CREATE INDEX IF NOT EXISTS idx_turn_session ON turn(session_id, turn_index);\n\n CREATE TABLE IF NOT EXISTS permission_phase (\n phase_id INTEGER PRIMARY KEY,\n session_id TEXT NOT NULL,\n from_mode TEXT,\n to_mode TEXT NOT NULL,\n trigger TEXT NOT NULL,\n t_valid TEXT NOT NULL,\n t_invalid TEXT,\n fact_id INTEGER\n );\n CREATE INDEX IF NOT EXISTS idx_phase_session ON permission_phase(session_id, t_valid);\n\n CREATE TABLE IF NOT EXISTS human_edit (\n edit_id INTEGER PRIMARY KEY,\n session_id TEXT NOT NULL,\n file_path TEXT NOT NULL,\n ts TEXT NOT NULL,\n fact_id INTEGER,\n UNIQUE (session_id, file_path, ts)\n );\n\n CREATE TABLE IF NOT EXISTS file_checkpoint (\n checkpoint_id INTEGER PRIMARY KEY,\n session_id TEXT NOT NULL,\n file_path TEXT NOT NULL,\n backup_file_name TEXT NOT NULL,\n version INTEGER NOT NULL,\n backup_time TEXT NOT NULL,\n fact_id INTEGER,\n UNIQUE (session_id, file_path, backup_file_name)\n );\n\n CREATE TABLE IF NOT EXISTS pr (\n pr_ref TEXT PRIMARY KEY, number INTEGER, repo TEXT, title TEXT, state TEXT, url TEXT, merged_at TEXT\n );\n CREATE TABLE IF NOT EXISTS branch (\n branch_ref TEXT PRIMARY KEY, repo TEXT, name TEXT NOT NULL, base TEXT, created_at TEXT, deleted_at TEXT\n );\n CREATE TABLE IF NOT EXISTS file (\n file_ref TEXT PRIMARY KEY, repo TEXT, path TEXT NOT NULL\n );\n CREATE TABLE IF NOT EXISTS task (\n task_ref TEXT PRIMARY KEY, task_id TEXT NOT NULL, initiative TEXT, title TEXT, status TEXT\n );\n CREATE TABLE IF NOT EXISTS subagent (\n agent_ref TEXT PRIMARY KEY,\n session_id TEXT,\n child_session_id TEXT,\n parent_agent_ref TEXT,\n agent_type TEXT,\n label TEXT,\n started_at TEXT,\n ended_at TEXT,\n fact_id INTEGER\n );\n CREATE INDEX IF NOT EXISTS idx_subagent_child ON subagent(child_session_id);\n CREATE TABLE IF NOT EXISTS artifact (\n artifact_ref TEXT PRIMARY KEY, kind TEXT, title TEXT, url TEXT, path TEXT, created_at TEXT\n );\n CREATE TABLE IF NOT EXISTS pr_merge_observation (\n number INTEGER NOT NULL, repo_hint TEXT, merged_at TEXT NOT NULL,\n PRIMARY KEY (number, repo_hint, merged_at)\n );\n CREATE TABLE IF NOT EXISTS pr_create_observation (\n tool_use_id TEXT PRIMARY KEY, title TEXT, number INTEGER, repo TEXT, url TEXT\n );\n`;\n\n/** Every derived table, in an order safe to clear. The watermark table is not derived. */\nexport const DERIVED_TABLES = [\n \"normalized_span\",\n \"normalized_event\",\n \"normalized_source\",\n `${KIT.spanFts}_span`,\n KIT.edge,\n \"turn\",\n \"permission_phase\",\n \"human_edit\",\n \"file_checkpoint\",\n \"subagent\",\n ...AUDIT_TABLES,\n FACET_TABLE,\n ...ORIGIN_TABLES,\n EPISODE_TABLE,\n \"session_model_usage\",\n \"session\",\n \"fact\",\n \"pr\",\n \"pr_merge_observation\",\n \"pr_create_observation\",\n \"branch\",\n \"file\",\n \"task\",\n \"artifact\",\n] as const;\n\nexport const MIGRATIONS: Migration[] = [\n kitMigration(1, { watermark: KIT.watermark, edge: KIT.edge, spanFts: KIT.spanFts }, \"kit tables\"),\n { version: 2, name: \"session graph tables\", up: (db) => db.exec(DOMAIN_DDL) },\n { version: 3, name: \"normalized conversations and source evidence\", up: (db) => { db.exec(NORMALIZED_DDL); backfillClaudeAliases(db); } },\n { version: 4, name: AUDIT_MIGRATION_NAME, up: applyAuditSchema },\n { version: 5, name: ORIGIN_MIGRATION_NAME, up: applyOriginSchema },\n { version: 6, name: EPISODE_TRANSCRIPT_MIGRATION_NAME, up: applyEpisodeTranscriptSchema },\n];\n","import type { TranscriptDelta } from \"@titan-design/session-read\";\nimport type { Db } from \"@titan-design/store-sqlite\";\n\ntype Row = Record<string, unknown>;\n\n/**\n * One API response is written as several assistant lines, each repeating its\n * usage. The row keeps the first line's identity and the largest count seen,\n * so a partial streaming copy never wins and chunk order cannot change it.\n */\nconst UPSERT_REQUEST = `\n INSERT INTO request (transcript_id, request_id, byte_offset, session_id, message_id, ts, model,\n input_tokens, cache_read_tokens, cache_creation_tokens, cache_creation_5m, cache_creation_1h,\n output_tokens, thinking_tokens, context_tokens, service_tier, is_sidechain)\n VALUES (@transcriptId, @requestId, @byteOffset, @sessionId, @messageId, @ts, @model,\n @inputTokens, @cacheReadTokens, @cacheCreationTokens, @cacheCreation5mTokens, @cacheCreation1hTokens,\n @outputTokens, @thinkingTokens, @inputTokens + @cacheReadTokens + @cacheCreationTokens, @serviceTier, @isSidechain)\n ON CONFLICT (transcript_id, request_id) DO UPDATE SET\n session_id = CASE WHEN excluded.byte_offset < byte_offset THEN excluded.session_id ELSE session_id END,\n message_id = CASE WHEN excluded.byte_offset < byte_offset THEN excluded.message_id ELSE message_id END,\n model = CASE WHEN excluded.byte_offset < byte_offset THEN excluded.model ELSE model END,\n service_tier = CASE WHEN excluded.byte_offset < byte_offset THEN excluded.service_tier ELSE service_tier END,\n is_sidechain = CASE WHEN excluded.byte_offset < byte_offset THEN excluded.is_sidechain ELSE is_sidechain END,\n byte_offset = MIN(byte_offset, excluded.byte_offset),\n ts = MIN(ts, excluded.ts),\n input_tokens = MAX(input_tokens, excluded.input_tokens),\n cache_read_tokens = MAX(cache_read_tokens, excluded.cache_read_tokens),\n cache_creation_tokens = MAX(cache_creation_tokens, excluded.cache_creation_tokens),\n cache_creation_5m = MAX(cache_creation_5m, excluded.cache_creation_5m),\n cache_creation_1h = MAX(cache_creation_1h, excluded.cache_creation_1h),\n output_tokens = MAX(output_tokens, excluded.output_tokens),\n thinking_tokens = MAX(thinking_tokens, excluded.thinking_tokens),\n context_tokens = MAX(input_tokens, excluded.input_tokens) + MAX(cache_read_tokens, excluded.cache_read_tokens)\n + MAX(cache_creation_tokens, excluded.cache_creation_tokens)`;\n\n/** Line-located rows are facts about one position in the file, so a re-read of the same bytes is a no-op. */\nconst INSERTS = {\n toolCalls: `INSERT INTO tool_call (transcript_id, byte_offset, block_index, session_id, ts, tool_use_id, name, family, mcp_server, input_chars)\n VALUES (@transcriptId, @byteOffset, @blockIndex, @sessionId, @ts, @toolUseId, @name, @family, @mcpServer, @inputChars)\n ON CONFLICT DO NOTHING`,\n inbound: `INSERT INTO inbound (transcript_id, byte_offset, block_index, session_id, ts, cause, delivery, detail, origin_server, from_name, msg_id, tool_use_id, is_error, content_hash, chars)\n VALUES (@transcriptId, @byteOffset, @blockIndex, @sessionId, @ts, @cause, @delivery, @detail, @originServer, @fromName, @msgId, @toolUseId, @isError, @contentHash, @chars)\n ON CONFLICT DO NOTHING`,\n contextBlocks: `INSERT INTO context_block (transcript_id, byte_offset, block_index, session_id, ts, source, tool_use_id, attachment_type, chars, is_media)\n VALUES (@transcriptId, @byteOffset, @blockIndex, @sessionId, @ts, @source, @toolUseId, @attachmentType, @chars, @isMedia)\n ON CONFLICT DO NOTHING`,\n compactions: `INSERT INTO compaction (transcript_id, byte_offset, session_id, ts, trigger, pre_tokens, post_tokens, dropped_tokens, duration_ms)\n VALUES (@transcriptId, @byteOffset, @sessionId, @ts, @trigger, @preTokens, @postTokens, @droppedTokens, @durationMs)\n ON CONFLICT DO NOTHING`,\n queueOps: `INSERT INTO queue_op (transcript_id, byte_offset, session_id, ts, operation, content_hash, origin_server)\n VALUES (@transcriptId, @byteOffset, @sessionId, @ts, @operation, @contentHash, @originServer)\n ON CONFLICT DO NOTHING`,\n signals: `INSERT INTO session_signal (transcript_id, byte_offset, block_index, session_id, ts, signal, detail, tool_use_id)\n VALUES (@transcriptId, @byteOffset, @blockIndex, @sessionId, @ts, @signal, @detail, @toolUseId)\n ON CONFLICT DO NOTHING`,\n costStates: `INSERT INTO cost_state_observation (transcript_id, byte_offset, session_id, ts, total_cost_usd, model_usage)\n VALUES (@transcriptId, @byteOffset, @sessionId, @ts, @totalCostUsd, @modelUsageJson)\n ON CONFLICT DO NOTHING`,\n} as const;\n\n/** Write one delta's audit events. Runs inside `applyDelta`'s transaction, so it opens none of its own. */\nexport function applyAudit(db: Db, transcriptId: number, delta: TranscriptDelta): void {\n run(db, UPSERT_REQUEST, transcriptId, delta.requests);\n for (const [list, sql] of Object.entries(INSERTS) as [keyof typeof INSERTS, string][]) {\n run(db, sql, transcriptId, delta[list]);\n }\n}\n\nfunction run(db: Db, sql: string, transcriptId: number, events: readonly object[]): void {\n if (events.length === 0) return;\n const statement = db.prepare(sql);\n const names = [...new Set([...sql.matchAll(/@(\\w+)/g)].map((m) => m[1]!))];\n for (const event of events) statement.run(bind(names, { ...(event as Row), transcriptId }));\n}\n\n/** better-sqlite3 rejects unused named parameters and cannot bind booleans. */\nfunction bind(names: readonly string[], row: Row): Row {\n return Object.fromEntries(names.map((name) => {\n const value = row[name] ?? null;\n return [name, typeof value === \"boolean\" ? Number(value) : value];\n }));\n}\n","import { EXTRACT_VERSION, TranscriptParseError, extractTranscript, type DiscoveredTranscript, type TranscriptDelta } from \"@titan-design/session-read\";\nimport type { Db, WatermarkRow } from \"@titan-design/store-sqlite\";\nimport { applyAudit } from \"./audit-apply.js\";\nimport { AUDIT_TABLES, FACET_TABLE } from \"./audit-schema.js\";\nimport type { SessionGraph } from \"./graph.js\";\n\n/** The one facet today: the eight audit tables, all written from the same extraction. */\nexport const AUDIT_FACET = \"audit\";\n\n/** Transcripts re-extracted per pass, so a daemon's pass stays short while the backlog drains. */\nexport const DEFAULT_FACET_LIMIT = 40;\n\nexport interface BackfillOptions {\n /** Transcripts visited this pass. `Infinity` clears the whole backlog. */\n limit?: number;\n /** The extraction version a facet must reach. Defaults to session-read's `EXTRACT_VERSION`. */\n version?: number;\n}\n\nexport interface BackfillSummary {\n backfilled: number;\n /** Stale transcripts left for later passes. */\n backlog: number;\n /** Sessions whose audit rows were rebuilt, for the caller's rollup. */\n sessionIds: string[];\n}\n\ninterface Candidate {\n row: WatermarkRow;\n transcript: DiscoveredTranscript;\n}\n\n/**\n * Bring the audit facet of already-indexed transcripts up to `version` without a\n * full rebuild: re-read each one up to its watermark and replace only its audit\n * rows. Legacy tables are never written, so their accumulating counts cannot double.\n */\nexport async function backfillFacets(graph: SessionGraph, transcripts: readonly DiscoveredTranscript[], options: BackfillOptions = {}): Promise<BackfillSummary> {\n const version = options.version ?? EXTRACT_VERSION;\n const stale = staleTranscripts(graph, transcripts, version);\n const visit = stale.slice(0, options.limit ?? DEFAULT_FACET_LIMIT);\n const sessionIds = new Set<string>();\n let backfilled = 0;\n for (const candidate of visit) {\n const touched = await backfillOne(graph, candidate, version);\n if (!touched) continue;\n backfilled += 1;\n for (const id of touched) sessionIds.add(id);\n }\n return { backfilled, backlog: stale.length - visit.length, sessionIds: [...sessionIds] };\n}\n\n/** Discovered, status `ok`, and below `version`; newest first so recent cost history lands first. */\nfunction staleTranscripts(graph: SessionGraph, transcripts: readonly DiscoveredTranscript[], version: number): Candidate[] {\n const byPath = new Map(transcripts.map((t) => [t.displayPath, t]));\n const versions = facetVersions(graph.db);\n const stale: Candidate[] = [];\n for (const row of graph.transcripts.list()) {\n const transcript = byPath.get(row.sourceKey);\n if (!transcript || row.status !== \"ok\" || (versions.get(row.sourceId) ?? -1) >= version) continue;\n stale.push({ row, transcript });\n }\n return stale.sort((a, b) => (b.row.fileMtime ?? \"\").localeCompare(a.row.fileMtime ?? \"\"));\n}\n\nfunction facetVersions(db: Db): Map<number, number> {\n const rows = db.prepare(`SELECT transcript_id, version FROM ${FACET_TABLE} WHERE facet = ?`).all(AUDIT_FACET) as { transcript_id: number; version: number }[];\n return new Map(rows.map((r) => [r.transcript_id, r.version]));\n}\n\n/** Returns the sessions touched, or `null` when the file could not be re-read and was marked instead. */\nasync function backfillOne(graph: SessionGraph, { row, transcript }: Candidate, version: number): Promise<string[] | null> {\n let delta: TranscriptDelta & { lastByteOffset: number };\n try {\n delta = await extractTranscript(transcript.absolutePath, { untilByteOffset: row.lastOffset, subagentId: transcript.subagentId });\n } catch (err) {\n // Mark rather than skip, or a broken file would hold a slot at the head of every pass.\n const status = unreadableStatus(err);\n if (!status) throw err;\n graph.transcripts.markStatus(row.sourceKey, status, err instanceof Error ? err.message : String(err));\n return null;\n }\n graph.db.transaction(() => {\n for (const table of AUDIT_TABLES) graph.db.prepare(`DELETE FROM \"${table}\" WHERE transcript_id = ?`).run(row.sourceId);\n applyAudit(graph.db, row.sourceId, delta);\n writeFacet(graph.db, row.sourceId, version, delta.lastByteOffset);\n })();\n return delta.sessions.map((s) => s.sessionId);\n}\n\nfunction unreadableStatus(err: unknown): \"missing\" | \"quarantined\" | null {\n if (err instanceof TranscriptParseError) return \"quarantined\";\n if ((err as NodeJS.ErrnoException | null)?.code === \"ENOENT\") return \"missing\";\n return null;\n}\n\nfunction writeFacet(db: Db, transcriptId: number, version: number, indexedTo: number): void {\n db.prepare(`\n INSERT INTO ${FACET_TABLE} (transcript_id, facet, version, indexed_to) VALUES (?, ?, ?, ?)\n ON CONFLICT (transcript_id, facet) DO UPDATE SET version = excluded.version, indexed_to = excluded.indexed_to`)\n .run(transcriptId, AUDIT_FACET, version, indexedTo);\n}\n\n/**\n * Record a forward read. A read from byte 0 covers the whole file, so it sets the\n * facet outright; a resumed read only extends a facet that is already current,\n * because the bytes before it may predate the audit tables.\n */\nexport function advanceFacet(db: Db, transcriptId: number, fromByteOffset: number, indexedTo: number, version: number = EXTRACT_VERSION): void {\n if (fromByteOffset === 0) {\n writeFacet(db, transcriptId, version, indexedTo);\n return;\n }\n db.prepare(`UPDATE ${FACET_TABLE} SET indexed_to = ? WHERE transcript_id = ? AND facet = ? AND version = ?`)\n .run(indexedTo, transcriptId, AUDIT_FACET, version);\n}\n","import { applyAudit } from \"./audit-apply.js\";\nimport { backfillClaudeAliases } from \"./normalized-schema.js\";\nimport { sessionRef, type TranscriptDelta } from \"@titan-design/session-read\";\nimport type { Db } from \"@titan-design/store-sqlite\";\nimport type { SessionGraph } from \"./graph.js\";\n\n/**\n * Apply one transcript chunk's delta in a single transaction, so a crash can\n * never leave rows committed behind a stale watermark or ahead of their rows.\n * Append-only tables are idempotent through unique indexes; session rows\n * accumulate; usage is left to the rollup, which recomputes it from `request`;\n * ref-keyed assets insert-if-absent with COALESCE merges that mirror\n * `EventFolder`'s rules.\n */\nexport function applyDelta(graph: SessionGraph, transcriptId: number, delta: TranscriptDelta, source: DeltaSource = {}): void {\n graph.db.transaction(() => {\n applyFacts(graph.db, transcriptId, delta);\n applySessions(graph.db, transcriptId, delta, source.account ?? null);\n backfillClaudeAliases(graph.db, delta.sessions.map(s => s.sessionId));\n applyAssets(graph.db, delta);\n applyPhases(graph.db, transcriptId, delta);\n applyLinkedRows(graph, transcriptId, delta);\n applyAudit(graph.db, transcriptId, delta);\n })();\n}\n\n/** What discovery knows about the file that the lines themselves do not carry. */\nexport interface DeltaSource {\n /** The Claude config dir the transcript was found under; `null` when discovery did not say. */\n account?: string | null;\n}\n\nconst INSERT_FACT = `\n INSERT INTO fact (transcript_id, byte_offset, byte_length, event_type, ts, seq, session_id, prompt_id, tool_use_id)\n VALUES (@transcriptId, @byteOffset, @byteLength, @eventType, @ts, @seq, @sessionId, @promptId, @toolUseId)\n ON CONFLICT (transcript_id, byte_offset) DO NOTHING`;\n\n/** Facts carry a per-transcript `seq` continuing from whatever is stored. */\nfunction applyFacts(db: Db, transcriptId: number, delta: TranscriptDelta): void {\n const next = db.prepare(\"SELECT COALESCE(MAX(seq), -1) + 1 AS next FROM fact WHERE transcript_id = ?\").get(transcriptId) as { next: number };\n const insert = db.prepare(INSERT_FACT);\n let seq = next.next;\n for (const f of delta.facts) {\n insert.run({ transcriptId, byteOffset: f.byteOffset, byteLength: f.byteLength, eventType: f.eventType, ts: f.ts, seq: seq++, sessionId: f.sessionId, promptId: f.promptId, toolUseId: f.toolUseId });\n }\n}\n\nconst UPSERT_SESSION = `\n INSERT INTO session (session_id, transcript_id, started_at, ended_at, start_type, cwd, git_branch, ai_title, seed_prompt, cli_version, account, turn_count, commit_count, push_count)\n VALUES (@sessionId, @transcriptId, @startedAt, @endedAt, @startType, @cwd, @gitBranch, @aiTitle, @seedPrompt, @cliVersion, @account, @turnDelta, @commitDelta, @pushDelta)\n ON CONFLICT (session_id) DO UPDATE SET\n started_at = MIN(COALESCE(started_at, excluded.started_at), COALESCE(excluded.started_at, started_at)),\n ended_at = MAX(COALESCE(ended_at, excluded.ended_at), COALESCE(excluded.ended_at, ended_at)),\n start_type = CASE\n WHEN excluded.start_type IS NULL THEN start_type\n WHEN start_type IS NULL THEN excluded.start_type\n WHEN COALESCE(excluded.started_at, started_at) < COALESCE(started_at, excluded.started_at) THEN excluded.start_type\n ELSE start_type END,\n cwd = COALESCE(excluded.cwd, cwd),\n git_branch = COALESCE(git_branch, excluded.git_branch),\n ai_title = COALESCE(excluded.ai_title, ai_title),\n seed_prompt = COALESCE(seed_prompt, excluded.seed_prompt),\n cli_version = COALESCE(excluded.cli_version, cli_version),\n account = COALESCE(excluded.account, account),\n turn_count = turn_count + excluded.turn_count,\n commit_count = commit_count + excluded.commit_count,\n push_count = push_count + excluded.push_count`;\n\nfunction applySessions(db: Db, transcriptId: number, delta: TranscriptDelta, account: string | null): void {\n const upsertSession = db.prepare(UPSERT_SESSION);\n for (const s of delta.sessions) upsertSession.run({ ...s, transcriptId, account });\n}\n\nconst ASSET_UPSERTS = {\n prs: `INSERT INTO pr (pr_ref, number, repo, title, url) VALUES (@prRef, @number, @repo, @title, @url)\n ON CONFLICT (pr_ref) DO UPDATE SET title = COALESCE(title, excluded.title), url = COALESCE(url, excluded.url)`,\n branches: `INSERT INTO branch (branch_ref, repo, name, base, created_at, deleted_at) VALUES (@branchRef, @repo, @name, @base, @createdAt, @deletedAt)\n ON CONFLICT (branch_ref) DO UPDATE SET base = COALESCE(base, excluded.base),\n created_at = MIN(COALESCE(created_at, excluded.created_at), COALESCE(excluded.created_at, created_at)),\n deleted_at = MAX(COALESCE(deleted_at, excluded.deleted_at), COALESCE(excluded.deleted_at, deleted_at))`,\n files: `INSERT INTO file (file_ref, repo, path) VALUES (@fileRef, @repo, @path) ON CONFLICT (file_ref) DO NOTHING`,\n tasks: `INSERT INTO task (task_ref, task_id, status) VALUES (@taskRef, @taskId, @status)\n ON CONFLICT (task_ref) DO UPDATE SET status = COALESCE(excluded.status, status)`,\n artifacts: `INSERT INTO artifact (artifact_ref, kind, title, url, path, created_at) VALUES (@artifactRef, @artifactKind, @title, @url, @path, @ts)\n ON CONFLICT (artifact_ref) DO NOTHING`,\n prMerges: `INSERT INTO pr_merge_observation (number, repo_hint, merged_at) VALUES (@number, @repoHint, @ts)\n ON CONFLICT (number, repo_hint, merged_at) DO NOTHING`,\n prCreates: `INSERT INTO pr_create_observation (tool_use_id, title, number, repo, url) VALUES (@toolUseId, @title, @number, @repo, @url)\n ON CONFLICT (tool_use_id) DO UPDATE SET title = COALESCE(title, excluded.title), number = COALESCE(number, excluded.number),\n repo = COALESCE(repo, excluded.repo), url = COALESCE(url, excluded.url)`,\n} as const;\n\nfunction applyAssets(db: Db, delta: TranscriptDelta): void {\n for (const [kind, sql] of Object.entries(ASSET_UPSERTS) as [keyof typeof ASSET_UPSERTS, string][]) {\n const statement = db.prepare(sql);\n for (const row of delta[kind] as unknown as Record<string, unknown>[]) statement.run(pick(row, sql));\n }\n}\n\n/** better-sqlite3 rejects unused named parameters, so pass only the ones the statement binds. */\nfunction pick(row: Record<string, unknown>, sql: string): Record<string, unknown> {\n const names = new Set([...sql.matchAll(/@(\\w+)/g)].map((m) => m[1]!));\n return Object.fromEntries([...names].map((name) => [name, row[name] ?? null]));\n}\n\n/**\n * Bi-temporal phase collapse: a candidate matching the session's open phase is a\n * no-op; otherwise the open phase closes at the new `t_valid` and a replacement\n * row is inserted. Done here so a chunk boundary mid-run cannot add a phase.\n */\nfunction applyPhases(db: Db, transcriptId: number, delta: TranscriptDelta): void {\n const current = db.prepare(\"SELECT phase_id, to_mode FROM permission_phase WHERE session_id = ? AND trigger = ? AND t_invalid IS NULL ORDER BY phase_id DESC LIMIT 1\");\n const close = db.prepare(\"UPDATE permission_phase SET t_invalid = ? WHERE phase_id = ?\");\n const insert = db.prepare(\"INSERT INTO permission_phase (session_id, from_mode, to_mode, trigger, t_valid, fact_id) VALUES (?, ?, ?, ?, ?, ?)\");\n for (const phase of delta.phases) {\n const open = current.get(phase.sessionId, phase.trigger) as { phase_id: number; to_mode: string } | undefined;\n if (open?.to_mode === phase.toMode) continue;\n if (open) close.run(phase.ts, open.phase_id);\n insert.run(phase.sessionId, open?.to_mode ?? null, phase.toMode, phase.trigger, phase.ts, factIdFor(db, transcriptId, phase.byteOffset));\n }\n}\n\nfunction applyLinkedRows(graph: SessionGraph, transcriptId: number, delta: TranscriptDelta): void {\n const { db } = graph;\n const factId = (byteOffset: number) => factIdFor(db, transcriptId, byteOffset);\n\n const upsertTurn = db.prepare(`\n INSERT INTO turn (prompt_id, session_id, turn_index, started_at, fact_id_start)\n VALUES (?, ?, (SELECT COALESCE(MAX(turn_index), -1) + 1 FROM turn WHERE session_id = ?), ?, ?)\n ON CONFLICT (prompt_id) DO UPDATE SET session_id = MIN(session_id, excluded.session_id)`);\n for (const t of delta.turns) upsertTurn.run(t.promptId, t.sessionId, t.sessionId, t.ts, factId(t.byteOffset));\n\n const insertEdit = db.prepare(\"INSERT INTO human_edit (session_id, file_path, ts, fact_id) VALUES (?, ?, ?, ?) ON CONFLICT (session_id, file_path, ts) DO NOTHING\");\n for (const e of delta.humanEdits) insertEdit.run(e.sessionId, e.filePath, e.ts, factId(e.byteOffset));\n\n const insertCheckpoint = db.prepare(`\n INSERT INTO file_checkpoint (session_id, file_path, backup_file_name, version, backup_time, fact_id) VALUES (?, ?, ?, ?, ?, ?)\n ON CONFLICT (session_id, file_path, backup_file_name) DO NOTHING`);\n for (const c of delta.fileCheckpoints) insertCheckpoint.run(c.sessionId, c.filePath, c.backupFileName, c.version, c.backupTime, factId(c.byteOffset));\n\n const upsertSubagent = db.prepare(`\n INSERT INTO subagent (agent_ref, session_id, agent_type, label, started_at, fact_id) VALUES (?, ?, ?, ?, ?, ?)\n ON CONFLICT (agent_ref) DO UPDATE SET session_id = COALESCE(session_id, excluded.session_id),\n agent_type = COALESCE(agent_type, excluded.agent_type), label = COALESCE(label, excluded.label), started_at = COALESCE(started_at, excluded.started_at)`);\n for (const s of delta.subagents) upsertSubagent.run(s.agentRef, s.sessionId, s.agentType, s.label, s.ts || null, factId(s.byteOffset));\n\n // The dispatch row and this bridge come from different lines; an upsert survives a chunk boundary between them.\n const linkTranscript = db.prepare(\"INSERT INTO subagent (agent_ref, child_session_id) VALUES (?, ?) ON CONFLICT (agent_ref) DO UPDATE SET child_session_id = excluded.child_session_id\");\n for (const l of delta.subagentTranscripts) linkTranscript.run(l.agentRef, l.childSessionId);\n\n for (const e of delta.edges) graph.edges.assert({ sourceRef: e.sourceRef, relation: e.relation, targetRef: e.targetRef, tValid: e.ts, factId: factId(e.byteOffset) });\n\n for (const span of delta.spans) {\n graph.spans.index({ ownerRef: sessionRef(span.sessionId), field: span.field, sourceId: transcriptId, byteOffset: span.byteOffset, byteLength: span.byteLength }, span.text);\n }\n}\n\nfunction factIdFor(db: Db, transcriptId: number, byteOffset: number): number | null {\n const row = db.prepare(\"SELECT fact_id FROM fact WHERE transcript_id = ? AND byte_offset = ?\").get(transcriptId, byteOffset) as { fact_id: number } | undefined;\n return row?.fact_id ?? null;\n}\n","import { sessionRef } from \"@titan-design/session-read\";\nimport type { SessionGraph } from \"./graph.js\";\nimport { AUDIT_TABLES, FACET_TABLE } from \"./audit-schema.js\";\nimport { EPISODE_TABLE } from \"./audit-schema-v5.js\";\nimport { KIT } from \"./schema.js\";\n\n/** Derived tables keyed by `session_id`, reachable from a transcript through `session`. */\nconst SESSION_SCOPED = [\"turn\", \"permission_phase\", \"human_edit\", \"file_checkpoint\", \"subagent\", \"session_model_usage\", EPISODE_TABLE] as const;\n\n/**\n * Drop every derived row one transcript produced, so re-reading it from byte 0\n * rebuilds those rows instead of doubling them.\n *\n * `resetIndex` already states the reason at corpus scale: rewinding alone is not\n * enough, because the accumulating upserts add a second copy of every count. A\n * rewritten single transcript has the same problem one file at a time.\n * `session.turn_count`, the `session_model_usage` token buckets and the\n * commit/push counts all sum into what is already there, and rows the rewrite\n * removed are never deleted — `fact` survives on its unique\n * `(transcript_id, byte_offset)` index, so stale facts simply persist.\n *\n * Shared identity rows survive on purpose. `pr`, `branch`, `file`, `task` and\n * `artifact` are keyed by ref, many transcripts assert the same one, and the\n * inserts are insert-if-absent; a single transcript cannot know whether it was\n * the only source. The two observation tables are left for the same reason —\n * `reconcile` folds them, and re-reading re-asserts the same rows.\n *\n * Audit rows and facet state carry `transcript_id` themselves, so they go by it\n * directly rather than through `session`.\n */\nexport function purgeTranscript(graph: SessionGraph, transcriptId: number): void {\n graph.db.transaction(() => {\n const owned = graph.db.prepare(\"SELECT session_id FROM session WHERE transcript_id = ?\").all(transcriptId) as { session_id: string }[];\n for (const { session_id } of owned) graph.spans.purgeOwner(sessionRef(session_id));\n\n // Children first: each subquery reads the `session` rows deleted last.\n for (const table of SESSION_SCOPED) {\n graph.db.prepare(`DELETE FROM \"${table}\" WHERE session_id IN (SELECT session_id FROM session WHERE transcript_id = ?)`).run(transcriptId);\n }\n graph.db.prepare(`DELETE FROM \"${KIT.edge}\" WHERE fact_id IN (SELECT fact_id FROM fact WHERE transcript_id = ?)`).run(transcriptId);\n for (const table of [...AUDIT_TABLES, FACET_TABLE]) {\n graph.db.prepare(`DELETE FROM \"${table}\" WHERE transcript_id = ?`).run(transcriptId);\n }\n graph.db.prepare(\"DELETE FROM fact WHERE transcript_id = ?\").run(transcriptId);\n graph.db.prepare(\"DELETE FROM session WHERE transcript_id = ?\").run(transcriptId);\n })();\n}\n","import type { Db } from \"@titan-design/store-sqlite\";\n\nconst IN_BATCH = \"SELECT value FROM json_each(@sessionIds)\";\n\n/** Order, gap and context growth by request position; `seq_in_session` is 0-based like `turn.turn_index`. */\nconst REQUEST_ORDER = `\n WITH ordered AS (\n SELECT transcript_id, request_id, ts, context_tokens,\n ROW_NUMBER() OVER w - 1 AS seq,\n LAG(ts) OVER w AS prev_ts,\n LAG(context_tokens) OVER w AS prev_context,\n LAG(output_tokens) OVER w AS prev_output\n FROM request WHERE session_id IN (${IN_BATCH})\n WINDOW w AS (PARTITION BY session_id ORDER BY ts, byte_offset, transcript_id, request_id)\n )\n UPDATE request SET seq_in_session = ordered.seq,\n gap_ms = CAST(ROUND((julianday(ordered.ts) - julianday(ordered.prev_ts)) * 86400000) AS INTEGER),\n ctx_delta = ordered.context_tokens - (ordered.prev_context + ordered.prev_output)\n FROM ordered WHERE request.transcript_id = ordered.transcript_id AND request.request_id = ordered.request_id`;\n\n/**\n * A request is woken by the last arrival before it in its own transcript and\n * session. A tool result names its tool through `tool_call`, and an\n * `AskUserQuestion` result is the human answering, not a tool reporting.\n */\nconst REQUEST_WAKE = `\n WITH hit AS (\n SELECT r.transcript_id, r.request_id,\n (SELECT MAX(i.byte_offset) FROM inbound i\n WHERE i.transcript_id = r.transcript_id AND i.session_id = r.session_id AND i.byte_offset < r.byte_offset) AS wake_offset\n FROM request r WHERE r.session_id IN (${IN_BATCH})\n ),\n tools AS (\n SELECT transcript_id, tool_use_id, name, family, mcp_server,\n ROW_NUMBER() OVER (PARTITION BY transcript_id, tool_use_id ORDER BY byte_offset, block_index) AS pick\n FROM tool_call WHERE session_id IN (${IN_BATCH})\n ),\n wake AS (\n SELECT hit.transcript_id, hit.request_id, hit.wake_offset, i.cause, i.delivery, i.detail, i.from_name,\n t.name AS tool_name, t.family, t.mcp_server\n FROM hit\n LEFT JOIN inbound i ON i.transcript_id = hit.transcript_id AND i.byte_offset = hit.wake_offset\n AND i.block_index = (SELECT MAX(block_index) FROM inbound j WHERE j.transcript_id = hit.transcript_id AND j.byte_offset = hit.wake_offset)\n LEFT JOIN tools t ON t.transcript_id = i.transcript_id AND t.tool_use_id = i.tool_use_id AND t.pick = 1\n )\n UPDATE request SET\n wake_cause = CASE WHEN wake.cause IS NULL THEN 'session_start'\n WHEN wake.tool_name = 'AskUserQuestion' THEN 'ask_user_answer' ELSE wake.cause END,\n wake_delivery = wake.delivery,\n wake_detail = COALESCE(wake.tool_name, wake.from_name, wake.detail),\n wake_tool_family = wake.family,\n wake_mcp_server = wake.mcp_server,\n wake_offset = wake.wake_offset\n FROM wake WHERE request.transcript_id = wake.transcript_id AND request.request_id = wake.request_id`;\n\n/** How long a message waited: its delivery paired with the latest earlier enqueue of the same content. */\nconst INBOUND_QUEUED = `\n UPDATE inbound SET queued_ms = (\n SELECT CAST(ROUND((julianday(inbound.ts) - julianday(q.ts)) * 86400000) AS INTEGER)\n FROM queue_op q\n WHERE q.transcript_id = inbound.transcript_id AND q.session_id = inbound.session_id\n AND q.operation = 'enqueue' AND q.content_hash = inbound.content_hash AND q.byte_offset < inbound.byte_offset\n ORDER BY q.byte_offset DESC LIMIT 1)\n WHERE session_id IN (${IN_BATCH})`;\n\n/** A compaction whose last arrival was a tool result fired inside a tool loop, not between turns. */\nconst COMPACTION_MID_LOOP = `\n UPDATE compaction SET mid_loop = COALESCE((\n SELECT i.delivery = 'tool_result' FROM inbound i\n WHERE i.transcript_id = compaction.transcript_id AND i.session_id = compaction.session_id AND i.byte_offset < compaction.byte_offset\n ORDER BY i.byte_offset DESC, i.block_index DESC LIMIT 1), 0)\n WHERE session_id IN (${IN_BATCH})`;\n\nconst TURN_WAKE = `\n UPDATE turn SET wake_cause = (\n SELECT i.cause FROM fact f JOIN inbound i ON i.transcript_id = f.transcript_id AND i.byte_offset = f.byte_offset\n WHERE f.fact_id = turn.fact_id_start ORDER BY i.block_index LIMIT 1)\n WHERE session_id IN (${IN_BATCH})`;\n\n/**\n * Usage is a sum over deduplicated requests, never an accumulation of lines.\n * A request copied into a second transcript counts once. Sessions with no\n * request rows keep what they have: their transcripts predate the table or are gone.\n */\nconst CLEAR_USAGE = `\n DELETE FROM session_model_usage\n WHERE session_id IN (${IN_BATCH}) AND session_id IN (SELECT session_id FROM request WHERE session_id IN (${IN_BATCH}))`;\n\nconst RECOMPUTE_USAGE = `\n WITH ranked AS (\n SELECT *, ROW_NUMBER() OVER (PARTITION BY session_id, request_id ORDER BY ts, transcript_id) AS pick\n FROM request WHERE session_id IN (${IN_BATCH})\n )\n INSERT INTO session_model_usage (session_id, model, input_tokens, output_tokens, cache_read_tokens, cache_creation_tokens, thinking_tokens, request_count)\n SELECT session_id, model, SUM(input_tokens), SUM(output_tokens), SUM(cache_read_tokens), SUM(cache_creation_tokens), SUM(thinking_tokens), COUNT(*)\n FROM ranked WHERE pick = 1 GROUP BY session_id, model`;\n\nconst STEPS = [REQUEST_ORDER, REQUEST_WAKE, INBOUND_QUEUED, COMPACTION_MID_LOOP, TURN_WAKE, CLEAR_USAGE, RECOMPUTE_USAGE] as const;\n\nexport type AuditRollup = (sessionIdsJson: string) => void;\n\n/** Prepare the audit recomputes once; the caller runs them per batch inside its own transaction. */\nexport function prepareAuditRollup(db: Db): AuditRollup {\n const statements = STEPS.map((sql) => db.prepare(sql));\n return (sessionIds) => {\n for (const statement of statements) statement.run({ sessionIds });\n };\n}\n","import { prepareAuditRollup } from \"./audit-rollup.js\";\nimport type { SessionGraph } from \"./graph.js\";\n\nconst BATCH = 400;\n\n/**\n * Turn aggregates that no single line can supply. Contract: recompute, never\n * accumulate. Every value is a pure function of the fact rows, so incremental\n * refreshes and full rebuilds converge regardless of chunk boundaries.\n */\nconst ROLLUP = `\n WITH ordered AS (\n SELECT fact_id, session_id, event_type, ts, prompt_id,\n COUNT(CASE WHEN event_type = 'user_prompt' THEN 1 END) OVER (\n PARTITION BY session_id ORDER BY ts, transcript_id, seq ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS turn_no,\n LAG(event_type) OVER (PARTITION BY session_id ORDER BY ts, transcript_id, seq) AS prev_type,\n LAG(ts) OVER (PARTITION BY session_id ORDER BY ts, transcript_id, seq) AS prev_ts\n FROM fact WHERE session_id IN (SELECT value FROM json_each(@sessionIds))\n ),\n owners AS (SELECT session_id, turn_no, prompt_id FROM ordered WHERE event_type = 'user_prompt'),\n agg AS (\n SELECT owners.prompt_id AS prompt_id, MAX(ordered.ts) AS ended_at,\n CAST(ROUND((julianday(MAX(ordered.ts)) - julianday(MIN(ordered.ts))) * 86400000) AS INTEGER) AS duration_ms,\n SUM(CASE WHEN ordered.event_type = 'tool_decision' THEN 1 ELSE 0 END) AS tool_call_count,\n CAST(COALESCE(SUM(CASE\n WHEN ordered.event_type IN ('assistant_response', 'tool_decision') AND ordered.prev_type IN ('user_prompt', 'tool_result', 'tool_result_error')\n THEN ROUND((julianday(ordered.ts) - julianday(ordered.prev_ts)) * 86400000) END), 0) AS INTEGER) AS thinking_ms\n FROM ordered JOIN owners ON owners.session_id = ordered.session_id AND owners.turn_no = ordered.turn_no\n GROUP BY owners.prompt_id\n )\n UPDATE turn SET ended_at = agg.ended_at, duration_ms = COALESCE(agg.duration_ms, 0),\n tool_call_count = agg.tool_call_count, thinking_ms = COALESCE(agg.thinking_ms, 0)\n FROM agg WHERE turn.prompt_id = agg.prompt_id`;\n\n/** `turn_index` is insert-order at write time; recomputing it from `started_at` makes it a property of the corpus. */\nconst RENUMBER_TURNS = `\n WITH ordered AS (\n SELECT prompt_id, ROW_NUMBER() OVER (PARTITION BY session_id ORDER BY started_at, prompt_id) - 1 AS idx\n FROM turn WHERE session_id IN (SELECT value FROM json_each(@sessionIds))\n )\n UPDATE turn SET turn_index = ordered.idx FROM ordered WHERE turn.prompt_id = ordered.prompt_id`;\n\n/** Recompute turn aggregates and the audit rollup for the given sessions in one transaction. */\nexport function rollupSessions(graph: SessionGraph, sessionIds: readonly string[]): number {\n const unique = [...new Set(sessionIds)];\n if (unique.length === 0) return 0;\n const aggregate = graph.db.prepare(ROLLUP);\n const renumber = graph.db.prepare(RENUMBER_TURNS);\n const audit = prepareAuditRollup(graph.db);\n return graph.db.transaction(() => {\n let updated = 0;\n for (let i = 0; i < unique.length; i += BATCH) {\n const batch = JSON.stringify(unique.slice(i, i + BATCH));\n renumber.run({ sessionIds: batch });\n updated += aggregate.run({ sessionIds: batch }).changes;\n audit(batch);\n }\n return updated;\n })();\n}\n\n/**\n * A merge sighting and the `pr-link` naming the same PR routinely live in different transcripts; fold at pass end.\n * Once the forge has checked a PR (`outcome_checked_at` set), its `merged_at` is forge-accurate and must not be\n * overwritten by a transcript sighting time on a later pass.\n */\nconst RECONCILE_PR_MERGES = `\n UPDATE pr SET state = 'merged',\n merged_at = (SELECT MIN(o.merged_at) FROM pr_merge_observation o WHERE o.number = pr.number AND (o.repo_hint IS NULL OR pr.repo LIKE '%/' || o.repo_hint))\n WHERE pr.outcome_checked_at IS NULL\n AND EXISTS (SELECT 1 FROM pr_merge_observation o WHERE o.number = pr.number AND (o.repo_hint IS NULL OR pr.repo LIKE '%/' || o.repo_hint))`;\n\n/** Both halves of a `gh pr create` make a real PR whether or not a `pr-link` ever mentioned it. */\nconst RECONCILE_PR_CREATES = `\n INSERT INTO pr (pr_ref, number, repo, title, url)\n SELECT 'pr:' || repo || '#' || number, number, repo, title, url FROM pr_create_observation\n WHERE number IS NOT NULL AND repo IS NOT NULL AND title IS NOT NULL\n ON CONFLICT (pr_ref) DO UPDATE SET title = COALESCE(pr.title, excluded.title), url = COALESCE(pr.url, excluded.url)`;\n\n/**\n * A subagent ends when its child session's last line does, not when the\n * dispatch's tool_result returns (most dispatches are async and return at\n * launch). Parentage comes from the dispatch that ran inside a child transcript.\n */\nconst RECONCILE_SUBAGENTS = `\n UPDATE subagent SET\n ended_at = COALESCE((SELECT s.ended_at FROM session s WHERE s.session_id = subagent.child_session_id), ended_at),\n parent_agent_ref = COALESCE((SELECT p.agent_ref FROM subagent p WHERE p.child_session_id = subagent.session_id), parent_agent_ref)`;\n\nexport interface ReconcileCounts {\n prMerges: number;\n prCreates: number;\n subagents: number;\n}\n\n/** Whole-table reconciliations, run once at the end of a refresh pass after the rollup. */\nexport function reconcile(graph: SessionGraph): ReconcileCounts {\n return {\n prCreates: graph.db.prepare(RECONCILE_PR_CREATES).run().changes,\n prMerges: graph.db.prepare(RECONCILE_PR_MERGES).run().changes,\n subagents: graph.db.prepare(RECONCILE_SUBAGENTS).run().changes,\n };\n}\n","import { promises as fs } from \"node:fs\";\nimport { contentHash, resumePoint } from \"@titan-design/locator\";\nimport { TranscriptParseError, extractTranscript, type DiscoveredTranscript } from \"@titan-design/session-read\";\nimport { applyDelta } from \"./apply.js\";\nimport { advanceFacet, backfillFacets } from \"./facet.js\";\nimport { allSessionIds, type SessionGraph } from \"./graph.js\";\nimport { enrichPrs, type PrEnrichment, type PrResolver } from \"./outcomes.js\";\nimport { resolveOrigins, type OriginEnrichment, type OriginResolver } from \"./origin.js\";\nimport { purgeTranscript } from \"./purge.js\";\nimport { reconcile, rollupSessions, type ReconcileCounts } from \"./rollup.js\";\nimport { allTaskIds, enrichTasks, NO_ENRICHMENT, type TaskEnrichment, type TaskResolver } from \"./tasks.js\";\n\nexport interface IndexOptions {\n /** Re-hash the already-read prefix to catch same-length rewrites. O(file), so opt in. */\n verifyHash?: boolean;\n /** Store a whole-file content hash for durability reporting. O(file), so opt in. */\n withContentHash?: boolean;\n /** Fill task title, initiative and present status from the caller's store. Absent means transcripts alone. */\n resolveTasks?: TaskResolver;\n /** Record who launched each session. Runs once per `refreshCorpus` pass, never per transcript. Absent means no origin rows. */\n resolveOrigins?: OriginResolver;\n /** Fill PR state, merge, close and review rounds from the caller's forge. Runs once per `refreshCorpus` pass. Absent means transcripts alone. */\n resolvePrs?: PrResolver;\n}\n\nexport interface RefreshOptions extends IndexOptions {\n /** Roll up every session, not just the ones this pass touched. */\n full?: boolean;\n /** Stale audit facets re-extracted per pass (default 40). `Infinity` clears the backlog. */\n facetLimit?: number;\n}\n\nexport type TranscriptOutcome =\n | { status: \"unchanged\" | \"indexed\" | \"rewound\"; transcriptId: number; sessionIds: string[]; facts: number; tasks: TaskEnrichment }\n | { status: \"missing\" | \"quarantined\"; transcriptId: number; sessionIds: string[]; facts: 0; tasks: TaskEnrichment; reason: string };\n\n/**\n * Bring one transcript up to date: read from its watermark (or byte 0 after a\n * rewrite), apply the delta, advance the watermark. A malformed line\n * quarantines the transcript instead of poisoning the pass.\n */\nexport async function indexTranscript(graph: SessionGraph, transcript: DiscoveredTranscript, options: IndexOptions = {}): Promise<TranscriptOutcome> {\n const row = graph.transcripts.ensure(transcript.displayPath);\n const entry = { path: transcript.displayPath, lastByteOffset: row.lastOffset, prefixHash: row.prefixHash, mtime: row.fileMtime };\n const point = await resumePoint(entry, transcript.absolutePath, { verifyHash: options.verifyHash });\n const base = { transcriptId: row.sourceId, sessionIds: [] as string[], tasks: NO_ENRICHMENT };\n if (point.state === \"missing\") {\n graph.transcripts.markStatus(transcript.displayPath, \"missing\", \"source file no longer exists\");\n return { ...base, status: \"missing\", facts: 0, reason: \"source file no longer exists\" };\n }\n if (point.state === \"unchanged\") {\n // A file that vanished and came back unchanged resumes at EOF, so there are no\n // bytes to read and `advance()` — the only writer of status 'ok' — never runs,\n // stranding the row on 'missing' forever. Clear it here rather than forcing a\n // re-read, which would rewrite the prefix hash from a zero-byte delta.\n // Quarantine is deliberately not cleared: the same bytes still will not parse.\n if (row.status === \"missing\") graph.transcripts.markStatus(transcript.displayPath, \"ok\", null);\n return { ...base, status: \"unchanged\", facts: 0 };\n }\n\n try {\n const delta = await extractTranscript(transcript.absolutePath, {\n fromByteOffset: point.start,\n priorPrefixHash: point.state === \"rewritten\" ? null : row.prefixHash,\n subagentId: transcript.subagentId,\n });\n // Two ways to learn a transcript was rewritten, and both must purge. `resumePoint`\n // catches a file that shrank; `extractTranscript` re-hashes the prefix it was asked\n // to skip and restarts from zero on its own when the bytes moved — a rotation that\n // left the file the same length or longer. Ignoring its answer replays the whole\n // file onto rows that were never removed, which is the accumulation purge exists\n // to prevent, reached by a different road.\n const rewound = point.state === \"rewritten\" || delta.restartedFromZero;\n // After extraction, never before: a parse failure quarantines the transcript,\n // and purging first would destroy rows we could then no longer rebuild.\n if (rewound) purgeTranscript(graph, row.sourceId);\n applyDelta(graph, row.sourceId, delta, { account: transcript.account });\n advanceFacet(graph.db, row.sourceId, rewound ? 0 : point.start, delta.lastByteOffset);\n const stat = await fs.stat(transcript.absolutePath);\n graph.transcripts.advance(transcript.displayPath, {\n lastOffset: delta.lastByteOffset,\n prefixHash: delta.prefixHash,\n fileSize: stat.size,\n fileMtime: stat.mtime.toISOString(),\n contentHash: options.withContentHash ? await contentHash(transcript.absolutePath) : null,\n });\n const sessionIds = delta.sessions.map((s) => s.sessionId);\n const taskIds = delta.tasks.map((t) => t.taskId);\n const tasks = taskIds.length > 0 ? await enrichTasks(graph, options.resolveTasks, taskIds) : NO_ENRICHMENT;\n return { ...base, sessionIds, tasks, status: rewound ? \"rewound\" : \"indexed\", facts: delta.facts.length };\n } catch (err) {\n if (!(err instanceof TranscriptParseError)) throw err;\n graph.transcripts.markStatus(transcript.displayPath, \"quarantined\", err.message);\n return { ...base, status: \"quarantined\", facts: 0, reason: err.message };\n }\n}\n\nexport interface RefreshSummary {\n transcripts: number;\n indexed: number;\n unchanged: number;\n rewound: number;\n missing: number;\n quarantined: number;\n facts: number;\n turnsRolledUp: number;\n reconciled: ReconcileCounts;\n tasks: TaskEnrichment;\n origins: OriginEnrichment;\n prs: PrEnrichment;\n markedMissing: number;\n facetsBackfilled: number;\n /** Transcripts whose audit facet is still stale after this pass. */\n facetBacklog: number;\n}\n\n/**\n * One pass over a corpus: index every transcript, re-extract a bounded batch of\n * stale audit facets, roll up the sessions that changed, resolve session\n * origins, reconcile cross-transcript observations, resolve PR outcomes,\n * enrich tasks, and mark rows whose source file is gone. Idempotent: a second pass over unchanged\n * files changes nothing.\n *\n * The resolver is hoisted out of the per-transcript loop and run once over the\n * whole task table, so a corpus of N transcripts costs one resolver call rather\n * than N, and a task whose store row changed refreshes even when no transcript\n * did. That bounds staleness to one pass.\n */\nexport async function refreshCorpus(graph: SessionGraph, transcripts: readonly DiscoveredTranscript[], options: RefreshOptions = {}): Promise<RefreshSummary> {\n const { resolveTasks, resolveOrigins: originResolver, resolvePrs, full, facetLimit, ...perTranscript } = options;\n const counts = { indexed: 0, unchanged: 0, rewound: 0, missing: 0, quarantined: 0 };\n const touched: string[] = [];\n let facts = 0;\n for (const transcript of transcripts) {\n const outcome = await indexTranscript(graph, transcript, perTranscript);\n counts[outcome.status] += 1;\n facts += outcome.facts;\n touched.push(...outcome.sessionIds);\n }\n const facets = await backfillFacets(graph, transcripts, { limit: facetLimit });\n touched.push(...facets.sessionIds);\n const turnsRolledUp = rollupSessions(graph, full ? allSessionIds(graph) : touched);\n // Before reconcile, so a worker's subagent row gets its ended_at in the same pass.\n const origins = await resolveOrigins(graph, originResolver);\n const reconciled = reconcile(graph);\n // After reconcile, so a merge a transcript witnessed is already sticky when the forge answers.\n const prs = await enrichPrs(graph, resolvePrs);\n const tasks = await enrichTasks(graph, resolveTasks, allTaskIds(graph));\n const markedMissing = await markMissing(graph, transcripts);\n const facetSummary = { facetsBackfilled: facets.backfilled, facetBacklog: facets.backlog };\n return { transcripts: transcripts.length, ...counts, facts, turnsRolledUp, reconciled, tasks, origins, prs, markedMissing, ...facetSummary };\n}\n\n/** Rows absent from discovery are only nominated; an `fs.stat` decides, so an empty scan cannot condemn the corpus. */\nasync function markMissing(graph: SessionGraph, discovered: readonly DiscoveredTranscript[]): Promise<number> {\n const present = new Set(discovered.map((t) => t.displayPath));\n const byPath = new Map(discovered.map((t) => [t.displayPath, t.absolutePath]));\n let marked = 0;\n for (const row of graph.transcripts.list()) {\n if (row.status === \"missing\" || present.has(row.sourceKey)) continue;\n const normalized = graph.db.prepare(\"SELECT descriptor FROM normalized_source WHERE transcript_id = ?\").get(row.sourceId) as { descriptor: string } | undefined;\n const absolute = normalized ? (JSON.parse(normalized.descriptor) as { path: string }).path : byPath.get(row.sourceKey) ?? row.sourceKey;\n if (await exists(absolute)) continue;\n graph.transcripts.markStatus(row.sourceKey, \"missing\", \"source file no longer exists\");\n marked += 1;\n }\n return marked;\n}\n\nasync function exists(absolutePath: string): Promise<boolean> {\n try {\n await fs.stat(absolutePath);\n return true;\n } catch {\n return false;\n }\n}\n","import type { SessionGraph } from \"./graph.js\";\n\n/** A PR the graph holds, as the resolver needs it to ask a forge. */\nexport interface PrKey {\n prRef: string;\n repo: string;\n number: number;\n}\n\n/**\n * What a forge knows and a transcript cannot state: a merge done by another\n * session or in the browser, a close, and the review history. Every field is\n * optional; an omitted or null field leaves whatever the transcripts derived.\n */\nexport interface ResolvedPr {\n /** `open`, `closed` or `merged`, in any case. */\n state?: string | null;\n mergedAt?: string | null;\n closedAt?: string | null;\n /** Stored as the resolver counts it; the round definition is open question Q6 in the TP-256 design. */\n reviewRounds?: number | null;\n}\n\n/** Resolutions keyed by `pr_ref` (`pr:acme/demo#7`). */\nexport type PrResolution = ReadonlyMap<string, ResolvedPr | null | undefined>;\n\n/**\n * Supplied by the caller, never by this package: session-graph is tier 2 and\n * must not learn which forge a product talks to. Called once per pass with every\n * PR whose outcome may still change.\n */\nexport type PrResolver = (prs: readonly PrKey[]) => PromiseLike<PrResolution> | PrResolution;\n\nexport interface PrEnrichment {\n /** PRs handed to the resolver. */\n requested: number;\n /** PR rows the resolver updated. */\n applied: number;\n /** The resolver threw; rows stand as the transcripts left them. */\n failed: boolean;\n /** Why it failed, for the caller to log. Absent unless `failed`. */\n error?: string;\n}\n\nexport const NO_PR_OUTCOMES: PrEnrichment = Object.freeze({ requested: 0, applied: 0, failed: false });\n\n/** A merge is final, so a merged PR is asked about once; open and closed PRs can still move. */\nconst PRS_NEEDING_OUTCOME = `\n SELECT pr_ref, repo, number FROM pr\n WHERE repo IS NOT NULL AND number IS NOT NULL AND (outcome_checked_at IS NULL OR state IS NOT 'merged')\n ORDER BY pr_ref`;\n\n/** A stale forge cache must not reopen a PR a transcript saw merged, so `merged` is sticky. */\nconst APPLY_OUTCOME = `\n UPDATE pr SET\n state = CASE WHEN state = 'merged' THEN state ELSE COALESCE(lower(@state), state) END,\n merged_at = COALESCE(@mergedAt, merged_at),\n closed_at = COALESCE(@closedAt, closed_at),\n review_rounds = COALESCE(@reviewRounds, review_rounds),\n outcome_checked_at = @checkedAt\n WHERE pr_ref = @prRef`;\n\nexport function prsNeedingOutcome(graph: SessionGraph): PrKey[] {\n const rows = graph.db.prepare(PRS_NEEDING_OUTCOME).all() as { pr_ref: string; repo: string; number: number }[];\n return rows.map((r) => ({ prRef: r.pr_ref, repo: r.repo, number: r.number }));\n}\n\n/**\n * Fill PR outcomes from a caller-supplied resolver. Runs after `reconcile`, so\n * it sees the merges the transcripts witnessed and only adds what they missed.\n * Updates rows and never inserts one: a PR enters the graph from a transcript.\n * A resolver that throws costs this pass its outcomes and nothing else.\n */\nexport async function enrichPrs(graph: SessionGraph, resolver: PrResolver | undefined): Promise<PrEnrichment> {\n if (!resolver) return NO_PR_OUTCOMES;\n const prs = prsNeedingOutcome(graph);\n if (prs.length === 0) return NO_PR_OUTCOMES;\n try {\n const resolved = await resolver(prs);\n return { requested: prs.length, applied: write(graph, resolved, new Date().toISOString()), failed: false };\n } catch (err) {\n return { requested: prs.length, applied: 0, failed: true, error: err instanceof Error ? err.message : String(err) };\n }\n}\n\nfunction write(graph: SessionGraph, resolved: PrResolution, checkedAt: string): number {\n const apply = graph.db.prepare(APPLY_OUTCOME);\n return graph.db.transaction(() => {\n let applied = 0;\n for (const [prRef, fields] of resolved) {\n if (!fields) continue;\n applied += apply.run({\n prRef,\n checkedAt,\n state: fields.state ?? null,\n mergedAt: fields.mergedAt ?? null,\n closedAt: fields.closedAt ?? null,\n reviewRounds: fields.reviewRounds ?? null,\n }).changes;\n }\n return applied;\n })();\n}\n","import { RELATIONS, sessionRef } from \"@titan-design/session-read\";\nimport type { SessionGraph } from \"./graph.js\";\n\n/**\n * Who started a session and why, as a launcher such as agent-chat recorded it.\n * A transcript cannot state this: a `claude -p` worker and a headless miner look\n * the same from inside. Every field but `originSystem` is optional.\n */\nexport interface ResolvedOrigin {\n originSystem: string;\n agentId?: string | null;\n agentName?: string | null;\n parentName?: string | null;\n parentSessionId?: string | null;\n profile?: string | null;\n modelAlias?: string | null;\n surface?: string | null;\n isolation?: string | null;\n depth?: number | null;\n /** `spawned`, `adopted`, `inherited` or `human`. */\n originKind?: string | null;\n configDir?: string | null;\n spawnCwd?: string | null;\n spawnedAt?: string | null;\n briefChars?: number | null;\n briefExcerpt?: string | null;\n briefPath?: string | null;\n launchArgs?: string | null;\n}\n\n/** A lifecycle event the launcher saw outside the transcript: `teleport`, `handoff`, `retired`, `exited`. */\nexport interface ExternalEvent {\n sessionId: string;\n ts: string;\n kind: string;\n detail?: string | null;\n /** Defaults to the session's resolved origin system. */\n originSystem?: string | null;\n}\n\nexport interface OriginResolution {\n /** Keyed by session id. */\n origins: Record<string, ResolvedOrigin>;\n externalEvents?: readonly ExternalEvent[];\n}\n\n/**\n * Supplied by the caller, never by this package: session-graph is tier 2 and\n * must not learn where a launcher keeps its records. Called once per pass with\n * every session that has no origin row or a stale one.\n */\nexport type OriginResolver = (sessionIds: readonly string[]) => PromiseLike<OriginResolution> | OriginResolution;\n\nexport interface OriginEnrichment {\n /** Session ids handed to the resolver. */\n requested: number;\n /** `session_origin` rows the resolver wrote. */\n applied: number;\n /** `session_external_event` rows the resolver wrote. */\n events: number;\n /** The resolver threw; origin rows stand as the last pass left them. */\n failed: boolean;\n /** Why it failed, for the caller to log. Absent unless `failed`. */\n error?: string;\n}\n\nexport const NO_ORIGINS: OriginEnrichment = Object.freeze({ requested: 0, applied: 0, events: 0, failed: false });\n\n/** A session whose transcript grew after its origin was resolved may have been retired or handed off since. */\nconst SESSIONS_NEEDING_ORIGIN = `\n SELECT s.session_id FROM session s LEFT JOIN session_origin o ON o.session_id = s.session_id\n WHERE o.session_id IS NULL OR o.resolved_at < s.ended_at\n ORDER BY s.session_id`;\n\nconst UPSERT_ORIGIN = `\n INSERT OR REPLACE INTO session_origin (session_id, origin_system, agent_id, agent_name, parent_name, parent_session_id,\n profile, model_alias, surface, isolation, depth, origin_kind, config_dir, spawn_cwd, spawned_at,\n brief_chars, brief_excerpt, brief_path, launch_args, resolved_at)\n VALUES (@sessionId, @originSystem, @agentId, @agentName, @parentName, @parentSessionId,\n @profile, @modelAlias, @surface, @isolation, @depth, @originKind, @configDir, @spawnCwd, @spawnedAt,\n @briefChars, @briefExcerpt, @briefPath, @launchArgs, @resolvedAt)`;\n\nconst UPSERT_EVENT = `\n INSERT INTO session_external_event (session_id, ts, origin_system, kind, detail)\n VALUES (@sessionId, @ts, COALESCE(@originSystem, (SELECT origin_system FROM session_origin WHERE session_id = @sessionId), 'unknown'), @kind, @detail)\n ON CONFLICT (session_id, ts, kind) DO UPDATE SET origin_system = excluded.origin_system, detail = excluded.detail`;\n\n/** Existing subagent queries then cover launcher-spawned workers unchanged; `reconcile` fills `ended_at` from the child session. */\nconst PROJECT_SUBAGENTS = `\n INSERT INTO subagent (agent_ref, session_id, child_session_id, agent_type, label, started_at)\n SELECT 'agent:' || origin_system || ':' || agent_id, parent_session_id, session_id, profile, agent_name, spawned_at\n FROM session_origin WHERE parent_session_id IS NOT NULL AND agent_id IS NOT NULL\n ON CONFLICT (agent_ref) DO UPDATE SET session_id = excluded.session_id, child_session_id = excluded.child_session_id,\n agent_type = excluded.agent_type, label = excluded.label, started_at = COALESCE(excluded.started_at, started_at)`;\n\nexport function sessionsNeedingOrigin(graph: SessionGraph): string[] {\n return (graph.db.prepare(SESSIONS_NEEDING_ORIGIN).all() as { session_id: string }[]).map((r) => r.session_id);\n}\n\n/**\n * Resolve origins for the sessions that lack a current one, then project every\n * stored origin into `spawned` edges and `subagent` rows. Projecting from the\n * table, not from this pass's answer, restores rows a parent transcript's purge\n * removed. A resolver that throws costs this pass its origins and nothing else.\n */\nexport async function resolveOrigins(graph: SessionGraph, resolver: OriginResolver | undefined): Promise<OriginEnrichment> {\n if (!resolver) return NO_ORIGINS;\n const sessionIds = sessionsNeedingOrigin(graph);\n try {\n const resolution = await resolver(sessionIds);\n const written = writeResolution(graph, resolution, new Date().toISOString());\n return { requested: sessionIds.length, ...written, failed: false };\n } catch (err) {\n return { requested: sessionIds.length, applied: 0, events: 0, failed: true, error: err instanceof Error ? err.message : String(err) };\n } finally {\n projectOrigins(graph);\n }\n}\n\nfunction writeResolution(graph: SessionGraph, resolution: OriginResolution, resolvedAt: string): { applied: number; events: number } {\n const upsertOrigin = graph.db.prepare(UPSERT_ORIGIN);\n const upsertEvent = graph.db.prepare(UPSERT_EVENT);\n return graph.db.transaction(() => {\n let applied = 0;\n for (const [sessionId, origin] of Object.entries(resolution.origins)) {\n applied += upsertOrigin.run(originRow(sessionId, origin, resolvedAt)).changes;\n }\n let events = 0;\n for (const e of resolution.externalEvents ?? []) {\n events += upsertEvent.run({ sessionId: e.sessionId, ts: e.ts, kind: e.kind, detail: e.detail ?? null, originSystem: e.originSystem ?? null }).changes;\n }\n return { applied, events };\n })();\n}\n\nfunction originRow(sessionId: string, o: ResolvedOrigin, resolvedAt: string): Record<string, string | number | null> {\n return {\n sessionId, originSystem: o.originSystem, resolvedAt,\n agentId: o.agentId ?? null, agentName: o.agentName ?? null, parentName: o.parentName ?? null, parentSessionId: o.parentSessionId ?? null,\n profile: o.profile ?? null, modelAlias: o.modelAlias ?? null, surface: o.surface ?? null, isolation: o.isolation ?? null,\n depth: o.depth ?? null, originKind: o.originKind ?? null, configDir: o.configDir ?? null, spawnCwd: o.spawnCwd ?? null,\n spawnedAt: o.spawnedAt ?? null, briefChars: o.briefChars ?? null, briefExcerpt: o.briefExcerpt ?? null,\n briefPath: o.briefPath ?? null, launchArgs: o.launchArgs ?? null,\n };\n}\n\nfunction projectOrigins(graph: SessionGraph): void {\n const spawned = graph.db.prepare(\"SELECT session_id, parent_session_id, spawned_at, resolved_at FROM session_origin WHERE parent_session_id IS NOT NULL\").all() as {\n session_id: string; parent_session_id: string; spawned_at: string | null; resolved_at: string;\n }[];\n graph.db.transaction(() => {\n graph.db.prepare(PROJECT_SUBAGENTS).run();\n for (const o of spawned) {\n graph.edges.assert({ sourceRef: sessionRef(o.parent_session_id), relation: RELATIONS.SPAWNED, targetRef: sessionRef(o.session_id), tValid: o.spawned_at ?? o.resolved_at });\n }\n })();\n}\n","import { taskRef } from \"@titan-design/session-read\";\nimport type { SessionGraph } from \"./graph.js\";\n\n/**\n * What a product's task store knows and a transcript cannot state: the task's\n * present title, its initiative, and the status it holds right now rather than\n * the one some command was observed to set. Every field is optional; an omitted\n * or null field leaves whatever the transcripts derived in place.\n */\nexport interface ResolvedTask {\n initiative?: string | null;\n title?: string | null;\n status?: string | null;\n /** The store's size estimate for the task, in whatever unit it keeps. */\n estimate?: number | null;\n}\n\n/** Resolutions keyed by bare task id (`AW-23`, not `task:AW-23`). */\nexport type TaskResolution = ReadonlyMap<string, ResolvedTask | null | undefined>;\n\n/**\n * Supplied by the caller, never by this package: session-graph is tier 2 and\n * must not learn where any product keeps its tasks. Called once per pass with\n * every task id at once, because a real resolver reads a store. Returning an id\n * that no transcript mentioned inserts that task; that is how a task nobody\n * worked on gets into the graph.\n */\nexport type TaskResolver = (taskIds: readonly string[]) => PromiseLike<TaskResolution> | TaskResolution;\n\nexport interface TaskEnrichment {\n /** Task ids handed to the resolver. */\n requested: number;\n /** Task rows the resolver wrote. */\n applied: number;\n /** The resolver threw; rows stand as the transcripts left them. */\n failed: boolean;\n /** Why it failed, for the caller to log. Absent unless `failed`. */\n error?: string;\n}\n\nexport const NO_ENRICHMENT: TaskEnrichment = Object.freeze({ requested: 0, applied: 0, failed: false });\n\n/**\n * COALESCE gives the resolver precedence over the transcripts on every field it\n * states, and none on the fields it omits: the store is the system of record for\n * a task's present status, while a transcript only witnesses a command that ran.\n */\nconst UPSERT_TASK = `\n INSERT INTO task (task_ref, task_id, initiative, title, status, estimate) VALUES (@taskRef, @taskId, @initiative, @title, @status, @estimate)\n ON CONFLICT (task_ref) DO UPDATE SET\n initiative = COALESCE(excluded.initiative, initiative),\n title = COALESCE(excluded.title, title),\n status = COALESCE(excluded.status, status),\n estimate = COALESCE(excluded.estimate, estimate)`;\n\nexport function allTaskIds(graph: SessionGraph): string[] {\n return (graph.db.prepare(\"SELECT task_id FROM task\").all() as { task_id: string }[]).map((r) => r.task_id);\n}\n\n/**\n * Enrich task rows from a caller-supplied resolver. Runs outside the delta's\n * transaction because a resolver is async; a crash between the two leaves rows\n * un-enriched, which the next pass corrects. A resolver that throws costs this\n * pass its enrichment and nothing else.\n */\nexport async function enrichTasks(graph: SessionGraph, resolver: TaskResolver | undefined, taskIds: readonly string[]): Promise<TaskEnrichment> {\n const unique = [...new Set(taskIds)];\n if (!resolver) return NO_ENRICHMENT;\n try {\n const resolved = await resolver(unique);\n return { requested: unique.length, applied: write(graph, resolved), failed: false };\n } catch (err) {\n return { requested: unique.length, applied: 0, failed: true, error: err instanceof Error ? err.message : String(err) };\n }\n}\n\nfunction write(graph: SessionGraph, resolved: TaskResolution): number {\n const upsert = graph.db.prepare(UPSERT_TASK);\n return graph.db.transaction(() => {\n let applied = 0;\n for (const [taskId, fields] of resolved) {\n if (!fields) continue;\n applied += upsert.run({\n taskRef: taskRef(taskId),\n taskId,\n initiative: fields.initiative ?? null,\n title: fields.title ?? null,\n status: fields.status ?? null,\n estimate: fields.estimate ?? null,\n }).changes;\n }\n return applied;\n })();\n}\n","import { EPISODE_TABLE } from \"./audit-schema-v5.js\";\nimport type { SessionGraph } from \"./graph.js\";\n\n/**\n * One stretch of a session as some segmentation heuristic cut it. The rule\n * lives above storage (session-analytics); this package only keeps its output.\n * Offsets are byte offsets into the session's transcript.\n */\nexport interface EpisodeRow {\n episodeIndex: number;\n heuristicVersion: number;\n startedAt: string;\n endedAt: string;\n startOffset: number;\n endOffset: number;\n /** `session_start`, `brief`, `channel_followup`, `idle_gap`, `pr_merge`, `spawn_wave_complete`, `task_wrap`, `context_reset`, or a newer heuristic's term. */\n openedBy: string;\n /** The transcript `startOffset`/`endOffset` fall in; a session resumed across transcripts can differ between the two. */\n startTranscriptId?: number | null;\n endTranscriptId?: number | null;\n assignmentOffset?: number | null;\n firstDeliverableOffset?: number | null;\n firstDeliverableSignal?: string | null;\n firstStatusOffset?: number | null;\n}\n\nconst DELETE_EPISODES = `DELETE FROM ${EPISODE_TABLE} WHERE session_id = ? AND heuristic = ?`;\n\nconst INSERT_EPISODE = `\n INSERT INTO ${EPISODE_TABLE} (session_id, episode_index, heuristic, heuristic_version, started_at, ended_at,\n start_offset, end_offset, start_transcript_id, end_transcript_id, opened_by, assignment_offset,\n first_deliverable_offset, first_deliverable_signal, first_status_offset)\n VALUES (@sessionId, @episodeIndex, @heuristic, @heuristicVersion, @startedAt, @endedAt,\n @startOffset, @endOffset, @startTranscriptId, @endTranscriptId, @openedBy, @assignmentOffset,\n @firstDeliverableOffset, @firstDeliverableSignal, @firstStatusOffset)`;\n\n/**\n * The only writer of `episode`. Replaces one heuristic's segmentation of one\n * session atomically and leaves every other heuristic's rows alone, so two rule\n * sets can coexist while one is compared against the other. Returns rows written.\n */\nexport function replaceEpisodes(graph: SessionGraph, sessionId: string, heuristic: string, rows: readonly EpisodeRow[]): number {\n const remove = graph.db.prepare(DELETE_EPISODES);\n const insert = graph.db.prepare(INSERT_EPISODE);\n return graph.db.transaction(() => {\n remove.run(sessionId, heuristic);\n for (const row of rows) insert.run(episodeParams(sessionId, heuristic, row));\n return rows.length;\n })();\n}\n\nfunction episodeParams(sessionId: string, heuristic: string, row: EpisodeRow): Record<string, string | number | null> {\n return {\n sessionId, heuristic,\n episodeIndex: row.episodeIndex, heuristicVersion: row.heuristicVersion,\n startedAt: row.startedAt, endedAt: row.endedAt, startOffset: row.startOffset, endOffset: row.endOffset, openedBy: row.openedBy,\n startTranscriptId: row.startTranscriptId ?? null, endTranscriptId: row.endTranscriptId ?? null,\n assignmentOffset: row.assignmentOffset ?? null, firstDeliverableOffset: row.firstDeliverableOffset ?? null,\n firstDeliverableSignal: row.firstDeliverableSignal ?? null, firstStatusOffset: row.firstStatusOffset ?? null,\n };\n}\n","import type { SessionGraph } from \"./graph.js\";\n\n/** USD per million tokens for one model prefix from one date. Shaped so session-analytics' `PRICE_TABLE` passes straight through. */\nexport interface PriceInput {\n /** Matched against `request.model` by longest prefix in `request_cost`. */\n modelPrefix: string;\n /** ISO date or timestamp; compared as text against `request.ts`. */\n effectiveFrom: string;\n input: number;\n cacheRead: number;\n cacheWrite5m: number;\n cacheWrite1h: number;\n output: number;\n}\n\nexport interface SyncPricesOptions {\n /** Stamped on every row so a report can name the table it priced with. */\n tableVersion: number;\n source?: string;\n}\n\n/** Replace every `price` row with `rows` in one transaction, so `request_cost` never reads a half-written table. */\nexport function syncPrices(graph: SessionGraph, rows: readonly PriceInput[], options: SyncPricesOptions): number {\n const insert = graph.db.prepare(\n `INSERT INTO price (model, effective_from, table_version, input_usd_mtok, cache_read_usd_mtok,\n cache_write_5m_usd_mtok, cache_write_1h_usd_mtok, output_usd_mtok, source)\n VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,\n );\n const source = options.source ?? null;\n graph.db.transaction(() => {\n graph.db.exec(\"DELETE FROM price\");\n for (const r of rows) {\n insert.run(r.modelPrefix, r.effectiveFrom, options.tableVersion, r.input, r.cacheRead, r.cacheWrite5m, r.cacheWrite1h, r.output, source);\n }\n })();\n return rows.length;\n}\n","import { randomUUID } from \"node:crypto\";\nimport { stat } from \"node:fs/promises\";\nimport { contentHash } from \"@titan-design/locator\";\nimport { conversationRef } from \"@titan-design/agent-protocol\";\nimport { SPAN_TEXT_CAP, readCodexObservations, type CodexReadResult, type NormalizedSessionObservation, type SessionSourceDescriptor, type SourceTextLocator } from \"@titan-design/session-read\";\nimport type { SessionGraph } from \"./graph.js\";\nimport { insertObservation, observationText } from \"./normalized-project.js\";\n\nexport interface NormalizedIndexResult { status: \"indexed\" | \"unchanged\" | \"missing\" | \"quarantined\"; conversationRef: string; observations: number; reason?: string }\n\n/** Replay changed sources into temporary staging; swap rows and watermark atomically. */\nexport async function indexCodexSource(graph: SessionGraph, source: SessionSourceDescriptor): Promise<NormalizedIndexResult> {\n const ref = conversationRef(source.conversation);\n const base = { conversationRef: ref, observations: 0 };\n const row = graph.transcripts.ensure(source.sourceId);\n let info;\n try { info = await stat(source.path); } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== \"ENOENT\") throw error;\n graph.transcripts.markStatus(source.sourceId, \"missing\", \"source unavailable\");\n return { ...base, status: \"missing\" };\n }\n // Always replay: the decoder verifies bytes, detects projections that arrived later,\n // and avoids trusting mtime alone. Equality of the resulting prefix is the fast no-op.\n const stage = `stage_${randomUUID().replaceAll(\"-\", \"\")}`;\n graph.db.exec(`CREATE TEMP TABLE ${stage}(seq INTEGER PRIMARY KEY, observation TEXT NOT NULL)`);\n let result: CodexReadResult | undefined;\n try {\n const fingerprint = await contentHash(source.path);\n const insert = graph.db.prepare(`INSERT INTO ${stage}(observation) VALUES (?)`);\n for await (const observation of readCodexObservations(source, {}, done => { result = done; })) insert.run(JSON.stringify(observation));\n if (!result) throw new Error(\"decoder completed without a resume boundary\");\n const boundary = (result as CodexReadResult).resumeBoundary;\n const prior = graph.db.prepare(\"SELECT descriptor FROM normalized_source WHERE transcript_id = ?\").get(row.sourceId) as { descriptor: string } | undefined;\n if (prior && row.contentHash === fingerprint && row.prefixHash === boundary.prefixHash && row.lastOffset === boundary.byteOffset) {\n graph.db.prepare(\"UPDATE normalized_source SET descriptor = ? WHERE transcript_id = ?\").run(JSON.stringify(source), row.sourceId);\n graph.transcripts.markStatus(source.sourceId, \"ok\", null);\n return { ...base, status: \"unchanged\" };\n }\n const count = graph.db.transaction(() => {\n purgeNormalizedSource(graph, row.sourceId);\n graph.db.prepare(\"INSERT OR IGNORE INTO conversation(ref,harness,namespace,native_id) VALUES (?,?,?,?)\").run(ref, source.harness, source.namespace, source.conversation.nativeId);\n graph.db.prepare(\"INSERT OR REPLACE INTO normalized_source VALUES (?,?,?,?)\").run(row.sourceId, source.sourceId, ref, JSON.stringify(source));\n const n = applyStaged(graph, stage, row.sourceId, ref);\n graph.transcripts.advance(source.sourceId, { lastOffset: boundary.byteOffset, prefixHash: boundary.prefixHash, fileSize: info.size, fileMtime: info.mtime.toISOString(), contentHash: fingerprint });\n return n;\n })();\n return { ...base, status: \"indexed\", observations: count };\n } catch (error) {\n const reason = error instanceof Error ? error.message : String(error);\n graph.transcripts.markStatus(source.sourceId, \"quarantined\", reason);\n return { ...base, status: \"quarantined\", reason };\n } finally { graph.db.exec(`DROP TABLE ${stage}`); }\n}\n\nfunction applyStaged(graph: SessionGraph, stage: string, transcriptId: number, ref: string): number {\n const spans = `${stage}_spans`;\n graph.db.exec(`CREATE TEMP TABLE ${spans}(field TEXT, offset INTEGER, length INTEGER, text TEXT, locators TEXT, PRIMARY KEY(field,offset))`);\n let count = 0;\n try {\n for (const row of stagedRows<{ observation: string }>(graph, stage)) {\n const o = JSON.parse(row.observation) as NormalizedSessionObservation;\n insertObservation(graph, transcriptId, o);\n for (const p of observationText(o)) stageText(graph, spans, p.field, p.text, p.locator);\n count++;\n }\n for (const s of stagedRows<{ field: string; offset: number; length: number; text: string; locators: string }>(graph, spans)) {\n const id = graph.spans.index({ ownerRef: ref, sourceId: transcriptId, field: s.field, byteOffset: s.offset, byteLength: s.length }, s.text);\n graph.db.prepare(\"INSERT INTO normalized_span VALUES (?,?)\").run(id, s.locators);\n }\n } finally { graph.db.exec(`DROP TABLE ${spans}`); }\n return count;\n}\n\nfunction stageText(graph: SessionGraph, table: string, field: string, text: string, locator: SourceTextLocator): void {\n const line = locator.evidence.line;\n const prior = graph.db.prepare(`SELECT text,locators FROM ${table} WHERE field = ? AND offset = ?`).get(field, line.byteOffset) as { text: string; locators: string } | undefined;\n const locators = prior ? JSON.parse(prior.locators) as unknown[] : [];\n locators.push(locator);\n graph.db.prepare(`INSERT OR REPLACE INTO ${table} VALUES (?,?,?,?,?)`).run(field, line.byteOffset, line.byteLength, (prior ? `${prior.text}\\n${text}` : text).slice(0, SPAN_TEXT_CAP), JSON.stringify(locators));\n}\n\nfunction purgeNormalizedSource(graph: SessionGraph, transcriptId: number): void {\n graph.db.prepare(\"DELETE FROM normalized_span WHERE span_id IN (SELECT span_id FROM search_span WHERE source_id = ?)\").run(transcriptId);\n graph.db.prepare(\"DELETE FROM search_span WHERE source_id = ?\").run(transcriptId);\n graph.db.prepare(\"DELETE FROM normalized_event WHERE transcript_id = ?\").run(transcriptId);\n}\n\n\n/** Finish each SELECT before writing; SQLite forbids writes during an active iterator. */\nfunction* stagedRows<T>(graph: SessionGraph, table: string): Generator<T> {\n const select = graph.db.prepare(`SELECT rowid AS cursor, * FROM ${table} WHERE rowid > ? ORDER BY rowid LIMIT 128`);\n let cursor = 0;\n for (;;) {\n const rows = select.all(cursor) as (T & { cursor: number })[];\n if (!rows.length) return;\n for (const row of rows) { cursor = row.cursor; yield row; }\n }\n}\n","import { conversationRef } from \"@titan-design/agent-protocol\";\nimport { normalizedSearchText, SPAN_TEXT_CAP, scopedConversationItemRef, type NormalizedSessionObservation as Observation, type SourceTextLocator } from \"@titan-design/session-read\";\nimport type { SessionGraph } from \"./graph.js\";\n\n/** Persist structural evidence only; prose remains in the source and transient FTS input. */\nexport function insertObservation(graph: SessionGraph, transcriptId: number, o: Observation): void {\n graph.db.prepare(`INSERT INTO normalized_event VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`).run(\n transcriptId, o.evidence.line.byteOffset, o.evidence.subrecord.index, o.evidence.line.byteLength,\n conversationRef(o.conversation), o.kind, o.timestamp,\n \"turn\" in o && o.turn ? scopedConversationItemRef(o.turn) : null,\n \"call\" in o ? scopedConversationItemRef(o.call) : null,\n \"item\" in o && o.item ? scopedConversationItemRef(o.item) : null,\n o.kind === \"native_turn\" ? o.phase : null,\n o.kind === \"tool_result\" && o.isError !== null ? Number(o.isError) : null,\n o.kind === \"usage\" ? JSON.stringify(o.measurement) : null,\n o.kind === \"metadata\" ? JSON.stringify(o.entries.filter(e => [\"cwd\", \"model\", \"cli_version\", \"git_branch\", \"title\"].includes(e.name))) : null,\n o.historyOrigin ? conversationRef(o.historyOrigin) : null,\n o.kind === \"lineage\" ? conversationRef(o.relatedConversation) : null,\n o.kind === \"lineage\" ? o.relationship : null,\n );\n}\n\nexport interface ObservationText { field: string; text: string; locator: SourceTextLocator }\nexport function observationText(o: Observation): ObservationText[] {\n if (o.kind === \"message\") return o.content.map(p => ({ field: o.role === \"user\" ? \"prompt\" : \"assistant_response\", text: p.text.slice(0, SPAN_TEXT_CAP), locator: p.locator }));\n if (o.kind === \"tool_call\" && o.inputLocator) return [{ field: \"tool_input\", text: normalizedSearchText(o.input), locator: o.inputLocator }];\n if (o.kind === \"tool_result\" && o.outputLocator) return [{ field: \"tool_result\", text: normalizedSearchText(o.output), locator: o.outputLocator }];\n return [];\n}\n","import { contentHash, prefixHash } from \"@titan-design/locator\";\nimport type { UsageMeasurement } from \"@titan-design/agent-protocol\";\nimport { readSessionSourceText, readSessionText, SessionUsageAccumulator, type SessionUsageSummary, type SourceTextLocator, type SessionSourceDescriptor, type SpanField } from \"@titan-design/session-read\";\nimport type { SessionGraph } from \"./graph.js\";\n\nexport interface IndexedSpan { sourceId: number; byteOffset: number; byteLength: number; field: string; spanId?: number }\n/** One resolver for search and error clustering; never display a raw JSON line. */\nexport async function readIndexedText(graph: SessionGraph, span: IndexedSpan): Promise<string | null> {\n const row = graph.db.prepare(`SELECT n.locators FROM normalized_span n JOIN search_span s USING(span_id)\n WHERE s.source_id = ? AND s.byte_offset = ? AND s.field = ?`).get(span.sourceId, span.byteOffset, span.field) as { locators: string } | undefined;\n if (row) {\n const source = graph.db.prepare(\"SELECT descriptor FROM normalized_source WHERE transcript_id = ?\").get(span.sourceId) as { descriptor: string } | undefined;\n if (!source) return null;\n const descriptor = JSON.parse(source.descriptor) as SessionSourceDescriptor;\n const watermark = graph.transcripts.list().find(t => t.sourceId === span.sourceId);\n try { if (!watermark?.prefixHash || await prefixHash(descriptor.path, watermark.lastOffset) !== watermark.prefixHash) return null; }\n catch { return null; }\n if (span.byteOffset + span.byteLength + 1 > watermark.lastOffset) {\n try { if (!watermark.contentHash || await contentHash(descriptor.path) !== watermark.contentHash) return null; } catch { return null; }\n }\n const texts = await Promise.all((JSON.parse(row.locators) as SourceTextLocator[]).map(locator => readSessionSourceText(locator, { sources: [JSON.parse(source.descriptor) as SessionSourceDescriptor] })));\n return texts.some(text => text === null) ? null : texts.join(\"\\n\");\n }\n const normalized = graph.db.prepare(\"SELECT 1 FROM normalized_source WHERE transcript_id = ?\").get(span.sourceId);\n if (normalized) return null;\n const legacy = graph.transcripts.list().find(t => t.sourceId === span.sourceId);\n return legacy ? readSessionText({ path: legacy.sourceKey, byteOffset: span.byteOffset, byteLength: span.byteLength, field: span.field as SpanField }) : null;\n}\n\nexport interface ConversationSummary {\n sessionId: string; harness: string; nativeId: string; namespace: string;\n title: string | null; startedAt: string | null; endedAt: string | null;\n cwd: string | null; gitBranch: string | null; turnCount: number; commitCount: number | null; pushCount: number | null;\n}\nexport function normalizedSessions(graph: SessionGraph, options: { ref?: string; limit?: number; since?: string } = {}): ConversationSummary[] {\n const rows = graph.db.prepare(`SELECT c.ref,c.harness,c.native_id,c.namespace,MIN(e.ts) AS started,\n COUNT(DISTINCT CASE WHEN e.kind = 'native_turn' THEN e.turn_ref END) AS turns\n FROM conversation c JOIN (SELECT DISTINCT conversation_ref FROM normalized_source) s ON s.conversation_ref = c.ref\n LEFT JOIN normalized_event e ON e.conversation_ref = c.ref AND e.history_origin IS NULL\n WHERE c.legacy_session_id IS NULL AND (? IS NULL OR c.ref = ?)\n GROUP BY c.ref HAVING (? IS NULL OR MIN(e.ts) >= ?)\n ORDER BY started DESC LIMIT ?`).all(options.ref ?? null,options.ref ?? null,options.since ?? null,options.since ?? null,options.limit ?? -1) as\n { ref: string; harness: string; native_id: string; namespace: string; started: string | null; turns: number }[];\n const meta = graph.db.prepare(`SELECT json_extract(j.value,'$.value') AS value\n FROM normalized_event e,json_each(e.metadata) j WHERE e.conversation_ref = ?\n AND e.history_origin IS NULL AND json_extract(j.value,'$.name') = ? ORDER BY e.ts DESC,e.byte_offset DESC,e.subrecord_index DESC LIMIT 1`);\n return rows.map(c => {\n const text = (key: string) => { const value = (meta.get(c.ref,key) as { value: unknown } | undefined)?.value; return typeof value === \"string\" ? value : null; };\n return { sessionId:c.ref,harness:c.harness,nativeId:c.native_id,namespace:c.namespace,title:text(\"title\"),startedAt:c.started,\n endedAt:null,cwd:text(\"cwd\"),gitBranch:text(\"git_branch\"),turnCount:c.turns,commitCount:null,pushCount:null };\n });\n}\n\nexport type NormalizedUsageSummary = SessionUsageSummary;\n/** Shared storage-free usage policy keeps graph and direct readers consistent. */\nexport function normalizedUsage(graph: SessionGraph, ref: string): NormalizedUsageSummary[] {\n // Snapshot epochs are local to a physical source; never add copies from different files.\n // Pick the source with the latest native timestamp (then fullest coverage, then stable ID).\n const preferred = graph.db.prepare(`SELECT transcript_id FROM normalized_event\n WHERE conversation_ref = ? AND usage IS NOT NULL AND history_origin IS NULL\n GROUP BY transcript_id ORDER BY MAX(ts) DESC, COUNT(*) DESC, transcript_id ASC LIMIT 1`).get(ref) as { transcript_id: number } | undefined;\n const rows = graph.db.prepare(`SELECT usage FROM normalized_event WHERE conversation_ref = ?\n AND usage IS NOT NULL AND history_origin IS NULL\n AND (json_extract(usage,'$.kind') = 'delta' OR transcript_id = ?)\n ORDER BY byte_offset,subrecord_index`);\n const accumulator = new SessionUsageAccumulator();\n for (const row of rows.iterate(ref, preferred?.transcript_id ?? -1) as Iterable<{ usage: string }>) {\n accumulator.add(JSON.parse(row.usage) as UsageMeasurement);\n }\n return accumulator.summaries();\n}\n"],"mappings":";AAAA,SAAS,WAAW,eAAe,gBAAgB,cAAc,qBAA8B;;;ACGxF,IAAM,uBAAuB;AAG7B,IAAM,eAAe;AAAA,EAC1B;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAGO,IAAM,cAAc;AAEpB,IAAM,YAAY;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;A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C;AACH;AAIO,SAAS,gBAAgB,OAAqB,KAAuC;AAG1F,QAAM,YAAY,MAAM,GAAG,QAAQ;AAAA;AAAA,2FAEsD,EAAE,IAAI,GAAG;AAClG,QAAM,OAAO,MAAM,GAAG,QAAQ;AAAA;AAAA;AAAA,yCAGS;AACvC,QAAM,cAAc,IAAI,wBAAwB;AAChD,aAAW,OAAO,KAAK,QAAQ,KAAK,WAAW,iBAAiB,EAAE,GAAkC;AAClG,gBAAY,IAAI,KAAK,MAAM,IAAI,KAAK,CAAqB;AAAA,EAC3D;AACA,SAAO,YAAY,UAAU;AAC/B;","names":["sessionRef","sessionRef","TranscriptParseError","extractTranscript","sessionRef","write","extractTranscript","stat","TranscriptParseError","contentHash","conversationRef","SPAN_TEXT_CAP","conversationRef","conversationRef","contentHash","SPAN_TEXT_CAP","contentHash"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@titan-design/session-graph",
3
- "version": "0.8.1",
3
+ "version": "0.9.0",
4
4
  "description": "Fold session events into the activity graph on store-sqlite",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",