@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.
- package/backend/auth/permissions.ts +21 -0
- package/backend/bootstrap.ts +18 -1
- package/backend/chat/engine-handoff.test.ts +229 -0
- package/backend/chat/engine-handoff.ts +439 -0
- package/backend/chat/stream-manager.ts +200 -16
- package/backend/database/migrations/066_create_memory_graph.ts +369 -0
- package/backend/database/migrations/index.ts +7 -0
- package/backend/database/queries/audit-log-queries.test.ts +10 -1
- package/backend/database/queries/graph-queries.ts +1764 -0
- package/backend/database/queries/index.ts +2 -0
- package/backend/database/queries/memory-queue-queries.ts +381 -0
- package/backend/database/queries/snapshot-queries.ts +20 -0
- package/backend/engine/README.md +45 -2
- package/backend/engine/adapters/copilot/stream.ts +37 -1
- package/backend/engine/adapters/pi/models.ts +19 -7
- package/backend/engine/adapters/pi/stream.ts +2 -1
- package/backend/engine/docs/adapter-contract.md +25 -8
- package/backend/engine/docs/adding-an-engine.md +40 -4
- package/backend/engine/docs/frontend-and-chat.md +66 -1
- package/backend/engine/docs/lessons-learned.md +165 -6
- package/backend/engine/docs/quick-reference.md +10 -0
- package/backend/engine/docs/stack.md +10 -0
- package/backend/engine/docs/websocket-routes.md +15 -1
- package/backend/engine/engine-setup.ts +1 -1
- package/backend/engine/index.test.ts +186 -0
- package/backend/engine/index.ts +117 -71
- package/backend/engine/install-recipes.test.ts +105 -0
- package/backend/engine/install-recipes.ts +4 -1
- package/backend/index.ts +9 -0
- package/backend/mcp/internal/config.ts +6 -0
- package/backend/mcp/internal/servers/index.ts +2 -0
- package/backend/mcp/internal/servers/memory-graph/description.ts +33 -0
- package/backend/mcp/internal/servers/memory-graph/format.ts +45 -0
- package/backend/mcp/internal/servers/memory-graph/index.ts +52 -0
- package/backend/mcp/internal/servers/memory-graph/runner.ts +342 -0
- package/backend/mcp/internal/servers/memory-graph/schema.ts +140 -0
- package/backend/memory/README.md +432 -0
- package/backend/memory/bootstrap.ts +101 -0
- package/backend/memory/compose.test.ts +198 -0
- package/backend/memory/compose.ts +343 -0
- package/backend/memory/config.ts +100 -0
- package/backend/memory/consolidate.ts +280 -0
- package/backend/memory/context.test.ts +321 -0
- package/backend/memory/context.ts +451 -0
- package/backend/memory/embedding/embedder.test.ts +141 -0
- package/backend/memory/embedding/embedder.ts +269 -0
- package/backend/memory/embedding/index.ts +17 -0
- package/backend/memory/embedding/install.ts +254 -0
- package/backend/memory/embedding/paths.ts +101 -0
- package/backend/memory/embedding/vector-cache.ts +270 -0
- package/backend/memory/extract/episodic.ts +725 -0
- package/backend/memory/extract/index.ts +133 -0
- package/backend/memory/extract/languages.ts +176 -0
- package/backend/memory/extract/scheduler.test.ts +352 -0
- package/backend/memory/extract/scheduler.ts +406 -0
- package/backend/memory/extract/structural.test.ts +215 -0
- package/backend/memory/extract/structural.ts +364 -0
- package/backend/memory/index.ts +37 -0
- package/backend/memory/indexer.ts +150 -0
- package/backend/memory/invalidate.ts +134 -0
- package/backend/memory/judge.ts +285 -0
- package/backend/memory/maintenance.ts +132 -0
- package/backend/memory/model.ts +91 -0
- package/backend/memory/notify.ts +102 -0
- package/backend/memory/readiness.ts +74 -0
- package/backend/memory/redact.test.ts +101 -0
- package/backend/memory/redact.ts +133 -0
- package/backend/memory/retention.ts +139 -0
- package/backend/memory/retrieval.eval.test.ts +301 -0
- package/backend/memory/retrieval.test.ts +1023 -0
- package/backend/memory/retrieval.ts +707 -0
- package/backend/memory/revise.test.ts +693 -0
- package/backend/memory/revise.ts +400 -0
- package/backend/memory/time.ts +31 -0
- package/backend/memory/view.ts +164 -0
- package/backend/shipped-runtime-imports.test.ts +228 -0
- package/backend/ws/index.ts +5 -1
- package/backend/ws/memory/crud.ts +631 -0
- package/backend/ws/memory/index.ts +41 -0
- package/backend/ws/sessions/crud.ts +10 -0
- package/backend/ws/snapshot/content.ts +85 -0
- package/backend/ws/snapshot/index.ts +4 -1
- package/backend/ws/snapshot/restore.ts +38 -4
- package/dist/assets/graph-layout.worker-CRFqN7ZQ.js +1 -0
- package/dist/assets/{index-KBGloYDk.js → index-BCv5HlPk.js} +1 -1
- package/dist/assets/{index-C4PD7B-x.js → index-BTGcf_Vy.js} +1 -1
- package/dist/assets/main-BrqMMMRX.css +1 -0
- package/dist/assets/main-CgmAFpU3.js +1036 -0
- package/dist/index.html +2 -2
- package/package.json +8 -2
- package/shared/types/database/connection.ts +9 -0
- package/shared/types/memory.ts +519 -0
- package/shared/utils/logger.ts +1 -0
- package/dist/assets/main-B0AA-88X.js +0 -622
- package/dist/assets/main-OsjA5Ab5.css +0 -1
- package/shared/utils/anonymous-user.ts +0 -168
|
@@ -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
|
+
};
|