pi-mega-compact 0.9.2 → 0.11.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 (143) hide show
  1. package/README.md +3 -2
  2. package/dist/extensions/dashboard-server/api-contracts/endpoints.js +95 -47
  3. package/dist/extensions/dashboard-server/api-contracts/index.js +1 -1
  4. package/dist/extensions/dashboard-server/api-contracts/turns.js +10 -0
  5. package/dist/extensions/dashboard-server/api-contracts.test.js +3 -2
  6. package/dist/extensions/dashboard-server/routes-topics.js +87 -0
  7. package/dist/extensions/dashboard-server/routes-turns.js +264 -0
  8. package/dist/extensions/dashboard-server/routes.js +3 -1
  9. package/dist/extensions/dashboard-server/server.js +6 -2
  10. package/dist/extensions/mega-compact.js +10 -6
  11. package/dist/extensions/mega-config.js +4 -0
  12. package/dist/extensions/mega-events/agent-handlers.js +62 -49
  13. package/dist/extensions/mega-events/context-handler.js +48 -2
  14. package/dist/extensions/mega-events/session-handlers.js +25 -1
  15. package/dist/extensions/mega-metrics-cmds.js +90 -0
  16. package/dist/extensions/mega-pipeline/recall.js +47 -17
  17. package/dist/extensions/mega-topics-cmds.js +111 -0
  18. package/dist/extensions/mega-turn-store.js +110 -0
  19. package/dist/extensions/mega-turn-store.test.js +68 -0
  20. package/dist/src/config/turns.js +48 -0
  21. package/dist/src/fork.js +33 -0
  22. package/dist/src/fork.test.js +81 -0
  23. package/dist/src/intent.js +51 -0
  24. package/dist/src/intent.test.js +78 -0
  25. package/dist/src/metrics/index.js +4 -0
  26. package/dist/src/metrics/turns.js +118 -0
  27. package/dist/src/metrics/turns.test.js +152 -0
  28. package/dist/src/store/sqlite/raw-transcript.js +5 -3
  29. package/dist/src/store/sqlite.dbmirror.test.js +9 -0
  30. package/dist/src/store/turns/connection.js +123 -0
  31. package/dist/src/store/turns/contract-compliance.test.js +428 -0
  32. package/dist/src/store/turns/index.js +31 -0
  33. package/dist/src/store/turns/memory-store.js +357 -0
  34. package/dist/src/store/turns/memory-store.test.js +9 -0
  35. package/dist/src/store/turns/migrations.js +178 -0
  36. package/dist/src/store/turns/migrations.test.js +138 -0
  37. package/dist/src/store/turns/schema.js +115 -0
  38. package/dist/src/store/turns/sqlite-store.js +455 -0
  39. package/dist/src/store/turns/sqlite-store.test.js +144 -0
  40. package/dist/src/store/turns/types.js +16 -0
  41. package/dist/src/topics/cluster.js +141 -0
  42. package/dist/src/topics/cluster.test.js +150 -0
  43. package/dist/src/topics/index.js +6 -0
  44. package/dist/src/topics/kselection.js +142 -0
  45. package/dist/src/topics/labels.js +56 -0
  46. package/dist/src/topics/store.js +119 -0
  47. package/dist/src/topics/store.test.js +117 -0
  48. package/dist/src/topics/types.js +8 -0
  49. package/dist/src/wiki.js +133 -0
  50. package/dist/src/wiki.test.js +171 -0
  51. package/extensions/dashboard-client/dist/assets/{AchievementTiles-QPo46Pwg.js → AchievementTiles-DZp_xQOW.js} +2 -2
  52. package/extensions/dashboard-client/dist/assets/{AchievementTiles-QPo46Pwg.js.map → AchievementTiles-DZp_xQOW.js.map} +1 -1
  53. package/extensions/dashboard-client/dist/assets/{AchievementsTab-BDJxRXRY.js → AchievementsTab-BzFHpAHM.js} +2 -2
  54. package/extensions/dashboard-client/dist/assets/{AchievementsTab-BDJxRXRY.js.map → AchievementsTab-BzFHpAHM.js.map} +1 -1
  55. package/extensions/dashboard-client/dist/assets/{CacheTab-CUMqXQjd.js → CacheTab-DEQbTq2T.js} +2 -2
  56. package/extensions/dashboard-client/dist/assets/{CacheTab-CUMqXQjd.js.map → CacheTab-DEQbTq2T.js.map} +1 -1
  57. package/extensions/dashboard-client/dist/assets/{ConfigTab-j1dRzurG.js → ConfigTab-DQ4FG33J.js} +2 -2
  58. package/extensions/dashboard-client/dist/assets/{ConfigTab-j1dRzurG.js.map → ConfigTab-DQ4FG33J.js.map} +1 -1
  59. package/extensions/dashboard-client/dist/assets/{EventsTab-CMglXK4p.js → EventsTab-D5HoEVYo.js} +2 -2
  60. package/extensions/dashboard-client/dist/assets/{EventsTab-CMglXK4p.js.map → EventsTab-D5HoEVYo.js.map} +1 -1
  61. package/extensions/dashboard-client/dist/assets/{GameTab-fpaDoyxi.js → GameTab-Jzsc4yeY.js} +2 -2
  62. package/extensions/dashboard-client/dist/assets/{GameTab-fpaDoyxi.js.map → GameTab-Jzsc4yeY.js.map} +1 -1
  63. package/extensions/dashboard-client/dist/assets/{MetricsTab-CWG2crG_.js → MetricsTab-D_XnsEYX.js} +2 -2
  64. package/extensions/dashboard-client/dist/assets/{MetricsTab-CWG2crG_.js.map → MetricsTab-D_XnsEYX.js.map} +1 -1
  65. package/extensions/dashboard-client/dist/assets/{OverviewTab-BaV2D2nf.js → OverviewTab-BMREvAth.js} +2 -2
  66. package/extensions/dashboard-client/dist/assets/{OverviewTab-BaV2D2nf.js.map → OverviewTab-BMREvAth.js.map} +1 -1
  67. package/extensions/dashboard-client/dist/assets/{ReposTab-C-0kuZ_0.js → ReposTab-DuyhOktG.js} +2 -2
  68. package/extensions/dashboard-client/dist/assets/{ReposTab-C-0kuZ_0.js.map → ReposTab-DuyhOktG.js.map} +1 -1
  69. package/extensions/dashboard-client/dist/assets/{SessionsTab-CSYhddCA.js → SessionsTab-mz_vz8i2.js} +2 -2
  70. package/extensions/dashboard-client/dist/assets/{SessionsTab-CSYhddCA.js.map → SessionsTab-mz_vz8i2.js.map} +1 -1
  71. package/extensions/dashboard-client/dist/assets/{TimeSavedCard-Dy4KRjSM.js → TimeSavedCard-B8AIjNTY.js} +2 -2
  72. package/extensions/dashboard-client/dist/assets/{TimeSavedCard-Dy4KRjSM.js.map → TimeSavedCard-B8AIjNTY.js.map} +1 -1
  73. package/extensions/dashboard-client/dist/assets/TopicsTab-DKuct4oD.js +2 -0
  74. package/extensions/dashboard-client/dist/assets/TopicsTab-DKuct4oD.js.map +1 -0
  75. package/extensions/dashboard-client/dist/assets/TurnsTab-11MGLxY8.js +2 -0
  76. package/extensions/dashboard-client/dist/assets/TurnsTab-11MGLxY8.js.map +1 -0
  77. package/extensions/dashboard-client/dist/assets/{index-D_WtU2TV.js → index-CqLN7STl.js} +10 -10
  78. package/extensions/dashboard-client/dist/assets/index-CqLN7STl.js.map +1 -0
  79. package/extensions/dashboard-client/dist/assets/{index-og3ghxyY.css → index-gn66lYD2.css} +1 -1
  80. package/extensions/dashboard-client/dist/assets/{useSSE-C9yVJlGP.js → useSSE-CXrQSbVY.js} +2 -2
  81. package/extensions/dashboard-client/dist/assets/{useSSE-C9yVJlGP.js.map → useSSE-CXrQSbVY.js.map} +1 -1
  82. package/extensions/dashboard-client/dist/index.html +2 -2
  83. package/extensions/dashboard-client/src/App.tsx +10 -2
  84. package/extensions/dashboard-client/src/api/client.ts +90 -1
  85. package/extensions/dashboard-client/src/main.tsx +1 -0
  86. package/extensions/dashboard-client/src/styles/turns.css +142 -0
  87. package/extensions/dashboard-client/src/tabs/TopicsTab.tsx +186 -0
  88. package/extensions/dashboard-client/src/tabs/TurnsTab.tsx +336 -0
  89. package/extensions/dashboard-server/api-contracts/endpoints.ts +394 -291
  90. package/extensions/dashboard-server/api-contracts/game-types.ts +141 -88
  91. package/extensions/dashboard-server/api-contracts/index.ts +153 -133
  92. package/extensions/dashboard-server/api-contracts/turns.ts +114 -0
  93. package/extensions/dashboard-server/api-contracts.test.ts +920 -919
  94. package/extensions/dashboard-server/routes-topics.ts +119 -0
  95. package/extensions/dashboard-server/routes-turns.ts +305 -0
  96. package/extensions/dashboard-server/routes.ts +8 -1
  97. package/extensions/dashboard-server/server.ts +6 -2
  98. package/extensions/mega-compact.ts +75 -59
  99. package/extensions/mega-config.ts +232 -220
  100. package/extensions/mega-events/agent-handlers.ts +194 -151
  101. package/extensions/mega-events/context-handler.ts +50 -1
  102. package/extensions/mega-events/session-handlers.ts +26 -5
  103. package/extensions/mega-metrics-cmds.ts +114 -0
  104. package/extensions/mega-pipeline/recall.ts +215 -152
  105. package/extensions/mega-topics-cmds.ts +151 -0
  106. package/extensions/mega-turn-store.test.ts +108 -0
  107. package/extensions/mega-turn-store.ts +169 -0
  108. package/package.json +3 -1
  109. package/src/config/turns.ts +69 -0
  110. package/src/fork.test.ts +94 -0
  111. package/src/fork.ts +78 -0
  112. package/src/intent.test.ts +87 -0
  113. package/src/intent.ts +115 -0
  114. package/src/metrics/index.ts +9 -0
  115. package/src/metrics/turns.test.ts +165 -0
  116. package/src/metrics/turns.ts +201 -0
  117. package/src/store/sqlite/raw-transcript.ts +9 -3
  118. package/src/store/sqlite.dbmirror.test.ts +10 -0
  119. package/src/store/turns/connection.ts +137 -0
  120. package/src/store/turns/contract-compliance.test.ts +562 -0
  121. package/src/store/turns/index.ts +65 -0
  122. package/src/store/turns/memory-store.test.ts +15 -0
  123. package/src/store/turns/memory-store.ts +469 -0
  124. package/src/store/turns/migrations.test.ts +161 -0
  125. package/src/store/turns/migrations.ts +203 -0
  126. package/src/store/turns/schema.ts +158 -0
  127. package/src/store/turns/sqlite-store.test.ts +161 -0
  128. package/src/store/turns/sqlite-store.ts +656 -0
  129. package/src/store/turns/types.ts +181 -0
  130. package/src/topics/cluster.test.ts +176 -0
  131. package/src/topics/cluster.ts +191 -0
  132. package/src/topics/index.ts +18 -0
  133. package/src/topics/kselection.ts +182 -0
  134. package/src/topics/labels.ts +67 -0
  135. package/src/topics/store.test.ts +132 -0
  136. package/src/topics/store.ts +208 -0
  137. package/src/topics/types.ts +64 -0
  138. package/src/wiki.test.ts +217 -0
  139. package/src/wiki.ts +198 -0
  140. package/dist/extensions/openclaw-mega-compact.js +0 -291
  141. package/dist/src/minilm.js +0 -92
  142. package/dist/src/wordpiece.js +0 -129
  143. package/extensions/dashboard-client/dist/assets/index-D_WtU2TV.js.map +0 -1
