@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,33 @@
1
+ /**
2
+ * Tool description. The agent reads this once per session, so it has to explain
3
+ * not just the actions but WHEN reaching for the graph beats guessing — and, just
4
+ * as importantly, that it does not have to write anything.
5
+ */
6
+
7
+ export const memoryToolDescription = `Query and curate Clopen's Memory Graph — a persistent store of what has been decided, tried and learned across past sessions of this workspace, plus a map of the codebase those memories attach to. It is shared by every AI engine and survives session switches, so a memory written months ago by a different model is still here.
8
+
9
+ YOU DO NOT NEED TO RECORD ANYTHING. Memories are written automatically from each finished conversation turn, including anything the user asks you to remember — saying "remember that I prefer X" is enough on its own, and there is deliberately no action here that stores a new memory. That is one write path rather than two, so what ends up in the graph is predictable. This tool is for reading it and for correcting what is already there.
10
+
11
+ Reach for it when:
12
+ - you are about to make an architectural choice, and an earlier session may already have made it (and rejected alternatives you are about to re-propose)
13
+ - something is failing in a way that feels like it has failed before
14
+ - you need to know why code looks the way it does, when the code itself does not say
15
+ - the user refers to a past discussion, decision or preference
16
+ - you want to know what a file or module is connected to before changing it
17
+ - a memory you were shown is wrong, out of date, or filed under the wrong kind
18
+
19
+ Relevant memories are already prepended to each turn automatically, so this tool is for going DEEPER than that: following up on something you have just discovered, asking about another project, or walking the graph. It is not a substitute for reading what you were given.
20
+
21
+ Actions:
22
+ - recall — natural-language search across memories and code entities. Runs keyword and semantic search together and expands into the graph, so it finds paraphrases as well as exact names. Use scope "all" to search every project, which is how you find that a problem was already solved in another repository.
23
+ - neighbours — walk outward from a node returned by recall. This is where the graph earns its keep: the memory you need is often adjacent to your match rather than being it.
24
+ - timeline — recent memories in order, for "what have we been doing here".
25
+ - update — correct a memory in place. Prefer this whenever an existing memory is nearly right: it keeps the node's connections and its history, where retiring it and letting a new one be written loses both.
26
+ - link — connect two nodes. Use "supersedes" when a memory replaces an older one and "contradicts" when two disagree and you cannot tell which is right.
27
+ - forget — archive a memory that was never true. It is retired from search, not deleted, so the reasoning trail survives and the user can restore it.
28
+ - restore — bring an archived memory back, when it was retired in error.
29
+ - stats — size and composition of the graph.
30
+
31
+ Forgetting and superseding are different claims and worth getting right. "forget" says a memory was WRONG. "supersedes" says it was true and has since been REPLACED — the old one stops being recalled but stays one hop from the new one, so the history of a decision remains answerable. Reach for supersedes whenever something changed rather than was mistaken.
32
+
33
+ Batch independent operations into one call. Each memory returned carries an id, its kind, how it was found, and how confident the writer was — treat low confidence as a lead, not a fact, and trust the current code over any memory that disagrees with it.`;
@@ -0,0 +1,45 @@
1
+ /**
2
+ * Rendering the run report.
3
+ *
4
+ * The report is the agent's only view of the graph, so it leads with the count
5
+ * that matters, keeps each operation's outcome separate, and says plainly when
6
+ * the graph was queried without project context — otherwise an empty result
7
+ * looks like "nothing was ever decided" when it actually means "you asked
8
+ * outside any project".
9
+ */
10
+
11
+ import type { RunReport } from './runner';
12
+
13
+ export function formatReport(report: RunReport): {
14
+ content: Array<{ type: 'text'; text: string }>;
15
+ isError?: boolean;
16
+ } {
17
+ const total = report.operations.length;
18
+ const ok = report.operations.filter(o => o.ok).length;
19
+
20
+ const lines: string[] = [`Memory Graph — ${ok}/${total} operation(s) succeeded`];
21
+
22
+ if (!report.projectScoped) {
23
+ lines.push('No project context for this call, so project-scoped memories were not searched.');
24
+ }
25
+
26
+ for (const [index, operation] of report.operations.entries()) {
27
+ lines.push('', `[${index + 1}] ${operation.action}${operation.ok ? '' : ' FAILED'}`);
28
+ lines.push(indent(operation.text));
29
+ }
30
+
31
+ return {
32
+ content: [{ type: 'text', text: lines.join('\n') }],
33
+ // Only a batch where nothing worked counts as an error: a partially useful
34
+ // result is still useful, and flagging it would push the agent to retry work
35
+ // that already landed.
36
+ ...(ok === 0 && total > 0 && { isError: true })
37
+ };
38
+ }
39
+
40
+ function indent(text: string): string {
41
+ return text
42
+ .split('\n')
43
+ .map(line => (line ? ` ${line}` : line))
44
+ .join('\n');
45
+ }
@@ -0,0 +1,52 @@
1
+ /**
2
+ * Memory Graph — internal MCP server.
3
+ *
4
+ * One tool. Every capability is an operation inside it, so recalling a memory and
5
+ * then walking its neighbours can be one call instead of a round trip each, and
6
+ * the whole surface fits in a single description the agent reads once.
7
+ *
8
+ * Exposed through the existing Streamable HTTP endpoint
9
+ * (`backend/mcp/internal/remote-server.ts`), which is what makes the graph
10
+ * agent-agnostic for free: every engine that can consume an MCP URL reaches the
11
+ * same store, with no per-engine work.
12
+ */
13
+
14
+ import { defineServer } from '../helper';
15
+ import { memoryToolDescription } from './description';
16
+ import { memoryToolSchema } from './schema';
17
+ import { runMemoryOperations } from './runner';
18
+ import { formatReport } from './format';
19
+
20
+ export default defineServer({
21
+ name: 'memory-graph',
22
+ title: 'Memory Graph',
23
+ description:
24
+ 'Persistent memory shared by every engine — past decisions, patterns and failures, plus the code they attach to, searchable across every project.',
25
+ version: '1.0.0',
26
+ tools: {
27
+ memory: {
28
+ description: memoryToolDescription,
29
+ schema: memoryToolSchema,
30
+ handler: async (args) => {
31
+ try {
32
+ const report = await runMemoryOperations(args as Parameters<typeof runMemoryOperations>[0]);
33
+ return formatReport(report);
34
+ } catch (error) {
35
+ // Nothing ran: the batch never started, so there is no partial report
36
+ // to render.
37
+ return {
38
+ content: [
39
+ {
40
+ type: 'text' as const,
41
+ text: `Memory Graph call failed before starting: ${
42
+ error instanceof Error ? error.message : 'Unknown error'
43
+ }`
44
+ }
45
+ ],
46
+ isError: true
47
+ };
48
+ }
49
+ }
50
+ }
51
+ }
52
+ });
@@ -0,0 +1,342 @@
1
+ /**
2
+ * Memory Graph tool runner.
3
+ *
4
+ * Executes a batch of operations in order and renders one report. Unlike the
5
+ * browser server, an operation here never mutates something the next operation
6
+ * depends on physically, so there is no coalescing or re-resolution — but the
7
+ * batch still runs sequentially, because `remember` followed by `link` is a
8
+ * common pair and the second needs the first's id.
9
+ *
10
+ * Project context is OPTIONAL by design. Every other internal MCP server can
11
+ * assume a project (a browser belongs to one), but the graph deliberately cannot:
12
+ * a global-scope question — "what does the user prefer", "which project handles
13
+ * auth" — has to be answerable before any project is selected. That is the shape
14
+ * cross-project chat needs, so `projectId` being null is a normal case here, not
15
+ * an error.
16
+ */
17
+
18
+ import { z } from 'zod';
19
+ import { graphQueries } from '$backend/database/queries/graph-queries';
20
+ import { projectContextService } from '$backend/mcp/internal/project-context';
21
+ import { markConsulted, retrieve } from '$backend/memory/retrieval';
22
+ import { scheduleVectorIndexing } from '$backend/memory/indexer';
23
+ import { getMemoryConfig } from '$backend/memory/config';
24
+ import { notifyGraphChanged } from '$backend/memory/notify';
25
+ import { getMemoryReadiness } from '$backend/memory/readiness';
26
+ import { embedder, vectorCache } from '$backend/memory/embedding';
27
+ import { debug } from '$shared/utils/logger';
28
+ import type { GraphNode, GraphRelation, RetrievalHit } from '$shared/types/memory';
29
+ import type { memorySchema } from './schema';
30
+
31
+ type Operation = z.infer<typeof memorySchema>;
32
+
33
+ export interface OperationReport {
34
+ action: string;
35
+ ok: boolean;
36
+ text: string;
37
+ }
38
+
39
+ export interface RunReport {
40
+ operations: OperationReport[];
41
+ projectScoped: boolean;
42
+ vectorSearchAvailable: boolean;
43
+ }
44
+
45
+ /** Where the batch is running: a project and session when one is in play. */
46
+ interface Context {
47
+ projectId: string | null;
48
+ sessionId: string | null;
49
+ }
50
+
51
+ function resolveContext(): Context {
52
+ return {
53
+ projectId: projectContextService.getCurrentProjectId(),
54
+ sessionId: projectContextService.getCurrentChatSessionId()
55
+ };
56
+ }
57
+
58
+ /** One line per hit: enough to act on, compact enough to batch. */
59
+ function renderHit(hit: RetrievalHit, currentProjectId: string | null): string {
60
+ const node = hit.node;
61
+ const found = hit.hops > 0 ? `via graph, ${hit.hops} hop${hit.hops > 1 ? 's' : ''}` : hit.channel;
62
+ // Where it came from, not what its scope value is. A memory learned in another
63
+ // repository is worth acting on when it is about a technology and misleading
64
+ // when read as a description of THIS codebase, and the agent can only tell the
65
+ // difference if it is told.
66
+ const where =
67
+ node.projectId === null
68
+ ? 'any project'
69
+ : node.projectId !== currentProjectId
70
+ ? 'learned in another project'
71
+ : node.scope;
72
+ const detail =
73
+ node.kind === 'structural'
74
+ ? (node.symbol ? `${node.symbol} — ${node.path}` : (node.path ?? ''))
75
+ : node.body.split('\n')[0].slice(0, 260);
76
+
77
+ return [
78
+ `[${node.id}] (${node.subkind}, ${where}, confidence ${node.confidence.toFixed(2)}, found by ${found})`,
79
+ ` ${node.label}`,
80
+ detail ? ` ${detail}` : ''
81
+ ]
82
+ .filter(Boolean)
83
+ .join('\n');
84
+ }
85
+
86
+ function renderNode(node: GraphNode, prefix = ''): string {
87
+ const detail = node.kind === 'structural' ? (node.path ?? '') : node.body.split('\n')[0].slice(0, 200);
88
+ return `${prefix}[${node.id}] (${node.subkind}) ${node.label}${detail ? `\n${prefix} ${detail}` : ''}`;
89
+ }
90
+
91
+ async function runOne(op: Operation, ctx: Context): Promise<OperationReport> {
92
+ switch (op.action) {
93
+ case 'recall': {
94
+ // Refused rather than answered lexically while the artifact is still
95
+ // arriving. A thin BM25 result set is indistinguishable to the agent from
96
+ // a complete one, so answering would let it conclude "nothing was decided"
97
+ // from "no shared keywords" — and act on that. Saying so plainly costs one
98
+ // turn; a wrong answer costs a wrong decision.
99
+ const readiness = getMemoryReadiness();
100
+ if (!readiness.canRecall) {
101
+ return {
102
+ action: op.action,
103
+ ok: false,
104
+ text: readiness.enabled
105
+ ? 'Memory recall is not ready yet — the local embedding model is still being set up. ' +
106
+ 'Do not treat this as "nothing has been decided"; proceed without memory for now.'
107
+ : 'Memory is switched off for this workspace.'
108
+ };
109
+ }
110
+
111
+ const result = retrieve({
112
+ query: op.query,
113
+ // "all" drops the project filter entirely, which is what makes
114
+ // "how did we solve this in another repo" answerable.
115
+ projectId: op.scope === 'all' ? undefined : ctx.projectId,
116
+ // Even a project-scoped lookup sees what other projects learned about
117
+ // TECHNOLOGY, ranked below what this one knows. Requiring `scope: "all"`
118
+ // for that meant an agent had to already suspect the answer lived
119
+ // elsewhere before it could find it — which is the "didn't know to ask"
120
+ // case memory exists to cover.
121
+ crossProject: true,
122
+ sessionId: ctx.sessionId ?? undefined,
123
+ kinds: op.kind && op.kind !== 'both' ? [op.kind] : undefined,
124
+ limit: op.limit ?? 10,
125
+ // An explicit lookup is answered with what MATCHES it, not with what
126
+ // matches it plus everything one edge away. Expansion belongs to
127
+ // turn-start injection, where a weak lead is still worth ranking and the
128
+ // agent never sees the ranking; asked a direct question, it turns
129
+ // "phoenix" into three correct rows plus sixty neighbours-of-neighbours,
130
+ // and an agent has no way to tell which is which. Same reasoning, and the
131
+ // same settings, as the Memory modal's search box.
132
+ expandHops: 0,
133
+ precise: true
134
+ });
135
+
136
+ // A deliberate lookup by an agent IS evidence of use, unlike the automatic
137
+ // turn-start injection — which is why `retrieve` no longer counts itself.
138
+ markConsulted(result.hits);
139
+
140
+ if (result.hits.length === 0) {
141
+ return {
142
+ action: op.action,
143
+ ok: true,
144
+ text: `No memory found for "${op.query}".${
145
+ op.scope === 'all' ? '' : ' Retry with scope "all" to search every project.'
146
+ }`
147
+ };
148
+ }
149
+
150
+ return {
151
+ action: op.action,
152
+ ok: true,
153
+ text:
154
+ `${result.hits.length} result(s) for "${op.query}"` +
155
+ `${result.vectorUsed ? '' : ' (keyword only — semantic search is still initializing)'}:\n\n` +
156
+ result.hits.map(hit => renderHit(hit, ctx.projectId)).join('\n\n')
157
+ };
158
+ }
159
+
160
+ case 'neighbours': {
161
+ const node = graphQueries.getById(op.nodeId);
162
+ if (!node) return { action: op.action, ok: false, text: `No node with id ${op.nodeId}.` };
163
+
164
+ const neighbours = graphQueries.neighbours(op.nodeId, op.hops ?? 1);
165
+ if (neighbours.length === 0) {
166
+ return { action: op.action, ok: true, text: `[${node.id}] ${node.label}\nNo connections yet.` };
167
+ }
168
+
169
+ const edges = graphQueries.edgesOf(op.nodeId);
170
+ const relationOf = (otherId: string): string => {
171
+ const edge = edges.find(e => e.srcId === otherId || e.dstId === otherId);
172
+ if (!edge) return 'connected';
173
+ return edge.srcId === op.nodeId ? `${edge.rel} →` : `← ${edge.rel}`;
174
+ };
175
+
176
+ return {
177
+ action: op.action,
178
+ ok: true,
179
+ text:
180
+ `[${node.id}] ${node.label}\n\n${neighbours.length} connection(s):\n` +
181
+ neighbours
182
+ .map(n => ` ${n.hops === 1 ? relationOf(n.node.id) : `${n.hops} hops`} ${renderNode(n.node)}`)
183
+ .join('\n')
184
+ };
185
+ }
186
+
187
+ case 'timeline': {
188
+ const nodes = graphQueries.timeline({
189
+ projectId: ctx.projectId,
190
+ sessionId: op.thisSessionOnly ? ctx.sessionId : null,
191
+ limit: op.limit ?? 20
192
+ });
193
+ if (nodes.length === 0) return { action: op.action, ok: true, text: 'No memories recorded yet.' };
194
+
195
+ return {
196
+ action: op.action,
197
+ ok: true,
198
+ text: `${nodes.length} recent memory/memories (newest first):\n` +
199
+ nodes.map(n => ` ${n.createdAt} ${renderNode(n)}`).join('\n')
200
+ };
201
+ }
202
+
203
+ case 'link': {
204
+ const from = graphQueries.getById(op.fromId);
205
+ const to = graphQueries.getById(op.toId);
206
+ if (!from) return { action: op.action, ok: false, text: `No node with id ${op.fromId}.` };
207
+ if (!to) return { action: op.action, ok: false, text: `No node with id ${op.toId}.` };
208
+
209
+ const edge = graphQueries.link({
210
+ srcId: op.fromId,
211
+ dstId: op.toId,
212
+ rel: op.relation as GraphRelation,
213
+ source: 'agent'
214
+ });
215
+ if (!edge) {
216
+ return { action: op.action, ok: false, text: 'Could not link those nodes (a node cannot link to itself).' };
217
+ }
218
+
219
+ // `supersedes` means the older memory should stop competing with the newer
220
+ // one in retrieval. It is marked superseded rather than ARCHIVED, which is a
221
+ // different claim: archiving says "this was never true", superseding says
222
+ // "this was true and no longer is". The node keeps its edges, stays readable,
223
+ // and sits one hop from the belief that replaced it.
224
+ notifyGraphChanged('linked', from.projectId);
225
+ if (op.relation === 'supersedes') {
226
+ graphQueries.supersede(op.toId, op.fromId);
227
+ return {
228
+ action: op.action,
229
+ ok: true,
230
+ text: `[${from.id}] now supersedes [${to.id}], which is no longer recalled but stays as history.`
231
+ };
232
+ }
233
+
234
+ return { action: op.action, ok: true, text: `[${from.id}] -[${op.relation}]-> [${to.id}]` };
235
+ }
236
+
237
+ case 'forget': {
238
+ const node = graphQueries.getById(op.nodeId);
239
+ if (!node) return { action: op.action, ok: false, text: `No node with id ${op.nodeId}.` };
240
+
241
+ graphQueries.archive(op.nodeId);
242
+ notifyGraphChanged('forgotten', node.projectId);
243
+ debug.log('memory', `Archived node ${op.nodeId} via MCP${op.reason ? `: ${op.reason}` : ''}`);
244
+ return {
245
+ action: op.action,
246
+ ok: true,
247
+ text: `Forgot [${node.id}] "${node.label}". It is out of search but the user can restore it from Memory.`
248
+ };
249
+ }
250
+
251
+ case 'update': {
252
+ const before = graphQueries.getById(op.nodeId);
253
+ if (!before) return { action: op.action, ok: false, text: `No node with id ${op.nodeId}.` };
254
+
255
+ const node = graphQueries.update(
256
+ op.nodeId,
257
+ {
258
+ ...(op.label !== undefined && { label: op.label }),
259
+ ...(op.body !== undefined && { body: op.body }),
260
+ ...(op.subkind !== undefined && { subkind: op.subkind })
261
+ },
262
+ // An agent's correction is an agent's correction. Recording it as the
263
+ // user's would exempt the node from structural decay, from eviction and
264
+ // from consolidation, and would tell every future turn a person had
265
+ // stated it — authority the model did not earn by editing.
266
+ 'agent'
267
+ );
268
+ if (!node) return { action: op.action, ok: false, text: `Could not update ${op.nodeId}.` };
269
+
270
+ // `update` drops the vector, because it described text that just changed.
271
+ scheduleVectorIndexing();
272
+ vectorCache.drop([node.id]);
273
+ notifyGraphChanged('edited', node.projectId);
274
+ return { action: op.action, ok: true, text: `Updated [${node.id}]: ${node.label}` };
275
+ }
276
+
277
+ case 'restore': {
278
+ const node = graphQueries.getById(op.nodeId);
279
+ if (!node) return { action: op.action, ok: false, text: `No node with id ${op.nodeId}.` };
280
+ if (!node.archivedAt) return { action: op.action, ok: true, text: `[${node.id}] was not archived.` };
281
+
282
+ graphQueries.restore(op.nodeId);
283
+ scheduleVectorIndexing();
284
+ notifyGraphChanged('restored', node.projectId);
285
+ return { action: op.action, ok: true, text: `Restored [${node.id}] "${node.label}".` };
286
+ }
287
+
288
+ case 'stats': {
289
+ const stats = graphQueries.stats();
290
+ return {
291
+ action: op.action,
292
+ ok: true,
293
+ text: [
294
+ `${stats.nodes} nodes, ${stats.edges} edges`,
295
+ ` episodic: ${stats.episodic} structural: ${stats.structural}`,
296
+ ` scope — session ${stats.byScope.session}, project ${stats.byScope.project}, global ${stats.byScope.global}`,
297
+ ` ${stats.vectors} node(s) have semantic vectors`,
298
+ ` ${stats.entities} canonical entity/entities, ${stats.confirmedUseful} confirmed useful`,
299
+ ` ${stats.superseded} superseded (history), ${stats.stale} standing on code that has changed`,
300
+ ` spread across ${stats.byProject.length} project(s)`
301
+ ].join('\n')
302
+ };
303
+ }
304
+ }
305
+ }
306
+
307
+ export async function runMemoryOperations(args: { operations: Operation[] }): Promise<RunReport> {
308
+ const config = getMemoryConfig();
309
+ if (!config.enabled) {
310
+ return {
311
+ operations: [{ action: 'disabled', ok: false, text: 'The Memory Graph is turned off in Settings → Infrastructure → Memory.' }],
312
+ projectScoped: false,
313
+ vectorSearchAvailable: false
314
+ };
315
+ }
316
+
317
+ const ctx = resolveContext();
318
+ const reports: OperationReport[] = [];
319
+
320
+ for (const op of args.operations) {
321
+ try {
322
+ reports.push(await runOne(op, ctx));
323
+ } catch (error) {
324
+ // One bad operation must not discard the results of the ones that
325
+ // already succeeded — the agent gets a partial, honest report.
326
+ reports.push({
327
+ action: op.action,
328
+ ok: false,
329
+ text: `Failed: ${error instanceof Error ? error.message : String(error)}`
330
+ });
331
+ }
332
+ }
333
+
334
+ return {
335
+ operations: reports,
336
+ projectScoped: ctx.projectId !== null,
337
+ // `embedder.ready` rather than `stats().vectors > 0`: stats runs eight
338
+ // COUNT(*) scans over the whole table, and this ran on every single tool
339
+ // call purely to fill in one boolean.
340
+ vectorSearchAvailable: embedder.ready
341
+ };
342
+ }
@@ -0,0 +1,140 @@
1
+ /**
2
+ * Tool schema for the Memory Graph.
3
+ *
4
+ * One tool, discriminated on `action`, following the Browser Automation server:
5
+ * a registry of actions inside a single tool rather than a dozen sibling tools.
6
+ * That keeps the graph's whole surface in one description the agent reads once,
7
+ * and lets a related pair of steps (recall, then walk a node's neighbours) be
8
+ * decided without another round trip through the tool list.
9
+ */
10
+
11
+ import { z } from 'zod';
12
+
13
+ const subkind = z
14
+ .enum(['decision', 'pattern', 'failure', 'preference', 'observation'])
15
+ .describe(
16
+ 'decision = a choice and its reason; pattern = a convention that holds; failure = something that broke and why; preference = how the user wants things done; observation = a durable fact'
17
+ );
18
+
19
+ const relation = z
20
+ .enum([
21
+ 'imports',
22
+ 'calls',
23
+ 'defines',
24
+ 'contains',
25
+ 'caused_by',
26
+ 'supersedes',
27
+ 'contradicts',
28
+ 'generalizes',
29
+ 'about',
30
+ 'relates_to'
31
+ ])
32
+ .describe(
33
+ 'about links a memory to code it concerns; supersedes marks a memory as replacing an older one; contradicts flags a conflict; relates_to is a plain association'
34
+ );
35
+
36
+ const recall = z.object({
37
+ action: z.literal('recall'),
38
+ query: z.string().min(1).describe('What you want to know, in natural language. Any language works.'),
39
+ scope: z
40
+ .enum(['project', 'all'])
41
+ .optional()
42
+ .describe(
43
+ 'project (default): this project plus global memories. all: every project — use when the question is not about the current codebase, or to find how something was solved elsewhere.'
44
+ ),
45
+ kind: z
46
+ .enum(['episodic', 'structural', 'both'])
47
+ .optional()
48
+ .describe('episodic = decisions/patterns/failures; structural = files/symbols/dependencies; both (default)'),
49
+ limit: z.number().int().min(1).max(40).optional().describe('Maximum results. Default 10.')
50
+ });
51
+
52
+ /**
53
+ * There is no `remember` action, and that is deliberate.
54
+ *
55
+ * Memories are written by ONE path: the automatic extraction that reads each
56
+ * finished turn (`backend/memory/extract/episodic.ts`). A second write path made
57
+ * the store unpredictable — the same fact could arrive either way, phrased
58
+ * differently, at different times, and an agent had no way to know which had
59
+ * already happened.
60
+ *
61
+ * Nothing is lost by removing it. When the user says "remember that I prefer X",
62
+ * extraction reads that sentence in the transcript and stores it, with the same
63
+ * schema and the same duplicate and revision handling as everything else. Asking
64
+ * the agent to also call a tool was asking it to do work the system was already
65
+ * doing, in a way that could disagree with itself.
66
+ *
67
+ * What remains here is what extraction CANNOT do: look things up on demand, walk
68
+ * the graph, and correct what is already stored.
69
+ */
70
+
71
+ /**
72
+ * Correcting a memory in place, rather than storing a competing one.
73
+ *
74
+ * Without this the only way to fix a memory was `remember` (which leaves the
75
+ * wrong one in the graph) or `forget` followed by `remember` (which loses its
76
+ * edges and its history). A memory that is nearly right is the common case, and
77
+ * it deserves an edit.
78
+ */
79
+ const update = z.object({
80
+ action: z.literal('update'),
81
+ nodeId: z.string().min(1).describe('Node id from a previous recall result.'),
82
+ label: z.string().optional().describe('Replacement one-sentence claim. Omit to keep the current one.'),
83
+ body: z.string().optional().describe('Replacement reasoning. Omit to keep the current one.'),
84
+ subkind: subkind.optional().describe('Correct the kind, when it was filed wrong.')
85
+ });
86
+
87
+ const restore = z.object({
88
+ action: z.literal('restore'),
89
+ nodeId: z.string().min(1).describe('Node id to bring back out of the archive.')
90
+ });
91
+
92
+ const neighbours = z.object({
93
+ action: z.literal('neighbours'),
94
+ nodeId: z.string().min(1).describe('Node id from a previous recall result.'),
95
+ hops: z.number().int().min(1).max(3).optional().describe('How far to walk. Default 1.')
96
+ });
97
+
98
+ const timeline = z.object({
99
+ action: z.literal('timeline'),
100
+ limit: z.number().int().min(1).max(60).optional().describe('How many recent memories. Default 20.'),
101
+ thisSessionOnly: z.boolean().optional().describe('Restrict to memories recorded during this conversation.')
102
+ });
103
+
104
+ const link = z.object({
105
+ action: z.literal('link'),
106
+ fromId: z.string().min(1).describe('Source node id.'),
107
+ toId: z.string().min(1).describe('Target node id.'),
108
+ relation
109
+ });
110
+
111
+ const forget = z.object({
112
+ action: z.literal('forget'),
113
+ nodeId: z.string().min(1).describe('Node id to retire.'),
114
+ reason: z
115
+ .string()
116
+ .optional()
117
+ .describe('Why it is no longer true. Recorded in the log; the node is archived, not destroyed.')
118
+ });
119
+
120
+ const stats = z.object({
121
+ action: z.literal('stats')
122
+ });
123
+
124
+ export const memorySchema = z.discriminatedUnion('action', [
125
+ recall,
126
+ update,
127
+ neighbours,
128
+ timeline,
129
+ link,
130
+ forget,
131
+ restore,
132
+ stats
133
+ ]);
134
+
135
+ export const memoryToolSchema = {
136
+ operations: z
137
+ .array(memorySchema)
138
+ .min(1)
139
+ .describe('Operations to run in order. Batch anything that does not depend on a previous result.')
140
+ };