@myrialabs/clopen 0.4.26 → 0.4.27

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.
Files changed (93) hide show
  1. package/backend/auth/permissions.ts +21 -0
  2. package/backend/bootstrap.ts +18 -1
  3. package/backend/chat/engine-handoff.test.ts +229 -0
  4. package/backend/chat/engine-handoff.ts +439 -0
  5. package/backend/chat/stream-manager.ts +200 -16
  6. package/backend/database/migrations/066_create_memory_graph.ts +369 -0
  7. package/backend/database/migrations/index.ts +7 -0
  8. package/backend/database/queries/audit-log-queries.test.ts +10 -1
  9. package/backend/database/queries/graph-queries.ts +1764 -0
  10. package/backend/database/queries/index.ts +2 -0
  11. package/backend/database/queries/memory-queue-queries.ts +381 -0
  12. package/backend/database/queries/snapshot-queries.ts +20 -0
  13. package/backend/engine/README.md +45 -2
  14. package/backend/engine/adapters/copilot/stream.ts +37 -1
  15. package/backend/engine/adapters/pi/models.ts +19 -7
  16. package/backend/engine/adapters/pi/stream.ts +2 -1
  17. package/backend/engine/docs/adapter-contract.md +25 -8
  18. package/backend/engine/docs/adding-an-engine.md +40 -4
  19. package/backend/engine/docs/frontend-and-chat.md +66 -1
  20. package/backend/engine/docs/lessons-learned.md +165 -6
  21. package/backend/engine/docs/quick-reference.md +10 -0
  22. package/backend/engine/docs/stack.md +10 -0
  23. package/backend/engine/docs/websocket-routes.md +15 -1
  24. package/backend/engine/engine-setup.ts +1 -1
  25. package/backend/engine/index.test.ts +186 -0
  26. package/backend/engine/index.ts +117 -71
  27. package/backend/engine/install-recipes.test.ts +105 -0
  28. package/backend/engine/install-recipes.ts +4 -1
  29. package/backend/index.ts +9 -0
  30. package/backend/mcp/internal/config.ts +6 -0
  31. package/backend/mcp/internal/servers/index.ts +2 -0
  32. package/backend/mcp/internal/servers/memory-graph/description.ts +33 -0
  33. package/backend/mcp/internal/servers/memory-graph/format.ts +45 -0
  34. package/backend/mcp/internal/servers/memory-graph/index.ts +52 -0
  35. package/backend/mcp/internal/servers/memory-graph/runner.ts +342 -0
  36. package/backend/mcp/internal/servers/memory-graph/schema.ts +140 -0
  37. package/backend/memory/README.md +432 -0
  38. package/backend/memory/bootstrap.ts +101 -0
  39. package/backend/memory/compose.test.ts +198 -0
  40. package/backend/memory/compose.ts +343 -0
  41. package/backend/memory/config.ts +100 -0
  42. package/backend/memory/consolidate.ts +280 -0
  43. package/backend/memory/context.test.ts +321 -0
  44. package/backend/memory/context.ts +451 -0
  45. package/backend/memory/embedding/embedder.test.ts +141 -0
  46. package/backend/memory/embedding/embedder.ts +269 -0
  47. package/backend/memory/embedding/index.ts +17 -0
  48. package/backend/memory/embedding/install.ts +254 -0
  49. package/backend/memory/embedding/paths.ts +101 -0
  50. package/backend/memory/embedding/vector-cache.ts +270 -0
  51. package/backend/memory/extract/episodic.ts +725 -0
  52. package/backend/memory/extract/index.ts +133 -0
  53. package/backend/memory/extract/languages.ts +176 -0
  54. package/backend/memory/extract/scheduler.test.ts +352 -0
  55. package/backend/memory/extract/scheduler.ts +406 -0
  56. package/backend/memory/extract/structural.test.ts +215 -0
  57. package/backend/memory/extract/structural.ts +364 -0
  58. package/backend/memory/index.ts +37 -0
  59. package/backend/memory/indexer.ts +150 -0
  60. package/backend/memory/invalidate.ts +134 -0
  61. package/backend/memory/judge.ts +285 -0
  62. package/backend/memory/maintenance.ts +132 -0
  63. package/backend/memory/model.ts +91 -0
  64. package/backend/memory/notify.ts +102 -0
  65. package/backend/memory/readiness.ts +74 -0
  66. package/backend/memory/redact.test.ts +101 -0
  67. package/backend/memory/redact.ts +133 -0
  68. package/backend/memory/retention.ts +139 -0
  69. package/backend/memory/retrieval.eval.test.ts +301 -0
  70. package/backend/memory/retrieval.test.ts +1023 -0
  71. package/backend/memory/retrieval.ts +707 -0
  72. package/backend/memory/revise.test.ts +693 -0
  73. package/backend/memory/revise.ts +400 -0
  74. package/backend/memory/time.ts +31 -0
  75. package/backend/memory/view.ts +164 -0
  76. package/backend/shipped-runtime-imports.test.ts +228 -0
  77. package/backend/ws/index.ts +5 -1
  78. package/backend/ws/memory/crud.ts +631 -0
  79. package/backend/ws/memory/index.ts +41 -0
  80. package/backend/ws/sessions/crud.ts +10 -0
  81. package/backend/ws/snapshot/restore.ts +38 -4
  82. package/dist/assets/graph-layout.worker-CRFqN7ZQ.js +1 -0
  83. package/dist/assets/{index-B6QGUN03.js → index-BCv5HlPk.js} +1 -1
  84. package/dist/assets/{index-DYa-GDsb.js → index-BTGcf_Vy.js} +1 -1
  85. package/dist/assets/main-BrqMMMRX.css +1 -0
  86. package/dist/assets/{main-Dznkfxsd.js → main-CgmAFpU3.js} +835 -426
  87. package/dist/index.html +2 -2
  88. package/package.json +8 -2
  89. package/shared/types/database/connection.ts +9 -0
  90. package/shared/types/memory.ts +519 -0
  91. package/shared/utils/logger.ts +1 -0
  92. package/dist/assets/main-Dh-MTGNR.css +0 -1
  93. package/shared/utils/anonymous-user.ts +0 -168
