@myrialabs/clopen 0.4.26 → 0.4.27

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (93) hide show
  1. package/backend/auth/permissions.ts +21 -0
  2. package/backend/bootstrap.ts +18 -1
  3. package/backend/chat/engine-handoff.test.ts +229 -0
  4. package/backend/chat/engine-handoff.ts +439 -0
  5. package/backend/chat/stream-manager.ts +200 -16
  6. package/backend/database/migrations/066_create_memory_graph.ts +369 -0
  7. package/backend/database/migrations/index.ts +7 -0
  8. package/backend/database/queries/audit-log-queries.test.ts +10 -1
  9. package/backend/database/queries/graph-queries.ts +1764 -0
  10. package/backend/database/queries/index.ts +2 -0
  11. package/backend/database/queries/memory-queue-queries.ts +381 -0
  12. package/backend/database/queries/snapshot-queries.ts +20 -0
  13. package/backend/engine/README.md +45 -2
  14. package/backend/engine/adapters/copilot/stream.ts +37 -1
  15. package/backend/engine/adapters/pi/models.ts +19 -7
  16. package/backend/engine/adapters/pi/stream.ts +2 -1
  17. package/backend/engine/docs/adapter-contract.md +25 -8
  18. package/backend/engine/docs/adding-an-engine.md +40 -4
  19. package/backend/engine/docs/frontend-and-chat.md +66 -1
  20. package/backend/engine/docs/lessons-learned.md +165 -6
  21. package/backend/engine/docs/quick-reference.md +10 -0
  22. package/backend/engine/docs/stack.md +10 -0
  23. package/backend/engine/docs/websocket-routes.md +15 -1
  24. package/backend/engine/engine-setup.ts +1 -1
  25. package/backend/engine/index.test.ts +186 -0
  26. package/backend/engine/index.ts +117 -71
  27. package/backend/engine/install-recipes.test.ts +105 -0
  28. package/backend/engine/install-recipes.ts +4 -1
  29. package/backend/index.ts +9 -0
  30. package/backend/mcp/internal/config.ts +6 -0
  31. package/backend/mcp/internal/servers/index.ts +2 -0
  32. package/backend/mcp/internal/servers/memory-graph/description.ts +33 -0
  33. package/backend/mcp/internal/servers/memory-graph/format.ts +45 -0
  34. package/backend/mcp/internal/servers/memory-graph/index.ts +52 -0
  35. package/backend/mcp/internal/servers/memory-graph/runner.ts +342 -0
  36. package/backend/mcp/internal/servers/memory-graph/schema.ts +140 -0
  37. package/backend/memory/README.md +432 -0
  38. package/backend/memory/bootstrap.ts +101 -0
  39. package/backend/memory/compose.test.ts +198 -0
  40. package/backend/memory/compose.ts +343 -0
  41. package/backend/memory/config.ts +100 -0
  42. package/backend/memory/consolidate.ts +280 -0
  43. package/backend/memory/context.test.ts +321 -0
  44. package/backend/memory/context.ts +451 -0
  45. package/backend/memory/embedding/embedder.test.ts +141 -0
  46. package/backend/memory/embedding/embedder.ts +269 -0
  47. package/backend/memory/embedding/index.ts +17 -0
  48. package/backend/memory/embedding/install.ts +254 -0
  49. package/backend/memory/embedding/paths.ts +101 -0
  50. package/backend/memory/embedding/vector-cache.ts +270 -0
  51. package/backend/memory/extract/episodic.ts +725 -0
  52. package/backend/memory/extract/index.ts +133 -0
  53. package/backend/memory/extract/languages.ts +176 -0
  54. package/backend/memory/extract/scheduler.test.ts +352 -0
  55. package/backend/memory/extract/scheduler.ts +406 -0
  56. package/backend/memory/extract/structural.test.ts +215 -0
  57. package/backend/memory/extract/structural.ts +364 -0
  58. package/backend/memory/index.ts +37 -0
  59. package/backend/memory/indexer.ts +150 -0
  60. package/backend/memory/invalidate.ts +134 -0
  61. package/backend/memory/judge.ts +285 -0
  62. package/backend/memory/maintenance.ts +132 -0
  63. package/backend/memory/model.ts +91 -0
  64. package/backend/memory/notify.ts +102 -0
  65. package/backend/memory/readiness.ts +74 -0
  66. package/backend/memory/redact.test.ts +101 -0
  67. package/backend/memory/redact.ts +133 -0
  68. package/backend/memory/retention.ts +139 -0
  69. package/backend/memory/retrieval.eval.test.ts +301 -0
  70. package/backend/memory/retrieval.test.ts +1023 -0
  71. package/backend/memory/retrieval.ts +707 -0
  72. package/backend/memory/revise.test.ts +693 -0
  73. package/backend/memory/revise.ts +400 -0
  74. package/backend/memory/time.ts +31 -0
  75. package/backend/memory/view.ts +164 -0
  76. package/backend/shipped-runtime-imports.test.ts +228 -0
  77. package/backend/ws/index.ts +5 -1
  78. package/backend/ws/memory/crud.ts +631 -0
  79. package/backend/ws/memory/index.ts +41 -0
  80. package/backend/ws/sessions/crud.ts +10 -0
  81. package/backend/ws/snapshot/restore.ts +38 -4
  82. package/dist/assets/graph-layout.worker-CRFqN7ZQ.js +1 -0
  83. package/dist/assets/{index-B6QGUN03.js → index-BCv5HlPk.js} +1 -1
  84. package/dist/assets/{index-DYa-GDsb.js → index-BTGcf_Vy.js} +1 -1
  85. package/dist/assets/main-BrqMMMRX.css +1 -0
  86. package/dist/assets/{main-Dznkfxsd.js → main-CgmAFpU3.js} +835 -426
  87. package/dist/index.html +2 -2
  88. package/package.json +8 -2
  89. package/shared/types/database/connection.ts +9 -0
  90. package/shared/types/memory.ts +519 -0
  91. package/shared/utils/logger.ts +1 -0
  92. package/dist/assets/main-Dh-MTGNR.css +0 -1
  93. package/shared/utils/anonymous-user.ts +0 -168
