@myrialabs/clopen 0.4.37 → 0.4.39

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 (193) hide show
  1. package/README.md +2 -2
  2. package/backend/auth/permissions.ts +39 -0
  3. package/backend/bootstrap.ts +16 -0
  4. package/backend/chat/stream-manager.ts +1 -1
  5. package/backend/database/crypto/envelope.test.ts +93 -0
  6. package/backend/database/crypto/envelope.ts +127 -0
  7. package/backend/database/crypto/index.ts +22 -0
  8. package/backend/database/crypto/master-key.ts +129 -0
  9. package/backend/database/crypto/secret-columns.ts +151 -0
  10. package/backend/database/migrations/071_create_notes_tables.ts +90 -0
  11. package/backend/database/migrations/072_encrypt_stored_secrets.ts +107 -0
  12. package/backend/database/migrations/073_create_integration_tables.ts +119 -0
  13. package/backend/database/migrations/074_create_work_tables.ts +94 -0
  14. package/backend/database/migrations/075_create_deploy_bindings.ts +54 -0
  15. package/backend/database/migrations/076_remove_memory_code_graph.ts +229 -0
  16. package/backend/database/migrations/077_create_integration_db_links.ts +150 -0
  17. package/backend/database/migrations/index.ts +49 -0
  18. package/backend/database/queries/db-client-connection-queries.ts +42 -12
  19. package/backend/database/queries/deploy-queries.ts +124 -0
  20. package/backend/database/queries/engine-queries.ts +23 -10
  21. package/backend/database/queries/graph-queries.ts +291 -247
  22. package/backend/database/queries/index.ts +10 -1
  23. package/backend/database/queries/integration-db-link-queries.ts +168 -0
  24. package/backend/database/queries/integration-queries.ts +325 -0
  25. package/backend/database/queries/mcp-server-queries.ts +38 -11
  26. package/backend/database/queries/note-queries.test.ts +190 -0
  27. package/backend/database/queries/note-queries.ts +269 -0
  28. package/backend/database/queries/profile-queries.ts +1 -1
  29. package/backend/database/queries/ssh-connection-queries.ts +19 -8
  30. package/backend/database/queries/work-queries.ts +210 -0
  31. package/backend/db-client/integrations/index.ts +37 -0
  32. package/backend/db-client/integrations/links.ts +533 -0
  33. package/backend/db-client/integrations/projector.test.ts +280 -0
  34. package/backend/db-client/integrations/projector.ts +256 -0
  35. package/backend/db-client/integrations/supabase-service.ts +266 -0
  36. package/backend/db-client/providers/registry.ts +27 -0
  37. package/backend/db-client/providers/supabase/adapter.ts +500 -0
  38. package/backend/db-client/providers/supabase/api-types.ts +92 -0
  39. package/backend/db-client/providers/supabase/apply-migration.ts +104 -0
  40. package/backend/db-client/providers/supabase/client.ts +259 -0
  41. package/backend/db-client/providers/supabase/features.ts +502 -0
  42. package/backend/db-client/providers/supabase/local.test.ts +78 -0
  43. package/backend/db-client/providers/supabase/local.ts +137 -0
  44. package/backend/db-client/providers/types.ts +137 -0
  45. package/backend/deployments/bindings.test.ts +43 -0
  46. package/backend/deployments/bindings.ts +216 -0
  47. package/backend/deployments/index.ts +53 -0
  48. package/backend/deployments/log-streams.ts +214 -0
  49. package/backend/deployments/prompts.ts +70 -0
  50. package/backend/deployments/providers/vercel/adapter.ts +757 -0
  51. package/backend/deployments/providers/vercel/build-logs.test.ts +80 -0
  52. package/backend/deployments/providers/vercel/build-logs.ts +211 -0
  53. package/backend/deployments/providers/vercel/client.ts +203 -0
  54. package/backend/deployments/providers/vercel/list.test.ts +624 -0
  55. package/backend/deployments/providers/vercel/normalise.test.ts +115 -0
  56. package/backend/deployments/providers/vercel/normalise.ts +113 -0
  57. package/backend/deployments/providers/vercel/types.ts +104 -0
  58. package/backend/deployments/registry.ts +27 -0
  59. package/backend/deployments/service.ts +458 -0
  60. package/backend/deployments/types.ts +278 -0
  61. package/backend/engine/docs/artifacts.md +22 -9
  62. package/backend/files/os-clipboard.test.ts +209 -0
  63. package/backend/files/os-clipboard.ts +567 -0
  64. package/backend/http/integration-hooks.ts +42 -0
  65. package/backend/http/notes-images.test.ts +228 -0
  66. package/backend/http/notes-images.ts +196 -0
  67. package/backend/index.ts +13 -0
  68. package/backend/integrations/accounts.ts +229 -0
  69. package/backend/integrations/health.ts +146 -0
  70. package/backend/integrations/index.ts +36 -0
  71. package/backend/integrations/projections/index.ts +0 -0
  72. package/backend/integrations/projections/mcp-projector.test.ts +204 -0
  73. package/backend/integrations/projections/mcp-projector.ts +163 -0
  74. package/backend/integrations/projections/types.ts +63 -0
  75. package/backend/integrations/registry/define.ts +38 -0
  76. package/backend/integrations/registry/index.ts +60 -0
  77. package/backend/integrations/registry/providers/context7.ts +44 -0
  78. package/backend/integrations/registry/providers/firecrawl.ts +41 -0
  79. package/backend/integrations/registry/providers/github.ts +78 -0
  80. package/backend/integrations/registry/providers/supabase.ts +61 -0
  81. package/backend/integrations/registry/providers/vercel.ts +46 -0
  82. package/backend/integrations/registry/types.ts +96 -0
  83. package/backend/integrations/webhooks/gateway.ts +160 -0
  84. package/backend/integrations/webhooks/verify.ts +65 -0
  85. package/backend/mcp/README.md +25 -3
  86. package/backend/mcp/external/config.ts +35 -1
  87. package/backend/mcp/index.ts +1 -1
  88. package/backend/mcp/internal/config.ts +1 -1
  89. package/backend/mcp/internal/servers/memory-graph/description.ts +3 -3
  90. package/backend/mcp/internal/servers/memory-graph/runner.ts +4 -9
  91. package/backend/mcp/internal/servers/memory-graph/schema.ts +0 -4
  92. package/backend/memory/README.md +57 -34
  93. package/backend/memory/compose.test.ts +3 -3
  94. package/backend/memory/compose.ts +6 -9
  95. package/backend/memory/config.ts +0 -5
  96. package/backend/memory/consolidate.ts +1 -2
  97. package/backend/memory/context.test.ts +8 -54
  98. package/backend/memory/context.ts +19 -25
  99. package/backend/memory/extract/episodic.ts +10 -12
  100. package/backend/memory/extract/index.ts +23 -52
  101. package/backend/memory/extract/scheduler.ts +3 -6
  102. package/backend/memory/index.ts +6 -5
  103. package/backend/memory/invalidate.ts +36 -48
  104. package/backend/memory/layout.ts +319 -130
  105. package/backend/memory/retention.ts +12 -42
  106. package/backend/memory/retrieval.eval.test.ts +2 -2
  107. package/backend/memory/retrieval.test.ts +228 -183
  108. package/backend/memory/retrieval.ts +22 -21
  109. package/backend/memory/revise.test.ts +62 -116
  110. package/backend/memory/revise.ts +0 -1
  111. package/backend/memory/view.ts +8 -5
  112. package/backend/notes/access.test.ts +82 -0
  113. package/backend/notes/access.ts +27 -0
  114. package/backend/notes/storage.test.ts +77 -0
  115. package/backend/notes/storage.ts +114 -0
  116. package/backend/permissions/service.ts +2 -2
  117. package/backend/profiles/service.ts +1 -1
  118. package/backend/projects/project-cleanup.ts +6 -0
  119. package/backend/snapshot/helpers.ts +35 -41
  120. package/backend/snapshot/snapshot-service.ts +90 -0
  121. package/backend/snapshot/turn-changes.test.ts +163 -0
  122. package/backend/snapshot/turn-changes.ts +131 -0
  123. package/backend/work/bindings.ts +124 -0
  124. package/backend/work/index.ts +42 -0
  125. package/backend/work/prompts.ts +150 -0
  126. package/backend/work/providers/github/actions-logs.ts +180 -0
  127. package/backend/work/providers/github/adapter.test.ts +88 -0
  128. package/backend/work/providers/github/adapter.ts +1255 -0
  129. package/backend/work/providers/github/client.ts +280 -0
  130. package/backend/work/providers/github/list-range.test.ts +158 -0
  131. package/backend/work/providers/github/token-kind.test.ts +42 -0
  132. package/backend/work/pull-requests.ts +242 -0
  133. package/backend/work/registry.ts +27 -0
  134. package/backend/work/service.ts +436 -0
  135. package/backend/work/start-work.test.ts +71 -0
  136. package/backend/work/start-work.ts +232 -0
  137. package/backend/work/types.ts +180 -0
  138. package/backend/ws/db-client/accounts.ts +225 -0
  139. package/backend/ws/db-client/connections.ts +34 -3
  140. package/backend/ws/db-client/context.ts +37 -0
  141. package/backend/ws/db-client/index.ts +20 -1
  142. package/backend/ws/db-client/supabase.ts +188 -0
  143. package/backend/ws/deployments/actions.ts +360 -0
  144. package/backend/ws/deployments/context.ts +43 -0
  145. package/backend/ws/deployments/crud.ts +152 -0
  146. package/backend/ws/deployments/index.ts +15 -0
  147. package/backend/ws/deployments/schemas.ts +183 -0
  148. package/backend/ws/files/clipboard.ts +78 -0
  149. package/backend/ws/files/index.ts +5 -0
  150. package/backend/ws/git/diff-budget.ts +70 -11
  151. package/backend/ws/index.ts +16 -2
  152. package/backend/ws/integrations/crud.ts +219 -0
  153. package/backend/ws/integrations/index.ts +22 -0
  154. package/backend/ws/mcp/crud.ts +25 -1
  155. package/backend/ws/memory/crud.ts +4 -16
  156. package/backend/ws/notes/index.ts +278 -0
  157. package/backend/ws/profiles/crud.ts +1 -1
  158. package/backend/ws/snapshot/changes.ts +279 -0
  159. package/backend/ws/snapshot/index.ts +4 -3
  160. package/backend/ws/work/actions.ts +206 -0
  161. package/backend/ws/work/context.ts +51 -0
  162. package/backend/ws/work/crud.ts +347 -0
  163. package/backend/ws/work/index.ts +17 -0
  164. package/backend/ws/work/pull-requests.ts +177 -0
  165. package/backend/ws/work/schemas.ts +226 -0
  166. package/dist/assets/{index-sJmS_CCm.js → index-BrF6nqld.js} +1 -1
  167. package/dist/assets/{index-Bik9TCBi.js → index-C8Gi-b6U.js} +1 -1
  168. package/dist/assets/main-Bd3gb79F.css +1 -0
  169. package/dist/assets/main-Bo1hD7mt.js +1191 -0
  170. package/dist/index.html +2 -2
  171. package/package.json +1 -1
  172. package/shared/constants/engine-tools.ts +1 -1
  173. package/shared/constants/tool-icons.ts +42 -0
  174. package/shared/types/database/schema.ts +41 -0
  175. package/shared/types/db-client/connection.ts +6 -0
  176. package/shared/types/db-client/index.ts +2 -0
  177. package/shared/types/db-client/integrations.ts +174 -0
  178. package/shared/types/db-client/supabase.ts +131 -0
  179. package/shared/types/deployments.ts +382 -0
  180. package/shared/types/integrations.ts +140 -0
  181. package/shared/types/memory.ts +34 -51
  182. package/shared/types/stores/settings.ts +8 -0
  183. package/shared/types/ui/components.ts +1 -1
  184. package/shared/types/work.ts +426 -0
  185. package/shared/utils/diff-calculator.test.ts +89 -0
  186. package/shared/utils/diff-calculator.ts +30 -65
  187. package/shared/utils/logger.ts +4 -0
  188. package/backend/memory/extract/languages.ts +0 -176
  189. package/backend/memory/extract/structural.test.ts +0 -215
  190. package/backend/memory/extract/structural.ts +0 -364
  191. package/backend/ws/snapshot/content.ts +0 -85
  192. package/dist/assets/main-DLqolBI2.css +0 -1
  193. package/dist/assets/main-Df1I3hnw.js +0 -1096
