-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathstore-postgres.ts
More file actions
2241 lines (2078 loc) · 114 KB
/
Copy pathstore-postgres.ts
File metadata and controls
2241 lines (2078 loc) · 114 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* PostgresStore — Production Store backed by PostgreSQL + pgvector
*
* ARCHITECTURE:
* • All projects share ONE PostgreSQL database.
* • Multi-tenancy: every table includes a `project_hash` column (first 16 hex chars
* of SHA-256(projectPath)). All queries filter by project_hash.
* • Vector search: pgvector `vector(768)` column + IVFFlat cosine index.
* • Full-text search: PostgreSQL tsvector/GIN index (replaces SQLite FTS5).
* • Hybrid search: BM25 (ts_rank) + cosine similarity, same formula as SqliteStore.
* • Hash chain: same SHA-256 chain logic, enforced by serialized INSERT via
* advisory locks (prevents concurrent writers racing on prev_hash).
* • RBAC: same token format (zcst.payload.hmac), same HMAC verification.
* Signing key stored in project_meta per project_hash.
*
* SECURITY:
* • All queries parameterized — no SQL injection possible.
* • project_hash is always derived server-side from projectPath — callers
* cannot supply an arbitrary hash to access another project's data.
* • Advisory lock (pg_advisory_xact_lock) serializes broadcast INSERTs per
* project to ensure hash chain integrity under concurrent writes.
* • Scrypt KDF for channel key (same as SqliteStore, same parameters).
* • Token HMAC verification is timing-safe (timingSafeEqual).
* • Row-level isolation: all queries include WHERE project_hash = $n.
*
* PERFORMANCE:
* • pg.Pool with configurable pool size (default 10 connections).
* • IVFFlat index on embeddings for O(√n) approximate cosine search.
* • GIN index on tsvector for O(log n) full-text search.
* • Complexity profile cached in project_meta (10-minute TTL, same as SqliteStore).
*/
import pg from "pg";
import { createHash, createHmac, randomBytes, randomUUID, scryptSync, timingSafeEqual } from "node:crypto";
import { Config } from "./config.js";
import { computeRowHash } from "./chain.js";
import { getEmbedding, cosineSimilarity, ACTIVE_MODEL } from "./embedder.js";
import { classifyFactKind, type EpistemicOpts } from "./memory.js";
import { computeSalience, salienceEnabled } from "./salience.js";
import { budgetFacts, effectiveImportance } from "./recall_budget.js";
import { extractCoReferences, classifyRelation } from "./indexing/community.js";
import { SIM_HIGH, MAX_SCAN_FACTS, detectConflict, autoResolveVictim } from "./contradiction_heuristics.js";
import { llmExtractEntities, entityEdgesFor, ENTITY_EXTRACT_ENABLED, ENTITY_BUDGET } from "./indexing/entity_extract.js";
import { detectCommunitiesFromRows } from "./indexing/community.js";
import { summarizeCommunity, answerGlobal, type CommunitySummaryRow } from "./indexing/community_summaries.js";
import { ROLE_PERMISSIONS, type AgentRole } from "./access-control.js";
import type {
Store,
MemoryStats,
MemoryLimits,
KbStats,
SearchOptions,
ExplainResult,
BroadcastOptions,
RecallOptions,
ChainStatus,
TokenPayload,
FetchStats,
} from "./store.js";
import type {
MemoryFact,
BroadcastType,
BroadcastMessage,
BroadcastResult,
KnowledgeEntry,
CrossProjectEntry,
RetentionTier,
ComplexityProfile,
} from "./store.js";
const { Pool } = pg;
// ─────────────────────────────────────────────────────────────────────────────
// Internal helpers
// ─────────────────────────────────────────────────────────────────────────────
function ph(projectPath: string): string {
return createHash("sha256").update(projectPath).digest("hex").slice(0, 16);
}
function todayUtc(): string {
return new Date().toISOString().slice(0, 10);
}
function sanitize(s: string, max: number): string {
return String(s).replace(/[\r\n\x00\x01-\x08\x0b\x0c\x0e-\x1f]/g, " ").trim().slice(0, max);
}
// Scrypt helpers (identical parameters to SqliteStore / memory.ts)
const SCRYPT_PREFIX = "scrypt:v1";
function hashChannelKeyScrypt(key: string): string {
const { SCRYPT_N, SCRYPT_R, SCRYPT_P, SCRYPT_KEYLEN, SCRYPT_SALT_BYTES, SCRYPT_MAXMEM } = Config;
const saltBuf = randomBytes(SCRYPT_SALT_BYTES);
const hashBuf = scryptSync(key, saltBuf, SCRYPT_KEYLEN, { N: SCRYPT_N, r: SCRYPT_R, p: SCRYPT_P, maxmem: SCRYPT_MAXMEM });
return `${SCRYPT_PREFIX}:${SCRYPT_N}:${SCRYPT_R}:${SCRYPT_P}:${saltBuf.toString("hex")}:${hashBuf.toString("hex")}`;
}
function verifyScryptHash(key: string, stored: string): boolean {
try {
if (!stored.startsWith(`${SCRYPT_PREFIX}:`)) return false;
const parts = stored.split(":");
if (parts.length !== 7) return false;
const N = parseInt(parts[2]!, 10);
const r = parseInt(parts[3]!, 10);
const p = parseInt(parts[4]!, 10);
const saltHex = parts[5]!;
const hashHex = parts[6]!;
if (isNaN(N) || isNaN(r) || isNaN(p) || N < 1024 || r < 1 || p < 1) return false;
const saltBuf = Buffer.from(saltHex, "hex");
const storedBuf = Buffer.from(hashHex, "hex");
const derivedBuf = scryptSync(key, saltBuf, storedBuf.length, {
N, r, p, maxmem: Config.SCRYPT_MAXMEM,
});
return timingSafeEqual(derivedBuf, storedBuf);
} catch {
return false;
}
}
// Token helpers (identical algorithm to access-control.ts)
function getOrCreateSigningKey(pool: pg.Pool, projectHash: string): Promise<string> {
return pool.query<{ value: string }>(
"SELECT value FROM project_meta WHERE project_hash = $1 AND key = 'zc_token_signing_key'",
[projectHash]
).then(async (res) => {
if (res.rows.length > 0) return res.rows[0]!.value;
const newKey = randomBytes(32).toString("hex");
await pool.query(
"INSERT INTO project_meta(project_hash, key, value) VALUES ($1, 'zc_token_signing_key', $2) ON CONFLICT DO NOTHING",
[projectHash, newKey]
);
// Re-read in case of race
const res2 = await pool.query<{ value: string }>(
"SELECT value FROM project_meta WHERE project_hash = $1 AND key = 'zc_token_signing_key'",
[projectHash]
);
return res2.rows[0]!.value;
});
}
function hmacSign(payload: string, key: string): string {
return createHmac("sha256", key).update(payload).digest("hex");
}
// ─────────────────────────────────────────────────────────────────────────────
// PostgresStore
// ─────────────────────────────────────────────────────────────────────────────
export class PostgresStore implements Store {
private pool: pg.Pool;
constructor(connectionString: string) {
this.pool = new Pool({
connectionString,
max: parseInt(process.env["ZC_PG_POOL_SIZE"] ?? "10", 10),
idleTimeoutMillis: 30_000,
connectionTimeoutMillis: 5_000,
// Statement timeout: 30s — prevents runaway queries
options: "--statement_timeout=30000",
});
}
/**
* Run on first use. Verifies the connection and applies all schema migrations.
* Idempotent — safe to call multiple times.
*/
async init(): Promise<void> {
const client = await this.pool.connect();
try {
// Verify pgvector is available
await client.query("CREATE EXTENSION IF NOT EXISTS vector");
// Apply all schema DDL (idempotent — uses IF NOT EXISTS / DO NOTHING)
await client.query(PG_SCHEMA_DDL);
} finally {
client.release();
}
}
// ── Working Memory ────────────────────────────────────────────────────────
async remember(projectPath: string, key: string, value: string, importance: number, agentId: string, epi: EpistemicOpts = {}): Promise<void> {
const projectHash = ph(projectPath);
const safeKey = sanitize(key, 100);
const safeValue = sanitize(value, 500);
const safeImp = Math.max(1, Math.min(5, Math.round(importance)));
const safeAgent = sanitize(agentId, 64);
const now = new Date().toISOString();
// v0.31.0 epistemology — explicit kind wins, else auto-classify (parity with rememberFact).
const KINDS = ["fact", "decision", "hypothesis", "prediction"];
const RES = ["open", "resolved_correct", "resolved_incorrect", "resolved_partial"];
const safeKind = epi.kind && KINDS.includes(epi.kind) ? epi.kind : classifyFactKind(safeValue);
const safeConf = (typeof epi.confidence === "number" && isFinite(epi.confidence)) ? Math.max(0, Math.min(1, epi.confidence)) : null;
const safeRes = epi.resolution && RES.includes(epi.resolution) ? epi.resolution : null;
const resolvedAt = (safeRes && safeRes !== "open") ? now : null;
// R1 — optional TTL: validate ISO, must be in the future; invalid values dropped.
const safeExpires: string | null = (() => {
if (!epi.expiresAt) return null;
const t = Date.parse(String(epi.expiresAt));
return Number.isFinite(t) && t > Date.now() ? new Date(t).toISOString() : null;
})();
await this.pool.query(`
INSERT INTO working_memory(project_hash, key, value, importance, agent_id, created_at, kind, confidence, resolution_status, resolved_at, origin, expires_at)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12)
ON CONFLICT(project_hash, key, agent_id) DO UPDATE SET
value = EXCLUDED.value,
importance = EXCLUDED.importance,
created_at = EXCLUDED.created_at,
kind = EXCLUDED.kind,
confidence = EXCLUDED.confidence,
resolution_status = EXCLUDED.resolution_status,
resolved_at = EXCLUDED.resolved_at,
origin = EXCLUDED.origin,
expires_at = EXCLUDED.expires_at,
valid_to = NULL,
superseded_by = NULL,
retired_reason = NULL
`, [projectHash, safeKey, safeValue, safeImp, safeAgent, now, safeKind, safeConf, safeRes, resolvedAt, epi.origin ? sanitize(epi.origin, 120) : "zc_remember", safeExpires]);
// (valid_to reset: re-asserting a RETIRED key REVIVES it — the agent explicitly said it again.)
// v0.36.0 — memory facts are now co-reference sources, so a memory WRITE must refresh
// the backlink graph too (previously only indexing did — memory edges would go stale).
// Debounced 5s + fire-and-forget: a burst of remembers still costs one rebuild.
this._scheduleBacklinkRebuild(projectPath);
// M1 (v0.41.0) — embed the LIVE fact (fire-and-forget, content-hash deduped) so
// focused recall can rank it by relevance. Same memory:<agent>:<key> source the
// eviction archive uses.
void this._storeEmbedding(projectHash, safeValue, `memory:${safeAgent}:${safeKey}`);
// Evict if over the dynamic limit
const limits = await this.getWorkingMemoryLimits(projectPath);
const countRes = await this.pool.query<{ n: string }>(
"SELECT COUNT(*) as n FROM working_memory WHERE project_hash = $1 AND agent_id = $2 AND valid_to IS NULL",
[projectHash, safeAgent]
);
const count = parseInt(countRes.rows[0]!.n, 10);
if (count > limits.max) {
const toEvictCount = count - limits.evictTo;
// v0.31.0: protect explicitly-tracked OPEN predictions/hypotheses + high-confidence decisions
// (additive — plain facts match neither clause and evict exactly as before).
const PROTECT = `NOT (
(kind IN ('prediction','hypothesis') AND resolution_status = 'open')
OR (kind = 'decision' AND confidence IS NOT NULL AND confidence >= 0.8)
)`;
const victims = (await this.pool.query<{ key: string; value: string }>(
`SELECT key, value FROM working_memory
WHERE project_hash = $1 AND agent_id = $2 AND valid_to IS NULL AND ${PROTECT}
ORDER BY importance ASC, created_at ASC
LIMIT $3`,
[projectHash, safeAgent, toEvictCount]
)).rows;
// Safety valve: if protected facts leave us short, fall back to unfiltered eviction
// for the remainder so the hard `max` bound always holds.
if (victims.length < toEvictCount) {
const have = new Set(victims.map((v) => v.key));
const extra = (await this.pool.query<{ key: string; value: string }>(
`SELECT key, value FROM working_memory
WHERE project_hash = $1 AND agent_id = $2 AND valid_to IS NULL
ORDER BY importance ASC, created_at ASC
LIMIT $3`,
[projectHash, safeAgent, toEvictCount]
)).rows;
for (const r of extra) { if (victims.length >= toEvictCount) break; if (!have.has(r.key)) { victims.push(r); have.add(r.key); } }
}
for (const row of victims) {
await this.pool.query(
"DELETE FROM working_memory WHERE project_hash = $1 AND key = $2 AND agent_id = $3",
[projectHash, row.key, safeAgent]
);
// Archive evicted fact to KB
await this.index(projectPath, row.value, `memory:${safeAgent}:${row.key}`);
}
}
}
// ── v0.37.0 Temporal fact retirement ───────────────────────────────────────
async retireFact(projectPath: string, key: string, agentId: string, supersededBy: string | null, reason: string): Promise<boolean> {
return this._retireFactByHash(ph(projectPath), key, agentId, supersededBy, reason);
}
private async _retireFactByHash(projectHash: string, key: string, agentId: string, supersededBy: string | null, reason: string): Promise<boolean> {
const safeKey = sanitize(key, 100);
const safeAgent = sanitize(agentId, 64);
const row = (await this.pool.query<{ value: string }>(
"SELECT value FROM working_memory WHERE project_hash = $1 AND key = $2 AND agent_id = $3 AND valid_to IS NULL",
[projectHash, safeKey, safeAgent])).rows[0];
if (!row) return false;
await this.pool.query(
"UPDATE working_memory SET valid_to = NOW(), superseded_by = $4, retired_reason = $5 WHERE project_hash = $1 AND key = $2 AND agent_id = $3",
[projectHash, safeKey, safeAgent, supersededBy ? sanitize(supersededBy, 100) : null, sanitize(reason, 100)]);
// Archive to the KB by hash (mirrors index()'s upserts — retire is non-destructive:
// the value stays findable via zc_search and revivable via reviveFact).
const source = `memory:${safeAgent}:${safeKey}`;
const now = new Date().toISOString();
try {
await this.pool.query(`
INSERT INTO knowledge_entries(project_hash, source, content, created_at)
VALUES ($1, $2, $3, $4)
ON CONFLICT(project_hash, source) DO UPDATE SET content = EXCLUDED.content, created_at = EXCLUDED.created_at
`, [projectHash, source, row.value, now]);
await this.pool.query(`
INSERT INTO source_meta(project_hash, source, source_type, retention_tier, created_at, l0_summary, l1_summary)
VALUES ($1, $2, 'internal', 'internal', $3, $4, $5)
ON CONFLICT(project_hash, source) DO UPDATE SET created_at = EXCLUDED.created_at, l0_summary = EXCLUDED.l0_summary, l1_summary = EXCLUDED.l1_summary
`, [projectHash, source, now, row.value.slice(0, Config.TIER_L0_CHARS).trim(), row.value.slice(0, Config.TIER_L1_CHARS).trim()]);
} catch { /* archival is best-effort — retirement itself already succeeded */ }
void this._rebuildBacklinksByHash(projectHash).catch(() => undefined);
return true;
}
async reviveFact(projectPath: string, key: string, agentId: string): Promise<boolean> {
return this._reviveFactByHash(ph(projectPath), key, agentId);
}
private async _reviveFactByHash(projectHash: string, key: string, agentId: string): Promise<boolean> {
const r = await this.pool.query(
"UPDATE working_memory SET valid_to = NULL, superseded_by = NULL, retired_reason = NULL WHERE project_hash = $1 AND key = $2 AND agent_id = $3 AND valid_to IS NOT NULL",
[projectHash, sanitize(key, 100), sanitize(agentId, 64)]);
if ((r.rowCount ?? 0) > 0) { void this._rebuildBacklinksByHash(projectHash).catch(() => undefined); return true; }
return false;
}
async forget(projectPath: string, key: string, agentId: string): Promise<boolean> {
const projectHash = ph(projectPath);
const safeKey = sanitize(key, 100);
const safeAgent = sanitize(agentId, 64);
// v0.38.0 — SOFT DELETE with a recovery window: forget RETIRES the fact (out of recall
// immediately, KB-archived, revivable for RETIRE_PURGE_DAYS) instead of hard-deleting.
void projectHash;
return this.retireFact(projectPath, safeKey, safeAgent, null, "forgotten");
}
async recall(
projectPath: string,
agentId: string,
opts: { focus?: string; from?: Date; to?: Date; asOf?: Date } = {},
): Promise<MemoryFact[]> {
const projectHash = ph(projectPath);
const safeAgent = sanitize(agentId, 64);
// M3 (v0.41.0) — AS-OF time travel: reconstruct what was true at a past moment.
// Includes facts retired SINCE then (they were live at asOf) and excludes facts
// created after — the transaction timeline (created_at/valid_to) makes this a
// pure predicate change, no history table needed. (Applied in the branch SQL below.)
// v0.22.2 — per-agent namespacing with shared pool. Each agent gets its
// own private notebook (agent_id = ZC_AGENT_ID = "developer", "orchestrator",
// etc.) AND always sees the project-wide "default" pool (cross-agent
// coordination: ownership tracking, last_session_summary, project state).
//
// Why: previously every fact was written under "default" and recall
// returned all 101+ facts for any agent on any task — massive token
// overhead for "tiny work." Per-agent gives each agent ONLY their own
// private decisions + the shared coordination layer.
//
// When agentId="default" explicitly: return only the shared pool
// (avoids redundant self-join).
let rows: MemoryFact[];
const COLS = `key, value, importance, agent_id, created_at, kind, confidence, resolution_status, resolved_at, access_count, last_retrieved_at, origin, valid_at`;
if (safeAgent === "default") {
// R1 — expired facts are excluded from live recall (the sweep formally retires them).
const live = opts.asOf ? `created_at <= $2 AND (valid_to IS NULL OR valid_to > $2)` : `valid_to IS NULL AND (expires_at IS NULL OR expires_at > NOW())`;
const params: unknown[] = opts.asOf ? [projectHash, opts.asOf] : [projectHash];
const res = await this.pool.query<MemoryFact>(
`SELECT ${COLS}
FROM working_memory WHERE project_hash = $1 AND agent_id = 'default' AND ${live}
ORDER BY importance DESC, created_at DESC`,
params
);
rows = res.rows;
} else {
// For per-agent agentId: UNION (their private notebook) + (shared 'default' pool)
const live = opts.asOf ? `created_at <= $3 AND (valid_to IS NULL OR valid_to > $3)` : `valid_to IS NULL AND (expires_at IS NULL OR expires_at > NOW())`;
const params: unknown[] = opts.asOf ? [projectHash, safeAgent, opts.asOf] : [projectHash, safeAgent];
const res = await this.pool.query<MemoryFact>(
`SELECT ${COLS}
FROM working_memory
WHERE project_hash = $1 AND (agent_id = $2 OR agent_id = 'default') AND ${live}
ORDER BY
CASE WHEN agent_id = $2 THEN 0 ELSE 1 END,
importance DESC,
created_at DESC`,
params
);
rows = res.rows;
}
// Tier-2 #4: secondary salience re-sort (importance stays primary) + best-effort
// access bump (single batched UPDATE via unnest, fire-and-forget). Inert when
// W_SALIENCE=0 — byte-identical ordering, no writes (the kill-switch).
// R8 (v0.43.0): sort key is EFFECTIVE importance (staleness-demoted, see
// recall_budget.ts; inert when ZC_RECALL_STALE_DEMOTE=0) and the bump covers
// only the facts that will RENDER under the recall budget — bumping every row
// reset last_retrieved_at project-wide each recall, making "stale" undetectable.
const demoteStale = Config.RECALL_STALE_DEMOTE > 0;
if ((salienceEnabled() || demoteStale) && rows.length > 0) {
const now = Date.now();
const k = (r: MemoryFact) => `${r.key} ${r.agent_id ?? ""}`;
const sal = salienceEnabled()
? new Map(rows.map((r) => [k(r), computeSalience(r.access_count, r.last_retrieved_at ?? null, now)]))
: null;
const prio = (r: MemoryFact) => (safeAgent !== "default" && r.agent_id === safeAgent ? 0 : 1);
const eff = (r: MemoryFact) => (demoteStale ? effectiveImportance(r, now) : r.importance);
rows = [...rows].sort((a, b) =>
prio(a) - prio(b) ||
eff(b) - eff(a) ||
(sal ? (sal.get(k(b)) ?? 0) - (sal.get(k(a)) ?? 0) : 0) ||
(a.created_at < b.created_at ? 1 : a.created_at > b.created_at ? -1 : 0)
);
if (salienceEnabled()) {
const toBump = budgetFacts(rows).rendered;
void this.pool.query(
`UPDATE working_memory AS w
SET access_count = COALESCE(w.access_count,0) + 1, last_retrieved_at = NOW()
FROM unnest($2::text[], $3::text[]) AS t(key, agent_id)
WHERE w.project_hash = $1 AND w.key = t.key AND w.agent_id = t.agent_id`,
[projectHash, toBump.map((r) => r.key), toBump.map((r) => r.agent_id ?? safeAgent)]
).catch(() => undefined);
}
}
// M1 (v0.41.0) — FOCUSED recall: with a focus string, re-rank live facts by
// blended relevance to the agent's CURRENT task (the M0 benchmark showed
// task-relevant facts ranking 74-79/81 under importance-only ordering).
// score = RECALL_W_REL·cosine + RECALL_W_IMP·(importance/5) + RECALL_W_SAL·salience
// Missing vectors ⇒ rel=0 (importance still ranks them — graceful until the
// backfill lands). Ollama down ⇒ unfocused order unchanged. No focus ⇒ byte-identical.
if (opts.focus && opts.focus.trim() && rows.length > 0) {
try {
const qEmbed = await getEmbedding(opts.focus.slice(0, 2000));
if (qEmbed) {
const sources = rows.map((r) => `memory:${r.agent_id ?? safeAgent}:${r.key}`);
const embRes = await this.pool.query<{ source: string; vector: string }>(
`SELECT source, vector::text FROM embeddings
WHERE project_hash = $1 AND model_name = $2 AND source = ANY($3)`,
[projectHash, ACTIVE_MODEL, sources]
);
const vecMap = new Map(embRes.rows.map((r) => [r.source, r.vector]));
const now = Date.now();
const scoreOf = (r: MemoryFact): number => {
const vs = vecMap.get(`memory:${r.agent_id ?? safeAgent}:${r.key}`);
let rel = 0;
if (vs) {
const nums = vs.slice(1, -1).split(",").map(Number);
rel = Math.max(0, cosineSimilarity(new Float32Array(nums), qEmbed.vector));
}
const sal = computeSalience(r.access_count, r.last_retrieved_at ?? null, now);
let score = Config.RECALL_W_REL * rel + Config.RECALL_W_IMP * (r.importance / 5) + Config.RECALL_W_SAL * sal;
// M3 — temporal window bonus: event-time (valid_at, else created_at)
// inside the parsed window ranks the fact above topic-only matches.
if (opts.from || opts.to) {
const evRaw = (r as MemoryFact & { valid_at?: string | Date | null }).valid_at ?? r.created_at;
const ev = evRaw instanceof Date ? evRaw.getTime() : Date.parse(String(evRaw));
const inWindow =
Number.isFinite(ev) &&
(!opts.from || ev >= opts.from.getTime()) &&
(!opts.to || ev <= opts.to.getTime());
// R3 — measured verdict: on the labeled corpus BOTH a hard relevance
// gate and a proportional bonus scored WORSE than the flat bonus
// (gold/noise relevance ranges overlap). Flat is the default;
// ZC_RECALL_TEMPORAL_REL_GATE>0 re-enables gating for corpora
// where the ranges separate.
if (inWindow) {
score += Config.RECALL_TEMPORAL_REL_GATE > 0
? (rel >= Config.RECALL_TEMPORAL_REL_GATE ? Config.RECALL_W_TEMPORAL : 0)
: Config.RECALL_W_TEMPORAL;
}
}
return score;
};
const scores = new Map(rows.map((r) => [r, scoreOf(r)]));
rows = [...rows].sort((a, b) =>
(scores.get(b)! - scores.get(a)!) ||
(b.importance - a.importance) ||
(a.created_at < b.created_at ? 1 : a.created_at > b.created_at ? -1 : 0)
);
}
} catch { /* focus ranking is best-effort — fall back to unfocused order */ }
}
return rows;
}
async archiveSummary(projectPath: string, summary: string): Promise<void> {
const safe = sanitize(summary, 2000);
const now = new Date().toISOString();
const source = `[SESSION_SUMMARY] ${now.slice(0, 10)}`;
await this.index(projectPath, safe, source, "internal", "summary");
await this.remember(projectPath, "last_session_summary", safe, 5, "default");
}
async getMemoryStats(projectPath: string, agentId: string): Promise<MemoryStats> {
const projectHash = ph(projectPath);
const safeAgent = sanitize(agentId, 64);
const [countRes, critRes] = await Promise.all([
this.pool.query<{ n: string }>(
"SELECT COUNT(*) as n FROM working_memory WHERE project_hash = $1 AND agent_id = $2 AND valid_to IS NULL",
[projectHash, safeAgent]
),
this.pool.query<{ n: string }>(
"SELECT COUNT(*) as n FROM working_memory WHERE project_hash = $1 AND agent_id = $2 AND importance >= 4 AND valid_to IS NULL",
[projectHash, safeAgent]
),
]);
const limits = await this.getWorkingMemoryLimits(projectPath);
return {
count: parseInt(countRes.rows[0]!.n, 10),
max: limits.max,
evictTo: limits.evictTo,
criticalCount: parseInt(critRes.rows[0]!.n, 10),
complexity: limits.profile,
};
}
async countImportance5(projectPath: string, agentId: string): Promise<number> {
const res = await this.pool.query<{ n: string }>(
"SELECT COUNT(*) as n FROM working_memory WHERE project_hash = $1 AND agent_id = $2 AND importance = 5 AND valid_to IS NULL",
[ph(projectPath), sanitize(agentId, 64)]
);
return parseInt(res.rows[0]!.n, 10);
}
async getWorkingMemoryLimits(projectPath: string, forceRecompute = false): Promise<MemoryLimits> {
const projectHash = ph(projectPath);
const WM_CACHE_TTL = 10 * 60 * 1000;
if (!forceRecompute) {
const res = await this.pool.query<{ value: string }>(
"SELECT value FROM project_meta WHERE project_hash = $1 AND key = 'zc_complexity_profile'",
[projectHash]
);
if (res.rows.length > 0) {
try {
const cached = JSON.parse(res.rows[0]!.value) as ComplexityProfile;
const ageMs = Date.now() - new Date(cached.computedAt).getTime();
if (ageMs < WM_CACHE_TTL) {
return { max: cached.computedLimit, evictTo: cached.evictTo, profile: cached };
}
} catch {}
}
}
// Compute fresh
const [kbRes, bcRes, agRes] = await Promise.all([
this.pool.query<{ n: string }>(
"SELECT COUNT(*) as n FROM source_meta WHERE project_hash = $1", [projectHash]
),
this.pool.query<{ n: string }>(
"SELECT COUNT(*) as n FROM broadcasts WHERE project_hash = $1", [projectHash]
),
this.pool.query<{ n: string }>(
"SELECT COUNT(*) as n FROM agent_sessions WHERE project_hash = $1 AND revoked = 0 AND expires_at > $2",
[projectHash, new Date().toISOString()]
),
]);
const kbEntries = parseInt(kbRes.rows[0]!.n, 10);
const broadcastCount = parseInt(bcRes.rows[0]!.n, 10);
const activeAgents = parseInt(agRes.rows[0]!.n, 10);
const kbBonus = Math.min(Math.floor(kbEntries / 15), 60);
const bcBonus = Math.min(Math.floor(broadcastCount / 30), 40);
const agentBonus = Math.min(activeAgents * 15, 50);
const computedLimit = Math.max(100, Math.min(250, 100 + kbBonus + bcBonus + agentBonus));
const evictTo = Math.floor(computedLimit * 0.80);
const computedAt = new Date().toISOString();
const profile: ComplexityProfile = {
kbEntries, broadcastCount, activeAgents,
computedLimit, evictTo, computedAt,
};
await this.pool.query(`
INSERT INTO project_meta(project_hash, key, value) VALUES ($1, 'zc_complexity_profile', $2)
ON CONFLICT(project_hash, key) DO UPDATE SET value = EXCLUDED.value
`, [projectHash, JSON.stringify(profile)]);
return { max: computedLimit, evictTo, profile };
}
// ── Knowledge Base ─────────────────────────────────────────────────────────
async index(
projectPath: string,
content: string,
source: string,
sourceType: "internal" | "external" = "internal",
retentionTier: RetentionTier = sourceType === "external" ? "external" : "internal"
): Promise<void> {
const projectHash = ph(projectPath);
const now = new Date().toISOString();
const safeSource = sanitize(source, 500);
const safeContent = sanitize(content, 50_000);
// L0/L1 summary tiers (same logic as knowledge.ts)
const l0 = safeContent.slice(0, Config.TIER_L0_CHARS).trim();
const l1 = safeContent.slice(0, Config.TIER_L1_CHARS).trim();
// Upsert knowledge entry
await this.pool.query(`
INSERT INTO knowledge_entries(project_hash, source, content, created_at)
VALUES ($1, $2, $3, $4)
ON CONFLICT(project_hash, source) DO UPDATE SET
content = EXCLUDED.content,
created_at = EXCLUDED.created_at
`, [projectHash, safeSource, safeContent, now]);
// Upsert source_meta
await this.pool.query(`
INSERT INTO source_meta(project_hash, source, source_type, retention_tier, created_at, l0_summary, l1_summary)
VALUES ($1, $2, $3, $4, $5, $6, $7)
ON CONFLICT(project_hash, source) DO UPDATE SET
source_type = EXCLUDED.source_type,
retention_tier = EXCLUDED.retention_tier,
created_at = EXCLUDED.created_at,
l0_summary = EXCLUDED.l0_summary,
l1_summary = EXCLUDED.l1_summary
`, [projectHash, safeSource, sourceType, retentionTier, now, l0, l1]);
// Fire-and-forget embedding computation
void this._storeEmbedding(projectHash, safeContent, safeSource);
// Tier-1 A: schedule a debounced backlink-graph rebuild over PG (fire-and-forget).
// THIS is what makes the backlink boost actually fire in the live PG deployment —
// PostgresStore.index does not route through indexContent's SQLite trigger.
this._scheduleBacklinkRebuild(projectPath);
}
private async _storeEmbedding(projectHash: string, content: string, source: string): Promise<void> {
try {
// v0.39.0 — content-addressable dedup (SQLite parity): identical content + same model
// ⇒ skip the Ollama call; hash-match with a DIFFERENT model ⇒ explicit re-embed.
const contentHash = createHash("sha256").update(content).digest("hex");
try {
const existing = (await this.pool.query<{ content_hash: string | null; model_name: string }>(
`SELECT content_hash, model_name FROM embeddings WHERE project_hash = $1 AND source = $2`,
[projectHash, source])).rows[0];
if (existing && existing.content_hash === contentHash && existing.model_name === ACTIVE_MODEL) return;
} catch { /* content_hash column absent (pre-migration) — fall through */ }
const result = await getEmbedding(content);
if (!result) return;
// pgvector expects "[x1,x2,...,xN]" string format
const vectorStr = "[" + result.vector.join(",") + "]";
await this.pool.query(`
INSERT INTO embeddings(project_hash, source, vector, model_name, dimensions, created_at, content_hash)
VALUES ($1, $2, $3::vector, $4, $5, $6, $7)
ON CONFLICT(project_hash, source) DO UPDATE SET
vector = EXCLUDED.vector,
model_name = EXCLUDED.model_name,
dimensions = EXCLUDED.dimensions,
created_at = EXCLUDED.created_at,
content_hash = EXCLUDED.content_hash
`, [projectHash, source, vectorStr, result.modelName, result.dimensions, new Date().toISOString(), contentHash]);
} catch {
// Embedding failure is non-fatal — falls back to BM25-only search
}
}
/**
* v0.39.0 — SAFE EMBEDDING-MODEL MIGRATION: budgeted re-embed of rows whose vectors were
* produced by a DIFFERENT model than the active one (they're invisible to search via the
* ACTIVE_MODEL filter — silently stale). Run by the enrichment cron until the backlog drains.
*/
async reembedStaleModels(budget: number = 40): Promise<{ reembedded: number; remaining: number; ollamaDown: boolean }> {
const stale = (await this.pool.query<{ project_hash: string; source: string }>(
`SELECT e.project_hash, e.source FROM embeddings e
WHERE e.model_name <> $1 LIMIT $2`, [ACTIVE_MODEL, budget])).rows;
const remainingRes = await this.pool.query<{ n: string }>(
`SELECT COUNT(*)::text AS n FROM embeddings WHERE model_name <> $1`, [ACTIVE_MODEL]);
let reembedded = 0;
for (const s of stale) {
const row = (await this.pool.query<{ content: string }>(
`SELECT content FROM knowledge_entries WHERE project_hash = $1 AND source = $2`,
[s.project_hash, s.source])).rows[0];
if (!row) {
// Source no longer exists — the stale vector is an orphan; drop it.
await this.pool.query(`DELETE FROM embeddings WHERE project_hash = $1 AND source = $2`, [s.project_hash, s.source]);
continue;
}
const emb = await getEmbedding(row.content);
if (!emb) return { reembedded, remaining: Number(remainingRes.rows[0]!.n) - reembedded, ollamaDown: true };
const vectorStr = "[" + emb.vector.join(",") + "]";
const contentHash = createHash("sha256").update(row.content).digest("hex");
await this.pool.query(`
UPDATE embeddings SET vector = $3::vector, model_name = $4, dimensions = $5, created_at = $6, content_hash = $7
WHERE project_hash = $1 AND source = $2`,
[s.project_hash, s.source, vectorStr, emb.modelName, emb.dimensions, new Date().toISOString(), contentHash]);
reembedded++;
}
return { reembedded, remaining: Math.max(0, Number(remainingRes.rows[0]!.n) - reembedded), ollamaDown: false };
}
async search(projectPath: string, queries: string[], opts: SearchOptions = {}): Promise<KnowledgeEntry[]> {
const projectHash = ph(projectPath);
const limit = opts.limit ?? Config.MAX_RESULTS;
const candidates = Config.BM25_CANDIDATES;
// Merge all query terms into one tsvector query
const rawQueryText = queries.join(" ");
// R4 (v0.42.0) — NL temporal window in KB search: "docs indexed last week about X"
// constrains candidates by created_at; the cleaned text (time phrase removed)
// does the matching so keyword/vector relevance concentrates on the topic.
const { parseTemporalQuery: parseTQ } = await import("./temporal_parse.js");
const tw = parseTQ(rawQueryText);
const queryText = (tw.from || tw.to) && tw.cleaned.trim() ? tw.cleaned : rawQueryText;
// BM25 candidates via ts_rank (PostgreSQL full-text)
type CandRow = { source: string; content: string; rank: number; source_type: string; synthetic?: boolean; created_at?: string | Date };
const bm25Res = await this.pool.query<CandRow>(`
SELECT ke.source, ke.content, ke.created_at,
ts_rank(to_tsvector('english', ke.content), plainto_tsquery('english', $2)) AS rank,
COALESCE(sm.source_type, 'internal') as source_type
FROM knowledge_entries ke
LEFT JOIN source_meta sm ON sm.project_hash = ke.project_hash AND sm.source = ke.source
WHERE ke.project_hash = $1
AND to_tsvector('english', ke.content) @@ plainto_tsquery('english', $2)
ORDER BY rank DESC
LIMIT $3
`, [projectHash, queryText, candidates]);
// M1 (v0.41.0) — candidate-pool fix. plainto_tsquery is implicit-AND: one word the
// target doc lacks ("what is the retry SCHEDULE…") returned ZERO results and the
// vector index was never consulted (the M0 benchmark's day-one finding). Two new
// channels fill the pool; ZC_BM25_OR_FALLBACK=0 / ZC_VECTOR_CANDIDATES=0 restore
// the legacy BM25-gated behaviour exactly.
const candMap = new Map<string, CandRow>(bm25Res.rows.map((r) => [r.source, r]));
// (a) OR-fallback keyword pass — any-term matches join when the AND pass under-fills.
if (Config.BM25_OR_FALLBACK && candMap.size < candidates) {
const terms = [...new Set(queryText.toLowerCase().split(/[^a-z0-9]+/).filter((w) => w.length >= 3))].slice(0, 12);
if (terms.length >= 2) {
try {
const orRes = await this.pool.query<CandRow>(`
SELECT ke.source, ke.content, ke.created_at,
ts_rank(to_tsvector('english', ke.content), to_tsquery('english', $2)) AS rank,
COALESCE(sm.source_type, 'internal') as source_type
FROM knowledge_entries ke
LEFT JOIN source_meta sm ON sm.project_hash = ke.project_hash AND sm.source = ke.source
WHERE ke.project_hash = $1
AND to_tsvector('english', ke.content) @@ to_tsquery('english', $2)
ORDER BY rank DESC
LIMIT $3
`, [projectHash, terms.join(" | "), candidates]);
for (const r of orRes.rows) if (!candMap.has(r.source)) candMap.set(r.source, r);
} catch { /* malformed tsquery — AND results only */ }
}
}
// (b) Independent vector candidates — nearest stored vectors join the pool even with
// zero keyword overlap (synthetic: they score via the cosine/graph channels only).
let qEmbedEarly: Awaited<ReturnType<typeof getEmbedding>> = null;
if (Config.VECTOR_CANDIDATES > 0) {
try {
qEmbedEarly = await getEmbedding(queryText);
if (qEmbedEarly) {
const qVecStr = "[" + qEmbedEarly.vector.join(",") + "]";
const vecRes = await this.pool.query<CandRow>(`
SELECT ke.source, ke.content, ke.created_at, 0 AS rank,
COALESCE(sm.source_type, 'internal') as source_type
FROM embeddings e
JOIN knowledge_entries ke ON ke.project_hash = e.project_hash AND ke.source = e.source
LEFT JOIN source_meta sm ON sm.project_hash = ke.project_hash AND sm.source = ke.source
WHERE e.project_hash = $1 AND e.model_name = $2
AND (e.vector <=> $3::vector) <= $5
ORDER BY e.vector <=> $3::vector
LIMIT $4
`, [projectHash, ACTIVE_MODEL, qVecStr, Config.VECTOR_CANDIDATES, 1 - Config.VECTOR_MIN_SIM]);
for (const r of vecRes.rows) if (!candMap.has(r.source)) candMap.set(r.source, { ...r, synthetic: true });
}
} catch { /* pgvector unavailable — keyword candidates only */ }
}
if (candMap.size === 0) return [];
let candRows = [...candMap.values()];
// R4 — apply the temporal window to candidates (created_at range).
if (tw.from || tw.to) {
candRows = candRows.filter((r) => {
const t = r.created_at instanceof Date ? r.created_at.getTime() : Date.parse(String(r.created_at ?? ""));
return Number.isFinite(t) &&
(!tw.from || t >= tw.from.getTime()) &&
(!tw.to || t <= tw.to.getTime());
});
if (candRows.length === 0) return [];
}
// Tier-1 A: backlink in-degree boost (PG mirror). ONE batched lookup, shared by the
// vector path AND the BM25 fallback. Empty when W_BACKLINK=0 / no rows / pre-migration
// ⇒ blBoost()=0 ⇒ ranking byte-identical to pre-backlink behaviour.
const blMap = new Map<string, number>();
if (Config.W_BACKLINK > 0) {
try {
const blRes = await this.pool.query<{ source: string; weighted_in: number }>(
`SELECT source, weighted_in FROM kb_backlinks_pg WHERE project_hash = $1 AND source = ANY($2)`,
[projectHash, candRows.map(r => r.source)]
);
for (const r of blRes.rows) blMap.set(r.source, r.weighted_in);
} catch { /* kb_backlinks_pg absent (pre-migration) — leave map empty */ }
}
const blBoost = (src: string): number => {
const wIn = blMap.get(src) ?? 0;
return wIn > 0 ? Config.W_BACKLINK * (Math.log(1 + wIn) / Math.log(1 + Config.BACKLINK_LOG_BASE)) : 0;
};
// Try vector reranking
let results: KnowledgeEntry[] = [];
try {
const qEmbed = qEmbedEarly ?? await getEmbedding(queryText);
if (qEmbed) {
const qVec = "[" + qEmbed.vector.join(",") + "]";
const sources = candRows.map(r => r.source);
// Get stored embeddings for ALL candidates (keyword + OR-fallback + vector-injected)
const embRes = await this.pool.query<{ source: string; vector: string }>(
`SELECT source, vector::text FROM embeddings
WHERE project_hash = $1 AND source = ANY($2) AND model_name = $3`,
[projectHash, sources, ACTIVE_MODEL]
);
const embMap = new Map(embRes.rows.map(r => [r.source, r.vector]));
const maxBm25 = Math.max(...candRows.map(r => r.rank), 1);
// Compute cosine for every candidate up front (needed by both fusion modes).
const withCos = candRows.map(row => {
let cosScore = 0;
const storedVecStr = embMap.get(row.source);
if (storedVecStr) {
// Parse pgvector "[x1,x2,...,xN]" string back to Float32Array
const nums = storedVecStr.slice(1, -1).split(",").map(Number);
cosScore = cosineSimilarity(new Float32Array(nums), qEmbed.vector);
}
return { row, cosScore };
});
// Tier-2 #3: RRF fuses per-list RANK positions (scale-free); weighted fuses
// normalized scores + additive backlink boost (byte-identical to v0.31.0).
const useRRF = Config.RETRIEVAL_FUSION === "rrf";
// BM25 rank list: keyword-evidence candidates ONLY (synthetic vector-injected
// rows have no keyword signal — they score via the cosine/graph channels).
const bm25RankMap = new Map(candRows.filter(r => !r.synthetic)
.sort((a, b) => b.rank - a.rank).map((r, i) => [r.source, i + 1]));
let cosRankMap: Map<string, number> | null = null;
let blRankMap: Map<string, number> | null = null;
let graphRankMap: Map<string, number> | null = null;
if (useRRF) {
cosRankMap = new Map([...withCos].sort((a, b) => b.cosScore - a.cosScore).map((x, i) => [x.row.source, i + 1]));
if (Config.W_BACKLINK > 0 && blMap.size > 0) {
blRankMap = new Map(candRows.map(r => ({ s: r.source, w: blMap.get(r.source) ?? 0 }))
.filter(x => x.w > 0).sort((a, b) => b.w - a.w).map((x, i) => [x.s, i + 1]));
}
// v0.37.0 — 4th list: graph neighbor expansion (SQLite parity). 1-hop kb_edges_pg
// neighbors of the top candidates, ranked by aggregate weight; out-of-set neighbors
// (KB sources + live memory facts) are pulled into the candidate pool.
if (Config.RRF_W_GRAPH > 0) {
try {
const topSeeds = candRows.slice(0, Config.GRAPH_EXPAND_TOP_K).map(r => r.source);
if (topSeeds.length > 0) {
// M4 (v0.41.0) — bounded multi-hop BFS (was 1-hop). A doc chain
// A→B→C where only A matches the query now surfaces C at depth 2,
// with per-hop weight decay so nearer neighbors dominate.
const seeds = new Set(topSeeds);
const nScore = new Map<string, number>();
let frontier = topSeeds;
const visited = new Set(topSeeds);
for (let depth = 1; depth <= Math.max(1, Config.GRAPH_MAX_DEPTH) && frontier.length > 0; depth++) {
const decay = Math.pow(Config.GRAPH_HOP_DECAY, depth - 1);
const eRows = (await this.pool.query<{ a: string; b: string; weight: number }>(
`SELECT from_source AS a, to_source AS b, weight FROM kb_edges_pg
WHERE project_hash = $1 AND (from_source = ANY($2) OR to_source = ANY($2))`,
[projectHash, frontier])).rows;
const frontierSet = new Set(frontier);
const next: string[] = [];
for (const e of eRows) {
const nb = frontierSet.has(e.a) ? e.b : (frontierSet.has(e.b) ? e.a : null);
if (!nb || seeds.has(nb)) continue;
nScore.set(nb, (nScore.get(nb) ?? 0) + (e.weight ?? 1) * decay);
if (!visited.has(nb)) { visited.add(nb); next.push(nb); }
}
frontier = next;
}
const rankedN = [...nScore.entries()].sort((x, y) => y[1] - x[1]).slice(0, Config.GRAPH_EXPAND_MAX);
if (rankedN.length > 0) {
graphRankMap = new Map(rankedN.map(([s], i) => [s, i + 1]));
const inSet = new Set(candRows.map(r => r.source));
const missing = rankedN.map(([s]) => s).filter(s => !inSet.has(s));
const kbMissing = missing.filter(s => !s.startsWith("memory:"));
const memMissing = missing.filter(s => s.startsWith("memory:"));
if (kbMissing.length > 0) {
const rows2 = (await this.pool.query<{ source: string; content: string }>(
`SELECT source, content FROM knowledge_entries WHERE project_hash = $1 AND source = ANY($2)`,
[projectHash, kbMissing])).rows;
for (const r of rows2) withCos.push({ row: { source: r.source, content: r.content, rank: 0, source_type: "internal" }, cosScore: 0 });
}
for (const s of memMissing) {
const parts = s.split(":");
if (parts.length < 3) continue;
const wm = (await this.pool.query<{ value: string }>(
`SELECT value FROM working_memory WHERE project_hash = $1 AND agent_id = $2 AND key = $3 AND valid_to IS NULL`,
[projectHash, parts[1], parts.slice(2).join(":")])).rows[0];
if (wm) withCos.push({ row: { source: s, content: wm.value, rank: 0, source_type: "internal" }, cosScore: 0 });
}
}
}
} catch { /* kb_edges_pg absent — no graph channel */ }
}
}
const scored = withCos.map(({ row, cosScore }) => {
let hybrid: number;
if (useRRF) {
const K = Config.RRF_K;
const br = bm25RankMap.get(row.source);
const cr = cosRankMap?.get(row.source);
const blr = blRankMap?.get(row.source);
const gr = graphRankMap?.get(row.source);
hybrid =
(br ? Config.RRF_W_BM25 / (K + br) : 0) +
(cr ? Config.RRF_W_VEC / (K + cr) : 0) +
(blr ? Config.RRF_W_BACKLINK / (K + blr) : 0) +
(gr ? Config.RRF_W_GRAPH / (K + gr) : 0);
} else {
hybrid = Config.W_BM25 * (row.rank / maxBm25) + Config.W_COSINE * cosScore + blBoost(row.source);
}
return { ...row, vectorScore: cosScore, hybridScore: hybrid };
});
scored.sort((a, b) => b.hybridScore - a.hybridScore);
results = scored.slice(0, limit).map(r => ({
source: r.source,
content: r.content,
snippet: r.content.slice(0, 200),
rank: r.hybridScore,
vectorScore: r.vectorScore,
backlinkScore: blBoost(r.source) || undefined,
sourceType: r.source_type,
nonAsciiSource: /[^\x00-\x7F]/.test(r.source),
}));
}
} catch {
// Vector reranking failed — fall back to BM25 only
}
if (results.length === 0) {
// BM25-only fallback (Ollama down). Tier-1 A: same backlink boost. W_BACKLINK=0
// ⇒ boost=0 ⇒ re-sort the already-rank-sorted rows by raw ts_rank ⇒ byte-identical.
const kwRows = candRows.filter(r => !r.synthetic);
const maxBm25Fb = Math.max(...kwRows.map(r => r.rank), 1);
const fb = kwRows.map(r => {
const boost = blBoost(r.source);
const rank = Config.W_BACKLINK > 0 ? (r.rank / maxBm25Fb) + boost : r.rank;
return { r, rank, boost };
});
fb.sort((a, b) => b.rank - a.rank);
results = fb.slice(0, limit).map(({ r, rank, boost }) => ({
source: r.source,
content: r.content,
snippet: r.content.slice(0, 200),
rank,
backlinkScore: boost || undefined,
sourceType: r.source_type,
nonAsciiSource: /[^\x00-\x7F]/.test(r.source),
}));
}
// Apply depth filtering (L0/L1/L2)
if (opts.depth && opts.depth !== "L2") {
const smRes = await this.pool.query<{ source: string; l0_summary: string; l1_summary: string }>(
"SELECT source, l0_summary, l1_summary FROM source_meta WHERE project_hash = $1 AND source = ANY($2)",
[projectHash, results.map(r => r.source)]
);
const smMap = new Map(smRes.rows.map(r => [r.source, r]));
results = results.map(r => {
const sm = smMap.get(r.source);
if (!sm) return r;
const content = opts.depth === "L0"
? (sm.l0_summary || r.content.slice(0, Config.TIER_L0_CHARS))
: (sm.l1_summary || r.content.slice(0, Config.TIER_L1_CHARS));
return { ...r, content, snippet: content.slice(0, 200) };
});
}
return results;
}
async searchGlobal(queries: string[], limit = 10): Promise<CrossProjectEntry[]> {
const queryText = queries.join(" ");
const res = await this.pool.query<{
source: string; content: string; rank: number;
source_type: string; project_hash: string; project_label: string;
}>(`
SELECT ke.source, ke.content,
ts_rank(to_tsvector('english', ke.content), plainto_tsquery('english', $1))
+ (CASE WHEN $3 > 0 AND bl.weighted_in IS NOT NULL