pi-mega-compact 0.4.23 → 0.4.25

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,243 @@
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
+
19
+ import { homedir } from "node:os";
20
+ import { join } from "node:path";
21
+ import { mkdirSync } from "node:fs";
22
+
23
+ // PGlite + pgvector are script-free WASM (no native build) → survive pi's
24
+ // install-script block. Imported lazily so a missing/broken package degrades
25
+ // gracefully instead of crashing module load.
26
+ import { PGlite, type PGlite as PGliteInstance } from "@electric-sql/pglite";
27
+ import { vector } from "@electric-sql/pglite-pgvector";
28
+
29
+ /** Vector dimension produced by the default TrigramEmbedder (src/embedder.ts). */
30
+ export const EMBEDDING_DIM = 512;
31
+
32
+ /** A single recall hit returned by the async index. */
33
+ export interface VectorIndexHit {
34
+ repoId: string;
35
+ sessionId: string;
36
+ checkpointId: string;
37
+ /** Cosine similarity in [0,1] (1 = identical). */
38
+ score: number;
39
+ }
40
+
41
+ let db: PGliteInstance | undefined;
42
+ let initPromise: Promise<PGliteInstance | undefined> | undefined;
43
+ let disabled = false;
44
+ let warned = false;
45
+
46
+ function indexDir(): string {
47
+ const override = process.env.MEGACOMPACT_VECTOR_INDEX_DIR;
48
+ if (override && override.trim() !== "") return override;
49
+ try {
50
+ return join(homedir(), ".pi", "mega-compact-vector");
51
+ } catch {
52
+ return join("/tmp", ".mega-compact-vector");
53
+ }
54
+ }
55
+
56
+ function logWarn(msg: string): void {
57
+ // Never throw — degradation is the whole point. One warning per process.
58
+ if (warned) return;
59
+ warned = true;
60
+ try {
61
+ console.warn(`[mega-compact:vectorIndex] ${msg} (falling back to sync scan)`);
62
+ } catch {
63
+ /* ignore */
64
+ }
65
+ }
66
+
67
+ /** Honor the emergency kill-switch. When set, the index is fully disabled. */
68
+ export function isVectorIndexDisabled(): boolean {
69
+ return (
70
+ disabled ||
71
+ process.env.MEGACOMPACT_PGLITE_DISABLED === "true" ||
72
+ process.env.MEGACOMPACT_PGLITE_DISABLED === "1"
73
+ );
74
+ }
75
+
76
+ /**
77
+ * Lazily open + schema-init the global PGlite DB. Idempotent and safe to call
78
+ * from many places. Returns undefined when disabled/unavailable so callers can
79
+ * fall back to the synchronous scan. Never throws.
80
+ */
81
+ export function initVectorIndex(): Promise<PGliteInstance | undefined> {
82
+ if (isVectorIndexDisabled()) return Promise.resolve(undefined);
83
+ if (db) return Promise.resolve(db);
84
+ if (initPromise) return initPromise;
85
+ initPromise = (async (): Promise<PGliteInstance | undefined> => {
86
+ try {
87
+ const dir = indexDir();
88
+ mkdirSync(dir, { recursive: true });
89
+ const pg = await new PGlite({
90
+ dataDir: dir,
91
+ extensions: { vector },
92
+ });
93
+ await pg.exec("CREATE EXTENSION IF NOT EXISTS vector;");
94
+ await pg.exec(`
95
+ CREATE TABLE IF NOT EXISTS vector_index (
96
+ repo_id TEXT NOT NULL,
97
+ session_id TEXT NOT NULL,
98
+ checkpoint_id TEXT NOT NULL,
99
+ embedding vector(${EMBEDDING_DIM}) NOT NULL,
100
+ PRIMARY KEY (repo_id, session_id, checkpoint_id)
101
+ );
102
+ `);
103
+ // HNSW index over cosine distance for fast NN. Created idempotently.
104
+ await pg.exec(
105
+ "CREATE INDEX IF NOT EXISTS vector_index_hnsw ON vector_index USING hnsw (embedding vector_cosine_ops);",
106
+ );
107
+ db = pg;
108
+ return pg;
109
+ } catch (err) {
110
+ disabled = true;
111
+ logWarn(`init failed: ${err instanceof Error ? err.message : String(err)}`);
112
+ return undefined;
113
+ }
114
+ })();
115
+ return initPromise;
116
+ }
117
+
118
+ function toVectorLiteral(v: number[]): string {
119
+ // pgvector text form: [a,b,c]. Guard against NaN/Inf for a clean literal.
120
+ const parts = v.map((x) => (Number.isFinite(x) ? x : 0));
121
+ return `[${parts.join(",")}]`;
122
+ }
123
+
124
+ /**
125
+ * Best-effort upsert of one checkpoint embedding into the global index.
126
+ * Dimension-mismatched vectors (e.g. a BYO embedder with dim ≠ 512) are skipped
127
+ * rather than corrupting the index. Fire-and-forget: resolved promise only;
128
+ * callers must NOT await this on the sync path. Never throws.
129
+ */
130
+ export async function upsertEmbedding(
131
+ repoId: string,
132
+ sessionId: string,
133
+ checkpointId: string,
134
+ embedding: number[],
135
+ ): Promise<void> {
136
+ if (isVectorIndexDisabled()) return;
137
+ if (!embedding || embedding.length !== EMBEDDING_DIM) {
138
+ // Dimension guard: skip without corrupting the fixed-dim index.
139
+ return;
140
+ }
141
+ try {
142
+ const pg = await initVectorIndex();
143
+ if (!pg) return;
144
+ const lit = toVectorLiteral(embedding);
145
+ await pg.query(
146
+ `INSERT INTO vector_index (repo_id, session_id, checkpoint_id, embedding)
147
+ VALUES ($1, $2, $3, $4::vector)
148
+ ON CONFLICT (repo_id, session_id, checkpoint_id)
149
+ DO UPDATE SET embedding = EXCLUDED.embedding;`,
150
+ [repoId, sessionId, checkpointId, lit],
151
+ );
152
+ } catch (err) {
153
+ disabled = true;
154
+ logWarn(`upsert failed: ${err instanceof Error ? err.message : String(err)}`);
155
+ }
156
+ }
157
+
158
+ export interface SearchAsyncOpts {
159
+ /** When provided, scope the NN search to a single repo; omit for cross-repo. */
160
+ repoId?: string;
161
+ /** Max hits (default 3). */
162
+ k?: number;
163
+ }
164
+
165
+ /**
166
+ * Cross-repo (or single-repo) HNSW nearest-neighbor search. Returns hits sorted
167
+ * by descending similarity. Never throws — on any failure returns [].
168
+ */
169
+ export async function searchAsync(
170
+ query: number[],
171
+ opts: SearchAsyncOpts = {},
172
+ ): Promise<VectorIndexHit[]> {
173
+ if (isVectorIndexDisabled() || !query || query.length !== EMBEDDING_DIM) return [];
174
+ const k = opts.k ?? 3;
175
+ const repoId = opts.repoId;
176
+ try {
177
+ const pg = await initVectorIndex();
178
+ if (!pg) return [];
179
+ const lit = toVectorLiteral(query);
180
+ const params: unknown[] = [lit, k];
181
+ let sql =
182
+ "SELECT repo_id, session_id, checkpoint_id, 1 - (embedding <=> $1::vector) AS score " +
183
+ "FROM vector_index";
184
+ if (repoId) {
185
+ sql += " WHERE repo_id = $3";
186
+ params.push(repoId);
187
+ }
188
+ sql += " ORDER BY embedding <=> $1::vector LIMIT $2";
189
+ const res = await pg.query(sql, params);
190
+ return res.rows.map((r: any) => ({
191
+ repoId: r.repo_id as string,
192
+ sessionId: r.session_id as string,
193
+ checkpointId: r.checkpoint_id as string,
194
+ score: r.score as number,
195
+ }));
196
+ } catch (err) {
197
+ disabled = true;
198
+ logWarn(`search failed: ${err instanceof Error ? err.message : String(err)}`);
199
+ return [];
200
+ }
201
+ }
202
+
203
+ /** Close the index (test teardown / shutdown). Safe to call when unopened. */
204
+ export async function closeVectorIndex(): Promise<void> {
205
+ if (db) {
206
+ try {
207
+ await db.close();
208
+ } catch {
209
+ /* ignore */
210
+ }
211
+ }
212
+ db = undefined;
213
+ initPromise = undefined;
214
+ }
215
+
216
+ /**
217
+ * Rebuild the entire index from the authoritative node:sqlite store. Used for
218
+ * backfill + DR. `enumerateRepoStateDirs` yields each repo's state dir; we read
219
+ * its checkpoint embeddings and bulk upsert. Best-effort: counts successes and
220
+ * skips failures. Returns {upserted, errors}.
221
+ */
222
+ export async function rebuildFromSqlite(
223
+ enumerateRepoStateDirs: () => Iterable<{ repoId: string; stateDir: string }>,
224
+ readCheckpoints: (
225
+ stateDir: string,
226
+ ) => Iterable<{ sessionId: string; checkpointId: string; embedding: number[] }>,
227
+ ): Promise<{ upserted: number; errors: number }> {
228
+ let upserted = 0;
229
+ let errors = 0;
230
+ const pg = await initVectorIndex();
231
+ if (!pg) return { upserted, errors: 1 };
232
+ for (const repo of enumerateRepoStateDirs()) {
233
+ for (const cp of readCheckpoints(repo.stateDir)) {
234
+ try {
235
+ await upsertEmbedding(repo.repoId, cp.sessionId, cp.checkpointId, cp.embedding);
236
+ upserted++;
237
+ } catch {
238
+ errors++;
239
+ }
240
+ }
241
+ }
242
+ return { upserted, errors };
243
+ }
@@ -26,6 +26,7 @@ import {
26
26
  listCheckpoints,
27
27
  nextCheckpointId,
28
28
  upsertCheckpoint,
29
+ getCheckpoint,
29
30
  loadSessionState,
30
31
  saveSessionState,
31
32
  upsertMinhashSignature,
@@ -38,6 +39,12 @@ import {
38
39
  repoStats as repoStatsFromStore,
39
40
  dataInvariantStats,
40
41
  } from "./store/sqlite.js";
42
+ import {
43
+ upsertEmbedding as indexUpsertEmbedding,
44
+ initVectorIndex,
45
+ searchAsync as vectorIndexSearch,
46
+ type VectorIndexHit,
47
+ } from "./store/vectorIndex.js";
41
48
  import { rehydrateRaptorTree } from "./dedup/raptor/index.js";
42
49
  import { stagedExpansion } from "./dedup/raptor/retrieval.js";
43
50
  import { migrateJsonToSqlite } from "./store/migrate.js";
@@ -98,6 +105,13 @@ export class VectorStore {
98
105
  private readonly cfg: DedupConfigShape;
99
106
  /** Optional monitoring target (Sprint 14). Undefined → no monitoring. */
100
107
  private readonly eventsPath?: string;
108
+ /**
109
+ * Repo key for the async PGlite vector index (Slice 2). We use the stateDir
110
+ * itself as the repo id — it is already unique per repo and available here
111
+ * without crossing into the pi-runtime layer (src/ stays pi-agnostic). The
112
+ * global index keys on repoId so recall can span repos.
113
+ */
114
+ private readonly repoId: string;
101
115
 
102
116
  constructor(
103
117
  opts: {
@@ -110,10 +124,13 @@ export class VectorStore {
110
124
  config?: DedupConfigShape;
111
125
  /** Optional events.log path for decision monitoring (Sprint 14). */
112
126
  eventsPath?: string;
127
+ /** Repo id for the async cross-repo vector index. Defaults to stateDir. */
128
+ repoId?: string;
113
129
  } = {},
114
130
  ) {
115
131
  this.embedder = opts.embedder ?? defaultEmbedder();
116
132
  this.stateDir = opts.stateDir ?? getStateDir();
133
+ this.repoId = opts.repoId ?? this.stateDir;
117
134
  // Sprint 14: all tier flags/thresholds flow from the single config source
118
135
  // (DedupConfig). The legacy opts.dedupSim / opts.l2Enabled remain accepted
119
136
  // for backward-compat callers but flags are authoritative via `cfg`.
@@ -371,6 +388,12 @@ export class VectorStore {
371
388
  // Cumulative store-wide dedup accounting (attempt, not collapsed).
372
389
  bumpDedupStats(false, this.stateDir);
373
390
  onTier?.({ tier: "new", status: "stored" });
391
+ // Slice 2: best-effort, fire-and-forget mirror of this new checkpoint into
392
+ // the async global PGlite/HNSW index. NEVER awaited — must not block or
393
+ // throw into the synchronous add() path. On failure the index degrades to
394
+ // the sync scan (handled inside vectorIndex). The node:sqlite store remains
395
+ // authoritative; the index is rebuildable from it at any time.
396
+ void indexUpsertEmbedding(this.repoId, sessionId, checkpointId, checkpoint.embedding);
374
397
  return { checkpoint, deduped: false };
375
398
  }
376
399
 
@@ -472,6 +495,60 @@ export class VectorStore {
472
495
  return ranked;
473
496
  }
474
497
 
498
+ /**
499
+ * Slice 2: async cross-repo (or single-repo) recall via the PGlite/HNSW index.
500
+ *
501
+ * This is the ONLY async recall surface and is a BONUS path — the synchronous
502
+ * `search()` above remains the default. `opts.repoId` scopes to one repo; omit
503
+ * it for cross-repo nearest-neighbor recall (the headline capability the sync
504
+ * per-session scan cannot provide).
505
+ *
506
+ * Best-effort: if the index is disabled/empty/failing, we fall back to the
507
+ * synchronous per-session `search()` for THIS repo so callers always get a
508
+ * sensible result. Hydrates each hit's StoredCheckpoint from the authoritative
509
+ * node:sqlite store (the hit's repoId doubles as that repo's stateDir), then
510
+ * MMR-dedupes the merged set.
511
+ */
512
+ async searchAsync(
513
+ sessionId: string,
514
+ query: string,
515
+ k = 3,
516
+ opts: { repoId?: string; crossRepo?: boolean } = {},
517
+ ): Promise<SearchHit[]> {
518
+ const sid = normalizeSessionId(sessionId);
519
+ const qv = this.embedder.embed(query);
520
+ // repoId filter: explicit opts.repoId wins; else this repo unless crossRepo.
521
+ const repoId = opts.repoId ?? (opts.crossRepo ? undefined : this.repoId);
522
+ let indexHits: VectorIndexHit[] = [];
523
+ try {
524
+ await initVectorIndex();
525
+ indexHits = await vectorIndexSearch(qv, { k: Math.max(k * 2, k), repoId });
526
+ } catch {
527
+ indexHits = [];
528
+ }
529
+ if (indexHits.length === 0) {
530
+ // Index empty/unavailable → synchronous per-session fallback (this repo).
531
+ return this.search(sid, query, k);
532
+ }
533
+ // Hydrate each index hit from the authoritative node:sqlite store. repoId is
534
+ // that repo's stateDir, so cross-repo hits resolve against their own store.
535
+ const hydrated: SearchHit[] = [];
536
+ for (const h of indexHits) {
537
+ const cp = getCheckpoint(h.sessionId, h.checkpointId, h.repoId);
538
+ if (cp && cp.dedupStatus !== "removed") {
539
+ hydrated.push({ checkpoint: cp, score: h.score });
540
+ }
541
+ }
542
+ if (hydrated.length === 0) return this.search(sid, query, k);
543
+ // MMR-dedupe the merged candidate set for diversity (mirrors sync search).
544
+ const mmrItems: MmrItem<SearchHit>[] = hydrated.map((h) => ({
545
+ item: h,
546
+ vector: h.checkpoint.embedding,
547
+ relevance: h.score,
548
+ }));
549
+ return mmrRerank(mmrItems, k, this.cfg.MMR_LAMBDA);
550
+ }
551
+
475
552
  /**
476
553
  * Serve the RAPTOR tree for a query (Fix D): rehydrate the persisted tree and
477
554
  * return its staged-expansion leaf hits as SearchHits. Returns [] when no tree