#1 Persistent memory for AI coding agents based on real-world benchmarks
TypeScript agentmemoryagentsaiclaudeclaudecodecodexcopilotcursorgenaiharnesshermesmemoryompopenclawopencodepi
fix: SessionStart context gate (#143) + retention-evict semantic leak (#124) (#145)
Rohit Ghumare3bad5430ed6f
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 62161967..586c3787 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -4,6 +4,40 @@ 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.10] — 2026-04-15++**Behavior change**: the PreToolUse and SessionStart hooks no longer run enrichment by default. SessionStart saves ~1-2K input tokens per session you start (the only path that was actually reaching the model, per the [Claude Code hook docs](https://code.claude.com/docs/en/hooks.md)). PreToolUse stops spawning a Node process and POSTing to `/agentmemory/enrich` on every file-touching tool call — a pure resource cleanup, not a token fix. If you were relying on either path, set `AGENTMEMORY_INJECT_CONTEXT=true` in `~/.agentmemory/.env` and restart. Observations are still captured via PostToolUse regardless.++### Fixed++- **Gate SessionStart context injection** ([#143](https://github.com/rohitg00/agentmemory/issues/143), thanks [@adrianricardo](https://github.com/adrianricardo)) — `src/hooks/session-start.ts` previously wrote ~1-2K chars of project context to stdout at every session start. Per the [Claude Code hook docs](https://code.claude.com/docs/en/hooks.md), `SessionStart` stdout is explicitly injected into the model's context ("where stdout is added as context that Claude can see and act on"), so this was adding real tokens to the first turn of every new session. Now gated behind `AGENTMEMORY_INJECT_CONTEXT`, default off. The session still gets registered for observation tracking — only the stdout echo is skipped.+- **Skip the PreToolUse enrichment round-trip when disabled** ([#143](https://github.com/rohitg00/agentmemory/issues/143)) — `src/hooks/pre-tool-use.ts` was POSTing `/agentmemory/enrich` on every `Edit`/`Write`/`Read`/`Glob`/`Grep` tool call and piping up to 4000 chars to stdout. The Claude Code docs make clear that PreToolUse stdout goes to the debug log, not the model context, so this was **not** burning user tokens — but it was spawning a Node process + full HTTP round-trip ~20x per user message with no effect on the conversation. Gating it makes the disabled hot path a ~15ms no-op Node startup instead of a ~100-300ms REST round-trip. **This is a resource cleanup, not a token fix**; leaving the gate in place protects forward in case Claude Code ever changes PreToolUse to inject stdout like SessionStart does.+- **`mem::retention-evict` no longer leaks semantic memories** ([#124](https://github.com/rohitg00/agentmemory/issues/124)) — the eviction loop was unconditionally calling `kv.delete(KV.memories, id)` for every below-threshold candidate, but retention scores are computed for both episodic (`KV.memories`) and semantic (`KV.semantic`) memories. When a candidate came from `KV.semantic`, the delete silently became a no-op (key wasn't in `mem:memories` to begin with) and the semantic row stayed alive forever with a sub-threshold score. Semantic memories could not be evicted by this path at all. Fix: add a `source: "episodic" | "semantic"` discriminator to `RetentionScore`, tag it at score creation, and branch the delete on `candidate.source`. For pre-0.8.10 rows with no `source` field (including semantic retention rows written by the old scorer), the loop probes both namespaces to find where the `memoryId` actually lives, so upgraded stores get their stranded semantic memories evicted without needing to re-score first. The response shape now also includes `evictedEpisodic` and `evictedSemantic` counts for observability.+- **`mem::retention-evict` now emits an audit record per sweep** ([#124](https://github.com/rohitg00/agentmemory/issues/124)) — retention eviction performs structural deletes (memories, retention scores, access logs) but was not calling `recordAudit()`, which made evictions invisible to audit consumers. Now batched one audit row per non-zero sweep, with `operation: "delete"`, `functionId: "mem::retention-evict"`, `targetIds` containing every evicted id, and `details.evicted` / `evictedEpisodic` / `evictedSemantic` / `threshold` for context. Zero-eviction sweeps intentionally do not write an audit row.++### Honest note on #143++My initial diagnosis on the #143 thread pattern-matched too quickly to #138 and overclaimed that PreToolUse stdout was the smoking gun behind "Claude Pro burned in 4 messages". It wasn't — per the docs, PreToolUse stdout is debug-log only. The actual background cause is that [Claude Pro's Claude Code quotas are documented as tight](https://www.theregister.com/2026/03/31/anthropic_claude_code_limits/) and Anthropic has publicly confirmed "people are hitting usage limits in Claude Code way faster than expected." agentmemory contributes ~1-2K tokens per session via SessionStart, and that contribution is worth eliminating, but this release does not and cannot make Claude Pro's base quotas roomier. Users on heavy tool-call workloads should consider Max 5x or Team tiers regardless of whether agentmemory is installed.++0.8.8's #138 fix (opt-in `mem::compress` via `AGENTMEMORY_AUTO_COMPRESS`) remains the correct fix for users with `ANTHROPIC_API_KEY` set — that path was a real per-observation Claude API burn and is unrelated to the Claude Code hook pipeline.++### Added++- **`AGENTMEMORY_INJECT_CONTEXT` env var** — default `false`. When `true`, restores the old SessionStart stdout write and the old PreToolUse `/enrich` round-trip. Startup banner prints a loud warning when it's on, mirroring the `AGENTMEMORY_AUTO_COMPRESS` warning from 0.8.8.+- **`isContextInjectionEnabled()`** helper in `src/config.ts` — single source of truth for the flag. The hooks read the env var directly (they're spawned as standalone `.mjs` files by Claude Code and don't bootstrap through `src/index.ts`), so the helper is there for the startup banner and future code paths.+- **5 subprocess regression tests** in `test/context-injection.test.ts` — spawns the compiled `pre-tool-use.mjs` and `session-start.mjs` hooks with real stdin/stdout pipes and asserts that stdout is empty when the env var is unset, when it's explicitly `false`, and that the disabled PreToolUse path exits under 1 second. Also asserts that the opt-in path with an unreachable backend still exits cleanly. Full suite: **724 passing** (was 719 + 5 new).++### Infrastructure++- **Startup banner** (`src/index.ts`) now prints `Context injection: OFF (default, #143)` on normal startup and a prominent WARNING when opt-in is enabled, so the mode is never silent.+- **Migration note**: if you were relying on the old SessionStart project-context injection or the old PreToolUse enrichment round-trip, add to `~/.agentmemory/.env`:+ ```env+ AGENTMEMORY_INJECT_CONTEXT=true+ ```+ and restart Claude Code. You'll see the startup warning in the engine logs confirming it's active.++[0.8.10]: https://github.com/rohitg00/agentmemory/compare/v0.8.9...v0.8.10+## [0.8.9] — 2026-04-14Two UX fixes for the Claude Code plugin install path, both reported in [#139](https://github.com/rohitg00/agentmemory/issues/139) by [@stefanfaur](https://github.com/stefanfaur).diff --git a/README.md b/README.mdindex 8d9c25c2..7ffc7112 100644--- a/README.md+++ b/README.md@@ -731,6 +731,20 @@ Create `~/.agentmemory/.env`:# LLM provider to compress the# observation — expect significant# token spend on active sessions.+# AGENTMEMORY_INJECT_CONTEXT=false # OFF by default (#143). When on:+ # - SessionStart may inject ~1-2K+ # chars of project context into+ # the first turn of each session+ # (this is what actually reaches+ # the model — Claude Code treats+ # SessionStart stdout as context)+ # - PreToolUse fires /agentmemory/enrich+ # on every file-touching tool call+ # (resource cleanup, not a token+ # fix — PreToolUse stdout is debug+ # log only per Claude Code docs)+ # Observations are still captured via+ # PostToolUse regardless of this flag.# GRAPH_EXTRACTION_ENABLED=false# CONSOLIDATION_ENABLED=true# LESSON_DECAY_ENABLED=truediff --git a/package-lock.json b/package-lock.jsonindex bfc0400b..ee09c28e 100644--- a/package-lock.json+++ b/package-lock.json@@ -1,12 +1,12 @@{"name": "@agentmemory/agentmemory",- "version": "0.8.9",+ "version": "0.8.10","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "@agentmemory/agentmemory",- "version": "0.8.9",+ "version": "0.8.10","license": "Apache-2.0","dependencies": {"@anthropic-ai/claude-agent-sdk": "^0.2.56",diff --git a/package.json b/package.jsonindex ad78ca46..cf71405b 100644--- a/package.json+++ b/package.json@@ -1,6 +1,6 @@{"name": "@agentmemory/agentmemory",- "version": "0.8.9",+ "version": "0.8.10","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.jsonindex 1133b77c..490015a6 100644--- a/packages/mcp/package.json+++ b/packages/mcp/package.json@@ -1,6 +1,6 @@{"name": "@agentmemory/mcp",- "version": "0.8.9",+ "version": "0.8.10","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.9"+ "@agentmemory/agentmemory": "~0.8.10"},"publishConfig": {"access": "public",diff --git a/plugin/.claude-plugin/plugin.json b/plugin/.claude-plugin/plugin.jsonindex 20984771..28af4fd4 100644--- a/plugin/.claude-plugin/plugin.json+++ b/plugin/.claude-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "agentmemory",- "version": "0.8.9",+ "version": "0.8.10","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/plugin/scripts/pre-tool-use.mjs b/plugin/scripts/pre-tool-use.mjsindex aa9432b0..5c641e22 100755--- a/plugin/scripts/pre-tool-use.mjs+++ b/plugin/scripts/pre-tool-use.mjs@@ -1,5 +1,6 @@#!/usr/bin/env node//#region src/hooks/pre-tool-use.ts+const INJECT_CONTEXT = process.env["AGENTMEMORY_INJECT_CONTEXT"] === "true";const REST_URL = process.env["AGENTMEMORY_URL"] || "http://localhost:3111";const SECRET = process.env["AGENTMEMORY_SECRET"] || "";function authHeaders() {@@ -8,6 +9,7 @@ function authHeaders() {return h;}async function main() {+ if (!INJECT_CONTEXT) return;let input = "";for await (const chunk of process.stdin) input += chunk;let data;diff --git a/plugin/scripts/session-start.mjs b/plugin/scripts/session-start.mjsindex 8c3bae85..33032fe1 100755--- a/plugin/scripts/session-start.mjs+++ b/plugin/scripts/session-start.mjs@@ -1,5 +1,6 @@#!/usr/bin/env node//#region src/hooks/session-start.ts+const INJECT_CONTEXT = process.env["AGENTMEMORY_INJECT_CONTEXT"] === "true";const REST_URL = process.env["AGENTMEMORY_URL"] || "http://localhost:3111";const SECRET = process.env["AGENTMEMORY_SECRET"] || "";function authHeaders() {@@ -29,7 +30,7 @@ async function main() {}),signal: AbortSignal.timeout(5e3)});- if (res.ok) {+ if (INJECT_CONTEXT && res.ok) {const result = await res.json();if (result.context) process.stdout.write(result.context);}diff --git a/src/config.ts b/src/config.tsindex 1d039951..6c8f4c1c 100644--- a/src/config.ts+++ b/src/config.ts@@ -204,6 +204,19 @@ export function isAutoCompressEnabled(): boolean {return getMergedEnv()["AGENTMEMORY_AUTO_COMPRESS"] === "true";}+// Hook-level context injection into Claude Code's conversation is OFF by+// default as of 0.8.10 (see #143). When disabled, pre-tool-use and+// session-start hooks still POST observations for background capture, but+// never write context to stdout — so Claude Code doesn't inject an extra+// ~4000-char blob into every tool turn. 0.8.8 stopped the agentmemory-side+// Claude calls (via ANTHROPIC_API_KEY); this stops the Claude Code-side+// token burn where every tool call silently grew the model input window.+// Users who want the in-conversation context injection explicitly opt in+// with AGENTMEMORY_INJECT_CONTEXT=true and get a loud startup warning.+export function isContextInjectionEnabled(): boolean {+ return getMergedEnv()["AGENTMEMORY_INJECT_CONTEXT"] === "true";+}+export function getConsolidationDecayDays(): number {return safeParseInt(getMergedEnv()["CONSOLIDATION_DECAY_DAYS"], 30);}diff --git a/src/functions/export-import.ts b/src/functions/export-import.tsindex 44d051bb..cc97a8ca 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", "0.8.8", "0.8.9"]);+ 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", "0.8.9", "0.8.10"]);if (!supportedVersions.has(importData.version)) {return {success: false,diff --git a/src/functions/retention.ts b/src/functions/retention.tsindex 178fc584..3dc0a6a5 100644--- a/src/functions/retention.ts+++ b/src/functions/retention.ts@@ -14,6 +14,7 @@ import {deleteAccessLog,normalizeAccessLog,} from "./access-tracker.js";+import { recordAudit } from "./audit.js";const DEFAULT_DECAY: DecayConfig = {lambda: 0.01,@@ -117,6 +118,13 @@ export function registerRetentionFunctions((1000 * 60 * 60 * 24)),);+ // Build all entries in memory first, then flush with Promise.all+ // so a full rescore is one batched KV write instead of N sequential+ // round-trips. Separate counts for the audit record at the end.+ const pendingWrites: Array<[string, RetentionScore]> = [];+ let episodicScored = 0;+ let semanticScored = 0;+for (const mem of memories) {if (!mem.isLatest) continue;const log = logsById.get(mem.id) ?? emptyAccessLog(mem.id);@@ -133,6 +141,7 @@ export function registerRetentionFunctions(const entry: RetentionScore = {memoryId: mem.id,+ source: "episodic",score,salience,temporalDecay,@@ -142,7 +151,8 @@ export function registerRetentionFunctions(};scores.push(entry);- await kv.set(KV.retentionScores, mem.id, entry);+ pendingWrites.push([mem.id, entry]);+ episodicScored++;}for (const sem of semanticMems) {@@ -176,6 +186,7 @@ export function registerRetentionFunctions(const entry: RetentionScore = {memoryId: sem.id,+ source: "semantic",score,salience,temporalDecay,@@ -185,9 +196,20 @@ export function registerRetentionFunctions(};scores.push(entry);- await kv.set(KV.retentionScores, sem.id, entry);+ pendingWrites.push([sem.id, entry]);+ semanticScored++;}+ // Flush all retention rows in parallel. N sequential writes was+ // making full rescores O(n) round-trips on stores with 1000++ // memories; batching drops that to O(1) wall time on the KV+ // backends that can pipeline.+ await Promise.all(+ pendingWrites.map(([id, entry]) =>+ kv.set(KV.retentionScores, id, entry),+ ),+ );+scores.sort((a, b) => b.score - a.score);const tiers = {@@ -213,6 +235,22 @@ export function registerRetentionFunctions(...tiers,});+ // Audit the rescore as a single batched event per sweep. We+ // intentionally pass an empty targetIds array — a mature store+ // can have 1000+ memory ids per rescore and flooding the audit+ // log with every memoryId on every cron tick is worse than+ // recording just the summary. The details payload has enough+ // context for observability (counts per source + per tier).+ if (scores.length > 0) {+ await recordAudit(kv, "retention_score", "mem::retention-score", [], {+ total: scores.length,+ episodic: episodicScored,+ semantic: semanticScored,+ tiers,+ config,+ });+ }+return { success: true, total: scores.length, tiers, scores };},);@@ -250,24 +288,74 @@ export function registerRetentionFunctions(};}+ // Branch on source (#124). Pre-0.8.10 rows have no `source` field,+ // and that includes semantic retention rows that were written by+ // the old scorer — so we can't just default to episodic, that+ // would silently no-op the delete and leave the stranded semantic+ // memory alive (the exact bug #124 is about). When `source` is+ // missing, probe both namespaces to find where the memoryId+ // actually lives and route the delete there. After one re-score+ // (mem::retention-score) every row will have the correct tag.let evicted = 0;+ let evictedEpisodic = 0;+ let evictedSemantic = 0;+ const evictedIds: string[] = [];for (const candidate of candidates) {try {- await kv.delete(KV.memories, candidate.memoryId);+ let scope: string;+ let resolvedSource: "episodic" | "semantic";+ if (candidate.source === "semantic") {+ scope = KV.semantic;+ resolvedSource = "semantic";+ } else if (candidate.source === "episodic") {+ scope = KV.memories;+ resolvedSource = "episodic";+ } else {+ const episodic = await kv.get(KV.memories, candidate.memoryId);+ if (episodic !== null) {+ scope = KV.memories;+ resolvedSource = "episodic";+ } else {+ scope = KV.semantic;+ resolvedSource = "semantic";+ }+ }+ await kv.delete(scope, candidate.memoryId);await kv.delete(KV.retentionScores, candidate.memoryId);await deleteAccessLog(kv, candidate.memoryId);evicted++;+ evictedIds.push(candidate.memoryId);+ if (resolvedSource === "semantic") evictedSemantic++;+ else evictedEpisodic++;} catch {continue;}}+ // Retention eviction is a structural delete path that removes+ // memories, retention scores, and access logs, so it needs to+ // emit an audit record per the repo's audit-coverage policy (see+ // mem::governance-delete for the reference pattern). Batched,+ // one record per invocation — per-candidate audits would flood+ // the audit log during normal eviction sweeps.+ if (evicted > 0) {+ await recordAudit(kv, "delete", "mem::retention-evict", evictedIds, {+ threshold,+ evicted,+ evictedEpisodic,+ evictedSemantic,+ reason: "retention score below threshold",+ });+ }+ctx.logger.info("Retention-based eviction complete", {evicted,+ evictedEpisodic,+ evictedSemantic,threshold,});- return { success: true, evicted };+ return { success: true, evicted, evictedEpisodic, evictedSemantic };},);}diff --git a/src/hooks/pre-tool-use.ts b/src/hooks/pre-tool-use.tsindex 10ddde5b..0f7ae724 100644--- a/src/hooks/pre-tool-use.ts+++ b/src/hooks/pre-tool-use.ts@@ -1,5 +1,21 @@#!/usr/bin/env node+// Pre-tool-use enrichment hook.+//+// THIS HOOK IS A NO-OP BY DEFAULT AS OF 0.8.10 (#143). Previously it+// fired /agentmemory/enrich on every Edit/Write/Read/Glob/Grep tool call+// and wrote up to 4000 chars of context to stdout. Claude Code reads+// PreToolUse stdout and prepends it to the model's next turn, which meant+// agentmemory was silently injecting ~1000 tokens into every tool turn+// via the user's Claude Code session. On Claude Pro that burned entire+// allocations in a handful of messages (@adrianricardo, #143).+//+// Users who explicitly want pre-tool enrichment opt in with:+// AGENTMEMORY_INJECT_CONTEXT=true in ~/.agentmemory/.env+// and restart Claude Code. Expect your session input token count to grow+// proportionally with the number of file-touching tool calls per turn.+const INJECT_CONTEXT = process.env["AGENTMEMORY_INJECT_CONTEXT"] === "true";+const REST_URL = process.env["AGENTMEMORY_URL"] || "http://localhost:3111";const SECRET = process.env["AGENTMEMORY_SECRET"] || "";@@ -10,6 +26,10 @@ function authHeaders(): Record<string, string> {}async function main() {+ // Default off: exit immediately so we don't even open stdin. This keeps+ // Claude Code's tool-call hot path as cheap as possible.+ if (!INJECT_CONTEXT) return;+let input = "";for await (const chunk of process.stdin) {input += chunk;diff --git a/src/hooks/session-start.ts b/src/hooks/session-start.tsindex 8d5f6790..047c19a1 100644--- a/src/hooks/session-start.ts+++ b/src/hooks/session-start.ts@@ -1,5 +1,14 @@#!/usr/bin/env node+// Session-start hook.+//+// Always registers the session for observation tracking (so memories+// captured on PostToolUse get attached to the right session). Only writes+// project context to stdout — which Claude Code prepends to the very first+// turn — when AGENTMEMORY_INJECT_CONTEXT=true. Default off as of 0.8.10+// (#143); see pre-tool-use.ts for the full explanation.+const INJECT_CONTEXT = process.env["AGENTMEMORY_INJECT_CONTEXT"] === "true";+const REST_URL = process.env["AGENTMEMORY_URL"] || "http://localhost:3111";const SECRET = process.env["AGENTMEMORY_SECRET"] || "";@@ -34,7 +43,10 @@ async function main() {signal: AbortSignal.timeout(5000),});- if (res.ok) {+ // Only write context to stdout when the user has explicitly opted+ // into injection. Registering the session is cheap and doesn't touch+ // Claude Code's input token window.+ if (INJECT_CONTEXT && res.ok) {const result = (await res.json()) as { context?: string };if (result.context) {process.stdout.write(result.context);diff --git a/src/index.ts b/src/index.tsindex d56fac40..03e645d6 100644--- a/src/index.ts+++ b/src/index.ts@@ -10,6 +10,7 @@ import {isGraphExtractionEnabled,isAutoCompressEnabled,isConsolidationEnabled,+ isContextInjectionEnabled,} from "./config.js";import {createProvider,@@ -181,6 +182,16 @@ async function main() {);}+ if (isContextInjectionEnabled()) {+ console.log(+ `[agentmemory] WARNING: AGENTMEMORY_INJECT_CONTEXT=true — the PreToolUse and SessionStart hooks will inject up to ~4000 chars of memory context into every tool turn. On Claude Pro this burns session tokens proportional to your tool-call frequency (see #143). Set AGENTMEMORY_INJECT_CONTEXT=false to disable.`,+ );+ } else {+ console.log(+ `[agentmemory] Context injection: OFF (default, #143) — hooks capture observations but do not inject context into Claude Code's conversation. Set AGENTMEMORY_INJECT_CONTEXT=true to opt-in (warning: expect your Claude Pro allocation to drain faster).`,+ );+ }+const teamConfig = loadTeamConfig();if (teamConfig) {registerTeamFunction(sdk, kv, teamConfig);diff --git a/src/types.ts b/src/types.tsindex 4756f4c0..92068bc9 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" | "0.8.8" | "0.8.9";+ 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" | "0.8.9" | "0.8.10";exportedAt: string;sessions: Session[];observations: Record<string, CompressedObservation[]>;@@ -472,6 +472,7 @@ export interface AuditEntry {| "sentinel_trigger"| "sketch_create"| "sketch_promote"+ | "retention_score"| "sketch_discard"| "crystallize"| "diagnose"@@ -792,6 +793,11 @@ export interface TemporalState {export interface RetentionScore {memoryId: string;+ // Which KV scope this row came from. Needed by mem::retention-evict+ // so the delete loop routes to KV.memories or KV.semantic correctly.+ // Missing on pre-0.8.10 rows — callers must treat `undefined` as+ // "unknown, assume episodic" for backwards-compat. See #124.+ source?: "episodic" | "semantic";score: number;salience: number;temporalDecay: number;diff --git a/src/version.ts b/src/version.tsindex a1bcfe4f..510d9aa1 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.8" | "0.8.9" = "0.8.9";+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.9" | "0.8.10" = "0.8.10";diff --git a/test/context-injection.test.ts b/test/context-injection.test.tsnew file mode 100644index 00000000..d7689638--- /dev/null+++ b/test/context-injection.test.ts@@ -0,0 +1,128 @@+import { describe, it, expect } from "vitest";+import { spawn } from "node:child_process";+import { join } from "node:path";++const HOOKS_DIR = join(import.meta.dirname, "..", "plugin", "scripts");++// Spawns a compiled plugin hook as a subprocess, feeds it JSON on stdin,+// and returns { stdout, stderr, exitCode, tookMs }. The test is about+// making sure the hook writes NOTHING to stdout when context injection is+// disabled — which is what Claude Code reads to decide whether to prepend+// memory context to the next tool turn.+function runHook(+ scriptName: string,+ stdin: string,+ env: Record<string, string>,+): Promise<{+ stdout: string;+ stderr: string;+ exitCode: number | null;+ tookMs: number;+}> {+ return new Promise((resolve, reject) => {+ const start = Date.now();+ const child = spawn(+ process.execPath,+ [join(HOOKS_DIR, scriptName)],+ {+ env: {+ // Start from a clean slate — don't leak test-runner env into+ // the hook. Only pass PATH and anything explicitly set by the+ // test case.+ PATH: process.env["PATH"] ?? "",+ ...env,+ },+ stdio: ["pipe", "pipe", "pipe"],+ },+ );++ let stdout = "";+ let stderr = "";+ child.stdout.on("data", (chunk) => {+ stdout += chunk.toString();+ });+ child.stderr.on("data", (chunk) => {+ stderr += chunk.toString();+ });+ child.on("error", reject);+ child.on("close", (exitCode) => {+ resolve({ stdout, stderr, exitCode, tookMs: Date.now() - start });+ });++ child.stdin.write(stdin);+ child.stdin.end();+ });+}++describe("pre-tool-use hook — context injection gate (#143)", () => {+ it("writes nothing to stdout when AGENTMEMORY_INJECT_CONTEXT is unset (default)", async () => {+ const payload = JSON.stringify({+ session_id: "ses_test",+ tool_name: "Read",+ tool_input: { file_path: "src/foo.ts" },+ });+ // No AGENTMEMORY_* env vars at all — simulates a fresh Claude Pro+ // install with no ~/.agentmemory/.env overrides.+ const result = await runHook("pre-tool-use.mjs", payload, {});+ expect(result.stdout).toBe("");+ expect(result.exitCode).toBe(0);+ });++ it("writes nothing to stdout when AGENTMEMORY_INJECT_CONTEXT=false explicitly", async () => {+ const payload = JSON.stringify({+ session_id: "ses_test",+ tool_name: "Edit",+ tool_input: { file_path: "src/foo.ts", old_string: "a", new_string: "b" },+ });+ const result = await runHook("pre-tool-use.mjs", payload, {+ AGENTMEMORY_INJECT_CONTEXT: "false",+ });+ expect(result.stdout).toBe("");+ expect(result.exitCode).toBe(0);+ });++ it("exits fast when disabled (no stdin consumption, no network fetch)", async () => {+ // The disabled path must not open stdin or reach for fetch — it+ // should return immediately. A 250ms budget is generous enough to+ // account for Node startup on CI while still catching any accidental+ // fetch round-trip or stdin buffering.+ const result = await runHook("pre-tool-use.mjs", "", {});+ expect(result.tookMs).toBeLessThan(1000);+ expect(result.stdout).toBe("");+ });++ it("when AGENTMEMORY_INJECT_CONTEXT=true, hook still runs but safely errors on unreachable backend", async () => {+ // Opt-in path. We point at a port that's guaranteed closed so the+ // fetch fails fast; the hook must still exit cleanly (the whole+ // point of the try/catch is not to break Claude Code) and must not+ // echo anything to stdout when the fetch fails.+ const payload = JSON.stringify({+ session_id: "ses_test",+ tool_name: "Read",+ tool_input: { file_path: "src/foo.ts" },+ });+ const result = await runHook("pre-tool-use.mjs", payload, {+ AGENTMEMORY_INJECT_CONTEXT: "true",+ AGENTMEMORY_URL: "http://127.0.0.1:1",+ });+ expect(result.exitCode).toBe(0);+ expect(result.stdout).toBe("");+ });+});++describe("session-start hook — context injection gate (#143)", () => {+ it("registers the session but writes nothing to stdout when AGENTMEMORY_INJECT_CONTEXT is unset", async () => {+ // Session registration POST will fail against the unreachable URL,+ // but the hook's try/catch must swallow that cleanly — Claude Code+ // must never see an error at session start.+ const payload = JSON.stringify({+ session_id: "ses_test",+ cwd: "/tmp/fake-project",+ });+ const result = await runHook("session-start.mjs", payload, {+ AGENTMEMORY_URL: "http://127.0.0.1:1",+ });+ expect(result.exitCode).toBe(0);+ expect(result.stdout).toBe("");+ });+});diff --git a/test/export-import.test.ts b/test/export-import.test.tsindex 7a5f1f16..b1a149f4 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.9");+ expect(result.version).toBe("0.8.10");expect(result.exportedAt).toBeDefined();expect(result.sessions.length).toBe(1);expect(result.sessions[0].id).toBe("ses_1");diff --git a/test/retention.test.ts b/test/retention.test.tsindex 70932b6c..2d647288 100644--- a/test/retention.test.ts+++ b/test/retention.test.ts@@ -242,4 +242,238 @@ describe("RetentionScoring", () => {const sem2 = result.scores.find((s: any) => s.memoryId === "sem_2");expect(sem1.score).toBeGreaterThan(sem2.score);});++ it("scores tag rows with their source scope (#124)", async () => {+ const { registerRetentionFunctions } = await import(+ "../src/functions/retention.js"+ );++ const sdk = mockSdk();+ const kv = mockKV(+ [makeMemory("mem_ep", "fact", 10)],+ [makeSemanticMemory("sem_sem", 10, 2)],+ );+ registerRetentionFunctions(sdk as never, kv as never);++ const result = (await sdk.trigger("mem::retention-score", {})) as any;+ const ep = result.scores.find((s: any) => s.memoryId === "mem_ep");+ const sem = result.scores.find((s: any) => s.memoryId === "sem_sem");+ expect(ep.source).toBe("episodic");+ expect(sem.source).toBe("semantic");++ // Also assert the source discriminator is persisted to mem:retention,+ // not just present in the transient response payload — the eviction+ // loop reads back from stored rows, so a regression in kv.set or+ // serialization would still pass the in-memory check above.+ const [epStored, semStored] = await Promise.all([+ kv.get("mem:retention", "mem_ep"),+ kv.get("mem:retention", "sem_sem"),+ ]);+ expect(epStored).toMatchObject({ source: "episodic" });+ expect(semStored).toMatchObject({ source: "semantic" });+ });++ it("mem::retention-evict deletes semantic memories from mem:semantic, not mem:memories (#124)", async () => {+ const { registerRetentionFunctions } = await import(+ "../src/functions/retention.js"+ );++ // Both are 500 days old with zero access → both will score below+ // the default cold threshold. Before #124 the loop silently called+ // kv.delete(mem:memories, <semantic-id>) which was a no-op, leaving+ // the semantic row in mem:semantic forever.+ const sdk = mockSdk();+ const kv = mockKV(+ [makeMemory("mem_evict", "fact", 500)],+ [makeSemanticMemory("sem_evict", 500, 0)],+ );+ registerRetentionFunctions(sdk as never, kv as never);++ await sdk.trigger("mem::retention-score", {});+ const result = (await sdk.trigger("mem::retention-evict", {+ threshold: 0.9,+ })) as any;++ expect(result.evicted).toBe(2);+ expect(result.evictedEpisodic).toBe(1);+ expect(result.evictedSemantic).toBe(1);++ const remainingEp = await kv.list("mem:memories");+ const remainingSem = await kv.list("mem:semantic");+ expect(remainingEp).toHaveLength(0);+ expect(remainingSem).toHaveLength(0);++ // Retention score rows also cleaned up for both.+ const remainingScores = await kv.list("mem:retention");+ expect(remainingScores).toHaveLength(0);+ });++ it("mem::retention-evict emits a single batched audit record on success (#124, audit policy)", async () => {+ const { registerRetentionFunctions } = await import(+ "../src/functions/retention.js"+ );++ const sdk = mockSdk();+ const kv = mockKV(+ [makeMemory("mem_a", "fact", 500), makeMemory("mem_b", "fact", 500)],+ [makeSemanticMemory("sem_c", 500, 0)],+ );+ registerRetentionFunctions(sdk as never, kv as never);++ await sdk.trigger("mem::retention-score", {});+ await sdk.trigger("mem::retention-evict", { threshold: 0.9 });++ // Retention-score ALSO emits an audit row (one per rescore, also+ // required by the repo audit-coverage policy), so filter the audit+ // log down to just the retention-evict entry we're asserting on.+ const allEntries = await kv.list<{+ operation: string;+ functionId: string;+ targetIds: string[];+ details: Record<string, unknown>;+ }>("mem:audit");+ const evictEntries = allEntries.filter(+ (e) => e.functionId === "mem::retention-evict",+ );+ expect(evictEntries).toHaveLength(1);+ const [entry] = evictEntries;+ expect(entry.operation).toBe("delete");+ expect([...entry.targetIds].sort()).toEqual(["mem_a", "mem_b", "sem_c"]);+ expect(entry.details.evicted).toBe(3);+ expect(entry.details.evictedEpisodic).toBe(2);+ expect(entry.details.evictedSemantic).toBe(1);+ });++ it("mem::retention-evict skips audit when evicted=0 (no spurious audit rows)", async () => {+ const { registerRetentionFunctions } = await import(+ "../src/functions/retention.js"+ );++ const sdk = mockSdk();+ // Memory is 1 day old → score will be high → nothing falls below+ // the strict 0.99 threshold → evict=0 → no evict audit row.+ // Retention-score itself still writes one audit row per sweep,+ // which is the expected behavior (zero-eviction != zero-rescore),+ // so we filter the audit log down to just the evict entries.+ const kv = mockKV([makeMemory("mem_keep", "architecture", 1)]);+ registerRetentionFunctions(sdk as never, kv as never);++ await sdk.trigger("mem::retention-score", {});+ await sdk.trigger("mem::retention-evict", { threshold: 0.0001 });++ const allEntries = await kv.list<{ functionId: string }>("mem:audit");+ const evictEntries = allEntries.filter(+ (e) => e.functionId === "mem::retention-evict",+ );+ expect(evictEntries).toHaveLength(0);+ });++ it("mem::retention-score emits a batched audit row per rescore (#124, audit policy)", async () => {+ const { registerRetentionFunctions } = await import(+ "../src/functions/retention.js"+ );++ const sdk = mockSdk();+ const kv = mockKV(+ [makeMemory("mem_a", "fact", 10), makeMemory("mem_b", "fact", 10)],+ [makeSemanticMemory("sem_c", 10, 2)],+ );+ registerRetentionFunctions(sdk as never, kv as never);++ await sdk.trigger("mem::retention-score", {});++ const allEntries = await kv.list<{+ operation: string;+ functionId: string;+ targetIds: string[];+ details: Record<string, unknown>;+ }>("mem:audit");+ const scoreEntries = allEntries.filter(+ (e) => e.functionId === "mem::retention-score",+ );+ expect(scoreEntries).toHaveLength(1);+ const [entry] = scoreEntries;+ expect(entry.operation).toBe("retention_score");+ // targetIds is intentionally empty — a mature store can have 1000++ // memory ids per rescore and flooding the audit log would be worse+ // than recording just the summary counts.+ expect(entry.targetIds).toEqual([]);+ expect(entry.details.total).toBe(3);+ expect(entry.details.episodic).toBe(2);+ expect(entry.details.semantic).toBe(1);+ });++ it("mem::retention-evict probes namespaces for legacy semantic rows (backwards-compat, #124)", async () => {+ const { registerRetentionFunctions } = await import(+ "../src/functions/retention.js"+ );++ // The actual nasty case from CodeRabbit's review: a pre-0.8.10+ // store that had a semantic memory scored by the old code path.+ // The retention row has NO source field and the memory lives in+ // mem:semantic. If the eviction path blindly defaults missing+ // source to episodic, it no-ops the delete and strands the+ // semantic row forever — which is the exact bug #124 is about.+ const sdk = mockSdk();+ const kv = mockKV([], [makeSemanticMemory("sem_legacy", 500, 0)]);+ registerRetentionFunctions(sdk as never, kv as never);++ await kv.set("mem:retention", "sem_legacy", {+ memoryId: "sem_legacy",+ // No `source` field — simulates a row written by 0.8.9 or earlier.+ score: 0.01,+ salience: 0,+ temporalDecay: 0,+ reinforcementBoost: 0,+ lastAccessed: new Date().toISOString(),+ accessCount: 0,+ });++ const result = (await sdk.trigger("mem::retention-evict", {+ threshold: 0.5,+ })) as any;+ expect(result.evicted).toBe(1);+ expect(result.evictedSemantic).toBe(1);+ expect(result.evictedEpisodic).toBe(0);++ // Most important assertion: the semantic row is GONE from+ // mem:semantic. Before the probe fix, this assertion failed+ // because the delete targeted mem:memories.+ const remainingSem = await kv.list("mem:semantic");+ expect(remainingSem).toHaveLength(0);+ });++ it("mem::retention-evict routes pre-0.8.10 episodic rows with missing source to mem:memories (#124)", async () => {+ const { registerRetentionFunctions } = await import(+ "../src/functions/retention.js"+ );++ // Simulate a store that was scored on 0.8.9 or earlier: retention+ // rows exist but they have no `source` field. The new eviction+ // loop must still route those to mem:memories so users don't get+ // stuck with un-evictable episodic rows after upgrading.+ const sdk = mockSdk();+ const kv = mockKV([makeMemory("mem_old", "fact", 500)]);+ registerRetentionFunctions(sdk as never, kv as never);++ // Directly plant a legacy-shape retention score (no `source` key).+ await kv.set("mem:retention", "mem_old", {+ memoryId: "mem_old",+ score: 0.01,+ salience: 0,+ temporalDecay: 0,+ reinforcementBoost: 0,+ lastAccessed: new Date().toISOString(),+ accessCount: 0,+ });++ const result = (await sdk.trigger("mem::retention-evict", {+ threshold: 0.5,+ })) as any;+ expect(result.evicted).toBe(1);+ expect(result.evictedEpisodic).toBe(1);+ expect(result.evictedSemantic).toBe(0);+ const remaining = await kv.list("mem:memories");+ expect(remaining).toHaveLength(0);+ });});