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.
@@ -0,0 +1,193 @@
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 {
13
+ openStore,
14
+ appendRawTranscript,
15
+ writeCheckpointEpoch,
16
+ upsertDedupMirror,
17
+ updateRawTranscriptRef,
18
+ getDbStats,
19
+ pruneOldRows,
20
+ checkpointWal,
21
+ vacuumDb,
22
+ integrityCheck,
23
+ reconcileDedupMirror,
24
+ autoMaintain,
25
+ type RawTranscriptRow,
26
+ type CheckpointEpoch,
27
+ } from "./sqlite.js";
28
+
29
+ function makeTmp(): string {
30
+ return mkdtempSync(join(tmpdir(), "dbmaint-test-"));
31
+ }
32
+
33
+ function makeRow(overrides: Partial<RawTranscriptRow> = {}): RawTranscriptRow {
34
+ return {
35
+ contentHash: `hash-${Math.random().toString(36).slice(2, 10)}`,
36
+ sessionId: "sess-1",
37
+ seq: 0,
38
+ role: "user",
39
+ contentBytes: "hello world",
40
+ toolName: null,
41
+ messageTimestamp: Date.now(),
42
+ checkpointEpoch: "epoch-1",
43
+ ...overrides,
44
+ };
45
+ }
46
+
47
+ function makeEpoch(overrides: Partial<CheckpointEpoch> = {}): CheckpointEpoch {
48
+ return {
49
+ epochId: `epoch-${Math.random().toString(36).slice(2, 10)}`,
50
+ sessionId: "sess-1",
51
+ startedSeq: 0,
52
+ committedSeq: 10,
53
+ checkpointId: "cp-1",
54
+ cutIndex: 10,
55
+ summaryMessageText: "test summary",
56
+ createdAt: Date.now(),
57
+ ...overrides,
58
+ };
59
+ }
60
+
61
+ describe("DB maintenance primitives (S27 Task 10)", () => {
62
+ let dir: string;
63
+ let db: ReturnType<typeof openStore>;
64
+
65
+ beforeEach(() => {
66
+ dir = makeTmp();
67
+ db = openStore(dir);
68
+ });
69
+
70
+ afterEach(() => {
71
+ rmSync(dir, { recursive: true, force: true });
72
+ });
73
+
74
+ describe("getDbStats", () => {
75
+ it("returns zero counts on an empty store", () => {
76
+ const s = getDbStats(dir);
77
+ assert.equal(s.tableCounts.raw_transcript, 0);
78
+ assert.equal(s.tableCounts.checkpoint_epochs, 0);
79
+ assert.equal(s.tableCounts.dedup_mirror, 0);
80
+ // main DB file exists (schema was written)
81
+ assert.ok(s.dbBytes > 0);
82
+ assert.ok(s.pageSize > 0);
83
+ assert.ok(s.pageCount > 0);
84
+ });
85
+
86
+ it("counts rows after inserts", () => {
87
+ appendRawTranscript(db, makeRow());
88
+ appendRawTranscript(db, makeRow());
89
+ const s = getDbStats(dir);
90
+ assert.equal(s.tableCounts.raw_transcript, 2);
91
+ });
92
+ });
93
+
94
+ describe("pruneOldRows", () => {
95
+ it("deletes nothing when all rows are recent", () => {
96
+ appendRawTranscript(db, makeRow({ messageTimestamp: Date.now() }));
97
+ const r = pruneOldRows(dir, 30);
98
+ assert.equal(r.affected, 0);
99
+ });
100
+
101
+ it("deletes raw_transcript rows older than the cutoff", () => {
102
+ const oldTs = Date.now() - 31 * 86_400_000;
103
+ appendRawTranscript(db, makeRow({ messageTimestamp: oldTs }));
104
+ appendRawTranscript(db, makeRow({ messageTimestamp: Date.now() }));
105
+ const r = pruneOldRows(dir, 30);
106
+ assert.equal(r.affected, 1);
107
+ assert.equal(getDbStats(dir).tableCounts.raw_transcript, 1);
108
+ });
109
+
110
+ it("deletes checkpoint_epochs older than the cutoff", () => {
111
+ const oldTs = Date.now() - 40 * 86_400_000;
112
+ writeCheckpointEpoch(db, makeEpoch({ createdAt: oldTs }));
113
+ writeCheckpointEpoch(db, makeEpoch({ createdAt: Date.now() }));
114
+ const r = pruneOldRows(dir, 30);
115
+ assert.equal(r.affected, 1);
116
+ assert.equal(getDbStats(dir).tableCounts.checkpoint_epochs, 1);
117
+ });
118
+ });
119
+
120
+ describe("integrityCheck", () => {
121
+ it("returns ['ok'] on a healthy DB", () => {
122
+ const lines = integrityCheck(dir);
123
+ assert.deepEqual(lines, ["ok"]);
124
+ });
125
+ });
126
+
127
+ describe("checkpointWal", () => {
128
+ it("runs without error and reports checkpointed frames", () => {
129
+ const r = checkpointWal(dir);
130
+ assert.ok(r.summary.includes("wal_checkpoint(TRUNCATE)"));
131
+ });
132
+ });
133
+
134
+ describe("vacuumDb", () => {
135
+ it("rebuilds the DB file", () => {
136
+ appendRawTranscript(db, makeRow());
137
+ const r = vacuumDb(dir);
138
+ assert.ok(r.summary.includes("VACUUM"));
139
+ // DB file still exists after vacuum
140
+ assert.ok(statSync(join(dir, "sqlite.db")).size > 0);
141
+ });
142
+ });
143
+
144
+ describe("reconcileDedupMirror", () => {
145
+ it("fixes ref_count drift and deletes orphans", () => {
146
+ // Insert a dedup_mirror row with ref_count = 5 (drift: actual refs = 1).
147
+ const hash = "hash-recon-1";
148
+ upsertDedupMirror(db, hash, "content-bytes-1", 0);
149
+ // Force a drift: bump ref_count without a matching raw_transcript row.
150
+ db.prepare("UPDATE dedup_mirror SET ref_count = 5 WHERE content_hash = ?").run(hash);
151
+ // Insert one raw_transcript row pointing at it. appendRawTranscript auto-
152
+ // assigns seq = MAX(seq)+1 = 1 for the first row in this session.
153
+ appendRawTranscript(db, makeRow({ contentHash: "rt-recon-1" }));
154
+ updateRawTranscriptRef(db, "sess-1", 1, hash);
155
+
156
+ const r = reconcileDedupMirror(dir);
157
+ // ref_count should now be 1 (one raw_transcript row points at it).
158
+ const dm = db
159
+ .prepare("SELECT ref_count FROM dedup_mirror WHERE content_hash = ?")
160
+ .get(hash) as { ref_count: number } | undefined;
161
+ assert.equal(dm?.ref_count, 1);
162
+ assert.equal(r.fixedRefCount, 1);
163
+ });
164
+
165
+ it("deletes orphan dedup_mirror rows (no raw_transcript refs)", () => {
166
+ // Insert a dedup_mirror row with ref_count > 0 but NO raw_transcript ref.
167
+ const hash = "hash-orphan-1";
168
+ upsertDedupMirror(db, hash, "orphan-content", 0);
169
+ db.prepare("UPDATE dedup_mirror SET ref_count = 3 WHERE content_hash = ?").run(hash);
170
+
171
+ const r = reconcileDedupMirror(dir);
172
+ const exists = db
173
+ .prepare("SELECT 1 FROM dedup_mirror WHERE content_hash = ?")
174
+ .get(hash);
175
+ assert.equal(exists, undefined);
176
+ assert.ok(r.orphansDeleted > 0);
177
+ });
178
+ });
179
+
180
+ describe("autoMaintain", () => {
181
+ it("runs best-effort and returns a summary string", () => {
182
+ appendRawTranscript(db, makeRow());
183
+ const result = autoMaintain(dir);
184
+ assert.ok(typeof result === "string");
185
+ assert.ok(result.startsWith("auto-maintain:"));
186
+ });
187
+
188
+ it("reports nothing to do on a fresh empty DB", () => {
189
+ const result = autoMaintain(dir);
190
+ assert.equal(result, "auto-maintain: nothing to do");
191
+ });
192
+ });
193
+ });
@@ -0,0 +1,219 @@
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 {
10
+ openStore,
11
+ appendRawTranscript,
12
+ listRawTranscriptRange,
13
+ writeCheckpointEpoch,
14
+ readCheckpointEpoch,
15
+ getActiveEpochForSession,
16
+ listCheckpointEpochs,
17
+ countRawTranscript,
18
+ type RawTranscriptRow,
19
+ type CheckpointEpoch,
20
+ } from "./sqlite.js";
21
+
22
+ function makeTmp(): string {
23
+ return mkdtempSync(join(tmpdir(), "dbmirror-test-"));
24
+ }
25
+
26
+ function makeRow(overrides: Partial<RawTranscriptRow> = {}): RawTranscriptRow {
27
+ return {
28
+ contentHash: `hash-${Math.random().toString(36).slice(2, 10)}`,
29
+ sessionId: "sess-1",
30
+ seq: 0,
31
+ role: "user",
32
+ contentBytes: "hello world",
33
+ toolName: null,
34
+ messageTimestamp: null,
35
+ checkpointEpoch: "epoch-1",
36
+ ...overrides,
37
+ };
38
+ }
39
+
40
+ function makeEpoch(overrides: Partial<CheckpointEpoch> = {}): CheckpointEpoch {
41
+ return {
42
+ epochId: `epoch-${Math.random().toString(36).slice(2, 10)}`,
43
+ sessionId: "sess-1",
44
+ startedSeq: 0,
45
+ committedSeq: 10,
46
+ checkpointId: "cp-1",
47
+ cutIndex: 10,
48
+ summaryMessageText: "test summary",
49
+ createdAt: Date.now(),
50
+ ...overrides,
51
+ };
52
+ }
53
+
54
+ describe("DB mirror", () => {
55
+ let dir: string;
56
+ let db: ReturnType<typeof openStore>;
57
+
58
+ beforeEach(() => {
59
+ dir = makeTmp();
60
+ db = openStore(dir);
61
+ });
62
+
63
+ afterEach(() => {
64
+ rmSync(dir, { recursive: true, force: true });
65
+ });
66
+
67
+ describe("appendRawTranscript", () => {
68
+ it("inserts a row and auto-assigns seq", () => {
69
+ const row = makeRow();
70
+ appendRawTranscript(db, row);
71
+ const count = countRawTranscript(db);
72
+ assert.equal(count, 1);
73
+ const rows = listRawTranscriptRange(db, "sess-1", 0, 999999);
74
+ assert.equal(rows.length, 1);
75
+ assert.equal(rows[0].contentHash, row.contentHash);
76
+ assert.equal(rows[0].role, "user");
77
+ });
78
+
79
+ it("is idempotent on content_hash PK — no duplicate rows", () => {
80
+ const row = makeRow({ contentHash: "fixed-hash" });
81
+ appendRawTranscript(db, row);
82
+ appendRawTranscript(db, row); // duplicate
83
+ const count = countRawTranscript(db);
84
+ assert.equal(count, 1);
85
+ });
86
+
87
+ it("increments seq across different messages in same session", () => {
88
+ appendRawTranscript(db, makeRow({ contentHash: "h1", sessionId: "s1" }));
89
+ appendRawTranscript(db, makeRow({ contentHash: "h2", sessionId: "s1" }));
90
+ appendRawTranscript(db, makeRow({ contentHash: "h3", sessionId: "s1" }));
91
+ const count = countRawTranscript(db);
92
+ assert.equal(count, 3);
93
+ });
94
+
95
+ it("stores tool_name and message_timestamp when provided", () => {
96
+ appendRawTranscript(
97
+ db,
98
+ makeRow({
99
+ contentHash: "tool-row",
100
+ role: "toolResult",
101
+ toolName: "bash",
102
+ messageTimestamp: 1234567890,
103
+ }),
104
+ );
105
+ const rows = listRawTranscriptRange(db, "sess-1", 0, 999999);
106
+ assert.equal(rows[0].toolName, "bash");
107
+ assert.equal(rows[0].messageTimestamp, 1234567890);
108
+ });
109
+
110
+ it("stores checkpoint_epoch", () => {
111
+ appendRawTranscript(db, makeRow({ checkpointEpoch: "ep-42" }));
112
+ const rows = listRawTranscriptRange(db, "sess-1", 0, 999999);
113
+ assert.equal(rows[0].checkpointEpoch, "ep-42");
114
+ });
115
+ });
116
+
117
+ describe("writeCheckpointEpoch + readCheckpointEpoch", () => {
118
+ it("round-trips a checkpoint epoch", () => {
119
+ const epoch = makeEpoch();
120
+ writeCheckpointEpoch(db, epoch);
121
+ const got = readCheckpointEpoch(db, epoch.epochId);
122
+ assert.ok(got);
123
+ assert.equal(got.epochId, epoch.epochId);
124
+ assert.equal(got.sessionId, epoch.sessionId);
125
+ assert.equal(got.committedSeq, epoch.committedSeq);
126
+ assert.equal(got.checkpointId, epoch.checkpointId);
127
+ assert.equal(got.cutIndex, epoch.cutIndex);
128
+ assert.equal(got.summaryMessageText, epoch.summaryMessageText);
129
+ });
130
+
131
+ it("is idempotent on epochId PK", () => {
132
+ const epoch = makeEpoch({ epochId: "ep-dup" });
133
+ writeCheckpointEpoch(db, epoch);
134
+ writeCheckpointEpoch(db, epoch); // duplicate
135
+ // Should not throw, still one row
136
+ const got = readCheckpointEpoch(db, "ep-dup");
137
+ assert.ok(got);
138
+ });
139
+
140
+ it("returns null for unknown epochId", () => {
141
+ const got = readCheckpointEpoch(db, "nonexistent");
142
+ assert.equal(got, null);
143
+ });
144
+ });
145
+
146
+ describe("getActiveEpochForSession", () => {
147
+ it("returns the most recent epoch for a session", () => {
148
+ writeCheckpointEpoch(
149
+ db,
150
+ makeEpoch({
151
+ epochId: "ep-old",
152
+ sessionId: "s1",
153
+ createdAt: 1000,
154
+ }),
155
+ );
156
+ writeCheckpointEpoch(
157
+ db,
158
+ makeEpoch({
159
+ epochId: "ep-new",
160
+ sessionId: "s1",
161
+ createdAt: 2000,
162
+ }),
163
+ );
164
+ const got = getActiveEpochForSession(db, "s1");
165
+ assert.ok(got);
166
+ assert.equal(got.epochId, "ep-new");
167
+ });
168
+
169
+ it("returns null if no epochs exist for session", () => {
170
+ const got = getActiveEpochForSession(db, "no-such-session");
171
+ assert.equal(got, null);
172
+ });
173
+ });
174
+
175
+ describe("checkpointEpochs()", () => {
176
+ it("returns all rows", () => {
177
+ writeCheckpointEpoch(db, makeEpoch({ epochId: "ep-a" }));
178
+ writeCheckpointEpoch(db, makeEpoch({ epochId: "ep-b" }));
179
+ const rows = listCheckpointEpochs(db);
180
+ assert.equal(rows.length, 2);
181
+ });
182
+ });
183
+
184
+ describe("integration: raw_transcript + checkpoint_epochs", () => {
185
+ it("full flow: append messages, write epoch, query both", () => {
186
+ // Append 5 messages
187
+ for (let i = 1; i <= 5; i++) {
188
+ appendRawTranscript(
189
+ db,
190
+ makeRow({
191
+ contentHash: `msg-${i}`,
192
+ sessionId: "s1",
193
+ checkpointEpoch: "ep-1",
194
+ }),
195
+ );
196
+ }
197
+ // Write epoch
198
+ writeCheckpointEpoch(
199
+ db,
200
+ makeEpoch({
201
+ epochId: "ep-1",
202
+ sessionId: "s1",
203
+ committedSeq: 5,
204
+ cutIndex: 5,
205
+ }),
206
+ );
207
+ // Verify transcript rows
208
+ const transcripts = listRawTranscriptRange(db, "s1", 0, 999999);
209
+ assert.equal(transcripts.length, 5);
210
+ for (const t of transcripts) {
211
+ assert.equal(t.checkpointEpoch, "ep-1");
212
+ }
213
+ // Verify epoch
214
+ const epoch = readCheckpointEpoch(db, "ep-1");
215
+ assert.ok(epoch);
216
+ assert.equal(epoch.committedSeq, 5);
217
+ });
218
+ });
219
+ });