pi-mega-compact 0.4.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.
- package/LICENSE +24 -0
- package/README.md +375 -0
- package/extensions/DASHBOARD.md +160 -0
- package/extensions/dashboard-server.test.ts +124 -0
- package/extensions/dashboard-server.ts +459 -0
- package/extensions/error-patterns.ts +175 -0
- package/extensions/mega-compact.test.ts +351 -0
- package/extensions/mega-compact.ts +846 -0
- package/extensions/openclaw-mega-compact.ts +370 -0
- package/package.json +61 -0
- package/src/adapt.ts +120 -0
- package/src/boundary.test.ts +61 -0
- package/src/boundary.ts +94 -0
- package/src/canary.ts +126 -0
- package/src/compact.test.ts +99 -0
- package/src/compact.ts +262 -0
- package/src/config/dedup.ts +120 -0
- package/src/config.ts +15 -0
- package/src/dedup/dedup.test.ts +46 -0
- package/src/dedup/digest.ts +40 -0
- package/src/dedup/l1-lsh.ts +67 -0
- package/src/dedup/l1-minhash.ts +90 -0
- package/src/dedup/l1-verify.ts +55 -0
- package/src/dedup/l1.test.ts +57 -0
- package/src/dedup/mmr.ts +54 -0
- package/src/dedup/normalize.ts +41 -0
- package/src/dedup/raptor/guardrails.ts +112 -0
- package/src/dedup/raptor/index.ts +118 -0
- package/src/dedup/raptor/kmeans.ts +156 -0
- package/src/dedup/raptor/raptor.test.ts +238 -0
- package/src/dedup/raptor/retrieval.ts +102 -0
- package/src/dedup/raptor/summarizer.ts +91 -0
- package/src/dedup/raptor/tree.ts +254 -0
- package/src/dedup/sprint12.test.ts +242 -0
- package/src/dedup/topk.ts +61 -0
- package/src/dedup-engine.test.ts +609 -0
- package/src/e2e.test.ts +843 -0
- package/src/embedder.ts +111 -0
- package/src/engine.test.ts +123 -0
- package/src/engine.ts +192 -0
- package/src/extractive.test.ts +156 -0
- package/src/extractive.ts +265 -0
- package/src/httpEmbedder.ts +154 -0
- package/src/log.test.ts +47 -0
- package/src/log.ts +60 -0
- package/src/monitoring.ts +171 -0
- package/src/ratio.bench.test.ts +1316 -0
- package/src/recall.integration.test.ts +96 -0
- package/src/recall.test.ts +59 -0
- package/src/recall.ts +100 -0
- package/src/sprint14.test.ts +245 -0
- package/src/store/backfill.ts +263 -0
- package/src/store/bloom.ts +122 -0
- package/src/store/compression.test.ts +83 -0
- package/src/store/compression.ts +203 -0
- package/src/store/integrity.ts +65 -0
- package/src/store/migrate.test.ts +158 -0
- package/src/store/migrate.ts +108 -0
- package/src/store/sprint10.test.ts +182 -0
- package/src/store/sqlite.ts +519 -0
- package/src/store.test.ts +169 -0
- package/src/store.ts +192 -0
- package/src/supersede.test.ts +42 -0
- package/src/supersede.ts +67 -0
- package/src/tokens.ts +35 -0
- package/src/types.test.ts +10 -0
- package/src/types.ts +49 -0
- package/src/vectorStore.test.ts +480 -0
- package/src/vectorStore.ts +544 -0
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* integrity.ts — post-backfill / audit integrity checks (Sprint 10).
|
|
3
|
+
*
|
|
4
|
+
* Two checks (QA #1 / QA #14 spirit, re-mapped locally):
|
|
5
|
+
* 1. Sentinel vs recomputed: the `session_state.stored_region_hashes` set must
|
|
6
|
+
* equal the set of `region_hash` values recomputed from `context_chunks`.
|
|
7
|
+
* A mismatch flags a tampered / stale sentinel (so the dedup sentinel can't
|
|
8
|
+
* miss a real duplicate).
|
|
9
|
+
* 2. Orphan id detection: any `injected_checkpoint_ids` entry that does not
|
|
10
|
+
* correspond to a real `context_chunks.id` is orphaned and flagged.
|
|
11
|
+
*
|
|
12
|
+
* Pure read-only verification — never mutates; returns a structured report.
|
|
13
|
+
* SQLite is the source of truth; no network (PREVENT-PI-004).
|
|
14
|
+
*/
|
|
15
|
+
|
|
16
|
+
import { openStore, listCheckpoints, loadSessionState } from "./sqlite.js";
|
|
17
|
+
import { getStateDir, normalizeSessionId } from "../store.js";
|
|
18
|
+
|
|
19
|
+
export interface IntegrityReport {
|
|
20
|
+
sessionId: string;
|
|
21
|
+
ok: boolean;
|
|
22
|
+
storedRegionHashes: number;
|
|
23
|
+
recomputedRegionHashes: number;
|
|
24
|
+
regionHashMismatch: boolean;
|
|
25
|
+
orphanInjectedIds: string[];
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/** Verify one session's sentinel set + injected-id integrity. */
|
|
29
|
+
export function checkSessionIntegrity(
|
|
30
|
+
sessionId: string,
|
|
31
|
+
stateDir: string = getStateDir(),
|
|
32
|
+
): IntegrityReport {
|
|
33
|
+
openStore(stateDir); // ensure schema is initialized for this state dir
|
|
34
|
+
const sid = normalizeSessionId(sessionId);
|
|
35
|
+
const state = loadSessionState(sessionId, stateDir);
|
|
36
|
+
const checkpoints = listCheckpoints(sessionId, stateDir);
|
|
37
|
+
|
|
38
|
+
// Recompute the region-hash set from the checkpoint rows (source of truth).
|
|
39
|
+
const recomputed = new Set(checkpoints.map((c) => c.regionHash).filter(Boolean));
|
|
40
|
+
const stored = new Set(state.storedRegionHashes);
|
|
41
|
+
const regionHashMismatch =
|
|
42
|
+
recomputed.size !== stored.size || [...recomputed].some((h) => !stored.has(h));
|
|
43
|
+
|
|
44
|
+
// Orphan injected ids: referenced but no matching checkpoint.
|
|
45
|
+
const validIds = new Set(checkpoints.map((c) => c.checkpointId));
|
|
46
|
+
const orphanInjectedIds = state.injectedCheckpointIds.filter((id) => !validIds.has(id));
|
|
47
|
+
|
|
48
|
+
return {
|
|
49
|
+
sessionId: sid,
|
|
50
|
+
ok: !regionHashMismatch && orphanInjectedIds.length === 0,
|
|
51
|
+
storedRegionHashes: stored.size,
|
|
52
|
+
recomputedRegionHashes: recomputed.size,
|
|
53
|
+
regionHashMismatch,
|
|
54
|
+
orphanInjectedIds,
|
|
55
|
+
};
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** Check every session present in the store. */
|
|
59
|
+
export function checkAllIntegrity(stateDir: string = getStateDir()): IntegrityReport[] {
|
|
60
|
+
const db = openStore(stateDir);
|
|
61
|
+
const rows = db.prepare("SELECT DISTINCT session_id FROM context_chunks").all() as {
|
|
62
|
+
session_id: string;
|
|
63
|
+
}[];
|
|
64
|
+
return rows.map((r) => checkSessionIntegrity(r.session_id, stateDir));
|
|
65
|
+
}
|
|
@@ -0,0 +1,158 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* migrate + recall integration test — Sprint 8 acceptance proofs.
|
|
3
|
+
*
|
|
4
|
+
* 1. Migration is lossless: a v0.1.0 `<sess>.checkpoints.json.gz` roundtrips
|
|
5
|
+
* into SQLite with checkpoint count + regionHash set identical, and the JSON
|
|
6
|
+
* file is retained as a DR snapshot.
|
|
7
|
+
* 2. Cross-process recall: compact in one VectorStore, then recall via a FRESH
|
|
8
|
+
* VectorStore over the SAME stateDir (re-opens the same sqlite.db file) — the
|
|
9
|
+
* checkpoint must reappear. Mirrors Sprint 6.1's durability requirement.
|
|
10
|
+
*
|
|
11
|
+
* Uses MEGACOMPACT_STATE_DIR overrides; never the real user state dir.
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
import { test } from "node:test";
|
|
15
|
+
import assert from "node:assert/strict";
|
|
16
|
+
import { mkdtempSync, rmSync, existsSync } from "node:fs";
|
|
17
|
+
import { tmpdir } from "node:os";
|
|
18
|
+
import { join } from "node:path";
|
|
19
|
+
import { VectorStore } from "../vectorStore.js";
|
|
20
|
+
import { writeGzJson } from "../store.js";
|
|
21
|
+
import type { StoredCheckpoint } from "../store.js";
|
|
22
|
+
import { migrateJsonToSqlite, readLegacyCheckpointFile } from "../store/migrate.js";
|
|
23
|
+
import { listCheckpoints, closeStore } from "../store/sqlite.js";
|
|
24
|
+
|
|
25
|
+
const baseTmp = mkdtempSync(join(tmpdir(), "mc-migrate-"));
|
|
26
|
+
let counter = 0;
|
|
27
|
+
function stateDir() {
|
|
28
|
+
return join(baseTmp, `run-${counter++}`);
|
|
29
|
+
}
|
|
30
|
+
function msgVec(): number[] {
|
|
31
|
+
// Deterministic 8-dim vector.
|
|
32
|
+
return [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8];
|
|
33
|
+
}
|
|
34
|
+
function fakeCheckpoints(sessionId: string): StoredCheckpoint[] {
|
|
35
|
+
return [
|
|
36
|
+
{
|
|
37
|
+
checkpointId: "chkpt_001",
|
|
38
|
+
sessionId,
|
|
39
|
+
summary: "Investigated the vector store and added a cosine helper.",
|
|
40
|
+
topicSummary: "Added cosine similarity helper to vector store.",
|
|
41
|
+
summaryHash: "a1b2c3d4e5f6a7b8",
|
|
42
|
+
keyDecisions: ["use linear scan"],
|
|
43
|
+
nextSteps: ["add tests"],
|
|
44
|
+
filesModified: ["src/vectorStore.ts"],
|
|
45
|
+
tokenEstimate: 1200,
|
|
46
|
+
regionHash: "r1",
|
|
47
|
+
embedding: msgVec(),
|
|
48
|
+
timestamp: 1,
|
|
49
|
+
},
|
|
50
|
+
{
|
|
51
|
+
checkpointId: "chkpt_002",
|
|
52
|
+
sessionId,
|
|
53
|
+
summary: "Refactored the recall path to dedupe against the window.",
|
|
54
|
+
topicSummary: "Recall dedup against injected set.",
|
|
55
|
+
summaryHash: "b2c3d4e5f6a7b8c9",
|
|
56
|
+
keyDecisions: [],
|
|
57
|
+
nextSteps: [],
|
|
58
|
+
filesModified: ["src/recall.ts"],
|
|
59
|
+
tokenEstimate: 900,
|
|
60
|
+
regionHash: "r2",
|
|
61
|
+
embedding: msgVec().map((v) => v + 0.01),
|
|
62
|
+
timestamp: 2,
|
|
63
|
+
},
|
|
64
|
+
];
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
test("migration: v0.1.0 JSON checkpoints migrate losslessly into SQLite", () => {
|
|
68
|
+
const dir = stateDir();
|
|
69
|
+
const sid = "sess_migrate_lossless";
|
|
70
|
+
// Write a legacy JSON checkpoint file (the format v0.1.0 shipped).
|
|
71
|
+
writeGzJson(join(dir, `${sid}.checkpoints.json.gz`), fakeCheckpoints(sid));
|
|
72
|
+
|
|
73
|
+
const result = migrateJsonToSqlite(dir);
|
|
74
|
+
assert.equal(result.sessionsScanned, 1);
|
|
75
|
+
assert.equal(result.checkpointsMigrated, 2);
|
|
76
|
+
assert.equal(result.alreadyPresent, 0);
|
|
77
|
+
|
|
78
|
+
// SQLite now has both checkpoints, regionHash preserved.
|
|
79
|
+
const migrated = listCheckpoints(sid, dir);
|
|
80
|
+
assert.equal(migrated.length, 2, "both checkpoints present");
|
|
81
|
+
assert.ok(migrated.every((c) => c.regionHash && c.regionHash.length > 0), "regionHash preserved");
|
|
82
|
+
assert.deepEqual(migrated.map((c) => c.checkpointId).sort(), ["chkpt_001", "chkpt_002"]);
|
|
83
|
+
|
|
84
|
+
// content_hash columns populated (needed by Sprint 9).
|
|
85
|
+
const legacy = readLegacyCheckpointFile(sid, dir);
|
|
86
|
+
assert.equal(legacy.length, 2, "legacy file intact (DR snapshot retained)");
|
|
87
|
+
assert.ok(existsSync(join(dir, `${sid}.checkpoints.json.gz`)), "JSON DR snapshot retained");
|
|
88
|
+
|
|
89
|
+
closeStore(dir);
|
|
90
|
+
});
|
|
91
|
+
|
|
92
|
+
test("migration: re-running is idempotent (no duplicates)", () => {
|
|
93
|
+
const dir = stateDir();
|
|
94
|
+
const sid = "sess_migrate_idem";
|
|
95
|
+
writeGzJson(join(dir, `${sid}.checkpoints.json.gz`), fakeCheckpoints(sid));
|
|
96
|
+
migrateJsonToSqlite(dir);
|
|
97
|
+
const r2 = migrateJsonToSqlite(dir);
|
|
98
|
+
assert.equal(r2.checkpointsMigrated, 0, "nothing new migrated");
|
|
99
|
+
assert.equal(r2.alreadyPresent, 2, "both counted as already present");
|
|
100
|
+
assert.equal(listCheckpoints(sid, dir).length, 2);
|
|
101
|
+
closeStore(dir);
|
|
102
|
+
});
|
|
103
|
+
|
|
104
|
+
test("cross-process recall: fresh VectorStore over same dir recalls prior checkpoint", () => {
|
|
105
|
+
const dir = stateDir();
|
|
106
|
+
const sid = "sess_xproc";
|
|
107
|
+
|
|
108
|
+
// Process A: compact a checkpoint into the store.
|
|
109
|
+
const a = new VectorStore({ stateDir: dir });
|
|
110
|
+
const added = a.add({
|
|
111
|
+
sessionId: sid,
|
|
112
|
+
summary: "Cross-process recall proof: persisted in process A.",
|
|
113
|
+
topicSummary: "Persisted checkpoint in process A.",
|
|
114
|
+
regionText: "cross process recall proof session A write path",
|
|
115
|
+
tokenEstimate: 500,
|
|
116
|
+
timestamp: 1,
|
|
117
|
+
});
|
|
118
|
+
assert.equal(added.deduped, false);
|
|
119
|
+
assert.equal(added.checkpoint.checkpointId, "chkpt_001");
|
|
120
|
+
|
|
121
|
+
// Force a clean reopen (simulates a new process opening the same file).
|
|
122
|
+
closeStore(dir);
|
|
123
|
+
|
|
124
|
+
// Process B: brand-new VectorStore, same stateDir.
|
|
125
|
+
const b = new VectorStore({ stateDir: dir });
|
|
126
|
+
const hits = b.search(sid, "cross process recall proof", 5);
|
|
127
|
+
assert.equal(hits.length, 1, "checkpoint survives cross-process reopen");
|
|
128
|
+
assert.equal(hits[0].checkpoint.checkpointId, "chkpt_001");
|
|
129
|
+
assert.ok(hits[0].score > 0.5, "recall is relevant");
|
|
130
|
+
|
|
131
|
+
closeStore(dir);
|
|
132
|
+
});
|
|
133
|
+
|
|
134
|
+
test("cross-process recall: injected state persists across reopen", () => {
|
|
135
|
+
const dir = stateDir();
|
|
136
|
+
const sid = "sess_xproc_inj";
|
|
137
|
+
const a = new VectorStore({ stateDir: dir });
|
|
138
|
+
const added = a.add({
|
|
139
|
+
sessionId: sid,
|
|
140
|
+
summary: "A checkpoint to inject and remember across processes.",
|
|
141
|
+
topicSummary: "Injected checkpoint.",
|
|
142
|
+
regionText: "injected state persists across process reopen test",
|
|
143
|
+
timestamp: 1,
|
|
144
|
+
});
|
|
145
|
+
a.markInjected(sid, added.checkpoint.checkpointId);
|
|
146
|
+
assert.equal(a.wasInjected(sid, added.checkpoint.checkpointId), true);
|
|
147
|
+
|
|
148
|
+
closeStore(dir);
|
|
149
|
+
|
|
150
|
+
const b = new VectorStore({ stateDir: dir });
|
|
151
|
+
assert.equal(b.wasInjected(sid, added.checkpoint.checkpointId), true, "injection remembered");
|
|
152
|
+
|
|
153
|
+
closeStore(dir);
|
|
154
|
+
});
|
|
155
|
+
|
|
156
|
+
test("cleanup", () => {
|
|
157
|
+
rmSync(baseTmp, { recursive: true, force: true });
|
|
158
|
+
});
|
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* migrate.ts — Sprint 8: bring v0.1.0 JSON checkpoint files into SQLite.
|
|
3
|
+
*
|
|
4
|
+
* Reads every `<sessionId>.checkpoints.json.gz` in the state dir, computes the
|
|
5
|
+
* dedup-tier columns (content_hash / content_hash2 / normalized_text) that
|
|
6
|
+
* Sprints 9-12 match on, and upserts into context_chunks idempotently
|
|
7
|
+
* (ON CONFLICT id DO NOTHING — re-running is a no-op). The JSON files are kept
|
|
8
|
+
* as disaster-recovery snapshots; they are never deleted.
|
|
9
|
+
*
|
|
10
|
+
* Runs on first VectorStore construction (auto-migrate) and is also exposed for
|
|
11
|
+
* the integration test to call explicitly.
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
import { createHash } from "node:crypto";
|
|
15
|
+
import { existsSync, readdirSync } from "node:fs";
|
|
16
|
+
import { join } from "node:path";
|
|
17
|
+
import { getStateDir, readGzJson, normalizeSessionId } from "../store.js";
|
|
18
|
+
import type { StoredCheckpoint } from "../store.js";
|
|
19
|
+
import { openStore, upsertCheckpoint, listCheckpoints } from "./sqlite.js";
|
|
20
|
+
|
|
21
|
+
/** Scan a state dir for v0.1.0 checkpoint JSON files. */
|
|
22
|
+
function legacyCheckpointFiles(stateDir: string): string[] {
|
|
23
|
+
if (!existsSync(stateDir)) return [];
|
|
24
|
+
return readdirSync(stateDir).filter((f) => f.endsWith(".checkpoints.json.gz"));
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** Derive the normalized text + two content hashes for the dedup tiers. */
|
|
28
|
+
export function deriveContentHashes(cp: StoredCheckpoint): {
|
|
29
|
+
normalizedText: string;
|
|
30
|
+
contentHash: string;
|
|
31
|
+
contentHash2: string;
|
|
32
|
+
} {
|
|
33
|
+
// L0/L1 basis: the human summary (whitespace-normalized).
|
|
34
|
+
const normalized = (cp.summary ?? "").replace(/\s+/g, " ").trim();
|
|
35
|
+
const contentHash = createHash("sha256").update(normalized).digest("hex");
|
|
36
|
+
// L2 basis: summary + extractive topic summary (catches paraphrased topics).
|
|
37
|
+
const basis2 = `${normalized}\n${cp.topicSummary ?? ""}`.trim();
|
|
38
|
+
const contentHash2 = createHash("sha256").update(basis2).digest("hex");
|
|
39
|
+
return { normalizedText: normalized, contentHash, contentHash2 };
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** Read a single legacy checkpoint file (lossless: returns every stored field). */
|
|
43
|
+
export function readLegacyCheckpointFile(sessionId: string, stateDir: string = getStateDir()): StoredCheckpoint[] {
|
|
44
|
+
const file = join(stateDir, `${normalizeSessionId(sessionId)}.checkpoints.json.gz`);
|
|
45
|
+
return readGzJson<StoredCheckpoint[]>(file, []);
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
export interface MigrationResult {
|
|
49
|
+
sessionsScanned: number;
|
|
50
|
+
checkpointsMigrated: number;
|
|
51
|
+
alreadyPresent: number;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* Migrate all legacy JSON checkpoint files in `stateDir` into SQLite.
|
|
56
|
+
* Idempotent — safe to call repeatedly. Does not delete JSON files.
|
|
57
|
+
*/
|
|
58
|
+
export function migrateJsonToSqlite(stateDir: string = getStateDir()): MigrationResult {
|
|
59
|
+
openStore(stateDir); // ensures schema exists
|
|
60
|
+
const files = legacyCheckpointFiles(stateDir);
|
|
61
|
+
let sessionsScanned = 0;
|
|
62
|
+
let migrated = 0;
|
|
63
|
+
let alreadyPresent = 0;
|
|
64
|
+
|
|
65
|
+
for (const file of files) {
|
|
66
|
+
// File name shape: <sessionId>.checkpoints.json.gz
|
|
67
|
+
const sessionId = file.replace(/\.checkpoints\.json\.gz$/, "");
|
|
68
|
+
const cps = readLegacyCheckpointFile(sessionId, stateDir);
|
|
69
|
+
if (cps.length === 0) continue;
|
|
70
|
+
sessionsScanned++;
|
|
71
|
+
|
|
72
|
+
const existing = new Set(listCheckpoints(sessionId, stateDir).map((c) => c.checkpointId));
|
|
73
|
+
for (const cp of cps) {
|
|
74
|
+
if (existing.has(cp.checkpointId)) {
|
|
75
|
+
alreadyPresent++;
|
|
76
|
+
continue;
|
|
77
|
+
}
|
|
78
|
+
const { normalizedText, contentHash, contentHash2 } = deriveContentHashes(cp);
|
|
79
|
+
upsertCheckpoint(
|
|
80
|
+
{ ...cp, summary: cp.summary ?? "", regionHash: cp.regionHash ?? "" },
|
|
81
|
+
stateDir,
|
|
82
|
+
);
|
|
83
|
+
// Persist the extra dedup columns (upsertCheckpoint sets them null).
|
|
84
|
+
setContentHashes(cp.checkpointId, contentHash, contentHash2, normalizedText, stateDir);
|
|
85
|
+
migrated++;
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
return { sessionsScanned, checkpointsMigrated: migrated, alreadyPresent };
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
// Direct column update for the computed hashes (kept out of upsertCheckpoint's
|
|
93
|
+
// hot path so the common write doesn't pay for hashing).
|
|
94
|
+
function setContentHashes(
|
|
95
|
+
checkpointId: string,
|
|
96
|
+
contentHash: string,
|
|
97
|
+
contentHash2: string,
|
|
98
|
+
normalizedText: string,
|
|
99
|
+
stateDir: string,
|
|
100
|
+
): void {
|
|
101
|
+
const Database = openStore(stateDir);
|
|
102
|
+
Database.prepare(
|
|
103
|
+
`UPDATE context_chunks
|
|
104
|
+
SET content_hash = @ch, content_hash2 = @ch2,
|
|
105
|
+
content_hash_version = 1, normalized_text = @nt
|
|
106
|
+
WHERE id = @id`,
|
|
107
|
+
).run({ id: checkpointId, ch: contentHash, ch2: contentHash2, nt: normalizedText });
|
|
108
|
+
}
|
|
@@ -0,0 +1,182 @@
|
|
|
1
|
+
import { test } from "node:test";
|
|
2
|
+
import assert from "node:assert/strict";
|
|
3
|
+
import { mkdtempSync, rmSync } from "node:fs";
|
|
4
|
+
import { tmpdir } from "node:os";
|
|
5
|
+
import { join } from "node:path";
|
|
6
|
+
import { VectorStore } from "../vectorStore.js";
|
|
7
|
+
import { normalize } from "../dedup/normalize.js";
|
|
8
|
+
import { openBloom, closeBloom } from "./bloom.js";
|
|
9
|
+
import { backfillContentHashes, isBackfillComplete } from "./backfill.js";
|
|
10
|
+
import { checkSessionIntegrity, checkAllIntegrity } from "./integrity.js";
|
|
11
|
+
import { openStore, closeStore, upsertCheckpoint, saveSessionState, loadSessionState } from "./sqlite.js";
|
|
12
|
+
import type { StoredCheckpoint } from "../store.js";
|
|
13
|
+
|
|
14
|
+
const baseTmp = mkdtempSync(join(tmpdir(), "mc-s10-"));
|
|
15
|
+
|
|
16
|
+
let counter = 0;
|
|
17
|
+
function store(opts: { dedupSim?: number } = {}) {
|
|
18
|
+
const dir = join(baseTmp, `run-${counter++}`);
|
|
19
|
+
return { s: new VectorStore({ dedupSim: opts.dedupSim ?? 0.9, stateDir: dir }), dir };
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
// --- L0 normalization upgrade (case/whitespace/ANSI collapse) --------------
|
|
23
|
+
|
|
24
|
+
test("Sprint 10 L0: case/whitespace/ANSI variants dedup to one row", () => {
|
|
25
|
+
const { s } = store();
|
|
26
|
+
const variants = ["user reviewed the auth module and merged the PR", " USER REVIEWED the AUTH module and MERGED the PR ", "USER REVIEWED THE AUTH MODULE AND MERGED THE PR"];
|
|
27
|
+
let added = 0;
|
|
28
|
+
for (const v of variants) {
|
|
29
|
+
const r = s.add({ sessionId: "sess_norm", summary: "x", regionText: v, timestamp: added + 1 });
|
|
30
|
+
if (!r.deduped) added++;
|
|
31
|
+
}
|
|
32
|
+
assert.equal(s.list("sess_norm").length, 1);
|
|
33
|
+
});
|
|
34
|
+
|
|
35
|
+
test("normalize case-folds so Foo/foo/FOO are equal", () => {
|
|
36
|
+
assert.equal(normalize("Foo Bar"), normalize("foo bar"));
|
|
37
|
+
assert.equal(normalize("FOO BAR"), normalize("foo bar"));
|
|
38
|
+
});
|
|
39
|
+
|
|
40
|
+
test("normalize strips ANSI before hashing", () => {
|
|
41
|
+
assert.equal(normalize("err\x1b[31m fatal\x1b[0m"), normalize("err fatal"));
|
|
42
|
+
});
|
|
43
|
+
|
|
44
|
+
// --- Bloom accelerator ------------------------------------------------------
|
|
45
|
+
|
|
46
|
+
test("bloom miss short-circuits the scan; hit is confirmed by query", () => {
|
|
47
|
+
const { s, dir } = store();
|
|
48
|
+
const raw = "the region text under test for bloom behavior";
|
|
49
|
+
s.add({ sessionId: "sess_bloom", summary: "x", regionText: raw, timestamp: 1 });
|
|
50
|
+
const bloom = openBloom(dir);
|
|
51
|
+
// content_hash for `raw` is present → hit path must confirm via query and dedup.
|
|
52
|
+
assert.equal(bloom.maybeHas("this-key-is-not-present"), false); // definitive miss
|
|
53
|
+
const r2 = s.add({ sessionId: "sess_bloom", summary: "x", regionText: raw, timestamp: 2 });
|
|
54
|
+
assert.equal(r2.deduped, true);
|
|
55
|
+
assert.equal(r2.reason, "contentHash");
|
|
56
|
+
});
|
|
57
|
+
|
|
58
|
+
test("bloom persists to disk and reloads warm", () => {
|
|
59
|
+
const dir = join(baseTmp, `run-${counter++}`);
|
|
60
|
+
const s1 = new VectorStore({ stateDir: dir });
|
|
61
|
+
s1.add({ sessionId: "sess_persist", summary: "x", regionText: "persisted region", timestamp: 1 });
|
|
62
|
+
closeBloom(dir); // evict cache so the next open reads from disk
|
|
63
|
+
const s2 = new VectorStore({ stateDir: dir });
|
|
64
|
+
const r = s2.add({ sessionId: "sess_persist", summary: "x", regionText: "persisted region", timestamp: 2 });
|
|
65
|
+
assert.equal(r.deduped, true);
|
|
66
|
+
});
|
|
67
|
+
|
|
68
|
+
// --- Atomic write + QA #13 timeout degrade ---------------------------------
|
|
69
|
+
|
|
70
|
+
test("duplicate add is idempotent (no partial rows, single checkpoint)", () => {
|
|
71
|
+
const { s } = store();
|
|
72
|
+
const raw = "idempotent region content for atomicity check";
|
|
73
|
+
const a = s.add({ sessionId: "sess_atom", summary: "x", regionText: raw, timestamp: 1 });
|
|
74
|
+
const b = s.add({ sessionId: "sess_atom", summary: "x", regionText: raw, timestamp: 2 });
|
|
75
|
+
assert.equal(a.deduped, false);
|
|
76
|
+
assert.equal(b.deduped, true);
|
|
77
|
+
assert.equal(s.list("sess_atom").length, 1);
|
|
78
|
+
});
|
|
79
|
+
|
|
80
|
+
// --- Backfill orchestrator -------------------------------------------------
|
|
81
|
+
|
|
82
|
+
test("backfill populates null content_hash rows and is idempotent", () => {
|
|
83
|
+
const dir = join(baseTmp, `run-${counter++}`);
|
|
84
|
+
openStore(dir);
|
|
85
|
+
// Seed two rows with null content_hash via direct upsert (simulating legacy data).
|
|
86
|
+
const cp = (id: string, summary: string): StoredCheckpoint => ({
|
|
87
|
+
checkpointId: id,
|
|
88
|
+
sessionId: "sess_bf",
|
|
89
|
+
summary,
|
|
90
|
+
keyDecisions: [],
|
|
91
|
+
nextSteps: [],
|
|
92
|
+
filesModified: [],
|
|
93
|
+
tokenEstimate: 0,
|
|
94
|
+
regionHash: "r",
|
|
95
|
+
embedding: [0, 0, 0],
|
|
96
|
+
timestamp: 1,
|
|
97
|
+
});
|
|
98
|
+
upsertCheckpoint(cp("chkpt_001", "alpha summary"), dir);
|
|
99
|
+
upsertCheckpoint(cp("chkpt_002", "beta summary"), dir);
|
|
100
|
+
|
|
101
|
+
const r1 = backfillContentHashes(dir);
|
|
102
|
+
assert.equal(r1.updated, 2);
|
|
103
|
+
assert.equal(r1.processed, 2);
|
|
104
|
+
assert.equal(isBackfillComplete(dir), true);
|
|
105
|
+
|
|
106
|
+
// Second run is a no-op (idempotent): no rows left to process.
|
|
107
|
+
const r2 = backfillContentHashes(dir);
|
|
108
|
+
assert.equal(r2.processed, 0);
|
|
109
|
+
});
|
|
110
|
+
|
|
111
|
+
test("backfill resolves a content_hash collision keeping the oldest row", () => {
|
|
112
|
+
const dir = join(baseTmp, `run-${counter++}`);
|
|
113
|
+
openStore(dir);
|
|
114
|
+
// Both rows share the same normalized summary → same content_hash.
|
|
115
|
+
const cp = (id: string): StoredCheckpoint => ({
|
|
116
|
+
checkpointId: id,
|
|
117
|
+
sessionId: "sess_dup",
|
|
118
|
+
summary: "identical normalized summary text",
|
|
119
|
+
keyDecisions: [],
|
|
120
|
+
nextSteps: [],
|
|
121
|
+
filesModified: [],
|
|
122
|
+
tokenEstimate: 0,
|
|
123
|
+
regionHash: "r",
|
|
124
|
+
embedding: [0, 0, 0],
|
|
125
|
+
timestamp: 1,
|
|
126
|
+
});
|
|
127
|
+
upsertCheckpoint(cp("chkpt_001"), dir);
|
|
128
|
+
upsertCheckpoint(cp("chkpt_002"), dir);
|
|
129
|
+
const r = backfillContentHashes(dir);
|
|
130
|
+
assert.equal(r.duplicatesResolved, 1);
|
|
131
|
+
assert.equal(r.updated, 1);
|
|
132
|
+
});
|
|
133
|
+
|
|
134
|
+
// --- Integrity checks ------------------------------------------------------
|
|
135
|
+
|
|
136
|
+
test("integrity flags a tampered storedRegionHashes set", () => {
|
|
137
|
+
const dir = join(baseTmp, `run-${counter++}`);
|
|
138
|
+
const s = new VectorStore({ stateDir: dir });
|
|
139
|
+
s.add({ sessionId: "sess_int", summary: "x", regionText: "integrity region one", timestamp: 1 });
|
|
140
|
+
s.add({ sessionId: "sess_int", summary: "y", regionText: "integrity region two", timestamp: 2 });
|
|
141
|
+
const okReport = checkSessionIntegrity("sess_int", dir);
|
|
142
|
+
assert.equal(okReport.ok, true); // consistent after normal adds
|
|
143
|
+
|
|
144
|
+
// Simulate tampering: the sentinel stores a region hash the checkpoints lack.
|
|
145
|
+
const db = openStore(dir);
|
|
146
|
+
db.prepare(
|
|
147
|
+
"UPDATE session_state SET stored_region_hashes = ? WHERE session_id = ?",
|
|
148
|
+
).run(JSON.stringify(["deadbeefcafe0000"]), "sess_int");
|
|
149
|
+
const tampered = checkSessionIntegrity("sess_int", dir);
|
|
150
|
+
assert.equal(tampered.ok, false);
|
|
151
|
+
assert.equal(tampered.regionHashMismatch, true);
|
|
152
|
+
});
|
|
153
|
+
|
|
154
|
+
test("integrity detects an orphan injectedCheckpointId", () => {
|
|
155
|
+
const dir = join(baseTmp, `run-${counter++}`);
|
|
156
|
+
const s = new VectorStore({ stateDir: dir });
|
|
157
|
+
s.add({ sessionId: "sess_orphan", summary: "x", regionText: "orphan region", timestamp: 1 });
|
|
158
|
+
// Manually inject a dangling id into session state (SQLite-backed).
|
|
159
|
+
const st = loadSessionState("sess_orphan", dir);
|
|
160
|
+
st.injectedCheckpointIds.push("chkpt_999");
|
|
161
|
+
saveSessionState("sess_orphan", st, dir);
|
|
162
|
+
const report = checkSessionIntegrity("sess_orphan", dir);
|
|
163
|
+
assert.equal(report.ok, false);
|
|
164
|
+
assert.deepEqual(report.orphanInjectedIds, ["chkpt_999"]);
|
|
165
|
+
});
|
|
166
|
+
|
|
167
|
+
test("checkAllIntegrity covers every session", () => {
|
|
168
|
+
const dir = join(baseTmp, `run-${counter++}`);
|
|
169
|
+
const s = new VectorStore({ stateDir: dir });
|
|
170
|
+
s.add({ sessionId: "sess_a", summary: "x", regionText: "a region", timestamp: 1 });
|
|
171
|
+
s.add({ sessionId: "sess_b", summary: "y", regionText: "b region", timestamp: 1 });
|
|
172
|
+
const reports = checkAllIntegrity(dir);
|
|
173
|
+
assert.equal(reports.length, 2);
|
|
174
|
+
assert.ok(reports.every((r: { ok: boolean }) => r.ok));
|
|
175
|
+
});
|
|
176
|
+
|
|
177
|
+
// --- cleanup ---------------------------------------------------------------
|
|
178
|
+
|
|
179
|
+
test("Sprint 10 cleanup", () => {
|
|
180
|
+
closeStore(baseTmp);
|
|
181
|
+
rmSync(baseTmp, { recursive: true, force: true });
|
|
182
|
+
});
|