@@ -0,0 +1,656 @@
1
+ /**
2
+ * sqlite-store.ts — SqliteTurnStore: the reference implementation.
3
+ *
4
+ * Private schema (SQL lives here + connection.ts, not in types.ts).
5
+ * All methods satisfy the TurnStore contract from types.ts.
6
+ * Append-only: no UPDATE on turns/turn_recall after INSERT (only in migration).
7
+ *
8
+ * PREVENT-PI-004: node:sqlite in-process only.
9
+ * PREVENT-002: all queries use bound parameters.
10
+ * PREVENT-001: safeJson not needed — no JSON columns in turns.db.
11
+ */
12
+
13
+ import { randomBytes } from "node:crypto";
14
+ import { statSync } from "node:fs";
15
+ import { join } from "node:path";
16
+ import type { DatabaseSync } from "node:sqlite";
17
+ import { openTurnDb, closeTurnDb } from "./connection.js";
18
+ import type {
19
+ TurnStore,
20
+ TurnReader,
21
+ TurnWriter,
22
+ TurnAdmin,
23
+ TurnId,
24
+ ConversationId,
25
+ SessionId,
26
+ TurnEntry,
27
+ TurnRecallEntry,
28
+ ConversationFork,
29
+ TurnFilter,
30
+ PruneReport,
31
+ RetentionPolicy,
32
+ StoreSnapshot,
33
+ ConversationStats,
34
+ TurnStoreOptions,
35
+ } from "./types.js";
36
+
37
+ // ─── Helpers ──────────────────────────────────────────────────────
38
+
39
+ function newConversationId(): ConversationId {
40
+ return `conv_${randomBytes(8).toString("hex")}`;
41
+ }
42
+
43
+ function normalizeSessionId(sid: SessionId): SessionId {
44
+ // Matches the existing normalizeSessionId in src/store.ts
45
+ return sid.replace(/-.*$/, "");
46
+ }
47
+
48
+ function rowToEntry(r: Record<string, unknown>): TurnEntry {
49
+ return {
50
+ conversationId: r.conversation_id as string,
51
+ sessionId: r.session_id as string,
52
+ turnIndex: r.turn_index as number,
53
+ role: r.role as TurnEntry["role"],
54
+ endedAt: r.ended_at as number,
55
+ ctxTokens: (r.ctx_tokens as number | null) ?? undefined,
56
+ ctxPercent: (r.ctx_percent as number | null) ?? undefined,
57
+ pressureBand:
58
+ (r.pressure_band as "green" | "yellow" | "red" | null) ?? undefined,
59
+ model: (r.model as string | null) ?? undefined,
60
+ epochId: (r.epoch_id as string | null) ?? undefined,
61
+ };
62
+ }
63
+
64
+ function rowToRecall(r: Record<string, unknown>): TurnRecallEntry {
65
+ return {
66
+ turnId: String(r.turn_id),
67
+ checkpointId: r.checkpoint_id as string,
68
+ score: r.score as number,
69
+ source: r.source as TurnRecallEntry["source"],
70
+ raptorLevel: (r.raptor_level as number | null) ?? undefined,
71
+ };
72
+ }
73
+
74
+ function rowToFork(r: Record<string, unknown>): ConversationFork {
75
+ return {
76
+ parentConversationId: r.parent_conversation_id as string,
77
+ childConversationId: r.child_conversation_id as string,
78
+ forkTurnIndex: r.fork_turn_index as number,
79
+ createdAt: r.created_at as number,
80
+ };
81
+ }
82
+
83
+ // ─── SqliteTurnStore ──────────────────────────────────────────────
84
+
85
+ export class SqliteTurnStore implements TurnStore {
86
+ private db: DatabaseSync;
87
+ private stateDir: string;
88
+ private opts: TurnStoreOptions;
89
+
90
+ constructor(options: TurnStoreOptions) {
91
+ this.opts = options;
92
+ this.stateDir = options.stateDir;
93
+ this.db = openTurnDb(options.stateDir, {
94
+ dbPath: options.dbPath,
95
+ inMemory: options.inMemory,
96
+ });
97
+ }
98
+
99
+ // ── TurnReader ──────────────────────────────────────────────
100
+
101
+ query(filter: TurnFilter): TurnEntry[] {
102
+ const clauses: string[] = [];
103
+ const params: (string | number)[] = [];
104
+
105
+ if (filter.conversationId !== undefined) {
106
+ clauses.push("conversation_id = ?");
107
+ params.push(filter.conversationId);
108
+ }
109
+ if (filter.sessionId !== undefined) {
110
+ clauses.push("session_id = ?");
111
+ params.push(normalizeSessionId(filter.sessionId));
112
+ }
113
+ if (filter.sinceMs !== undefined) {
114
+ clauses.push("ended_at >= ?");
115
+ params.push(filter.sinceMs);
116
+ }
117
+ if (filter.untilMs !== undefined) {
118
+ clauses.push("ended_at <= ?");
119
+ params.push(filter.untilMs);
120
+ }
121
+ if (filter.pressureBand !== undefined) {
122
+ clauses.push("pressure_band = ?");
123
+ params.push(filter.pressureBand);
124
+ }
125
+
126
+ const where = clauses.length > 0 ? `WHERE ${clauses.join(" AND ")}` : "";
127
+ const limit = filter.limit ?? 1000;
128
+ const offset = filter.offset ?? 0;
129
+
130
+ const rows = this.db
131
+ .prepare(
132
+ `SELECT * FROM turns ${where} ORDER BY ended_at ASC LIMIT ? OFFSET ?`,
133
+ )
134
+ .all(...params, limit, offset) as Array<Record<string, unknown>>;
135
+
136
+ return rows.map(rowToEntry);
137
+ }
138
+
139
+ getTurn(turnId: TurnId): TurnEntry | undefined {
140
+ const row = this.db
141
+ .prepare("SELECT * FROM turns WHERE id = ?")
142
+ .get(Number(turnId)) as Record<string, unknown> | undefined;
143
+ return row ? rowToEntry(row) : undefined;
144
+ }
145
+
146
+ getTurnByIndex(
147
+ conversationId: ConversationId,
148
+ turnIndex: number,
149
+ ): TurnEntry | undefined {
150
+ const row = this.db
151
+ .prepare(
152
+ "SELECT * FROM turns WHERE conversation_id = ? AND turn_index = ?",
153
+ )
154
+ .get(conversationId, turnIndex) as Record<string, unknown> | undefined;
155
+ return row ? rowToEntry(row) : undefined;
156
+ }
157
+
158
+ listRecall(turnId: TurnId): TurnRecallEntry[] {
159
+ const rows = this.db
160
+ .prepare(
161
+ "SELECT * FROM turn_recall WHERE turn_id = ? ORDER BY score DESC",
162
+ )
163
+ .all(Number(turnId)) as Array<Record<string, unknown>>;
164
+ return rows.map(rowToRecall);
165
+ }
166
+
167
+ listRecallByIndex(
168
+ conversationId: ConversationId,
169
+ turnIndex: number,
170
+ ): TurnRecallEntry[] {
171
+ const row = this.db
172
+ .prepare(
173
+ "SELECT id FROM turns WHERE conversation_id = ? AND turn_index = ?",
174
+ )
175
+ .get(conversationId, turnIndex) as { id: number } | undefined;
176
+ if (!row) return [];
177
+ return this.listRecall(String(row.id));
178
+ }
179
+
180
+ listForks(conversationId: ConversationId): ConversationFork[] {
181
+ const rows = this.db
182
+ .prepare(
183
+ "SELECT * FROM conversation_forks WHERE parent_conversation_id = ? ORDER BY created_at ASC",
184
+ )
185
+ .all(conversationId) as Array<Record<string, unknown>>;
186
+ return rows.map(rowToFork);
187
+ }
188
+
189
+ countTurns(conversationId: ConversationId): number {
190
+ const row = this.db
191
+ .prepare("SELECT COUNT(*) as cnt FROM turns WHERE conversation_id = ?")
192
+ .get(conversationId) as { cnt: number };
193
+ return row.cnt;
194
+ }
195
+
196
+ conversationStats(conversationId: ConversationId): ConversationStats {
197
+ const rows = this.db
198
+ .prepare(
199
+ "SELECT ended_at, ctx_percent, pressure_band FROM turns WHERE conversation_id = ? ORDER BY ended_at ASC",
200
+ )
201
+ .all(conversationId) as Array<Record<string, unknown>>;
202
+
203
+ if (rows.length === 0) {
204
+ return {
205
+ turnCount: 0,
206
+ firstTurnAt: 0,
207
+ lastTurnAt: 0,
208
+ avgCtxPercent: 0,
209
+ pressureBands: {},
210
+ };
211
+ }
212
+
213
+ let ctxSum = 0;
214
+ let ctxCount = 0;
215
+ const bands: Record<string, number> = {};
216
+
217
+ for (const r of rows) {
218
+ if (r.ctx_percent !== null) {
219
+ ctxSum += r.ctx_percent as number;
220
+ ctxCount++;
221
+ }
222
+ const band = r.pressure_band as string | null;
223
+ if (band) bands[band] = (bands[band] ?? 0) + 1;
224
+ }
225
+
226
+ return {
227
+ turnCount: rows.length,
228
+ firstTurnAt: rows[0].ended_at as number,
229
+ lastTurnAt: rows[rows.length - 1].ended_at as number,
230
+ avgCtxPercent: ctxCount > 0 ? ctxSum / ctxCount : 0,
231
+ pressureBands: bands,
232
+ };
233
+ }
234
+
235
+ // ── TurnWriter ──────────────────────────────────────────────
236
+
237
+ appendTurn(entry: TurnEntry): TurnId {
238
+ const sid = normalizeSessionId(entry.sessionId);
239
+ this.persistSessionConv(sid, entry.conversationId);
240
+ this.db
241
+ .prepare(
242
+ `INSERT INTO turns (conversation_id, session_id, turn_index, role, ended_at,
243
+ ctx_tokens, ctx_percent, pressure_band, model)
244
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,
245
+ )
246
+ .run(
247
+ entry.conversationId,
248
+ sid,
249
+ entry.turnIndex,
250
+ entry.role,
251
+ entry.endedAt,
252
+ entry.ctxTokens ?? null,
253
+ entry.ctxPercent ?? null,
254
+ entry.pressureBand ?? null,
255
+ entry.model ?? null,
256
+ );
257
+ const row = this.db
258
+ .prepare(
259
+ "SELECT id FROM turns WHERE conversation_id = ? AND turn_index = ?",
260
+ )
261
+ .get(entry.conversationId, entry.turnIndex) as { id: number } | undefined;
262
+ return String(row!.id);
263
+ }
264
+
265
+ /** Persist the session → conversation mapping when a turn is written. */
266
+ private persistSessionConv(sid: string, conversationId: string): void {
267
+ this.db
268
+ .prepare(
269
+ "INSERT OR IGNORE INTO session_conversations (session_id, conversation_id) VALUES (?, ?)",
270
+ )
271
+ .run(sid, conversationId);
272
+ }
273
+
274
+ appendRecall(entry: TurnRecallEntry): void {
275
+ this.db
276
+ .prepare(
277
+ `INSERT OR IGNORE INTO turn_recall (turn_id, checkpoint_id, score, source, raptor_level)
278
+ VALUES (?, ?, ?, ?, ?)`,
279
+ )
280
+ .run(
281
+ Number(entry.turnId),
282
+ entry.checkpointId,
283
+ entry.score,
284
+ entry.source,
285
+ entry.raptorLevel ?? null,
286
+ );
287
+ }
288
+
289
+ ensureConversationId(sessionId: SessionId): ConversationId {
290
+ const sid = normalizeSessionId(sessionId);
291
+ // Check session_conversations table first (persistent mapping)
292
+ const row = this.db
293
+ .prepare(
294
+ "SELECT conversation_id FROM session_conversations WHERE session_id = ?",
295
+ )
296
+ .get(sid) as { conversation_id: string } | undefined;
297
+ if (row) return row.conversation_id;
298
+
299
+ // Check if any turn exists for this session (fallback)
300
+ const turnRow = this.db
301
+ .prepare(
302
+ "SELECT conversation_id FROM turns WHERE session_id = ? ORDER BY ended_at DESC LIMIT 1",
303
+ )
304
+ .get(sid) as { conversation_id: string } | undefined;
305
+ if (turnRow) {
306
+ // Persist the mapping so future calls are consistent
307
+ this.db
308
+ .prepare(
309
+ "INSERT OR IGNORE INTO session_conversations (session_id, conversation_id) VALUES (?, ?)",
310
+ )
311
+ .run(sid, turnRow.conversation_id);
312
+ return turnRow.conversation_id;
313
+ }
314
+
315
+ // No turns yet — generate and persist a new conversation id
316
+ const convId = newConversationId();
317
+ this.db
318
+ .prepare(
319
+ "INSERT OR IGNORE INTO session_conversations (session_id, conversation_id) VALUES (?, ?)",
320
+ )
321
+ .run(sid, convId);
322
+ return convId;
323
+ }
324
+
325
+ forkConversation(
326
+ parentId: ConversationId,
327
+ forkTurnIndex: number,
328
+ ): ConversationId {
329
+ const childId = newConversationId();
330
+ const now = Date.now();
331
+
332
+ // 1. Record the fork lineage
333
+ this.db
334
+ .prepare(
335
+ `INSERT INTO conversation_forks (parent_conversation_id, child_conversation_id, fork_turn_index, created_at)
336
+ VALUES (?, ?, ?, ?)`,
337
+ )
338
+ .run(parentId, childId, forkTurnIndex, now);
339
+
340
+ // 2. Find the parent's turn at forkTurnIndex
341
+ const parentTurn = this.db
342
+ .prepare(
343
+ "SELECT id FROM turns WHERE conversation_id = ? AND turn_index = ?",
344
+ )
345
+ .get(parentId, forkTurnIndex) as { id: number } | undefined;
346
+
347
+ if (!parentTurn) return childId; // no parent turn at that index — nothing to seed
348
+
349
+ // 3. Create a seed turn in the child conversation (turnIndex 0, role system)
350
+ this.db
351
+ .prepare(
352
+ `INSERT INTO turns (conversation_id, session_id, turn_index, role, ended_at)
353
+ VALUES (?, ?, 0, 'system', ?)`,
354
+ )
355
+ .run(childId, `fork_${childId}`, now);
356
+
357
+ const childTurnRow = this.db
358
+ .prepare(
359
+ "SELECT id FROM turns WHERE conversation_id = ? AND turn_index = 0",
360
+ )
361
+ .get(childId) as { id: number } | undefined;
362
+ if (!childTurnRow) return childId;
363
+
364
+ // 4. Copy the parent's recall entries into the child's seed turn
365
+ const parentRecall = this.db
366
+ .prepare(
367
+ "SELECT checkpoint_id, score, source, raptor_level FROM turn_recall WHERE turn_id = ?",
368
+ )
369
+ .all(parentTurn.id) as Array<Record<string, unknown>>;
370
+
371
+ const insertRecall = this.db.prepare(
372
+ `INSERT OR IGNORE INTO turn_recall (turn_id, checkpoint_id, score, source, raptor_level)
373
+ VALUES (?, ?, ?, ?, ?)`,
374
+ );
375
+ for (const r of parentRecall) {
376
+ insertRecall.run(
377
+ childTurnRow.id,
378
+ r.checkpoint_id as string,
379
+ r.score as number,
380
+ r.source as string,
381
+ (r.raptor_level as number | null) ?? null,
382
+ );
383
+ }
384
+
385
+ return childId;
386
+ }
387
+
388
+ // ── TurnAdmin ───────────────────────────────────────────────
389
+
390
+ prune(policy: RetentionPolicy): PruneReport {
391
+ const beforeSize = this.dbSizeBytes();
392
+ const cutoff = Date.now() - policy.maxTurnAgeMs;
393
+
394
+ // Find conversations with turns to potentially prune
395
+ const convRows = this.db
396
+ .prepare("SELECT DISTINCT conversation_id FROM turns")
397
+ .all() as Array<{ conversation_id: string }>;
398
+
399
+ let turnsRemoved = 0;
400
+ let recallRemoved = 0;
401
+
402
+ for (const { conversation_id } of convRows) {
403
+ // Count total turns in this conversation
404
+ const total = this.db
405
+ .prepare("SELECT COUNT(*) as cnt FROM turns WHERE conversation_id = ?")
406
+ .get(conversation_id) as { cnt: number };
407
+
408
+ // Keep at least keepMinPerConversation — delete only the oldest
409
+ const canDelete = Math.max(0, total.cnt - policy.keepMinPerConversation);
410
+ if (canDelete === 0) continue;
411
+
412
+ // Find old turns to delete
413
+ const oldTurns = this.db
414
+ .prepare(
415
+ `SELECT id FROM turns WHERE conversation_id = ? AND ended_at < ?
416
+ ORDER BY ended_at ASC LIMIT ?`,
417
+ )
418
+ .all(conversation_id, cutoff, canDelete) as Array<{
419
+ id: number;
420
+ }>;
421
+
422
+ if (oldTurns.length === 0) continue;
423
+
424
+ const ids = oldTurns.map((t) => t.id);
425
+ const placeholders = ids.map(() => "?").join(",");
426
+
427
+ // Delete recall for those turns
428
+ const delRecall = this.db
429
+ .prepare(`DELETE FROM turn_recall WHERE turn_id IN (${placeholders})`)
430
+ .run(...ids);
431
+ recallRemoved += Number(delRecall.changes);
432
+
433
+ // Delete the turns
434
+ const delTurns = this.db
435
+ .prepare(`DELETE FROM turns WHERE id IN (${placeholders})`)
436
+ .run(...ids);
437
+ turnsRemoved += Number(delTurns.changes);
438
+ }
439
+
440
+ // Count preserved branches
441
+ const branchesPreserved = (
442
+ this.db
443
+ .prepare("SELECT COUNT(*) as cnt FROM conversation_forks")
444
+ .get() as { cnt: number }
445
+ ).cnt;
446
+
447
+ if (policy.vacuumAfterPrune && (turnsRemoved > 0 || recallRemoved > 0)) {
448
+ this.vacuum();
449
+ }
450
+
451
+ const afterSize = this.dbSizeBytes();
452
+
453
+ return {
454
+ turnsRemoved,
455
+ recallRemoved,
456
+ branchesPreserved,
457
+ freedBytes: Math.max(0, beforeSize - afterSize),
458
+ };
459
+ }
460
+
461
+ vacuum(): void {
462
+ this.db.exec("VACUUM");
463
+ }
464
+
465
+ checkpoint(): StoreSnapshot {
466
+ // Query turns in row-id order (ended_at ASC with unique constraint)
467
+ const turnRows = this.db
468
+ .prepare("SELECT * FROM turns ORDER BY ended_at ASC")
469
+ .all() as Array<Record<string, unknown>>;
470
+ const turns = turnRows.map(rowToEntry);
471
+
472
+ // Build mapping: row_id → 1-based position in turns array
473
+ const rowIdToPos = new Map<number, number>();
474
+ for (let i = 0; i < turnRows.length; i++) {
475
+ rowIdToPos.set(turnRows[i].id as number, i + 1);
476
+ }
477
+
478
+ const recallRows = this.db
479
+ .prepare("SELECT * FROM turn_recall ORDER BY turn_id ASC")
480
+ .all() as Array<Record<string, unknown>>;
481
+
482
+ // Replace recall's turnId with the 1-based position of the referenced turn
483
+ // in the turns array. This makes the TurnId stable across restore.
484
+ const recall = recallRows.map((r) => {
485
+ const originalTurnId = r.turn_id as number;
486
+ const stableTurnId = rowIdToPos.get(originalTurnId) ?? originalTurnId;
487
+ return {
488
+ turnId: String(stableTurnId),
489
+ checkpointId: r.checkpoint_id as string,
490
+ score: r.score as number,
491
+ source: r.source as TurnRecallEntry["source"],
492
+ raptorLevel: (r.raptor_level as number | null) ?? undefined,
493
+ };
494
+ });
495
+
496
+ const forks = (
497
+ this.db
498
+ .prepare("SELECT * FROM conversation_forks ORDER BY created_at ASC")
499
+ .all() as Array<Record<string, unknown>>
500
+ ).map(rowToFork);
501
+
502
+ return {
503
+ version: 1,
504
+ exportedAt: Date.now(),
505
+ turns,
506
+ recall,
507
+ forks,
508
+ };
509
+ }
510
+
511
+ restore(from: StoreSnapshot): void {
512
+ this.clear();
513
+ const insertTurn = this.db.prepare(
514
+ `INSERT INTO turns (conversation_id, session_id, turn_index, role, ended_at,
515
+ ctx_tokens, ctx_percent, pressure_band, model)
516
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,
517
+ );
518
+ const insertRecall = this.db.prepare(
519
+ `INSERT INTO turn_recall (turn_id, checkpoint_id, score, source, raptor_level)
520
+ VALUES (?, ?, ?, ?, ?)`,
521
+ );
522
+ const insertFork = this.db.prepare(
523
+ `INSERT INTO conversation_forks (parent_conversation_id, child_conversation_id, fork_turn_index, created_at)
524
+ VALUES (?, ?, ?, ?)`,
525
+ );
526
+
527
+ this.db.exec("BEGIN TRANSACTION");
528
+ try {
529
+ // Map: 1-based position → new auto-increment row ID
530
+ const posToNewId = new Map<number, number>();
531
+
532
+ for (let i = 0; i < from.turns.length; i++) {
533
+ const t = from.turns[i];
534
+ insertTurn.run(
535
+ t.conversationId,
536
+ normalizeSessionId(t.sessionId),
537
+ t.turnIndex,
538
+ t.role,
539
+ t.endedAt,
540
+ t.ctxTokens ?? null,
541
+ t.ctxPercent ?? null,
542
+ t.pressureBand ?? null,
543
+ t.model ?? null,
544
+ );
545
+ const row = this.db
546
+ .prepare(
547
+ "SELECT id FROM turns WHERE conversation_id = ? AND turn_index = ?",
548
+ )
549
+ .get(t.conversationId, t.turnIndex) as { id: number } | undefined;
550
+ if (row) posToNewId.set(i + 1, row.id);
551
+ }
552
+
553
+ // Recall's turnId is now the 1-based position from checkpoint().
554
+ // Map it to the new row ID.
555
+ for (const r of from.recall) {
556
+ const targetTurnId =
557
+ posToNewId.get(Number(r.turnId)) ?? Number(r.turnId);
558
+ insertRecall.run(
559
+ targetTurnId,
560
+ r.checkpointId,
561
+ r.score,
562
+ r.source,
563
+ r.raptorLevel ?? null,
564
+ );
565
+ }
566
+
567
+ for (const f of from.forks) {
568
+ insertFork.run(
569
+ f.parentConversationId,
570
+ f.childConversationId,
571
+ f.forkTurnIndex,
572
+ f.createdAt,
573
+ );
574
+ }
575
+ this.db.exec("COMMIT");
576
+ } catch (err) {
577
+ this.db.exec("ROLLBACK");
578
+ throw err;
579
+ }
580
+ }
581
+
582
+ clear(): void {
583
+ this.db.exec("DELETE FROM turn_recall");
584
+ this.db.exec("DELETE FROM conversation_forks");
585
+ this.db.exec("DELETE FROM turns");
586
+ this.db.exec("DELETE FROM session_conversations");
587
+ // Reset autoincrement
588
+ this.db.exec(
589
+ "DELETE FROM sqlite_sequence WHERE name IN ('turns','turn_recall','conversation_forks')",
590
+ );
591
+ }
592
+
593
+ stampTurnsEpoch(sessionId: SessionId, epochId: string): number {
594
+ const sid = normalizeSessionId(sessionId);
595
+ const res = this.db
596
+ .prepare(
597
+ "UPDATE turns SET epoch_id = ? WHERE session_id = ? AND epoch_id IS NULL",
598
+ )
599
+ .run(epochId, sid);
600
+ return Number(res.changes ?? 0);
601
+ }
602
+
603
+ // ── Capability gating ───────────────────────────────────────
604
+
605
+ asReader(): TurnReader {
606
+ return {
607
+ query: (f) => this.query(f),
608
+ getTurn: (id) => this.getTurn(id),
609
+ getTurnByIndex: (c, t) => this.getTurnByIndex(c, t),
610
+ listRecall: (id) => this.listRecall(id),
611
+ listRecallByIndex: (c, t) => this.listRecallByIndex(c, t),
612
+ listForks: (id) => this.listForks(id),
613
+ countTurns: (id) => this.countTurns(id),
614
+ conversationStats: (id) => this.conversationStats(id),
615
+ };
616
+ }
617
+
618
+ asWriter(): TurnWriter {
619
+ return {
620
+ appendTurn: (e) => this.appendTurn(e),
621
+ appendRecall: (e) => this.appendRecall(e),
622
+ ensureConversationId: (s) => this.ensureConversationId(s),
623
+ forkConversation: (p, t) => this.forkConversation(p, t),
624
+ };
625
+ }
626
+
627
+ asAdmin(): TurnAdmin {
628
+ return {
629
+ prune: (p) => this.prune(p),
630
+ vacuum: () => this.vacuum(),
631
+ checkpoint: () => this.checkpoint(),
632
+ restore: (s) => this.restore(s),
633
+ clear: () => this.clear(),
634
+ stampTurnsEpoch: (s, e) => this.stampTurnsEpoch(s, e),
635
+ };
636
+ }
637
+
638
+ close(): void {
639
+ closeTurnDb(this.stateDir, {
640
+ dbPath: this.opts.dbPath,
641
+ inMemory: this.opts.inMemory,
642
+ });
643
+ }
644
+
645
+ // ── Private helpers ─────────────────────────────────────────
646
+
647
+ private dbSizeBytes(): number {
648
+ if (this.opts.inMemory) return 0;
649
+ try {
650
+ const path = this.opts.dbPath ?? join(this.stateDir, "turns.db");
651
+ return statSync(path).size;
652
+ } catch {
653
+ return 0;
654
+ }
655
+ }
656
+ }