@myrialabs/clopen 0.4.26 → 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/restore.ts +38 -4
- package/dist/assets/graph-layout.worker-CRFqN7ZQ.js +1 -0
- package/dist/assets/{index-B6QGUN03.js → index-BCv5HlPk.js} +1 -1
- package/dist/assets/{index-DYa-GDsb.js → index-BTGcf_Vy.js} +1 -1
- package/dist/assets/main-BrqMMMRX.css +1 -0
- package/dist/assets/{main-Dznkfxsd.js → main-CgmAFpU3.js} +835 -426
- 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-Dh-MTGNR.css +0 -1
- package/shared/utils/anonymous-user.ts +0 -168
|
@@ -0,0 +1,631 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Memory Graph handlers (the Memory modal + Settings → Infrastructure → Memory).
|
|
3
|
+
*
|
|
4
|
+
* - memory:graph — nodes/edges for the visualization, with communities
|
|
5
|
+
* - memory:node — one node plus its neighbourhood, for the inspector
|
|
6
|
+
* - memory:search — hybrid retrieval, the same path agents use
|
|
7
|
+
* - memory:stats — size and composition
|
|
8
|
+
* - memory:save-node — edit a memory's summary, reasoning or kind
|
|
9
|
+
* - memory:draft-node / memory:create-node — write one by hand
|
|
10
|
+
* - memory:archive-node / memory:restore-nodes — "forget" and undo it
|
|
11
|
+
* - memory:forgotten / memory:delete-nodes / memory:purge
|
|
12
|
+
* - memory:status / memory:retry-failed
|
|
13
|
+
* - memory:config / memory:save-config
|
|
14
|
+
*
|
|
15
|
+
* Reads are open to any authenticated user, because the graph is what explains
|
|
16
|
+
* the project to whoever is working on it. Mutations are admin-gated in
|
|
17
|
+
* `backend/auth/permissions.ts`, matching skills / mcp_servers / subagents:
|
|
18
|
+
* memory is instance-global, so one member editing it changes what every agent
|
|
19
|
+
* is told on every future turn.
|
|
20
|
+
*/
|
|
21
|
+
|
|
22
|
+
import { t } from 'elysia';
|
|
23
|
+
import { createRouter, type WSConnection } from '$shared/utils/ws-server';
|
|
24
|
+
import { ws } from '$backend/utils/ws';
|
|
25
|
+
import { projectContextService } from '$backend/mcp/internal/project-context';
|
|
26
|
+
import { debug } from '$shared/utils/logger';
|
|
27
|
+
import { graphQueries } from '$backend/database/queries/graph-queries';
|
|
28
|
+
import { buildGraphView, buildNodeDetail } from '$backend/memory/view';
|
|
29
|
+
import { markConsulted, retrieve } from '$backend/memory/retrieval';
|
|
30
|
+
import { scheduleVectorIndexing } from '$backend/memory/indexer';
|
|
31
|
+
import { getMemoryConfig, setMemoryConfig } from '$backend/memory/config';
|
|
32
|
+
import { notifyGraphChanged, notifyMemoryStatus } from '$backend/memory/notify';
|
|
33
|
+
import { memoryQueueQueries } from '$backend/database/queries/memory-queue-queries';
|
|
34
|
+
import { runningExtractions, startExtractionRunner } from '$backend/memory/extract';
|
|
35
|
+
import { createMemory, draftMemory } from '$backend/memory/compose';
|
|
36
|
+
import { resetGraphEmptiness } from '$backend/memory/context';
|
|
37
|
+
import { getMemoryReadiness } from '$backend/memory/readiness';
|
|
38
|
+
import { reconcileVectorIndex } from '$backend/memory/indexer';
|
|
39
|
+
import { ensureEmbeddingArtifact, embedder, vectorCache } from '$backend/memory/embedding';
|
|
40
|
+
import type { EngineType } from '$shared/types/unified';
|
|
41
|
+
import type { GraphNodeKind, GraphScope, GraphSource } from '$shared/types/memory';
|
|
42
|
+
|
|
43
|
+
const KIND = t.Union([t.Literal('episodic'), t.Literal('structural')]);
|
|
44
|
+
const SCOPE = t.Union([t.Literal('session'), t.Literal('project'), t.Literal('global')]);
|
|
45
|
+
const SOURCE = t.Union([t.Literal('agent'), t.Literal('user')]);
|
|
46
|
+
const EPISODIC_SUBKIND = t.Union([
|
|
47
|
+
t.Literal('decision'),
|
|
48
|
+
t.Literal('pattern'),
|
|
49
|
+
t.Literal('failure'),
|
|
50
|
+
t.Literal('preference'),
|
|
51
|
+
t.Literal('observation'),
|
|
52
|
+
t.Literal('entity')
|
|
53
|
+
]);
|
|
54
|
+
|
|
55
|
+
const NODE = t.Object({
|
|
56
|
+
id: t.String(),
|
|
57
|
+
kind: t.String(),
|
|
58
|
+
subkind: t.String(),
|
|
59
|
+
scope: t.String(),
|
|
60
|
+
projectId: t.Union([t.String(), t.Null()]),
|
|
61
|
+
sessionId: t.Union([t.String(), t.Null()]),
|
|
62
|
+
label: t.String(),
|
|
63
|
+
body: t.String(),
|
|
64
|
+
path: t.Union([t.String(), t.Null()]),
|
|
65
|
+
symbol: t.Union([t.String(), t.Null()]),
|
|
66
|
+
language: t.Union([t.String(), t.Null()]),
|
|
67
|
+
digest: t.String(),
|
|
68
|
+
confidence: t.Number(),
|
|
69
|
+
weight: t.Number(),
|
|
70
|
+
accessCount: t.Number(),
|
|
71
|
+
source: t.String(),
|
|
72
|
+
assertedBy: t.String(),
|
|
73
|
+
reach: t.String(),
|
|
74
|
+
reachJudged: t.Boolean(),
|
|
75
|
+
pinned: t.Boolean(),
|
|
76
|
+
archivedAt: t.Union([t.String(), t.Null()]),
|
|
77
|
+
createdAt: t.String(),
|
|
78
|
+
updatedAt: t.String(),
|
|
79
|
+
accessedAt: t.Union([t.String(), t.Null()]),
|
|
80
|
+
supersededBy: t.Union([t.String(), t.Null()]),
|
|
81
|
+
usefulCount: t.Number(),
|
|
82
|
+
unhelpfulCount: t.Number(),
|
|
83
|
+
staleAt: t.Union([t.String(), t.Null()]),
|
|
84
|
+
entityKey: t.Union([t.String(), t.Null()])
|
|
85
|
+
});
|
|
86
|
+
|
|
87
|
+
const MEMORY_MODEL = t.Object({
|
|
88
|
+
engine: t.String(),
|
|
89
|
+
providerSlug: t.Optional(t.String()),
|
|
90
|
+
modelId: t.String(),
|
|
91
|
+
accountId: t.Optional(t.Number())
|
|
92
|
+
});
|
|
93
|
+
|
|
94
|
+
const CONFIG = t.Object({
|
|
95
|
+
enabled: t.Boolean(),
|
|
96
|
+
recordCode: t.Boolean(),
|
|
97
|
+
recordMemories: t.Boolean(),
|
|
98
|
+
autoRecall: t.Boolean(),
|
|
99
|
+
model: t.Union([MEMORY_MODEL, t.Null()])
|
|
100
|
+
});
|
|
101
|
+
|
|
102
|
+
/** Mirrors `MemoryReadiness`; see backend/memory/readiness.ts for why the two
|
|
103
|
+
* halves have different prerequisites. */
|
|
104
|
+
const READINESS = t.Object({
|
|
105
|
+
enabled: t.Boolean(),
|
|
106
|
+
canRecall: t.Boolean(),
|
|
107
|
+
canRecord: t.Boolean(),
|
|
108
|
+
setupRequired: t.Boolean(),
|
|
109
|
+
blockers: t.Array(t.Union([t.Literal('embedding'), t.Literal('model')])),
|
|
110
|
+
embedding: t.Object({
|
|
111
|
+
ready: t.Boolean(),
|
|
112
|
+
phase: t.Union([
|
|
113
|
+
t.Literal('idle'),
|
|
114
|
+
t.Literal('downloading'),
|
|
115
|
+
t.Literal('installed'),
|
|
116
|
+
t.Literal('waiting'),
|
|
117
|
+
t.Literal('failed')
|
|
118
|
+
]),
|
|
119
|
+
attempts: t.Number(),
|
|
120
|
+
error: t.Union([t.String(), t.Null()]),
|
|
121
|
+
failure: t.Union([
|
|
122
|
+
t.Literal('network'),
|
|
123
|
+
t.Literal('corrupt'),
|
|
124
|
+
t.Literal('unpublished'),
|
|
125
|
+
t.Null()
|
|
126
|
+
]),
|
|
127
|
+
permanent: t.Boolean(),
|
|
128
|
+
nextAttemptAt: t.Union([t.String(), t.Null()]),
|
|
129
|
+
receivedBytes: t.Number(),
|
|
130
|
+
totalBytes: t.Number()
|
|
131
|
+
}),
|
|
132
|
+
model: t.Object({
|
|
133
|
+
configured: t.Boolean(),
|
|
134
|
+
engine: t.Union([t.String(), t.Null()]),
|
|
135
|
+
modelId: t.Union([t.String(), t.Null()])
|
|
136
|
+
})
|
|
137
|
+
});
|
|
138
|
+
|
|
139
|
+
/**
|
|
140
|
+
* How the modal's project multi-select reaches a query.
|
|
141
|
+
*
|
|
142
|
+
* `projectIds` is tri-state on the wire and each state means something
|
|
143
|
+
* different: ABSENT is "every project" (the cross-project view), an EMPTY array
|
|
144
|
+
* is "global only" — nothing selected is a narrowing, not the absence of one —
|
|
145
|
+
* and a non-empty array is those projects plus the globals that apply inside
|
|
146
|
+
* every one of them.
|
|
147
|
+
*
|
|
148
|
+
* Cross-project is admin-only. Reads are otherwise open, because the graph is
|
|
149
|
+
* what explains a project to whoever is working on it and withholding that would
|
|
150
|
+
* defeat the feature. But "every project at once" is a different request: memory
|
|
151
|
+
* is instance-global, so it would show a member everything every other team has
|
|
152
|
+
* ever worked on, including repositories they have no access to. Narrowing to
|
|
153
|
+
* the caller's current project is the honest degradation — they still see
|
|
154
|
+
* everything that applies where they are, plus the globals.
|
|
155
|
+
*
|
|
156
|
+
* Mutations are gated separately, in `backend/auth/permissions.ts`.
|
|
157
|
+
*/
|
|
158
|
+
function scopeForRole(conn: WSConnection, requested: string[] | undefined): string[] | undefined {
|
|
159
|
+
if (requested !== undefined) return requested;
|
|
160
|
+
if (ws.getRole(conn) === 'admin') return undefined;
|
|
161
|
+
|
|
162
|
+
const current = projectContextService.getCurrentProjectId();
|
|
163
|
+
debug.log('path', 'memory: cross-project read narrowed to current project (not admin)');
|
|
164
|
+
// No project selected and not an admin: global-scope memories only, which an
|
|
165
|
+
// empty selection already means.
|
|
166
|
+
return current ? [current] : [];
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
export const memoryCrudHandler = createRouter()
|
|
170
|
+
.http('memory:graph', {
|
|
171
|
+
data: t.Object({
|
|
172
|
+
projectIds: t.Optional(t.Array(t.String())),
|
|
173
|
+
kinds: t.Optional(t.Array(KIND)),
|
|
174
|
+
subkinds: t.Optional(t.Array(t.String())),
|
|
175
|
+
scopes: t.Optional(t.Array(SCOPE)),
|
|
176
|
+
sources: t.Optional(t.Array(SOURCE)),
|
|
177
|
+
includeArchived: t.Optional(t.Boolean()),
|
|
178
|
+
includeSuperseded: t.Optional(t.Boolean()),
|
|
179
|
+
limit: t.Optional(t.Number())
|
|
180
|
+
}),
|
|
181
|
+
response: t.Object({
|
|
182
|
+
nodes: t.Array(t.Object({
|
|
183
|
+
id: t.String(),
|
|
184
|
+
kind: t.String(),
|
|
185
|
+
subkind: t.String(),
|
|
186
|
+
scope: t.String(),
|
|
187
|
+
label: t.String(),
|
|
188
|
+
projectId: t.Union([t.String(), t.Null()]),
|
|
189
|
+
degree: t.Number(),
|
|
190
|
+
weight: t.Number(),
|
|
191
|
+
pinned: t.Boolean(),
|
|
192
|
+
community: t.Number(),
|
|
193
|
+
createdAt: t.String()
|
|
194
|
+
})),
|
|
195
|
+
edges: t.Array(t.Object({
|
|
196
|
+
id: t.Number(),
|
|
197
|
+
source: t.String(),
|
|
198
|
+
target: t.String(),
|
|
199
|
+
rel: t.String(),
|
|
200
|
+
weight: t.Number()
|
|
201
|
+
})),
|
|
202
|
+
totalNodes: t.Number(),
|
|
203
|
+
truncated: t.Boolean()
|
|
204
|
+
})
|
|
205
|
+
}, async ({ conn, data }) => {
|
|
206
|
+
debug.log('path', 'memory:graph');
|
|
207
|
+
return buildGraphView({
|
|
208
|
+
projectIds: scopeForRole(conn, data.projectIds),
|
|
209
|
+
kinds: data.kinds as GraphNodeKind[] | undefined,
|
|
210
|
+
subkinds: data.subkinds,
|
|
211
|
+
scopes: data.scopes as GraphScope[] | undefined,
|
|
212
|
+
sources: data.sources as GraphSource[] | undefined,
|
|
213
|
+
includeArchived: data.includeArchived,
|
|
214
|
+
includeSuperseded: data.includeSuperseded,
|
|
215
|
+
limit: data.limit
|
|
216
|
+
});
|
|
217
|
+
})
|
|
218
|
+
.http('memory:node', {
|
|
219
|
+
data: t.Object({ nodeId: t.String(), hops: t.Optional(t.Number()) }),
|
|
220
|
+
response: t.Object({
|
|
221
|
+
node: t.Union([NODE, t.Null()]),
|
|
222
|
+
neighbours: t.Array(t.Object({ node: NODE, hops: t.Number() }))
|
|
223
|
+
})
|
|
224
|
+
}, async ({ data }) => {
|
|
225
|
+
debug.log('path', `memory:node ${data.nodeId}`);
|
|
226
|
+
const detail = buildNodeDetail(data.nodeId, data.hops ?? 1);
|
|
227
|
+
return detail ?? { node: null, neighbours: [] };
|
|
228
|
+
})
|
|
229
|
+
.http('memory:search', {
|
|
230
|
+
data: t.Object({
|
|
231
|
+
query: t.String(),
|
|
232
|
+
projectIds: t.Optional(t.Array(t.String())),
|
|
233
|
+
kinds: t.Optional(t.Array(KIND)),
|
|
234
|
+
subkinds: t.Optional(t.Array(t.String())),
|
|
235
|
+
sources: t.Optional(t.Array(SOURCE)),
|
|
236
|
+
limit: t.Optional(t.Number()),
|
|
237
|
+
includeArchived: t.Optional(t.Boolean()),
|
|
238
|
+
includeSuperseded: t.Optional(t.Boolean())
|
|
239
|
+
}),
|
|
240
|
+
response: t.Object({
|
|
241
|
+
hits: t.Array(t.Object({
|
|
242
|
+
node: NODE,
|
|
243
|
+
score: t.Number(),
|
|
244
|
+
channel: t.String(),
|
|
245
|
+
lexicalRank: t.Union([t.Number(), t.Null()]),
|
|
246
|
+
vectorRank: t.Union([t.Number(), t.Null()]),
|
|
247
|
+
hops: t.Number(),
|
|
248
|
+
snippet: t.Union([t.String(), t.Null()])
|
|
249
|
+
})),
|
|
250
|
+
vectorUsed: t.Boolean(),
|
|
251
|
+
elapsedMs: t.Number(),
|
|
252
|
+
profile: t.Object({
|
|
253
|
+
shape: t.String(),
|
|
254
|
+
lexicalWeight: t.Number(),
|
|
255
|
+
vectorWeight: t.Number()
|
|
256
|
+
})
|
|
257
|
+
})
|
|
258
|
+
}, async ({ conn, data }) => {
|
|
259
|
+
debug.log('path', 'memory:search');
|
|
260
|
+
const result = retrieve({
|
|
261
|
+
query: data.query,
|
|
262
|
+
projectIds: scopeForRole(conn, data.projectIds),
|
|
263
|
+
kinds: data.kinds as GraphNodeKind[] | undefined,
|
|
264
|
+
subkinds: data.subkinds,
|
|
265
|
+
sources: data.sources as GraphSource[] | undefined,
|
|
266
|
+
limit: data.limit ?? 20,
|
|
267
|
+
includeArchived: data.includeArchived,
|
|
268
|
+
includeSuperseded: data.includeSuperseded,
|
|
269
|
+
// A typed query is answered with what MATCHES it, not with what matches
|
|
270
|
+
// it plus everything one edge away. Expansion is right for turn-start
|
|
271
|
+
// injection — the useful memory is often adjacent to the match — and
|
|
272
|
+
// wrong here: a user searching "phoenix" was being shown memories about
|
|
273
|
+
// calculators, because a neighbour of a neighbour had been dragged in.
|
|
274
|
+
expandHops: 0,
|
|
275
|
+
// And the vector channel has to earn its rows rather than admit any
|
|
276
|
+
// positive cosine. See `RetrievalOptions.precise`.
|
|
277
|
+
precise: true
|
|
278
|
+
});
|
|
279
|
+
// A person typing a query is deliberately consulting memory, so it counts —
|
|
280
|
+
// unlike the automatic turn-start injection, which retrieves on every turn
|
|
281
|
+
// and would otherwise be measuring itself.
|
|
282
|
+
markConsulted(result.hits);
|
|
283
|
+
return result;
|
|
284
|
+
})
|
|
285
|
+
.http('memory:stats', {
|
|
286
|
+
data: t.Object({}),
|
|
287
|
+
response: t.Object({
|
|
288
|
+
nodes: t.Number(),
|
|
289
|
+
edges: t.Number(),
|
|
290
|
+
episodic: t.Number(),
|
|
291
|
+
structural: t.Number(),
|
|
292
|
+
vectors: t.Number(),
|
|
293
|
+
byScope: t.Object({ session: t.Number(), project: t.Number(), global: t.Number() }),
|
|
294
|
+
byProject: t.Array(t.Object({ projectId: t.Union([t.String(), t.Null()]), count: t.Number() })),
|
|
295
|
+
superseded: t.Number(),
|
|
296
|
+
stale: t.Number(),
|
|
297
|
+
entities: t.Number(),
|
|
298
|
+
confirmedUseful: t.Number(),
|
|
299
|
+
forgotten: t.Number(),
|
|
300
|
+
embedding: t.Object({
|
|
301
|
+
ready: t.Boolean(),
|
|
302
|
+
installed: t.Boolean(),
|
|
303
|
+
version: t.Union([t.String(), t.Null()]),
|
|
304
|
+
dim: t.Union([t.Number(), t.Null()]),
|
|
305
|
+
rows: t.Union([t.Number(), t.Null()]),
|
|
306
|
+
error: t.Union([t.String(), t.Null()])
|
|
307
|
+
})
|
|
308
|
+
})
|
|
309
|
+
}, async () => {
|
|
310
|
+
debug.log('path', 'memory:stats');
|
|
311
|
+
return { ...graphQueries.stats(), embedding: embedder.status() };
|
|
312
|
+
})
|
|
313
|
+
.http('memory:save-node', {
|
|
314
|
+
data: t.Object({
|
|
315
|
+
nodeId: t.String(),
|
|
316
|
+
label: t.Optional(t.String()),
|
|
317
|
+
body: t.Optional(t.String()),
|
|
318
|
+
subkind: t.Optional(t.String())
|
|
319
|
+
}),
|
|
320
|
+
response: t.Object({ node: t.Union([NODE, t.Null()]) })
|
|
321
|
+
}, async ({ data }) => {
|
|
322
|
+
debug.log('path', `memory:save-node ${data.nodeId}`);
|
|
323
|
+
const node = graphQueries.update(
|
|
324
|
+
data.nodeId,
|
|
325
|
+
{
|
|
326
|
+
...(data.label !== undefined && { label: data.label }),
|
|
327
|
+
...(data.body !== undefined && { body: data.body }),
|
|
328
|
+
...(data.subkind !== undefined && { subkind: data.subkind as never })
|
|
329
|
+
},
|
|
330
|
+
// A person typed this, which is what exempts the node from decay and from
|
|
331
|
+
// every automatic removal.
|
|
332
|
+
'user'
|
|
333
|
+
);
|
|
334
|
+
// The edit changed the text a vector describes, so `update` dropped it —
|
|
335
|
+
// ask for a fresh one rather than leaving the node semantically stale.
|
|
336
|
+
if (node) {
|
|
337
|
+
vectorCache.drop([node.id]);
|
|
338
|
+
scheduleVectorIndexing();
|
|
339
|
+
notifyGraphChanged('edited', node.projectId);
|
|
340
|
+
}
|
|
341
|
+
return { node };
|
|
342
|
+
})
|
|
343
|
+
.http('memory:archive-node', {
|
|
344
|
+
data: t.Object({ nodeId: t.String() }),
|
|
345
|
+
response: t.Object({ success: t.Boolean() })
|
|
346
|
+
}, async ({ data }) => {
|
|
347
|
+
debug.log('path', `memory:archive-node ${data.nodeId}`);
|
|
348
|
+
graphQueries.archive(data.nodeId);
|
|
349
|
+
resetGraphEmptiness();
|
|
350
|
+
notifyGraphChanged('forgotten');
|
|
351
|
+
return { success: true };
|
|
352
|
+
})
|
|
353
|
+
/**
|
|
354
|
+
* Bring memories back into recall — one, or a selection.
|
|
355
|
+
*
|
|
356
|
+
* Restores BOTH kinds of "no longer recalled". Archiving says "this was never
|
|
357
|
+
* true"; superseding says "something newer replaced it", and that second
|
|
358
|
+
* judgement was made automatically, by a model reading a transcript. Leaving
|
|
359
|
+
* it as the one thing the user could not undo would have meant their only
|
|
360
|
+
* recourse against a wrong revision was permanent deletion — which is how
|
|
361
|
+
* "reversible" ends up being a property of the schema rather than of the
|
|
362
|
+
* product.
|
|
363
|
+
*/
|
|
364
|
+
.http('memory:restore-nodes', {
|
|
365
|
+
data: t.Object({ nodeIds: t.Array(t.String()) }),
|
|
366
|
+
response: t.Object({ restored: t.Number() })
|
|
367
|
+
}, async ({ data }) => {
|
|
368
|
+
debug.log('path', `memory:restore-nodes (${data.nodeIds.length})`);
|
|
369
|
+
const restored = graphQueries.restoreNodes(data.nodeIds);
|
|
370
|
+
if (restored > 0) {
|
|
371
|
+
scheduleVectorIndexing();
|
|
372
|
+
resetGraphEmptiness();
|
|
373
|
+
notifyGraphChanged('restored');
|
|
374
|
+
}
|
|
375
|
+
return { restored };
|
|
376
|
+
})
|
|
377
|
+
/**
|
|
378
|
+
* Shape free text into a memory, for review before anything is stored.
|
|
379
|
+
*
|
|
380
|
+
* Returns a draft rather than saving, because what the user types is one field
|
|
381
|
+
* and what the graph stores is six. Filling the other five without showing the
|
|
382
|
+
* result would mean a store whose contents nobody had read — and this is the
|
|
383
|
+
* one write path where a person is present to read them.
|
|
384
|
+
*/
|
|
385
|
+
.http('memory:draft-node', {
|
|
386
|
+
data: t.Object({
|
|
387
|
+
text: t.String(),
|
|
388
|
+
projectId: t.Optional(t.String()),
|
|
389
|
+
/** False to skip the model entirely and keep the text as written. */
|
|
390
|
+
structure: t.Optional(t.Boolean())
|
|
391
|
+
}),
|
|
392
|
+
response: t.Object({
|
|
393
|
+
draft: t.Union([
|
|
394
|
+
t.Object({
|
|
395
|
+
subkind: t.String(),
|
|
396
|
+
scope: t.String(),
|
|
397
|
+
label: t.String(),
|
|
398
|
+
body: t.String(),
|
|
399
|
+
entities: t.Array(t.String()),
|
|
400
|
+
relatedPaths: t.Array(t.String()),
|
|
401
|
+
structured: t.Boolean(),
|
|
402
|
+
duplicateOf: t.Union([
|
|
403
|
+
t.Object({ id: t.String(), label: t.String(), score: t.Number() }),
|
|
404
|
+
t.Null()
|
|
405
|
+
]),
|
|
406
|
+
note: t.Union([t.String(), t.Null()])
|
|
407
|
+
}),
|
|
408
|
+
t.Null()
|
|
409
|
+
])
|
|
410
|
+
})
|
|
411
|
+
}, async ({ data }) => {
|
|
412
|
+
debug.log('path', 'memory:draft-node');
|
|
413
|
+
const draft = await draftMemory({
|
|
414
|
+
text: data.text,
|
|
415
|
+
projectId: data.projectId || projectContextService.getCurrentProjectId(),
|
|
416
|
+
...(data.structure !== undefined && { structure: data.structure })
|
|
417
|
+
});
|
|
418
|
+
return { draft };
|
|
419
|
+
})
|
|
420
|
+
/** Store a reviewed draft. Always `source: 'user'`. */
|
|
421
|
+
.http('memory:create-node', {
|
|
422
|
+
data: t.Object({
|
|
423
|
+
subkind: EPISODIC_SUBKIND,
|
|
424
|
+
scope: t.Union([t.Literal('project'), t.Literal('global')]),
|
|
425
|
+
label: t.String(),
|
|
426
|
+
body: t.String(),
|
|
427
|
+
entities: t.Optional(t.Array(t.String())),
|
|
428
|
+
relatedPaths: t.Optional(t.Array(t.String())),
|
|
429
|
+
projectId: t.Optional(t.String()),
|
|
430
|
+
pinned: t.Optional(t.Boolean()),
|
|
431
|
+
reinforceId: t.Optional(t.String())
|
|
432
|
+
}),
|
|
433
|
+
response: t.Object({ node: t.Union([NODE, t.Null()]) })
|
|
434
|
+
}, async ({ data }) => {
|
|
435
|
+
debug.log('path', 'memory:create-node');
|
|
436
|
+
const node = createMemory({
|
|
437
|
+
subkind: data.subkind,
|
|
438
|
+
scope: data.scope,
|
|
439
|
+
label: data.label,
|
|
440
|
+
body: data.body,
|
|
441
|
+
entities: data.entities ?? [],
|
|
442
|
+
relatedPaths: data.relatedPaths ?? [],
|
|
443
|
+
projectId: data.projectId || projectContextService.getCurrentProjectId(),
|
|
444
|
+
pinned: data.pinned ?? false,
|
|
445
|
+
reinforceId: data.reinforceId ?? null
|
|
446
|
+
});
|
|
447
|
+
return { node };
|
|
448
|
+
})
|
|
449
|
+
|
|
450
|
+
|
|
451
|
+
|
|
452
|
+
/**
|
|
453
|
+
* The forgotten list: memories that have been archived or superseded.
|
|
454
|
+
*
|
|
455
|
+
* Soft delete was always meant to be reviewable, but with nothing to review it
|
|
456
|
+
* with, "reversible" was a property of the schema rather than of the product.
|
|
457
|
+
* Archived and superseded are shown together because from here they are one
|
|
458
|
+
* category — "no longer recalled" — even though the graph keeps the distinction
|
|
459
|
+
* between "was never true" and "is no longer true", which the row still states.
|
|
460
|
+
*/
|
|
461
|
+
/**
|
|
462
|
+
* What the extraction queue is doing.
|
|
463
|
+
*
|
|
464
|
+
* Open to any member, because it answers "is memory working right now", and a
|
|
465
|
+
* user watching the graph fail to grow deserves an answer whether or not they
|
|
466
|
+
* can change the setting that fixes it.
|
|
467
|
+
*/
|
|
468
|
+
.http('memory:status', {
|
|
469
|
+
data: t.Object({}),
|
|
470
|
+
response: t.Object({
|
|
471
|
+
pending: t.Number(),
|
|
472
|
+
retrying: t.Number(),
|
|
473
|
+
failed: t.Number(),
|
|
474
|
+
running: t.Number(),
|
|
475
|
+
nextAttemptAt: t.Union([t.String(), t.Null()]),
|
|
476
|
+
lastError: t.Union([t.String(), t.Null()]),
|
|
477
|
+
modelConfigured: t.Boolean()
|
|
478
|
+
})
|
|
479
|
+
}, async () => {
|
|
480
|
+
return {
|
|
481
|
+
...memoryQueueQueries.status(),
|
|
482
|
+
running: runningExtractions(),
|
|
483
|
+
modelConfigured: getMemoryConfig().model !== null
|
|
484
|
+
};
|
|
485
|
+
})
|
|
486
|
+
/**
|
|
487
|
+
* Whether memory can actually recall and record, and what is missing.
|
|
488
|
+
*
|
|
489
|
+
* Separate from `memory:status`, which reports the extraction QUEUE. This one
|
|
490
|
+
* answers "is the feature usable at all", which is what the setup banner needs
|
|
491
|
+
* and what nothing could answer before: a user whose artifact never downloaded
|
|
492
|
+
* saw an empty graph and no explanation for it.
|
|
493
|
+
*/
|
|
494
|
+
.http('memory:readiness', {
|
|
495
|
+
data: t.Object({}),
|
|
496
|
+
response: READINESS
|
|
497
|
+
}, async () => {
|
|
498
|
+
return getMemoryReadiness();
|
|
499
|
+
})
|
|
500
|
+
/**
|
|
501
|
+
* Install the embedding artifact now.
|
|
502
|
+
*
|
|
503
|
+
* Forces a restart of a schedule that has given up — a checksum mismatch and an
|
|
504
|
+
* unpublished release both stop deliberately, and a user who has fixed either
|
|
505
|
+
* (upgraded, or come back online after a proxy mangled the download) has no
|
|
506
|
+
* other way to say so.
|
|
507
|
+
*/
|
|
508
|
+
.http('memory:install-embedding', {
|
|
509
|
+
data: t.Object({}),
|
|
510
|
+
response: READINESS
|
|
511
|
+
}, async () => {
|
|
512
|
+
debug.log('memory', 'Embedding artifact install requested');
|
|
513
|
+
await ensureEmbeddingArtifact(true);
|
|
514
|
+
// Vectors for everything recorded while recall was unavailable.
|
|
515
|
+
if (embedder.status().ready) void reconcileVectorIndex();
|
|
516
|
+
return getMemoryReadiness();
|
|
517
|
+
})
|
|
518
|
+
/**
|
|
519
|
+
* Put every failed extraction back in the queue.
|
|
520
|
+
*
|
|
521
|
+
* Exists because the usual cause of exhaustion is something the user has just
|
|
522
|
+
* fixed — chosen a model, re-authenticated an account, restarted an engine —
|
|
523
|
+
* and waiting for a server restart to find that out is a poor answer.
|
|
524
|
+
*/
|
|
525
|
+
.http('memory:retry-failed', {
|
|
526
|
+
data: t.Object({}),
|
|
527
|
+
response: t.Object({ requeued: t.Number() })
|
|
528
|
+
}, async () => {
|
|
529
|
+
const requeued = memoryQueueQueries.retryFailed();
|
|
530
|
+
debug.log('memory', `Re-queued ${requeued} failed extraction(s) on request`);
|
|
531
|
+
if (requeued > 0) {
|
|
532
|
+
startExtractionRunner();
|
|
533
|
+
notifyMemoryStatus();
|
|
534
|
+
}
|
|
535
|
+
return { requeued };
|
|
536
|
+
})
|
|
537
|
+
.http('memory:forgotten', {
|
|
538
|
+
data: t.Object({
|
|
539
|
+
projectIds: t.Optional(t.Array(t.String())),
|
|
540
|
+
limit: t.Optional(t.Number()),
|
|
541
|
+
offset: t.Optional(t.Number())
|
|
542
|
+
}),
|
|
543
|
+
response: t.Object({
|
|
544
|
+
nodes: t.Array(NODE),
|
|
545
|
+
total: t.Number()
|
|
546
|
+
})
|
|
547
|
+
}, async ({ conn, data }) => {
|
|
548
|
+
debug.log('path', 'memory:forgotten');
|
|
549
|
+
const projectIds = scopeForRole(conn, data.projectIds);
|
|
550
|
+
return {
|
|
551
|
+
nodes: graphQueries.listArchived({
|
|
552
|
+
projectIds,
|
|
553
|
+
limit: Math.min(data.limit ?? 200, 500),
|
|
554
|
+
offset: data.offset ?? 0
|
|
555
|
+
}),
|
|
556
|
+
total: graphQueries.countArchived({ projectIds })
|
|
557
|
+
};
|
|
558
|
+
})
|
|
559
|
+
/**
|
|
560
|
+
* Permanently delete specific memories. Reached only from the forgotten list,
|
|
561
|
+
* so everything it touches has already been archived once — two deliberate
|
|
562
|
+
* decisions rather than one.
|
|
563
|
+
*/
|
|
564
|
+
.http('memory:delete-nodes', {
|
|
565
|
+
data: t.Object({ nodeIds: t.Array(t.String()) }),
|
|
566
|
+
response: t.Object({ deleted: t.Number() })
|
|
567
|
+
}, async ({ data }) => {
|
|
568
|
+
debug.log('path', `memory:delete-nodes (${data.nodeIds.length})`);
|
|
569
|
+
const deleted = graphQueries.deleteNodes(data.nodeIds);
|
|
570
|
+
if (deleted > 0) {
|
|
571
|
+
vectorCache.drop(data.nodeIds);
|
|
572
|
+
resetGraphEmptiness();
|
|
573
|
+
notifyGraphChanged('deleted');
|
|
574
|
+
}
|
|
575
|
+
return { deleted };
|
|
576
|
+
})
|
|
577
|
+
/**
|
|
578
|
+
* Delete every memory in one project, or in the whole instance.
|
|
579
|
+
*
|
|
580
|
+
* `projectIds` absent means EVERYTHING, including the global memories that
|
|
581
|
+
* belong to the user rather than to any repository — which is why the two are
|
|
582
|
+
* separate actions in the UI rather than one control with a checkbox. A project
|
|
583
|
+
* purge deliberately leaves globals alone: preferences and conventions were
|
|
584
|
+
* never that project's to hold.
|
|
585
|
+
*/
|
|
586
|
+
.http('memory:purge', {
|
|
587
|
+
data: t.Object({ projectIds: t.Optional(t.Array(t.String())) }),
|
|
588
|
+
response: t.Object({ nodes: t.Number(), edges: t.Number() })
|
|
589
|
+
}, async ({ data }) => {
|
|
590
|
+
debug.log(
|
|
591
|
+
'path',
|
|
592
|
+
`memory:purge ${data.projectIds === undefined ? 'EVERYTHING' : `${data.projectIds.length} project(s)`}`
|
|
593
|
+
);
|
|
594
|
+
|
|
595
|
+
const result = graphQueries.purge(data.projectIds);
|
|
596
|
+
// The cache is holding vectors for rows that no longer exist, and injection
|
|
597
|
+
// may now be looking at an empty graph.
|
|
598
|
+
vectorCache.reset();
|
|
599
|
+
resetGraphEmptiness();
|
|
600
|
+
notifyGraphChanged('purged', data.projectIds?.[0] ?? null);
|
|
601
|
+
debug.log('memory', `Purged ${result.nodes} node(s) and ${result.edges} edge(s)`);
|
|
602
|
+
return result;
|
|
603
|
+
})
|
|
604
|
+
.http('memory:config', {
|
|
605
|
+
data: t.Object({}),
|
|
606
|
+
response: CONFIG
|
|
607
|
+
}, async () => {
|
|
608
|
+
debug.log('path', 'memory:config');
|
|
609
|
+
return getMemoryConfig();
|
|
610
|
+
})
|
|
611
|
+
.http('memory:save-config', {
|
|
612
|
+
data: t.Object({
|
|
613
|
+
enabled: t.Optional(t.Boolean()),
|
|
614
|
+
recordCode: t.Optional(t.Boolean()),
|
|
615
|
+
recordMemories: t.Optional(t.Boolean()),
|
|
616
|
+
autoRecall: t.Optional(t.Boolean()),
|
|
617
|
+
model: t.Optional(t.Union([MEMORY_MODEL, t.Null()]))
|
|
618
|
+
}),
|
|
619
|
+
response: CONFIG
|
|
620
|
+
}, async ({ data }) => {
|
|
621
|
+
debug.log('path', 'memory:save-config');
|
|
622
|
+
return setMemoryConfig({
|
|
623
|
+
...(data.enabled !== undefined && { enabled: data.enabled }),
|
|
624
|
+
...(data.recordCode !== undefined && { recordCode: data.recordCode }),
|
|
625
|
+
...(data.recordMemories !== undefined && { recordMemories: data.recordMemories }),
|
|
626
|
+
...(data.autoRecall !== undefined && { autoRecall: data.autoRecall }),
|
|
627
|
+
...(data.model !== undefined && {
|
|
628
|
+
model: data.model ? { ...data.model, engine: data.model.engine as EngineType } : null
|
|
629
|
+
})
|
|
630
|
+
});
|
|
631
|
+
});
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Memory Router — the Memory Graph panel and Settings → Infrastructure → Memory.
|
|
3
|
+
*/
|
|
4
|
+
|
|
5
|
+
import { t } from 'elysia';
|
|
6
|
+
import { createRouter } from '$shared/utils/ws-server';
|
|
7
|
+
import { memoryCrudHandler } from './crud';
|
|
8
|
+
|
|
9
|
+
export const memoryRouter = createRouter()
|
|
10
|
+
/**
|
|
11
|
+
* The graph changed. Broadcast globally rather than per session, because the
|
|
12
|
+
* memory graph is instance-wide: a memory written by one member's chat is
|
|
13
|
+
* immediately part of what every other member's Memory view is showing.
|
|
14
|
+
*
|
|
15
|
+
* The payload deliberately carries no data, only a reason. Diffing the graph
|
|
16
|
+
* over the wire would mean a second serialization format to keep in step with
|
|
17
|
+
* `memory:graph`, and the view refetches in a few milliseconds anyway — this
|
|
18
|
+
* is a doorbell, not a delivery.
|
|
19
|
+
*/
|
|
20
|
+
.emit('memory:changed', t.Object({
|
|
21
|
+
reason: t.String(),
|
|
22
|
+
projectId: t.Union([t.String(), t.Null()])
|
|
23
|
+
}))
|
|
24
|
+
/**
|
|
25
|
+
* The extraction queue moved: something was enqueued, retried, or gave up.
|
|
26
|
+
*
|
|
27
|
+
* Separate from `memory:changed` because a queue event frequently means NOTHING
|
|
28
|
+
* was written — a model failed, or none is configured — which is precisely the
|
|
29
|
+
* situation where a silent UI is worst.
|
|
30
|
+
*/
|
|
31
|
+
.emit('memory:status-changed', t.Object({}))
|
|
32
|
+
/**
|
|
33
|
+
* Setup progressed: the embedding artifact started downloading, landed or
|
|
34
|
+
* failed, or an extraction model was chosen.
|
|
35
|
+
*
|
|
36
|
+
* Distinct from the queue event because it answers "is memory usable at all"
|
|
37
|
+
* rather than "is there work outstanding". The setup banner listens to this one
|
|
38
|
+
* and to nothing else, so a busy extraction queue cannot make it flicker.
|
|
39
|
+
*/
|
|
40
|
+
.emit('memory:readiness-changed', t.Object({}))
|
|
41
|
+
.merge(memoryCrudHandler);
|
|
@@ -19,6 +19,8 @@ import { ws } from '$backend/utils/ws';
|
|
|
19
19
|
import { streamManager } from '../../chat/stream-manager';
|
|
20
20
|
import { snapshotService } from '../../snapshot/snapshot-service';
|
|
21
21
|
import { blobStore } from '../../snapshot/blob-store';
|
|
22
|
+
import { cancelEpisodicIngest } from '../../memory/extract';
|
|
23
|
+
import { forgetSessionContext } from '../../memory/context';
|
|
22
24
|
import { broadcastPresence } from '../projects/status';
|
|
23
25
|
import { debug } from '$shared/utils/logger';
|
|
24
26
|
import { requireCurrentProjectAccess, requireProjectAccess, requireSessionAccess } from '../access';
|
|
@@ -254,6 +256,12 @@ export const crudHandler = createRouter()
|
|
|
254
256
|
// Clear in-memory snapshot baseline
|
|
255
257
|
snapshotService.clearSessionBaseline(data.id);
|
|
256
258
|
|
|
259
|
+
// Drop any memory extraction parked for this session. It reads the message
|
|
260
|
+
// chain, which is about to be deleted, and its injection bookkeeping is now
|
|
261
|
+
// about a session that no longer exists.
|
|
262
|
+
cancelEpisodicIngest(data.id);
|
|
263
|
+
forgetSessionContext(data.id);
|
|
264
|
+
|
|
257
265
|
// Delete session and all related DB data (messages, snapshots, branches, relationships, unread)
|
|
258
266
|
sessionQueries.delete(data.id);
|
|
259
267
|
|
|
@@ -329,6 +337,8 @@ export const crudHandler = createRouter()
|
|
|
329
337
|
// Clear in-memory snapshot baselines for all sessions
|
|
330
338
|
for (const s of sessions) {
|
|
331
339
|
snapshotService.clearSessionBaseline(s.id);
|
|
340
|
+
cancelEpisodicIngest(s.id);
|
|
341
|
+
forgetSessionContext(s.id);
|
|
332
342
|
}
|
|
333
343
|
|
|
334
344
|
// Delete all sessions and related DB data (messages, snapshots, branches, relationships, unread)
|