@vellumai/assistant 0.10.5-dev.202607051933.b756a91 → 0.10.5-dev.202607052029.2d00037
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/Dockerfile +1 -0
- package/package.json +1 -1
- package/src/cli/commands/memory/__tests__/memory-items.test.ts +445 -0
- package/src/cli/commands/memory/index.ts +10 -1
- package/src/cli/commands/memory/items.ts +490 -0
- package/src/monitoring/__tests__/page-cache.test.ts +81 -0
- package/src/monitoring/page-cache.ts +152 -0
- package/src/monitoring/resource-sampler.ts +14 -3
- package/src/plugins/defaults/index.ts +4 -3
package/Dockerfile
CHANGED
package/package.json
CHANGED
|
@@ -0,0 +1,445 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Tests for the `assistant memory items` CLI subgroup (item CRUD).
|
|
3
|
+
*
|
|
4
|
+
* Validates:
|
|
5
|
+
* - Verb registration (list/get/create/update/delete) under `memory items`.
|
|
6
|
+
* - Each verb maps to the right `cliIpcCall` method with the right
|
|
7
|
+
* pathParams/queryParams/body shape.
|
|
8
|
+
* - Local validation (missing update flags, invalid --importance, blank ID)
|
|
9
|
+
* fails before any IPC call.
|
|
10
|
+
* - `delete` refuses to run non-interactively without --force.
|
|
11
|
+
* - IPC error paths return a non-zero exit code without throwing.
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
import { beforeEach, describe, expect, mock, test } from "bun:test";
|
|
15
|
+
|
|
16
|
+
import { Command } from "commander";
|
|
17
|
+
|
|
18
|
+
// ---------------------------------------------------------------------------
|
|
19
|
+
// Mock state
|
|
20
|
+
// ---------------------------------------------------------------------------
|
|
21
|
+
|
|
22
|
+
/** The last `cliIpcCall` invocation captured for assertions. */
|
|
23
|
+
let lastIpcCall: {
|
|
24
|
+
method: string;
|
|
25
|
+
|
|
26
|
+
params?: any;
|
|
27
|
+
} | null = null;
|
|
28
|
+
|
|
29
|
+
/** The result that cliIpcCall will return. */
|
|
30
|
+
let mockIpcResult: {
|
|
31
|
+
ok: boolean;
|
|
32
|
+
result?: unknown;
|
|
33
|
+
error?: string;
|
|
34
|
+
statusCode?: number;
|
|
35
|
+
} = { ok: true, result: {} };
|
|
36
|
+
|
|
37
|
+
/** Captured log output for assertion. */
|
|
38
|
+
let logOutput: string[] = [];
|
|
39
|
+
|
|
40
|
+
// ---------------------------------------------------------------------------
|
|
41
|
+
// Mocks
|
|
42
|
+
// ---------------------------------------------------------------------------
|
|
43
|
+
|
|
44
|
+
mock.module("../../../../ipc/cli-client.js", () => ({
|
|
45
|
+
cliIpcCall: async (method: string, params?: unknown) => {
|
|
46
|
+
lastIpcCall = { method, params };
|
|
47
|
+
return mockIpcResult;
|
|
48
|
+
},
|
|
49
|
+
exitFromIpcResult: (r: { error?: string; statusCode?: number }) => {
|
|
50
|
+
process.exitCode =
|
|
51
|
+
r.statusCode === undefined
|
|
52
|
+
? 10
|
|
53
|
+
: r.statusCode >= 500
|
|
54
|
+
? 3
|
|
55
|
+
: r.statusCode >= 400
|
|
56
|
+
? 2
|
|
57
|
+
: 1;
|
|
58
|
+
throw new Error(r.error ?? "Unknown error");
|
|
59
|
+
},
|
|
60
|
+
}));
|
|
61
|
+
|
|
62
|
+
const capture = (...args: unknown[]) => {
|
|
63
|
+
logOutput.push(args.map(String).join(" "));
|
|
64
|
+
};
|
|
65
|
+
const fakeLogger = {
|
|
66
|
+
info: capture,
|
|
67
|
+
warn: capture,
|
|
68
|
+
error: capture,
|
|
69
|
+
debug: () => {},
|
|
70
|
+
};
|
|
71
|
+
mock.module("../../../logger.js", () => ({
|
|
72
|
+
log: fakeLogger,
|
|
73
|
+
getCliLogger: () => fakeLogger,
|
|
74
|
+
}));
|
|
75
|
+
|
|
76
|
+
// ---------------------------------------------------------------------------
|
|
77
|
+
// Import module under test (after mocks)
|
|
78
|
+
// ---------------------------------------------------------------------------
|
|
79
|
+
|
|
80
|
+
const { registerMemoryItemsCommand } = await import("../items.js");
|
|
81
|
+
|
|
82
|
+
// ---------------------------------------------------------------------------
|
|
83
|
+
// Test helpers
|
|
84
|
+
// ---------------------------------------------------------------------------
|
|
85
|
+
|
|
86
|
+
function buildProgram(): Command {
|
|
87
|
+
const program = new Command();
|
|
88
|
+
program.exitOverride();
|
|
89
|
+
program.configureOutput({
|
|
90
|
+
writeErr: () => {},
|
|
91
|
+
writeOut: () => {},
|
|
92
|
+
});
|
|
93
|
+
const memory = program.command("memory");
|
|
94
|
+
registerMemoryItemsCommand(memory);
|
|
95
|
+
return program;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
async function runCommand(
|
|
99
|
+
args: string[],
|
|
100
|
+
): Promise<{ stdout: string; exitCode: number }> {
|
|
101
|
+
const originalStdoutWrite = process.stdout.write.bind(process.stdout);
|
|
102
|
+
const originalStderrWrite = process.stderr.write.bind(process.stderr);
|
|
103
|
+
const stdoutChunks: string[] = [];
|
|
104
|
+
|
|
105
|
+
process.stdout.write = ((chunk: unknown) => {
|
|
106
|
+
stdoutChunks.push(typeof chunk === "string" ? chunk : String(chunk));
|
|
107
|
+
return true;
|
|
108
|
+
}) as typeof process.stdout.write;
|
|
109
|
+
|
|
110
|
+
process.stderr.write = (() => true) as typeof process.stderr.write;
|
|
111
|
+
|
|
112
|
+
process.exitCode = 0;
|
|
113
|
+
|
|
114
|
+
try {
|
|
115
|
+
const program = buildProgram();
|
|
116
|
+
await program.parseAsync(["node", "assistant", ...args]);
|
|
117
|
+
} catch {
|
|
118
|
+
if (process.exitCode === 0) {
|
|
119
|
+
process.exitCode = 1;
|
|
120
|
+
}
|
|
121
|
+
} finally {
|
|
122
|
+
process.stdout.write = originalStdoutWrite;
|
|
123
|
+
process.stderr.write = originalStderrWrite;
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
const exitCode = process.exitCode ?? 0;
|
|
127
|
+
process.exitCode = 0;
|
|
128
|
+
|
|
129
|
+
return { exitCode, stdout: stdoutChunks.join("") };
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
const ITEM = {
|
|
133
|
+
id: "9f2c4f3a-3f1a-41e4-88e7-abc123def456",
|
|
134
|
+
kind: "semantic",
|
|
135
|
+
subject: "Coffee preference",
|
|
136
|
+
statement: "Prefers oat-milk lattes",
|
|
137
|
+
status: "active",
|
|
138
|
+
confidence: 0.95,
|
|
139
|
+
importance: 0.8,
|
|
140
|
+
firstSeenAt: 1_700_000_000_000,
|
|
141
|
+
lastSeenAt: 1_700_000_000_000,
|
|
142
|
+
};
|
|
143
|
+
|
|
144
|
+
// ---------------------------------------------------------------------------
|
|
145
|
+
// Setup
|
|
146
|
+
// ---------------------------------------------------------------------------
|
|
147
|
+
|
|
148
|
+
beforeEach(() => {
|
|
149
|
+
lastIpcCall = null;
|
|
150
|
+
mockIpcResult = { ok: true, result: { item: ITEM } };
|
|
151
|
+
logOutput = [];
|
|
152
|
+
process.exitCode = 0;
|
|
153
|
+
});
|
|
154
|
+
|
|
155
|
+
// ---------------------------------------------------------------------------
|
|
156
|
+
// Registration
|
|
157
|
+
// ---------------------------------------------------------------------------
|
|
158
|
+
|
|
159
|
+
describe("verb registration", () => {
|
|
160
|
+
test("registers items under memory with the CRUD verbs", () => {
|
|
161
|
+
const program = buildProgram();
|
|
162
|
+
const memory = program.commands.find((c) => c.name() === "memory");
|
|
163
|
+
expect(memory).toBeDefined();
|
|
164
|
+
const items = memory!.commands.find((c) => c.name() === "items");
|
|
165
|
+
expect(items).toBeDefined();
|
|
166
|
+
const names = items!.commands.map((c) => c.name());
|
|
167
|
+
for (const verb of ["list", "get", "create", "update", "delete"]) {
|
|
168
|
+
expect(names).toContain(verb);
|
|
169
|
+
}
|
|
170
|
+
});
|
|
171
|
+
});
|
|
172
|
+
|
|
173
|
+
// ---------------------------------------------------------------------------
|
|
174
|
+
// list
|
|
175
|
+
// ---------------------------------------------------------------------------
|
|
176
|
+
|
|
177
|
+
describe("memory items list", () => {
|
|
178
|
+
test("calls listMemoryItems with only the provided filters", async () => {
|
|
179
|
+
mockIpcResult = {
|
|
180
|
+
ok: true,
|
|
181
|
+
result: { items: [ITEM], total: 1, kindCounts: { semantic: 1 } },
|
|
182
|
+
};
|
|
183
|
+
const { exitCode } = await runCommand([
|
|
184
|
+
"memory",
|
|
185
|
+
"items",
|
|
186
|
+
"list",
|
|
187
|
+
"--kind",
|
|
188
|
+
"semantic",
|
|
189
|
+
"--limit",
|
|
190
|
+
"20",
|
|
191
|
+
]);
|
|
192
|
+
expect(exitCode).toBe(0);
|
|
193
|
+
expect(lastIpcCall?.method).toBe("listMemoryItems");
|
|
194
|
+
expect(lastIpcCall?.params).toEqual({
|
|
195
|
+
queryParams: { kind: "semantic", limit: "20" },
|
|
196
|
+
});
|
|
197
|
+
});
|
|
198
|
+
|
|
199
|
+
test("--json emits the raw response", async () => {
|
|
200
|
+
mockIpcResult = {
|
|
201
|
+
ok: true,
|
|
202
|
+
result: { items: [ITEM], total: 1, kindCounts: { semantic: 1 } },
|
|
203
|
+
};
|
|
204
|
+
const { exitCode, stdout } = await runCommand([
|
|
205
|
+
"memory",
|
|
206
|
+
"items",
|
|
207
|
+
"list",
|
|
208
|
+
"--json",
|
|
209
|
+
]);
|
|
210
|
+
expect(exitCode).toBe(0);
|
|
211
|
+
const parsed = JSON.parse(stdout);
|
|
212
|
+
expect(parsed.total).toBe(1);
|
|
213
|
+
expect(parsed.items[0].id).toBe(ITEM.id);
|
|
214
|
+
});
|
|
215
|
+
|
|
216
|
+
test("IPC failure exits non-zero", async () => {
|
|
217
|
+
mockIpcResult = { ok: false, error: "boom", statusCode: 500 };
|
|
218
|
+
const { exitCode } = await runCommand(["memory", "items", "list"]);
|
|
219
|
+
expect(exitCode).toBe(3);
|
|
220
|
+
});
|
|
221
|
+
});
|
|
222
|
+
|
|
223
|
+
// ---------------------------------------------------------------------------
|
|
224
|
+
// get
|
|
225
|
+
// ---------------------------------------------------------------------------
|
|
226
|
+
|
|
227
|
+
describe("memory items get", () => {
|
|
228
|
+
test("calls getMemoryItem with pathParams.id", async () => {
|
|
229
|
+
const { exitCode } = await runCommand(["memory", "items", "get", ITEM.id]);
|
|
230
|
+
expect(exitCode).toBe(0);
|
|
231
|
+
expect(lastIpcCall?.method).toBe("getMemoryItem");
|
|
232
|
+
expect(lastIpcCall?.params).toEqual({ pathParams: { id: ITEM.id } });
|
|
233
|
+
});
|
|
234
|
+
|
|
235
|
+
test("blank ID fails without an IPC call", async () => {
|
|
236
|
+
const { exitCode } = await runCommand(["memory", "items", "get", " "]);
|
|
237
|
+
expect(exitCode).toBe(1);
|
|
238
|
+
expect(lastIpcCall).toBeNull();
|
|
239
|
+
});
|
|
240
|
+
|
|
241
|
+
test("not-found error exits with 4xx code", async () => {
|
|
242
|
+
mockIpcResult = {
|
|
243
|
+
ok: false,
|
|
244
|
+
error: "Memory item not found",
|
|
245
|
+
statusCode: 404,
|
|
246
|
+
};
|
|
247
|
+
const { exitCode } = await runCommand(["memory", "items", "get", ITEM.id]);
|
|
248
|
+
expect(exitCode).toBe(2);
|
|
249
|
+
});
|
|
250
|
+
});
|
|
251
|
+
|
|
252
|
+
// ---------------------------------------------------------------------------
|
|
253
|
+
// create
|
|
254
|
+
// ---------------------------------------------------------------------------
|
|
255
|
+
|
|
256
|
+
describe("memory items create", () => {
|
|
257
|
+
test("calls createMemoryItem with the assembled body", async () => {
|
|
258
|
+
const { exitCode } = await runCommand([
|
|
259
|
+
"memory",
|
|
260
|
+
"items",
|
|
261
|
+
"create",
|
|
262
|
+
"--kind",
|
|
263
|
+
"semantic",
|
|
264
|
+
"--statement",
|
|
265
|
+
"Prefers oat-milk lattes",
|
|
266
|
+
"--subject",
|
|
267
|
+
"Coffee preference",
|
|
268
|
+
"--importance",
|
|
269
|
+
"0.9",
|
|
270
|
+
]);
|
|
271
|
+
expect(exitCode).toBe(0);
|
|
272
|
+
expect(lastIpcCall?.method).toBe("createMemoryItem");
|
|
273
|
+
expect(lastIpcCall?.params).toEqual({
|
|
274
|
+
body: {
|
|
275
|
+
kind: "semantic",
|
|
276
|
+
statement: "Prefers oat-milk lattes",
|
|
277
|
+
subject: "Coffee preference",
|
|
278
|
+
importance: 0.9,
|
|
279
|
+
},
|
|
280
|
+
});
|
|
281
|
+
expect(logOutput.join("\n")).toContain(ITEM.id);
|
|
282
|
+
});
|
|
283
|
+
|
|
284
|
+
test("rejects out-of-range --importance before IPC", async () => {
|
|
285
|
+
const { exitCode } = await runCommand([
|
|
286
|
+
"memory",
|
|
287
|
+
"items",
|
|
288
|
+
"create",
|
|
289
|
+
"--kind",
|
|
290
|
+
"semantic",
|
|
291
|
+
"--statement",
|
|
292
|
+
"x",
|
|
293
|
+
"--importance",
|
|
294
|
+
"3",
|
|
295
|
+
]);
|
|
296
|
+
expect(exitCode).toBe(1);
|
|
297
|
+
expect(lastIpcCall).toBeNull();
|
|
298
|
+
});
|
|
299
|
+
|
|
300
|
+
test("missing required --statement fails parse", async () => {
|
|
301
|
+
const { exitCode } = await runCommand([
|
|
302
|
+
"memory",
|
|
303
|
+
"items",
|
|
304
|
+
"create",
|
|
305
|
+
"--kind",
|
|
306
|
+
"semantic",
|
|
307
|
+
]);
|
|
308
|
+
expect(exitCode).toBe(1);
|
|
309
|
+
expect(lastIpcCall).toBeNull();
|
|
310
|
+
});
|
|
311
|
+
});
|
|
312
|
+
|
|
313
|
+
// ---------------------------------------------------------------------------
|
|
314
|
+
// update
|
|
315
|
+
// ---------------------------------------------------------------------------
|
|
316
|
+
|
|
317
|
+
describe("memory items update", () => {
|
|
318
|
+
test("calls updateMemoryItem with pathParams and partial body", async () => {
|
|
319
|
+
const { exitCode } = await runCommand([
|
|
320
|
+
"memory",
|
|
321
|
+
"items",
|
|
322
|
+
"update",
|
|
323
|
+
ITEM.id,
|
|
324
|
+
"--statement",
|
|
325
|
+
"Prefers tea",
|
|
326
|
+
"--importance",
|
|
327
|
+
"0.5",
|
|
328
|
+
]);
|
|
329
|
+
expect(exitCode).toBe(0);
|
|
330
|
+
expect(lastIpcCall?.method).toBe("updateMemoryItem");
|
|
331
|
+
expect(lastIpcCall?.params).toEqual({
|
|
332
|
+
pathParams: { id: ITEM.id },
|
|
333
|
+
body: { statement: "Prefers tea", importance: 0.5 },
|
|
334
|
+
});
|
|
335
|
+
});
|
|
336
|
+
|
|
337
|
+
test("requires at least one update flag", async () => {
|
|
338
|
+
const { exitCode } = await runCommand([
|
|
339
|
+
"memory",
|
|
340
|
+
"items",
|
|
341
|
+
"update",
|
|
342
|
+
ITEM.id,
|
|
343
|
+
]);
|
|
344
|
+
expect(exitCode).toBe(1);
|
|
345
|
+
expect(lastIpcCall).toBeNull();
|
|
346
|
+
expect(logOutput.join("\n")).toContain("At least one update flag");
|
|
347
|
+
});
|
|
348
|
+
|
|
349
|
+
test("--status active is forwarded (restore path)", async () => {
|
|
350
|
+
const { exitCode } = await runCommand([
|
|
351
|
+
"memory",
|
|
352
|
+
"items",
|
|
353
|
+
"update",
|
|
354
|
+
ITEM.id,
|
|
355
|
+
"--status",
|
|
356
|
+
"active",
|
|
357
|
+
]);
|
|
358
|
+
expect(exitCode).toBe(0);
|
|
359
|
+
expect(lastIpcCall?.params).toEqual({
|
|
360
|
+
pathParams: { id: ITEM.id },
|
|
361
|
+
body: { status: "active" },
|
|
362
|
+
});
|
|
363
|
+
});
|
|
364
|
+
|
|
365
|
+
test("conflict error exits with 4xx code", async () => {
|
|
366
|
+
mockIpcResult = {
|
|
367
|
+
ok: false,
|
|
368
|
+
error: "Another memory item with this content already exists",
|
|
369
|
+
statusCode: 409,
|
|
370
|
+
};
|
|
371
|
+
const { exitCode } = await runCommand([
|
|
372
|
+
"memory",
|
|
373
|
+
"items",
|
|
374
|
+
"update",
|
|
375
|
+
ITEM.id,
|
|
376
|
+
"--statement",
|
|
377
|
+
"dupe",
|
|
378
|
+
]);
|
|
379
|
+
expect(exitCode).toBe(2);
|
|
380
|
+
});
|
|
381
|
+
});
|
|
382
|
+
|
|
383
|
+
// ---------------------------------------------------------------------------
|
|
384
|
+
// delete
|
|
385
|
+
// ---------------------------------------------------------------------------
|
|
386
|
+
|
|
387
|
+
describe("memory items delete", () => {
|
|
388
|
+
test("--force calls deleteMemoryItem without prompting", async () => {
|
|
389
|
+
mockIpcResult = { ok: true, result: null };
|
|
390
|
+
const { exitCode } = await runCommand([
|
|
391
|
+
"memory",
|
|
392
|
+
"items",
|
|
393
|
+
"delete",
|
|
394
|
+
ITEM.id,
|
|
395
|
+
"--force",
|
|
396
|
+
]);
|
|
397
|
+
expect(exitCode).toBe(0);
|
|
398
|
+
expect(lastIpcCall?.method).toBe("deleteMemoryItem");
|
|
399
|
+
expect(lastIpcCall?.params).toEqual({ pathParams: { id: ITEM.id } });
|
|
400
|
+
expect(logOutput.join("\n")).toContain(`Deleted memory item: ${ITEM.id}`);
|
|
401
|
+
});
|
|
402
|
+
|
|
403
|
+
test("refuses non-interactive delete without --force", async () => {
|
|
404
|
+
// Tests run with stdin not a TTY, so the confirm prompt refuses.
|
|
405
|
+
mockIpcResult = { ok: true, result: null };
|
|
406
|
+
const { exitCode } = await runCommand([
|
|
407
|
+
"memory",
|
|
408
|
+
"items",
|
|
409
|
+
"delete",
|
|
410
|
+
ITEM.id,
|
|
411
|
+
]);
|
|
412
|
+
expect(exitCode).toBe(1);
|
|
413
|
+
expect(lastIpcCall).toBeNull();
|
|
414
|
+
});
|
|
415
|
+
|
|
416
|
+
test("--force --json emits a deletion envelope", async () => {
|
|
417
|
+
mockIpcResult = { ok: true, result: null };
|
|
418
|
+
const { exitCode, stdout } = await runCommand([
|
|
419
|
+
"memory",
|
|
420
|
+
"items",
|
|
421
|
+
"delete",
|
|
422
|
+
ITEM.id,
|
|
423
|
+
"--force",
|
|
424
|
+
"--json",
|
|
425
|
+
]);
|
|
426
|
+
expect(exitCode).toBe(0);
|
|
427
|
+
expect(JSON.parse(stdout)).toEqual({ deleted: true, id: ITEM.id });
|
|
428
|
+
});
|
|
429
|
+
|
|
430
|
+
test("IPC failure exits non-zero", async () => {
|
|
431
|
+
mockIpcResult = {
|
|
432
|
+
ok: false,
|
|
433
|
+
error: "Memory item not found",
|
|
434
|
+
statusCode: 404,
|
|
435
|
+
};
|
|
436
|
+
const { exitCode } = await runCommand([
|
|
437
|
+
"memory",
|
|
438
|
+
"items",
|
|
439
|
+
"delete",
|
|
440
|
+
ITEM.id,
|
|
441
|
+
"--force",
|
|
442
|
+
]);
|
|
443
|
+
expect(exitCode).toBe(2);
|
|
444
|
+
});
|
|
445
|
+
});
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import type { Command } from "commander";
|
|
2
2
|
|
|
3
3
|
import { registerCommand } from "../../lib/register-command.js";
|
|
4
|
+
import { registerMemoryItemsCommand } from "./items.js";
|
|
4
5
|
import { registerMemoryRetrospectiveCommand } from "./memory-retrospective.js";
|
|
5
6
|
import { registerMemoryV2Command } from "./memory-v2.js";
|
|
6
7
|
import { registerMemoryV3Command } from "./memory-v3.js";
|
|
@@ -10,21 +11,29 @@ export function registerMemoryCommand(program: Command): void {
|
|
|
10
11
|
registerCommand(program, {
|
|
11
12
|
name: "memory",
|
|
12
13
|
transport: "ipc",
|
|
13
|
-
description:
|
|
14
|
+
description:
|
|
15
|
+
"Manage memory items and maintain the assistant memory subsystem",
|
|
14
16
|
build: (memory) => {
|
|
15
17
|
memory.addHelpText(
|
|
16
18
|
"after",
|
|
17
19
|
`
|
|
20
|
+
The 'items' subgroup exposes full CRUD over individual memory items
|
|
21
|
+
(remembered facts) — list, get, create, update, delete.
|
|
22
|
+
|
|
18
23
|
The memory subsystem retrieves concept pages two ways: the v2 concept-page
|
|
19
24
|
activation model (prose pages with directed edges) and the v3 section-lane
|
|
20
25
|
model (section-grain lanes cached as live shadow state). Each subgroup exposes
|
|
21
26
|
operator-facing maintenance verbs — reindexing, backfills, validation, and evals.
|
|
22
27
|
|
|
23
28
|
Examples:
|
|
29
|
+
$ assistant memory items list --search "coffee"
|
|
30
|
+
$ assistant memory items update 9f2c4f3a-3f1a-41e4-88e7-abc123 --statement "Prefers tea"
|
|
31
|
+
$ assistant memory items delete 9f2c4f3a-3f1a-41e4-88e7-abc123
|
|
24
32
|
$ assistant memory v2 validate
|
|
25
33
|
$ assistant memory v3 rebuild-index`,
|
|
26
34
|
);
|
|
27
35
|
|
|
36
|
+
registerMemoryItemsCommand(memory);
|
|
28
37
|
registerMemoryV2Command(memory);
|
|
29
38
|
registerMemoryV3Command(memory);
|
|
30
39
|
registerMemoryRetrospectiveCommand(memory);
|
|
@@ -0,0 +1,490 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `assistant memory items` CLI subgroup.
|
|
3
|
+
*
|
|
4
|
+
* Full CRUD over individual memory items (graph nodes), each subcommand a
|
|
5
|
+
* thin IPC wrapper over the daemon's memory-item routes:
|
|
6
|
+
*
|
|
7
|
+
* - `list` → listMemoryItems
|
|
8
|
+
* - `get` → getMemoryItem
|
|
9
|
+
* - `create` → createMemoryItem
|
|
10
|
+
* - `update` → updateMemoryItem
|
|
11
|
+
* - `delete` → deleteMemoryItem
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
import type { Command } from "commander";
|
|
15
|
+
|
|
16
|
+
import { cliIpcCall, exitFromIpcResult } from "../../../ipc/cli-client.js";
|
|
17
|
+
import { confirmPrompt } from "../../lib/confirm-prompt.js";
|
|
18
|
+
import { registerCommand } from "../../lib/register-command.js";
|
|
19
|
+
import { log } from "../../logger.js";
|
|
20
|
+
import { writeOutput } from "../../output.js";
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* Memory kinds accepted by the daemon's memory-item routes. Mirrored here
|
|
24
|
+
* for help text only — the route validates and rejects unknown kinds.
|
|
25
|
+
*/
|
|
26
|
+
const MEMORY_KINDS =
|
|
27
|
+
"episodic, semantic, procedural, emotional, prospective, behavioral, narrative, shared";
|
|
28
|
+
|
|
29
|
+
interface MemoryItemPayload {
|
|
30
|
+
id: string;
|
|
31
|
+
kind: string;
|
|
32
|
+
subject: string;
|
|
33
|
+
statement: string;
|
|
34
|
+
status: string;
|
|
35
|
+
confidence: number;
|
|
36
|
+
importance: number;
|
|
37
|
+
firstSeenAt: number;
|
|
38
|
+
lastSeenAt: number;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
interface ListMemoryItemsResponse {
|
|
42
|
+
items: MemoryItemPayload[];
|
|
43
|
+
total: number;
|
|
44
|
+
kindCounts: Record<string, number>;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
interface MemoryItemResponse {
|
|
48
|
+
item: MemoryItemPayload;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
function parseImportance(raw: string): number | null {
|
|
52
|
+
const parsed = Number(raw);
|
|
53
|
+
if (!Number.isFinite(parsed) || parsed < 0 || parsed > 1) {
|
|
54
|
+
log.error(
|
|
55
|
+
`Invalid --importance "${raw}". Must be a number between 0 and 1.`,
|
|
56
|
+
);
|
|
57
|
+
process.exitCode = 1;
|
|
58
|
+
return null;
|
|
59
|
+
}
|
|
60
|
+
return parsed;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
function requireId(
|
|
64
|
+
id: string,
|
|
65
|
+
opts: { json?: boolean },
|
|
66
|
+
cmd: Command,
|
|
67
|
+
): string | null {
|
|
68
|
+
const trimmed = id.trim();
|
|
69
|
+
if (!trimmed) {
|
|
70
|
+
const error =
|
|
71
|
+
"Memory item ID is required. Run 'assistant memory items list' to find it.";
|
|
72
|
+
if (opts.json) {
|
|
73
|
+
writeOutput(cmd, { ok: false, error });
|
|
74
|
+
} else {
|
|
75
|
+
log.error(error);
|
|
76
|
+
}
|
|
77
|
+
process.exitCode = 1;
|
|
78
|
+
return null;
|
|
79
|
+
}
|
|
80
|
+
return trimmed;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
export function registerMemoryItemsCommand(memory: Command): void {
|
|
84
|
+
registerCommand(memory, {
|
|
85
|
+
name: "items",
|
|
86
|
+
transport: "ipc",
|
|
87
|
+
description: "Manage individual memory items (full CRUD)",
|
|
88
|
+
build: (items) => {
|
|
89
|
+
items.addHelpText(
|
|
90
|
+
"after",
|
|
91
|
+
`
|
|
92
|
+
Memory items are individual remembered facts (graph nodes) with a kind
|
|
93
|
+
(${MEMORY_KINDS}),
|
|
94
|
+
a subject line, and a statement. Items are normally created by the
|
|
95
|
+
assistant via the remember tool; 'items create' exists for manual seeding
|
|
96
|
+
and repair.
|
|
97
|
+
|
|
98
|
+
Examples:
|
|
99
|
+
$ assistant memory items list --search "coffee"
|
|
100
|
+
$ assistant memory items update 9f2c4f3a-3f1a-41e4-88e7-abc123 --statement "Prefers tea"
|
|
101
|
+
$ assistant memory items delete 9f2c4f3a-3f1a-41e4-88e7-abc123`,
|
|
102
|
+
);
|
|
103
|
+
|
|
104
|
+
// ── list ──────────────────────────────────────────────────────────────
|
|
105
|
+
|
|
106
|
+
items
|
|
107
|
+
.command("list")
|
|
108
|
+
.alias("ls")
|
|
109
|
+
.description("List memory items with filtering, search, and pagination")
|
|
110
|
+
.option("--kind <kind>", `Filter by kind (${MEMORY_KINDS})`)
|
|
111
|
+
.option(
|
|
112
|
+
"--status <status>",
|
|
113
|
+
"Filter by status: active (default), inactive, or all",
|
|
114
|
+
)
|
|
115
|
+
.option("--search <query>", "Semantic/full-text search query")
|
|
116
|
+
.option(
|
|
117
|
+
"--sort <field>",
|
|
118
|
+
"Sort field: lastSeenAt (default), importance, kind, or firstSeenAt",
|
|
119
|
+
)
|
|
120
|
+
.option("--order <order>", "asc or desc (default desc)")
|
|
121
|
+
.option("--limit <n>", "Max results (default 100)")
|
|
122
|
+
.option("--offset <n>", "Pagination offset (default 0)")
|
|
123
|
+
.option("--json", "Machine-readable compact JSON output")
|
|
124
|
+
.addHelpText(
|
|
125
|
+
"after",
|
|
126
|
+
`
|
|
127
|
+
Behavior:
|
|
128
|
+
Lists memory items (remembered facts) from the assistant's memory store.
|
|
129
|
+
With --search, results are ranked by semantic relevance when the embedding
|
|
130
|
+
backend is available, falling back to substring match otherwise. Deleted
|
|
131
|
+
items are hidden unless --status inactive or --status all is passed.
|
|
132
|
+
|
|
133
|
+
Examples:
|
|
134
|
+
$ assistant memory items list
|
|
135
|
+
$ assistant memory items list --kind semantic --limit 20
|
|
136
|
+
$ assistant memory items list --search "favorite restaurants" --json`,
|
|
137
|
+
)
|
|
138
|
+
.action(
|
|
139
|
+
async (
|
|
140
|
+
opts: {
|
|
141
|
+
kind?: string;
|
|
142
|
+
status?: string;
|
|
143
|
+
search?: string;
|
|
144
|
+
sort?: string;
|
|
145
|
+
order?: string;
|
|
146
|
+
limit?: string;
|
|
147
|
+
offset?: string;
|
|
148
|
+
json?: boolean;
|
|
149
|
+
},
|
|
150
|
+
cmd: Command,
|
|
151
|
+
) => {
|
|
152
|
+
const queryParams: Record<string, string> = {};
|
|
153
|
+
if (opts.kind) {
|
|
154
|
+
queryParams.kind = opts.kind;
|
|
155
|
+
}
|
|
156
|
+
if (opts.status) {
|
|
157
|
+
queryParams.status = opts.status;
|
|
158
|
+
}
|
|
159
|
+
if (opts.search) {
|
|
160
|
+
queryParams.search = opts.search;
|
|
161
|
+
}
|
|
162
|
+
if (opts.sort) {
|
|
163
|
+
queryParams.sort = opts.sort;
|
|
164
|
+
}
|
|
165
|
+
if (opts.order) {
|
|
166
|
+
queryParams.order = opts.order;
|
|
167
|
+
}
|
|
168
|
+
if (opts.limit) {
|
|
169
|
+
queryParams.limit = opts.limit;
|
|
170
|
+
}
|
|
171
|
+
if (opts.offset) {
|
|
172
|
+
queryParams.offset = opts.offset;
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
const result = await cliIpcCall<ListMemoryItemsResponse>(
|
|
176
|
+
"listMemoryItems",
|
|
177
|
+
{ queryParams },
|
|
178
|
+
);
|
|
179
|
+
|
|
180
|
+
if (!result.ok) {
|
|
181
|
+
return exitFromIpcResult(result, cmd);
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
const response = result.result ?? {
|
|
185
|
+
items: [],
|
|
186
|
+
total: 0,
|
|
187
|
+
kindCounts: {},
|
|
188
|
+
};
|
|
189
|
+
|
|
190
|
+
if (opts.json) {
|
|
191
|
+
writeOutput(cmd, response);
|
|
192
|
+
return;
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
if (response.items.length === 0) {
|
|
196
|
+
log.info("No memory items found.");
|
|
197
|
+
return;
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
const kindWidth = Math.max(
|
|
201
|
+
4,
|
|
202
|
+
...response.items.map((item) => item.kind.length),
|
|
203
|
+
);
|
|
204
|
+
console.log(
|
|
205
|
+
`${"ID".padEnd(36)} ${"KIND".padEnd(kindWidth)} ${"IMP".padEnd(4)} SUBJECT`,
|
|
206
|
+
);
|
|
207
|
+
for (const item of response.items) {
|
|
208
|
+
console.log(
|
|
209
|
+
`${item.id.padEnd(36)} ${item.kind.padEnd(kindWidth)} ${item.importance.toFixed(2)} ${item.subject}`,
|
|
210
|
+
);
|
|
211
|
+
}
|
|
212
|
+
console.log(
|
|
213
|
+
`\n${response.items.length} of ${response.total} memory item(s)`,
|
|
214
|
+
);
|
|
215
|
+
},
|
|
216
|
+
);
|
|
217
|
+
|
|
218
|
+
// ── get ───────────────────────────────────────────────────────────────
|
|
219
|
+
|
|
220
|
+
items
|
|
221
|
+
.command("get <id>")
|
|
222
|
+
.description("Get a single memory item by ID")
|
|
223
|
+
.option("--json", "Machine-readable compact JSON output")
|
|
224
|
+
.addHelpText(
|
|
225
|
+
"after",
|
|
226
|
+
`
|
|
227
|
+
Arguments:
|
|
228
|
+
<id> Memory item ID (UUID) — run 'assistant memory items list' to find it.
|
|
229
|
+
|
|
230
|
+
Examples:
|
|
231
|
+
$ assistant memory items get 9f2c4f3a-3f1a-41e4-88e7-abc123
|
|
232
|
+
$ assistant memory items get 9f2c4f3a-3f1a-41e4-88e7-abc123 --json`,
|
|
233
|
+
)
|
|
234
|
+
.action(async (id: string, opts: { json?: boolean }, cmd: Command) => {
|
|
235
|
+
const itemId = requireId(id, opts, cmd);
|
|
236
|
+
if (!itemId) {
|
|
237
|
+
return;
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
const result = await cliIpcCall<MemoryItemResponse>("getMemoryItem", {
|
|
241
|
+
pathParams: { id: itemId },
|
|
242
|
+
});
|
|
243
|
+
|
|
244
|
+
if (!result.ok) {
|
|
245
|
+
return exitFromIpcResult(result, cmd);
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
writeOutput(cmd, result.result);
|
|
249
|
+
});
|
|
250
|
+
|
|
251
|
+
// ── create ────────────────────────────────────────────────────────────
|
|
252
|
+
|
|
253
|
+
items
|
|
254
|
+
.command("create")
|
|
255
|
+
.description("Create a new memory item")
|
|
256
|
+
.requiredOption("--kind <kind>", `Memory kind (${MEMORY_KINDS})`)
|
|
257
|
+
.requiredOption("--statement <text>", "Statement content of the memory")
|
|
258
|
+
.option("--subject <text>", "Subject line (defaults to the statement)")
|
|
259
|
+
.option("--importance <n>", "Importance score 0-1 (default 0.8)")
|
|
260
|
+
.option("--json", "Machine-readable compact JSON output")
|
|
261
|
+
.addHelpText(
|
|
262
|
+
"after",
|
|
263
|
+
`
|
|
264
|
+
Behavior:
|
|
265
|
+
Creates a memory graph node and enqueues its embedding so it becomes
|
|
266
|
+
recallable. Fails with a conflict error if an active item with identical
|
|
267
|
+
content already exists. Memories are normally formed by the assistant via
|
|
268
|
+
the remember tool — use this for manual seeding and repair.
|
|
269
|
+
|
|
270
|
+
Examples:
|
|
271
|
+
$ assistant memory items create --kind semantic --statement "User prefers dark mode"
|
|
272
|
+
$ assistant memory items create --kind procedural --subject "Deploys" \\
|
|
273
|
+
--statement "Deploys go out Tuesdays after standup" --importance 0.9`,
|
|
274
|
+
)
|
|
275
|
+
.action(
|
|
276
|
+
async (
|
|
277
|
+
opts: {
|
|
278
|
+
kind: string;
|
|
279
|
+
statement: string;
|
|
280
|
+
subject?: string;
|
|
281
|
+
importance?: string;
|
|
282
|
+
json?: boolean;
|
|
283
|
+
},
|
|
284
|
+
cmd: Command,
|
|
285
|
+
) => {
|
|
286
|
+
const body: Record<string, unknown> = {
|
|
287
|
+
kind: opts.kind,
|
|
288
|
+
statement: opts.statement,
|
|
289
|
+
};
|
|
290
|
+
if (opts.subject !== undefined) {
|
|
291
|
+
body.subject = opts.subject;
|
|
292
|
+
}
|
|
293
|
+
if (opts.importance !== undefined) {
|
|
294
|
+
const parsed = parseImportance(opts.importance);
|
|
295
|
+
if (parsed == null) {
|
|
296
|
+
return;
|
|
297
|
+
}
|
|
298
|
+
body.importance = parsed;
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
const result = await cliIpcCall<MemoryItemResponse>(
|
|
302
|
+
"createMemoryItem",
|
|
303
|
+
{ body },
|
|
304
|
+
);
|
|
305
|
+
|
|
306
|
+
if (!result.ok) {
|
|
307
|
+
return exitFromIpcResult(result, cmd);
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
if (opts.json) {
|
|
311
|
+
writeOutput(cmd, result.result);
|
|
312
|
+
return;
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
log.info(`Created memory item: ${result.result?.item.id}`);
|
|
316
|
+
},
|
|
317
|
+
);
|
|
318
|
+
|
|
319
|
+
// ── update ────────────────────────────────────────────────────────────
|
|
320
|
+
|
|
321
|
+
items
|
|
322
|
+
.command("update <id>")
|
|
323
|
+
.description("Update fields on an existing memory item")
|
|
324
|
+
.option("--subject <text>", "Replace the subject line")
|
|
325
|
+
.option("--statement <text>", "Replace the statement content")
|
|
326
|
+
.option("--kind <kind>", `Change the kind (${MEMORY_KINDS})`)
|
|
327
|
+
.option(
|
|
328
|
+
"--status <status>",
|
|
329
|
+
"Set status: active (restores a deleted item) or superseded",
|
|
330
|
+
)
|
|
331
|
+
.option("--importance <n>", "Set importance score 0-1")
|
|
332
|
+
.option("--json", "Machine-readable compact JSON output")
|
|
333
|
+
.addHelpText(
|
|
334
|
+
"after",
|
|
335
|
+
`
|
|
336
|
+
Arguments:
|
|
337
|
+
<id> Memory item ID (UUID) — run 'assistant memory items list' to find it.
|
|
338
|
+
|
|
339
|
+
Behavior:
|
|
340
|
+
Partially updates the given fields; anything not passed is left unchanged.
|
|
341
|
+
Content changes trigger re-embedding so recall stays consistent. Setting
|
|
342
|
+
--status active restores a previously deleted item; --status superseded
|
|
343
|
+
retires it (same effect as 'assistant memory items delete'). Fails with a
|
|
344
|
+
conflict error when the new content duplicates another active item.
|
|
345
|
+
|
|
346
|
+
Examples:
|
|
347
|
+
$ assistant memory items update 9f2c4f3a-3f1a-41e4-88e7-abc123 --statement "Prefers tea over coffee"
|
|
348
|
+
$ assistant memory items update 9f2c4f3a-3f1a-41e4-88e7-abc123 --importance 0.9 --kind semantic
|
|
349
|
+
$ assistant memory items update 9f2c4f3a-3f1a-41e4-88e7-abc123 --status active`,
|
|
350
|
+
)
|
|
351
|
+
.action(
|
|
352
|
+
async (
|
|
353
|
+
id: string,
|
|
354
|
+
opts: {
|
|
355
|
+
subject?: string;
|
|
356
|
+
statement?: string;
|
|
357
|
+
kind?: string;
|
|
358
|
+
status?: string;
|
|
359
|
+
importance?: string;
|
|
360
|
+
json?: boolean;
|
|
361
|
+
},
|
|
362
|
+
cmd: Command,
|
|
363
|
+
) => {
|
|
364
|
+
const itemId = requireId(id, opts, cmd);
|
|
365
|
+
if (!itemId) {
|
|
366
|
+
return;
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
const body: Record<string, unknown> = {};
|
|
370
|
+
if (opts.subject !== undefined) {
|
|
371
|
+
body.subject = opts.subject;
|
|
372
|
+
}
|
|
373
|
+
if (opts.statement !== undefined) {
|
|
374
|
+
body.statement = opts.statement;
|
|
375
|
+
}
|
|
376
|
+
if (opts.kind !== undefined) {
|
|
377
|
+
body.kind = opts.kind;
|
|
378
|
+
}
|
|
379
|
+
if (opts.status !== undefined) {
|
|
380
|
+
body.status = opts.status;
|
|
381
|
+
}
|
|
382
|
+
if (opts.importance !== undefined) {
|
|
383
|
+
const parsed = parseImportance(opts.importance);
|
|
384
|
+
if (parsed == null) {
|
|
385
|
+
return;
|
|
386
|
+
}
|
|
387
|
+
body.importance = parsed;
|
|
388
|
+
}
|
|
389
|
+
|
|
390
|
+
if (Object.keys(body).length === 0) {
|
|
391
|
+
log.error(
|
|
392
|
+
"At least one update flag is required. Run 'assistant memory items update --help' for the available flags.",
|
|
393
|
+
);
|
|
394
|
+
process.exitCode = 1;
|
|
395
|
+
return;
|
|
396
|
+
}
|
|
397
|
+
|
|
398
|
+
const result = await cliIpcCall<MemoryItemResponse>(
|
|
399
|
+
"updateMemoryItem",
|
|
400
|
+
{ pathParams: { id: itemId }, body },
|
|
401
|
+
);
|
|
402
|
+
|
|
403
|
+
if (!result.ok) {
|
|
404
|
+
return exitFromIpcResult(result, cmd);
|
|
405
|
+
}
|
|
406
|
+
|
|
407
|
+
if (opts.json) {
|
|
408
|
+
writeOutput(cmd, result.result);
|
|
409
|
+
return;
|
|
410
|
+
}
|
|
411
|
+
|
|
412
|
+
log.info(`Updated memory item: ${itemId}`);
|
|
413
|
+
},
|
|
414
|
+
);
|
|
415
|
+
|
|
416
|
+
// ── delete ────────────────────────────────────────────────────────────
|
|
417
|
+
|
|
418
|
+
items
|
|
419
|
+
.command("delete <id>")
|
|
420
|
+
.alias("rm")
|
|
421
|
+
.description("Delete a memory item")
|
|
422
|
+
.option("--force", "Skip the confirmation prompt")
|
|
423
|
+
.option("--json", "Machine-readable compact JSON output")
|
|
424
|
+
.addHelpText(
|
|
425
|
+
"after",
|
|
426
|
+
`
|
|
427
|
+
Options:
|
|
428
|
+
--force Skip the destructive y/N confirmation prompt. Required when stdin
|
|
429
|
+
is not a TTY (e.g. in scripts and CI).
|
|
430
|
+
--json Output the deletion result as compact JSON.
|
|
431
|
+
|
|
432
|
+
Arguments:
|
|
433
|
+
<id> Memory item ID (UUID) — run 'assistant memory items list' to find it.
|
|
434
|
+
|
|
435
|
+
Behavior:
|
|
436
|
+
Soft-deletes the memory item — it stops being recalled and its embeddings
|
|
437
|
+
are removed from the index, but the underlying record is retained. A
|
|
438
|
+
deleted item can be restored with
|
|
439
|
+
'assistant memory items update <id> --status active'.
|
|
440
|
+
|
|
441
|
+
Examples:
|
|
442
|
+
$ assistant memory items delete 9f2c4f3a-3f1a-41e4-88e7-abc123
|
|
443
|
+
$ assistant memory items delete 9f2c4f3a-3f1a-41e4-88e7-abc123 --force --json`,
|
|
444
|
+
)
|
|
445
|
+
.action(
|
|
446
|
+
async (
|
|
447
|
+
id: string,
|
|
448
|
+
opts: { force?: boolean; json?: boolean },
|
|
449
|
+
cmd: Command,
|
|
450
|
+
) => {
|
|
451
|
+
const itemId = requireId(id, opts, cmd);
|
|
452
|
+
if (!itemId) {
|
|
453
|
+
return;
|
|
454
|
+
}
|
|
455
|
+
|
|
456
|
+
if (!opts.force) {
|
|
457
|
+
const decision = await confirmPrompt({
|
|
458
|
+
question: `Delete memory item "${itemId}"? [y/N] `,
|
|
459
|
+
isTTY: Boolean(process.stdin.isTTY),
|
|
460
|
+
refuseNonInteractiveMessage: `Refusing to delete memory item "${itemId}" non-interactively. Pass --force to confirm.`,
|
|
461
|
+
});
|
|
462
|
+
if (decision === "non-interactive") {
|
|
463
|
+
process.exitCode = 1;
|
|
464
|
+
return;
|
|
465
|
+
}
|
|
466
|
+
if (decision === "denied") {
|
|
467
|
+
log.info("Delete cancelled.");
|
|
468
|
+
return;
|
|
469
|
+
}
|
|
470
|
+
}
|
|
471
|
+
|
|
472
|
+
const result = await cliIpcCall<null>("deleteMemoryItem", {
|
|
473
|
+
pathParams: { id: itemId },
|
|
474
|
+
});
|
|
475
|
+
|
|
476
|
+
if (!result.ok) {
|
|
477
|
+
return exitFromIpcResult(result, cmd);
|
|
478
|
+
}
|
|
479
|
+
|
|
480
|
+
if (opts.json) {
|
|
481
|
+
writeOutput(cmd, { deleted: true, id: itemId });
|
|
482
|
+
return;
|
|
483
|
+
}
|
|
484
|
+
|
|
485
|
+
log.info(`Deleted memory item: ${itemId}`);
|
|
486
|
+
},
|
|
487
|
+
);
|
|
488
|
+
},
|
|
489
|
+
});
|
|
490
|
+
}
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
import { mkdirSync, writeFileSync } from "node:fs";
|
|
2
|
+
import { join } from "node:path";
|
|
3
|
+
import { describe, expect, test } from "bun:test";
|
|
4
|
+
|
|
5
|
+
import { getDataDir, getDbPath } from "../../util/platform.js";
|
|
6
|
+
import { getTrackedDataFiles, parseFincoreJson } from "../page-cache.js";
|
|
7
|
+
|
|
8
|
+
describe("parseFincoreJson", () => {
|
|
9
|
+
test("parses numeric and string-numeric fincore output", () => {
|
|
10
|
+
const stdout = JSON.stringify({
|
|
11
|
+
fincore: [
|
|
12
|
+
{
|
|
13
|
+
res: 1363148800,
|
|
14
|
+
pages: 332800,
|
|
15
|
+
size: 2147483648,
|
|
16
|
+
file: "/workspace/data/db/assistant.db",
|
|
17
|
+
},
|
|
18
|
+
{
|
|
19
|
+
res: "4096",
|
|
20
|
+
pages: "1",
|
|
21
|
+
size: "8192",
|
|
22
|
+
file: "/workspace/data/db/assistant.db-wal",
|
|
23
|
+
},
|
|
24
|
+
],
|
|
25
|
+
});
|
|
26
|
+
|
|
27
|
+
expect(parseFincoreJson(stdout)).toEqual([
|
|
28
|
+
{
|
|
29
|
+
path: "/workspace/data/db/assistant.db",
|
|
30
|
+
sizeBytes: 2147483648,
|
|
31
|
+
residentBytes: 1363148800,
|
|
32
|
+
residentRatio: 1363148800 / 2147483648,
|
|
33
|
+
},
|
|
34
|
+
{
|
|
35
|
+
path: "/workspace/data/db/assistant.db-wal",
|
|
36
|
+
sizeBytes: 8192,
|
|
37
|
+
residentBytes: 4096,
|
|
38
|
+
residentRatio: 0.5,
|
|
39
|
+
},
|
|
40
|
+
]);
|
|
41
|
+
});
|
|
42
|
+
|
|
43
|
+
test("empty file yields a null ratio", () => {
|
|
44
|
+
const rows = parseFincoreJson(
|
|
45
|
+
JSON.stringify({ fincore: [{ res: 0, size: 0, file: "/tmp/empty" }] }),
|
|
46
|
+
);
|
|
47
|
+
expect(rows[0].residentRatio).toBeNull();
|
|
48
|
+
});
|
|
49
|
+
|
|
50
|
+
test("tolerates malformed output", () => {
|
|
51
|
+
expect(parseFincoreJson("")).toEqual([]);
|
|
52
|
+
expect(parseFincoreJson("not json")).toEqual([]);
|
|
53
|
+
expect(parseFincoreJson(JSON.stringify({ fincore: "nope" }))).toEqual([]);
|
|
54
|
+
expect(
|
|
55
|
+
parseFincoreJson(JSON.stringify({ fincore: [{ file: 42, res: "x" }] })),
|
|
56
|
+
).toEqual([]);
|
|
57
|
+
});
|
|
58
|
+
});
|
|
59
|
+
|
|
60
|
+
describe("getTrackedDataFiles", () => {
|
|
61
|
+
test("returns existing db sidecars and the largest qdrant files", () => {
|
|
62
|
+
const dbPath = getDbPath();
|
|
63
|
+
mkdirSync(join(getDataDir(), "db"), { recursive: true });
|
|
64
|
+
writeFileSync(dbPath, "x".repeat(64));
|
|
65
|
+
writeFileSync(`${dbPath}-wal`, "x".repeat(32));
|
|
66
|
+
// No -shm file — it must not be reported.
|
|
67
|
+
|
|
68
|
+
const segments = join(getDataDir(), "qdrant", "collections", "c1");
|
|
69
|
+
mkdirSync(segments, { recursive: true });
|
|
70
|
+
writeFileSync(join(segments, "big.seg"), "x".repeat(100));
|
|
71
|
+
writeFileSync(join(segments, "small.seg"), "x".repeat(10));
|
|
72
|
+
|
|
73
|
+
const tracked = getTrackedDataFiles(1);
|
|
74
|
+
|
|
75
|
+
expect(tracked).toEqual([
|
|
76
|
+
dbPath,
|
|
77
|
+
`${dbPath}-wal`,
|
|
78
|
+
join(segments, "big.seg"),
|
|
79
|
+
]);
|
|
80
|
+
});
|
|
81
|
+
});
|
|
@@ -0,0 +1,152 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Page-cache residency attribution for the assistant's large data files, for
|
|
3
|
+
* high-memory snapshots. The memory.stat `file` number says how much page
|
|
4
|
+
* cache the cgroup holds; this says *which files* it is — e.g. "1.3 GB of the
|
|
5
|
+
* cache is assistant.db" — via `fincore(1)` (util-linux), which reports the
|
|
6
|
+
* cached page count per file without touching the file's contents.
|
|
7
|
+
*
|
|
8
|
+
* Reads are best-effort: when the fincore binary is missing or fails, the
|
|
9
|
+
* snapshot records null rather than failing.
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
import { execFile } from "node:child_process";
|
|
13
|
+
import { existsSync, readdirSync, statSync } from "node:fs";
|
|
14
|
+
import { join } from "node:path";
|
|
15
|
+
import { promisify } from "node:util";
|
|
16
|
+
|
|
17
|
+
import { getDataDir, getDbPath } from "../util/platform.js";
|
|
18
|
+
|
|
19
|
+
const execFileAsync = promisify(execFile);
|
|
20
|
+
|
|
21
|
+
/** Cap on directory entries visited when hunting for large qdrant files. */
|
|
22
|
+
const MAX_WALK_ENTRIES = 20_000;
|
|
23
|
+
|
|
24
|
+
export interface FileResidency {
|
|
25
|
+
path: string;
|
|
26
|
+
sizeBytes: number;
|
|
27
|
+
/** Bytes of this file currently resident in the page cache. */
|
|
28
|
+
residentBytes: number;
|
|
29
|
+
/** residentBytes / sizeBytes, or null for an empty file. */
|
|
30
|
+
residentRatio: number | null;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* Parse `fincore --bytes --json` output. util-linux emits
|
|
35
|
+
* `{"fincore": [{"res": ..., "pages": ..., "size": ..., "file": ...}]}`;
|
|
36
|
+
* numeric columns are strings on older versions, so values go through
|
|
37
|
+
* Number().
|
|
38
|
+
*/
|
|
39
|
+
export function parseFincoreJson(stdout: string): FileResidency[] {
|
|
40
|
+
let parsed: unknown;
|
|
41
|
+
try {
|
|
42
|
+
parsed = JSON.parse(stdout);
|
|
43
|
+
} catch {
|
|
44
|
+
return [];
|
|
45
|
+
}
|
|
46
|
+
const rows = (parsed as { fincore?: unknown[] })?.fincore;
|
|
47
|
+
if (!Array.isArray(rows)) {
|
|
48
|
+
return [];
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
const out: FileResidency[] = [];
|
|
52
|
+
for (const row of rows) {
|
|
53
|
+
const { res, size, file } = row as {
|
|
54
|
+
res?: unknown;
|
|
55
|
+
size?: unknown;
|
|
56
|
+
file?: unknown;
|
|
57
|
+
};
|
|
58
|
+
const residentBytes = Number(res);
|
|
59
|
+
const sizeBytes = Number(size);
|
|
60
|
+
if (
|
|
61
|
+
typeof file !== "string" ||
|
|
62
|
+
!Number.isFinite(residentBytes) ||
|
|
63
|
+
!Number.isFinite(sizeBytes)
|
|
64
|
+
) {
|
|
65
|
+
continue;
|
|
66
|
+
}
|
|
67
|
+
out.push({
|
|
68
|
+
path: file,
|
|
69
|
+
sizeBytes,
|
|
70
|
+
residentBytes,
|
|
71
|
+
residentRatio: sizeBytes > 0 ? residentBytes / sizeBytes : null,
|
|
72
|
+
});
|
|
73
|
+
}
|
|
74
|
+
return out;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/** The largest `limit` regular files under `root`, bounded-walk, largest first. */
|
|
78
|
+
function largestFilesUnder(
|
|
79
|
+
root: string,
|
|
80
|
+
limit: number,
|
|
81
|
+
): Array<{ path: string; sizeBytes: number }> {
|
|
82
|
+
const found: Array<{ path: string; sizeBytes: number }> = [];
|
|
83
|
+
const queue = [root];
|
|
84
|
+
let visited = 0;
|
|
85
|
+
while (queue.length > 0 && visited < MAX_WALK_ENTRIES) {
|
|
86
|
+
const dir = queue.shift()!;
|
|
87
|
+
let entries: string[];
|
|
88
|
+
try {
|
|
89
|
+
entries = readdirSync(dir);
|
|
90
|
+
} catch {
|
|
91
|
+
continue;
|
|
92
|
+
}
|
|
93
|
+
for (const entry of entries) {
|
|
94
|
+
if (++visited > MAX_WALK_ENTRIES) {
|
|
95
|
+
break;
|
|
96
|
+
}
|
|
97
|
+
const path = join(dir, entry);
|
|
98
|
+
try {
|
|
99
|
+
const stat = statSync(path);
|
|
100
|
+
if (stat.isDirectory()) {
|
|
101
|
+
queue.push(path);
|
|
102
|
+
} else if (stat.isFile()) {
|
|
103
|
+
found.push({ path, sizeBytes: stat.size });
|
|
104
|
+
}
|
|
105
|
+
} catch {
|
|
106
|
+
// Removed mid-walk — skip.
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
found.sort((a, b) => b.sizeBytes - a.sizeBytes);
|
|
111
|
+
return found.slice(0, limit);
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/**
|
|
115
|
+
* The data files worth attributing cache to: the SQLite database (plus its
|
|
116
|
+
* WAL/shm sidecars) and the largest files under the qdrant storage directory.
|
|
117
|
+
* Only files that currently exist are returned.
|
|
118
|
+
*/
|
|
119
|
+
export function getTrackedDataFiles(qdrantLimit = 10): string[] {
|
|
120
|
+
const dbPath = getDbPath();
|
|
121
|
+
const candidates = [dbPath, `${dbPath}-wal`, `${dbPath}-shm`].filter((p) =>
|
|
122
|
+
existsSync(p),
|
|
123
|
+
);
|
|
124
|
+
const qdrantFiles = largestFilesUnder(
|
|
125
|
+
join(getDataDir(), "qdrant"),
|
|
126
|
+
qdrantLimit,
|
|
127
|
+
);
|
|
128
|
+
return [...candidates, ...qdrantFiles.map((f) => f.path)];
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/**
|
|
132
|
+
* Page-cache residency for `paths` via fincore. Null when fincore is
|
|
133
|
+
* unavailable or fails (the binary ships in util-linux-extra); an empty input
|
|
134
|
+
* yields an empty result.
|
|
135
|
+
*/
|
|
136
|
+
export async function readFileResidency(
|
|
137
|
+
paths: string[],
|
|
138
|
+
): Promise<FileResidency[] | null> {
|
|
139
|
+
if (paths.length === 0) {
|
|
140
|
+
return [];
|
|
141
|
+
}
|
|
142
|
+
try {
|
|
143
|
+
const { stdout } = await execFileAsync(
|
|
144
|
+
"fincore",
|
|
145
|
+
["--bytes", "--json", ...paths],
|
|
146
|
+
{ timeout: 10_000, maxBuffer: 4 * 1024 * 1024 },
|
|
147
|
+
);
|
|
148
|
+
return parseFincoreJson(stdout);
|
|
149
|
+
} catch {
|
|
150
|
+
return null;
|
|
151
|
+
}
|
|
152
|
+
}
|
|
@@ -33,6 +33,7 @@ import { getDiskUsageInfo } from "../util/disk-usage.js";
|
|
|
33
33
|
import { getLogger } from "../util/logger.js";
|
|
34
34
|
import { getMonitoringDataDir } from "../util/platform.js";
|
|
35
35
|
import { buildProcessTree, listProcesses } from "../util/process-tree.js";
|
|
36
|
+
import { getTrackedDataFiles, readFileResidency } from "./page-cache.js";
|
|
36
37
|
import { topProcessesByMemory } from "./process-memory.js";
|
|
37
38
|
import { SampleRingBuffer } from "./sample-ring-buffer.js";
|
|
38
39
|
import { topSlabCaches } from "./slabinfo.js";
|
|
@@ -163,9 +164,9 @@ export function takeSample(
|
|
|
163
164
|
|
|
164
165
|
/**
|
|
165
166
|
* Capture a high-memory snapshot to the snapshots directory: the triggering
|
|
166
|
-
* sample, the
|
|
167
|
-
* kernel slab caches, and the full process tree of the container.
|
|
168
|
-
* {@link MAX_SNAPSHOTS} newest.
|
|
167
|
+
* sample, page-cache residency of the large data files, the top processes by
|
|
168
|
+
* PSS, the top kernel slab caches, and the full process tree of the container.
|
|
169
|
+
* Prunes to {@link MAX_SNAPSHOTS} newest.
|
|
169
170
|
*/
|
|
170
171
|
export async function writeHighMemSnapshot(
|
|
171
172
|
dataDir: string,
|
|
@@ -185,9 +186,19 @@ export async function writeHighMemSnapshot(
|
|
|
185
186
|
log.warn({ err }, "Failed to enumerate process tree for snapshot");
|
|
186
187
|
}
|
|
187
188
|
|
|
189
|
+
// Attributes the memory.stat `file` charge to specific files (SQLite DB +
|
|
190
|
+
// WAL, largest qdrant segments); null when fincore is unavailable.
|
|
191
|
+
let fileResidency: Awaited<ReturnType<typeof readFileResidency>> = null;
|
|
192
|
+
try {
|
|
193
|
+
fileResidency = await readFileResidency(getTrackedDataFiles());
|
|
194
|
+
} catch (err) {
|
|
195
|
+
log.warn({ err }, "Failed to read page-cache residency for snapshot");
|
|
196
|
+
}
|
|
197
|
+
|
|
188
198
|
const snapshot = {
|
|
189
199
|
ts: sample.ts,
|
|
190
200
|
sample,
|
|
201
|
+
fileResidency,
|
|
191
202
|
// PSS-ranked with per-process anon/file split; PSS sums reconcile against
|
|
192
203
|
// the cgroup total where an RSS sum double-counts shared pages.
|
|
193
204
|
topProcesses: topProcessesByMemory(15),
|
|
@@ -65,7 +65,6 @@ import memoryPostCompact from "./memory/hooks/post-compact.js";
|
|
|
65
65
|
import memoryUserPromptSubmit from "./memory/hooks/user-prompt-submit.js";
|
|
66
66
|
import { memoryInjectors } from "./memory/injectors.js";
|
|
67
67
|
import memoryPkg from "./memory/package.json" with { type: "json" };
|
|
68
|
-
import { registerDefaultPluginPersistenceHooks } from "./memory/persistence-hooks-registration.js";
|
|
69
68
|
import {
|
|
70
69
|
memoryV3Injector,
|
|
71
70
|
memoryV3SpotlightInjector,
|
|
@@ -477,7 +476,10 @@ export function registerDefaultPluginInjectors(): void {
|
|
|
477
476
|
* so integration tests that exercise the full agent loop have a
|
|
478
477
|
* production-parity plugin stack. Use this in `beforeEach` of tests that
|
|
479
478
|
* dispatch through pipelines with a terminal that assumes the default
|
|
480
|
-
* plugin handles every op (e.g. compaction).
|
|
479
|
+
* plugin handles every op (e.g. compaction). Deliberately does NOT touch
|
|
480
|
+
* the memory plugin's persistence-lifecycle seam — that is a memory-plugin
|
|
481
|
+
* concept (`memory/persistence-hooks-registration.ts`), and tests that
|
|
482
|
+
* exercise persistence side effects register it themselves.
|
|
481
483
|
*
|
|
482
484
|
* Tests that specifically need an empty hook registry (pipeline-unit tests)
|
|
483
485
|
* should continue to call {@link resetHookRegistryForTests} directly.
|
|
@@ -495,5 +497,4 @@ export function resetPluginRegistryAndRegisterDefaults(): void {
|
|
|
495
497
|
registerDefaultPlugins();
|
|
496
498
|
clearInjectorRegistry();
|
|
497
499
|
registerDefaultPluginInjectors();
|
|
498
|
-
registerDefaultPluginPersistenceHooks();
|
|
499
500
|
}
|