@myrialabs/clopen 0.4.26 → 0.4.28

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 (98) 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/claude/message-converter.ts +5 -24
  15. package/backend/engine/adapters/copilot/stream.ts +37 -1
  16. package/backend/engine/adapters/pi/models.ts +19 -7
  17. package/backend/engine/adapters/pi/stream.ts +2 -1
  18. package/backend/engine/docs/adapter-contract.md +25 -8
  19. package/backend/engine/docs/adding-an-engine.md +40 -4
  20. package/backend/engine/docs/frontend-and-chat.md +66 -1
  21. package/backend/engine/docs/lessons-learned.md +165 -6
  22. package/backend/engine/docs/quick-reference.md +10 -0
  23. package/backend/engine/docs/stack.md +10 -0
  24. package/backend/engine/docs/websocket-routes.md +15 -1
  25. package/backend/engine/engine-setup.ts +1 -1
  26. package/backend/engine/index.test.ts +186 -0
  27. package/backend/engine/index.ts +117 -71
  28. package/backend/engine/install-recipes.test.ts +105 -0
  29. package/backend/engine/install-recipes.ts +4 -1
  30. package/backend/index.ts +9 -0
  31. package/backend/mcp/internal/config.ts +6 -0
  32. package/backend/mcp/internal/servers/index.ts +2 -0
  33. package/backend/mcp/internal/servers/memory-graph/description.ts +33 -0
  34. package/backend/mcp/internal/servers/memory-graph/format.ts +45 -0
  35. package/backend/mcp/internal/servers/memory-graph/index.ts +52 -0
  36. package/backend/mcp/internal/servers/memory-graph/runner.ts +342 -0
  37. package/backend/mcp/internal/servers/memory-graph/schema.ts +140 -0
  38. package/backend/memory/README.md +432 -0
  39. package/backend/memory/bootstrap.ts +101 -0
  40. package/backend/memory/compose.test.ts +198 -0
  41. package/backend/memory/compose.ts +343 -0
  42. package/backend/memory/config.ts +100 -0
  43. package/backend/memory/consolidate.ts +280 -0
  44. package/backend/memory/context.test.ts +321 -0
  45. package/backend/memory/context.ts +451 -0
  46. package/backend/memory/embedding/embedder.test.ts +141 -0
  47. package/backend/memory/embedding/embedder.ts +269 -0
  48. package/backend/memory/embedding/index.ts +17 -0
  49. package/backend/memory/embedding/install.ts +254 -0
  50. package/backend/memory/embedding/paths.ts +101 -0
  51. package/backend/memory/embedding/vector-cache.ts +270 -0
  52. package/backend/memory/extract/episodic.ts +725 -0
  53. package/backend/memory/extract/index.ts +133 -0
  54. package/backend/memory/extract/languages.ts +176 -0
  55. package/backend/memory/extract/scheduler.test.ts +352 -0
  56. package/backend/memory/extract/scheduler.ts +406 -0
  57. package/backend/memory/extract/structural.test.ts +215 -0
  58. package/backend/memory/extract/structural.ts +364 -0
  59. package/backend/memory/index.ts +37 -0
  60. package/backend/memory/indexer.ts +150 -0
  61. package/backend/memory/invalidate.ts +134 -0
  62. package/backend/memory/judge.ts +285 -0
  63. package/backend/memory/maintenance.ts +132 -0
  64. package/backend/memory/model.ts +91 -0
  65. package/backend/memory/notify.ts +102 -0
  66. package/backend/memory/readiness.ts +74 -0
  67. package/backend/memory/redact.test.ts +101 -0
  68. package/backend/memory/redact.ts +133 -0
  69. package/backend/memory/retention.ts +139 -0
  70. package/backend/memory/retrieval.eval.test.ts +301 -0
  71. package/backend/memory/retrieval.test.ts +1023 -0
  72. package/backend/memory/retrieval.ts +707 -0
  73. package/backend/memory/revise.test.ts +693 -0
  74. package/backend/memory/revise.ts +400 -0
  75. package/backend/memory/time.ts +31 -0
  76. package/backend/memory/view.ts +164 -0
  77. package/backend/shipped-runtime-imports.test.ts +228 -0
  78. package/backend/ws/engine/claude/accounts.ts +4 -12
  79. package/backend/ws/engine/codex/accounts.ts +4 -13
  80. package/backend/ws/engine/pty-output.test.ts +37 -0
  81. package/backend/ws/engine/pty-output.ts +43 -0
  82. package/backend/ws/index.ts +5 -1
  83. package/backend/ws/memory/crud.ts +631 -0
  84. package/backend/ws/memory/index.ts +41 -0
  85. package/backend/ws/sessions/crud.ts +10 -0
  86. package/backend/ws/snapshot/restore.ts +38 -4
  87. package/dist/assets/graph-layout.worker-CRFqN7ZQ.js +1 -0
  88. package/dist/assets/{index-DYa-GDsb.js → index-BujQYGBm.js} +1 -1
  89. package/dist/assets/{index-B6QGUN03.js → index-DRMOgS9y.js} +1 -1
  90. package/dist/assets/{main-Dznkfxsd.js → main-BrYtWn-4.js} +832 -423
  91. package/dist/assets/main-BrqMMMRX.css +1 -0
  92. package/dist/index.html +2 -2
  93. package/package.json +8 -2
  94. package/shared/types/database/connection.ts +9 -0
  95. package/shared/types/memory.ts +519 -0
  96. package/shared/utils/logger.ts +1 -0
  97. package/dist/assets/main-Dh-MTGNR.css +0 -1
  98. package/shared/utils/anonymous-user.ts +0 -168