@@ -33,13 +33,17 @@ import type {
33
33
  } from '$shared/types/unified';
34
34
  import type { EngineType } from '$shared/types/unified';
35
35
  import type { DatabaseMessage } from '$shared/types/database/schema';
36
- import { getProjectEngine, initializeProjectEngine } from '../engine';
37
- import { messageQueries, sessionQueries } from '../database/queries';
36
+ import { findProjectEngine, initializeProjectEngine } from '../engine';
37
+ import { messageQueries, projectQueries, sessionQueries } from '../database/queries';
38
38
  import { snapshotService } from '../snapshot/snapshot-service';
39
+ import { snapshotQueries } from '../database/queries/snapshot-queries';
39
40
  import { projectContextService, refreshExpiringExternalOAuth } from '../mcp';
40
41
  import { resolveActiveProfileId } from '../profiles';
41
42
  import { browserMcpControl } from '../preview';
42
43
  import { extractMessageText } from '../snapshot/helpers';
44
+ import { deferEpisodicIngest, ingestTurn } from '../memory/extract';
45
+ import { buildMemoryContext, withMemoryContext } from '../memory/context';
46
+ import { buildEngineHandoff, resolveBranchEngine, withHandoff } from './engine-handoff';
43
47
  import { debug } from '$shared/utils/logger';
44
48
  import { DEFAULT_MODEL_ID, DEFAULT_MODEL_NAME } from '$shared/constants/engines';
45
49
 
@@ -136,6 +140,66 @@ interface RequestEngineContext {
136
140
  * model name). The adapter supplies type/provider/model.id; stream-manager
137
141
  * is the single source of truth for the rest.
138
142
  */
