@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,693 @@
1
+ /**
2
+ * Belief revision, structural invalidation and retention.
3
+ *
4
+ * Against a real in-memory SQLite database with both migrations applied, for the
5
+ * same reason `retrieval.test.ts` does it: the behaviour under test is mostly SQL
6
+ * — which rows a superseded node disappears from, which subkinds decay, which
7
+ * nodes retention is allowed to touch — and a mocked query layer would assert the
8
+ * test's idea of that SQL rather than the database's.
9
+ *
10
+ * The vector-dependent half (near-duplicate detection) needs the on-demand
11
+ * embedding artifact and is skipped without it.
12
+ */
13
+
14
+ import { beforeEach, describe, expect, it, mock } from 'bun:test';
15
+ import { Database } from 'bun:sqlite';
16
+ import type { DatabaseConnection } from '$shared/types/database/connection';
17
+ import * as migration066 from '$backend/database/migrations/066_create_memory_graph';
18
+
19
+ let db: Database;
20
+
21
+ // The whole module surface, not just `getDatabase`. `mock.module` replaces the
22
+ // module for the entire test PROCESS, so a partial stub leaves any file that runs
23
+ // afterwards unable to import the missing names — surfacing as
24
+ // "Export named 'closeDatabase' not found" in a test that never touched memory.
25
+ mock.module('$backend/database', () => ({
26
+ getDatabase: () => db,
27
+ initializeDatabase: async () => db,
28
+ closeDatabase: () => {},
29
+ resetDatabase: async () => {},
30
+ getDatabaseInfo: async () => ({}),
31
+ vacuumDatabase: async () => {}
32
+ }));
33
+
34
+ const { graphQueries, entityKeyFor } = await import('$backend/database/queries/graph-queries');
35
+ const { retrieve } = await import('./retrieval');
36
+ const { applyFeedback, recordContradictions, linkEntities } = await import('./revise');
37
+ const { invalidateForChanges } = await import('./invalidate');
38
+ const { applyRetention } = await import('./retention');
39
+
40
+ const PROJECT = 'project-a';
41
+
42
+ function memory(label: string, overrides: Record<string, unknown> = {}) {
43
+ return graphQueries.upsert({
44
+ kind: 'episodic',
45
+ subkind: 'decision',
46
+ projectId: PROJECT,
47
+ label,
48
+ ...overrides
49
+ } as Parameters<typeof graphQueries.upsert>[0]);
50
+ }
51
+
52
+ function file(path: string) {
53
+ return graphQueries.upsert({
54
+ kind: 'structural',
55
+ subkind: 'file',
56
+ projectId: PROJECT,
57
+ label: path,
58
+ path
59
+ });
60
+ }
61
+
62
+ /** Backdate a node so age-gated behaviour can be exercised without waiting. */
63
+ function backdate(id: string, days: number): void {
64
+ db.prepare(
65
+ `UPDATE graph_nodes SET updated_at = datetime('now', ?), archived_at =
66
+ CASE WHEN archived_at IS NULL THEN NULL ELSE datetime('now', ?) END
67
+ WHERE id = ?`
68
+ ).run(`-${days} days`, `-${days} days`, id);
69
+ }
70
+
71
+ beforeEach(() => {
72
+ db = new Database(':memory:');
73
+ db.exec('PRAGMA foreign_keys = ON');
74
+ migration066.up(db as unknown as DatabaseConnection);
75
+ // The queue's orphan sweep joins against sessions; a stub is enough here.
76
+ db.exec(`CREATE TABLE IF NOT EXISTS chat_sessions (id TEXT PRIMARY KEY)`);
77
+ });
78
+
79
+ describe('supersession', () => {
80
+ it('removes the old belief from retrieval but keeps it readable', () => {
81
+ const old = memory('The project uses Postgres for storage');
82
+ const current = memory('The project uses SQLite for storage');
83
+
84
+ expect(graphQueries.supersede(old.id, current.id)).toBe(true);
85
+
86
+ const hits = retrieve({ query: 'storage project uses', projectId: PROJECT, expandHops: 0 }).hits;
87
+ expect(hits.map(h => h.node.id)).not.toContain(old.id);
88
+
89
+ // Not archived: it was true once, and the distinction is the point.
90
+ const stored = graphQueries.getById(old.id)!;
91
+ expect(stored.archivedAt).toBeNull();
92
+ expect(stored.supersededBy).toBe(current.id);
93
+ });
94
+
95
+ it('records an edge so the history of a decision stays answerable', () => {
96
+ const old = memory('Sessions are keyed by user id');
97
+ const current = memory('Sessions are keyed by device id');
98
+ graphQueries.supersede(old.id, current.id);
99
+
100
+ const edges = graphQueries.edgesOf(current.id);
101
+ expect(edges.some(e => e.rel === 'supersedes' && e.dstId === old.id)).toBe(true);
102
+ });
103
+
104
+ it('collapses a chain rather than leaving it to be walked at read time', () => {
105
+ // A → B → C must leave A pointing at C. Otherwise "is this current?" needs a
106
+ // recursive walk on a path that runs on every turn.
107
+ const a = memory('v1');
108
+ const b = memory('v2');
109
+ const c = memory('v3');
110
+
111
+ graphQueries.supersede(a.id, b.id);
112
+ graphQueries.supersede(b.id, c.id);
113
+
114
+ expect(graphQueries.getById(a.id)!.supersededBy).toBe(c.id);
115
+ });
116
+
117
+ it('refuses to create a cycle', () => {
118
+ const a = memory('A');
119
+ const b = memory('B');
120
+ graphQueries.supersede(a.id, b.id);
121
+ expect(graphQueries.supersede(b.id, a.id)).toBe(false);
122
+ });
123
+
124
+ it('ignores an id the model was never shown', () => {
125
+ // The model can only relate to memories it actually read. Anything else was
126
+ // hallucinated, and drawing an edge to it would assert a disagreement
127
+ // nothing observed.
128
+ const shown = memory('Shown to the model');
129
+ const unshown = memory('Never shown to the model');
130
+ const fresh = memory('The new belief');
131
+
132
+ recordContradictions(fresh.id, [shown.id, unshown.id], new Set([shown.id]));
133
+
134
+ const edges = graphQueries.edgesOf(fresh.id).filter(e => e.rel === 'contradicts');
135
+ expect(edges.map(e => e.dstId)).toEqual([shown.id]);
136
+ });
137
+
138
+ it('records a contradiction instead of retiring anything', () => {
139
+ // The whole correction: automatic revision NOTICES, the read path CHOOSES.
140
+ // A model reading one turn cannot tell a repealed rule from an exception
141
+ // being taken, and freezing that guess into a destructive write is what let
142
+ // a task-local exception retire a standing prohibition.
143
+ const standing = memory('Never use the agent tool', { subkind: 'preference', scope: 'global', projectId: null });
144
+ const exception = memory('Use the agent tool for this analysis', {
145
+ subkind: 'preference',
146
+ scope: 'session',
147
+ projectId: null
148
+ });
149
+
150
+ recordContradictions(exception.id, [standing.id], new Set([standing.id]));
151
+
152
+ expect(graphQueries.getById(standing.id)!.supersededBy).toBeNull();
153
+ expect(graphQueries.getById(exception.id)!.supersededBy).toBeNull();
154
+ expect(graphQueries.edgesOf(exception.id).some(e => e.rel === 'contradicts' && e.dstId === standing.id)).toBe(
155
+ true
156
+ );
157
+ });
158
+
159
+ it('refuses to let an inference retire something the user stated', () => {
160
+ // The measured production failure, pinned. `source` said "a model wrote
161
+ // both"; the question every consumer was actually asking is "who said it",
162
+ // and nothing could answer it until `asserted_by` existed.
163
+ const stated = memory('Never use the agent tool', { assertedBy: 'user', subkind: 'preference' });
164
+ const inferred = memory('The agent tool is appropriate for deep analysis', {
165
+ assertedBy: 'inferred',
166
+ subkind: 'preference'
167
+ });
168
+
169
+ expect(graphQueries.supersede(stated.id, inferred.id)).toBe(false);
170
+ expect(graphQueries.getById(stated.id)!.supersededBy).toBeNull();
171
+ });
172
+
173
+ it('refuses to let a one-off instruction repeal a standing rule', () => {
174
+ // Independent of authority: an exception taken for one task is not a policy,
175
+ // however recently or confidently it was taken.
176
+ const standing = memory('Always run the checks before committing', { scope: 'global', projectId: null });
177
+ const oneOff = memory('Skip the checks for this commit', { scope: 'session', projectId: null });
178
+
179
+ expect(graphQueries.supersede(standing.id, oneOff.id)).toBe(false);
180
+ expect(graphQueries.getById(standing.id)!.supersededBy).toBeNull();
181
+ });
182
+
183
+ it('leaves superseded memories out of stats and the graph view', () => {
184
+ const old = memory('Old');
185
+ const current = memory('New');
186
+ graphQueries.supersede(old.id, current.id);
187
+
188
+ const stats = graphQueries.stats();
189
+ expect(stats.episodic).toBe(1);
190
+ expect(stats.superseded).toBe(1);
191
+ expect(graphQueries.list({ projectId: PROJECT }).map(n => n.id)).not.toContain(old.id);
192
+ });
193
+ });
194
+
195
+ describe('usefulness feedback', () => {
196
+ it('rewards a memory the next turn actually used', () => {
197
+ const node = memory('Bun is the only supported runtime');
198
+ applyFeedback([{ id: node.id, verdict: 'used' }], new Set([node.id]));
199
+
200
+ const after = graphQueries.getById(node.id)!;
201
+ expect(after.usefulCount).toBe(1);
202
+ expect(after.weight).toBeGreaterThan(node.weight);
203
+ expect(after.confidence).toBeGreaterThan(node.confidence);
204
+ });
205
+
206
+ it('costs confidence when a turn shows a memory to be wrong', () => {
207
+ const node = memory('The default port is 3000', { confidence: 0.8 });
208
+ applyFeedback([{ id: node.id, verdict: 'wrong' }], new Set([node.id]));
209
+ expect(graphQueries.getById(node.id)!.confidence).toBeLessThan(0.8);
210
+ });
211
+
212
+ it('treats "ignored" as weak evidence and does not punish confidence', () => {
213
+ // Most memories offered to a turn have no bearing on it through no fault of
214
+ // their own. Decaying them for that would empty the graph of anything niche.
215
+ const node = memory('Snapshots are gitignore-aware', { confidence: 0.7 });
216
+ applyFeedback([{ id: node.id, verdict: 'ignored' }], new Set([node.id]));
217
+
218
+ const after = graphQueries.getById(node.id)!;
219
+ expect(after.confidence).toBe(0.7);
220
+ expect(after.unhelpfulCount).toBe(1);
221
+ });
222
+
223
+ it('ignores a verdict for a memory that was never injected', () => {
224
+ const node = memory('Never handed to the turn', { confidence: 0.8 });
225
+ applyFeedback([{ id: node.id, verdict: 'wrong' }], new Set(['some-other-id']));
226
+ expect(graphQueries.getById(node.id)!.confidence).toBe(0.8);
227
+ });
228
+ });
229
+
230
+ describe('canonical entities', () => {
231
+ it('collapses differently-worded names onto one key', () => {
232
+ expect(entityKeyFor('Arga Fairuz')).toBe(entityKeyFor('arga fairuz.'));
233
+ expect(entityKeyFor('!')).toBeNull();
234
+ });
235
+
236
+ it('gathers several statements about one person without creating a node', () => {
237
+ // The failure this replaces: five memories about one person sitting as five
238
+ // islands. The fix used to be a stub NODE per subject, which on a real graph
239
+ // made 115 of 208 nodes empty-bodied names. An index answers the same
240
+ // question and adds nothing to the graph.
241
+ const a = memory('Arga prefers Svelte 5 runes', { subkind: 'preference' });
242
+ const b = memory('Arga works full-stack in TypeScript', { subkind: 'entity' });
243
+ const c = memory('Arga is based in Indonesia', { subkind: 'observation' });
244
+
245
+ for (const node of [a, b, c]) linkEntities(node.id, ['Arga']);
246
+
247
+ const about = graphQueries.memoriesAboutEntity('arga').map(n => n.id);
248
+ expect(about).toEqual(expect.arrayContaining([a.id, b.id, c.id]));
249
+
250
+ // And no stub was created for it.
251
+ expect(graphQueries.list({ projectId: null }).filter(n => n.entityKey !== null)).toHaveLength(0);
252
+ });
253
+
254
+ it('keeps spelling variants of one subject on the same key', () => {
255
+ // The old normaliser kept punctuation as a separator, so "Myria Labs" and
256
+ // "MyriaLabs" keyed differently — a dozen of 115 entities on the real graph
257
+ // were pure spelling forks.
258
+ expect(entityKeyFor('Myria Labs')).toBe(entityKeyFor('MyriaLabs'));
259
+ expect(entityKeyFor('Express')).toBe(entityKeyFor('Express.js'));
260
+ expect(entityKeyFor('Vue')).toBe(entityKeyFor('Vue 3'));
261
+ expect(entityKeyFor('Tailwind CSS')).toBe(entityKeyFor('Tailwind CSS v4'));
262
+ // But two different things stay apart: the second is not a version of the first.
263
+ expect(entityKeyFor('Docker')).not.toBe(entityKeyFor('Docker Compose'));
264
+ });
265
+
266
+ it('replaces a memory\'s entities rather than accumulating every phrasing', () => {
267
+ const node = memory('The billing cutover is in March');
268
+ linkEntities(node.id, ['Phoenix', 'Stripe']);
269
+ linkEntities(node.id, ['Phoenix']);
270
+
271
+ expect(graphQueries.entityNamesOf(node.id)).toEqual(['Phoenix']);
272
+ });
273
+ });
274
+
275
+ describe('structural invalidation', () => {
276
+ it('ages an observation about changed code but not the decision behind it', () => {
277
+ const target = file('backend/chat/stream-manager.ts');
278
+ const observation = memory('Stream manager captures the snapshot in its finally block', {
279
+ subkind: 'observation',
280
+ confidence: 0.9
281
+ });
282
+ const decision = memory('Snapshots are captured at stream end so Bash edits are seen', {
283
+ subkind: 'decision',
284
+ confidence: 0.9
285
+ });
286
+ const preference = memory('Arga wants English in all durable text', {
287
+ subkind: 'preference',
288
+ confidence: 0.9
289
+ });
290
+
291
+ for (const node of [observation, decision, preference]) {
292
+ graphQueries.link({ srcId: node.id, dstId: target.id, rel: 'about' });
293
+ }
294
+
295
+ invalidateForChanges({ projectId: PROJECT, changedPaths: ['backend/chat/stream-manager.ts'] });
296
+
297
+ expect(graphQueries.getById(observation.id)!.confidence).toBeLessThan(0.9);
298
+ expect(graphQueries.getById(observation.id)!.staleAt).not.toBeNull();
299
+ // The reason a file changed is not invalidated by the file changing — very
300
+ // often it IS the change.
301
+ expect(graphQueries.getById(decision.id)!.confidence).toBe(0.9);
302
+ expect(graphQueries.getById(preference.id)!.confidence).toBe(0.9);
303
+ });
304
+
305
+ it('never ages a memory a person wrote or pinned', () => {
306
+ const target = file('backend/a.ts');
307
+ const authored = memory('Hand-written note about a.ts', {
308
+ subkind: 'observation',
309
+ confidence: 0.9,
310
+ source: 'user'
311
+ });
312
+ const pinned = memory('Pinned note about a.ts', {
313
+ subkind: 'observation',
314
+ confidence: 0.9,
315
+ pinned: true
316
+ });
317
+ for (const node of [authored, pinned]) {
318
+ graphQueries.link({ srcId: node.id, dstId: target.id, rel: 'about' });
319
+ }
320
+
321
+ invalidateForChanges({ projectId: PROJECT, changedPaths: ['backend/a.ts'] });
322
+
323
+ expect(graphQueries.getById(authored.id)!.confidence).toBe(0.9);
324
+ expect(graphQueries.getById(pinned.id)!.confidence).toBe(0.9);
325
+ });
326
+
327
+ it('retires the nodes of a file that no longer exists', () => {
328
+ // Otherwise BM25 keeps offering a path that is gone, which sends an agent to
329
+ // read a file that was deleted — a specific, repeatable waste of a turn.
330
+ file('backend/gone.ts');
331
+ graphQueries.upsert({
332
+ kind: 'structural',
333
+ subkind: 'symbol',
334
+ projectId: PROJECT,
335
+ label: 'goneHelper',
336
+ path: 'backend/gone.ts',
337
+ symbol: 'goneHelper'
338
+ });
339
+
340
+ const result = invalidateForChanges({
341
+ projectId: PROJECT,
342
+ changedPaths: [],
343
+ deletedPaths: ['backend/gone.ts']
344
+ });
345
+
346
+ expect(result.archived).toBe(2);
347
+ const hits = retrieve({ query: 'goneHelper', projectId: PROJECT, expandHops: 0 }).hits;
348
+ expect(hits).toHaveLength(0);
349
+ });
350
+
351
+ it('clears staleness when the memory is re-observed', () => {
352
+ const target = file('backend/b.ts');
353
+ const node = memory('b.ts exports a queue', { subkind: 'observation', confidence: 0.9 });
354
+ graphQueries.link({ srcId: node.id, dstId: target.id, rel: 'about' });
355
+ invalidateForChanges({ projectId: PROJECT, changedPaths: ['backend/b.ts'] });
356
+ expect(graphQueries.getById(node.id)!.staleAt).not.toBeNull();
357
+
358
+ // Re-extracting the same claim is the evidence that it survived the change.
359
+ memory('b.ts exports a queue', { subkind: 'observation' });
360
+ expect(graphQueries.getById(node.id)!.staleAt).toBeNull();
361
+ });
362
+ });
363
+
364
+ describe('retention', () => {
365
+ it('archives an old auto memory that has never proved anything', () => {
366
+ const node = memory('An inference nobody ever used', { confidence: 0.3 });
367
+ backdate(node.id, 200);
368
+
369
+ applyRetention();
370
+ expect(graphQueries.getById(node.id)!.archivedAt).not.toBeNull();
371
+ });
372
+
373
+ it.each([
374
+ ['user-authored', { source: 'user' as const, confidence: 0.3 }],
375
+ ['pinned', { pinned: true, confidence: 0.3 }],
376
+ ['confident', { confidence: 0.9 }]
377
+ ])('never evicts a %s memory', (_label, overrides) => {
378
+ const node = memory(`Protected: ${_label}`, overrides);
379
+ backdate(node.id, 400);
380
+
381
+ applyRetention();
382
+ expect(graphQueries.getById(node.id)!.archivedAt).toBeNull();
383
+ });
384
+
385
+ it('never evicts a memory that was confirmed useful', () => {
386
+ const node = memory('Low confidence but it worked', { confidence: 0.2 });
387
+ applyFeedback([{ id: node.id, verdict: 'used' }], new Set([node.id]));
388
+ backdate(node.id, 400);
389
+
390
+ applyRetention();
391
+ expect(graphQueries.getById(node.id)!.archivedAt).toBeNull();
392
+ });
393
+
394
+ it('permanently removes an auto node archived long ago', () => {
395
+ const node = memory('Archived and forgotten');
396
+ graphQueries.archive(node.id);
397
+ backdate(node.id, 200);
398
+
399
+ applyRetention();
400
+ expect(graphQueries.getById(node.id)).toBeNull();
401
+ });
402
+
403
+ it('keeps a recently archived node so it can still be restored', () => {
404
+ const node = memory('Archived yesterday');
405
+ graphQueries.archive(node.id);
406
+ backdate(node.id, 1);
407
+
408
+ applyRetention();
409
+ expect(graphQueries.getById(node.id)).not.toBeNull();
410
+ });
411
+ });
412
+
413
+ describe('forgetting and deleting', () => {
414
+ /**
415
+ * Edges deliberately survive archiving — that is what keeps the reasoning trail
416
+ * intact — so a traversal that does not filter walks straight into a memory the
417
+ * user has already forgotten and presents it as a live connection. Retrieval
418
+ * filtered correctly while the inspector and the MCP `neighbours` action did
419
+ * not, which is why forgotten memories kept reappearing.
420
+ */
421
+ it('keeps a forgotten memory out of a neighbour walk', () => {
422
+ const target = file('backend/auth.ts');
423
+ const live = memory('Auth uses short-lived tokens');
424
+ const forgotten = memory('Auth used to use cookies');
425
+ for (const node of [live, forgotten]) {
426
+ graphQueries.link({ srcId: node.id, dstId: target.id, rel: 'about' });
427
+ }
428
+
429
+ graphQueries.archive(forgotten.id);
430
+
431
+ const ids = graphQueries.neighbours(target.id, 1).map(n => n.node.id);
432
+ expect(ids).toContain(live.id);
433
+ expect(ids).not.toContain(forgotten.id);
434
+ // The edge itself is untouched: this is a display rule, not a deletion.
435
+ expect(graphQueries.edgesOf(forgotten.id)).toHaveLength(1);
436
+ });
437
+
438
+ it('keeps a superseded memory out of a neighbour walk', () => {
439
+ const target = file('backend/db.ts');
440
+ const current = memory('Storage is SQLite');
441
+ const old = memory('Storage is Postgres');
442
+ for (const node of [current, old]) {
443
+ graphQueries.link({ srcId: node.id, dstId: target.id, rel: 'about' });
444
+ }
445
+ graphQueries.supersede(old.id, current.id);
446
+
447
+ const ids = graphQueries.neighbours(target.id, 1).map(n => n.node.id);
448
+ expect(ids).not.toContain(old.id);
449
+ });
450
+
451
+ it('lists both the archived and the superseded as forgotten', () => {
452
+ const archived = memory('Wrong from the start');
453
+ const old = memory('True once');
454
+ const current = memory('True now');
455
+ graphQueries.archive(archived.id);
456
+ graphQueries.supersede(old.id, current.id);
457
+
458
+ const ids = graphQueries.listArchived({ projectId: PROJECT }).map(n => n.id);
459
+ expect(ids).toEqual(expect.arrayContaining([archived.id, old.id]));
460
+ expect(ids).not.toContain(current.id);
461
+ expect(graphQueries.countArchived({ projectId: PROJECT })).toBe(2);
462
+ });
463
+
464
+ it('hard-deletes selected nodes and their edges', () => {
465
+ const node = memory('To be deleted');
466
+ const target = file('backend/x.ts');
467
+ graphQueries.link({ srcId: node.id, dstId: target.id, rel: 'about' });
468
+ graphQueries.archive(node.id);
469
+
470
+ expect(graphQueries.deleteNodes([node.id])).toBe(1);
471
+ expect(graphQueries.getById(node.id)).toBeNull();
472
+ expect(graphQueries.edgesOf(target.id)).toHaveLength(0);
473
+ });
474
+
475
+ it('does not orphan a node whose replacement was deleted', () => {
476
+ // Otherwise the older memory keeps a `superseded_by` pointing at nothing,
477
+ // which hides it from every read forever with no way to find out why.
478
+ const old = memory('Older belief');
479
+ const current = memory('Newer belief');
480
+ graphQueries.supersede(old.id, current.id);
481
+
482
+ graphQueries.deleteNodes([current.id]);
483
+ expect(graphQueries.getById(old.id)!.supersededBy).toBeNull();
484
+ });
485
+ });
486
+
487
+ describe('purge', () => {
488
+ it('empties one project and leaves the others alone', () => {
489
+ const mine = memory('Belongs to project A');
490
+ const theirs = graphQueries.upsert({
491
+ kind: 'episodic',
492
+ subkind: 'decision',
493
+ projectId: 'project-b',
494
+ label: 'Belongs to project B'
495
+ });
496
+
497
+ const result = graphQueries.purge([PROJECT]);
498
+ expect(result.nodes).toBeGreaterThan(0);
499
+ expect(graphQueries.getById(mine.id)).toBeNull();
500
+ expect(graphQueries.getById(theirs.id)).not.toBeNull();
501
+ });
502
+
503
+ it('leaves global memories alone when one project is purged', () => {
504
+ // Preferences and conventions were never that repository's to hold, so losing
505
+ // them because one project was cleaned would be a surprise.
506
+ const global = graphQueries.upsert({
507
+ kind: 'episodic',
508
+ subkind: 'preference',
509
+ scope: 'global',
510
+ projectId: null,
511
+ label: 'Writes everything in English'
512
+ });
513
+ memory('Belongs to the project');
514
+
515
+ graphQueries.purge([PROJECT]);
516
+ expect(graphQueries.getById(global.id)).not.toBeNull();
517
+ });
518
+
519
+ it('empties everything when no project is named', () => {
520
+ memory('Project memory');
521
+ graphQueries.upsert({
522
+ kind: 'episodic',
523
+ subkind: 'preference',
524
+ scope: 'global',
525
+ projectId: null,
526
+ label: 'Global memory'
527
+ });
528
+
529
+ graphQueries.purge();
530
+ expect(graphQueries.stats().nodes).toBe(0);
531
+ expect(graphQueries.stats().edges).toBe(0);
532
+ });
533
+
534
+ it('leaves nothing in the lexical index behind', () => {
535
+ // The FTS mirror is not a foreign key, so a purge that forgets it leaves
536
+ // search returning rows whose nodes no longer exist.
537
+ memory('Findable by search', { body: 'something distinctive to match on' });
538
+ graphQueries.purge();
539
+
540
+ expect(retrieve({ query: 'distinctive', projectId: PROJECT }).hits).toHaveLength(0);
541
+ });
542
+ });
543
+
544
+ describe('who wrote it', () => {
545
+ it('records an agent edit as an agent edit', () => {
546
+ // This hard-coded `'user'`, and the MCP `update` action goes through it — so
547
+ // one correction by a model made the node permanently exempt from structural
548
+ // decay, from eviction and from consolidation, while the injected block told
549
+ // every future turn a person had said it.
550
+ const node = memory('The cache is invalidated on write');
551
+ const edited = graphQueries.update(node.id, { label: 'The cache is invalidated on read' }, 'agent');
552
+
553
+ expect(edited!.source).toBe('agent');
554
+ expect(edited!.label).toBe('The cache is invalidated on read');
555
+ });
556
+
557
+ it('leaves a hand-written memory untouched by structural decay', () => {
558
+ const target = file('src/cache.ts');
559
+ const mine = memory('The cache is invalidated on write', { subkind: 'observation', source: 'user' });
560
+ graphQueries.link({ srcId: mine.id, dstId: target.id, rel: 'about' });
561
+
562
+ invalidateForChanges({ projectId: PROJECT, changedPaths: ['src/cache.ts'] });
563
+
564
+ const after = graphQueries.getById(mine.id)!;
565
+ expect(after.staleAt).toBeNull();
566
+ expect(after.confidence).toBe(mine.confidence);
567
+ });
568
+ });
569
+
570
+ describe('structural decay', () => {
571
+ it('does not compound when the same file changes repeatedly', () => {
572
+ // Ten turns of iterating on one file used to multiply an observation's
573
+ // confidence by 0.82 ten times over — 0.14, below the injection floor — so an
574
+ // ordinary afternoon silently destroyed everything known about whatever was
575
+ // being worked on.
576
+ const target = file('src/stream.ts');
577
+ const note = memory('The stream captures its snapshot in a finally block', {
578
+ subkind: 'observation',
579
+ confidence: 0.9
580
+ });
581
+ graphQueries.link({ srcId: note.id, dstId: target.id, rel: 'about' });
582
+
583
+ for (let turn = 0; turn < 10; turn++) {
584
+ invalidateForChanges({ projectId: PROJECT, changedPaths: ['src/stream.ts'] });
585
+ }
586
+
587
+ const after = graphQueries.getById(note.id)!;
588
+ // Exactly one application of the observation rate, not ten.
589
+ expect(after.confidence).toBeCloseTo(0.9 * 0.82, 5);
590
+ expect(after.staleAt).not.toBeNull();
591
+ });
592
+
593
+ it('ages it again once the cool-off has passed', () => {
594
+ const target = file('src/stream.ts');
595
+ const note = memory('An observation about the stream', { subkind: 'observation', confidence: 0.9 });
596
+ graphQueries.link({ srcId: note.id, dstId: target.id, rel: 'about' });
597
+
598
+ invalidateForChanges({ projectId: PROJECT, changedPaths: ['src/stream.ts'] });
599
+ db.prepare(`UPDATE graph_nodes SET stale_at = datetime('now', '-2 days') WHERE id = ?`).run(note.id);
600
+ invalidateForChanges({ projectId: PROJECT, changedPaths: ['src/stream.ts'] });
601
+
602
+ expect(graphQueries.getById(note.id)!.confidence).toBeCloseTo(0.9 * 0.82 * 0.82, 5);
603
+ });
604
+ });
605
+
606
+ describe('restoring', () => {
607
+ it('undoes a supersession, not only an archive', () => {
608
+ // Supersession is a judgement a model made while reading a transcript.
609
+ // Leaving it as the one thing a user could not undo meant their only recourse
610
+ // against a wrong revision was permanent deletion.
611
+ const old = memory('Deploys go out on Fridays');
612
+ const current = memory('Deploys go out on Tuesdays');
613
+ graphQueries.supersede(old.id, current.id);
614
+
615
+ expect(graphQueries.restoreNodes([old.id])).toBe(1);
616
+
617
+ const after = graphQueries.getById(old.id)!;
618
+ expect(after.supersededBy).toBeNull();
619
+ expect(after.archivedAt).toBeNull();
620
+ // The edge goes with it: leaving it would draw a claim nothing is making.
621
+ expect(graphQueries.edgesOf(current.id).some(e => e.rel === 'supersedes')).toBe(false);
622
+ });
623
+
624
+ it('puts a restored memory back into search', () => {
625
+ const node = memory('Findable again', { body: 'a distinctive phrase to match on' });
626
+ graphQueries.archive(node.id);
627
+ expect(retrieve({ query: 'distinctive', projectId: PROJECT }).hits).toHaveLength(0);
628
+
629
+ graphQueries.restoreNodes([node.id]);
630
+ expect(retrieve({ query: 'distinctive', projectId: PROJECT }).hits.map(h => h.node.id)).toContain(node.id);
631
+ });
632
+
633
+ it('restores a whole selection in one call', () => {
634
+ const a = memory('First');
635
+ const b = memory('Second');
636
+ graphQueries.archive(a.id);
637
+ graphQueries.archive(b.id);
638
+
639
+ expect(graphQueries.restoreNodes([a.id, b.id])).toBe(2);
640
+ expect(graphQueries.getById(a.id)!.archivedAt).toBeNull();
641
+ expect(graphQueries.getById(b.id)!.archivedAt).toBeNull();
642
+ });
643
+ });
644
+
645
+ describe('bounding the structural half', () => {
646
+ it('removes symbols nothing refers to and nothing has touched', () => {
647
+ // The structural half is what actually grows without bound — a node per
648
+ // changed file, per directory and up to twenty-five per file's symbols, every
649
+ // turn — and none of the episodic retention queries look at it at all.
650
+ const symbol = graphQueries.upsert({
651
+ kind: 'structural',
652
+ subkind: 'symbol',
653
+ projectId: PROJECT,
654
+ label: 'forgottenHelper',
655
+ path: 'src/old.ts',
656
+ symbol: 'forgottenHelper'
657
+ });
658
+ backdate(symbol.id, 200);
659
+
660
+ expect(graphQueries.pruneStructural({ maxAgeDays: 120, limit: 100 })).toBe(1);
661
+ expect(graphQueries.getById(symbol.id)).toBeNull();
662
+ });
663
+
664
+ it('spares a symbol a memory is about', () => {
665
+ // Deleting it would sever the `about` edge, which is the join both halves of
666
+ // the graph exist for.
667
+ const symbol = graphQueries.upsert({
668
+ kind: 'structural',
669
+ subkind: 'symbol',
670
+ projectId: PROJECT,
671
+ label: 'loadBearing',
672
+ path: 'src/core.ts',
673
+ symbol: 'loadBearing'
674
+ });
675
+ const note = memory('loadBearing must stay synchronous');
676
+ graphQueries.link({ srcId: note.id, dstId: symbol.id, rel: 'about' });
677
+ backdate(symbol.id, 200);
678
+
679
+ expect(graphQueries.pruneStructural({ maxAgeDays: 120, limit: 100 })).toBe(0);
680
+ expect(graphQueries.getById(symbol.id)).not.toBeNull();
681
+ });
682
+
683
+ it('spares file nodes, however old', () => {
684
+ // A file node is what a path lookup resolves to, and `invalidate.ts` already
685
+ // retires files the moment the disk says they are gone — better evidence
686
+ // than age.
687
+ const node = file('src/rarely-touched.ts');
688
+ backdate(node.id, 400);
689
+
690
+ expect(graphQueries.pruneStructural({ maxAgeDays: 120, limit: 100 })).toBe(0);
691
+ expect(graphQueries.getById(node.id)).not.toBeNull();
692
+ });
693
+ });