pi-mega-compact 0.4.24 → 0.4.26

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,236 @@
1
+ /**
2
+ * vectorIndex.ts — Slice 2 async vector index (PGlite/pgvector HNSW).
3
+ *
4
+ * A REDUNDANT, additive, ASYNC index layered over the synchronous node:sqlite
5
+ * store (which remains the authoritative source of truth). The sync linear
6
+ * cosine scan over `embedding_blob` stays the DEFAULT recall path; this index
7
+ * exists only to provide real cross-repo / cross-session HNSW nearest-neighbor
8
+ * recall. It is best-effort and non-fatal: any init/write failure degrades to
9
+ * the sync scan and must NEVER break add(), compaction, or extension load.
10
+ *
11
+ * PREVENT-PI-004: PGlite is WASM Postgres — fully local, zero network.
12
+ *
13
+ * Index topology (decision 2026-07-15): ONE global PGlite DB, `repo_id` is a
14
+ * first-class column. `searchAsync(q, k, {repoId?})` → omit repoId for cross-repo
15
+ * NN, pass repoId to scope to a single repo. The sync store is per-repo (state
16
+ * dir); this global index is the thing that makes cross-repo recall possible.
17
+ */
18
+ import { homedir } from "node:os";
19
+ import { join } from "node:path";
20
+ import { mkdirSync, rmSync, existsSync } from "node:fs";
21
+ // PGlite + pgvector are script-free WASM (no native build) → survive pi's
22
+ // install-script block. Imported lazily so a missing/broken package degrades
23
+ // gracefully instead of crashing module load.
24
+ import { PGlite } from "@electric-sql/pglite";
25
+ import { vector } from "@electric-sql/pglite-pgvector";
26
+ /** Vector dimension produced by the default TrigramEmbedder (src/embedder.ts). */
27
+ export const EMBEDDING_DIM = 512;
28
+ let db;
29
+ let initPromise;
30
+ let disabled = false;
31
+ let warned = false;
32
+ function indexDir() {
33
+ const override = process.env.MEGACOMPACT_VECTOR_INDEX_DIR;
34
+ if (override && override.trim() !== "")
35
+ return override;
36
+ try {
37
+ return join(homedir(), ".pi", "mega-compact-vector");
38
+ }
39
+ catch {
40
+ return join("/tmp", ".mega-compact-vector");
41
+ }
42
+ }
43
+ function logWarn(msg) {
44
+ // Never throw — degradation is the whole point. One warning per process.
45
+ if (warned)
46
+ return;
47
+ warned = true;
48
+ try {
49
+ console.warn(`[mega-compact:vectorIndex] ${msg} (falling back to sync scan)`);
50
+ }
51
+ catch {
52
+ /* ignore */
53
+ }
54
+ }
55
+ /** Honor the emergency kill-switch. When set, the index is fully disabled. */
56
+ export function isVectorIndexDisabled() {
57
+ return (disabled ||
58
+ process.env.MEGACOMPACT_PGLITE_DISABLED === "true" ||
59
+ process.env.MEGACOMPACT_PGLITE_DISABLED === "1");
60
+ }
61
+ /**
62
+ * Lazily open + schema-init the global PGlite DB. Idempotent and safe to call
63
+ * from many places. Returns undefined when disabled/unavailable so callers can
64
+ * fall back to the synchronous scan. Never throws.
65
+ */
66
+ export function initVectorIndex() {
67
+ if (isVectorIndexDisabled())
68
+ return Promise.resolve(undefined);
69
+ if (db)
70
+ return Promise.resolve(db);
71
+ if (initPromise)
72
+ return initPromise;
73
+ initPromise = openPgLite(/* retryOnCorrupt */ true);
74
+ return initPromise;
75
+ }
76
+ /**
77
+ * Open + schema-init PGlite. When `retryOnCorrupt` is true, a WASM-level
78
+ * abort (typically from a corrupted/torn data dir) triggers a delete + one
79
+ * retry — the dir is rebuilt from scratch by PGlite's initdb.
80
+ */
81
+ async function openPgLite(retryOnCorrupt) {
82
+ try {
83
+ const dir = indexDir();
84
+ mkdirSync(dir, { recursive: true });
85
+ const pg = await new PGlite({
86
+ dataDir: dir,
87
+ extensions: { vector },
88
+ });
89
+ await pg.exec("CREATE EXTENSION IF NOT EXISTS vector;");
90
+ await pg.exec(`
91
+ CREATE TABLE IF NOT EXISTS vector_index (
92
+ repo_id TEXT NOT NULL,
93
+ session_id TEXT NOT NULL,
94
+ checkpoint_id TEXT NOT NULL,
95
+ embedding vector(${EMBEDDING_DIM}) NOT NULL,
96
+ PRIMARY KEY (repo_id, session_id, checkpoint_id)
97
+ );
98
+ `);
99
+ // HNSW index over cosine distance for fast NN. Created idempotently.
100
+ await pg.exec("CREATE INDEX IF NOT EXISTS vector_index_hnsw ON vector_index USING hnsw (embedding vector_cosine_ops);");
101
+ db = pg;
102
+ return pg;
103
+ }
104
+ catch (err) {
105
+ const msg = err instanceof Error ? err.message : String(err);
106
+ // Self-heal: a WASM Aborted() typically means the data dir is corrupted
107
+ // (torn WAL from concurrent access). Delete it and retry once.
108
+ if (retryOnCorrupt &&
109
+ (msg.includes("Aborted") || msg.includes("RuntimeError"))) {
110
+ try {
111
+ const dir = indexDir();
112
+ if (existsSync(dir)) {
113
+ rmSync(dir, { recursive: true, force: true });
114
+ }
115
+ // Clear singleton state so the retry starts fresh.
116
+ initPromise = undefined;
117
+ return openPgLite(/* retryOnCorrupt */ false);
118
+ }
119
+ catch {
120
+ // Self-heal failed — fall through to disable.
121
+ }
122
+ }
123
+ disabled = true;
124
+ logWarn(`init failed: ${msg}`);
125
+ return undefined;
126
+ }
127
+ }
128
+ function toVectorLiteral(v) {
129
+ // pgvector text form: [a,b,c]. Guard against NaN/Inf for a clean literal.
130
+ const parts = v.map((x) => (Number.isFinite(x) ? x : 0));
131
+ return `[${parts.join(",")}]`;
132
+ }
133
+ /**
134
+ * Best-effort upsert of one checkpoint embedding into the global index.
135
+ * Dimension-mismatched vectors (e.g. a BYO embedder with dim ≠ 512) are skipped
136
+ * rather than corrupting the index. Fire-and-forget: resolved promise only;
137
+ * callers must NOT await this on the sync path. Never throws.
138
+ */
139
+ export async function upsertEmbedding(repoId, sessionId, checkpointId, embedding) {
140
+ if (isVectorIndexDisabled())
141
+ return;
142
+ if (!embedding || embedding.length !== EMBEDDING_DIM) {
143
+ // Dimension guard: skip without corrupting the fixed-dim index.
144
+ return;
145
+ }
146
+ try {
147
+ const pg = await initVectorIndex();
148
+ if (!pg)
149
+ return;
150
+ const lit = toVectorLiteral(embedding);
151
+ await pg.query(`INSERT INTO vector_index (repo_id, session_id, checkpoint_id, embedding)
152
+ VALUES ($1, $2, $3, $4::vector)
153
+ ON CONFLICT (repo_id, session_id, checkpoint_id)
154
+ DO UPDATE SET embedding = EXCLUDED.embedding;`, [repoId, sessionId, checkpointId, lit]);
155
+ }
156
+ catch (err) {
157
+ disabled = true;
158
+ logWarn(`upsert failed: ${err instanceof Error ? err.message : String(err)}`);
159
+ }
160
+ }
161
+ /**
162
+ * Cross-repo (or single-repo) HNSW nearest-neighbor search. Returns hits sorted
163
+ * by descending similarity. Never throws — on any failure returns [].
164
+ */
165
+ export async function searchAsync(query, opts = {}) {
166
+ if (isVectorIndexDisabled() || !query || query.length !== EMBEDDING_DIM)
167
+ return [];
168
+ const k = opts.k ?? 3;
169
+ const repoId = opts.repoId;
170
+ try {
171
+ const pg = await initVectorIndex();
172
+ if (!pg)
173
+ return [];
174
+ const lit = toVectorLiteral(query);
175
+ const params = [lit, k];
176
+ let sql = "SELECT repo_id, session_id, checkpoint_id, 1 - (embedding <=> $1::vector) AS score " +
177
+ "FROM vector_index";
178
+ if (repoId) {
179
+ sql += " WHERE repo_id = $3";
180
+ params.push(repoId);
181
+ }
182
+ sql += " ORDER BY embedding <=> $1::vector LIMIT $2";
183
+ const res = await pg.query(sql, params);
184
+ return res.rows.map((r) => ({
185
+ repoId: r.repo_id,
186
+ sessionId: r.session_id,
187
+ checkpointId: r.checkpoint_id,
188
+ score: r.score,
189
+ }));
190
+ }
191
+ catch (err) {
192
+ disabled = true;
193
+ logWarn(`search failed: ${err instanceof Error ? err.message : String(err)}`);
194
+ return [];
195
+ }
196
+ }
197
+ /** Close the index (test teardown / shutdown). Safe to call when unopened. */
198
+ export async function closeVectorIndex() {
199
+ if (db) {
200
+ try {
201
+ await db.close();
202
+ }
203
+ catch {
204
+ /* ignore */
205
+ }
206
+ }
207
+ db = undefined;
208
+ initPromise = undefined;
209
+ disabled = false;
210
+ warned = false;
211
+ }
212
+ /**
213
+ * Rebuild the entire index from the authoritative node:sqlite store. Used for
214
+ * backfill + DR. `enumerateRepoStateDirs` yields each repo's state dir; we read
215
+ * its checkpoint embeddings and bulk upsert. Best-effort: counts successes and
216
+ * skips failures. Returns {upserted, errors}.
217
+ */
218
+ export async function rebuildFromSqlite(enumerateRepoStateDirs, readCheckpoints) {
219
+ let upserted = 0;
220
+ let errors = 0;
221
+ const pg = await initVectorIndex();
222
+ if (!pg)
223
+ return { upserted, errors: 1 };
224
+ for (const repo of enumerateRepoStateDirs()) {
225
+ for (const cp of readCheckpoints(repo.stateDir)) {
226
+ try {
227
+ await upsertEmbedding(repo.repoId, cp.sessionId, cp.checkpointId, cp.embedding);
228
+ upserted++;
229
+ }
230
+ catch {
231
+ errors++;
232
+ }
233
+ }
234
+ }
235
+ return { upserted, errors };
236
+ }
@@ -0,0 +1,99 @@
1
+ /**
2
+ * vectorIndex.test.ts — Slice 2 async PGlite/HNSW vector index.
3
+ *
4
+ * Proves: cross-repo nearest-neighbor recall, repoId scoping, the dimension
5
+ * guard (non-512 vectors skipped, never corrupt the index), and graceful
6
+ * degradation when the index is disabled (kill-switch) — all without touching
7
+ * the synchronous node:sqlite store.
8
+ *
9
+ * The index is a WASM Postgres (PGlite) — fully local, zero network
10
+ * (PREVENT-PI-004). Each test isolates state via MEGACOMPACT_VECTOR_INDEX_DIR.
11
+ */
12
+ import { test } from "node:test";
13
+ import assert from "node:assert/strict";
14
+ import { mkdtempSync, rmSync } from "node:fs";
15
+ import { tmpdir } from "node:os";
16
+ import { join } from "node:path";
17
+ import { EMBEDDING_DIM, initVectorIndex, upsertEmbedding, searchAsync, closeVectorIndex, isVectorIndexDisabled, } from "./vectorIndex.js";
18
+ /** A 512-dim unit-ish vector with a single spike at `idx` (deterministic NN). */
19
+ function spikeVec(idx, magnitude = 1) {
20
+ const v = new Array(EMBEDDING_DIM).fill(0);
21
+ v[idx % EMBEDDING_DIM] = magnitude;
22
+ return v;
23
+ }
24
+ function isolateIndexDir() {
25
+ const dir = mkdtempSync(join(tmpdir(), "mc-vecidx-"));
26
+ process.env.MEGACOMPACT_VECTOR_INDEX_DIR = dir;
27
+ return dir;
28
+ }
29
+ test("cross-repo HNSW nearest-neighbor recall across repos + repoId scoping", async () => {
30
+ delete process.env.MEGACOMPACT_PGLITE_DISABLED;
31
+ const dir = isolateIndexDir();
32
+ try {
33
+ await closeVectorIndex(); // ensure a fresh singleton for this dir
34
+ const pg = await initVectorIndex();
35
+ assert.ok(pg, "index should initialize (PGlite WASM available)");
36
+ // repoA: two checkpoints; repoB: one checkpoint. Distinct spike directions.
37
+ await upsertEmbedding("/repoA/.pi/mega-compact", "sessA", "chkpt_001", spikeVec(0));
38
+ await upsertEmbedding("/repoA/.pi/mega-compact", "sessA", "chkpt_002", spikeVec(5));
39
+ await upsertEmbedding("/repoB/.pi/mega-compact", "sessB", "chkpt_001", spikeVec(0));
40
+ // Cross-repo query near spike(0): nearest are the two spike(0) rows, one per repo.
41
+ const cross = await searchAsync(spikeVec(0), { k: 2 });
42
+ assert.equal(cross.length, 2, "cross-repo returns two nearest");
43
+ const repos = new Set(cross.map((h) => h.repoId));
44
+ assert.ok(repos.has("/repoA/.pi/mega-compact"), "hit from repoA");
45
+ assert.ok(repos.has("/repoB/.pi/mega-compact"), "hit from repoB");
46
+ assert.ok(cross[0].score > 0.99, "top hit is near-identical (cosine ~1)");
47
+ // Scoped to repoA only: excludes repoB even though repoB has an identical vec.
48
+ const scoped = await searchAsync(spikeVec(0), { k: 5, repoId: "/repoA/.pi/mega-compact" });
49
+ assert.ok(scoped.length >= 1, "scoped returns repoA hits");
50
+ assert.ok(scoped.every((h) => h.repoId === "/repoA/.pi/mega-compact"), "repoId filter excludes other repos");
51
+ }
52
+ finally {
53
+ await closeVectorIndex();
54
+ rmSync(dir, { recursive: true, force: true });
55
+ delete process.env.MEGACOMPACT_VECTOR_INDEX_DIR;
56
+ }
57
+ });
58
+ test("dimension guard: non-512 vectors are skipped, never corrupt the index", async () => {
59
+ delete process.env.MEGACOMPACT_PGLITE_DISABLED;
60
+ const dir = isolateIndexDir();
61
+ try {
62
+ await closeVectorIndex();
63
+ await initVectorIndex();
64
+ // Wrong-dimension vector (BYO embedder mismatch) must be silently skipped.
65
+ await upsertEmbedding("/repoC/.pi/mega-compact", "sessC", "chkpt_001", [1, 2, 3]);
66
+ const hits = await searchAsync(spikeVec(0), { k: 5 });
67
+ assert.equal(hits.length, 0, "no rows stored for a mismatched-dim vector");
68
+ // A correct-dim vector still stores fine afterward (index not corrupted).
69
+ await upsertEmbedding("/repoC/.pi/mega-compact", "sessC", "chkpt_002", spikeVec(3));
70
+ const ok = await searchAsync(spikeVec(3), { k: 1 });
71
+ assert.equal(ok.length, 1, "valid vector stored after a skipped one");
72
+ assert.equal(ok[0].checkpointId, "chkpt_002");
73
+ }
74
+ finally {
75
+ await closeVectorIndex();
76
+ rmSync(dir, { recursive: true, force: true });
77
+ delete process.env.MEGACOMPACT_VECTOR_INDEX_DIR;
78
+ }
79
+ });
80
+ test("kill-switch: MEGACOMPACT_PGLITE_DISABLED disables the index gracefully", async () => {
81
+ const dir = isolateIndexDir();
82
+ process.env.MEGACOMPACT_PGLITE_DISABLED = "true";
83
+ try {
84
+ await closeVectorIndex();
85
+ assert.equal(isVectorIndexDisabled(), true, "kill-switch reported disabled");
86
+ const pg = await initVectorIndex();
87
+ assert.equal(pg, undefined, "init returns undefined when disabled");
88
+ // Upsert + search are no-ops that never throw and return empty.
89
+ await upsertEmbedding("/repoD/.pi/mega-compact", "sessD", "chkpt_001", spikeVec(0));
90
+ const hits = await searchAsync(spikeVec(0), { k: 3 });
91
+ assert.deepEqual(hits, [], "search returns [] when disabled");
92
+ }
93
+ finally {
94
+ delete process.env.MEGACOMPACT_PGLITE_DISABLED;
95
+ await closeVectorIndex();
96
+ rmSync(dir, { recursive: true, force: true });
97
+ delete process.env.MEGACOMPACT_VECTOR_INDEX_DIR;
98
+ }
99
+ });
@@ -19,7 +19,8 @@ import { isNearDuplicate } from "./dedup/l1-verify.js";
19
19
  import { mmrRerank } from "./dedup/mmr.js";