143
+ /** One file's hash pair inside a snapshot's `session_changes` map. */
144
+ interface SnapshotChange {
145
+ oldHash?: string;
146
+ newHash?: string;
147
+ }
148
+
149
+ /**
150
+ * Parsed `session_changes`, which is stored as a JSON string. Returns an empty
151
+ * map when the column is absent or unparseable — a snapshot with no recorded
152
+ * changes simply gives the Memory Graph nothing to ingest.
153
+ */
154
+ function parseSessionChanges(raw: string | null | undefined): Record<string, SnapshotChange> {
155
+ if (!raw) return {};
156
+ try {
157
+ const parsed = JSON.parse(raw) as Record<string, SnapshotChange>;
158
+ return parsed && typeof parsed === 'object' ? parsed : {};
159
+ } catch {
160
+ return {};
161
+ }
162
+ }
163
+
164
+ /**
165
+ * What actually changed on disk during THIS turn.
166
+ *
167
+ * `session_changes` is cumulative: it records every file that differs from the
168
+ * SESSION's baseline, so it only ever grows as a session runs. Handing it to the
169
+ * Memory Graph as "files changed this turn" was wrong in three ways at once — the
170
+ * extraction prompt described a hundred files as belonging to one turn, the
171
+ * sixty-file cap re-ingested whatever sorted first while genuinely new files fell
172
+ * off the end, and every file in the session was re-upserted every turn, which
173
+ * flattened the reinforcement signal it was supposed to produce.
174
+ *
175
+ * Differencing against the parent snapshot recovers the real delta: a path is in
176
+ * it when its content hash differs from what the previous checkpoint recorded.
177
+ */
178
+ function diffSnapshotAgainstParent(snapshot: {
179
+ session_changes?: unknown;
180
+ parent_snapshot_id?: string | null;
181
+ }): { changed: string[]; deleted: string[] } {
182
+ const current = parseSessionChanges(snapshot?.session_changes as string | null | undefined);
183
+ const parentId = snapshot?.parent_snapshot_id ?? null;
184
+ const parent = parentId
185
+ ? parseSessionChanges(snapshotQueries.getById(parentId)?.session_changes as string | null | undefined)
186
+ : {};
187
+
188
+ const changed: string[] = [];
189
+ const deleted: string[] = [];
190
+
191
+ for (const [path, entry] of Object.entries(current)) {
192
+ const before = parent[path];
193
+ // Unchanged since the previous checkpoint — it belongs to an earlier turn.
194
+ if (before && before.newHash === entry.newHash) continue;
195
+ // An empty `newHash` is how the snapshot service records a deletion.
196
+ if (!entry.newHash) deleted.push(path);
197
+ else changed.push(path);
198
+ }
199
+
200
+ return { changed, deleted };
201
+ }
202
+
139
203
  function enrichMessageEngine(
140
204
  message: UnifiedMessage,
141
205
  ctx: RequestEngineContext,
@@ -492,14 +556,26 @@ class StreamManager extends EventEmitter {
492
556
  if (!projectPath) throw new Error('Project path is required. Please select a valid project directory.');
493
557
  if (!projectPathExists) throw new Error(`Project path does not exist: ${projectPath}. Please select a valid project directory.`);
494
558
 
559
+ // Which engine produced the trailing part of this branch. When it differs
560
+ // from the engine the user just picked, the branch's SDK session id
561
+ // belongs to a foreign store and MUST NOT be used as a resume target —
562
+ // the conversation is carried over as prompt content instead (see
563
+ // buildEngineHandoff below). Null means a fresh branch: nothing to hand
564
+ // over, nothing to resume.
565
+ const branchEngine = chatSessionId ? resolveBranchEngine(chatSessionId) : null;
566
+ const engineSwitched = branchEngine !== null && branchEngine !== requestEngine.type;
567
+
495
568
  // Get resume session ID (branch-aware).
496
569
  // Primary: use parentSessionId carried by the UserMessage — set by the
497
570
  // frontend from the last assistant/reasoning sessionId in the current branch.
498
571
  // Fallback: walk the HEAD chain in the DB (handles messages sent from
499
572
  // older clients or tool-result user messages that lack parentSessionId).
500
573
  let resumeSessionId: string | undefined = undefined;
501
- if (chatSessionId) {
502
- // Primary source: parent.sessionId on the raw prompt
574
+ if (chatSessionId && !engineSwitched) {
575
+ // Primary source: parent.sessionId on the raw prompt.
576
+ // Note this is client-supplied and engine-blind, which is why the
577
+ // engineSwitched guard above is authoritative — an older client will
578
+ // happily send the previous engine's id.
503
579
  const promptParentSessionId = rawPrompt?.parent?.sessionId;
504
580
  if (promptParentSessionId && promptParentSessionId !== chatSessionId) {
505
581
  resumeSessionId = promptParentSessionId;
@@ -579,6 +655,11 @@ class StreamManager extends EventEmitter {
579
655
  return;
580
656
  }
581
657
 
658
+ // Push back any memory summary parked for this session. Extraction talks to
659
+ // the same engine this stream is about to use, and on a shared-process
660
+ // engine that request would queue against the user's reply.
661
+ if (chatSessionId) deferEpisodicIngest(chatSessionId);
662
+
582
663
  const engine = await initializeProjectEngine(projectId, requestEngine.type);
583
664
 
584
665
  if ((streamState.status as string) === 'cancelled' || streamState.abortController?.signal.aborted) {
@@ -586,9 +667,81 @@ class StreamManager extends EventEmitter {
586
667
  return;
587
668
  }
588
669
 
589
- // Detect orphaned user messages and prepend context (claude-code only)
670
+ // ── Cross-engine handoff ──
671
+ // The user switched engine mid-conversation, so the new engine has no
672
+ // native session to resume. Replay the branch as prompt content. This
673
+ // is prepended to the ENGINE prompt only — `userMessage` (already saved
674
+ // above) stays clean, so the transcript never reaches the timeline.
590
675
  let enginePrompt = userMessage;
591
- if (requestEngine.type === 'claude-code' && chatSessionId) {
676
+ if (engineSwitched && chatSessionId) {
677
+ try {
678
+ const handoff = buildEngineHandoff(
679
+ chatSessionId,
680
+ requestEngine.type,
681
+ requestEngine.model.id || '',
682
+ branchEngine,
683
+ userMessageId
684
+ );
685
+ if (handoff) {
686
+ enginePrompt = withHandoff(userMessage, handoff.blocks);
687
+ const { turns, clearedToolResults, droppedAttachments, estimatedTokens } = handoff.stats;
688
+ debug.log(
689
+ 'chat',
690
+ `Engine handoff ${branchEngine} → ${requestEngine.type}: ${turns} turn(s), ~${estimatedTokens} tokens` +
691
+ (clearedToolResults ? `, ${clearedToolResults} tool result(s) cleared` : '') +
692
+ (droppedAttachments ? `, ${droppedAttachments} attachment(s) omitted (unsupported by target)` : '')
693
+ );
694
+ }
695
+ } catch (error) {
696
+ // A failed handoff must not block the turn — the engine simply
697
+ // starts without carried context.
698
+ debug.error('chat', 'Engine handoff failed, continuing without carried context:', error);
699
+ }
700
+ }
701
+
702
+ // ── Memory Graph injection ──
703
+ // Relevant memories from earlier sessions, retrieved from the user's own
704
+ // words. Done here rather than per adapter so every engine behaves the
705
+ // same, and prepended to the ENGINE prompt only — like the handoff above,
706
+ // `userMessage` stays clean so this never reaches the timeline.
707
+ try {
708
+ // The files this session has been working in are seeds too. A turn whose
709
+ // text carries no retrievable signal — "continue", "fix it" — still has a
710
+ // working set, and that is often the only thing pointing at the memory
711
+ // that matters.
712
+ const anchorPaths = chatSessionId
713
+ ? Object.keys(
714
+ parseSessionChanges(
715
+ snapshotQueries.getLatestBySessionId(chatSessionId)?.session_changes as string | undefined
716
+ )
717
+ ).slice(-40)
718
+ : [];
719
+
720
+ const memory = buildMemoryContext({
721
+ query: extractMessageText(userMessage),
722
+ projectId: projectId ?? null,
723
+ sessionId: chatSessionId ?? null,
724
+ anchorPaths,
725
+ // So a memory learned in another repository can say which one. Without
726
+ // the name, a travelling insight reads as a claim about the project in
727
+ // front of the agent — which is worse than not surfacing it at all.
728
+ projectNames: new Map(projectQueries.getAll().map(project => [project.id, project.name]))
729
+ });
730
+ if (memory) {
731
+ enginePrompt = withMemoryContext(enginePrompt, memory.text);
732
+ debug.log(
733
+ 'memory',
734
+ `Injected ${memory.text.length} chars of memory context (${memory.nodeIds.length} memories):\n${memory.text}`
735
+ );
736
+ }
737
+ } catch (error) {
738
+ debug.warn('memory', 'Memory injection failed, continuing without it:', error);
739
+ }
740
+
741
+ // Detect orphaned user messages and prepend context (claude-code only).
742
+ // Same idea as the handoff above but for the in-engine case: messages the
743
+ // engine's own session never saw because an earlier turn was cancelled.
744
+ if (!engineSwitched && requestEngine.type === 'claude-code' && chatSessionId) {
592
745
  try {
593
746
  const head = sessionQueries.getHead(chatSessionId);
594
747
  if (head) {
@@ -1142,13 +1295,43 @@ class StreamManager extends EventEmitter {
1142
1295
  }
1143
1296
  } finally {
1144
1297
  const { projectPath, projectId, chatSessionId } = requestData;
1145
- if (projectPath && projectId && chatSessionId && userMessageId) {
1146
- snapshotService.captureSnapshot(projectPath, projectId, chatSessionId, userMessageId)
1147
- .then(() => {
1148
- debug.log('chat', `Stream-end snapshot captured for message: ${userMessageId}`);
1298
+ // Captured into a const: `userMessageId` is reassigned during the stream,
1299
+ // so its narrowing does not survive into the async callback below.
1300
+ const snapshotMessageId = userMessageId;
1301
+ if (projectPath && projectId && chatSessionId && snapshotMessageId) {
1302
+ // The Memory Graph is fed from the SNAPSHOT rather than from tool calls.
1303
+ // The snapshot is a gitignore-aware disk diff, so it also catches files
1304
+ // rewritten through Bash, a codemod or a formatter — none of which appear
1305
+ // as an Edit/Write tool call. Passing the snapshot straight in leaves the
1306
+ // `snapshot:captured` broadcast payload (a WS schema) untouched.
1307
+ //
1308
+ // Ingestion is attached with `finally`, NOT with `then`, and that is the
1309
+ // difference between losing a conversation and losing a file list. A
1310
+ // snapshot can fail for reasons the transcript has no stake in — a
1311
+ // permission error, a path that vanished mid-turn, a repository that grew
1312
+ // past a limit — and hanging the only write path in the feature off its
1313
+ // success meant one of those quietly cost the turn's memories entirely.
1314
+ // The code can be re-read next turn; the conversation happened once.
1315
+ snapshotService.captureSnapshot(projectPath, projectId, chatSessionId, snapshotMessageId)
1316
+ .then(snapshot => {
1317
+ debug.log('chat', `Stream-end snapshot captured for message: ${snapshotMessageId}`);
1149
1318
  this.emit('snapshot:captured', { projectId, chatSessionId });
1319
+ return snapshot ? diffSnapshotAgainstParent(snapshot) : null;
1150
1320
  })
1151
- .catch(err => debug.error('chat', 'Failed to capture stream-end snapshot:', err));
1321
+ .catch(err => {
1322
+ debug.error('chat', 'Failed to capture stream-end snapshot:', err);
1323
+ return null;
1324
+ })
1325
+ .then(delta => {
1326
+ void ingestTurn({
1327
+ projectId,
1328
+ projectPath,
1329
+ sessionId: chatSessionId,
1330
+ userMessageId: snapshotMessageId,
1331
+ changedPaths: delta?.changed ?? [],
1332
+ deletedPaths: delta?.deleted ?? []
1333
+ });
1334
+ });
1152
1335
  }
1153
1336
  }
1154
1337
  }
@@ -1208,11 +1391,12 @@ class StreamManager extends EventEmitter {
1208
1391
  return false;
1209
1392
  }
1210
1393
 
1211
- // Get the engine for this project
1394
+ // The stream is live, so its engine already exists. Look it up rather than
1395
+ // creating one — a fresh instance holds no pending question to answer.
1212
1396
  const pid = streamState.projectId || 'default';
1213
- const engine = getProjectEngine(pid, streamState.engine);
1397
+ const engine = findProjectEngine(pid, streamState.engine);
1214
1398
 
1215
- if (!engine.resolveUserAnswer) {
1399
+ if (!engine?.resolveUserAnswer) {
1216
1400
  debug.warn('chat', 'resolveUserAnswer: Engine does not support resolveUserAnswer');
1217
1401
  return false;
1218
1402
  }
@@ -1346,8 +1530,8 @@ class StreamManager extends EventEmitter {
1346
1530
  // events and update presence — preventing infinite loader on the frontend.
1347
1531
  const projectId = streamState.projectId || 'default';
1348
1532
  try {
1349
- const engine = getProjectEngine(projectId, streamState.engine);
1350
- if (engine.isActive) {
1533
+ const engine = findProjectEngine(projectId, streamState.engine);
1534
+ if (engine?.isActive) {
1351
1535
  await Promise.race([
1352
1536
  engine.cancel(),
1353
1537
  new Promise<void>(resolve => setTimeout(resolve, 5000))
@@ -0,0 +1,369 @@
1
+ import type { DatabaseConnection } from '$shared/types/database/connection';
2
+ import { debug } from '$shared/utils/logger';
3
+
4
+ export const description =
5
+ 'Create the Memory Graph: nodes, edges, vectors, entity index, the FTS5 mirror and the extraction queue';
6
+
7
+ /**
8
+ * The Memory Graph holds two kinds of memory in ONE store so they can reference
9
+ * each other:
10
+ *
11
+ * - `episodic` — decisions, patterns, failures, preferences, observations
12
+ * carried over from past work, whichever engine produced it.
13
+ * - `structural` — the codebase as entities: files, symbols, modules and the
14
+ * dependencies between them.
15
+ *
16
+ * The join between them is an edge (`rel = 'about'`), which is what makes this a
17
+ * single graph rather than two systems sharing a database. Asking "what touches
18
+ * module Y" then also surfaces the decisions made around it, and asking "what
19
+ * did we decide about X" surfaces the code it applies to.
20
+ *
21
+ * `project_id` is provenance, not a fence: there is one graph for the whole
22
+ * instance and edges may cross projects. Whether a memory travels is `reach`,
23
+ * decided per memory — which is what lets a Svelte gotcha found in one repository
24
+ * be recalled in another, and is the foundation the cross-project global chat is
25
+ * built on. Queries narrow by reach; the storage never partitions.
26
+ */
27
+ export const up = (db: DatabaseConnection): void => {
28
+ debug.log('migration', 'Creating memory graph tables...');
29
+
30
+ // ── nodes ────────────────────────────────────────────────────────────────
31
+ // Three groups of columns, and it is worth knowing which is which:
32
+ //
33
+ // IDENTITY — `digest` is the dedupe key: a stable hash of what identifies the
34
+ // node (repo-relative path for a file, normalised claim for a memory).
35
+ // Extraction runs on every turn and would otherwise re-add the same memory
36
+ // endlessly, so writes upsert on it rather than insert blindly.
37
+ // `digest_version` records which algorithm produced it, so a changed basis
38
+ // can be re-derived deliberately instead of silently forking the graph into
39
+ // duplicates. `entity_key` gives entity-shaped nodes a canonical identity.
40
+ //
41
+ // STANDING — `weight` is reinforcement; `access_count`/`accessed_at` feed
42
+ // retrieval decay. `useful_count`/`unhelpful_count` are the closed loop:
43
+ // access only records that a memory was RETRIEVED, which is not evidence of
44
+ // anything and feeds back into its own ranking, while these record what the
45
+ // next turn actually did with it. `pinned` exempts a node from decay and
46
+ // from automatic pruning.
47
+ //
48
+ // AUTHORITY AND REACH — deliberately four columns rather than two, because
49
+ // collapsing them is what produced the worst bugs this feature had:
50
+ // `source` — which write path wrote this: hand-written through the
51
+ // composer, or not.
52
+ // `asserted_by` — whose claim it is: `user` (they said it), `assistant`
53
+ // (it asserted it) or `inferred` (a model concluded it).
54
+ // Kept apart from `source` so an agent's inference can
55
+ // never retire something a person typed by hand.
56
+ // `reach` — `here` for a claim about this codebase, `anywhere` for a
57
+ // claim about a language, runtime, library or practice
58
+ // that someone on a different project would want. Kept
59
+ // apart from `project_id` so provenance stops acting as a
60
+ // filter.
61
+ // `reach_judged`— whether a model has classified the reach yet, so
62
+ // "judged to be local" is distinguishable from "nobody has
63
+ // looked" and the maintenance pass only revisits the
64
+ // second group.
65
+ //
66
+ // LIFECYCLE — `superseded_by` is belief revision: the node stays (its edges
67
+ // explain how the current belief was reached) but leaves retrieval, so an
68
+ // agent is never handed two versions of one fact. `stale_at` is structural
69
+ // invalidation, set when code a memory is `about` changed underneath it.
70
+ // `archived_at` soft-deletes, so a wrong memory can be dismissed without
71
+ // losing the edges that explain how it was reached.
72
+ //
73
+ // `fts_rowid` points at this node's row in the FTS mirror; see the mirror's
74
+ // own note below for why it is not optional.
75
+ db.exec(`
76
+ CREATE TABLE IF NOT EXISTS graph_nodes (
77
+ id TEXT PRIMARY KEY,
78
+ kind TEXT NOT NULL,
79
+ subkind TEXT NOT NULL,
80
+ scope TEXT NOT NULL DEFAULT 'project',
81
+ project_id TEXT,
82
+ session_id TEXT,
83
+ label TEXT NOT NULL,
84
+ body TEXT NOT NULL DEFAULT '',
85
+ path TEXT,
86
+ symbol TEXT,
87
+ language TEXT,
88
+ digest TEXT NOT NULL,
89
+ -- Callers always supply the current DIGEST_VERSION explicitly; the
90
+ -- default exists only so the column can be NOT NULL.
91
+ digest_version INTEGER NOT NULL DEFAULT 1,
92
+ entity_key TEXT,
93
+ confidence REAL NOT NULL DEFAULT 0.5,
94
+ weight REAL NOT NULL DEFAULT 1.0,
95
+ access_count INTEGER NOT NULL DEFAULT 0,
96
+ useful_count INTEGER NOT NULL DEFAULT 0,
97
+ unhelpful_count INTEGER NOT NULL DEFAULT 0,
98
+ source TEXT NOT NULL DEFAULT 'agent',
99
+ asserted_by TEXT NOT NULL DEFAULT 'inferred',
100
+ reach TEXT NOT NULL DEFAULT 'here',
101
+ reach_judged INTEGER NOT NULL DEFAULT 0,
102
+ pinned INTEGER NOT NULL DEFAULT 0,
103
+ superseded_by TEXT REFERENCES graph_nodes(id) ON DELETE SET NULL,
104
+ stale_at DATETIME,
105
+ archived_at DATETIME,
106
+ fts_rowid INTEGER,
107
+ created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
108
+ updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
109
+ accessed_at DATETIME
110
+ )
111
+ `);
112
+
113
+ // SQLite treats every NULL as distinct in a UNIQUE index, so global-scope
114
+ // rows (project_id IS NULL) would never de-duplicate under a plain UNIQUE.
115
+ // Key on a COALESCE expression the way permission_sets (049) does.
116
+ db.exec(`
117
+ CREATE UNIQUE INDEX IF NOT EXISTS idx_graph_nodes_digest
118
+ ON graph_nodes (COALESCE(project_id, ''), kind, digest)
119
+ `);
120
+ db.exec(`CREATE INDEX IF NOT EXISTS idx_graph_nodes_project ON graph_nodes (project_id, kind)`);
121
+ db.exec(`CREATE INDEX IF NOT EXISTS idx_graph_nodes_scope ON graph_nodes (scope, kind)`);
122
+ db.exec(`CREATE INDEX IF NOT EXISTS idx_graph_nodes_session ON graph_nodes (session_id)`);
123
+ db.exec(`CREATE INDEX IF NOT EXISTS idx_graph_nodes_path ON graph_nodes (COALESCE(project_id, ''), path)`);
124
+
125
+ // One canonical node per entity key, per project, shaped like the digest index
126
+ // so a project-local entity is still possible.
127
+ db.exec(`
128
+ CREATE UNIQUE INDEX IF NOT EXISTS idx_graph_nodes_entity
129
+ ON graph_nodes (COALESCE(project_id, ''), entity_key)
130
+ WHERE entity_key IS NOT NULL
131
+ `);
132
+
133
+ // Retrieval filters on "is this still the current belief" on every query, in
134
+ // both channels, so it needs to be cheap.
135
+ db.exec(`CREATE INDEX IF NOT EXISTS idx_graph_nodes_current ON graph_nodes (superseded_by, archived_at)`);
136
+ // Retention scans by age and by how little a node has earned its place.
137
+ db.exec(`CREATE INDEX IF NOT EXISTS idx_graph_nodes_retention ON graph_nodes (source, pinned, archived_at)`);
138
+
139
+ // The scans that run on a timer. Partial indexes, because every one of them
140
+ // only ever looks at live rows and stays small however much history piles up.
141
+ //
142
+ // The vector backfill's driving query: live episodic nodes, newest first.
143
+ db.exec(`
144
+ CREATE INDEX IF NOT EXISTS idx_graph_nodes_live_episodic
145
+ ON graph_nodes (kind, updated_at DESC)
146
+ WHERE archived_at IS NULL AND superseded_by IS NULL
147
+ `);
148
+ // Eviction scans by age over model-written, unpinned, never-useful rows.
149
+ db.exec(`
150
+ CREATE INDEX IF NOT EXISTS idx_graph_nodes_evictable
151
+ ON graph_nodes (source, pinned, useful_count, access_count, updated_at)
152
+ WHERE archived_at IS NULL AND superseded_by IS NULL
153
+ `);
154
+ // Standing instructions: a query-independent lookup that runs on every turn,
155
+ // so it must be an index seek rather than a scan of the episodic half.
156
+ db.exec(`
157
+ CREATE INDEX IF NOT EXISTS idx_graph_nodes_standing
158
+ ON graph_nodes (asserted_by, subkind, project_id)
159
+ WHERE kind = 'episodic' AND archived_at IS NULL AND superseded_by IS NULL
160
+ `);
161
+ // Cross-project recall filters on reach before anything else.
162
+ db.exec(`
163
+ CREATE INDEX IF NOT EXISTS idx_graph_nodes_reach
164
+ ON graph_nodes (reach, kind)
165
+ WHERE archived_at IS NULL AND superseded_by IS NULL
166
+ `);
167
+ // The reclassification pass looks for what has not been judged.
168
+ db.exec(`
169
+ CREATE INDEX IF NOT EXISTS idx_graph_nodes_reach_pending
170
+ ON graph_nodes (reach_judged, kind)
171
+ WHERE archived_at IS NULL AND superseded_by IS NULL
172
+ `);
173
+ // The Forgotten list, which is the only view that reads archived rows.
174
+ db.exec(`CREATE INDEX IF NOT EXISTS idx_graph_nodes_archived ON graph_nodes (archived_at)`);
175
+ db.exec(`CREATE INDEX IF NOT EXISTS idx_graph_nodes_superseded ON graph_nodes (superseded_by)`);
176
+ // Structural retirement walks path-keyed rows per project.
177
+ db.exec(`CREATE INDEX IF NOT EXISTS idx_graph_nodes_structural_path ON graph_nodes (project_id, kind, path)`);
178
+
179
+ // ── edges ────────────────────────────────────────────────────────────────
180
+ // Relations, grouped by what they connect:
181
+ // structural ↔ structural : imports | calls | defines | contains
182
+ // episodic ↔ episodic : caused_by | supersedes | contradicts | generalizes
183
+ // episodic → structural : about ← the bridge between both halves
184
+ // any ↔ any : relates_to (user-drawn, no semantics implied)
185
+ //
186
+ // `relates_to` is USER-DRAWN ONLY. An automatic similarity linker used to
187
+ // write it from vector neighbourhoods and it fabricated most of the graph:
188
+ // against a corpus of eighty sentences all shaped "X is a project that does
189
+ // Y", every pair is similar in SHAPE rather than in SUBJECT, so 144 of 371
190
+ // edges were pairings like "Vantum monorepo phase 1.8" ↔ "ChatKit runs on
191
+ // Node.js 18+". Connecting statements that share a subject is what the entity
192
+ // index below does directly and exactly; nothing infers `relates_to` now.
193
+ //
194
+ // Direction is meaningful for every relation except `relates_to`. Both ends
195
+ // cascade so archiving/removing a node cannot leave dangling edges.
196
+ db.exec(`
197
+ CREATE TABLE IF NOT EXISTS graph_edges (
198
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
199
+ src_id TEXT NOT NULL REFERENCES graph_nodes(id) ON DELETE CASCADE,
200
+ dst_id TEXT NOT NULL REFERENCES graph_nodes(id) ON DELETE CASCADE,
201
+ rel TEXT NOT NULL,
202
+ weight REAL NOT NULL DEFAULT 1.0,
203
+ source TEXT NOT NULL DEFAULT 'agent',
204
+ created_at DATETIME DEFAULT CURRENT_TIMESTAMP
205
+ )
206
+ `);
207
+ db.exec(`CREATE UNIQUE INDEX IF NOT EXISTS idx_graph_edges_unique ON graph_edges (src_id, dst_id, rel)`);
208
+ db.exec(`CREATE INDEX IF NOT EXISTS idx_graph_edges_src ON graph_edges (src_id)`);
209
+ db.exec(`CREATE INDEX IF NOT EXISTS idx_graph_edges_dst ON graph_edges (dst_id)`);
210
+ // `edgesOf` / invalidation filter by relation far more often than not.
211
+ db.exec(`CREATE INDEX IF NOT EXISTS idx_graph_edges_rel ON graph_edges (rel)`);
212
+ // `contradicts` is walked for every candidate on the read path.
213
+ db.exec(`CREATE INDEX IF NOT EXISTS idx_graph_edges_contradicts ON graph_edges (rel, src_id, dst_id)`);
214
+
215
+ // ── entities ─────────────────────────────────────────────────────────────
216
+ // The subjects a memory is about ("Bun", "PostgreSQL", "Myria Labs"), so five
217
+ // statements about one subject converge on one place instead of being five
218
+ // islands.
219
+ //
220
+ // An ATTRIBUTE of the memory, not a node of its own. Canonical entity nodes
221
+ // were tried first and became half the graph: 115 of 208 episodic nodes were
222
+ // name-only stubs with an empty body, `about` pointed at a stub 220 times and
223
+ // at a file 6, and an empty body means no vector — so a stub could never be
224
+ // found semantically while still being offered to the model as something to
225
+ // adjudicate against. A name is not a claim; it cannot agree or disagree with
226
+ // one. As rows here, joined into the FTS text below, "what do we know about
227
+ // Bun" is an index lookup instead of a graph hop.
228
+ db.exec(`
229
+ CREATE TABLE IF NOT EXISTS graph_node_entities (
230
+ node_id TEXT NOT NULL REFERENCES graph_nodes(id) ON DELETE CASCADE,
231
+ entity_key TEXT NOT NULL,
232
+ name TEXT NOT NULL,
233
+ PRIMARY KEY (node_id, entity_key)
234
+ )
235
+ `);
236
+ db.exec(`CREATE INDEX IF NOT EXISTS idx_graph_node_entities_key ON graph_node_entities (entity_key)`);
237
+
238
+ // ── vectors ──────────────────────────────────────────────────────────────
239
+ // One int8-quantized vector per node (float32 scale + int8 components, 260
240
+ // bytes at 256 dims) produced by the local embedder. `model` records which
241
+ // artifact version wrote it so swapping the model invalidates stale vectors
242
+ // instead of silently mixing two embedding spaces.
243
+ db.exec(`
244
+ CREATE TABLE IF NOT EXISTS graph_vectors (
245
+ node_id TEXT PRIMARY KEY REFERENCES graph_nodes(id) ON DELETE CASCADE,
246
+ dim INTEGER NOT NULL,
247
+ model TEXT NOT NULL,
248
+ vec BLOB NOT NULL,
249
+ updated_at DATETIME DEFAULT CURRENT_TIMESTAMP
250
+ )
251
+ `);
252
+ db.exec(`CREATE INDEX IF NOT EXISTS idx_graph_vectors_model ON graph_vectors (model)`);
253
+
254
+ // ── lexical index ────────────────────────────────────────────────────────
255
+ // BM25 is not a fallback for the vector search — both run on every query and
256
+ // their rankings are fused (see backend/memory/retrieval.ts). Lexical is what
257
+ // finds identifiers, paths and error names, which embeddings are weakest at.
258
+ //
259
+ // A standalone table (not `content=graph_nodes`) because the indexed text is
260
+ // derived from several columns, matching the choice made for messages_fts (064).
261
+ //
262
+ // `node_id` is UNINDEXED, which is why `graph_nodes.fts_rowid` exists: without
263
+ // it, the `DELETE ... WHERE node_id = ?` that every upsert performs is a full
264
+ // scan of the FTS content table. One busy turn upserts a file node, a module
265
+ // node and up to twenty-five symbol nodes for each of sixty files — roughly
266
+ // fifteen hundred full scans of a table that only grows. Keeping the rowid on
267
+ // the node turns each of those into a primary-key lookup.
268
+ db.exec(`
269
+ CREATE VIRTUAL TABLE IF NOT EXISTS graph_nodes_fts USING fts5(
270
+ node_id UNINDEXED,
271
+ project_id UNINDEXED,
272
+ scope UNINDEXED,
273
+ kind UNINDEXED,
274
+ text
275
+ )
276
+ `);
277
+
278
+ // ── extraction queue ─────────────────────────────────────────────────────
279
+ // Where a finished turn waits to be summarised.
280
+ //
281
+ // A table rather than an in-memory map, because a map lost turns three ways
282
+ // silently: a failed model call (rate limited, account expired, engine
283
+ // restarting, no model configured) was logged and dropped with no second
284
+ // attempt ever; a restart discarded everything parked; and none of it was
285
+ // visible, so memory simply did not grow and the only way to find out why was
286
+ // to read the server log. Rows survive a crash, a failure schedules a retry
287
+ // with backoff, and the queue is countable — the UI can say "3 waiting, 1
288
+ // retrying" instead of leaving the user to guess.
289
+ //
290
+ // ONE ROW PER SESSION, enforced by the unique index. That is not just
291
+ // deduplication — it IS the "bank the oldest boundary" rule from the scheduler
292
+ // expressed in the schema: a new turn in a session already queued merges into
293
+ // the existing row and keeps its `user_message_id`, because the transcript runs
294
+ // from that message to the end of the chain and the older boundary is the one
295
+ // that covers everything since.
296
+ db.exec(`
297
+ CREATE TABLE IF NOT EXISTS memory_extraction_queue (
298
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
299
+ session_id TEXT NOT NULL,
300
+ project_id TEXT NOT NULL,
301
+ project_path TEXT NOT NULL,
302
+ -- The OLDEST turn boundary not yet summarised; see the note above.
303
+ user_message_id TEXT NOT NULL,
304
+ -- JSON arrays. Accumulated across every turn merged into this row.
305
+ changed_paths TEXT NOT NULL DEFAULT '[]',
306
+ deleted_paths TEXT NOT NULL DEFAULT '[]',
307
+ -- Memories injected into those turns, so the extraction can adjudicate them.
308
+ injected_ids TEXT NOT NULL DEFAULT '[]',
309
+ attempts INTEGER NOT NULL DEFAULT 0,
310
+ last_error TEXT,
311
+ -- pending: will run once ready_at passes. failed: attempts exhausted,
312
+ -- kept so it stays visible and can be retried deliberately.
313
+ status TEXT NOT NULL DEFAULT 'pending',
314
+ -- Bumped on every merge. Extraction runs the moment a turn ends, so a
315
+ -- turn can finish while the previous one is still being summarised and
316
+ -- enqueueing merges into the row already in flight — whose runner would
317
+ -- then delete it on success, taking the merged-in turn with it. The
318
+ -- runner remembers the revision it claimed and its delete is conditional
319
+ -- on the row still being at it.
320
+ revision INTEGER NOT NULL DEFAULT 0,
321
+ -- The idle delay and the retry backoff are both expressed here, so the
322
+ -- runner only ever asks "what is due?".
323
+ ready_at DATETIME NOT NULL,
324
+ created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
325
+ updated_at DATETIME DEFAULT CURRENT_TIMESTAMP
326
+ )
327
+ `);
328
+ db.exec(`CREATE UNIQUE INDEX IF NOT EXISTS idx_memory_queue_session ON memory_extraction_queue (session_id)`);
329
+ // The runner's only hot query: due rows, oldest first.
330
+ db.exec(`CREATE INDEX IF NOT EXISTS idx_memory_queue_due ON memory_extraction_queue (status, ready_at)`);
331
+
332
+ debug.log('migration', 'Memory graph tables created');
333
+ };
334
+
335
+ export const down = (db: DatabaseConnection): void => {
336
+ debug.log('migration', 'Dropping memory graph tables...');
337
+ db.exec(`DROP INDEX IF EXISTS idx_memory_queue_due`);
338
+ db.exec(`DROP INDEX IF EXISTS idx_memory_queue_session`);
339
+ db.exec(`DROP TABLE IF EXISTS memory_extraction_queue`);
340
+ db.exec(`DROP TABLE IF EXISTS graph_nodes_fts`);
341
+ db.exec(`DROP INDEX IF EXISTS idx_graph_vectors_model`);
342
+ db.exec(`DROP TABLE IF EXISTS graph_vectors`);
343
+ db.exec(`DROP INDEX IF EXISTS idx_graph_node_entities_key`);
344
+ db.exec(`DROP TABLE IF EXISTS graph_node_entities`);
345
+ db.exec(`DROP INDEX IF EXISTS idx_graph_edges_contradicts`);
346
+ db.exec(`DROP INDEX IF EXISTS idx_graph_edges_rel`);
347
+ db.exec(`DROP INDEX IF EXISTS idx_graph_edges_dst`);
348
+ db.exec(`DROP INDEX IF EXISTS idx_graph_edges_src`);
349
+ db.exec(`DROP INDEX IF EXISTS idx_graph_edges_unique`);
350
+ db.exec(`DROP TABLE IF EXISTS graph_edges`);
351
+ db.exec(`DROP INDEX IF EXISTS idx_graph_nodes_structural_path`);
352
+ db.exec(`DROP INDEX IF EXISTS idx_graph_nodes_superseded`);
353
+ db.exec(`DROP INDEX IF EXISTS idx_graph_nodes_archived`);
354
+ db.exec(`DROP INDEX IF EXISTS idx_graph_nodes_reach_pending`);
355
+ db.exec(`DROP INDEX IF EXISTS idx_graph_nodes_reach`);
356
+ db.exec(`DROP INDEX IF EXISTS idx_graph_nodes_standing`);
357
+ db.exec(`DROP INDEX IF EXISTS idx_graph_nodes_evictable`);
358
+ db.exec(`DROP INDEX IF EXISTS idx_graph_nodes_live_episodic`);
359
+ db.exec(`DROP INDEX IF EXISTS idx_graph_nodes_retention`);
360
+ db.exec(`DROP INDEX IF EXISTS idx_graph_nodes_current`);
361
+ db.exec(`DROP INDEX IF EXISTS idx_graph_nodes_entity`);
362
+ db.exec(`DROP INDEX IF EXISTS idx_graph_nodes_path`);
363
+ db.exec(`DROP INDEX IF EXISTS idx_graph_nodes_session`);
364
+ db.exec(`DROP INDEX IF EXISTS idx_graph_nodes_scope`);
365
+ db.exec(`DROP INDEX IF EXISTS idx_graph_nodes_project`);
366
+ db.exec(`DROP INDEX IF EXISTS idx_graph_nodes_digest`);
367
+ db.exec(`DROP TABLE IF EXISTS graph_nodes`);
368
+ debug.log('migration', 'Memory graph tables dropped');
369
+ };