@myrialabs/clopen 0.4.26 → 0.4.28

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (98) hide show
  1. package/backend/auth/permissions.ts +21 -0
  2. package/backend/bootstrap.ts +18 -1
  3. package/backend/chat/engine-handoff.test.ts +229 -0
  4. package/backend/chat/engine-handoff.ts +439 -0
  5. package/backend/chat/stream-manager.ts +200 -16
  6. package/backend/database/migrations/066_create_memory_graph.ts +369 -0
  7. package/backend/database/migrations/index.ts +7 -0
  8. package/backend/database/queries/audit-log-queries.test.ts +10 -1
  9. package/backend/database/queries/graph-queries.ts +1764 -0
  10. package/backend/database/queries/index.ts +2 -0
  11. package/backend/database/queries/memory-queue-queries.ts +381 -0
  12. package/backend/database/queries/snapshot-queries.ts +20 -0
  13. package/backend/engine/README.md +45 -2
  14. package/backend/engine/adapters/claude/message-converter.ts +5 -24
  15. package/backend/engine/adapters/copilot/stream.ts +37 -1
  16. package/backend/engine/adapters/pi/models.ts +19 -7
  17. package/backend/engine/adapters/pi/stream.ts +2 -1
  18. package/backend/engine/docs/adapter-contract.md +25 -8
  19. package/backend/engine/docs/adding-an-engine.md +40 -4
  20. package/backend/engine/docs/frontend-and-chat.md +66 -1
  21. package/backend/engine/docs/lessons-learned.md +165 -6
  22. package/backend/engine/docs/quick-reference.md +10 -0
  23. package/backend/engine/docs/stack.md +10 -0
  24. package/backend/engine/docs/websocket-routes.md +15 -1
  25. package/backend/engine/engine-setup.ts +1 -1
  26. package/backend/engine/index.test.ts +186 -0
  27. package/backend/engine/index.ts +117 -71
  28. package/backend/engine/install-recipes.test.ts +105 -0
  29. package/backend/engine/install-recipes.ts +4 -1
  30. package/backend/index.ts +9 -0
  31. package/backend/mcp/internal/config.ts +6 -0
  32. package/backend/mcp/internal/servers/index.ts +2 -0
  33. package/backend/mcp/internal/servers/memory-graph/description.ts +33 -0
  34. package/backend/mcp/internal/servers/memory-graph/format.ts +45 -0
  35. package/backend/mcp/internal/servers/memory-graph/index.ts +52 -0
  36. package/backend/mcp/internal/servers/memory-graph/runner.ts +342 -0
  37. package/backend/mcp/internal/servers/memory-graph/schema.ts +140 -0
  38. package/backend/memory/README.md +432 -0
  39. package/backend/memory/bootstrap.ts +101 -0
  40. package/backend/memory/compose.test.ts +198 -0
  41. package/backend/memory/compose.ts +343 -0
  42. package/backend/memory/config.ts +100 -0
  43. package/backend/memory/consolidate.ts +280 -0
  44. package/backend/memory/context.test.ts +321 -0
  45. package/backend/memory/context.ts +451 -0
  46. package/backend/memory/embedding/embedder.test.ts +141 -0
  47. package/backend/memory/embedding/embedder.ts +269 -0
  48. package/backend/memory/embedding/index.ts +17 -0
  49. package/backend/memory/embedding/install.ts +254 -0
  50. package/backend/memory/embedding/paths.ts +101 -0
  51. package/backend/memory/embedding/vector-cache.ts +270 -0
  52. package/backend/memory/extract/episodic.ts +725 -0
  53. package/backend/memory/extract/index.ts +133 -0
  54. package/backend/memory/extract/languages.ts +176 -0
  55. package/backend/memory/extract/scheduler.test.ts +352 -0
  56. package/backend/memory/extract/scheduler.ts +406 -0
  57. package/backend/memory/extract/structural.test.ts +215 -0
  58. package/backend/memory/extract/structural.ts +364 -0
  59. package/backend/memory/index.ts +37 -0
  60. package/backend/memory/indexer.ts +150 -0
  61. package/backend/memory/invalidate.ts +134 -0
  62. package/backend/memory/judge.ts +285 -0
  63. package/backend/memory/maintenance.ts +132 -0
  64. package/backend/memory/model.ts +91 -0
  65. package/backend/memory/notify.ts +102 -0
  66. package/backend/memory/readiness.ts +74 -0
  67. package/backend/memory/redact.test.ts +101 -0
  68. package/backend/memory/redact.ts +133 -0
  69. package/backend/memory/retention.ts +139 -0
  70. package/backend/memory/retrieval.eval.test.ts +301 -0
  71. package/backend/memory/retrieval.test.ts +1023 -0
  72. package/backend/memory/retrieval.ts +707 -0
  73. package/backend/memory/revise.test.ts +693 -0
  74. package/backend/memory/revise.ts +400 -0
  75. package/backend/memory/time.ts +31 -0
  76. package/backend/memory/view.ts +164 -0
  77. package/backend/shipped-runtime-imports.test.ts +228 -0
  78. package/backend/ws/engine/claude/accounts.ts +4 -12
  79. package/backend/ws/engine/codex/accounts.ts +4 -13
  80. package/backend/ws/engine/pty-output.test.ts +37 -0
  81. package/backend/ws/engine/pty-output.ts +43 -0
  82. package/backend/ws/index.ts +5 -1
  83. package/backend/ws/memory/crud.ts +631 -0
  84. package/backend/ws/memory/index.ts +41 -0
  85. package/backend/ws/sessions/crud.ts +10 -0
  86. package/backend/ws/snapshot/restore.ts +38 -4
  87. package/dist/assets/graph-layout.worker-CRFqN7ZQ.js +1 -0
  88. package/dist/assets/{index-DYa-GDsb.js → index-BujQYGBm.js} +1 -1
  89. package/dist/assets/{index-B6QGUN03.js → index-DRMOgS9y.js} +1 -1
  90. package/dist/assets/{main-Dznkfxsd.js → main-BrYtWn-4.js} +832 -423
  91. package/dist/assets/main-BrqMMMRX.css +1 -0
  92. package/dist/index.html +2 -2
  93. package/package.json +8 -2
  94. package/shared/types/database/connection.ts +9 -0
  95. package/shared/types/memory.ts +519 -0
  96. package/shared/utils/logger.ts +1 -0
  97. package/dist/assets/main-Dh-MTGNR.css +0 -1
  98. package/shared/utils/anonymous-user.ts +0 -168
