pi-mega-compact 0.7.8 → 0.8.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.
Files changed (122) hide show
  1. package/README.md +11 -12
  2. package/dist/extensions/dashboard-server/html.js +1023 -0
  3. package/dist/extensions/dashboard-server/html.test.js +41 -0
  4. package/dist/extensions/dashboard-server/index-reader.js +133 -0
  5. package/dist/extensions/dashboard-server/server.js +530 -0
  6. package/dist/extensions/dashboard-server/server.test.js +120 -0
  7. package/dist/extensions/dashboard-server/snapshot.js +43 -0
  8. package/dist/extensions/dashboard-server/state.js +30 -0
  9. package/dist/extensions/dashboard-server/types.js +5 -0
  10. package/dist/extensions/dashboard-server-s32.test.js +181 -0
  11. package/dist/extensions/dashboard-server.js +7 -1315
  12. package/dist/extensions/mega-commands.js +162 -134
  13. package/dist/extensions/mega-compact.js +3 -0
  14. package/dist/extensions/mega-compact.test.js +90 -21
  15. package/dist/extensions/mega-conflict-cmds.js +5 -1
  16. package/dist/extensions/mega-dashboard-cmds.js +29 -22
  17. package/dist/extensions/mega-db-cmds.js +11 -2
  18. package/dist/extensions/mega-events/agent-handlers.js +222 -0
  19. package/dist/extensions/mega-events/compact-handlers.js +162 -0
  20. package/dist/extensions/mega-events/context-handler.js +249 -0
  21. package/dist/extensions/mega-events/register.js +21 -0
  22. package/dist/extensions/mega-events/session-handlers.js +142 -0
  23. package/dist/extensions/mega-events.js +15 -699
  24. package/dist/extensions/mega-game-cmds.js +106 -0
  25. package/dist/extensions/mega-game-cmds.test.js +113 -0
  26. package/dist/extensions/mega-pipeline/compact.js +324 -0
  27. package/dist/extensions/mega-pipeline/memory-review.js +38 -0
  28. package/dist/extensions/mega-pipeline/recall.js +147 -0
  29. package/dist/extensions/mega-pipeline.js +9 -480
  30. package/dist/extensions/mega-runtime/helpers.js +40 -0
  31. package/dist/extensions/mega-runtime/query.js +29 -0
  32. package/dist/extensions/mega-runtime/state.js +877 -0
  33. package/dist/extensions/mega-runtime/state.test.js +171 -0
  34. package/dist/extensions/mega-runtime/widget.js +270 -0
  35. package/dist/extensions/mega-runtime/widget.test.js +160 -0
  36. package/dist/extensions/mega-runtime.js +15 -947
  37. package/dist/src/config/themes.js +84 -0
  38. package/dist/src/config/themes.test.js +94 -0
  39. package/dist/src/game/scoring.js +105 -0
  40. package/dist/src/game/scoring.test.js +98 -0
  41. package/dist/src/store/sqlite/checkpoints.js +145 -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/game-achievements.js +111 -0
  45. package/dist/src/store/sqlite/game-achievements.test.js +67 -0
  46. package/dist/src/store/sqlite/game-scores.js +105 -0
  47. package/dist/src/store/sqlite/game-scores.test.js +106 -0
  48. package/dist/src/store/sqlite/game-state.js +54 -0
  49. package/dist/src/store/sqlite/game-state.test.js +76 -0
  50. package/dist/src/store/sqlite/global-index.js +224 -0
  51. package/dist/src/store/sqlite/maintenance.js +235 -0
  52. package/dist/src/store/sqlite/memories.js +164 -0
  53. package/dist/src/store/sqlite/meta.js +82 -0
  54. package/dist/src/store/sqlite/model-snapshots.js +47 -0
  55. package/dist/src/store/sqlite/raptor.js +57 -0
  56. package/dist/src/store/sqlite/raw-transcript.js +134 -0
  57. package/dist/src/store/sqlite/schema.js +294 -0
  58. package/dist/src/store/sqlite/session-state.js +28 -0
  59. package/dist/src/store/sqlite/stats.js +66 -0
  60. package/dist/src/store/sqlite/utils.js +120 -0
  61. package/dist/src/store/sqlite.js +23 -1607
  62. package/extensions/dashboard-server/html.test.ts +50 -0
  63. package/extensions/dashboard-server/html.ts +1026 -0
  64. package/extensions/dashboard-server/index-reader.ts +130 -0
  65. package/extensions/dashboard-server/server.test.ts +131 -0
  66. package/extensions/dashboard-server/server.ts +505 -0
  67. package/extensions/dashboard-server/snapshot.ts +44 -0
  68. package/extensions/dashboard-server/state.ts +33 -0
  69. package/extensions/dashboard-server/types.ts +134 -0
  70. package/extensions/dashboard-server-s32.test.ts +195 -0
  71. package/extensions/dashboard-server.ts +7 -1431
  72. package/extensions/mega-commands.ts +33 -10
  73. package/extensions/mega-compact.test.ts +198 -43
  74. package/extensions/mega-compact.ts +3 -0
  75. package/extensions/mega-conflict-cmds.ts +6 -2
  76. package/extensions/mega-dashboard-cmds.ts +30 -23
  77. package/extensions/mega-db-cmds.ts +11 -3
  78. package/extensions/mega-events/agent-handlers.ts +262 -0
  79. package/extensions/mega-events/compact-handlers.ts +192 -0
  80. package/extensions/mega-events/context-handler.ts +290 -0
  81. package/extensions/mega-events/register.ts +37 -0
  82. package/extensions/mega-events/session-handlers.ts +165 -0
  83. package/extensions/mega-events.ts +15 -780
  84. package/extensions/mega-game-cmds.test.ts +137 -0
  85. package/extensions/mega-game-cmds.ts +122 -0
  86. package/extensions/mega-pipeline/compact.ts +366 -0
  87. package/extensions/mega-pipeline/memory-review.ts +46 -0
  88. package/extensions/mega-pipeline/recall.ts +165 -0
  89. package/extensions/mega-pipeline.ts +9 -537
  90. package/extensions/mega-runtime/helpers.ts +68 -0
  91. package/extensions/mega-runtime/query.ts +29 -0
  92. package/extensions/mega-runtime/state.test.ts +171 -0
  93. package/extensions/mega-runtime/state.ts +967 -0
  94. package/extensions/mega-runtime/widget.test.ts +185 -0
  95. package/extensions/mega-runtime/widget.ts +359 -0
  96. package/extensions/mega-runtime.ts +15 -1093
  97. package/package.json +4 -3
  98. package/src/config/themes.test.ts +116 -0
  99. package/src/config/themes.ts +124 -0
  100. package/src/game/scoring.test.ts +103 -0
  101. package/src/game/scoring.ts +158 -0
  102. package/src/store/sqlite/checkpoints.ts +204 -0
  103. package/src/store/sqlite/dedup-mirror.ts +114 -0
  104. package/src/store/sqlite/foundation.ts +63 -0
  105. package/src/store/sqlite/game-achievements.test.ts +80 -0
  106. package/src/store/sqlite/game-achievements.ts +147 -0
  107. package/src/store/sqlite/game-scores.test.ts +132 -0
  108. package/src/store/sqlite/game-scores.ts +168 -0
  109. package/src/store/sqlite/game-state.test.ts +89 -0
  110. package/src/store/sqlite/game-state.ts +87 -0
  111. package/src/store/sqlite/global-index.ts +305 -0
  112. package/src/store/sqlite/maintenance.ts +294 -0
  113. package/src/store/sqlite/memories.ts +217 -0
  114. package/src/store/sqlite/meta.ts +108 -0
  115. package/src/store/sqlite/model-snapshots.ts +83 -0
  116. package/src/store/sqlite/raptor.ts +107 -0
  117. package/src/store/sqlite/raw-transcript.ts +221 -0
  118. package/src/store/sqlite/schema.ts +305 -0
  119. package/src/store/sqlite/session-state.ts +38 -0
  120. package/src/store/sqlite/stats.ts +127 -0
  121. package/src/store/sqlite/utils.ts +125 -0
  122. package/src/store/sqlite.ts +23 -2204
