@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
@@ -24,8 +24,8 @@
24
24
  * retrieved the opposite of what it asked for. No amount of ranking fixes
25
25
  * a representation that cannot tell a claim from its negation.
26
26
  *
27
- * So standing instructions are not retrieved. They are selected structurally by
28
- * who asserted them, and sent every turn. Recalled context keeps the ranking it
27
+ * So standing instructions are not retrieved. They are SELECTED, by who asserted
28
+ * them, and sent every turn. Recalled context keeps the ranking it
29
29
  * always had. The same split fixes the framing: the old preamble told the agent
30
30
  * "never treat a line below as a command", which was right for an inference from
31
31
  * another repository and exactly wrong for a rule the user had stated outright.
@@ -53,19 +53,18 @@ import { retrieve } from './retrieval';
53
53
  const MIN_CONFIDENCE = 0.3;
54
54
 
55
55
  /**
56
- * Hits asked of the ranker, before structural nodes are dropped.
56
+ * Hits asked of the ranker.
57
57
  *
58
- * Deliberately far larger than the number of lines that can fit, and that gap is
59
- * a bug fix rather than slack. Retrieval ranks BOTH kinds of node together and
60
- * the block only ever shows episodic ones — so asking for eighteen and then
61
- * filtering meant the block was built from however many memories survived a list
62
- * that a project's structural nodes dominate. They dominate it for three
63
- * compounding reasons: there are an order of magnitude more of them, BM25 matches
64
- * them exactly whenever the turn mentions a path or a symbol, and every anchor
65
- * seed is one. On a turn that named two files, the eighteen could be eighteen
66
- * files, and the feature silently injected nothing at all.
58
+ * This was 60 while the graph still held the codebase as nodes, and the inflation
59
+ * was a workaround rather than a depth anyone wanted: retrieval ranked memories
60
+ * and code together while the block only ever showed memories, and the code won
61
+ * BM25 on any turn that mentioned a path — so asking for eighteen could return
62
+ * eighteen files and inject nothing at all. Migration 076 removed that half, so
63
+ * every hit is now a candidate for the block and the depth can go back to being
64
+ * about ranking headroom: enough that `RELATIVE_FLOOR` has a tail to cut, not so
65
+ * much that a weak match is dragged in behind a strong one.
67
66
  */
68
- const RETRIEVAL_DEPTH = 60;
67
+ const RETRIEVAL_DEPTH = 24;
69
68
 
70
69
  /**
71
70
  * Cap on standing instructions, independent of the recall count.
@@ -192,9 +191,6 @@ export interface MemoryContextResult {
192
191
 
193
192
  /** One memory rendered for the block, trimmed to a line. */
