@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,285 @@
1
+ /**
2
+ * The two judgements the graph makes about itself on a timer, both of which used
3
+ * to be made by a cosine threshold and neither of which a similarity score can
4
+ * answer.
5
+ *
6
+ * 1. **Are these two memories the same claim?** Measured against the shipped
7
+ * artifact on labelled pairs: same-claim pairs score 0.63–0.77, opposite
8
+ * pairs 0.70–0.99, unrelated-but-similar pairs up to 0.92. Every genuine
9
+ * duplicate scores below the median opposite, because a mean-pooled static
10
+ * embedding has no representation for negation — "prefers to use the agent
11
+ * tool" against "prefers NOT to use the agent tool" scores 0.9938. The same
12
+ * pairs put to a model: 11 of 12 correct on the harder three-way question,
13
+ * against 6 of 12 for cosine on the easier two-way one.
14
+ *
15
+ * 2. **Would this memory help someone on a different project?** Nothing tried
16
+ * to answer this before; `project_id` was doing double duty as provenance
17
+ * and as a fence, so a Svelte reactivity gotcha debugged in one repository
18
+ * was invisible in every other. Measured: a model answers it correctly 15
19
+ * times in 16, with zero errors in the damaging direction (a codebase fact
20
+ * wrongly released to travel).
21
+ *
22
+ * Both run on the maintenance timer, never on a path anyone waits on, using the
23
+ * same configured model as extraction. Both are bounded per pass. Both fail
24
+ * closed: a model that cannot be reached leaves the graph exactly as it was.
25
+ */
26
+
27
+ import { initializeEngine } from '$backend/engine';
28
+ import { resolveGenerationTarget } from '$backend/engine/resolve-model';
29
+ import { getDatabase } from '$backend/database';
30
+ import { graphQueries } from '$backend/database/queries/graph-queries';
31
+ import { debug } from '$shared/utils/logger';
32
+ import { existsSync, mkdirSync } from 'node:fs';
33
+ import { join } from 'node:path';
34
+ import { getClopenDir } from '$backend/utils/paths';
35
+ import { getMemoryConfig, type MemoryModelConfig } from './config';
36
+ import { findDuplicateCandidates, mergeDuplicate } from './revise';
37
+ import { notifyGraphChanged } from './notify';
38
+ import type { GraphNode, GraphReach } from '$shared/types/memory';
39
+
40
+ /** Pairs adjudicated per pass. One model call covers all of them. */
41
+ const MAX_PAIRS_PER_RUN = 12;
42
+
43
+ /** Memories reclassified per pass. */
44
+ const MAX_REACH_PER_RUN = 20;
45
+
46
+ /**
47
+ * The same empty directory extraction uses.
48
+ *
49
+ * Engines implement `generateStructured` by opening a session in the directory
50
+ * they are given, so pointing it at a repository puts that repository's
51
+ * instruction files in the model's context. For extraction that produced
52
+ * memories about a codebase nobody had mentioned; for a judgement it would bias
53
+ * the answer toward whatever the open project happens to use.
54
+ */
55
+ function workdir(): string {
56
+ const dir = join(getClopenDir(), 'memory', 'extract');
57
+ if (!existsSync(dir)) mkdirSync(dir, { recursive: true });
58
+ return dir;
59
+ }
60
+
61
+ async function generate<T>(model: MemoryModelConfig, prompt: string, schema: Record<string, unknown>): Promise<T | null> {
62
+ try {
63
+ const engine = await initializeEngine(model.engine);
64
+ if (!engine.generateStructured) return null;
65
+ const target = await resolveGenerationTarget(engine, model.modelId, model.providerSlug);
66
+ const accountId = model.accountId ?? target.accountId;
67
+ return await engine.generateStructured<T>({
68
+ prompt,
69
+ providerSlug: target.providerSlug,
70
+ modelId: target.modelId,
71
+ schema,
72
+ projectPath: workdir(),
73
+ ...(accountId != null && { accountId })
74
+ });
75
+ } catch (error) {
76
+ debug.warn('memory', 'Memory judgement call failed', error);
77
+ return null;
78
+ }
79
+ }
80
+
81
+ // ─────────────────────────────────────────────────────────────────────────────
82
+ // 1. Duplicates
83
+ // ─────────────────────────────────────────────────────────────────────────────
84
+
85
+ const RELATION_SCHEMA = {
86
+ type: 'object',
87
+ additionalProperties: false,
88
+ properties: {
89
+ verdicts: {
90
+ type: 'array',
91
+ items: {
92
+ type: 'object',
93
+ additionalProperties: false,
94
+ properties: {
95
+ index: { type: 'number' },
96
+ relation: {
97
+ type: 'string',
98
+ enum: ['same', 'opposite', 'different'],
99
+ description:
100
+ 'same = B asserts what A asserts, in other words; storing both is redundant. opposite = B cannot be true at the same time as A. different = about something else or a different aspect; both can be true and both are worth keeping.'
101
+ }
102
+ },
103
+ required: ['index', 'relation']
104
+ }
105
+ }
106
+ },
107
+ required: ['verdicts']
108
+ };
109
+
110
+ /**
111
+ * Collapse the pairs a model agrees are one claim, and record the ones it says
112
+ * disagree.
113
+ *
114
+ * This is the pass that decides whether the graph is still usable after six
115
+ * months. Without it, a model rephrases the same fact every time it sees it and
116
+ * the store grows linearly with the number of turns — measured on the real
117
+ * graph, five separate copies of "Arga is a full-stack developer" were taking
118
+ * five of the nine slots the injected block had to spend.
119
+ *
120
+ * A pair the model calls `opposite` is NOT merged. It gets a `contradicts` edge
121
+ * and both stay live; which one is current is decided on the read path, every
122
+ * turn, from authority and recency rather than from a similarity score.
123
+ */
124
+ export async function collapseDuplicates(): Promise<number> {
125
+ const config = getMemoryConfig();
126
+ if (!config.enabled || !config.model) return 0;
127
+
128
+ const pairs = findDuplicateCandidates(200).slice(0, MAX_PAIRS_PER_RUN);
129
+ if (pairs.length === 0) return 0;
130
+
131
+ const listing = pairs
132
+ .map((pair, index) => `${index}.\n A: ${describe(pair.a)}\n B: ${describe(pair.b)}`)
133
+ .join('\n');
134
+
135
+ const result = await generate<{ verdicts?: { index: number; relation: string }[] }>(
136
+ config.model,
137
+ `For each numbered pair of memories, say how B relates to A.
138
+
139
+ Judge the CLAIM, not the wording. Two sentences that share most of their words can still be opposite — "prefers to use X" and "prefers not to use X" differ by one word and cannot both hold. Two that share no words can still be the same claim.
140
+
141
+ When unsure, answer "different". Merging two memories that were actually different destroys one of them; keeping two that say the same thing costs a line.
142
+
143
+ ${listing}
144
+
145
+ Return one verdict per index.`,
146
+ RELATION_SCHEMA
147
+ );
148
+
149
+ let merged = 0;
150
+ let conflicts = 0;
151
+ for (const verdict of result?.verdicts ?? []) {
152
+ const pair = pairs[verdict.index];
153
+ if (!pair) continue;
154
+
155
+ if (verdict.relation === 'same') {
156
+ // The winner is the one with the better claim to being current: authority
157
+ // first, then recency. `mergeDuplicate` goes through `supersede`, whose
158
+ // guards refuse a merge that would retire a person's memory behind a
159
+ // model's — in which case the pair simply stays as two.
160
+ const [winner, loser] = order(pair.a, pair.b);
161
+ if (mergeDuplicate(winner.id, loser.id)) merged++;
162
+ } else if (verdict.relation === 'opposite') {
163
+ const [newer, older] = order(pair.a, pair.b);
164
+ if (graphQueries.contradict(newer.id, older.id)) conflicts++;
165
+ }
166
+ }
167
+
168
+ if (merged > 0 || conflicts > 0) {
169
+ debug.log('memory', `Duplicate pass: ${merged} merged, ${conflicts} contradiction(s) recorded`);
170
+ notifyGraphChanged('edited', null);
171
+ }
172
+ return merged;
173
+ }
174
+
175
+ function describe(node: GraphNode): string {
176
+ const body = node.body.trim().split('\n')[0];
177
+ return body ? `${node.label} — ${body.slice(0, 160)}` : node.label;
178
+ }
179
+
180
+ /** Which of two memories should survive a merge, strongest first. */
181
+ function order(a: GraphNode, b: GraphNode): [GraphNode, GraphNode] {
182
+ if (a.source !== b.source) return a.source === 'user' ? [a, b] : [b, a];
183
+ if (a.assertedBy !== b.assertedBy && (a.assertedBy === 'user' || b.assertedBy === 'user')) {
184
+ return a.assertedBy === 'user' ? [a, b] : [b, a];
185
+ }
186
+ return Date.parse(`${a.updatedAt}Z`) >= Date.parse(`${b.updatedAt}Z`) ? [a, b] : [b, a];
187
+ }
188
+
189
+ // ─────────────────────────────────────────────────────────────────────────────
190
+ // 2. Reach
191
+ // ─────────────────────────────────────────────────────────────────────────────
192
+
193
+ const REACH_SCHEMA = {
194
+ type: 'object',
195
+ additionalProperties: false,
196
+ properties: {
197
+ verdicts: {
198
+ type: 'array',
199
+ items: {
200
+ type: 'object',
201
+ additionalProperties: false,
202
+ properties: {
203
+ index: { type: 'number' },
204
+ reach: { type: 'string', enum: ['here', 'anywhere'] }
205
+ },
206
+ required: ['index', 'reach']
207
+ }
208
+ }
209
+ },
210
+ required: ['verdicts']
211
+ };
212
+
213
+ /**
214
+ * Decide which existing memories describe a technology rather than a codebase,
215
+ * so they can travel.
216
+ *
217
+ * `reach` defaults to `here` on purpose: a memory wrongly kept local is invisible
218
+ * until this pass reaches it, while one wrongly released appears in every project
219
+ * immediately, and only the first is recoverable by waiting. This is what walks
220
+ * that back, a batch at a time, for memories an extraction failed to classify.
221
+ */
222
+ export async function reclassifyReach(): Promise<number> {
223
+ const config = getMemoryConfig();
224
+ if (!config.enabled || !config.model) return 0;
225
+
226
+ const rows = getDatabase()
227
+ .prepare(
228
+ `SELECT id FROM graph_nodes
229
+ WHERE kind = 'episodic' AND reach_judged = 0
230
+ AND archived_at IS NULL AND superseded_by IS NULL
231
+ AND subkind <> 'entity'
232
+ ORDER BY weight DESC, updated_at DESC
233
+ LIMIT ?`
234
+ )
235
+ .all(MAX_REACH_PER_RUN) as { id: string }[];
236
+ if (rows.length === 0) return 0;
237
+
238
+ const nodes = graphQueries.getByIds(rows.map(row => row.id));
239
+ if (nodes.length === 0) return 0;
240
+
241
+ const listing = nodes.map((node, index) => `${index}. ${describe(node)}`).join('\n');
242
+
243
+ const result = await generate<{ verdicts?: { index: number; reach: string }[] }>(
244
+ config.model,
245
+ `Each line is a note taken while working on one software project. Decide whether the note would still be useful to someone working on a DIFFERENT project.
246
+
247
+ here = the note is about this particular codebase — its choices, its structure, its configuration. Someone on another project cannot act on it.
248
+ anywhere = the note is about a language, framework, runtime, library or general practice. Someone on another project using the same technology would want to know it, even though it was learned here.
249
+
250
+ The test is not whether a project name appears. "Project X deploys to Fly.io" is here, because another project deploys somewhere else. "Bun swallows unhandled rejections" is anywhere, because Bun behaves that way in every project.
251
+
252
+ ${listing}
253
+
254
+ Return one verdict per index.`,
255
+ REACH_SCHEMA
256
+ );
257
+ if (!result?.verdicts?.length) return 0;
258
+
259
+ const db = getDatabase();
260
+ const mark = db.prepare(`UPDATE graph_nodes SET reach = ?, reach_judged = 1 WHERE id = ?`);
261
+ let travelling = 0;
262
+ let judged = 0;
263
+ // One transaction: this is a bulk rewrite of rows the read path filters on, and
264
+ // a half-applied batch would leave the graph disagreeing with itself about
265
+ // which memories are allowed to cross a project boundary.
266
+ const write = (): void => {
267
+ for (const verdict of result.verdicts ?? []) {
268
+ const node = nodes[verdict.index];
269
+ if (!node) continue;
270
+ const reach: GraphReach = verdict.reach === 'anywhere' ? 'anywhere' : 'here';
271
+ mark.run(reach, node.id);
272
+ judged++;
273
+ if (reach === 'anywhere') travelling++;
274
+ }
275
+ };
276
+ // `transaction` is optional on the connection interface, so the batch falls back
277
+ // to plain statements rather than not running at all.
278
+ if (db.transaction) db.transaction(write)();
279
+ else write();
280
+
281
+ if (judged > 0) {
282
+ debug.log('memory', `Reach pass: judged ${judged} memory/memories, ${travelling} of them travel`);
283
+ }
284
+ return judged;
285
+ }
@@ -0,0 +1,132 @@
1
+ /**
2
+ * Background maintenance for the Memory Graph.
3
+ *
4
+ * Three jobs that make the graph better rather than bigger — collapsing
5
+ * duplicates, consolidating clusters into generalisations, and applying the
6
+ * retention policy — none of which anything waits on.
7
+ *
8
+ * Timing is the whole design here. Consolidation calls a model, and it calls it
9
+ * through the SAME engine the user chats with, which is the contention that
10
+ * `extract/scheduler.ts` exists to avoid. So maintenance obeys the same rule and
11
+ * one stricter: it runs only when NO session has an extraction parked or in
12
+ * flight, which is a proxy for "nobody is mid-conversation". A user who works all
13
+ * day simply gets their maintenance overnight, which is when it should happen
14
+ * anyway.
15
+ *
16
+ * The cheap jobs (duplicate collapse, retention) are pure SQL and run on the same
17
+ * tick regardless, because they cost microseconds and cannot compete with
18
+ * anything.
19
+ */
20
+
21
+ import { projectQueries } from '$backend/database/queries/project-queries';
22
+ import { debug } from '$shared/utils/logger';
23
+ import { getMemoryConfig } from './config';
24
+ import { consolidateMemories } from './consolidate';
25
+ import { hasPendingExtraction } from './extract/scheduler';
26
+ import { collapseDuplicates, reclassifyReach } from './judge';
27
+ import { applyRetention } from './retention';
28
+
29
+ /**
30
+ * How often maintenance considers running. Not how often it runs — most ticks
31
+ * find a busy instance, or nothing to do, and return immediately.
32
+ */
33
+ const TICK_MS = 30 * 60_000;
34
+
35
+ /** Delay before the first tick, so it never lands during startup. */
36
+ const FIRST_TICK_MS = 5 * 60_000;
37
+
38
+ /**
39
+ * Minimum gap between two consolidation passes.
40
+ *
41
+ * Consolidation costs a model call per cluster and its input barely changes
42
+ * within a day, so running it every tick would spend tokens re-examining
43
+ * clusters it already declined to summarise.
44
+ */
45
+ const CONSOLIDATE_EVERY_MS = 12 * 60 * 60_000;
46
+
47
+ let timer: ReturnType<typeof setInterval> | null = null;
48
+ let running = false;
49
+ let lastConsolidation = 0;
50
+
51
+ /** Start the maintenance loop. Idempotent. */
52
+ export function startMemoryMaintenance(): void {
53
+ if (timer) return;
54
+ // `unref` so a pending tick never holds the process open on shutdown — this is
55
+ // housekeeping, and nothing here is worth delaying an exit for.
56
+ timer = setInterval(() => void tick(), TICK_MS);
57
+ timer.unref?.();
58
+
59
+ const first = setTimeout(() => void tick(), FIRST_TICK_MS);
60
+ first.unref?.();
61
+ }
62
+
63
+ export function stopMemoryMaintenance(): void {
64
+ if (!timer) return;
65
+ clearInterval(timer);
66
+ timer = null;
67
+ }
68
+
69
+ /**
70
+ * Run one maintenance pass now, regardless of the schedule. Used by tests and
71
+ * available for a future manual "tidy memory" action in Settings.
72
+ */
73
+ export async function runMaintenanceNow(options?: { consolidate?: boolean }): Promise<void> {
74
+ await pass(options?.consolidate ?? true);
75
+ }
76
+
77
+ async function tick(): Promise<void> {
78
+ if (running) return;
79
+ const config = getMemoryConfig();
80
+ if (!config.enabled) return;
81
+
82
+ // Somebody is mid-conversation. Consolidation would queue a model call against
83
+ // their next message on a shared-process engine, and the cheap jobs can just as
84
+ // well wait thirty minutes.
85
+ if (hasPendingExtraction()) return;
86
+
87
+ running = true;
88
+ try {
89
+ const consolidate = Date.now() - lastConsolidation >= CONSOLIDATE_EVERY_MS;
90
+ await pass(consolidate);
91
+ if (consolidate) lastConsolidation = Date.now();
92
+ } finally {
93
+ running = false;
94
+ }
95
+ }
96
+
97
+ async function pass(consolidate: boolean): Promise<void> {
98
+ try {
99
+ applyRetention();
100
+
101
+ if (!consolidate) return;
102
+
103
+ // Both of these call a model, so they sit behind the same gate as
104
+ // consolidation rather than running every tick. Duplicates first: collapsing
105
+ // five copies of one fact into one is what frees the recall budget that
106
+ // everything downstream spends, and reclassifying a memory that is about to
107
+ // be merged away would be wasted work.
108
+ if (hasPendingExtraction()) return;
109
+ await collapseDuplicates();
110
+ if (hasPendingExtraction()) return;
111
+ await reclassifyReach();
112
+
113
+ // Global memories first — they are the ones every project sees, so the
114
+ // benefit of tidying them is the widest.
115
+ const projects: { id: string | null; path: string }[] = [
116
+ { id: null, path: process.cwd() },
117
+ ...projectQueries.getAll().map(project => ({ id: project.id as string, path: project.path as string }))
118
+ ];
119
+
120
+ for (const project of projects) {
121
+ // Re-checked between projects: a user coming back mid-pass should not have
122
+ // their first message queued behind the remaining ones.
123
+ if (hasPendingExtraction()) {
124
+ debug.log('memory', 'Maintenance yielded — a session became active');
125
+ return;
126
+ }
127
+ await consolidateMemories(project.id, project.path);
128
+ }
129
+ } catch (error) {
130
+ debug.warn('memory', 'Maintenance pass failed (non-fatal)', error);
131
+ }
132
+ }
@@ -0,0 +1,91 @@
1
+ /**
2
+ * Choosing the model that writes memories, without asking.
3
+ *
4
+ * This used to live in `MemoryModelSettings.svelte`, which defaulted to the
5
+ * assistant model on mount. That works only for a user who OPENS
6
+ * Settings → Model → Memory — and nothing prompts them to. Everyone else ran
7
+ * with `model: null`, so every finished turn was queued, refused for want of a
8
+ * model, and banked forever: memory looked switched on and recorded nothing.
9
+ * A default that depends on a settings page being visited is not a default.
10
+ *
11
+ * So the choice is made here, from the same rule the Assistant page uses
12
+ * (`pickDefaultModel` — the most capable model the engine offers, measured by
13
+ * how many capability badges it carries), and it is made at two moments:
14
+ *
15
+ * - at startup, best-effort, so a fresh install is configured before the user
16
+ * has done anything at all;
17
+ * - immediately before the first extraction, because at startup the catalog
18
+ * may not be loaded yet, while by the time a turn has finished the engine
19
+ * has certainly been asked for its models.
20
+ *
21
+ * It only ever fills a HOLE. An explicit choice is never overwritten, including
22
+ * back to itself — this is a default, not a policy.
23
+ */
24
+
25
+ import { DEFAULT_ENGINE, getModelsByEngine, pickDefaultModel, registerModels } from '$shared/constants/engines';
26
+ import { debug } from '$shared/utils/logger';
27
+ import { getEngine } from '$backend/engine';
28
+ import type { EngineType } from '$shared/types/unified';
29
+ import { getMemoryConfig, setMemoryConfig, type MemoryModelConfig } from './config';
30
+ import { notifyMemoryReadiness } from './notify';
31
+
32
+ /** Shared in-flight promise, so a startup call and a first extraction do not race. */
33
+ let inFlight: Promise<MemoryModelConfig | null> | null = null;
34
+
35
+ /**
36
+ * Return the configured extraction model, choosing a default if none is set.
37
+ *
38
+ * Resolves to null when no catalog is reachable — an engine that has never been
39
+ * authenticated has no models to pick from, and inventing an id would produce a
40
+ * failure at extraction time rather than an honest "not configured yet".
41
+ */
42
+ export function ensureMemoryModel(): Promise<MemoryModelConfig | null> {
43
+ const existing = getMemoryConfig().model;
44
+ if (existing?.modelId) return Promise.resolve(existing);
45
+ if (inFlight) return inFlight;
46
+ inFlight = resolve().finally(() => {
47
+ inFlight = null;
48
+ });
49
+ return inFlight;
50
+ }
51
+
52
+ async function resolve(): Promise<MemoryModelConfig | null> {
53
+ // Re-read: a concurrent caller may have filled it while this one waited.
54
+ const current = getMemoryConfig().model;
55
+ if (current?.modelId) return current;
56
+
57
+ const engineType: EngineType = DEFAULT_ENGINE;
58
+
59
+ // The registry is populated by `models:list`, which the UI calls. Only pay for
60
+ // a catalog fetch when this process has not seen the engine yet — at startup
61
+ // it usually has not.
62
+ let catalog = getModelsByEngine(engineType);
63
+ if (catalog.length === 0) {
64
+ try {
65
+ const engine = await getEngine(engineType);
66
+ catalog = await engine.getAvailableModels();
67
+ registerModels(engineType, catalog);
68
+ } catch (error) {
69
+ debug.warn('memory', `Could not load the ${engineType} catalog to pick a memory model`, error);
70
+ return null;
71
+ }
72
+ }
73
+
74
+ const pick = pickDefaultModel(catalog);
75
+ if (!pick) {
76
+ debug.log('memory', `No ${engineType} model available yet — memory extraction stays unconfigured`);
77
+ return null;
78
+ }
79
+
80
+ const model: MemoryModelConfig = {
81
+ engine: engineType,
82
+ modelId: pick.engine.model.id,
83
+ ...(pick.engine.provider && { providerSlug: pick.engine.provider }),
84
+ ...(pick.engine.account.id && { accountId: pick.engine.account.id })
85
+ };
86
+
87
+ setMemoryConfig({ model });
88
+ notifyMemoryReadiness();
89
+ debug.log('memory', `Memory extraction model defaulted to ${engineType}/${model.modelId}`);
90
+ return model;
91
+ }
@@ -0,0 +1,102 @@
1
+ /**
2
+ * Telling open Memory views that the graph moved.
3
+ *
4
+ * Without this the visualization was a snapshot taken at mount: a conversation
5
+ * could write eight memories while the modal sat open in another tab and none of
6
+ * them appeared until the browser was reloaded. For a feature whose whole premise
7
+ * is "this fills up as you work", that is the wrong default.
8
+ *
9
+ * The broadcast is COALESCED, and that is the load-bearing part. A single turn's
10
+ * ingestion writes a file node, a module node, a `contains` edge and up to
11
+ * twenty-five symbol nodes per file, then episodic extraction adds memories and
12
+ * edges on top — hundreds of mutations within a second or two. Emitting per write
13
+ * would flood every connected client and, worse, make the graph view refetch and
14
+ * re-lay-out repeatedly while the writes were still landing. One event on the
15
+ * trailing edge is what a viewer actually needs.
16
+ *
17
+ * It is a doorbell, not a delivery: the payload carries a reason and nothing
18
+ * else. Diffing the graph over the wire would mean maintaining a second
19
+ * serialization alongside `memory:graph` for a refetch that costs milliseconds.
20
+ */
21
+
22
+ import { ws } from '$backend/utils/ws';
23
+ import { debug } from '$shared/utils/logger';
24
+
25
+ /**
26
+ * Window over which mutations are folded into one notification.
27
+ *
28
+ * Long enough to cover a turn's ingestion burst, short enough that a user
29
+ * watching the graph sees their conversation appear while they still associate it
30
+ * with what they just said.
31
+ */
32
+ const COALESCE_MS = 600;
33
+
34
+ let timer: ReturnType<typeof setTimeout> | null = null;
35
+ let pendingReason = '';
36
+ let pendingProjectId: string | null = null;
37
+ let statusTimer: ReturnType<typeof setTimeout> | null = null;
38
+
39
+ /**
40
+ * Note that the graph changed. Cheap, idempotent, and safe to call from inside a
41
+ * loop — call it after any write rather than trying to work out whether this
42
+ * particular write was interesting.
43
+ */
44
+ export function notifyGraphChanged(reason: string, projectId: string | null = null): void {
45
+ pendingReason = reason;
46
+ pendingProjectId = projectId;
47
+ if (timer) return;
48
+
49
+ timer = setTimeout(() => {
50
+ timer = null;
51
+ try {
52
+ ws.emit.global('memory:changed', { reason: pendingReason, projectId: pendingProjectId });
53
+ } catch (error) {
54
+ // A view that misses a refresh is a stale view, not a broken one, and this
55
+ // is called from write paths that must never fail for a UI concern.
56
+ debug.warn('memory', 'Failed to broadcast memory change', error);
57
+ }
58
+ }, COALESCE_MS);
59
+ // Housekeeping — never a reason to hold the process open at shutdown.
60
+ timer.unref?.();
61
+ }
62
+
63
+ /**
64
+ * Tell open views that the extraction queue moved.
65
+ *
66
+ * Separate from `notifyGraphChanged` because they answer different questions and
67
+ * fire at different moments: the graph changes when a memory is written, the
68
+ * queue changes when one is enqueued, retried, or gives up — including the case
69
+ * where nothing was written at all, which is exactly when the user most needs to
70
+ * be told something is happening.
71
+ *
72
+ * Coalesced on a shorter window than the graph, because the counts are small and
73
+ * a status that lags behind the thing it describes is worse than no status.
74
+ */
75
+ export function notifyMemoryStatus(): void {
76
+ if (statusTimer) return;
77
+ statusTimer = setTimeout(() => {
78
+ statusTimer = null;
79
+ try {
80
+ ws.emit.global('memory:status-changed', {});
81
+ } catch (error) {
82
+ debug.warn('memory', 'Failed to broadcast memory status', error);
83
+ }
84
+ }, 200);
85
+ statusTimer.unref?.();
86
+ }
87
+
88
+ /**
89
+ * Tell open views that setup progressed — the artifact started downloading,
90
+ * landed, failed, or a model was chosen.
91
+ *
92
+ * Uncoalesced, unlike the two above. These transitions are rare (a handful over
93
+ * the life of an install) and each one changes what the banner says, so delaying
94
+ * them buys nothing and makes a progress bar lag behind the download it tracks.
95
+ */
96
+ export function notifyMemoryReadiness(): void {
97
+ try {
98
+ ws.emit.global('memory:readiness-changed', {});
99
+ } catch (error) {
100
+ debug.warn('memory', 'Failed to broadcast memory readiness', error);
101
+ }
102
+ }
@@ -0,0 +1,74 @@
1
+ /**
2
+ * Whether memory is actually usable, and what is missing when it is not.
3
+ *
4
+ * Memory has two halves with DIFFERENT prerequisites, and collapsing them into
5
+ * one "enabled" flag is what made the feature feel broken during setup:
6
+ *
7
+ * RECALL needs the embedding artifact. Retrieval fuses BM25 with vector
8
+ * similarity, and lexical alone cannot match a question phrased differently
9
+ * from the memory holding the answer — an Indonesian question against an
10
+ * English memory shares no terms, so BM25 returns nothing. Half a retriever is
11
+ * not a degraded retriever, it is a retriever that silently misses.
12
+ *
13
+ * RECORDING needs a model. It does NOT need the artifact: the indexer
14
+ * backfills vectors whenever the artifact arrives, so a memory written today
15
+ * becomes searchable the moment setup finishes.
16
+ *
17
+ * Recording is deliberately NOT gated on recall being ready. The turns a user has
18
+ * while a 44 MB download runs are usually the ones that establish a project, and
19
+ * throwing them away to keep a boolean tidy is the worse failure — they are
20
+ * exactly the memories that would have been worth keeping.
21
+ *
22
+ * `setupRequired` is what the banner reads. It stays true until BOTH halves work,
23
+ * because a user whose memory records but never recalls has a feature that
24
+ * appears to do nothing at all.
25
+ */
26
+
27
+ import { getMemoryConfig } from './config';
28
+ import { embedder, getEmbeddingInstallStatus, type EmbeddingInstallStatus } from './embedding';
29
+
30
+ export interface MemoryReadiness {
31
+ /** Master switch from Settings → Infrastructure → Memory. */
32
+ enabled: boolean;
33
+ /** Retrieval, automatic injection and the MCP `recall` action. */
34
+ canRecall: boolean;
35
+ /** Episodic extraction from finished turns. */
36
+ canRecord: boolean;
37
+ /** True while anything still needs doing, and what the banner keys on. */
38
+ setupRequired: boolean;
39
+ /** Ordered list of what is missing, most actionable first. */
40
+ blockers: MemoryBlocker[];
41
+ embedding: EmbeddingInstallStatus & { ready: boolean };
42
+ model: { configured: boolean; engine: string | null; modelId: string | null };
43
+ }
44
+
45
+ export type MemoryBlocker = 'embedding' | 'model';
46
+
47
+ export function getMemoryReadiness(): MemoryReadiness {
48
+ const config = getMemoryConfig();
49
+ const install = getEmbeddingInstallStatus();
50
+ const embeddingReady = embedder.status().ready;
51
+ const modelConfigured = Boolean(config.model?.modelId);
52
+
53
+ const blockers: MemoryBlocker[] = [];
54
+ // The artifact comes first: it is the one the user cannot fix by choosing
55
+ // something, so it is the one worth surfacing while it is still downloading.
56
+ if (!embeddingReady) blockers.push('embedding');
57
+ if (!modelConfigured) blockers.push('model');
58
+
59
+ return {
60
+ enabled: config.enabled,
61
+ canRecall: config.enabled && embeddingReady,
62
+ canRecord: config.enabled && modelConfigured,
63
+ // Nothing to set up when the whole feature is switched off — a banner
64
+ // nagging about a feature the user deliberately disabled is just noise.
65
+ setupRequired: config.enabled && blockers.length > 0,
66
+ blockers,
67
+ embedding: { ...install, ready: embeddingReady },
68
+ model: {
69
+ configured: modelConfigured,
70
+ engine: config.model?.engine ?? null,
71
+ modelId: config.model?.modelId ?? null
72
+ }
73
+ };
74
+ }