Skip to content

#1 Persistent memory for AI coding agents based on real-world benchmarks

fix(capture): distinct ids for repeated prompts, lock-safe spool, authenticated recovery commands (#1468)

Rohit Ghumareabb87d2c609a
diff --git a/plugin/scripts/_capture.mjs b/plugin/scripts/_capture.mjs
index d6d80934..4926f197 100644
--- a/plugin/scripts/_capture.mjs
+++ b/plugin/scripts/_capture.mjs
@@ -112,6 +112,10 @@ function hostScalar(host, fields) {
function digest(parts) {
return createHash("sha256").update(parts.join("\0")).digest("hex").slice(0, 32);
}
+function hasHostIdentity(host) {
+ const source = host && typeof host === "object" ? host : {};
+ return hostScalar(source, HOST_ID_FIELDS) !== void 0 || hostScalar(source, HOST_TIME_FIELDS) !== void 0;
+}
function deriveEventId(hookType, sessionId, host, content) {
const source = host && typeof host === "object" ? host : {};
const hostId = hostScalar(source, HOST_ID_FIELDS);
@@ -487,11 +491,11 @@ function appendSpool(url, eventId, body, reason, options = {}) {
}
const bytes = Buffer.byteLength(line);
if (bytes > policy.maxRecordBytes) return note("too-large", bytes);
- return withLock(paths.lock, () => {
+ return withLock(paths.lock, (locked) => {
let expired = 0;
- if (fileSize(paths.file) + bytes > policy.maxBytes) expired = pruneExpiredLocked(paths, policy);
+ if (locked && fileSize(paths.file) + bytes > policy.maxBytes) expired = pruneExpiredLocked(paths, policy);
const over = fileSize(paths.file) + sentBytes(paths) + bytes - policy.maxBytes;
- if (over > 0) evictSent(paths, over);
+ if (locked && over > 0) evictSent(paths, over);
if (fileSize(paths.file) + sentBytes(paths) + bytes > policy.maxBytes) {
if (expired) writeStats(paths, (s) => void (s.expired += expired));
return note("full", bytes);
@@ -648,7 +652,8 @@ function claimFiles(paths) {
} catch {}
if (fileSize(paths.file) > 0) {
const target = join(paths.dir, `${paths.name}.draining-${process.pid}-${Date.now()}.jsonl`);
- withLock(paths.lock, () => {
+ withLock(paths.lock, (locked) => {
+ if (!locked) return;
try {
renameSync(paths.file, target);
claimed.push(target);
@@ -662,6 +667,20 @@ function requeueLocked(paths, leftover) {
const existing = existsSync(paths.file) ? parseLines(readFileSync(paths.file, "utf-8")).records : [];
rewriteLocked(paths, [...leftover, ...existing]);
}
+function requeueUnlocked(paths, leftover) {
+ if (leftover.length === 0) return;
+ const target = join(paths.dir, `${paths.name}.draining-${process.pid}-${Date.now()}-requeue.jsonl`);
+ const fd = openSync(target, "wx", 384);
+ try {
+ writeSync(fd, serialize(leftover));
+ fsyncSync(fd);
+ } finally {
+ closeSync(fd);
+ }
+ try {
+ utimesSync(target, 0, 0);
+ } catch {}
+}
function spoolHasRecords(url, dir) {
return fileSize(spoolPaths(url, dir).file) > 0;
}
@@ -750,7 +769,7 @@ async function drainSpool(url, send, options = {}) {
}
}
result.remaining = leftover.length;
- withLock(paths.lock, () => requeueLocked(paths, leftover), 2e3);
+ withLock(paths.lock, (locked) => locked ? requeueLocked(paths, leftover) : requeueUnlocked(paths, leftover), 2e3);
for (const file of files) try {
unlinkSync(file);
} catch {}
@@ -785,10 +804,14 @@ function authHeaders() {
if (SECRET) h["Authorization"] = `Bearer ${SECRET}`;
return h;
}
-function withEventId(body, host, content) {
+function withEventId(body, host, content, options = {}) {
+ const source = options.stable || hasHostIdentity(host) ? host : {
+ ...host,
+ timestamp: body.timestamp
+ };
return {
...body,
- eventId: deriveEventId(body.hookType, body.sessionId, host, content ?? body.data)
+ eventId: deriveEventId(body.hookType, body.sessionId, source, content ?? body.data)
};
}
function classify(status) {
diff --git a/plugin/scripts/session-end.mjs b/plugin/scripts/session-end.mjs
index d9be519d..ff60e20a 100755
--- a/plugin/scripts/session-end.mjs
+++ b/plugin/scripts/session-end.mjs
@@ -98,7 +98,7 @@ async function main() {
transcript: data.transcript_path,
index,
prompt
- }), 3e3)));
+ }, { stable: true }), 3e3)));
}
fetch(`${REST_URL}/agentmemory/session/end`, {
method: "POST",
diff --git a/src/capture/event-id.ts b/src/capture/event-id.ts
index 270042b3..5f02c681 100644
--- a/src/capture/event-id.ts
+++ b/src/capture/event-id.ts
@@ -50,6 +50,11 @@ function digest(parts: string[]): string {
return createHash("sha256").update(parts.join("\u0000")).digest("hex").slice(0, 32);
}
+export function hasHostIdentity(host: Record<string, unknown> | null | undefined): boolean {
+ const source = host && typeof host === "object" ? host : {};
+ return hostScalar(source, HOST_ID_FIELDS) !== undefined || hostScalar(source, HOST_TIME_FIELDS) !== undefined;
+}
+
export function deriveEventId(
hookType: string,
sessionId: string,
diff --git a/src/capture/spool.ts b/src/capture/spool.ts
index b9d7cdc9..5b71b4a8 100644
--- a/src/capture/spool.ts
+++ b/src/capture/spool.ts
@@ -343,11 +343,11 @@ export function appendSpool(
}
const bytes = Buffer.byteLength(line);
if (bytes > policy.maxRecordBytes) return note("too-large", bytes);
- return withLock(paths.lock, () => {
+ return withLock(paths.lock, (locked) => {
let expired = 0;
- if (fileSize(paths.file) + bytes > policy.maxBytes) expired = pruneExpiredLocked(paths, policy);
+ if (locked && fileSize(paths.file) + bytes > policy.maxBytes) expired = pruneExpiredLocked(paths, policy);
const over = fileSize(paths.file) + sentBytes(paths) + bytes - policy.maxBytes;
- if (over > 0) evictSent(paths, over);
+ if (locked && over > 0) evictSent(paths, over);
if (fileSize(paths.file) + sentBytes(paths) + bytes > policy.maxBytes) {
if (expired) writeStats(paths, (s) => void (s.expired += expired));
return note("full", bytes);
@@ -515,7 +515,8 @@ function claimFiles(paths: SpoolPaths): string[] {
} catch {}
if (fileSize(paths.file) > 0) {
const target = join(paths.dir, `${paths.name}.draining-${process.pid}-${Date.now()}.jsonl`);
- withLock(paths.lock, () => {
+ withLock(paths.lock, (locked) => {
+ if (!locked) return;
try {
renameSync(paths.file, target);
claimed.push(target);
@@ -531,6 +532,21 @@ function requeueLocked(paths: SpoolPaths, leftover: SpoolRecord[]): void {
rewriteLocked(paths, [...leftover, ...existing]);
}
+function requeueUnlocked(paths: SpoolPaths, leftover: SpoolRecord[]): void {
+ if (leftover.length === 0) return;
+ const target = join(paths.dir, `${paths.name}.draining-${process.pid}-${Date.now()}-requeue.jsonl`);
+ const fd = openSync(target, "wx", 0o600);
+ try {
+ writeSync(fd, serialize(leftover));
+ fsyncSync(fd);
+ } finally {
+ closeSync(fd);
+ }
+ try {
+ utimesSync(target, 0, 0);
+ } catch {}
+}
+
export function spoolHasRecords(url: string, dir?: string): boolean {
return fileSize(spoolPaths(url, dir).file) > 0;
}
@@ -607,7 +623,7 @@ export async function drainSpool(
}
}
result.remaining = leftover.length;
- withLock(paths.lock, () => requeueLocked(paths, leftover), 2000);
+ withLock(paths.lock, (locked) => (locked ? requeueLocked(paths, leftover) : requeueUnlocked(paths, leftover)), 2000);
for (const file of files) {
try {
unlinkSync(file);
diff --git a/src/cli/capture.ts b/src/cli/capture.ts
index 2cfdb67e..99ea81e9 100644
--- a/src/cli/capture.ts
+++ b/src/cli/capture.ts
@@ -1,4 +1,5 @@
import { drainSpool, parseSentMark, retainSent, spoolSummary, type SendOutcome, type SpoolRecord } from "../capture/spool.js";
+import { CURL_AUTH_HEADER } from "../functions/status.js";
interface CaptureCommandOptions {
base: string;
@@ -99,7 +100,7 @@ export async function runCaptureCommand(options: CaptureCommandOptions): Promise
log(` ${item.status.padEnd(8)} ${item.eventId} attempts=${item.attempts} ${item.preview ?? ""}`);
}
if (inbox && inbox.dead > 0) {
- log(`Retry dead letters: curl -X POST ${options.base}/agentmemory/capture/retry -H "Content-Type: application/json" -d '{"all":true}'`);
+ log(`Retry dead letters: curl -X POST ${options.base}/agentmemory/capture/retry ${CURL_AUTH_HEADER} -H "Content-Type: application/json" -d '{"all":true}'`);
}
return 0;
}
diff --git a/src/functions/status.ts b/src/functions/status.ts
index 3de59da5..fdf2c2b1 100644
--- a/src/functions/status.ts
+++ b/src/functions/status.ts
@@ -446,6 +446,14 @@ export function evaluateStatus(input: StatusInputs): StatusReport {
});
}
+ if (input.capture === null) {
+ problems.push({
+ level: "info",
+ code: "capture-check-unavailable",
+ message: "The capture inbox did not answer in time, so capture was not checked.",
+ fix: "The check runs again on the next status request. If it keeps timing out, the state store is overloaded: check the server log.",
+ });
+ }
problems.push(...captureProblems(input.capture ?? null, input.now, input.ports.rest));
if (input.stateStore && !input.stateStore.ok) {
@@ -505,6 +513,8 @@ export function evaluateStatus(input: StatusInputs): StatusReport {
const RECENT_DROP_MS = 24 * 60 * 60 * 1000;
+export const CURL_AUTH_HEADER = '-H "Authorization: Bearer ${AGENTMEMORY_SECRET:-$(cat ~/.agentmemory/secret)}"';
+
export function captureRestBase(restPort: number | null): string {
return `http://localhost:${restPort ?? 3111}/agentmemory`;
}
@@ -519,7 +529,7 @@ function captureProblems(capture: CaptureStatus | null, now: Date, restPort: num
level: "warn",
code: "capture-dead-letters",
message: `${plural(inbox.dead, "captured observation")} could not be stored after ${plural(capture.policy.maxAttempts, "attempt")} and ${inbox.dead === 1 ? "is parked as a dead letter" : "are parked as dead letters"}${inbox.lastError ? `: ${inbox.lastError}` : "."}`,
- fix: `List them with curl -s '${base}/capture?status=dead'. After fixing the cause, retry them with curl -X POST ${base}/capture/retry -H "Content-Type: application/json" -d '{"all":true}'.`,
+ fix: `List them with curl -s ${CURL_AUTH_HEADER} '${base}/capture?status=dead'. After fixing the cause, retry them with curl -X POST ${base}/capture/retry ${CURL_AUTH_HEADER} -H "Content-Type: application/json" -d '{"all":true}'.`,
});
}
if (inbox && inbox.retrying + inbox.pending > 0) {
@@ -536,21 +546,26 @@ function captureProblems(capture: CaptureStatus | null, now: Date, restPort: num
level: "info",
code: "capture-spool-waiting",
message: `${plural(waiting, "observation")} captured while the server was unreachable ${waiting === 1 ? "is" : "are"} waiting in the local capture spool.`,
- fix: `They are sent on the next hook call and at every start. To send them now: npx @agentmemory/agentmemory capture --drain, or curl -X POST ${base}/capture/drain.`,
+ fix: `They are sent on the next hook call and at every start. To send them now: npx @agentmemory/agentmemory capture --drain, or curl -X POST ${base}/capture/drain ${CURL_AUTH_HEADER}.`,
});
}
+ let dropped = 0;
+ let latest: { at: number; reason: string; maxBytes: number; maxAgeHours: number } | null = null;
for (const spool of capture.spool) {
+ dropped += spool.stats.dropped;
const lastDrop = spool.stats.lastDropAt ? Date.parse(spool.stats.lastDropAt) : NaN;
- if (Number.isFinite(lastDrop) && now.getTime() - lastDrop < RECENT_DROP_MS) {
- problems.push({
- level: "warn",
- code: "capture-spool-dropped",
- message: `The local capture spool dropped ${plural(spool.stats.dropped, "observation")} in total (latest reason: ${spool.stats.lastDropReason ?? "unknown"}), so those tool calls are not in memory.`,
- fix: `The spool holds at most ${Math.round(spool.maxBytes / 1024)} KiB for ${spool.maxAgeHours} hours. Raise AGENTMEMORY_CAPTURE_SPOOL_MAX_BYTES, keep agentmemory running while agents work, or check that AGENTMEMORY_CAPTURE_SPOOL is not false.`,
- });
- break;
+ if (Number.isFinite(lastDrop) && (!latest || lastDrop > latest.at)) {
+ latest = { at: lastDrop, reason: spool.stats.lastDropReason ?? "unknown", maxBytes: spool.maxBytes, maxAgeHours: spool.maxAgeHours };
}
}
+ if (latest && now.getTime() - latest.at < RECENT_DROP_MS) {
+ problems.push({
+ level: "warn",
+ code: "capture-spool-dropped",
+ message: `The local capture spool dropped ${plural(dropped, "observation")} in total (latest reason: ${latest.reason}), so those tool calls are not in memory.`,
+ fix: `The spool holds at most ${Math.round(latest.maxBytes / 1024)} KiB for ${latest.maxAgeHours} hours. Raise AGENTMEMORY_CAPTURE_SPOOL_MAX_BYTES, keep agentmemory running while agents work, or check that AGENTMEMORY_CAPTURE_SPOOL is not false.`,
+ });
+ }
return problems;
}
@@ -803,7 +818,7 @@ a{color:inherit}
<header><h1>agentmemory</h1><span class="badge ${report.status}">${report.status}</span>
<span class="meta">v${escapeHtml(report.service.version)} · engine ${escapeHtml(report.service.engineVersion)} · checked ${escapeHtml(report.checkedAt)} · <a href="?format=json">json</a></span></header>
<p class="lead ${report.status}">${escapeHtml(report.headline)}</p>
-<p class="live">A snapshot from when this page loaded. <a href="${escapeHtml(viewerUrl)}">Open the live version in the viewer &rarr;</a> From a terminal: <code>curl -s ${ports.rest ? `http://localhost:${escapeHtml(ports.rest)}` : ""}/agentmemory/status</code> returns this report as JSON.</p>
+<p class="live">A snapshot from when this page loaded. <a href="${escapeHtml(viewerUrl)}">Open the live version in the viewer &rarr;</a> From a terminal: <code>curl -s ${escapeHtml(CURL_AUTH_HEADER)} ${ports.rest ? `http://localhost:${escapeHtml(ports.rest)}` : ""}/agentmemory/status</code> returns this report as JSON.</p>
<h2>Problems</h2><ul class="problems">${problems}</ul>
<h2>Engine and connection</h2><table>
${row("Engine connection", escapeHtml(report.health?.connectionState ?? "unknown"))}
@@ -852,7 +867,7 @@ ${processRows(report)}
}
export function graphCompactCommand(restPort: number | null): string {
- return `curl -X POST http://localhost:${restPort ?? 3111}/agentmemory/graph/compact -H "Content-Type: application/json" -d '{}'`;
+ return `curl -X POST http://localhost:${restPort ?? 3111}/agentmemory/graph/compact ${CURL_AUTH_HEADER} -H "Content-Type: application/json" -d '{}'`;
}
export const UNINDEXED_SCAN_REUSE_MS = 30_000;
diff --git a/src/hooks/_capture.ts b/src/hooks/_capture.ts
index c17fc669..059f6780 100644
--- a/src/hooks/_capture.ts
+++ b/src/hooks/_capture.ts
@@ -1,6 +1,6 @@
import { spawn } from "node:child_process";
import { resolveClientSecret } from "../secret-store.js";
-import { deriveEventId } from "../capture/event-id.js";
+import { deriveEventId, hasHostIdentity } from "../capture/event-id.js";
import {
appendSpool,
drainInProgress,
@@ -39,10 +39,16 @@ export function authHeaders(): Record<string, string> {
return h;
}
-export function withEventId(body: ObserveBody, host: Record<string, unknown>, content?: unknown): ObserveBody {
+export function withEventId(
+ body: ObserveBody,
+ host: Record<string, unknown>,
+ content?: unknown,
+ options: { stable?: boolean } = {},
+): ObserveBody {
+ const source = options.stable || hasHostIdentity(host) ? host : { ...host, timestamp: body.timestamp };
return {
...body,
- eventId: deriveEventId(body.hookType, body.sessionId, host, content ?? body.data),
+ eventId: deriveEventId(body.hookType, body.sessionId, source, content ?? body.data),
};
}
diff --git a/src/hooks/session-end.ts b/src/hooks/session-end.ts
index 04bdf77e..bd652922 100644
--- a/src/hooks/session-end.ts
+++ b/src/hooks/session-end.ts
@@ -73,6 +73,7 @@ async function main() {
{ hookType: "prompt_submit", sessionId, project, cwd, timestamp, data: { prompt } },
{},
{ source: "transcript", transcript: data.transcript_path, index, prompt },
+ { stable: true },
),
3000,
),
diff --git a/test/capture-review-fixes.test.ts b/test/capture-review-fixes.test.ts
new file mode 100644
index 00000000..7db797d9
--- /dev/null
+++ b/test/capture-review-fixes.test.ts
@@ -0,0 +1,210 @@
+import { describe, it, expect, afterEach } from "vitest";
+import { spawn } from "node:child_process";
+import { createServer, type Server } from "node:http";
+import { existsSync, mkdtempSync, readFileSync, readdirSync, statSync, utimesSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { appendSpool, drainSpool, retainSent, spoolPaths, spoolPolicy, type SpoolRecord } from "../src/capture/spool.js";
+import { withEventId, type ObserveBody } from "../src/hooks/_capture.js";
+import { CURL_AUTH_HEADER, evaluateStatus, graphCompactCommand, type StatusInputs } from "../src/functions/status.js";
+import type { CaptureStatus } from "../src/functions/capture.js";
+
+const HOOKS_DIR = join(import.meta.dirname, "..", "plugin", "scripts");
+const URL = "http://localhost:3111";
+
+function body(timestamp: string, data: unknown = { prompt: "continue" }): ObserveBody {
+ return { hookType: "prompt_submit", sessionId: "ses_ids", project: "p", cwd: "/w", timestamp, data };
+}
+
+function record(eventId: string, spooledAt = new Date().toISOString()): SpoolRecord {
+ return { v: 1, eventId, spooledAt, reason: "unreachable", attempts: 0, body: { hookType: "post_tool_use", sessionId: "s", data: { n: eventId } } };
+}
+
+function lines(file: string): SpoolRecord[] {
+ if (!existsSync(file)) return [];
+ return readFileSync(file, "utf-8").split("\n").filter(Boolean).map((l) => JSON.parse(l) as SpoolRecord);
+}
+
+describe("event ids for hooks without a host id", () => {
+ it("gives repeated identical prompts different ids", () => {
+ const a = withEventId(body("2026-10-02T10:00:00.000Z"), { session_id: "ses_ids", prompt: "continue" });
+ const b = withEventId(body("2026-10-02T10:00:05.000Z"), { session_id: "ses_ids", prompt: "continue" });
+ expect(a.eventId).not.toBe(b.eventId);
+ });
+
+ it("keeps the host id stable regardless of the hook timestamp", () => {
+ const host = { session_id: "ses_ids", tool_use_id: "toolu_abc12345" };
+ const a = withEventId(body("2026-10-02T10:00:00.000Z"), host);
+ const b = withEventId(body("2026-10-02T10:00:05.000Z"), host);
+ expect(a.eventId).toBe(b.eventId);
+ });
+
+ it("keeps transcript replays stable when asked", () => {
+ const content = { source: "transcript", transcript: "/t.jsonl", index: 3, prompt: "continue" };
+ const a = withEventId(body("2026-10-02T10:00:00.000Z"), {}, content, { stable: true });
+ const b = withEventId(body("2026-10-02T11:00:00.000Z"), {}, content, { stable: true });
+ expect(a.eventId).toBe(b.eventId);
+ });
+});
+
+describe("prompt-submit hook stores identical prompts twice", () => {
+ let server: Server | undefined;
+
+ afterEach(async () => {
+ if (server) await new Promise<void>((resolve) => server!.close(() => resolve()));
+ server = undefined;
+ });
+
+ it("sends two distinct event ids for the same prompt text", async () => {
+ const received: Array<Record<string, unknown>> = [];
+ server = createServer((req, res) => {
+ let raw = "";
+ req.on("data", (c) => (raw += c));
+ req.on("end", () => {
+ try {
+ received.push(JSON.parse(raw));
+ } catch {}
+ res.writeHead(201, { "content-type": "application/json" });
+ res.end(JSON.stringify({ status: "accepted" }));
+ });
+ });
+ await new Promise<void>((resolve) => server!.listen(0, "127.0.0.1", () => resolve()));
+ const addr = server.address();
+ const port = typeof addr === "object" && addr ? addr.port : 0;
+ const home = mkdtempSync(join(tmpdir(), "am-prompt-twice-"));
+ const env = {
+ PATH: process.env["PATH"] ?? "",
+ HOME: home,
+ AGENTMEMORY_URL: `http://127.0.0.1:${port}`,
+ AGENTMEMORY_CAPTURE_SPOOL_DIR: join(home, "spool"),
+ };
+ const payload = JSON.stringify({ session_id: "ses_twice", cwd: "/work/p", hook_event_name: "UserPromptSubmit", prompt: "continue" });
+ for (let i = 0; i < 2; i++) {
+ await new Promise<void>((resolve, reject) => {
+ const child = spawn(process.execPath, [join(HOOKS_DIR, "prompt-submit.mjs")], { env, stdio: ["pipe", "ignore", "ignore"] });
+ child.on("error", reject);
+ child.on("close", () => resolve());
+ child.stdin.end(payload);
+ });
+ await new Promise((r) => setTimeout(r, 5));
+ }
+ const prompts = received.filter((r) => r["hookType"] === "prompt_submit");
+ expect(prompts).toHaveLength(2);
+ expect(prompts[0]!["eventId"]).not.toBe(prompts[1]!["eventId"]);
+ });
+});
+
+describe("spool operations without the lock", () => {
+ it("does not evict kept records when the append could not take the lock", () => {
+ const dir = mkdtempSync(join(tmpdir(), "am-spool-unlocked-"));
+ const policy = { ...spoolPolicy({}), maxBytes: 64 * 1024, maxRecordBytes: 16 * 1024 };
+ const paths = spoolPaths(URL, dir);
+ expect(retainSent(URL, "ev_kept_1", { data: { big: "x".repeat(15_000) } }, { bootId: "bootAAAA1111", durableAfterMs: 60_000 }, { policy, dir })).toBe(true);
+ for (let i = 0; i < 3; i++) appendSpool(URL, `ev_fill_${i}`, { data: { big: "y".repeat(15_000) } }, "unreachable", { policy, dir });
+ const keptBefore = readdirSync(dir).filter((f) => f.includes(".sent-"));
+ expect(keptBefore).toHaveLength(1);
+ writeFileSync(paths.lock, "999999\n");
+ const result = appendSpool(URL, "ev_overflow", { data: { big: "z".repeat(15_000) } }, "unreachable", { policy, dir });
+ expect(result.spooled).toBe(false);
+ expect(readdirSync(dir).filter((f) => f.includes(".sent-"))).toEqual(keptBefore);
+ });
+
+ it("leaves the main spool file alone and requeues to a separate file when the lock is held", async () => {
+ const dir = mkdtempSync(join(tmpdir(), "am-spool-requeue-"));
+ const paths = spoolPaths(URL, dir);
+ writeFileSync(paths.file, JSON.stringify(record("ev_main")) + "\n");
+ const orphan = join(dir, `${paths.name}.draining-1-1.jsonl`);
+ writeFileSync(orphan, JSON.stringify(record("ev_orphan")) + "\n");
+ utimesSync(orphan, 0, 0);
+ writeFileSync(paths.lock, "999999\n");
+ const result = await drainSpool(URL, async () => "retry", { dir });
+ expect(result.claimed).toBe(1);
+ expect(lines(paths.file).map((r) => r.eventId)).toEqual(["ev_main"]);
+ expect(existsSync(orphan)).toBe(false);
+ const requeued = readdirSync(dir).filter((f) => f.endsWith("-requeue.jsonl"));
+ expect(requeued).toHaveLength(1);
+ const file = join(dir, requeued[0]!);
+ expect(lines(file).map((r) => r.eventId)).toEqual(["ev_orphan"]);
+ expect(statSync(file).mtimeMs).toBe(0);
+ });
+});
+
+function statusInputs(capture: CaptureStatus | null | undefined): StatusInputs {
+ return {
+ now: new Date("2026-10-02T12:00:00.000Z"),
+ version: "0.10.0",
+ engineVersion: "0.22.1",
+ uptimeSeconds: 60,
+ stateBackend: "file",
+ ports: { rest: 3111, streams: 3112, viewer: 3113 },
+ health: { status: "healthy", alerts: [], notes: [], connectionState: "connected" },
+ circuitBreaker: { state: "closed", failures: 0 },
+ functionMetrics: [],
+ provider: "llm",
+ embeddingProvider: "embeddings",
+ flags: [],
+ index: { bm25Documents: 1, vectorDocuments: 1, observationsIndexed: 1, missingObservations: 0, sessions: 1, bm25Incomplete: false, pendingVectorBackfill: 0 },
+ graph: null,
+ graphExtractionEnabled: false,
+ auditLegacy: null,
+ capture,
+ };
+}
+
+function spoolSummaryWith(dropped: number, lastDropAt: string, reason: string) {
+ return {
+ enabled: true,
+ path: "/tmp/x.jsonl",
+ records: 0,
+ bytes: 0,
+ oldestAt: null,
+ retained: 0,
+ retainedBytes: 0,
+ maxBytes: 5 * 1024 * 1024,
+ maxAgeHours: 168,
+ stats: { spooled: 0, dropped, droppedBytes: 0, expired: 0, delivered: 0, duplicates: 0, rejected: 0, lastDropAt, lastDropReason: reason },
+ };
+}
+
+function capture(spool: ReturnType<typeof spoolSummaryWith>[], dead = 0): CaptureStatus {
+ return {
+ policy: { maxAttempts: 5, retryIntervalMs: 10_000, dedupRetentionHours: 168 },
+ inbox: { pending: 0, retrying: 0, dead, oldestAcceptedAt: null, nextAttemptAt: null, lastError: null },
+ sinceStart: { accepted: 0, completed: 0, duplicates: 0, retried: 0, recovered: 0, deadLettered: 0, rejected: 0, pruned: 0 },
+ lastSweepAt: null,
+ lastPruneAt: null,
+ lastBootDrain: null,
+ spool,
+ } as unknown as CaptureStatus;
+}
+
+describe("capture status", () => {
+ it("says capture was not checked when the capture status is unavailable", () => {
+ const report = evaluateStatus(statusInputs(null));
+ const p = report.problems.find((x) => x.code === "capture-check-unavailable");
+ expect(p?.level).toBe("info");
+ expect(report.status).not.toBe("ok");
+ });
+
+ it("adds nothing when capture status is simply not provided", () => {
+ expect(evaluateStatus(statusInputs(undefined)).problems.map((p) => p.code)).not.toContain("capture-check-unavailable");
+ });
+
+ it("sums drops across spools and reports the most recent reason", () => {
+ const report = evaluateStatus(
+ statusInputs(capture([spoolSummaryWith(2, "2026-10-02T11:00:00.000Z", "full"), spoolSummaryWith(3, "2026-10-02T11:30:00.000Z", "too-large")])),
+ );
+ const drops = report.problems.filter((p) => p.code === "capture-spool-dropped");
+ expect(drops).toHaveLength(1);
+ expect(drops[0]!.message).toContain("5 observations");
+ expect(drops[0]!.message).toContain("too-large");
+ });
+
+ it("prints recovery commands that send the secret", () => {
+ const report = evaluateStatus(statusInputs(capture([], 2)));
+ const dead = report.problems.find((p) => p.code === "capture-dead-letters");
+ expect(dead?.fix?.split(CURL_AUTH_HEADER).length).toBe(3);
+ expect(graphCompactCommand(3111)).toContain(CURL_AUTH_HEADER);
+ expect(CURL_AUTH_HEADER).toContain("Authorization: Bearer");
+ });
+});
diff --git a/test/status.test.ts b/test/status.test.ts
index cc992a97..0059e4a2 100644
--- a/test/status.test.ts
+++ b/test/status.test.ts
@@ -420,7 +420,7 @@ describe("status for beginners", () => {
);
const html = renderStatusHtml(report, "n", { viewerUrl: "http://127.0.0.1:3113/#health" });
expect(html).toContain('<a href="http://127.0.0.1:3113/#health">Open the live version in the viewer');
- expect(html).toContain("curl -s http://localhost:3111/agentmemory/status");
+ expect(html).toContain("curl -s -H &quot;Authorization: Bearer ${AGENTMEMORY_SECRET:-$(cat ~/.agentmemory/secret)}&quot; http://localhost:3111/agentmemory/status");
expect(html).toContain("50 MB of 4096 MB (1%)");
expect(html).toContain("1.3 ms");
expect(renderStatusHtml(report, "n")).toContain('href="/agentmemory/viewer#health"');