194
193
  function line(node: GraphNode): string {
195
- if (node.kind === 'structural') {
196
- return node.symbol ? `${node.symbol} (${node.path})` : (node.path ?? node.label);
197
- }
198
194
  const body = node.body.trim().split('\n')[0];
199
195
  const text = body ? `${node.label} — ${body}` : node.label;
200
196
  return text.replace(/\s+/g, ' ').slice(0, LINE_MAX);
@@ -223,11 +219,12 @@ function provenance(node: GraphNode, currentProjectId: string | null, names?: Ma
223
219
  /**
224
220
  * Build the injected block, or null when there is nothing worth injecting.
225
221
  *
226
- * Structural hits are deliberately excluded from the block. The agent can read
227
- * the repository itself, so telling it that a file exists wastes budget; what it
228
- * cannot recover by reading is why a decision was made. Structural nodes still
229
- * do the important work — they are how retrieval *reaches* the relevant
230
- * episodic memories through `about` edges.
222
+ * Every hit is a memory, which is the point the graph was eventually rebuilt
223
+ * around. It used to rank the codebase alongside them and then drop all of it
224
+ * here — the agent can read the repository, so telling it that a file exists
225
+ * wastes budget, while what it cannot recover by reading is why a decision was
226
+ * made. Filtering at the end meant paying for the ranking anyway; migration 076
227
+ * removed the half instead.
231
228
  */
232
229
  export function buildMemoryContext(input: MemoryContextInput): MemoryContextResult | null {
233
230
  const config = getMemoryConfig();
@@ -276,10 +273,7 @@ export function buildMemoryContext(input: MemoryContextInput): MemoryContextResu
276
273
  // Never say the same thing twice in one block. A standing rule that also ranks
277
274
  // for the query is already above, with stronger framing.
278
275
  const recalled = hits.filter(
279
- hit =>
280
- hit.node.kind === 'episodic' &&
281
- hit.node.confidence >= MIN_CONFIDENCE &&
282
- !standingIds.has(hit.node.id)
276
+ hit => hit.node.confidence >= MIN_CONFIDENCE && !standingIds.has(hit.node.id)
283
277
  );
284
278
 
285
279
  // The bar is the best RECALLABLE hit. Setting it from the whole ranking instead
@@ -251,8 +251,6 @@ export interface EpisodicIngestInput {
251
251
  changedPaths: string[];
252
252
  /** Repo-relative paths that no longer exist on disk. */
253
253
  deletedPaths?: string[];
254
- /** Path → structural node id, from structural extraction, for `about` edges. */
255
- fileNodes: Map<string, string>;
256
254
  /** Memories that were injected into this turn, for adjudication. */
257
255
  injectedMemoryIds?: string[];
258
256
  }
@@ -573,7 +571,6 @@ export async function ingestEpisodicMemories(input: EpisodicIngestInput): Promis
573
571
  // recognised as travelling now travels, even though the stored text does
574
572
  // not change.
575
573
  graphQueries.upsert({
576
- kind: 'episodic',
577
574
  subkind: duplicate.subkind,
578
575
  scope: duplicate.scope,
579
576
  projectId: duplicate.projectId,
@@ -591,11 +588,14 @@ export async function ingestEpisodicMemories(input: EpisodicIngestInput): Promis
591
588
  // is the one being reinforced.
592
589
  recordContradictions(duplicate.id, opposites, new Set([...candidateIds, ...writtenThisTurn.map(e => e.node.id)]));
593
590
  linkEntities(duplicate.id, memory.entities ?? []);
591
+ // The paths too: a rephrasing usually names the files better than the
592
+ // original did, and this is the same "a later reading is a better one"
593
+ // rule `setPaths` is built on.
594
+ if (memory.relatedPaths?.length) graphQueries.setPaths(duplicate.id, memory.relatedPaths);
594
595
  continue;
595
596
  }
596
597
 
597
598
  const node = graphQueries.upsert({
598
- kind: 'episodic',
599
599
  subkind: memory.subkind,
600
600
  scope,
601
601
  projectId,
@@ -619,14 +619,12 @@ export async function ingestEpisodicMemories(input: EpisodicIngestInput): Promis
619
619
  // ── entities ────────────────────────────────────────────────────────
620
620
  linkEntities(node.id, memory.entities ?? []);
621
621
 
622
- // `about` edges are what make the two halves one graph: from here a question
623
- // about the code reaches this memory, and this memory names the code.
624
- for (const rawPath of memory.relatedPaths ?? []) {
625
- const path = rawPath.replace(/\\/g, '/').replace(/^\.\//, '');
626
- const targetId = input.fileNodes.get(path) ?? graphQueries.getByPath(input.projectId, path)?.id;
627
- if (!targetId) continue;
628
- graphQueries.link({ srcId: node.id, dstId: targetId, rel: 'about', source: 'agent' });
629
- }
622
+ // ── the code this is about ──────────────────────────────────────────
623
+ // Stored on the memory rather than as an edge to a node standing in for the
624
+ // file. It is what invalidation ages this memory against, what an anchored
625
+ // query seeds from, and — through `indexedText` — what makes a pasted path
626
+ // find what is known about it.
627
+ graphQueries.setPaths(node.id, memory.relatedPaths ?? []);
630
628
  }
631
629
 
632
630
  if (written > 0) {
@@ -1,12 +1,16 @@
1
1
  /**
2
2
  * Turn ingestion — the Memory Graph's write path.
3
3
  *
4
- * Called once per turn, after the snapshot has been captured. Structural
5
- * extraction runs first and returns its path → node map, which episodic
6
- * extraction then uses to attach `about` edges: the memory has to be able to
7
- * name the code it concerns, and the code node must therefore already exist.
8
- * Between the two, structural invalidation ages the memories whose code just
9
- * changed underneath them.
4
+ * Called once per turn, after the snapshot has been captured. Two things happen,
5
+ * in this order: the memories standing on code that just changed are aged, and
6
+ * the turn is queued to be summarised into new ones. Ageing goes first so a
7
+ * memory written by THIS turn is not immediately decayed by the same turn's
8
+ * changes — it was written in full knowledge of them.
9
+ *
10
+ * This used to begin by parsing every changed file into nodes for the graph.
11
+ * Migration 076 removed that half: the agent can read the repository, and those
12
+ * nodes never reached a prompt. What a memory is about is now a list of paths on
13
+ * the memory itself, recorded by episodic extraction.
10
14
  *
11
15
  * Writes are automatic rather than left to the agent's initiative. A graph that
12
16
  * only fills when a model remembers to call a `remember` tool stays empty — the
@@ -18,13 +22,9 @@
18
22
  import { debug } from '$shared/utils/logger';
19
23
  import { getMemoryConfig } from '../config';
20
24
  import { takeInjectedMemories } from '../context';
21
- import { scheduleVectorIndexing } from '../indexer';
22
25
  import { invalidateForChanges } from '../invalidate';
23
- import { notifyGraphChanged } from '../notify';
24
26
  import { scheduleEpisodicIngest } from './scheduler';
25
- import { ingestStructuralChanges } from './structural';
26
27
 
27
- export { ingestStructuralChanges } from './structural';
28
28
  export { ingestEpisodicMemories } from './episodic';
29
29
  export {
30
30
  deferEpisodicIngest,
@@ -52,60 +52,32 @@ export interface TurnIngestInput {
52
52
  * the extraction prompt described a hundred files as "changed this turn".
53
53
  */
54
54
  changedPaths: string[];
55
- /** Paths that no longer exist on disk, so their nodes can be retired. */
55
+ /** Paths that no longer exist on disk. */
56
56
  deletedPaths?: string[];
57
57
  }
58
58
 
59
59
  /**
60
- * Ingest one completed turn: structural nodes now, episodic summary later.
60
+ * Ingest one completed turn: age what the change contradicts, queue the summary.
61
61
  *
62
62
  * Fire-and-forget from the caller's perspective and guaranteed not to throw —
63
63
  * the turn is already over, so nothing here may surface as a user-visible
64
64
  * failure.
65
65
  */
66
- export async function ingestTurn(input: TurnIngestInput): Promise<void> {
66
+ export function ingestTurn(input: TurnIngestInput): void {
67
67
  const config = getMemoryConfig();
68
68
  if (!config.enabled) return;
69
69
 
70
- // The structural half is allowed to fail on its own.
70
+ // The code just moved. Memories that described how it worked are now standing
71
+ // on something that changed, and the ones that explain WHY it changed are not
72
+ // — see `invalidate.ts` for why one rate would be worse than doing nothing.
71
73
  //
72
- // It reads the disk, and reading the disk can go wrong in ways the episodic
73
- // half has no stake in — a file that vanished mid-turn, a permission error, a
74
- // snapshot that never completed. Sharing one `try` meant any of those cost the
75
- // TRANSCRIPT too, and the transcript is the irreplaceable half: the code can
76
- // be re-read on the next turn, while the conversation that explained why it
77
- // changed exists once.
78
- let fileNodes = new Map<string, string>();
79
- if (config.recordCode) {
80
- try {
81
- const structural = await ingestStructuralChanges({
82
- projectId: input.projectId,
83
- projectPath: input.projectPath,
84
- sessionId: input.sessionId,
85
- changedPaths: input.changedPaths
86
- });
87
- fileNodes = structural.fileNodes;
88
-
89
- // Structural nodes are searchable immediately; ask for their vectors now
90
- // rather than waiting for episodic extraction to finish talking to a model.
91
- if (structural.files > 0) {
92
- scheduleVectorIndexing();
93
- notifyGraphChanged('code', input.projectId);
94
- }
95
-
96
- // The code just moved. Memories that described how it worked are now
97
- // standing on something that changed, and the ones that explain WHY it
98
- // changed are not — see `invalidate.ts` for why one rate would be worse
99
- // than doing nothing.
100
- invalidateForChanges({
101
- projectId: input.projectId,
102
- changedPaths: input.changedPaths,
103
- deletedPaths: input.deletedPaths
104
- });
105
- } catch (error) {
106
- debug.warn('memory', 'Structural ingestion failed (non-fatal)', error);
107
- }
108
- }
74
+ // Runs whether or not new memories are being recorded: ageing what is already
75
+ // stored is not the same job as writing more of it, and a user who turned
76
+ // recording off still wants what they have to stay honest.
77
+ invalidateForChanges({
78
+ changedPaths: input.changedPaths,
79
+ deletedPaths: input.deletedPaths
80
+ });
109
81
 
110
82
  if (!config.recordMemories) return;
111
83
 
@@ -121,7 +93,6 @@ export async function ingestTurn(input: TurnIngestInput): Promise<void> {
121
93
  userMessageId: input.userMessageId,
122
94
  changedPaths: input.changedPaths,
123
95
  deletedPaths: input.deletedPaths,
124
- fileNodes,
125
96
  // Consumed here rather than read: the memories injected into this turn are
126
97
  // adjudicated exactly once, by the extraction that reads the turn they
127
98
  // were given to.
@@ -46,8 +46,9 @@
46
46
  * delete is conditional on it, so the merged-in turn is never thrown away with
47
47
  * the one that succeeded.
48
48
  *
49
- * Structural extraction is NOT queued — it reads the disk diff, touches no model,
50
- * costs microseconds, and its nodes should be searchable at once.
49
+ * Invalidation is NOT queued — it reads the disk diff, touches no model, costs
50
+ * one indexed lookup, and a memory standing on code that just moved should say so
51
+ * before the next turn rather than after the next extraction.
51
52
  */
52
53
 
53
54
  import { memoryQueueQueries, type QueuedExtraction } from '$backend/database/queries/memory-queue-queries';
@@ -334,10 +335,6 @@ async function runOne(entry: QueuedExtraction): Promise<void> {
334
335
  userMessageId: entry.userMessageId,
335
336
  changedPaths: entry.changedPaths,
336
337
  deletedPaths: entry.deletedPaths,
337
- // Rebuilt from the graph rather than carried through the queue: a Map of
338
- // path → node id does not serialise usefully, and `getByPath` finds the
339
- // same nodes. The only cost is a lookup per path.
340
- fileNodes: new Map<string, string>(),
341
338
  injectedMemoryIds: entry.injectedMemoryIds
342
339
  });
343
340
 
@@ -1,16 +1,17 @@
1
1
  /**
2
2
  * Memory Graph — public surface.
3
3
  *
4
- * One graph holds institutional/episodic memory and structural memory of the
5
- * codebase together (migration 066), so an agent can ask "what did we decide
6
- * about X" and "what is connected to Y" of the same store, whichever engine is
7
- * driving the session.
4
+ * One store of what past work established — decisions, patterns, failures,
5
+ * preferences — shared by every engine, so an agent can ask "what did we decide
6
+ * about X" whatever is driving the session. Each memory carries the files it
7
+ * claims something about, which is what ages it when they change and what an
8
+ * anchored query seeds from (migrations 066 and 076).
8
9
  *
9
10
  * Layout:
10
11
  * embedding/ local static-embedding model, installed on demand
11
12
  * retrieval.ts BM25 + vector + graph expansion, fused with RRF
12
13
  * indexer.ts backfills vectors behind writes
13
- * extract/ turns work into memory (structural from disk diffs, episodic per turn)
14
+ * extract/ turns each finished turn into memories
14
15
  * compose.ts the hand-written path: free text in, reviewed memory out
15
16
  * context.ts token-budgeted injection at turn start
16
17
  * time.ts reads SQLite timestamps as the UTC they actually are
@@ -2,13 +2,17 @@
2
2
  * Structural invalidation — letting the code tell memory when it has gone out of
3
3
  * date.
4
4
  *
5
- * This is the thing the single-store design was for, and until now it was the
6
- * one part of the argument that was not cashed in. Episodic and structural
7
- * memory live in one graph joined by `about` edges, which means the write path
8
- * already knows, for every file that changed on disk this turn, exactly which
9
- * memories claimed something about it. Nothing else in this space can do that:
10
- * a conversation-memory product has no view of the codebase, and a code-graph
11
- * product keeps its conversation facts somewhere else.
5
+ * Every memory records the files it claims something about (`graph_node_paths`,
6
+ * migration 076), and the write path already knows which files changed on disk
7
+ * this turn. Intersecting the two is the whole mechanism: a memory standing on
8
+ * code that just moved is a memory to trust slightly less, and nothing else in
9
+ * this space can make that connection — a conversation-memory product has no
10
+ * view of the codebase, and a code-graph product keeps its conversation facts
11
+ * somewhere else.
12
+ *
13
+ * This used to walk from a path to a file NODE to the `about` edges hanging off
14
+ * it. The node in between was 81% of the graph and did nothing else worth
15
+ * keeping, so the lookup is now a single index seek on the path itself.
12
16
  *
13
17
  * The decay is per subkind, and that distinction is the whole design:
14
18
  *
@@ -43,11 +47,11 @@
43
47
  * effect, everything the graph knew about whatever was being worked on.
44
48
  */
45
49
 
46
- import { graphQueries } from '$backend/database/queries/graph-queries';
50
+ import { graphQueries, normalizePath } from '$backend/database/queries/graph-queries';
47
51
  import { debug } from '$shared/utils/logger';
48
52
 
49
53
  /**
50
- * Confidence multiplier per subkind when the code a memory is `about` changes.
54
+ * Confidence multiplier per subkind when the code a memory is about changes.
51
55
  * A subkind absent from this map, or mapped to 1, is never decayed.
52
56
  */
53
57
  const DECAY_BY_SUBKIND: Record<string, number> = {
@@ -63,68 +67,52 @@ const DECAY_BY_SUBKIND: Record<string, number> = {
63
67
  const MAX_FILES = 60;
64
68
 
65
69
  export interface InvalidationInput {
66
- projectId: string;
67
70
  /** Repo-relative paths that changed on disk this turn. */
68
71
  changedPaths: string[];
69
- /** Paths that no longer exist — the file was deleted or renamed away. */
72
+ /**
73
+ * Paths that no longer exist — the file was deleted or renamed away.
74
+ *
75
+ * Treated as changed rather than as a category of its own. Deletion is the
76
+ * strongest form of "the code moved underneath this", and the per-subkind
77
+ * rates already say the right thing about it: an observation describing a file
78
+ * that is gone should fall, while the decision that removed it should not.
79
+ *
80
+ * The attribution itself is left alone. A memory about a file that no longer
81
+ * exists is still a memory about that file, and severing the link would lose
82
+ * the only record of what a since-deleted module taught.
83
+ */
70
84
  deletedPaths?: string[];
71
85
  }
72
86
 
73
87
  export interface InvalidationResult {
74
88
  /** Memories whose confidence was reduced. */
75
89
  decayed: number;
76
- /** Structural nodes retired because their file is gone. */
77
- archived: number;
78
90
  }
79
91
 
80
92
  /**
81
93
  * Age the memories attached to code that just changed.
82
94
  *
83
- * Runs on the write path immediately after structural extraction, so the file
84
- * nodes it looks up are the ones that pass has just upserted. Deliberately
85
- * OUTSIDE that pass's transaction: structural ingest holds a write transaction
86
- * across several thousand statements, and extending it over an unrelated read
87
- * would widen the window in which nothing else can write for no benefit —
88
- * decaying a memory is idempotent within the cool-off window, so it does not
89
- * need to roll back with the ingest.
90
- *
91
95
  * Never throws: a memory left slightly over-confident is a far smaller problem
92
96
  * than a failed turn-completion hook.
93
97
  */
94
98
  export function invalidateForChanges(input: InvalidationInput): InvalidationResult {
95
- const result: InvalidationResult = { decayed: 0, archived: 0 };
99
+ const result: InvalidationResult = { decayed: 0 };
96
100
 
97
101
  try {
98
- // A deleted file's structural nodes are retired outright. Keeping them would
99
- // mean BM25 continues to offer paths that no longer exist, which sends an
100
- // agent to read a file that is gone — a specific, repeatable waste of a turn.
101
- const deleted = [...new Set(input.deletedPaths ?? [])].slice(0, MAX_FILES);
102
- if (deleted.length > 0) {
103
- result.archived = graphQueries.archiveMissingFiles(input.projectId, deleted);
104
- }
105
-
106
- const changed = input.changedPaths.slice(0, MAX_FILES);
107
- if (changed.length === 0) return result;
108
-
109
- const fileNodes = graphQueries.getByPaths(input.projectId, changed);
110
- if (fileNodes.length === 0) return result;
111
-
112
- // Only ONE hop, and only `about` edges. Two hops would reach the memories
113
- // attached to every file this one imports, and editing a file is not
114
- // evidence about its dependencies. Resolved in one query rather than by
115
- // walking every edge of every changed file — on a sixty-file turn most of
116
- // those edges are `defines` and `imports`, which invalidation has no
117
- // interest in and would still have to load.
118
- const affected = graphQueries.memoriesAbout(fileNodes.map(node => node.id));
102
+ const paths = [
103
+ ...new Set([...input.changedPaths, ...(input.deletedPaths ?? [])].map(normalizePath))
104
+ ]
105
+ .filter(Boolean)
106
+ .slice(0, MAX_FILES);
107
+ if (paths.length === 0) return result;
119
108
 
109
+ const affected = graphQueries.memoriesForPaths(paths);
120
110
  if (affected.length === 0) return result;
111
+
121
112
  result.decayed = graphQueries.markStale(affected, DECAY_BY_SUBKIND);
122
113
 
123
- if (result.decayed > 0 || result.archived > 0) {
124
- debug.log(
125
- 'memory',
126
- `Structural invalidation: ${result.decayed} memory/memories aged, ${result.archived} node(s) retired`
127
- );
114
+ if (result.decayed > 0) {
115
+ debug.log('memory', `Structural invalidation: ${result.decayed} memory/memories aged`);
128
116
  }
129
117
  } catch (error) {
130
118
  debug.warn('memory', 'Structural invalidation failed (non-fatal)', error);