@titan-design/session-graph 0.5.0 → 0.6.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/README.md +25 -6
- package/dist/index.d.ts +65 -13
- package/dist/index.js +382 -24
- package/dist/index.js.map +1 -1
- package/package.json +3 -3
package/README.md
CHANGED
|
@@ -14,7 +14,8 @@ import { openSessionGraph, refreshCorpus } from "@titan-design/session-graph";
|
|
|
14
14
|
|
|
15
15
|
const graph = openSessionGraph("~/.local/state/miner/index.sqlite3");
|
|
16
16
|
const summary = await refreshCorpus(graph, await discoverTranscripts());
|
|
17
|
-
// summary.indexed, summary.unchanged, summary.rewound, summary.quarantined, summary.missing
|
|
17
|
+
// summary.indexed, summary.unchanged, summary.rewound, summary.quarantined, summary.missing,
|
|
18
|
+
// summary.facetsBackfilled, summary.facetBacklog
|
|
18
19
|
```
|
|
19
20
|
|
|
20
21
|
`openSessionGraph` takes an optional `schemaVersion`: the highest migration version the
|
|
@@ -29,15 +30,23 @@ passes 1002.
|
|
|
29
30
|
checks the file (`unchanged`, `appended`, `rewritten`, `missing`), reads the delta with
|
|
30
31
|
`extractTranscript`, applies it in one transaction, and advances the watermark with the
|
|
31
32
|
new prefix hash. A malformed line quarantines that transcript only.
|
|
32
|
-
2. `
|
|
33
|
-
|
|
33
|
+
2. `backfillFacets` re-extracts the audit facet of already-indexed transcripts whose
|
|
34
|
+
`transcript_facet` version is below session-read's `EXTRACT_VERSION`: up to
|
|
35
|
+
`facetLimit` of them per pass (default 40), newest `file_mtime` first, each read from
|
|
36
|
+
byte 0 to its watermark. It replaces that transcript's rows in the eight audit tables
|
|
37
|
+
and never writes the legacy tables, so their accumulating counts cannot double.
|
|
38
|
+
Transcripts that are `missing` or `quarantined` are skipped. `summary.facetsBackfilled`
|
|
39
|
+
and `summary.facetBacklog` report progress; pass `facetLimit: Infinity` to clear the
|
|
40
|
+
backlog in one pass. A classifier change is a version bump, not a `resetIndex`.
|
|
41
|
+
3. `rollupSessions` recomputes turn aggregates (index, end, duration, tool calls, thinking
|
|
42
|
+
time) for the sessions that changed, including those the backfill touched. Recompute, never accumulate, so incremental and
|
|
34
43
|
full passes converge.
|
|
35
|
-
|
|
44
|
+
4. `reconcile` folds cross-transcript observations: `gh pr merge` sightings onto PRs,
|
|
36
45
|
complete `gh pr create` sightings into new PR rows, subagent end times and parentage
|
|
37
46
|
from child sessions.
|
|
38
|
-
|
|
47
|
+
5. `enrichTasks` runs if the caller passed a `resolveTasks` resolver, once over the whole
|
|
39
48
|
task table. See below.
|
|
40
|
-
|
|
49
|
+
6. Rows whose source file has vanished are marked `missing`. Their facts stay: surviving
|
|
41
50
|
Claude Code's own pruning is much of the point.
|
|
42
51
|
|
|
43
52
|
`resetIndex` clears every derived table and rewinds watermarks; the next refresh rebuilds
|
|
@@ -100,6 +109,16 @@ files are not needed to migrate. Back up the database before upgrading; restorin
|
|
|
100
109
|
that backup is the rollback path for an older binary. Explicit `resetIndex` remains a
|
|
101
110
|
destructive rebuild and requires the original sources; it is never run by migration.
|
|
102
111
|
|
|
112
|
+
Migration 4, `audit tables`, adds one table per session-read audit event kind
|
|
113
|
+
(`request`, `tool_call`, `inbound`, `context_block`, `compaction`, `queue_op`,
|
|
114
|
+
`session_signal`, `cost_state_observation`) plus `transcript_facet`, and adds
|
|
115
|
+
`session.account` and five rollup or outcome columns. It creates only empty tables and
|
|
116
|
+
nullable columns, so existing rows are untouched; transcripts indexed before it gain
|
|
117
|
+
audit rows through `backfillFacets` on later refreshes. `request` holds one row per `(transcript_id, request_id)`:
|
|
118
|
+
the several assistant lines of one API response collapse to the first line's offset and
|
|
119
|
+
the largest value of each token column. `session.account` comes from discovery, not the
|
|
120
|
+
transcript. `purgeTranscript` and `resetIndex` clear all nine tables.
|
|
121
|
+
|
|
103
122
|
For snapshot-only usage across multiple physical sources, queries select one source
|
|
104
123
|
by latest native usage timestamp, then greatest usage-record coverage and stable
|
|
105
124
|
source ID. Source-local reset epochs cannot safely be summed across copies. This is
|
package/dist/index.d.ts
CHANGED
|
@@ -39,17 +39,58 @@ declare const KIT: {
|
|
|
39
39
|
*/
|
|
40
40
|
declare 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 (strftime('%Y-%m-%dT%H:%M:%fZ','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";
|
|
41
41
|
/** Every derived table, in an order safe to clear. The watermark table is not derived. */
|
|
42
|
-
declare const DERIVED_TABLES: readonly ["normalized_span", "normalized_event", "normalized_source", "search_span", "edge", "turn", "permission_phase", "human_edit", "file_checkpoint", "subagent", "session_model_usage", "session", "fact", "pr", "pr_merge_observation", "pr_create_observation", "branch", "file", "task", "artifact"];
|
|
42
|
+
declare const DERIVED_TABLES: readonly ["normalized_span", "normalized_event", "normalized_source", "search_span", "edge", "turn", "permission_phase", "human_edit", "file_checkpoint", "subagent", "request", "tool_call", "inbound", "context_block", "compaction", "queue_op", "session_signal", "cost_state_observation", "transcript_facet", "session_model_usage", "session", "fact", "pr", "pr_merge_observation", "pr_create_observation", "branch", "file", "task", "artifact"];
|
|
43
43
|
declare const MIGRATIONS: Migration[];
|
|
44
44
|
|
|
45
|
+
/** Recorded in `_migration`; store-sqlite refuses a database whose applied name differs, so never rename it. */
|
|
46
|
+
declare const AUDIT_MIGRATION_NAME = "audit tables";
|
|
47
|
+
/** Tables written per transcript by `applyAudit` and dropped by `purgeTranscript`. */
|
|
48
|
+
declare const AUDIT_TABLES: readonly ["request", "tool_call", "inbound", "context_block", "compaction", "queue_op", "session_signal", "cost_state_observation"];
|
|
49
|
+
/** Per-transcript read state for each audit facet; cleared with the audit rows so a re-read starts clean. */
|
|
50
|
+
declare const FACET_TABLE = "transcript_facet";
|
|
51
|
+
declare 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";
|
|
52
|
+
|
|
53
|
+
/** Write one delta's audit events. Runs inside `applyDelta`'s transaction, so it opens none of its own. */
|
|
54
|
+
declare function applyAudit(db: Db, transcriptId: number, delta: TranscriptDelta): void;
|
|
55
|
+
|
|
56
|
+
/** The one facet today: the eight audit tables, all written from the same extraction. */
|
|
57
|
+
declare const AUDIT_FACET = "audit";
|
|
58
|
+
/** Transcripts re-extracted per pass, so a daemon's pass stays short while the backlog drains. */
|
|
59
|
+
declare const DEFAULT_FACET_LIMIT = 40;
|
|
60
|
+
interface BackfillOptions {
|
|
61
|
+
/** Transcripts visited this pass. `Infinity` clears the whole backlog. */
|
|
62
|
+
limit?: number;
|
|
63
|
+
/** The extraction version a facet must reach. Defaults to session-read's `EXTRACT_VERSION`. */
|
|
64
|
+
version?: number;
|
|
65
|
+
}
|
|
66
|
+
interface BackfillSummary {
|
|
67
|
+
backfilled: number;
|
|
68
|
+
/** Stale transcripts left for later passes. */
|
|
69
|
+
backlog: number;
|
|
70
|
+
/** Sessions whose audit rows were rebuilt, for the caller's rollup. */
|
|
71
|
+
sessionIds: string[];
|
|
72
|
+
}
|
|
73
|
+
/**
|
|
74
|
+
* Bring the audit facet of already-indexed transcripts up to `version` without a
|
|
75
|
+
* full rebuild: re-read each one up to its watermark and replace only its audit
|
|
76
|
+
* rows. Legacy tables are never written, so their accumulating counts cannot double.
|
|
77
|
+
*/
|
|
78
|
+
declare function backfillFacets(graph: SessionGraph, transcripts: readonly DiscoveredTranscript[], options?: BackfillOptions): Promise<BackfillSummary>;
|
|
79
|
+
|
|
45
80
|
/**
|
|
46
81
|
* Apply one transcript chunk's delta in a single transaction, so a crash can
|
|
47
82
|
* never leave rows committed behind a stale watermark or ahead of their rows.
|
|
48
|
-
* Append-only tables are idempotent through unique indexes; session
|
|
49
|
-
*
|
|
50
|
-
*
|
|
83
|
+
* Append-only tables are idempotent through unique indexes; session rows
|
|
84
|
+
* accumulate; usage is left to the rollup, which recomputes it from `request`;
|
|
85
|
+
* ref-keyed assets insert-if-absent with COALESCE merges that mirror
|
|
86
|
+
* `EventFolder`'s rules.
|
|
51
87
|
*/
|
|
52
|
-
declare function applyDelta(graph: SessionGraph, transcriptId: number, delta: TranscriptDelta): void;
|
|
88
|
+
declare function applyDelta(graph: SessionGraph, transcriptId: number, delta: TranscriptDelta, source?: DeltaSource): void;
|
|
89
|
+
/** What discovery knows about the file that the lines themselves do not carry. */
|
|
90
|
+
interface DeltaSource {
|
|
91
|
+
/** The Claude config dir the transcript was found under; `null` when discovery did not say. */
|
|
92
|
+
account?: string | null;
|
|
93
|
+
}
|
|
53
94
|
|
|
54
95
|
/**
|
|
55
96
|
* Drop every derived row one transcript produced, so re-reading it from byte 0
|
|
@@ -68,10 +109,13 @@ declare function applyDelta(graph: SessionGraph, transcriptId: number, delta: Tr
|
|
|
68
109
|
* inserts are insert-if-absent; a single transcript cannot know whether it was
|
|
69
110
|
* the only source. The two observation tables are left for the same reason —
|
|
70
111
|
* `reconcile` folds them, and re-reading re-asserts the same rows.
|
|
112
|
+
*
|
|
113
|
+
* Audit rows and facet state carry `transcript_id` themselves, so they go by it
|
|
114
|
+
* directly rather than through `session`.
|
|
71
115
|
*/
|
|
72
116
|
declare function purgeTranscript(graph: SessionGraph, transcriptId: number): void;
|
|
73
117
|
|
|
74
|
-
/** Recompute turn aggregates for the given sessions in one transaction. */
|
|
118
|
+
/** Recompute turn aggregates and the audit rollup for the given sessions in one transaction. */
|
|
75
119
|
declare function rollupSessions(graph: SessionGraph, sessionIds: readonly string[]): number;
|
|
76
120
|
interface ReconcileCounts {
|
|
77
121
|
prMerges: number;
|
|
@@ -130,6 +174,12 @@ interface IndexOptions {
|
|
|
130
174
|
/** Fill task title, initiative and present status from the caller's store. Absent means transcripts alone. */
|
|
131
175
|
resolveTasks?: TaskResolver;
|
|
132
176
|
}
|
|
177
|
+
interface RefreshOptions extends IndexOptions {
|
|
178
|
+
/** Roll up every session, not just the ones this pass touched. */
|
|
179
|
+
full?: boolean;
|
|
180
|
+
/** Stale audit facets re-extracted per pass (default 40). `Infinity` clears the backlog. */
|
|
181
|
+
facetLimit?: number;
|
|
182
|
+
}
|
|
133
183
|
type TranscriptOutcome = {
|
|
134
184
|
status: "unchanged" | "indexed" | "rewound";
|
|
135
185
|
transcriptId: number;
|
|
@@ -162,11 +212,15 @@ interface RefreshSummary {
|
|
|
162
212
|
reconciled: ReconcileCounts;
|
|
163
213
|
tasks: TaskEnrichment;
|
|
164
214
|
markedMissing: number;
|
|
215
|
+
facetsBackfilled: number;
|
|
216
|
+
/** Transcripts whose audit facet is still stale after this pass. */
|
|
217
|
+
facetBacklog: number;
|
|
165
218
|
}
|
|
166
219
|
/**
|
|
167
|
-
* One pass over a corpus: index every transcript,
|
|
168
|
-
*
|
|
169
|
-
*
|
|
220
|
+
* One pass over a corpus: index every transcript, re-extract a bounded batch of
|
|
221
|
+
* stale audit facets, roll up the sessions that changed, reconcile
|
|
222
|
+
* cross-transcript observations, enrich tasks, and mark rows whose source file
|
|
223
|
+
* is gone. Idempotent: a second pass over unchanged files
|
|
170
224
|
* changes nothing.
|
|
171
225
|
*
|
|
172
226
|
* The resolver is hoisted out of the per-transcript loop and run once over the
|
|
@@ -174,9 +228,7 @@ interface RefreshSummary {
|
|
|
174
228
|
* than N, and a task whose store row changed refreshes even when no transcript
|
|
175
229
|
* did. That bounds staleness to one pass.
|
|
176
230
|
*/
|
|
177
|
-
declare function refreshCorpus(graph: SessionGraph, transcripts: readonly DiscoveredTranscript[], options?:
|
|
178
|
-
full?: boolean;
|
|
179
|
-
}): Promise<RefreshSummary>;
|
|
231
|
+
declare function refreshCorpus(graph: SessionGraph, transcripts: readonly DiscoveredTranscript[], options?: RefreshOptions): Promise<RefreshSummary>;
|
|
180
232
|
|
|
181
233
|
interface NormalizedIndexResult {
|
|
182
234
|
status: "indexed" | "unchanged" | "missing" | "quarantined";
|
|
@@ -222,4 +274,4 @@ declare function normalizedUsage(graph: SessionGraph, ref: string): NormalizedUs
|
|
|
222
274
|
/** Ambiguity is explicit; workspace session bodies remain in their original namespace. */
|
|
223
275
|
declare function resolveConversationAlias(db: Db, legacyRef: string): string | null;
|
|
224
276
|
|
|
225
|
-
export { type ConversationSummary, DERIVED_TABLES, DOMAIN_DDL, type IndexOptions, type IndexedSpan, KIT, MIGRATIONS, NO_ENRICHMENT, type NormalizedIndexResult, type NormalizedUsageSummary, type OpenSessionGraphOptions, type ReconcileCounts, type RefreshSummary, type ResolvedTask, type SessionGraph, type TaskEnrichment, type TaskResolution, type TaskResolver, type TranscriptOutcome, allSessionIds, allTaskIds, applyDelta, enrichTasks, indexCodexSource, indexTranscript, normalizedSessions, normalizedUsage, openSessionGraph, purgeTranscript, readIndexedText, reconcile, refreshCorpus, resetIndex, resolveConversationAlias, rollupSessions };
|
|
277
|
+
export { AUDIT_DDL, AUDIT_FACET, AUDIT_MIGRATION_NAME, AUDIT_TABLES, type BackfillOptions, type BackfillSummary, type ConversationSummary, DEFAULT_FACET_LIMIT, DERIVED_TABLES, DOMAIN_DDL, type DeltaSource, FACET_TABLE, type IndexOptions, type IndexedSpan, KIT, MIGRATIONS, NO_ENRICHMENT, type NormalizedIndexResult, type NormalizedUsageSummary, type OpenSessionGraphOptions, type ReconcileCounts, type RefreshOptions, type RefreshSummary, type ResolvedTask, type SessionGraph, type TaskEnrichment, type TaskResolution, type TaskResolver, type TranscriptOutcome, allSessionIds, allTaskIds, applyAudit, applyDelta, backfillFacets, enrichTasks, indexCodexSource, indexTranscript, normalizedSessions, normalizedUsage, openSessionGraph, purgeTranscript, readIndexedText, reconcile, refreshCorpus, resetIndex, resolveConversationAlias, rollupSessions };
|
package/dist/index.js
CHANGED
|
@@ -1,6 +1,134 @@
|
|
|
1
1
|
// src/graph.ts
|
|
2
2
|
import { EdgeTable, SpanFtsTables, WatermarkTable, openDatabase, runMigrations } from "@titan-design/store-sqlite";
|
|
3
3
|
|
|
4
|
+
// src/audit-schema.ts
|
|
5
|
+
var AUDIT_MIGRATION_NAME = "audit tables";
|
|
6
|
+
var AUDIT_TABLES = [
|
|
7
|
+
"request",
|
|
8
|
+
"tool_call",
|
|
9
|
+
"inbound",
|
|
10
|
+
"context_block",
|
|
11
|
+
"compaction",
|
|
12
|
+
"queue_op",
|
|
13
|
+
"session_signal",
|
|
14
|
+
"cost_state_observation"
|
|
15
|
+
];
|
|
16
|
+
var FACET_TABLE = "transcript_facet";
|
|
17
|
+
var AUDIT_DDL = `
|
|
18
|
+
CREATE TABLE IF NOT EXISTS request (
|
|
19
|
+
transcript_id INTEGER NOT NULL,
|
|
20
|
+
request_id TEXT NOT NULL,
|
|
21
|
+
byte_offset INTEGER NOT NULL, -- first line seen for this request
|
|
22
|
+
session_id TEXT NOT NULL,
|
|
23
|
+
message_id TEXT,
|
|
24
|
+
ts TEXT NOT NULL,
|
|
25
|
+
model TEXT NOT NULL,
|
|
26
|
+
input_tokens INTEGER NOT NULL DEFAULT 0,
|
|
27
|
+
cache_read_tokens INTEGER NOT NULL DEFAULT 0,
|
|
28
|
+
cache_creation_tokens INTEGER NOT NULL DEFAULT 0,
|
|
29
|
+
cache_creation_5m INTEGER NOT NULL DEFAULT 0,
|
|
30
|
+
cache_creation_1h INTEGER NOT NULL DEFAULT 0,
|
|
31
|
+
output_tokens INTEGER NOT NULL DEFAULT 0,
|
|
32
|
+
thinking_tokens INTEGER NOT NULL DEFAULT 0,
|
|
33
|
+
context_tokens INTEGER NOT NULL DEFAULT 0, -- input + cache_read + cache_creation
|
|
34
|
+
service_tier TEXT,
|
|
35
|
+
is_sidechain INTEGER NOT NULL DEFAULT 0,
|
|
36
|
+
-- rollup-owned, recomputed for touched sessions:
|
|
37
|
+
seq_in_session INTEGER,
|
|
38
|
+
gap_ms INTEGER, -- since previous request in the session
|
|
39
|
+
ctx_delta INTEGER, -- context_tokens - (prev.context_tokens + prev.output_tokens)
|
|
40
|
+
wake_cause TEXT,
|
|
41
|
+
wake_delivery TEXT,
|
|
42
|
+
wake_detail TEXT, -- tool name, channel sender, or NULL
|
|
43
|
+
wake_tool_family TEXT,
|
|
44
|
+
wake_mcp_server TEXT,
|
|
45
|
+
wake_offset INTEGER, -- byte_offset of the inbound row
|
|
46
|
+
PRIMARY KEY (transcript_id, request_id)
|
|
47
|
+
) WITHOUT ROWID;
|
|
48
|
+
CREATE INDEX IF NOT EXISTS idx_request_session_ts ON request(session_id, ts);
|
|
49
|
+
CREATE INDEX IF NOT EXISTS idx_request_ts ON request(ts);
|
|
50
|
+
CREATE INDEX IF NOT EXISTS idx_request_id ON request(request_id);
|
|
51
|
+
|
|
52
|
+
CREATE TABLE IF NOT EXISTS tool_call (
|
|
53
|
+
transcript_id INTEGER NOT NULL, byte_offset INTEGER NOT NULL, block_index INTEGER NOT NULL,
|
|
54
|
+
session_id TEXT NOT NULL, ts TEXT NOT NULL, tool_use_id TEXT NOT NULL,
|
|
55
|
+
name TEXT NOT NULL, family TEXT NOT NULL, mcp_server TEXT, input_chars INTEGER NOT NULL,
|
|
56
|
+
PRIMARY KEY (transcript_id, byte_offset, block_index)
|
|
57
|
+
) WITHOUT ROWID;
|
|
58
|
+
CREATE INDEX IF NOT EXISTS idx_tool_call_use ON tool_call(tool_use_id);
|
|
59
|
+
|
|
60
|
+
CREATE TABLE IF NOT EXISTS inbound (
|
|
61
|
+
transcript_id INTEGER NOT NULL, byte_offset INTEGER NOT NULL, block_index INTEGER NOT NULL,
|
|
62
|
+
session_id TEXT NOT NULL, ts TEXT NOT NULL,
|
|
63
|
+
cause TEXT NOT NULL, delivery TEXT NOT NULL, detail TEXT,
|
|
64
|
+
origin_server TEXT, from_name TEXT, msg_id TEXT, tool_use_id TEXT,
|
|
65
|
+
is_error INTEGER NOT NULL DEFAULT 0, content_hash TEXT NOT NULL, chars INTEGER NOT NULL,
|
|
66
|
+
queued_ms INTEGER, -- rollup-owned
|
|
67
|
+
PRIMARY KEY (transcript_id, byte_offset, block_index)
|
|
68
|
+
) WITHOUT ROWID;
|
|
69
|
+
CREATE INDEX IF NOT EXISTS idx_inbound_session ON inbound(session_id, byte_offset);
|
|
70
|
+
|
|
71
|
+
CREATE TABLE IF NOT EXISTS context_block (
|
|
72
|
+
transcript_id INTEGER NOT NULL, byte_offset INTEGER NOT NULL, block_index INTEGER NOT NULL,
|
|
73
|
+
session_id TEXT NOT NULL, ts TEXT NOT NULL, source TEXT NOT NULL,
|
|
74
|
+
tool_use_id TEXT, attachment_type TEXT, chars INTEGER NOT NULL, is_media INTEGER NOT NULL DEFAULT 0,
|
|
75
|
+
PRIMARY KEY (transcript_id, byte_offset, block_index)
|
|
76
|
+
) WITHOUT ROWID;
|
|
77
|
+
CREATE INDEX IF NOT EXISTS idx_context_block_session ON context_block(session_id, source);
|
|
78
|
+
|
|
79
|
+
CREATE TABLE IF NOT EXISTS compaction (
|
|
80
|
+
transcript_id INTEGER NOT NULL, byte_offset INTEGER NOT NULL,
|
|
81
|
+
session_id TEXT NOT NULL, ts TEXT NOT NULL, trigger TEXT,
|
|
82
|
+
pre_tokens INTEGER, post_tokens INTEGER, dropped_tokens INTEGER, duration_ms INTEGER,
|
|
83
|
+
mid_loop INTEGER, -- rollup-owned: previous inbound was a tool_result
|
|
84
|
+
PRIMARY KEY (transcript_id, byte_offset)
|
|
85
|
+
) WITHOUT ROWID;
|
|
86
|
+
|
|
87
|
+
CREATE TABLE IF NOT EXISTS queue_op (
|
|
88
|
+
transcript_id INTEGER NOT NULL, byte_offset INTEGER NOT NULL,
|
|
89
|
+
session_id TEXT NOT NULL, ts TEXT NOT NULL, operation TEXT NOT NULL,
|
|
90
|
+
content_hash TEXT, origin_server TEXT,
|
|
91
|
+
PRIMARY KEY (transcript_id, byte_offset)
|
|
92
|
+
) WITHOUT ROWID;
|
|
93
|
+
CREATE INDEX IF NOT EXISTS idx_queue_op_hash ON queue_op(session_id, content_hash);
|
|
94
|
+
|
|
95
|
+
CREATE TABLE IF NOT EXISTS session_signal (
|
|
96
|
+
transcript_id INTEGER NOT NULL, byte_offset INTEGER NOT NULL, block_index INTEGER NOT NULL,
|
|
97
|
+
session_id TEXT NOT NULL, ts TEXT NOT NULL, signal TEXT NOT NULL, detail TEXT, tool_use_id TEXT,
|
|
98
|
+
-- one Bash block can emit up to three signals (commit, push, pr_create); the signal name disambiguates them
|
|
99
|
+
PRIMARY KEY (transcript_id, byte_offset, block_index, signal)
|
|
100
|
+
) WITHOUT ROWID;
|
|
101
|
+
CREATE INDEX IF NOT EXISTS idx_signal_session ON session_signal(session_id, ts);
|
|
102
|
+
|
|
103
|
+
CREATE TABLE IF NOT EXISTS cost_state_observation (
|
|
104
|
+
transcript_id INTEGER NOT NULL, byte_offset INTEGER NOT NULL,
|
|
105
|
+
session_id TEXT NOT NULL, ts TEXT, total_cost_usd REAL NOT NULL, model_usage TEXT NOT NULL,
|
|
106
|
+
PRIMARY KEY (transcript_id, byte_offset)
|
|
107
|
+
) WITHOUT ROWID;
|
|
108
|
+
|
|
109
|
+
CREATE TABLE IF NOT EXISTS transcript_facet (
|
|
110
|
+
transcript_id INTEGER NOT NULL, facet TEXT NOT NULL,
|
|
111
|
+
version INTEGER NOT NULL, indexed_to INTEGER NOT NULL,
|
|
112
|
+
PRIMARY KEY (transcript_id, facet)
|
|
113
|
+
) WITHOUT ROWID;
|
|
114
|
+
`;
|
|
115
|
+
var AUDIT_COLUMNS = [
|
|
116
|
+
["session", "account", "TEXT"],
|
|
117
|
+
["turn", "wake_cause", "TEXT"],
|
|
118
|
+
["task", "estimate", "REAL"],
|
|
119
|
+
["pr", "review_rounds", "INTEGER"],
|
|
120
|
+
["pr", "closed_at", "TEXT"],
|
|
121
|
+
["pr", "outcome_checked_at", "TEXT"]
|
|
122
|
+
];
|
|
123
|
+
function applyAuditSchema(db) {
|
|
124
|
+
db.exec(AUDIT_DDL);
|
|
125
|
+
for (const [table, column, type] of AUDIT_COLUMNS) addColumnIfMissing(db, table, column, type);
|
|
126
|
+
}
|
|
127
|
+
function addColumnIfMissing(db, table, column, type) {
|
|
128
|
+
const present = db.prepare("SELECT 1 FROM pragma_table_info(?) WHERE name = ?").get(table, column);
|
|
129
|
+
if (!present) db.exec(`ALTER TABLE "${table}" ADD COLUMN "${column}" ${type}`);
|
|
130
|
+
}
|
|
131
|
+
|
|
4
132
|
// src/normalized-schema.ts
|
|
5
133
|
import { conversationRef } from "@titan-design/agent-protocol";
|
|
6
134
|
var NORMALIZED_DDL = `
|
|
@@ -188,6 +316,8 @@ var DERIVED_TABLES = [
|
|
|
188
316
|
"human_edit",
|
|
189
317
|
"file_checkpoint",
|
|
190
318
|
"subagent",
|
|
319
|
+
...AUDIT_TABLES,
|
|
320
|
+
FACET_TABLE,
|
|
191
321
|
"session_model_usage",
|
|
192
322
|
"session",
|
|
193
323
|
"fact",
|
|
@@ -205,7 +335,8 @@ var MIGRATIONS = [
|
|
|
205
335
|
{ version: 3, name: "normalized conversations and source evidence", up: (db) => {
|
|
206
336
|
db.exec(NORMALIZED_DDL);
|
|
207
337
|
backfillClaudeAliases(db);
|
|
208
|
-
} }
|
|
338
|
+
} },
|
|
339
|
+
{ version: 4, name: AUDIT_MIGRATION_NAME, up: applyAuditSchema }
|
|
209
340
|
];
|
|
210
341
|
|
|
211
342
|
// src/graph.ts
|
|
@@ -230,16 +361,152 @@ function allSessionIds(graph) {
|
|
|
230
361
|
return graph.db.prepare("SELECT session_id FROM session").all().map((r) => r.session_id);
|
|
231
362
|
}
|
|
232
363
|
|
|
364
|
+
// src/audit-apply.ts
|
|
365
|
+
var UPSERT_REQUEST = `
|
|
366
|
+
INSERT INTO request (transcript_id, request_id, byte_offset, session_id, message_id, ts, model,
|
|
367
|
+
input_tokens, cache_read_tokens, cache_creation_tokens, cache_creation_5m, cache_creation_1h,
|
|
368
|
+
output_tokens, thinking_tokens, context_tokens, service_tier, is_sidechain)
|
|
369
|
+
VALUES (@transcriptId, @requestId, @byteOffset, @sessionId, @messageId, @ts, @model,
|
|
370
|
+
@inputTokens, @cacheReadTokens, @cacheCreationTokens, @cacheCreation5mTokens, @cacheCreation1hTokens,
|
|
371
|
+
@outputTokens, @thinkingTokens, @inputTokens + @cacheReadTokens + @cacheCreationTokens, @serviceTier, @isSidechain)
|
|
372
|
+
ON CONFLICT (transcript_id, request_id) DO UPDATE SET
|
|
373
|
+
session_id = CASE WHEN excluded.byte_offset < byte_offset THEN excluded.session_id ELSE session_id END,
|
|
374
|
+
message_id = CASE WHEN excluded.byte_offset < byte_offset THEN excluded.message_id ELSE message_id END,
|
|
375
|
+
model = CASE WHEN excluded.byte_offset < byte_offset THEN excluded.model ELSE model END,
|
|
376
|
+
service_tier = CASE WHEN excluded.byte_offset < byte_offset THEN excluded.service_tier ELSE service_tier END,
|
|
377
|
+
is_sidechain = CASE WHEN excluded.byte_offset < byte_offset THEN excluded.is_sidechain ELSE is_sidechain END,
|
|
378
|
+
byte_offset = MIN(byte_offset, excluded.byte_offset),
|
|
379
|
+
ts = MIN(ts, excluded.ts),
|
|
380
|
+
input_tokens = MAX(input_tokens, excluded.input_tokens),
|
|
381
|
+
cache_read_tokens = MAX(cache_read_tokens, excluded.cache_read_tokens),
|
|
382
|
+
cache_creation_tokens = MAX(cache_creation_tokens, excluded.cache_creation_tokens),
|
|
383
|
+
cache_creation_5m = MAX(cache_creation_5m, excluded.cache_creation_5m),
|
|
384
|
+
cache_creation_1h = MAX(cache_creation_1h, excluded.cache_creation_1h),
|
|
385
|
+
output_tokens = MAX(output_tokens, excluded.output_tokens),
|
|
386
|
+
thinking_tokens = MAX(thinking_tokens, excluded.thinking_tokens),
|
|
387
|
+
context_tokens = MAX(input_tokens, excluded.input_tokens) + MAX(cache_read_tokens, excluded.cache_read_tokens)
|
|
388
|
+
+ MAX(cache_creation_tokens, excluded.cache_creation_tokens)`;
|
|
389
|
+
var INSERTS = {
|
|
390
|
+
toolCalls: `INSERT INTO tool_call (transcript_id, byte_offset, block_index, session_id, ts, tool_use_id, name, family, mcp_server, input_chars)
|
|
391
|
+
VALUES (@transcriptId, @byteOffset, @blockIndex, @sessionId, @ts, @toolUseId, @name, @family, @mcpServer, @inputChars)
|
|
392
|
+
ON CONFLICT DO NOTHING`,
|
|
393
|
+
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)
|
|
394
|
+
VALUES (@transcriptId, @byteOffset, @blockIndex, @sessionId, @ts, @cause, @delivery, @detail, @originServer, @fromName, @msgId, @toolUseId, @isError, @contentHash, @chars)
|
|
395
|
+
ON CONFLICT DO NOTHING`,
|
|
396
|
+
contextBlocks: `INSERT INTO context_block (transcript_id, byte_offset, block_index, session_id, ts, source, tool_use_id, attachment_type, chars, is_media)
|
|
397
|
+
VALUES (@transcriptId, @byteOffset, @blockIndex, @sessionId, @ts, @source, @toolUseId, @attachmentType, @chars, @isMedia)
|
|
398
|
+
ON CONFLICT DO NOTHING`,
|
|
399
|
+
compactions: `INSERT INTO compaction (transcript_id, byte_offset, session_id, ts, trigger, pre_tokens, post_tokens, dropped_tokens, duration_ms)
|
|
400
|
+
VALUES (@transcriptId, @byteOffset, @sessionId, @ts, @trigger, @preTokens, @postTokens, @droppedTokens, @durationMs)
|
|
401
|
+
ON CONFLICT DO NOTHING`,
|
|
402
|
+
queueOps: `INSERT INTO queue_op (transcript_id, byte_offset, session_id, ts, operation, content_hash, origin_server)
|
|
403
|
+
VALUES (@transcriptId, @byteOffset, @sessionId, @ts, @operation, @contentHash, @originServer)
|
|
404
|
+
ON CONFLICT DO NOTHING`,
|
|
405
|
+
signals: `INSERT INTO session_signal (transcript_id, byte_offset, block_index, session_id, ts, signal, detail, tool_use_id)
|
|
406
|
+
VALUES (@transcriptId, @byteOffset, @blockIndex, @sessionId, @ts, @signal, @detail, @toolUseId)
|
|
407
|
+
ON CONFLICT DO NOTHING`,
|
|
408
|
+
costStates: `INSERT INTO cost_state_observation (transcript_id, byte_offset, session_id, ts, total_cost_usd, model_usage)
|
|
409
|
+
VALUES (@transcriptId, @byteOffset, @sessionId, @ts, @totalCostUsd, @modelUsageJson)
|
|
410
|
+
ON CONFLICT DO NOTHING`
|
|
411
|
+
};
|
|
412
|
+
function applyAudit(db, transcriptId, delta) {
|
|
413
|
+
run(db, UPSERT_REQUEST, transcriptId, delta.requests);
|
|
414
|
+
for (const [list, sql] of Object.entries(INSERTS)) {
|
|
415
|
+
run(db, sql, transcriptId, delta[list]);
|
|
416
|
+
}
|
|
417
|
+
}
|
|
418
|
+
function run(db, sql, transcriptId, events) {
|
|
419
|
+
if (events.length === 0) return;
|
|
420
|
+
const statement = db.prepare(sql);
|
|
421
|
+
const names = [...new Set([...sql.matchAll(/@(\w+)/g)].map((m) => m[1]))];
|
|
422
|
+
for (const event of events) statement.run(bind(names, { ...event, transcriptId }));
|
|
423
|
+
}
|
|
424
|
+
function bind(names, row) {
|
|
425
|
+
return Object.fromEntries(names.map((name) => {
|
|
426
|
+
const value = row[name] ?? null;
|
|
427
|
+
return [name, typeof value === "boolean" ? Number(value) : value];
|
|
428
|
+
}));
|
|
429
|
+
}
|
|
430
|
+
|
|
431
|
+
// src/facet.ts
|
|
432
|
+
import { EXTRACT_VERSION, TranscriptParseError, extractTranscript } from "@titan-design/session-read";
|
|
433
|
+
var AUDIT_FACET = "audit";
|
|
434
|
+
var DEFAULT_FACET_LIMIT = 40;
|
|
435
|
+
async function backfillFacets(graph, transcripts, options = {}) {
|
|
436
|
+
const version = options.version ?? EXTRACT_VERSION;
|
|
437
|
+
const stale = staleTranscripts(graph, transcripts, version);
|
|
438
|
+
const visit = stale.slice(0, options.limit ?? DEFAULT_FACET_LIMIT);
|
|
439
|
+
const sessionIds = /* @__PURE__ */ new Set();
|
|
440
|
+
let backfilled = 0;
|
|
441
|
+
for (const candidate of visit) {
|
|
442
|
+
const touched = await backfillOne(graph, candidate, version);
|
|
443
|
+
if (!touched) continue;
|
|
444
|
+
backfilled += 1;
|
|
445
|
+
for (const id of touched) sessionIds.add(id);
|
|
446
|
+
}
|
|
447
|
+
return { backfilled, backlog: stale.length - visit.length, sessionIds: [...sessionIds] };
|
|
448
|
+
}
|
|
449
|
+
function staleTranscripts(graph, transcripts, version) {
|
|
450
|
+
const byPath = new Map(transcripts.map((t) => [t.displayPath, t]));
|
|
451
|
+
const versions = facetVersions(graph.db);
|
|
452
|
+
const stale = [];
|
|
453
|
+
for (const row of graph.transcripts.list()) {
|
|
454
|
+
const transcript = byPath.get(row.sourceKey);
|
|
455
|
+
if (!transcript || row.status !== "ok" || (versions.get(row.sourceId) ?? -1) >= version) continue;
|
|
456
|
+
stale.push({ row, transcript });
|
|
457
|
+
}
|
|
458
|
+
return stale.sort((a, b) => (b.row.fileMtime ?? "").localeCompare(a.row.fileMtime ?? ""));
|
|
459
|
+
}
|
|
460
|
+
function facetVersions(db) {
|
|
461
|
+
const rows = db.prepare(`SELECT transcript_id, version FROM ${FACET_TABLE} WHERE facet = ?`).all(AUDIT_FACET);
|
|
462
|
+
return new Map(rows.map((r) => [r.transcript_id, r.version]));
|
|
463
|
+
}
|
|
464
|
+
async function backfillOne(graph, { row, transcript }, version) {
|
|
465
|
+
let delta;
|
|
466
|
+
try {
|
|
467
|
+
delta = await extractTranscript(transcript.absolutePath, { untilByteOffset: row.lastOffset, subagentId: transcript.subagentId });
|
|
468
|
+
} catch (err) {
|
|
469
|
+
const status = unreadableStatus(err);
|
|
470
|
+
if (!status) throw err;
|
|
471
|
+
graph.transcripts.markStatus(row.sourceKey, status, err instanceof Error ? err.message : String(err));
|
|
472
|
+
return null;
|
|
473
|
+
}
|
|
474
|
+
graph.db.transaction(() => {
|
|
475
|
+
for (const table of AUDIT_TABLES) graph.db.prepare(`DELETE FROM "${table}" WHERE transcript_id = ?`).run(row.sourceId);
|
|
476
|
+
applyAudit(graph.db, row.sourceId, delta);
|
|
477
|
+
writeFacet(graph.db, row.sourceId, version, delta.lastByteOffset);
|
|
478
|
+
})();
|
|
479
|
+
return delta.sessions.map((s) => s.sessionId);
|
|
480
|
+
}
|
|
481
|
+
function unreadableStatus(err) {
|
|
482
|
+
if (err instanceof TranscriptParseError) return "quarantined";
|
|
483
|
+
if (err?.code === "ENOENT") return "missing";
|
|
484
|
+
return null;
|
|
485
|
+
}
|
|
486
|
+
function writeFacet(db, transcriptId, version, indexedTo) {
|
|
487
|
+
db.prepare(`
|
|
488
|
+
INSERT INTO ${FACET_TABLE} (transcript_id, facet, version, indexed_to) VALUES (?, ?, ?, ?)
|
|
489
|
+
ON CONFLICT (transcript_id, facet) DO UPDATE SET version = excluded.version, indexed_to = excluded.indexed_to`).run(transcriptId, AUDIT_FACET, version, indexedTo);
|
|
490
|
+
}
|
|
491
|
+
function advanceFacet(db, transcriptId, fromByteOffset, indexedTo, version = EXTRACT_VERSION) {
|
|
492
|
+
if (fromByteOffset === 0) {
|
|
493
|
+
writeFacet(db, transcriptId, version, indexedTo);
|
|
494
|
+
return;
|
|
495
|
+
}
|
|
496
|
+
db.prepare(`UPDATE ${FACET_TABLE} SET indexed_to = ? WHERE transcript_id = ? AND facet = ? AND version = ?`).run(indexedTo, transcriptId, AUDIT_FACET, version);
|
|
497
|
+
}
|
|
498
|
+
|
|
233
499
|
// src/apply.ts
|
|
234
500
|
import { sessionRef } from "@titan-design/session-read";
|
|
235
|
-
function applyDelta(graph, transcriptId, delta) {
|
|
501
|
+
function applyDelta(graph, transcriptId, delta, source = {}) {
|
|
236
502
|
graph.db.transaction(() => {
|
|
237
503
|
applyFacts(graph.db, transcriptId, delta);
|
|
238
|
-
applySessions(graph.db, transcriptId, delta);
|
|
504
|
+
applySessions(graph.db, transcriptId, delta, source.account ?? null);
|
|
239
505
|
backfillClaudeAliases(graph.db, delta.sessions.map((s) => s.sessionId));
|
|
240
506
|
applyAssets(graph.db, delta);
|
|
241
507
|
applyPhases(graph.db, transcriptId, delta);
|
|
242
508
|
applyLinkedRows(graph, transcriptId, delta);
|
|
509
|
+
applyAudit(graph.db, transcriptId, delta);
|
|
243
510
|
})();
|
|
244
511
|
}
|
|
245
512
|
var INSERT_FACT = `
|
|
@@ -255,8 +522,8 @@ function applyFacts(db, transcriptId, delta) {
|
|
|
255
522
|
}
|
|
256
523
|
}
|
|
257
524
|
var UPSERT_SESSION = `
|
|
258
|
-
INSERT INTO session (session_id, transcript_id, started_at, ended_at, start_type, cwd, git_branch, ai_title, seed_prompt, cli_version, turn_count, commit_count, push_count)
|
|
259
|
-
VALUES (@sessionId, @transcriptId, @startedAt, @endedAt, @startType, @cwd, @gitBranch, @aiTitle, @seedPrompt, @cliVersion, @turnDelta, @commitDelta, @pushDelta)
|
|
525
|
+
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)
|
|
526
|
+
VALUES (@sessionId, @transcriptId, @startedAt, @endedAt, @startType, @cwd, @gitBranch, @aiTitle, @seedPrompt, @cliVersion, @account, @turnDelta, @commitDelta, @pushDelta)
|
|
260
527
|
ON CONFLICT (session_id) DO UPDATE SET
|
|
261
528
|
started_at = MIN(COALESCE(started_at, excluded.started_at), COALESCE(excluded.started_at, started_at)),
|
|
262
529
|
ended_at = MAX(COALESCE(ended_at, excluded.ended_at), COALESCE(excluded.ended_at, ended_at)),
|
|
@@ -270,22 +537,13 @@ var UPSERT_SESSION = `
|
|
|
270
537
|
ai_title = COALESCE(excluded.ai_title, ai_title),
|
|
271
538
|
seed_prompt = COALESCE(seed_prompt, excluded.seed_prompt),
|
|
272
539
|
cli_version = COALESCE(excluded.cli_version, cli_version),
|
|
540
|
+
account = COALESCE(excluded.account, account),
|
|
273
541
|
turn_count = turn_count + excluded.turn_count,
|
|
274
542
|
commit_count = commit_count + excluded.commit_count,
|
|
275
543
|
push_count = push_count + excluded.push_count`;
|
|
276
|
-
|
|
277
|
-
INSERT INTO session_model_usage (session_id, model, input_tokens, output_tokens, cache_read_tokens, cache_creation_tokens, thinking_tokens, request_count)
|
|
278
|
-
VALUES (@sessionId, @model, @inputTokens, @outputTokens, @cacheReadTokens, @cacheCreationTokens, @thinkingTokens, @requestCount)
|
|
279
|
-
ON CONFLICT (session_id, model) DO UPDATE SET
|
|
280
|
-
input_tokens = input_tokens + excluded.input_tokens, output_tokens = output_tokens + excluded.output_tokens,
|
|
281
|
-
cache_read_tokens = cache_read_tokens + excluded.cache_read_tokens,
|
|
282
|
-
cache_creation_tokens = cache_creation_tokens + excluded.cache_creation_tokens,
|
|
283
|
-
thinking_tokens = thinking_tokens + excluded.thinking_tokens, request_count = request_count + excluded.request_count`;
|
|
284
|
-
function applySessions(db, transcriptId, delta) {
|
|
544
|
+
function applySessions(db, transcriptId, delta, account) {
|
|
285
545
|
const upsertSession = db.prepare(UPSERT_SESSION);
|
|
286
|
-
for (const s of delta.sessions) upsertSession.run({ ...s, transcriptId });
|
|
287
|
-
const upsertUsage = db.prepare(UPSERT_USAGE);
|
|
288
|
-
for (const u of delta.usage) upsertUsage.run(u);
|
|
546
|
+
for (const s of delta.sessions) upsertSession.run({ ...s, transcriptId, account });
|
|
289
547
|
}
|
|
290
548
|
var ASSET_UPSERTS = {
|
|
291
549
|
prs: `INSERT INTO pr (pr_ref, number, repo, title, url) VALUES (@prRef, @number, @repo, @title, @url)
|
|
@@ -368,11 +626,97 @@ function purgeTranscript(graph, transcriptId) {
|
|
|
368
626
|
graph.db.prepare(`DELETE FROM "${table}" WHERE session_id IN (SELECT session_id FROM session WHERE transcript_id = ?)`).run(transcriptId);
|
|
369
627
|
}
|
|
370
628
|
graph.db.prepare(`DELETE FROM "${KIT.edge}" WHERE fact_id IN (SELECT fact_id FROM fact WHERE transcript_id = ?)`).run(transcriptId);
|
|
629
|
+
for (const table of [...AUDIT_TABLES, FACET_TABLE]) {
|
|
630
|
+
graph.db.prepare(`DELETE FROM "${table}" WHERE transcript_id = ?`).run(transcriptId);
|
|
631
|
+
}
|
|
371
632
|
graph.db.prepare("DELETE FROM fact WHERE transcript_id = ?").run(transcriptId);
|
|
372
633
|
graph.db.prepare("DELETE FROM session WHERE transcript_id = ?").run(transcriptId);
|
|
373
634
|
})();
|
|
374
635
|
}
|
|
375
636
|
|
|
637
|
+
// src/audit-rollup.ts
|
|
638
|
+
var IN_BATCH = "SELECT value FROM json_each(@sessionIds)";
|
|
639
|
+
var REQUEST_ORDER = `
|
|
640
|
+
WITH ordered AS (
|
|
641
|
+
SELECT transcript_id, request_id, ts, context_tokens,
|
|
642
|
+
ROW_NUMBER() OVER w - 1 AS seq,
|
|
643
|
+
LAG(ts) OVER w AS prev_ts,
|
|
644
|
+
LAG(context_tokens) OVER w AS prev_context,
|
|
645
|
+
LAG(output_tokens) OVER w AS prev_output
|
|
646
|
+
FROM request WHERE session_id IN (${IN_BATCH})
|
|
647
|
+
WINDOW w AS (PARTITION BY session_id ORDER BY ts, byte_offset, transcript_id, request_id)
|
|
648
|
+
)
|
|
649
|
+
UPDATE request SET seq_in_session = ordered.seq,
|
|
650
|
+
gap_ms = CAST(ROUND((julianday(ordered.ts) - julianday(ordered.prev_ts)) * 86400000) AS INTEGER),
|
|
651
|
+
ctx_delta = ordered.context_tokens - (ordered.prev_context + ordered.prev_output)
|
|
652
|
+
FROM ordered WHERE request.transcript_id = ordered.transcript_id AND request.request_id = ordered.request_id`;
|
|
653
|
+
var REQUEST_WAKE = `
|
|
654
|
+
WITH hit AS (
|
|
655
|
+
SELECT r.transcript_id, r.request_id,
|
|
656
|
+
(SELECT MAX(i.byte_offset) FROM inbound i
|
|
657
|
+
WHERE i.transcript_id = r.transcript_id AND i.session_id = r.session_id AND i.byte_offset < r.byte_offset) AS wake_offset
|
|
658
|
+
FROM request r WHERE r.session_id IN (${IN_BATCH})
|
|
659
|
+
),
|
|
660
|
+
tools AS (
|
|
661
|
+
SELECT transcript_id, tool_use_id, name, family, mcp_server,
|
|
662
|
+
ROW_NUMBER() OVER (PARTITION BY transcript_id, tool_use_id ORDER BY byte_offset, block_index) AS pick
|
|
663
|
+
FROM tool_call WHERE session_id IN (${IN_BATCH})
|
|
664
|
+
),
|
|
665
|
+
wake AS (
|
|
666
|
+
SELECT hit.transcript_id, hit.request_id, hit.wake_offset, i.cause, i.delivery, i.detail, i.from_name,
|
|
667
|
+
t.name AS tool_name, t.family, t.mcp_server
|
|
668
|
+
FROM hit
|
|
669
|
+
LEFT JOIN inbound i ON i.transcript_id = hit.transcript_id AND i.byte_offset = hit.wake_offset
|
|
670
|
+
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)
|
|
671
|
+
LEFT JOIN tools t ON t.transcript_id = i.transcript_id AND t.tool_use_id = i.tool_use_id AND t.pick = 1
|
|
672
|
+
)
|
|
673
|
+
UPDATE request SET
|
|
674
|
+
wake_cause = CASE WHEN wake.cause IS NULL THEN 'session_start'
|
|
675
|
+
WHEN wake.tool_name = 'AskUserQuestion' THEN 'ask_user_answer' ELSE wake.cause END,
|
|
676
|
+
wake_delivery = wake.delivery,
|
|
677
|
+
wake_detail = COALESCE(wake.tool_name, wake.from_name, wake.detail),
|
|
678
|
+
wake_tool_family = wake.family,
|
|
679
|
+
wake_mcp_server = wake.mcp_server,
|
|
680
|
+
wake_offset = wake.wake_offset
|
|
681
|
+
FROM wake WHERE request.transcript_id = wake.transcript_id AND request.request_id = wake.request_id`;
|
|
682
|
+
var INBOUND_QUEUED = `
|
|
683
|
+
UPDATE inbound SET queued_ms = (
|
|
684
|
+
SELECT CAST(ROUND((julianday(inbound.ts) - julianday(q.ts)) * 86400000) AS INTEGER)
|
|
685
|
+
FROM queue_op q
|
|
686
|
+
WHERE q.transcript_id = inbound.transcript_id AND q.session_id = inbound.session_id
|
|
687
|
+
AND q.operation = 'enqueue' AND q.content_hash = inbound.content_hash AND q.byte_offset < inbound.byte_offset
|
|
688
|
+
ORDER BY q.byte_offset DESC LIMIT 1)
|
|
689
|
+
WHERE session_id IN (${IN_BATCH})`;
|
|
690
|
+
var COMPACTION_MID_LOOP = `
|
|
691
|
+
UPDATE compaction SET mid_loop = COALESCE((
|
|
692
|
+
SELECT i.delivery = 'tool_result' FROM inbound i
|
|
693
|
+
WHERE i.transcript_id = compaction.transcript_id AND i.session_id = compaction.session_id AND i.byte_offset < compaction.byte_offset
|
|
694
|
+
ORDER BY i.byte_offset DESC, i.block_index DESC LIMIT 1), 0)
|
|
695
|
+
WHERE session_id IN (${IN_BATCH})`;
|
|
696
|
+
var TURN_WAKE = `
|
|
697
|
+
UPDATE turn SET wake_cause = (
|
|
698
|
+
SELECT i.cause FROM fact f JOIN inbound i ON i.transcript_id = f.transcript_id AND i.byte_offset = f.byte_offset
|
|
699
|
+
WHERE f.fact_id = turn.fact_id_start ORDER BY i.block_index LIMIT 1)
|
|
700
|
+
WHERE session_id IN (${IN_BATCH})`;
|
|
701
|
+
var CLEAR_USAGE = `
|
|
702
|
+
DELETE FROM session_model_usage
|
|
703
|
+
WHERE session_id IN (${IN_BATCH}) AND session_id IN (SELECT session_id FROM request WHERE session_id IN (${IN_BATCH}))`;
|
|
704
|
+
var RECOMPUTE_USAGE = `
|
|
705
|
+
WITH ranked AS (
|
|
706
|
+
SELECT *, ROW_NUMBER() OVER (PARTITION BY session_id, request_id ORDER BY ts, transcript_id) AS pick
|
|
707
|
+
FROM request WHERE session_id IN (${IN_BATCH})
|
|
708
|
+
)
|
|
709
|
+
INSERT INTO session_model_usage (session_id, model, input_tokens, output_tokens, cache_read_tokens, cache_creation_tokens, thinking_tokens, request_count)
|
|
710
|
+
SELECT session_id, model, SUM(input_tokens), SUM(output_tokens), SUM(cache_read_tokens), SUM(cache_creation_tokens), SUM(thinking_tokens), COUNT(*)
|
|
711
|
+
FROM ranked WHERE pick = 1 GROUP BY session_id, model`;
|
|
712
|
+
var STEPS = [REQUEST_ORDER, REQUEST_WAKE, INBOUND_QUEUED, COMPACTION_MID_LOOP, TURN_WAKE, CLEAR_USAGE, RECOMPUTE_USAGE];
|
|
713
|
+
function prepareAuditRollup(db) {
|
|
714
|
+
const statements = STEPS.map((sql) => db.prepare(sql));
|
|
715
|
+
return (sessionIds) => {
|
|
716
|
+
for (const statement of statements) statement.run({ sessionIds });
|
|
717
|
+
};
|
|
718
|
+
}
|
|
719
|
+
|
|
376
720
|
// src/rollup.ts
|
|
377
721
|
var BATCH = 400;
|
|
378
722
|
var ROLLUP = `
|
|
@@ -409,12 +753,14 @@ function rollupSessions(graph, sessionIds) {
|
|
|
409
753
|
if (unique.length === 0) return 0;
|
|
410
754
|
const aggregate = graph.db.prepare(ROLLUP);
|
|
411
755
|
const renumber = graph.db.prepare(RENUMBER_TURNS);
|
|
756
|
+
const audit = prepareAuditRollup(graph.db);
|
|
412
757
|
return graph.db.transaction(() => {
|
|
413
758
|
let updated = 0;
|
|
414
759
|
for (let i = 0; i < unique.length; i += BATCH) {
|
|
415
760
|
const batch = JSON.stringify(unique.slice(i, i + BATCH));
|
|
416
761
|
renumber.run({ sessionIds: batch });
|
|
417
762
|
updated += aggregate.run({ sessionIds: batch }).changes;
|
|
763
|
+
audit(batch);
|
|
418
764
|
}
|
|
419
765
|
return updated;
|
|
420
766
|
})();
|
|
@@ -443,7 +789,7 @@ function reconcile(graph) {
|
|
|
443
789
|
// src/refresh.ts
|
|
444
790
|
import { promises as fs } from "fs";
|
|
445
791
|
import { contentHash, resumePoint } from "@titan-design/locator";
|
|
446
|
-
import { TranscriptParseError, extractTranscript } from "@titan-design/session-read";
|
|
792
|
+
import { TranscriptParseError as TranscriptParseError2, extractTranscript as extractTranscript2 } from "@titan-design/session-read";
|
|
447
793
|
|
|
448
794
|
// src/tasks.ts
|
|
449
795
|
import { taskRef } from "@titan-design/session-read";
|
|
@@ -500,14 +846,15 @@ async function indexTranscript(graph, transcript, options = {}) {
|
|
|
500
846
|
return { ...base, status: "unchanged", facts: 0 };
|
|
501
847
|
}
|
|
502
848
|
try {
|
|
503
|
-
const delta = await
|
|
849
|
+
const delta = await extractTranscript2(transcript.absolutePath, {
|
|
504
850
|
fromByteOffset: point.start,
|
|
505
851
|
priorPrefixHash: point.state === "rewritten" ? null : row.prefixHash,
|
|
506
852
|
subagentId: transcript.subagentId
|
|
507
853
|
});
|
|
508
854
|
const rewound = point.state === "rewritten" || delta.restartedFromZero;
|
|
509
855
|
if (rewound) purgeTranscript(graph, row.sourceId);
|
|
510
|
-
applyDelta(graph, row.sourceId, delta);
|
|
856
|
+
applyDelta(graph, row.sourceId, delta, { account: transcript.account });
|
|
857
|
+
advanceFacet(graph.db, row.sourceId, rewound ? 0 : point.start, delta.lastByteOffset);
|
|
511
858
|
const stat2 = await fs.stat(transcript.absolutePath);
|
|
512
859
|
graph.transcripts.advance(transcript.displayPath, {
|
|
513
860
|
lastOffset: delta.lastByteOffset,
|
|
@@ -521,13 +868,13 @@ async function indexTranscript(graph, transcript, options = {}) {
|
|
|
521
868
|
const tasks = taskIds.length > 0 ? await enrichTasks(graph, options.resolveTasks, taskIds) : NO_ENRICHMENT;
|
|
522
869
|
return { ...base, sessionIds, tasks, status: rewound ? "rewound" : "indexed", facts: delta.facts.length };
|
|
523
870
|
} catch (err) {
|
|
524
|
-
if (!(err instanceof
|
|
871
|
+
if (!(err instanceof TranscriptParseError2)) throw err;
|
|
525
872
|
graph.transcripts.markStatus(transcript.displayPath, "quarantined", err.message);
|
|
526
873
|
return { ...base, status: "quarantined", facts: 0, reason: err.message };
|
|
527
874
|
}
|
|
528
875
|
}
|
|
529
876
|
async function refreshCorpus(graph, transcripts, options = {}) {
|
|
530
|
-
const { resolveTasks, ...perTranscript } = options;
|
|
877
|
+
const { resolveTasks, full, facetLimit, ...perTranscript } = options;
|
|
531
878
|
const counts = { indexed: 0, unchanged: 0, rewound: 0, missing: 0, quarantined: 0 };
|
|
532
879
|
const touched = [];
|
|
533
880
|
let facts = 0;
|
|
@@ -537,11 +884,14 @@ async function refreshCorpus(graph, transcripts, options = {}) {
|
|
|
537
884
|
facts += outcome.facts;
|
|
538
885
|
touched.push(...outcome.sessionIds);
|
|
539
886
|
}
|
|
540
|
-
const
|
|
887
|
+
const facets = await backfillFacets(graph, transcripts, { limit: facetLimit });
|
|
888
|
+
touched.push(...facets.sessionIds);
|
|
889
|
+
const turnsRolledUp = rollupSessions(graph, full ? allSessionIds(graph) : touched);
|
|
541
890
|
const reconciled = reconcile(graph);
|
|
542
891
|
const tasks = await enrichTasks(graph, resolveTasks, allTaskIds(graph));
|
|
543
892
|
const markedMissing = await markMissing(graph, transcripts);
|
|
544
|
-
|
|
893
|
+
const facetSummary = { facetsBackfilled: facets.backfilled, facetBacklog: facets.backlog };
|
|
894
|
+
return { transcripts: transcripts.length, ...counts, facts, turnsRolledUp, reconciled, tasks, markedMissing, ...facetSummary };
|
|
545
895
|
}
|
|
546
896
|
async function markMissing(graph, discovered) {
|
|
547
897
|
const present = new Set(discovered.map((t) => t.displayPath));
|
|
@@ -775,14 +1125,22 @@ function normalizedUsage(graph, ref) {
|
|
|
775
1125
|
return accumulator.summaries();
|
|
776
1126
|
}
|
|
777
1127
|
export {
|
|
1128
|
+
AUDIT_DDL,
|
|
1129
|
+
AUDIT_FACET,
|
|
1130
|
+
AUDIT_MIGRATION_NAME,
|
|
1131
|
+
AUDIT_TABLES,
|
|
1132
|
+
DEFAULT_FACET_LIMIT,
|
|
778
1133
|
DERIVED_TABLES,
|
|
779
1134
|
DOMAIN_DDL,
|
|
1135
|
+
FACET_TABLE,
|
|
780
1136
|
KIT,
|
|
781
1137
|
MIGRATIONS,
|
|
782
1138
|
NO_ENRICHMENT,
|
|
783
1139
|
allSessionIds,
|
|
784
1140
|
allTaskIds,
|
|
1141
|
+
applyAudit,
|
|
785
1142
|
applyDelta,
|
|
1143
|
+
backfillFacets,
|
|
786
1144
|
enrichTasks,
|
|
787
1145
|
indexCodexSource,
|
|
788
1146
|
indexTranscript,
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/graph.ts","../src/normalized-schema.ts","../src/schema.ts","../src/apply.ts","../src/purge.ts","../src/rollup.ts","../src/refresh.ts","../src/tasks.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 { 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 { 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 \"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];\n","import { 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 and usage\n * rows accumulate; ref-keyed assets insert-if-absent with COALESCE merges that\n * mirror `EventFolder`'s rules.\n */\nexport function applyDelta(graph: SessionGraph, transcriptId: number, delta: TranscriptDelta): void {\n graph.db.transaction(() => {\n applyFacts(graph.db, transcriptId, delta);\n applySessions(graph.db, transcriptId, delta);\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 })();\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, turn_count, commit_count, push_count)\n VALUES (@sessionId, @transcriptId, @startedAt, @endedAt, @startType, @cwd, @gitBranch, @aiTitle, @seedPrompt, @cliVersion, @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 turn_count = turn_count + excluded.turn_count,\n commit_count = commit_count + excluded.commit_count,\n push_count = push_count + excluded.push_count`;\n\nconst UPSERT_USAGE = `\n INSERT INTO session_model_usage (session_id, model, input_tokens, output_tokens, cache_read_tokens, cache_creation_tokens, thinking_tokens, request_count)\n VALUES (@sessionId, @model, @inputTokens, @outputTokens, @cacheReadTokens, @cacheCreationTokens, @thinkingTokens, @requestCount)\n ON CONFLICT (session_id, model) DO UPDATE SET\n input_tokens = input_tokens + excluded.input_tokens, output_tokens = output_tokens + excluded.output_tokens,\n cache_read_tokens = cache_read_tokens + excluded.cache_read_tokens,\n cache_creation_tokens = cache_creation_tokens + excluded.cache_creation_tokens,\n thinking_tokens = thinking_tokens + excluded.thinking_tokens, request_count = request_count + excluded.request_count`;\n\nfunction applySessions(db: Db, transcriptId: number, delta: TranscriptDelta): void {\n const upsertSession = db.prepare(UPSERT_SESSION);\n for (const s of delta.sessions) upsertSession.run({ ...s, transcriptId });\n const upsertUsage = db.prepare(UPSERT_USAGE);\n for (const u of delta.usage) upsertUsage.run(u);\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 { 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\"] 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 */\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 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 { 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 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 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 }\n return updated;\n })();\n}\n\n/** A merge sighting and the `pr-link` naming the same PR routinely live in different transcripts; fold at pass end. */\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 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 { allSessionIds, type SessionGraph } from \"./graph.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}\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);\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 markedMissing: number;\n}\n\n/**\n * One pass over a corpus: index every transcript, roll up the sessions that\n * changed, reconcile cross-transcript observations, enrich tasks, and mark rows\n * whose source file is gone. Idempotent: a second pass over unchanged files\n * 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: IndexOptions & { full?: boolean } = {}): Promise<RefreshSummary> {\n const { resolveTasks, ...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 turnsRolledUp = rollupSessions(graph, options.full ? allSessionIds(graph) : touched);\n const reconciled = reconcile(graph);\n const tasks = await enrichTasks(graph, resolveTasks, allTaskIds(graph));\n const markedMissing = await markMissing(graph, transcripts);\n return { transcripts: transcripts.length, ...counts, facts, turnsRolledUp, reconciled, tasks, markedMissing };\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 { 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}\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) VALUES (@taskRef, @taskId, @initiative, @title, @status)\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\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 }).changes;\n }\n return applied;\n })();\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(J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AO,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","stat","contentHash","conversationRef","SPAN_TEXT_CAP","conversationRef","conversationRef","contentHash","SPAN_TEXT_CAP","contentHash"]}
|
|
1
|
+
{"version":3,"sources":["../src/graph.ts","../src/audit-schema.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/tasks.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 { 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 { 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 \"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];\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 { 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\"] 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/** A merge sighting and the `pr-link` naming the same PR routinely live in different transcripts; fold at pass end. */\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 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 { 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}\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 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, reconcile\n * cross-transcript observations, enrich tasks, and mark rows whose source file\n * is gone. Idempotent: a second pass over unchanged files\n * 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, 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 const reconciled = reconcile(graph);\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, 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 { 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}\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) VALUES (@taskRef, @taskId, @initiative, @title, @status)\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\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 }).changes;\n }\n return applied;\n })();\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;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;AAAA;AAAA;AAAA;AAoGlB,IAAM,gBAAgB;AAAA,EAC3B,CAAC,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,EAAE,KAAI,GAAG,GAAsC;AAAO,aAAO,OAAO,UAAU,WAAW,QAAQ;AAAA,IAAM;AAC/J,WAAO;AAAA,MAAE,WAAU,EAAE;AAAA,MAAI,SAAQ,EAAE;AAAA,MAAQ,UAAS,EAAE;AAAA,MAAU,WAAU,EAAE;AAAA,MAAU,OAAM,KAAK,OAAO;AAAA,MAAE,WAAU,EAAE;AAAA,MACpH,SAAQ;AAAA,MAAK,KAAI,KAAK,KAAK;AAAA,MAAE,WAAU,KAAK,YAAY;AAAA,MAAE,WAAU,EAAE;AAAA,MAAM,aAAY;AAAA,MAAK,WAAU;AAAA,IAAK;AAAA,EAChH,CAAC;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","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.
|
|
3
|
+
"version": "0.6.0",
|
|
4
4
|
"description": "Fold session events into the activity graph on store-sqlite",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/index.js",
|
|
@@ -33,8 +33,8 @@
|
|
|
33
33
|
"dependencies": {
|
|
34
34
|
"@titan-design/cluster": "^0.1.2",
|
|
35
35
|
"@titan-design/locator": "^0.2.1",
|
|
36
|
-
"@titan-design/session-read": "^0.
|
|
37
|
-
"@titan-design/store-sqlite": "^0.3.
|
|
36
|
+
"@titan-design/session-read": "^0.5.0",
|
|
37
|
+
"@titan-design/store-sqlite": "^0.3.1",
|
|
38
38
|
"@titan-design/agent-protocol": "^0.1.0"
|
|
39
39
|
},
|
|
40
40
|
"scripts": {
|