@myrialabs/clopen 0.4.25 → 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 (96) 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/content.ts +85 -0
  82. package/backend/ws/snapshot/index.ts +4 -1
  83. package/backend/ws/snapshot/restore.ts +38 -4
  84. package/dist/assets/graph-layout.worker-CRFqN7ZQ.js +1 -0
  85. package/dist/assets/{index-KBGloYDk.js → index-BCv5HlPk.js} +1 -1
  86. package/dist/assets/{index-C4PD7B-x.js → index-BTGcf_Vy.js} +1 -1
  87. package/dist/assets/main-BrqMMMRX.css +1 -0
  88. package/dist/assets/main-CgmAFpU3.js +1036 -0
  89. package/dist/index.html +2 -2
  90. package/package.json +8 -2
  91. package/shared/types/database/connection.ts +9 -0
  92. package/shared/types/memory.ts +519 -0
  93. package/shared/utils/logger.ts +1 -0
  94. package/dist/assets/main-B0AA-88X.js +0 -622
  95. package/dist/assets/main-OsjA5Ab5.css +0 -1
  96. package/shared/utils/anonymous-user.ts +0 -168
@@ -0,0 +1,725 @@
1
+ /**
2
+ * Episodic extraction — turning a finished turn into durable memory.
3
+ *
4
+ * This is the one part of the Memory Graph that calls a model, and it is placed
5
+ * where that cost is invisible: after the turn has finished streaming, off the
6
+ * render path, with nothing waiting on the result. A slow extraction delays only
7
+ * when a memory becomes searchable, never when the user sees their answer.
8
+ *
9
+ * Because it is the only model call in the system, it does THREE jobs rather than
10
+ * one, all from the same transcript and the same request:
11
+ *
12
+ * 1. **Extract** what the turn established that is worth keeping.
13
+ * 2. **Revise** — decide whether each new memory replaces something the graph
14
+ * already holds, or merely restates it. This needs a reader of the turn;
15
+ * cosine can tell that two memories are about the same thing but not which
16
+ * of them is currently true.
17
+ * 3. **Adjudicate** the memories that were injected INTO this turn: which
18
+ * actually helped, which were wrong. That is the only evidence in the whole
19
+ * system about whether a memory is any good, and it exists for free here
20
+ * because the turn that consumed them is exactly what is being read.
21
+ *
22
+ * What it looks at is the transcript of the turn plus which files changed on
23
+ * disk. Reading the transcript rather than only the diff is the point — a diff
24
+ * shows what changed, but the reason it changed, the approach that failed first,
25
+ * and the preference the user stated along the way exist only in the
26
+ * conversation.
27
+ *
28
+ * Everything is written in English regardless of the chat's language. That keeps
29
+ * the corpus in one language so embeddings compare cleanly and the same claim
30
+ * made in two languages de-duplicates instead of becoming two nodes. The
31
+ * repository already requires English for durable text, so this follows suit.
32
+ */
33
+
34
+ import { existsSync, mkdirSync } from 'node:fs';
35
+ import { join } from 'node:path';
36
+ import { messageQueries } from '$backend/database/queries/message-queries';
37
+ import { graphQueries } from '$backend/database/queries/graph-queries';
38
+ import { initializeEngine } from '$backend/engine';
39
+ import { resolveGenerationTarget } from '$backend/engine/resolve-model';
40
+ import { getClopenDir } from '$backend/utils/paths';
41
+ import { debug } from '$shared/utils/logger';
42
+ import type {
43
+ EpisodicSubkind,
44
+ GraphAssertedBy,
45
+ GraphNode,
46
+ GraphReach,
47
+ GraphScope,
48
+ MemoryVerdict
49
+ } from '$shared/types/memory';
50
+ import type { UnifiedMessage } from '$shared/types/unified';
51
+ import { embedder } from '../embedding';
52
+ import { getMemoryConfig, type MemoryModelConfig } from '../config';
53
+ import { ensureMemoryModel } from '../model';
54
+ import { redactSecrets } from '../redact';
55
+ import {
56
+ applyFeedback,
57
+ findRelatedCandidates,
58
+ gatherRelatedMemories,
59
+ linkEntities,
60
+ recordContradictions,
61
+ renderRelatedMemories
62
+ } from '../revise';
63
+
64
+ /** Transcript characters handed to the model. Enough for a turn, bounded for cost. */
65
+ const MAX_TRANSCRIPT_CHARS = 24_000;
66
+
67
+ /**
68
+ * Memories accepted from one turn.
69
+ *
70
+ * Lowered from eight, because eight was being reached by splitting one fact
71
+ * rather than by finding eight. A single "what is this project?" turn produced
72
+ * five separate observations — payments, referrals, OTP auth, localisation —
73
+ * that were one answer about one repository, and every one of them competes for
74
+ * the same recall slot on every future turn. The prompt asks for fewer and
75
+ * larger; this is the backstop.
76
+ */
77
+ const MAX_MEMORIES_PER_TURN = 5;
78
+
79
+ /**
80
+ * Cosine at which two memories from the SAME response are treated as one.
81
+ *
82
+ * Deliberately high, and deliberately scoped to a single response. See the call
83
+ * site for why the objection that removed this threshold everywhere else — that
84
+ * cosine scores a claim and its negation higher than a claim and its own
85
+ * restatement — does not apply within one model answer describing one turn.
86
+ */
87
+ const SELF_DUPLICATE = 0.85;
88
+
89
+ /**
90
+ * How long one extraction may take before it is abandoned.
91
+ *
92
+ * Generous, because a slow local model summarising a long turn is normal and
93
+ * nobody is waiting on the answer. Finite, because this is the only write path in
94
+ * the feature and it sits inside a drain loop that processes one entry at a time
95
+ * — so a call that never returns does not merely lose its own turn, it stops
96
+ * recording entirely and holds maintenance down with it.
97
+ */
98
+ const EXTRACTION_TIMEOUT_MS = 4 * 60_000;
99
+
100
+ /**
101
+ * Strict JSON Schema, shaped for the lowest common denominator across engines:
102
+ * OpenAI's strict structured-output mode requires `additionalProperties: false`,
103
+ * every property listed in `required`, and optionality expressed as a nullable
104
+ * union rather than an absent key. Claude/OpenCode/Copilot/Qwen all accept it —
105
+ * same reasoning as `COMMIT_MESSAGE_SCHEMA` in backend/ws/git/commit-message.ts.
106
+ */
107
+ const MEMORY_SCHEMA = {
108
+ type: 'object',
109
+ additionalProperties: false,
110
+ properties: {
111
+ memories: {
112
+ type: 'array',
113
+ description:
114
+ 'Every durable fact the turn stated, whatever its subject, each written in English. Empty only when the turn stated no fact at all.',
115
+ items: {
116
+ type: 'object',
117
+ additionalProperties: false,
118
+ properties: {
119
+ subkind: {
120
+ type: 'string',
121
+ enum: ['decision', 'pattern', 'failure', 'preference', 'observation', 'entity'],
122
+ description:
123
+ 'entity = who someone is (name, role, expertise); preference = how the user wants things done; decision = a choice made and its reason; pattern = a convention that holds; failure = something that broke and why; observation = a durable fact about the system'
124
+ },
125
+ scope: {
126
+ type: 'string',
127
+ enum: ['session', 'project', 'global'],
128
+ description:
129
+ 'How LONG this holds. session = an instruction for the task at hand only, which does not change any standing rule — "for this analysis, use X" is session even when it goes against a standing rule, because it is an exception being taken, not the rule being repealed. project = a standing claim about this codebase. global = a standing claim about how the user works everywhere.'
130
+ },
131
+ reach: {
132
+ type: 'string',
133
+ enum: ['here', 'anywhere'],
134
+ description:
135
+ 'WHERE this is useful, which is a different question from where it was learned. here = about this particular codebase, its choices, its layout, its configuration; someone on another project cannot act on it. anywhere = about a language, framework, runtime, library or general practice, and someone on a different project would want to know it. The test is not whether a project name appears: "Project X deploys to Fly.io" is here because another project deploys elsewhere, while "Bun swallows unhandled rejections" is anywhere because Bun behaves that way in every project.'
136
+ },
137
+ assertedBy: {
138
+ type: 'string',
139
+ enum: ['user', 'assistant', 'inferred'],
140
+ description:
141
+ 'Whose claim this is. user = the user said it in the transcript. assistant = the assistant asserted it. inferred = nobody said it outright and you concluded it from what you read. Judge only from the transcript; do not mark something as the user\'s unless they actually said it.'
142
+ },
143
+ label: {
144
+ type: 'string',
145
+ description:
146
+ 'MUST BE WRITTEN IN ENGLISH, whatever language the conversation used. One sentence stating the memory, with its subject named, specific enough to be useful out of context. Max 140 characters.'
147
+ },
148
+ body: {
149
+ type: 'string',
150
+ description:
151
+ 'MUST BE WRITTEN IN ENGLISH, whatever language the conversation used. The reasoning: why this is true, what it rules out, what breaks without it. Two or three sentences.'
152
+ },
153
+ confidence: {
154
+ type: 'number',
155
+ description: '0.4 when inferred, 0.7 when clearly implied, 0.95 when stated outright by the user.'
156
+ },
157
+ relatedPaths: {
158
+ type: 'array',
159
+ description:
160
+ 'Repo-relative paths this memory is about. Only paths that appear in the turn. Empty when none apply.',
161
+ items: { type: 'string' }
162
+ },
163
+ entities: {
164
+ type: 'array',
165
+ description:
166
+ 'People, tools, companies or systems this memory is ABOUT, by name — "Arga", "Bun", "Cloudflare". Names only, no description. Empty when the memory is about no particular named thing.',
167
+ items: { type: 'string' }
168
+ },
169
+ relations: {
170
+ type: 'array',
171
+ description:
172
+ 'How this memory relates to each of the NEIGHBOURS listed under it. Judge the CLAIM, not the wording: two sentences sharing most of their words can still be opposite, and two sharing none can still be the same claim. Include an entry only for neighbours that are "same" or "opposite"; leave the rest out.',
173
+ items: {
174
+ type: 'object',
175
+ additionalProperties: false,
176
+ properties: {
177
+ id: { type: 'string', description: 'Id of the neighbour, exactly as listed.' },
178
+ relation: {
179
+ type: 'string',
180
+ enum: ['same', 'opposite', 'different'],
181
+ description:
182
+ 'same = asserts the same thing in different words, so storing both would be redundant. opposite = cannot be true at the same time as this memory. different = about something else, or a different aspect; both can be true and both are worth keeping.'
183
+ }
184
+ },
185
+ required: ['id', 'relation']
186
+ }
187
+ }
188
+ },
189
+ required: [
190
+ 'subkind',
191
+ 'scope',
192
+ 'reach',
193
+ 'assertedBy',
194
+ 'label',
195
+ 'body',
196
+ 'confidence',
197
+ 'relatedPaths',
198
+ 'entities',
199
+ 'relations'
200
+ ]
201
+ }
202
+ },
203
+ feedback: {
204
+ type: 'array',
205
+ description:
206
+ 'A verdict for each memory listed under MEMORIES GIVEN TO THIS TURN. Judge only from the transcript: did the assistant actually act on it, or did the turn show it to be wrong?',
207
+ items: {
208
+ type: 'object',
209
+ additionalProperties: false,
210
+ properties: {
211
+ id: { type: 'string', description: 'Id from MEMORIES GIVEN TO THIS TURN.' },
212
+ verdict: {
213
+ type: 'string',
214
+ enum: ['used', 'wrong', 'ignored'],
215
+ description:
216
+ 'used = the turn relied on it or it was clearly correct; wrong = the turn contradicted it or it caused a mistake; ignored = it simply had no bearing on this turn (the common case, and not a criticism)'
217
+ }
218
+ },
219
+ required: ['id', 'verdict']
220
+ }
221
+ }
222
+ },
223
+ required: ['memories', 'feedback']
224
+ };
225
+
226
+ interface ExtractedMemory {
227
+ subkind: EpisodicSubkind;
228
+ scope: GraphScope;
229
+ reach: GraphReach;
230
+ assertedBy: GraphAssertedBy;
231
+ label: string;
232
+ body: string;
233
+ confidence: number;
234
+ relatedPaths: string[];
235
+ entities: string[];
236
+ relations: { id: string; relation: 'same' | 'opposite' | 'different' }[];
237
+ }
238
+
239
+ interface ExtractionResponse {
240
+ memories?: ExtractedMemory[];
241
+ feedback?: { id: string; verdict: MemoryVerdict }[];
242
+ }
243
+
244
+ export interface EpisodicIngestInput {
245
+ projectId: string;
246
+ projectPath: string;
247
+ sessionId: string;
248
+ /** The user message that opened the OLDEST turn not yet extracted. */
249
+ userMessageId: string;
250
+ /** Repo-relative paths that changed on disk this turn. */
251
+ changedPaths: string[];
252
+ /** Repo-relative paths that no longer exist on disk. */
253
+ deletedPaths?: string[];
254
+ /** Path → structural node id, from structural extraction, for `about` edges. */
255
+ fileNodes: Map<string, string>;
256
+ /** Memories that were injected into this turn, for adjudication. */
257
+ injectedMemoryIds?: string[];
258
+ }
259
+
260
+ /** Plain text of a message's content blocks. */
261
+ function messageText(message: UnifiedMessage): string {
262
+ if (message.type === 'compact_boundary') return '';
263
+
264
+ // Reasoning is INCLUDED, and it is some of the highest-value text in the
265
+ // transcript. The final answer states a conclusion; the reasoning states why
266
+ // one approach was chosen over another, which is precisely what a `decision`
267
+ // memory is and what cannot be recovered by reading the diff afterwards. It is
268
+ // truncated because reasoning blocks can be very long and most of the length is
269
+ // exploration that led nowhere.
270
+ if (message.type === 'reasoning') {
271
+ const text = (message as { content?: unknown }).content;
272
+ if (typeof text === 'string') return text.slice(0, 2_000);
273
+ if (!Array.isArray(text)) return '';
274
+ return (text as Record<string, unknown>[])
275
+ .filter(block => typeof block.text === 'string')
276
+ .map(block => block.text as string)
277
+ .join('\n')
278
+ .slice(0, 2_000);
279
+ }
280
+
281
+ const content = (message as { content?: unknown }).content;
282
+ if (!Array.isArray(content)) return '';
283
+
284
+ const parts: string[] = [];
285
+ for (const block of content as Record<string, unknown>[]) {
286
+ if (block.type === 'text' && typeof block.text === 'string') {
287
+ parts.push(block.text);
288
+ } else if (block.type === 'tool_use' && typeof block.name === 'string') {
289
+ // Tool NAMES are useful context ("it ran the tests"), but arguments are
290
+ // mostly file contents and would swamp the transcript budget.
291
+ parts.push(`[tool: ${block.name}]`);
292
+ } else if (block.type === 'tool_result') {
293
+ // Failures are the highest-signal thing in a transcript — they are what
294
+ // becomes a `failure` memory that stops the mistake being repeated.
295
+ const isError = block.isError === true || block.is_error === true;
296
+ if (isError) {
297
+ const text = typeof block.content === 'string' ? block.content : JSON.stringify(block.content ?? '');
298
+ parts.push(`[tool failed: ${text.slice(0, 600)}]`);
299
+ }
300
+ }
301
+ }
302
+ return parts.join('\n').trim();
303
+ }
304
+
305
+ /**
306
+ * Transcript of everything since `userMessageId`, oldest first.
307
+ *
308
+ * Reads the session's visible chain and slices from that user message, so a turn
309
+ * on a forked branch sees its own history rather than an abandoned one — and so a
310
+ * session that stayed busy, and therefore banked several turns behind one parked
311
+ * boundary, has all of them summarised together.
312
+ */
313
+ function buildTranscript(sessionId: string, userMessageId: string): string {
314
+ const chain = messageQueries.getBySessionId(sessionId);
315
+ const startIndex = chain.findIndex(m => m.messageId === userMessageId);
316
+ const turn = startIndex === -1 ? chain.slice(-8) : chain.slice(startIndex);
317
+
318
+ const lines: string[] = [];
319
+ for (const message of turn) {
320
+ const text = messageText(message);
321
+ if (!text) continue;
322
+ const role = message.type === 'user' ? 'USER' : message.type === 'reasoning' ? 'REASONING' : 'ASSISTANT';
323
+ lines.push(`${role}: ${text}`);
324
+ }
325
+
326
+ const transcript = lines.join('\n\n');
327
+ if (transcript.length <= MAX_TRANSCRIPT_CHARS) return transcript;
328
+
329
+ // Keep the tail: the end of a turn holds the conclusion and any final
330
+ // correction, which is where the durable memory usually is.
331
+ return `…\n${transcript.slice(-MAX_TRANSCRIPT_CHARS)}`;
332
+ }
333
+
334
+ function buildPrompt(options: {
335
+ transcript: string;
336
+ changedPaths: string[];
337
+ related: string;
338
+ injected: string;
339
+ }): string {
340
+ const files = options.changedPaths.length
341
+ ? options.changedPaths.slice(0, 40).map(p => `- ${p}`).join('\n')
342
+ : '- (no files changed on disk)';
343
+
344
+ return `You keep a long-term memory. Read one span of a work session and write down everything stated in it that would still be worth knowing weeks from now, in a different session, to someone with no other context.
345
+
346
+ WRITE EVERY MEMORY IN ENGLISH, both label and body. The conversation below is usually in another language; translate as you record it. A corpus in mixed languages neither compares nor de-duplicates, so the same fact stated once in each language becomes two unrelated entries that never connect.
347
+
348
+ THE TEST IS WHETHER IT COULD BE READ BACK OUT OF THE REPOSITORY.
349
+
350
+ An agent in a later session can open the code, the config and the lockfile in seconds. Anything it would find there is not worth a memory, however true. What it can NEVER recover that way is what happened in the conversation: why a choice was made and what was rejected, what the user asked for and objected to, what was tried and failed, and the conventions people follow that the code merely reflects.
351
+
352
+ WRITE DOWN:
353
+ - decisions and the reasoning behind them, including the option that was not taken
354
+ - preferences and corrections the user stated
355
+ - failures: what broke, why, and what fixed it
356
+ - conventions and constraints that hold beyond the file they were noticed in
357
+ - who someone is, and how they work
358
+ - behaviour of a language, runtime, framework or library that surprised someone
359
+
360
+ DO NOT WRITE DOWN:
361
+ - what the project is built with, unless the turn explains WHY it was chosen. "The project uses Prisma with PostgreSQL" is in package.json
362
+ - a feature inventory of the codebase — payments, auth, localization, uploads. Listing the directory answers that faster than recalling it
363
+ - a blow-by-blow account of what the agent did (that is history, not knowledge)
364
+ - a restatement of the code diff
365
+ - something true only for this one turn, with no bearing on later ones
366
+ - content-free pleasantries ("thanks", "ok", "continue")
367
+ - credentials, tokens, keys or anything else secret, even in passing
368
+
369
+ A turn that only ANSWERED A QUESTION about existing code has usually established nothing durable, and returning an empty list is the right answer far more often than it feels like. A memory that merely describes the code costs recall budget on every future turn and tells the reader what it could have looked up.
370
+
371
+ PAY PARTICULAR ATTENTION TO CORRECTIONS. When the user says a version of "no, not like that", "don't do X", "I'd rather you Y", that is the single highest-value thing in the transcript: it is a preference stated explicitly, it usually generalises beyond this turn, and it is the kind of thing that gets re-litigated every session until someone writes it down. Record it as a preference with high confidence, phrased as the rule rather than as the incident.
372
+
373
+ PREFER FEWER, LARGER MEMORIES. If a turn establishes one thing, write ONE. Five notes saying a marketplace takes payments, has referrals, uses OTP and compiles SCSS are one fact about one project split five ways, competing with each other for the same slot forever.
374
+
375
+ How to write each one:
376
+ - English. Not the language of the conversation. Check this before returning.
377
+ - The label must stand alone, with the subject named. "Arga is a full-stack developer working in JavaScript and TypeScript", not "the user introduced themselves". "Sessions are rejected once the auth token expires", not "fixed the bug".
378
+ - Pick the closest subkind. entity = who or what something is. preference = how someone wants things done. decision = a choice and its reason. pattern = a convention that holds. failure = something that broke and why. observation = anything else durable.
379
+ - scope "global" = true beyond this codebase (people, preferences, cross-project conventions). scope "project" = true of this codebase only.
380
+ - relatedPaths must be paths that appear below; never invent one. Most memories have none.
381
+ - entities names the people, tools or systems the memory is about, so statements about the same subject are stored together.
382
+
383
+ WRITE IT SO IT TRAVELS. When the turn establishes something about a language, a runtime, a library or a way of working, state the RULE rather than the incident: "In Svelte 5 a multi-statement derived block must use $derived.by", not "fixed the total showing a function". The rule is useful in another project six months from now; the incident is not. When the turn establishes something about this codebase in particular, say which codebase it is about.
384
+
385
+ RELATING TO WHAT IS ALREADY KNOWN
386
+ Each of your memories may be compared against the neighbours listed under EXISTING MEMORIES. For every neighbour that is either the SAME claim or the OPPOSITE claim, add an entry to relations. Judge the claim, not the wording.
387
+ - same — it says what you are saying, in other words. The existing memory is reinforced instead of a near-copy being stored.
388
+ - opposite — it cannot be true at the same time as yours. Both are kept; the system decides which is current each time it is asked, using who said it and how recently.
389
+ - Everything else you may leave out.
390
+
391
+ Do not try to decide which of two conflicting memories should win, and do not withhold a memory because it disagrees with something stored. Recording the disagreement IS the answer.
392
+
393
+ EXISTING MEMORIES:
394
+ ${options.related}
395
+
396
+ MEMORIES GIVEN TO THIS TURN:
397
+ ${options.injected}
398
+ For each of those, return a verdict in feedback. "ignored" is the ordinary answer and carries no criticism — most memories offered to a turn simply do not bear on it. Reserve "wrong" for one the transcript actually shows to be incorrect.
399
+
400
+ Files changed on disk during this span:
401
+ ${files}
402
+
403
+ Transcript:
404
+ ${options.transcript}`;
405
+ }
406
+
407
+ /**
408
+ * What happened to one queued extraction.
409
+ *
410
+ * The distinction that matters is between "there was nothing to record" and
411
+ * "this could not be recorded right now". Both used to return 0, so the queue
412
+ * deleted the entry either way and a model outage cost the user a conversation.
413
+ *
414
+ * `countsAsAttempt` separates a genuine failure from a condition the user has to
415
+ * resolve. No model configured will not start working by being retried harder;
416
+ * burning attempts on it would park the entry as failed within minutes, for
417
+ * something that is fixed by visiting a settings page.
418
+ */
419
+ export type EpisodicIngestResult =
420
+ | { ok: true; written: number }
421
+ | { ok: false; error: string; countsAsAttempt: boolean };
422
+
423
+ /**
424
+ * Extract and store episodic memories for a finished turn.
425
+ *
426
+ * Never throws: extraction is a best-effort enrichment of work the user already
427
+ * considers done, so a model error, a missing account or a malformed response is
428
+ * REPORTED to the queue rather than raised at a caller who cannot act on it.
429
+ */
430
+ export async function ingestEpisodicMemories(input: EpisodicIngestInput): Promise<EpisodicIngestResult> {
431
+ const config = getMemoryConfig();
432
+ // Switched off. The user decided this; drop the entry rather than hoarding
433
+ // work for a feature they have turned off.
434
+ if (!config.enabled || !config.recordMemories) return { ok: true, written: 0 };
435
+
436
+ // Switched ON with nothing to run it. Pick a default first: at startup the
437
+ // engine catalog is often not loaded yet, but by the time a turn has finished
438
+ // it certainly is, which makes this the reliable moment to choose one.
439
+ //
440
+ // Still keep the turn if that fails — the moment a model becomes available,
441
+ // everything banked while it was missing gets summarised.
442
+ const model = config.model ?? (await ensureMemoryModel());
443
+ if (!model) {
444
+ return { ok: false, error: 'No model is configured for writing memories', countsAsAttempt: false };
445
+ }
446
+
447
+ const rawTranscript = buildTranscript(input.sessionId, input.userMessageId);
448
+ // Only skip a span with no dialogue at all (a bare tool run, an interrupted
449
+ // stream). The floor is deliberately low: "my name is Arga, a full-stack
450
+ // developer" is a short turn and one of the most valuable things the graph can
451
+ // hold, so a length threshold tuned for code discussions would throw it away.
452
+ if (rawTranscript.trim().length < 24) return { ok: true, written: 0 };
453
+
454
+ // Redaction happens BEFORE the model sees the text, not after. A summariser
455
+ // asked to record what a turn established will happily quote the API key it
456
+ // was shown, and by then the secret is in a durable, re-injected, instance-wide
457
+ // store. See backend/memory/redact.ts.
458
+ const redacted = redactSecrets(rawTranscript);
459
+ if (redacted.hits.length > 0) {
460
+ debug.log('memory', `Redacted ${redacted.hits.join(', ')} from transcript before extraction`);
461
+ }
462
+
463
+ const related = gatherRelatedMemories({
464
+ transcript: redacted.text,
465
+ projectId: input.projectId,
466
+ sessionId: input.sessionId
467
+ });
468
+ const candidateIds = new Set(related.map(memory => memory.id));
469
+
470
+ const injectedIds = new Set(input.injectedMemoryIds ?? []);
471
+ const injectedListing = renderInjected(input.injectedMemoryIds ?? []);
472
+
473
+ let response: ExtractionResponse;
474
+ try {
475
+ response = await requestExtraction(
476
+ model,
477
+ buildPrompt({
478
+ transcript: redacted.text,
479
+ changedPaths: input.changedPaths,
480
+ related: renderRelatedMemories(related),
481
+ injected: injectedListing
482
+ })
483
+ );
484
+ } catch (error) {
485
+ // Retriable by default. Almost everything that reaches here is transient —
486
+ // a rate limit, an engine restarting, a token being refreshed — and the one
487
+ // outcome that cannot be undone is throwing the turn away.
488
+ const message = error instanceof Error ? error.message : String(error);
489
+ debug.warn('memory', 'Episodic extraction failed', error);
490
+ return { ok: false, error: message, countsAsAttempt: true };
491
+ }
492
+
493
+ // Feedback first: it is independent of whether anything new was extracted, and
494
+ // a turn that recorded nothing can still have proved a memory wrong.
495
+ const scored = applyFeedback(response.feedback ?? [], injectedIds);
496
+ if (scored > 0) debug.log('memory', `Scored ${scored} injected memory/memories`);
497
+
498
+ const memories = Array.isArray(response.memories) ? response.memories : [];
499
+ let written = 0;
500
+
501
+ // Memories written by THIS extraction, with their vectors, so each one can be
502
+ // compared against the ones before it. Vector indexing is scheduled rather than
503
+ // synchronous, so nothing written in this loop exists in `graph_vectors` yet —
504
+ // which is how one turn about a single Svelte rule produced three memories
505
+ // stating it, two of them at cosine 0.8955.
506
+ const writtenThisTurn: { node: GraphNode; vector: Float32Array }[] = [];
507
+
508
+ for (const memory of memories.slice(0, MAX_MEMORIES_PER_TURN)) {
509
+ if (!memory?.label?.trim()) continue;
510
+
511
+ // The model's own text is redacted too. It was asked not to record secrets,
512
+ // and asking is not a control.
513
+ const label = redactSecrets(memory.label.trim()).text.slice(0, 300);
514
+ const body = redactSecrets((memory.body ?? '').trim()).text;
515
+ if (!label) continue;
516
+
517
+ const scope: GraphScope =
518
+ memory.scope === 'global' ? 'global' : memory.scope === 'session' ? 'session' : 'project';
519
+ // A global memory belongs to the user, not the repository it was noticed in,
520
+ // so it is stored without a project — that is what lets it apply everywhere
521
+ // and be found before any project is selected.
522
+ const projectId = scope === 'global' ? null : input.projectId;
523
+ const assertedBy: GraphAssertedBy =
524
+ memory.assertedBy === 'user' ? 'user' : memory.assertedBy === 'assistant' ? 'assistant' : 'inferred';
525
+ // A one-off instruction never travels: it was true of one task in one
526
+ // session, and carrying it into another project is the failure this scope
527
+ // exists to prevent.
528
+ const reach: GraphReach = scope === 'session' ? 'here' : memory.reach === 'anywhere' ? 'anywhere' : 'here';
529
+
530
+ // ── what this restates or contradicts ───────────────────────────────
531
+ // The model's own verdicts come first — it read the turn — and are checked
532
+ // against the ids it was actually shown. Anything it did not rule on falls
533
+ // through to being stored on its own, which is the safe default: a duplicate
534
+ // costs a line of budget, a discarded memory is gone.
535
+ const verdicts = new Map<string, 'same' | 'opposite' | 'different'>();
536
+ for (const relation of memory.relations ?? []) {
537
+ if (!relation?.id) continue;
538
+ const known = candidateIds.has(relation.id) || writtenThisTurn.some(entry => entry.node.id === relation.id);
539
+ if (known) verdicts.set(relation.id, relation.relation);
540
+ }
541
+
542
+ const sameAs = [...verdicts.entries()].find(([, relation]) => relation === 'same')?.[0];
543
+ const opposites = [...verdicts.entries()].filter(([, relation]) => relation === 'opposite').map(([id]) => id);
544
+
545
+ // One narrow place cosine is still trusted to decide: against the memories
546
+ // THIS response already produced. The model cannot relate its own outputs to
547
+ // each other — they have no ids until they are written — and it does restate
548
+ // itself: one turn about a single Svelte rule returned three memories saying
549
+ // it three ways. Within one response the reversal risk that makes cosine
550
+ // unusable elsewhere does not exist, because the model is describing one turn
551
+ // rather than revising a belief, so a high score here really does mean "said
552
+ // twice".
553
+ const selfDuplicate =
554
+ findRelatedCandidates({
555
+ text: `${label}\n${body}`,
556
+ subkind: memory.subkind,
557
+ projectId,
558
+ extra: writtenThisTurn
559
+ }).find(
560
+ candidate =>
561
+ candidate.score >= SELF_DUPLICATE && writtenThisTurn.some(entry => entry.node.id === candidate.node.id)
562
+ )?.node ?? null;
563
+
564
+ const duplicate = selfDuplicate ?? (sameAs ? (graphQueries.getById(sameAs) ?? null) : null);
565
+
566
+ if (duplicate) {
567
+ // Reinforce through the existing node's own identity, which is what turns
568
+ // a rephrasing into evidence for the memory it rephrases instead of a
569
+ // second entry that competes with it.
570
+ //
571
+ // The reinforcement carries the NEW memory's authority and reach upward
572
+ // (see `upsert`): a rule the user restated outright is now theirs, and one
573
+ // recognised as travelling now travels, even though the stored text does
574
+ // not change.
575
+ graphQueries.upsert({
576
+ kind: 'episodic',
577
+ subkind: duplicate.subkind,
578
+ scope: duplicate.scope,
579
+ projectId: duplicate.projectId,
580
+ sessionId: duplicate.sessionId,
581
+ digest: duplicate.digest,
582
+ label: duplicate.label,
583
+ body: duplicate.body,
584
+ confidence: Math.max(duplicate.confidence, clampConfidence(memory.confidence)),
585
+ source: duplicate.source,
586
+ assertedBy,
587
+ reach,
588
+ reachJudged: true
589
+ });
590
+ // Contradictions belong to the memory that actually makes the claim, which
591
+ // is the one being reinforced.
592
+ recordContradictions(duplicate.id, opposites, new Set([...candidateIds, ...writtenThisTurn.map(e => e.node.id)]));
593
+ linkEntities(duplicate.id, memory.entities ?? []);
594
+ continue;
595
+ }
596
+
597
+ const node = graphQueries.upsert({
598
+ kind: 'episodic',
599
+ subkind: memory.subkind,
600
+ scope,
601
+ projectId,
602
+ sessionId: scope === 'global' ? null : input.sessionId,
603
+ label,
604
+ body,
605
+ confidence: clampConfidence(memory.confidence),
606
+ source: 'agent',
607
+ assertedBy,
608
+ reach,
609
+ reachJudged: true
610
+ });
611
+ written++;
612
+
613
+ const vector = embedder.embed(`${label}\n${body}`, { minTokens: 6 });
614
+ if (vector) writtenThisTurn.push({ node, vector });
615
+
616
+ // ── disagreements, recorded rather than acted on ────────────────────
617
+ recordContradictions(node.id, opposites, new Set([...candidateIds, ...writtenThisTurn.map(e => e.node.id)]));
618
+
619
+ // ── entities ────────────────────────────────────────────────────────
620
+ linkEntities(node.id, memory.entities ?? []);
621
+
622
+ // `about` edges are what make the two halves one graph: from here a question
623
+ // about the code reaches this memory, and this memory names the code.
624
+ for (const rawPath of memory.relatedPaths ?? []) {
625
+ const path = rawPath.replace(/\\/g, '/').replace(/^\.\//, '');
626
+ const targetId = input.fileNodes.get(path) ?? graphQueries.getByPath(input.projectId, path)?.id;
627
+ if (!targetId) continue;
628
+ graphQueries.link({ srcId: node.id, dstId: targetId, rel: 'about', source: 'agent' });
629
+ }
630
+ }
631
+
632
+ if (written > 0) {
633
+ debug.log('memory', `Episodic ingest: ${written} memory/memories from session ${input.sessionId.slice(0, 8)}`);
634
+ }
635
+ return { ok: true, written };
636
+ }
637
+
638
+ /** The injected memories, as the model sees them for adjudication. */
639
+ function renderInjected(ids: string[]): string {
640
+ if (ids.length === 0) return '- (none were injected into this turn)';
641
+ const nodes = graphQueries.getByIds(ids);
642
+ if (nodes.length === 0) return '- (none were injected into this turn)';
643
+ return nodes.map(node => `- [${node.id}] (${node.subkind}) ${node.label}`).join('\n');
644
+ }
645
+
646
+ function clampConfidence(value: unknown): number {
647
+ const n = typeof value === 'number' ? value : 0.5;
648
+ if (!Number.isFinite(n)) return 0.5;
649
+ return Math.min(1, Math.max(0.1, n));
650
+ }
651
+
652
+ /**
653
+ * Ask the configured model for structured memories, relations and verdicts.
654
+ *
655
+ * Two things here are not incidental.
656
+ *
657
+ * IT RUNS IN A NEUTRAL DIRECTORY, not the user's repository. Engines implement
658
+ * `generateStructured` by opening one of their own sessions in `projectPath`, so
659
+ * the repository's instruction files land in the model's context alongside the
660
+ * transcript — and it writes them down. Measured: a span whose entire content was
661
+ * "halo, nama saya Arga" produced "Arga is the user working on the Clopen
662
+ * project", and another produced "Clopen uses Bun as the exclusive runtime —
663
+ * Node.js and Deno are not supported", a sentence lifted from the repository's
664
+ * CLAUDE.md that nobody in the conversation had said. It also made the call less
665
+ * reliable: pointed at a repository, 3 of 12 runs failed outright (truncated
666
+ * JSON, or the model answering about the directory instead of the task) against
667
+ * 1 of 12 from an empty directory. Extraction is a text transformation; giving it
668
+ * a codebase to look at can only contaminate it.
669
+ *
670
+ * IT HAS A DEADLINE. This is the only write path in the feature and it had no
671
+ * timeout of its own, on top of a `drain()` loop with no deadline either — so one
672
+ * hung call froze recording AND stood maintenance down until the process was
673
+ * restarted, silently. Observed in testing: a single call that had not returned
674
+ * after thirty-five minutes.
675
+ */
676
+ async function requestExtraction(model: MemoryModelConfig, prompt: string): Promise<ExtractionResponse> {
677
+ const engine = await initializeEngine(model.engine);
678
+ if (!engine.generateStructured) {
679
+ throw new Error(`Engine "${model.engine}" does not support structured generation`);
680
+ }
681
+
682
+ // The stored providerSlug/accountId can be stale — a model may have moved
683
+ // provider or the account may be gone (see resolve-model.ts).
684
+ const target = await resolveGenerationTarget(engine, model.modelId, model.providerSlug);
685
+ const accountId = model.accountId ?? target.accountId;
686
+
687
+ const abortController = new AbortController();
688
+ const deadline = setTimeout(() => abortController.abort(), EXTRACTION_TIMEOUT_MS);
689
+ try {
690
+ const result = await Promise.race([
691
+ engine.generateStructured<ExtractionResponse>({
692
+ prompt,
693
+ providerSlug: target.providerSlug,
694
+ modelId: target.modelId,
695
+ schema: MEMORY_SCHEMA,
696
+ projectPath: getExtractionWorkdir(),
697
+ abortController,
698
+ ...(accountId != null && { accountId })
699
+ }),
700
+ // The abort signal is honoured by some adapters and ignored by others, so
701
+ // the race is what actually bounds the wait. A run that keeps going in the
702
+ // background is wasted work; a run that keeps the queue is a stopped
703
+ // feature.
704
+ new Promise<never>((_, reject) =>
705
+ setTimeout(
706
+ () => reject(new Error(`Extraction timed out after ${Math.round(EXTRACTION_TIMEOUT_MS / 1000)}s`)),
707
+ EXTRACTION_TIMEOUT_MS
708
+ )
709
+ )
710
+ ]);
711
+ return result ?? {};
712
+ } finally {
713
+ clearTimeout(deadline);
714
+ }
715
+ }
716
+
717
+ /**
718
+ * An empty, Clopen-owned directory for the extraction model to open a session
719
+ * in. Created once; its emptiness is the point.
720
+ */
721
+ function getExtractionWorkdir(): string {
722
+ const dir = join(getClopenDir(), 'memory', 'extract');
723
+ if (!existsSync(dir)) mkdirSync(dir, { recursive: true });
724
+ return dir;
725
+ }