@@ -0,0 +1,364 @@
1
+ /**
2
+ * Structural extraction — the codebase as graph nodes.
3
+ *
4
+ * The input is the set of files that CHANGED ON DISK during a turn, taken from
5
+ * the snapshot service. That source matters more than it looks: snapshots are a
6
+ * gitignore-aware disk diff against the session baseline
7
+ * (`snapshot-service.ts:166` — "the source of truth is the DISK"), so a file is
8
+ * seen no matter how it was edited.
9
+ *
10
+ * Deriving this from tool calls instead would have been wrong. Agents rewrite
11
+ * files through `Bash` constantly — `sed -i`, a codemod script, `git checkout`,
12
+ * a formatter, a build step — and none of that appears as an Edit or Write tool
13
+ * call. Watching the disk sees all of it and needs no per-engine knowledge of
14
+ * tool names, which also means every engine gets identical behaviour for free.
15
+ *
16
+ * Only changed files are read. There is no repository-wide indexing pass, so the
17
+ * cost is bounded by how much the turn actually touched, and the graph grows to
18
+ * describe the parts of the codebase that are genuinely being worked on.
19
+ */
20
+
21
+ import { readFile, stat } from 'node:fs/promises';
22
+ import { basename, join, posix, relative, resolve } from 'node:path';
23
+ import { graphQueries } from '$backend/database/queries/graph-queries';
24
+ import { debug } from '$shared/utils/logger';
25
+ import type { GraphNode } from '$shared/types/memory';
26
+ import { detectLanguage, extractDefinitions, extractImports, isParseable, RESOLVE_EXTENSIONS } from './languages';
27
+
28
+ /** Files parsed per turn. A large refactor is summarised, not exhaustively mapped. */
29
+ const MAX_FILES_PER_TURN = 60;
30
+
31
+ /** Source files above this are skipped — bundles and generated blobs teach nothing. */
32
+ const MAX_FILE_BYTES = 400_000;
33
+
34
+ /** Symbol nodes created per file, so a barrel export cannot flood the graph. */
35
+ const MAX_SYMBOLS_PER_FILE = 25;
36
+
37
+ /** Paths that describe machinery rather than the project's own design. */
38
+ const IGNORED_SEGMENTS = new Set([
39
+ 'node_modules',
40
+ 'dist',
41
+ 'build',
42
+ '.git',
43
+ '.svelte-kit',
44
+ 'coverage',
45
+ 'vendor',
46
+ '__pycache__',
47
+ 'target',
48
+ '.next',
49
+ '.cache'
50
+ ]);
51
+
52
+ export interface StructuralIngestInput {
53
+ projectId: string;
54
+ projectPath: string;
55
+ sessionId: string | null;
56
+ /** Repo-relative paths that changed on disk this turn. */
57
+ changedPaths: string[];
58
+ }
59
+
60
+ /**
61
+ * Everything one file contributes, resolved off disk before any row is written.
62
+ *
63
+ * The two phases are separated on purpose. Parsing is async (`readFile`, `stat`)
64
+ * and SQLite transactions are synchronous, so interleaving them would mean either
65
+ * no transaction at all — which is what this originally did, at a cost of several
66
+ * thousand individually-durable statements on a busy turn — or a transaction held
67
+ * open across every file read on the machine.
68
+ */
69
+ interface ParsedFile {
70
+ path: string;
71
+ language: string | null;
72
+ /** Repo-relative paths this file imports, already resolved to real files. */
73
+ importsLocal: string[];
74
+ /** npm package names this file imports. */
75
+ importsExternal: string[];
76
+ definitions: string[];
77
+ }
78
+
79
+ export interface StructuralIngestResult {
80
+ files: number;
81
+ symbols: number;
82
+ edges: number;
83
+ /** Path → node id, so episodic extraction can attach `about` edges. */
84
+ fileNodes: Map<string, string>;
85
+ }
86
+
87
+ function isIgnored(path: string): boolean {
88
+ return path.split(/[/\\]/).some(segment => IGNORED_SEGMENTS.has(segment));
89
+ }
90
+
91
+ /** Normalize to forward slashes so Windows and POSIX produce the same digest. */
92
+ function normalize(path: string): string {
93
+ return path.replace(/\\/g, '/');
94
+ }
95
+
96
+ /**
97
+ * Resolve an import specifier to a repo-relative path, or null when it points
98
+ * outside the project (a package, a stdlib module, an unresolvable alias).
99
+ *
100
+ * Only relative specifiers are resolved. TypeScript path aliases (`$backend/…`)
101
+ * would need tsconfig parsing per project and are deliberately left alone: a
102
+ * wrong edge is worse than a missing one, because it invents a dependency the
103
+ * codebase does not have.
104
+ */
105
+ async function resolveImport(
106
+ fromPath: string,
107
+ specifier: string,
108
+ projectPath: string
109
+ ): Promise<string | null> {
110
+ if (!specifier.startsWith('.')) return null;
111
+
112
+ const baseDir = posix.dirname(normalize(fromPath));
113
+ const joined = posix.normalize(posix.join(baseDir, specifier));
114
+
115
+ // Escaping the project root means it is not ours to describe.
116
+ if (joined.startsWith('..')) return null;
117
+
118
+ const candidates = [
119
+ joined,
120
+ ...RESOLVE_EXTENSIONS.map(ext => `${joined}${ext}`),
121
+ ...RESOLVE_EXTENSIONS.map(ext => posix.join(joined, `index${ext}`))
122
+ ];
123
+
124
+ for (const candidate of candidates) {
125
+ // Strip any query/hash a bundler-style specifier might carry.
126
+ const clean = candidate.split(/[?#]/)[0];
127
+ const absolute = resolve(projectPath, clean);
128
+ // Containment check: a crafted specifier must not let this stat outside
129
+ // the project.
130
+ if (relative(projectPath, absolute).startsWith('..')) continue;
131
+ try {
132
+ const info = await stat(absolute);
133
+ if (info.isFile()) return clean;
134
+ } catch {
135
+ // keep trying
136
+ }
137
+ }
138
+ return null;
139
+ }
140
+
141
+ /** Upsert the file node for a repo-relative path. */
142
+ function upsertFileNode(projectId: string, path: string, sessionId: string | null): GraphNode {
143
+ const normalized = normalize(path);
144
+ return graphQueries.upsert({
145
+ kind: 'structural',
146
+ subkind: 'file',
147
+ scope: 'project',
148
+ projectId,
149
+ sessionId,
150
+ label: basename(normalized),
151
+ body: normalized,
152
+ path: normalized,
153
+ language: detectLanguage(normalized),
154
+ // Structural facts read off disk are near-certain, but "near": the file
155
+ // existed when it was read and may not now.
156
+ confidence: 0.9,
157
+ source: 'agent'
158
+ });
159
+ }
160
+
161
+ /**
162
+ * Turn a turn's disk changes into structural nodes and edges.
163
+ *
164
+ * Never throws — a file that vanished mid-turn, or an unreadable path, is
165
+ * skipped. This runs after the user's turn has already completed, so failing
166
+ * loudly would only break something the user considers finished.
167
+ */
168
+ export async function ingestStructuralChanges(
169
+ input: StructuralIngestInput
170
+ ): Promise<StructuralIngestResult> {
171
+ const { projectId, projectPath, sessionId } = input;
172
+ const result: StructuralIngestResult = { files: 0, symbols: 0, edges: 0, fileNodes: new Map() };
173
+
174
+ const paths = input.changedPaths
175
+ .map(normalize)
176
+ .filter(path => path && !isIgnored(path))
177
+ .slice(0, MAX_FILES_PER_TURN);
178
+
179
+ if (paths.length === 0) return result;
180
+
181
+ // ── phase 1: read and parse, off the database entirely ──────────────────
182
+ const parsed: ParsedFile[] = [];
183
+ for (const path of paths) {
184
+ try {
185
+ parsed.push(await parseFile(path, projectPath));
186
+ } catch (error) {
187
+ debug.warn('memory', `Structural extraction skipped ${path}`, error);
188
+ }
189
+ }
190
+
191
+ // ── phase 2: one transaction for every write ────────────────────────────
192
+ // A busy turn touching sixty files that define twenty-five symbols each is
193
+ // several thousand statements, and each upsert is itself a SELECT, an
194
+ // INSERT/UPDATE and an FTS rewrite. Outside a transaction every one of those is
195
+ // its own durability barrier, which made this by far the most expensive thing
196
+ // on the write path — for no benefit, since a partially-ingested turn is not a
197
+ // state anyone wants to keep anyway.
198
+ try {
199
+ graphQueries.transaction(() => {
200
+ for (const file of parsed) {
201
+ const fileNode = upsertFileNode(projectId, file.path, sessionId);
202
+ result.files++;
203
+ result.fileNodes.set(file.path, fileNode.id);
204
+
205
+ // Directory containment gives the graph its skeleton, which is what makes
206
+ // community detection produce meaningful "lobes" in the visualization
207
+ // rather than one undifferentiated cloud.
208
+ const parent = posix.dirname(file.path);
209
+ if (parent && parent !== '.' && parent !== '/') {
210
+ const moduleNode = graphQueries.upsert({
211
+ kind: 'structural',
212
+ subkind: 'module',
213
+ scope: 'project',
214
+ projectId,
215
+ label: basename(parent),
216
+ body: parent,
217
+ path: parent,
218
+ confidence: 0.9,
219
+ source: 'agent'
220
+ });
221
+ if (graphQueries.link({ srcId: moduleNode.id, dstId: fileNode.id, rel: 'contains' })) {
222
+ result.edges++;
223
+ }
224
+ }
225
+
226
+ for (const target of file.importsLocal) {
227
+ const targetNode = upsertFileNode(projectId, target, sessionId);
228
+ if (graphQueries.link({ srcId: fileNode.id, dstId: targetNode.id, rel: 'imports' })) {
229
+ result.edges++;
230
+ }
231
+ }
232
+
233
+ // Non-relative specifiers become dependency nodes, which is what makes
234
+ // "what in this codebase touches puppeteer" answerable — and, across
235
+ // projects, "which repositories share this dependency".
236
+ for (const pkg of file.importsExternal) {
237
+ const depNode = graphQueries.upsert({
238
+ kind: 'structural',
239
+ subkind: 'dependency',
240
+ scope: 'global',
241
+ projectId: null,
242
+ label: pkg,
243
+ body: pkg,
244
+ confidence: 0.8,
245
+ source: 'agent'
246
+ });
247
+ if (graphQueries.link({ srcId: fileNode.id, dstId: depNode.id, rel: 'imports' })) {
248
+ result.edges++;
249
+ }
250
+ }
251
+
252
+ for (const name of file.definitions) {
253
+ const symbolNode = graphQueries.upsert({
254
+ kind: 'structural',
255
+ subkind: 'symbol',
256
+ scope: 'project',
257
+ projectId,
258
+ sessionId,
259
+ label: name,
260
+ body: `${name} — ${file.path}`,
261
+ path: file.path,
262
+ symbol: name,
263
+ language: file.language,
264
+ // Regex-derived, so lower than a file's existence.
265
+ confidence: 0.6,
266
+ source: 'agent'
267
+ });
268
+ result.symbols++;
269
+ if (graphQueries.link({ srcId: fileNode.id, dstId: symbolNode.id, rel: 'defines' })) {
270
+ result.edges++;
271
+ }
272
+ }
273
+ }
274
+ });
275
+ } catch (error) {
276
+ // The transaction rolled back, so the graph is exactly as it was. This runs
277
+ // after the user's turn has already completed, so failing loudly would only
278
+ // break something they consider finished.
279
+ debug.warn('memory', 'Structural ingest rolled back', error);
280
+ return { files: 0, symbols: 0, edges: 0, fileNodes: new Map() };
281
+ }
282
+
283
+ debug.log(
284
+ 'memory',
285
+ `Structural ingest: ${result.files} file(s), ${result.symbols} symbol(s), ${result.edges} edge(s)`
286
+ );
287
+ return result;
288
+ }
289
+
290
+ /**
291
+ * Read one file and resolve everything the graph needs from it. Touches no
292
+ * database — see the two-phase note on `ParsedFile`.
293
+ */
294
+ async function parseFile(path: string, projectPath: string): Promise<ParsedFile> {
295
+ const absolute = join(projectPath, path);
296
+ const language = detectLanguage(path);
297
+
298
+ // A file that vanished mid-turn still gets its node: the memories pointing at
299
+ // it remain true history, and `invalidate.ts` is what retires it once the
300
+ // snapshot confirms the deletion. Only the read is skipped.
301
+ let source: string | null = null;
302
+ if (isParseable(language)) {
303
+ try {
304
+ const info = await stat(absolute);
305
+ if (info.isFile() && info.size <= MAX_FILE_BYTES) {
306
+ source = await readFile(absolute, 'utf8');
307
+ }
308
+ } catch {
309
+ source = null;
310
+ }
311
+ }
312
+
313
+ const parsed: ParsedFile = { path, language, importsLocal: [], importsExternal: [], definitions: [] };
314
+ if (!source || !language) return parsed;
315
+
316
+ for (const specifier of extractImports(source, language)) {
317
+ const target = await resolveImport(path, specifier, projectPath);
318
+ if (target) {
319
+ parsed.importsLocal.push(target);
320
+ continue;
321
+ }
322
+ const pkg = externalPackageName(specifier);
323
+ if (pkg) parsed.importsExternal.push(pkg);
324
+ }
325
+
326
+ parsed.importsLocal = [...new Set(parsed.importsLocal)];
327
+ parsed.importsExternal = [...new Set(parsed.importsExternal)];
328
+ parsed.definitions = extractDefinitions(source, language).slice(0, MAX_SYMBOLS_PER_FILE);
329
+ return parsed;
330
+ }
331
+
332
+ /** npm package names: lowercase, no leading dot/underscore, limited punctuation. */
333
+ const NPM_NAME = /^[a-z0-9][a-z0-9._-]*$/;
334
+
335
+ /**
336
+ * Package name from a bare import specifier: `@scope/pkg/sub` → `@scope/pkg`,
337
+ * `lodash/merge` → `lodash`. Returns null for anything that is not actually a
338
+ * package.
339
+ *
340
+ * Rejecting non-packages matters more than it sounds. A build-tool path alias
341
+ * (`$shared/types`, `~/lib`, `@/utils`) is not a dependency, and turning one into
342
+ * a node invents a shared dependency between every file that uses the alias —
343
+ * which then distorts community detection and, because the resulting node's label
344
+ * is a two-token fragment, pollutes vector search as well. Aliases cannot be
345
+ * resolved to real files without parsing each project's build config, so they are
346
+ * dropped rather than guessed at.
347
+ */
348
+ function externalPackageName(specifier: string): string | null {
349
+ const cleaned = specifier.replace(/^node:/, '').split(/[?#]/)[0];
350
+ if (!cleaned || cleaned.startsWith('/') || cleaned.startsWith('.')) return null;
351
+
352
+ const segments = cleaned.split('/');
353
+ if (cleaned.startsWith('@')) {
354
+ // A scoped package is `@scope/name`; `@/utils` has an empty scope and is an
355
+ // alias, not a package.
356
+ if (segments.length < 2) return null;
357
+ const scope = segments[0].slice(1);
358
+ if (!NPM_NAME.test(scope) || !NPM_NAME.test(segments[1])) return null;
359
+ return `${segments[0]}/${segments[1]}`;
360
+ }
361
+
362
+ // Filters `$shared`, `~lib`, `#internal` and Windows-style absolute includes.
363
+ return NPM_NAME.test(segments[0]) ? segments[0] : null;
364
+ }
@@ -0,0 +1,37 @@
1
+ /**
2
+ * Memory Graph — public surface.
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.
8
+ *
9
+ * Layout:
10
+ * embedding/ local static-embedding model, installed on demand
11
+ * retrieval.ts BM25 + vector + graph expansion, fused with RRF
12
+ * indexer.ts backfills vectors behind writes
13
+ * extract/ turns work into memory (structural from disk diffs, episodic per turn)
14
+ * compose.ts the hand-written path: free text in, reviewed memory out
15
+ * context.ts token-budgeted injection at turn start
16
+ * time.ts reads SQLite timestamps as the UTC they actually are
17
+ * redact.ts keeps credentials out of durable storage
18
+ * revise.ts belief revision — duplicates, supersession, entities, feedback
19
+ * invalidate.ts ages memories whose code changed underneath them
20
+ * consolidate.ts compresses clusters of memories into generalisations
21
+ * retention.ts the bound on how large the graph may grow
22
+ * maintenance.ts runs the background jobs when nobody is working
23
+ */
24
+
25
+ export { retrieve, profileQuery, markConsulted } from './retrieval';
26
+ export { redactSecrets, neutralizeForPrompt, containsSecret } from './redact';
27
+ export { findRelatedCandidates, findDuplicateCandidates, mergeDuplicate, linkEntities, recordContradictions } from './revise';
28
+ export { draftMemory, createMemory } from './compose';
29
+ export { invalidateForChanges } from './invalidate';
30
+ export { consolidateMemories } from './consolidate';
31
+ export { applyRetention } from './retention';
32
+ export { startMemoryMaintenance, stopMemoryMaintenance, runMaintenanceNow } from './maintenance';
33
+ export { scheduleVectorIndexing, drain as drainVectorIndex, reconcileVectorIndex } from './indexer';
34
+ export { embedder, ensureEmbeddingArtifact, isEmbeddingArtifactInstalled, type EmbedderStatus } from './embedding';
35
+ export { getMemoryReadiness, type MemoryReadiness, type MemoryBlocker } from './readiness';
36
+ export { ensureMemoryModel } from './model';
37
+ export { bootstrapMemoryGraph } from './bootstrap';
@@ -0,0 +1,150 @@
1
+ /**
2
+ * Vector indexer.
3
+ *
4
+ * Nodes are written the moment they are extracted, but their vectors are filled
5
+ * in behind the write. That separation is deliberate: the embedding artifact
6
+ * installs on demand, so a node created in the first minutes of a fresh install
7
+ * must not have to wait for a 41 MB download to exist. Until vectors land,
8
+ * retrieval runs on BM25 and graph traversal, and the same node becomes
9
+ * semantically searchable later without being rewritten.
10
+ *
11
+ * Work is drained in small batches on a timer rather than per-node so a busy turn
12
+ * that touches forty files does not turn into forty separate passes.
13
+ */
14
+
15
+ import { graphQueries } from '$backend/database/queries/graph-queries';
16
+ import { debug } from '$shared/utils/logger';
17
+ import { embedder, packVector, vectorCache } from './embedding';
18
+ import { EMBEDDING_VERSION } from './embedding/paths';
19
+ import { notifyGraphChanged } from './notify';
20
+
21
+ /** Nodes embedded per drain. ~0.05 ms each, so a batch is a fraction of a millisecond. */
22
+ const BATCH_SIZE = 200;
23
+
24
+ /** Delay before a drain, so a burst of writes coalesces into one pass. */
25
+ const DEBOUNCE_MS = 400;
26
+
27
+ /**
28
+ * Fewest tokens a node must have to earn a vector.
29
+ *
30
+ * Measured against this artifact: real memories tokenize to 12–30 tokens and
31
+ * path-rich file nodes to ~20, while a bare `index.ts` is 8 and a stray
32
+ * two-token label is 2. Below roughly ten tokens the mean-pooled vector stops
33
+ * describing meaning and starts scoring highly against everything, which is how
34
+ * a filename ends up outranking the decision someone actually asked about.
35
+ *
36
+ * Excluded nodes are still fully searchable — a filename or symbol is what BM25
37
+ * is best at, so nothing is lost by keeping them out of the vector channel.
38
+ */
39
+ const MIN_TOKENS_FOR_VECTOR = 10;
40
+
41
+ let timer: ReturnType<typeof setTimeout> | null = null;
42
+ let draining = false;
43
+ /** A write arrived mid-drain and still needs a pass. See `scheduleVectorIndexing`. */
44
+ let dirty = false;
45
+
46
+ /**
47
+ * Ask for a drain soon. Cheap and idempotent — call it after any write that adds
48
+ * or changes node text.
49
+ *
50
+ * A request that arrives while a drain is already running is REMEMBERED rather
51
+ * than dropped. Returning early there looks harmless and is not: the running
52
+ * drain has already taken its batch, so a node written a moment later is not in
53
+ * it, nothing is scheduled, and that node stays unvectorized until some
54
+ * unrelated write happens to schedule the next pass — or until a restart. The
55
+ * symptom is a memory that is lexically findable and semantically invisible,
56
+ * which is indistinguishable from the ranker simply not rating it.
57
+ */
58
+ export function scheduleVectorIndexing(): void {
59
+ if (draining) {
60
+ dirty = true;
61
+ return;
62
+ }
63
+ if (timer) return;
64
+ timer = setTimeout(() => {
65
+ timer = null;
66
+ void drain();
67
+ }, DEBOUNCE_MS);
68
+ }
69
+
70
+ /**
71
+ * Embed nodes that have no vector for the current artifact version. Returns how
72
+ * many were written. Safe to call directly; concurrent calls collapse into one.
73
+ */
74
+ export async function drain(): Promise<number> {
75
+ if (draining) return 0;
76
+ if (!embedder.ready && !(await embedder.load())) return 0;
77
+
78
+ draining = true;
79
+ dirty = false;
80
+ let written = 0;
81
+ try {
82
+ // Loop so a large backlog (a freshly installed artifact facing an existing
83
+ // graph) is cleared without waiting for a drain per batch.
84
+ for (;;) {
85
+ const pending = graphQueries.nodesMissingVectors(EMBEDDING_VERSION, BATCH_SIZE);
86
+ if (pending.length === 0) break;
87
+
88
+ const vectorized: typeof pending = [];
89
+ for (const node of pending) {
90
+ const vec = embedder.embed(graphQueries.embeddableText(node), {
91
+ minTokens: MIN_TOKENS_FOR_VECTOR
92
+ });
93
+ if (!vec) {
94
+ // Too short to embed meaningfully (or entirely out-of-vocabulary).
95
+ // Store a zero vector: it records that this node was considered, so it
96
+ // is not re-picked on every drain forever, and it scores 0 in
97
+ // similarity so it never competes. The node stays fully reachable
98
+ // through BM25 and the graph.
99
+ const zero = packVector(new Float32Array(embedder.dim ?? 0));
100
+ graphQueries.setVector(node.id, embedder.dim ?? 0, EMBEDDING_VERSION, zero);
101
+ vectorCache.set(node.id, zero);
102
+ continue;
103
+ }
104
+ const packed = packVector(vec);
105
+ graphQueries.setVector(node.id, vec.length, EMBEDDING_VERSION, packed);
106
+ vectorCache.set(node.id, packed);
107
+ vectorized.push(node);
108
+ written++;
109
+ }
110
+
111
+ if (pending.length < BATCH_SIZE) break;
112
+ // Yield between batches so a big backfill cannot monopolise the loop.
113
+ await new Promise(resolve => setTimeout(resolve, 0));
114
+ }
115
+
116
+ } catch (error) {
117
+ debug.error('memory', 'Vector indexing failed', error);
118
+ } finally {
119
+ draining = false;
120
+ }
121
+
122
+ if (written > 0) {
123
+ debug.log('memory', `Indexed ${written} memory vector(s)`);
124
+ notifyGraphChanged('links');
125
+ }
126
+
127
+ // A write that landed while this pass was running still needs one.
128
+ if (dirty) {
129
+ dirty = false;
130
+ scheduleVectorIndexing();
131
+ }
132
+ return written;
133
+ }
134
+
135
+ /**
136
+ * Bring the vector index in line with the installed artifact, then backfill.
137
+ * Called once the artifact is known to be ready.
138
+ *
139
+ * Vectors from a different artifact version are deleted rather than kept:
140
+ * cosine between two different embedding spaces is meaningless, and mixing them
141
+ * would silently corrupt ranking in a way that is very hard to notice.
142
+ */
143
+ export async function reconcileVectorIndex(): Promise<void> {
144
+ const removed = graphQueries.pruneVectorsForOtherModels(EMBEDDING_VERSION);
145
+ if (removed > 0) {
146
+ debug.log('memory', `Dropped ${removed} vector(s) from a previous embedding artifact`);
147
+ }
148
+ vectorCache.reset();
149
+ await drain();
150
+ }
@@ -0,0 +1,134 @@
1
+ /**
2
+ * Structural invalidation — letting the code tell memory when it has gone out of
3
+ * date.
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.
12
+ *
13
+ * The decay is per subkind, and that distinction is the whole design:
14
+ *
15
+ * observation — "the stream manager captures the snapshot in its finally
16
+ * block". A statement ABOUT the code, invalidated by the code
17
+ * changing. Decays hard.
18
+ * failure — "restoring a snapshot mid-stream corrupts the tree". Usually
19
+ * fixed by the very change that touched the file, so it decays,
20
+ * but less: a fixed bug is still worth knowing about.
21
+ * pattern — a convention. Survives an individual file being edited, but a
22
+ * sustained rewrite is evidence it may no longer hold.
23
+ * decision — "we chose SQLite over Postgres because…". The REASON the change
24
+ * happened. A rewrite is not evidence against it; frequently it
25
+ * is the decision being carried out. Does not decay.
26
+ * preference — belongs to the user, not the file. Does not decay.
27
+ * entity — belongs to the world. Does not decay.
28
+ *
29
+ * Applying one rate to all six would be strictly worse than doing nothing: it
30
+ * would either leave stale observations at full confidence or quietly destroy
31
+ * the decisions that are the most valuable thing in the store.
32
+ *
33
+ * Nothing is deleted here. Confidence falls and `stale_at` is set, so a memory
34
+ * drops below the injection floor and out of the top of rankings while staying
35
+ * fully readable, restorable and visible in the graph view.
36
+ *
37
+ * And the decay does not COMPOUND: `markStale` refuses to touch a memory it
38
+ * already marked within the last few hours. One code change is one piece of
39
+ * evidence however many times the file is saved, and without that guard an
40
+ * ordinary afternoon of iterating on a single file multiplies every observation
41
+ * about it by 0.82 ten times over — 0.14, well under the injection floor. The
42
+ * mechanism meant to keep stale memories honest would instead have deleted, in
43
+ * effect, everything the graph knew about whatever was being worked on.
44
+ */
45
+
46
+ import { graphQueries } from '$backend/database/queries/graph-queries';
47
+ import { debug } from '$shared/utils/logger';
48
+
49
+ /**
50
+ * Confidence multiplier per subkind when the code a memory is `about` changes.
51
+ * A subkind absent from this map, or mapped to 1, is never decayed.
52
+ */
53
+ const DECAY_BY_SUBKIND: Record<string, number> = {
54
+ observation: 0.82,
55
+ failure: 0.92,
56
+ pattern: 0.97,
57
+ decision: 1,
58
+ preference: 1,
59
+ entity: 1
60
+ };
61
+
62
+ /** Files examined per turn. Beyond this the turn was a bulk operation. */
63
+ const MAX_FILES = 60;
64
+
65
+ export interface InvalidationInput {
66
+ projectId: string;
67
+ /** Repo-relative paths that changed on disk this turn. */
68
+ changedPaths: string[];
69
+ /** Paths that no longer exist — the file was deleted or renamed away. */
70
+ deletedPaths?: string[];
71
+ }
72
+
73
+ export interface InvalidationResult {
74
+ /** Memories whose confidence was reduced. */
75
+ decayed: number;
76
+ /** Structural nodes retired because their file is gone. */
77
+ archived: number;
78
+ }
79
+
80
+ /**
81
+ * Age the memories attached to code that just changed.
82
+ *
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
+ * Never throws: a memory left slightly over-confident is a far smaller problem
92
+ * than a failed turn-completion hook.
93
+ */
94
+ export function invalidateForChanges(input: InvalidationInput): InvalidationResult {
95
+ const result: InvalidationResult = { decayed: 0, archived: 0 };
96
+
97
+ 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));
119
+
120
+ if (affected.length === 0) return result;
121
+ result.decayed = graphQueries.markStale(affected, DECAY_BY_SUBKIND);
122
+
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
+ );
128
+ }
129
+ } catch (error) {
130
+ debug.warn('memory', 'Structural invalidation failed (non-fatal)', error);
131
+ }
132
+
133
+ return result;
134
+ }