Skip to content

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

fix: stop burning Claude tokens on every PostToolUse hook (#138) (#140)

Rohit Ghumare281e10ca8cb4
diff --git a/CHANGELOG.md b/CHANGELOG.md
index ac6bda3c..e1799b9a 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -4,6 +4,32 @@ All notable changes to agentmemory will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
+## [0.8.8] — 2026-04-14
+
+**Behavior change**: per-observation LLM compression is now opt-in. If you were relying on LLM-generated summaries (the old default), set `AGENTMEMORY_AUTO_COMPRESS=true` in `~/.agentmemory/.env` and restart.
+
+### Fixed
+
+- **Stop silently burning Claude API tokens on every tool invocation** ([#138](https://github.com/rohitg00/agentmemory/issues/138), thanks [@olcor1](https://github.com/olcor1)) — the old `mem::observe` path fired `mem::compress` unconditionally on every PostToolUse hook, which called Claude via the user's `ANTHROPIC_API_KEY` to turn each raw observation into a structured summary. An active coding session (50-200 tool calls/hour) could run through hundreds of thousands of tokens in minutes, which is the exact opposite of what a memory tool should do. The new default path skips the LLM call and uses a zero-token **synthetic compression** step that derives `type`, `title`, `narrative`, and `files` from the raw tool name, tool input, and tool output directly. Recall and BM25 search still work — you just lose the LLM-generated summaries unless you opt in.
+
+### Added
+
+- **`AGENTMEMORY_AUTO_COMPRESS` env var** — default `false`. When `true`, restores the old per-observation LLM compression path. The engine startup banner now prints a loud warning when it's on, reminding you that it spends tokens proportional to your session tool-use frequency.
+- **`src/functions/compress-synthetic.ts`** — the new zero-LLM compression helper. `buildSyntheticCompression(raw)` maps tool names to `ObservationType` (via camelCase-aware substring matching for `Read`/`Write`/`Edit`/`Bash`/`Grep`/`WebFetch`/`Task`/etc.), pulls file paths out of `tool_input.file_path` / `pattern` / etc., and truncates narratives to 400 chars so one huge tool output can't blow up the BM25 index.
+- **Regression test** `test/auto-compress.test.ts` — 8 cases covering the default path (no `mem::compress` trigger, synthetic observation stored in KV), explicit opt-in, tool-name-to-type mapping, file-path extraction, narrative truncation, and the `post_tool_failure` → `error` path. Full suite: 707 passing.
+
+### Infrastructure
+
+- **Startup banner** (`src/index.ts:171`) now prints either `Auto-compress: OFF (default, #138)` or a prominent warning when opt-in is enabled, so the mode is never silent.
+- **Migration note**: if you were running 0.8.7 or earlier with `ANTHROPIC_API_KEY` set, your token usage will drop sharply on upgrade. Search quality may also drop slightly because narratives are now derived from raw tool I/O instead of Claude-generated summaries. If you want the old behavior:
+ ```env
+ # ~/.agentmemory/.env
+ AGENTMEMORY_AUTO_COMPRESS=true
+ ```
+ and restart. Existing compressed observations in `~/.agentmemory/` are untouched.
+
+[0.8.8]: https://github.com/rohitg00/agentmemory/compare/v0.8.7...v0.8.8
+
## [0.8.7] — 2026-04-14
One-line fix for a brown-paper-bag bug reported in [#136](https://github.com/rohitg00/agentmemory/issues/136).
diff --git a/README.md b/README.md
index 1f2beff3..05797da0 100644
--- a/README.md
+++ b/README.md
@@ -718,6 +718,11 @@ Create `~/.agentmemory/.env`:
# III_REST_PORT=3111
# Features
+# AGENTMEMORY_AUTO_COMPRESS=false # OFF by default (#138). When on,
+ # every PostToolUse hook calls your
+ # LLM provider to compress the
+ # observation — expect significant
+ # token spend on active sessions.
# GRAPH_EXTRACTION_ENABLED=false
# CONSOLIDATION_ENABLED=true
# LESSON_DECAY_ENABLED=true
diff --git a/package-lock.json b/package-lock.json
index 3fd68b26..3c15c03c 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "@agentmemory/agentmemory",
- "version": "0.8.7",
+ "version": "0.8.8",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "@agentmemory/agentmemory",
- "version": "0.8.7",
+ "version": "0.8.8",
"license": "Apache-2.0",
"dependencies": {
"@anthropic-ai/claude-agent-sdk": "^0.2.56",
diff --git a/package.json b/package.json
index f5b14d33..551a0596 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
{
"name": "@agentmemory/agentmemory",
- "version": "0.8.7",
+ "version": "0.8.8",
"description": "Persistent memory for AI coding agents, powered by iii-engine's three primitives",
"type": "module",
"main": "dist/index.mjs",
diff --git a/packages/mcp/package.json b/packages/mcp/package.json
index f5a6f901..fd6b6159 100644
--- a/packages/mcp/package.json
+++ b/packages/mcp/package.json
@@ -1,6 +1,6 @@
{
"name": "@agentmemory/mcp",
- "version": "0.8.7",
+ "version": "0.8.8",
"description": "Standalone MCP server for agentmemory — thin shim that re-exposes @agentmemory/agentmemory's MCP entrypoint",
"type": "module",
"bin": {
@@ -28,7 +28,7 @@
"homepage": "https://github.com/rohitg00/agentmemory#readme",
"bugs": "https://github.com/rohitg00/agentmemory/issues",
"dependencies": {
- "@agentmemory/agentmemory": "~0.8.7"
+ "@agentmemory/agentmemory": "~0.8.8"
},
"publishConfig": {
"access": "public",
diff --git a/plugin/.claude-plugin/plugin.json b/plugin/.claude-plugin/plugin.json
index 3adc85fd..7a5e4241 100644
--- a/plugin/.claude-plugin/plugin.json
+++ b/plugin/.claude-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "agentmemory",
- "version": "0.8.7",
+ "version": "0.8.8",
"description": "Persistent memory for AI coding agents -- captures tool usage, compresses via LLM, injects context into future sessions. 12 hooks, 43 MCP tools, 4 skills, real-time viewer.",
"author": {
"name": "Rohit Ghumare",
diff --git a/src/config.ts b/src/config.ts
index 936c43c3..1d039951 100644
--- a/src/config.ts
+++ b/src/config.ts
@@ -194,6 +194,16 @@ export function isConsolidationEnabled(): boolean {
return getMergedEnv()["CONSOLIDATION_ENABLED"] === "true";
}
+// Per-observation LLM compression is OFF by default as of 0.8.8 (see #138).
+// When disabled, observations are captured and indexed via a synthetic
+// (zero-LLM) compression path so recall/search still works. Users who want
+// richer LLM-generated summaries can set AGENTMEMORY_AUTO_COMPRESS=true in
+// ~/.agentmemory/.env — but should expect their Claude API token usage to
+// climb proportionally with session tool-use frequency.
+export function isAutoCompressEnabled(): boolean {
+ return getMergedEnv()["AGENTMEMORY_AUTO_COMPRESS"] === "true";
+}
+
export function getConsolidationDecayDays(): number {
return safeParseInt(getMergedEnv()["CONSOLIDATION_DECAY_DAYS"], 30);
}
diff --git a/src/functions/compress-synthetic.ts b/src/functions/compress-synthetic.ts
new file mode 100644
index 00000000..f931ba00
--- /dev/null
+++ b/src/functions/compress-synthetic.ts
@@ -0,0 +1,102 @@
+import type {
+ RawObservation,
+ CompressedObservation,
+ ObservationType,
+} from "../types.js";
+
+// Zero-LLM compression path. Converts a RawObservation into a
+// CompressedObservation using only heuristics — no Claude call, no token
+// spend. This is the default as of 0.8.8 (#138); users who want richer
+// LLM-generated summaries set AGENTMEMORY_AUTO_COMPRESS=true.
+
+function inferType(
+ toolName: string | undefined,
+ hookType: string,
+): ObservationType {
+ if (hookType === "post_tool_failure") return "error";
+ if (hookType === "prompt_submit") return "conversation";
+ if (hookType === "subagent_stop" || hookType === "task_completed")
+ return "subagent";
+ if (hookType === "notification") return "notification";
+
+ if (!toolName) return "other";
+ // Normalize camelCase and kebab-case into word chunks so we can match
+ // substrings like "WebFetch" -> "web" / "fetch".
+ const n = toolName
+ .replace(/([a-z])([A-Z])/g, "$1_$2")
+ .replace(/[-\s]+/g, "_")
+ .toLowerCase();
+ const hasWord = (word: string) =>
+ new RegExp(`(^|_)${word}(_|$)`).test(n) ||
+ n === word ||
+ n.endsWith(word) ||
+ n.startsWith(word);
+ if (["fetch", "http", "web"].some(hasWord)) return "web_fetch";
+ if (["grep", "search", "glob", "find"].some(hasWord)) return "search";
+ if (["bash", "shell", "exec", "run"].some(hasWord)) return "command_run";
+ if (["edit", "update", "patch", "replace"].some(hasWord)) return "file_edit";
+ if (["write", "create"].some(hasWord)) return "file_write";
+ if (["read", "view"].some(hasWord)) return "file_read";
+ if (["task", "agent"].some(hasWord)) return "subagent";
+ return "other";
+}
+
+function extractFiles(input: unknown): string[] {
+ if (!input || typeof input !== "object") return [];
+ const o = input as Record<string, unknown>;
+ const out = new Set<string>();
+ for (const key of [
+ "file_path",
+ "filepath",
+ "path",
+ "filePath",
+ "file",
+ "pattern",
+ ]) {
+ const v = o[key];
+ if (typeof v === "string" && v.length > 0 && v.length < 512) out.add(v);
+ }
+ return [...out];
+}
+
+function stringifyForNarrative(v: unknown): string {
+ if (v == null) return "";
+ if (typeof v === "string") return v;
+ try {
+ return JSON.stringify(v);
+ } catch {
+ return String(v);
+ }
+}
+
+function truncate(s: string, n: number): string {
+ return s.length > n ? s.slice(0, n - 1) + "\u2026" : s;
+}
+
+export function buildSyntheticCompression(
+ raw: RawObservation,
+): CompressedObservation {
+ const toolName = raw.toolName ?? raw.hookType;
+ const inputStr = stringifyForNarrative(raw.toolInput);
+ const outputStr = stringifyForNarrative(raw.toolOutput);
+ const promptStr = raw.userPrompt ?? "";
+
+ const narrativeParts = [promptStr, inputStr, outputStr].filter(
+ (s) => s.length > 0,
+ );
+
+ return {
+ id: raw.id,
+ sessionId: raw.sessionId,
+ timestamp: raw.timestamp,
+ type: inferType(toolName, raw.hookType),
+ title: truncate(toolName || "observation", 80),
+ subtitle: inputStr ? truncate(inputStr, 120) : undefined,
+ facts: [],
+ narrative: truncate(narrativeParts.join(" | "), 400),
+ concepts: [],
+ files: extractFiles(raw.toolInput),
+ importance: 5,
+ confidence: 0.3,
+ };
+}
diff --git a/src/functions/export-import.ts b/src/functions/export-import.ts
index b90dbb91..76b597e8 100644
--- a/src/functions/export-import.ts
+++ b/src/functions/export-import.ts
@@ -175,7 +175,7 @@ export function registerExportImportFunction(sdk: ISdk, kv: StateKV): void {
const strategy = data.strategy || "merge";
const importData = data.exportData;
- const supportedVersions = new Set(["0.3.0", "0.4.0", "0.5.0", "0.6.0", "0.6.1", "0.7.0", "0.7.2", "0.7.3", "0.7.4", "0.7.5", "0.7.6", "0.7.7", "0.7.9", "0.8.0", "0.8.1", "0.8.2", "0.8.3", "0.8.4", "0.8.5", "0.8.6", "0.8.7"]);
+ const supportedVersions = new Set(["0.3.0", "0.4.0", "0.5.0", "0.6.0", "0.6.1", "0.7.0", "0.7.2", "0.7.3", "0.7.4", "0.7.5", "0.7.6", "0.7.7", "0.7.9", "0.8.0", "0.8.1", "0.8.2", "0.8.3", "0.8.4", "0.8.5", "0.8.6", "0.8.7", "0.8.8"]);
if (!supportedVersions.has(importData.version)) {
return {
success: false,
diff --git a/src/functions/observe.ts b/src/functions/observe.ts
index 2e280752..74f74362 100644
--- a/src/functions/observe.ts
+++ b/src/functions/observe.ts
@@ -6,6 +6,9 @@ import { StateKV } from "../state/kv.js";
import { stripPrivateData } from "./privacy.js";
import { DedupMap } from "./dedup.js";
import { withKeyedLock } from "../state/keyed-mutex.js";
+import { isAutoCompressEnabled } from "../config.js";
+import { buildSyntheticCompression } from "./compress-synthetic.js";
+import { getSearchIndex } from "./search.js";
export function registerObserveFunction(
sdk: ISdk,
@@ -126,16 +129,47 @@ export function registerObserveFunction(
});
}
- sdk.triggerVoid("mem::compress", {
- observationId: obsId,
- sessionId: payload.sessionId,
- raw,
- });
+ // Per-observation LLM compression is opt-in as of 0.8.8 (#138).
+ // Default path: build a zero-LLM synthetic compression so recall
+ // and BM25 search still work without burning the user's Claude
+ // token allocation on every tool invocation.
+ if (isAutoCompressEnabled()) {
+ sdk.triggerVoid("mem::compress", {
+ observationId: obsId,
+ sessionId: payload.sessionId,
+ raw,
+ });
+ } else {
+ const synthetic = buildSyntheticCompression(raw);
+ await kv.set(
+ KV.observations(payload.sessionId),
+ obsId,
+ synthetic,
+ );
+ getSearchIndex().add(synthetic);
+ sdk.triggerVoid("stream::set", {
+ stream_name: STREAM.name,
+ group_id: STREAM.group(payload.sessionId),
+ item_id: obsId,
+ data: { type: "compressed", observation: synthetic },
+ });
+ sdk.triggerVoid("stream::set", {
+ stream_name: STREAM.name,
+ group_id: STREAM.viewerGroup,
+ item_id: obsId,
+ data: {
+ type: "compressed",
+ observation: synthetic,
+ sessionId: payload.sessionId,
+ },
+ });
+ }
ctx.logger.info("Observation captured", {
obsId,
sessionId: payload.sessionId,
hook: payload.hookType,
+ compress: isAutoCompressEnabled() ? "llm" : "synthetic",
});
return { observationId: obsId };
});
diff --git a/src/index.ts b/src/index.ts
index 288f9400..d56fac40 100644
--- a/src/index.ts
+++ b/src/index.ts
@@ -8,6 +8,7 @@ import {
loadTeamConfig,
loadSnapshotConfig,
isGraphExtractionEnabled,
+ isAutoCompressEnabled,
isConsolidationEnabled,
} from "./config.js";
import {
@@ -170,6 +171,16 @@ async function main() {
registerConsolidationPipelineFunction(sdk, kv, provider);
console.log(`[agentmemory] Consolidation pipeline: registered (CONSOLIDATION_ENABLED=${isConsolidationEnabled() ? "true" : "false"})`);
+ if (isAutoCompressEnabled()) {
+ console.log(
+ `[agentmemory] WARNING: AGENTMEMORY_AUTO_COMPRESS=true — every PostToolUse observation will be sent to your LLM provider for compression. This spends API tokens proportional to your session tool-use frequency (see #138). Set AGENTMEMORY_AUTO_COMPRESS=false to disable.`,
+ );
+ } else {
+ console.log(
+ `[agentmemory] Auto-compress: OFF (default, #138) — observations indexed via zero-LLM synthetic compression. Set AGENTMEMORY_AUTO_COMPRESS=true to opt-in to LLM-powered summaries (uses your API key).`,
+ );
+ }
+
const teamConfig = loadTeamConfig();
if (teamConfig) {
registerTeamFunction(sdk, kv, teamConfig);
diff --git a/src/types.ts b/src/types.ts
index 4143dc9b..d568ad0f 100644
--- a/src/types.ts
+++ b/src/types.ts
@@ -252,7 +252,7 @@ export interface ExportPagination {
}
export interface ExportData {
- version: "0.3.0" | "0.4.0" | "0.5.0" | "0.6.0" | "0.6.1" | "0.7.0" | "0.7.2" | "0.7.3" | "0.7.4" | "0.7.5" | "0.7.6" | "0.7.9" | "0.8.0" | "0.8.1" | "0.8.2" | "0.8.3" | "0.8.4" | "0.8.5" | "0.8.6" | "0.8.7";
+ version: "0.3.0" | "0.4.0" | "0.5.0" | "0.6.0" | "0.6.1" | "0.7.0" | "0.7.2" | "0.7.3" | "0.7.4" | "0.7.5" | "0.7.6" | "0.7.9" | "0.8.0" | "0.8.1" | "0.8.2" | "0.8.3" | "0.8.4" | "0.8.5" | "0.8.6" | "0.8.7" | "0.8.8";
exportedAt: string;
sessions: Session[];
observations: Record<string, CompressedObservation[]>;
diff --git a/src/version.ts b/src/version.ts
index e7cfada8..5700e195 100644
--- a/src/version.ts
+++ b/src/version.ts
@@ -1 +1 @@
-export const VERSION: "0.3.0" | "0.4.0" | "0.5.0" | "0.6.0" | "0.6.1" | "0.7.0" | "0.7.2" | "0.7.3" | "0.7.4" | "0.7.5" | "0.7.6" | "0.8.1" | "0.8.2" | "0.8.3" | "0.8.4" | "0.8.5" | "0.8.6" | "0.8.7" = "0.8.7";
+export const VERSION: "0.3.0" | "0.4.0" | "0.5.0" | "0.6.0" | "0.6.1" | "0.7.0" | "0.7.2" | "0.7.3" | "0.7.4" | "0.7.5" | "0.7.6" | "0.8.1" | "0.8.2" | "0.8.3" | "0.8.4" | "0.8.5" | "0.8.6" | "0.8.7" | "0.8.8" = "0.8.8";
diff --git a/test/auto-compress.test.ts b/test/auto-compress.test.ts
new file mode 100644
index 00000000..52b02790
--- /dev/null
+++ b/test/auto-compress.test.ts
@@ -0,0 +1,236 @@
+import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
+import type { RawObservation } from "../src/types.js";
+
+vi.mock("iii-sdk", () => ({
+ getContext: () => ({
+ logger: { info: () => {}, warn: () => {}, error: () => {} },
+ }),
+}));
+
+function mockKV() {
+ const store = new Map<string, Map<string, unknown>>();
+ return {
+ store,
+ get: async <T>(scope: string, key: string): Promise<T | null> =>
+ (store.get(scope)?.get(key) as T) ?? null,
+ set: async <T>(scope: string, key: string, data: T): Promise<T> => {
+ if (!store.has(scope)) store.set(scope, new Map());
+ store.get(scope)!.set(key, data);
+ return data;
+ },
+ delete: async (scope: string, key: string) => {
+ store.get(scope)?.delete(key);
+ },
+ list: async <T>(scope: string): Promise<T[]> => {
+ const m = store.get(scope);
+ return m ? (Array.from(m.values()) as T[]) : [];
+ },
+ };
+}
+
+function mockSdk() {
+ const fns = new Map<string, Function>();
+ const triggered: Array<{ id: string; data: unknown }> = [];
+ return {
+ fns,
+ triggered,
+ registerFunction: (opts: { id: string }, fn: Function) => {
+ fns.set(opts.id, fn);
+ },
+ trigger: async (id: string, data: unknown) => {
+ const fn = fns.get(id);
+ if (fn) return fn(data);
+ return null;
+ },
+ triggerVoid: (id: string, data: unknown) => {
+ triggered.push({ id, data });
+ },
+ };
+}
+
+function validPayload(overrides: Partial<Record<string, unknown>> = {}) {
+ return {
+ sessionId: "ses_test",
+ hookType: "post_tool_use",
+ timestamp: new Date().toISOString(),
+ data: {
+ tool_name: "Read",
+ tool_input: { file_path: "src/foo.ts" },
+ tool_output: "file contents here",
+ },
+ ...overrides,
+ };
+}
+
+describe("mem::observe auto-compress gate (#138)", () => {
+ beforeEach(() => {
+ // Reset module cache so observe.js re-imports config.js with the
+ // fresh AGENTMEMORY_AUTO_COMPRESS env state. Without this, a later
+ // test that sets the env var can be undermined by cached module
+ // state from an earlier test (and vice versa).
+ vi.resetModules();
+ delete process.env["AGENTMEMORY_AUTO_COMPRESS"];
+ });
+ afterEach(() => {
+ delete process.env["AGENTMEMORY_AUTO_COMPRESS"];
+ });
+
+ it("default (AGENTMEMORY_AUTO_COMPRESS unset): does NOT fire mem::compress", async () => {
+ const { registerObserveFunction } = await import(
+ "../src/functions/observe.js"
+ );
+ const sdk = mockSdk();
+ const kv = mockKV();
+ registerObserveFunction(sdk as never, kv as never);
+
+ const result = (await sdk.trigger(
+ "mem::observe",
+ validPayload(),
+ )) as { observationId: string };
+
+ expect(result.observationId).toBeTruthy();
+ const compressCalls = sdk.triggered.filter((t) => t.id === "mem::compress");
+ expect(compressCalls).toHaveLength(0);
+ });
+
+ it("default: stores a synthetic CompressedObservation with the raw-derived fields", async () => {
+ const { registerObserveFunction } = await import(
+ "../src/functions/observe.js"
+ );
+ const sdk = mockSdk();
+ const kv = mockKV();
+ registerObserveFunction(sdk as never, kv as never);
+
+ const payload = validPayload();
+ await sdk.trigger("mem::observe", payload);
+
+ const scope = `mem:obs:${payload.sessionId}`;
+ const stored = kv.store.get(scope);
+ expect(stored).toBeDefined();
+ expect(stored!.size).toBe(1);
+ const [entry] = Array.from(stored!.values());
+ const obs = entry as {
+ type: string;
+ title: string;
+ files: string[];
+ confidence: number;
+ };
+ expect(obs.type).toBe("file_read");
+ expect(obs.title).toBe("Read");
+ expect(obs.files).toContain("src/foo.ts");
+ expect(obs.confidence).toBe(0.3);
+ });
+
+ it("AGENTMEMORY_AUTO_COMPRESS=true: fires mem::compress exactly once", async () => {
+ process.env["AGENTMEMORY_AUTO_COMPRESS"] = "true";
+ const { registerObserveFunction } = await import(
+ "../src/functions/observe.js"
+ );
+ const sdk = mockSdk();
+ const kv = mockKV();
+ registerObserveFunction(sdk as never, kv as never);
+
+ await sdk.trigger("mem::observe", validPayload());
+
+ const compressCalls = sdk.triggered.filter((t) => t.id === "mem::compress");
+ expect(compressCalls).toHaveLength(1);
+ });
+
+ it("AGENTMEMORY_AUTO_COMPRESS=false explicitly: does NOT fire mem::compress", async () => {
+ process.env["AGENTMEMORY_AUTO_COMPRESS"] = "false";
+ const { registerObserveFunction } = await import(
+ "../src/functions/observe.js"
+ );
+ const sdk = mockSdk();
+ const kv = mockKV();
+ registerObserveFunction(sdk as never, kv as never);
+
+ await sdk.trigger("mem::observe", validPayload());
+
+ const compressCalls = sdk.triggered.filter((t) => t.id === "mem::compress");
+ expect(compressCalls).toHaveLength(0);
+ });
+});
+
+describe("buildSyntheticCompression", () => {
+ it("maps common tool names to the right ObservationType", async () => {
+ const { buildSyntheticCompression } = await import(
+ "../src/functions/compress-synthetic.js"
+ );
+ const base: RawObservation = {
+ id: "obs_1",
+ sessionId: "ses_1",
+ timestamp: new Date().toISOString(),
+ hookType: "post_tool_use",
+ raw: {},
+ };
+ const cases: Array<[string, string]> = [
+ ["Read", "file_read"],
+ ["Write", "file_write"],
+ ["Edit", "file_edit"],
+ ["Bash", "command_run"],
+ ["Grep", "search"],
+ ["WebFetch", "web_fetch"],
+ ["Task", "subagent"],
+ ["UnknownTool", "other"],
+ ];
+ for (const [name, expectedType] of cases) {
+ const synthetic = (
+ await import("../src/functions/compress-synthetic.js")
+ ).buildSyntheticCompression({ ...base, toolName: name });
+ expect(synthetic.type, `${name} -> ${expectedType}`).toBe(expectedType);
+ }
+ // silence unused warning — buildSyntheticCompression is used above
+ expect(typeof buildSyntheticCompression).toBe("function");
+ });
+
+ it("extracts file paths from tool_input into the files array", async () => {
+ const { buildSyntheticCompression } = await import(
+ "../src/functions/compress-synthetic.js"
+ );
+ const synth = buildSyntheticCompression({
+ id: "obs_2",
+ sessionId: "ses_1",
+ timestamp: new Date().toISOString(),
+ hookType: "post_tool_use",
+ toolName: "Edit",
+ toolInput: { file_path: "/app/src/bar.ts", pattern: "foo" },
+ raw: {},
+ });
+ expect(synth.files).toContain("/app/src/bar.ts");
+ expect(synth.files).toContain("foo");
+ expect(synth.type).toBe("file_edit");
+ });
+
+ it("truncates long narratives so it can't blow up the index", async () => {
+ const { buildSyntheticCompression } = await import(
+ "../src/functions/compress-synthetic.js"
+ );
+ const longInput = "x".repeat(2000);
+ const synth = buildSyntheticCompression({
+ id: "obs_3",
+ sessionId: "ses_1",
+ timestamp: new Date().toISOString(),
+ hookType: "post_tool_use",
+ toolName: "Bash",
+ toolInput: { command: longInput },
+ toolOutput: longInput,
+ raw: {},
+ });
+ expect(synth.narrative.length).toBeLessThanOrEqual(400);
+ });
+
+ it("maps post_tool_failure to the error type even with no tool name", async () => {
+ const { buildSyntheticCompression } = await import(
+ "../src/functions/compress-synthetic.js"
+ );
+ const synth = buildSyntheticCompression({
+ id: "obs_4",
+ sessionId: "ses_1",
+ timestamp: new Date().toISOString(),
+ hookType: "post_tool_failure",
+ raw: {},
+ });
+ expect(synth.type).toBe("error");
+ });
+});
diff --git a/test/export-import.test.ts b/test/export-import.test.ts
index a3953947..7c523973 100644
--- a/test/export-import.test.ts
+++ b/test/export-import.test.ts
@@ -118,7 +118,7 @@ describe("Export/Import Functions", () => {
it("export produces valid ExportData structure", async () => {
const result = (await sdk.trigger("mem::export", {})) as ExportData;
- expect(result.version).toBe("0.8.7");
+ expect(result.version).toBe("0.8.8");
expect(result.exportedAt).toBeDefined();
expect(result.sessions.length).toBe(1);
expect(result.sessions[0].id).toBe("ses_1");