pi-mega-compact 0.7.3 → 0.7.5

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.
@@ -17,12 +17,12 @@
17
17
  * All queries are parameterized (PREVENT-002) — never string-concatenated.
18
18
  */
19
19
  import { DatabaseSync } from "node:sqlite";
20
- import { existsSync, mkdirSync } from "node:fs";
20
+ import { existsSync, mkdirSync, statSync } from "node:fs";
21
21
  import { homedir, tmpdir } from "node:os";
22
22
  import { join } from "node:path";
23
23
  import { getStateDir } from "../store.js";
24
24
  import { normalizeSessionId } from "../store.js";
25
- const SCHEMA_VERSION = 1;
25
+ const SCHEMA_VERSION = 2;
26
26
  /** Encode a float vector as a little-endian Float32 BLOB for cosine scanning. */
27
27
  function encodeEmbedding(v) {
28
28
  const buf = Buffer.allocUnsafe(v.length * 4);
@@ -457,6 +457,54 @@ function initSchema(db) {
457
457
  normalized_text,
458
458
  tokenize='trigram'
459
459
  );
460
+
461
+ -- S27: durable raw-transcript mirror (MEGACOMPACT_DB_MIRROR). Appended
462
+ -- RAW message bytes per session so a compacted window can be rehydrated
463
+ -- from the local store instead of the pi runtime transcript (which is
464
+ -- trimmed). PK is (content_hash, session_id) — NOT content_hash alone —
465
+ -- so identical content in different sessions never collides. Additive:
466
+ -- CREATE TABLE IF NOT EXISTS leaves existing DBs untouched on open until
467
+ -- the S27 mirror flag is flipped on. All queries parameterized (PREVENT-002).
468
+ CREATE TABLE IF NOT EXISTS raw_transcript (
469
+ content_hash TEXT NOT NULL,
470
+ session_id TEXT NOT NULL,
471
+ seq INTEGER NOT NULL,
472
+ role TEXT NOT NULL,
473
+ content_bytes TEXT NOT NULL,
474
+ tool_name TEXT,
475
+ message_timestamp INTEGER, -- ORIGINAL msg ts at append, NOT served
476
+ checkpoint_epoch TEXT NOT NULL,
477
+ PRIMARY KEY (content_hash, session_id)
478
+ );
479
+ CREATE INDEX IF NOT EXISTS idx_rt_session_seq ON raw_transcript(session_id, seq);
480
+ CREATE INDEX IF NOT EXISTS idx_rt_epoch ON raw_transcript(checkpoint_epoch);
481
+
482
+ -- S27: checkpoint-epoch registry. One row per compaction epoch; the
483
+ -- summary_message_text is the verbatim system message that replaced the
484
+ -- trimmed prefix. Informational bookkeeping (the raw_transcript rows are
485
+ -- authoritative); refresh-safe via ON CONFLICT(epoch_id) DO UPDATE.
486
+ CREATE TABLE IF NOT EXISTS checkpoint_epochs (
487
+ epoch_id TEXT PRIMARY KEY,
488
+ session_id TEXT NOT NULL,
489
+ started_seq INTEGER NOT NULL,
490
+ committed_seq INTEGER NOT NULL,
491
+ summary_message_text TEXT NOT NULL,
492
+ cut_index INTEGER NOT NULL,
493
+ checkpoint_id TEXT NOT NULL,
494
+ created_at INTEGER NOT NULL
495
+ );
496
+ CREATE INDEX IF NOT EXISTS idx_epoch_session ON checkpoint_epochs(session_id, created_at DESC);
497
+
498
+ -- S27 Task 6: dedup_mirror for space-efficient deduplicated storage.
499
+ -- Each unique content_hash stores its bytes ONCE; raw_transcript rows
500
+ -- reference this table via content_ref instead of storing duplicate content_bytes inline.
501
+ CREATE TABLE IF NOT EXISTS dedup_mirror (
502
+ content_hash TEXT PRIMARY KEY,
503
+ content_bytes TEXT NOT NULL,
504
+ ref_count INTEGER NOT NULL DEFAULT 1,
505
+ first_seen_seq INTEGER NOT NULL,
506
+ created_at INTEGER NOT NULL
507
+ );
460
508
  `);
461
509
  // Idempotent column migrations. `CREATE TABLE IF NOT EXISTS` is a no-op on a
462
510
  // pre-existing table, so new columns added to context_chunks after a store was
@@ -464,6 +512,8 @@ function initSchema(db) {
464
512
  // databases created by an older version — otherwise repoStats()/upsert crash
465
513
  // with "no such column" and the extension fails to load. Additive only.
466
514
  ensureColumn(db, "context_chunks", "original_token_estimate", "INTEGER");
515
+ // S27 Task 6: content_ref column in raw_transcript for dedup_mirror references.
516
+ ensureColumn(db, "raw_transcript", "content_ref", "TEXT");
467
517
  // S20 memory-RAG extension: additive columns for auto-review ops. Idempotent —
468
518
  // only alters DBs created by an older version that lack these columns.
469
519
  ensureColumn(db, "memories", "category", "TEXT");
@@ -1112,3 +1162,425 @@ export function clearRaptorNodes(sessionId, stateDir = getStateDir()) {
1112
1162
  const db = openStore(stateDir);
1113
1163
  db.prepare("DELETE FROM raptor_nodes WHERE session_id = ?").run(normalizeSessionId(sessionId));
1114
1164
  }
1165
+ function rowToRawTranscript(row) {
1166
+ return {
1167
+ contentHash: row.content_hash,
1168
+ sessionId: row.session_id,
1169
+ seq: Number(row.seq),
1170
+ role: row.role,
1171
+ contentBytes: row.content_bytes,
1172
+ toolName: row.tool_name ?? null,
1173
+ messageTimestamp: row.message_timestamp == null ? null : Number(row.message_timestamp),
1174
+ checkpointEpoch: row.checkpoint_epoch,
1175
+ };
1176
+ }
1177
+ function rowToCheckpointEpoch(row) {
1178
+ return {
1179
+ epochId: row.epoch_id,
1180
+ sessionId: row.session_id,
1181
+ startedSeq: Number(row.started_seq),
1182
+ committedSeq: Number(row.committed_seq),
1183
+ summaryMessageText: row.summary_message_text,
1184
+ cutIndex: Number(row.cut_index),
1185
+ checkpointId: row.checkpoint_id,
1186
+ createdAt: Number(row.created_at),
1187
+ };
1188
+ }
1189
+ /**
1190
+ * Append one raw-message row to the durable mirror. Idempotent by
1191
+ * (content_hash, session_id) via INSERT OR IGNORE — re-appending the same
1192
+ * content for the same session is a no-op. seq is assigned server-side as
1193
+ * COALESCE(MAX(seq),0)+1 within the session, so callers never need to compute
1194
+ * it. Pass an open store handle (openStore) — matches the other DatabaseSync
1195
+ * helpers. Parameterized (PREVENT-002).
1196
+ */
1197
+ export function appendRawTranscript(db, row) {
1198
+ withTx(db, () => {
1199
+ db.prepare(`INSERT OR IGNORE INTO raw_transcript
1200
+ (content_hash, session_id, seq, role, content_bytes, tool_name, message_timestamp, checkpoint_epoch)
1201
+ VALUES (
1202
+ @content_hash, @session_id,
1203
+ COALESCE((SELECT MAX(seq) FROM raw_transcript WHERE session_id = @session_id), 0) + 1,
1204
+ @role, @content_bytes, @tool_name, @message_timestamp, @checkpoint_epoch
1205
+ )`).run({
1206
+ "@content_hash": row.contentHash,
1207
+ "@session_id": row.sessionId,
1208
+ "@role": row.role,
1209
+ "@content_bytes": row.contentBytes,
1210
+ "@tool_name": row.toolName,
1211
+ "@message_timestamp": row.messageTimestamp,
1212
+ "@checkpoint_epoch": row.checkpointEpoch,
1213
+ });
1214
+ });
1215
+ }
1216
+ /**
1217
+ * List raw-transcript rows for a session in [fromSeq, toSeq], ordered by seq
1218
+ * ascending. Returns camel-cased RawTranscriptRow[]. Parameterized.
1219
+ */
1220
+ export function listRawTranscriptRange(db, sessionId, fromSeq, toSeq) {
1221
+ const rows = db
1222
+ .prepare(`SELECT content_hash, session_id, seq, role, content_bytes, tool_name, message_timestamp, checkpoint_epoch
1223
+ FROM raw_transcript
1224
+ WHERE session_id = @session_id AND seq >= @from_seq AND seq <= @to_seq
1225
+ ORDER BY seq ASC`)
1226
+ .all({
1227
+ "@session_id": sessionId,
1228
+ "@from_seq": fromSeq,
1229
+ "@to_seq": toSeq,
1230
+ });
1231
+ return rows.map(rowToRawTranscript);
1232
+ }
1233
+ /**
1234
+ * Insert (or refresh) a checkpoint-epoch row. ON CONFLICT(epoch_id) DO UPDATE
1235
+ * so re-running the same compaction epoch is idempotent / refresh-safe.
1236
+ * Parameterized (PREVENT-002).
1237
+ */
1238
+ export function writeCheckpointEpoch(db, epoch) {
1239
+ withTx(db, () => {
1240
+ db.prepare(`INSERT INTO checkpoint_epochs
1241
+ (epoch_id, session_id, started_seq, committed_seq, summary_message_text, cut_index, checkpoint_id, created_at)
1242
+ VALUES (@epoch_id, @session_id, @started_seq, @committed_seq, @summary_message_text, @cut_index, @checkpoint_id, @created_at)
1243
+ ON CONFLICT(epoch_id) DO UPDATE SET
1244
+ session_id = excluded.session_id,
1245
+ started_seq = excluded.started_seq,
1246
+ committed_seq = excluded.committed_seq,
1247
+ summary_message_text = excluded.summary_message_text,
1248
+ cut_index = excluded.cut_index,
1249
+ checkpoint_id = excluded.checkpoint_id,
1250
+ created_at = excluded.created_at`).run({
1251
+ "@epoch_id": epoch.epochId,
1252
+ "@session_id": epoch.sessionId,
1253
+ "@started_seq": epoch.startedSeq,
1254
+ "@committed_seq": epoch.committedSeq,
1255
+ "@summary_message_text": epoch.summaryMessageText,
1256
+ "@cut_index": epoch.cutIndex,
1257
+ "@checkpoint_id": epoch.checkpointId,
1258
+ "@created_at": epoch.createdAt,
1259
+ });
1260
+ });
1261
+ }
1262
+ /** Read one checkpoint-epoch row by id (or null if absent). Parameterized. */
1263
+ export function readCheckpointEpoch(db, epochId) {
1264
+ const row = db
1265
+ .prepare(`SELECT epoch_id, session_id, started_seq, committed_seq, summary_message_text, cut_index, checkpoint_id, created_at
1266
+ FROM checkpoint_epochs WHERE epoch_id = @epoch_id`)
1267
+ .get({ "@epoch_id": epochId });
1268
+ return row ? rowToCheckpointEpoch(row) : null;
1269
+ }
1270
+ /**
1271
+ * Latest checkpoint-epoch row for a session (highest created_at), or null if
1272
+ * none. Parameterized (PREVENT-002).
1273
+ */
1274
+ export function getActiveEpochForSession(db, sessionId) {
1275
+ const row = db
1276
+ .prepare(`SELECT epoch_id, session_id, started_seq, committed_seq, summary_message_text, cut_index, checkpoint_id, created_at
1277
+ FROM checkpoint_epochs
1278
+ WHERE session_id = @session_id
1279
+ ORDER BY created_at DESC
1280
+ LIMIT 1`)
1281
+ .get({ "@session_id": sessionId });
1282
+ return row ? rowToCheckpointEpoch(row) : null;
1283
+ }
1284
+ /** List all checkpoint epochs (diagnostic / test helper). */
1285
+ export function listCheckpointEpochs(db) {
1286
+ const rows = db
1287
+ .prepare(`SELECT epoch_id, session_id, started_seq, committed_seq, summary_message_text, cut_index, checkpoint_id, created_at
1288
+ FROM checkpoint_epochs
1289
+ ORDER BY created_at DESC`)
1290
+ .all();
1291
+ return rows.map(rowToCheckpointEpoch);
1292
+ }
1293
+ /** Count raw transcript rows (diagnostic / test helper). */
1294
+ export function countRawTranscript(db) {
1295
+ const row = db.prepare(`SELECT COUNT(*) AS cnt FROM raw_transcript`).get();
1296
+ return row.cnt;
1297
+ }
1298
+ /**
1299
+ * Upsert a row into dedup_mirror. If the hash already exists, increment ref_count.
1300
+ * Returns true if this was a NEW unique content (first insert), false if it was a duplicate.
1301
+ */
1302
+ export function upsertDedupMirror(db, contentHash, contentBytes, seq) {
1303
+ const now = Date.now();
1304
+ const existing = db
1305
+ .prepare(`SELECT content_hash FROM dedup_mirror WHERE content_hash = @hash`)
1306
+ .get({ "@hash": contentHash });
1307
+ if (existing) {
1308
+ db.prepare(`UPDATE dedup_mirror SET ref_count = ref_count + 1 WHERE content_hash = @hash`).run({
1309
+ "@hash": contentHash,
1310
+ });
1311
+ return false;
1312
+ }
1313
+ db.prepare(`INSERT INTO dedup_mirror (content_hash, content_bytes, ref_count, first_seen_seq, created_at)
1314
+ VALUES (@hash, @bytes, 1, @seq, @now)`).run({
1315
+ "@hash": contentHash,
1316
+ "@bytes": contentBytes,
1317
+ "@seq": seq,
1318
+ "@now": now,
1319
+ });
1320
+ return true;
1321
+ }
1322
+ /**
1323
+ * Get dedup ratio for a session: total bytes vs unique bytes.
1324
+ */
1325
+ export function getDedupRatio(db, sessionId) {
1326
+ const totalRow = db
1327
+ .prepare(`SELECT COALESCE(SUM(LENGTH(content_bytes)), 0) AS total
1328
+ FROM raw_transcript
1329
+ WHERE session_id = @session_id`)
1330
+ .get({ "@session_id": sessionId });
1331
+ const uniqueRow = db
1332
+ .prepare(`SELECT COALESCE(SUM(LENGTH(content_bytes)), 0) AS unique_bytes
1333
+ FROM dedup_mirror`)
1334
+ .get();
1335
+ const totalBytes = totalRow.total;
1336
+ const uniqueBytes = uniqueRow.unique_bytes;
1337
+ const ratio = uniqueBytes > 0 ? totalBytes / uniqueBytes : 1;
1338
+ return { totalBytes, uniqueBytes, ratio };
1339
+ }
1340
+ /**
1341
+ * Get dedup mirror stats (diagnostic / test helper).
1342
+ */
1343
+ export function getDedupMirrorStats(db) {
1344
+ const row = db
1345
+ .prepare(`SELECT COUNT(*) AS cnt,
1346
+ COALESCE(SUM(LENGTH(content_bytes)), 0) AS total_bytes,
1347
+ COALESCE(AVG(ref_count), 0) AS avg_ref
1348
+ FROM dedup_mirror`)
1349
+ .get();
1350
+ return { rowCount: row.cnt, totalBytes: row.total_bytes, avgRefCount: row.avg_ref };
1351
+ }
1352
+ /**
1353
+ * Update raw_transcript.content_ref to point to dedup_mirror.
1354
+ */
1355
+ export function updateRawTranscriptRef(db, sessionId, seq, contentHash) {
1356
+ db.prepare(`UPDATE raw_transcript SET content_ref = @ref WHERE session_id = @sid AND seq = @seq`).run({
1357
+ "@ref": contentHash,
1358
+ "@sid": sessionId,
1359
+ "@seq": seq,
1360
+ });
1361
+ }
1362
+ const DB_TABLE_NAMES = [
1363
+ "context_chunks",
1364
+ "session_state",
1365
+ "raw_transcript",
1366
+ "checkpoint_epochs",
1367
+ "dedup_mirror",
1368
+ "memories",
1369
+ "dedup_stats",
1370
+ "daily_log",
1371
+ ];
1372
+ function fileSizeIfExists(path) {
1373
+ try {
1374
+ const st = statSync(path);
1375
+ return st.size;
1376
+ }
1377
+ catch {
1378
+ return 0;
1379
+ }
1380
+ }
1381
+ /**
1382
+ * Gather DB stats for /mega-db-stats: per-table row counts, disk footprint
1383
+ * (main + WAL + SHM), page count, freelist, WAL frame count.
1384
+ *
1385
+ * Read-only: no PRAGMA writes, no VACUUM. Safe to call any time.
1386
+ */
1387
+ export function getDbStats(stateDir = getStateDir()) {
1388
+ const db = openStore(stateDir);
1389
+ const tableCounts = {};
1390
+ for (const t of DB_TABLE_NAMES) {
1391
+ try {
1392
+ const row = db.prepare(`SELECT COUNT(*) AS c FROM ${t}`).get();
1393
+ if (row)
1394
+ tableCounts[t] = row.c;
1395
+ }
1396
+ catch {
1397
+ // Table doesn't exist on this DB (e.g. raw_transcript on a pre-S27 store).
1398
+ // Skip silently — /mega-db-stats lists only tables that exist.
1399
+ }
1400
+ }
1401
+ const pageStat = db.prepare("PRAGMA page_count").get();
1402
+ const freelistStat = db.prepare("PRAGMA freelist_count").get();
1403
+ const pageSizeStat = db.prepare("PRAGMA page_size").get();
1404
+ let walFrames = 0;
1405
+ try {
1406
+ const walInfo = db.prepare("PRAGMA wal_info").get();
1407
+ walFrames = walInfo?.frames ?? 0;
1408
+ }
1409
+ catch {
1410
+ // node:sqlite may not expose wal_info on all versions; not fatal.
1411
+ }
1412
+ const dbPath = join(stateDir, "sqlite.db");
1413
+ return {
1414
+ tableCounts,
1415
+ dbBytes: fileSizeIfExists(dbPath),
1416
+ walBytes: fileSizeIfExists(`${dbPath}-wal`),
1417
+ shmBytes: fileSizeIfExists(`${dbPath}-shm`),
1418
+ pageSize: pageSizeStat?.page_size ?? 0,
1419
+ pageCount: pageStat?.page_count ?? 0,
1420
+ freelistPages: freelistStat?.freelist_count ?? 0,
1421
+ walFrames,
1422
+ };
1423
+ }
1424
+ /**
1425
+ * Prune raw_transcript + checkpoint_epochs rows older than `daysOld`.
1426
+ * Uses `message_timestamp` (raw_transcript) and `created_at` (epochs), both
1427
+ * epoch-ms. Returns the total deleted rows + reclaimed disk bytes.
1428
+ *
1429
+ * PREVENT-002: parameterized. PREVENT-PI-004: local SQLite only.
1430
+ */
1431
+ export function pruneOldRows(stateDir = getStateDir(), daysOld = 30) {
1432
+ const db = openStore(stateDir);
1433
+ const cutoff = Date.now() - daysOld * 86_400_000;
1434
+ const beforeBytes = fileSizeIfExists(join(stateDir, "sqlite.db"));
1435
+ // raw_transcript: message_timestamp may be NULL (pre-S27 rows); those use
1436
+ // the row's insertion order implicitly via seq, so we prune NULL-ts rows
1437
+ // only when the whole session is older than the cutoff (join via session_id
1438
+ // to checkpoint_epochs.created_at). Simpler: prune NULL-ts rows older than
1439
+ // cutoff by falling back to the MIN(created_at) of their epoch.
1440
+ // Delete raw_transcript rows whose message_timestamp is older than cutoff,
1441
+ // OR whose message_timestamp is NULL and the session's latest epoch is older.
1442
+ const delRt = db.prepare(`DELETE FROM raw_transcript
1443
+ WHERE message_timestamp IS NOT NULL AND message_timestamp < ?
1444
+ OR (message_timestamp IS NULL
1445
+ AND session_id IN (
1446
+ SELECT session_id FROM checkpoint_epochs
1447
+ GROUP BY session_id HAVING MAX(created_at) < ?
1448
+ ))`).run(cutoff, cutoff);
1449
+ const rtDeleted = delRt?.changes ?? 0;
1450
+ // checkpoint_epochs: created_at is NOT NULL.
1451
+ const delEp = db.prepare(`DELETE FROM checkpoint_epochs WHERE created_at < ?`).run(cutoff);
1452
+ const epDeleted = delEp?.changes ?? 0;
1453
+ // dedup_mirror: cascade-delete orphan rows whose ref_count has dropped to 0
1454
+ // after the raw_transcript deletes. Safe even if FK is off (raw_transcript has
1455
+ // no FK to dedup_mirror; ref_count is maintained by the dedup pipeline).
1456
+ const delDedup = db.prepare(`DELETE FROM dedup_mirror WHERE ref_count <= 0`).run();
1457
+ const dedupDeleted = delDedup?.changes ?? 0;
1458
+ const afterBytes = fileSizeIfExists(join(stateDir, "sqlite.db"));
1459
+ const total = rtDeleted + epDeleted + dedupDeleted;
1460
+ return {
1461
+ affected: total,
1462
+ reclaimedBytes: Math.max(0, beforeBytes - afterBytes),
1463
+ summary: `pruned ${rtDeleted} raw_transcript + ${epDeleted} epochs + ${dedupDeleted} dedup_mirror rows older than ${daysOld}d`,
1464
+ };
1465
+ }
1466
+ /**
1467
+ * Force a WAL checkpoint (TRUNCATE mode) so the -wal sidecar is reclaimed.
1468
+ * Returns the WAL bytes reclaimed (pre-wal size minus post-wal size).
1469
+ */
1470
+ export function checkpointWal(stateDir = getStateDir()) {
1471
+ const db = openStore(stateDir);
1472
+ const dbPath = join(stateDir, "sqlite.db");
1473
+ const beforeWal = fileSizeIfExists(`${dbPath}-wal`);
1474
+ // PRAGMA wal_checkpoint(TRUNCATE) blocks until all frames are folded into the
1475
+ // main db and the WAL file is truncated to 0 bytes.
1476
+ const res = db.prepare("PRAGMA wal_checkpoint(TRUNCATE)").get();
1477
+ const afterWal = fileSizeIfExists(`${dbPath}-wal`);
1478
+ const reclaimed = Math.max(0, beforeWal - afterWal);
1479
+ return {
1480
+ affected: res?.checkpointed ?? 0,
1481
+ reclaimedBytes: reclaimed,
1482
+ summary: `wal_checkpoint(TRUNCATE): ${res?.checkpointed ?? 0} frames folded, WAL ${beforeWal}→${afterWal} bytes${res?.busy ? " (busy: " + res.busy + ")" : ""}`,
1483
+ };
1484
+ }
1485
+ /**
1486
+ * VACUUM the main DB file (rebuilds pages, reclaims freelist space).
1487
+ * Heavy: briefly doubles disk usage. Run only when freelist is large or the
1488
+ * user explicitly invokes /mega-db-vacuum.
1489
+ */
1490
+ export function vacuumDb(stateDir = getStateDir()) {
1491
+ const db = openStore(stateDir);
1492
+ const dbPath = join(stateDir, "sqlite.db");
1493
+ const beforeBytes = fileSizeIfExists(dbPath);
1494
+ db.exec("VACUUM"); // VACUUM cannot be parameterized; it rewrites the whole DB.
1495
+ const afterBytes = fileSizeIfExists(dbPath);
1496
+ const reclaimed = Math.max(0, beforeBytes - afterBytes);
1497
+ return {
1498
+ affected: 0,
1499
+ reclaimedBytes: reclaimed,
1500
+ summary: `VACUUM: db ${beforeBytes}→${afterBytes} bytes (reclaimed ${reclaimed})`,
1501
+ };
1502
+ }
1503
+ /**
1504
+ * Run `PRAGMA integrity_check` and return the result lines.
1505
+ * Returns ["ok"] when the DB is healthy; otherwise returns the error lines.
1506
+ */
1507
+ export function integrityCheck(stateDir = getStateDir()) {
1508
+ const db = openStore(stateDir);
1509
+ const rows = db.prepare("PRAGMA integrity_check").all();
1510
+ return (rows ?? []).map((r) => r.integrity_check);
1511
+ }
1512
+ /**
1513
+ * Reconcile dedup_mirror vs raw_transcript after pruning or crashes:
1514
+ * 1. Recompute ref_count = COUNT(raw_transcript rows pointing at this hash).
1515
+ * 2. Delete orphan dedup_mirror rows whose recomputed ref_count is 0.
1516
+ * 3. Backfill raw_transcript.content_ref for rows still storing inline bytes.
1517
+ *
1518
+ * Idempotent. Read-modify-write within a single transaction (withTx).
1519
+ */
1520
+ export function reconcileDedupMirror(stateDir = getStateDir()) {
1521
+ const db = openStore(stateDir);
1522
+ const result = { fixedRefCount: 0, orphansDeleted: 0, refsBackfilled: 0 };
1523
+ withTx(db, () => {
1524
+ // 1. Recompute ref_count for every dedup_mirror row from the actual
1525
+ // raw_transcript references.
1526
+ const recompute = db.prepare(`UPDATE dedup_mirror AS dm
1527
+ SET ref_count = COALESCE((
1528
+ SELECT COUNT(*) FROM raw_transcript rt WHERE rt.content_ref = dm.content_hash
1529
+ ), 0)
1530
+ WHERE dm.ref_count != COALESCE((
1531
+ SELECT COUNT(*) FROM raw_transcript rt WHERE rt.content_ref = dm.content_hash
1532
+ ), 0)`).run();
1533
+ result.fixedRefCount = recompute?.changes ?? 0;
1534
+ // 2. Delete orphan dedup_mirror rows (no raw_transcript refs).
1535
+ const delOrphans = db.prepare(`DELETE FROM dedup_mirror
1536
+ WHERE content_hash NOT IN (SELECT DISTINCT content_ref FROM raw_transcript WHERE content_ref IS NOT NULL)`).run();
1537
+ result.orphansDeleted = delOrphans?.changes ?? 0;
1538
+ // 3. Backfill content_ref for rows still storing inline content_bytes (no
1539
+ // ref yet). Only safe when a matching dedup_mirror row exists; otherwise
1540
+ // we'd need to insert one, which is the dedup pipeline's job, not the
1541
+ // reconciler's.
1542
+ const backfill = db.prepare(`UPDATE raw_transcript AS rt
1543
+ SET content_ref = (
1544
+ SELECT dm.content_hash FROM dedup_mirror dm WHERE dm.content_bytes = rt.content_bytes
1545
+ )
1546
+ WHERE rt.content_ref IS NULL
1547
+ AND EXISTS (SELECT 1 FROM dedup_mirror dm WHERE dm.content_bytes = rt.content_bytes)`).run();
1548
+ result.refsBackfilled = backfill?.changes ?? 0;
1549
+ });
1550
+ return result;
1551
+ }
1552
+ /**
1553
+ * One-shot auto-maintenance pass for the session_start hook: prune old rows,
1554
+ * checkpoint the WAL if it's grown large, and (only if the DB is huge) VACUUM.
1555
+ * Best-effort: swallows errors so a session never fails to start over a
1556
+ * housekeeping hiccup. Returns a short summary for the diagnostic log.
1557
+ */
1558
+ export function autoMaintain(stateDir = getStateDir()) {
1559
+ try {
1560
+ const stats = getDbStats(stateDir);
1561
+ const parts = [];
1562
+ // Prune rows older than 30d (default retention).
1563
+ const prune = pruneOldRows(stateDir, 30);
1564
+ if (prune.affected > 0)
1565
+ parts.push(`pruned ${prune.affected}`);
1566
+ // Checkpoint the WAL if it's over 10 MB (avoid pathological WAL growth).
1567
+ if (stats.walBytes > 10 * 1024 * 1024) {
1568
+ const ck = checkpointWal(stateDir);
1569
+ if (ck.reclaimedBytes > 0)
1570
+ parts.push(`wal -${ck.reclaimedBytes}B`);
1571
+ }
1572
+ // VACUUM only if the DB is over 100 MB AND freelist is >20% of pages.
1573
+ if (stats.dbBytes > 100 * 1024 * 1024 &&
1574
+ stats.pageCount > 0 &&
1575
+ stats.freelistPages / stats.pageCount > 0.2) {
1576
+ const v = vacuumDb(stateDir);
1577
+ if (v.reclaimedBytes > 0)
1578
+ parts.push(`vacuum -${v.reclaimedBytes}B`);
1579
+ }
1580
+ return parts.length ? `auto-maintain: ${parts.join(", ")}` : "auto-maintain: nothing to do";
1581
+ }
1582
+ catch (err) {
1583
+ // Never block session start over housekeeping.
1584
+ return `auto-maintain: skipped (${err.message})`;
1585
+ }
1586
+ }
@@ -32,6 +32,7 @@ import { registerEventHandlers } from "./mega-events.js";
32
32
  import { registerCommands } from "./mega-commands.js";
33
33
  import { registerDashboardCommands } from "./mega-dashboard-cmds.js";
34
34
  import { registerConflictCommands } from "./mega-conflict-cmds.js";
35
+ import { registerDbCommands } from "./mega-db-cmds.js";
35
36
 
36
37
  export default function (pi: ExtensionAPI) {
37
38
  const config = loadConfig();
@@ -40,4 +41,5 @@ export default function (pi: ExtensionAPI) {
40
41
  registerCommands(pi, runtime, config);
41
42
  registerDashboardCommands(pi, runtime);
42
43
  registerConflictCommands(pi, runtime);
44
+ registerDbCommands(pi, runtime);
43
45
  }
@@ -75,6 +75,13 @@ export interface MegaConfig {
75
75
  * trim + pi native auto-compaction instead (compact and continue). Kept for
76
76
  * one release as rollback. */
77
77
  legacyDurableTrim: boolean;
78
+ /** S27: durable raw-transcript DB mirror (MEGACOMPACT_DB_MIRROR). When on,
79
+ * raw message bytes + checkpoint-epoch bookkeeping are appended to the
80
+ * SQLite store so a compacted window can be rehydrated locally instead of
81
+ * from the pi runtime transcript. Default OFF — additive, no behavior
82
+ * change until flipped on. legacyDurableTrim takes precedence (the legacy
83
+ * v0.4.28 ctx.compact() path does not emit the S27 mirror hook). */
84
+ dbMirror: boolean;
78
85
  /** Cross-repo recall enabled (S17). Resume + /mega-recall --cross-repo can
79
86
  * pull checkpoints from OTHER repos via the PGlite HNSW index. Default true. */
80
87
  crossRepoEnabled: boolean;
@@ -214,6 +221,7 @@ export function loadConfig(): MegaConfig {
214
221
  dedupSim: Number(process.env.MEGACOMPACT_DEDUP_SIM ?? "0.9"),
215
222
  raptorEnabled: envBool("MEGACOMPACT_RAPTOR_ENABLED", true),
216
223
  legacyDurableTrim: envBool("MEGACOMPACT_LEGACY_DURABLE_TRIM", false),
224
+ dbMirror: envBool("MEGACOMPACT_DB_MIRROR", false),
217
225
  crossRepoEnabled: envBool("MEGACOMPACT_CROSSREPO_ENABLED", true),
218
226
  crossRepoCosine: Number(process.env.MEGACOMPACT_CROSSREPO_COSINE ?? "0.90"),
219
227
  memoryAutoReview: envBool("MEGACOMPACT_MEMORY_AUTO_REVIEW", true),
@@ -0,0 +1,107 @@
1
+ /**
2
+ * mega-db-cmds.ts — S27 Task 10 DB maintenance /commands.
3
+ *
4
+ * Registers /mega-db-stats, /mega-db-prune, /mega-db-vacuum, /mega-db-check,
5
+ * /mega-db-reconcile slash commands backed by the maintenance primitives in
6
+ * src/store/sqlite.ts. All operations are local SQLite (PREVENT-PI-004) with
7
+ * parameterized queries (PREVENT-002).
8
+ *
9
+ * Auto-maintenance (prune + WAL checkpoint) also runs once per session_start
10
+ * via the wiring in mega-events.ts (best-effort, non-blocking).
11
+ */
12
+
13
+ import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
14
+ import type { MegaRuntime } from "./mega-runtime.js";
15
+ import {
16
+ getDbStats,
17
+ pruneOldRows,
18
+ checkpointWal,
19
+ vacuumDb,
20
+ integrityCheck,
21
+ reconcileDedupMirror,
22
+ type DedupReconcileResult,
23
+ } from "../src/store/sqlite.js";
24
+
25
+ /** Format a byte count as a human-readable string (KB / MB / GB). */
26
+ function fmtBytes(n: number): string {
27
+ if (n < 1024) return `${n}B`;
28
+ if (n < 1024 * 1024) return `${(n / 1024).toFixed(1)}KB`;
29
+ if (n < 1024 * 1024 * 1024) return `${(n / (1024 * 1024)).toFixed(1)}MB`;
30
+ return `${(n / (1024 * 1024 * 1024)).toFixed(2)}GB`;
31
+ }
32
+
33
+ /** Register the /mega-db-* maintenance commands. */
34
+ export function registerDbCommands(pi: ExtensionAPI, runtime: MegaRuntime): void {
35
+ const stateDir = runtime.currentStateDir;
36
+
37
+ pi.registerCommand("mega-db-stats", {
38
+ description:
39
+ "Show mega-compact SQLite DB stats: table row counts, disk footprint (db + WAL + SHM), page count, freelist, WAL frames.",
40
+ handler: async (_args: string, ctx: ExtensionContext) => {
41
+ const s = getDbStats(stateDir);
42
+ ctx.ui.notify(`[mega-compact] DB stats — ${stateDir}`);
43
+ ctx.ui.notify(` main: ${fmtBytes(s.dbBytes)} wal: ${fmtBytes(s.walBytes)} shm: ${fmtBytes(s.shmBytes)}`);
44
+ ctx.ui.notify(
45
+ ` pages: ${s.pageCount} (${s.pageSize}B each), freelist: ${s.freelistPages} (${s.pageCount > 0 ? ((s.freelistPages / s.pageCount) * 100).toFixed(1) : "0"}% reusable), wal frames: ${s.walFrames}`,
46
+ );
47
+ const tableLines = Object.entries(s.tableCounts)
48
+ .sort((a, b) => b[1] - a[1])
49
+ .map(([t, c]) => ` ${t.padEnd(22)} ${String(c).padStart(8)}`);
50
+ if (tableLines.length === 0) {
51
+ ctx.ui.notify(" (no tables populated yet)");
52
+ } else {
53
+ ctx.ui.notify(" table row counts:");
54
+ for (const l of tableLines) ctx.ui.notify(l);
55
+ }
56
+ },
57
+ });
58
+
59
+ pi.registerCommand("mega-db-prune", {
60
+ description:
61
+ "Prune raw_transcript + checkpoint_epochs + orphan dedup_mirror rows older than N days (default 30). Usage: /mega-db-prune [days]",
62
+ handler: async (args: string, ctx: ExtensionContext) => {
63
+ const days = Number.parseInt(args.trim().split(/\s+/)[0] ?? "30", 10);
64
+ const d = Number.isFinite(days) && days > 0 ? days : 30;
65
+ const r = pruneOldRows(stateDir, d);
66
+ ctx.ui.notify(`[mega-compact] ${r.summary} (reclaimed ${fmtBytes(r.reclaimedBytes)})`);
67
+ },
68
+ });
69
+
70
+ pi.registerCommand("mega-db-vacuum", {
71
+ description:
72
+ "VACUUM the mega-compact SQLite DB (rebuild pages, reclaim freelist space). Heavy: briefly doubles disk usage.",
73
+ handler: async (_args: string, ctx: ExtensionContext) => {
74
+ const r = vacuumDb(stateDir);
75
+ ctx.ui.notify(`[mega-compact] ${r.summary}`);
76
+ },
77
+ });
78
+
79
+ pi.registerCommand("mega-db-check", {
80
+ description:
81
+ "Run PRAGMA integrity_check + a WAL checkpoint on the mega-compact SQLite DB. Use after a crash or to fold the WAL into the main file.",
82
+ handler: async (_args: string, ctx: ExtensionContext) => {
83
+ const lines = integrityCheck(stateDir);
84
+ const healthy = lines.length === 1 && lines[0] === "ok";
85
+ ctx.ui.notify(
86
+ `[mega-compact] integrity_check: ${healthy ? "✓ ok" : `⚠ ${lines.length} issue(s)`}`,
87
+ );
88
+ if (!healthy) {
89
+ for (const l of lines.slice(0, 10)) ctx.ui.notify(` ${l}`);
90
+ if (lines.length > 10) ctx.ui.notify(` … and ${lines.length - 10} more`);
91
+ }
92
+ const ck = checkpointWal(stateDir);
93
+ ctx.ui.notify(`[mega-compact] ${ck.summary}`);
94
+ },
95
+ });
96
+
97
+ pi.registerCommand("mega-db-reconcile", {
98
+ description:
99
+ "Reconcile dedup_mirror.ref_count vs actual raw_transcript refs: fix drift, delete orphan dedup rows, backfill missing content_ref. Run after /mega-db-prune or a crash.",
100
+ handler: async (_args: string, ctx: ExtensionContext) => {
101
+ const r: DedupReconcileResult = reconcileDedupMirror(stateDir);
102
+ ctx.ui.notify(
103
+ `[mega-compact] dedup reconcile: fixed ${r.fixedRefCount} ref_count drift, deleted ${r.orphansDeleted} orphan(s), backfilled ${r.refsBackfilled} content_ref`,
104
+ );
105
+ },
106
+ });
107
+ }