pi-mega-compact 0.7.8 → 0.7.9

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.
Files changed (112) hide show
  1. package/README.md +11 -12
  2. package/dist/extensions/dashboard-server/helpers.js +37 -0
  3. package/dist/extensions/dashboard-server/html/all-repos-tab.js +26 -0
  4. package/dist/extensions/dashboard-server/html/body-open.js +23 -0
  5. package/dist/extensions/dashboard-server/html/current-repo-tab.js +130 -0
  6. package/dist/extensions/dashboard-server/html/head-open.js +16 -0
  7. package/dist/extensions/dashboard-server/html/high-score-tab.js +25 -0
  8. package/dist/extensions/dashboard-server/html/repo-detail-modal.js +26 -0
  9. package/dist/extensions/dashboard-server/html/script.js +259 -0
  10. package/dist/extensions/dashboard-server/html/styles.js +103 -0
  11. package/dist/extensions/dashboard-server/html/summary-tab.js +19 -0
  12. package/dist/extensions/dashboard-server/html-template.js +41 -0
  13. package/dist/extensions/dashboard-server/html.js +756 -0
  14. package/dist/extensions/dashboard-server/index-reader.js +133 -0
  15. package/dist/extensions/dashboard-server/server.js +370 -0
  16. package/dist/extensions/dashboard-server/snapshot.js +43 -0
  17. package/dist/extensions/dashboard-server/state.js +30 -0
  18. package/dist/extensions/dashboard-server/types.js +5 -0
  19. package/dist/extensions/dashboard-server.js +7 -1315
  20. package/dist/extensions/mega-commands.js +162 -134
  21. package/dist/extensions/mega-compact.test.js +90 -21
  22. package/dist/extensions/mega-conflict-cmds.js +5 -1
  23. package/dist/extensions/mega-dashboard-cmds.js +29 -22
  24. package/dist/extensions/mega-db-cmds.js +11 -2
  25. package/dist/extensions/mega-events/agent-handlers.js +173 -0
  26. package/dist/extensions/mega-events/compact-handlers.js +133 -0
  27. package/dist/extensions/mega-events/context-handler.js +249 -0
  28. package/dist/extensions/mega-events/register.js +21 -0
  29. package/dist/extensions/mega-events/session-handlers.js +142 -0
  30. package/dist/extensions/mega-events.js +15 -699
  31. package/dist/extensions/mega-pipeline/compact.js +324 -0
  32. package/dist/extensions/mega-pipeline/memory-review.js +38 -0
  33. package/dist/extensions/mega-pipeline/recall.js +147 -0
  34. package/dist/extensions/mega-pipeline.js +9 -480
  35. package/dist/extensions/mega-runtime/helpers.js +40 -0
  36. package/dist/extensions/mega-runtime/query.js +29 -0
  37. package/dist/extensions/mega-runtime/state.js +711 -0
  38. package/dist/extensions/mega-runtime/widget.js +197 -0
  39. package/dist/extensions/mega-runtime.js +15 -947
  40. package/dist/src/store/sqlite/checkpoints.js +145 -0
  41. package/dist/src/store/sqlite/connection.js +35 -0
  42. package/dist/src/store/sqlite/dedup-mirror.js +64 -0
  43. package/dist/src/store/sqlite/foundation.js +38 -0
  44. package/dist/src/store/sqlite/global-index.js +224 -0
  45. package/dist/src/store/sqlite/index-store.js +167 -0
  46. package/dist/src/store/sqlite/maintenance.js +235 -0
  47. package/dist/src/store/sqlite/memories.js +164 -0
  48. package/dist/src/store/sqlite/memory.js +54 -0
  49. package/dist/src/store/sqlite/meta.js +82 -0
  50. package/dist/src/store/sqlite/minhash-lsh.js +47 -0
  51. package/dist/src/store/sqlite/model-snapshots.js +47 -0
  52. package/dist/src/store/sqlite/raptor.js +57 -0
  53. package/dist/src/store/sqlite/raw-transcript.js +134 -0
  54. package/dist/src/store/sqlite/schema.js +250 -0
  55. package/dist/src/store/sqlite/session-state.js +28 -0
  56. package/dist/src/store/sqlite/sessions.js +39 -0
  57. package/dist/src/store/sqlite/stats.js +66 -0
  58. package/dist/src/store/sqlite/transaction.js +19 -0
  59. package/dist/src/store/sqlite/utils.js +120 -0
  60. package/dist/src/store/sqlite.js +20 -1607
  61. package/dist/src/vectorStore/add.js +260 -0
  62. package/dist/src/vectorStore/dedup.js +52 -0
  63. package/dist/src/vectorStore/index.js +10 -0
  64. package/dist/src/vectorStore/queries.js +83 -0
  65. package/dist/src/vectorStore/search.js +95 -0
  66. package/dist/src/vectorStore/session.js +19 -0
  67. package/dist/src/vectorStore/store.js +105 -0
  68. package/dist/src/vectorStore/types.js +6 -0
  69. package/dist/src/vectorStore/utils.js +23 -0
  70. package/extensions/dashboard-server/html.ts +758 -0
  71. package/extensions/dashboard-server/index-reader.ts +130 -0
  72. package/extensions/dashboard-server/server.ts +358 -0
  73. package/extensions/dashboard-server/snapshot.ts +44 -0
  74. package/extensions/dashboard-server/state.ts +33 -0
  75. package/extensions/dashboard-server/types.ts +134 -0
  76. package/extensions/dashboard-server.ts +7 -1431
  77. package/extensions/mega-commands.ts +33 -10
  78. package/extensions/mega-compact.test.ts +198 -43
  79. package/extensions/mega-conflict-cmds.ts +6 -2
  80. package/extensions/mega-dashboard-cmds.ts +30 -23
  81. package/extensions/mega-db-cmds.ts +11 -3
  82. package/extensions/mega-events/agent-handlers.ts +214 -0
  83. package/extensions/mega-events/compact-handlers.ts +164 -0
  84. package/extensions/mega-events/context-handler.ts +290 -0
  85. package/extensions/mega-events/register.ts +37 -0
  86. package/extensions/mega-events/session-handlers.ts +165 -0
  87. package/extensions/mega-events.ts +15 -780
  88. package/extensions/mega-pipeline/compact.ts +366 -0
  89. package/extensions/mega-pipeline/memory-review.ts +46 -0
  90. package/extensions/mega-pipeline/recall.ts +165 -0
  91. package/extensions/mega-pipeline.ts +9 -537
  92. package/extensions/mega-runtime/helpers.ts +68 -0
  93. package/extensions/mega-runtime/query.ts +29 -0
  94. package/extensions/mega-runtime/state.ts +797 -0
  95. package/extensions/mega-runtime/widget.ts +258 -0
  96. package/extensions/mega-runtime.ts +15 -1093
  97. package/package.json +4 -3
  98. package/src/store/sqlite/checkpoints.ts +204 -0
  99. package/src/store/sqlite/dedup-mirror.ts +114 -0
  100. package/src/store/sqlite/foundation.ts +63 -0
  101. package/src/store/sqlite/global-index.ts +305 -0
  102. package/src/store/sqlite/maintenance.ts +294 -0
  103. package/src/store/sqlite/memories.ts +217 -0
  104. package/src/store/sqlite/meta.ts +108 -0
  105. package/src/store/sqlite/model-snapshots.ts +83 -0
  106. package/src/store/sqlite/raptor.ts +107 -0
  107. package/src/store/sqlite/raw-transcript.ts +221 -0
  108. package/src/store/sqlite/schema.ts +258 -0
  109. package/src/store/sqlite/session-state.ts +38 -0
  110. package/src/store/sqlite/stats.ts +127 -0
  111. package/src/store/sqlite/utils.ts +125 -0
  112. package/src/store/sqlite.ts +20 -2204
