@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,406 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* When episodic extraction runs, and what happens when it does not.
|
|
3
|
+
*
|
|
4
|
+
* ── why it no longer waits ──
|
|
5
|
+
* Extraction calls a model through the SAME engine the user is chatting with, so
|
|
6
|
+
* on a shared-process engine that request competes with the next chat turn. That
|
|
7
|
+
* used to buy six seconds of enforced quiet before a summary could start.
|
|
8
|
+
*
|
|
9
|
+
* The trade was priced wrong. What the delay bought was a slightly shorter queue;
|
|
10
|
+
* what it cost was that a memory did not exist until six seconds after the turn
|
|
11
|
+
* that produced it — an agent could not read back what had just been established,
|
|
12
|
+
* the graph visibly lagged the conversation it was meant to be following, and a
|
|
13
|
+
* session where the user kept typing deferred its own extraction indefinitely.
|
|
14
|
+
* Waiting to avoid a queue is only worth it when somebody is waiting on the
|
|
15
|
+
* queue, and nobody is waiting on this one.
|
|
16
|
+
*
|
|
17
|
+
* So a finished turn is summarised NOW. The only thing that still holds it back
|
|
18
|
+
* is an ACTIVE stream — a summary generated mid-answer competes with the answer —
|
|
19
|
+
* and even that is bounded by MAX_DEFER_SECONDS, so a session that never goes
|
|
20
|
+
* quiet is summarised anyway instead of accumulating a span longer than the
|
|
21
|
+
* transcript budget can carry.
|
|
22
|
+
*
|
|
23
|
+
* ── why the queue is a TABLE ──
|
|
24
|
+
* It used to be a `Map` in this module, which lost a turn's memories silently in
|
|
25
|
+
* three different ways: a failed model call was caught, logged and dropped with no
|
|
26
|
+
* second attempt; a restart discarded everything parked; and none of it was
|
|
27
|
+
* visible, so memory simply did not grow and the only explanation was in the
|
|
28
|
+
* server log. Extraction is the sole write path for the whole feature, which makes
|
|
29
|
+
* "it failed once and gave up" an unusually expensive default.
|
|
30
|
+
*
|
|
31
|
+
* Now it is `memory_extraction_queue` (migration 066). A failure schedules a
|
|
32
|
+
* retry with exponential backoff, exhausting the attempts marks the row FAILED
|
|
33
|
+
* rather than deleting it, and startup puts failed rows back — because the usual
|
|
34
|
+
* causes (no model configured, an expired account, an engine that was down) are
|
|
35
|
+
* exactly the kind of thing that a restart means someone has just changed.
|
|
36
|
+
*
|
|
37
|
+
* ── what is banked ──
|
|
38
|
+
* ONE ROW PER SESSION, holding the OLDEST turn boundary not yet summarised. The
|
|
39
|
+
* transcript runs from that message to the end of the chain, so one extraction
|
|
40
|
+
* covers every turn since. Keeping the newest, as the original did, silently
|
|
41
|
+
* discarded everything in between.
|
|
42
|
+
*
|
|
43
|
+
* That merge now has a race to answer for, because extraction runs immediately: a
|
|
44
|
+
* turn can finish while the previous one is still being read, and it merges into
|
|
45
|
+
* the row already in flight. The runner therefore claims a REVISION and its
|
|
46
|
+
* delete is conditional on it, so the merged-in turn is never thrown away with
|
|
47
|
+
* the one that succeeded.
|
|
48
|
+
*
|
|
49
|
+
* Structural extraction is NOT queued — it reads the disk diff, touches no model,
|
|
50
|
+
* costs microseconds, and its nodes should be searchable at once.
|
|
51
|
+
*/
|
|
52
|
+
|
|
53
|
+
import { memoryQueueQueries, type QueuedExtraction } from '$backend/database/queries/memory-queue-queries';
|
|
54
|
+
import { debug } from '$shared/utils/logger';
|
|
55
|
+
import { ingestEpisodicMemories, type EpisodicIngestInput } from './episodic';
|
|
56
|
+
import { scheduleVectorIndexing } from '../indexer';
|
|
57
|
+
import { notifyGraphChanged, notifyMemoryStatus } from '../notify';
|
|
58
|
+
import { resetGraphEmptiness } from '../context';
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* Delay between a turn finishing and its summary starting. Zero: a finished turn
|
|
62
|
+
* is summarised NOW.
|
|
63
|
+
*
|
|
64
|
+
* This used to be six seconds of enforced quiet, on the reasoning that
|
|
65
|
+
* extraction talks to the same engine the user is chatting with and would queue
|
|
66
|
+
* against their next message. That cost was real but it was priced wrong. What
|
|
67
|
+
* the delay bought was a slightly shorter queue on shared-process engines; what
|
|
68
|
+
* it cost was that a memory did not exist until six seconds after the turn that
|
|
69
|
+
* produced it — so an agent could not read back what had just been established,
|
|
70
|
+
* the graph visibly lagged the conversation it was supposed to be following,
|
|
71
|
+
* and any session where the user kept typing pushed its own extraction out
|
|
72
|
+
* indefinitely. Waiting to avoid a queue is only worth it if somebody is waiting
|
|
73
|
+
* on the queue, and nobody is waiting on this one.
|
|
74
|
+
*
|
|
75
|
+
* The runner still takes one entry at a time, so extraction competes with at
|
|
76
|
+
* most one request rather than with a burst.
|
|
77
|
+
*/
|
|
78
|
+
const IDLE_DELAY_SECONDS = 0;
|
|
79
|
+
|
|
80
|
+
/**
|
|
81
|
+
* Ceiling on how long an entry may be pushed back by new activity.
|
|
82
|
+
*
|
|
83
|
+
* `deferEpisodicIngest` moves an entry while a stream is live so a summary is
|
|
84
|
+
* never generated mid-answer. Without a ceiling that is unbounded: an
|
|
85
|
+
* auto-continuing agent, or a user in a fast back-and-forth, defers the same
|
|
86
|
+
* entry forever, its transcript grows past the character budget, and the head of
|
|
87
|
+
* the span — where the decisions usually are — falls off the front.
|
|
88
|
+
*/
|
|
89
|
+
const MAX_DEFER_SECONDS = 120;
|
|
90
|
+
|
|
91
|
+
/** How often the runner asks the queue what is due. */
|
|
92
|
+
const TICK_MS = 4_000;
|
|
93
|
+
|
|
94
|
+
/**
|
|
95
|
+
* Attempts before an entry is parked as failed.
|
|
96
|
+
*
|
|
97
|
+
* Generous, because the failures this is protecting against are transient by
|
|
98
|
+
* nature — a rate limit, an engine restarting, a token being refreshed — and the
|
|
99
|
+
* cost of one more attempt is a background model call nobody is waiting on, while
|
|
100
|
+
* the cost of giving up is a conversation the user will never get back.
|
|
101
|
+
*/
|
|
102
|
+
const MAX_ATTEMPTS = 5;
|
|
103
|
+
|
|
104
|
+
/** Exponential backoff, capped. 30s, 2m, 8m, 32m, then an hour. */
|
|
105
|
+
function backoffSeconds(attempts: number): number {
|
|
106
|
+
return Math.min(30 * 4 ** attempts, 3_600);
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/** How long to wait before re-checking a condition the user has to fix. */
|
|
110
|
+
const NOT_CONFIGURED_RETRY_SECONDS = 300;
|
|
111
|
+
|
|
112
|
+
let timer: ReturnType<typeof setInterval> | null = null;
|
|
113
|
+
let draining = false;
|
|
114
|
+
let running = 0;
|
|
115
|
+
|
|
116
|
+
/** Park a finished turn. Merges into whatever this session already has queued. */
|
|
117
|
+
export function scheduleEpisodicIngest(input: EpisodicIngestInput): void {
|
|
118
|
+
try {
|
|
119
|
+
memoryQueueQueries.enqueue({
|
|
120
|
+
sessionId: input.sessionId,
|
|
121
|
+
projectId: input.projectId,
|
|
122
|
+
projectPath: input.projectPath,
|
|
123
|
+
userMessageId: input.userMessageId,
|
|
124
|
+
changedPaths: input.changedPaths,
|
|
125
|
+
deletedPaths: input.deletedPaths,
|
|
126
|
+
injectedMemoryIds: input.injectedMemoryIds,
|
|
127
|
+
delaySeconds: IDLE_DELAY_SECONDS
|
|
128
|
+
});
|
|
129
|
+
notifyMemoryStatus();
|
|
130
|
+
start();
|
|
131
|
+
// Do not wait for the next tick: the entry is due the instant it is written,
|
|
132
|
+
// and a four-second poll would put back most of the delay just removed.
|
|
133
|
+
void drain();
|
|
134
|
+
} catch (error) {
|
|
135
|
+
debug.warn('memory', 'Failed to queue extraction', error);
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
/**
|
|
140
|
+
* Called when a session starts streaming. Pushes its pending extraction back so
|
|
141
|
+
* the model is never asked to summarise while the user is waiting on a reply.
|
|
142
|
+
*
|
|
143
|
+
* Bounded by `MAX_DEFER_SECONDS` from when the entry was created, so a session
|
|
144
|
+
* that never goes quiet still gets summarised rather than accumulating a span
|
|
145
|
+
* longer than the transcript budget can carry.
|
|
146
|
+
*/
|
|
147
|
+
export function deferEpisodicIngest(sessionId: string): void {
|
|
148
|
+
try {
|
|
149
|
+
memoryQueueQueries.deferUntilStreamEnds(sessionId, MAX_DEFER_SECONDS);
|
|
150
|
+
} catch (error) {
|
|
151
|
+
debug.warn('memory', 'Failed to defer extraction', error);
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
/** Drop a session's pending extraction (the session was deleted or reset). */
|
|
156
|
+
export function cancel(sessionId: string): void {
|
|
157
|
+
try {
|
|
158
|
+
memoryQueueQueries.removeBySession(sessionId);
|
|
159
|
+
notifyMemoryStatus();
|
|
160
|
+
} catch (error) {
|
|
161
|
+
debug.warn('memory', 'Failed to cancel extraction', error);
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
/**
|
|
166
|
+
* True when something is about to run, or is running.
|
|
167
|
+
*
|
|
168
|
+
* Read by `maintenance.ts` as its "somebody is working" signal: both compete for
|
|
169
|
+
* the same engine, so the expensive background jobs stand down while this holds.
|
|
170
|
+
*
|
|
171
|
+
* "About to run" is the load-bearing word, and getting it wrong disabled the
|
|
172
|
+
* entire maintenance loop on a default install. This used to answer "is any row
|
|
173
|
+
* pending", but an entry that cannot run — no model configured — stays pending
|
|
174
|
+
* forever by design, re-checking every few minutes so it starts the moment a
|
|
175
|
+
* model is chosen. Every such entry made this permanently true, so duplicate
|
|
176
|
+
* collapse, retention and consolidation never ran once, on exactly the instances
|
|
177
|
+
* whose graphs most needed tidying. A row whose next attempt is an hour away is
|
|
178
|
+
* not somebody working; it is somebody waiting.
|
|
179
|
+
*/
|
|
180
|
+
export function hasPendingExtraction(): boolean {
|
|
181
|
+
if (running > 0) return true;
|
|
182
|
+
try {
|
|
183
|
+
return memoryQueueQueries.dueWithin(IMMINENT_SECONDS) > 0;
|
|
184
|
+
} catch {
|
|
185
|
+
return false;
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
/** How soon a queued extraction has to be before maintenance stands down for it. */
|
|
190
|
+
const IMMINENT_SECONDS = 90;
|
|
191
|
+
|
|
192
|
+
/**
|
|
193
|
+
* Start the runner and put previously-failed entries back in the queue.
|
|
194
|
+
*
|
|
195
|
+
* Idempotent, and safe to call from the enqueue path — the common case is a
|
|
196
|
+
* server that has been idle since startup.
|
|
197
|
+
*/
|
|
198
|
+
export function startExtractionRunner(): void {
|
|
199
|
+
if (timer) return;
|
|
200
|
+
|
|
201
|
+
try {
|
|
202
|
+
const revived = memoryQueueQueries.retryFailed();
|
|
203
|
+
if (revived > 0) {
|
|
204
|
+
debug.log('memory', `Re-queued ${revived} extraction(s) that had previously failed`);
|
|
205
|
+
}
|
|
206
|
+
} catch (error) {
|
|
207
|
+
debug.warn('memory', 'Failed to revive the extraction queue', error);
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
timer = setInterval(() => void drain(), TICK_MS);
|
|
211
|
+
// Housekeeping: never a reason to hold the process open at shutdown.
|
|
212
|
+
timer.unref?.();
|
|
213
|
+
void drain();
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
export function stopExtractionRunner(): void {
|
|
217
|
+
if (!timer) return;
|
|
218
|
+
clearInterval(timer);
|
|
219
|
+
timer = null;
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
const start = startExtractionRunner;
|
|
223
|
+
|
|
224
|
+
/**
|
|
225
|
+
* Run everything queued NOW, ignoring the idle delay.
|
|
226
|
+
*
|
|
227
|
+
* Called on shutdown, so a clean stop does not leave a turn's memories to a
|
|
228
|
+
* process that may not come back for a while, and by tests that need the write to
|
|
229
|
+
* have happened.
|
|
230
|
+
*/
|
|
231
|
+
export async function flushEpisodicIngest(budgetMs = 8_000): Promise<void> {
|
|
232
|
+
let entries: QueuedExtraction[];
|
|
233
|
+
try {
|
|
234
|
+
entries = memoryQueueQueries.all().filter(entry => entry.status === 'pending');
|
|
235
|
+
} catch {
|
|
236
|
+
return;
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
// BOUNDED, because this runs inside graceful shutdown. Each entry is a model
|
|
240
|
+
// call with no timeout of its own, so a handful of sessions against a stalled
|
|
241
|
+
// or rate-limited engine could hold the process open for minutes — and the
|
|
242
|
+
// whole point of the queue being a table is that nothing is lost by stopping:
|
|
243
|
+
// whatever is left is picked up by the next start, which re-queues it anyway.
|
|
244
|
+
const deadline = Date.now() + budgetMs;
|
|
245
|
+
for (const entry of entries) {
|
|
246
|
+
if (Date.now() >= deadline) {
|
|
247
|
+
debug.log('memory', `Shutdown flush stopped at the ${budgetMs} ms budget; the rest stays queued`);
|
|
248
|
+
return;
|
|
249
|
+
}
|
|
250
|
+
await runOne(entry);
|
|
251
|
+
}
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
/**
|
|
255
|
+
* Longest one drain may run before it yields.
|
|
256
|
+
*
|
|
257
|
+
* One slow entry delays every entry behind it, and `draining` being true
|
|
258
|
+
* suppresses every later trigger — so a backlog against a slow model could hold
|
|
259
|
+
* the flag for hours, during which `hasPendingExtraction()` keeps maintenance
|
|
260
|
+
* stood down. Yielding on a deadline costs nothing: the queue is a table, the
|
|
261
|
+
* timer fires again, and whatever is left is picked up with the same guarantees.
|
|
262
|
+
*/
|
|
263
|
+
const DRAIN_BUDGET_MS = 15 * 60_000;
|
|
264
|
+
|
|
265
|
+
/**
|
|
266
|
+
* Extractions in flight at once.
|
|
267
|
+
*
|
|
268
|
+
* This used to be one, and the reason was real: extraction calls a model through
|
|
269
|
+
* the same engine the user is chatting with, so several at once would queue
|
|
270
|
+
* against their next message on a shared-process engine. Two changes since have
|
|
271
|
+
* made that argument much weaker. Extraction opens its own session in a neutral
|
|
272
|
+
* directory rather than the user's project, and it runs the moment a turn ends
|
|
273
|
+
* rather than competing with an active one — `hasActiveStream` still holds a
|
|
274
|
+
* banked turn while its session is streaming.
|
|
275
|
+
*
|
|
276
|
+
* What serial cost instead was visible immediately: forty finished chats meant
|
|
277
|
+
* forty model calls end to end, each of them a minute or more, with the graph
|
|
278
|
+
* catching up over the following hour and `hasPendingExtraction()` holding
|
|
279
|
+
* maintenance down the whole time.
|
|
280
|
+
*
|
|
281
|
+
* Three is a compromise rather than a measurement. It is enough that a backlog
|
|
282
|
+
* drains in a third of the time, and few enough that an engine with one shared
|
|
283
|
+
* process is not swamped by memory work while somebody is trying to use it.
|
|
284
|
+
*/
|
|
285
|
+
const MAX_CONCURRENT = 3;
|
|
286
|
+
|
|
287
|
+
/**
|
|
288
|
+
* Take due entries, up to `MAX_CONCURRENT` at a time.
|
|
289
|
+
*
|
|
290
|
+
* Claiming is safe under concurrency without a lock: `due()` orders by next
|
|
291
|
+
* attempt and each runner's delete is conditional on the revision it claimed
|
|
292
|
+
* (migration 066), so the worst a double-claim can do is extract the same span
|
|
293
|
+
* twice — and the second write upserts onto the same digests, which is
|
|
294
|
+
* reinforcement rather than duplication. Entries are still taken in batches
|
|
295
|
+
* rather than as an unbounded pool so the ceiling is genuinely a ceiling.
|
|
296
|
+
*/
|
|
297
|
+
async function drain(): Promise<void> {
|
|
298
|
+
if (draining) return;
|
|
299
|
+
draining = true;
|
|
300
|
+
const deadline = Date.now() + DRAIN_BUDGET_MS;
|
|
301
|
+
try {
|
|
302
|
+
for (;;) {
|
|
303
|
+
const due = memoryQueueQueries.due(MAX_CONCURRENT);
|
|
304
|
+
if (due.length === 0) return;
|
|
305
|
+
|
|
306
|
+
// `allSettled`, not `all`: one entry throwing must not abandon the others
|
|
307
|
+
// mid-flight. `runOne` already handles its own failures, so this is a
|
|
308
|
+
// backstop against something unexpected in the bookkeeping around it.
|
|
309
|
+
await Promise.allSettled(due.map(entry => runOne(entry)));
|
|
310
|
+
|
|
311
|
+
if (Date.now() >= deadline) {
|
|
312
|
+
debug.log(
|
|
313
|
+
'memory',
|
|
314
|
+
`Extraction drain yielded at the ${DRAIN_BUDGET_MS / 60_000} minute budget; the rest stays queued`
|
|
315
|
+
);
|
|
316
|
+
return;
|
|
317
|
+
}
|
|
318
|
+
}
|
|
319
|
+
} catch (error) {
|
|
320
|
+
debug.warn('memory', 'Extraction drain failed', error);
|
|
321
|
+
} finally {
|
|
322
|
+
draining = false;
|
|
323
|
+
}
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
async function runOne(entry: QueuedExtraction): Promise<void> {
|
|
327
|
+
running++;
|
|
328
|
+
notifyMemoryStatus();
|
|
329
|
+
try {
|
|
330
|
+
const result = await ingestEpisodicMemories({
|
|
331
|
+
projectId: entry.projectId,
|
|
332
|
+
projectPath: entry.projectPath,
|
|
333
|
+
sessionId: entry.sessionId,
|
|
334
|
+
userMessageId: entry.userMessageId,
|
|
335
|
+
changedPaths: entry.changedPaths,
|
|
336
|
+
deletedPaths: entry.deletedPaths,
|
|
337
|
+
// Rebuilt from the graph rather than carried through the queue: a Map of
|
|
338
|
+
// path → node id does not serialise usefully, and `getByPath` finds the
|
|
339
|
+
// same nodes. The only cost is a lookup per path.
|
|
340
|
+
fileNodes: new Map<string, string>(),
|
|
341
|
+
injectedMemoryIds: entry.injectedMemoryIds
|
|
342
|
+
});
|
|
343
|
+
|
|
344
|
+
if (result.ok) {
|
|
345
|
+
// Quoting the revision this run claimed. Extraction starts the instant a
|
|
346
|
+
// turn ends, so a later turn can finish and merge into this row while the
|
|
347
|
+
// model is still reading the earlier one — and an unconditional delete
|
|
348
|
+
// would take that turn's boundary and paths with it. A refused delete
|
|
349
|
+
// means the row moved on and the next pass covers what was added.
|
|
350
|
+
if (!memoryQueueQueries.remove(entry.id, entry.revision)) {
|
|
351
|
+
debug.log('memory', `Session ${entry.sessionId.slice(0, 8)} banked another turn mid-extraction`);
|
|
352
|
+
}
|
|
353
|
+
if (result.written > 0) {
|
|
354
|
+
scheduleVectorIndexing();
|
|
355
|
+
// The graph has content now, so turn-start injection stops suppressing
|
|
356
|
+
// its own block (see `context.ts`).
|
|
357
|
+
resetGraphEmptiness();
|
|
358
|
+
notifyGraphChanged('memories', entry.projectId);
|
|
359
|
+
}
|
|
360
|
+
return;
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
// Not a failure of this turn — a condition the user has to resolve. Waiting
|
|
364
|
+
// costs nothing and the entry stays exactly where it is.
|
|
365
|
+
if (!result.countsAsAttempt) {
|
|
366
|
+
memoryQueueQueries.recordFailure(entry.id, result.error, NOT_CONFIGURED_RETRY_SECONDS, {
|
|
367
|
+
countsAsAttempt: false
|
|
368
|
+
});
|
|
369
|
+
return;
|
|
370
|
+
}
|
|
371
|
+
|
|
372
|
+
const attempts = entry.attempts + 1;
|
|
373
|
+
if (attempts >= MAX_ATTEMPTS) {
|
|
374
|
+
memoryQueueQueries.markFailed(entry.id, result.error);
|
|
375
|
+
debug.warn(
|
|
376
|
+
'memory',
|
|
377
|
+
`Extraction for session ${entry.sessionId.slice(0, 8)} failed ${attempts}x, parked: ${result.error}`
|
|
378
|
+
);
|
|
379
|
+
return;
|
|
380
|
+
}
|
|
381
|
+
|
|
382
|
+
memoryQueueQueries.recordFailure(entry.id, result.error, backoffSeconds(entry.attempts));
|
|
383
|
+
debug.log(
|
|
384
|
+
'memory',
|
|
385
|
+
`Extraction attempt ${attempts} failed, retrying in ${backoffSeconds(entry.attempts)}s: ${result.error}`
|
|
386
|
+
);
|
|
387
|
+
} catch (error) {
|
|
388
|
+
// A throw from outside `ingestEpisodicMemories` — a database problem, most
|
|
389
|
+
// likely. Treated as retriable for the same reason as everything else here:
|
|
390
|
+
// dropping the entry is the one outcome that cannot be undone.
|
|
391
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
392
|
+
try {
|
|
393
|
+
memoryQueueQueries.recordFailure(entry.id, message, backoffSeconds(entry.attempts));
|
|
394
|
+
} catch {
|
|
395
|
+
debug.error('memory', 'Extraction failed and could not be re-queued', error);
|
|
396
|
+
}
|
|
397
|
+
} finally {
|
|
398
|
+
running--;
|
|
399
|
+
notifyMemoryStatus();
|
|
400
|
+
}
|
|
401
|
+
}
|
|
402
|
+
|
|
403
|
+
/** How many extractions are running this instant — part of the status payload. */
|
|
404
|
+
export function runningExtractions(): number {
|
|
405
|
+
return running;
|
|
406
|
+
}
|
|
@@ -0,0 +1,215 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Structural extraction tests.
|
|
3
|
+
*
|
|
4
|
+
* Run against a real temporary project on disk and a real in-memory SQLite
|
|
5
|
+
* database, because what is being tested is precisely the interaction with the
|
|
6
|
+
* filesystem: which import specifiers resolve to real files, which are packages,
|
|
7
|
+
* and which are neither.
|
|
8
|
+
*
|
|
9
|
+
* Two cases here exist because they were live bugs found during bring-up, and
|
|
10
|
+
* both were quiet — they produced a plausible-looking graph that degraded
|
|
11
|
+
* retrieval rather than throwing:
|
|
12
|
+
*
|
|
13
|
+
* - a build-tool path alias (`$shared/types`) was turned into a "dependency"
|
|
14
|
+
* node, inventing a shared dependency between every file using the alias;
|
|
15
|
+
* - structural nodes were given embedding vectors, and their path-fragment
|
|
16
|
+
* text scored above correct answers for natural-language questions.
|
|
17
|
+
*/
|
|
18
|
+
|
|
19
|
+
import { afterEach, beforeEach, describe, expect, it, mock } from 'bun:test';
|
|
20
|
+
import { Database } from 'bun:sqlite';
|
|
21
|
+
import { mkdtemp, mkdir, rm, writeFile } from 'node:fs/promises';
|
|
22
|
+
import { join } from 'node:path';
|
|
23
|
+
import { tmpdir } from 'node:os';
|
|
24
|
+
import type { DatabaseConnection } from '$shared/types/database/connection';
|
|
25
|
+
import * as migration066 from '$backend/database/migrations/066_create_memory_graph';
|
|
26
|
+
|
|
27
|
+
let db: Database;
|
|
28
|
+
|
|
29
|
+
// The whole module surface, not just `getDatabase`. `mock.module` replaces the
|
|
30
|
+
// module for the entire test PROCESS, so a partial stub leaves any file that runs
|
|
31
|
+
// afterwards unable to import the missing names — surfacing as
|
|
32
|
+
// "Export named 'closeDatabase' not found" in a test that never touched memory.
|
|
33
|
+
mock.module('$backend/database', () => ({
|
|
34
|
+
getDatabase: () => db,
|
|
35
|
+
initializeDatabase: async () => db,
|
|
36
|
+
closeDatabase: () => {},
|
|
37
|
+
resetDatabase: async () => {},
|
|
38
|
+
getDatabaseInfo: async () => ({}),
|
|
39
|
+
vacuumDatabase: async () => {}
|
|
40
|
+
}));
|
|
41
|
+
|
|
42
|
+
const { graphQueries } = await import('$backend/database/queries/graph-queries');
|
|
43
|
+
const { ingestStructuralChanges } = await import('./structural');
|
|
44
|
+
|
|
45
|
+
const PROJECT_ID = 'structural-test';
|
|
46
|
+
let projectPath: string;
|
|
47
|
+
|
|
48
|
+
beforeEach(async () => {
|
|
49
|
+
db = new Database(':memory:');
|
|
50
|
+
db.exec('PRAGMA foreign_keys = ON');
|
|
51
|
+
migration066.up(db as unknown as DatabaseConnection);
|
|
52
|
+
|
|
53
|
+
projectPath = await mkdtemp(join(tmpdir(), 'clopen-structural-'));
|
|
54
|
+
});
|
|
55
|
+
|
|
56
|
+
afterEach(async () => {
|
|
57
|
+
await rm(projectPath, { recursive: true, force: true });
|
|
58
|
+
});
|
|
59
|
+
|
|
60
|
+
async function write(relativePath: string, contents: string): Promise<void> {
|
|
61
|
+
const full = join(projectPath, relativePath);
|
|
62
|
+
await mkdir(join(full, '..'), { recursive: true });
|
|
63
|
+
await writeFile(full, contents, 'utf8');
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
function ingest(changedPaths: string[]) {
|
|
67
|
+
return ingestStructuralChanges({ projectId: PROJECT_ID, projectPath, sessionId: 'session-1', changedPaths });
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
describe('structural extraction', () => {
|
|
71
|
+
it('creates a file node and its containing module', async () => {
|
|
72
|
+
await write('src/service.ts', 'export function run(): void {}\n');
|
|
73
|
+
|
|
74
|
+
const result = await ingest(['src/service.ts']);
|
|
75
|
+
expect(result.files).toBe(1);
|
|
76
|
+
|
|
77
|
+
const file = graphQueries.getByPath(PROJECT_ID, 'src/service.ts');
|
|
78
|
+
expect(file).not.toBeNull();
|
|
79
|
+
expect(file!.language).toBe('typescript');
|
|
80
|
+
expect(file!.label).toBe('service.ts');
|
|
81
|
+
|
|
82
|
+
// The module edge is what gives the graph a skeleton, which is what makes
|
|
83
|
+
// community detection produce meaningful lobes rather than one cloud.
|
|
84
|
+
const neighbours = graphQueries.neighbours(file!.id, 1);
|
|
85
|
+
expect(neighbours.some(n => n.node.subkind === 'module' && n.node.path === 'src')).toBe(true);
|
|
86
|
+
});
|
|
87
|
+
|
|
88
|
+
it('resolves a relative import to the file it actually points at', async () => {
|
|
89
|
+
await write('src/a.ts', "import { b } from './b';\nexport const a = 1;\n");
|
|
90
|
+
await write('src/b.ts', 'export const b = 2;\n');
|
|
91
|
+
|
|
92
|
+
await ingest(['src/a.ts']);
|
|
93
|
+
|
|
94
|
+
const a = graphQueries.getByPath(PROJECT_ID, 'src/a.ts')!;
|
|
95
|
+
const b = graphQueries.getByPath(PROJECT_ID, 'src/b.ts');
|
|
96
|
+
expect(b).not.toBeNull();
|
|
97
|
+
expect(graphQueries.edgesOf(a.id).some(e => e.srcId === a.id && e.dstId === b!.id && e.rel === 'imports')).toBe(true);
|
|
98
|
+
});
|
|
99
|
+
|
|
100
|
+
it('records a real package as a global dependency node', async () => {
|
|
101
|
+
await write('src/uses-pkg.ts', "import merge from 'lodash/merge';\nimport { z } from 'zod';\n");
|
|
102
|
+
|
|
103
|
+
await ingest(['src/uses-pkg.ts']);
|
|
104
|
+
|
|
105
|
+
const deps = graphQueries
|
|
106
|
+
.list({ projectId: null, kinds: ['structural'] })
|
|
107
|
+
.filter(node => node.subkind === 'dependency')
|
|
108
|
+
.map(node => node.label)
|
|
109
|
+
.sort();
|
|
110
|
+
|
|
111
|
+
// Scoped to the package, not the subpath — `lodash/merge` is still lodash.
|
|
112
|
+
expect(deps).toEqual(['lodash', 'zod']);
|
|
113
|
+
// Dependencies are global so the same package links projects together.
|
|
114
|
+
expect(graphQueries.list({ projectId: null }).every(n => n.projectId === null)).toBe(true);
|
|
115
|
+
});
|
|
116
|
+
|
|
117
|
+
it('never turns a build-tool path alias into a dependency', async () => {
|
|
118
|
+
await write(
|
|
119
|
+
'src/aliased.ts',
|
|
120
|
+
[
|
|
121
|
+
"import type { X } from '$shared/types';",
|
|
122
|
+
"import { y } from '~/lib/y';",
|
|
123
|
+
"import { z } from '@/utils/z';",
|
|
124
|
+
"import { w } from '#internal/w';",
|
|
125
|
+
"import { real } from 'nanoid';"
|
|
126
|
+
].join('\n')
|
|
127
|
+
);
|
|
128
|
+
|
|
129
|
+
await ingest(['src/aliased.ts']);
|
|
130
|
+
|
|
131
|
+
const deps = graphQueries
|
|
132
|
+
.list({ projectId: null, kinds: ['structural'] })
|
|
133
|
+
.filter(node => node.subkind === 'dependency')
|
|
134
|
+
.map(node => node.label);
|
|
135
|
+
|
|
136
|
+
// Only the genuine package survives. An alias is not a dependency, and
|
|
137
|
+
// inventing one would connect every file that uses it.
|
|
138
|
+
expect(deps).toEqual(['nanoid']);
|
|
139
|
+
});
|
|
140
|
+
|
|
141
|
+
it('names exported definitions and links them to their file', async () => {
|
|
142
|
+
await write(
|
|
143
|
+
'src/defs.ts',
|
|
144
|
+
[
|
|
145
|
+
'export function alpha(): void {}',
|
|
146
|
+
'export class Beta {}',
|
|
147
|
+
'export interface Gamma { x: number }',
|
|
148
|
+
'export const delta = 4;',
|
|
149
|
+
'function notExported(): void {}'
|
|
150
|
+
].join('\n')
|
|
151
|
+
);
|
|
152
|
+
|
|
153
|
+
await ingest(['src/defs.ts']);
|
|
154
|
+
|
|
155
|
+
const file = graphQueries.getByPath(PROJECT_ID, 'src/defs.ts')!;
|
|
156
|
+
const symbols = graphQueries
|
|
157
|
+
.neighbours(file.id, 1)
|
|
158
|
+
.filter(n => n.node.subkind === 'symbol')
|
|
159
|
+
.map(n => n.node.symbol)
|
|
160
|
+
.sort();
|
|
161
|
+
|
|
162
|
+
expect(symbols).toEqual(['Beta', 'Gamma', 'alpha', 'delta']);
|
|
163
|
+
// Local helpers are not part of the module's surface, so they are not nodes.
|
|
164
|
+
expect(symbols).not.toContain('notExported');
|
|
165
|
+
});
|
|
166
|
+
|
|
167
|
+
it('skips generated and vendored directories', async () => {
|
|
168
|
+
await write('node_modules/pkg/index.js', 'module.exports = 1;\n');
|
|
169
|
+
await write('dist/bundle.js', 'console.log(1);\n');
|
|
170
|
+
await write('src/real.ts', 'export const real = 1;\n');
|
|
171
|
+
|
|
172
|
+
const result = await ingest(['node_modules/pkg/index.js', 'dist/bundle.js', 'src/real.ts']);
|
|
173
|
+
expect(result.files).toBe(1);
|
|
174
|
+
expect(graphQueries.getByPath(PROJECT_ID, 'src/real.ts')).not.toBeNull();
|
|
175
|
+
});
|
|
176
|
+
|
|
177
|
+
it('re-ingesting the same file reinforces rather than duplicates', async () => {
|
|
178
|
+
await write('src/again.ts', 'export const again = 1;\n');
|
|
179
|
+
|
|
180
|
+
await ingest(['src/again.ts']);
|
|
181
|
+
const first = graphQueries.getByPath(PROJECT_ID, 'src/again.ts')!;
|
|
182
|
+
await ingest(['src/again.ts']);
|
|
183
|
+
const second = graphQueries.getByPath(PROJECT_ID, 'src/again.ts')!;
|
|
184
|
+
|
|
185
|
+
expect(second.id).toBe(first.id);
|
|
186
|
+
expect(second.weight).toBeGreaterThan(first.weight);
|
|
187
|
+
});
|
|
188
|
+
|
|
189
|
+
it('keeps structural nodes out of the vector index', async () => {
|
|
190
|
+
await write('src/vectors.ts', 'export const vectors = 1;\n');
|
|
191
|
+
await ingest(['src/vectors.ts']);
|
|
192
|
+
graphQueries.upsert({
|
|
193
|
+
kind: 'episodic',
|
|
194
|
+
subkind: 'decision',
|
|
195
|
+
projectId: PROJECT_ID,
|
|
196
|
+
label: 'Vectors are only computed for prose memories, never for file paths'
|
|
197
|
+
});
|
|
198
|
+
|
|
199
|
+
const pending = graphQueries.nodesMissingVectors('test-model', 100);
|
|
200
|
+
|
|
201
|
+
// Embedding a path yields a bag of fragments that scores highly against
|
|
202
|
+
// arbitrary questions; names are BM25's job. Only the memory is queued.
|
|
203
|
+
expect(pending).toHaveLength(1);
|
|
204
|
+
expect(pending[0].kind).toBe('episodic');
|
|
205
|
+
});
|
|
206
|
+
|
|
207
|
+
it('does not fail on a path that no longer exists', async () => {
|
|
208
|
+
const result = await ingest(['src/deleted.ts']);
|
|
209
|
+
|
|
210
|
+
// A file removed during the turn still deserves its node — memories pointing
|
|
211
|
+
// at it remain true history — but nothing may throw on the way there.
|
|
212
|
+
expect(result.files).toBe(1);
|
|
213
|
+
expect(graphQueries.getByPath(PROJECT_ID, 'src/deleted.ts')).not.toBeNull();
|
|
214
|
+
});
|
|
215
|
+
});
|