@myrialabs/clopen 0.4.25 → 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 (96) 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/content.ts +85 -0
  82. package/backend/ws/snapshot/index.ts +4 -1
  83. package/backend/ws/snapshot/restore.ts +38 -4
  84. package/dist/assets/graph-layout.worker-CRFqN7ZQ.js +1 -0
  85. package/dist/assets/{index-KBGloYDk.js → index-BCv5HlPk.js} +1 -1
  86. package/dist/assets/{index-C4PD7B-x.js → index-BTGcf_Vy.js} +1 -1
  87. package/dist/assets/main-BrqMMMRX.css +1 -0
  88. package/dist/assets/main-CgmAFpU3.js +1036 -0
  89. package/dist/index.html +2 -2
  90. package/package.json +8 -2
  91. package/shared/types/database/connection.ts +9 -0
  92. package/shared/types/memory.ts +519 -0
  93. package/shared/utils/logger.ts +1 -0
  94. package/dist/assets/main-B0AA-88X.js +0 -622
  95. package/dist/assets/main-OsjA5Ab5.css +0 -1
  96. package/shared/utils/anonymous-user.ts +0 -168
@@ -0,0 +1,1023 @@
1
+ /**
2
+ * Memory Graph schema + retrieval tests.
3
+ *
4
+ * These run against a REAL in-memory SQLite database with migration 066 applied,
5
+ * rather than a hand-mocked query surface. The interesting behaviour here lives
6
+ * in the SQL — the COALESCE-based digest uniqueness, the FTS5 mirror, the
7
+ * cross-project filters — and a mock would assert the test's own idea of that
8
+ * SQL instead of the database's.
9
+ *
10
+ * The vector channel needs the on-demand artifact, so tests that depend on it
11
+ * are skipped when it is absent; the lexical, graph and fusion behaviour is
12
+ * covered regardless.
13
+ */
14
+
15
+ import { beforeEach, describe, expect, it, mock } from 'bun:test';
16
+ import { Database } from 'bun:sqlite';
17
+ import type { DatabaseConnection } from '$shared/types/database/connection';
18
+ import * as migration066 from '$backend/database/migrations/066_create_memory_graph';
19
+
20
+ let db: Database;
21
+
22
+ // The whole module surface, not just `getDatabase`. `mock.module` replaces the
23
+ // module for the entire test PROCESS, so a partial stub leaves any file that runs
24
+ // afterwards unable to import the missing names — surfacing as
25
+ // "Export named 'closeDatabase' not found" in a test that never touched memory.
26
+ mock.module('$backend/database', () => ({
27
+ getDatabase: () => db,
28
+ initializeDatabase: async () => db,
29
+ closeDatabase: () => {},
30
+ resetDatabase: async () => {},
31
+ getDatabaseInfo: async () => ({}),
32
+ vacuumDatabase: async () => {}
33
+ }));
34
+
35
+ const { graphQueries, deriveDigest } = await import('$backend/database/queries/graph-queries');
36
+ const { retrieve, markConsulted, profileQuery } = await import('./retrieval');
37
+ const { embedder } = await import('./embedding');
38
+ const { isEmbeddingArtifactInstalled } = await import('./embedding/paths');
39
+
40
+ const PROJECT_A = 'project-a';
41
+ const PROJECT_B = 'project-b';
42
+
43
+ function resetDatabase(): void {
44
+ db = new Database(':memory:');
45
+ db.exec('PRAGMA foreign_keys = ON');
46
+ migration066.up(db as unknown as DatabaseConnection);
47
+ }
48
+
49
+ beforeEach(() => {
50
+ resetDatabase();
51
+ });
52
+
53
+ describe('graph schema', () => {
54
+ it('upserts on digest instead of duplicating, and reinforces weight', () => {
55
+ const first = graphQueries.upsert({
56
+ kind: 'episodic',
57
+ subkind: 'decision',
58
+ projectId: PROJECT_A,
59
+ label: 'Engine SDKs install on demand',
60
+ body: 'They are not bundled into the global install.'
61
+ });
62
+ const second = graphQueries.upsert({
63
+ kind: 'episodic',
64
+ subkind: 'decision',
65
+ projectId: PROJECT_A,
66
+ label: 'Engine SDKs install on demand',
67
+ body: 'They are not bundled into the global install.'
68
+ });
69
+
70
+ expect(second.id).toBe(first.id);
71
+ expect(second.weight).toBeGreaterThan(first.weight);
72
+ expect(graphQueries.count({ projectId: PROJECT_A })).toBe(1);
73
+ });
74
+
75
+ it('treats the same claim in two projects as two nodes', () => {
76
+ const input = {
77
+ kind: 'episodic' as const,
78
+ subkind: 'pattern' as const,
79
+ label: 'Runes are used for state',
80
+ body: 'Traditional stores are avoided.'
81
+ };
82
+ const a = graphQueries.upsert({ ...input, projectId: PROJECT_A });
83
+ const b = graphQueries.upsert({ ...input, projectId: PROJECT_B });
84
+
85
+ expect(a.id).not.toBe(b.id);
86
+ expect(a.digest).toBe(b.digest);
87
+ });
88
+
89
+ it('de-duplicates global nodes even though project_id is NULL', () => {
90
+ // SQLite counts every NULL as distinct in a UNIQUE index, so this only
91
+ // works because the index keys on COALESCE(project_id, '').
92
+ const input = {
93
+ kind: 'episodic' as const,
94
+ subkind: 'preference' as const,
95
+ scope: 'global' as const,
96
+ projectId: null,
97
+ label: 'All PR-facing text is written in English'
98
+ };
99
+ graphQueries.upsert(input);
100
+ graphQueries.upsert(input);
101
+
102
+ expect(graphQueries.count({ projectId: null })).toBe(1);
103
+ });
104
+
105
+ it('never lets an automatic write overwrite user-authored text', () => {
106
+ const node = graphQueries.upsert({
107
+ kind: 'episodic',
108
+ subkind: 'decision',
109
+ projectId: PROJECT_A,
110
+ label: 'Original label',
111
+ source: 'user'
112
+ });
113
+
114
+ graphQueries.upsert({
115
+ kind: 'episodic',
116
+ subkind: 'decision',
117
+ projectId: PROJECT_A,
118
+ label: 'Machine-rewritten label',
119
+ digest: node.digest,
120
+ source: 'agent'
121
+ });
122
+
123
+ expect(graphQueries.getById(node.id)!.label).toBe('Original label');
124
+ });
125
+
126
+ it('re-derives the digest after a manual edit so extraction cannot revert it', () => {
127
+ const node = graphQueries.upsert({
128
+ kind: 'episodic',
129
+ subkind: 'observation',
130
+ projectId: PROJECT_A,
131
+ label: 'Snapshots use the file watcher'
132
+ });
133
+
134
+ graphQueries.update(node.id, { label: 'Snapshots scan the disk, not the watcher' });
135
+ const edited = graphQueries.getById(node.id)!;
136
+ expect(edited.digest).not.toBe(node.digest);
137
+
138
+ // The original claim now hashes to a free digest, so re-extracting it adds a
139
+ // new node rather than overwriting the correction.
140
+ graphQueries.upsert({
141
+ kind: 'episodic',
142
+ subkind: 'observation',
143
+ projectId: PROJECT_A,
144
+ label: 'Snapshots use the file watcher'
145
+ });
146
+ expect(graphQueries.getById(node.id)!.label).toBe('Snapshots scan the disk, not the watcher');
147
+ expect(graphQueries.count({ projectId: PROJECT_A })).toBe(2);
148
+ });
149
+
150
+ it('gives each dependency its own identity', () => {
151
+ // Dependencies carry no path or symbol, so without a name-based fallback they
152
+ // all hash to the same digest and each new package overwrites the last.
153
+ const lodash = deriveDigest({ kind: 'structural', subkind: 'dependency', label: 'lodash' });
154
+ const zod = deriveDigest({ kind: 'structural', subkind: 'dependency', label: 'zod' });
155
+ expect(lodash).not.toBe(zod);
156
+ });
157
+
158
+ it('keeps structural identity tied to path and symbol', () => {
159
+ const a = deriveDigest({ kind: 'structural', subkind: 'file', label: 'x', path: 'backend/a.ts' });
160
+ const b = deriveDigest({ kind: 'structural', subkind: 'file', label: 'totally different label', path: 'backend/a.ts' });
161
+ const c = deriveDigest({ kind: 'structural', subkind: 'file', label: 'x', path: 'backend/b.ts' });
162
+
163
+ expect(a).toBe(b);
164
+ expect(a).not.toBe(c);
165
+ });
166
+ });
167
+
168
+ describe('graph edges', () => {
169
+ it('rejects self-loops and strengthens repeated links', () => {
170
+ const a = graphQueries.upsert({ kind: 'episodic', subkind: 'decision', projectId: PROJECT_A, label: 'A' });
171
+ const b = graphQueries.upsert({ kind: 'structural', subkind: 'file', projectId: PROJECT_A, label: 'b.ts', path: 'b.ts' });
172
+
173
+ expect(graphQueries.link({ srcId: a.id, dstId: a.id, rel: 'about' })).toBeNull();
174
+
175
+ const first = graphQueries.link({ srcId: a.id, dstId: b.id, rel: 'about' })!;
176
+ const second = graphQueries.link({ srcId: a.id, dstId: b.id, rel: 'about' })!;
177
+ expect(second.id).toBe(first.id);
178
+ expect(second.weight).toBeGreaterThan(first.weight);
179
+ });
180
+
181
+ it('cascades edges when a node is hard-deleted', () => {
182
+ const a = graphQueries.upsert({ kind: 'episodic', subkind: 'decision', projectId: PROJECT_A, label: 'A' });
183
+ const b = graphQueries.upsert({ kind: 'structural', subkind: 'file', projectId: PROJECT_A, label: 'b.ts', path: 'b.ts' });
184
+ graphQueries.link({ srcId: a.id, dstId: b.id, rel: 'about' });
185
+
186
+ graphQueries.remove(b.id);
187
+ expect(graphQueries.edgesOf(a.id)).toHaveLength(0);
188
+ });
189
+
190
+ it('walks multiple hops and reports distance', () => {
191
+ const a = graphQueries.upsert({ kind: 'episodic', subkind: 'decision', projectId: PROJECT_A, label: 'A' });
192
+ const b = graphQueries.upsert({ kind: 'structural', subkind: 'file', projectId: PROJECT_A, label: 'b.ts', path: 'b.ts' });
193
+ const c = graphQueries.upsert({ kind: 'structural', subkind: 'file', projectId: PROJECT_A, label: 'c.ts', path: 'c.ts' });
194
+ graphQueries.link({ srcId: a.id, dstId: b.id, rel: 'about' });
195
+ graphQueries.link({ srcId: b.id, dstId: c.id, rel: 'imports' });
196
+
197
+ const oneHop = graphQueries.neighbours(a.id, 1);
198
+ expect(oneHop.map(n => n.node.id)).toEqual([b.id]);
199
+
200
+ const twoHops = graphQueries.neighbours(a.id, 2);
201
+ expect(twoHops.find(n => n.node.id === c.id)?.hops).toBe(2);
202
+ });
203
+
204
+ it('bridges episodic and structural memory through `about`', () => {
205
+ const decision = graphQueries.upsert({
206
+ kind: 'episodic',
207
+ subkind: 'decision',
208
+ projectId: PROJECT_A,
209
+ label: 'Credentials are read from the database, never from env vars'
210
+ });
211
+ const file = graphQueries.upsert({
212
+ kind: 'structural',
213
+ subkind: 'file',
214
+ projectId: PROJECT_A,
215
+ label: 'engine-queries.ts',
216
+ path: 'backend/database/queries/engine-queries.ts'
217
+ });
218
+ graphQueries.link({ srcId: decision.id, dstId: file.id, rel: 'about' });
219
+
220
+ // Arriving from the code should reach the decision made about it.
221
+ const fromCode = graphQueries.neighbours(file.id, 1);
222
+ expect(fromCode.map(n => n.node.id)).toContain(decision.id);
223
+ });
224
+ });
225
+
226
+ describe('lexical retrieval', () => {
227
+ beforeEach(() => {
228
+ graphQueries.upsert({
229
+ kind: 'episodic',
230
+ subkind: 'failure',
231
+ projectId: PROJECT_A,
232
+ label: 'Codex exits with code 1 when its home directory is missing',
233
+ body: 'getCodexHomeDir now creates the directory on access.'
234
+ });
235
+ graphQueries.upsert({
236
+ kind: 'structural',
237
+ subkind: 'file',
238
+ projectId: PROJECT_A,
239
+ label: 'sdk-loader.ts',
240
+ path: 'backend/engine/sdk-loader.ts'
241
+ });
242
+ graphQueries.upsert({
243
+ kind: 'episodic',
244
+ subkind: 'decision',
245
+ projectId: PROJECT_B,
246
+ label: 'Preview capture uses fitScale times device pixel ratio'
247
+ });
248
+ });
249
+
250
+ it('finds a memory by an identifier in its body', () => {
251
+ const result = retrieve({ query: 'getCodexHomeDir', projectId: PROJECT_A, expandHops: 0 });
252
+ expect(result.hits[0].node.label).toContain('Codex exits with code 1');
253
+ });
254
+
255
+ it('matches a path fragment, because paths are indexed split as well as whole', () => {
256
+ const result = retrieve({ query: 'sdk loader', projectId: PROJECT_A, expandHops: 0 });
257
+ expect(result.hits.map(h => h.node.path)).toContain('backend/engine/sdk-loader.ts');
258
+ });
259
+
260
+ it('scopes results to one project but still admits global memories', () => {
261
+ graphQueries.upsert({
262
+ kind: 'episodic',
263
+ subkind: 'preference',
264
+ scope: 'global',
265
+ projectId: null,
266
+ label: 'Preview quality is preferred over frame rate'
267
+ });
268
+
269
+ const scoped = retrieve({ query: 'preview', projectId: PROJECT_A, expandHops: 0 });
270
+ const labels = scoped.hits.map(h => h.node.label);
271
+ expect(labels).toContain('Preview quality is preferred over frame rate');
272
+ expect(labels).not.toContain('Preview capture uses fitScale times device pixel ratio');
273
+ });
274
+
275
+ it('searches across every project when no project is given', () => {
276
+ const all = retrieve({ query: 'preview', expandHops: 0 });
277
+ expect(all.hits.map(h => h.node.projectId)).toContain(PROJECT_B);
278
+ });
279
+
280
+ it('survives punctuation-only and empty queries', () => {
281
+ expect(retrieve({ query: '' }).hits).toHaveLength(0);
282
+ expect(retrieve({ query: ' ??? ' }).hits).toHaveLength(0);
283
+ expect(() => retrieve({ query: 'a" OR "b' })).not.toThrow();
284
+ });
285
+
286
+ it('drops archived nodes from the index and restores them on demand', () => {
287
+ const node = graphQueries.upsert({
288
+ kind: 'episodic',
289
+ subkind: 'observation',
290
+ projectId: PROJECT_A,
291
+ label: 'Zstd compresses large WebSocket responses'
292
+ });
293
+
294
+ graphQueries.archive(node.id);
295
+ expect(retrieve({ query: 'zstd', projectId: PROJECT_A, expandHops: 0 }).hits).toHaveLength(0);
296
+
297
+ graphQueries.restore(node.id);
298
+ expect(retrieve({ query: 'zstd', projectId: PROJECT_A, expandHops: 0 }).hits).toHaveLength(1);
299
+ });
300
+ });
301
+
302
+ describe('graph expansion', () => {
303
+ it('surfaces a neighbour of a match that the query itself never mentions', () => {
304
+ const file = graphQueries.upsert({
305
+ kind: 'structural',
306
+ subkind: 'file',
307
+ projectId: PROJECT_A,
308
+ label: 'snapshot-service.ts',
309
+ path: 'backend/snapshot/snapshot-service.ts'
310
+ });
311
+ const decision = graphQueries.upsert({
312
+ kind: 'episodic',
313
+ subkind: 'decision',
314
+ projectId: PROJECT_A,
315
+ label: 'The disk is the source of truth, not the watcher dirty set'
316
+ });
317
+ graphQueries.link({ srcId: decision.id, dstId: file.id, rel: 'about' });
318
+
319
+ const direct = retrieve({ query: 'snapshot-service', projectId: PROJECT_A, expandHops: 0 });
320
+ expect(direct.hits.map(h => h.node.id)).not.toContain(decision.id);
321
+
322
+ const expanded = retrieve({ query: 'snapshot-service', projectId: PROJECT_A, expandHops: 1 });
323
+ const hit = expanded.hits.find(h => h.node.id === decision.id);
324
+ expect(hit).toBeDefined();
325
+ expect(hit!.channel).toBe('graph');
326
+ expect(hit!.hops).toBe(1);
327
+ });
328
+
329
+ it('ranks an expanded neighbour below the direct match that produced it', () => {
330
+ const file = graphQueries.upsert({
331
+ kind: 'structural',
332
+ subkind: 'file',
333
+ projectId: PROJECT_A,
334
+ label: 'stream-manager.ts',
335
+ path: 'backend/chat/stream-manager.ts'
336
+ });
337
+ const note = graphQueries.upsert({
338
+ kind: 'episodic',
339
+ subkind: 'observation',
340
+ projectId: PROJECT_A,
341
+ label: 'Unrelated wording entirely'
342
+ });
343
+ graphQueries.link({ srcId: note.id, dstId: file.id, rel: 'about' });
344
+
345
+ const result = retrieve({ query: 'stream-manager', projectId: PROJECT_A, expandHops: 1 });
346
+ expect(result.hits[0].node.id).toBe(file.id);
347
+ });
348
+ });
349
+
350
+ describe('ranking priors', () => {
351
+ it('prefers a pinned memory over an equally-matching unpinned one', () => {
352
+ graphQueries.upsert({
353
+ kind: 'episodic',
354
+ subkind: 'decision',
355
+ projectId: PROJECT_A,
356
+ label: 'Compression applies to websocket responses'
357
+ });
358
+ const pinned = graphQueries.upsert({
359
+ kind: 'episodic',
360
+ subkind: 'decision',
361
+ projectId: PROJECT_A,
362
+ label: 'Compression applies to websocket payloads',
363
+ pinned: true
364
+ });
365
+
366
+ const result = retrieve({ query: 'compression websocket', projectId: PROJECT_A, expandHops: 0 });
367
+ expect(result.hits[0].node.id).toBe(pinned.id);
368
+ });
369
+
370
+ /**
371
+ * Retrieval used to count its own results as accesses, and that number then fed
372
+ * back into the prior that produced them. Automatic injection retrieves on every
373
+ * single turn, so the loop had nothing to do with whether a memory was any good:
374
+ * whatever ranked highly ranked more highly next time. Only a DELIBERATE
375
+ * consultation counts now.
376
+ */
377
+ it('does not count an access merely for retrieving a node', () => {
378
+ const node = graphQueries.upsert({
379
+ kind: 'episodic',
380
+ subkind: 'decision',
381
+ projectId: PROJECT_A,
382
+ label: 'Cursor pagination replaced full chain loading'
383
+ });
384
+
385
+ retrieve({ query: 'cursor pagination', projectId: PROJECT_A, expandHops: 0 });
386
+ expect(graphQueries.getById(node.id)!.accessCount).toBe(0);
387
+ });
388
+
389
+ it('counts an access when a caller says the result was consulted', () => {
390
+ const node = graphQueries.upsert({
391
+ kind: 'episodic',
392
+ subkind: 'decision',
393
+ projectId: PROJECT_A,
394
+ label: 'Cursor pagination replaced full chain loading'
395
+ });
396
+
397
+ const result = retrieve({ query: 'cursor pagination', projectId: PROJECT_A, expandHops: 0 });
398
+ markConsulted(result.hits);
399
+ expect(graphQueries.getById(node.id)!.accessCount).toBe(1);
400
+ });
401
+ });
402
+
403
+ const describeIfEmbedding = isEmbeddingArtifactInstalled() ? describe : describe.skip;
404
+
405
+ describeIfEmbedding('vector retrieval', () => {
406
+ it('answers an Indonesian question about an English memory', async () => {
407
+ await embedder.load();
408
+
409
+ const target = graphQueries.upsert({
410
+ kind: 'episodic',
411
+ subkind: 'failure',
412
+ projectId: PROJECT_A,
413
+ label: 'The browser preview stayed stuck on Loading because early ICE candidates were not buffered'
414
+ });
415
+ graphQueries.upsert({
416
+ kind: 'episodic',
417
+ subkind: 'pattern',
418
+ projectId: PROJECT_A,
419
+ label: 'Svelte runes are used for state management across the frontend'
420
+ });
421
+ graphQueries.upsert({
422
+ kind: 'episodic',
423
+ subkind: 'observation',
424
+ projectId: PROJECT_A,
425
+ label: 'SQLite migrations are numbered sequentially and seeders run after them'
426
+ });
427
+
428
+ // Vectors are written by the indexer, which is what retrieval reads.
429
+ const { drain } = await import('./indexer');
430
+ await drain();
431
+
432
+ // Not one word of this query appears in any stored memory, so BM25 returns
433
+ // nothing at all and anything that comes back came from the vector channel.
434
+ const result = retrieve({ query: 'halaman tidak mau tampil', projectId: PROJECT_A, expandHops: 0 });
435
+ expect(result.vectorUsed).toBe(true);
436
+ expect(result.hits[0].node.id).toBe(target.id);
437
+ expect(result.hits[0].channel).toBe('vector');
438
+ expect(result.hits[0].lexicalRank).toBeNull();
439
+ });
440
+
441
+ it('lets the lexical channel correct a vector mistake', async () => {
442
+ await embedder.load();
443
+
444
+ const target = graphQueries.upsert({
445
+ kind: 'episodic',
446
+ subkind: 'decision',
447
+ projectId: PROJECT_A,
448
+ label: 'Permissions are enforced by a runtime hook because Clopen auto approves everything'
449
+ });
450
+ // Measured against this artifact, "izin tool ditegakkan di mana?" scores
451
+ // this unrelated memory (0.204) ABOVE the correct one (0.107) — mean-pooled
452
+ // static embeddings put short texts closer together than their meanings do.
453
+ // A vector-only retriever would answer wrongly here.
454
+ graphQueries.upsert({
455
+ kind: 'episodic',
456
+ subkind: 'observation',
457
+ projectId: PROJECT_A,
458
+ label: 'The git panel actions stay visible regardless of repository state'
459
+ });
460
+
461
+ const { drain } = await import('./indexer');
462
+ await drain();
463
+
464
+ // With one shared term ("permissions") BM25 has a say, and fusion puts the
465
+ // right memory back on top. This is the case that justifies running both
466
+ // channels on every query rather than picking one.
467
+ const result = retrieve({ query: 'permissions ditegakkan di mana?', projectId: PROJECT_A, expandHops: 0 });
468
+ expect(result.hits[0].node.id).toBe(target.id);
469
+ });
470
+
471
+ it('finds every memory about one subject through the entity index', async () => {
472
+ await embedder.load();
473
+
474
+ // Three statements about one person, phrased differently. They used to be
475
+ // connected by similarity linking, which on a real corpus of "X is a project
476
+ // that does Y" sentences produced 144 edges that were mostly nonsense — every
477
+ // pair was similar in SHAPE rather than in SUBJECT. The entities a memory
478
+ // names answer the same question directly, and exactly.
479
+ const arga = [
480
+ 'Arga is a full-stack developer working in the JavaScript and TypeScript ecosystem',
481
+ 'Arga is a full-stack developer with five years of experience based in Indonesia',
482
+ 'Arga is the user of this workspace: a JavaScript and TypeScript full-stack developer'
483
+ ].map(label => graphQueries.upsert({ kind: 'episodic', subkind: 'entity', projectId: PROJECT_A, label }));
484
+ for (const node of arga) graphQueries.setEntities(node.id, [{ key: 'arga', name: 'Arga' }]);
485
+
486
+ const unrelated = graphQueries.upsert({
487
+ kind: 'episodic',
488
+ subkind: 'observation',
489
+ projectId: PROJECT_A,
490
+ label: 'Zstd compression is applied to large WebSocket responses'
491
+ });
492
+
493
+ const about = graphQueries.memoriesAboutEntity('arga').map(n => n.id);
494
+ for (const node of arga) expect(about).toContain(node.id);
495
+ expect(about).not.toContain(unrelated.id);
496
+ });
497
+
498
+ it('connects memories that name the same subject, without storing an edge', () => {
499
+ // Removing similarity linking took a real graph from 371 edges to 6 and left
500
+ // the view a field of disconnected dots. What was wrong with those edges was
501
+ // that COSINE chose them — two memories are related when they are about the
502
+ // same THING, which extraction already records.
503
+ const a = graphQueries.upsert({ kind: 'episodic', subkind: 'observation', projectId: PROJECT_A, label: 'TunnelKit exposes three tunnel modes' });
504
+ const b = graphQueries.upsert({ kind: 'episodic', subkind: 'decision', projectId: PROJECT_A, label: 'TunnelKit was extracted into its own library' });
505
+ const unrelated = graphQueries.upsert({ kind: 'episodic', subkind: 'observation', projectId: 'project-z', label: 'Something else entirely' });
506
+ graphQueries.setEntities(a.id, [{ key: 'tunnelkit', name: 'TunnelKit' }]);
507
+ graphQueries.setEntities(b.id, [{ key: 'tunnelkit', name: 'TunnelKit' }]);
508
+
509
+ const derived = graphQueries.derivedEdges([a.id, b.id, unrelated.id]);
510
+ expect(derived.some(e => e.via === 'subject' && [e.srcId, e.dstId].includes(a.id) && [e.srcId, e.dstId].includes(b.id))).toBe(true);
511
+
512
+ // Derived, not stored: nothing was written that could outlive the claim.
513
+ expect(graphQueries.edgesOf(a.id)).toHaveLength(0);
514
+ });
515
+
516
+ it('reaches a memory about the same subject in one traversal hop', () => {
517
+ const a = graphQueries.upsert({ kind: 'episodic', subkind: 'observation', projectId: PROJECT_A, label: 'First note about the subject' });
518
+ const b = graphQueries.upsert({ kind: 'episodic', subkind: 'observation', projectId: PROJECT_A, label: 'Second note about the subject' });
519
+ graphQueries.setEntities(a.id, [{ key: 'ptykit', name: 'PtyKit' }]);
520
+ graphQueries.setEntities(b.id, [{ key: 'ptykit', name: 'PtyKit' }]);
521
+
522
+ expect(graphQueries.neighbours(a.id, 1).map(n => n.node.id)).toContain(b.id);
523
+ });
524
+
525
+ it('does not connect a subject shared by too much of the graph', () => {
526
+ // A word everyone uses is not a relationship. Connecting forty memories
527
+ // through "TypeScript" would recreate the fabricated structure that
528
+ // similarity linking produced, from a different cause.
529
+ const ids: string[] = [];
530
+ for (let i = 0; i < 30; i++) {
531
+ const node = graphQueries.upsert({ kind: 'episodic', subkind: 'observation', projectId: PROJECT_A, label: `Note ${i}` });
532
+ graphQueries.setEntities(node.id, [{ key: 'typescript', name: 'TypeScript' }]);
533
+ ids.push(node.id);
534
+ }
535
+ expect(graphQueries.derivedEdges(ids).some(e => e.via === 'subject')).toBe(false);
536
+ });
537
+
538
+ it('never invents an edge between two memories', async () => {
539
+ await embedder.load();
540
+
541
+ // Similarity linking is gone. Nothing writes `relates_to` automatically any
542
+ // more, so a graph of related-sounding memories has no edges at all until a
543
+ // person or a model draws one deliberately.
544
+ const nodes = [
545
+ 'This repository is a Vantum monorepo at phase 1.8 containing core and CLI',
546
+ 'ChatKit runs on Node.js 18 and Bun with its design tokens kept local',
547
+ 'CommonForms Detection Service is a FastAPI PDF pipeline',
548
+ 'Programmer Finder uses Flutter for the app and Elixir for the API'
549
+ ].map(label => graphQueries.upsert({ kind: 'episodic', subkind: 'observation', projectId: PROJECT_A, label }));
550
+
551
+ for (const node of nodes) {
552
+ expect(graphQueries.edgesOf(node.id).filter(e => e.rel === 'relates_to')).toHaveLength(0);
553
+ }
554
+ });
555
+
556
+ it('marks a hit found by both channels as `both`', async () => {
557
+ await embedder.load();
558
+
559
+ graphQueries.upsert({
560
+ kind: 'episodic',
561
+ subkind: 'decision',
562
+ projectId: PROJECT_A,
563
+ label: 'Engine SDKs are installed on demand into the managed stack directory'
564
+ });
565
+
566
+ const { drain } = await import('./indexer');
567
+ await drain();
568
+
569
+ const result = retrieve({ query: 'engine SDK installed on demand', projectId: PROJECT_A, expandHops: 0 });
570
+ expect(result.hits[0].channel).toBe('both');
571
+ expect(result.hits[0].lexicalRank).not.toBeNull();
572
+ expect(result.hits[0].vectorRank).not.toBeNull();
573
+ });
574
+ });
575
+
576
+ describe('query profiling', () => {
577
+ /**
578
+ * The two channels are not equally good at the two kinds of question, and which
579
+ * kind a query is can be told from its surface without a model. Getting this
580
+ * wrong in either direction is expensive: weighting vectors on an identifier
581
+ * buries the exact match, and weighting lexical on a paraphrase leaves the
582
+ * cross-language case with nothing.
583
+ */
584
+ it.each([
585
+ ['backend/memory/retrieval.ts', 'code'],
586
+ ['EngineNotReadyError', 'code'],
587
+ ['stream_manager.captureSnapshot()', 'code'],
588
+ ['kenapa kita memilih SQLite daripada Postgres', 'prose'],
589
+ ['what did we decide about authentication', 'prose']
590
+ ] as const)('reads %s as %s', (query, shape) => {
591
+ expect(profileQuery(query).shape).toBe(shape);
592
+ });
593
+
594
+ it('tilts fusion toward the channel that suits the query', () => {
595
+ const code = profileQuery('backend/memory/retrieval.ts');
596
+ const prose = profileQuery('why do we keep memories in one graph');
597
+
598
+ expect(code.lexicalWeight).toBeGreaterThan(code.vectorWeight);
599
+ expect(prose.vectorWeight).toBeGreaterThan(prose.lexicalWeight);
600
+ });
601
+
602
+ it('reports the profile it used, so ranking stays explainable', () => {
603
+ const result = retrieve({ query: 'backend/memory/retrieval.ts', projectId: PROJECT_A });
604
+ expect(result.profile.shape).toBe('code');
605
+ });
606
+ });
607
+
608
+ describe('graph expansion', () => {
609
+ /**
610
+ * Edges deliberately cross project boundaries — that is what lets a pattern
611
+ * proven in one repository be reused in another. Traversal therefore has to
612
+ * re-apply the scope filter, or one hop from a shared dependency node reaches
613
+ * another project's files and, through them, another project's memories — into a
614
+ * block that is about to be injected into THIS project's prompt.
615
+ */
616
+ it('does not cross into another project through a shared node', () => {
617
+ const shared = graphQueries.upsert({
618
+ kind: 'structural',
619
+ subkind: 'dependency',
620
+ scope: 'global',
621
+ projectId: null,
622
+ label: 'zod'
623
+ });
624
+ const mine = graphQueries.upsert({
625
+ kind: 'structural',
626
+ subkind: 'file',
627
+ projectId: PROJECT_A,
628
+ label: 'mine.ts',
629
+ path: 'mine.ts'
630
+ });
631
+ const theirs = graphQueries.upsert({
632
+ kind: 'episodic',
633
+ subkind: 'decision',
634
+ projectId: PROJECT_B,
635
+ label: 'Another team decided to validate every boundary with zod'
636
+ });
637
+ graphQueries.link({ srcId: mine.id, dstId: shared.id, rel: 'imports' });
638
+ graphQueries.link({ srcId: theirs.id, dstId: shared.id, rel: 'about' });
639
+
640
+ const hits = retrieve({ query: 'zod', projectId: PROJECT_A, expandHops: 2 }).hits;
641
+ expect(hits.map(h => h.node.id)).not.toContain(theirs.id);
642
+ });
643
+
644
+ it('does not leak another session\'s private memories', () => {
645
+ const shared = graphQueries.upsert({
646
+ kind: 'structural',
647
+ subkind: 'file',
648
+ projectId: PROJECT_A,
649
+ label: 'shared.ts',
650
+ path: 'shared.ts'
651
+ });
652
+ const priv = graphQueries.upsert({
653
+ kind: 'episodic',
654
+ subkind: 'observation',
655
+ scope: 'session',
656
+ projectId: PROJECT_A,
657
+ sessionId: 'other-session',
658
+ label: 'Private to another conversation entirely'
659
+ });
660
+ graphQueries.link({ srcId: priv.id, dstId: shared.id, rel: 'about' });
661
+
662
+ const hits = retrieve({
663
+ query: 'shared.ts',
664
+ projectId: PROJECT_A,
665
+ sessionId: 'my-session',
666
+ expandHops: 2
667
+ }).hits;
668
+ expect(hits.map(h => h.node.id)).not.toContain(priv.id);
669
+ });
670
+
671
+ it('reaches a memory through the file the turn is working in', () => {
672
+ // The "continue" case: the query says nothing, the working set says plenty.
673
+ const target = graphQueries.upsert({
674
+ kind: 'structural',
675
+ subkind: 'file',
676
+ projectId: PROJECT_A,
677
+ label: 'auth.ts',
678
+ path: 'backend/auth.ts'
679
+ });
680
+ const lesson = graphQueries.upsert({
681
+ kind: 'episodic',
682
+ subkind: 'failure',
683
+ projectId: PROJECT_A,
684
+ label: 'Rotating the signing key without a grace period logged everyone out'
685
+ });
686
+ graphQueries.link({ srcId: lesson.id, dstId: target.id, rel: 'about' });
687
+
688
+ const hits = retrieve({
689
+ query: 'lanjutkan',
690
+ projectId: PROJECT_A,
691
+ anchorPaths: ['backend/auth.ts'],
692
+ expandHops: 1
693
+ }).hits;
694
+ expect(hits.map(h => h.node.id)).toContain(lesson.id);
695
+ });
696
+
697
+ it('does not let a hub node drown the result in its neighbours', () => {
698
+ // Activation is divided by the neighbour count, so a forty-edge hub passes
699
+ // almost nothing to any one of them. A flat per-hop bonus — what a plain BFS
700
+ // expansion gives — has exactly the opposite behaviour.
701
+ const hub = graphQueries.upsert({
702
+ kind: 'structural',
703
+ subkind: 'file',
704
+ projectId: PROJECT_A,
705
+ label: 'hub.ts',
706
+ path: 'hub.ts'
707
+ });
708
+ const direct = graphQueries.upsert({
709
+ kind: 'episodic',
710
+ subkind: 'decision',
711
+ projectId: PROJECT_A,
712
+ label: 'hub.ts is the shared barrel export for the module'
713
+ });
714
+ graphQueries.link({ srcId: direct.id, dstId: hub.id, rel: 'about' });
715
+ for (let i = 0; i < 30; i++) {
716
+ const leaf = graphQueries.upsert({
717
+ kind: 'episodic',
718
+ subkind: 'observation',
719
+ projectId: PROJECT_A,
720
+ label: `Unrelated note number ${i} about nothing in particular`
721
+ });
722
+ graphQueries.link({ srcId: leaf.id, dstId: hub.id, rel: 'about' });
723
+ }
724
+
725
+ const hits = retrieve({ query: 'hub.ts barrel export', projectId: PROJECT_A, expandHops: 1 }).hits;
726
+ expect(hits[0].node.id).toBe(direct.id);
727
+ });
728
+ });
729
+
730
+ describe('lexical query building', () => {
731
+ it('splits identifiers on punctuation instead of stripping it', () => {
732
+ // Copying the message index's behaviour turned `stream-manager` into
733
+ // `streammanager`, which matches nothing. Prose and code need opposite
734
+ // treatment.
735
+ expect(graphQueries.buildFtsQuery('stream-manager')).toBe('"stream"* OR "manager"*');
736
+ });
737
+
738
+ it('caps the term count, because two callers pass long text', () => {
739
+ // A user pasting a stack trace, and belief revision, which queries with four
740
+ // thousand characters of transcript. Hundreds of OR-ed prefix terms is a parse
741
+ // tree deep enough to hit SQLite's expression limit — which throws, is caught,
742
+ // and silently removes the lexical channel from exactly the queries that had
743
+ // the most to say.
744
+ const long = Array.from({ length: 400 }, (_, i) => `term${i}`).join(' ');
745
+ const query = graphQueries.buildFtsQuery(long)!;
746
+
747
+ expect(query.split(' OR ')).toHaveLength(32);
748
+ });
749
+
750
+ it('answers a query of nothing but punctuation with null', () => {
751
+ expect(graphQueries.buildFtsQuery('--- ... ###')).toBeNull();
752
+ });
753
+ });
754
+
755
+ describe('multi-project scoping', () => {
756
+ function memoryIn(projectId: string | null, label: string) {
757
+ return graphQueries.upsert({
758
+ kind: 'episodic',
759
+ subkind: 'decision',
760
+ scope: projectId ? 'project' : 'global',
761
+ projectId,
762
+ label,
763
+ body: 'shared vocabulary distinctivetoken'
764
+ });
765
+ }
766
+
767
+ it('covers every named project plus the globals that apply inside them', () => {
768
+ const a = memoryIn(PROJECT_A, 'A decision in project A');
769
+ const b = memoryIn(PROJECT_B, 'A decision in project B');
770
+ const global = memoryIn(null, 'A decision that holds everywhere');
771
+ const other = memoryIn('project-c', 'A decision in project C');
772
+
773
+ const ids = retrieve({
774
+ query: 'distinctivetoken',
775
+ projectIds: [PROJECT_A, PROJECT_B],
776
+ expandHops: 0
777
+ }).hits.map(hit => hit.node.id);
778
+
779
+ expect(ids).toContain(a.id);
780
+ expect(ids).toContain(b.id);
781
+ expect(ids).toContain(global.id);
782
+ expect(ids).not.toContain(other.id);
783
+ });
784
+
785
+ it('reads an empty selection as global only', () => {
786
+ // Nothing selected is a narrowing, not the absence of one: the user has
787
+ // deselected every repository, and what remains is what was never a
788
+ // repository's to begin with.
789
+ const scoped = memoryIn(PROJECT_A, 'A decision in project A');
790
+ const global = memoryIn(null, 'A decision that holds everywhere');
791
+
792
+ const ids = retrieve({ query: 'distinctivetoken', projectIds: [], expandHops: 0 }).hits.map(
793
+ hit => hit.node.id
794
+ );
795
+
796
+ expect(ids).toContain(global.id);
797
+ expect(ids).not.toContain(scoped.id);
798
+ });
799
+
800
+ it('keeps expansion inside the selection', () => {
801
+ // Edges deliberately cross projects, so one hop from a shared dependency used
802
+ // to reach another project's files and, through them, another project's
803
+ // memories — into a block about to be injected into this project's prompt.
804
+ const mine = memoryIn(PROJECT_A, 'Uses the shared queue distinctivetoken');
805
+ const theirs = memoryIn('project-c', 'Also uses the shared queue');
806
+ const shared = graphQueries.upsert({
807
+ kind: 'structural',
808
+ subkind: 'dependency',
809
+ scope: 'global',
810
+ projectId: null,
811
+ label: 'shared-queue'
812
+ });
813
+ graphQueries.link({ srcId: mine.id, dstId: shared.id, rel: 'about' });
814
+ graphQueries.link({ srcId: theirs.id, dstId: shared.id, rel: 'about' });
815
+
816
+ const ids = retrieve({
817
+ query: 'distinctivetoken',
818
+ projectIds: [PROJECT_A],
819
+ expandHops: 2
820
+ }).hits.map(hit => hit.node.id);
821
+
822
+ expect(ids).toContain(mine.id);
823
+ expect(ids).not.toContain(theirs.id);
824
+ });
825
+ });
826
+
827
+ describe('memory that crosses projects', () => {
828
+ /**
829
+ * The capability one shared graph exists for, and the thing that made it
830
+ * impossible: `project_id` was answering two questions at once — where a memory
831
+ * was learned, and where it applies. Measured on a seeded three-project corpus,
832
+ * automatic injection delivered 1 of 7 cross-project answers while the ranker
833
+ * already had 5 of them at rank one. The filter was discarding what retrieval
834
+ * had found.
835
+ */
836
+ function travelling(projectId: string, label: string, body = '') {
837
+ return graphQueries.upsert({
838
+ kind: 'episodic',
839
+ subkind: 'pattern',
840
+ scope: 'project',
841
+ projectId,
842
+ label,
843
+ body,
844
+ reach: 'anywhere',
845
+ confidence: 0.9
846
+ });
847
+ }
848
+
849
+ function local(projectId: string, label: string, body = '') {
850
+ return graphQueries.upsert({
851
+ kind: 'episodic',
852
+ subkind: 'decision',
853
+ scope: 'project',
854
+ projectId,
855
+ label,
856
+ body,
857
+ reach: 'here',
858
+ confidence: 0.9
859
+ });
860
+ }
861
+
862
+ it('reaches a technology insight learned in another project', () => {
863
+ const gotcha = travelling(
864
+ 'project-b',
865
+ 'Bun suppresses crashes when an unhandledRejection listener is registered',
866
+ 'The Web-API addEventListener with preventDefault does not.'
867
+ );
868
+
869
+ const ids = retrieve({
870
+ query: 'unhandledRejection listener suppresses crashes bun',
871
+ projectId: PROJECT_A,
872
+ crossProject: true,
873
+ expandHops: 0
874
+ }).hits.map(hit => hit.node.id);
875
+
876
+ expect(ids).toContain(gotcha.id);
877
+ });
878
+
879
+ it('leaves another project\'s own answer at home', () => {
880
+ // The risk of lifting the filter, and why `reach` and not a flat discount is
881
+ // what does it: every project answers "where does this deploy" differently,
882
+ // and being handed another project's answer is worse than being handed none.
883
+ const theirs = local('project-b', 'This project deploys to Vercel on every merge');
884
+ const mine = local(PROJECT_A, 'This project deploys to Fly.io for the private network');
885
+
886
+ const ids = retrieve({
887
+ query: 'where does this project deploy',
888
+ projectId: PROJECT_A,
889
+ crossProject: true,
890
+ expandHops: 0
891
+ }).hits.map(hit => hit.node.id);
892
+
893
+ expect(ids).toContain(mine.id);
894
+ expect(ids).not.toContain(theirs.id);
895
+ });
896
+
897
+ it('never lets another project\'s files travel', () => {
898
+ // `reach` is forced to `here` for structural nodes on insert, so a path from
899
+ // another repository cannot arrive however the caller asks. This is the leak
900
+ // the blanket project filter was originally added to stop, kept.
901
+ graphQueries.upsert({
902
+ kind: 'structural',
903
+ subkind: 'file',
904
+ scope: 'project',
905
+ projectId: 'project-b',
906
+ label: 'packages/distinctivemodule/index.ts',
907
+ path: 'packages/distinctivemodule/index.ts',
908
+ reach: 'anywhere'
909
+ });
910
+
911
+ const hits = retrieve({
912
+ query: 'distinctivemodule',
913
+ projectId: PROJECT_A,
914
+ crossProject: true,
915
+ expandHops: 1
916
+ }).hits;
917
+
918
+ expect(hits.filter(hit => hit.node.kind === 'structural')).toHaveLength(0);
919
+ });
920
+
921
+ it('ranks a local memory above an equally-matching travelled one', () => {
922
+ const foreign = travelling('project-b', 'Guard factories keep authorisation off route files');
923
+ const here = travelling(PROJECT_A, 'Guard factories keep authorisation off route files here');
924
+
925
+ const hits = retrieve({
926
+ query: 'guard factories authorisation route files',
927
+ projectId: PROJECT_A,
928
+ crossProject: true,
929
+ expandHops: 0
930
+ }).hits;
931
+
932
+ const homeRank = hits.findIndex(hit => hit.node.id === here.id);
933
+ const awayRank = hits.findIndex(hit => hit.node.id === foreign.id);
934
+ expect(homeRank).toBeGreaterThanOrEqual(0);
935
+ expect(awayRank).toBeGreaterThan(homeRank);
936
+ });
937
+
938
+ it('does not cross projects unless asked', () => {
939
+ const gotcha = travelling('project-b', 'Tailwind v4 moves configuration into distinctivetoken CSS');
940
+
941
+ const ids = retrieve({ query: 'distinctivetoken', projectId: PROJECT_A, expandHops: 0 }).hits.map(
942
+ hit => hit.node.id
943
+ );
944
+ expect(ids).not.toContain(gotcha.id);
945
+ });
946
+ });
947
+
948
+ describe('conflicting memories', () => {
949
+ /**
950
+ * Belief revision now happens HERE rather than at write time. The write path
951
+ * records that two memories disagree; this decides which one is current, on
952
+ * every turn, under a rule with no model in it.
953
+ */
954
+ function preference(label: string, overrides: Record<string, unknown> = {}) {
955
+ return graphQueries.upsert({
956
+ kind: 'episodic',
957
+ subkind: 'preference',
958
+ scope: 'global',
959
+ projectId: null,
960
+ label,
961
+ confidence: 0.9,
962
+ ...overrides
963
+ } as Parameters<typeof graphQueries.upsert>[0]);
964
+ }
965
+
966
+ it('hands over what the user said, not what a model inferred', () => {
967
+ const stated = preference('Never use the distinctivetoken tool', { assertedBy: 'user' });
968
+ const inferred = preference('The distinctivetoken tool is appropriate here', { assertedBy: 'inferred' });
969
+ graphQueries.contradict(inferred.id, stated.id);
970
+
971
+ const ids = retrieve({ query: 'distinctivetoken tool', expandHops: 0 }).hits.map(hit => hit.node.id);
972
+ expect(ids).toContain(stated.id);
973
+ expect(ids).not.toContain(inferred.id);
974
+ });
975
+
976
+ it('prefers a standing rule to a one-off instruction', () => {
977
+ const standing = preference('Always run the distinctivetoken checks', { assertedBy: 'user' });
978
+ const oneOff = preference('Skip the distinctivetoken checks for this task', {
979
+ assertedBy: 'user',
980
+ scope: 'session'
981
+ });
982
+ graphQueries.contradict(oneOff.id, standing.id);
983
+
984
+ const ids = retrieve({ query: 'distinctivetoken checks', expandHops: 0 }).hits.map(hit => hit.node.id);
985
+ expect(ids).toContain(standing.id);
986
+ expect(ids).not.toContain(oneOff.id);
987
+ });
988
+
989
+ it('prefers the later statement when nothing else separates them', () => {
990
+ const older = preference('Deploy distinctivetoken builds on Friday', { assertedBy: 'user' });
991
+ const newer = preference('Never deploy distinctivetoken builds on Friday', { assertedBy: 'user' });
992
+ db.prepare(`UPDATE graph_nodes SET updated_at = datetime('now', '-3 days') WHERE id = ?`).run(older.id);
993
+ graphQueries.contradict(newer.id, older.id);
994
+
995
+ const ids = retrieve({ query: 'distinctivetoken builds friday', expandHops: 0 }).hits.map(hit => hit.node.id);
996
+ expect(ids).toContain(newer.id);
997
+ expect(ids).not.toContain(older.id);
998
+ });
999
+
1000
+ it('leaves the loser in the graph, not out of it', () => {
1001
+ // The point of deciding at read time: a wrong call costs one line, and the
1002
+ // memory is still there when the evidence changes.
1003
+ const stated = preference('Never use the distinctivetoken tool', { assertedBy: 'user' });
1004
+ const inferred = preference('The distinctivetoken tool is appropriate here', { assertedBy: 'inferred' });
1005
+ graphQueries.contradict(inferred.id, stated.id);
1006
+
1007
+ expect(graphQueries.getById(inferred.id)!.supersededBy).toBeNull();
1008
+ expect(graphQueries.getById(inferred.id)!.archivedAt).toBeNull();
1009
+ expect(graphQueries.list({ projectId: null }).map(n => n.id)).toContain(inferred.id);
1010
+ });
1011
+
1012
+ it('says nothing when only one side of a disagreement is in the results', () => {
1013
+ // A contradiction with something the query never surfaced is not this turn's
1014
+ // argument to settle, and silently dropping a hit because of an absent rival
1015
+ // would make results depend on rows nobody asked about.
1016
+ const shown = preference('Use distinctivetoken formatting everywhere', { assertedBy: 'inferred' });
1017
+ const absent = preference('Whitespace is settled by the editor configuration', { assertedBy: 'user' });
1018
+ graphQueries.contradict(absent.id, shown.id);
1019
+
1020
+ const ids = retrieve({ query: 'distinctivetoken formatting', expandHops: 0 }).hits.map(hit => hit.node.id);
1021
+ expect(ids).toContain(shown.id);
1022
+ });
1023
+ });