@@ -0,0 +1,57 @@
1
+ /**
2
+ * raptor.ts — Sprint 13 RAPTOR node persistence.
3
+ */
4
+ import { getStateDir, normalizeSessionId } from "../../store.js";
5
+ import { openStore, jsonText, encodeEmbedding, decodeEmbedding } from "./utils.js";
6
+ /** Persist a single RAPTOR node (upsert by (session_id, id)). */
7
+ export function upsertRaptorNode(node, stateDir = getStateDir()) {
8
+ const db = openStore(stateDir);
9
+ db.prepare(`INSERT INTO raptor_nodes(id, session_id, level, parent_id, children, summary, embedding_blob, quality_marker, token_estimate, built_at)
10
+ VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
11
+ ON CONFLICT(session_id, id) DO UPDATE SET
12
+ level=excluded.level, parent_id=excluded.parent_id, children=excluded.children,
13
+ summary=excluded.summary, embedding_blob=excluded.embedding_blob,
14
+ quality_marker=excluded.quality_marker, token_estimate=excluded.token_estimate,
15
+ built_at=excluded.built_at`).run(node.id, node.sessionId, node.level, node.parentId, jsonText(node.children), node.summary, encodeEmbedding(node.embedding), node.qualityMarker, node.tokenEstimate, node.builtAt);
16
+ }
17
+ /** Persist an entire built RAPTOR tree for a session (shadow or live). */
18
+ export function saveRaptorTree(sessionId, tree, builtAt, stateDir = getStateDir()) {
19
+ for (const node of tree.nodes.values()) {
20
+ upsertRaptorNode({
21
+ id: node.id,
22
+ sessionId,
23
+ level: node.level,
24
+ parentId: node.parentId,
25
+ children: node.children,
26
+ summary: node.summary,
27
+ embedding: node.embedding,
28
+ qualityMarker: node.qualityMarker,
29
+ tokenEstimate: node.tokenEstimate,
30
+ builtAt,
31
+ }, stateDir);
32
+ }
33
+ }
34
+ /** Load all RAPTOR nodes for a session. */
35
+ export function listRaptorNodes(sessionId, stateDir = getStateDir()) {
36
+ const db = openStore(stateDir);
37
+ const rows = db
38
+ .prepare("SELECT * FROM raptor_nodes WHERE session_id = ? ORDER BY level ASC, id ASC")
39
+ .all(normalizeSessionId(sessionId));
40
+ return rows.map((row) => ({
41
+ id: row.id,
42
+ sessionId: row.session_id,
43
+ level: row.level,
44
+ parentId: row.parent_id ?? null,
45
+ children: row.children ? JSON.parse(row.children) : [],
46
+ summary: row.summary ?? "",
47
+ embedding: decodeEmbedding(row.embedding_blob),
48
+ qualityMarker: row.quality_marker ?? "low",
49
+ tokenEstimate: row.token_estimate ?? 0,
50
+ builtAt: Number(row.built_at ?? 0),
51
+ }));
52
+ }
53
+ /** Delete all RAPTOR nodes for a session (rollback/cleanup). */
54
+ export function clearRaptorNodes(sessionId, stateDir = getStateDir()) {
55
+ const db = openStore(stateDir);
56
+ db.prepare("DELETE FROM raptor_nodes WHERE session_id = ?").run(normalizeSessionId(sessionId));
57
+ }
@@ -0,0 +1,134 @@
1
+ import { withTx } from "./utils.js";
2
+ function rowToRawTranscript(row) {
3
+ return {
4
+ contentHash: row.content_hash,
5
+ sessionId: row.session_id,
6
+ seq: Number(row.seq),
7
+ role: row.role,
8
+ contentBytes: row.content_bytes,
9
+ toolName: row.tool_name ?? null,
10
+ messageTimestamp: row.message_timestamp == null ? null : Number(row.message_timestamp),
11
+ checkpointEpoch: row.checkpoint_epoch,
12
+ };
13
+ }
14
+ function rowToCheckpointEpoch(row) {
15
+ return {
16
+ epochId: row.epoch_id,
17
+ sessionId: row.session_id,
18
+ startedSeq: Number(row.started_seq),
19
+ committedSeq: Number(row.committed_seq),
20
+ summaryMessageText: row.summary_message_text,
21
+ cutIndex: Number(row.cut_index),
22
+ checkpointId: row.checkpoint_id,
23
+ createdAt: Number(row.created_at),
24
+ };
25
+ }
26
+ /**
27
+ * Append one raw-message row to the durable mirror. Idempotent by
28
+ * (content_hash, session_id) via INSERT OR IGNORE — re-appending the same
29
+ * content for the same session is a no-op. seq is assigned server-side as
30
+ * COALESCE(MAX(seq),0)+1 within the session, so callers never need to compute
31
+ * it. Pass an open store handle (openStore) — matches the other DatabaseSync
32
+ * helpers. Parameterized (PREVENT-002).
33
+ */
34
+ export function appendRawTranscript(db, row) {
35
+ withTx(db, () => {
36
+ db.prepare(`INSERT OR IGNORE INTO raw_transcript
37
+ (content_hash, session_id, seq, role, content_bytes, tool_name, message_timestamp, checkpoint_epoch)
38
+ VALUES (
39
+ @content_hash, @session_id,
40
+ COALESCE((SELECT MAX(seq) FROM raw_transcript WHERE session_id = @session_id), 0) + 1,
41
+ @role, @content_bytes, @tool_name, @message_timestamp, @checkpoint_epoch
42
+ )`).run({
43
+ "@content_hash": row.contentHash,
44
+ "@session_id": row.sessionId,
45
+ "@role": row.role,
46
+ "@content_bytes": row.contentBytes,
47
+ "@tool_name": row.toolName,
48
+ "@message_timestamp": row.messageTimestamp,
49
+ "@checkpoint_epoch": row.checkpointEpoch,
50
+ });
51
+ });
52
+ }
53
+ /**
54
+ * List raw-transcript rows for a session in [fromSeq, toSeq], ordered by seq
55
+ * ascending. Returns camel-cased RawTranscriptRow[]. Parameterized.
56
+ */
57
+ export function listRawTranscriptRange(db, sessionId, fromSeq, toSeq) {
58
+ const rows = db
59
+ .prepare(`SELECT content_hash, session_id, seq, role, content_bytes, tool_name, message_timestamp, checkpoint_epoch
60
+ FROM raw_transcript
61
+ WHERE session_id = @session_id AND seq >= @from_seq AND seq <= @to_seq
62
+ ORDER BY seq ASC`)
63
+ .all({
64
+ "@session_id": sessionId,
65
+ "@from_seq": fromSeq,
66
+ "@to_seq": toSeq,
67
+ });
68
+ return rows.map(rowToRawTranscript);
69
+ }
70
+ /**
71
+ * Insert (or refresh) a checkpoint-epoch row. ON CONFLICT(epoch_id) DO UPDATE
72
+ * so re-running the same compaction epoch is idempotent / refresh-safe.
73
+ * Parameterized (PREVENT-002).
74
+ */
75
+ export function writeCheckpointEpoch(db, epoch) {
76
+ withTx(db, () => {
77
+ db.prepare(`INSERT INTO checkpoint_epochs
78
+ (epoch_id, session_id, started_seq, committed_seq, summary_message_text, cut_index, checkpoint_id, created_at)
79
+ VALUES (@epoch_id, @session_id, @started_seq, @committed_seq, @summary_message_text, @cut_index, @checkpoint_id, @created_at)
80
+ ON CONFLICT(epoch_id) DO UPDATE SET
81
+ session_id = excluded.session_id,
82
+ started_seq = excluded.started_seq,
83
+ committed_seq = excluded.committed_seq,
84
+ summary_message_text = excluded.summary_message_text,
85
+ cut_index = excluded.cut_index,
86
+ checkpoint_id = excluded.checkpoint_id,
87
+ created_at = excluded.created_at`).run({
88
+ "@epoch_id": epoch.epochId,
89
+ "@session_id": epoch.sessionId,
90
+ "@started_seq": epoch.startedSeq,
91
+ "@committed_seq": epoch.committedSeq,
92
+ "@summary_message_text": epoch.summaryMessageText,
93
+ "@cut_index": epoch.cutIndex,
94
+ "@checkpoint_id": epoch.checkpointId,
95
+ "@created_at": epoch.createdAt,
96
+ });
97
+ });
98
+ }
99
+ /** Read one checkpoint-epoch row by id (or null if absent). Parameterized. */
100
+ export function readCheckpointEpoch(db, epochId) {
101
+ const row = db
102
+ .prepare(`SELECT epoch_id, session_id, started_seq, committed_seq, summary_message_text, cut_index, checkpoint_id, created_at
103
+ FROM checkpoint_epochs WHERE epoch_id = @epoch_id`)
104
+ .get({ "@epoch_id": epochId });
105
+ return row ? rowToCheckpointEpoch(row) : null;
106
+ }
107
+ /**
108
+ * Latest checkpoint-epoch row for a session (highest created_at), or null if
109
+ * none. Parameterized (PREVENT-002).
110
+ */
111
+ export function getActiveEpochForSession(db, sessionId) {
112
+ const row = db
113
+ .prepare(`SELECT epoch_id, session_id, started_seq, committed_seq, summary_message_text, cut_index, checkpoint_id, created_at
114
+ FROM checkpoint_epochs
115
+ WHERE session_id = @session_id
116
+ ORDER BY created_at DESC
117
+ LIMIT 1`)
118
+ .get({ "@session_id": sessionId });
119
+ return row ? rowToCheckpointEpoch(row) : null;
120
+ }
121
+ /** List all checkpoint epochs (diagnostic / test helper). */
122
+ export function listCheckpointEpochs(db) {
123
+ const rows = db
124
+ .prepare(`SELECT epoch_id, session_id, started_seq, committed_seq, summary_message_text, cut_index, checkpoint_id, created_at
125
+ FROM checkpoint_epochs
126
+ ORDER BY created_at DESC`)
127
+ .all();
128
+ return rows.map(rowToCheckpointEpoch);
129
+ }
130
+ /** Count raw transcript rows (diagnostic / test helper). */
131
+ export function countRawTranscript(db) {
132
+ const row = db.prepare(`SELECT COUNT(*) AS cnt FROM raw_transcript`).get();
133
+ return row.cnt;
134
+ }
@@ -0,0 +1,250 @@
1
+ const SCHEMA_VERSION = 2;
2
+ /**
3
+ * Add `column` (with `decl`, e.g. "INTEGER") to `table` if it does not already
4
+ * exist. Idempotent: checks PRAGMA table_info first, so it is safe to run on
5
+ * every open. Table/column/decl are code-controlled constants (never user
6
+ * input), so the unavoidable identifier interpolation here does not violate
7
+ * PREVENT-002 (no external data reaches this SQL).
8
+ */
9
+ export function ensureColumn(db, table, column, decl) {
10
+ const cols = db.prepare(`PRAGMA table_info(${table})`).all();
11
+ if (cols.some((c) => c.name === column))
12
+ return;
13
+ db.exec(`ALTER TABLE ${table} ADD COLUMN ${column} ${decl}`);
14
+ }
15
+ export function initSchema(db) {
16
+ db.exec(`
17
+ CREATE TABLE IF NOT EXISTS context_chunks (
18
+ id TEXT NOT NULL,
19
+ session_id TEXT NOT NULL,
20
+ region_hash TEXT,
21
+ content_hash TEXT,
22
+ content_hash2 TEXT,
23
+ content_hash_version INTEGER,
24
+ normalized_text TEXT,
25
+ summary TEXT,
26
+ topic_summary TEXT,
27
+ summary_hash TEXT,
28
+ key_decisions TEXT, -- JSON array
29
+ next_steps TEXT, -- JSON array
30
+ files_modified TEXT, -- JSON array
31
+ embedding_blob BLOB, -- float32 vector
32
+ token_estimate INTEGER,
33
+ original_token_estimate INTEGER, -- dropped region size (tokens saved = orig − stored)
34
+ timestamp INTEGER,
35
+ dedup_status TEXT DEFAULT 'active',
36
+ compressed_original BLOB -- optional DR copy
37
+ );
38
+ -- Primary key is (session_id, id): checkpoint ids are unique per session
39
+ -- (chkpt_001 per session), not globally, so a bare id PK would collide
40
+ -- across sessions on the nextCheckpointId sequence.
41
+ CREATE UNIQUE INDEX IF NOT EXISTS idx_chunks_pk
42
+ ON context_chunks(session_id, id);
43
+ CREATE INDEX IF NOT EXISTS idx_chunks_session ON context_chunks(session_id);
44
+ CREATE INDEX IF NOT EXISTS idx_chunks_region ON context_chunks(region_hash);
45
+ CREATE INDEX IF NOT EXISTS idx_chunks_content ON context_chunks(content_hash);
46
+ -- Partial UNIQUE (QA #1): null content_hash rows never violate the constraint;
47
+ -- ON CONFLICT DO NOTHING makes backfill + L0 inserts safe.
48
+ CREATE UNIQUE INDEX IF NOT EXISTS idx_content_hash
49
+ ON context_chunks(session_id, content_hash) WHERE content_hash IS NOT NULL;
50
+
51
+ -- Sprint 11: MinHash signature + LSH bucket tables for L1 near-dup dedup.
52
+ CREATE TABLE IF NOT EXISTS minhash_signatures (
53
+ chunk_id TEXT NOT NULL,
54
+ session_id TEXT NOT NULL,
55
+ signature_version INTEGER NOT NULL,
56
+ signatures TEXT NOT NULL, -- JSON array of 256 uint32
57
+ PRIMARY KEY (chunk_id, signature_version)
58
+ );
59
+ CREATE INDEX IF NOT EXISTS idx_minhash_session ON minhash_signatures(session_id);
60
+
61
+ CREATE TABLE IF NOT EXISTS dedup_lsh_buckets (
62
+ bucket_key TEXT NOT NULL,
63
+ chunk_id TEXT NOT NULL,
64
+ session_id TEXT NOT NULL,
65
+ signature_version INTEGER NOT NULL,
66
+ PRIMARY KEY (bucket_key, chunk_id)
67
+ );
68
+ CREATE INDEX IF NOT EXISTS idx_lsh_bucket ON dedup_lsh_buckets(bucket_key, session_id);
69
+
70
+ CREATE TABLE IF NOT EXISTS session_state (
71
+ session_id TEXT PRIMARY KEY,
72
+ injected_checkpoint_ids TEXT, -- JSON array
73
+ stored_region_hashes TEXT -- JSON array
74
+ );
75
+
76
+ CREATE TABLE IF NOT EXISTS meta (
77
+ key TEXT PRIMARY KEY,
78
+ value TEXT
79
+ );
80
+
81
+ -- Sprint 13 (RAPTOR): hierarchical summary tree nodes. children are a JSON
82
+ -- array of child node ids (or raw leaf ids at the bottom); embedding_blob
83
+ -- is the node centroid. Additive; retrieval ignores this table until
84
+ -- Sprint 14 promotes RAPTOR out of shadow mode.
85
+ CREATE TABLE IF NOT EXISTS raptor_nodes (
86
+ id TEXT NOT NULL,
87
+ session_id TEXT NOT NULL,
88
+ level INTEGER NOT NULL,
89
+ parent_id TEXT,
90
+ children TEXT, -- JSON array of child ids
91
+ summary TEXT,
92
+ embedding_blob BLOB, -- float32 centroid
93
+ quality_marker TEXT DEFAULT 'low',
94
+ token_estimate INTEGER,
95
+ built_at INTEGER, -- S25: epoch ms when the tree was built (freshness guard)
96
+ PRIMARY KEY (session_id, id)
97
+ );
98
+ CREATE INDEX IF NOT EXISTS idx_raptor_session ON raptor_nodes(session_id);
99
+ CREATE INDEX IF NOT EXISTS idx_raptor_parent ON raptor_nodes(parent_id);
100
+
101
+ -- Foundation for future features (resume sessions, daily log, lessons
102
+ -- learned). Scaffolded now so all store data lives in SQLite from day one;
103
+ -- population is minimal (touchSession / logDaily on compact) and the full
104
+ -- UI/recall for these lands in later sprints.
105
+
106
+ -- Per-session registry (resume + per-repo session history).
107
+ CREATE TABLE IF NOT EXISTS sessions (
108
+ session_id TEXT PRIMARY KEY,
109
+ repo TEXT,
110
+ started_at INTEGER,
111
+ ended_at INTEGER,
112
+ last_compacted_at INTEGER,
113
+ status TEXT DEFAULT 'active'
114
+ );
115
+
116
+ -- Append-only daily activity log (the "daily log" feature seed).
117
+ CREATE TABLE IF NOT EXISTS daily_log (
118
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
119
+ day TEXT NOT NULL, -- YYYY-MM-DD
120
+ session_id TEXT,
121
+ event TEXT, -- e.g. 'compact'
122
+ detail TEXT,
123
+ tokens_saved INTEGER DEFAULT 0,
124
+ ts INTEGER
125
+ );
126
+ CREATE INDEX IF NOT EXISTS idx_daily_log_day ON daily_log(day);
127
+
128
+ -- Active model/provider for cost estimation + the future multi-repo
129
+ -- dashboard (Phase 5b). One row per (repo, model change); latest wins.
130
+ CREATE TABLE IF NOT EXISTS model_snapshots (
131
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
132
+ repo_root TEXT NOT NULL,
133
+ provider TEXT NOT NULL,
134
+ provider_name TEXT,
135
+ model_id TEXT NOT NULL,
136
+ model_name TEXT,
137
+ input_rate REAL, -- USD per input token (Model.cost.input)
138
+ output_rate REAL, -- USD per output token (Model.cost.output)
139
+ context_window INTEGER,
140
+ max_tokens INTEGER,
141
+ reasoning INTEGER DEFAULT 0,
142
+ captured_at INTEGER
143
+ );
144
+ CREATE INDEX IF NOT EXISTS idx_model_repo ON model_snapshots(repo_root);
145
+
146
+ -- Lessons learned (future recall/browse feature seed).
147
+ CREATE TABLE IF NOT EXISTS lessons (
148
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
149
+ session_id TEXT,
150
+ repo TEXT,
151
+ lesson TEXT,
152
+ ts INTEGER
153
+ );
154
+
155
+ -- Durable "save to memory" store (taken over from memory extensions).
156
+ -- One row per saved memory; scoped by repo so memory travels with the
157
+ -- clone. All params are parameterized (PREVENT-002).
158
+ CREATE TABLE IF NOT EXISTS memories (
159
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
160
+ repo TEXT,
161
+ kind TEXT DEFAULT 'note', -- note | fact | decision | preference
162
+ content TEXT NOT NULL,
163
+ tags TEXT, -- JSON array of strings
164
+ created_at INTEGER,
165
+ last_recalled_at INTEGER,
166
+ -- S20 memory-RAG extension (auto-review add/replace/remove ops).
167
+ category TEXT, -- typed bucket, e.g. decision | fact | preference
168
+ target TEXT, -- optional subject/scope this memory targets
169
+ last_referenced INTEGER, -- last time memory was referenced by recall (epoch s)
170
+ source_turn INTEGER -- conversation turn that produced this memory
171
+ );
172
+ CREATE INDEX IF NOT EXISTS idx_memories_repo ON memories(repo);
173
+
174
+ -- FTS5 trigram virtual table (Sprint 9+ pg_trgm-equivalent verification).
175
+ CREATE VIRTUAL TABLE IF NOT EXISTS context_chunks_trgm USING fts5(
176
+ id UNINDEXED,
177
+ normalized_text,
178
+ tokenize='trigram'
179
+ );
180
+
181
+ -- S27: durable raw-transcript mirror (MEGACOMPACT_DB_MIRROR). Appended
182
+ -- RAW message bytes per session so a compacted window can be rehydrated
183
+ -- from the local store instead of the pi runtime transcript (which is
184
+ -- trimmed). PK is (content_hash, session_id) — NOT content_hash alone —
185
+ -- so identical content in different sessions never collides. Additive:
186
+ -- CREATE TABLE IF NOT EXISTS leaves existing DBs untouched on open until
187
+ -- the S27 mirror flag is flipped on. All queries parameterized (PREVENT-002).
188
+ CREATE TABLE IF NOT EXISTS raw_transcript (
189
+ content_hash TEXT NOT NULL,
190
+ session_id TEXT NOT NULL,
191
+ seq INTEGER NOT NULL,
192
+ role TEXT NOT NULL,
193
+ content_bytes TEXT NOT NULL,
194
+ tool_name TEXT,
195
+ message_timestamp INTEGER, -- ORIGINAL msg ts at append, NOT served
196
+ checkpoint_epoch TEXT NOT NULL,
197
+ PRIMARY KEY (content_hash, session_id)
198
+ );
199
+ CREATE INDEX IF NOT EXISTS idx_rt_session_seq ON raw_transcript(session_id, seq);
200
+ CREATE INDEX IF NOT EXISTS idx_rt_epoch ON raw_transcript(checkpoint_epoch);
201
+
202
+ -- S27: checkpoint-epoch registry. One row per compaction epoch; the
203
+ -- summary_message_text is the verbatim system message that replaced the
204
+ -- trimmed prefix. Informational bookkeeping (the raw_transcript rows are
205
+ -- authoritative); refresh-safe via ON CONFLICT(epoch_id) DO UPDATE.
206
+ CREATE TABLE IF NOT EXISTS checkpoint_epochs (
207
+ epoch_id TEXT PRIMARY KEY,
208
+ session_id TEXT NOT NULL,
209
+ started_seq INTEGER NOT NULL,
210
+ committed_seq INTEGER NOT NULL,
211
+ summary_message_text TEXT NOT NULL,
212
+ cut_index INTEGER NOT NULL,
213
+ checkpoint_id TEXT NOT NULL,
214
+ created_at INTEGER NOT NULL
215
+ );
216
+ CREATE INDEX IF NOT EXISTS idx_epoch_session ON checkpoint_epochs(session_id, created_at DESC);
217
+
218
+ -- S27 Task 6: dedup_mirror for space-efficient deduplicated storage.
219
+ -- Each unique content_hash stores its bytes ONCE; raw_transcript rows
220
+ -- reference this table via content_ref instead of storing duplicate content_bytes inline.
221
+ CREATE TABLE IF NOT EXISTS dedup_mirror (
222
+ content_hash TEXT PRIMARY KEY,
223
+ content_bytes TEXT NOT NULL,
224
+ ref_count INTEGER NOT NULL DEFAULT 1,
225
+ first_seen_seq INTEGER NOT NULL,
226
+ created_at INTEGER NOT NULL
227
+ );
228
+ `);
229
+ // Idempotent column migrations. `CREATE TABLE IF NOT EXISTS` is a no-op on a
230
+ // pre-existing table, so new columns added to context_chunks after a store was
231
+ // first created (e.g. original_token_estimate in v0.4.2) must be ALTERed in for
232
+ // databases created by an older version — otherwise repoStats()/upsert crash
233
+ // with "no such column" and the extension fails to load. Additive only.
234
+ ensureColumn(db, "context_chunks", "original_token_estimate", "INTEGER");
235
+ // S27 Task 6: content_ref column in raw_transcript for dedup_mirror references.
236
+ ensureColumn(db, "raw_transcript", "content_ref", "TEXT");
237
+ // S20 memory-RAG extension: additive columns for auto-review ops. Idempotent —
238
+ // only alters DBs created by an older version that lack these columns.
239
+ ensureColumn(db, "memories", "category", "TEXT");
240
+ ensureColumn(db, "memories", "target", "TEXT");
241
+ ensureColumn(db, "memories", "last_referenced", "INTEGER");
242
+ ensureColumn(db, "memories", "source_turn", "INTEGER");
243
+ // S25: RAPTOR freshness-guard timestamp. Additive; old DBs have NULL → 0 →
244
+ // treated as stale → flat fallback (safe).
245
+ ensureColumn(db, "raptor_nodes", "built_at", "INTEGER");
246
+ const v = db.prepare("SELECT value FROM meta WHERE key='schema_version'").get();
247
+ if (!v) {
248
+ db.prepare("INSERT INTO meta(key, value) VALUES(?, ?)").run("schema_version", String(SCHEMA_VERSION));
249
+ }
250
+ }
@@ -0,0 +1,28 @@
1
+ import { getStateDir, normalizeSessionId } from "../../store.js";
2
+ import { openStore, jsonText } from "./utils.js";
3
+ function loadSessionStateRow(sid, db) {
4
+ const row = db.prepare("SELECT * FROM session_state WHERE session_id = ?").get(sid);
5
+ if (!row) {
6
+ return { injectedCheckpointIds: [], storedRegionHashes: [] };
7
+ }
8
+ return {
9
+ injectedCheckpointIds: row.injected_checkpoint_ids ? JSON.parse(row.injected_checkpoint_ids) : [],
10
+ storedRegionHashes: row.stored_region_hashes ? JSON.parse(row.stored_region_hashes) : [],
11
+ };
12
+ }
13
+ export function loadSessionState(sessionId, stateDir = getStateDir()) {
14
+ return loadSessionStateRow(normalizeSessionId(sessionId), openStore(stateDir));
15
+ }
16
+ export function saveSessionState(sessionId, state, stateDir = getStateDir()) {
17
+ const db = openStore(stateDir);
18
+ const sid = normalizeSessionId(sessionId);
19
+ db.prepare(`INSERT INTO session_state(session_id, injected_checkpoint_ids, stored_region_hashes)
20
+ VALUES(@sid, @inj, @reg)
21
+ ON CONFLICT(session_id) DO UPDATE SET
22
+ injected_checkpoint_ids=excluded.injected_checkpoint_ids,
23
+ stored_region_hashes=excluded.stored_region_hashes`).run({
24
+ sid,
25
+ inj: jsonText(state.injectedCheckpointIds),
26
+ reg: jsonText(state.storedRegionHashes),
27
+ });
28
+ }
@@ -0,0 +1,39 @@
1
+ /**
2
+ * Future-feature foundation: resume sessions, daily activity log, lessons learned.
3
+ *
4
+ * Scaffolded tables + minimal helpers so all store data lives in SQLite from
5
+ * day one. Full UI/recall for these lands in later sprints. All queries are
6
+ * parameterized (PREVENT-002).
7
+ */
8
+ import { getStateDir, normalizeSessionId } from "../../store.js";
9
+ import { openStore } from "./connection.js";
10
+ /** Upsert a `sessions` row (resume + per-repo session history). */
11
+ export function touchSession(sessionId, repo, stateDir = getStateDir()) {
12
+ const db = openStore(stateDir);
13
+ const sid = normalizeSessionId(sessionId);
14
+ const existing = db
15
+ .prepare("SELECT started_at FROM sessions WHERE session_id = ?")
16
+ .get(sid);
17
+ const now = Math.floor(Date.now() / 1000);
18
+ if (!existing) {
19
+ db.prepare(`INSERT INTO sessions(session_id, repo, started_at, last_compacted_at, status)
20
+ VALUES(?, ?, ?, ?, 'active')`).run(sid, repo ?? null, now, now);
21
+ }
22
+ else {
23
+ db.prepare("UPDATE sessions SET last_compacted_at = ?, repo = COALESCE(?, repo), status = 'active' WHERE session_id = ?").run(now, repo ?? null, sid);
24
+ }
25
+ }
26
+ /** Append a `daily_log` entry (day = YYYY-MM-DD, local-naive from Date). */
27
+ export function logDaily(sessionId, event, detail, tokensSaved, stateDir = getStateDir()) {
28
+ const db = openStore(stateDir);
29
+ const day = new Date().toISOString().slice(0, 10);
30
+ const now = Math.floor(Date.now() / 1000);
31
+ db.prepare(`INSERT INTO daily_log(day, session_id, event, detail, tokens_saved, ts)
32
+ VALUES(?, ?, ?, ?, ?, ?)`).run(day, normalizeSessionId(sessionId), event, detail ?? null, tokensSaved, now);
33
+ }
34
+ /** Append a `lessons` entry (future lessons-learned browse/recall). */
35
+ export function addLesson(sessionId, repo, lesson, stateDir = getStateDir()) {
36
+ const db = openStore(stateDir);
37
+ const now = Math.floor(Date.now() / 1000);
38
+ db.prepare(`INSERT INTO lessons(session_id, repo, lesson, ts) VALUES(?, ?, ?, ?)`).run(normalizeSessionId(sessionId), repo ?? null, lesson, now);
39
+ }
@@ -0,0 +1,66 @@
1
+ /**
2
+ * stats.ts — per-session, repo-wide, and data-invariant stats.
3
+ */
4
+ import { getStateDir, normalizeSessionId } from "../../store.js";
5
+ import { openStore } from "./utils.js";
6
+ import { getMetaNumber, getDedupStats } from "./meta.js";
7
+ export function storeStats(sessionId, stateDir = getStateDir()) {
8
+ const db = openStore(stateDir);
9
+ const sid = normalizeSessionId(sessionId);
10
+ const row = db
11
+ .prepare(`SELECT COUNT(*) AS c, COALESCE(SUM(token_estimate),0) AS tok,
12
+ MAX(id) AS lastId
13
+ FROM context_chunks WHERE session_id = ?`)
14
+ .get(sid);
15
+ let lastSummary;
16
+ if (row.lastId) {
17
+ const s = db.prepare("SELECT summary FROM context_chunks WHERE id = ?").get(row.lastId);
18
+ lastSummary = s?.summary;
19
+ }
20
+ return {
21
+ checkpointCount: row.c,
22
+ totalTokenEstimate: row.tok,
23
+ lastCheckpointId: row.lastId ?? undefined,
24
+ lastSummary,
25
+ };
26
+ }
27
+ export function dataInvariantStats(stateDir = getStateDir()) {
28
+ const db = openStore(stateDir);
29
+ const row = db
30
+ .prepare(`SELECT
31
+ COUNT(compressed_original) AS withBlob,
32
+ COALESCE(SUM(LENGTH(compressed_original)),0) AS blobBytes,
33
+ SUM(CASE WHEN compressed_original IS NULL THEN 1 ELSE 0 END) AS noBlob
34
+ FROM context_chunks WHERE dedup_status != 'removed'`)
35
+ .get();
36
+ const removed = db
37
+ .prepare(`SELECT COUNT(*) AS c FROM context_chunks WHERE dedup_status = 'removed'`)
38
+ .get();
39
+ return {
40
+ regionsRetained: row.withBlob,
41
+ compressedOriginalBytes: row.blobBytes,
42
+ regionsWithoutBlob: row.noBlob ?? 0,
43
+ bytesPermanentlyDeleted: 0,
44
+ duplicatesCollapsed: removed.c,
45
+ };
46
+ }
47
+ export function repoStats(stateDir = getStateDir()) {
48
+ const db = openStore(stateDir);
49
+ const row = db
50
+ .prepare(`SELECT COUNT(*) AS c, COALESCE(SUM(token_estimate),0) AS tok,
51
+ COALESCE(SUM(original_token_estimate),0) AS orig,
52
+ COUNT(DISTINCT session_id) AS sessions
53
+ FROM context_chunks WHERE dedup_status != 'removed'`)
54
+ .get();
55
+ const ds = getDedupStats(stateDir);
56
+ return {
57
+ checkpointCount: row.c,
58
+ totalTokenEstimate: row.tok,
59
+ originalTokens: row.orig,
60
+ sessionCount: row.sessions,
61
+ tokensSaved: getMetaNumber("tokens_saved", stateDir),
62
+ dedupAttempts: ds.attempts,
63
+ dedupCollapsed: ds.deduped,
64
+ storageDedupRate: ds.attempts === 0 ? 0 : ds.deduped / ds.attempts,
65
+ };
66
+ }
@@ -0,0 +1,19 @@
1
+ /**
2
+ * Transaction wrapper using SAVEPOINT so it nests safely under an outer
3
+ * transaction (unlike `BEGIN`, which SQLite rejects when one is already open).
4
+ *
5
+ * Mirrors better-sqlite3's `db.transaction(fn)` semantics — callers that wrap a
6
+ * batch in withTx (e.g. backfill) can still call helpers that also use withTx.
7
+ */
8
+ export function withTx(db, fn) {
9
+ db.exec("SAVEPOINT mc_tx");
10
+ try {
11
+ fn();
12
+ db.exec("RELEASE mc_tx");
13
+ }
14
+ catch (e) {
15
+ db.exec("ROLLBACK TO mc_tx");
16
+ db.exec("RELEASE mc_tx");
17
+ throw e;
18
+ }
19
+ }