@@ -27,7 +27,6 @@ import type {
27
27
  GraphEdgeInput,
28
28
  GraphNode,
29
29
  GraphNodeInput,
30
- GraphNodeKind,
31
30
  GraphRelation,
32
31
  GraphScope,
33
32
  GraphSource,
@@ -36,16 +35,12 @@ import type {
36
35
 
37
36
  interface GraphNodeRow {
38
37
  id: string;
39
- kind: GraphNodeKind;
40
38
  subkind: string;
41
39
  scope: GraphScope;
42
40
  project_id: string | null;
43
41
  session_id: string | null;
44
42
  label: string;
45
43
  body: string;
46
- path: string | null;
47
- symbol: string | null;
48
- language: string | null;
49
44
  digest: string;
50
45
  confidence: number;
51
46
  weight: number;
@@ -81,16 +76,12 @@ interface GraphEdgeRow {
81
76
  function toNode(row: GraphNodeRow): GraphNode {
82
77
  return {
83
78
  id: row.id,
84
- kind: row.kind,
85
79
  subkind: row.subkind as GraphNode['subkind'],
86
80
  scope: row.scope,
87
81
  projectId: row.project_id,
88
82
  sessionId: row.session_id,
89
83
  label: row.label,
90
84
  body: row.body,
91
- path: row.path,
92
- symbol: row.symbol,
93
- language: row.language,
94
85
  digest: row.digest,
95
86
  confidence: row.confidence,
96
87
  weight: row.weight,
@@ -125,22 +116,28 @@ function toEdge(row: GraphEdgeRow): GraphEdge {
125
116
  }
126
117
 
127
118
  /**
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
119
+ * Text a memory contributes to the lexical index: its label, its body, the
120
+ * subjects it names and the files it claims something about.
121
+ *
122
+ * Both attributes are joined in for the same reason. They used to be findable
123
+ * because each was a NODE — an entity node, a file node — and a question that
124
+ * named one reached the memory by an edge. Nothing stands in for them now, so
125
+ * unless the memory carries them into its own indexed text, "what do we know
126
+ * about Bun" matches only memories that happen to spell Bun in their prose, and
127
+ * a pasted path matches nothing at all.
128
+ *
129
+ * Paths are also split on their separators so `sdk-loader` matches
130
130
  * `backend/engine/sdk-loader.ts` — BM25 tokenizes on word boundaries and would
131
131
  * otherwise treat the whole path as one opaque term.
132
132
  */
133
- function indexedText(node: Pick<GraphNode, 'label' | 'body' | 'path' | 'symbol'> & { entityNames?: string[] }): string {
133
+ function indexedText(
134
+ node: Pick<GraphNode, 'label' | 'body'> & { entityNames?: string[]; paths?: string[] }
135
+ ): string {
134
136
  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
137
  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(' '));
138
+ for (const path of node.paths ?? []) {
139
+ parts.push(path);
140
+ parts.push(path.split(/[/\\._-]+/).filter(Boolean).join(' '));
144
141
  }
145
142
  return parts.filter(Boolean).join('\n').trim();
146
143
  }
@@ -154,6 +151,20 @@ function indexedText(node: Pick<GraphNode, 'label' | 'body' | 'path' | 'symbol'>
154
151
  */
155
152
  export const DIGEST_VERSION = 2;
156
153
 
154
+ /**
155
+ * The value written to `graph_nodes.kind`, which is now always the same one.
156
+ *
157
+ * The column survives migration 076 as a constant rather than being dropped: it
158
+ * is part of the unique digest index and of the FTS mirror's schema, and
159
+ * rebuilding both across a live memory store to reclaim one constant column
160
+ * would be real risk for no benefit. Nothing above this file has the concept.
161
+ *
162
+ * The SQL that still spells `kind = 'episodic'` is not leftover: those queries
163
+ * are served by PARTIAL indexes declared on that predicate (migration 066), and
164
+ * dropping it from the WHERE would make them unusable.
165
+ */
166
+ const NODE_KIND = 'episodic';
167
+
157
168
  /**
158
169
  * Most terms one FTS5 MATCH may carry. See `buildFtsQuery` for why there is a
159
170
  * bound at all; 32 is comfortably more than any real question and far below the
@@ -194,8 +205,17 @@ export function entityKeyFor(name: string): string | null {
194
205
  }
195
206
 
196
207
  /**
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
208
+ * One spelling for a repo-relative path, so the same file is one key however it
209
+ * was typed. Backslashes become slashes, a leading `./` goes, and a leading `/`
210
+ * with it — a model asked for repo-relative paths returns absolute ones often
211
+ * enough that silently storing both forms is a real cost.
212
+ */
213
+ export function normalizePath(path: string): string {
214
+ return path.trim().replace(/\\/g, '/').replace(/^\.\//, '').replace(/^\/+/, '');
215
+ }
216
+
217
+ /**
218
+ * Stable identity for a node when the caller does not supply one: its normalized
199
219
  * claim, so the same decision phrased with different whitespace or casing
200
220
  * reinforces rather than duplicates.
201
221
  *
@@ -213,22 +233,8 @@ export function deriveDigest(input: GraphNodeInput): string {
213
233
  return sha(`entity:${input.entityKey}`);
214
234
  }
215
235
 
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);
236
+ const claim = (input.label + ' ' + (input.body ?? '')).toLowerCase().replace(/\s+/g, ' ').trim();
237
+ return sha(`${input.subkind}:${claim}`);
232
238
  }
233
239
 
234
240
  /** 20 hex characters of SHA-256 — 80 bits, far past collision risk at this scale. */
@@ -239,10 +245,11 @@ function sha(basis: string): string {
239
245
  /**
240
246
  * What a caller may narrow a listing by.
241
247
  *
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.
248
+ * `subkinds` and `sources` are what the filter is actually made of. A kind
249
+ * toggle used to sit above them — memories or code — and it could not answer any
250
+ * real question of the graph: "show only what the user stated, not what was
251
+ * inferred", or "only the failures". It went with the code half in migration
252
+ * 076, and these are what remain, both attributes the store always carried.
246
253
  */
247
254
  export interface GraphListFilter {
248
255
  /** `undefined` = every project; `null` = global-scope nodes only. */
@@ -253,7 +260,6 @@ export interface GraphListFilter {
253
260
  * narrowing, not an absence of one.
254
261
  */
255
262
  projectIds?: string[];
256
- kinds?: GraphNodeKind[];
257
263
  subkinds?: string[];
258
264
  scopes?: GraphScope[];
259
265
  sources?: GraphSource[];
@@ -269,6 +275,17 @@ export interface GraphListFilter {
269
275
  * Kept in one place because the three drifting apart is how a node ends up
270
276
  * counted but not shown, or shown in the graph after being forgotten.
271
277
  */
278
+ /**
279
+ * An edge nothing stored: two memories grouped by something they both name.
280
+ * `via` is kept because the view colours by it and the weights differ per source.
281
+ */
282
+ export interface DerivedEdge {
283
+ srcId: string;
284
+ dstId: string;
285
+ weight: number;
286
+ via: 'subject' | 'path' | 'project';
287
+ }
288
+
272
289
  /**
273
290
  * An id set as ONE bound parameter instead of one placeholder per id.
274
291
  *
@@ -328,10 +345,6 @@ function buildNodeFilter(
328
345
  const params: unknown[] = [];
329
346
 
330
347
  appendProjectFilter(filter, where, params, as);
331
- if (filter.kinds?.length) {
332
- where.push(`${as}kind IN (${filter.kinds.map(() => '?').join(',')})`);
333
- params.push(...filter.kinds);
334
- }
335
348
  if (filter.subkinds?.length) {
336
349
  where.push(`${as}subkind IN (${filter.subkinds.map(() => '?').join(',')})`);
337
350
  params.push(...filter.subkinds);
@@ -378,7 +391,7 @@ export const graphQueries = {
378
391
  `SELECT * FROM graph_nodes
379
392
  WHERE COALESCE(project_id, '') = COALESCE(?, '') AND kind = ? AND digest = ?`
380
393
  )
381
- .get(projectId, input.kind, digest) as GraphNodeRow | null;
394
+ .get(projectId, NODE_KIND, digest) as GraphNodeRow | null;
382
395
 
383
396
  if (existing) {
384
397
  const source = input.source ?? 'agent';
@@ -430,21 +443,18 @@ export const graphQueries = {
430
443
  db.prepare(
431
444
  `INSERT INTO graph_nodes (
432
445
  id, kind, subkind, scope, project_id, session_id, label, body,
433
- path, symbol, language, digest, confidence, source, pinned,
446
+ digest, confidence, source, pinned,
434
447
  entity_key, digest_version, asserted_by, reach, reach_judged
435
- ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`
448
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`
436
449
  ).run(
437
450
  id,
438
- input.kind,
451
+ NODE_KIND,
439
452
  input.subkind,
440
453
  input.scope ?? (projectId ? 'project' : 'global'),
441
454
  projectId,
442
455
  input.sessionId ?? null,
443
456
  input.label,
444
457
  input.body ?? '',
445
- input.path ?? null,
446
- input.symbol ?? null,
447
- input.language ?? null,
448
458
  digest,
449
459
  input.confidence ?? 0.5,
450
460
  input.source ?? 'agent',
@@ -452,10 +462,8 @@ export const graphQueries = {
452
462
  input.entityKey ?? null,
453
463
  DIGEST_VERSION,
454
464
  input.assertedBy ?? 'inferred',
455
- // Structural nodes are a repository's files and never travel, whatever a
456
- // caller passes.
457
- input.kind === 'structural' ? 'here' : (input.reach ?? 'here'),
458
- input.kind === 'structural' || input.reachJudged ? 1 : 0
465
+ input.reach ?? 'here',
466
+ input.reachJudged ? 1 : 0
459
467
  );
460
468
 
461
469
  this.syncFts(id);
@@ -475,26 +483,13 @@ export const graphQueries = {
475
483
  return rows.map(toNode);
476
484
  },
477
485
 
478
- /** Structural node for a repo-relative path, when one exists. */
479
- getByPath(projectId: string | null, path: string): GraphNode | null {
480
- const row = getDatabase()
481
- .prepare(
482
- `SELECT * FROM graph_nodes
483
- WHERE COALESCE(project_id, '') = COALESCE(?, '') AND kind = 'structural' AND path = ?
484
- ORDER BY CASE subkind WHEN 'file' THEN 0 ELSE 1 END
485
- LIMIT 1`
486
- )
487
- .get(projectId, path) as GraphNodeRow | null;
488
- return row ? toNode(row) : null;
489
- },
490
-
491
486
  /**
492
487
  * Edit the human-facing fields of a node (the graph editor's save path).
493
488
  *
494
489
  * `source` is a PARAMETER, not a constant, and getting that wrong was quietly
495
490
  * expensive. This used to hard-code `'user'`, and the MCP `update` action goes
496
491
  * through here — so one edit by an agent made the node permanently exempt from
497
- * structural decay (`markStale` skips `source = 'user'`), from eviction, and
492
+ * staleness decay (`markStale` skips `source = 'user'`), from eviction, and
498
493
  * from consolidation, while the injected block advertised it to every future
499
494
  * turn as "stated by user". A model's correction was being given a human's
500
495
  * authority.
@@ -526,7 +521,7 @@ export const graphQueries = {
526
521
  // to promote it to the user's word. Same reasoning as `source` being a
527
522
  // parameter here rather than a constant.
528
523
  source === 'user' ? 'user' : current.assertedBy,
529
- current.kind === 'structural' ? 'here' : (patch.reach ?? current.reach),
524
+ patch.reach ?? current.reach,
530
525
  id
531
526
  );
532
527
 
@@ -535,21 +530,18 @@ export const graphQueries = {
535
530
  // overwrite the edit. Re-deriving re-parents identity onto what the user
536
531
  // actually wrote.
537
532
  const updated = this.getById(id)!;
538
- if (updated.kind === 'episodic') {
539
- const digest = deriveDigest({
540
- kind: updated.kind,
541
- subkind: updated.subkind,
542
- label: updated.label,
543
- body: updated.body
544
- });
545
- const clash = db
546
- .prepare(
547
- `SELECT id FROM graph_nodes
548
- WHERE COALESCE(project_id, '') = COALESCE(?, '') AND kind = ? AND digest = ? AND id != ?`
549
- )
550
- .get(updated.projectId, updated.kind, digest, id) as { id: string } | null;
551
- if (!clash) db.prepare(`UPDATE graph_nodes SET digest = ? WHERE id = ?`).run(digest, id);
552
- }
533
+ const digest = deriveDigest({
534
+ subkind: updated.subkind,
535
+ label: updated.label,
536
+ body: updated.body
537
+ });
538
+ const clash = db
539
+ .prepare(
540
+ `SELECT id FROM graph_nodes
541
+ WHERE COALESCE(project_id, '') = COALESCE(?, '') AND kind = ? AND digest = ? AND id != ?`
542
+ )
543
+ .get(updated.projectId, NODE_KIND, digest, id) as { id: string } | null;
544
+ if (!clash) db.prepare(`UPDATE graph_nodes SET digest = ? WHERE id = ?`).run(digest, id);
553
545
 
554
546
  this.syncFts(id);
555
547
  // The vector describes text that just changed, so it must be recomputed.
@@ -647,22 +639,28 @@ export const graphQueries = {
647
639
  },
648
640
 
649
641
  /**
650
- * Structural nodes for a set of repo-relative paths, in one query.
642
+ * Memories that claim something about any of a set of repo-relative paths.
651
643
  *
652
- * Used to turn the files a session is working in into retrieval seeds, so the
653
- * lookup happens once per turn rather than once per path.
644
+ * The one question the structural half existed to answer, asked directly.
645
+ * Retrieval uses it to turn the files a session is working in into seeds, and
646
+ * invalidation uses it to find what a change has aged — both once per turn
647
+ * rather than once per path, and both as an index seek rather than a walk
648
+ * through file nodes that stood in for the strings.
654
649
  */
655
- getByPaths(projectId: string | null, paths: string[]): GraphNode[] {
650
+ nodesForPaths(projectId: string | null, paths: string[], limit = 60): GraphNode[] {
656
651
  if (paths.length === 0) return [];
657
652
  const placeholders = paths.map(() => '?').join(',');
658
653
  const rows = getDatabase()
659
654
  .prepare(
660
- `SELECT * FROM graph_nodes
661
- WHERE COALESCE(project_id, '') = COALESCE(?, '')
662
- AND kind = 'structural' AND subkind = 'file'
663
- AND archived_at IS NULL AND path IN (${placeholders})`
655
+ `SELECT DISTINCT n.* FROM graph_node_paths p
656
+ INNER JOIN graph_nodes n ON n.id = p.node_id
657
+ WHERE COALESCE(n.project_id, '') = COALESCE(?, '')
658
+ AND p.path IN (${placeholders})
659
+ AND n.archived_at IS NULL AND n.superseded_by IS NULL
660
+ ORDER BY n.pinned DESC, n.weight DESC, n.updated_at DESC
661
+ LIMIT ?`
664
662
  )
665
- .all(projectId, ...paths) as GraphNodeRow[];
663
+ .all(projectId, ...paths, limit) as GraphNodeRow[];
666
664
  return rows.map(toNode);
667
665
  },
668
666
 
@@ -762,7 +760,8 @@ export const graphQueries = {
762
760
  // ── entities ────────────────────────────────────────────────────────────
763
761
 
764
762
  /**
765
- * Record what a memory is about, replacing whatever was recorded before.
763
+ * Record which subjects a memory is about, replacing whatever was recorded
764
+ * before.
766
765
  *
767
766
  * Replace rather than append, because extraction re-reads the same memory
768
767
  * whenever it is reinforced and a later reading is a better one — appending
@@ -825,41 +824,65 @@ export const graphQueries = {
825
824
  * memory's entities are rewritten, and no way for an edge to outlive the claim
826
825
  * it came from.
827
826
  *
828
- * Two bounds, both about hubs.
827
+ * THREE GROUPINGS: a shared subject, a shared FILE, and the same codebase, in
828
+ * descending order of what they say about two memories. The file grouping is
829
+ * what the code half used to provide by accident — two memories about
830
+ * `retrieval.ts` were joined through the file NODE sitting between them — and
831
+ * migration 076 kept the attribution while dropping the connection. 985 of one
832
+ * real graph's 2,062 memories share a file with another; none of it was drawn.
829
833
  *
830
- * A subject shared by a large slice of the graph is not a relationship, it is a
831
- * word everyone happens to use. "TypeScript" across forty memories says nothing
832
- * about any two of them, and connecting them all would recreate the
833
- * fabricated-structure problem from a different cause. `MAX_SUBJECT_MEMBERS`
834
- * drops those.
834
+ * A LARGE GROUP IS DAMPED, NOT DISCARDED, and that correction is why this is
835
+ * worth reading twice. The rule used to be that a group of more than two dozen
836
+ * is "a word everyone happens to use" and got dropped outright. Measured on a
837
+ * real graph the sixteen groups it discarded were `Clopen` (496 members),
838
+ * `Arga` (299), `wpuploader` (131), `nna-dms-backend` (130) — product and
839
+ * project names, which is to say the most meaningful lobes the picture could
840
+ * have had. It threw away 1,627 memberships and left 62% of the graph as
841
+ * isolated dots, because past a couple of thousand memories every real topic
842
+ * clears two dozen and only the incidental ones stay small.
835
843
  *
836
- * And within a subject each memory links only to the few strongest members
837
- * rather than to all of them. A clique of thirteen is seventy-eight lines
838
- * saying one thing; bounded degree says the same thing, keeps the cluster
844
+ * The concern behind the rule was still right: a subject shared by a quarter of
845
+ * the store does say less about any two of its members. So it is expressed as
846
+ * WEIGHT — divided by the log of the group's size — which is what Louvain
847
+ * actually reads. Measured, that is the difference between one lobe of 293 and
848
+ * a spread of 198/153/144/122/121.
849
+ *
850
+ * Degree stays bounded either way, which was always the real protection: each
851
+ * memory links to a few of the strongest members rather than to all of them,
852
+ * and a large group links to fewer still. A clique of thirteen is seventy-eight
853
+ * lines saying one thing; bounded degree says the same thing, keeps the cluster
839
854
  * visible, and stays linear as the graph grows.
840
855
  */
841
- derivedEdges(nodeIds: string[]): { srcId: string; dstId: string; weight: number; via: 'subject' | 'project' }[] {
856
+ derivedEdges(nodeIds: string[]): DerivedEdge[] {
842
857
  if (nodeIds.length < 2) return [];
843
858
 
844
- /** Above this a group is a common word rather than a shared topic. */
845
- const MAX_GROUP_MEMBERS = 24;
859
+ /** Past this a group is broad enough to link sparsely and weigh less. */
860
+ const LARGE_GROUP = 24;
846
861
  /** Links each memory draws per group, toward the heaviest members. */
847
862
  const LINKS_PER_MEMBER = 4;
863
+ /** …and inside a large group, where a full fan would be a hairball. */
864
+ const LINKS_IN_LARGE_GROUP = 2;
848
865
 
849
866
  const set = idSet(nodeIds);
850
- const edges: { srcId: string; dstId: string; weight: number; via: 'subject' | 'project' }[] = [];
867
+ const edges: DerivedEdge[] = [];
851
868
  const seen = new Set<string>();
852
869
 
853
870
  /** Chain a group's members, heaviest first, into bounded-degree edges. */
854
- const connect = (members: string[], weight: number, via: 'subject' | 'project'): void => {
855
- if (members.length < 2 || members.length > MAX_GROUP_MEMBERS) return;
871
+ const connect = (members: string[], weight: number, via: DerivedEdge['via']): void => {
872
+ if (members.length < 2) return;
873
+ const large = members.length > LARGE_GROUP;
874
+ const links = large ? LINKS_IN_LARGE_GROUP : LINKS_PER_MEMBER;
875
+ // `log10`, so the damping is gentle where it should be — a group of 30
876
+ // keeps 40% of its weight and one of 500 keeps 27% — rather than a cliff
877
+ // at whatever number the constant happens to be.
878
+ const scaled = large ? weight / (1 + Math.log10(members.length)) : weight;
856
879
  for (let i = 0; i < members.length; i++) {
857
- for (let j = i + 1; j < Math.min(members.length, i + 1 + LINKS_PER_MEMBER); j++) {
880
+ for (let j = i + 1; j < Math.min(members.length, i + 1 + links); j++) {
858
881
  const [a, b] = members[i] < members[j] ? [members[i], members[j]] : [members[j], members[i]];
859
882
  const key = `${a}|${b}`;
860
883
  if (seen.has(key)) continue;
861
884
  seen.add(key);
862
- edges.push({ srcId: a, dstId: b, weight, via });
885
+ edges.push({ srcId: a, dstId: b, weight: scaled, via });
863
886
  }
864
887
  }
865
888
  };
@@ -875,10 +898,7 @@ export const graphQueries = {
875
898
  )
876
899
  .all(set) as { groupKey: string; nodeId: string }[];
877
900
  // Appended, not rebuilt. Spreading the existing array on every row made this
878
- // quadratic in the size of a group — invisible for the subject groups, which
879
- // are capped at two dozen, and the dominant cost of the whole call for the
880
- // project groups, which routinely run to hundreds before the size check
881
- // below discards them.
901
+ // quadratic in the size of a group, and groups routinely run to hundreds.
882
902
  const bySubject = new Map<string, string[]>();
883
903
  for (const row of rows) {
884
904
  const members = bySubject.get(row.groupKey);
@@ -890,6 +910,28 @@ export const graphQueries = {
890
910
  // to be written first.
891
911
  for (const members of bySubject.values()) connect(members, 1, 'subject');
892
912
 
913
+ // ── shared file ──────────────────────────────────────────────────────
914
+ // Between a subject and a codebase in what it says: two memories about the
915
+ // same file are talking about the same thing far more often than two that
916
+ // merely share a repository, and less reliably than two that name the same
917
+ // subject outright.
918
+ const pathRows = getDatabase()
919
+ .prepare(
920
+ `SELECT p.path AS groupKey, p.node_id AS nodeId
921
+ FROM graph_node_paths p
922
+ INNER JOIN graph_nodes n ON n.id = p.node_id
923
+ WHERE p.node_id IN ${ID_SET}
924
+ ORDER BY p.path, n.weight DESC, n.updated_at DESC`
925
+ )
926
+ .all(set) as { groupKey: string; nodeId: string }[];
927
+ const byPath = new Map<string, string[]>();
928
+ for (const row of pathRows) {
929
+ const members = byPath.get(row.groupKey);
930
+ if (members) members.push(row.nodeId);
931
+ else byPath.set(row.groupKey, [row.nodeId]);
932
+ }
933
+ for (const members of byPath.values()) connect(members, 0.7, 'path');
934
+
893
935
  // ── same codebase ────────────────────────────────────────────────────
894
936
  // Weaker on purpose. Two memories about tunnelkit are related BECAUSE they
895
937
  // are about tunnelkit; two memories that merely live in the same repository
@@ -919,6 +961,36 @@ export const graphQueries = {
919
961
  },
920
962
 
921
963
  /** Ids sharing a subject with `nodeId`, for one hop of traversal. */
964
+ /**
965
+ * Memories that claim something about one of the same files — the traversal
966
+ * half of the `path` grouping above.
967
+ *
968
+ * Without this, removing the code half cost retrieval a route it used to have:
969
+ * a question that matched a memory about `retrieval.ts` could reach the other
970
+ * memories about that file in two hops, through the file node between them.
971
+ * `neighbours` walks this the way it walks shared subjects.
972
+ */
973
+ pathNeighbourIds(nodeId: string, limit = 12): string[] {
974
+ try {
975
+ return (
976
+ getDatabase()
977
+ .prepare(
978
+ `SELECT DISTINCT other.node_id AS id
979
+ FROM graph_node_paths mine
980
+ INNER JOIN graph_node_paths other ON other.path = mine.path
981
+ INNER JOIN graph_nodes n ON n.id = other.node_id
982
+ WHERE mine.node_id = ? AND other.node_id <> ?
983
+ AND n.archived_at IS NULL AND n.superseded_by IS NULL
984
+ ORDER BY n.weight DESC, n.updated_at DESC
985
+ LIMIT ?`
986
+ )
987
+ .all(nodeId, nodeId, limit) as { id: string }[]
988
+ ).map(row => row.id);
989
+ } catch {
990
+ return [];
991
+ }
992
+ },
993
+
922
994
  entityNeighbourIds(nodeId: string, limit = 12): string[] {
923
995
  try {
924
996
  return (
@@ -965,6 +1037,97 @@ export const graphQueries = {
965
1037
  }
966
1038
  },
967
1039
 
1040
+ // ── paths ───────────────────────────────────────────────────────────────
1041
+
1042
+ /**
1043
+ * Record which files a memory claims something about, replacing whatever was
1044
+ * recorded before.
1045
+ *
1046
+ * Replace rather than append, for the same reason `setEntities` does: a later
1047
+ * reading of the same memory is a better one, and appending would accumulate
1048
+ * every path any extraction ever associated with it — including the ones a
1049
+ * since-abandoned approach touched.
1050
+ *
1051
+ * Paths are normalized here rather than at the call sites. They arrive from a
1052
+ * model, from a disk diff and from Windows, and `backend\\memory\\x.ts`,
1053
+ * `./backend/memory/x.ts` and `backend/memory/x.ts` have to be one key or the
1054
+ * lookup that invalidation depends on quietly misses.
1055
+ */
1056
+ setPaths(nodeId: string, paths: string[]): number {
1057
+ const db = getDatabase();
1058
+ const normalized = [...new Set(paths.map(normalizePath).filter(Boolean))] as string[];
1059
+ db.prepare(`DELETE FROM graph_node_paths WHERE node_id = ?`).run(nodeId);
1060
+ const insert = db.prepare(`INSERT OR IGNORE INTO graph_node_paths (node_id, path) VALUES (?, ?)`);
1061
+ for (const path of normalized) insert.run(nodeId, path);
1062
+ // The paths are part of the memory's searchable text, so the mirror is now
1063
+ // out of date. See `indexedText`.
1064
+ this.syncFts(nodeId);
1065
+ return normalized.length;
1066
+ },
1067
+
1068
+ /** The files one memory claims something about. */
1069
+ pathsOf(nodeId: string): string[] {
1070
+ return (
1071
+ getDatabase().prepare(`SELECT path FROM graph_node_paths WHERE node_id = ?`).all(nodeId) as {
1072
+ path: string;
1073
+ }[]
1074
+ ).map(row => row.path);
1075
+ },
1076
+
1077
+ /** Paths for many memories at once, for listings and the inspector. */
1078
+ pathsFor(nodeIds: string[]): Map<string, string[]> {
1079
+ const byNode = new Map<string, string[]>();
1080
+ if (nodeIds.length === 0) return byNode;
1081
+ const rows = getDatabase()
1082
+ .prepare(`SELECT node_id, path FROM graph_node_paths WHERE node_id IN ${ID_SET}`)
1083
+ .all(idSet(nodeIds)) as { node_id: string; path: string }[];
1084
+ for (const row of rows) {
1085
+ const paths = byNode.get(row.node_id);
1086
+ if (paths) paths.push(row.path);
1087
+ else byNode.set(row.node_id, [row.path]);
1088
+ }
1089
+ return byNode;
1090
+ },
1091
+
1092
+ /**
1093
+ * Ids of the memories attached to any of these paths — what invalidation ages.
1094
+ *
1095
+ * Deliberately not scoped to a project. A memory judged `anywhere` is attached
1096
+ * to the path where it was learned, and the decay is evidence about the CLAIM
1097
+ * rather than about the repository: if the file that taught it has been
1098
+ * rewritten, that is a reason to trust it slightly less wherever it travels.
1099
+ * The caller passes paths from one project's disk diff, so a collision needs
1100
+ * two repositories to share a repo-relative path AND a memory about it.
1101
+ */
1102
+ memoriesForPaths(paths: string[]): string[] {
1103
+ if (paths.length === 0) return [];
1104
+ const placeholders = paths.map(() => '?').join(',');
1105
+ const rows = getDatabase()
1106
+ .prepare(
1107
+ `SELECT DISTINCT p.node_id AS id FROM graph_node_paths p
1108
+ INNER JOIN graph_nodes n ON n.id = p.node_id
1109
+ WHERE p.path IN (${placeholders})
1110
+ AND n.archived_at IS NULL AND n.superseded_by IS NULL`
1111
+ )
1112
+ .all(...paths) as { id: string }[];
1113
+ return rows.map(row => row.id);
1114
+ },
1115
+
1116
+ /**
1117
+ * Run `fn` inside one SQLite transaction.
1118
+ *
1119
+ * A memory write is a SELECT, an INSERT or UPDATE, an FTS rewrite and its
1120
+ * attribute rows. Outside a transaction each of those is its own durability
1121
+ * barrier, so the batch paths — one turn's extraction, a purge, a merge — are
1122
+ * worth grouping.
1123
+ */
1124
+ transaction<T>(fn: () => T): T {
1125
+ const db = getDatabase();
1126
+ // Not every driver exposes transactions (see `DatabaseConnection`). Running
1127
+ // the block unbatched is the correct degradation: slower, identical result.
1128
+ return db.transaction ? db.transaction(fn)() : fn();
1129
+ },
1130
+
968
1131
  /** Live memories that contradict any of `ids`, in both directions. */
969
1132
  contradictionsFor(ids: string[]): { srcId: string; dstId: string }[] {
970
1133
  if (ids.length === 0) return [];
@@ -1086,43 +1249,6 @@ export const graphQueries = {
1086
1249
  return touched;
1087
1250
  },
1088
1251
 
1089
- /**
1090
- * Memories that claim something about any of these code nodes, in one query.
1091
- *
1092
- * `about` points memory → code, so the memory is always the source. Replaces a
1093
- * per-file `edgesOf` loop that pulled every edge of every changed file — on a
1094
- * turn touching sixty files, most of them `defines` and `imports` edges that
1095
- * invalidation has no interest in.
1096
- */
1097
- memoriesAbout(codeNodeIds: string[]): string[] {
1098
- if (codeNodeIds.length === 0) return [];
1099
- const placeholders = codeNodeIds.map(() => '?').join(',');
1100
- const rows = getDatabase()
1101
- .prepare(
1102
- `SELECT DISTINCT e.src_id AS id FROM graph_edges e
1103
- INNER JOIN graph_nodes n ON n.id = e.src_id
1104
- WHERE e.rel = 'about' AND e.dst_id IN (${placeholders})
1105
- AND n.archived_at IS NULL AND n.superseded_by IS NULL`
1106
- )
1107
- .all(...codeNodeIds) as { id: string }[];
1108
- return rows.map(row => row.id);
1109
- },
1110
-
1111
- /**
1112
- * Run `fn` inside one SQLite transaction.
1113
- *
1114
- * Structural ingestion performs several thousand statements per busy turn
1115
- * (a file upsert is a SELECT, an INSERT/UPDATE and an FTS rewrite, and a file
1116
- * can define 25 symbols). Outside a transaction each one is its own durability
1117
- * barrier, which is the single largest cost on the write path.
1118
- */
1119
- transaction<T>(fn: () => T): T {
1120
- const db = getDatabase();
1121
- // Not every driver exposes transactions (see `DatabaseConnection`). Running
1122
- // the block unbatched is the correct degradation: slower, identical result.
1123
- return db.transaction ? db.transaction(fn)() : fn();
1124
- },
1125
-
1126
1252
  /** Record that retrieval surfaced these nodes, feeding the usage signal. */
1127
1253
  markAccessed(ids: string[]): void {
1128
1254
  if (ids.length === 0) return;
@@ -1166,7 +1292,7 @@ export const graphQueries = {
1166
1292
  return;
1167
1293
  }
1168
1294
 
1169
- const text = indexedText({ ...node, entityNames: this.entityNamesOf(id) });
1295
+ const text = indexedText({ ...node, entityNames: this.entityNamesOf(id), paths: this.pathsOf(id) });
1170
1296
  if (!text) {
1171
1297
  db.prepare(`UPDATE graph_nodes SET fts_rowid = NULL WHERE id = ?`).run(id);
1172
1298
  return;
@@ -1174,7 +1300,7 @@ export const graphQueries = {
1174
1300
 
1175
1301
  const result = db
1176
1302
  .prepare(`INSERT INTO graph_nodes_fts (node_id, project_id, scope, kind, text) VALUES (?, ?, ?, ?, ?)`)
1177
- .run(id, node.projectId ?? '', node.scope, node.kind, text) as { lastInsertRowid?: number | bigint };
1303
+ .run(id, node.projectId ?? '', node.scope, NODE_KIND, text) as { lastInsertRowid?: number | bigint };
1178
1304
  db.prepare(`UPDATE graph_nodes SET fts_rowid = ? WHERE id = ?`).run(
1179
1305
  Number(result.lastInsertRowid ?? 0),
1180
1306
  id
@@ -1362,12 +1488,13 @@ export const graphQueries = {
1362
1488
  }
1363
1489
  }
1364
1490
 
1365
- // Memories about the same subject are neighbours too, without an edge in
1366
- // the table. This is what the entity NODE used to provide as two hops
1367
- // through a stub; it is one hop now, and it is the only structure the
1368
- // episodic half has left since similarity linking was removed.
1491
+ // Memories about the same subject — or about the same file — are
1492
+ // neighbours too, without an edge in the table. The first is what the
1493
+ // entity NODE used to provide as two hops through a stub; the second is
1494
+ // what the FILE node used to provide the same way. Both are one hop now,
1495
+ // and together they are the structure the graph has.
1369
1496
  for (const id of frontier) {
1370
- for (const candidate of this.entityNeighbourIds(id)) {
1497
+ for (const candidate of [...this.entityNeighbourIds(id), ...this.pathNeighbourIds(id)]) {
1371
1498
  if (distance.has(candidate)) continue;
1372
1499
  distance.set(candidate, depth);
1373
1500
  next.push(candidate);
@@ -1519,8 +1646,6 @@ export const graphQueries = {
1519
1646
  return {
1520
1647
  nodes: one(`SELECT COUNT(*) AS c FROM graph_nodes WHERE ${live}`),
1521
1648
  edges: one(`SELECT COUNT(*) AS c FROM graph_edges`),
1522
- episodic: one(`SELECT COUNT(*) AS c FROM graph_nodes WHERE ${live} AND kind = 'episodic'`),
1523
- structural: one(`SELECT COUNT(*) AS c FROM graph_nodes WHERE ${live} AND kind = 'structural'`),
1524
1649
  vectors: one(`SELECT COUNT(*) AS c FROM graph_vectors`),
1525
1650
  byScope,
1526
1651
  byProject,
@@ -1731,72 +1856,6 @@ export const graphQueries = {
1731
1856
  return ids.length;
1732
1857
  },
1733
1858
 
1734
- /**
1735
- * Structural nodes nothing in the graph depends on any more.
1736
- *
1737
- * This is the bound on the term that actually dominates growth. Every turn
1738
- * writes a node per changed file, per directory and up to twenty-five per
1739
- * file's symbols, so on a repository under active development the structural
1740
- * half outgrows the episodic half by an order of magnitude — and episodic
1741
- * retention does not touch it, because none of those queries look at
1742
- * `kind = 'structural'`.
1743
- *
1744
- * What is safe to remove is narrow and stays narrow: a `symbol` or `module`
1745
- * node, untouched for `maxAgeDays`, that NO memory is `about`. A file node is
1746
- * spared even when nothing points at it — it is the anchor a path lookup
1747
- * resolves to, and `invalidate.ts` already retires files the moment the disk
1748
- * says they are gone, which is better evidence than age. Anything a memory
1749
- * hangs off is spared outright: deleting it would sever the `about` edge that
1750
- * is the entire reason both halves live in one graph.
1751
- */
1752
- pruneStructural(options: { maxAgeDays: number; limit: number }): number {
1753
- const db = getDatabase();
1754
- const ids = (
1755
- db
1756
- .prepare(
1757
- `SELECT n.id AS id FROM graph_nodes n
1758
- WHERE n.kind = 'structural'
1759
- AND n.subkind IN ('symbol', 'module')
1760
- AND n.pinned = 0
1761
- AND n.source != 'user'
1762
- AND julianday('now') - julianday(n.updated_at) > ?
1763
- AND NOT EXISTS (
1764
- SELECT 1 FROM graph_edges e WHERE e.rel = 'about' AND e.dst_id = n.id
1765
- )
1766
- ORDER BY n.updated_at ASC
1767
- LIMIT ?`
1768
- )
1769
- .all(options.maxAgeDays, options.limit) as { id: string }[]
1770
- ).map(r => r.id);
1771
-
1772
- if (ids.length === 0) return 0;
1773
- const placeholders = ids.map(() => '?').join(',');
1774
- this.dropFts(ids);
1775
- db.prepare(`DELETE FROM graph_nodes WHERE id IN (${placeholders})`).run(...ids);
1776
- return ids.length;
1777
- },
1778
-
1779
- /**
1780
- * Structural nodes whose file no longer exists on disk, so the graph stops
1781
- * pointing agents at paths that are gone. Symbols of a removed file go with
1782
- * it — a symbol has no meaning without the file that defined it.
1783
- */
1784
- archiveMissingFiles(projectId: string, paths: string[]): number {
1785
- if (paths.length === 0) return 0;
1786
- const placeholders = paths.map(() => '?').join(',');
1787
- const ids = (
1788
- getDatabase()
1789
- .prepare(
1790
- `SELECT id FROM graph_nodes
1791
- WHERE project_id = ? AND kind = 'structural' AND path IN (${placeholders})
1792
- AND archived_at IS NULL`
1793
- )
1794
- .all(projectId, ...paths) as { id: string }[]
1795
- ).map(r => r.id);
1796
-
1797
- return this.archiveNodes(ids);
1798
- },
1799
-
1800
1859
  // ── vectors ─────────────────────────────────────────────────────────────
1801
1860
 
1802
1861
  setVector(nodeId: string, dim: number, model: string, vec: Uint8Array): void {
@@ -1811,22 +1870,7 @@ export const graphQueries = {
1811
1870
  .run(nodeId, dim, model, vec);
1812
1871
  },
1813
1872
 
1814
- /**
1815
- * Nodes that still need a vector for the current model.
1816
- *
1817
- * EPISODIC ONLY, deliberately. A structural node is identified by a name and a
1818
- * path, and embedding that produces a bag of path fragments rather than a
1819
- * meaning — measured, `backend/database/queries/index.ts` scored above a
1820
- * correct answer for two unrelated natural-language questions, because
1821
- * mean-pooled fragments land near the middle of the space where everything
1822
- * looks vaguely similar. Names and paths are precisely what BM25 is best at,
1823
- * so structural nodes lose nothing by staying lexical.
1824
- *
1825
- * Code is still reachable semantically, just not directly: a question finds
1826
- * the memory *about* a file, and graph expansion crosses the `about` edge to
1827
- * the file itself. That is the intended route — and the reason both kinds of
1828
- * memory live in one graph.
1829
- */
1873
+ /** Memories that still need a vector for the current model. */
1830
1874
  nodesMissingVectors(model: string, limit: number = 200): GraphNode[] {
1831
1875
  const rows = getDatabase()
1832
1876
  .prepare(