#1 Persistent memory for AI coding agents based on real-world benchmarks
TypeScript agentmemoryagentsaiclaudeclaudecodecodexcopilotcursorgenaiharnesshermesmemoryompopenclawopencodepi
feat(hooks): capture the assistant's final reply from the Stop hook (#1510)
Dmitrii Zhukov85dc30fb22dd
diff --git a/AGENTS.md b/AGENTS.mdindex df4575ab..a78c8674 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -86,7 +86,7 @@ case "memory_your_tool": {Hook scripts in `src/hooks/` are standalone Node.js scripts (no iii-sdk import). They read JSON from stdin, make HTTP calls to the REST API, and exit. There are two patterns depending on whether Claude Code consumes the script's stdout:- **Context-injecting hooks** (`pre-tool-use`, `pre-compact`, `session-start`) write recalled context to stdout for Claude Code to inject. These MUST use `try/catch` with `await fetch(..., { signal: AbortSignal.timeout(N) })` — the script has to wait for the response before exiting, and the timeout is the only bound on hang time.-- **Telemetry-only hooks** (`notification`, `post-tool-failure`, `post-tool-use`, `prompt-submit`, `stop`, `session-end`, `subagent-start`, `subagent-stop`, `task-completed`) write nothing to stdout. These MUST use fire-and-forget `fetch(..., { signal: AbortSignal.timeout(N) }).catch(() => {})` paired with `setTimeout(() => process.exit(0), 500).unref()`. The unawaited fetch dispatches the request; the unref'd `setTimeout` force-exits the process after the request has been flushed to the local daemon's socket buffer (~500ms is enough for single-request hooks; use 1500ms for multi-request hooks like `stop` and `session-end` so all fetches have time to start, especially when `AGENTMEMORY_URL` points to a remote daemon). Without the `setTimeout` Node keeps the event loop alive waiting for any in-flight fetch to settle, which means the hook still blocks Claude Code's next-prompt boundary for up to the AbortSignal duration — exactly the bug fire-and-forget is meant to fix.+- **Telemetry-only hooks** (`notification`, `post-tool-failure`, `post-tool-use`, `prompt-submit`, `stop`, `session-end`, `subagent-start`, `subagent-stop`, `task-completed`) write nothing to stdout. These MUST use fire-and-forget `fetch(..., { signal: AbortSignal.timeout(N) }).catch(() => {})` paired with `setTimeout(() => process.exit(0), 500).unref()`. The unawaited fetch dispatches the request; the unref'd `setTimeout` force-exits the process after the request has been flushed to the local daemon's socket buffer (~500ms is enough for single-request hooks; use 1500ms for multi-request hooks like `stop` and `session-end` so all fetches have time to start, especially when `AGENTMEMORY_URL` points to a remote daemon). `stop` awaits its reply capture (bounded by `OBSERVE_TIMEOUT_MS`, capped at that timeout plus 1500ms) before posting `/session/end`, so the reply is stored before finalization is requested, and then gives `/session/end` the usual 1500ms; a Stop without a reply exits as it did before. An acknowledged capture does not mean the session summary already reflects the reply — compression for the turn can still be pending when finalization runs. Without the `setTimeout` Node keeps the event loop alive waiting for any in-flight fetch to settle, which means the hook still blocks Claude Code's next-prompt boundary for up to the AbortSignal duration — exactly the bug fire-and-forget is meant to fix.## Coding Standardsdiff --git a/README.md b/README.mdindex e6de23e0..526fb608 100644--- a/README.md+++ b/README.md@@ -1029,7 +1029,7 @@ Memories decay over time (Ebbinghaus curve). Frequently accessed memories streng| `PostToolUseFailure` | Error context || `PreCompact` | Re-injects memory before compaction || `SubagentStart/Stop` | Sub-agent lifecycle |-| `Stop` | End-of-session summary |+| `Stop` | Assistant's final reply of each turn (privacy-filtered) || `SessionEnd` | Session complete marker |### Key Capabilitiesdiff --git a/plugin/scripts/_capture.mjs b/plugin/scripts/_capture.mjsindex e4a136a7..9fd588a8 100644--- a/plugin/scripts/_capture.mjs+++ b/plugin/scripts/_capture.mjs@@ -920,6 +920,6 @@ async function runDrainChild() {}).catch(() => void 0);}//#endregion-export { REST_URL, authHeaders, captureObservation, isDrainChild, runDrainChild, withEventId };+export { REST_URL, authHeaders, captureObservation, isDrainChild, runDrainChild, stripPrivateData, withEventId };//# sourceMappingURL=_capture.mjs.map\ No newline at end of filediff --git a/plugin/scripts/stop.mjs b/plugin/scripts/stop.mjsindex b73743ef..8dde180a 100755--- a/plugin/scripts/stop.mjs+++ b/plugin/scripts/stop.mjs@@ -1,73 +1,43 @@#!/usr/bin/env node-import { readFileSync } from "node:fs";-import { homedir } from "node:os";-import { join } from "node:path";-//#region src/secret-store.ts-const SECRET_KEY = "AGENTMEMORY_SECRET";-function agentmemoryHomeDir() {- return join(homedir(), ".agentmemory");-}-function secretFilePath() {- return join(agentmemoryHomeDir(), "secret");-}-function usable(value) {- if (typeof value !== "string") return "";- const trimmed = value.trim();- if (!trimmed) return "";- if (trimmed.startsWith("${") && trimmed.endsWith("}")) return "";- return trimmed;-}-function unquote(value) {- const quote = value[0];- if ((quote === "\"" || quote === "'") && value.length > 1) {- const close = value.indexOf(quote, 1);- if (close !== -1) return value.slice(1, close);- }- const hash = value.indexOf(" #");- return hash === -1 ? value : value.slice(0, hash).trim();-}-function readEnvFileSecret() {- let content;+import { execSync } from "node:child_process";+import { realpathSync } from "node:fs";+import { basename, dirname, resolve } from "node:path";+import { REST_URL, authHeaders, captureObservation, isDrainChild, runDrainChild, stripPrivateData, withEventId } from "./_capture.mjs";+//#region src/hooks/_project.ts+function resolveProject(cwd) {+ const explicit = process.env["AGENTMEMORY_PROJECT_NAME"];+ if (explicit && explicit.trim()) return explicit.trim();+ const dir = cwd && cwd.trim() ? cwd : process.cwd();try {- content = readFileSync(join(agentmemoryHomeDir(), ".env"), "utf-8");- } catch {- return "";- }- if (typeof content !== "string") return "";- let found = "";- for (const line of content.split("\n")) {- const trimmed = line.trim();- if (trimmed.startsWith("#")) continue;- const eq = trimmed.indexOf("=");- if (eq === -1) continue;- if (trimmed.slice(0, eq).replace(/^export\s+/, "").trim() !== SECRET_KEY) continue;- found = usable(unquote(trimmed.slice(eq + 1).trim()));- }- return found;+ const [top, gitDir, commonDir] = execSync("git rev-parse --show-toplevel --git-dir --git-common-dir", {+ cwd: dir,+ stdio: [+ "ignore",+ "pipe",+ "ignore"+ ],+ timeout: 500+ }).toString().trim().split(/\r?\n/);+ if (top) return basename(repositoryRoot(dir, top, gitDir, commonDir));+ } catch {}+ return basename(dir);}-function readStoredSecret() {- try {- return usable(readFileSync(secretFilePath(), "utf-8"));- } catch {- return "";- }+function repositoryRoot(dir, top, gitDir, commonDir) {+ if (!gitDir || !commonDir) return top;+ const physical = realpathSync(dir);+ const common = resolve(physical, commonDir);+ if (resolve(physical, gitDir) === common || basename(common) !== ".git") return top;+ return dirname(common);}-function isLoopbackUrl(url) {- let hostname;- try {- hostname = new URL(url).hostname.toLowerCase();- } catch {- return false;+function hookCwd(data) {+ if (!data || typeof data !== "object") return void 0;+ if (typeof data.cwd === "string" && data.cwd.trim()) return data.cwd;+ const roots = data.workspace_roots;+ if (Array.isArray(roots)) {+ for (const root of roots) if (typeof root === "string" && root.trim()) return root;}- const bare = hostname.replace(/^\[|\]$/g, "");- return bare === "localhost" || bare === "::1" || /^127(?:\.\d{1,3}){3}$/.test(bare);-}-function resolveClientSecret(baseUrl, env = process.env) {- const fromEnv = usable(env[SECRET_KEY]);- if (fromEnv) return fromEnv;- if (env.AGENTMEMORY_CREDENTIAL_MODE === "explicit") return "";- if (!isLoopbackUrl(baseUrl)) return "";- return readEnvFileSecret() || readStoredSecret();+ const projectDir = process.env["DEVIN_PROJECT_DIR"] || process.env["CLAUDE_PROJECT_DIR"];+ if (projectDir && projectDir.trim()) return projectDir;}//#endregion//#region src/hooks/stop.ts@@ -76,14 +46,24 @@ function isSdkChildContext(payload) {if (!payload || typeof payload !== "object") return false;return payload.entrypoint === "sdk-ts";}-const REST_URL = process.env["AGENTMEMORY_URL"] || "http://localhost:3111";-const SECRET = resolveClientSecret(REST_URL);-function authHeaders() {- const h = { "Content-Type": "application/json" };- if (SECRET) h["Authorization"] = `Bearer ${SECRET}`;- return h;+const OBSERVE_TIMEOUT_MS = 2e3;+const EXIT_CAP_MS = 3500;+const END_CAP_MS = 1500;+const REPLY_MAX_CHARS = 4e3;+function boundReply(reply) {+ const safe = stripPrivateData(reply);+ if (safe.length <= REPLY_MAX_CHARS) return { text: safe };+ let head = Math.ceil((REPLY_MAX_CHARS - 1) / 2);+ let tail = safe.length - (REPLY_MAX_CHARS - 1 - head);+ if (/[\uD800-\uDBFF]/.test(safe[head - 1])) head--;+ if (/[\uDC00-\uDFFF]/.test(safe[tail])) tail++;+ return {+ text: `${safe.slice(0, head)}\u2026${safe.slice(tail)}`,+ bytes: Buffer.byteLength(safe, "utf8")+ };}async function main() {+ if (isDrainChild()) return runDrainChild();let input = "";for await (const chunk of process.stdin) input += chunk;let data;@@ -95,6 +75,25 @@ async function main() {if (!data || typeof data !== "object") return;if (isSdkChildContext(data)) return;const sessionId = data.session_id || data.sessionId || data.conversation_id || "unknown";+ const reply = data.last_assistant_message;+ if (typeof reply === "string" && reply.trim()) {+ const capture = setTimeout(() => process.exit(0), EXIT_CAP_MS).unref();+ const cwd = hookCwd(data) || process.cwd();+ const bounded = boundReply(reply);+ await captureObservation(withEventId({+ hookType: "stop",+ sessionId,+ project: resolveProject(cwd),+ cwd,+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),+ data: {+ last_assistant_message: bounded.text,+ ...bounded.bytes === void 0 ? {} : { last_assistant_message_bytes: bounded.bytes }+ }+ }, {}), OBSERVE_TIMEOUT_MS).catch(() => {});+ clearTimeout(capture);+ }+ setTimeout(() => process.exit(0), END_CAP_MS).unref();fetch(`${REST_URL}/agentmemory/session/end`, {method: "POST",headers: authHeaders(),@@ -104,7 +103,6 @@ async function main() {}),signal: AbortSignal.timeout(5e3)}).catch(() => {});- setTimeout(() => process.exit(0), 1500).unref();}main().catch(() => process.exit(0));//#endregiondiff --git a/scripts/release-gate/run.mjs b/scripts/release-gate/run.mjsindex 6b76b2b6..b5b025b8 100644--- a/scripts/release-gate/run.mjs+++ b/scripts/release-gate/run.mjs@@ -774,14 +774,15 @@ async function main() {const sid = `gate-capture-${randomBytes(4).toString("hex")}`;markers.capture = [marker("amber"), marker("birch"), marker("cedar")];markers.prompt = marker("prompt");+ markers.reply = marker("reply");d.sessionId = sid;const timings = [];timings.push((await instA.hook("SessionStart", { session_id: sid, source: "startup" })).ms);timings.push((await instA.hook("UserPromptSubmit", { session_id: sid, prompt: `Investigate the flaky parser test ${markers.prompt}` })).ms);for (const m of markers.capture) timings.push((await instA.hook("PostToolUse", instA.toolEvent(sid, m))).ms);- timings.push((await instA.hook("Stop", { session_id: sid, stop_hook_active: false })).ms);+ timings.push((await instA.hook("Stop", { session_id: sid, stop_hook_active: false, last_assistant_message: `The parser flake came from CRLF handling ${markers.reply} in the tokenizer` })).ms);d.hookMs = timings;- for (const m of markers.capture) {+ for (const m of [...markers.capture, markers.reply]) {await poll(`search to find ${m}`, () => instA.searchFinds(m), { timeoutMs: 20_000 });const n = await instA.countMarker(sid, m);assert(n === 1, `marker ${m} is stored in ${n} observations, expected 1`);@@ -829,20 +830,23 @@ async function main() {await instA.stop();const sid = `gate-offline-${randomBytes(4).toString("hex")}`;markers.offline = [marker("cobalt"), marker("indigo"), marker("violet")];+ markers.offlineReply = marker("lapis");+ const recovered = [...markers.offline, markers.offlineReply];const hookMs = [];for (const m of markers.offline) hookMs.push((await instA.hook("PostToolUse", instA.toolEvent(sid, m))).ms);+ hookMs.push((await instA.hook("Stop", { session_id: sid, stop_hook_active: false, last_assistant_message: `Offline turn ended with ${markers.offlineReply} pending` })).ms);d.hookMs = hookMs;assert(Math.max(...hookMs) < 5000, `a hook took ${Math.max(...hookMs)} ms while the service was down`);const cap = await mustRun("agentmemory capture --json", gate.bin("agentmemory"), ["capture", "--json"], { env: instA.env(), cwd: instA.cwd, timeoutMs: 30_000 });const spool = JSON.parse(cap.stdout.slice(cap.stdout.indexOf("{"))).spool;d.spooledWhileDown = spool.records;- assert(spool.records >= markers.offline.length, `spool holds ${spool.records} records, expected ${markers.offline.length}`);+ assert(spool.records >= recovered.length, `spool holds ${spool.records} records, expected ${recovered.length}`);d.restartMs = await instA.start();- for (const m of markers.offline) {+ for (const m of recovered) {await poll(`recovered observation ${m}`, async () => (await instA.countMarker(sid, m)) >= 1, { timeoutMs: 30_000 });await poll(`search to find ${m}`, () => instA.searchFinds(m), { timeoutMs: 20_000 });}- for (const m of markers.offline) {+ for (const m of recovered) {const n = await instA.countMarker(sid, m);assert(n === 1, `offline marker ${m} is stored ${n} times, expected 1`);}@@ -1009,7 +1013,7 @@ async function main() {return t.sessions === source.sessions && t.observations === source.observations && t.memories === source.memories ? t : null;}, { timeoutMs: 60_000, intervalMs: 1000 });d.restored = restored;- const probe = [...(markers.capture ?? []), ...(markers.offline ?? [])];+ const probe = [...(markers.capture ?? []), ...(markers.offline ?? []), markers.reply, markers.offlineReply].filter(Boolean);for (const m of probe) await poll(`restored search to find ${m}`, () => instC.searchFinds(m), { timeoutMs: 30_000 });if (markers.mcp) {const mem = await request("GET", `${instC.base}/memories`);diff --git a/src/functions/compress-synthetic.ts b/src/functions/compress-synthetic.tsindex 000199b5..0f324f86 100644--- a/src/functions/compress-synthetic.ts+++ b/src/functions/compress-synthetic.ts@@ -73,6 +73,15 @@ function truncate(s: string, n: number): string {return s.slice(0, end) + "\u2026";}+function keepEnds(s: string, n: number): string {+ if (s.length <= n) return s;+ let head = Math.ceil((n - 1) / 2);+ let tail = s.length - (n - 1 - head);+ if (/[\uD800-\uDBFF]/.test(s[head - 1])) head--;+ if (/[\uDC00-\uDFFF]/.test(s[tail])) tail++;+ return s.slice(0, head) + "\u2026" + s.slice(tail);+}+export function buildSyntheticCompression(raw: RawObservation,): CompressedObservation {@@ -80,9 +89,10 @@ export function buildSyntheticCompression(const inputStr = stringifyForNarrative(raw.toolInput);const outputStr = stringifyForNarrative(raw.toolOutput);const promptStr = raw.userPrompt ?? "";+ const responseStr = keepEnds(raw.assistantResponse ?? "", 400);const source = createObservationSource(raw);- const narrativeParts = [promptStr, inputStr, outputStr].filter(+ const narrativeParts = [promptStr, inputStr, outputStr, responseStr].filter((s) => s.length > 0,);const payload = source.payload;diff --git a/src/functions/compress.ts b/src/functions/compress.tsindex 41e6387f..27138033 100644--- a/src/functions/compress.ts+++ b/src/functions/compress.ts@@ -145,13 +145,14 @@ export function registerCompressFunction(}}- const retainedOutput = raw.toolOutput ?? raw.assistantResponse ?? (raw.raw && Object.keys(Object(raw.raw)).length > 0 ? raw.raw : undefined);+ const retainedOutput = raw.toolOutput ?? (raw.raw && Object.keys(Object(raw.raw)).length > 0 ? raw.raw : undefined);const prompt = buildCompressionPrompt({hookType: raw.hookType,toolName: raw.toolName,toolInput: raw.toolInput,toolOutput: imageDescription ? `[Image Description]: ${imageDescription}\n\n${retainedOutput ?? ""}` : retainedOutput,userPrompt: raw.userPrompt,+ assistantResponse: raw.assistantResponse,timestamp: raw.timestamp,});const validator = (response: string) => {diff --git a/src/functions/observation-source.ts b/src/functions/observation-source.tsindex aff6fb0a..3454f0f3 100644--- a/src/functions/observation-source.ts+++ b/src/functions/observation-source.ts@@ -43,8 +43,11 @@ export function createObservationSource(if (Object.values(fields).every((value) => value === undefined)) fields.payload = raw.raw;const retained = sanitize(fields) as Record<string, unknown>;const hookType = prefixWithinBytes(stripPrivateData(raw.hookType), 128) as HookType;- const originalBytes = Math.max(bytes({ hookType: raw.hookType, ...retained }), previous?.originalBytes ?? 0);- const truncated = previous?.truncated === true || hookType !== raw.hookType;+ const dropped = raw.assistantResponseBytes === undefined+ ? 0+ : Math.max(0, raw.assistantResponseBytes - Buffer.byteLength(raw.assistantResponse ?? "", "utf8"));+ const originalBytes = Math.max(bytes({ hookType: raw.hookType, ...retained }) + dropped, previous?.originalBytes ?? 0);+ const truncated = previous?.truncated === true || hookType !== raw.hookType || dropped > 0;const full = { hookType, originalBytes, truncated, ...retained };if (bytes(full) <= maxBytes) return full;diff --git a/src/functions/observe.ts b/src/functions/observe.tsindex 0556bf26..be320266 100644--- a/src/functions/observe.ts+++ b/src/functions/observe.ts@@ -161,6 +161,10 @@ export function registerObserveFunction(if (payload.hookType === "stop") {const response = d["assistant_response"] ?? d["last_assistant_message"] ?? d["response"];if (typeof response === "string") raw.assistantResponse = response;+ const originalBytes = d["last_assistant_message_bytes"];+ if (typeof originalBytes === "number" && Number.isSafeInteger(originalBytes) && originalBytes >= 0) {+ raw.assistantResponseBytes = originalBytes;+ }}extractedImage = extractImage(sanitizedRaw);diff --git a/src/hooks/_capture.ts b/src/hooks/_capture.tsindex 059f6780..021c8bff 100644--- a/src/hooks/_capture.ts+++ b/src/hooks/_capture.ts@@ -14,6 +14,8 @@ import {type SpoolRecord,} from "../capture/spool.js";+export { stripPrivateData } from "../functions/privacy.js";+export const REST_URL = process.env["AGENTMEMORY_URL"] || "http://localhost:3111";const SECRET = resolveClientSecret(REST_URL);const DRAIN_CHILD_ENV = "AGENTMEMORY_CAPTURE_DRAIN_CHILD";diff --git a/src/hooks/stop.ts b/src/hooks/stop.tsindex 968acb9a..8594a7bc 100644--- a/src/hooks/stop.ts+++ b/src/hooks/stop.ts@@ -1,5 +1,6 @@#!/usr/bin/env node-import { resolveClientSecret } from "../secret-store.js";+import { resolveProject, hookCwd } from "./_project.js";+import { REST_URL, authHeaders, captureObservation, isDrainChild, runDrainChild, stripPrivateData, withEventId } from "./_capture.js";// Inlined — see src/hooks/sdk-guard.ts for canonical version. Kept local// per-hook so tsdown does not emit a shared hashed chunk that would churn@@ -10,16 +11,25 @@ function isSdkChildContext(payload: unknown): boolean {return (payload as { entrypoint?: unknown }).entrypoint === "sdk-ts";}-const REST_URL = process.env["AGENTMEMORY_URL"] || "http://localhost:3111";-const SECRET = resolveClientSecret(REST_URL);+const OBSERVE_TIMEOUT_MS = 2000;+const EXIT_CAP_MS = 3500;+const END_CAP_MS = 1500;+const REPLY_MAX_CHARS = 4000;-function authHeaders(): Record<string, string> {- const h: Record<string, string> = { "Content-Type": "application/json" };- if (SECRET) h["Authorization"] = `Bearer ${SECRET}`;- return h;+// stripPrivateData only matches a closed <private> block, so the whole reply+// has to be redacted before anything shortens it.+function boundReply(reply: string): { text: string; bytes?: number } {+ const safe = stripPrivateData(reply);+ if (safe.length <= REPLY_MAX_CHARS) return { text: safe };+ let head = Math.ceil((REPLY_MAX_CHARS - 1) / 2);+ let tail = safe.length - (REPLY_MAX_CHARS - 1 - head);+ if (/[\uD800-\uDBFF]/.test(safe[head - 1]!)) head--;+ if (/[\uDC00-\uDFFF]/.test(safe[tail]!)) tail++;+ return { text: `${safe.slice(0, head)}\u2026${safe.slice(tail)}`, bytes: Buffer.byteLength(safe, "utf8") };}async function main() {+ if (isDrainChild()) return runDrainChild();let input = "";for await (const chunk of process.stdin) {input += chunk;@@ -40,15 +50,33 @@ async function main() {}const sessionId = ((data.session_id || data.sessionId || data.conversation_id) as string) || "unknown";+ const reply = data.last_assistant_message;+ if (typeof reply === "string" && reply.trim()) {+ const capture = setTimeout(() => process.exit(0), EXIT_CAP_MS).unref();+ const cwd = hookCwd(data) || process.cwd();+ const bounded = boundReply(reply);+ const body = {+ hookType: "stop",+ sessionId,+ project: resolveProject(cwd),+ cwd,+ timestamp: new Date().toISOString(),+ data: {+ last_assistant_message: bounded.text,+ ...(bounded.bytes === undefined ? {} : { last_assistant_message_bytes: bounded.bytes }),+ },+ };+ await captureObservation(withEventId(body, {}), OBSERVE_TIMEOUT_MS).catch(() => {});+ clearTimeout(capture);+ }+ setTimeout(() => process.exit(0), END_CAP_MS).unref();fetch(`${REST_URL}/agentmemory/session/end`, {method: "POST",headers: authHeaders(),body: JSON.stringify({ sessionId, final: false }),signal: AbortSignal.timeout(5000),}).catch(() => {});-- setTimeout(() => process.exit(0), 1500).unref();}main().catch(() => process.exit(0));diff --git a/src/prompts/compression.ts b/src/prompts/compression.tsindex 198c45bf..b90a268b 100644--- a/src/prompts/compression.ts+++ b/src/prompts/compression.ts@@ -34,6 +34,7 @@ export function buildCompressionPrompt(observation: {toolInput?: unknown;toolOutput?: unknown;userPrompt?: string;+ assistantResponse?: string;timestamp: string;}): string {const parts = [@@ -59,6 +60,9 @@ export function buildCompressionPrompt(observation: {if (observation.userPrompt) {parts.push(`User prompt:\n${truncate(observation.userPrompt, 2000)}`);}+ if (observation.assistantResponse) {+ parts.push(`Assistant response:\n${truncate(observation.assistantResponse, 4000)}`);+ }return parts.join("\n\n");}diff --git a/src/types.ts b/src/types.tsindex f7619ceb..0feecabc 100644--- a/src/types.ts+++ b/src/types.ts@@ -61,6 +61,7 @@ export interface RawObservation {toolOutput?: unknown;userPrompt?: string;assistantResponse?: string;+ assistantResponseBytes?: number;raw: unknown;modality?: "text" | "image" | "mixed";imageData?: string;diff --git a/test/auto-compress.test.ts b/test/auto-compress.test.tsindex 8069fc74..8118f5c9 100644--- a/test/auto-compress.test.ts+++ b/test/auto-compress.test.ts@@ -270,6 +270,36 @@ describe("buildSyntheticCompression", () => {expect(synth.narrative.length).toBeLessThanOrEqual(400);});+ it("puts the assistant reply of a stop observation into the narrative", async () => {+ const { buildSyntheticCompression } = await import(+ "../src/functions/compress-synthetic.js"+ );+ const synth = buildSyntheticCompression({+ id: "obs_5",+ sessionId: "ses_1",+ timestamp: new Date().toISOString(),+ hookType: "stop",+ assistantResponse: "We decided to use bge-m3 for Spanish embeddings.",+ raw: {},+ });+ expect(synth.narrative).toBe("We decided to use bge-m3 for Spanish embeddings.");+ });++ it("keeps the opening and the end of a long reply without splitting a character", async () => {+ const { buildSyntheticCompression } = await import(+ "../src/functions/compress-synthetic.js"+ );+ const synth = buildSyntheticCompression({+ id: "obs_6",+ sessionId: "ses_1",+ timestamp: new Date().toISOString(),+ hookType: "stop",+ assistantResponse: "a".repeat(199) + "😀" + "b".repeat(3000) + "😀" + "c".repeat(198),+ raw: {},+ });+ expect(synth.narrative).toBe("a".repeat(199) + "…" + "c".repeat(198));+ });+it("maps post_tool_failure to the error type even with no tool name", async () => {const { buildSyntheticCompression } = await import("../src/functions/compress-synthetic.js"@@ -284,3 +314,15 @@ describe("buildSyntheticCompression", () => {expect(synth.type).toBe("error");});});++describe("buildCompressionPrompt", () => {+ it("gives the model the assistant reply of a stop observation", async () => {+ const { buildCompressionPrompt } = await import("../src/prompts/compression.js");+ const prompt = buildCompressionPrompt({+ hookType: "stop",+ assistantResponse: "We decided to use bge-m3 for Spanish embeddings.",+ timestamp: "2026-10-03T15:23:24.000Z",+ });+ expect(prompt).toContain("Assistant response:\nWe decided to use bge-m3 for Spanish embeddings.");+ });+});diff --git a/test/hook-exit-timing.test.ts b/test/hook-exit-timing.test.tsindex b0a05408..f331cc05 100644--- a/test/hook-exit-timing.test.ts+++ b/test/hook-exit-timing.test.ts@@ -24,6 +24,7 @@ describe("hook exit timing", () => {"post-tool-failure.ts","post-tool-use.ts","prompt-submit.ts",+ "stop.ts","subagent-start.ts","subagent-stop.ts","task-completed.ts",@@ -36,6 +37,7 @@ describe("hook exit timing", () => {"post-tool-failure.ts","post-tool-use.ts","prompt-submit.ts",+ "stop.ts","subagent-start.ts","subagent-stop.ts","task-completed.ts",diff --git a/test/hook-shared-capture.test.ts b/test/hook-shared-capture.test.tsindex 8e915eaf..3f97b4a3 100644--- a/test/hook-shared-capture.test.ts+++ b/test/hook-shared-capture.test.ts@@ -9,6 +9,7 @@ const captureHooks = ["post-tool-use","prompt-submit","session-end",+ "stop","subagent-start","subagent-stop","task-completed",@@ -29,7 +30,7 @@ describe("shared capture module in plugin/scripts", () => {});it("leaves hooks that do not capture self-contained", () => {- for (const hook of ["session-start", "pre-tool-use", "stop", "pre-compact", "post-commit"]) {+ for (const hook of ["session-start", "pre-tool-use", "pre-compact", "post-commit"]) {expect(existsSync(join(scriptsDir, `${hook}.mjs`))).toBe(true);expect(readFileSync(join(scriptsDir, `${hook}.mjs`), "utf-8")).not.toContain("_capture.mjs");}diff --git a/test/observation-source.test.ts b/test/observation-source.test.tsindex 0ce16f27..c816a4f5 100644--- a/test/observation-source.test.ts+++ b/test/observation-source.test.ts@@ -170,6 +170,32 @@ describe("retained observation source", () => {expect(JSON.stringify(updates)).not.toContain(tail);});+ it("makes a captured stop reply searchable and keeps it as the replay response", async () => {+ const { observe, call } = rig();+ const reply = "We decided to use bge-m3 for Spanish embeddings because it handles accents.";+ const saved = await observe("stop", { last_assistant_message: reply });+ expect(saved.source?.assistantResponse).toBe(reply);+ expect(saved.narrative).toContain(reply);+ expect(JSON.stringify(await call("mem::search", { query: "Spanish embeddings accents" }))).toContain(saved.id);+ });++ it("gives the compression model the reply of a stop observation", async () => {+ const r = rig();+ vi.stubEnv("AGENTMEMORY_AUTO_COMPRESS", "true");+ const provider: MemoryProvider = {+ name: "test", summarize: vi.fn(),+ compress: vi.fn(async () => "<observation><type>decision</type><title>Chose bge-m3 embeddings</title><facts><fact>bge-m3 for Spanish</fact></facts><narrative>The agent chose bge-m3.</narrative><concepts><concept>embeddings</concept></concepts><files></files><importance>7</importance></observation>"),+ };+ registerCompressFunction(r.sdk as never, r.kv as never, provider);+ const reply = "We decided to use bge-m3 for Spanish embeddings.";+ const saved = await r.observe("stop", { last_assistant_message: reply });+ const prompt = vi.mocked(provider.compress).mock.calls[0][1];+ expect(prompt).toContain(`Assistant response:\n${reply}`);+ expect(prompt.split(reply).length - 1).toBe(1);+ expect(saved.title).toBe("Chose bge-m3 embeddings");+ expect(saved.source?.assistantResponse).toBe(reply);+ });+it("leaves sanitized stored source intact when model compression fails", async () => {const r = rig();vi.stubEnv("AGENTMEMORY_AUTO_COMPRESS", "true");diff --git a/test/stop-hook-reply.test.ts b/test/stop-hook-reply.test.tsnew file mode 100644index 00000000..a18b052b--- /dev/null+++ b/test/stop-hook-reply.test.ts@@ -0,0 +1,479 @@+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { spawn } from "node:child_process";+import { createServer, type Server } from "node:http";+import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { mockKV, mockSdk } from "./helpers/mocks.js";+import { drainInProgress } from "../src/capture/spool.js";+import { KV } from "../src/state/schema.js";+import type { CompressedObservation, MemoryProvider, Session } from "../src/types.js";++vi.mock("../src/logger.js", () => ({ logger: { info: vi.fn(), warn: vi.fn(), error: vi.fn() } }));++const HOOK = join(import.meta.dirname, "..", "plugin", "scripts", "stop.mjs");+const SESSION = "ses_stop_reply";+const OBSERVE_TIMEOUT_MS = 2000;+const EXIT_CAP_MS = 3500;++type Received = { path: string; body: Record<string, unknown>; auth?: string; at: number; answeredAt?: number };++type Daemon = {+ port: number;+ kv: ReturnType<typeof mockKV>;+ received: Received[];+ call: (id: string, payload: unknown) => Promise<any>;+ close: () => Promise<void>;+};++const ROUTES: Record<string, string> = {+ "/agentmemory/observe": "api::observe",+ "/agentmemory/session/end": "api::session::end",+};++let home: string;+const daemons: Daemon[] = [];+const hookPorts = new Set<number>();++function sleep(ms: number): Promise<void> {+ return new Promise((resolve) => setTimeout(resolve, ms));+}++async function waitFor(check: () => boolean, ms: number): Promise<boolean> {+ const deadline = Date.now() + ms;+ while (Date.now() < deadline) {+ if (check()) return true;+ await sleep(50);+ }+ return check();+}++function provider(compress?: (prompt: string) => string): MemoryProvider {+ return {+ name: "test",+ compress: vi.fn(async (_system: string, prompt: string) => (compress ? compress(prompt) : "")),+ summarize: vi.fn(async () => ""),+ };+}++async function startDaemon(+ options: {+ port?: number;+ observeDelayMs?: number;+ hangObserve?: boolean;+ hangSessionEnd?: boolean;+ llm?: MemoryProvider;+ } = {},+): Promise<Daemon> {+ vi.resetModules();+ const { registerObserveFunction } = await import("../src/functions/observe.js");+ const { registerCaptureFunctions } = await import("../src/functions/capture.js");+ const { registerCompressFunction } = await import("../src/functions/compress.js");+ const { registerSummarizeFunction } = await import("../src/functions/summarize.js");+ const { registerSearchFunction } = await import("../src/functions/search.js");+ const { registerApiTriggers } = await import("../src/triggers/api.js");+ const { registerEventTriggers } = await import("../src/triggers/events.js");+ const kv = mockKV();+ const sdk = mockSdk({ looseTrigger: true });+ const invoke = sdk.trigger;+ sdk.trigger = (async (input: Parameters<typeof invoke>[0], data?: unknown) => {+ if (typeof input === "object" && input.action) {+ void invoke(input).catch(() => {});+ return undefined;+ }+ return invoke(input, data);+ }) as typeof invoke;+ const llm = options.llm ?? provider();+ registerObserveFunction(sdk as never, kv as never);+ registerCaptureFunctions(sdk as never, kv as never, { durableAfterMs: 0 });+ registerCompressFunction(sdk as never, kv as never, llm);+ registerSummarizeFunction(sdk as never, kv as never, llm);+ registerSearchFunction(sdk as never, kv as never);+ registerApiTriggers(sdk as never, kv as never);+ registerEventTriggers(sdk as never, kv as never);+ const call = (id: string, payload: unknown) => sdk.trigger(id, payload) as Promise<any>;+ const received: Received[] = [];+ const server: Server = createServer((req, res) => {+ let raw = "";+ req.on("data", (chunk) => (raw += chunk));+ req.on("end", async () => {+ const entry: Received = { path: req.url ?? "", body: JSON.parse(raw || "{}"), auth: req.headers.authorization, at: Date.now() };+ received.push(entry);+ if (entry.path === "/agentmemory/observe") {+ if (options.hangObserve) return;+ if (options.observeDelayMs) await sleep(options.observeDelayMs);+ }+ if (entry.path === "/agentmemory/session/end" && options.hangSessionEnd) return;+ const route = ROUTES[entry.path];+ const response = route ? await call(route, { body: entry.body, headers: {} }) : { status_code: 404, body: {} };+ entry.answeredAt = Date.now();+ res.writeHead(response.status_code, { "content-type": "application/json" });+ res.end(JSON.stringify(response.body ?? {}));+ });+ });+ await new Promise<void>((resolve) => server.listen(options.port ?? 0, "127.0.0.1", () => resolve()));+ const port = (server.address() as { port: number }).port;+ const daemon: Daemon = {+ port,+ kv,+ received,+ call,+ close: () => {+ server.closeAllConnections();+ return new Promise<void>((resolve) => server.close(() => resolve()));+ },+ };+ daemons.push(daemon);+ return daemon;+}++async function freePort(): Promise<number> {+ const probe = createServer();+ await new Promise<void>((resolve) => probe.listen(0, "127.0.0.1", () => resolve()));+ const port = (probe.address() as { port: number }).port;+ await new Promise<void>((resolve) => probe.close(() => resolve()));+ return port;+}++function runHook(+ port: number,+ payload: Record<string, unknown>,+ env: Record<string, string> = {},+): Promise<{ code: number | null; startedAt: number; ms: number }> {+ const startedAt = Date.now();+ hookPorts.add(port);+ return new Promise((resolve, reject) => {+ const child = spawn(process.execPath, [HOOK], {+ env: {+ PATH: process.env["PATH"] ?? "",+ HOME: home,+ AGENTMEMORY_URL: `http://127.0.0.1:${port}`,+ AGENTMEMORY_CAPTURE_SPOOL_DIR: join(home, "spool"),+ ...env,+ },+ stdio: ["pipe", "ignore", "ignore"],+ });+ child.on("error", reject);+ child.on("close", (code) => resolve({ code, startedAt, ms: Date.now() - startedAt }));+ child.stdin.end(JSON.stringify(payload));+ });+}++function stop(extra: Record<string, unknown> = {}): Record<string, unknown> {+ return {+ session_id: SESSION,+ prompt_id: "6f1c2a8e-5b7d-4c11-9a3e-2d4f6b8c0e12",+ transcript_path: "/tmp/does-not-matter.jsonl",+ cwd: "/work/project",+ hook_event_name: "Stop",+ stop_hook_active: false,+ ...extra,+ };+}++function observes(daemon: Daemon): Received[] {+ return daemon.received.filter((r) => r.path === "/agentmemory/observe");+}++function sessionEnds(daemon: Daemon): Received[] {+ return daemon.received.filter((r) => r.path === "/agentmemory/session/end");+}++function storedReplies(daemon: Daemon): CompressedObservation[] {+ const rows = [...(daemon.kv.store.get(KV.observations(SESSION))?.values() ?? [])] as CompressedObservation[];+ return rows.filter((o) => o.source?.hookType === "stop");+}++function spooled(port: number): Array<{ eventId: string; reason: string; body: Record<string, unknown> }> {+ const file = join(home, "spool", `local-${port}.jsonl`);+ if (!existsSync(file)) return [];+ return readFileSync(file, "utf-8").split("\n").filter(Boolean).map((line) => JSON.parse(line));+}++async function search(daemon: Daemon, query: string): Promise<string> {+ return JSON.stringify(await daemon.call("mem::search", { query }));+}++async function seedSession(daemon: Daemon): Promise<void> {+ await daemon.call("mem::observe", {+ hookType: "prompt_submit",+ sessionId: SESSION,+ project: "project",+ cwd: "/work/project",+ timestamp: new Date().toISOString(),+ data: { prompt: "Why does the parser test flake on Windows?" },+ });+}++describe("packaged Stop hook reply capture", () => {+ beforeEach(() => {+ home = mkdtempSync(join(tmpdir(), "am-stop-reply-"));+ hookPorts.clear();+ vi.stubEnv("AGENTMEMORY_AUTO_COMPRESS", "false");+ vi.stubEnv("AGENTMEMORY_AGENT_SCOPE", "shared");+ vi.stubEnv("AGENTMEMORY_FINALIZE_IDLE_MS", "120000");+ });++ afterEach(async () => {+ await Promise.all(daemons.splice(0).map((d) => d.close()));+ vi.unstubAllEnvs();+ const spool = join(home, "spool");+ const draining = () => [...hookPorts].some((p) => drainInProgress(`http://127.0.0.1:${p}`, spool));+ expect(await waitFor(() => !draining(), 5000)).toBe(true);+ rmSync(home, { recursive: true, force: true, maxRetries: 3, retryDelay: 100 });+ });++ it("stores a delayed reply before an immediate finalization summarizes the session", async () => {+ vi.stubEnv("AGENTMEMORY_FINALIZE_IDLE_MS", "0");+ const llm = provider();+ const daemon = await startDaemon({ observeDelayMs: 800, llm });+ await seedSession(daemon);+ const reply = "The parser flaked because the tokenizer kept carriage returns; we normalised line endings first.";++ const run = await runHook(daemon.port, stop({ last_assistant_message: reply }));++ expect(run.code).toBe(0);+ const [observe] = observes(daemon);+ const [end] = sessionEnds(daemon);+ expect(observe!.body).toMatchObject({ hookType: "stop", sessionId: SESSION, project: "project", cwd: "/work/project" });+ expect(end!.body).toEqual({ sessionId: SESSION, final: false });+ expect(end!.at).toBeGreaterThanOrEqual(observe!.answeredAt!);+ expect(await waitFor(() => vi.mocked(llm.summarize).mock.calls.length > 0, 5000)).toBe(true);+ expect(JSON.stringify(vi.mocked(llm.summarize).mock.calls)).toContain("we normalised line endings first");+ }, 15_000);++ it("still ends the turn when the capture outlives its bound, and keeps the reply for replay", async () => {+ vi.stubEnv("AGENTMEMORY_FINALIZE_IDLE_MS", "0");+ const daemon = await startDaemon({ hangObserve: true });+ await seedSession(daemon);++ const run = await runHook(daemon.port, stop({ last_assistant_message: "Hung capture reply: retry the flaky parser job." }));++ expect(run.code).toBe(0);+ expect(run.ms).toBeLessThan(EXIT_CAP_MS);+ const [end] = sessionEnds(daemon);+ expect(end!.body).toEqual({ sessionId: SESSION, final: false });+ expect(end!.at - run.startedAt).toBeGreaterThanOrEqual(OBSERVE_TIMEOUT_MS - 100);+ expect(((await daemon.kv.get(KV.sessions, SESSION)) as Session).status).toBe("completed");+ const [record] = spooled(daemon.port);+ expect(record!.reason).toBe("timeout");+ expect(record!.eventId).toBe(observes(daemon)[0]!.body["eventId"]);+ expect(JSON.stringify(record!.body)).toContain("retry the flaky parser job");+ }, 15_000);++ it("replays a reply spooled while the server was down, without its secrets", async () => {+ const port = await freePort();+ const key = "sk-ant-" + "b".repeat(32);+ const reply = `Rotated the staging key ${key} and kept <private>vault-path-canary</private> out of notes. Marker cobaltreply stays searchable.`;++ const offline = await runHook(port, stop({ last_assistant_message: reply }));++ expect(offline.code).toBe(0);+ expect(offline.ms).toBeLessThan(EXIT_CAP_MS);+ const [record] = spooled(port);+ expect(record!.body["hookType"]).toBe("stop");+ expect(JSON.stringify(record)).toContain("cobaltreply");+ expect(JSON.stringify(record)).not.toContain(key);+ expect(JSON.stringify(record)).not.toContain("vault-path-canary");++ const daemon = await startDaemon({ port });+ await runHook(port, stop({ stop_hook_active: true, last_assistant_message: "Back online: every parser test passes." }));++ expect(await waitFor(() => storedReplies(daemon).length === 2, 8000)).toBe(true);+ expect(await waitFor(() => spooled(port).length === 0, 3000)).toBe(true);+ expect(observes(daemon).filter((r) => r.body["eventId"] === record!.eventId)).toHaveLength(1);+ const replayed = storedReplies(daemon).find((o) => o.source?.assistantResponse?.includes("cobaltreply"))!;+ expect(JSON.stringify(replayed)).not.toContain(key);+ expect(JSON.stringify(replayed)).not.toContain("vault-path-canary");+ expect(await search(daemon, "cobaltreply")).toContain(replayed.id);+ }, 15_000);++ it("sends nothing from inside an SDK child session", async () => {+ const daemon = await startDaemon();++ await runHook(daemon.port, stop({ entrypoint: "sdk-ts", last_assistant_message: "Child reply." }));+ await runHook(daemon.port, stop({ last_assistant_message: "Child reply." }), { AGENTMEMORY_SDK_CHILD: "1" });++ expect(daemon.received).toHaveLength(0);+ });++ it("authenticates the capture and the turn end the same way", async () => {+ const daemon = await startDaemon();+ mkdirSync(join(home, ".agentmemory"), { recursive: true });+ writeFileSync(join(home, ".agentmemory", "secret"), "stored-secret-0123456789abcdef\n");+ const reply = { last_assistant_message: "Authenticated reply." };++ await runHook(daemon.port, stop(reply));+ await runHook(daemon.port, stop(reply), { AGENTMEMORY_CREDENTIAL_MODE: "explicit" });+ await runHook(daemon.port, stop(reply), { AGENTMEMORY_SECRET: "env-secret-0123456789abcdef" });++ expect(daemon.received.map((r) => [r.path, r.auth])).toEqual([+ ["/agentmemory/observe", "Bearer stored-secret-0123456789abcdef"],+ ["/agentmemory/session/end", "Bearer stored-secret-0123456789abcdef"],+ ["/agentmemory/observe", undefined],+ ["/agentmemory/session/end", undefined],+ ["/agentmemory/observe", "Bearer env-secret-0123456789abcdef"],+ ["/agentmemory/session/end", "Bearer env-secret-0123456789abcdef"],+ ]);+ });++ it("keeps blank replies out of memory but still ends the turn", async () => {+ const daemon = await startDaemon();++ for (const extra of [{}, { last_assistant_message: " \n" }, { last_assistant_message: 42 }]) {+ expect((await runHook(daemon.port, stop(extra))).code).toBe(0);+ }++ expect(observes(daemon)).toHaveLength(0);+ expect(sessionEnds(daemon).map((r) => r.body)).toEqual([+ { sessionId: SESSION, final: false },+ { sessionId: SESSION, final: false },+ { sessionId: SESSION, final: false },+ ]);+ });++ it("caps a long reply and keeps both its opening and its conclusion searchable", async () => {+ const daemon = await startDaemon();+ const reply = `Opening: the parser investigation is done. ${"Checked another fixture and its line endings. ".repeat(60)}Conclusion: switch the tokenizer to quasarlex streaming.`;++ await runHook(daemon.port, stop({ last_assistant_message: reply }));+ await runHook(daemon.port, stop({ stop_hook_active: true, last_assistant_message: "z".repeat(10_000) }));++ const capped = observes(daemon)[1]!.body["data"] as { last_assistant_message: string };+ expect(capped.last_assistant_message).toHaveLength(4000);+ const stored = storedReplies(daemon).find((o) => o.source?.assistantResponse === reply)!;+ expect(stored.narrative.length).toBeLessThanOrEqual(400);+ expect(stored.narrative).toContain("Opening: the parser investigation is done.");+ expect(stored.narrative).toContain("switch the tokenizer to quasarlex streaming.");+ expect(await search(daemon, "quasarlex")).toContain(stored.id);+ });++ it("stores every reply when a blocking Stop hook continues the same prompt", async () => {+ const daemon = await startDaemon();+ const reply = "Two parser tests still fail.";++ await runHook(daemon.port, stop({ last_assistant_message: reply }));+ await runHook(daemon.port, stop({ stop_hook_active: true, last_assistant_message: reply }));++ const ids = observes(daemon).map((r) => r.body["eventId"]);+ expect(new Set(ids).size).toBe(2);+ expect(storedReplies(daemon).map((o) => o.source?.assistantResponse)).toEqual([reply, reply]);+ expect(sessionEnds(daemon)).toHaveLength(2);+ });++ it("gives the turn end its own short bound, with or without a reply", async () => {+ const daemon = await startDaemon({ hangSessionEnd: true });++ const silent = await runHook(daemon.port, stop());+ const replied = await runHook(daemon.port, stop({ last_assistant_message: "Stored before the turn end hung." }));++ expect(silent.ms).toBeLessThan(EXIT_CAP_MS - 1000);+ expect(replied.ms).toBeLessThan(EXIT_CAP_MS - 1000);+ expect(storedReplies(daemon)).toHaveLength(1);+ }, 15_000);++ it("does not split a character at either edge of the reply cap", async () => {+ const daemon = await startDaemon();+ const atHead = `${"a".repeat(1999)}\u{1F600}${"b".repeat(2500)}`;+ const atTail = `${"a".repeat(3000)}\u{1F600}${"b".repeat(1998)}`;++ await runHook(daemon.port, stop({ last_assistant_message: atHead }));+ await runHook(daemon.port, stop({ stop_hook_active: true, last_assistant_message: atTail }));++ for (const sent of observes(daemon).map((r) => (r.body["data"] as { last_assistant_message: string }).last_assistant_message)) {+ expect(sent).not.toMatch(/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/);+ expect(sent.length).toBeLessThanOrEqual(4000);+ expect(sent.startsWith("a")).toBe(true);+ expect(sent.endsWith("b")).toBe(true);+ }+ });++ it("redacts a private block that the reply cap would cut open", async () => {+ const canary = "cobaltcanary";+ const tail = `${"b".repeat(3000)}Conclusion: ship the vermilionfix patch.`;+ const cases = {+ head: `${"a".repeat(1960)}<private>${canary}${"x".repeat(700)}</private>${tail}`,+ tail: `${"a".repeat(2500)}<private>${"x".repeat(100)}${canary}</private>${"b".repeat(1900)}`,+ };+ const port = await freePort();+ const daemon = await startDaemon();++ for (const reply of Object.values(cases)) {+ await runHook(port, stop({ last_assistant_message: reply }));+ await runHook(daemon.port, stop({ stop_hook_active: true, last_assistant_message: reply }));+ }++ expect(JSON.stringify(spooled(port))).not.toContain(canary);+ expect(observes(daemon)).toHaveLength(2);+ for (const observed of observes(daemon)) {+ const sent = (observed.body["data"] as { last_assistant_message: string }).last_assistant_message;+ expect(sent).not.toContain(canary);+ expect(sent).toContain("[REDACTED]");+ }+ for (const stored of storedReplies(daemon)) {+ expect(JSON.stringify(stored)).not.toContain(canary);+ expect(stored.source?.assistantResponse).toContain("[REDACTED]");+ }+ }, 15_000);++ it("keeps the conclusion of a reply longer than the cap recallable", async () => {+ const daemon = await startDaemon();+ const reply = `Opening: the parser investigation is done. ${"Checked another fixture and its line endings. ".repeat(142)}Conclusion: switch the tokenizer to quasarlex streaming.`;+ expect(reply.length).toBeGreaterThan(6500);++ await runHook(daemon.port, stop({ last_assistant_message: reply }));++ const wire = observes(daemon)[0]!.body["data"] as { last_assistant_message: string; last_assistant_message_bytes?: number };+ expect(wire.last_assistant_message).toHaveLength(4000);+ expect(wire.last_assistant_message_bytes).toBe(reply.length);+ const [stored] = storedReplies(daemon);+ expect(stored!.source?.truncated).toBe(true);+ expect(stored!.source?.originalBytes).toBeGreaterThanOrEqual(reply.length);+ expect(stored!.source?.assistantResponse).toContain("Conclusion: switch the tokenizer to quasarlex streaming.");+ expect(stored!.narrative).toContain("Opening: the parser investigation is done.");+ expect(stored!.narrative).toContain("quasarlex streaming.");+ expect(await search(daemon, "quasarlex")).toContain(stored!.id);+ }, 15_000);++ it("reports a reply that fits the cap as untruncated", async () => {+ const daemon = await startDaemon();++ await runHook(daemon.port, stop({ last_assistant_message: "Short reply, nothing dropped." }));++ const wire = observes(daemon)[0]!.body["data"] as Record<string, unknown>;+ expect(wire["last_assistant_message_bytes"]).toBeUndefined();+ expect(storedReplies(daemon)[0]!.source?.truncated).toBe(false);+ });++ it("makes the reply recallable through synthetic compression", async () => {+ const daemon = await startDaemon();+ const reply = "We decided to use bge-m3 for Spanish embeddings because it handles accents.";++ await runHook(daemon.port, stop({ last_assistant_message: reply }));++ const [stored] = storedReplies(daemon);+ expect(stored!.narrative).toBe(reply);+ expect(stored!.source?.assistantResponse).toBe(reply);+ expect(await search(daemon, "Spanish embeddings accents")).toContain(stored!.id);+ });++ it("makes the reply recallable through LLM compression", async () => {+ vi.stubEnv("AGENTMEMORY_AUTO_COMPRESS", "true");+ const escape = (s: string) => s.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">");+ const llm = provider((prompt) => {+ const reply = escape(prompt.split("Assistant response:\n")[1] ?? "");+ return `<observation><type>decision</type><title>Chose the embedding model</title><facts><fact>${reply}</fact></facts><narrative>${reply}</narrative><concepts><concept>embeddings</concept></concepts><files></files><importance>7</importance></observation>`;+ });+ const daemon = await startDaemon({ llm });+ const reply = "We decided to use bge-m3 for Spanish embeddings because it handles accents.";++ await runHook(daemon.port, stop({ last_assistant_message: reply }));++ expect(await waitFor(() => storedReplies(daemon)[0]?.title === "Chose the embedding model", 3000)).toBe(true);+ expect(vi.mocked(llm.compress).mock.calls[0]![1]).toContain(`Assistant response:\n${reply}`);+ const [stored] = storedReplies(daemon);+ expect(stored!.narrative).toBe(reply);+ expect(stored!.source?.assistantResponse).toBe(reply);+ expect(await search(daemon, "Spanish embeddings accents")).toContain(stored!.id);+ });+});