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.
@@ -41,7 +41,44 @@ export function formatRecallBlock(hits) {
41
41
  * it records injections via `markInjected` so the next call dedupes. The
42
42
  * `store` is passed by the extension (defaults to the engine's default store).
43
43
  */
44
+ /**
45
+ * Recall and inline context from the checkpoint store.
46
+ *
47
+ * S27 contract — DB-Mirror demotion:
48
+ *
49
+ * When `MEGACOMPACT_DB_MIRROR` is ON, the `raw_transcript` table is the
50
+ * canonical, byte-stable source of truth for message reconstruction. The
51
+ * `dedup_mirror` provides space-efficient storage with ref_count tracking
52
+ * (see src/mirror/dedup.ts). The legacy JSON checkpoint is retained as a
53
+ * DR snapshot only (see src/store.ts checkpoint helpers).
54
+ *
55
+ * The recall function continues to work from the VectorStore (checkpoint
56
+ * summaries + embeddings) for fast semantic search — this path is unaffected
57
+ * by the mirror flag. If full transcript reconstruction is ever needed
58
+ * (replay, export, debug), prefer reading from `raw_transcript + dedup_mirror`
59
+ * via `listRawTranscriptRange()` + `dedupTranscript()` instead of the legacy
60
+ * JSON checkpoint. Falls back to legacy checkpoint if mirror is empty
61
+ * (pre-migration sessions).
62
+ *
63
+ * Pi-agnostic: no pi runtime imports (src/ invariant).
64
+ */
44
65
  export function recallAndInline(opts, store) {
66
+ // ── S27 Recall Demotion ─────────────────────────────────────────────
67
+ //
68
+ // When MEGACOMPACT_DB_MIRROR is ON, the raw_transcript + dedup_mirror
69
+ // tables are preferred for byte-stable reconstruction. The current
70
+ // recall path (VectorStore search → format → inject) is unaffected —
71
+ // it provides fast semantic search over checkpoint summaries.
72
+ //
73
+ // If full transcript reconstruction is ever needed (replay, export,
74
+ // debug), call reconstructFromMirror(db, sessionId, fromSeq, toSeq)
75
+ // from src/mirror/dedup.ts instead of reading from the legacy JSON
76
+ // checkpoint. Falls back to legacy checkpoint if mirror is empty
77
+ // (pre-migration sessions).
78
+ //
79
+ // Invariant: raw_transcript + dedup_mirror are additive and never
80
+ // lose data. The legacy JSON checkpoint remains as a DR snapshot.
81
+ // ─────────────────────────────────────────────────────────────────────
45
82
  const limit = opts.limit ?? 3;
46
83
  const skip = opts.skipInjected ?? true;
47
84
  const maxTokens = opts.recallMaxTokens ?? 0; // 0 = unbounded (legacy behavior)
@@ -0,0 +1,158 @@
1
+ /**
2
+ * Tests for S27 Task 10 DB maintenance primitives.
3
+ *
4
+ * Covers getDbStats, pruneOldRows, checkpointWal, vacuumDb, integrityCheck,
5
+ * reconcileDedupMirror, autoMaintain. All against a tmp SQLite store.
6
+ */
7
+ import { describe, it, beforeEach, afterEach } from "node:test";
8
+ import assert from "node:assert/strict";
9
+ import { mkdtempSync, rmSync, statSync } from "node:fs";
10
+ import { join } from "node:path";
11
+ import { tmpdir } from "node:os";
12
+ import { openStore, appendRawTranscript, writeCheckpointEpoch, upsertDedupMirror, updateRawTranscriptRef, getDbStats, pruneOldRows, checkpointWal, vacuumDb, integrityCheck, reconcileDedupMirror, autoMaintain, } from "./sqlite.js";
13
+ function makeTmp() {
14
+ return mkdtempSync(join(tmpdir(), "dbmaint-test-"));
15
+ }
16
+ function makeRow(overrides = {}) {
17
+ return {
18
+ contentHash: `hash-${Math.random().toString(36).slice(2, 10)}`,
19
+ sessionId: "sess-1",
20
+ seq: 0,
21
+ role: "user",
22
+ contentBytes: "hello world",
23
+ toolName: null,
24
+ messageTimestamp: Date.now(),
25
+ checkpointEpoch: "epoch-1",
26
+ ...overrides,
27
+ };
28
+ }
29
+ function makeEpoch(overrides = {}) {
30
+ return {
31
+ epochId: `epoch-${Math.random().toString(36).slice(2, 10)}`,
32
+ sessionId: "sess-1",
33
+ startedSeq: 0,
34
+ committedSeq: 10,
35
+ checkpointId: "cp-1",
36
+ cutIndex: 10,
37
+ summaryMessageText: "test summary",
38
+ createdAt: Date.now(),
39
+ ...overrides,
40
+ };
41
+ }
42
+ describe("DB maintenance primitives (S27 Task 10)", () => {
43
+ let dir;
44
+ let db;
45
+ beforeEach(() => {
46
+ dir = makeTmp();
47
+ db = openStore(dir);
48
+ });
49
+ afterEach(() => {
50
+ rmSync(dir, { recursive: true, force: true });
51
+ });
52
+ describe("getDbStats", () => {
53
+ it("returns zero counts on an empty store", () => {
54
+ const s = getDbStats(dir);
55
+ assert.equal(s.tableCounts.raw_transcript, 0);
56
+ assert.equal(s.tableCounts.checkpoint_epochs, 0);
57
+ assert.equal(s.tableCounts.dedup_mirror, 0);
58
+ // main DB file exists (schema was written)
59
+ assert.ok(s.dbBytes > 0);
60
+ assert.ok(s.pageSize > 0);
61
+ assert.ok(s.pageCount > 0);
62
+ });
63
+ it("counts rows after inserts", () => {
64
+ appendRawTranscript(db, makeRow());
65
+ appendRawTranscript(db, makeRow());
66
+ const s = getDbStats(dir);
67
+ assert.equal(s.tableCounts.raw_transcript, 2);
68
+ });
69
+ });
70
+ describe("pruneOldRows", () => {
71
+ it("deletes nothing when all rows are recent", () => {
72
+ appendRawTranscript(db, makeRow({ messageTimestamp: Date.now() }));
73
+ const r = pruneOldRows(dir, 30);
74
+ assert.equal(r.affected, 0);
75
+ });
76
+ it("deletes raw_transcript rows older than the cutoff", () => {
77
+ const oldTs = Date.now() - 31 * 86_400_000;
78
+ appendRawTranscript(db, makeRow({ messageTimestamp: oldTs }));
79
+ appendRawTranscript(db, makeRow({ messageTimestamp: Date.now() }));
80
+ const r = pruneOldRows(dir, 30);
81
+ assert.equal(r.affected, 1);
82
+ assert.equal(getDbStats(dir).tableCounts.raw_transcript, 1);
83
+ });
84
+ it("deletes checkpoint_epochs older than the cutoff", () => {
85
+ const oldTs = Date.now() - 40 * 86_400_000;
86
+ writeCheckpointEpoch(db, makeEpoch({ createdAt: oldTs }));
87
+ writeCheckpointEpoch(db, makeEpoch({ createdAt: Date.now() }));
88
+ const r = pruneOldRows(dir, 30);
89
+ assert.equal(r.affected, 1);
90
+ assert.equal(getDbStats(dir).tableCounts.checkpoint_epochs, 1);
91
+ });
92
+ });
93
+ describe("integrityCheck", () => {
94
+ it("returns ['ok'] on a healthy DB", () => {
95
+ const lines = integrityCheck(dir);
96
+ assert.deepEqual(lines, ["ok"]);
97
+ });
98
+ });
99
+ describe("checkpointWal", () => {
100
+ it("runs without error and reports checkpointed frames", () => {
101
+ const r = checkpointWal(dir);
102
+ assert.ok(r.summary.includes("wal_checkpoint(TRUNCATE)"));
103
+ });
104
+ });
105
+ describe("vacuumDb", () => {
106
+ it("rebuilds the DB file", () => {
107
+ appendRawTranscript(db, makeRow());
108
+ const r = vacuumDb(dir);
109
+ assert.ok(r.summary.includes("VACUUM"));
110
+ // DB file still exists after vacuum
111
+ assert.ok(statSync(join(dir, "sqlite.db")).size > 0);
112
+ });
113
+ });
114
+ describe("reconcileDedupMirror", () => {
115
+ it("fixes ref_count drift and deletes orphans", () => {
116
+ // Insert a dedup_mirror row with ref_count = 5 (drift: actual refs = 1).
117
+ const hash = "hash-recon-1";
118
+ upsertDedupMirror(db, hash, "content-bytes-1", 0);
119
+ // Force a drift: bump ref_count without a matching raw_transcript row.
120
+ db.prepare("UPDATE dedup_mirror SET ref_count = 5 WHERE content_hash = ?").run(hash);
121
+ // Insert one raw_transcript row pointing at it. appendRawTranscript auto-
122
+ // assigns seq = MAX(seq)+1 = 1 for the first row in this session.
123
+ appendRawTranscript(db, makeRow({ contentHash: "rt-recon-1" }));
124
+ updateRawTranscriptRef(db, "sess-1", 1, hash);
125
+ const r = reconcileDedupMirror(dir);
126
+ // ref_count should now be 1 (one raw_transcript row points at it).
127
+ const dm = db
128
+ .prepare("SELECT ref_count FROM dedup_mirror WHERE content_hash = ?")
129
+ .get(hash);
130
+ assert.equal(dm?.ref_count, 1);
131
+ assert.equal(r.fixedRefCount, 1);
132
+ });
133
+ it("deletes orphan dedup_mirror rows (no raw_transcript refs)", () => {
134
+ // Insert a dedup_mirror row with ref_count > 0 but NO raw_transcript ref.
135
+ const hash = "hash-orphan-1";
136
+ upsertDedupMirror(db, hash, "orphan-content", 0);
137
+ db.prepare("UPDATE dedup_mirror SET ref_count = 3 WHERE content_hash = ?").run(hash);
138
+ const r = reconcileDedupMirror(dir);
139
+ const exists = db
140
+ .prepare("SELECT 1 FROM dedup_mirror WHERE content_hash = ?")
141
+ .get(hash);
142
+ assert.equal(exists, undefined);
143
+ assert.ok(r.orphansDeleted > 0);
144
+ });
145
+ });
146
+ describe("autoMaintain", () => {
147
+ it("runs best-effort and returns a summary string", () => {
148
+ appendRawTranscript(db, makeRow());
149
+ const result = autoMaintain(dir);
150
+ assert.ok(typeof result === "string");
151
+ assert.ok(result.startsWith("auto-maintain:"));
152
+ });
153
+ it("reports nothing to do on a fresh empty DB", () => {
154
+ const result = autoMaintain(dir);
155
+ assert.equal(result, "auto-maintain: nothing to do");
156
+ });
157
+ });
158
+ });
@@ -0,0 +1,175 @@
1
+ /**
2
+ * Tests for DB-mirror raw_transcript + checkpoint_epochs tables.
3
+ */
4
+ import { describe, it, beforeEach, afterEach } from "node:test";
5
+ import assert from "node:assert/strict";
6
+ import { mkdtempSync, rmSync } from "node:fs";
7
+ import { join } from "node:path";
8
+ import { tmpdir } from "node:os";
9
+ import { openStore, appendRawTranscript, listRawTranscriptRange, writeCheckpointEpoch, readCheckpointEpoch, getActiveEpochForSession, listCheckpointEpochs, countRawTranscript, } from "./sqlite.js";
10
+ function makeTmp() {
11
+ return mkdtempSync(join(tmpdir(), "dbmirror-test-"));
12
+ }
13
+ function makeRow(overrides = {}) {
14
+ return {
15
+ contentHash: `hash-${Math.random().toString(36).slice(2, 10)}`,
16
+ sessionId: "sess-1",
17
+ seq: 0,
18
+ role: "user",
19
+ contentBytes: "hello world",
20
+ toolName: null,
21
+ messageTimestamp: null,
22
+ checkpointEpoch: "epoch-1",
23
+ ...overrides,
24
+ };
25
+ }
26
+ function makeEpoch(overrides = {}) {
27
+ return {
28
+ epochId: `epoch-${Math.random().toString(36).slice(2, 10)}`,
29
+ sessionId: "sess-1",
30
+ startedSeq: 0,
31
+ committedSeq: 10,
32
+ checkpointId: "cp-1",
33
+ cutIndex: 10,
34
+ summaryMessageText: "test summary",
35
+ createdAt: Date.now(),
36
+ ...overrides,
37
+ };
38
+ }
39
+ describe("DB mirror", () => {
40
+ let dir;
41
+ let db;
42
+ beforeEach(() => {
43
+ dir = makeTmp();
44
+ db = openStore(dir);
45
+ });
46
+ afterEach(() => {
47
+ rmSync(dir, { recursive: true, force: true });
48
+ });
49
+ describe("appendRawTranscript", () => {
50
+ it("inserts a row and auto-assigns seq", () => {
51
+ const row = makeRow();
52
+ appendRawTranscript(db, row);
53
+ const count = countRawTranscript(db);
54
+ assert.equal(count, 1);
55
+ const rows = listRawTranscriptRange(db, "sess-1", 0, 999999);
56
+ assert.equal(rows.length, 1);
57
+ assert.equal(rows[0].contentHash, row.contentHash);
58
+ assert.equal(rows[0].role, "user");
59
+ });
60
+ it("is idempotent on content_hash PK — no duplicate rows", () => {
61
+ const row = makeRow({ contentHash: "fixed-hash" });
62
+ appendRawTranscript(db, row);
63
+ appendRawTranscript(db, row); // duplicate
64
+ const count = countRawTranscript(db);
65
+ assert.equal(count, 1);
66
+ });
67
+ it("increments seq across different messages in same session", () => {
68
+ appendRawTranscript(db, makeRow({ contentHash: "h1", sessionId: "s1" }));
69
+ appendRawTranscript(db, makeRow({ contentHash: "h2", sessionId: "s1" }));
70
+ appendRawTranscript(db, makeRow({ contentHash: "h3", sessionId: "s1" }));
71
+ const count = countRawTranscript(db);
72
+ assert.equal(count, 3);
73
+ });
74
+ it("stores tool_name and message_timestamp when provided", () => {
75
+ appendRawTranscript(db, makeRow({
76
+ contentHash: "tool-row",
77
+ role: "toolResult",
78
+ toolName: "bash",
79
+ messageTimestamp: 1234567890,
80
+ }));
81
+ const rows = listRawTranscriptRange(db, "sess-1", 0, 999999);
82
+ assert.equal(rows[0].toolName, "bash");
83
+ assert.equal(rows[0].messageTimestamp, 1234567890);
84
+ });
85
+ it("stores checkpoint_epoch", () => {
86
+ appendRawTranscript(db, makeRow({ checkpointEpoch: "ep-42" }));
87
+ const rows = listRawTranscriptRange(db, "sess-1", 0, 999999);
88
+ assert.equal(rows[0].checkpointEpoch, "ep-42");
89
+ });
90
+ });
91
+ describe("writeCheckpointEpoch + readCheckpointEpoch", () => {
92
+ it("round-trips a checkpoint epoch", () => {
93
+ const epoch = makeEpoch();
94
+ writeCheckpointEpoch(db, epoch);
95
+ const got = readCheckpointEpoch(db, epoch.epochId);
96
+ assert.ok(got);
97
+ assert.equal(got.epochId, epoch.epochId);
98
+ assert.equal(got.sessionId, epoch.sessionId);
99
+ assert.equal(got.committedSeq, epoch.committedSeq);
100
+ assert.equal(got.checkpointId, epoch.checkpointId);
101
+ assert.equal(got.cutIndex, epoch.cutIndex);
102
+ assert.equal(got.summaryMessageText, epoch.summaryMessageText);
103
+ });
104
+ it("is idempotent on epochId PK", () => {
105
+ const epoch = makeEpoch({ epochId: "ep-dup" });
106
+ writeCheckpointEpoch(db, epoch);
107
+ writeCheckpointEpoch(db, epoch); // duplicate
108
+ // Should not throw, still one row
109
+ const got = readCheckpointEpoch(db, "ep-dup");
110
+ assert.ok(got);
111
+ });
112
+ it("returns null for unknown epochId", () => {
113
+ const got = readCheckpointEpoch(db, "nonexistent");
114
+ assert.equal(got, null);
115
+ });
116
+ });
117
+ describe("getActiveEpochForSession", () => {
118
+ it("returns the most recent epoch for a session", () => {
119
+ writeCheckpointEpoch(db, makeEpoch({
120
+ epochId: "ep-old",
121
+ sessionId: "s1",
122
+ createdAt: 1000,
123
+ }));
124
+ writeCheckpointEpoch(db, makeEpoch({
125
+ epochId: "ep-new",
126
+ sessionId: "s1",
127
+ createdAt: 2000,
128
+ }));
129
+ const got = getActiveEpochForSession(db, "s1");
130
+ assert.ok(got);
131
+ assert.equal(got.epochId, "ep-new");
132
+ });
133
+ it("returns null if no epochs exist for session", () => {
134
+ const got = getActiveEpochForSession(db, "no-such-session");
135
+ assert.equal(got, null);
136
+ });
137
+ });
138
+ describe("checkpointEpochs()", () => {
139
+ it("returns all rows", () => {
140
+ writeCheckpointEpoch(db, makeEpoch({ epochId: "ep-a" }));
141
+ writeCheckpointEpoch(db, makeEpoch({ epochId: "ep-b" }));
142
+ const rows = listCheckpointEpochs(db);
143
+ assert.equal(rows.length, 2);
144
+ });
145
+ });
146
+ describe("integration: raw_transcript + checkpoint_epochs", () => {
147
+ it("full flow: append messages, write epoch, query both", () => {
148
+ // Append 5 messages
149
+ for (let i = 1; i <= 5; i++) {
150
+ appendRawTranscript(db, makeRow({
151
+ contentHash: `msg-${i}`,
152
+ sessionId: "s1",
153
+ checkpointEpoch: "ep-1",
154
+ }));
155
+ }
156
+ // Write epoch
157
+ writeCheckpointEpoch(db, makeEpoch({
158
+ epochId: "ep-1",
159
+ sessionId: "s1",
160
+ committedSeq: 5,
161
+ cutIndex: 5,
162
+ }));
163
+ // Verify transcript rows
164
+ const transcripts = listRawTranscriptRange(db, "s1", 0, 999999);
165
+ assert.equal(transcripts.length, 5);
166
+ for (const t of transcripts) {
167
+ assert.equal(t.checkpointEpoch, "ep-1");
168
+ }
169
+ // Verify epoch
170
+ const epoch = readCheckpointEpoch(db, "ep-1");
171
+ assert.ok(epoch);
172
+ assert.equal(epoch.committedSeq, 5);
173
+ });
174
+ });
175
+ });