@@ -0,0 +1,1764 @@
1
+ /**
2
+ * Memory Graph Queries
3
+ *
4
+ * CRUD and traversal for `graph_nodes` / `graph_edges` / `graph_vectors` plus the
5
+ * `graph_nodes_fts` mirror (migration 066). Instance-global and admin-managed —
6
+ * no `user_id` column — mirroring skills / mcp_servers / subagents.
7
+ *
8
+ * Two invariants live here rather than in callers:
9
+ *
10
+ * 1. **Writes upsert on `digest`.** Extraction runs every turn and would
11
+ * otherwise re-add the same memory endlessly. A repeat write reinforces the
12
+ * existing node (bumping `weight`) instead of duplicating it.
13
+ * 2. **The FTS mirror is never updated by callers.** Every mutation that
14
+ * changes indexed text syncs `graph_nodes_fts` in the same transaction, the
15
+ * way message-queries owns `messages_fts`.
16
+ *
17
+ * Vectors are written separately (see backend/memory/indexer.ts) because they
18
+ * depend on the on-demand embedding artifact, which may not be installed yet.
19
+ */
20
+
21
+ import { nanoid } from 'nanoid';
22
+ import { getDatabase } from '../index';
23
+ import { debug } from '$shared/utils/logger';
24
+ import { AUTHORITY_RANK } from '$shared/types/memory';
25
+ import type {
26
+ GraphEdge,
27
+ GraphEdgeInput,
28
+ GraphNode,
29
+ GraphNodeInput,
30
+ GraphNodeKind,
31
+ GraphRelation,
32
+ GraphScope,
33
+ GraphSource,
34
+ GraphStats
35
+ } from '$shared/types/memory';
36
+
37
+ interface GraphNodeRow {
38
+ id: string;
39
+ kind: GraphNodeKind;
40
+ subkind: string;
41
+ scope: GraphScope;
42
+ project_id: string | null;
43
+ session_id: string | null;
44
+ label: string;
45
+ body: string;
46
+ path: string | null;
47
+ symbol: string | null;
48
+ language: string | null;
49
+ digest: string;
50
+ confidence: number;
51
+ weight: number;
52
+ access_count: number;
53
+ source: string;
54
+ asserted_by: string;
55
+ reach: string;
56
+ reach_judged: number;
57
+ pinned: number;
58
+ archived_at: string | null;
59
+ created_at: string;
60
+ updated_at: string;
61
+ accessed_at: string | null;
62
+ superseded_by: string | null;
63
+ useful_count: number;
64
+ unhelpful_count: number;
65
+ stale_at: string | null;
66
+ entity_key: string | null;
67
+ /** rowid of this node's row in `graph_nodes_fts` — see `syncFts`. */
68
+ fts_rowid: number | null;
69
+ }
70
+
71
+ interface GraphEdgeRow {
72
+ id: number;
73
+ src_id: string;
74
+ dst_id: string;
75
+ rel: GraphRelation;
76
+ weight: number;
77
+ source: string;
78
+ created_at: string;
79
+ }
80
+
81
+ function toNode(row: GraphNodeRow): GraphNode {
82
+ return {
83
+ id: row.id,
84
+ kind: row.kind,
85
+ subkind: row.subkind as GraphNode['subkind'],
86
+ scope: row.scope,
87
+ projectId: row.project_id,
88
+ sessionId: row.session_id,
89
+ label: row.label,
90
+ body: row.body,
91
+ path: row.path,
92
+ symbol: row.symbol,
93
+ language: row.language,
94
+ digest: row.digest,
95
+ confidence: row.confidence,
96
+ weight: row.weight,
97
+ accessCount: row.access_count,
98
+ source: row.source as GraphNode['source'],
99
+ assertedBy: (row.asserted_by ?? 'inferred') as GraphNode['assertedBy'],
100
+ reach: (row.reach ?? 'here') as GraphNode['reach'],
101
+ reachJudged: row.reach_judged === 1,
102
+ pinned: row.pinned === 1,
103
+ archivedAt: row.archived_at,
104
+ createdAt: row.created_at,
105
+ updatedAt: row.updated_at,
106
+ accessedAt: row.accessed_at,
107
+ supersededBy: row.superseded_by ?? null,
108
+ usefulCount: row.useful_count ?? 0,
109
+ unhelpfulCount: row.unhelpful_count ?? 0,
110
+ staleAt: row.stale_at ?? null,
111
+ entityKey: row.entity_key ?? null
112
+ };
113
+ }
114
+
115
+ function toEdge(row: GraphEdgeRow): GraphEdge {
116
+ return {
117
+ id: row.id,
118
+ srcId: row.src_id,
119
+ dstId: row.dst_id,
120
+ rel: row.rel,
121
+ weight: row.weight,
122
+ source: row.source as GraphEdge['source'],
123
+ createdAt: row.created_at
124
+ };
125
+ }
126
+
127
+ /**
128
+ * Text a node contributes to the lexical index: its label, its body, and its
129
+ * path/symbol. Paths are also split on separators so `sdk-loader` matches
130
+ * `backend/engine/sdk-loader.ts` — BM25 tokenizes on word boundaries and would
131
+ * otherwise treat the whole path as one opaque term.
132
+ */
133
+ function indexedText(node: Pick<GraphNode, 'label' | 'body' | 'path' | 'symbol'> & { entityNames?: string[] }): string {
134
+ const parts = [node.label, node.body];
135
+ if (node.symbol) parts.push(node.symbol);
136
+ // The entities a memory names used to be findable because each was a node of
137
+ // its own. They are an attribute now, so the memories that name them have to
138
+ // carry them into the lexical index — otherwise "what do we know about Bun"
139
+ // only matches memories that happen to spell Bun in their prose.
140
+ if (node.entityNames?.length) parts.push(node.entityNames.join(' '));
141
+ if (node.path) {
142
+ parts.push(node.path);
143
+ parts.push(node.path.split(/[/\\._-]+/).filter(Boolean).join(' '));
144
+ }
145
+ return parts.filter(Boolean).join('\n').trim();
146
+ }
147
+
148
+ /**
149
+ * Identity algorithm version, stored per row as `digest_version`.
150
+ *
151
+ * Bump when the basis or the hash changes. Rows at an older version can then be
152
+ * re-derived deliberately instead of silently forking into duplicates the next
153
+ * time extraction sees the same fact.
154
+ */
155
+ export const DIGEST_VERSION = 2;
156
+
157
+ /**
158
+ * Most terms one FTS5 MATCH may carry. See `buildFtsQuery` for why there is a
159
+ * bound at all; 32 is comfortably more than any real question and far below the
160
+ * point where the OR tree becomes a problem.
161
+ */
162
+ const MAX_FTS_TERMS = 32;
163
+
164
+ /**
165
+ * Canonical form of an entity name: the thing five differently-worded mentions
166
+ * of one subject must agree on.
167
+ *
168
+ * Separators are REMOVED rather than normalised, and a trailing version is
169
+ * dropped. The first version replaced punctuation with a hyphen and kept it,
170
+ * which meant the key still encoded how someone happened to type the name — and
171
+ * against a real graph that forked "Myria Labs" from "MyriaLabs", "Express" from
172
+ * "Express.js", "Vue" from "Vue 3", "Tailwind" from "Tailwind CSS v4" and
173
+ * "PostgreSQL" from "PostgreSQL 15". A dozen of 115 entities were pure spelling
174
+ * duplicates.
175
+ *
176
+ * Version stripping is deliberately shallow — a trailing number only. "Docker"
177
+ * and "Docker Compose" stay apart, because they are different things and the
178
+ * second is not a version of the first.
179
+ */
180
+ export function entityKeyFor(name: string): string | null {
181
+ const key = name
182
+ .normalize('NFKD')
183
+ .replace(/[̀-ͯ]/g, '')
184
+ .toLowerCase()
185
+ .replace(/\s+v?\d+(\.\d+)*$/, '')
186
+ .replace(/[^a-z0-9]+/g, '')
187
+ // "Express" and "Express.js" are one library; so are Node/Node.js and
188
+ // Vue/Vue.js. Narrow on purpose — only a trailing `js`, and only when
189
+ // something is left. The known cost is that an entity genuinely ending in
190
+ // those two letters would fold into its stem, which no real technology name
191
+ // in this corpus does.
192
+ .replace(/js$/, '');
193
+ return key.length >= 2 ? key.slice(0, 120) : null;
194
+ }
195
+
196
+ /**
197
+ * Stable identity for a node when the caller does not supply one. Structural
198
+ * nodes are identified by what they point at; episodic nodes by their normalized
199
+ * claim, so the same decision phrased with different whitespace or casing
200
+ * reinforces rather than duplicates.
201
+ *
202
+ * SHA-256 rather than `Bun.hash`. The hash is PERSISTED as a node's identity, so
203
+ * it has to mean the same thing after a runtime upgrade — and Bun documents no
204
+ * cross-version stability guarantee for `Bun.hash`. A seed change there would not
205
+ * fail loudly; it would silently re-duplicate every memory in the graph on the
206
+ * next extraction, which is close to the worst failure this store can have.
207
+ */
208
+ export function deriveDigest(input: GraphNodeInput): string {
209
+ // A canonical entity IS its key — that is the whole point. Two statements
210
+ // about the same person must land on one node no matter how they are phrased,
211
+ // so content plays no part in the identity of an entity node.
212
+ if (input.entityKey) {
213
+ return sha(`entity:${input.entityKey}`);
214
+ }
215
+
216
+ let basis: string;
217
+ if (input.kind === 'structural') {
218
+ // Identity is what the node points AT, so the label may be rewritten (a file
219
+ // renamed in the graph's display) without splitting it into a second node.
220
+ //
221
+ // Dependency nodes have neither path nor symbol — a package is not a
222
+ // location in the repository — so they must key on their name. Without that
223
+ // fallback every dependency in the workspace collapses onto one shared
224
+ // digest and each new package silently overwrites the previous one.
225
+ const located = `${input.path ?? ''}:${input.symbol ?? ''}`;
226
+ const identity = located === ':' ? input.label.trim().toLowerCase() : located;
227
+ basis = `${input.subkind}:${identity}`;
228
+ } else {
229
+ basis = `${input.subkind}:${(input.label + ' ' + (input.body ?? '')).toLowerCase().replace(/\s+/g, ' ').trim()}`;
230
+ }
231
+ return sha(basis);
232
+ }
233
+
234
+ /** 20 hex characters of SHA-256 — 80 bits, far past collision risk at this scale. */
235
+ function sha(basis: string): string {
236
+ return Bun.SHA256.hash(basis, 'hex').slice(0, 20);
237
+ }
238
+
239
+ /**
240
+ * What a caller may narrow a listing by.
241
+ *
242
+ * `subkinds` and `sources` were added because a two-way kind toggle could not
243
+ * answer real questions of the graph: "show only what the user stated, not what
244
+ * was inferred", or "only the failures". Both are attributes the store has always
245
+ * carried and nothing could filter on.
246
+ */
247
+ export interface GraphListFilter {
248
+ /** `undefined` = every project; `null` = global-scope nodes only. */
249
+ projectId?: string | null;
250
+ /**
251
+ * A SET of projects, from the modal's multi-select. Takes precedence over
252
+ * `projectId`. An empty array means global only — nothing selected is a
253
+ * narrowing, not an absence of one.
254
+ */
255
+ projectIds?: string[];
256
+ kinds?: GraphNodeKind[];
257
+ subkinds?: string[];
258
+ scopes?: GraphScope[];
259
+ sources?: GraphSource[];
260
+ includeArchived?: boolean;
261
+ includeSuperseded?: boolean;
262
+ /** Show ONLY archived nodes — what the "forgotten" list is. */
263
+ archivedOnly?: boolean;
264
+ }
265
+
266
+ /**
267
+ * The WHERE fragment shared by `list`, `count` and `listArchived`.
268
+ *
269
+ * Kept in one place because the three drifting apart is how a node ends up
270
+ * counted but not shown, or shown in the graph after being forgotten.
271
+ */
272
+ function appendProjectFilter(filter: GraphListFilter, where: string[], params: unknown[]): void {
273
+ if (filter.projectIds !== undefined) {
274
+ // Nothing selected is "global only", not "everything": the user has narrowed
275
+ // away every repository, and what remains is what was never a repository's.
276
+ if (filter.projectIds.length === 0) where.push(`project_id IS NULL`);
277
+ else {
278
+ where.push(`(project_id IN (${filter.projectIds.map(() => '?').join(',')}) OR project_id IS NULL)`);
279
+ params.push(...filter.projectIds);
280
+ }
281
+ return;
282
+ }
283
+ if (filter.projectId === undefined) return;
284
+ if (filter.projectId === null) {
285
+ where.push(`project_id IS NULL`);
286
+ return;
287
+ }
288
+ // A project view also shows the global memories that apply to it —
289
+ // conventions and preferences are part of that project's context.
290
+ where.push(`(project_id = ? OR project_id IS NULL)`);
291
+ params.push(filter.projectId);
292
+ }
293
+
294
+ function buildNodeFilter(filter: GraphListFilter): { where: string[]; params: unknown[] } {
295
+ const where: string[] = [];
296
+ const params: unknown[] = [];
297
+
298
+ appendProjectFilter(filter, where, params);
299
+ if (filter.kinds?.length) {
300
+ where.push(`kind IN (${filter.kinds.map(() => '?').join(',')})`);
301
+ params.push(...filter.kinds);
302
+ }
303
+ if (filter.subkinds?.length) {
304
+ where.push(`subkind IN (${filter.subkinds.map(() => '?').join(',')})`);
305
+ params.push(...filter.subkinds);
306
+ }
307
+ if (filter.scopes?.length) {
308
+ where.push(`scope IN (${filter.scopes.map(() => '?').join(',')})`);
309
+ params.push(...filter.scopes);
310
+ }
311
+ if (filter.sources?.length) {
312
+ where.push(`source IN (${filter.sources.map(() => '?').join(',')})`);
313
+ params.push(...filter.sources);
314
+ }
315
+
316
+ if (filter.archivedOnly) where.push(`archived_at IS NOT NULL`);
317
+ else if (!filter.includeArchived) where.push(`archived_at IS NULL`);
318
+
319
+ // The graph view shows current beliefs. Superseded ones stay reachable by
320
+ // walking a `supersedes` edge from the node that replaced them, which is where
321
+ // that history belongs.
322
+ if (!filter.includeSuperseded) where.push(`superseded_by IS NULL`);
323
+
324
+ return { where, params };
325
+ }
326
+
327
+ export const graphQueries = {
328
+ // ── nodes ───────────────────────────────────────────────────────────────
329
+
330
+ /**
331
+ * Insert a node, or reinforce the existing one with the same digest.
332
+ *
333
+ * Reinforcement is what keeps a re-observed memory ranked above a one-off:
334
+ * `weight` grows sub-linearly (capped) and confidence takes the higher of the
335
+ * two. The label/body are refreshed because a later extraction usually phrases
336
+ * the same claim better, but a user-authored node is never overwritten by an
337
+ * automatic one — hand-written memory outranks inference.
338
+ */
339
+ upsert(input: GraphNodeInput): GraphNode {
340
+ const db = getDatabase();
341
+ const digest = input.digest ?? deriveDigest(input);
342
+ const projectId = input.projectId ?? null;
343
+
344
+ const existing = db
345
+ .prepare(
346
+ `SELECT * FROM graph_nodes
347
+ WHERE COALESCE(project_id, '') = COALESCE(?, '') AND kind = ? AND digest = ?`
348
+ )
349
+ .get(projectId, input.kind, digest) as GraphNodeRow | null;
350
+
351
+ if (existing) {
352
+ const source = input.source ?? 'agent';
353
+ const keepText = existing.source === 'user' && source !== 'user';
354
+ const label = keepText ? existing.label : input.label;
355
+ const body = keepText ? existing.body : (input.body ?? existing.body);
356
+
357
+ // Authority only ever climbs. A memory the user stated, re-observed later
358
+ // by a model that could not tell who said it, must not quietly demote to
359
+ // `inferred` and lose its place in the standing-instructions block.
360
+ const assertedBy =
361
+ AUTHORITY_RANK[(input.assertedBy ?? 'inferred') as GraphNode['assertedBy']] >
362
+ AUTHORITY_RANK[(existing.asserted_by ?? 'inferred') as GraphNode['assertedBy']]
363
+ ? (input.assertedBy as string)
364
+ : (existing.asserted_by ?? 'inferred');
365
+
366
+ // Reach climbs too: once something has been judged to travel, a later
367
+ // write that failed to notice does not lock it back into one repository.
368
+ const reach = input.reach === 'anywhere' || existing.reach === 'anywhere' ? 'anywhere' : 'here';
369
+ const reachJudged = input.reachJudged || existing.reach_judged === 1 ? 1 : 0;
370
+
371
+ // `stale_at` is cleared: the memory has just been re-observed, which is
372
+ // exactly the evidence that it survived whatever code change marked it
373
+ // stale. `superseded_by` is deliberately NOT cleared — that was a
374
+ // judgement about which of two beliefs is current, and re-stating the old
375
+ // one is not grounds to overturn it. Revision has to overturn revision.
376
+ db.prepare(
377
+ `UPDATE graph_nodes
378
+ SET label = ?, body = ?, weight = MIN(weight + 0.25, 10.0),
379
+ confidence = MAX(confidence, ?), stale_at = NULL,
380
+ asserted_by = ?, reach = ?, reach_judged = ?,
381
+ updated_at = CURRENT_TIMESTAMP
382
+ WHERE id = ?`
383
+ ).run(
384
+ label,
385
+ body,
386
+ input.confidence ?? existing.confidence,
387
+ assertedBy,
388
+ reach,
389
+ reachJudged,
390
+ existing.id
391
+ );
392
+
393
+ this.syncFts(existing.id);
394
+ return this.getById(existing.id)!;
395
+ }
396
+
397
+ const id = nanoid();
398
+ db.prepare(
399
+ `INSERT INTO graph_nodes (
400
+ id, kind, subkind, scope, project_id, session_id, label, body,
401
+ path, symbol, language, digest, confidence, source, pinned,
402
+ entity_key, digest_version, asserted_by, reach, reach_judged
403
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`
404
+ ).run(
405
+ id,
406
+ input.kind,
407
+ input.subkind,
408
+ input.scope ?? (projectId ? 'project' : 'global'),
409
+ projectId,
410
+ input.sessionId ?? null,
411
+ input.label,
412
+ input.body ?? '',
413
+ input.path ?? null,
414
+ input.symbol ?? null,
415
+ input.language ?? null,
416
+ digest,
417
+ input.confidence ?? 0.5,
418
+ input.source ?? 'agent',
419
+ input.pinned ? 1 : 0,
420
+ input.entityKey ?? null,
421
+ DIGEST_VERSION,
422
+ input.assertedBy ?? 'inferred',
423
+ // Structural nodes are a repository's files and never travel, whatever a
424
+ // caller passes.
425
+ input.kind === 'structural' ? 'here' : (input.reach ?? 'here'),
426
+ input.kind === 'structural' || input.reachJudged ? 1 : 0
427
+ );
428
+
429
+ this.syncFts(id);
430
+ return this.getById(id)!;
431
+ },
432
+
433
+ getById(id: string): GraphNode | null {
434
+ const row = getDatabase().prepare(`SELECT * FROM graph_nodes WHERE id = ?`).get(id) as GraphNodeRow | null;
435
+ return row ? toNode(row) : null;
436
+ },
437
+
438
+ getByIds(ids: string[]): GraphNode[] {
439
+ if (ids.length === 0) return [];
440
+ const placeholders = ids.map(() => '?').join(',');
441
+ const rows = getDatabase()
442
+ .prepare(`SELECT * FROM graph_nodes WHERE id IN (${placeholders})`)
443
+ .all(...ids) as GraphNodeRow[];
444
+ return rows.map(toNode);
445
+ },
446
+
447
+ /** Structural node for a repo-relative path, when one exists. */
448
+ getByPath(projectId: string | null, path: string): GraphNode | null {
449
+ const row = getDatabase()
450
+ .prepare(
451
+ `SELECT * FROM graph_nodes
452
+ WHERE COALESCE(project_id, '') = COALESCE(?, '') AND kind = 'structural' AND path = ?
453
+ ORDER BY CASE subkind WHEN 'file' THEN 0 ELSE 1 END
454
+ LIMIT 1`
455
+ )
456
+ .get(projectId, path) as GraphNodeRow | null;
457
+ return row ? toNode(row) : null;
458
+ },
459
+
460
+ /**
461
+ * Edit the human-facing fields of a node (the graph editor's save path).
462
+ *
463
+ * `source` is a PARAMETER, not a constant, and getting that wrong was quietly
464
+ * expensive. This used to hard-code `'user'`, and the MCP `update` action goes
465
+ * through here — so one edit by an agent made the node permanently exempt from
466
+ * structural decay (`markStale` skips `source = 'user'`), from eviction, and
467
+ * from consolidation, while the injected block advertised it to every future
468
+ * turn as "stated by user". A model's correction was being given a human's
469
+ * authority.
470
+ */
471
+ update(
472
+ id: string,
473
+ patch: Partial<Pick<GraphNode, 'label' | 'body' | 'subkind' | 'scope' | 'confidence' | 'pinned' | 'reach'>>,
474
+ source: GraphSource = 'user'
475
+ ): GraphNode | null {
476
+ const db = getDatabase();
477
+ const current = this.getById(id);
478
+ if (!current) return null;
479
+
480
+ db.prepare(
481
+ `UPDATE graph_nodes
482
+ SET label = ?, body = ?, subkind = ?, scope = ?, confidence = ?, pinned = ?,
483
+ source = ?, asserted_by = ?, reach = ?, reach_judged = 1,
484
+ updated_at = CURRENT_TIMESTAMP
485
+ WHERE id = ?`
486
+ ).run(
487
+ patch.label ?? current.label,
488
+ patch.body ?? current.body,
489
+ patch.subkind ?? current.subkind,
490
+ patch.scope ?? current.scope,
491
+ patch.confidence ?? current.confidence,
492
+ (patch.pinned ?? current.pinned) ? 1 : 0,
493
+ source,
494
+ // A person editing a memory adopts it; an agent editing one does not get
495
+ // to promote it to the user's word. Same reasoning as `source` being a
496
+ // parameter here rather than a constant.
497
+ source === 'user' ? 'user' : current.assertedBy,
498
+ current.kind === 'structural' ? 'here' : (patch.reach ?? current.reach),
499
+ id
500
+ );
501
+
502
+ // A hand-edited node's text no longer matches its derived digest; leaving
503
+ // the old one would let the next automatic extraction of the ORIGINAL text
504
+ // overwrite the edit. Re-deriving re-parents identity onto what the user
505
+ // actually wrote.
506
+ const updated = this.getById(id)!;
507
+ if (updated.kind === 'episodic') {
508
+ const digest = deriveDigest({
509
+ kind: updated.kind,
510
+ subkind: updated.subkind,
511
+ label: updated.label,
512
+ body: updated.body
513
+ });
514
+ const clash = db
515
+ .prepare(
516
+ `SELECT id FROM graph_nodes
517
+ WHERE COALESCE(project_id, '') = COALESCE(?, '') AND kind = ? AND digest = ? AND id != ?`
518
+ )
519
+ .get(updated.projectId, updated.kind, digest, id) as { id: string } | null;
520
+ if (!clash) db.prepare(`UPDATE graph_nodes SET digest = ? WHERE id = ?`).run(digest, id);
521
+ }
522
+
523
+ this.syncFts(id);
524
+ // The vector describes text that just changed, so it must be recomputed.
525
+ db.prepare(`DELETE FROM graph_vectors WHERE node_id = ?`).run(id);
526
+ return this.getById(id);
527
+ },
528
+
529
+ /** Soft-delete: leaves edges intact so the reasoning path is still visible. */
530
+ archive(id: string): void {
531
+ getDatabase().prepare(`UPDATE graph_nodes SET archived_at = CURRENT_TIMESTAMP WHERE id = ?`).run(id);
532
+ this.dropFts([id]);
533
+ },
534
+
535
+ /** Batch soft-delete — the same statement per node, one FTS sweep. */
536
+ archiveNodes(ids: string[]): number {
537
+ if (ids.length === 0) return 0;
538
+ const placeholders = ids.map(() => '?').join(',');
539
+ getDatabase()
540
+ .prepare(
541
+ `UPDATE graph_nodes SET archived_at = CURRENT_TIMESTAMP
542
+ WHERE id IN (${placeholders}) AND archived_at IS NULL`
543
+ )
544
+ .run(...ids);
545
+ this.dropFts(ids);
546
+ return ids.length;
547
+ },
548
+
549
+ /**
550
+ * Bring memories back into recall.
551
+ *
552
+ * Clears BOTH kinds of "no longer recalled", because from the Forgotten list
553
+ * they are one list and a Restore that silently skipped half of it would be
554
+ * worse than no Restore at all. Archiving says "this was never true";
555
+ * superseding says "something newer replaced it". Both are judgements the
556
+ * graph made on its own — supersession by a model reading a transcript — so
557
+ * both have to be reversible by the person who disagrees, or "reversible" is a
558
+ * property of the schema rather than of the product.
559
+ *
560
+ * The `supersedes` edge is removed with it: leaving it would draw a claim in
561
+ * the graph view that is no longer being made.
562
+ */
563
+ restoreNodes(ids: string[]): number {
564
+ if (ids.length === 0) return 0;
565
+ const db = getDatabase();
566
+ const placeholders = ids.map(() => '?').join(',');
567
+
568
+ return this.transaction(() => {
569
+ const rows = db
570
+ .prepare(
571
+ `SELECT id, superseded_by FROM graph_nodes
572
+ WHERE id IN (${placeholders}) AND (archived_at IS NOT NULL OR superseded_by IS NOT NULL)`
573
+ )
574
+ .all(...ids) as { id: string; superseded_by: string | null }[];
575
+ if (rows.length === 0) return 0;
576
+
577
+ const live = rows.map(row => row.id);
578
+ const livePlaceholders = live.map(() => '?').join(',');
579
+ db.prepare(
580
+ `UPDATE graph_nodes SET archived_at = NULL, superseded_by = NULL, updated_at = CURRENT_TIMESTAMP
581
+ WHERE id IN (${livePlaceholders})`
582
+ ).run(...live);
583
+
584
+ for (const row of rows) {
585
+ if (!row.superseded_by) continue;
586
+ db.prepare(`DELETE FROM graph_edges WHERE src_id = ? AND dst_id = ? AND rel = 'supersedes'`).run(
587
+ row.superseded_by,
588
+ row.id
589
+ );
590
+ }
591
+
592
+ for (const id of live) this.syncFts(id);
593
+ return live.length;
594
+ });
595
+ },
596
+
597
+ restore(id: string): void {
598
+ this.restoreNodes([id]);
599
+ },
600
+
601
+ /** Hard-delete. Edges and the vector cascade; the FTS mirror is manual. */
602
+ remove(id: string): void {
603
+ this.dropFts([id]);
604
+ getDatabase().prepare(`DELETE FROM graph_nodes WHERE id = ?`).run(id);
605
+ },
606
+
607
+ /** The canonical node for an entity, if one has been created. */
608
+ getByEntityKey(projectId: string | null, entityKey: string): GraphNode | null {
609
+ const row = getDatabase()
610
+ .prepare(
611
+ `SELECT * FROM graph_nodes
612
+ WHERE COALESCE(project_id, '') = COALESCE(?, '') AND entity_key = ?`
613
+ )
614
+ .get(projectId, entityKey) as GraphNodeRow | null;
615
+ return row ? toNode(row) : null;
616
+ },
617
+
618
+ /**
619
+ * Structural nodes for a set of repo-relative paths, in one query.
620
+ *
621
+ * Used to turn the files a session is working in into retrieval seeds, so the
622
+ * lookup happens once per turn rather than once per path.
623
+ */
624
+ getByPaths(projectId: string | null, paths: string[]): GraphNode[] {
625
+ if (paths.length === 0) return [];
626
+ const placeholders = paths.map(() => '?').join(',');
627
+ const rows = getDatabase()
628
+ .prepare(
629
+ `SELECT * FROM graph_nodes
630
+ WHERE COALESCE(project_id, '') = COALESCE(?, '')
631
+ AND kind = 'structural' AND subkind = 'file'
632
+ AND archived_at IS NULL AND path IN (${placeholders})`
633
+ )
634
+ .all(projectId, ...paths) as GraphNodeRow[];
635
+ return rows.map(toNode);
636
+ },
637
+
638
+ /**
639
+ * Mark `oldId` as replaced by `newId`: belief revision.
640
+ *
641
+ * DESTRUCTIVE, and therefore RESERVED FOR PEOPLE. This is the one operation in
642
+ * the feature that removes a memory from every future recall in a single step,
643
+ * and it used to be driven by a model's opinion of one turn. Measured, that
644
+ * opinion retired a hand-written standing rule in one run out of two, on the
645
+ * strength of a task-local exception the model itself flagged as possibly "a
646
+ * specific exception for this task".
647
+ *
648
+ * Automatic contradiction handling now writes a `contradicts` edge instead and
649
+ * lets the read path pick a winner on every turn (see `resolveConflicts`). A
650
+ * wrong verdict there costs one mis-ranked line; a wrong verdict here costs a
651
+ * memory. Callers that are not acting on a person's explicit instruction should
652
+ * use `contradict()`.
653
+ *
654
+ * The old node is NOT archived. Archiving would say "this was never true";
655
+ * superseding says "this was true and is not any more", which is a different
656
+ * claim and the one worth keeping — the edge is what lets someone ask why the
657
+ * current belief is what it is. It simply stops being retrieved.
658
+ *
659
+ * A chain is collapsed rather than followed: if A already superseded B, and C
660
+ * now supersedes A, B is repointed at C too. Otherwise "is this current?"
661
+ * would need a recursive walk on the read path, which runs every turn.
662
+ */
663
+ supersede(oldId: string, newId: string): boolean {
664
+ if (oldId === newId) return false;
665
+ const db = getDatabase();
666
+ const older = this.getById(oldId);
667
+ const newer = this.getById(newId);
668
+ if (!older || !newer) return false;
669
+ // Refuse to point the new belief at itself through a cycle.
670
+ if (newer.supersededBy === oldId) return false;
671
+
672
+ // Authority never runs downhill. A memory the user stated cannot be retired
673
+ // by one the assistant asserted or a model inferred, however recent or
674
+ // confident. The disagreement is still real, so the caller's contradiction
675
+ // edge (written by `contradict`) is what carries it instead.
676
+ if (AUTHORITY_RANK[older.assertedBy] > AUTHORITY_RANK[newer.assertedBy]) {
677
+ debug.log(
678
+ 'memory',
679
+ `Refused supersession: ${newer.assertedBy}-asserted memory cannot retire a ${older.assertedBy}-asserted one`
680
+ );
681
+ return false;
682
+ }
683
+
684
+ // Durability never runs uphill either. A one-off instruction is an exception
685
+ // being taken, not a rule being repealed, and a claim about one repository
686
+ // does not settle a claim about how the user works everywhere.
687
+ const DURABILITY: Record<GraphScope, number> = { session: 0, project: 1, global: 2 };
688
+ if (DURABILITY[newer.scope] < DURABILITY[older.scope]) {
689
+ debug.log('memory', `Refused supersession: ${newer.scope}-scoped memory cannot retire a ${older.scope}-scoped one`);
690
+ return false;
691
+ }
692
+
693
+ db.prepare(`UPDATE graph_nodes SET superseded_by = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?`).run(
694
+ newId,
695
+ oldId
696
+ );
697
+ db.prepare(`UPDATE graph_nodes SET superseded_by = ? WHERE superseded_by = ?`).run(newId, oldId);
698
+
699
+ this.link({ srcId: newId, dstId: oldId, rel: 'supersedes', source: 'agent' });
700
+ // Out of the lexical index for the same reason it is out of retrieval.
701
+ this.dropFts([oldId]);
702
+ return true;
703
+ },
704
+
705
+ /**
706
+ * Record that two memories make claims that cannot both be current.
707
+ *
708
+ * This is what automatic revision writes instead of superseding, and the whole
709
+ * difference is that NOTHING IS REMOVED. Both memories stay live, stay
710
+ * searchable, stay in the graph view; the read path decides on each turn which
711
+ * of them to hand to the agent, and the user can see the disagreement and
712
+ * settle it.
713
+ *
714
+ * The reasoning is asymmetric in a way the old design ignored. A model reading
715
+ * one turn is guessing at whether a rule was repealed or an exception taken —
716
+ * it cannot see the next turn, or the user's face. Freezing that guess into a
717
+ * destructive write meant a bad guess was unrecoverable in practice, because
718
+ * nobody reviews a store that is working. Freezing it into an EDGE means a bad
719
+ * guess is one line ranked wrongly, re-decided from scratch every turn against
720
+ * evidence that keeps arriving.
721
+ *
722
+ * Both directions are stored as one edge from the newer claim to the older, so
723
+ * "what does this disagree with" is a single indexed lookup either way.
724
+ */
725
+ contradict(newId: string, oldId: string): boolean {
726
+ if (newId === oldId) return false;
727
+ if (!this.getById(newId) || !this.getById(oldId)) return false;
728
+ return this.link({ srcId: newId, dstId: oldId, rel: 'contradicts', source: 'agent' }) !== null;
729
+ },
730
+
731
+ // ── entities ────────────────────────────────────────────────────────────
732
+
733
+ /**
734
+ * Record what a memory is about, replacing whatever was recorded before.
735
+ *
736
+ * Replace rather than append, because extraction re-reads the same memory
737
+ * whenever it is reinforced and a later reading is a better one — appending
738
+ * would accumulate every phrasing the model ever used for the same subject,
739
+ * which is the failure the canonical key exists to prevent.
740
+ *
741
+ * Re-syncs the lexical index, since the names are part of the memory's
742
+ * searchable text now rather than nodes of their own.
743
+ */
744
+ setEntities(nodeId: string, entities: { key: string; name: string }[]): number {
745
+ const db = getDatabase();
746
+ db.prepare(`DELETE FROM graph_node_entities WHERE node_id = ?`).run(nodeId);
747
+ const insert = db.prepare(
748
+ `INSERT OR IGNORE INTO graph_node_entities (node_id, entity_key, name) VALUES (?, ?, ?)`
749
+ );
750
+ for (const entity of entities) insert.run(nodeId, entity.key, entity.name);
751
+ this.syncFts(nodeId);
752
+ return entities.length;
753
+ },
754
+
755
+ /** The names a memory was recorded as being about. */
756
+ entityNamesOf(nodeId: string): string[] {
757
+ return (
758
+ getDatabase().prepare(`SELECT name FROM graph_node_entities WHERE node_id = ?`).all(nodeId) as {
759
+ name: string;
760
+ }[]
761
+ ).map(row => row.name);
762
+ },
763
+
764
+ /** Names for many memories at once, for listings and the graph view. */
765
+ entityNamesFor(nodeIds: string[]): Map<string, string[]> {
766
+ const byNode = new Map<string, string[]>();
767
+ if (nodeIds.length === 0) return byNode;
768
+ const rows = getDatabase()
769
+ .prepare(
770
+ `SELECT node_id, name FROM graph_node_entities WHERE node_id IN (${nodeIds.map(() => '?').join(',')})`
771
+ )
772
+ .all(...nodeIds) as { node_id: string; name: string }[];
773
+ for (const row of rows) {
774
+ byNode.set(row.node_id, [...(byNode.get(row.node_id) ?? []), row.name]);
775
+ }
776
+ return byNode;
777
+ },
778
+
779
+ /**
780
+ * Edges DERIVED from two memories being about the same subject.
781
+ *
782
+ * Removing similarity linking removed almost all of the graph's structure —
783
+ * 371 edges became 6 — and that was an over-correction with a visible cost: the
784
+ * view turned into a field of disconnected dots. What was wrong with those 144
785
+ * edges was never that they connected memories; it was that COSINE decided
786
+ * which ones. Two memories are related when they are about the same THING, not
787
+ * when they are phrased alike, and extraction already records what each memory
788
+ * is about.
789
+ *
790
+ * So the relation is stated rather than inferred, and it is derived at READ
791
+ * time rather than stored: nothing to keep in sync, nothing to repair when a
792
+ * memory's entities are rewritten, and no way for an edge to outlive the claim
793
+ * it came from.
794
+ *
795
+ * Two bounds, both about hubs.
796
+ *
797
+ * A subject shared by a large slice of the graph is not a relationship, it is a
798
+ * word everyone happens to use. "TypeScript" across forty memories says nothing
799
+ * about any two of them, and connecting them all would recreate the
800
+ * fabricated-structure problem from a different cause. `MAX_SUBJECT_MEMBERS`
801
+ * drops those.
802
+ *
803
+ * And within a subject each memory links only to the few strongest members
804
+ * rather than to all of them. A clique of thirteen is seventy-eight lines
805
+ * saying one thing; bounded degree says the same thing, keeps the cluster
806
+ * visible, and stays linear as the graph grows.
807
+ */
808
+ derivedEdges(nodeIds: string[]): { srcId: string; dstId: string; weight: number; via: 'subject' | 'project' }[] {
809
+ if (nodeIds.length < 2) return [];
810
+
811
+ /** Above this a group is a common word rather than a shared topic. */
812
+ const MAX_GROUP_MEMBERS = 24;
813
+ /** Links each memory draws per group, toward the heaviest members. */
814
+ const LINKS_PER_MEMBER = 4;
815
+
816
+ const placeholders = nodeIds.map(() => '?').join(',');
817
+ const edges: { srcId: string; dstId: string; weight: number; via: 'subject' | 'project' }[] = [];
818
+ const seen = new Set<string>();
819
+
820
+ /** Chain a group's members, heaviest first, into bounded-degree edges. */
821
+ const connect = (members: string[], weight: number, via: 'subject' | 'project'): void => {
822
+ if (members.length < 2 || members.length > MAX_GROUP_MEMBERS) return;
823
+ for (let i = 0; i < members.length; i++) {
824
+ for (let j = i + 1; j < Math.min(members.length, i + 1 + LINKS_PER_MEMBER); j++) {
825
+ const [a, b] = members[i] < members[j] ? [members[i], members[j]] : [members[j], members[i]];
826
+ const key = `${a}|${b}`;
827
+ if (seen.has(key)) continue;
828
+ seen.add(key);
829
+ edges.push({ srcId: a, dstId: b, weight, via });
830
+ }
831
+ }
832
+ };
833
+
834
+ // ── shared subject ───────────────────────────────────────────────────
835
+ const rows = getDatabase()
836
+ .prepare(
837
+ `SELECT e.entity_key AS groupKey, e.node_id AS nodeId
838
+ FROM graph_node_entities e
839
+ INNER JOIN graph_nodes n ON n.id = e.node_id
840
+ WHERE e.node_id IN (${placeholders})
841
+ ORDER BY e.entity_key, n.weight DESC, n.updated_at DESC`
842
+ )
843
+ .all(...nodeIds) as { groupKey: string; nodeId: string }[];
844
+ const bySubject = new Map<string, string[]>();
845
+ for (const row of rows) bySubject.set(row.groupKey, [...(bySubject.get(row.groupKey) ?? []), row.nodeId]);
846
+ // `members` is heaviest-first, so linking forward attaches the tail of a
847
+ // subject to its most reinforced memories rather than to whichever happened
848
+ // to be written first.
849
+ for (const members of bySubject.values()) connect(members, 1, 'subject');
850
+
851
+ // ── same codebase ────────────────────────────────────────────────────
852
+ // Weaker on purpose. Two memories about tunnelkit are related BECAUSE they
853
+ // are about tunnelkit; two memories that merely live in the same repository
854
+ // are related the way two books on one shelf are. Louvain reads the weight,
855
+ // so a project holds together only where subjects do not already say more.
856
+ //
857
+ // It also catches what nothing else can. Eleven memories in the real graph
858
+ // named no subject at all — extraction simply left the field empty — and
859
+ // they are exactly the "the calculator app has three modes" kind of note
860
+ // that clearly belongs with its neighbours and had no way to say so.
861
+ const projectRows = getDatabase()
862
+ .prepare(
863
+ `SELECT project_id AS groupKey, id AS nodeId FROM graph_nodes
864
+ WHERE id IN (${placeholders}) AND project_id IS NOT NULL AND kind = 'episodic'
865
+ ORDER BY project_id, weight DESC, updated_at DESC`
866
+ )
867
+ .all(...nodeIds) as { groupKey: string; nodeId: string }[];
868
+ const byProject = new Map<string, string[]>();
869
+ for (const row of projectRows) byProject.set(row.groupKey, [...(byProject.get(row.groupKey) ?? []), row.nodeId]);
870
+ for (const members of byProject.values()) connect(members, 0.4, 'project');
871
+
872
+ return edges;
873
+ },
874
+
875
+ /** Ids sharing a subject with `nodeId`, for one hop of traversal. */
876
+ entityNeighbourIds(nodeId: string, limit = 12): string[] {
877
+ try {
878
+ return (
879
+ getDatabase()
880
+ .prepare(
881
+ `SELECT DISTINCT other.node_id AS id
882
+ FROM graph_node_entities mine
883
+ INNER JOIN graph_node_entities other ON other.entity_key = mine.entity_key
884
+ INNER JOIN graph_nodes n ON n.id = other.node_id
885
+ WHERE mine.node_id = ? AND other.node_id <> ?
886
+ AND n.archived_at IS NULL AND n.superseded_by IS NULL
887
+ ORDER BY n.weight DESC, n.updated_at DESC
888
+ LIMIT ?`
889
+ )
890
+ .all(nodeId, nodeId, limit) as { id: string }[]
891
+ ).map(row => row.id);
892
+ } catch {
893
+ return [];
894
+ }
895
+ },
896
+
897
+ /**
898
+ * Every memory recorded as being about one subject.
899
+ *
900
+ * This is what the entity NODE existed to answer, and it answers it better:
901
+ * an index seek returning the memories themselves, rather than a hop into a
902
+ * hub and back out through whichever of its edges survived the activation
903
+ * split.
904
+ */
905
+ memoriesAboutEntity(key: string, limit = 20): GraphNode[] {
906
+ try {
907
+ const rows = getDatabase()
908
+ .prepare(
909
+ `SELECT n.* FROM graph_node_entities e
910
+ INNER JOIN graph_nodes n ON n.id = e.node_id
911
+ WHERE e.entity_key = ? AND n.archived_at IS NULL AND n.superseded_by IS NULL
912
+ ORDER BY n.weight DESC, n.updated_at DESC
913
+ LIMIT ?`
914
+ )
915
+ .all(key, limit) as GraphNodeRow[];
916
+ return rows.map(toNode);
917
+ } catch {
918
+ return [];
919
+ }
920
+ },
921
+
922
+ /** Live memories that contradict any of `ids`, in both directions. */
923
+ contradictionsFor(ids: string[]): { srcId: string; dstId: string }[] {
924
+ if (ids.length === 0) return [];
925
+ const placeholders = ids.map(() => '?').join(',');
926
+ return getDatabase()
927
+ .prepare(
928
+ `SELECT src_id AS srcId, dst_id AS dstId FROM graph_edges
929
+ WHERE rel = 'contradicts' AND (src_id IN (${placeholders}) OR dst_id IN (${placeholders}))`
930
+ )
931
+ .all(...ids, ...ids) as { srcId: string; dstId: string }[];
932
+ },
933
+
934
+ /**
935
+ * The claims that hold on every turn regardless of what was asked.
936
+ *
937
+ * Retrieval cannot deliver these, and no amount of ranking will fix that. A
938
+ * standing instruction has no topical overlap with "analyse this project", so
939
+ * similarity search will always rank it below whatever the question was
940
+ * actually about — measured, human-stated rules reached the prompt on 3 of 20
941
+ * opportunities. Worse, static embeddings cannot represent negation, so a query
942
+ * that states a prohibition retrieves the permission: asking "jangan gunakan
943
+ * agent tool" returned "requested use of agent tool" as the top hit.
944
+ *
945
+ * So they are not retrieved at all. They are SELECTED — structurally, by who
946
+ * asserted them and how durable they are — and prepended to every turn.
947
+ *
948
+ * `session`-scoped rows are excluded: a one-off instruction belongs to the turn
949
+ * that gave it, and the engine still has that turn in its own history.
950
+ */
951
+ standingInstructions(projectId: string | null, limit: number): GraphNode[] {
952
+ const rows = getDatabase()
953
+ .prepare(
954
+ `SELECT * FROM graph_nodes
955
+ WHERE kind = 'episodic'
956
+ AND archived_at IS NULL AND superseded_by IS NULL
957
+ AND scope IN ('project', 'global')
958
+ AND subkind IN ('preference', 'decision', 'pattern')
959
+ AND (asserted_by = 'user' OR pinned = 1)
960
+ AND (project_id IS NULL OR project_id = ?)
961
+ AND confidence >= 0.3
962
+ ORDER BY pinned DESC,
963
+ CASE subkind WHEN 'preference' THEN 0 WHEN 'decision' THEN 1 ELSE 2 END,
964
+ updated_at DESC
965
+ LIMIT ?`
966
+ )
967
+ .all(projectId, limit) as GraphNodeRow[];
968
+ return rows.map(toNode);
969
+ },
970
+
971
+ /**
972
+ * Record what a later turn did with a memory that was handed to it.
973
+ *
974
+ * This is the only evidence in the system that a memory is any good.
975
+ * `access_count` records that a memory was RETRIEVED, which is a fact about
976
+ * the ranker rather than about the memory, and letting it feed back into
977
+ * ranking is how popular memories crowd out correct ones.
978
+ *
979
+ * `wrong` costs confidence rather than deleting: one turn misreading a memory
980
+ * should not destroy it, but three should push it below the injection floor.
981
+ */
982
+ recordFeedback(id: string, verdict: 'used' | 'wrong' | 'ignored'): void {
983
+ const db = getDatabase();
984
+ if (verdict === 'used') {
985
+ db.prepare(
986
+ `UPDATE graph_nodes
987
+ SET useful_count = useful_count + 1,
988
+ weight = MIN(weight + 0.5, 10.0),
989
+ confidence = MIN(confidence + 0.05, 1.0)
990
+ WHERE id = ?`
991
+ ).run(id);
992
+ return;
993
+ }
994
+ if (verdict === 'wrong') {
995
+ db.prepare(
996
+ `UPDATE graph_nodes
997
+ SET unhelpful_count = unhelpful_count + 1,
998
+ confidence = MAX(confidence - 0.2, 0.05)
999
+ WHERE id = ?`
1000
+ ).run(id);
1001
+ return;
1002
+ }
1003
+ // 'ignored' is weak evidence — most memories in a block are irrelevant to
1004
+ // the turn through no fault of their own — so it is counted and nothing else.
1005
+ db.prepare(`UPDATE graph_nodes SET unhelpful_count = unhelpful_count + 1 WHERE id = ?`).run(id);
1006
+ },
1007
+
1008
+ /**
1009
+ * Mark memories as standing on code that has since changed.
1010
+ *
1011
+ * Decay is per subkind because the subkinds age differently: an `observation`
1012
+ * about how a file works is invalidated by that file being rewritten, while a
1013
+ * `decision` about why it was written that way survives the rewrite — the
1014
+ * decision is the reason the change happened. Applying one rate to both would
1015
+ * either keep stale observations or destroy durable decisions.
1016
+ */
1017
+ markStale(nodeIds: string[], factorBySubkind: Record<string, number>, coolOffHours = 6): number {
1018
+ if (nodeIds.length === 0) return 0;
1019
+ const db = getDatabase();
1020
+ let touched = 0;
1021
+ // The cool-off is what stops decay COMPOUNDING per turn. Without it, editing
1022
+ // one file across ten turns multiplies every observation about it by
1023
+ // 0.82 ten times over — 0.14, below the injection floor — so an ordinary
1024
+ // afternoon of iteration silently destroys everything the graph knew about
1025
+ // the file being worked on. One code change is one piece of evidence,
1026
+ // however many times it is saved.
1027
+ const update = db.prepare(
1028
+ `UPDATE graph_nodes
1029
+ SET confidence = MAX(confidence * ?, 0.05), stale_at = CURRENT_TIMESTAMP
1030
+ WHERE id = ? AND pinned = 0 AND source != 'user'
1031
+ AND (stale_at IS NULL OR stale_at < datetime('now', ?))`
1032
+ );
1033
+ const window = `-${Math.max(0, Math.round(coolOffHours))} hours`;
1034
+ for (const node of this.getByIds(nodeIds)) {
1035
+ const factor = factorBySubkind[node.subkind];
1036
+ if (factor === undefined || factor >= 1) continue;
1037
+ const result = update.run(factor, node.id, window) as { changes?: number };
1038
+ if (Number(result.changes ?? 0) > 0) touched++;
1039
+ }
1040
+ return touched;
1041
+ },
1042
+
1043
+ /**
1044
+ * Memories that claim something about any of these code nodes, in one query.
1045
+ *
1046
+ * `about` points memory → code, so the memory is always the source. Replaces a
1047
+ * per-file `edgesOf` loop that pulled every edge of every changed file — on a
1048
+ * turn touching sixty files, most of them `defines` and `imports` edges that
1049
+ * invalidation has no interest in.
1050
+ */
1051
+ memoriesAbout(codeNodeIds: string[]): string[] {
1052
+ if (codeNodeIds.length === 0) return [];
1053
+ const placeholders = codeNodeIds.map(() => '?').join(',');
1054
+ const rows = getDatabase()
1055
+ .prepare(
1056
+ `SELECT DISTINCT e.src_id AS id FROM graph_edges e
1057
+ INNER JOIN graph_nodes n ON n.id = e.src_id
1058
+ WHERE e.rel = 'about' AND e.dst_id IN (${placeholders})
1059
+ AND n.archived_at IS NULL AND n.superseded_by IS NULL`
1060
+ )
1061
+ .all(...codeNodeIds) as { id: string }[];
1062
+ return rows.map(row => row.id);
1063
+ },
1064
+
1065
+ /**
1066
+ * Run `fn` inside one SQLite transaction.
1067
+ *
1068
+ * Structural ingestion performs several thousand statements per busy turn
1069
+ * (a file upsert is a SELECT, an INSERT/UPDATE and an FTS rewrite, and a file
1070
+ * can define 25 symbols). Outside a transaction each one is its own durability
1071
+ * barrier, which is the single largest cost on the write path.
1072
+ */
1073
+ transaction<T>(fn: () => T): T {
1074
+ const db = getDatabase();
1075
+ // Not every driver exposes transactions (see `DatabaseConnection`). Running
1076
+ // the block unbatched is the correct degradation: slower, identical result.
1077
+ return db.transaction ? db.transaction(fn)() : fn();
1078
+ },
1079
+
1080
+ /** Record that retrieval surfaced these nodes, feeding the usage signal. */
1081
+ markAccessed(ids: string[]): void {
1082
+ if (ids.length === 0) return;
1083
+ const placeholders = ids.map(() => '?').join(',');
1084
+ getDatabase()
1085
+ .prepare(
1086
+ `UPDATE graph_nodes
1087
+ SET access_count = access_count + 1, accessed_at = CURRENT_TIMESTAMP
1088
+ WHERE id IN (${placeholders})`
1089
+ )
1090
+ .run(...ids);
1091
+ },
1092
+
1093
+ // ── FTS mirror ──────────────────────────────────────────────────────────
1094
+
1095
+ /**
1096
+ * Rewrite one node's row in the lexical index. Archived nodes are removed.
1097
+ *
1098
+ * The delete goes through `fts_rowid`, NOT through `node_id`, and that is the
1099
+ * difference between this being free and this being the most expensive
1100
+ * statement on the write path. `graph_nodes_fts` is a standalone FTS5 table
1101
+ * whose `node_id` is UNINDEXED, so `WHERE node_id = ?` is a full scan of the
1102
+ * content table — and this function runs on every upsert, which on a busy turn
1103
+ * means fifteen hundred full scans of a table that only grows (migration 066).
1104
+ * A rowid is a primary key, so the same delete is a lookup.
1105
+ */
1106
+ syncFts(id: string): void {
1107
+ const db = getDatabase();
1108
+ const current = db.prepare(`SELECT fts_rowid FROM graph_nodes WHERE id = ?`).get(id) as {
1109
+ fts_rowid: number | null;
1110
+ } | null;
1111
+ if (current?.fts_rowid != null) {
1112
+ db.prepare(`DELETE FROM graph_nodes_fts WHERE rowid = ?`).run(current.fts_rowid);
1113
+ }
1114
+
1115
+ const node = this.getById(id);
1116
+ if (!node || node.archivedAt || node.supersededBy) {
1117
+ if (current?.fts_rowid != null) {
1118
+ db.prepare(`UPDATE graph_nodes SET fts_rowid = NULL WHERE id = ?`).run(id);
1119
+ }
1120
+ return;
1121
+ }
1122
+
1123
+ const text = indexedText({ ...node, entityNames: this.entityNamesOf(id) });
1124
+ if (!text) {
1125
+ db.prepare(`UPDATE graph_nodes SET fts_rowid = NULL WHERE id = ?`).run(id);
1126
+ return;
1127
+ }
1128
+
1129
+ const result = db
1130
+ .prepare(`INSERT INTO graph_nodes_fts (node_id, project_id, scope, kind, text) VALUES (?, ?, ?, ?, ?)`)
1131
+ .run(id, node.projectId ?? '', node.scope, node.kind, text) as { lastInsertRowid?: number | bigint };
1132
+ db.prepare(`UPDATE graph_nodes SET fts_rowid = ? WHERE id = ?`).run(
1133
+ Number(result.lastInsertRowid ?? 0),
1134
+ id
1135
+ );
1136
+ },
1137
+
1138
+ /**
1139
+ * Drop a set of nodes from the lexical index in one statement.
1140
+ *
1141
+ * Same rowid argument as `syncFts`, applied to the batch paths — archiving a
1142
+ * deleted file's symbols, purging a project, collapsing duplicates. The
1143
+ * sub-select is index-covered on `graph_nodes.id`, so the FTS side only ever
1144
+ * sees primary keys.
1145
+ */
1146
+ dropFts(ids: string[]): void {
1147
+ if (ids.length === 0) return;
1148
+ const db = getDatabase();
1149
+ const placeholders = ids.map(() => '?').join(',');
1150
+ db.prepare(
1151
+ `DELETE FROM graph_nodes_fts
1152
+ WHERE rowid IN (SELECT fts_rowid FROM graph_nodes WHERE id IN (${placeholders}) AND fts_rowid IS NOT NULL)`
1153
+ ).run(...ids);
1154
+ db.prepare(`UPDATE graph_nodes SET fts_rowid = NULL WHERE id IN (${placeholders})`).run(...ids);
1155
+ },
1156
+
1157
+ /**
1158
+ * Turn free-typed text into a safe FTS5 MATCH query: quoted prefix terms
1159
+ * OR-ed together. Quoting is the injection guard — no user character can
1160
+ * reach FTS5 as syntax.
1161
+ *
1162
+ * Unlike `sessionQueries.buildFtsQuery`, punctuation SPLITS a word instead of
1163
+ * being stripped from it. That difference matters here because this index
1164
+ * holds code: stripping would turn `stream-manager` into `streammanager`,
1165
+ * which matches nothing, whereas splitting yields `stream` and `manager` —
1166
+ * the same tokens FTS5 stored for the path.
1167
+ *
1168
+ * Terms are OR-ed rather than AND-ed because retrieval is a ranking problem,
1169
+ * not a filter: a node matching three of four terms should still be offered,
1170
+ * with BM25 deciding how highly. Single-character terms are dropped, since as
1171
+ * prefixes they match a large share of the index and swamp the ranking.
1172
+ */
1173
+ buildFtsQuery(raw: string): string | null {
1174
+ const terms = [
1175
+ ...new Set(
1176
+ raw
1177
+ .split(/[^\p{L}\p{N}]+/u)
1178
+ .filter(t => t.length > 1)
1179
+ .map(t => t.toLowerCase())
1180
+ )
1181
+ ];
1182
+ if (terms.length === 0) return null;
1183
+
1184
+ // The term count is CAPPED, and not for tidiness. Two callers pass long text
1185
+ // here: a user who pasted a stack trace into chat, and belief revision, which
1186
+ // deliberately queries with four thousand characters of transcript. Both
1187
+ // produce hundreds of OR-ed prefix terms — every one of them a separate index
1188
+ // range scan, over a parse tree deep enough to hit SQLite's expression-depth
1189
+ // limit. That throws, retrieval catches it, and the lexical channel silently
1190
+ // disappears for exactly the queries that had the most to say.
1191
+ //
1192
+ // Longest first is a rough proxy for most selective: `EngineNotReadyError`
1193
+ // discriminates, `the` does not, and a prefix search on a short common word
1194
+ // matches a large share of the index while contributing nothing to the
1195
+ // ranking.
1196
+ if (terms.length > MAX_FTS_TERMS) {
1197
+ terms.sort((a, b) => b.length - a.length);
1198
+ terms.length = MAX_FTS_TERMS;
1199
+ }
1200
+ return terms.map(t => `"${t}"*`).join(' OR ');
1201
+ },
1202
+
1203
+ // ── edges ───────────────────────────────────────────────────────────────
1204
+
1205
+ /**
1206
+ * Create an edge, or strengthen it when it already exists. Self-loops are
1207
+ * rejected: they carry no information and would make traversal double-count
1208
+ * a node's own weight.
1209
+ */
1210
+ link(input: GraphEdgeInput): GraphEdge | null {
1211
+ if (input.srcId === input.dstId) return null;
1212
+
1213
+ const db = getDatabase();
1214
+ const existing = db
1215
+ .prepare(`SELECT * FROM graph_edges WHERE src_id = ? AND dst_id = ? AND rel = ?`)
1216
+ .get(input.srcId, input.dstId, input.rel) as GraphEdgeRow | null;
1217
+
1218
+ if (existing) {
1219
+ db.prepare(`UPDATE graph_edges SET weight = MIN(weight + 0.25, 10.0) WHERE id = ?`).run(existing.id);
1220
+ return toEdge(
1221
+ db.prepare(`SELECT * FROM graph_edges WHERE id = ?`).get(existing.id) as GraphEdgeRow
1222
+ );
1223
+ }
1224
+
1225
+ try {
1226
+ const result = db
1227
+ .prepare(`INSERT INTO graph_edges (src_id, dst_id, rel, weight, source) VALUES (?, ?, ?, ?, ?)`)
1228
+ .run(input.srcId, input.dstId, input.rel, input.weight ?? 1.0, input.source ?? 'agent') as {
1229
+ lastInsertRowid?: number | bigint;
1230
+ };
1231
+ return toEdge(
1232
+ db.prepare(`SELECT * FROM graph_edges WHERE id = ?`).get(Number(result.lastInsertRowid)) as GraphEdgeRow
1233
+ );
1234
+ } catch (error) {
1235
+ // Foreign keys are ON, so linking a node that has since been deleted
1236
+ // fails here rather than leaving a dangling edge.
1237
+ debug.warn('memory', `Failed to link ${input.srcId} -[${input.rel}]-> ${input.dstId}`, error);
1238
+ return null;
1239
+ }
1240
+ },
1241
+
1242
+ /** Every edge touching a node, in either direction. */
1243
+ edgesOf(nodeId: string): GraphEdge[] {
1244
+ const rows = getDatabase()
1245
+ .prepare(`SELECT * FROM graph_edges WHERE src_id = ? OR dst_id = ?`)
1246
+ .all(nodeId, nodeId) as GraphEdgeRow[];
1247
+ return rows.map(toEdge);
1248
+ },
1249
+
1250
+ /** Every edge with both ends inside the given set — the induced subgraph. */
1251
+ edgesWithin(nodeIds: string[]): GraphEdge[] {
1252
+ if (nodeIds.length === 0) return [];
1253
+ const placeholders = nodeIds.map(() => '?').join(',');
1254
+ const rows = getDatabase()
1255
+ .prepare(
1256
+ `SELECT * FROM graph_edges
1257
+ WHERE src_id IN (${placeholders}) AND dst_id IN (${placeholders})`
1258
+ )
1259
+ .all(...nodeIds, ...nodeIds) as GraphEdgeRow[];
1260
+ return rows.map(toEdge);
1261
+ },
1262
+
1263
+ /**
1264
+ * Neighbours of a node up to `hops` away, breadth-first, with the distance at
1265
+ * which each was reached.
1266
+ *
1267
+ * Written as an iterative walk rather than a recursive CTE on purpose: the
1268
+ * per-level `LIMIT` is what stops one hub node (a heavily-imported file, say)
1269
+ * from dragging half the graph into a result set. A recursive CTE cannot cap
1270
+ * fan-out per level without materialising it first.
1271
+ */
1272
+ neighbours(
1273
+ nodeId: string,
1274
+ hops: number = 1,
1275
+ perLevelLimit: number = 60,
1276
+ options: { includeArchived?: boolean; includeSuperseded?: boolean } = {}
1277
+ ): { node: GraphNode; hops: number }[] {
1278
+ const db = getDatabase();
1279
+ const distance = new Map<string, number>([[nodeId, 0]]);
1280
+ let frontier = [nodeId];
1281
+
1282
+ for (let depth = 1; depth <= Math.max(0, hops); depth++) {
1283
+ if (frontier.length === 0) break;
1284
+ const placeholders = frontier.map(() => '?').join(',');
1285
+ const rows = db
1286
+ .prepare(
1287
+ `SELECT src_id, dst_id, weight FROM graph_edges
1288
+ WHERE src_id IN (${placeholders}) OR dst_id IN (${placeholders})
1289
+ ORDER BY weight DESC
1290
+ LIMIT ?`
1291
+ )
1292
+ .all(...frontier, ...frontier, perLevelLimit) as { src_id: string; dst_id: string }[];
1293
+
1294
+ const next: string[] = [];
1295
+ for (const row of rows) {
1296
+ for (const candidate of [row.src_id, row.dst_id]) {
1297
+ if (distance.has(candidate)) continue;
1298
+ distance.set(candidate, depth);
1299
+ next.push(candidate);
1300
+ }
1301
+ }
1302
+
1303
+ // Memories about the same subject are neighbours too, without an edge in
1304
+ // the table. This is what the entity NODE used to provide as two hops
1305
+ // through a stub; it is one hop now, and it is the only structure the
1306
+ // episodic half has left since similarity linking was removed.
1307
+ for (const id of frontier) {
1308
+ for (const candidate of this.entityNeighbourIds(id)) {
1309
+ if (distance.has(candidate)) continue;
1310
+ distance.set(candidate, depth);
1311
+ next.push(candidate);
1312
+ }
1313
+ }
1314
+ frontier = next;
1315
+ }
1316
+
1317
+ distance.delete(nodeId);
1318
+ if (distance.size === 0) return [];
1319
+
1320
+ // Archived and superseded nodes are excluded HERE rather than by callers.
1321
+ // Edges deliberately survive both — that is what keeps the reasoning trail
1322
+ // intact — so a traversal that does not filter will happily walk into a
1323
+ // memory the user has already forgotten and present it as a live
1324
+ // connection. That was visible in the inspector and in the MCP
1325
+ // `neighbours` action while retrieval, which does filter, looked correct.
1326
+ const nodes = this.getByIds([...distance.keys()]).filter(node => {
1327
+ if (!options.includeArchived && node.archivedAt) return false;
1328
+ if (!options.includeSuperseded && node.supersededBy) return false;
1329
+ return true;
1330
+ });
1331
+ return nodes
1332
+ .map(node => ({ node, hops: distance.get(node.id) ?? 1 }))
1333
+ .sort((a, b) => a.hops - b.hops);
1334
+ },
1335
+
1336
+ // ── listing & stats ─────────────────────────────────────────────────────
1337
+
1338
+ /**
1339
+ * Nodes for the graph view. `projectId === undefined` means every project —
1340
+ * the cross-project view; `null` means global-scope nodes only.
1341
+ */
1342
+ list(filter: GraphListFilter & { limit?: number }): GraphNode[] {
1343
+ const { where, params } = buildNodeFilter(filter);
1344
+
1345
+ const clause = where.length ? `WHERE ${where.join(' AND ')}` : '';
1346
+ params.push(filter.limit ?? 2000);
1347
+
1348
+ const rows = getDatabase()
1349
+ .prepare(
1350
+ `SELECT * FROM graph_nodes ${clause}
1351
+ ORDER BY pinned DESC, weight DESC, updated_at DESC
1352
+ LIMIT ?`
1353
+ )
1354
+ .all(...params) as GraphNodeRow[];
1355
+ return rows.map(toNode);
1356
+ },
1357
+
1358
+ /**
1359
+ * Whether the graph holds any live memory at all.
1360
+ *
1361
+ * `EXISTS`, not `COUNT`, because the only caller runs on every turn and only
1362
+ * needs to know whether to bother saying anything.
1363
+ */
1364
+ hasEpisodic(): boolean {
1365
+ const row = getDatabase()
1366
+ .prepare(
1367
+ `SELECT 1 AS present FROM graph_nodes
1368
+ WHERE kind = 'episodic' AND archived_at IS NULL AND superseded_by IS NULL
1369
+ LIMIT 1`
1370
+ )
1371
+ .get() as { present: number } | null;
1372
+ return row !== null && row !== undefined;
1373
+ },
1374
+
1375
+ /** Count matching the same filter as `list`, before the display cap. */
1376
+ count(filter: GraphListFilter): number {
1377
+ const { where, params } = buildNodeFilter(filter);
1378
+ const clause = where.length ? `WHERE ${where.join(' AND ')}` : '';
1379
+ const row = getDatabase().prepare(`SELECT COUNT(*) AS c FROM graph_nodes ${clause}`).get(...params) as {
1380
+ c: number;
1381
+ };
1382
+ return row.c;
1383
+ },
1384
+
1385
+ /** Chronological memories for a session or project — backs the timeline view. */
1386
+ timeline(filter: { projectId?: string | null; sessionId?: string | null; limit?: number }): GraphNode[] {
1387
+ const where: string[] = [`archived_at IS NULL`, `superseded_by IS NULL`, `kind = 'episodic'`];
1388
+ const params: unknown[] = [];
1389
+
1390
+ if (filter.sessionId) {
1391
+ where.push(`session_id = ?`);
1392
+ params.push(filter.sessionId);
1393
+ } else if (filter.projectId !== undefined && filter.projectId !== null) {
1394
+ where.push(`project_id = ?`);
1395
+ params.push(filter.projectId);
1396
+ }
1397
+ params.push(filter.limit ?? 100);
1398
+
1399
+ const rows = getDatabase()
1400
+ .prepare(`SELECT * FROM graph_nodes WHERE ${where.join(' AND ')} ORDER BY created_at DESC LIMIT ?`)
1401
+ .all(...params) as GraphNodeRow[];
1402
+ return rows.map(toNode);
1403
+ },
1404
+
1405
+ stats(): GraphStats {
1406
+ const db = getDatabase();
1407
+ const one = (sql: string, ...params: unknown[]): number =>
1408
+ (db.prepare(sql).get(...params) as { c: number }).c;
1409
+
1410
+ const byScope = { session: 0, project: 0, global: 0 } as Record<GraphScope, number>;
1411
+ for (const row of db
1412
+ .prepare(`SELECT scope, COUNT(*) AS c FROM graph_nodes WHERE archived_at IS NULL GROUP BY scope`)
1413
+ .all() as { scope: GraphScope; c: number }[]) {
1414
+ byScope[row.scope] = row.c;
1415
+ }
1416
+
1417
+ const byProject = (
1418
+ db
1419
+ .prepare(
1420
+ `SELECT project_id, COUNT(*) AS c FROM graph_nodes
1421
+ WHERE archived_at IS NULL GROUP BY project_id ORDER BY c DESC`
1422
+ )
1423
+ .all() as { project_id: string | null; c: number }[]
1424
+ ).map(r => ({ projectId: r.project_id, count: r.c }));
1425
+
1426
+ const live = `archived_at IS NULL AND superseded_by IS NULL`;
1427
+ return {
1428
+ nodes: one(`SELECT COUNT(*) AS c FROM graph_nodes WHERE ${live}`),
1429
+ edges: one(`SELECT COUNT(*) AS c FROM graph_edges`),
1430
+ episodic: one(`SELECT COUNT(*) AS c FROM graph_nodes WHERE ${live} AND kind = 'episodic'`),
1431
+ structural: one(`SELECT COUNT(*) AS c FROM graph_nodes WHERE ${live} AND kind = 'structural'`),
1432
+ vectors: one(`SELECT COUNT(*) AS c FROM graph_vectors`),
1433
+ byScope,
1434
+ byProject,
1435
+ superseded: one(`SELECT COUNT(*) AS c FROM graph_nodes WHERE superseded_by IS NOT NULL`),
1436
+ forgotten: one(
1437
+ `SELECT COUNT(*) AS c FROM graph_nodes WHERE archived_at IS NOT NULL OR superseded_by IS NOT NULL`
1438
+ ),
1439
+ stale: one(`SELECT COUNT(*) AS c FROM graph_nodes WHERE ${live} AND stale_at IS NOT NULL`),
1440
+ entities: one(`SELECT COUNT(*) AS c FROM graph_nodes WHERE ${live} AND entity_key IS NOT NULL`),
1441
+ confirmedUseful: one(`SELECT COUNT(*) AS c FROM graph_nodes WHERE ${live} AND useful_count > 0`)
1442
+ };
1443
+ },
1444
+
1445
+ /**
1446
+ * Forgotten memories, newest first — what the "Forgotten" list shows.
1447
+ *
1448
+ * Archiving is a soft delete precisely so it can be reviewed, but until this
1449
+ * existed there was no way to see what had been archived, which made the
1450
+ * reviewability theoretical. Superseded nodes are deliberately included: from
1451
+ * the user's point of view "no longer recalled" is one category, even though
1452
+ * the graph distinguishes "was never true" from "is no longer true".
1453
+ */
1454
+ listArchived(filter: GraphListFilter & { limit?: number; offset?: number }): GraphNode[] {
1455
+ const where: string[] = [`(archived_at IS NOT NULL OR superseded_by IS NOT NULL)`];
1456
+ const params: unknown[] = [];
1457
+ appendProjectFilter(filter, where, params);
1458
+
1459
+ params.push(filter.limit ?? 200, filter.offset ?? 0);
1460
+ const rows = getDatabase()
1461
+ .prepare(
1462
+ `SELECT * FROM graph_nodes WHERE ${where.join(' AND ')}
1463
+ ORDER BY COALESCE(archived_at, updated_at) DESC
1464
+ LIMIT ? OFFSET ?`
1465
+ )
1466
+ .all(...params) as GraphNodeRow[];
1467
+ return rows.map(toNode);
1468
+ },
1469
+
1470
+ /** How many forgotten memories match, for the list's header and paging. */
1471
+ countArchived(filter: GraphListFilter): number {
1472
+ const where: string[] = [`(archived_at IS NOT NULL OR superseded_by IS NOT NULL)`];
1473
+ const params: unknown[] = [];
1474
+ appendProjectFilter(filter, where, params);
1475
+
1476
+ return (
1477
+ getDatabase()
1478
+ .prepare(`SELECT COUNT(*) AS c FROM graph_nodes WHERE ${where.join(' AND ')}`)
1479
+ .get(...params) as { c: number }
1480
+ ).c;
1481
+ },
1482
+
1483
+ /**
1484
+ * Permanently delete specific nodes. Edges and vectors cascade; the FTS mirror
1485
+ * is manual, as everywhere else in this file.
1486
+ *
1487
+ * This is the only hard delete a user can reach directly, and it is reached
1488
+ * only from the Forgotten list — so a memory has always been archived first.
1489
+ */
1490
+ deleteNodes(ids: string[]): number {
1491
+ if (ids.length === 0) return 0;
1492
+ const db = getDatabase();
1493
+ const placeholders = ids.map(() => '?').join(',');
1494
+
1495
+ return this.transaction(() => {
1496
+ // Counted before the delete rather than read from `changes`, which on a
1497
+ // cascading delete reports rows removed from every table rather than the
1498
+ // nodes the caller asked about.
1499
+ const existing = (
1500
+ db.prepare(`SELECT COUNT(*) AS c FROM graph_nodes WHERE id IN (${placeholders})`).get(...ids) as {
1501
+ c: number;
1502
+ }
1503
+ ).c;
1504
+
1505
+ this.dropFts(ids);
1506
+ // Nodes that pointed AT a deleted node as their current belief would be
1507
+ // left claiming to be superseded by something that no longer exists, which
1508
+ // hides them from retrieval forever with nothing to explain why. They come
1509
+ // BACK into the lexical index at the same time, for the same reason.
1510
+ const orphaned = (
1511
+ db
1512
+ .prepare(`SELECT id FROM graph_nodes WHERE superseded_by IN (${placeholders})`)
1513
+ .all(...ids) as { id: string }[]
1514
+ ).map(row => row.id);
1515
+ if (orphaned.length > 0) {
1516
+ db.prepare(
1517
+ `UPDATE graph_nodes SET superseded_by = NULL WHERE superseded_by IN (${placeholders})`
1518
+ ).run(...ids);
1519
+ }
1520
+ db.prepare(`DELETE FROM graph_nodes WHERE id IN (${placeholders})`).run(...ids);
1521
+ for (const id of orphaned) this.syncFts(id);
1522
+ return existing;
1523
+ });
1524
+ },
1525
+
1526
+ /**
1527
+ * Delete every memory in a set of projects, or in the whole instance.
1528
+ *
1529
+ * `projectIds === undefined` means EVERYTHING, including the global-scope
1530
+ * memories that belong to the user rather than to any repository. A project
1531
+ * purge deliberately does NOT touch those: preferences and conventions were
1532
+ * never that project's to hold, and losing them because one repository was
1533
+ * cleaned would be a surprise. That is why the two are separate actions in the
1534
+ * UI rather than one control with a checkbox.
1535
+ */
1536
+ purge(projectIds?: string[]): { nodes: number; edges: number } {
1537
+ const db = getDatabase();
1538
+
1539
+ return this.transaction(() => {
1540
+ const before = (db.prepare(`SELECT COUNT(*) AS c FROM graph_edges`).get() as { c: number }).c;
1541
+
1542
+ if (projectIds === undefined) {
1543
+ const nodes = (db.prepare(`SELECT COUNT(*) AS c FROM graph_nodes`).get() as { c: number }).c;
1544
+ db.prepare(`DELETE FROM graph_nodes_fts`).run();
1545
+ db.prepare(`DELETE FROM graph_nodes`).run();
1546
+ const after = (db.prepare(`SELECT COUNT(*) AS c FROM graph_edges`).get() as { c: number }).c;
1547
+ return { nodes, edges: before - after };
1548
+ }
1549
+ if (projectIds.length === 0) return { nodes: 0, edges: 0 };
1550
+
1551
+ const placeholders = projectIds.map(() => '?').join(',');
1552
+ const match = `project_id IN (${placeholders})`;
1553
+
1554
+ const doomed = (
1555
+ db.prepare(`SELECT id FROM graph_nodes WHERE ${match}`).all(...projectIds) as { id: string }[]
1556
+ ).map(row => row.id);
1557
+ if (doomed.length === 0) return { nodes: 0, edges: 0 };
1558
+
1559
+ // In chunks: a purge can cover tens of thousands of nodes, and SQLite has a
1560
+ // hard ceiling on bound parameters per statement.
1561
+ for (let i = 0; i < doomed.length; i += 400) this.dropFts(doomed.slice(i, i + 400));
1562
+
1563
+ const orphaned = (
1564
+ db
1565
+ .prepare(`SELECT id FROM graph_nodes WHERE superseded_by IN (SELECT id FROM graph_nodes WHERE ${match})`)
1566
+ .all(...projectIds) as { id: string }[]
1567
+ ).map(row => row.id);
1568
+ db.prepare(
1569
+ `UPDATE graph_nodes SET superseded_by = NULL
1570
+ WHERE superseded_by IN (SELECT id FROM graph_nodes WHERE ${match})`
1571
+ ).run(...projectIds);
1572
+ db.prepare(`DELETE FROM graph_nodes WHERE ${match}`).run(...projectIds);
1573
+ for (const id of orphaned) this.syncFts(id);
1574
+
1575
+ const after = (db.prepare(`SELECT COUNT(*) AS c FROM graph_edges`).get() as { c: number }).c;
1576
+ return { nodes: doomed.length, edges: before - after };
1577
+ });
1578
+ },
1579
+
1580
+ // ── retention ───────────────────────────────────────────────────────────
1581
+
1582
+ /**
1583
+ * Auto-written memories that have earned no place: never confirmed useful,
1584
+ * never read, low confidence, and old enough that they were not going to be.
1585
+ *
1586
+ * The predicate is deliberately conjunctive. Age alone is not decay — a
1587
+ * decision from a year ago may be the most load-bearing thing in the graph —
1588
+ * so a node has to fail every test at once before it is a candidate. Anything
1589
+ * a person touched (`source = 'user'`), pinned, or ever marked useful is
1590
+ * exempt outright.
1591
+ */
1592
+ evictionCandidates(options: { maxAgeDays: number; maxConfidence: number; limit: number }): GraphNode[] {
1593
+ const rows = getDatabase()
1594
+ .prepare(
1595
+ `SELECT * FROM graph_nodes
1596
+ WHERE kind = 'episodic'
1597
+ AND source = 'agent'
1598
+ AND pinned = 0
1599
+ AND archived_at IS NULL
1600
+ AND superseded_by IS NULL
1601
+ AND useful_count = 0
1602
+ AND access_count = 0
1603
+ AND confidence <= ?
1604
+ AND entity_key IS NULL
1605
+ AND julianday('now') - julianday(updated_at) > ?
1606
+ ORDER BY confidence ASC, updated_at ASC
1607
+ LIMIT ?`
1608
+ )
1609
+ .all(options.maxConfidence, options.maxAgeDays, options.limit) as GraphNodeRow[];
1610
+ return rows.map(toNode);
1611
+ },
1612
+
1613
+ /**
1614
+ * Permanently remove archived auto-written nodes older than `maxAgeDays`.
1615
+ *
1616
+ * Archiving is reversible on purpose, but "reversible forever" means the table
1617
+ * only grows. A node a person archived by hand is never purged here — undoing
1618
+ * that is exactly the case soft-delete exists for.
1619
+ */
1620
+ purgeArchived(maxAgeDays: number, limit: number): number {
1621
+ const db = getDatabase();
1622
+ const ids = (
1623
+ db
1624
+ .prepare(
1625
+ `SELECT id FROM graph_nodes
1626
+ WHERE archived_at IS NOT NULL
1627
+ AND source = 'agent'
1628
+ AND pinned = 0
1629
+ AND julianday('now') - julianday(archived_at) > ?
1630
+ LIMIT ?`
1631
+ )
1632
+ .all(maxAgeDays, limit) as { id: string }[]
1633
+ ).map(r => r.id);
1634
+
1635
+ if (ids.length === 0) return 0;
1636
+ const placeholders = ids.map(() => '?').join(',');
1637
+ this.dropFts(ids);
1638
+ db.prepare(`DELETE FROM graph_nodes WHERE id IN (${placeholders})`).run(...ids);
1639
+ return ids.length;
1640
+ },
1641
+
1642
+ /**
1643
+ * Structural nodes nothing in the graph depends on any more.
1644
+ *
1645
+ * This is the bound on the term that actually dominates growth. Every turn
1646
+ * writes a node per changed file, per directory and up to twenty-five per
1647
+ * file's symbols, so on a repository under active development the structural
1648
+ * half outgrows the episodic half by an order of magnitude — and episodic
1649
+ * retention does not touch it, because none of those queries look at
1650
+ * `kind = 'structural'`.
1651
+ *
1652
+ * What is safe to remove is narrow and stays narrow: a `symbol` or `module`
1653
+ * node, untouched for `maxAgeDays`, that NO memory is `about`. A file node is
1654
+ * spared even when nothing points at it — it is the anchor a path lookup
1655
+ * resolves to, and `invalidate.ts` already retires files the moment the disk
1656
+ * says they are gone, which is better evidence than age. Anything a memory
1657
+ * hangs off is spared outright: deleting it would sever the `about` edge that
1658
+ * is the entire reason both halves live in one graph.
1659
+ */
1660
+ pruneStructural(options: { maxAgeDays: number; limit: number }): number {
1661
+ const db = getDatabase();
1662
+ const ids = (
1663
+ db
1664
+ .prepare(
1665
+ `SELECT n.id AS id FROM graph_nodes n
1666
+ WHERE n.kind = 'structural'
1667
+ AND n.subkind IN ('symbol', 'module')
1668
+ AND n.pinned = 0
1669
+ AND n.source != 'user'
1670
+ AND julianday('now') - julianday(n.updated_at) > ?
1671
+ AND NOT EXISTS (
1672
+ SELECT 1 FROM graph_edges e WHERE e.rel = 'about' AND e.dst_id = n.id
1673
+ )
1674
+ ORDER BY n.updated_at ASC
1675
+ LIMIT ?`
1676
+ )
1677
+ .all(options.maxAgeDays, options.limit) as { id: string }[]
1678
+ ).map(r => r.id);
1679
+
1680
+ if (ids.length === 0) return 0;
1681
+ const placeholders = ids.map(() => '?').join(',');
1682
+ this.dropFts(ids);
1683
+ db.prepare(`DELETE FROM graph_nodes WHERE id IN (${placeholders})`).run(...ids);
1684
+ return ids.length;
1685
+ },
1686
+
1687
+ /**
1688
+ * Structural nodes whose file no longer exists on disk, so the graph stops
1689
+ * pointing agents at paths that are gone. Symbols of a removed file go with
1690
+ * it — a symbol has no meaning without the file that defined it.
1691
+ */
1692
+ archiveMissingFiles(projectId: string, paths: string[]): number {
1693
+ if (paths.length === 0) return 0;
1694
+ const placeholders = paths.map(() => '?').join(',');
1695
+ const ids = (
1696
+ getDatabase()
1697
+ .prepare(
1698
+ `SELECT id FROM graph_nodes
1699
+ WHERE project_id = ? AND kind = 'structural' AND path IN (${placeholders})
1700
+ AND archived_at IS NULL`
1701
+ )
1702
+ .all(projectId, ...paths) as { id: string }[]
1703
+ ).map(r => r.id);
1704
+
1705
+ return this.archiveNodes(ids);
1706
+ },
1707
+
1708
+ // ── vectors ─────────────────────────────────────────────────────────────
1709
+
1710
+ setVector(nodeId: string, dim: number, model: string, vec: Uint8Array): void {
1711
+ getDatabase()
1712
+ .prepare(
1713
+ `INSERT INTO graph_vectors (node_id, dim, model, vec, updated_at)
1714
+ VALUES (?, ?, ?, ?, CURRENT_TIMESTAMP)
1715
+ ON CONFLICT(node_id) DO UPDATE SET
1716
+ dim = excluded.dim, model = excluded.model, vec = excluded.vec,
1717
+ updated_at = CURRENT_TIMESTAMP`
1718
+ )
1719
+ .run(nodeId, dim, model, vec);
1720
+ },
1721
+
1722
+ /**
1723
+ * Nodes that still need a vector for the current model.
1724
+ *
1725
+ * EPISODIC ONLY, deliberately. A structural node is identified by a name and a
1726
+ * path, and embedding that produces a bag of path fragments rather than a
1727
+ * meaning — measured, `backend/database/queries/index.ts` scored above a
1728
+ * correct answer for two unrelated natural-language questions, because
1729
+ * mean-pooled fragments land near the middle of the space where everything
1730
+ * looks vaguely similar. Names and paths are precisely what BM25 is best at,
1731
+ * so structural nodes lose nothing by staying lexical.
1732
+ *
1733
+ * Code is still reachable semantically, just not directly: a question finds
1734
+ * the memory *about* a file, and graph expansion crosses the `about` edge to
1735
+ * the file itself. That is the intended route — and the reason both kinds of
1736
+ * memory live in one graph.
1737
+ */
1738
+ nodesMissingVectors(model: string, limit: number = 200): GraphNode[] {
1739
+ const rows = getDatabase()
1740
+ .prepare(
1741
+ `SELECT n.* FROM graph_nodes n
1742
+ LEFT JOIN graph_vectors v ON v.node_id = n.id AND v.model = ?
1743
+ WHERE n.archived_at IS NULL AND n.superseded_by IS NULL
1744
+ AND n.kind = 'episodic' AND n.entity_key IS NULL AND v.node_id IS NULL
1745
+ ORDER BY n.updated_at DESC
1746
+ LIMIT ?`
1747
+ )
1748
+ .all(model, limit) as GraphNodeRow[];
1749
+ return rows.map(toNode);
1750
+ },
1751
+
1752
+ /** Text to embed for a node — the same basis the lexical index uses. */
1753
+ embeddableText(node: GraphNode): string {
1754
+ return indexedText(node);
1755
+ },
1756
+
1757
+ /** Drop vectors written by a different artifact version. */
1758
+ pruneVectorsForOtherModels(model: string): number {
1759
+ const result = getDatabase().prepare(`DELETE FROM graph_vectors WHERE model != ?`).run(model) as {
1760
+ changes?: number;
1761
+ };
1762
+ return Number(result.changes ?? 0);
1763
+ }
1764
+ };