@@ -0,0 +1,221 @@
1
+ /**
2
+ * raw-transcript.ts — S27 durable raw-transcript mirror + checkpoint-epoch registry.
3
+ *
4
+ * ADDITIVE + flag-default-OFF (MEGACOMPACT_DB_MIRROR). No behavior change
5
+ * until the flag is flipped on; the tables are created IF NOT EXISTS on
6
+ * open so existing stores are untouched. These helpers are storage primitives
7
+ * only — the runtime hook (Task 5) wires them into the compaction flow. All
8
+ * queries use @-parameterized placeholders (PREVENT-002); no `any` types
9
+ * (PREVENT-011).
10
+ */
11
+ import type { DatabaseSync } from "node:sqlite";
12
+ import { withTx } from "./utils.js";
13
+
14
+ /** One appended raw-message row in the durable mirror. */
15
+ export interface RawTranscriptRow {
16
+ contentHash: string;
17
+ sessionId: string;
18
+ seq: number;
19
+ role: string;
20
+ contentBytes: string;
21
+ toolName: string | null;
22
+ /** ORIGINAL message timestamp captured at append time (NOT a served ts). */
23
+ messageTimestamp: number | null;
24
+ checkpointEpoch: string;
25
+ }
26
+
27
+ /** One checkpoint-epoch bookkeeping row (informational registry). */
28
+ export interface CheckpointEpoch {
29
+ epochId: string;
30
+ sessionId: string;
31
+ startedSeq: number;
32
+ committedSeq: number;
33
+ summaryMessageText: string;
34
+ cutIndex: number;
35
+ checkpointId: string;
36
+ createdAt: number;
37
+ }
38
+
39
+ /** DB row shape for raw_transcript (snake_case column names). */
40
+ interface RawTranscriptDBRow {
41
+ content_hash: string;
42
+ session_id: string;
43
+ seq: number;
44
+ role: string;
45
+ content_bytes: string;
46
+ tool_name: string | null;
47
+ message_timestamp: number | null;
48
+ checkpoint_epoch: string;
49
+ }
50
+
51
+ /** DB row shape for checkpoint_epochs (snake_case column names). */
52
+ interface CheckpointEpochDBRow {
53
+ epoch_id: string;
54
+ session_id: string;
55
+ started_seq: number;
56
+ committed_seq: number;
57
+ summary_message_text: string;
58
+ cut_index: number;
59
+ checkpoint_id: string;
60
+ created_at: number;
61
+ }
62
+
63
+ function rowToRawTranscript(row: RawTranscriptDBRow): RawTranscriptRow {
64
+ return {
65
+ contentHash: row.content_hash,
66
+ sessionId: row.session_id,
67
+ seq: Number(row.seq),
68
+ role: row.role,
69
+ contentBytes: row.content_bytes,
70
+ toolName: row.tool_name ?? null,
71
+ messageTimestamp:
72
+ row.message_timestamp == null ? null : Number(row.message_timestamp),
73
+ checkpointEpoch: row.checkpoint_epoch,
74
+ };
75
+ }
76
+
77
+ function rowToCheckpointEpoch(row: CheckpointEpochDBRow): CheckpointEpoch {
78
+ return {
79
+ epochId: row.epoch_id,
80
+ sessionId: row.session_id,
81
+ startedSeq: Number(row.started_seq),
82
+ committedSeq: Number(row.committed_seq),
83
+ summaryMessageText: row.summary_message_text,
84
+ cutIndex: Number(row.cut_index),
85
+ checkpointId: row.checkpoint_id,
86
+ createdAt: Number(row.created_at),
87
+ };
88
+ }
89
+
90
+ /**
91
+ * Append one raw-message row to the durable mirror. Idempotent by
92
+ * (content_hash, session_id) via INSERT OR IGNORE — re-appending the same
93
+ * content for the same session is a no-op. seq is assigned server-side as
94
+ * COALESCE(MAX(seq),0)+1 within the session, so callers never need to compute
95
+ * it. Pass an open store handle (openStore) — matches the other DatabaseSync
96
+ * helpers. Parameterized (PREVENT-002).
97
+ */
98
+ export function appendRawTranscript(db: DatabaseSync, row: RawTranscriptRow): void {
99
+ withTx(db, () => {
100
+ db.prepare(
101
+ `INSERT OR IGNORE INTO raw_transcript
102
+ (content_hash, session_id, seq, role, content_bytes, tool_name, message_timestamp, checkpoint_epoch)
103
+ VALUES (
104
+ @content_hash, @session_id,
105
+ COALESCE((SELECT MAX(seq) FROM raw_transcript WHERE session_id = @session_id), 0) + 1,
106
+ @role, @content_bytes, @tool_name, @message_timestamp, @checkpoint_epoch
107
+ )`,
108
+ ).run({
109
+ "@content_hash": row.contentHash,
110
+ "@session_id": row.sessionId,
111
+ "@role": row.role,
112
+ "@content_bytes": row.contentBytes,
113
+ "@tool_name": row.toolName,
114
+ "@message_timestamp": row.messageTimestamp,
115
+ "@checkpoint_epoch": row.checkpointEpoch,
116
+ });
117
+ });
118
+ }
119
+
120
+ /**
121
+ * List raw-transcript rows for a session in [fromSeq, toSeq], ordered by seq
122
+ * ascending. Returns camel-cased RawTranscriptRow[]. Parameterized.
123
+ */
124
+ export function listRawTranscriptRange(
125
+ db: DatabaseSync,
126
+ sessionId: string,
127
+ fromSeq: number,
128
+ toSeq: number,
129
+ ): RawTranscriptRow[] {
130
+ const rows = db
131
+ .prepare(
132
+ `SELECT content_hash, session_id, seq, role, content_bytes, tool_name, message_timestamp, checkpoint_epoch
133
+ FROM raw_transcript
134
+ WHERE session_id = @session_id AND seq >= @from_seq AND seq <= @to_seq
135
+ ORDER BY seq ASC`,
136
+ )
137
+ .all({
138
+ "@session_id": sessionId,
139
+ "@from_seq": fromSeq,
140
+ "@to_seq": toSeq,
141
+ }) as unknown as RawTranscriptDBRow[];
142
+ return rows.map(rowToRawTranscript);
143
+ }
144
+
145
+ /**
146
+ * Insert (or refresh) a checkpoint-epoch row. ON CONFLICT(epoch_id) DO UPDATE
147
+ * so re-running the same compaction epoch is idempotent / refresh-safe.
148
+ * Parameterized (PREVENT-002).
149
+ */
150
+ export function writeCheckpointEpoch(db: DatabaseSync, epoch: CheckpointEpoch): void {
151
+ withTx(db, () => {
152
+ db.prepare(
153
+ `INSERT INTO checkpoint_epochs
154
+ (epoch_id, session_id, started_seq, committed_seq, summary_message_text, cut_index, checkpoint_id, created_at)
155
+ VALUES (@epoch_id, @session_id, @started_seq, @committed_seq, @summary_message_text, @cut_index, @checkpoint_id, @created_at)
156
+ ON CONFLICT(epoch_id) DO UPDATE SET
157
+ session_id = excluded.session_id,
158
+ started_seq = excluded.started_seq,
159
+ committed_seq = excluded.committed_seq,
160
+ summary_message_text = excluded.summary_message_text,
161
+ cut_index = excluded.cut_index,
162
+ checkpoint_id = excluded.checkpoint_id,
163
+ created_at = excluded.created_at`,
164
+ ).run({
165
+ "@epoch_id": epoch.epochId,
166
+ "@session_id": epoch.sessionId,
167
+ "@started_seq": epoch.startedSeq,
168
+ "@committed_seq": epoch.committedSeq,
169
+ "@summary_message_text": epoch.summaryMessageText,
170
+ "@cut_index": epoch.cutIndex,
171
+ "@checkpoint_id": epoch.checkpointId,
172
+ "@created_at": epoch.createdAt,
173
+ });
174
+ });
175
+ }
176
+
177
+ /** Read one checkpoint-epoch row by id (or null if absent). Parameterized. */
178
+ export function readCheckpointEpoch(db: DatabaseSync, epochId: string): CheckpointEpoch | null {
179
+ const row = db
180
+ .prepare(
181
+ `SELECT epoch_id, session_id, started_seq, committed_seq, summary_message_text, cut_index, checkpoint_id, created_at
182
+ FROM checkpoint_epochs WHERE epoch_id = @epoch_id`,
183
+ )
184
+ .get({ "@epoch_id": epochId }) as unknown as CheckpointEpochDBRow | undefined;
185
+ return row ? rowToCheckpointEpoch(row) : null;
186
+ }
187
+
188
+ /**
189
+ * Latest checkpoint-epoch row for a session (highest created_at), or null if
190
+ * none. Parameterized (PREVENT-002).
191
+ */
192
+ export function getActiveEpochForSession(db: DatabaseSync, sessionId: string): CheckpointEpoch | null {
193
+ const row = db
194
+ .prepare(
195
+ `SELECT epoch_id, session_id, started_seq, committed_seq, summary_message_text, cut_index, checkpoint_id, created_at
196
+ FROM checkpoint_epochs
197
+ WHERE session_id = @session_id
198
+ ORDER BY created_at DESC
199
+ LIMIT 1`,
200
+ )
201
+ .get({ "@session_id": sessionId }) as unknown as CheckpointEpochDBRow | undefined;
202
+ return row ? rowToCheckpointEpoch(row) : null;
203
+ }
204
+
205
+ /** List all checkpoint epochs (diagnostic / test helper). */
206
+ export function listCheckpointEpochs(db: DatabaseSync): CheckpointEpoch[] {
207
+ const rows = db
208
+ .prepare(
209
+ `SELECT epoch_id, session_id, started_seq, committed_seq, summary_message_text, cut_index, checkpoint_id, created_at
210
+ FROM checkpoint_epochs
211
+ ORDER BY created_at DESC`,
212
+ )
213
+ .all() as unknown as CheckpointEpochDBRow[];
214
+ return rows.map(rowToCheckpointEpoch);
215
+ }
216
+
217
+ /** Count raw transcript rows (diagnostic / test helper). */
218
+ export function countRawTranscript(db: DatabaseSync): number {
219
+ const row = db.prepare(`SELECT COUNT(*) AS cnt FROM raw_transcript`).get() as { cnt: number };
220
+ return row.cnt;
221
+ }
@@ -0,0 +1,305 @@
1
+ /**
2
+ * schema.ts — table creation, migrations, `ensureColumn`, PRAGMA setup.
3
+ */
4
+ import { DatabaseSync } from "node:sqlite";
5
+ import { ACHIEVEMENT_DEFS } from "../../game/scoring.js";
6
+
7
+ const SCHEMA_VERSION = 2;
8
+
9
+ /**
10
+ * Add `column` (with `decl`, e.g. "INTEGER") to `table` if it does not already
11
+ * exist. Idempotent: checks PRAGMA table_info first, so it is safe to run on
12
+ * every open. Table/column/decl are code-controlled constants (never user
13
+ * input), so the unavoidable identifier interpolation here does not violate
14
+ * PREVENT-002 (no external data reaches this SQL).
15
+ */
16
+ export function ensureColumn(db: DatabaseSync, table: string, column: string, decl: string): void {
17
+ const cols = db.prepare(`PRAGMA table_info(${table})`).all() as Array<{ name: string }>;
18
+ if (cols.some((c) => c.name === column)) return;
19
+ db.exec(`ALTER TABLE ${table} ADD COLUMN ${column} ${decl}`);
20
+ }
21
+
22
+ export function initSchema(db: DatabaseSync): void {
23
+ db.exec(`
24
+ CREATE TABLE IF NOT EXISTS context_chunks (
25
+ id TEXT NOT NULL,
26
+ session_id TEXT NOT NULL,
27
+ region_hash TEXT,
28
+ content_hash TEXT,
29
+ content_hash2 TEXT,
30
+ content_hash_version INTEGER,
31
+ normalized_text TEXT,
32
+ summary TEXT,
33
+ topic_summary TEXT,
34
+ summary_hash TEXT,
35
+ key_decisions TEXT, -- JSON array
36
+ next_steps TEXT, -- JSON array
37
+ files_modified TEXT, -- JSON array
38
+ embedding_blob BLOB, -- float32 vector
39
+ token_estimate INTEGER,
40
+ original_token_estimate INTEGER, -- dropped region size (tokens saved = orig − stored)
41
+ timestamp INTEGER,
42
+ dedup_status TEXT DEFAULT 'active',
43
+ compressed_original BLOB -- optional DR copy
44
+ );
45
+ -- Primary key is (session_id, id): checkpoint ids are unique per session
46
+ -- (chkpt_001 per session), not globally, so a bare id PK would collide
47
+ -- across sessions on the nextCheckpointId sequence.
48
+ CREATE UNIQUE INDEX IF NOT EXISTS idx_chunks_pk
49
+ ON context_chunks(session_id, id);
50
+ CREATE INDEX IF NOT EXISTS idx_chunks_session ON context_chunks(session_id);
51
+ CREATE INDEX IF NOT EXISTS idx_chunks_region ON context_chunks(region_hash);
52
+ CREATE INDEX IF NOT EXISTS idx_chunks_content ON context_chunks(content_hash);
53
+ -- Partial UNIQUE (QA #1): null content_hash rows never violate the constraint;
54
+ -- ON CONFLICT DO NOTHING makes backfill + L0 inserts safe.
55
+ CREATE UNIQUE INDEX IF NOT EXISTS idx_content_hash
56
+ ON context_chunks(session_id, content_hash) WHERE content_hash IS NOT NULL;
57
+
58
+ -- Sprint 11: MinHash signature + LSH bucket tables for L1 near-dup dedup.
59
+ CREATE TABLE IF NOT EXISTS minhash_signatures (
60
+ chunk_id TEXT NOT NULL,
61
+ session_id TEXT NOT NULL,
62
+ signature_version INTEGER NOT NULL,
63
+ signatures TEXT NOT NULL, -- JSON array of 256 uint32
64
+ PRIMARY KEY (chunk_id, signature_version)
65
+ );
66
+ CREATE INDEX IF NOT EXISTS idx_minhash_session ON minhash_signatures(session_id);
67
+
68
+ CREATE TABLE IF NOT EXISTS dedup_lsh_buckets (
69
+ bucket_key TEXT NOT NULL,
70
+ chunk_id TEXT NOT NULL,
71
+ session_id TEXT NOT NULL,
72
+ signature_version INTEGER NOT NULL,
73
+ PRIMARY KEY (bucket_key, chunk_id)
74
+ );
75
+ CREATE INDEX IF NOT EXISTS idx_lsh_bucket ON dedup_lsh_buckets(bucket_key, session_id);
76
+
77
+ CREATE TABLE IF NOT EXISTS session_state (
78
+ session_id TEXT PRIMARY KEY,
79
+ injected_checkpoint_ids TEXT, -- JSON array
80
+ stored_region_hashes TEXT -- JSON array
81
+ );
82
+
83
+ CREATE TABLE IF NOT EXISTS meta (
84
+ key TEXT PRIMARY KEY,
85
+ value TEXT
86
+ );
87
+
88
+ -- Sprint 13 (RAPTOR): hierarchical summary tree nodes. children are a JSON
89
+ -- array of child node ids (or raw leaf ids at the bottom); embedding_blob
90
+ -- is the node centroid. Additive; retrieval ignores this table until
91
+ -- Sprint 14 promotes RAPTOR out of shadow mode.
92
+ CREATE TABLE IF NOT EXISTS raptor_nodes (
93
+ id TEXT NOT NULL,
94
+ session_id TEXT NOT NULL,
95
+ level INTEGER NOT NULL,
96
+ parent_id TEXT,
97
+ children TEXT, -- JSON array of child ids
98
+ summary TEXT,
99
+ embedding_blob BLOB, -- float32 centroid
100
+ quality_marker TEXT DEFAULT 'low',
101
+ token_estimate INTEGER,
102
+ built_at INTEGER, -- S25: epoch ms when the tree was built (freshness guard)
103
+ PRIMARY KEY (session_id, id)
104
+ );
105
+ CREATE INDEX IF NOT EXISTS idx_raptor_session ON raptor_nodes(session_id);
106
+ CREATE INDEX IF NOT EXISTS idx_raptor_parent ON raptor_nodes(parent_id);
107
+
108
+ -- Foundation for future features (resume sessions, daily log, lessons
109
+ -- learned). Scaffolded now so all store data lives in SQLite from day one;
110
+ -- population is minimal (touchSession / logDaily on compact) and the full
111
+ -- UI/recall for these lands in later sprints.
112
+
113
+ -- Per-session registry (resume + per-repo session history).
114
+ CREATE TABLE IF NOT EXISTS sessions (
115
+ session_id TEXT PRIMARY KEY,
116
+ repo TEXT,
117
+ started_at INTEGER,
118
+ ended_at INTEGER,
119
+ last_compacted_at INTEGER,
120
+ status TEXT DEFAULT 'active'
121
+ );
122
+
123
+ -- Append-only daily activity log (the "daily log" feature seed).
124
+ CREATE TABLE IF NOT EXISTS daily_log (
125
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
126
+ day TEXT NOT NULL, -- YYYY-MM-DD
127
+ session_id TEXT,
128
+ event TEXT, -- e.g. 'compact'
129
+ detail TEXT,
130
+ tokens_saved INTEGER DEFAULT 0,
131
+ ts INTEGER
132
+ );
133
+ CREATE INDEX IF NOT EXISTS idx_daily_log_day ON daily_log(day);
134
+
135
+ -- Active model/provider for cost estimation + the future multi-repo
136
+ -- dashboard (Phase 5b). One row per (repo, model change); latest wins.
137
+ CREATE TABLE IF NOT EXISTS model_snapshots (
138
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
139
+ repo_root TEXT NOT NULL,
140
+ provider TEXT NOT NULL,
141
+ provider_name TEXT,
142
+ model_id TEXT NOT NULL,
143
+ model_name TEXT,
144
+ input_rate REAL, -- USD per input token (Model.cost.input)
145
+ output_rate REAL, -- USD per output token (Model.cost.output)
146
+ context_window INTEGER,
147
+ max_tokens INTEGER,
148
+ reasoning INTEGER DEFAULT 0,
149
+ captured_at INTEGER
150
+ );
151
+ CREATE INDEX IF NOT EXISTS idx_model_repo ON model_snapshots(repo_root);
152
+
153
+ -- Lessons learned (future recall/browse feature seed).
154
+ CREATE TABLE IF NOT EXISTS lessons (
155
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
156
+ session_id TEXT,
157
+ repo TEXT,
158
+ lesson TEXT,
159
+ ts INTEGER
160
+ );
161
+
162
+ -- Durable "save to memory" store (taken over from memory extensions).
163
+ -- One row per saved memory; scoped by repo so memory travels with the
164
+ -- clone. All params are parameterized (PREVENT-002).
165
+ CREATE TABLE IF NOT EXISTS memories (
166
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
167
+ repo TEXT,
168
+ kind TEXT DEFAULT 'note', -- note | fact | decision | preference
169
+ content TEXT NOT NULL,
170
+ tags TEXT, -- JSON array of strings
171
+ created_at INTEGER,
172
+ last_recalled_at INTEGER,
173
+ -- S20 memory-RAG extension (auto-review add/replace/remove ops).
174
+ category TEXT, -- typed bucket, e.g. decision | fact | preference
175
+ target TEXT, -- optional subject/scope this memory targets
176
+ last_referenced INTEGER, -- last time memory was referenced by recall (epoch s)
177
+ source_turn INTEGER -- conversation turn that produced this memory
178
+ );
179
+ CREATE INDEX IF NOT EXISTS idx_memories_repo ON memories(repo);
180
+
181
+ -- FTS5 trigram virtual table (Sprint 9+ pg_trgm-equivalent verification).
182
+ CREATE VIRTUAL TABLE IF NOT EXISTS context_chunks_trgm USING fts5(
183
+ id UNINDEXED,
184
+ normalized_text,
185
+ tokenize='trigram'
186
+ );
187
+
188
+ -- S27: durable raw-transcript mirror (MEGACOMPACT_DB_MIRROR). Appended
189
+ -- RAW message bytes per session so a compacted window can be rehydrated
190
+ -- from the local store instead of the pi runtime transcript (which is
191
+ -- trimmed). PK is (content_hash, session_id) — NOT content_hash alone —
192
+ -- so identical content in different sessions never collides. Additive:
193
+ -- CREATE TABLE IF NOT EXISTS leaves existing DBs untouched on open until
194
+ -- the S27 mirror flag is flipped on. All queries parameterized (PREVENT-002).
195
+ CREATE TABLE IF NOT EXISTS raw_transcript (
196
+ content_hash TEXT NOT NULL,
197
+ session_id TEXT NOT NULL,
198
+ seq INTEGER NOT NULL,
199
+ role TEXT NOT NULL,
200
+ content_bytes TEXT NOT NULL,
201
+ tool_name TEXT,
202
+ message_timestamp INTEGER, -- ORIGINAL msg ts at append, NOT served
203
+ checkpoint_epoch TEXT NOT NULL,
204
+ PRIMARY KEY (content_hash, session_id)
205
+ );
206
+ CREATE INDEX IF NOT EXISTS idx_rt_session_seq ON raw_transcript(session_id, seq);
207
+ CREATE INDEX IF NOT EXISTS idx_rt_epoch ON raw_transcript(checkpoint_epoch);
208
+
209
+ -- S27: checkpoint-epoch registry. One row per compaction epoch; the
210
+ -- summary_message_text is the verbatim system message that replaced the
211
+ -- trimmed prefix. Informational bookkeeping (the raw_transcript rows are
212
+ -- authoritative); refresh-safe via ON CONFLICT(epoch_id) DO UPDATE.
213
+ CREATE TABLE IF NOT EXISTS checkpoint_epochs (
214
+ epoch_id TEXT PRIMARY KEY,
215
+ session_id TEXT NOT NULL,
216
+ started_seq INTEGER NOT NULL,
217
+ committed_seq INTEGER NOT NULL,
218
+ summary_message_text TEXT NOT NULL,
219
+ cut_index INTEGER NOT NULL,
220
+ checkpoint_id TEXT NOT NULL,
221
+ created_at INTEGER NOT NULL
222
+ );
223
+ CREATE INDEX IF NOT EXISTS idx_epoch_session ON checkpoint_epochs(session_id, created_at DESC);
224
+
225
+ -- S27 Task 6: dedup_mirror for space-efficient deduplicated storage.
226
+ -- Each unique content_hash stores its bytes ONCE; raw_transcript rows
227
+ -- reference this table via content_ref instead of storing duplicate content_bytes inline.
228
+ CREATE TABLE IF NOT EXISTS dedup_mirror (
229
+ content_hash TEXT PRIMARY KEY,
230
+ content_bytes TEXT NOT NULL,
231
+ ref_count INTEGER NOT NULL DEFAULT 1,
232
+ first_seen_seq INTEGER NOT NULL,
233
+ created_at INTEGER NOT NULL
234
+ );
235
+
236
+ -- S30 game mode: global toggle state (single row, id=1). Holds the
237
+ -- game-mode on/off switch, the active visual-effect theme id, and the TUI
238
+ -- widget display mode. Global across all repos; written by /mega-game and
239
+ -- the dashboard settings strip (S32). Local SQLite (PREVENT-PI-004).
240
+ CREATE TABLE IF NOT EXISTS game_state (
241
+ id INTEGER PRIMARY KEY CHECK(id = 1),
242
+ game_mode_on INTEGER NOT NULL DEFAULT 0,
243
+ theme TEXT NOT NULL DEFAULT 'transparent',
244
+ tui_display_mode TEXT NOT NULL DEFAULT 'full'
245
+ CHECK(tui_display_mode IN ('full','minimal'))
246
+ );
247
+ -- S33 game mode: per-repo leaderboard metrics. One row per recorded event
248
+ -- (turn_end / session_compact); leaderboard() derives rankings. 'repos' is
249
+ -- derived (COUNT DISTINCT, never recorded). Local SQLite (PREVENT-PI-004).
250
+ CREATE TABLE IF NOT EXISTS game_scores (
251
+ repo_root TEXT NOT NULL,
252
+ metric TEXT NOT NULL CHECK(metric IN ('cache','dedupe','turns','repos','mega_cache')),
253
+ ts INTEGER NOT NULL,
254
+ value REAL NOT NULL,
255
+ meta TEXT,
256
+ PRIMARY KEY(repo_root, metric, ts)
257
+ ) WITHOUT ROWID;
258
+ CREATE INDEX IF NOT EXISTS idx_game_scores_metric_ts ON game_scores(metric, ts);
259
+
260
+ -- S35 game mode: achievements (9 rows, seeded idempotently on first open).
261
+ -- hidden=1 AND unlocked_at IS NULL => render NOTHING (no teaser). Local SQLite.
262
+ CREATE TABLE IF NOT EXISTS game_achievements (
263
+ id TEXT PRIMARY KEY,
264
+ title TEXT NOT NULL,
265
+ description TEXT NOT NULL,
266
+ hidden INTEGER NOT NULL DEFAULT 0 CHECK(hidden IN (0,1)),
267
+ icon TEXT,
268
+ unlocked_at INTEGER NULL
269
+ ) WITHOUT ROWID;
270
+ `);
271
+ // Idempotent column migrations. `CREATE TABLE IF NOT EXISTS` is a no-op on a
272
+ // pre-existing table, so new columns added to context_chunks after a store was
273
+ // first created (e.g. original_token_estimate in v0.4.2) must be ALTERed in for
274
+ // databases created by an older version — otherwise repoStats()/upsert crash
275
+ // with "no such column" and the extension fails to load. Additive only.
276
+ ensureColumn(db, "context_chunks", "original_token_estimate", "INTEGER");
277
+ // S27 Task 6: content_ref column in raw_transcript for dedup_mirror references.
278
+ ensureColumn(db, "raw_transcript", "content_ref", "TEXT");
279
+ // S20 memory-RAG extension: additive columns for auto-review ops. Idempotent —
280
+ // only alters DBs created by an older version that lack these columns.
281
+ ensureColumn(db, "memories", "category", "TEXT");
282
+ ensureColumn(db, "memories", "target", "TEXT");
283
+ ensureColumn(db, "memories", "last_referenced", "INTEGER");
284
+ ensureColumn(db, "memories", "source_turn", "INTEGER");
285
+ // S25: RAPTOR freshness-guard timestamp. Additive; old DBs have NULL → 0 →
286
+ // treated as stale → flat fallback (safe).
287
+ ensureColumn(db, "raptor_nodes", "built_at", "INTEGER");
288
+ // S35: idempotent seed of the 9 achievement rows. ON CONFLICT(id) DO
289
+ // NOTHING so a re-open never clobbers an already-unlocked row's
290
+ // unlocked_at. No user input reaches this SQL (PREVENT-002 safe).
291
+ const seedAch = db.prepare(
292
+ `INSERT INTO game_achievements (id, title, description, hidden, icon)
293
+ VALUES (?, ?, ?, ?, ?) ON CONFLICT(id) DO NOTHING`,
294
+ );
295
+ for (const d of ACHIEVEMENT_DEFS) {
296
+ seedAch.run(d.id, d.title, d.description, d.hidden ? 1 : 0, d.icon);
297
+ }
298
+
299
+ const v = db.prepare("SELECT value FROM meta WHERE key='schema_version'").get() as
300
+ | { value: string }
301
+ | undefined;
302
+ if (!v) {
303
+ db.prepare("INSERT INTO meta(key, value) VALUES(?, ?)").run("schema_version", String(SCHEMA_VERSION));
304
+ }
305
+ }
@@ -0,0 +1,38 @@
1
+ /**
2
+ * session-state.ts — `session_state` table (injection tracking).
3
+ */
4
+ import type { DatabaseSync } from "node:sqlite";
5
+ import type { SessionState } from "../../store.js";
6
+ import { getStateDir, normalizeSessionId } from "../../store.js";
7
+ import { openStore, jsonText } from "./utils.js";
8
+
9
+ function loadSessionStateRow(sid: string, db: DatabaseSync): SessionState {
10
+ const row = db.prepare("SELECT * FROM session_state WHERE session_id = ?").get(sid) as any;
11
+ if (!row) {
12
+ return { injectedCheckpointIds: [], storedRegionHashes: [] };
13
+ }
14
+ return {
15
+ injectedCheckpointIds: row.injected_checkpoint_ids ? JSON.parse(row.injected_checkpoint_ids) : [],
16
+ storedRegionHashes: row.stored_region_hashes ? JSON.parse(row.stored_region_hashes) : [],
17
+ };
18
+ }
19
+
20
+ export function loadSessionState(sessionId: string, stateDir: string = getStateDir()): SessionState {
21
+ return loadSessionStateRow(normalizeSessionId(sessionId), openStore(stateDir));
22
+ }
23
+
24
+ export function saveSessionState(sessionId: string, state: SessionState, stateDir: string = getStateDir()): void {
25
+ const db = openStore(stateDir);
26
+ const sid = normalizeSessionId(sessionId);
27
+ db.prepare(
28
+ `INSERT INTO session_state(session_id, injected_checkpoint_ids, stored_region_hashes)
29
+ VALUES(@sid, @inj, @reg)
30
+ ON CONFLICT(session_id) DO UPDATE SET
31
+ injected_checkpoint_ids=excluded.injected_checkpoint_ids,
32
+ stored_region_hashes=excluded.stored_region_hashes`,
33
+ ).run({
34
+ sid,
35
+ inj: jsonText(state.injectedCheckpointIds),
36
+ reg: jsonText(state.storedRegionHashes),
37
+ });
38
+ }
@@ -0,0 +1,127 @@
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
+
8
+ export interface StoreStats {
9
+ checkpointCount: number;
10
+ totalTokenEstimate: number;
11
+ lastCheckpointId: string | undefined;
12
+ lastSummary: string | undefined;
13
+ }
14
+
15
+ export function storeStats(sessionId: string, stateDir: string = getStateDir()): StoreStats {
16
+ const db = openStore(stateDir);
17
+ const sid = normalizeSessionId(sessionId);
18
+ const row = db
19
+ .prepare(
20
+ `SELECT COUNT(*) AS c, COALESCE(SUM(token_estimate),0) AS tok,
21
+ MAX(id) AS lastId
22
+ FROM context_chunks WHERE session_id = ?`,
23
+ )
24
+ .get(sid) as { c: number; tok: number; lastId: string | null };
25
+ let lastSummary: string | undefined;
26
+ if (row.lastId) {
27
+ const s = db.prepare("SELECT summary FROM context_chunks WHERE id = ?").get(row.lastId) as
28
+ | { summary: string }
29
+ | undefined;
30
+ lastSummary = s?.summary;
31
+ }
32
+ return {
33
+ checkpointCount: row.c,
34
+ totalTokenEstimate: row.tok,
35
+ lastCheckpointId: row.lastId ?? undefined,
36
+ lastSummary,
37
+ };
38
+ }
39
+
40
+ /** Repo-wide stats — aggregates every session in this store (one per repo).
41
+ * Backed by the SQLite `meta` cumulative counters (`tokens_saved`,
42
+ * `dedup_attempts`, `deduped`) plus a SUM over all `context_chunks`. This is the
43
+ * cumulative, resumable, cross-device view the dashboard surfaces as "Repo …". */
44
+ export interface RepoStats {
45
+ /** Total checkpoints across all sessions (excludes SemDeDup-removed rows). */
46
+ checkpointCount: number;
47
+ /** Sum of all stored checkpoint token estimates (repo-wide). */
48
+ totalTokenEstimate: number;
49
+ /** Total active sessions with at least one checkpoint. */
50
+ sessionCount: number;
51
+ /** Cumulative stored-summary tokens saved (Σ stored summaries). */
52
+ tokensSaved: number;
53
+ /** Sum of original dropped-region token estimates (repo-wide). */
54
+ originalTokens: number;
55
+ /** Cumulative dedup add() attempts (store-wide). */
56
+ dedupAttempts: number;
57
+ /** Cumulative deduped collapses (store-wide). */
58
+ dedupCollapsed: number;
59
+ /** Storage dedup rate (deduped / attempts), 0..1. */
60
+ storageDedupRate: number;
61
+ }
62
+
63
+ /**
64
+ * Data-safety invariant metrics (Phase 0 — trust foundation). Proves that every
65
+ * compacted region is still recoverable: we retain a compressed_original blob for
66
+ * each checkpoint and permanently delete nothing. "removed" rows are SemDeDup
67
+ * duplicates whose ORIGINAL is still retained on the surviving checkpoint — they
68
+ * are not data loss, so they are reported separately, not as deletions.
69
+ */
70
+ export interface DataInvariantStats {
71
+ /** Checkpoints with a recoverable compressed_original blob. */
72
+ regionsRetained: number;
73
+ /** Total bytes of compressed_original retained (recoverable verbatim). */
74
+ compressedOriginalBytes: number;
75
+ /** Checkpoints missing a compressed_original blob (pre-blob or direct add). */
76
+ regionsWithoutBlob: number;
77
+ /** Bytes permanently deleted by the extension. ALWAYS 0 — the invariant. */
78
+ bytesPermanentlyDeleted: number;
79
+ /** Duplicate rows collapsed by dedup (original retained on the survivor). */
80
+ duplicatesCollapsed: number;
81
+ }
82
+
83
+ export function dataInvariantStats(stateDir: string = getStateDir()): DataInvariantStats {
84
+ const db = openStore(stateDir);
85
+ const row = db
86
+ .prepare(
87
+ `SELECT
88
+ COUNT(compressed_original) AS withBlob,
89
+ COALESCE(SUM(LENGTH(compressed_original)),0) AS blobBytes,
90
+ SUM(CASE WHEN compressed_original IS NULL THEN 1 ELSE 0 END) AS noBlob
91
+ FROM context_chunks WHERE dedup_status != 'removed'`,
92
+ )
93
+ .get() as { withBlob: number; blobBytes: number; noBlob: number };
94
+ const removed = db
95
+ .prepare(`SELECT COUNT(*) AS c FROM context_chunks WHERE dedup_status = 'removed'`)
96
+ .get() as { c: number };
97
+ return {
98
+ regionsRetained: row.withBlob,
99
+ compressedOriginalBytes: row.blobBytes,
100
+ regionsWithoutBlob: row.noBlob ?? 0,
101
+ bytesPermanentlyDeleted: 0,
102
+ duplicatesCollapsed: removed.c,
103
+ };
104
+ }
105
+
106
+ export function repoStats(stateDir: string = getStateDir()): RepoStats {
107
+ const db = openStore(stateDir);
108
+ const row = db
109
+ .prepare(
110
+ `SELECT COUNT(*) AS c, COALESCE(SUM(token_estimate),0) AS tok,
111
+ COALESCE(SUM(original_token_estimate),0) AS orig,
112
+ COUNT(DISTINCT session_id) AS sessions
113
+ FROM context_chunks WHERE dedup_status != 'removed'`,
114
+ )
115
+ .get() as { c: number; tok: number; orig: number; sessions: number };
116
+ const ds = getDedupStats(stateDir);
117
+ return {
118
+ checkpointCount: row.c,
119
+ totalTokenEstimate: row.tok,
120
+ originalTokens: row.orig,
121
+ sessionCount: row.sessions,
122
+ tokensSaved: getMetaNumber("tokens_saved", stateDir),
123
+ dedupAttempts: ds.attempts,
124
+ dedupCollapsed: ds.deduped,
125
+ storageDedupRate: ds.attempts === 0 ? 0 : ds.deduped / ds.attempts,
126
+ };
127
+ }