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,82 @@
1
+ /**
2
+ * meta.ts — `meta` table key/value helpers + cumulative counters
3
+ * (tokens_saved, dedup stats, compact count, recall injected, cache-hit tokens).
4
+ */
5
+ import { getStateDir } from "../../store.js";
6
+ import { openStore } from "./utils.js";
7
+ /** Read a string-valued meta key (or undefined). Used for cumulative counters. */
8
+ export function getMeta(key, stateDir = getStateDir()) {
9
+ const db = openStore(stateDir);
10
+ const row = db.prepare("SELECT value FROM meta WHERE key = ?").get(key);
11
+ return row?.value;
12
+ }
13
+ /**
14
+ * Cumulative "tokens saved" — the sum of stored checkpoint token estimates across
15
+ * all compactions in this store (one per repo). Persisted in the SQLite `meta`
16
+ * table so it survives session restarts and travels with the repo's state dir,
17
+ * mirroring how `storageDedupRate` is cumulative. Incremented in VectorStore.add()
18
+ * when a new (non-deduped) checkpoint is persisted.
19
+ */
20
+ export function getTokensSaved(stateDir = getStateDir()) {
21
+ const raw = getMeta("tokens_saved", stateDir);
22
+ const n = raw == null ? 0 : Number(raw);
23
+ return Number.isFinite(n) ? n : 0;
24
+ }
25
+ /** Add `delta` (>=0) to the cumulative tokens-saved counter. */
26
+ export function addTokensSaved(delta, stateDir = getStateDir()) {
27
+ if (!(delta > 0))
28
+ return;
29
+ const db = openStore(stateDir);
30
+ db.prepare(`INSERT INTO meta(key, value) VALUES('tokens_saved', ?)
31
+ ON CONFLICT(key) DO UPDATE SET value = CAST(CAST(value AS INTEGER) + ? AS TEXT)`).run(String(delta), delta);
32
+ }
33
+ /** Read a store-wide integer counter from the meta table (0 if absent). */
34
+ export function getMetaNumber(key, stateDir = getStateDir()) {
35
+ const raw = getMeta(key, stateDir);
36
+ const n = raw == null ? 0 : Number(raw);
37
+ return Number.isFinite(n) ? n : 0;
38
+ }
39
+ /** Atomically add `delta` to an integer meta counter. */
40
+ function incMeta(key, delta, stateDir = getStateDir()) {
41
+ if (!(delta > 0))
42
+ return;
43
+ const db = openStore(stateDir);
44
+ db.prepare(`INSERT INTO meta(key, value) VALUES(?, ?)
45
+ ON CONFLICT(key) DO UPDATE SET value = CAST(CAST(value AS INTEGER) + ? AS TEXT)`).run(key, String(delta), delta);
46
+ }
47
+ /** Read the cumulative store-wide dedup counters. */
48
+ export function getDedupStats(stateDir = getStateDir()) {
49
+ return {
50
+ attempts: getMetaNumber("dedup_attempts", stateDir),
51
+ deduped: getMetaNumber("deduped", stateDir),
52
+ };
53
+ }
54
+ /** Increment the store-wide dedup counters for one add() call. */
55
+ export function bumpDedupStats(deduped, stateDir = getStateDir()) {
56
+ incMeta("dedup_attempts", 1, stateDir);
57
+ if (deduped)
58
+ incMeta("deduped", 1, stateDir);
59
+ }
60
+ // --- Live dashboard counters (schemaless meta key/value — NO migration) -----
61
+ // These reuse the private `incMeta` atomically-incrementing integer counter so
62
+ // all cumulative tallies live in the same `meta` table as tokens_saved etc.
63
+ export function incCompactCount(stateDir = getStateDir()) {
64
+ incMeta("compact_count", 1, stateDir);
65
+ }
66
+ export function getCompactCount(stateDir = getStateDir()) {
67
+ return getMetaNumber("compact_count", stateDir);
68
+ }
69
+ export function incRecallInjected(n, stateDir = getStateDir()) {
70
+ if (n > 0)
71
+ incMeta("recall_injected", n, stateDir);
72
+ }
73
+ export function getRecallInjected(stateDir = getStateDir()) {
74
+ return getMetaNumber("recall_injected", stateDir);
75
+ }
76
+ export function incCacheHitTokens(delta, stateDir = getStateDir()) {
77
+ if (delta > 0)
78
+ incMeta("cache_hit_tokens_saved", delta, stateDir);
79
+ }
80
+ export function getCacheHitTokensSaved(stateDir = getStateDir()) {
81
+ return getMetaNumber("cache_hit_tokens_saved", stateDir);
82
+ }
@@ -0,0 +1,47 @@
1
+ /**
2
+ * model-snapshots.ts — `model_snapshots` table (active model/provider per repo).
3
+ */
4
+ import { getStateDir } from "../../store.js";
5
+ import { openStore } from "./utils.js";
6
+ /** Persist the active model/provider for a repo (latest row wins per repo). */
7
+ export function recordModelSnapshot(repoRoot, snap, stateDir = getStateDir()) {
8
+ const db = openStore(stateDir);
9
+ db.prepare(`INSERT INTO model_snapshots
10
+ (repo_root, provider, provider_name, model_id, model_name, input_rate,
11
+ output_rate, context_window, max_tokens, reasoning, captured_at)
12
+ VALUES (@repo_root, @provider, @provider_name, @model_id, @model_name,
13
+ @input_rate, @output_rate, @context_window, @max_tokens, @reasoning, @captured_at)`).run({
14
+ repo_root: repoRoot,
15
+ provider: snap.provider,
16
+ provider_name: snap.providerName,
17
+ model_id: snap.modelId,
18
+ model_name: snap.modelName,
19
+ input_rate: snap.inputRate,
20
+ output_rate: snap.outputRate,
21
+ context_window: snap.contextWindow,
22
+ max_tokens: snap.maxTokens,
23
+ reasoning: snap.reasoning ? 1 : 0,
24
+ captured_at: Date.now(),
25
+ });
26
+ }
27
+ /** Most recent model/provider snapshot for a repo, or undefined. */
28
+ export function latestModelSnapshot(stateDir = getStateDir()) {
29
+ const db = openStore(stateDir);
30
+ const row = db
31
+ .prepare(`SELECT * FROM model_snapshots ORDER BY captured_at DESC LIMIT 1`)
32
+ .get();
33
+ if (!row)
34
+ return undefined;
35
+ return {
36
+ provider: row.provider,
37
+ providerName: row.provider_name,
38
+ modelId: row.model_id,
39
+ modelName: row.model_name,
40
+ inputRate: row.input_rate,
41
+ outputRate: row.output_rate,
42
+ contextWindow: row.context_window,
43
+ maxTokens: row.max_tokens,
44
+ reasoning: row.reasoning === 1,
45
+ capturedAt: row.captured_at,
46
+ };
47
+ }
@@ -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,294 @@
1
+ import { ACHIEVEMENT_DEFS } from "../../game/scoring.js";
2
+ const SCHEMA_VERSION = 2;
3
+ /**
4
+ * Add `column` (with `decl`, e.g. "INTEGER") to `table` if it does not already
5
+ * exist. Idempotent: checks PRAGMA table_info first, so it is safe to run on
6
+ * every open. Table/column/decl are code-controlled constants (never user
7
+ * input), so the unavoidable identifier interpolation here does not violate
8
+ * PREVENT-002 (no external data reaches this SQL).
9
+ */
10
+ export function ensureColumn(db, table, column, decl) {
11
+ const cols = db.prepare(`PRAGMA table_info(${table})`).all();
12
+ if (cols.some((c) => c.name === column))
13
+ return;
14
+ db.exec(`ALTER TABLE ${table} ADD COLUMN ${column} ${decl}`);
15
+ }
16
+ export function initSchema(db) {
17
+ db.exec(`
18
+ CREATE TABLE IF NOT EXISTS context_chunks (
19
+ id TEXT NOT NULL,
20
+ session_id TEXT NOT NULL,
21
+ region_hash TEXT,
22
+ content_hash TEXT,
23
+ content_hash2 TEXT,
24
+ content_hash_version INTEGER,
25
+ normalized_text TEXT,
26
+ summary TEXT,
27
+ topic_summary TEXT,
28
+ summary_hash TEXT,
29
+ key_decisions TEXT, -- JSON array
30
+ next_steps TEXT, -- JSON array
31
+ files_modified TEXT, -- JSON array
32
+ embedding_blob BLOB, -- float32 vector
33
+ token_estimate INTEGER,
34
+ original_token_estimate INTEGER, -- dropped region size (tokens saved = orig − stored)
35
+ timestamp INTEGER,
36
+ dedup_status TEXT DEFAULT 'active',
37
+ compressed_original BLOB -- optional DR copy
38
+ );
39
+ -- Primary key is (session_id, id): checkpoint ids are unique per session
40
+ -- (chkpt_001 per session), not globally, so a bare id PK would collide
41
+ -- across sessions on the nextCheckpointId sequence.
42
+ CREATE UNIQUE INDEX IF NOT EXISTS idx_chunks_pk
43
+ ON context_chunks(session_id, id);
44
+ CREATE INDEX IF NOT EXISTS idx_chunks_session ON context_chunks(session_id);
45
+ CREATE INDEX IF NOT EXISTS idx_chunks_region ON context_chunks(region_hash);
46
+ CREATE INDEX IF NOT EXISTS idx_chunks_content ON context_chunks(content_hash);
47
+ -- Partial UNIQUE (QA #1): null content_hash rows never violate the constraint;
48
+ -- ON CONFLICT DO NOTHING makes backfill + L0 inserts safe.
49
+ CREATE UNIQUE INDEX IF NOT EXISTS idx_content_hash
50
+ ON context_chunks(session_id, content_hash) WHERE content_hash IS NOT NULL;
51
+
52
+ -- Sprint 11: MinHash signature + LSH bucket tables for L1 near-dup dedup.
53
+ CREATE TABLE IF NOT EXISTS minhash_signatures (
54
+ chunk_id TEXT NOT NULL,
55
+ session_id TEXT NOT NULL,
56
+ signature_version INTEGER NOT NULL,
57
+ signatures TEXT NOT NULL, -- JSON array of 256 uint32
58
+ PRIMARY KEY (chunk_id, signature_version)
59
+ );
60
+ CREATE INDEX IF NOT EXISTS idx_minhash_session ON minhash_signatures(session_id);
61
+
62
+ CREATE TABLE IF NOT EXISTS dedup_lsh_buckets (
63
+ bucket_key TEXT NOT NULL,
64
+ chunk_id TEXT NOT NULL,
65
+ session_id TEXT NOT NULL,
66
+ signature_version INTEGER NOT NULL,
67
+ PRIMARY KEY (bucket_key, chunk_id)
68
+ );
69
+ CREATE INDEX IF NOT EXISTS idx_lsh_bucket ON dedup_lsh_buckets(bucket_key, session_id);
70
+
71
+ CREATE TABLE IF NOT EXISTS session_state (
72
+ session_id TEXT PRIMARY KEY,
73
+ injected_checkpoint_ids TEXT, -- JSON array
74
+ stored_region_hashes TEXT -- JSON array
75
+ );
76
+
77
+ CREATE TABLE IF NOT EXISTS meta (
78
+ key TEXT PRIMARY KEY,
79
+ value TEXT
80
+ );
81
+
82
+ -- Sprint 13 (RAPTOR): hierarchical summary tree nodes. children are a JSON
83
+ -- array of child node ids (or raw leaf ids at the bottom); embedding_blob
84
+ -- is the node centroid. Additive; retrieval ignores this table until
85
+ -- Sprint 14 promotes RAPTOR out of shadow mode.
86
+ CREATE TABLE IF NOT EXISTS raptor_nodes (
87
+ id TEXT NOT NULL,
88
+ session_id TEXT NOT NULL,
89
+ level INTEGER NOT NULL,
90
+ parent_id TEXT,
91
+ children TEXT, -- JSON array of child ids
92
+ summary TEXT,
93
+ embedding_blob BLOB, -- float32 centroid
94
+ quality_marker TEXT DEFAULT 'low',
95
+ token_estimate INTEGER,
96
+ built_at INTEGER, -- S25: epoch ms when the tree was built (freshness guard)
97
+ PRIMARY KEY (session_id, id)
98
+ );
99
+ CREATE INDEX IF NOT EXISTS idx_raptor_session ON raptor_nodes(session_id);
100
+ CREATE INDEX IF NOT EXISTS idx_raptor_parent ON raptor_nodes(parent_id);
101
+
102
+ -- Foundation for future features (resume sessions, daily log, lessons
103
+ -- learned). Scaffolded now so all store data lives in SQLite from day one;
104
+ -- population is minimal (touchSession / logDaily on compact) and the full
105
+ -- UI/recall for these lands in later sprints.
106
+
107
+ -- Per-session registry (resume + per-repo session history).
108
+ CREATE TABLE IF NOT EXISTS sessions (
109
+ session_id TEXT PRIMARY KEY,
110
+ repo TEXT,
111
+ started_at INTEGER,
112
+ ended_at INTEGER,
113
+ last_compacted_at INTEGER,
114
+ status TEXT DEFAULT 'active'
115
+ );
116
+
117
+ -- Append-only daily activity log (the "daily log" feature seed).
118
+ CREATE TABLE IF NOT EXISTS daily_log (
119
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
120
+ day TEXT NOT NULL, -- YYYY-MM-DD
121
+ session_id TEXT,
122
+ event TEXT, -- e.g. 'compact'
123
+ detail TEXT,
124
+ tokens_saved INTEGER DEFAULT 0,
125
+ ts INTEGER
126
+ );
127
+ CREATE INDEX IF NOT EXISTS idx_daily_log_day ON daily_log(day);
128
+
129
+ -- Active model/provider for cost estimation + the future multi-repo
130
+ -- dashboard (Phase 5b). One row per (repo, model change); latest wins.
131
+ CREATE TABLE IF NOT EXISTS model_snapshots (
132
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
133
+ repo_root TEXT NOT NULL,
134
+ provider TEXT NOT NULL,
135
+ provider_name TEXT,
136
+ model_id TEXT NOT NULL,
137
+ model_name TEXT,
138
+ input_rate REAL, -- USD per input token (Model.cost.input)
139
+ output_rate REAL, -- USD per output token (Model.cost.output)
140
+ context_window INTEGER,
141
+ max_tokens INTEGER,
142
+ reasoning INTEGER DEFAULT 0,
143
+ captured_at INTEGER
144
+ );
145
+ CREATE INDEX IF NOT EXISTS idx_model_repo ON model_snapshots(repo_root);
146
+
147
+ -- Lessons learned (future recall/browse feature seed).
148
+ CREATE TABLE IF NOT EXISTS lessons (
149
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
150
+ session_id TEXT,
151
+ repo TEXT,
152
+ lesson TEXT,
153
+ ts INTEGER
154
+ );
155
+
156
+ -- Durable "save to memory" store (taken over from memory extensions).
157
+ -- One row per saved memory; scoped by repo so memory travels with the
158
+ -- clone. All params are parameterized (PREVENT-002).
159
+ CREATE TABLE IF NOT EXISTS memories (
160
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
161
+ repo TEXT,
162
+ kind TEXT DEFAULT 'note', -- note | fact | decision | preference
163
+ content TEXT NOT NULL,
164
+ tags TEXT, -- JSON array of strings
165
+ created_at INTEGER,
166
+ last_recalled_at INTEGER,
167
+ -- S20 memory-RAG extension (auto-review add/replace/remove ops).
168
+ category TEXT, -- typed bucket, e.g. decision | fact | preference
169
+ target TEXT, -- optional subject/scope this memory targets
170
+ last_referenced INTEGER, -- last time memory was referenced by recall (epoch s)
171
+ source_turn INTEGER -- conversation turn that produced this memory
172
+ );
173
+ CREATE INDEX IF NOT EXISTS idx_memories_repo ON memories(repo);
174
+
175
+ -- FTS5 trigram virtual table (Sprint 9+ pg_trgm-equivalent verification).
176
+ CREATE VIRTUAL TABLE IF NOT EXISTS context_chunks_trgm USING fts5(
177
+ id UNINDEXED,
178
+ normalized_text,
179
+ tokenize='trigram'
180
+ );
181
+
182
+ -- S27: durable raw-transcript mirror (MEGACOMPACT_DB_MIRROR). Appended
183
+ -- RAW message bytes per session so a compacted window can be rehydrated
184
+ -- from the local store instead of the pi runtime transcript (which is
185
+ -- trimmed). PK is (content_hash, session_id) — NOT content_hash alone —
186
+ -- so identical content in different sessions never collides. Additive:
187
+ -- CREATE TABLE IF NOT EXISTS leaves existing DBs untouched on open until
188
+ -- the S27 mirror flag is flipped on. All queries parameterized (PREVENT-002).
189
+ CREATE TABLE IF NOT EXISTS raw_transcript (
190
+ content_hash TEXT NOT NULL,
191
+ session_id TEXT NOT NULL,
192
+ seq INTEGER NOT NULL,
193
+ role TEXT NOT NULL,
194
+ content_bytes TEXT NOT NULL,
195
+ tool_name TEXT,
196
+ message_timestamp INTEGER, -- ORIGINAL msg ts at append, NOT served
197
+ checkpoint_epoch TEXT NOT NULL,
198
+ PRIMARY KEY (content_hash, session_id)
199
+ );
200
+ CREATE INDEX IF NOT EXISTS idx_rt_session_seq ON raw_transcript(session_id, seq);
201
+ CREATE INDEX IF NOT EXISTS idx_rt_epoch ON raw_transcript(checkpoint_epoch);
202
+
203
+ -- S27: checkpoint-epoch registry. One row per compaction epoch; the
204
+ -- summary_message_text is the verbatim system message that replaced the
205
+ -- trimmed prefix. Informational bookkeeping (the raw_transcript rows are
206
+ -- authoritative); refresh-safe via ON CONFLICT(epoch_id) DO UPDATE.
207
+ CREATE TABLE IF NOT EXISTS checkpoint_epochs (
208
+ epoch_id TEXT PRIMARY KEY,
209
+ session_id TEXT NOT NULL,
210
+ started_seq INTEGER NOT NULL,
211
+ committed_seq INTEGER NOT NULL,
212
+ summary_message_text TEXT NOT NULL,
213
+ cut_index INTEGER NOT NULL,
214
+ checkpoint_id TEXT NOT NULL,
215
+ created_at INTEGER NOT NULL
216
+ );
217
+ CREATE INDEX IF NOT EXISTS idx_epoch_session ON checkpoint_epochs(session_id, created_at DESC);
218
+
219
+ -- S27 Task 6: dedup_mirror for space-efficient deduplicated storage.
220
+ -- Each unique content_hash stores its bytes ONCE; raw_transcript rows
221
+ -- reference this table via content_ref instead of storing duplicate content_bytes inline.
222
+ CREATE TABLE IF NOT EXISTS dedup_mirror (
223
+ content_hash TEXT PRIMARY KEY,
224
+ content_bytes TEXT NOT NULL,
225
+ ref_count INTEGER NOT NULL DEFAULT 1,
226
+ first_seen_seq INTEGER NOT NULL,
227
+ created_at INTEGER NOT NULL
228
+ );
229
+
230
+ -- S30 game mode: global toggle state (single row, id=1). Holds the
231
+ -- game-mode on/off switch, the active visual-effect theme id, and the TUI
232
+ -- widget display mode. Global across all repos; written by /mega-game and
233
+ -- the dashboard settings strip (S32). Local SQLite (PREVENT-PI-004).
234
+ CREATE TABLE IF NOT EXISTS game_state (
235
+ id INTEGER PRIMARY KEY CHECK(id = 1),
236
+ game_mode_on INTEGER NOT NULL DEFAULT 0,
237
+ theme TEXT NOT NULL DEFAULT 'transparent',
238
+ tui_display_mode TEXT NOT NULL DEFAULT 'full'
239
+ CHECK(tui_display_mode IN ('full','minimal'))
240
+ );
241
+ -- S33 game mode: per-repo leaderboard metrics. One row per recorded event
242
+ -- (turn_end / session_compact); leaderboard() derives rankings. 'repos' is
243
+ -- derived (COUNT DISTINCT, never recorded). Local SQLite (PREVENT-PI-004).
244
+ CREATE TABLE IF NOT EXISTS game_scores (
245
+ repo_root TEXT NOT NULL,
246
+ metric TEXT NOT NULL CHECK(metric IN ('cache','dedupe','turns','repos','mega_cache')),
247
+ ts INTEGER NOT NULL,
248
+ value REAL NOT NULL,
249
+ meta TEXT,
250
+ PRIMARY KEY(repo_root, metric, ts)
251
+ ) WITHOUT ROWID;
252
+ CREATE INDEX IF NOT EXISTS idx_game_scores_metric_ts ON game_scores(metric, ts);
253
+
254
+ -- S35 game mode: achievements (9 rows, seeded idempotently on first open).
255
+ -- hidden=1 AND unlocked_at IS NULL => render NOTHING (no teaser). Local SQLite.
256
+ CREATE TABLE IF NOT EXISTS game_achievements (
257
+ id TEXT PRIMARY KEY,
258
+ title TEXT NOT NULL,
259
+ description TEXT NOT NULL,
260
+ hidden INTEGER NOT NULL DEFAULT 0 CHECK(hidden IN (0,1)),
261
+ icon TEXT,
262
+ unlocked_at INTEGER NULL
263
+ ) WITHOUT ROWID;
264
+ `);
265
+ // Idempotent column migrations. `CREATE TABLE IF NOT EXISTS` is a no-op on a
266
+ // pre-existing table, so new columns added to context_chunks after a store was
267
+ // first created (e.g. original_token_estimate in v0.4.2) must be ALTERed in for
268
+ // databases created by an older version — otherwise repoStats()/upsert crash
269
+ // with "no such column" and the extension fails to load. Additive only.
270
+ ensureColumn(db, "context_chunks", "original_token_estimate", "INTEGER");
271
+ // S27 Task 6: content_ref column in raw_transcript for dedup_mirror references.
272
+ ensureColumn(db, "raw_transcript", "content_ref", "TEXT");
273
+ // S20 memory-RAG extension: additive columns for auto-review ops. Idempotent —
274
+ // only alters DBs created by an older version that lack these columns.
275
+ ensureColumn(db, "memories", "category", "TEXT");
276
+ ensureColumn(db, "memories", "target", "TEXT");
277
+ ensureColumn(db, "memories", "last_referenced", "INTEGER");
278
+ ensureColumn(db, "memories", "source_turn", "INTEGER");
279
+ // S25: RAPTOR freshness-guard timestamp. Additive; old DBs have NULL → 0 →
280
+ // treated as stale → flat fallback (safe).
281
+ ensureColumn(db, "raptor_nodes", "built_at", "INTEGER");
282
+ // S35: idempotent seed of the 9 achievement rows. ON CONFLICT(id) DO
283
+ // NOTHING so a re-open never clobbers an already-unlocked row's
284
+ // unlocked_at. No user input reaches this SQL (PREVENT-002 safe).
285
+ const seedAch = db.prepare(`INSERT INTO game_achievements (id, title, description, hidden, icon)
286
+ VALUES (?, ?, ?, ?, ?) ON CONFLICT(id) DO NOTHING`);
287
+ for (const d of ACHIEVEMENT_DEFS) {
288
+ seedAch.run(d.id, d.title, d.description, d.hidden ? 1 : 0, d.icon);
289
+ }
290
+ const v = db.prepare("SELECT value FROM meta WHERE key='schema_version'").get();
291
+ if (!v) {
292
+ db.prepare("INSERT INTO meta(key, value) VALUES(?, ?)").run("schema_version", String(SCHEMA_VERSION));
293
+ }
294
+ }
@@ -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
+ }