20
20
  import { topK } from "./dedup/topk.js";
21
21
  import { openBloom, saveBloom } from "./store/bloom.js";
22
- import { listCheckpoints, nextCheckpointId, upsertCheckpoint, loadSessionState, saveSessionState, upsertMinhashSignature, insertLshBuckets, lshCandidateChunks, setDedupStatus, addTokensSaved, getDedupStats, bumpDedupStats, repoStats as repoStatsFromStore, dataInvariantStats, } from "./store/sqlite.js";
22
+ import { listCheckpoints, nextCheckpointId, upsertCheckpoint, getCheckpoint, loadSessionState, saveSessionState, upsertMinhashSignature, insertLshBuckets, lshCandidateChunks, setDedupStatus, addTokensSaved, getDedupStats, bumpDedupStats, repoStats as repoStatsFromStore, dataInvariantStats, } from "./store/sqlite.js";
23
+ import { initVectorIndex, searchAsync as vectorIndexSearch, } from "./store/vectorIndex.js";
23
24
  import { rehydrateRaptorTree } from "./dedup/raptor/index.js";
24
25
  import { stagedExpansion } from "./dedup/raptor/retrieval.js";
25
26
  import { migrateJsonToSqlite } from "./store/migrate.js";
@@ -39,9 +40,17 @@ export class VectorStore {
39
40
  cfg;
40
41
  /** Optional monitoring target (Sprint 14). Undefined → no monitoring. */
41
42
  eventsPath;
43
+ /**
44
+ * Repo key for the async PGlite vector index (Slice 2). We use the stateDir
45
+ * itself as the repo id — it is already unique per repo and available here
46
+ * without crossing into the pi-runtime layer (src/ stays pi-agnostic). The
47
+ * global index keys on repoId so recall can span repos.
48
+ */
49
+ repoId;
42
50
  constructor(opts = {}) {
43
51
  this.embedder = opts.embedder ?? defaultEmbedder();
44
52
  this.stateDir = opts.stateDir ?? getStateDir();
53
+ this.repoId = opts.repoId ?? this.stateDir;
45
54
  // Sprint 14: all tier flags/thresholds flow from the single config source
46
55
  // (DedupConfig). The legacy opts.dedupSim / opts.l2Enabled remain accepted
47
56
  // for backward-compat callers but flags are authoritative via `cfg`.
@@ -370,6 +379,56 @@ export class VectorStore {
370
379
  const ranked = mmrRerank(mmrItems, k, this.cfg.MMR_LAMBDA);
371
380
  return ranked;
372
381
  }
382
+ /**
383
+ * Slice 2: async cross-repo (or single-repo) recall via the PGlite/HNSW index.
384
+ *
385
+ * This is the ONLY async recall surface and is a BONUS path — the synchronous
386
+ * `search()` above remains the default. `opts.repoId` scopes to one repo; omit
387
+ * it for cross-repo nearest-neighbor recall (the headline capability the sync
388
+ * per-session scan cannot provide).
389
+ *
390
+ * Best-effort: if the index is disabled/empty/failing, we fall back to the
391
+ * synchronous per-session `search()` for THIS repo so callers always get a
392
+ * sensible result. Hydrates each hit's StoredCheckpoint from the authoritative
393
+ * node:sqlite store (the hit's repoId doubles as that repo's stateDir), then
394
+ * MMR-dedupes the merged set.
395
+ */
396
+ async searchAsync(sessionId, query, k = 3, opts = {}) {
397
+ const sid = normalizeSessionId(sessionId);
398
+ const qv = this.embedder.embed(query);
399
+ // repoId filter: explicit opts.repoId wins; else this repo unless crossRepo.
400
+ const repoId = opts.repoId ?? (opts.crossRepo ? undefined : this.repoId);
401
+ let indexHits = [];
402
+ try {
403
+ await initVectorIndex();
404
+ indexHits = await vectorIndexSearch(qv, { k: Math.max(k * 2, k), repoId });
405
+ }
406
+ catch {
407
+ indexHits = [];
408
+ }
409
+ if (indexHits.length === 0) {
410
+ // Index empty/unavailable → synchronous per-session fallback (this repo).
411
+ return this.search(sid, query, k);
412
+ }
413
+ // Hydrate each index hit from the authoritative node:sqlite store. repoId is
414
+ // that repo's stateDir, so cross-repo hits resolve against their own store.
415
+ const hydrated = [];
416
+ for (const h of indexHits) {
417
+ const cp = getCheckpoint(h.sessionId, h.checkpointId, h.repoId);
418
+ if (cp && cp.dedupStatus !== "removed") {
419
+ hydrated.push({ checkpoint: cp, score: h.score });
420
+ }
421
+ }
422
+ if (hydrated.length === 0)
423
+ return this.search(sid, query, k);
424
+ // MMR-dedupe the merged candidate set for diversity (mirrors sync search).
425
+ const mmrItems = hydrated.map((h) => ({
426
+ item: h,
427
+ vector: h.checkpoint.embedding,
428
+ relevance: h.score,
429
+ }));
430
+ return mmrRerank(mmrItems, k, this.cfg.MMR_LAMBDA);
431
+ }
373
432
  /**
374
433
  * Serve the RAPTOR tree for a query (Fix D): rehydrate the persisted tree and
375
434
  * return its staged-expansion leaf hits as SearchHits. Returns [] when no tree
@@ -0,0 +1,129 @@
1
+ /**
2
+ * wordpiece.ts — a self-contained WordPiece tokenizer for BERT/MiniLM.
3
+ *
4
+ * Loads the canonical `vocab.txt` (bert-base-uncased, ~30K tokens) from disk and
5
+ * implements the standard uncased BERT preprocessing + greedy longest-match
6
+ * WordPiece segmentation. No native dependency, no network — the vocab file is a
7
+ * local artifact fetched once by scripts/setup-minilm.mjs (PREVENT-PI-004).
8
+ *
9
+ * This mirrors HuggingFace `BertTokenizer` closely enough for sentence-embedding
10
+ * use: lowercase, strip accents, split on whitespace + punctuation, then
11
+ * WordPiece each token with the `##` continuation convention. Special tokens
12
+ * [CLS]/[SEP] are added by the caller's encode().
13
+ */
14
+ import { readFileSync, existsSync } from "node:fs";
15
+ const UNK = "[UNK]";
16
+ const CLS = "[CLS]";
17
+ const SEP = "[SEP]";
18
+ const PAD = "[PAD]";
19
+ const MAX_INPUT_CHARS_PER_WORD = 200;
20
+ export class WordPieceTokenizer {
21
+ vocab;
22
+ clsId;
23
+ sepId;
24
+ padId;
25
+ unkId;
26
+ constructor(vocab) {
27
+ this.vocab = vocab;
28
+ this.clsId = vocab.get(CLS) ?? 101;
29
+ this.sepId = vocab.get(SEP) ?? 102;
30
+ this.padId = vocab.get(PAD) ?? 0;
31
+ this.unkId = vocab.get(UNK) ?? 100;
32
+ }
33
+ /** Build a tokenizer from a vocab.txt file (one token per line, index = line). */
34
+ static fromVocabFile(path) {
35
+ if (!existsSync(path)) {
36
+ throw new Error(`WordPiece vocab not found at ${path}. Run: node scripts/setup-minilm.mjs`);
37
+ }
38
+ const lines = readFileSync(path, "utf-8").split("\n");
39
+ const vocab = new Map();
40
+ for (let i = 0; i < lines.length; i++) {
41
+ const tok = lines[i].replace(/\r$/, "");
42
+ if (tok.length > 0 || i < lines.length - 1)
43
+ vocab.set(tok, i);
44
+ }
45
+ return new WordPieceTokenizer(vocab);
46
+ }
47
+ /** Uncased BERT basic tokenization: lowercase, strip accents, split on ws+punct. */
48
+ basicTokenize(text) {
49
+ // NFD + strip combining marks (accent removal), then lowercase.
50
+ const cleaned = text
51
+ .normalize("NFD")
52
+ .replace(/[̀-ͯ]/g, "")
53
+ .toLowerCase();
54
+ const tokens = [];
55
+ let buf = "";
56
+ const flush = () => {
57
+ if (buf.length > 0) {
58
+ tokens.push(buf);
59
+ buf = "";
60
+ }
61
+ };
62
+ for (const ch of cleaned) {
63
+ if (/\s/.test(ch)) {
64
+ flush();
65
+ }
66
+ else if (/[!-/:-@[-`{-~¡-¿]/.test(ch)) {
67
+ // Punctuation becomes its own token.
68
+ flush();
69
+ tokens.push(ch);
70
+ }
71
+ else {
72
+ buf += ch;
73
+ }
74
+ }
75
+ flush();
76
+ return tokens;
77
+ }
78
+ /** Greedy longest-match WordPiece for a single word. */
79
+ wordpiece(word) {
80
+ if (word.length > MAX_INPUT_CHARS_PER_WORD)
81
+ return [UNK];
82
+ const pieces = [];
83
+ let start = 0;
84
+ while (start < word.length) {
85
+ let end = word.length;
86
+ let cur = null;
87
+ while (start < end) {
88
+ let sub = word.slice(start, end);
89
+ if (start > 0)
90
+ sub = "##" + sub;
91
+ if (this.vocab.has(sub)) {
92
+ cur = sub;
93
+ break;
94
+ }
95
+ end--;
96
+ }
97
+ if (cur === null)
98
+ return [UNK]; // any unmatchable piece → whole word is UNK
99
+ pieces.push(cur);
100
+ start = end;
101
+ }
102
+ return pieces;
103
+ }
104
+ /** Tokenize text into WordPiece token strings (no special tokens). */
105
+ tokenize(text) {
106
+ const out = [];
107
+ for (const word of this.basicTokenize(text)) {
108
+ for (const piece of this.wordpiece(word))
109
+ out.push(piece);
110
+ }
111
+ return out;
112
+ }
113
+ /**
114
+ * Encode text into model inputs with [CLS]…[SEP], truncated to `maxLen`.
115
+ * attention_mask is all 1s (no padding for single-sequence inference).
116
+ */
117
+ encode(text, maxLen = 256) {
118
+ const pieces = this.tokenize(text).slice(0, Math.max(0, maxLen - 2));
119
+ const inputIds = [this.clsId];
120
+ for (const p of pieces)
121
+ inputIds.push(this.vocab.get(p) ?? this.unkId);
122
+ inputIds.push(this.sepId);
123
+ return {
124
+ inputIds,
125
+ attentionMask: inputIds.map(() => 1),
126
+ tokenTypeIds: inputIds.map(() => 0),
127
+ };
128
+ }
129
+ }
@@ -22,6 +22,7 @@ import {
22
22
  import { resolveRepoRoot, preserveRecentForPressure, type MegaConfig } from "./mega-config.js";
23
23
  import { runRaptor } from "../src/dedup/raptor/index.js";
24
24
  import { loadDedupConfig } from "../src/config/dedup.js";
25
+ import { upsertEmbedding as indexUpsertEmbedding } from "../src/store/vectorIndex.js";
25
26
 
26
27
  export type RunCompactResult =
27
28
  | { skipped: true }
@@ -164,6 +165,29 @@ export function runCompact(
164
165
  }
165
166
  }
166
167
 
168
+ // Slice 2: best-effort mirror of the new checkpoint into the async global
169
+ // PGlite/HNSW vector index. Fires once per compaction (not per-add), so the
170
+ // shared global dir is never hammered by concurrent test workers.
171
+ // Non-fatal: a WASM init failure degrades to the sync scan silently.
172
+ if (!result.deduped) {
173
+ try {
174
+ const all = runtime.store.list(sid);
175
+ const latest = all.find((cp) => cp.checkpointId === result.checkpointId);
176
+ if (latest?.embedding) {
177
+ void indexUpsertEmbedding(
178
+ runtime.currentStateDir,
179
+ sid,
180
+ latest.checkpointId,
181
+ latest.embedding,
182
+ ).catch(() => {
183
+ /* non-fatal: index refresh never blocks a compaction */
184
+ });
185
+ }
186
+ } catch {
187
+ /* non-fatal: index refresh never blocks a compaction */
188
+ }
189
+ }
190
+
167
191
  runtime.setStatus(
168
192
  ctx,
169
193
  runtime.rt.persistedThisSession
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-mega-compact",
3
- "version": "0.4.24",
3
+ "version": "0.4.26",
4
4
  "description": "Layered, local, vector-backed context compressor for pi — supersede/collapse/cluster compaction with deduped inline recall.",
5
5
  "type": "module",
6
6
  "license": "BSD-2-Clause",
@@ -57,6 +57,8 @@
57
57
  "typescript": "^5.4.0"
58
58
  },
59
59
  "dependencies": {
60
+ "@electric-sql/pglite": "^0.5.4",
61
+ "@electric-sql/pglite-pgvector": "^0.0.5",
60
62
  "@mongodb-js/zstd": "^7.0.0"
61
63
  }
62
64
  }
package/src/recall.ts CHANGED
@@ -137,3 +137,66 @@ export function recallAndInline(
137
137
  empty: toInject.length === 0,
138
138
  };
139
139
  }
140
+
141
+ /**
142
+ * Slice 2 async cross-repo recall. Same dedup/bound/inline contract as
143
+ * `recallAndInline`, but backed by `VectorStore.searchAsync` so it can recall
144
+ * across repos (HNSW NN over the global PGlite index) when `opts.crossRepo` is
145
+ * set. The synchronous `recallAndInline` is unchanged and remains the default
146
+ * per-session path. Inline-window dedupe + token cap (Fix C) apply here too.
147
+ *
148
+ * `store` must provide `searchAsync` (the live VectorStore does). Errors fall
149
+ * back to an empty result — recall is a bonus, never a hard dependency.
150
+ */
151
+ export async function recallAndInlineAsync(
152
+ opts: RecallInjectOptions & { crossRepo?: boolean; repoId?: string },
153
+ store: Pick<VectorStore, "searchAsync" | "wasInjected" | "markInjected">,
154
+ ): Promise<RecallInjectResult> {
155
+ const limit = opts.limit ?? 3;
156
+ const skip = opts.skipInjected ?? true;
157
+ const maxTokens = opts.recallMaxTokens ?? 0;
158
+ const doWindowDedupe = opts.windowDedupe ?? false;
159
+ const dedupSim = opts.dedupSim ?? 0.9;
160
+
161
+ let hits: SearchHit[] = [];
162
+ try {
163
+ hits = await store.searchAsync(opts.sessionId, opts.query, limit, {
164
+ crossRepo: opts.crossRepo,
165
+ repoId: opts.repoId,
166
+ });
167
+ } catch {
168
+ hits = [];
169
+ }
170
+
171
+ let liveEmbeddings: number[][] = [];
172
+ if (doWindowDedupe && opts.liveWindow && opts.liveWindow.length > 0) {
173
+ const embedder = defaultEmbedder();
174
+ liveEmbeddings = opts.liveWindow.map((m) => embedder.embed(m));
175
+ }
176
+
177
+ const toInject: SearchHit[] = [];
178
+ const parts: string[] = [];
179
+ let blockTokens = 0;
180
+
181
+ for (const h of hits) {
182
+ if (skip && store.wasInjected(opts.sessionId, h.checkpoint.checkpointId)) continue;
183
+ if (doWindowDedupe && liveEmbeddings.length > 0) {
184
+ const hitVec = defaultEmbedder().embed(h.checkpoint.summary);
185
+ if (liveEmbeddings.some((v) => cosineSimilarity(v, hitVec) >= dedupSim)) continue;
186
+ }
187
+ const part = formatRecallBlock([h]);
188
+ const partTokens = estimateBlockTokens(part);
189
+ if (maxTokens > 0 && blockTokens + partTokens > maxTokens) break;
190
+ parts.push(part);
191
+ toInject.push(h);
192
+ blockTokens += partTokens;
193
+ store.markInjected(opts.sessionId, h.checkpoint.checkpointId);
194
+ }
195
+
196
+ const block = parts.join("\n");
197
+ const report = toInject.map(
198
+ (h) => ` • ${h.checkpoint.checkpointId} (${h.checkpoint.summary.slice(0, 60).replace(/\n/g, " ")}…)`,
199
+ );
200
+
201
+ return { toInject, report, block, empty: toInject.length === 0 };
202
+ }