@@ -0,0 +1,707 @@
1
+ /**
2
+ * Hybrid retrieval over the Memory Graph.
3
+ *
4
+ * Three signals, combined on **every** query — this is not a fallback chain:
5
+ *
6
+ * 1. **Lexical (BM25 over FTS5)** finds identifiers, paths and error names.
7
+ * Embeddings are weakest exactly here, because a rare symbol like
8
+ * `EngineNotReadyError` has no semantic neighbourhood to sit in.
9
+ * 2. **Vector (local static embeddings)** finds paraphrase and cross-language
10
+ * matches — an Indonesian question reaching an English memory with no shared
11
+ * word. BM25 is blind to that.
12
+ * 3. **Graph expansion** pulls in what the direct matches are connected to,
13
+ * which is the whole point of storing memory as a graph: the best answer is
14
+ * often adjacent to the match rather than the match itself.
15
+ *
16
+ * The two ranked lists are merged with Reciprocal Rank Fusion. RRF is used
17
+ * instead of blending raw scores because BM25 and cosine are not comparable
18
+ * quantities — one is unbounded and corpus-relative, the other is bounded — so
19
+ * any weighted sum of the two would need per-corpus calibration to mean
20
+ * anything. Ranks need none.
21
+ *
22
+ * A conditional "use vectors only if lexical found nothing" design was
23
+ * considered and rejected: identical queries would take different code paths as
24
+ * the corpus grew, making results feel arbitrary. Both channels always run;
25
+ * whichever has signal contributes it. What DOES vary is how much each is
26
+ * trusted — see `profileQuery`.
27
+ *
28
+ * No LLM is involved and no network call is made. Target is well under 30 ms so
29
+ * this can run on every turn.
30
+ */
31
+
32
+ import { getDatabase } from '$backend/database';
33
+ import { graphQueries } from '$backend/database/queries/graph-queries';
34
+ import { debug } from '$shared/utils/logger';
35
+ import { embedder, vectorCache } from './embedding';
36
+ import { EMBEDDING_VERSION } from './embedding/paths';
37
+ import { ageInDays } from './time';
38
+ import { AUTHORITY_RANK } from '$shared/types/memory';
39
+ import type {
40
+ GraphNode,
41
+ QueryProfile,
42
+ RetrievalChannel,
43
+ RetrievalHit,
44
+ RetrievalOptions,
45
+ RetrievalResult
46
+ } from '$shared/types/memory';
47
+
48
+ /**
49
+ * RRF damping constant. 60 is the value from the original Cormack et al.
50
+ * formulation and is deliberately large relative to our result sizes: it keeps
51
+ * rank 1 from dominating rank 2, so a node both channels rank modestly outranks
52
+ * one channel's confident-but-lonely top hit. That is the behaviour we want —
53
+ * agreement between a lexical and a semantic match is the strongest signal here.
54
+ */
55
+ const RRF_K = 60;
56
+
57
+ /** How many candidates each channel contributes before fusion. */
58
+ const CHANNEL_DEPTH = 60;
59
+
60
+ /**
61
+ * Ceiling on vectors scored per query. Similarity is a brute-force scan (no ANN
62
+ * index), which is the right trade at this scale: 20k packed vectors is ~5 MB and
63
+ * scores in a few milliseconds, while an ANN index would add a dependency and a
64
+ * rebuild step for a corpus that fits in cache. Should a graph ever exceed this,
65
+ * the cap keeps latency bounded rather than degrading silently — and it is
66
+ * ordered so the most reinforced, most recent memories are the ones scored.
67
+ */
68
+ const MAX_VECTORS_SCANNED = 20_000;
69
+
70
+ /** Seeds that spreading activation starts from, strongest fused rank first. */
71
+ const MAX_SEEDS = 6;
72
+
73
+ /**
74
+ * Precise-mode gating for the vector channel (see `RetrievalOptions.precise`).
75
+ *
76
+ * The z is lower than `relate.ts` uses, because linking creates a permanent edge
77
+ * while a search result is disposable — the cost of being slightly too generous
78
+ * here is one extra row on screen, not a corrupted graph.
79
+ */
80
+ const PRECISE_Z = 1.0;
81
+ const PRECISE_FLOOR = 0.35;
82
+
83
+ /** Below this many candidates a distribution is too small to gate against. */
84
+ const PRECISE_MIN_SAMPLE = 8;
85
+
86
+ /**
87
+ * How much a memory learned in ANOTHER project is discounted here.
88
+ *
89
+ * MEASURED, on a seeded three-project corpus with deliberate per-project
90
+ * disagreements (each project deploys somewhere different, uses a different
91
+ * database, runs tests differently). The curve is flat where it matters and
92
+ * falls off a cliff below it:
93
+ *
94
+ * ×1.00 transfer recall@3 7/7, locality 4/4 — but nothing separates a
95
+ * travelling insight from another project's answer
96
+ * ×0.85 transfer 6/7, locality 4/4 <- shipped
97
+ * ×0.80 transfer 6/7, locality 4/4
98
+ * ×0.50 transfer 0/7 — the discount swallows the feature whole
99
+ *
100
+ * 0.85 sits in the middle of the flat band rather than at either edge, so a
101
+ * corpus that grows in one direction does not fall off it. It is a tie-break,
102
+ * not a gate: what actually keeps another project's answer out is `reach`, and
103
+ * this only decides the order when both are eligible.
104
+ */
105
+ const FOREIGN_PROJECT_PENALTY = 0.85;
106
+
107
+ /**
108
+ * Fraction of a seed's activation that flows to each neighbour per hop.
109
+ *
110
+ * This is personalized-PageRank-shaped rather than a flat bonus: activation is
111
+ * divided by the neighbour count, so a hub node with forty edges passes almost
112
+ * nothing to any one of them while a memory with two edges passes a real amount.
113
+ * A flat per-hop score — what a plain BFS expansion gives — has the opposite
114
+ * behaviour, and hubs are exactly the nodes a memory graph accumulates.
115
+ */
116
+ const SPREAD_DAMPING = 0.45;
117
+
118
+ interface Candidate {
119
+ node: GraphNode;
120
+ lexicalRank: number | null;
121
+ vectorRank: number | null;
122
+ snippet: string | null;
123
+ hops: number;
124
+ /** Accumulated spreading-activation mass, for graph-reached candidates. */
125
+ activation: number;
126
+ }
127
+
128
+ interface FilterSql {
129
+ clause: string;
130
+ params: unknown[];
131
+ }
132
+
133
+ /**
134
+ * How a query should be read.
135
+ *
136
+ * The two channels are not equally good at the two kinds of question, and which
137
+ * kind a query is can be told from its surface without a model. `getByPath` and
138
+ * `backend/memory/relate.ts` are identifiers: BM25 matches them exactly, while a
139
+ * mean-pooled static embedding of a path fragment lands in the crowded middle of
140
+ * the space and mostly adds noise. "kenapa kita pakai SQLite" is the reverse —
141
+ * it shares no token with the English memory that answers it, and only the vector
142
+ * channel can cross that gap.
143
+ *
144
+ * The weights are deliberately mild (0.6 / 1.4 rather than 0 / 2). A query that
145
+ * looks like code often still has a prose answer, so this tilts the fusion
146
+ * rather than disabling half of it.
147
+ */
148
+ export function profileQuery(query: string): QueryProfile {
149
+ const tokens = query.split(/\s+/).filter(Boolean);
150
+ if (tokens.length === 0) return { shape: 'prose', lexicalWeight: 1, vectorWeight: 1 };
151
+
152
+ const codey = tokens.filter(token =>
153
+ // A path separator, a file extension, snake_case, camelCase, or a call.
154
+ /[/\\]/.test(token) ||
155
+ /\.[a-z]{1,4}\b/i.test(token) ||
156
+ /[a-z0-9]_[a-z0-9]/i.test(token) ||
157
+ /[a-z][A-Z]/.test(token) ||
158
+ /\(\)/.test(token)
159
+ ).length;
160
+
161
+ const ratio = codey / tokens.length;
162
+ // A short query that is ENTIRELY an identifier is the clearest signal there
163
+ // is: someone pasted a symbol and wants what is known about it.
164
+ if (ratio >= 0.6) return { shape: 'code', lexicalWeight: 1.4, vectorWeight: 0.6 };
165
+ if (ratio >= 0.2) return { shape: 'mixed', lexicalWeight: 1.15, vectorWeight: 0.85 };
166
+ return { shape: 'prose', lexicalWeight: 0.8, vectorWeight: 1.2 };
167
+ }
168
+
169
+ /**
170
+ * Shared WHERE fragment so both channels see the same corpus. Without this the
171
+ * two rank lists could be drawn from different populations and fusion would be
172
+ * comparing incomparable sets.
173
+ *
174
+ * `projectId: undefined` means "every project" — the cross-project case that
175
+ * backs global chat. A concrete project also admits global-scope nodes, because
176
+ * user-level conventions apply inside every project.
177
+ */
178
+ function buildFilter(options: RetrievalOptions, alias: string): FilterSql {
179
+ const where: string[] = [];
180
+ const params: unknown[] = [];
181
+
182
+ // `reach = 'anywhere'` is what a memory learned elsewhere needs to be admitted
183
+ // here. Structural nodes are excluded by construction — their reach is written
184
+ // as `here` on insert — so another repository's file paths can never arrive,
185
+ // which is the leak the blanket project filter was originally added to stop.
186
+ const travelling = options.crossProject ? ` OR ${alias}.reach = 'anywhere'` : '';
187
+
188
+ if (options.projectIds !== undefined) {
189
+ if (options.projectIds.length === 0) {
190
+ where.push(`(${alias}.project_id IS NULL${travelling})`);
191
+ } else {
192
+ where.push(
193
+ `(${alias}.project_id IN (${options.projectIds.map(() => '?').join(',')}) OR ${alias}.project_id IS NULL${travelling})`
194
+ );
195
+ params.push(...options.projectIds);
196
+ }
197
+ } else if (options.projectId !== undefined) {
198
+ if (options.projectId === null) {
199
+ where.push(`(${alias}.project_id IS NULL${travelling})`);
200
+ } else {
201
+ where.push(`(${alias}.project_id = ? OR ${alias}.project_id IS NULL${travelling})`);
202
+ params.push(options.projectId);
203
+ }
204
+ }
205
+ if (options.sessionId) {
206
+ // Session-scoped memories are private to their session; everything broader
207
+ // stays visible, so asking inside a session sees both.
208
+ where.push(`(${alias}.scope != 'session' OR ${alias}.session_id = ?)`);
209
+ params.push(options.sessionId);
210
+ }
211
+ if (options.scopes?.length) {
212
+ where.push(`${alias}.scope IN (${options.scopes.map(() => '?').join(',')})`);
213
+ params.push(...options.scopes);
214
+ }
215
+ if (options.kinds?.length) {
216
+ where.push(`${alias}.kind IN (${options.kinds.map(() => '?').join(',')})`);
217
+ params.push(...options.kinds);
218
+ }
219
+ if (options.subkinds?.length) {
220
+ where.push(`${alias}.subkind IN (${options.subkinds.map(() => '?').join(',')})`);
221
+ params.push(...options.subkinds);
222
+ }
223
+ if (options.sources?.length) {
224
+ where.push(`${alias}.source IN (${options.sources.map(() => '?').join(',')})`);
225
+ params.push(...options.sources);
226
+ }
227
+ if (!options.includeArchived) where.push(`${alias}.archived_at IS NULL`);
228
+ // Superseded memories are history. Handing an agent both the old and the new
229
+ // version of a fact makes it adjudicate them on every turn, which is the exact
230
+ // work belief revision exists to have already done.
231
+ if (!options.includeSuperseded) where.push(`${alias}.superseded_by IS NULL`);
232
+
233
+ return { clause: where.length ? `AND ${where.join(' AND ')}` : '', params };
234
+ }
235
+
236
+ /**
237
+ * The same filter as a predicate over already-loaded nodes.
238
+ *
239
+ * Graph expansion reaches nodes through EDGES rather than through a query, and
240
+ * edges deliberately cross project boundaries (that is what lets a pattern
241
+ * proven in one repository be reused in another). Without re-checking the filter
242
+ * here, one hop from a shared dependency node would pull another project's files
243
+ * — and, through them, another project's memories — into a block that is about to
244
+ * be injected into this project's prompt. Traversal has to obey the same scope
245
+ * rules the channels do.
246
+ */
247
+ function makeFilterPredicate(options: RetrievalOptions): (node: GraphNode) => boolean {
248
+ const scopes = options.scopes?.length ? new Set(options.scopes) : null;
249
+ const kinds = options.kinds?.length ? new Set(options.kinds) : null;
250
+ const subkinds = options.subkinds?.length ? new Set(options.subkinds) : null;
251
+ const sources = options.sources?.length ? new Set(options.sources) : null;
252
+
253
+ const projectIds = options.projectIds ? new Set(options.projectIds) : null;
254
+
255
+ return (node: GraphNode): boolean => {
256
+ // Same admission rule as `buildFilter`, so traversal cannot reach anything
257
+ // the channels were not allowed to return.
258
+ const travels = options.crossProject === true && node.reach === 'anywhere' && node.kind === 'episodic';
259
+ if (projectIds) {
260
+ if (node.projectId !== null && !projectIds.has(node.projectId) && !travels) return false;
261
+ } else if (options.projectId !== undefined) {
262
+ if (options.projectId === null) {
263
+ if (node.projectId !== null && !travels) return false;
264
+ } else if (node.projectId !== null && node.projectId !== options.projectId && !travels) {
265
+ return false;
266
+ }
267
+ }
268
+ if (options.sessionId && node.scope === 'session' && node.sessionId !== options.sessionId) return false;
269
+ if (scopes && !scopes.has(node.scope)) return false;
270
+ if (kinds && !kinds.has(node.kind)) return false;
271
+ if (subkinds && !subkinds.has(node.subkind)) return false;
272
+ if (sources && !sources.has(node.source)) return false;
273
+ if (!options.includeArchived && node.archivedAt) return false;
274
+ if (!options.includeSuperseded && node.supersededBy) return false;
275
+ return true;
276
+ };
277
+ }
278
+
279
+ /** BM25 hits, best first, with a highlighted snippet. */
280
+ function lexicalSearch(options: RetrievalOptions): { id: string; snippet: string }[] {
281
+ const ftsQuery = graphQueries.buildFtsQuery(options.query);
282
+ if (!ftsQuery) return [];
283
+
284
+ const filter = buildFilter(options, 'n');
285
+ try {
286
+ return getDatabase()
287
+ .prepare(
288
+ `SELECT fts.node_id AS id,
289
+ snippet(graph_nodes_fts, 4, char(1), char(2), '…', 16) AS snippet
290
+ FROM graph_nodes_fts fts
291
+ INNER JOIN graph_nodes n ON n.id = fts.node_id
292
+ WHERE graph_nodes_fts MATCH ? ${filter.clause}
293
+ ORDER BY rank
294
+ LIMIT ?`
295
+ )
296
+ .all(ftsQuery, ...filter.params, CHANNEL_DEPTH) as { id: string; snippet: string }[];
297
+ } catch (error) {
298
+ // A malformed MATCH expression must not take the whole retrieval down —
299
+ // the vector channel can still answer.
300
+ debug.warn('memory', 'Lexical retrieval failed', error);
301
+ return [];
302
+ }
303
+ }
304
+
305
+ /**
306
+ * Cosine hits, best first. Empty when the embedding artifact is not loaded.
307
+ *
308
+ * Only episodic nodes carry vectors (see `nodesMissingVectors`), so this channel
309
+ * searches prose while the lexical channel covers names and paths. The join does
310
+ * that filtering implicitly — a node with no vector row is simply not a
311
+ * candidate.
312
+ */
313
+ function vectorSearch(options: RetrievalOptions): { id: string; score: number }[] {
314
+ try {
315
+ const query = embedder.embed(options.query);
316
+ if (!query) return [];
317
+
318
+ // SQLite is asked for IDS, not blobs. The scan is index-covered over columns
319
+ // the filter already needs, and the vectors themselves come from the resident
320
+ // cache — reading twenty thousand BLOBs per turn was the single most
321
+ // expensive thing on the read path, and it grew with the corpus while the
322
+ // arithmetic it fed did not.
323
+ const filter = buildFilter(options, 'n');
324
+ const candidates = (
325
+ getDatabase()
326
+ .prepare(
327
+ `SELECT v.node_id AS id
328
+ FROM graph_vectors v
329
+ INNER JOIN graph_nodes n ON n.id = v.node_id
330
+ WHERE v.model = ? AND v.dim = ? ${filter.clause}
331
+ ORDER BY n.pinned DESC, n.weight DESC, n.updated_at DESC
332
+ LIMIT ?`
333
+ )
334
+ .all(EMBEDDING_VERSION, query.length, ...filter.params, MAX_VECTORS_SCANNED) as { id: string }[]
335
+ ).map(row => row.id);
336
+ if (candidates.length === 0) return [];
337
+
338
+ vectorCache.ensure();
339
+
340
+ // Only the sign is filtered, not the magnitude.
341
+ //
342
+ // An absolute cutoff is tempting and wrong here. Measured on this artifact,
343
+ // a correct cross-language match often scores 0.11–0.20 while an unrelated
344
+ // pair can reach 0.24 — the distributions overlap, because mean-pooled
345
+ // static embeddings put short texts closer together than their meanings
346
+ // warrant. Any threshold that removed the noise would remove real answers
347
+ // too. Ordering is still informative even where the absolute value is not,
348
+ // so magnitude is left to decide rank and BM25 is what corrects the
349
+ // mistakes vectors make. This is the concrete reason retrieval fuses two
350
+ // channels rather than trusting either.
351
+ const scored = vectorCache.score(query, candidates, 0);
352
+
353
+ // In precise mode a vector hit has to EARN its place rather than merely beat
354
+ // zero. The cutoff is relative to this query's own score distribution for the
355
+ // same reason `relate.ts` uses one: with static embeddings the absolute
356
+ // numbers are not comparable across queries, but "unusually close for this
357
+ // query" is meaningful. An absolute floor sits under it, because standing out
358
+ // from a field of near-zeros still means nothing.
359
+ //
360
+ // Injection deliberately does NOT use this: there a weak semantic lead is
361
+ // still worth ranking, and BM25 corrects it. A search box is the opposite —
362
+ // sixty loosely-related results read as a broken feature.
363
+ if (options.precise && scored.length >= PRECISE_MIN_SAMPLE) {
364
+ const mean = scored.reduce((sum, entry) => sum + entry.score, 0) / scored.length;
365
+ const variance = scored.reduce((sum, entry) => sum + (entry.score - mean) ** 2, 0) / scored.length;
366
+ const stddev = Math.sqrt(variance);
367
+ const cutoff = Math.max(mean + PRECISE_Z * stddev, PRECISE_FLOOR);
368
+ return scored.filter(entry => entry.score >= cutoff).slice(0, CHANNEL_DEPTH);
369
+ }
370
+
371
+ return scored.slice(0, CHANNEL_DEPTH);
372
+ } catch (error) {
373
+ debug.warn('memory', 'Vector retrieval failed', error);
374
+ return [];
375
+ }
376
+ }
377
+
378
+ /**
379
+ * Prior applied on top of the fused rank: memories that have PROVED useful and
380
+ * are still current outrank ones written once and never confirmed, and old
381
+ * untouched memories fade without ever disappearing.
382
+ *
383
+ * `useful_count` carries the reinforcement here, not `access_count`. Being
384
+ * retrieved is a fact about the ranker, and letting it feed its own input is a
385
+ * loop that ends with the same handful of memories injected forever regardless
386
+ * of the question. Being USED is evidence, and it is adjudicated by the
387
+ * following turn (see `extract/episodic.ts`).
388
+ *
389
+ * Deliberately gentle (logarithmic, bounded, floored) — the query should decide
390
+ * relevance, with track record only breaking ties.
391
+ */
392
+ function prior(node: GraphNode): number {
393
+ if (node.pinned) return 1.5;
394
+
395
+ const proven = Math.log1p(node.usefulCount) * 0.18;
396
+ const rejected = Math.log1p(node.unhelpfulCount) * 0.1;
397
+ const reinforcement = Math.max(0.5, 1 + Math.log1p(Math.max(0, node.weight - 1)) * 0.15 + proven - rejected);
398
+
399
+ const ageDays = ageInDays(node.accessedAt ?? node.updatedAt);
400
+ const recency = 0.6 + 0.4 * Math.exp(-ageDays / 90);
401
+
402
+ // A memory whose code changed underneath it is not wrong, but it has stopped
403
+ // being evidence about the current state of the repository.
404
+ const staleness = node.staleAt ? 0.7 : 1;
405
+
406
+ return reinforcement * recency * staleness * (0.5 + 0.5 * node.confidence);
407
+ }
408
+
409
+ function channelOf(candidate: Candidate): RetrievalChannel {
410
+ if (candidate.hops > 0) return 'graph';
411
+ if (candidate.lexicalRank !== null && candidate.vectorRank !== null) return 'both';
412
+ if (candidate.vectorRank !== null) return 'vector';
413
+ return 'lexical';
414
+ }
415
+
416
+ /**
417
+ * Retrieve memories for a query. Never throws: a failure in one channel degrades
418
+ * the result rather than the caller, because this runs on the turn path.
419
+ */
420
+ export function retrieve(options: RetrievalOptions): RetrievalResult {
421
+ const started = performance.now();
422
+ const profile = profileQuery(options.query);
423
+
424
+ try {
425
+ return { ...rank(options, profile), elapsedMs: performance.now() - started, profile };
426
+ } catch (error) {
427
+ // Retrieval is an enrichment. Everything that calls it — turn injection, the
428
+ // MCP tool, the Memory modal — is better off with no memories than with an
429
+ // exception, so the guarantee in the docstring is enforced rather than hoped
430
+ // for.
431
+ debug.error('memory', 'Retrieval failed; returning no hits', error);
432
+ return { hits: [], vectorUsed: false, elapsedMs: performance.now() - started, profile };
433
+ }
434
+ }
435
+
436
+ function rank(options: RetrievalOptions, profile: QueryProfile): { hits: RetrievalHit[]; vectorUsed: boolean } {
437
+ const limit = options.limit ?? 12;
438
+
439
+ const lexical = lexicalSearch(options);
440
+ const vector = vectorSearch(options);
441
+
442
+ const candidates = new Map<string, Candidate>();
443
+ const ensure = (id: string, node: GraphNode): Candidate => {
444
+ let existing = candidates.get(id);
445
+ if (!existing) {
446
+ existing = { node, lexicalRank: null, vectorRank: null, snippet: null, hops: 0, activation: 0 };
447
+ candidates.set(id, existing);
448
+ }
449
+ return existing;
450
+ };
451
+
452
+ // One batched read for both channels' ids rather than a lookup per hit.
453
+ const directIds = [...new Set([...lexical.map(l => l.id), ...vector.map(v => v.id)])];
454
+ const nodesById = new Map(graphQueries.getByIds(directIds).map(n => [n.id, n]));
455
+
456
+ lexical.forEach((hit, index) => {
457
+ const node = nodesById.get(hit.id);
458
+ if (!node) return;
459
+ const candidate = ensure(hit.id, node);
460
+ candidate.lexicalRank = index + 1;
461
+ candidate.snippet = hit.snippet;
462
+ });
463
+
464
+ vector.forEach((hit, index) => {
465
+ const node = nodesById.get(hit.id);
466
+ if (!node) return;
467
+ ensure(hit.id, node).vectorRank = index + 1;
468
+ });
469
+
470
+ const accept = makeFilterPredicate(options);
471
+
472
+ // ── anchors ────────────────────────────────────────────────────────────
473
+ // The files the session is working in are seeds too. Without this, a turn
474
+ // whose text carries no retrievable signal — "continue", "fix it", "coba
475
+ // lagi", which is a large share of real turns — retrieves nothing at all,
476
+ // even when the graph holds a failure memory about the exact file on screen.
477
+ // The query says nothing; the working set says plenty.
478
+ const anchors = anchorSeeds(options, accept);
479
+ for (const node of anchors) {
480
+ if (candidates.has(node.id)) continue;
481
+ candidates.set(node.id, {
482
+ node,
483
+ lexicalRank: null,
484
+ vectorRank: null,
485
+ snippet: null,
486
+ hops: 0,
487
+ // Anchors are context, not answers: they enter with a small activation so
488
+ // they can pull their neighbours in without outranking a real match.
489
+ activation: 1 / (RRF_K + CHANNEL_DEPTH)
490
+ });
491
+ }
492
+
493
+ // ── graph expansion (spreading activation) ─────────────────────────────
494
+ const expandHops = options.expandHops ?? 1;
495
+ if (expandHops > 0 && candidates.size > 0) {
496
+ spread(candidates, expandHops, accept, profile);
497
+ }
498
+
499
+ // ── fuse ───────────────────────────────────────────────────────────────
500
+ const home = options.projectId ?? null;
501
+ const scored: RetrievalHit[] = [...candidates.values()]
502
+ .filter(candidate => accept(candidate.node))
503
+ .map(candidate => {
504
+ const base = candidate.hops > 0 ? candidate.activation : rrfScore(candidate, profile) + candidate.activation;
505
+ // A memory that travelled here from another repository is worth having and
506
+ // is not worth outranking one from this one when both match equally.
507
+ const foreign =
508
+ candidate.node.projectId !== null && home !== null && candidate.node.projectId !== home
509
+ ? FOREIGN_PROJECT_PENALTY
510
+ : 1;
511
+ return {
512
+ node: candidate.node,
513
+ score: base * prior(candidate.node) * foreign,
514
+ channel: channelOf(candidate),
515
+ lexicalRank: candidate.lexicalRank,
516
+ vectorRank: candidate.vectorRank,
517
+ hops: candidate.hops,
518
+ snippet: candidate.snippet
519
+ };
520
+ })
521
+ .sort((a, b) => b.score - a.score);
522
+
523
+ const hits = resolveConflicts(scored).slice(0, limit);
524
+ return { hits, vectorUsed: vector.length > 0 };
525
+ }
526
+
527
+ /**
528
+ * Drop the losing side of every pair of memories that contradict each other.
529
+ *
530
+ * This is where belief revision actually happens now. The write path records a
531
+ * disagreement and destroys nothing; the decision is made HERE, from scratch, on
532
+ * every turn, by a rule with no model in it:
533
+ *
534
+ * 1. **Authority.** What the user said beats what the assistant asserted beats
535
+ * what a model inferred. This is the ordering the old design had no column
536
+ * for, which is how an inference came to retire a hand-written rule.
537
+ * 2. **Durability.** A standing rule beats a one-off instruction. An exception
538
+ * taken for one task is not a policy, however recently it was taken.
539
+ * 3. **Recency.** Between two claims of equal standing, the later one is the
540
+ * user's current position — which is the whole of what "the newest
541
+ * instruction wins" was supposed to mean.
542
+ *
543
+ * Deciding at read time rather than write time is what makes a wrong call
544
+ * cheap. The loser is not removed from the graph, is still searchable, still
545
+ * shows in the view, and comes back the moment the evidence changes.
546
+ */
547
+ function resolveConflicts(hits: RetrievalHit[]): RetrievalHit[] {
548
+ if (hits.length < 2) return hits;
549
+
550
+ let edges: { srcId: string; dstId: string }[];
551
+ try {
552
+ edges = graphQueries.contradictionsFor(hits.map(hit => hit.node.id));
553
+ } catch (error) {
554
+ debug.warn('memory', 'Conflict resolution failed; returning every hit', error);
555
+ return hits;
556
+ }
557
+ if (edges.length === 0) return hits;
558
+
559
+ const byId = new Map(hits.map(hit => [hit.node.id, hit.node]));
560
+ const losers = new Set<string>();
561
+ for (const edge of edges) {
562
+ const a = byId.get(edge.srcId);
563
+ const b = byId.get(edge.dstId);
564
+ // Only decide between two memories that BOTH reached this result set. A
565
+ // contradiction with something the query never surfaced is not this turn's
566
+ // argument to settle.
567
+ if (!a || !b) continue;
568
+ losers.add(currentOf(a, b) === a ? b.id : a.id);
569
+ }
570
+ if (losers.size === 0) return hits;
571
+
572
+ return hits.filter(hit => !losers.has(hit.node.id));
573
+ }
574
+
575
+ const DURABILITY: Record<GraphNode['scope'], number> = { session: 0, project: 1, global: 2 };
576
+
577
+ /** Which of two contradicting memories is the current belief. */
578
+ function currentOf(a: GraphNode, b: GraphNode): GraphNode {
579
+ const authority = AUTHORITY_RANK[a.assertedBy] - AUTHORITY_RANK[b.assertedBy];
580
+ if (authority !== 0) return authority > 0 ? a : b;
581
+
582
+ const durability = DURABILITY[a.scope] - DURABILITY[b.scope];
583
+ if (durability !== 0) return durability > 0 ? a : b;
584
+
585
+ // `updatedAt`, not `createdAt`: a memory re-observed this week is the user's
586
+ // current position even if it was first written months ago.
587
+ return Date.parse(`${a.updatedAt}Z`) >= Date.parse(`${b.updatedAt}Z`) ? a : b;
588
+ }
589
+
590
+ /**
591
+ * Structural nodes for the paths the caller says it is working in.
592
+ *
593
+ * These are looked up rather than searched: a path is an exact key, and running
594
+ * it through BM25 would be both slower and less precise.
595
+ */
596
+ function anchorSeeds(options: RetrievalOptions, accept: (node: GraphNode) => boolean): GraphNode[] {
597
+ const paths = options.anchorPaths;
598
+ if (!paths?.length || options.projectId === undefined || options.projectId === null) return [];
599
+ try {
600
+ return graphQueries.getByPaths(options.projectId, paths.slice(0, 40)).filter(accept);
601
+ } catch (error) {
602
+ debug.warn('memory', 'Anchor seeding failed', error);
603
+ return [];
604
+ }
605
+ }
606
+
607
+ /**
608
+ * Push activation out from the strongest candidates along their edges.
609
+ *
610
+ * Expanding from EVERY match would flood the result with weakly-related
611
+ * neighbours, which is how graph retrieval usually goes wrong, so only the top
612
+ * seeds emit. Each seed's mass is divided among its neighbours and damped per
613
+ * hop, so being reached from two different seeds accumulates — which is the
614
+ * property that makes a two-hop node worth surfacing at all — while a single
615
+ * edge from a forty-edge hub contributes almost nothing.
616
+ */
617
+ function spread(
618
+ candidates: Map<string, Candidate>,
619
+ hops: number,
620
+ accept: (node: GraphNode) => boolean,
621
+ profile: QueryProfile
622
+ ): void {
623
+ const seeds = [...candidates.values()]
624
+ .filter(candidate => candidate.hops === 0)
625
+ .sort((a, b) => rrfScore(b, profile) - rrfScore(a, profile))
626
+ .slice(0, MAX_SEEDS);
627
+
628
+ let frontier = seeds.map(seed => ({
629
+ id: seed.node.id,
630
+ mass: Math.max(rrfScore(seed, profile), 1 / (RRF_K + CHANNEL_DEPTH))
631
+ }));
632
+ const seedIds = new Set(frontier.map(entry => entry.id));
633
+
634
+ for (let depth = 1; depth <= hops; depth++) {
635
+ const next = new Map<string, number>();
636
+
637
+ for (const { id, mass } of frontier) {
638
+ let neighbours: { node: GraphNode; hops: number }[];
639
+ try {
640
+ neighbours = graphQueries.neighbours(id, 1, 24);
641
+ } catch (error) {
642
+ debug.warn('memory', `Expansion failed at ${id}`, error);
643
+ continue;
644
+ }
645
+
646
+ // Filtered BEFORE the fan-out is counted, so a node whose neighbours are
647
+ // mostly in another project does not have its activation diluted by
648
+ // edges that were never eligible to receive any.
649
+ const eligible = neighbours.filter(entry => accept(entry.node));
650
+ if (eligible.length === 0) continue;
651
+
652
+ const share = (mass * SPREAD_DAMPING) / eligible.length;
653
+ for (const entry of eligible) {
654
+ if (seedIds.has(entry.node.id)) continue;
655
+
656
+ const existing = candidates.get(entry.node.id);
657
+ if (existing) {
658
+ // Already a direct match — it keeps its own rank; the extra mass only
659
+ // confirms it.
660
+ existing.activation += share;
661
+ continue;
662
+ }
663
+ candidates.set(entry.node.id, {
664
+ node: entry.node,
665
+ lexicalRank: null,
666
+ vectorRank: null,
667
+ snippet: null,
668
+ hops: depth,
669
+ activation: share
670
+ });
671
+ next.set(entry.node.id, (next.get(entry.node.id) ?? 0) + share);
672
+ }
673
+ }
674
+
675
+ frontier = [...next.entries()].map(([id, mass]) => ({ id, mass }));
676
+ if (frontier.length === 0) break;
677
+ }
678
+ }
679
+
680
+ /**
681
+ * Reciprocal Rank Fusion contribution of a candidate's two ranks, tilted by how
682
+ * the query was read (see `profileQuery`).
683
+ */
684
+ function rrfScore(candidate: Candidate, profile: QueryProfile): number {
685
+ let score = 0;
686
+ if (candidate.lexicalRank !== null) score += profile.lexicalWeight / (RRF_K + candidate.lexicalRank);
687
+ if (candidate.vectorRank !== null) score += profile.vectorWeight / (RRF_K + candidate.vectorRank);
688
+ return score;
689
+ }
690
+
691
+ /**
692
+ * Record that a human or an agent deliberately consulted these memories.
693
+ *
694
+ * Kept OUT of `retrieve` on purpose. Automatic turn-start injection retrieves on
695
+ * every single turn, so counting that as usage would make `access_count` a
696
+ * measure of how often the ranker picked a node — which then feeds the ranker.
697
+ * Only deliberate reads (the MCP `recall` action, a search in the Memory modal)
698
+ * count.
699
+ */
700
+ export function markConsulted(hits: RetrievalHit[]): void {
701
+ if (hits.length === 0) return;
702
+ try {
703
+ graphQueries.markAccessed(hits.map(hit => hit.node.id));
704
+ } catch (error) {
705
+ debug.warn('memory', 'Failed to record memory access', error);
706
+ }
707
+ }