@vellumai/assistant 0.10.7-dev.202607101836.11f2eba → 0.10.7-dev.202607101934.29f4d92
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/package.json +1 -1
- package/src/__tests__/tool-execution-abort-cleanup.test.ts +5 -26
- package/src/persistence/__tests__/message-content-file.test.ts +51 -3
- package/src/persistence/llm-request-log-sink-clickhouse.ts +2 -8
- package/src/persistence/llm-request-log-store.ts +2 -8
- package/src/persistence/message-content-file.ts +68 -6
- package/src/persistence/migrations/326-move-injection-events-to-memory-db.ts +104 -0
- package/src/persistence/schema/memory-injection.ts +3 -1
- package/src/persistence/steps.ts +2 -0
- package/src/plugins/defaults/memory/__tests__/db-memory-attach.test.ts +22 -18
- package/src/plugins/defaults/memory/__tests__/table-relocation.test.ts +49 -0
- package/src/plugins/defaults/memory/routes/__tests__/memory-v2-simulate-route.test.ts +1 -6
- package/src/plugins/defaults/memory/routes/memory-v2-routes.ts +3 -8
- package/src/plugins/defaults/memory/v2/__tests__/injection-events.test.ts +60 -62
- package/src/plugins/defaults/memory/v2/__tests__/router.test.ts +7 -20
- package/src/plugins/defaults/memory/v2/harness/router-retriever.ts +1 -8
- package/src/plugins/defaults/memory/v2/injection-events.ts +33 -14
- package/src/plugins/defaults/memory/v2/injection.ts +1 -2
- package/src/plugins/defaults/memory/v2/router.ts +4 -14
package/package.json
CHANGED
|
@@ -16,32 +16,11 @@ import { join } from "node:path";
|
|
|
16
16
|
import { afterEach, beforeEach, describe, expect, mock, test } from "bun:test";
|
|
17
17
|
|
|
18
18
|
// ── Shared mock setup ────────────────────────────────────────────────────────
|
|
19
|
-
//
|
|
20
|
-
//
|
|
21
|
-
|
|
22
|
-
mock
|
|
23
|
-
|
|
24
|
-
ui: {},
|
|
25
|
-
|
|
26
|
-
provider: "anthropic",
|
|
27
|
-
model: "test",
|
|
28
|
-
maxTokens: 4096,
|
|
29
|
-
dataDir: "/tmp",
|
|
30
|
-
timeouts: {
|
|
31
|
-
shellDefaultTimeoutSec: 120,
|
|
32
|
-
shellMaxTimeoutSec: 600,
|
|
33
|
-
permissionTimeoutSec: 300,
|
|
34
|
-
},
|
|
35
|
-
rateLimit: { maxRequestsPerMinute: 0 },
|
|
36
|
-
secretDetection: {
|
|
37
|
-
enabled: false,
|
|
38
|
-
},
|
|
39
|
-
}),
|
|
40
|
-
loadConfig: () => ({}),
|
|
41
|
-
invalidateConfigCache: () => {},
|
|
42
|
-
loadRawConfig: () => ({}),
|
|
43
|
-
saveRawConfig: () => {},
|
|
44
|
-
}));
|
|
19
|
+
// The real config loader serves these tests: it reads from the per-test temp
|
|
20
|
+
// workspace and returns schema defaults (the timeout values the shell tool
|
|
21
|
+
// needs are the documented defaults). Mocking `config/loader` here would force
|
|
22
|
+
// the mock to mirror the loader's full export surface — modules under test
|
|
23
|
+
// import it by name, and a partial mock fails to link.
|
|
45
24
|
|
|
46
25
|
// shell.ts uses the script proxy — stub it to avoid network side-effects.
|
|
47
26
|
mock.module("../tools/network/script-proxy/index.js", () => ({
|
|
@@ -169,13 +169,61 @@ describe("resolveMessageContentBlocks", () => {
|
|
|
169
169
|
expect(resolveMessageContentBlocks(JSON.stringify(blocks))).toEqual(blocks);
|
|
170
170
|
});
|
|
171
171
|
|
|
172
|
-
test("passes
|
|
173
|
-
|
|
172
|
+
test("passes typed blocks outside the union through untouched", () => {
|
|
173
|
+
// Persisted kinds like ui_surface live outside the provider union;
|
|
174
|
+
// their renderers own their shape, so repair must not rewrite them.
|
|
175
|
+
const historical = [
|
|
176
|
+
textBlock("kept as-is"),
|
|
177
|
+
{ type: "ui_surface", surfaceType: "call_summary", data: { x: 1 } },
|
|
178
|
+
{ type: "some_retired_block_kind", payload: 1 },
|
|
179
|
+
];
|
|
174
180
|
expect(resolveMessageContentBlocks(JSON.stringify(historical))).toEqual(
|
|
175
|
-
historical as
|
|
181
|
+
historical as ContentBlock[],
|
|
176
182
|
);
|
|
177
183
|
});
|
|
178
184
|
|
|
185
|
+
test("wraps type-less values in a text block carrying the payload", () => {
|
|
186
|
+
const historical = [{ payload: 1 }, "bare string"];
|
|
187
|
+
expect(resolveMessageContentBlocks(JSON.stringify(historical))).toEqual([
|
|
188
|
+
textBlock('{"payload":1}'),
|
|
189
|
+
textBlock('"bare string"'),
|
|
190
|
+
]);
|
|
191
|
+
});
|
|
192
|
+
|
|
193
|
+
test("repairs a web_search_tool_result with a missing tool_use_id", () => {
|
|
194
|
+
const historical = [
|
|
195
|
+
{ type: "web_search_tool_result", content: { encrypted: "blob" } },
|
|
196
|
+
];
|
|
197
|
+
expect(resolveMessageContentBlocks(JSON.stringify(historical))).toEqual([
|
|
198
|
+
{
|
|
199
|
+
type: "web_search_tool_result",
|
|
200
|
+
tool_use_id: "",
|
|
201
|
+
content: { encrypted: "blob" },
|
|
202
|
+
},
|
|
203
|
+
]);
|
|
204
|
+
});
|
|
205
|
+
|
|
206
|
+
test("repairs a text block with missing or non-string text", () => {
|
|
207
|
+
const historical = [{ type: "text" }, { type: "text", text: 42 }];
|
|
208
|
+
expect(resolveMessageContentBlocks(JSON.stringify(historical))).toEqual([
|
|
209
|
+
textBlock(""),
|
|
210
|
+
textBlock("42"),
|
|
211
|
+
]);
|
|
212
|
+
});
|
|
213
|
+
|
|
214
|
+
test("repairs a tool_result with object-valued content in place", () => {
|
|
215
|
+
const historical = [
|
|
216
|
+
{ type: "tool_result", tool_use_id: "tu-1", content: { some: "obj" } },
|
|
217
|
+
];
|
|
218
|
+
expect(resolveMessageContentBlocks(JSON.stringify(historical))).toEqual([
|
|
219
|
+
{
|
|
220
|
+
type: "tool_result",
|
|
221
|
+
tool_use_id: "tu-1",
|
|
222
|
+
content: '{"some":"obj"}',
|
|
223
|
+
},
|
|
224
|
+
]);
|
|
225
|
+
});
|
|
226
|
+
|
|
179
227
|
test("folds a reserved-path ref to blocks", () => {
|
|
180
228
|
const rel = writeRefFixture("test-resolve-blocks", "m.jsonl");
|
|
181
229
|
expect(resolveMessageContentBlocks(JSON.stringify({ ref: rel }))).toEqual([
|
|
@@ -29,13 +29,7 @@
|
|
|
29
29
|
* Writes are best-effort: a ClickHouse outage logs and is swallowed so it
|
|
30
30
|
* can never abort a turn.
|
|
31
31
|
*/
|
|
32
|
-
|
|
33
|
-
// store imports this module, so it is reached transitively by the large set of
|
|
34
|
-
// tests that stub `config/loader` with a partial mock exposing only
|
|
35
|
-
// `getConfig`. A named import would fail to link against those mocks; a
|
|
36
|
-
// namespace access degrades to `undefined` at call time instead, which the
|
|
37
|
-
// factory's try/catch treats as "no sink" (→ local SQLite). Matches the store.
|
|
38
|
-
import * as configLoader from "../config/loader.js";
|
|
32
|
+
import { getConfigReadOnly } from "../config/loader.js";
|
|
39
33
|
import type { LlmRequestLogsClickHouseConfig } from "../config/schemas/llm-request-logs.js";
|
|
40
34
|
import { credentialKey } from "../security/credential-key.js";
|
|
41
35
|
import { getSecureKeyAsync } from "../security/secure-keys.js";
|
|
@@ -313,7 +307,7 @@ let cachedSink: { key: string; sink: ClickHouseLlmRequestLogSink } | null =
|
|
|
313
307
|
export function getClickHouseLlmRequestLogSink(): ClickHouseLlmRequestLogSink | null {
|
|
314
308
|
let cfg;
|
|
315
309
|
try {
|
|
316
|
-
cfg =
|
|
310
|
+
cfg = getConfigReadOnly().llmRequestLogs;
|
|
317
311
|
} catch {
|
|
318
312
|
return null;
|
|
319
313
|
}
|
|
@@ -16,13 +16,7 @@ import {
|
|
|
16
16
|
import { v4 as uuid } from "uuid";
|
|
17
17
|
|
|
18
18
|
import { CALL_SITE_SYNTHETIC_AGENT_ERROR_MESSAGE } from "../api/constants/call-sites.js";
|
|
19
|
-
|
|
20
|
-
// store is reached transitively by a large number of tests that stub
|
|
21
|
-
// `config/loader` with a partial mock exposing only `getConfig`. A named
|
|
22
|
-
// import would fail to link against those mocks ("Export … not found"); a
|
|
23
|
-
// namespace access degrades to `undefined` at call time instead, which the
|
|
24
|
-
// try/catch in `llmRequestLoggingEnabled` treats as "enabled".
|
|
25
|
-
import * as configLoader from "../config/loader.js";
|
|
19
|
+
import { getConfigReadOnly } from "../config/loader.js";
|
|
26
20
|
import type { LLMCallSite } from "../config/schemas/llm.js";
|
|
27
21
|
import { AssistantError, ProviderError } from "../util/errors.js";
|
|
28
22
|
import {
|
|
@@ -64,7 +58,7 @@ function logsDb(): DrizzleDb {
|
|
|
64
58
|
*/
|
|
65
59
|
export function llmRequestLoggingEnabled(): boolean {
|
|
66
60
|
try {
|
|
67
|
-
return
|
|
61
|
+
return getConfigReadOnly().llmRequestLogs?.enabled !== false;
|
|
68
62
|
} catch {
|
|
69
63
|
return true;
|
|
70
64
|
}
|
|
@@ -182,6 +182,61 @@ function resolveRefToBlocks(ref: MessageContentRef): ContentBlock[] {
|
|
|
182
182
|
return blocks;
|
|
183
183
|
}
|
|
184
184
|
|
|
185
|
+
/** Serialize an arbitrary value for embedding in a repaired text block. */
|
|
186
|
+
function safeJson(value: unknown): string {
|
|
187
|
+
try {
|
|
188
|
+
return JSON.stringify(value) ?? "";
|
|
189
|
+
} catch {
|
|
190
|
+
return String(value);
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
/**
|
|
195
|
+
* Repair a historical block that fails the current schema. Field-level
|
|
196
|
+
* repair for the variants whose string fields consumers touch directly
|
|
197
|
+
* (text, tool_result, web_search_tool_result); any other block that at
|
|
198
|
+
* least carries a string `type` passes through untouched — persisted
|
|
199
|
+
* kinds outside the provider union (e.g. `ui_surface`) are live data
|
|
200
|
+
* whose renderers own their shape. Only type-less values are wrapped in
|
|
201
|
+
* a text block carrying their serialized payload.
|
|
202
|
+
*/
|
|
203
|
+
function coerceLegacyBlock(block: unknown): ContentBlock {
|
|
204
|
+
if (typeof block === "object" && block !== null) {
|
|
205
|
+
const rec = block as Record<string, unknown>;
|
|
206
|
+
if (rec.type === "text") {
|
|
207
|
+
return {
|
|
208
|
+
type: "text",
|
|
209
|
+
text: typeof rec.text === "string" ? rec.text : safeJson(rec.text),
|
|
210
|
+
};
|
|
211
|
+
}
|
|
212
|
+
if (rec.type === "tool_result" || rec.type === "web_search_tool_result") {
|
|
213
|
+
const toolUseId =
|
|
214
|
+
typeof rec.tool_use_id === "string" ? rec.tool_use_id : "";
|
|
215
|
+
if (rec.type === "web_search_tool_result") {
|
|
216
|
+
// content is opaque (provider-specific) — only the id needs repair.
|
|
217
|
+
return {
|
|
218
|
+
type: "web_search_tool_result",
|
|
219
|
+
tool_use_id: toolUseId,
|
|
220
|
+
content: rec.content,
|
|
221
|
+
};
|
|
222
|
+
}
|
|
223
|
+
return {
|
|
224
|
+
type: "tool_result",
|
|
225
|
+
tool_use_id: toolUseId,
|
|
226
|
+
content:
|
|
227
|
+
typeof rec.content === "string" ? rec.content : safeJson(rec.content),
|
|
228
|
+
...(typeof rec.is_error === "boolean"
|
|
229
|
+
? { is_error: rec.is_error }
|
|
230
|
+
: {}),
|
|
231
|
+
};
|
|
232
|
+
}
|
|
233
|
+
if (typeof rec.type === "string") {
|
|
234
|
+
return block as ContentBlock;
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
return { type: "text", text: safeJson(block) };
|
|
238
|
+
}
|
|
239
|
+
|
|
185
240
|
/**
|
|
186
241
|
* Resolve a stored `messages.content` value to a `ContentBlock[]`.
|
|
187
242
|
*
|
|
@@ -192,6 +247,11 @@ function resolveRefToBlocks(ref: MessageContentRef): ContentBlock[] {
|
|
|
192
247
|
* (parity with the legacy readers); any other legacy plain string or
|
|
193
248
|
* non-array JSON becomes a text block carrying the raw value.
|
|
194
249
|
*
|
|
250
|
+
* Every returned block is guaranteed to satisfy the ContentBlock schema —
|
|
251
|
+
* historical rows with malformed or retired block shapes are repaired
|
|
252
|
+
* per-block ({@link coerceLegacyBlock}) rather than passed through, so
|
|
253
|
+
* consumers can use variant fields without runtime shape guards.
|
|
254
|
+
*
|
|
195
255
|
* Never throws — content reads must not take down read paths.
|
|
196
256
|
*/
|
|
197
257
|
export function resolveMessageContentBlocks(raw: unknown): ContentBlock[] {
|
|
@@ -221,15 +281,17 @@ export function resolveMessageContentBlocks(raw: unknown): ContentBlock[] {
|
|
|
221
281
|
if (result.success) {
|
|
222
282
|
return result.data;
|
|
223
283
|
}
|
|
224
|
-
// Historical rows may carry
|
|
225
|
-
//
|
|
226
|
-
//
|
|
227
|
-
// wrap; this is the one legacy boundary the schema cannot close.
|
|
284
|
+
// Historical rows may carry malformed or retired block shapes. Repair
|
|
285
|
+
// per block — valid blocks stay untouched — so the returned array
|
|
286
|
+
// always satisfies the schema. Only the rare invalid row pays this.
|
|
228
287
|
log.warn(
|
|
229
288
|
{ issueCount: result.error.issues.length },
|
|
230
|
-
"Inline content array has
|
|
289
|
+
"Inline content array has invalid block shapes; repairing per block",
|
|
231
290
|
);
|
|
232
|
-
return parsed
|
|
291
|
+
return parsed.map((block) => {
|
|
292
|
+
const one = contentBlockSchema.safeParse(block);
|
|
293
|
+
return one.success ? one.data : coerceLegacyBlock(block);
|
|
294
|
+
});
|
|
233
295
|
}
|
|
234
296
|
return [{ type: "text", text: raw }];
|
|
235
297
|
}
|
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
import type { Database } from "bun:sqlite";
|
|
2
|
+
|
|
3
|
+
import { getMemoryDbPath } from "../../util/memory-db-path.js";
|
|
4
|
+
import {
|
|
5
|
+
type DrizzleDb,
|
|
6
|
+
getMemorySqlite,
|
|
7
|
+
getSqliteFrom,
|
|
8
|
+
} from "../db-connection.js";
|
|
9
|
+
import {
|
|
10
|
+
drainStagedTable,
|
|
11
|
+
type RelocationSpec,
|
|
12
|
+
stageTableForRelocation,
|
|
13
|
+
} from "./helpers/relocation.js";
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* Readers of `memory_v2_injection_events` bound their scans to the last
|
|
17
|
+
* 6 half-lives (6 × 3 days) — events past that window contribute <1.6% each
|
|
18
|
+
* to the decayed score and are never queried. Mirrors `READ_WINDOW_MS` in
|
|
19
|
+
* `plugins/defaults/memory/v2/injection-events.ts` (duplicated by design:
|
|
20
|
+
* persistence migrations do not import plugin code).
|
|
21
|
+
*/
|
|
22
|
+
const READ_WINDOW_MS = 6 * 3 * 24 * 60 * 60 * 1000;
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* How to drain `memory_v2_injection_events` from `main` into the memory DB.
|
|
26
|
+
* Rows older than the score read window are purged without copying — no
|
|
27
|
+
* reader ever looks at them, so carrying them over would only re-seed dead
|
|
28
|
+
* weight in the new file.
|
|
29
|
+
*/
|
|
30
|
+
export const INJECTION_EVENTS_RELOCATION: RelocationSpec = {
|
|
31
|
+
table: "memory_v2_injection_events",
|
|
32
|
+
targetDbPath: getMemoryDbPath,
|
|
33
|
+
columns: ["id", "slug", "injected_at"],
|
|
34
|
+
copyWhere: `injected_at >= strftime('%s','now') * 1000 - ${READ_WINDOW_MS}`,
|
|
35
|
+
};
|
|
36
|
+
|
|
37
|
+
const CREATE_TABLE = /*sql*/ `
|
|
38
|
+
CREATE TABLE IF NOT EXISTS memory_v2_injection_events (
|
|
39
|
+
id INTEGER PRIMARY KEY,
|
|
40
|
+
slug TEXT NOT NULL,
|
|
41
|
+
injected_at INTEGER NOT NULL
|
|
42
|
+
)
|
|
43
|
+
`;
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* Create the `memory_v2_injection_events` table and its indexes on the memory
|
|
47
|
+
* connection. Idempotent (`IF NOT EXISTS`) — the dedicated connection itself
|
|
48
|
+
* performs no DDL on open, so this migration owns the schema. Exported so
|
|
49
|
+
* tests can stand up the memory-side schema without running the full drain.
|
|
50
|
+
*/
|
|
51
|
+
export function ensureInjectionEventsSchema(memoryRaw: Database): void {
|
|
52
|
+
memoryRaw.exec(CREATE_TABLE);
|
|
53
|
+
memoryRaw.exec(/*sql*/ `
|
|
54
|
+
CREATE INDEX IF NOT EXISTS idx_memory_v2_injection_events_slug_time
|
|
55
|
+
ON memory_v2_injection_events (slug, injected_at)
|
|
56
|
+
`);
|
|
57
|
+
memoryRaw.exec(/*sql*/ `
|
|
58
|
+
CREATE INDEX IF NOT EXISTS idx_memory_v2_injection_events_time
|
|
59
|
+
ON memory_v2_injection_events (injected_at)
|
|
60
|
+
`);
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/**
|
|
64
|
+
* Move `memory_v2_injection_events` — the append-only EMA event log behind
|
|
65
|
+
* memory router tier-2 scoring — into the dedicated memory database
|
|
66
|
+
* (`assistant-memory.db`), alongside `memory_jobs` (migration 298). The log
|
|
67
|
+
* grows with every router selection; housing it with the other high-churn
|
|
68
|
+
* memory state keeps the main DB and its WAL out of that write path, and the
|
|
69
|
+
* accessors in `plugins/defaults/memory/v2/injection-events.ts` read/write it
|
|
70
|
+
* over the dedicated memory connection (see `getMemoryDb()`).
|
|
71
|
+
*
|
|
72
|
+
* Like migrations 297/298 the move is incremental: create the table (and
|
|
73
|
+
* indexes) on the memory connection, rename any populated
|
|
74
|
+
* `main.memory_v2_injection_events` aside to
|
|
75
|
+
* `memory_v2_injection_events__relocating`, then drain it in awaited batches
|
|
76
|
+
* (see `helpers/relocation.ts`) per {@link INJECTION_EVENTS_RELOCATION}. On a
|
|
77
|
+
* fresh install the main-side table created by migration 256 is empty, so
|
|
78
|
+
* staging just drops it.
|
|
79
|
+
*
|
|
80
|
+
* Throws (rather than returning) if the memory database cannot be opened, so
|
|
81
|
+
* the runner records the step as failed instead of applied and retries it on
|
|
82
|
+
* a later boot — never renaming the source aside without a target to write
|
|
83
|
+
* to. The throw is caught per-step by the runner, so startup is not aborted.
|
|
84
|
+
*/
|
|
85
|
+
export async function migrateMoveInjectionEventsToMemoryDb(
|
|
86
|
+
database: DrizzleDb,
|
|
87
|
+
): Promise<void> {
|
|
88
|
+
const memoryRaw = getMemorySqlite();
|
|
89
|
+
if (!memoryRaw) {
|
|
90
|
+
throw new Error(
|
|
91
|
+
"memory database unavailable — deferring memory_v2_injection_events relocation",
|
|
92
|
+
);
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
ensureInjectionEventsSchema(memoryRaw);
|
|
96
|
+
|
|
97
|
+
const raw = getSqliteFrom(database);
|
|
98
|
+
const needsDrain = stageTableForRelocation(
|
|
99
|
+
raw,
|
|
100
|
+
INJECTION_EVENTS_RELOCATION.table,
|
|
101
|
+
);
|
|
102
|
+
|
|
103
|
+
if (needsDrain) await drainStagedTable(raw, INJECTION_EVENTS_RELOCATION);
|
|
104
|
+
}
|
|
@@ -7,7 +7,9 @@ import {
|
|
|
7
7
|
} from "drizzle-orm/sqlite-core";
|
|
8
8
|
|
|
9
9
|
// Time-series of memory-v2 card injections, used by the router to decay a
|
|
10
|
-
// concept's recent injection pressure.
|
|
10
|
+
// concept's recent injection pressure. Lives in the dedicated memory database
|
|
11
|
+
// (`assistant-memory.db`), not main — access it via the memory connection
|
|
12
|
+
// (`getMemoryDb()` / `getMemorySqlite()`).
|
|
11
13
|
export const memoryV2InjectionEvents = sqliteTable(
|
|
12
14
|
"memory_v2_injection_events",
|
|
13
15
|
{
|
package/src/persistence/steps.ts
CHANGED
|
@@ -433,6 +433,7 @@ import { migrateAddProcessingResumeAttempts } from "./migrations/322-add-process
|
|
|
433
433
|
import { migrateDeleteNonDefaultMemoryScopes } from "./migrations/323-delete-non-default-memory-scopes.js";
|
|
434
434
|
import { migrateMessageFinalizedColumn } from "./migrations/324-message-finalized-column.js";
|
|
435
435
|
import { createConfigSettingEventsTable } from "./migrations/325-create-config-setting-events.js";
|
|
436
|
+
import { migrateMoveInjectionEventsToMemoryDb } from "./migrations/326-move-injection-events-to-memory-db.js";
|
|
436
437
|
import type { MigrationStep } from "./migrations/run-migrations.js";
|
|
437
438
|
|
|
438
439
|
export const migrationSteps: MigrationStep[] = [
|
|
@@ -1337,4 +1338,5 @@ export const migrationSteps: MigrationStep[] = [
|
|
|
1337
1338
|
migrateDeleteNonDefaultMemoryScopes,
|
|
1338
1339
|
migrateMessageFinalizedColumn,
|
|
1339
1340
|
createConfigSettingEventsTable,
|
|
1341
|
+
migrateMoveInjectionEventsToMemoryDb,
|
|
1340
1342
|
];
|
|
@@ -8,8 +8,9 @@
|
|
|
8
8
|
* the *main* WAL is exactly what this split exists to prevent.
|
|
9
9
|
* 2. The main connection no longer ATTACHes the memory file: there is no
|
|
10
10
|
* `memory` schema on its `database_list`.
|
|
11
|
-
* 3.
|
|
12
|
-
* connection
|
|
11
|
+
* 3. The relocated memory tables (`memory_jobs`, `memory_v2_injection_events`)
|
|
12
|
+
* live in the dedicated memory connection, not in the main connection —
|
|
13
|
+
* proving the physical split.
|
|
13
14
|
* 4. `runAsyncSqlite({ dbPath })` targets the given file via the sqlite3
|
|
14
15
|
* CLI backend, leaving the main DB untouched.
|
|
15
16
|
*/
|
|
@@ -51,23 +52,26 @@ describe("memory database connection", () => {
|
|
|
51
52
|
expect(attached.some((e) => e.name === "memory")).toBe(false);
|
|
52
53
|
});
|
|
53
54
|
|
|
54
|
-
test("memory_jobs
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
55
|
+
test.each(["memory_jobs", "memory_v2_injection_events"])(
|
|
56
|
+
"%s lives in the memory connection, not main",
|
|
57
|
+
(table) => {
|
|
58
|
+
const inMemory = getMemorySqlite()!
|
|
59
|
+
.query<
|
|
60
|
+
{ name: string },
|
|
61
|
+
[string]
|
|
62
|
+
>(`SELECT name FROM sqlite_master WHERE type='table' AND name = ?`)
|
|
63
|
+
.get(table);
|
|
64
|
+
expect(inMemory?.name).toBe(table);
|
|
62
65
|
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
66
|
+
const inMain = getSqlite()
|
|
67
|
+
.query<
|
|
68
|
+
{ name: string },
|
|
69
|
+
[string]
|
|
70
|
+
>(`SELECT name FROM main.sqlite_master WHERE name = ?`)
|
|
71
|
+
.get(table);
|
|
72
|
+
expect(inMain).toBeNull();
|
|
73
|
+
},
|
|
74
|
+
);
|
|
71
75
|
|
|
72
76
|
test.if(sqlite3Available)(
|
|
73
77
|
"runAsyncSqlite({ dbPath }) targets the given file, not the main DB",
|
|
@@ -26,6 +26,8 @@ const { drainStagedTable, stageTableForRelocation } =
|
|
|
26
26
|
await import("../../../../persistence/migrations/helpers/relocation.js");
|
|
27
27
|
const { MEMORY_JOBS_RELOCATION } =
|
|
28
28
|
await import("../../../../persistence/migrations/298-move-memory-jobs-to-memory-db.js");
|
|
29
|
+
const { INJECTION_EVENTS_RELOCATION } =
|
|
30
|
+
await import("../../../../persistence/migrations/326-move-injection-events-to-memory-db.js");
|
|
29
31
|
|
|
30
32
|
await initializeDb();
|
|
31
33
|
|
|
@@ -128,3 +130,50 @@ describe("memory_jobs drain", () => {
|
|
|
128
130
|
]);
|
|
129
131
|
});
|
|
130
132
|
});
|
|
133
|
+
|
|
134
|
+
describe("memory_v2_injection_events drain", () => {
|
|
135
|
+
test("copies in-window rows, purges rows older than the read window, drops staging", async () => {
|
|
136
|
+
const sqlite = getSqlite();
|
|
137
|
+
const memory = getMemorySqlite()!;
|
|
138
|
+
|
|
139
|
+
// Clean slate: empty live table, fresh populated staging table.
|
|
140
|
+
memory.exec(`DELETE FROM memory_v2_injection_events`);
|
|
141
|
+
sqlite.exec(
|
|
142
|
+
`DROP TABLE IF EXISTS main."memory_v2_injection_events__relocating"`,
|
|
143
|
+
);
|
|
144
|
+
sqlite.exec(/*sql*/ `
|
|
145
|
+
CREATE TABLE main."memory_v2_injection_events__relocating" (
|
|
146
|
+
id INTEGER PRIMARY KEY, slug TEXT NOT NULL, injected_at INTEGER NOT NULL
|
|
147
|
+
)
|
|
148
|
+
`);
|
|
149
|
+
|
|
150
|
+
const now = Date.now();
|
|
151
|
+
const readWindowMs = 18 * 24 * 60 * 60 * 1000; // 6 half-lives of 3 days
|
|
152
|
+
const insert = sqlite.prepare(
|
|
153
|
+
`INSERT INTO main."memory_v2_injection_events__relocating"
|
|
154
|
+
(id, slug, injected_at) VALUES (?, ?, ?)`,
|
|
155
|
+
);
|
|
156
|
+
insert.run(1, "fresh-a", now - 1000);
|
|
157
|
+
insert.run(2, "fresh-b", now - readWindowMs / 2);
|
|
158
|
+
insert.run(3, "stale-a", now - readWindowMs - 24 * 60 * 60 * 1000);
|
|
159
|
+
insert.run(4, "stale-b", now - 2 * readWindowMs);
|
|
160
|
+
|
|
161
|
+
await drainStagedTable(sqlite, INJECTION_EVENTS_RELOCATION);
|
|
162
|
+
|
|
163
|
+
// Staging dropped.
|
|
164
|
+
expect(existsInMain("memory_v2_injection_events__relocating")).toBe(false);
|
|
165
|
+
|
|
166
|
+
// Only the in-window rows landed in the memory database, ids preserved;
|
|
167
|
+
// rows past the score read window were purged without being copied.
|
|
168
|
+
const kept = memory
|
|
169
|
+
.query<
|
|
170
|
+
{ id: number; slug: string },
|
|
171
|
+
[]
|
|
172
|
+
>(`SELECT id, slug FROM memory_v2_injection_events ORDER BY id`)
|
|
173
|
+
.all();
|
|
174
|
+
expect(kept).toEqual([
|
|
175
|
+
{ id: 1, slug: "fresh-a" },
|
|
176
|
+
{ id: 2, slug: "fresh-b" },
|
|
177
|
+
]);
|
|
178
|
+
});
|
|
179
|
+
});
|
|
@@ -51,15 +51,10 @@ mock.module("../../v2/now-text.js", () => ({
|
|
|
51
51
|
// zero scores since the test workspace has no event history.
|
|
52
52
|
const recordCalls: Array<{ slugs: readonly string[]; at: number }> = [];
|
|
53
53
|
mock.module("../../v2/injection-events.js", () => ({
|
|
54
|
-
recordInjectionEvents: (
|
|
55
|
-
_db: unknown,
|
|
56
|
-
slugs: readonly string[],
|
|
57
|
-
at: number,
|
|
58
|
-
) => {
|
|
54
|
+
recordInjectionEvents: (slugs: readonly string[], at: number) => {
|
|
59
55
|
recordCalls.push({ slugs, at });
|
|
60
56
|
},
|
|
61
57
|
computeInjectionScores: (
|
|
62
|
-
_db: unknown,
|
|
63
58
|
slugs: readonly string[],
|
|
64
59
|
_now: number,
|
|
65
60
|
): Map<string, number> => new Map(slugs.map((s) => [s, 0])),
|
|
@@ -336,7 +336,7 @@ async function handleEmaScores({
|
|
|
336
336
|
|
|
337
337
|
const pageIndex = await getPageIndex(getWorkspaceDir());
|
|
338
338
|
const slugs = pageIndex.entries.map((e) => e.slug);
|
|
339
|
-
const scores = computeInjectionScores(
|
|
339
|
+
const scores = computeInjectionScores(slugs, Date.now());
|
|
340
340
|
|
|
341
341
|
const entries: MemoryV2EmaScoresEntry[] = pageIndex.entries.map((entry) => ({
|
|
342
342
|
slug: entry.slug,
|
|
@@ -536,7 +536,6 @@ export async function handleSimulateRouter({
|
|
|
536
536
|
nowText,
|
|
537
537
|
priorEverInjected: [],
|
|
538
538
|
config: mergedConfig,
|
|
539
|
-
database: getDb(),
|
|
540
539
|
...(profileOverride !== undefined
|
|
541
540
|
? { overrideProfile: profileOverride }
|
|
542
541
|
: {}),
|
|
@@ -550,11 +549,7 @@ export async function handleSimulateRouter({
|
|
|
550
549
|
});
|
|
551
550
|
|
|
552
551
|
const pageIndex = await getPageIndex(workspaceDir);
|
|
553
|
-
const scores = computeInjectionScores(
|
|
554
|
-
getDb(),
|
|
555
|
-
routerResult.selectedSlugs,
|
|
556
|
-
Date.now(),
|
|
557
|
-
);
|
|
552
|
+
const scores = computeInjectionScores(routerResult.selectedSlugs, Date.now());
|
|
558
553
|
|
|
559
554
|
const sourceBySlug: Record<string, RouterSource> = {};
|
|
560
555
|
for (const [slug, source] of routerResult.sourceBySlug.entries()) {
|
|
@@ -660,7 +655,7 @@ export async function handleCompareRetrievers({
|
|
|
660
655
|
|
|
661
656
|
// The router is always comparand #1 (the harness self-test against its own
|
|
662
657
|
// logged ground truth).
|
|
663
|
-
const retrievers: Retriever[] = [createRouterRetriever(
|
|
658
|
+
const retrievers: Retriever[] = [createRouterRetriever()];
|
|
664
659
|
|
|
665
660
|
return runComparisonOverHistory({
|
|
666
661
|
db,
|
|
@@ -1,21 +1,25 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* Tests for `assistant/src/memory/v2/injection-events.ts` and
|
|
3
|
-
* migration `256-memory-v2-injection-events.ts`.
|
|
2
|
+
* Tests for `assistant/src/plugins/defaults/memory/v2/injection-events.ts` and
|
|
3
|
+
* the main-DB migration `256-memory-v2-injection-events.ts`.
|
|
4
4
|
*
|
|
5
5
|
* Coverage matrix:
|
|
6
|
-
* - Migration creates the table + both indexes; safe to
|
|
6
|
+
* - Migration 256 creates the main-side table + both indexes; safe to
|
|
7
|
+
* re-run. (The table is subsequently relocated to the memory DB by
|
|
8
|
+
* migration 326 — see table-relocation.test.ts for drain coverage.)
|
|
7
9
|
* - Backfill replays router-sourced concepts from memory_v2_activation_logs
|
|
8
10
|
* and is idempotent on a forced re-run with cleared checkpoint.
|
|
9
11
|
* - Backfill is a no-op when the activation-logs table doesn't exist
|
|
10
12
|
* (pre-234 DB).
|
|
11
|
-
* - recordInjectionEvents appends one row per slug per call
|
|
12
|
-
* is a no-op.
|
|
13
|
+
* - recordInjectionEvents appends one row per slug per call to the memory
|
|
14
|
+
* connection; empty list is a no-op.
|
|
13
15
|
* - computeInjectionScore matches the closed-form decay at known deltas
|
|
14
16
|
* (0d ≈ 1, 3d ≈ 0.5, 6d ≈ 0.25) and sums multiple events linearly.
|
|
15
17
|
* - computeInjectionScores returns the same per-slug values in batch and
|
|
16
18
|
* omits slugs with no events.
|
|
17
19
|
*
|
|
18
|
-
* Uses
|
|
20
|
+
* Uses in-memory bun:sqlite databases — the accessor tests install one into
|
|
21
|
+
* the `memory` singleton slot (where the accessors resolve their connection),
|
|
22
|
+
* the migration tests drive a plain main-DB handle. No real workspace DB.
|
|
19
23
|
*/
|
|
20
24
|
|
|
21
25
|
import { Database } from "bun:sqlite";
|
|
@@ -25,11 +29,16 @@ import { drizzle } from "drizzle-orm/bun-sqlite";
|
|
|
25
29
|
|
|
26
30
|
import type { DrizzleDb } from "../../../../../persistence/db-connection.js";
|
|
27
31
|
import { getSqliteFrom } from "../../../../../persistence/db-connection.js";
|
|
32
|
+
import {
|
|
33
|
+
clearStoredDb,
|
|
34
|
+
setStoredDb,
|
|
35
|
+
} from "../../../../../persistence/db-singleton.js";
|
|
28
36
|
import { migrateMemoryV2ActivationLogs } from "../../../../../persistence/migrations/234-memory-v2-activation-logs.js";
|
|
29
37
|
import {
|
|
30
38
|
downMemoryV2InjectionEvents,
|
|
31
39
|
migrateMemoryV2InjectionEvents,
|
|
32
40
|
} from "../../../../../persistence/migrations/256-memory-v2-injection-events.js";
|
|
41
|
+
import { ensureInjectionEventsSchema } from "../../../../../persistence/migrations/326-move-injection-events-to-memory-db.js";
|
|
33
42
|
import * as schema from "../../../../../persistence/schema/index.js";
|
|
34
43
|
import {
|
|
35
44
|
computeInjectionScore,
|
|
@@ -51,14 +60,25 @@ const CHECKPOINTS_DDL = /*sql*/ `
|
|
|
51
60
|
|
|
52
61
|
let sqlite: Database;
|
|
53
62
|
let database: DrizzleDb;
|
|
63
|
+
let memorySqlite: Database;
|
|
54
64
|
|
|
55
65
|
beforeEach(() => {
|
|
56
66
|
sqlite = new Database(":memory:");
|
|
57
67
|
database = drizzle(sqlite, { schema });
|
|
58
68
|
getSqliteFrom(database).exec(CHECKPOINTS_DDL);
|
|
69
|
+
|
|
70
|
+
// The accessors resolve the dedicated memory connection through the
|
|
71
|
+
// `memory` singleton slot — install a fresh in-memory DB there with the
|
|
72
|
+
// relocated table's schema. `clearStoredDb` in afterEach runs the closer.
|
|
73
|
+
memorySqlite = new Database(":memory:");
|
|
74
|
+
ensureInjectionEventsSchema(memorySqlite);
|
|
75
|
+
setStoredDb("memory", drizzle(memorySqlite, { schema }), () =>
|
|
76
|
+
memorySqlite.close(),
|
|
77
|
+
);
|
|
59
78
|
});
|
|
60
79
|
|
|
61
80
|
afterEach(() => {
|
|
81
|
+
clearStoredDb("memory");
|
|
62
82
|
sqlite.close();
|
|
63
83
|
});
|
|
64
84
|
|
|
@@ -197,14 +217,10 @@ describe("migrateMemoryV2InjectionEvents", () => {
|
|
|
197
217
|
});
|
|
198
218
|
|
|
199
219
|
describe("recordInjectionEvents", () => {
|
|
200
|
-
beforeEach(() => {
|
|
201
|
-
migrateMemoryV2InjectionEvents(database);
|
|
202
|
-
});
|
|
203
|
-
|
|
204
220
|
test("appends one row per slug at the same timestamp", () => {
|
|
205
221
|
const t = 1_000_000;
|
|
206
|
-
recordInjectionEvents(
|
|
207
|
-
const rows =
|
|
222
|
+
recordInjectionEvents(["alice", "bob", "alice"], t);
|
|
223
|
+
const rows = memorySqlite
|
|
208
224
|
.query(
|
|
209
225
|
`SELECT slug, injected_at FROM memory_v2_injection_events ORDER BY id`,
|
|
210
226
|
)
|
|
@@ -216,9 +232,23 @@ describe("recordInjectionEvents", () => {
|
|
|
216
232
|
]);
|
|
217
233
|
});
|
|
218
234
|
|
|
235
|
+
test("writes land in the memory connection, not the main DB handle", () => {
|
|
236
|
+
recordInjectionEvents(["alice"], 1_000_000);
|
|
237
|
+
const inMain = getSqliteFrom(database)
|
|
238
|
+
.query(
|
|
239
|
+
`SELECT name FROM sqlite_master WHERE type='table' AND name='memory_v2_injection_events'`,
|
|
240
|
+
)
|
|
241
|
+
.get();
|
|
242
|
+
expect(inMain).toBeFalsy();
|
|
243
|
+
const { n } = memorySqlite
|
|
244
|
+
.query(`SELECT COUNT(*) as n FROM memory_v2_injection_events`)
|
|
245
|
+
.get() as { n: number };
|
|
246
|
+
expect(n).toBe(1);
|
|
247
|
+
});
|
|
248
|
+
|
|
219
249
|
test("empty list is a no-op", () => {
|
|
220
|
-
recordInjectionEvents(
|
|
221
|
-
const { n } =
|
|
250
|
+
recordInjectionEvents([], 1_000_000);
|
|
251
|
+
const { n } = memorySqlite
|
|
222
252
|
.query(`SELECT COUNT(*) as n FROM memory_v2_injection_events`)
|
|
223
253
|
.get() as { n: number };
|
|
224
254
|
expect(n).toBe(0);
|
|
@@ -226,87 +256,55 @@ describe("recordInjectionEvents", () => {
|
|
|
226
256
|
});
|
|
227
257
|
|
|
228
258
|
describe("computeInjectionScore", () => {
|
|
229
|
-
beforeEach(() => {
|
|
230
|
-
migrateMemoryV2InjectionEvents(database);
|
|
231
|
-
});
|
|
232
|
-
|
|
233
259
|
test("returns 0 for a slug with no events", () => {
|
|
234
|
-
expect(computeInjectionScore(
|
|
260
|
+
expect(computeInjectionScore("missing", Date.now())).toBe(0);
|
|
235
261
|
});
|
|
236
262
|
|
|
237
263
|
test("single event 0 days ago → score ≈ 1", () => {
|
|
238
264
|
const now = 10_000_000_000;
|
|
239
|
-
recordInjectionEvents(
|
|
240
|
-
expect(computeInjectionScore(
|
|
265
|
+
recordInjectionEvents(["alice"], now);
|
|
266
|
+
expect(computeInjectionScore("alice", now)).toBeCloseTo(1, 5);
|
|
241
267
|
});
|
|
242
268
|
|
|
243
269
|
test("single event 3 days (one half-life) ago → score ≈ 0.5", () => {
|
|
244
270
|
const now = 10_000_000_000;
|
|
245
|
-
recordInjectionEvents(
|
|
246
|
-
|
|
247
|
-
["alice"],
|
|
248
|
-
now - INJECTION_SCORE_HALF_LIFE_MS,
|
|
249
|
-
);
|
|
250
|
-
expect(computeInjectionScore(database, "alice", now)).toBeCloseTo(0.5, 5);
|
|
271
|
+
recordInjectionEvents(["alice"], now - INJECTION_SCORE_HALF_LIFE_MS);
|
|
272
|
+
expect(computeInjectionScore("alice", now)).toBeCloseTo(0.5, 5);
|
|
251
273
|
});
|
|
252
274
|
|
|
253
275
|
test("single event 6 days (two half-lives) ago → score ≈ 0.25", () => {
|
|
254
276
|
const now = 10_000_000_000;
|
|
255
|
-
recordInjectionEvents(
|
|
256
|
-
|
|
257
|
-
["alice"],
|
|
258
|
-
now - 2 * INJECTION_SCORE_HALF_LIFE_MS,
|
|
259
|
-
);
|
|
260
|
-
expect(computeInjectionScore(database, "alice", now)).toBeCloseTo(0.25, 5);
|
|
277
|
+
recordInjectionEvents(["alice"], now - 2 * INJECTION_SCORE_HALF_LIFE_MS);
|
|
278
|
+
expect(computeInjectionScore("alice", now)).toBeCloseTo(0.25, 5);
|
|
261
279
|
});
|
|
262
280
|
|
|
263
281
|
test("multiple events sum independently", () => {
|
|
264
282
|
const now = 10_000_000_000;
|
|
265
|
-
recordInjectionEvents(
|
|
266
|
-
recordInjectionEvents(
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
now - INJECTION_SCORE_HALF_LIFE_MS,
|
|
270
|
-
);
|
|
271
|
-
recordInjectionEvents(
|
|
272
|
-
database,
|
|
273
|
-
["alice"],
|
|
274
|
-
now - 2 * INJECTION_SCORE_HALF_LIFE_MS,
|
|
275
|
-
);
|
|
276
|
-
expect(computeInjectionScore(database, "alice", now)).toBeCloseTo(1.75, 5);
|
|
283
|
+
recordInjectionEvents(["alice"], now);
|
|
284
|
+
recordInjectionEvents(["alice"], now - INJECTION_SCORE_HALF_LIFE_MS);
|
|
285
|
+
recordInjectionEvents(["alice"], now - 2 * INJECTION_SCORE_HALF_LIFE_MS);
|
|
286
|
+
expect(computeInjectionScore("alice", now)).toBeCloseTo(1.75, 5);
|
|
277
287
|
});
|
|
278
288
|
});
|
|
279
289
|
|
|
280
290
|
describe("computeInjectionScores", () => {
|
|
281
|
-
beforeEach(() => {
|
|
282
|
-
migrateMemoryV2InjectionEvents(database);
|
|
283
|
-
});
|
|
284
|
-
|
|
285
291
|
test("returns the same per-slug values as the single-slug helper", () => {
|
|
286
292
|
const now = 10_000_000_000;
|
|
287
|
-
recordInjectionEvents(
|
|
288
|
-
recordInjectionEvents(
|
|
289
|
-
database,
|
|
290
|
-
["alice"],
|
|
291
|
-
now - INJECTION_SCORE_HALF_LIFE_MS,
|
|
292
|
-
);
|
|
293
|
+
recordInjectionEvents(["alice", "bob"], now);
|
|
294
|
+
recordInjectionEvents(["alice"], now - INJECTION_SCORE_HALF_LIFE_MS);
|
|
293
295
|
|
|
294
|
-
const scores = computeInjectionScores(
|
|
295
|
-
database,
|
|
296
|
-
["alice", "bob", "ghost"],
|
|
297
|
-
now,
|
|
298
|
-
);
|
|
296
|
+
const scores = computeInjectionScores(["alice", "bob", "ghost"], now);
|
|
299
297
|
expect(scores.get("alice")).toBeCloseTo(1.5, 5);
|
|
300
298
|
expect(scores.get("bob")).toBeCloseTo(1, 5);
|
|
301
299
|
// ghost has no events — omitted from the result, not present as 0.
|
|
302
300
|
expect(scores.has("ghost")).toBe(false);
|
|
303
301
|
expect(scores.get("alice")).toBeCloseTo(
|
|
304
|
-
computeInjectionScore(
|
|
302
|
+
computeInjectionScore("alice", now),
|
|
305
303
|
5,
|
|
306
304
|
);
|
|
307
305
|
});
|
|
308
306
|
|
|
309
307
|
test("empty slug list returns empty map", () => {
|
|
310
|
-
expect(computeInjectionScores(
|
|
308
|
+
expect(computeInjectionScores([], Date.now()).size).toBe(0);
|
|
311
309
|
});
|
|
312
310
|
});
|
|
@@ -74,13 +74,12 @@ mock.module("../skill-store.js", () => ({
|
|
|
74
74
|
}));
|
|
75
75
|
|
|
76
76
|
// Stub `computeInjectionScores` so tier-2 tests can dictate scores
|
|
77
|
-
// without spinning up a real bun:sqlite db
|
|
78
|
-
// covered by the splitTier2 unit tests in
|
|
79
|
-
// score-formula tests in injection-events.test.ts.
|
|
77
|
+
// without spinning up a real bun:sqlite db in the memory singleton slot.
|
|
78
|
+
// Real production wiring is covered by the splitTier2 unit tests in
|
|
79
|
+
// page-index.test.ts and the score-formula tests in injection-events.test.ts.
|
|
80
80
|
const scoresStub = new Map<string, number>();
|
|
81
81
|
mock.module("../injection-events.js", () => ({
|
|
82
82
|
computeInjectionScores: (
|
|
83
|
-
_db: unknown,
|
|
84
83
|
slugs: readonly string[],
|
|
85
84
|
_now: number,
|
|
86
85
|
): Map<string, number> => {
|
|
@@ -956,10 +955,6 @@ describe("runRouter — tier 1 (recently modified)", () => {
|
|
|
956
955
|
// ---------------------------------------------------------------------------
|
|
957
956
|
|
|
958
957
|
describe("runRouter — tier 2 (highest EMA)", () => {
|
|
959
|
-
// Any non-null value passes the `params.database` check in the orchestrator;
|
|
960
|
-
// the real db is never touched because computeInjectionScores is mocked.
|
|
961
|
-
const stubDb = {} as Parameters<typeof runRouter>[0]["database"];
|
|
962
|
-
|
|
963
958
|
beforeEach(async () => {
|
|
964
959
|
await writePage(workspaceDir, makePage("alpha", { summary: "A" }));
|
|
965
960
|
await writePage(workspaceDir, makePage("bravo", { summary: "B" }));
|
|
@@ -974,7 +969,6 @@ describe("runRouter — tier 2 (highest EMA)", () => {
|
|
|
974
969
|
workspaceDir,
|
|
975
970
|
...COMMON_PARAMS,
|
|
976
971
|
config: makeConfig(),
|
|
977
|
-
database: stubDb,
|
|
978
972
|
});
|
|
979
973
|
expect(providerCalls).toHaveLength(1);
|
|
980
974
|
});
|
|
@@ -989,7 +983,6 @@ describe("runRouter — tier 2 (highest EMA)", () => {
|
|
|
989
983
|
workspaceDir,
|
|
990
984
|
...COMMON_PARAMS,
|
|
991
985
|
config: makeConfig({ tier2Size: 2 }),
|
|
992
|
-
database: stubDb,
|
|
993
986
|
});
|
|
994
987
|
expect(providerCalls.length).toBe(2);
|
|
995
988
|
|
|
@@ -1025,7 +1018,6 @@ describe("runRouter — tier 2 (highest EMA)", () => {
|
|
|
1025
1018
|
workspaceDir,
|
|
1026
1019
|
...COMMON_PARAMS,
|
|
1027
1020
|
config: makeConfig({ tier1Size: 2, tier2Size: 2 }),
|
|
1028
|
-
database: stubDb,
|
|
1029
1021
|
});
|
|
1030
1022
|
expect(providerCalls.length).toBe(3);
|
|
1031
1023
|
|
|
@@ -1054,7 +1046,6 @@ describe("runRouter — tier 2 (highest EMA)", () => {
|
|
|
1054
1046
|
workspaceDir,
|
|
1055
1047
|
...COMMON_PARAMS,
|
|
1056
1048
|
config: makeConfig({ tier2Size: 100 }),
|
|
1057
|
-
database: stubDb,
|
|
1058
1049
|
});
|
|
1059
1050
|
expect(providerCalls.length).toBe(2);
|
|
1060
1051
|
const tier2Prompt = providerCalls[0].systemPrompt ?? "";
|
|
@@ -1071,7 +1062,6 @@ describe("runRouter — tier 2 (highest EMA)", () => {
|
|
|
1071
1062
|
workspaceDir,
|
|
1072
1063
|
...COMMON_PARAMS,
|
|
1073
1064
|
config: makeConfig({ tier1Size: 1, tier2Size: 1 }),
|
|
1074
|
-
database: stubDb,
|
|
1075
1065
|
});
|
|
1076
1066
|
|
|
1077
1067
|
// Every selected slug should have a tier tag — exactly one of:
|
|
@@ -1092,20 +1082,17 @@ describe("runRouter — tier 2 (highest EMA)", () => {
|
|
|
1092
1082
|
expect(tags.has("tier2")).toBe(true);
|
|
1093
1083
|
});
|
|
1094
1084
|
|
|
1095
|
-
test("tier2_size set
|
|
1096
|
-
|
|
1085
|
+
test("tier2_size set with all-zero scores skips tier 2 (degraded memory DB)", async () => {
|
|
1086
|
+
// No scores stubbed — mirrors `computeInjectionScores` returning an
|
|
1087
|
+
// empty map when the memory connection is unavailable. Tier 2 must
|
|
1088
|
+
// select nothing rather than pulling in arbitrary pages.
|
|
1097
1089
|
providerStub = makeProvider(toolUseResponse([1]));
|
|
1098
1090
|
await runRouter({
|
|
1099
1091
|
workspaceDir,
|
|
1100
1092
|
...COMMON_PARAMS,
|
|
1101
1093
|
config: makeConfig({ tier2Size: 2 }),
|
|
1102
|
-
// No database → tier 2 silently skipped.
|
|
1103
1094
|
});
|
|
1104
1095
|
expect(providerCalls).toHaveLength(1);
|
|
1105
|
-
const warned = warnLogs.some((l) =>
|
|
1106
|
-
JSON.stringify(l.args).includes("tier2_size set but no database"),
|
|
1107
|
-
);
|
|
1108
|
-
expect(warned).toBe(true);
|
|
1109
1096
|
});
|
|
1110
1097
|
});
|
|
1111
1098
|
|
|
@@ -7,7 +7,6 @@
|
|
|
7
7
|
* its own injected ground truth.
|
|
8
8
|
*/
|
|
9
9
|
|
|
10
|
-
import type { DrizzleDb } from "../../../../../persistence/db-connection.js";
|
|
11
10
|
import { runRouter } from "../router.js";
|
|
12
11
|
import type {
|
|
13
12
|
RetrievalInput,
|
|
@@ -15,12 +14,7 @@ import type {
|
|
|
15
14
|
Retriever,
|
|
16
15
|
} from "./retriever.js";
|
|
17
16
|
|
|
18
|
-
|
|
19
|
-
* @param database optional handle for tier-2 EMA scoring, forwarded to
|
|
20
|
-
* `runRouter`. Omit to exercise only the tier-1 / tier-3 paths (as the router's
|
|
21
|
-
* own tests do).
|
|
22
|
-
*/
|
|
23
|
-
export function createRouterRetriever(database?: DrizzleDb): Retriever {
|
|
17
|
+
export function createRouterRetriever(): Retriever {
|
|
24
18
|
return {
|
|
25
19
|
name: "router",
|
|
26
20
|
async retrieve(input: RetrievalInput): Promise<RetrievalOutput> {
|
|
@@ -31,7 +25,6 @@ export function createRouterRetriever(database?: DrizzleDb): Retriever {
|
|
|
31
25
|
priorEverInjected: input.priorEverInjected,
|
|
32
26
|
config: input.config,
|
|
33
27
|
...(input.signal ? { signal: input.signal } : {}),
|
|
34
|
-
...(database ? { database } : {}),
|
|
35
28
|
});
|
|
36
29
|
return {
|
|
37
30
|
selectedSlugs: result.selectedSlugs,
|
|
@@ -1,5 +1,4 @@
|
|
|
1
|
-
import
|
|
2
|
-
import { getSqliteFrom } from "../../../../persistence/db-connection.js";
|
|
1
|
+
import { getMemorySqlite } from "../../../../persistence/db-connection.js";
|
|
3
2
|
import { getLogger } from "../logging.js";
|
|
4
3
|
|
|
5
4
|
const log = getLogger("memory-v2-injection-events");
|
|
@@ -18,25 +17,43 @@ export const INJECTION_SCORE_LAMBDA =
|
|
|
18
17
|
|
|
19
18
|
// Events past 6 half-lives contribute <1.6% each. Reads bound the scan to
|
|
20
19
|
// this window so per-slug score computation stays cheap as history grows.
|
|
20
|
+
// Migration 326 uses the same window to purge dead rows during relocation.
|
|
21
21
|
const READ_WINDOW_MS = 6 * INJECTION_SCORE_HALF_LIFE_MS;
|
|
22
22
|
|
|
23
23
|
function decayContribution(elapsedMs: number): number {
|
|
24
24
|
return Math.exp(-INJECTION_SCORE_LAMBDA * elapsedMs);
|
|
25
25
|
}
|
|
26
26
|
|
|
27
|
+
/**
|
|
28
|
+
* The dedicated memory connection (`assistant-memory.db`), where
|
|
29
|
+
* `memory_v2_injection_events` lives. `null` when the file cannot be opened
|
|
30
|
+
* — every caller here degrades rather than throwing: the event log is a
|
|
31
|
+
* scoring signal, and losing it must never break routing or a turn.
|
|
32
|
+
*/
|
|
33
|
+
function memorySqliteOrNull(context: string) {
|
|
34
|
+
const sqlite = getMemorySqlite();
|
|
35
|
+
if (!sqlite) {
|
|
36
|
+
log.warn(
|
|
37
|
+
{ context },
|
|
38
|
+
"memory database unavailable; injection events degraded",
|
|
39
|
+
);
|
|
40
|
+
}
|
|
41
|
+
return sqlite;
|
|
42
|
+
}
|
|
43
|
+
|
|
27
44
|
/**
|
|
28
45
|
* Append one event per slug. Best-effort — a SQLite write must never abort
|
|
29
46
|
* the agent turn on top of a successful routing decision the rest of the
|
|
30
47
|
* caller depends on.
|
|
31
48
|
*/
|
|
32
49
|
export function recordInjectionEvents(
|
|
33
|
-
database: DrizzleDb,
|
|
34
50
|
slugs: readonly string[],
|
|
35
51
|
injectedAt: number,
|
|
36
52
|
): void {
|
|
37
53
|
if (slugs.length === 0) return;
|
|
38
54
|
try {
|
|
39
|
-
const raw =
|
|
55
|
+
const raw = memorySqliteOrNull("recordInjectionEvents");
|
|
56
|
+
if (!raw) return;
|
|
40
57
|
const insert = raw.prepare(
|
|
41
58
|
`INSERT INTO memory_v2_injection_events (slug, injected_at) VALUES (?, ?)`,
|
|
42
59
|
);
|
|
@@ -52,14 +69,14 @@ export function recordInjectionEvents(
|
|
|
52
69
|
}
|
|
53
70
|
}
|
|
54
71
|
|
|
55
|
-
/**
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
72
|
+
/**
|
|
73
|
+
* `score(now) = Σᵢ exp(-λ × (now - tᵢ))` over events within READ_WINDOW_MS.
|
|
74
|
+
* Returns 0 when the memory database is unavailable.
|
|
75
|
+
*/
|
|
76
|
+
export function computeInjectionScore(slug: string, now: number): number {
|
|
77
|
+
const raw = memorySqliteOrNull("computeInjectionScore");
|
|
78
|
+
if (!raw) return 0;
|
|
61
79
|
const cutoff = now - READ_WINDOW_MS;
|
|
62
|
-
const raw = getSqliteFrom(database);
|
|
63
80
|
const rows = raw
|
|
64
81
|
.query(
|
|
65
82
|
`SELECT injected_at FROM memory_v2_injection_events
|
|
@@ -75,17 +92,19 @@ export function computeInjectionScore(
|
|
|
75
92
|
* Batch variant of `computeInjectionScore` — single SQL pass scoped to the
|
|
76
93
|
* requested slugs so tier assignment doesn't issue O(M) queries. Slugs
|
|
77
94
|
* with no events in the read window are omitted from the result; callers
|
|
78
|
-
* should treat a missing entry as score 0.
|
|
95
|
+
* should treat a missing entry as score 0. Returns an empty map when the
|
|
96
|
+
* memory database is unavailable, so a degraded connection reads as
|
|
97
|
+
* all-zero scores (tier 2 simply selects nothing).
|
|
79
98
|
*/
|
|
80
99
|
export function computeInjectionScores(
|
|
81
|
-
database: DrizzleDb,
|
|
82
100
|
slugs: readonly string[],
|
|
83
101
|
now: number,
|
|
84
102
|
): Map<string, number> {
|
|
85
103
|
const out = new Map<string, number>();
|
|
86
104
|
if (slugs.length === 0) return out;
|
|
105
|
+
const raw = memorySqliteOrNull("computeInjectionScores");
|
|
106
|
+
if (!raw) return out;
|
|
87
107
|
const cutoff = now - READ_WINDOW_MS;
|
|
88
|
-
const raw = getSqliteFrom(database);
|
|
89
108
|
const placeholders = slugs.map(() => "?").join(",");
|
|
90
109
|
const rows = raw
|
|
91
110
|
.query(
|
|
@@ -612,7 +612,6 @@ async function injectViaRouter(args: {
|
|
|
612
612
|
nowText,
|
|
613
613
|
priorEverInjected,
|
|
614
614
|
config,
|
|
615
|
-
database,
|
|
616
615
|
...(signal ? { signal } : {}),
|
|
617
616
|
});
|
|
618
617
|
|
|
@@ -622,7 +621,7 @@ async function injectViaRouter(args: {
|
|
|
622
621
|
// errors — a SQLite write must not abort the turn on top of a successful
|
|
623
622
|
// routing decision the rest of this function depends on.
|
|
624
623
|
if (routerResult.failureReason === null) {
|
|
625
|
-
recordInjectionEvents(
|
|
624
|
+
recordInjectionEvents(routerResult.selectedSlugs, Date.now());
|
|
626
625
|
}
|
|
627
626
|
|
|
628
627
|
if (routerResult.failureReason !== null) {
|
|
@@ -41,7 +41,6 @@ import {
|
|
|
41
41
|
import { z } from "zod";
|
|
42
42
|
|
|
43
43
|
import type { AssistantConfig } from "../../../../config/types.js";
|
|
44
|
-
import type { DrizzleDb } from "../../../../persistence/db-connection.js";
|
|
45
44
|
import {
|
|
46
45
|
cachedTextBlock,
|
|
47
46
|
extractToolUse,
|
|
@@ -186,13 +185,6 @@ interface RunRouterParams {
|
|
|
186
185
|
priorEverInjected: readonly EverInjectedEntry[];
|
|
187
186
|
config: AssistantConfig;
|
|
188
187
|
signal?: AbortSignal;
|
|
189
|
-
/**
|
|
190
|
-
* Database handle for reading EMA scores when `tier2_size` is set. When
|
|
191
|
-
* absent, tier 2 is silently skipped (pages flow tier 1 → tier 3). The
|
|
192
|
-
* production caller (`injectViaRouter`) always passes it; tests that
|
|
193
|
-
* only exercise tier 1 / tier 3 paths can omit it.
|
|
194
|
-
*/
|
|
195
|
-
database?: DrizzleDb;
|
|
196
188
|
/**
|
|
197
189
|
* Per-call profile override forwarded to `getConfiguredProvider`. When
|
|
198
190
|
* set, the `memoryRouter` call site resolves against this profile name
|
|
@@ -271,16 +263,14 @@ export async function runRouter(
|
|
|
271
263
|
|
|
272
264
|
let tier2: PageIndex | null = null;
|
|
273
265
|
let afterTier2: PageIndex = afterTier1;
|
|
274
|
-
if (tier2Size !== null &&
|
|
266
|
+
if (tier2Size !== null && afterTier1.entries.length > 0) {
|
|
267
|
+
// EMA scores come from the dedicated memory connection; when it is
|
|
268
|
+
// unavailable the scores read as all-zero and tier 2 selects nothing.
|
|
275
269
|
const slugs = afterTier1.entries.map((e) => e.slug);
|
|
276
|
-
const scores = computeInjectionScores(
|
|
270
|
+
const scores = computeInjectionScores(slugs, Date.now());
|
|
277
271
|
const split = splitTier2(afterTier1, tier2Size, scores);
|
|
278
272
|
tier2 = split.tier2;
|
|
279
273
|
afterTier2 = split.rest;
|
|
280
|
-
} else if (tier2Size !== null && !params.database) {
|
|
281
|
-
log.warn(
|
|
282
|
-
"tier2_size set but no database passed to runRouter; skipping tier 2",
|
|
283
|
-
);
|
|
284
274
|
}
|
|
285
275
|
|
|
286
276
|
const tier3Batches = partitionPageIndex(afterTier2, batchSize).filter(
|