#1 Persistent memory for AI coding agents based on real-world benchmarks
TypeScript agentmemoryagentsaiclaudeclaudecodecodexcopilotcursorgenaiharnesshermesmemoryompopenclawopencodepi
chore: remove issue and PR references from code and tests (#1469)
Rohit Ghumareda78ea897126
diff --git a/.env.example b/.env.exampleindex d5376654..af00f191 100644--- a/.env.example+++ b/.env.example@@ -71,7 +71,7 @@# Opt-in Claude-subscription fallback (spawns @anthropic-ai/claude-agent-sdk# child sessions). Off by default — the agent-sdk fallback can trigger-# Stop-hook recursion (#149 follow-up) when invoked from inside Claude Code.+# Stop-hook recursion when invoked from inside Claude Code.# AGENTMEMORY_ALLOW_AGENT_SDK=true# FALLBACK_PROVIDERS=anthropic,gemini # Comma-separated chain tried after the primary provider returns an error (e.g. rate limit)@@ -131,7 +131,7 @@# -----------------------------------------------------------------------------# AGENTMEMORY_AUTO_COMPRESS=true # Run LLM-written compression on every observation batch. Requires BOTH this flag and a configured provider; a provider alone leaves synthetic compression active.-# AGENTMEMORY_INJECT_CONTEXT=true # Inject recalled memories back into agent prompts (#143). Default off — hooks capture observations but do not modify conversation.+# AGENTMEMORY_INJECT_CONTEXT=true # Inject recalled memories back into agent prompts. Default off — hooks capture observations but do not modify conversation.# CONSOLIDATION_ENABLED=true # Run the 4-tier consolidation pipeline (memories → semantic → procedural). Default off — opt in once you've measured the LLM cost.# CONSOLIDATION_DECAY_DAYS=30 # Age (days) after which non-reinforced memories decay during consolidation# GRAPH_EXTRACTION_ENABLED=true # Extract concept-graph edges on remember; powers the graph-traversal recall path@@ -144,7 +144,7 @@# AGENTMEMORY_LLM_NOTHINK=1# AGENTMEMORY_REFLECT=true # Periodically auto-synthesize lessons from memories-# AGENTMEMORY_DROP_STALE_INDEX=true # Drop on-disk BM25 / vector index on startup if dim guard fires (#248). Recovery toggle for stuck-state debugging.+# AGENTMEMORY_DROP_STALE_INDEX=true # Drop on-disk BM25 / vector index on startup if dim guard fires. Recovery toggle for stuck-state debugging.# AGENTMEMORY_IMAGE_EMBEDDINGS=true # Enable image embeddings when an image provider is present (experimental).# AGENTMEMORY_AUDIT_RETENTION_MONTHS=6 # Drop whole audit-log month scopes older than N months on a daily sweep. Default 0 = keep audit history forever.# AGENTMEMORY_AUDIT_MIGRATE_MAX_BYTES=33554432 # Largest legacy mem:audit scope file the one-time migration will read locally. Default 32 MiB; bigger or unreadable stores are left frozen.diff --git a/benchmark/load-100k.ts b/benchmark/load-100k.tsindex 676aa647..255de135 100644--- a/benchmark/load-100k.ts+++ b/benchmark/load-100k.ts@@ -1,28 +1,3 @@-/**- * Load harness — seeds N synthetic memories against a local agentmemory- * daemon, then drives a matrix of (N, concurrency, endpoint) cells and- * records p50 / p90 / p99 latency + throughput per cell.- *- * Spec: GitHub issue #346.- *- * Runs against an already-running daemon at `http://localhost:3111` by- * default. Set `AGENTMEMORY_BENCH_AUTOSTART=1` to spawn one via- * `node dist/cli.js start` for the duration of the run.- *- * Env knobs:- * AGENTMEMORY_BENCH_AUTOSTART "1" to spawn the daemon (default: assume up)- * AGENTMEMORY_URL base URL of the daemon (default: http://localhost:3111)- * BENCH_N comma-separated N sizes (default: 1000,10000,100000)- * BENCH_C comma-separated concurrency levels (default: 1,10,100)- * BENCH_OPS ops per cell during measurement (default: 200)- * BENCH_SEED seed for the mulberry32 RNG (default: 0xC0FFEE)- * BENCH_OUT_DIR results dir (default: benchmark/results)- *- * The harness writes one JSON file per run named- * `load-100k-<short-git-sha>.json`. The git sha is best-effort — falls- * back to a timestamp when run outside a checkout.- */-import { spawn, type ChildProcess } from "node:child_process";import { execFileSync } from "node:child_process";import { mkdirSync, writeFileSync, existsSync } from "node:fs";diff --git a/iii-config.docker.yaml b/iii-config.docker.yamlindex 10863607..4cc638a4 100644--- a/iii-config.docker.yaml+++ b/iii-config.docker.yaml@@ -46,7 +46,7 @@ workers:enabled: trueservice_name: agentmemoryexporter: memory- # See iii-config.yaml for the rationale on 0.1 / console-off (#519).+ # See iii-config.yaml for the rationale on 0.1 / console-off.sampling_ratio: 0.1metrics_enabled: truelogs_enabled: truediff --git a/iii-config.yaml b/iii-config.yamlindex 91cd1d70..642d046f 100644--- a/iii-config.yaml+++ b/iii-config.yaml@@ -47,7 +47,7 @@ workers:# subscriber lagged" WARN, and that WARN re-enters the same# stream the subscriber is failing to drain — a positive# feedback loop that wrote 137 GB to daemon.log.new on one user- # in a few days (#519).+ # in a few days.sampling_ratio: 0.1metrics_enabled: truelogs_enabled: truediff --git a/integrations/hermes/__init__.py b/integrations/hermes/__init__.pyindex 33e1d598..878a6524 100644--- a/integrations/hermes/__init__.py+++ b/integrations/hermes/__init__.py@@ -78,19 +78,6 @@ TIMEOUT = 5LOOPBACK_HOSTS = {"localhost", "127.0.0.1", "::1"}_plaintext_bearer_warned = False-# agentmemory's documented runtime config lives at ~/.agentmemory/.env.-# When agentmemory is launched as a systemd user service (or any other-# process manager that loads that file directly), those values never-# reach an interactive shell. `hermes memory status` then reads-# os.environ in the Hermes CLI process, finds AGENTMEMORY_URL /-# AGENTMEMORY_SECRET unset, and reports the plugin as "Missing" even-# though the service is healthy and live sessions can use it (#250).-#-# Preload the file at plugin-import time using os.environ.setdefault so-# we never override anything the user explicitly set in the shell. The-# preload is best-effort and silent on any failure (file absent,-# unreadable, malformed) — the plugin falls back to its existing default-# (http://localhost:3111) and Hermes status reflects that.def _preload_agentmemory_dotenv() -> None:candidates: list[Path] = []home = os.environ.get("HOME")@@ -114,10 +101,6 @@ def _preload_agentmemory_dotenv() -> None:os.environ.setdefault(key, value)except (OSError, UnicodeDecodeError):continue- # Guarantee AGENTMEMORY_URL is set so `hermes memory status` never- # reports it as Missing when a user runs agentmemory at the default- # localhost:3111 (or via systemd with the URL line commented out in- # ~/.agentmemory/.env because it matches the default). #520.os.environ.setdefault("AGENTMEMORY_URL", DEFAULT_BASE_URL)diff --git a/integrations/pi/index.ts b/integrations/pi/index.tsindex 786d9700..804c1a9d 100644--- a/integrations/pi/index.ts+++ b/integrations/pi/index.ts@@ -393,7 +393,6 @@ export default function agentmemoryExtension(pi: ExtensionAPI) {// /new, /resume, /fork and reloads fire this too; only quit ends the session.if (event.reason !== "quit") return;if (!lastHealthOk || !sessionId) return;- // session/end already fans out the summary server-side (#1203).await callAgentMemory("session/end", {body: { sessionId },timeoutMs: 5_000,diff --git a/plugin/skills/agentmemory-agents/REFERENCE.md b/plugin/skills/agentmemory-agents/REFERENCE.mdindex 84d637d8..57702319 100644--- a/plugin/skills/agentmemory-agents/REFERENCE.md+++ b/plugin/skills/agentmemory-agents/REFERENCE.md@@ -11,7 +11,7 @@ Generated from `src/cli/connect/index.ts`. Do not edit the block below by hand;| Antigravity CLI (agy) | `antigravity-cli` | Using MCP via ~/.gemini/config/mcp_config.json (the agy CLI, not the Antigravity IDE, that one is `connect antigravity`). The `/mcp` slash command inside agy lists configured servers. Pass --with-hooks to also install the native ~/.gemini/config/hooks.json auto-capture hooks. || Claude Code | `claude-code` | Using MCP. Hooks are also available, see https://github.com/rohitg00/agentmemory#claude-code-one-block-paste-it. || Cline | `cline` | Using MCP via ~/.cline/mcp.json (CLI). VS Code users: add the same block via Cline Settings → MCP Servers → Edit JSON. |-| Codex CLI | `codex` | Using MCP. Hooks ship via the Codex plugin; on Codex Desktop, also pass --with-hooks to install the global hooks.json workaround for openai/codex#16430. |+| Codex CLI | `codex` | Using MCP. Hooks ship via the Codex plugin; on Codex Desktop, also pass --with-hooks to install the global hooks.json workaround. || Continue | `continue` | Using MCP via ~/.continue/config.yaml (preferred) or config.json (legacy, only when no yaml). || GitHub Copilot CLI | `copilot-cli` | Using MCP. Install the plugin too for full hooks/skills coverage. || Cursor | `cursor` | Using MCP (the only protocol Cursor speaks). Memory bridge runs at :3111 underneath. |diff --git a/src/cli/connect/claude-code.ts b/src/cli/connect/claude-code.tsindex 6d9ef067..1882be86 100644--- a/src/cli/connect/claude-code.ts+++ b/src/cli/connect/claude-code.ts@@ -58,9 +58,6 @@ export const adapter: ConnectAdapter = {const alreadyHas = entryMatches(servers["agentmemory"]);if (alreadyHas && !opts.force) {logAlreadyWired("Claude Code", CLAUDE_JSON);- // --with-hooks is independent of MCP wiring (issue #508). Run the- // hooks fallback even when MCP is already in place so users with a- // healthy MCP setup can still pick up version-stable hook paths.if (opts.withHooks) {const hookResult = installClaudeHooks(opts);if (hookResult.kind === "skipped") {@@ -118,17 +115,6 @@ export const adapter: ConnectAdapter = {},};-/**- * Merge the bundled `plugin/hooks/hooks.json` into- * `~/.claude/settings.json`'s top-level `hooks` field with absolute- * script paths. Use this when agentmemory is NOT installed through- * `/plugin marketplace add` (e.g. MCP standalone wiring), so the- * hook scripts survive version bumps without `${CLAUDE_PLUGIN_ROOT}`- * expansion (issue #508).- *- * Re-install strips entries whose command points under- * `<pluginRoot>/scripts/`; unrelated user hook entries survive.- */function installClaudeHooks(opts: ConnectOptions): ConnectResult {let pluginRoot: string;try {@@ -165,7 +151,7 @@ function installClaudeHooks(opts: ConnectOptions): ConnectResult {const next: ClaudeSettings = { ...existing, hooks: merged.hooks };writeJsonAtomic(CLAUDE_SETTINGS, next);- logInstalled("Claude Code hooks (workaround for #508)", CLAUDE_SETTINGS);+ logInstalled("Claude Code hooks", CLAUDE_SETTINGS);p.log.info("User-scope hook entries reference absolute paths under the bundled plugin/ dir. Re-run `agentmemory connect claude-code --with-hooks` after upgrading agentmemory to refresh them.",);diff --git a/src/cli/connect/codex-hooks.ts b/src/cli/connect/codex-hooks.tsindex f2a3a3bd..0a97eb82 100644--- a/src/cli/connect/codex-hooks.ts+++ b/src/cli/connect/codex-hooks.ts@@ -2,35 +2,6 @@ import { existsSync, readFileSync } from "node:fs";import { dirname, join, resolve } from "node:path";import { fileURLToPath } from "node:url";-/**- * Shared merge engine for writing agentmemory's bundled hook scripts into- * a host's global, user-scope hooks config. Originally built as a- * workaround for openai/codex#16430 — Codex Desktop does not dispatch- * plugin-local `hooks.json` even though both `CodexHooks` and `PluginHooks`- * feature flags are stable + default-enabled in- * `codex-rs/features/src/lib.rs`. Until upstream fixes plugin-scope- * dispatch, the same hook commands can be mirrored into the global- * `~/.codex/hooks.json`, which is loaded reliably.- *- * The same merge logic now also backs Claude Code's `--with-hooks`- * fallback (`~/.claude/settings.json`, #508 workaround) and Droid's- * native `~/.factory/hooks.json` install, since both hosts consume the- * identical `{ hooks: { <event>: [{ matcher?, hooks: [{ type, command }] }] } }`- * shape — only the bundled manifest file passed to `buildMergedHooks`- * differs per host.- *- * This module builds that merge, with `${CLAUDE_PLUGIN_ROOT}` resolved to- * the bundled `plugin/` directory so the user-scope file does not depend- * on env-var expansion (only Claude Code actually injects- * `CLAUDE_PLUGIN_ROOT` for plugin-scope hooks — the token is reused here- * purely as an internal placeholder for "the bundled plugin/ dir").- *- * Identification on re-install: every command we write contains the- * resolved `<pluginRoot>/scripts/` prefix, so subsequent installs can- * strip our entries and re-add cleanly without touching the user's other- * hook entries.- */-type HookHandler = { type: string; command: string };type HookEntry = { matcher?: string; hooks: HookHandler[] };export type HookManifest = { hooks: Record<string, HookEntry[]> };diff --git a/src/cli/connect/codex.ts b/src/cli/connect/codex.tsindex d0290f85..b31b35d1 100644--- a/src/cli/connect/codex.ts+++ b/src/cli/connect/codex.ts@@ -66,7 +66,7 @@ export const adapter: ConnectAdapter = {category: "native",docs: "https://github.com/rohitg00/agentmemory#codex-cli-codex-plugin-platform",protocolNote:- "→ Using MCP. Hooks ship via the Codex plugin; on Codex Desktop, also pass --with-hooks to install the global hooks.json workaround for openai/codex#16430.",+ "→ Using MCP. Hooks ship via the Codex plugin; on Codex Desktop, also pass --with-hooks to install the global hooks.json workaround.",detect(): boolean {return existsSync(CODEX_DIR);@@ -133,12 +133,6 @@ export const adapter: ConnectAdapter = {},};-/**- * Install the global `~/.codex/hooks.json` fallback. See- * `codex-hooks.ts` for context (openai/codex#16430). Returns a result- * describing the side effect for the caller's summary; failures here do- * not roll back the MCP wiring.- */function installCodexHooks(opts: ConnectOptions): ConnectResult {let pluginRoot: string;try {@@ -168,7 +162,7 @@ function installCodexHooks(opts: ConnectOptions): ConnectResult {writeJsonAtomic(CODEX_HOOKS, merged);- logInstalled("Codex hooks (workaround for openai/codex#16430)", CODEX_HOOKS);+ logInstalled("Codex hooks", CODEX_HOOKS);p.log.warn("Codex runs only trusted hooks: launch `codex` (the TUI) once and choose \"Trust all and continue\" at the \"Hooks need review\" prompt. `codex exec` never shows the prompt, so hooks stay inert until then.",);diff --git a/src/cli/connect/json-mcp-adapter.ts b/src/cli/connect/json-mcp-adapter.tsindex 9966e297..0b76aa75 100644--- a/src/cli/connect/json-mcp-adapter.ts+++ b/src/cli/connect/json-mcp-adapter.ts@@ -29,11 +29,6 @@ export type JsonMcpAdapterConfig = {// Extra fields merged into the agentmemory entry. Droid requires// type: "stdio"; other hosts ignore unknown fields.extraEntryFields?: Record<string, unknown>;- // Invoked when `--with-hooks` is passed, independent of whether the MCP- // entry was freshly installed or already wired (mirrors the Claude Code /- // Codex adapters, issue #508 pattern) — hosts that ship a native hook- // config alongside MCP (e.g. Droid's `~/.factory/hooks.json`) pass this- // to install/refresh their hook manifest.installHooks?: (opts: ConnectOptions) => ConnectResult;};diff --git a/src/cli/connect/types.ts b/src/cli/connect/types.tsindex eedd76f5..24938887 100644--- a/src/cli/connect/types.ts+++ b/src/cli/connect/types.ts@@ -1,15 +1,6 @@export type ConnectOptions = {dryRun: boolean;force: boolean;- /**- * When true, adapters that ship a native hook config alongside MCP- * additionally write it: Codex (`~/.codex/hooks.json`, workaround for- * openai/codex#16430), Claude Code (`~/.claude/settings.json`, workaround- * for #508), Droid (`~/.factory/hooks.json`, its native hooks config),- * and DeepSeek Harness (`$DSH_HOME/agentmemory.hooks.json` plus a- * hooks-claude-code patch row). No-op for adapters without a hooks- * installer.- */withHooks?: boolean;/*** When true (default), after wiring the agent's MCP/hooks, also write a@@ -31,12 +22,6 @@ export type ConnectAdapter = {* opt-in bridge for MCP-only clients.*/protocolNote?: string;- /**- * Integration style, used by onboarding to group agents. "native" =- * ships a first-party plugin / lifecycle hooks; "mcp" = wires the MCP- * server only. Declared on the adapter so the picker never needs a- * separate hardcoded list (#872). Defaults to "mcp" when omitted.- */category?: "native" | "mcp";detect(): boolean;install(opts: ConnectOptions): Promise<ConnectResult>;diff --git a/src/cli/connect/util.ts b/src/cli/connect/util.tsindex c47b7f40..9aa62087 100644--- a/src/cli/connect/util.ts+++ b/src/cli/connect/util.ts@@ -10,18 +10,6 @@ import { dirname, join } from "node:path";import { homedir } from "node:os";import * as p from "@clack/prompts";-// Env values use ${VAR:-default} expansion so the wired MCP entry-// inherits AGENTMEMORY_URL / AGENTMEMORY_SECRET / AGENTMEMORY_TOOLS-// from the user's shell, but never fails parse when the var is unset-// (#510). Earlier `${VAR}` form caused Claude Code to silently drop the-// server when no shell-level export existed — per the Claude Code MCP-// docs, "If a required environment variable is not set and has no-// default value, Claude Code will fail to parse the config."-//-// Defaults match the documented runtime: localhost:3111 (no auth, all-// tools). One wired entry now serves local AND remote (Kubernetes /-// reverse-proxied) deployments without doctor-warning duplicates (#375)-// AND fresh installs that haven't exported envs (#510).export const AGENTMEMORY_MCP_BLOCK = {command: "npx",args: ["-y", "@agentmemory/mcp"],diff --git a/src/cli/onboarding.ts b/src/cli/onboarding.tsindex 926cdbea..52b0c6ed 100644--- a/src/cli/onboarding.ts+++ b/src/cli/onboarding.ts@@ -32,13 +32,6 @@ import type { ConnectResult } from "./connect/types.js";const __dirname = dirname(fileURLToPath(import.meta.url));-// Native plugin row — these agents ship an agentmemory plugin or-// first-party integration. Glyphs match SkillKit's published set-// where they overlap; the rest fall back to the generic `◇`.-// Display glyph per agent; the agent set itself comes from connect's-// ADAPTERS (single source of truth) so the picker can never drift from-// what `agentmemory connect` can actually wire (#872). Unknown adapters-// fall back to a neutral glyph.const AGENT_GLYPH: Record<string, string> = {"claude-code": "⟁","copilot-cli": "◈",diff --git a/src/functions/audit.ts b/src/functions/audit.tsindex aeed9c28..2c778a2a 100644--- a/src/functions/audit.ts+++ b/src/functions/audit.ts@@ -10,34 +10,6 @@ import { getEnvVar, getAuditMigrateMaxBytes } from "../config.js";import { runtimeConfigPath } from "../cli/engine-launch.js";import { ENGINE_DEFAULT_SAVE_INTERVAL_MS, engineSaveIntervalMs, engineStateConfigPaths } from "../cli/engine-config.js";-// Audit coverage policy (issue #125).-//-// Every structural deletion of a memory, observation, session, or-// semantic row MUST call recordAudit. Two shapes are allowed, keyed to-// whether the caller is scoped or bulk:-//-// Scoped deletions — a user-visible, per-call action removing a-// bounded set of items. Emit ONE audit row per call with targetIds-// populated. Examples: mem::governance-delete, mem::forget.-//-// Bulk deletions — automatic sweeps (retention, TTL eviction,-// auto-forget) that can remove hundreds of rows per invocation.-// Emit ONE batched audit row per invocation with targetIds listing-// every removed id and details.evicted holding the count. Per-item-// audit rows would flood the audit log during routine sweeps.-//-// Either shape is required; silent deletes are not acceptable.-//-// operation field:-// - "delete" — permanent removal (governance, retention sweep, evict).-// - "forget" — forget/removal flows. Scoped when emitted by-// mem::forget (user-initiated); bulk-batched when-// emitted by mem::auto-forget (automatic sweep).-// - everything else — see AuditEntry["operation"] union in src/types.ts.-//-// When adding a new deletion path, add an explicit recordAudit call-// BEFORE kv.delete(...) and match one of the two shapes above.-const AUDIT_MIGRATE_FUNCTION_ID = "mem::audit-migrate";const AUDIT_MIGRATION_COPY_CONCURRENCY = 32;const AUDIT_MIGRATION_DELETE_CONCURRENCY = 8;diff --git a/src/functions/compress-synthetic.ts b/src/functions/compress-synthetic.tsindex 0875a218..d7884e7c 100644--- a/src/functions/compress-synthetic.ts+++ b/src/functions/compress-synthetic.ts@@ -5,11 +5,6 @@ import type {} from "../types.js";import { createObservationSource } from "./observation-source.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,diff --git a/src/functions/context.ts b/src/functions/context.tsindex 3aa6f570..d712e4e4 100644--- a/src/functions/context.ts+++ b/src/functions/context.ts@@ -124,12 +124,6 @@ export function registerContextFunction(}}- // Lessons — closes the loop opened by mem::lesson-save / mem::reflect.- // Without this block, lessons sit in KV and only surface when the agent- // thinks to call memory_lesson_recall. Ranking puts project-scoped- // lessons ahead of global ones, then weights by confidence; we cap at- // 10 to keep the block bounded since the outer token-budget loop- // below will drop the whole block if it doesn't fit. #457.const relevantLessons = lessons.filter((l) => !l.deleted && (!l.project || l.project === data.project)).sort((a, b) => {diff --git a/src/functions/graph-retrieval.ts b/src/functions/graph-retrieval.tsindex 10fd51a7..dbe37bbc 100644--- a/src/functions/graph-retrieval.ts+++ b/src/functions/graph-retrieval.ts@@ -227,17 +227,6 @@ export class GraphRetrieval {return latest;}- // Weighted shortest-path traversal (#328). Replaces the prior BFS,- // which fell back to edge-count order and ignored the 0.1-1.0 weight- // attached to every graph edge. Dijkstra over `cost = 1/weight`- // (cheaper edges = stronger relationships) returns the- // highest-weighted path to each reachable node within maxDepth. Also- // tightens the perf profile:- // - Adjacency built once in O(V+E) (previous BFS re-filtered- // allEdges per visited node, O(V·E) overall).- // - Min-heap dequeue is O(log V) per pop (previous queue.shift()- // was O(n) — the dominant cost on graphs above ~200 nodes per- // the contributor's benchmark in #328).private dijkstraTraversal(startNode: GraphNode,allNodes: GraphNode[],@@ -304,9 +293,6 @@ export class GraphRetrieval {}}-// Minimal binary min-heap. Pulled inline so graph-retrieval doesn't-// take a new dependency for the perf-critical inner loop of #328.-// Comparator returns negative when `a` should pop before `b`.class MinHeap<T> {private heap: T[] = [];diff --git a/src/functions/graph.ts b/src/functions/graph.tsindex dc15e0e3..5b26530e 100644--- a/src/functions/graph.ts+++ b/src/functions/graph.ts@@ -19,20 +19,9 @@ import { recordAudit, safeAudit } from "./audit.js";import { logger } from "../logger.js";import { scrubRecord } from "./privacy.js";-// #753: keep the response payload below the iii state channel ceiling.-// 500 nodes + their incident edges hold well under the limit on the-// reported 11k-node / 28k-edge corpus, and 5,000 is the upper bound a-// caller can request explicitly. Tuned conservatively because edges-// fan out faster than nodes.const DEFAULT_GRAPH_QUERY_LIMIT = 500;const MAX_GRAPH_QUERY_LIMIT = 5000;-// #814: the precomputed snapshot covers the top-degree subgraph used by-// the empty-body / nodeType-only branch — the path the viewer hits on-// tab load. Sized to match the default query limit so the snapshot can-// service a default-cap request without falling back to live-// enumeration. Aggregate stats (nodesByType / edgesByType) are computed-// fresh during rebuild and stored alongside.const SNAPSHOT_TOP_NODES = DEFAULT_GRAPH_QUERY_LIMIT;const SNAPSHOT_KEY = "current";@@ -201,15 +190,6 @@ function paginateFromSnapshot(};}-// #814 v2: the rebuild path won't terminate on corpora large enough-// that kv.list returns a payload too big to JSON.parse without-// starving the iii heartbeat. We don't actually know the corpus size-// without enumerating, but we can refuse to start a rebuild if the-// snapshot's recorded `totalNodes` already exceeds this threshold —-// the rebuild path is unreliable above it, and an incremental-// extract-driven snapshot is the right approach for those corpora.-// Operators above the threshold should use mem::graph-reset and let-// future extracts rebuild incrementally.const REBUILD_SAFE_NODE_CEILING = 25000;function nameIndexKey(type: string, name: string): string {@@ -401,12 +381,6 @@ function paginate(};}-// Parse all key="value" pairs from a tag's attribute string, in any-// order. The previous parser hard-coded attribute order-// (type before name on <entity>, type/source/target/weight on-// <relationship>) and silently dropped nodes/edges when the upstream-// LLM emitted attributes in a different order — Codex in particular-// likes to lead with `name=` (#635).function parseAttrs(raw: string): Record<string, string> {const attrs: Record<string, string> = {};const attrRegex = /([A-Za-z_][\w:-]*)="([^"]*)"/g;@@ -428,11 +402,6 @@ function parseGraphXml(const edges: GraphEdge[] = [];const now = new Date().toISOString();- // Two passes because <entity> can be self-closing or have a body- // (<property> children). The self-closing form needs `[^>]*[^/]` on- // the attr group so the trailing `/` isn't swallowed into the match- // (root cause of #494). The explicit-close form picks up the- // property block.const entitySelfClose = /<entity\b([^>]*?)\/>/g;const entityWithBody = /<entity\b([^>]*[^/])>([\s\S]*?)<\/entity>/g;@@ -578,16 +547,6 @@ export function extractGraphHeuristics(return { nodes, edges };}-// Shared persistence for a batch of extracted/imported nodes and edges.-// Factored out of mem::graph-extract so structural importers (graphify)-// reuse the exact same name-index upsert, degree bookkeeping, and snapshot-// maintenance — which also makes re-imports idempotent: an existing-// (type, name) resolves through the name index and merges instead of-// duplicating.-// #814 v2: targeted name-index lookups replace the O(n) scan over-// `kv.list<GraphNode>(KV.graphNodes)`. At 75K nodes the list payload-// exceeds the iii heartbeat budget and the worker dies before merge can-// complete. Each name-index entry is a single small kv.get/set pair.export async function persistGraphDelta(kv: StateKV,rawNodes: GraphNode[],@@ -617,11 +576,6 @@ export async function persistGraphDelta(let existing: GraphNode | null = null;if (existingId) {existing = await kv.get<GraphNode>(KV.graphNodes, existingId);- // #825 follow-up: name-index lookups can resolve into- // pre-reset rows. Drop them so extract writes a fresh- // node + index entry instead of silently reconnecting- // to a legacy orphan (which would keep the snapshot at- // 0 forever after a reset).if (existing &&snap.resetAt &&@@ -673,7 +627,6 @@ export async function persistGraphDelta(let existing: GraphEdge | null = null;if (existingId) {existing = await kv.get<GraphEdge>(KV.graphEdges, existingId);- // Same #825 orphan check as the node path above.if (existing &&snap.resetAt &&@@ -942,12 +895,6 @@ export function registerGraphFunction(},);- // #753: every branch now applies a default cap and reports the- // unbounded `total*` counts. Before this change, an unfiltered POST- // /graph/query body (`{}`) on a corpus with ~10k+ nodes serialized- // to a payload large enough that the iii state response channel- // rejected it with HTTP 500 "Invocation stopped", leaving the viewer- // graph tab silently blank.sdk.registerFunction("mem::graph-query",async (data: {startNodeId?: string;@@ -960,13 +907,6 @@ export function registerGraphFunction(const maxDepth = Math.min(data.maxDepth || 3, 5);const { limit, offset } = resolvePagination(data.limit, data.offset);- // #814 v2: the empty-body / nodeType-only path NEVER enumerates.- // It reads the snapshot exclusively. The snapshot is updated- // inline by graph-extract, so for newly-built corpora it's- // always current. For legacy corpora missing a snapshot the- // operator must run mem::graph-snapshot-rebuild (safe under- // REBUILD_SAFE_NODE_CEILING) or mem::graph-reset to wipe and- // rebuild incrementally from new observations.const noWalk = !data.query && !data.startNodeId;if (noWalk) {const snap = await readSnapshot(kv);@@ -984,7 +924,7 @@ export function registerGraphFunction(offset,warning:"No graph snapshot available. Either no graph has been " +- "extracted yet, or you are on a legacy corpus from a pre-#814 " ++ "extracted yet, or you are on a legacy corpus from an older " +"agentmemory build. Run POST /agentmemory/graph/snapshot-rebuild " +"(safe up to ~25K nodes) or POST /agentmemory/graph/reset to " +"wipe and let future extracts repopulate.",@@ -1097,12 +1037,6 @@ export function registerGraphFunction(},);- // #814 v2: graph-stats reads the snapshot exclusively. The snapshot- // is maintained inline by mem::graph-extract, so for any corpus built- // on a post-#814 agentmemory the stats are always current without an- // enumeration. Legacy corpora without a snapshot get an empty- // envelope + a warning pointing at the snapshot-rebuild or graph-reset- // endpoints — never a 500.sdk.registerFunction("mem::graph-stats", async () => {const snap = await readSnapshot(kv);if (snap) {@@ -1132,32 +1066,10 @@ export function registerGraphFunction(};});- // #814 v2: explicit rebuild backfills the snapshot AND the name /- // edge-key / degree indexes from existing graphNodes/graphEdges- // scopes. This is the path operators run once after upgrading to a- // post-#814 build to bring legacy corpora online. It enumerates via- // kv.list — the same pair that breaks at 75K+ — so we refuse to- // run on corpora large enough that the response payload would- // block the worker heartbeat. Above the ceiling the only safe path- // is mem::graph-reset followed by incremental re-extraction.sdk.registerFunction("mem::graph-snapshot-rebuild",async (data?: { force?: boolean }) => {const started = Date.now();- // #825: pre-flight refusal for legacy corpora. The old guard- // checked node count AFTER kv.list, but the heartbeat dies at- // ~0.35s on a 75K-node response — long before the wall-clock- // budget can fire. We can't safely enumerate to discover size.- //- // Heuristic: if no snapshot exists, the corpus is either empty- // or legacy. The empty case has nothing to rebuild; the legacy- // case will crash. Refuse both unless `force: true` is passed- // (operator opt-in to attempt rebuild on a corpus they know is- // small enough — typically under 10K nodes on the default iii- // state adapter).- // Strict boolean check on force — accept only literal `true`,- // never truthy strings/numbers, so a hand-crafted JSON payload- // can't accidentally bypass the legacy-corpus safeguard.const forceRebuild = data?.force === true;try {const existing = await readSnapshot(kv);@@ -1303,27 +1215,6 @@ export function registerGraphFunction(}});- // #814 v2 + #825: clean-restart escape hatch for corpora of any- // size, including the legacy 75K+ case that crashes kv.list.- //- // Previous reset walked kv.list<GraphNode/Edge>(...) which is the- // exact primitive that heartbeat-crashes the worker on the corpus- // this reset was meant to recover (Allan's repro, 0.35s death).- //- // The new design is enumeration-free: write an empty snapshot and- // return. The hot path (mem::graph-query empty-body, mem::graph-stats)- // reads ONLY the snapshot post-#816, so a fresh empty snapshot- // makes the graph behave as if it were empty for every read.- //- // Future extracts repopulate the snapshot + side-indexes- // incrementally (graph-extract is O(1) per node post-#816 — it does- // not consult the legacy rows).- //- // Trade-off: legacy rows in KV.graphNodes / KV.graphEdges remain on- // disk as unreferenced orphans. They consume disk but are never- // read by any post-#816 code path. Cleanup is deferred to a future- // chunked-vacuum job; #816's broken vacuum-via-list strategy is- // what we are leaving behind here.sdk.registerFunction("mem::graph-reset", async () => {const started = Date.now();// Stamp resetAt=now on the empty snapshot. Futurediff --git a/src/functions/migrate-vector-index.ts b/src/functions/migrate-vector-index.tsindex 058eab84..55e58bc4 100644--- a/src/functions/migrate-vector-index.ts+++ b/src/functions/migrate-vector-index.ts@@ -12,11 +12,6 @@ export interface MigrateVectorIndexResult {failedSessions: string[];}-// Validate one embedding's shape against the provider's declared dimensions-// before pushing it into the index. Mirrors the symmetric guard in-// search.ts::vectorIndexAddGuarded — without this, a misconfigured-// provider returning the wrong-length Float32Array would silently corrupt-// the rebuilt index (per #248).function isValidEmbedding(embedding: Float32Array,provider: EmbeddingProvider,diff --git a/src/functions/obsidian-export.ts b/src/functions/obsidian-export.tsindex 06f2d28a..467eadb4 100644--- a/src/functions/obsidian-export.ts+++ b/src/functions/obsidian-export.ts@@ -27,9 +27,6 @@ function sanitize(name: string): string {return name.replace(/[<>:"/\\|?*\x00-\x1f]/g, "_").slice(0, 100);}-// #729: every record helper used to crash on null/undefined fields,-// poisoning the whole export. These helpers stay strict about types but-// return sensible fallbacks instead of throwing.function hasExportId<T extends { id?: unknown }>(item: T | null | undefined,): item is T & { id: string } {@@ -277,10 +274,6 @@ export function registerObsidianExportFunction(sessions: join(vaultDir, "sessions"),};- // Outer try/catch keeps the function from ever throwing out to the- // iii engine's HTTP serializer; #729 surfaced an unhandled- // TypeError as `{"error":"[object Object]"}`. With this guard the- // worst case is `{success: false, error: <string>}`.try {const roots = [getExportRoot()];await Promise.all(Object.values(dirs).map((dir) => mkdirConfined(dir, roots)));diff --git a/src/functions/recent-searches-sweep.ts b/src/functions/recent-searches-sweep.tsindex 3b75a7e2..52877460 100644--- a/src/functions/recent-searches-sweep.ts+++ b/src/functions/recent-searches-sweep.ts@@ -5,10 +5,6 @@ import { logger } from "../logger.js";import { getFollowupStats, type RecentSearch } from "./smart-search.js";import { getFollowupWindowSeconds } from "../config.js";-// #771: TTL sweep for the followup-rate diagnostic scope. `recentSearches`-// only needs the most recent entry per session, but stale rows accumulate-// when sessions go idle. Hourly sweep deletes rows whose last update is-// older than the retention window.const RETENTION_MS = 24 * 60 * 60 * 1000;export function registerRecentSearchesSweepFunction(@@ -48,8 +44,6 @@ export function registerRecentSearchesSweepFunction(},);- // #771: read-back surface for `agentmemory status` and external- // dashboards that don't go through the OTEL collector.sdk.registerFunction("mem::diagnostic::followup-stats",async (): Promise<{diff --git a/src/functions/remember.ts b/src/functions/remember.tsindex 0e9f5f5a..8d891637 100644--- a/src/functions/remember.ts+++ b/src/functions/remember.ts@@ -197,11 +197,6 @@ export function registerRememberFunction(sdk: IIIClient, kv: StateKV): void {}await kv.set(KV.memories, memory.id, memory);- // Without this, mem::remember persists the row but the BM25- // index never sees it, so memory_smart_search and memory_recall- // return empty even seconds after save (#257). Use try/catch so- // an indexing failure doesn't block the save itself — the- // restart-time rebuild will pick the memory up either way.try {getSearchIndex().add(memoryToObservation(memory));scheduleIndexSave();diff --git a/src/functions/retention.ts b/src/functions/retention.tsindex b718cbf5..ebe5a564 100644--- a/src/functions/retention.ts+++ b/src/functions/retention.ts@@ -325,14 +325,6 @@ 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;diff --git a/src/functions/search.ts b/src/functions/search.tsindex 8fe22e01..d157a6b4 100644--- a/src/functions/search.ts+++ b/src/functions/search.ts@@ -199,13 +199,6 @@ export function clipEmbedInput(text: string): string {return text.slice(0, EMBED_MAX_CHARS)}-// Single guarded vector-index write. Returns true on success. Logs and-// no-ops on:-// - dimension mismatch (mis-configured provider would silently corrupt-// the index per #248 otherwise — guarded at persistence load there;-// this is the symmetric guard at the write site)-// - embed throwing (network, rate limit, provider down)-// Always soft-fails so a downed embedder doesn't break the upstream save.export async function vectorIndexAddGuarded(id: string,sessionId: string,@@ -721,19 +714,6 @@ export function registerSearchFunction(sdk: IIIClient, kv: StateKV): void {}const projectFilter = typeof data.project === 'string' && data.project.trim().length > 0 ? data.project.trim() : undefinedconst cwdFilter = typeof data.cwd === 'string' && data.cwd.trim().length > 0 ? data.cwd.trim() : undefined- // #817: agent-scope isolation. mem::search backs REST /search,- // memory_recall and recall_context. Without filtering here a- // worker booted with AGENT_ID=B + AGENTMEMORY_AGENT_SCOPE=isolated- // could read A's memories — the cross-agent leak the issue- // documented. Mirrors the smart-search pattern: wildcard "*"- // bypasses, explicit agentId pins, isolated mode falls back to- // the worker's own AGENT_ID.- //- // Fail-closed: if isolated mode is on AND no explicit agentId- // is given AND env AGENT_ID is unset, refuse the call rather- // than silently dropping the filter. Allowing the call through- // with filterAgentId=undefined is the same leak this fix is- // supposed to close.const isolated = isAgentScopeIsolated();const explicitAgentId =typeof data.agentId === "string" && data.agentId.trim().length > 0@@ -894,10 +874,6 @@ export function registerSearchFunction(sdk: IIIClient, kv: StateKV): void {candidates.push(r)}- // Second pass: load observations in parallel. Fall back to- // KV.memories when the observation lookup misses — entries indexed- // via mem::remember live in the memories scope under a synthetic- // sessionId, so the observation key never exists (#265).const obsResults = await Promise.all(candidates.map(async (r) => {if (r.observation) return r.observation@@ -915,10 +891,6 @@ export function registerSearchFunction(sdk: IIIClient, kv: StateKV): void {for (let i = 0; i < candidates.length; i++) {const obs = obsResults[i]if (!obs) continue- // #817: enforce agent-scope after the observation/memory is- // loaded. The BM25 index doesn't carry agentId so the filter- // happens post-lookup. Wildcard ("*") and no-isolation paths- // resolved filterAgentId=undefined upstream and pass through.if (filterAgentId !== undefined && obs.agentId !== filterAgentId) continueif (enriched.length >= effectiveLimit) breakenriched.push({diff --git a/src/functions/slots.ts b/src/functions/slots.tsindex 3bd336fb..0d3d0cee 100644--- a/src/functions/slots.ts+++ b/src/functions/slots.ts@@ -97,8 +97,6 @@ export const DEFAULT_SLOTS: ReadonlyArray<},];-// Read merged env so values loaded from ~/.agentmemory/.env are-// honoured. process.env alone misses .env-only exports (#678).export function isSlotsEnabled(): boolean {return getEnvVar("AGENTMEMORY_SLOTS") === "true";}diff --git a/src/functions/smart-search.ts b/src/functions/smart-search.tsindex a58f8553..cd16a72e 100644--- a/src/functions/smart-search.ts+++ b/src/functions/smart-search.ts@@ -23,11 +23,6 @@ import { logger } from "../logger.js";import { withoutObservationSource } from "./observation-source.js";import { getCounters } from "../telemetry/setup.js";-// #771: smart-search followup-rate diagnostic. Stored per session as-// the most recent search payload, used to detect whether the next-// search inside the window had a disjoint result set. sessionId is-// duplicated into the row so the hourly sweep can delete by it-// (StateKV.list returns values only).export interface RecentSearch {sessionId: string;query: string;@@ -93,23 +88,10 @@ export function registerSmartSearchFunction(// roles through one server. "*" opts out of the env-default// scope and returns hits from every agent.agentId?: string;- // #771: session anchor for the followup-rate diagnostic. The- // API trigger fills this from req.body / headers; direct- // sdk.trigger callers can pass it explicitly.sessionId?: string;- // #771: marks viewer-originated searches so the diagnostic- // ignores them — only agent-initiated re-queries should count.source?: string;}) => {- // Compute the agent filter once, up front. Both the expandIds- // branch and the hybrid-search branch consult it — otherwise- // expandIds becomes a cross-agent leak (#554 follow-up).- //- // #817 follow-up: fail-closed when isolated mode is on AND no- // agent id is resolvable from any source. Silently letting- // filterAgentId fall through to `undefined` would be the same- // cross-agent leak this filter is meant to prevent.const isolated = isAgentScopeIsolated();const explicitAgentId =typeof data.agentId === "string" && data.agentId.trim().length > 0@@ -228,13 +210,6 @@ export function registerSmartSearchFunction(compact.map((r) => r.obsId),);- // #771: followup-rate diagnostic. Only fires for agent-initiated- // searches that carry a sessionId — viewer-originated searches- // (source === "viewer") and direct-sdk callers without a session- // anchor are skipped. The result-set comparison uses obsIds: a- // disjoint set under the window suggests the previous call's- // results were not used, which is our directional proxy for- // reader-failure-with-evidence.if (data.sessionId &&typeof data.sessionId === "string" &&diff --git a/src/functions/summarize.ts b/src/functions/summarize.tsindex 0ed03a24..931f67c3 100644--- a/src/functions/summarize.ts+++ b/src/functions/summarize.ts@@ -186,10 +186,6 @@ async function produceSummaryXml(return { response, mode: "chunked", chunks: chunks.length, skipped };}-// #783: many LLMs (DeepSeek, GPT variants, some Anthropic responses)-// wrap structured XML in markdown code fences or add conversational-// text before/after. Strip those wrappers before the tag regex so a-// well-formed summary doesn't get silently dropped as parse_failed.function stripXmlWrappers(raw: string): string {if (!raw) return "";let cleaned = raw.trim();@@ -275,11 +271,6 @@ export function registerSummarizeFunction(}try {- // #783: chunk-level produceSummaryXml retries internally, but- // the final merge used to parse once and bail. Wrap the- // produce-and-parse pair in the same 2-attempt loop so a- // markdown-wrapped or otherwise wrapped response gets a- // second roll-of-the-dice instead of dropping the summary.let summary: SessionSummary | null = null;let response = "";let mode = "single";diff --git a/src/hooks/pre-tool-use.ts b/src/hooks/pre-tool-use.tsindex 1aa038c4..51024e86 100644--- a/src/hooks/pre-tool-use.ts+++ b/src/hooks/pre-tool-use.ts@@ -7,20 +7,6 @@ function isSdkChildContext(payload: unknown): boolean {return (payload as { entrypoint?: unknown }).entrypoint === "sdk-ts";}-// 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";diff --git a/src/hooks/sdk-guard.ts b/src/hooks/sdk-guard.tsindex 8cc5f217..07a6f664 100644--- a/src/hooks/sdk-guard.ts+++ b/src/hooks/sdk-guard.ts@@ -1,22 +1,3 @@-/**- * Recursion guard shared by every hook script.- *- * A Claude Code session spawned via @anthropic-ai/claude-agent-sdk inherits- * the same plugin hooks as the parent CC session. If any hook script in that- * child session calls back into /agentmemory/* (e.g. Stop → /summarize →- * provider.summarize() → another child session), we get unbounded recursion- * that burns tokens and fills .claude/projects/ with ghost sessions- * (#149 follow-up; see reported loop under v0.9.1).- *- * Two signals identify a SDK-child context:- * 1. AGENTMEMORY_SDK_CHILD=1 env var — set by our agent-sdk provider- * before it spawns `query()`. Inherited by child processes.- * 2. payload.entrypoint === "sdk-ts" — CC writes this into the hook- * stdin jsonl when the session was spawned by the Agent SDK.- *- * Hook scripts must call isSdkChildContext(payload) EARLY and return- * silently when it is true.- */export function isSdkChildContext(payload: unknown): boolean {if (process.env.AGENTMEMORY_SDK_CHILD === "1") return true;if (!payload || typeof payload !== "object") return false;diff --git a/src/hooks/session-start.ts b/src/hooks/session-start.tsindex 15e09160..33e029af 100644--- a/src/hooks/session-start.ts+++ b/src/hooks/session-start.ts@@ -10,22 +10,11 @@ function isSdkChildContext(payload: unknown): boolean {return (payload as { entrypoint?: unknown }).entrypoint === "sdk-ts";}-// 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 = resolveClientSecret(REST_URL);-// When the server is unreachable a 5s timeout multiplies hard under-// concurrent fan-out (Slack bots, multi-agent harnesses) and becomes a-// positive feedback loop that OOM-kills iii-engine (#221). Cap tight on-// both paths and skip the await entirely when the response is unused.const INJECT_TIMEOUT_MS = 1500;const REGISTER_TIMEOUT_MS = 800;diff --git a/src/hooks/stop.ts b/src/hooks/stop.tsindex e392d45b..d67e54a4 100644--- a/src/hooks/stop.ts+++ b/src/hooks/stop.ts@@ -41,7 +41,6 @@ async function main() {const sessionId = ((data.session_id || data.sessionId || data.conversation_id) as string) || "unknown";- // session/end already fans out the summary server-side (#1203).fetch(`${REST_URL}/agentmemory/session/end`, {method: "POST",headers: authHeaders(),diff --git a/src/hooks/subagent-start.ts b/src/hooks/subagent-start.tsindex 3c37ca3f..3f037d9c 100644--- a/src/hooks/subagent-start.ts+++ b/src/hooks/subagent-start.ts@@ -10,10 +10,6 @@ function isSdkChildContext(payload: unknown): boolean {return (payload as { entrypoint?: unknown }).entrypoint === "sdk-ts";}-// Passive telemetry only — nothing reads the response, so the previous-// `await` was pure latency. Tightened from 2000ms to a defensive cap so a-// slow/unreachable server can't stack onto every concurrent subagent-// startup (#221).const OBSERVE_TIMEOUT_MS = 800;const EXIT_CAP_MS = 1300;diff --git a/src/index.ts b/src/index.tsindex c6e5166c..cc59d46d 100644--- a/src/index.ts+++ b/src/index.ts@@ -158,13 +158,6 @@ function hasGetMeter();}-// Top-level safety net for iii-engine invocation timeouts (issue #204).-// Under sustained write load (e.g. Claude Code hooks across many-// projects) `state::set` can occasionally exceed the SDK's 30s timeout.-// We don't want one such timeout to terminate the long-lived memory-// service — the rejection is surfaced to the relevant call site via-// .catch() where it matters; everything else is logged-and-continued.-// Throttle logs to avoid spamming on bursts.let lastUnhandledLogAt = 0;process.on("unhandledRejection", (reason) => {const now = Date.now();@@ -703,10 +696,6 @@ async function main() {insightDecayTimer.unref();}- // #771: hourly TTL sweep for the followup-rate diagnostic. The- // recent-searches scope only needs the last entry per session;- // sweeping anything older than the retention window keeps the scope- // from growing unbounded across long-lived deployments.const recentSearchesSweepTimer = setInterval(async () => {try {await sdk.trigger({diff --git a/src/logger.ts b/src/logger.tsindex 8d4ad379..4d7a0936 100644--- a/src/logger.ts+++ b/src/logger.ts@@ -1,29 +1,3 @@-// Thin logging shim for agentmemory.-//-// iii-sdk v0.11 dropped `getContext()`, which had been the source of a-// contextual logger in every function handler (`getContext().logger`).-// Migrating directly to the v0.11 OTEL-based `getLogger()` would force-// every call site to care about the OTEL Logger API shape (`emit(...)`-// with severity numbers and attributes maps). Instead, this module-// exposes a single `logger` singleton with the same `.info/.warn/.error`-// signature the old code used, so the mechanical replacement across-// 30+ function files is: drop the `getContext` import, drop the-// `const ctx = getContext();` line, and rename `ctx.logger.*` to-// `logger.*`. Nothing else changes.-//-// Output goes to stderr as `[agentmemory] <level> <msg> <json-fields>`.-// The iii-engine's `iii-exec` worker runs the agentmemory binary as a-// child process and forwards stderr into `docker logs-// agentmemory-iii-engine-1`, so these lines end up next to the engine's-// own output without needing any OTEL wiring. If we later want-// structured OTEL logs, this file is the only thing that changes.-//-// See rohitg00/agentmemory#143 follow-up — the #116 migration updated-// test mocks but left the real `getContext()` imports in place, which-// passed `npm test` (tests mock iii-sdk) and `npm run build` (tsdown-// doesn't type-check) but crashed `node dist/index.mjs` on first-// import.-type Fields = Record<string, unknown> | undefined;function fmt(level: string, msg: string, fields: Fields): string {diff --git a/src/mcp/rest-proxy.ts b/src/mcp/rest-proxy.tsindex f0f15d9f..91a67320 100644--- a/src/mcp/rest-proxy.ts+++ b/src/mcp/rest-proxy.ts@@ -67,14 +67,6 @@ function authHeader(): Record<string, string> {return secret ? { authorization: `Bearer ${secret}` } : {};}-/**- * Probes the agentmemory server's livez endpoint. Returns a Response-shaped- * object whose `ok` flag drives the proxy/local-fallback decision.- *- * Tests can swap this via {@link setLivezProbe} to avoid the real 2s- * AbortController race that destabilises mcp-standalone test runs (#449).- * Production callers should leave it on the default.- */export type LivezProbe = (url: string,timeoutMs: number,diff --git a/src/mcp/server.ts b/src/mcp/server.tsindex 395c674f..be5ad365 100644--- a/src/mcp/server.ts+++ b/src/mcp/server.ts@@ -101,10 +101,6 @@ export function registerMcpEndpoints(body: { error: "token_budget must be a positive integer" },};}- // #817: forward agentId so mem::search applies the same- // isolation filter smart-search uses. Default behavior is- // unchanged (no agentId → falls back to env AGENT_ID when- // AGENTMEMORY_AGENT_SCOPE=isolated; "*" wildcard bypasses).const recallAgentId =typeof args.agentId === "string" && args.agentId.trim().length > 0? (args.agentId as string).trim()@@ -1649,9 +1645,6 @@ export function registerMcpEndpoints(},};}- // #817: mem::search now enforces agent-scope upstream when- // AGENTMEMORY_AGENT_SCOPE=isolated, so the search half of- // this prompt is safe by default.const searchResult = await sdk.trigger({function_id: "mem::search",@@ -1659,18 +1652,6 @@ export function registerMcpEndpoints(}).catch(() => ({ results: [] }));const memories = await kv.list<Memory>(KV.memories);- // #817: also filter the memory list. recall_context's- // second source is the latest-memory feed, which leaks- // cross-agent rows when isolated mode is on. Mirror the- // search-side filter explicitly here; the upstream filter- // doesn't apply to a raw kv.list.- //- // Fail-closed: if isolated mode is on but no AGENT_ID is- // available, return an empty `relevant` array rather than- // letting every memory through. The mem::search call- // above already throws in this case, but the kv.list feed- // is a separate path that has to enforce isolation on its- // own.const isolated = isAgentScopeIsolated();const activeAgentId = isolated ? getAgentId() : undefined;const relevant =diff --git a/src/mcp/standalone.ts b/src/mcp/standalone.tsindex 46c44bf3..b173934a 100644--- a/src/mcp/standalone.ts+++ b/src/mcp/standalone.ts@@ -389,9 +389,6 @@ export async function handleToolCall(const handle = await resolveHandle();announceMode(handle);- // Tools the local InMemoryKV fallback doesn't implement: forward straight- // to the server. Local validation would otherwise raise "Unknown tool"- // (issue #234).if (!IMPLEMENTED_TOOLS.has(toolName)) {if (handle.mode === "proxy") {try {diff --git a/src/providers/_openai-shared.ts b/src/providers/_openai-shared.tsindex 09566b1a..2041b40f 100644--- a/src/providers/_openai-shared.ts+++ b/src/providers/_openai-shared.ts@@ -87,19 +87,6 @@ function v1AzureUrl(baseUrl: string, path: string): string {return url.toString();}-// Append an OpenAI-compatible route to the base URL without producing-// a doubled version segment. Three cases:-//-// 1. Empty path (just a hostname) — OpenAI default: prepend `/v1/`.-// https://api.openai.com → https://api.openai.com/v1/chat/completions-// 2. Path already ends with `/v1` — provider-documented base, treat-// it as the version anchor and append the route directly.-// https://api.deepseek.com/v1 → https://api.deepseek.com/v1/chat/completions-// (without this, we'd produce /v1/v1/chat/completions and 404. #628)-// 3. Path ends with any other versioned or path segment — provider-// uses a non-OpenAI version scheme (Zhipu /api/paas/v4, others) —-// append the route directly, no `/v1/` injected.-// https://open.bigmodel.cn/api/paas/v4 → .../v4/chat/completions (#646)function appendOpenAIRoute(baseUrl: string, route: string): string {const trimmedBase = baseUrl.replace(/\/+$/, "");const cleanRoute = route.startsWith("/") ? route : `/${route}`;diff --git a/src/providers/agent-sdk.ts b/src/providers/agent-sdk.tsindex 06d59461..9c497993 100644--- a/src/providers/agent-sdk.ts+++ b/src/providers/agent-sdk.ts@@ -1,25 +1,6 @@import { AsyncLocalStorage } from 'node:async_hooks'import type { MemoryProvider } from '../types.js'-// #781: the recursion guard used to live on `process.env.AGENTMEMORY_SDK_CHILD`-// (#181). #472 then introduced chunked summarize that runs chunks-// concurrently in the same process via Promise.all. The first chunk-// flipped the global env to "1" synchronously before its `await`, and-// every sibling chunk in the same batch immediately bailed out as a-// "child" — returning "" — so half-plus of the chunks failed to parse-// and the summarize threw `too_many_chunks_skipped: N/N`.-//-// Split the guard so each concern uses the right primitive:-//-// - **In-process** recursion guard: AsyncLocalStorage. Scoped to the-// async call tree of the SDK query, so concurrent siblings on the-// same provider instance no longer see each other's marker.-// - **Cross-process** recursion guard for hooks: still-// `process.env.AGENTMEMORY_SDK_CHILD = "1"` around the SDK call.-// Subprocesses spawned by `@anthropic-ai/claude-agent-sdk` inherit-// `process.env` at spawn time, so the hook scripts (which run as-// separate processes) still see the marker and skip their REST-// callback to /summarize. ALS does not cross process boundaries.const sdkChildContext = new AsyncLocalStorage<true>()// Module-level refcount for the process.env marker. A per-call snapshot@@ -62,14 +43,6 @@ export class AgentSDKProvider implements MemoryProvider {// summarize via Promise.all) each have their own ALS frame, so they// do not poison each other.if (sdkChildContext.getStore()) {- // We are already inside a Claude Agent SDK-spawned async call- // tree. Spawning another one would let its plugin-hook-driven- // Stop loop re-enter /agentmemory/summarize and cause unbounded- // recursion (#149 follow-up). Degrade to empty string so callers- // short-circuit. The chunk retry path in src/functions/summarize.ts- // treats "" as a parse failure but only the in-process re-entry- // path can reach this branch — legitimate concurrent siblings now- // run with their own ALS frames.return ''}diff --git a/src/providers/embedding/openai.ts b/src/providers/embedding/openai.tsindex 50344626..a048b902 100644--- a/src/providers/embedding/openai.ts+++ b/src/providers/embedding/openai.ts@@ -12,42 +12,6 @@ import { resolveDimensions } from "./_dimensions.js";const DEFAULT_MODEL = "text-embedding-3-small";-/**- * OpenAI-compatible embedding provider.- *- * Shares transport (URL builder, auth header, Azure detection) with- * the OpenAI LLM provider via `_openai-shared` (#371). Same env knobs- * pick up automatically: when `OPENAI_BASE_URL` points at an Azure- * resource (`.openai.azure.com` hostname) the embedding request uses- * Azure's `/embeddings` path with the `api-version` query param and- * `api-key` header instead of `Authorization: Bearer`.- *- * Required env vars:- * OPENAI_API_KEY — API key (fallback for OPENAI_EMBEDDING_API_KEY)- *- * Optional:- * OPENAI_BASE_URL — base URL without path (default: https://api.openai.com).- * Azure: https://<resource>.openai.azure.com/openai/deployments/<deployment>- * OPENAI_EMBEDDING_BASE_URL — embedding-specific base URL override (defaults- * to OPENAI_BASE_URL). Lets operators run- * embeddings on a separate endpoint from chat —- * e.g. local Ollama / LM Studio / llama.cpp /- * vLLM at http://localhost:1234 for unlimited- * free embeddings, while keeping chat- * completions on a rate-limited but high-quality- * hosted provider. Azure detection runs on- * whichever URL ends up selected.- * OPENAI_EMBEDDING_API_KEY — separate API key for the embedding endpoint- * (defaults to OPENAI_API_KEY). Useful when the- * embedding endpoint requires a different key- * or no key at all (set to e.g. "local" for- * endpoints that ignore Authorization).- * OPENAI_API_VERSION — Azure api-version query param (default: 2024-08-01-preview)- * OPENAI_EMBEDDING_MODEL — model name (default: text-embedding-3-small)- * OPENAI_EMBEDDING_DIMENSIONS — override reported dimensions (required for- * custom / self-hosted models not in the- * shared MODEL_DIMENSIONS table)- */export class OpenAIEmbeddingProvider implements EmbeddingProvider {readonly name = "openai";readonly dimensions: number;diff --git a/src/providers/index.ts b/src/providers/index.tsindex 0ecef149..4245e03a 100644--- a/src/providers/index.ts+++ b/src/providers/index.ts@@ -25,13 +25,6 @@ function requireEnvVar(key: string): string {return value;}-// #778: fallback providers used to inherit the primary provider's-// model name (e.g. fallback Gemini was called with `gpt-4o-mini`),-// 404'd every call, and tripped the circuit breaker — making-// FALLBACK_PROVIDERS actively worse than no fallback. Each provider-// must resolve its OWN env-driven default model. Mirrors the resolution-// in detectProvider() so primary + fallback agree on what each-// provider's default model is.function defaultModelFor(providerType: ProviderConfig["provider"]): string {switch (providerType) {case "openai":@@ -68,11 +61,6 @@ export function createFallbackProvider(for (const providerType of fallbackConfig.providers) {if (providerType === config.provider) continue;try {- // #778: resolve the fallback's OWN default model (or its env- // override) rather than copying config.model from the primary.- // Without this, FALLBACK_PROVIDERS=gemini on an OpenAI primary- // would call Gemini with `gpt-4o-mini`, get a 404 every time,- // and trip the circuit breaker.const fbConfig: ProviderConfig = {provider: providerType,model: defaultModelFor(providerType),diff --git a/src/providers/noop.ts b/src/providers/noop.tsindex 63ef083e..fb30a7ae 100644--- a/src/providers/noop.ts+++ b/src/providers/noop.ts@@ -1,12 +1,5 @@import type { MemoryProvider } from "../types.js";-/**- * Returns empty strings for every call. Used when no LLM API key is set- * AND the user has not opted into the agent-sdk fallback via- * AGENTMEMORY_ALLOW_AGENT_SDK=true. Callers (compress, summarize) must- * detect the empty result and short-circuit instead of spawning a- * provider session (#149 / Stop-hook recursion loop fix).- */export function isNoopProvider(provider: { name: string }): boolean {return provider.name === "noop" || provider.name === "resilient(noop)";}diff --git a/src/providers/openai.ts b/src/providers/openai.tsindex 31ee158e..46500cf8 100644--- a/src/providers/openai.ts+++ b/src/providers/openai.ts@@ -80,12 +80,6 @@ export class OpenAIProvider implements MemoryProvider {const body: Record<string, unknown> = {model: this.model,max_tokens: this.maxTokens,- // OpenAI API spec defines `stream` as defaulting to false, so omitting- // it should yield a JSON response. Some OpenAI-compatible proxies- // (notably 9Router < 0.4.56 — see decolua/9router#1260) default to- // text/event-stream when `stream` is absent, which crashes the- // `response.json()` call below with `Unexpected token 'd', "data: {"id"...`.- // Send it explicitly so non-spec endpoints route to non-streaming too.stream: false,messages: [{ role: "system", content: systemPrompt },@@ -96,12 +90,6 @@ export class OpenAIProvider implements MemoryProvider {body.reasoning_effort = this.reasoningEffort;}- // Bound the request via the shared fetchWithTimeout helper, which- // owns the AbortController + clearTimeout cleanup for every raw-fetch- // provider (minimax, openrouter, gemini, openrouter-embed, etc.).- // OPENAI_TIMEOUT_MS keeps its v0.9.17 meaning (OpenAI-scoped alias,- // takes precedence); when unset we fall through to- // AGENTMEMORY_LLM_TIMEOUT_MS and finally the 60s default. See #446.let response: Response;try {response = await fetchWithTimeout(@@ -138,9 +126,6 @@ export class OpenAIProvider implements MemoryProvider {if (content) {return content;}- // Fallback: some thinking models return reasoning but no content.- // DeepSeek V4 / Qwen3 / GLM / Kimi return `reasoning_content`;- // older OpenAI o-series + some compatibles return `reasoning`. #627const reasoning = message?.reasoning ?? message?.reasoning_content;if (reasoning) {return reasoning;@@ -151,11 +136,6 @@ export class OpenAIProvider implements MemoryProvider {}}-// Resolves the outbound-fetch timeout for the OpenAI LLM path.-// Precedence (preserving v0.9.17 behaviour):-// 1. OPENAI_TIMEOUT_MS — OpenAI-scoped alias (back-compat)-// 2. AGENTMEMORY_LLM_TIMEOUT_MS — global LLM/embedding timeout (#446)-// 3. 60 000 ms defaultfunction resolveTimeout(): number {const openaiRaw = getEnvVar("OPENAI_TIMEOUT_MS");const openai = parsePositiveInt(openaiRaw);diff --git a/src/state/schema.ts b/src/state/schema.tsindex 08627556..1f2365f9 100644--- a/src/state/schema.ts+++ b/src/state/schema.ts@@ -17,25 +17,7 @@ export const KV = {claudeBridge: "mem:claude-bridge",graphNodes: "mem:graph:nodes",graphEdges: "mem:graph:edges",- // #814: precomputed snapshot of the top-degree subgraph and aggregate- // type counts. Saves /graph/query and /graph/stats from a full- // kv.list enumeration over 75K+ node corpora, which exceeds the iii- // invocation timeout and surfaces as "Invocation stopped" 500s.- // Single fixed key ("current") so writes are read-modify-write under- // the same keyed mutex as graph-extract.graphSnapshot: "mem:graph:snapshot",- // #814 v2: targeted-lookup indexes so graph-extract never enumerates- // the full nodes/edges scope. Each entry is a single small kv.get,- // bounded payload — works at 75K+ nodes where kv.list would block- // the worker event loop (37MB WS frame parse blocks heartbeat,- // worker is declared dead before any Promise.race timer can fire).- // - graphNameIndex: key `${type}|${name}` -> nodeId. Replaces the- // existingNodes.find() O(n) dedup scan inside mem::graph-extract.- // - graphEdgeKey: key `${src}|${tgt}|${type}` -> edgeId. Same for- // edge dedup.- // - graphNodeDegree: key nodeId -> incident-edge count. Read /- // incremented on edge writes to maintain the snapshot top-N- // ranking without scanning all edges.graphNameIndex: "mem:graph:name-index",graphEdgeKey: "mem:graph:edge-key",graphNodeDegree: "mem:graph:node-degree",@@ -73,8 +55,6 @@ export const KV = {globalSlots: "mem:slots:global",state: "mem:state",commits: "mem:commits",- // #771: tracks the most recent smart-search call per session, used by- // the followup-rate diagnostic. Key = sessionId. TTL-swept hourly.recentSearches: "mem:recent-searches",projectSessionsIndex: "mem:idx:project-sessions",obsSessionIndex: (shard: number) => `mem:idx:obs:${shard}`,diff --git a/src/state/vector-index.ts b/src/state/vector-index.tsindex ddd79a4a..d66a14d0 100644--- a/src/state/vector-index.ts+++ b/src/state/vector-index.ts@@ -1,10 +1,3 @@-// Pass byteOffset + byteLength explicitly so the round-trip survives-// Node's Buffer pool. Buffer.from(b64, "base64") returns a slice of a-// shared 8KB pool (poolSize), and `new Float32Array(buf.buffer)` ignores-// the slice metadata — it would mint a 2048-element view over the whole-// pool. Same risk on the encode side if the input Float32Array is itself-// a sliced view. Reported as a phantom "2048 dimensions on disk" crash-// in #455 / #469 / #584 / #587.export function float32ToBase64(arr: Float32Array): string {return Buffer.from(arr.buffer, arr.byteOffset, arr.byteLength).toString("base64",diff --git a/src/telemetry/setup.ts b/src/telemetry/setup.tsindex fc55b4f5..71a0e0b5 100644--- a/src/telemetry/setup.ts+++ b/src/telemetry/setup.ts@@ -39,18 +39,7 @@ interface Counters {auditLog: Counter;snapshotCreate: Counter;governanceDelete: Counter;- // #771: smart-search follow-up proxy. Incremented when a session- // issues a second smart-search inside the configured window AND the- // new result set has zero overlap with the previous one (a- // directional signal for "the first results didn't satisfy"). Treat- // as directional, not absolute — legitimate query refinement counts- // here too.smartSearchFollowupWithinWindow: Counter;- // #771: benchmark-mode counter. Incremented by the benchmark scorer- // when judge_correct === false AND the gold-evidence-IDs are a- // subset of the retrieved-context-IDs (reader missed the answer- // despite retrieval being correct). Never incremented by core in- // live use; reserved here so dashboards keep a stable name.readerFailureWithEvidence: Counter;}diff --git a/src/triggers/api.ts b/src/triggers/api.tsindex 2c280f77..80885c8f 100644--- a/src/triggers/api.ts+++ b/src/triggers/api.ts@@ -244,7 +244,7 @@ export function buildConfigFlags() {needsLlm: true,description: "Every observation is compressed by the LLM for richer summaries (costs tokens). OFF uses zero-LLM synthetic compression.",enableHow: "Set AGENTMEMORY_AUTO_COMPRESS=true and provide an LLM key.",- docsHref: "https://github.com/rohitg00/agentmemory/issues/138",+ docsHref: "https://github.com/rohitg00/agentmemory#environment-variables",},{key: "AGENTMEMORY_INJECT_CONTEXT",@@ -255,7 +255,7 @@ export function buildConfigFlags() {needsLlm: false,description: "Hooks write recalled context into Claude Code's conversation. OFF captures in the background without injecting.",enableHow: "Set AGENTMEMORY_INJECT_CONTEXT=true and restart.",- docsHref: "https://github.com/rohitg00/agentmemory/issues/143",+ docsHref: "https://github.com/rohitg00/agentmemory#environment-variables",},];}@@ -889,10 +889,6 @@ export function registerApiTriggers(body: { error: "token_budget must be a positive integer" },};}- // #817: propagate agentId so the upstream isolation filter- // applies. Honors body.agentId (POST body), ?agentId=... query- // param, or implicit fallback to the worker's AGENT_ID when- // AGENTMEMORY_AGENT_SCOPE=isolated.const bodyAgentId =typeof body.agentId === "string" && body.agentId.trim().length > 0? (body.agentId as string).trim()@@ -1763,9 +1759,6 @@ export function registerApiTriggers(body: { error: "query or expandIds is required" },};}- // #771: route the X-Agentmemory-Source header into the payload so- // the followup-rate diagnostic can skip viewer-originated calls.- // Body wins if both are set (advanced callers explicitly override).const headers = (req.headers || {}) as Record<string, string | string[] | undefined>;const sourceHeader = headers["x-agentmemory-source"] ?? headers["X-Agentmemory-Source"];const sourceFromHeader = Array.isArray(sourceHeader) ? sourceHeader[0] : sourceHeader;@@ -1793,9 +1786,6 @@ export function registerApiTriggers(config: { api_path: "/agentmemory/smart-search", http_method: "POST" },});- // #771: read-back endpoint for the followup-rate diagnostic. Returns- // a directional signal — overcounts on legitimate query refinement —- // so help text + the CLI status line carry the same caveat.sdk.registerFunction("api::diagnostic-followup",async (req: HttpRequest): Promise<Response> => {const authErr = checkAuth(req, secret);@@ -2120,11 +2110,6 @@ export function registerApiTriggers(config: { api_path: "/agentmemory/graph/node", http_method: "GET" },});- // #814: explicit snapshot rebuild endpoint. Pays the full graph- // enumeration once and persists a top-degree subgraph + aggregate- // counts so subsequent /graph/query and /graph/stats calls skip the- // unbounded kv.list. Operator-grade endpoint exposed for the viewer- // banner action and CLI repair.sdk.registerFunction("api::graph-snapshot-rebuild",async (req: HttpRequest): Promise<Response> => {const authErr = checkAuth(req, secret);@@ -2146,10 +2131,6 @@ export function registerApiTriggers(config: { api_path: "/agentmemory/graph/snapshot-rebuild", http_method: "POST" },});- // #814 v2: clean-restart endpoint for legacy corpora too large for- // safe rebuild. Wipes graph state without touching observations, so- // recall + history stay intact while the graph rebuilds incrementally- // from new extracts (or a one-shot /graph/build replay).sdk.registerFunction("api::graph-reset",async (req: HttpRequest): Promise<Response> => {const authErr = checkAuth(req, secret);@@ -2239,10 +2220,6 @@ export function registerApiTriggers(config: { api_path: "/agentmemory/graph/extract", http_method: "POST" },});- // Backfill the knowledge graph from existing compressed observations.- // Viewer calls this when the graph is empty (#666). Iterates every- // session, collects observations that have a `title` (compressed only),- // and feeds them through `mem::graph-extract` in batches.sdk.registerFunction("api::graph-build",async (req: HttpRequest<{ batchSize?: number }>): Promise<Response> => {const authErr = checkAuth(req, secret);diff --git a/src/types.ts b/src/types.tsindex cb28e20e..02c1b520 100644--- a/src/types.ts+++ b/src/types.ts@@ -487,11 +487,6 @@ export interface GraphQueryResult {nodes: GraphNode[];edges: GraphEdge[];depth: number;- // #753: pagination + truncation signals for large graphs. `total*`- // counts reflect the full unbounded result for the given filter so- // the viewer can show "showing N of M" without re-querying. `truncated`- // is true when the default cap kicked in (operator may have wanted- // the full set but didn't ask for one).totalNodes?: number;totalEdges?: number;truncated?: boolean;@@ -499,22 +494,11 @@ export interface GraphQueryResult {// detect when the default was applied vs an explicit `limit`.limit?: number;offset?: number;- // #814: indicates the response came from the precomputed top-degree- // snapshot rather than a live kv.list enumeration. Set only on the- // empty-body / nodeType-only branch on large corpora where the- // unbounded enumeration would exceed the iii invocation timeout.fromSnapshot?: boolean;degrees?: Record<string, number>;- // #814: when the snapshot is stale or absent and the live fallback- // also failed, expose an explanatory note so the viewer can surface- // an actionable banner instead of a blank graph.warning?: string;}-// #814: persisted top-degree subgraph + aggregate counts. Stored under-// KV.graphSnapshot with a single key "current". `dirty` is set true by-// mem::graph-extract after writes and flipped false when the snapshot-// rebuild completes.export interface GraphSnapshot {version: 1;topNodes: GraphNode[];@@ -533,11 +517,6 @@ export interface GraphSnapshot {};updatedAt: string;dirty: boolean;- // #825 follow-up: ISO timestamp set by mem::graph-reset. After- // reset, mem::graph-extract treats any pre-resetAt node as an- // orphan (skip merge, write fresh) so future extracts don't- // silently reconnect to legacy rows via stale name-index entries.- // Absent / 1970 epoch = no reset has run.resetAt?: string;}@@ -990,10 +969,6 @@ 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" and probe both scopes for backwards-compat. See #124.source?: "episodic" | "semantic";score: number;salience: number;diff --git a/src/viewer/index.html b/src/viewer/index.htmlindex c09868e8..21a28844 100644--- a/src/viewer/index.html+++ b/src/viewer/index.html@@ -5,14 +5,6 @@<meta name="viewport" content="width=device-width, initial-scale=1.0"><title>agentmemory viewer</title><link rel="icon" type="image/svg+xml" href="/favicon.svg">- <!-- Removed Google Fonts <link> in #323: the viewer CSP is strict- (default-src 'none', style-src 'unsafe-inline', font-src 'self')- and external stylesheets from fonts.googleapis.com were blocked,- producing console CSP violations that some browsers (Windows- Edge in particular) escalate into broader script-execution- issues. System-font fallbacks are already declared on every- --font-* CSS variable below, so the viewer renders fine with- Georgia / system serif / system sans / system mono. --><style>:root {--bg: #F9F9F7;@@ -2078,11 +2070,6 @@if (!res.ok) {if (res.status === 401) showViewerAuthPrompt();console.warn('[viewer] API ' + (fetchOpts.method || 'GET') + ' ' + path + ' returned ' + res.status);- // Non-2xx responses resolve to null so callers can keep treating- // null as "request failed" (e.g. loadGraph's disabled/error state).- // The health endpoint opts out via readErrorBody: it intentionally- // responds 503 with a valid JSON body when status is "critical"- // (see #1019), and the dashboard badge needs that body.if (!readErrorBody) return null;try {return await res.json();diff --git a/test/agent-id-scope.test.ts b/test/agent-id-scope.test.tsindex b74e5c74..849c71fe 100644--- a/test/agent-id-scope.test.ts+++ b/test/agent-id-scope.test.ts@@ -6,7 +6,7 @@ vi.mock("../src/logger.js", () => ({// AGENT_ID scope for multi-agent memory isolation.-describe("loadAgentScope (#554)", () => {+describe("loadAgentScope", () => {const ORIG = process.env["AGENT_ID"];beforeEach(() => {vi.resetModules();@@ -43,7 +43,7 @@ describe("loadAgentScope (#554)", () => {});});-describe("mem::remember stamps agentId on the Memory (#554)", () => {+describe("mem::remember stamps agentId on the Memory", () => {const ORIG = process.env["AGENT_ID"];beforeEach(() => {vi.resetModules();@@ -214,7 +214,7 @@ describe("mem::remember stamps agentId on the Memory (#554)", () => {});});-describe("AGENTMEMORY_AGENT_SCOPE mode (#554)", () => {+describe("AGENTMEMORY_AGENT_SCOPE mode", () => {const ORIG_ID = process.env["AGENT_ID"];const ORIG_MODE = process.env["AGENTMEMORY_AGENT_SCOPE"];beforeEach(() => {diff --git a/test/agent-isolation-search.test.ts b/test/agent-isolation-search.test.tsindex 929407b5..dadf1c65 100644--- a/test/agent-isolation-search.test.ts+++ b/test/agent-isolation-search.test.ts@@ -130,7 +130,7 @@ async function seedTwoAgents(kv: ReturnType<typeof makeMockKV>) {idx.add(obsB);}-describe("mem::search agent-scope isolation (#817 follow-up)", () => {+describe("mem::search agent-scope isolation", () => {let sdk: ReturnType<typeof makeMockSdk>;let kv: ReturnType<typeof makeMockKV>;diff --git a/test/agent-sdk-provider.test.ts b/test/agent-sdk-provider.test.tsindex bab17b9f..4bf1a768 100644--- a/test/agent-sdk-provider.test.ts+++ b/test/agent-sdk-provider.test.ts@@ -1,10 +1,5 @@import { describe, it, expect, beforeEach, afterEach, vi } from "vitest";-// #781: concurrent siblings on the agent-sdk provider used to bail out-// empty because the recursion guard mutated process.env synchronously-// before the first await. With the guard scoped to AsyncLocalStorage,-// each sibling runs in its own context and receives the real SDK result.-// vi.mock is hoisted above module-scope `const`/`let`, so the factory's// closure can't safely reference non-hoisted bindings. Use vi.hoisted to// declare the mock's mutable state alongside the mock itself.@@ -37,7 +32,7 @@ vi.mock("@anthropic-ai/claude-agent-sdk", () => ({import { AgentSDKProvider } from "../src/providers/agent-sdk.js";-describe("AgentSDKProvider recursion guard (#781)", () => {+describe("AgentSDKProvider recursion guard", () => {beforeEach(() => {state.queryCalls.length = 0;state.mockResult = "<result>ok</result>";diff --git a/test/auto-compress.test.ts b/test/auto-compress.test.tsindex 13d25ce4..8069fc74 100644--- a/test/auto-compress.test.ts+++ b/test/auto-compress.test.ts@@ -72,7 +72,7 @@ function validPayload(overrides: Partial<Record<string, unknown>> = {}) {};}-describe("mem::observe auto-compress gate (#138)", () => {+describe("mem::observe auto-compress gate", () => {beforeEach(() => {// Reset module cache so observe.js re-imports config.js with the// fresh AGENTMEMORY_AUTO_COMPRESS env state. Without this, a laterdiff --git a/test/capture-filter.test.ts b/test/capture-filter.test.tsindex 6767c1a0..28869ff2 100644--- a/test/capture-filter.test.ts+++ b/test/capture-filter.test.ts@@ -20,7 +20,7 @@ describe("bareToolName", () => {});});-describe("shouldCaptureTool (#993)", () => {+describe("shouldCaptureTool", () => {const envKeys = ["AGENTMEMORY_CAPTURE_ALLOW","AGENTMEMORY_CAPTURE_DENY",diff --git a/test/claude-bridge-path.test.ts b/test/claude-bridge-path.test.tsindex f9c8f185..567f6d67 100644--- a/test/claude-bridge-path.test.ts+++ b/test/claude-bridge-path.test.ts@@ -8,7 +8,7 @@ import { loadClaudeBridgeConfig } from "../src/config.js";// where <slug> replaces every / and \ with - and KEEPS any leading -.// The memory/ subdirectory holds MEMORY.md (the index) plus per-topic// .md files — this is where Claude Code 2.x actually reads/writes.-describe("loadClaudeBridgeConfig path (#625)", () => {+describe("loadClaudeBridgeConfig path", () => {const ORIG_ENV = { ...process.env };beforeEach(() => {delete process.env["CLAUDE_MEMORY_BRIDGE"];diff --git a/test/cli-connect.test.ts b/test/cli-connect.test.tsindex ce1cc344..cc4656eb 100644--- a/test/cli-connect.test.ts+++ b/test/cli-connect.test.ts@@ -78,7 +78,7 @@ describe("agentmemory connect — dispatcher", () => {}});- it("every adapter declares a category so onboarding never needs a separate list (#872)", () => {+ it("every adapter declares a category so onboarding never needs a separate list", () => {for (const a of ADAPTERS) {expect(["native", "mcp"].includes(a.category as string),@@ -145,7 +145,7 @@ describe("agentmemory connect — claude-code adapter (mock filesystem)", () =>expect(second.kind).toBe("already-wired");});- it("install() writes env passthrough block for AGENTMEMORY_URL + AGENTMEMORY_SECRET (#375)", async () => {+ it("install() writes env passthrough block for AGENTMEMORY_URL + AGENTMEMORY_SECRET", async () => {// Remote deployments (k8s, reverse proxy) set AGENTMEMORY_URL +// AGENTMEMORY_SECRET in the shell. The wired MCP entry must honour// those via ${VAR} expansion so a single entry covers both local@@ -220,7 +220,7 @@ describe("agentmemory connect — claude-code adapter (mock filesystem)", () =>});});-describe("agentmemory connect — opencode adapter (#872)", () => {+describe("agentmemory connect — opencode adapter", () => {let tmpHome: string;let originalHome: string | undefined;let originalUserprofile: string | undefined;diff --git a/test/cli-second-instance-guard.test.ts b/test/cli-second-instance-guard.test.tsindex 3336b559..fe4d5db0 100644--- a/test/cli-second-instance-guard.test.ts+++ b/test/cli-second-instance-guard.test.ts@@ -7,7 +7,7 @@ import { readFileSync } from "node:fs";// engine restart). Two guards prevent that: unknown subcommands error instead// of falling through to the server boot, and the boot path probes livez and// refuses when a live daemon already answers on the resolved port.-describe("CLI second-instance guards (#1140)", () => {+describe("CLI second-instance guards", () => {const src = readFileSync("src/cli.ts", "utf-8");it("unknown subcommands do not fall through to the server boot", () => {diff --git a/test/consistency.test.ts b/test/consistency.test.tsindex 9e2cc53f..a8a6b119 100644--- a/test/consistency.test.ts+++ b/test/consistency.test.ts@@ -83,12 +83,7 @@ describe("Consistency checks", () => {}});- it("every host-path bind mount in docker-compose.yml is in the published files list (#136)", () => {- // Regression guard for #136: docker-compose.yml references- // ./iii-config.docker.yaml as a read-only bind mount, but the file- // was missing from the published tarball. Docker silently creates- // missing bind sources as empty directories, so the engine crashed- // with "Is a directory (os error 21)" at /app/config.yaml.+ it("every host-path bind mount in docker-compose.yml is in the published files list", () => {const compose = readText("docker-compose.yml");const pkg = JSON.parse(readText("package.json"));const files: string[] = pkg.files ?? [];diff --git a/test/context-injection.test.ts b/test/context-injection.test.tsindex d7689638..fc6a79f0 100644--- a/test/context-injection.test.ts+++ b/test/context-injection.test.ts@@ -54,7 +54,7 @@ function runHook(});}-describe("pre-tool-use hook — context injection gate (#143)", () => {+describe("pre-tool-use hook — context injection gate", () => {it("writes nothing to stdout when AGENTMEMORY_INJECT_CONTEXT is unset (default)", async () => {const payload = JSON.stringify({session_id: "ses_test",@@ -110,7 +110,7 @@ describe("pre-tool-use hook — context injection gate (#143)", () => {});});-describe("session-start hook — context injection gate (#143)", () => {+describe("session-start hook — context injection gate", () => {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 Codediff --git a/test/context-lessons.test.ts b/test/context-lessons.test.tsindex e2a93cbf..10ddc4de 100644--- a/test/context-lessons.test.ts+++ b/test/context-lessons.test.ts@@ -72,7 +72,7 @@ async function seedLesson(return lesson;}-describe("mem::context — lessons auto-injection (#457)", () => {+describe("mem::context — lessons auto-injection", () => {let kv: ReturnType<typeof mockKV>;let handler: ContextHandler;diff --git a/test/diagnostic-followup-rate.test.ts b/test/diagnostic-followup-rate.test.tsindex d747e330..aa626067 100644--- a/test/diagnostic-followup-rate.test.ts+++ b/test/diagnostic-followup-rate.test.ts@@ -85,7 +85,7 @@ function makeHit(obsId: string, sessionId = "ses_1"): HybridSearchResult {} as HybridSearchResult;}-describe("Smart-search followup-rate diagnostic (#771)", () => {+describe("Smart-search followup-rate diagnostic", () => {let sdk: any;let kv: ReturnType<typeof mockKV>;let searchResults: HybridSearchResult[];diff --git a/test/diagnostics.test.ts b/test/diagnostics.test.tsindex 1e168767..85d4494a 100644--- a/test/diagnostics.test.ts+++ b/test/diagnostics.test.ts@@ -763,7 +763,7 @@ describe("Diagnostics Functions", () => {expect(result.checks.some((c) => c.category === "summaries")).toBe(true);});- describe("defensive row-shape handling (CodeRabbit #473 review)", () => {+ describe("defensive row-shape handling", () => {it("NaN/Infinity confidence on a lesson is flagged as warn, not silently passed", async () => {await kv.set(KV.lessons, "lsn_nan", {id: "lsn_nan", content: "x", context: "", confidence: NaN,diff --git a/test/export-incremental-budget.test.ts b/test/export-incremental-budget.test.tsindex 4b47e09a..e7ac00e8 100644--- a/test/export-incremental-budget.test.ts+++ b/test/export-incremental-budget.test.ts@@ -62,7 +62,7 @@ function seedSessions(kv: ReturnType<typeof countingKV>, count: number, obsBytes}}-describe("mem::export stops assembling once the frame budget is exceeded (#1334)", () => {+describe("mem::export stops assembling once the frame budget is exceeded", () => {it("never lists observations or the graph when memories alone exceed the limit", async () => {const kv = countingKV();const sdk = mockSdk();diff --git a/test/fallback-model-resolution.test.ts b/test/fallback-model-resolution.test.tsindex 779d4b68..987c9e3d 100644--- a/test/fallback-model-resolution.test.ts+++ b/test/fallback-model-resolution.test.ts@@ -1,9 +1,5 @@import { describe, it, expect, beforeEach, afterEach, vi } from "vitest";-// #778: fallback providers used to inherit the primary provider's-// model name and 404 on every call. Each fallback must resolve its-// own env-driven default model.-const captured: Array<{ provider: string; model: string }> = [];vi.mock("../src/providers/openai.js", () => ({@@ -72,7 +68,7 @@ vi.mock("../src/providers/minimax.js", () => ({import { createFallbackProvider } from "../src/providers/index.js";import type { ProviderConfig, FallbackConfig } from "../src/types.js";-describe("Fallback provider model resolution (#778)", () => {+describe("Fallback provider model resolution", () => {const savedEnv: Record<string, string | undefined> = {};const envKeys = ["OPENAI_API_KEY",diff --git a/test/fetch-timeout.test.ts b/test/fetch-timeout.test.tsindex f4a42867..1240e760 100644--- a/test/fetch-timeout.test.ts+++ b/test/fetch-timeout.test.ts@@ -432,15 +432,7 @@ describe("Provider hang regression — OpenRouterEmbeddingProvider", () => {});});-// ─────────────────────────────────────────────────────────────-// #446 — OpenAI LLM provider env-var precedence-//-// v0.9.17 shipped OPENAI_TIMEOUT_MS (OpenAI-scoped). PR #379 then-// shipped AGENTMEMORY_LLM_TIMEOUT_MS (shared). The provider now-// honours both: OPENAI_TIMEOUT_MS wins for back-compat, with-// AGENTMEMORY_LLM_TIMEOUT_MS as the global fall-back.-// ─────────────────────────────────────────────────────────────-describe("OpenAIProvider timeout env precedence (#446)", () => {+describe("OpenAIProvider timeout env precedence", () => {beforeEach(() => {delete process.env["OPENAI_TIMEOUT_MS"];delete process.env["AGENTMEMORY_LLM_TIMEOUT_MS"];@@ -511,13 +503,7 @@ describe("OpenAIProvider timeout env precedence (#446)", () => {});});-// ─────────────────────────────────────────────────────────────-// #627 — OpenAI provider must read message.reasoning_content-// DeepSeek V4 / Qwen3 / GLM / Kimi return reasoning_content (with-// underscore); only checking `reasoning` left thinking-model output-// dropped on the floor and tripped the compress circuit breaker.-// ─────────────────────────────────────────────────────────────-describe("OpenAIProvider thinking-model fallback (#627)", () => {+describe("OpenAIProvider thinking-model fallback", () => {beforeEach(() => {delete process.env["OPENAI_TIMEOUT_MS"];delete process.env["AGENTMEMORY_LLM_TIMEOUT_MS"];diff --git a/test/governance.test.ts b/test/governance.test.tsindex 43c622aa..b1efd21a 100644--- a/test/governance.test.ts+++ b/test/governance.test.ts@@ -257,7 +257,7 @@ describe("Governance Functions", () => {});});-describe("governance deletes count only what was really deleted (#1427, #1428)", () => {+describe("governance deletes count only what was really deleted", () => {let sdk: ReturnType<typeof mockSdk>;let kv: ReturnType<typeof mockKV>;diff --git a/test/graph-retrieval.test.ts b/test/graph-retrieval.test.tsindex 2eb3f923..9c469905 100644--- a/test/graph-retrieval.test.ts+++ b/test/graph-retrieval.test.ts@@ -184,12 +184,7 @@ describe("GraphRetrieval", () => {expect(directScore).toBeGreaterThan(indirectScore);});- // Dijkstra path selection (#328). The BFS implementation this- // replaced visited a node via its first-discovered path regardless- // of edge weight. Dijkstra picks the highest-weight (lowest- // 1/weight cost) path, so a one-hop weak edge no longer beats a- // two-hop chain of strong edges to the same node.- it("picks the weight-optimal path under Dijkstra, not the edge-count-shortest one (#328)", async () => {+ it("picks the weight-optimal path under Dijkstra, not the edge-count-shortest one", async () => {const nodes = [makeNode("n1", "Start", "concept", ["obs_start"]),makeNode("n2", "Mid", "concept", ["obs_mid"]),@@ -251,14 +246,7 @@ describe("GraphRetrieval", () => {expect(Number.isFinite(weak!.score)).toBe(true);});- it("scores startNode observations at 1.0 via the fallback path, not 0.5 via the path-scoring loop (#328 review)", async () => {- // Regression for a bug surfaced by inline review on #463: if the- // traversal includes a length-1 path for the startNode itself,- // the generic path-scoring loop in searchByEntities computes- // avgWeight=0.5 (empty edgeWeights → fallback) and pathLength=1,- // yielding score=0.5, then marks the obs as visited. The- // dedicated score=1.0 fallback loop for startNode obs is then- // skipped via the visitedObs guard — dead code.+ it("scores startNode observations at 1.0 via the fallback path, not 0.5 via the path-scoring loop", async () => {const nodes = [makeNode("n1", "React", "library", ["obs_root"]),makeNode("n2", "Hook", "concept", ["obs_neighbor"]),diff --git a/test/graph.test.ts b/test/graph.test.tsindex 176f63ba..d3c26313 100644--- a/test/graph.test.ts+++ b/test/graph.test.ts@@ -142,7 +142,7 @@ describe("Graph Functions", () => {expect(edges[0].type).toBe("uses");});- it("graph-extract tolerates reordered attributes (#635)", async () => {+ it("graph-extract tolerates reordered attributes", async () => {// Codex CLI's LLM tends to emit attribute order name→type and// source→target→type rather than the hard-coded type-first /// type/source/target/weight sequence the old parser required.@@ -225,12 +225,6 @@ describe("Graph Functions", () => {expect(result.error).toContain("No observations");});- // #753: an unbounded {} body used to materialize every node+edge in- // one payload, which exceeded the iii state response channel on- // large corpora (11k+ nodes) and returned HTTP 500 "Invocation- // stopped". The fix caps the page at DEFAULT_GRAPH_QUERY_LIMIT (500)- // and surfaces totalNodes / totalEdges so callers know it was- // truncated.it("caps an unbounded graph-query body to a default page and reports totals", async () => {// Seed a graph with more nodes than the default page size.const NODE_COUNT = 1200;@@ -262,8 +256,6 @@ describe("Graph Functions", () => {await kv.set("mem:graph:edges", edge.id, edge);}- // Post-#814 the empty-body path reads the snapshot exclusively.- // Backfill the snapshot from the seeded data first.await sdk.trigger("mem::graph-snapshot-rebuild", { force: true });const unbounded = (await sdk.trigger(@@ -399,10 +391,7 @@ describe("Graph Functions", () => {expect(page.totalEdges).toBe(11);});- // #814: precomputed snapshot path. The viewer-tab default-cap query- // and graph-stats both have to work at 75K-node scale where the- // full kv.list enumeration exceeds the iii invocation budget.- describe("snapshot cache (#814)", () => {+ describe("snapshot cache", () => {async function seed(nodeCount: number, edgeCount: number) {for (let i = 0; i < nodeCount; i++) {await kv.set("mem:graph:nodes", `n_${i}`, {@@ -504,9 +493,6 @@ describe("Graph Functions", () => {});it("graph-extract updates snapshot inline (no kv.list, dirty stays false)", async () => {- // Post-#814 v2 the snapshot is updated incrementally on every- // extract — no dirty flag bounces. Test asserts that after an- // extract the snapshot reflects the new nodes/edges.await sdk.trigger("mem::graph-extract", { observations: [testObs] });const snap = await kv.get<{@@ -540,8 +526,6 @@ describe("Graph Functions", () => {});it("graph-stats returns empty envelope + warning when no snapshot exists", async () => {- // Seed nodes but never rebuild the snapshot — simulates a legacy- // corpus on a post-#814 upgrade.await seed(5, 5);const stats = (await sdk.trigger("mem::graph-stats", {})) as {@@ -569,7 +553,7 @@ describe("Graph Functions", () => {expect(snap?.stats.totalNodes).toBe(0);});- it("graph-reset writes empty snapshot; legacy rows stay as orphans (#825)", async () => {+ it("graph-reset writes empty snapshot; legacy rows stay as orphans", async () => {await sdk.trigger("mem::graph-extract", { observations: [testObs] });// Index entries exist after the extract.const nameBefore = await kv.get(@@ -580,11 +564,6 @@ describe("Graph Functions", () => {await sdk.trigger("mem::graph-reset", {});- // Post-#825: reset is enumeration-free. It writes an empty- // snapshot; the legacy index rows remain on disk as orphans- // but are never read by any post-#816 code path (hot path- // reads only the snapshot, which is now empty). Asserting the- // visible behavior: snapshot empty, hot path returns empty.const snap = await kv.get<{stats: { totalNodes: number; totalEdges: number };}>("mem:graph:snapshot", "current");@@ -597,7 +576,7 @@ describe("Graph Functions", () => {// the oversized-corpus rebuild refusal. The hot path never enumerates// any more, but the rebuild endpoint AND the BFS / query branches// still call kv.list — both need explicit failure-mode tests.- describe("snapshot write must not fail open (#1381)", () => {+ describe("snapshot write must not fail open", () => {async function seedSnapshot(totalNodes: number) {await kv.set("mem:graph:snapshot", "current", {version: 1,@@ -687,7 +666,7 @@ describe("Graph Functions", () => {});});- describe("snapshot-reported total floor (#1382)", () => {+ describe("snapshot-reported total floor", () => {function seedSnapshot(stats: { totalNodes: number; nodesByType: Record<string, number> },topNodeCount: number,@@ -752,7 +731,7 @@ describe("Graph Functions", () => {});});- describe("budget + tooLarge guards (#814 v2)", () => {+ describe("budget + tooLarge guards", () => {function slowKV(delayMs: number) {const base = mockKV();return {@@ -847,12 +826,8 @@ describe("Graph Functions", () => {expect(result.totalNodes).toBeGreaterThanOrEqual(25001);});- // #825: new pre-flight refusal when no snapshot exists (signals- // legacy corpus that would crash on kv.list). force=true bypasses.it("graph-snapshot-rebuild refuses on legacy corpus (no snapshot) without force", async () => {const localKv = mockKV();- // Seed nodes but never persist a snapshot → simulates a corpus- // built on a pre-#814 agentmemory.await localKv.set("mem:graph:nodes", "legacy_n", {id: "legacy_n",type: "concept",diff --git a/test/health-thresholds.test.ts b/test/health-thresholds.test.tsindex bdbe5d53..e41708ac 100644--- a/test/health-thresholds.test.ts+++ b/test/health-thresholds.test.ts@@ -18,7 +18,7 @@ function snap(over: Partial<HealthSnapshot> = {}): HealthSnapshot {}describe("evaluateHealth memory severity", () => {- it("stays healthy when heap fills a tiny steady-state process (issue #158)", () => {+ it("stays healthy when heap fills a tiny steady-state process", () => {const s = snap({memory: {heapUsed: 45 * 1024 * 1024,@@ -35,7 +35,7 @@ describe("evaluateHealth memory severity", () => {expect(notes.find((n) => n.startsWith("memory_heap_tight_"))).toBeDefined();});- it("measures heap against the V8 limit, not the allocated heap (#1406)", () => {+ it("measures heap against the V8 limit, not the allocated heap", () => {const mb = 1024 * 1024;const reported = snap({memory: { heapUsed: 589 * mb, heapTotal: 629 * mb, heapLimit: 4144 * mb, rss: 923 * mb, external: 0 },diff --git a/test/hybrid-search.test.ts b/test/hybrid-search.test.tsindex 811247ac..4d921fd1 100644--- a/test/hybrid-search.test.ts+++ b/test/hybrid-search.test.ts@@ -143,7 +143,7 @@ describe("HybridSearch", () => {expect(results).toEqual([]);});- it("falls back to KV.memories when an indexed entry is a saved memory (#265)", async () => {+ it("falls back to KV.memories when an indexed entry is a saved memory", async () => {// mem::remember writes to KV.memories under the synthetic sessionId// "memory" — the BM25 index sees that synthetic sessionId, but// KV.observations("memory") never has anything.diff --git a/test/mcp-standalone-proxy.test.ts b/test/mcp-standalone-proxy.test.tsindex 8b0aee6c..fa0dbcf5 100644--- a/test/mcp-standalone-proxy.test.ts+++ b/test/mcp-standalone-proxy.test.ts@@ -15,7 +15,7 @@ function installFetch(handler: (url: string, init?: RequestInit) => Response): Fconst BASE = "http://localhost:3111";-describe("@agentmemory/mcp standalone — server proxy (issue #159)", () => {+describe("@agentmemory/mcp standalone — server proxy", () => {const originalFetch = globalThis.fetch;beforeEach(() => {@@ -75,7 +75,7 @@ describe("@agentmemory/mcp standalone — server proxy (issue #159)", () => {expect(body.results[0].id).toBe("m1");});- it("proxies memory_recall to POST /agentmemory/search and forwards format/token_budget (#507)", async () => {+ it("proxies memory_recall to POST /agentmemory/search and forwards format/token_budget", async () => {const calls: Array<{ url: string; body?: unknown }> = [];installFetch((url, init) => {if (url.endsWith("/agentmemory/livez")) return new Response("ok", { status: 200 });@@ -115,7 +115,7 @@ describe("@agentmemory/mcp standalone — server proxy (issue #159)", () => {expect(calls.find((c) => c.url.endsWith("/agentmemory/smart-search"))).toBeUndefined();});- it("memory_recall defaults format to 'full' when omitted (#507)", async () => {+ it("memory_recall defaults format to 'full' when omitted", async () => {let recallBody: Record<string, unknown> | undefined;installFetch((url, init) => {if (url.endsWith("/agentmemory/livez")) return new Response("ok", { status: 200 });@@ -269,7 +269,7 @@ describe("@agentmemory/mcp standalone — server proxy (issue #159)", () => {expect(probeCount).toBe(1);});- it("forwards non-essential tools to /agentmemory/mcp/call (#234)", async () => {+ it("forwards non-essential tools to /agentmemory/mcp/call", async () => {const calls: Array<{ url: string; body?: unknown }> = [];installFetch((url, init) => {if (url.endsWith("/agentmemory/livez")) {@@ -306,7 +306,7 @@ describe("@agentmemory/mcp standalone — server proxy (issue #159)", () => {});});- it("rejects non-essential tools when no server is reachable (#234)", async () => {+ it("rejects non-essential tools when no server is reachable", async () => {installFetch(() => {throw new Error("ECONNREFUSED");});@@ -380,7 +380,7 @@ describe("@agentmemory/mcp standalone — server proxy (issue #159)", () => {expect(joined).toMatch(/AGENTMEMORY_FORCE_PROXY/);});- it("local fallback tools/list returns all 7 IMPLEMENTED_TOOLS regardless of AGENTMEMORY_TOOLS env (#234)", async () => {+ it("local fallback tools/list returns all 7 IMPLEMENTED_TOOLS regardless of AGENTMEMORY_TOOLS env", async () => {const { handleToolsList } = await import("../src/mcp/standalone.js");installFetch(() => {throw new Error("ECONNREFUSED");diff --git a/test/mcp-standalone.test.ts b/test/mcp-standalone.test.tsindex 3dcc80ae..7c0c128e 100644--- a/test/mcp-standalone.test.ts+++ b/test/mcp-standalone.test.ts@@ -33,12 +33,6 @@ import {} from "../src/mcp/rest-proxy.js";import { writeFileSync } from "node:fs";-// Issue #449: hard-coded fetch() against :3111 in the livez probe was racing-// with vitest's mock setup, making this file the "10-11 pre-existing failures"-// referenced in the last 5 release notes. Stub the probe with an instant-// ok:false response so the shim takes the deterministic InMemoryKV fallback-// path on every test. Guard the real network with a fetch trap so any-// regression that bypasses the DI seam fails loudly instead of timing out.const instantLocalFallbackProbe = vi.fn(async () => ({ok: false,status: 0,@@ -163,7 +157,7 @@ describe("handleToolCall", () => {resetHandleForTests();});- it("livez probe stub is invoked instead of the real fetch (issue #449)", async () => {+ it("livez probe stub is invoked instead of the real fetch", async () => {const kv = new InMemoryKV();await handleToolCall("memory_save", { content: "regression guard" }, kv);expect(instantLocalFallbackProbe).toHaveBeenCalledTimes(1);@@ -223,7 +217,7 @@ describe("handleToolCall", () => {expect(parsed.results[0].content).toBe("TypeScript is great");});- it("memory_save accepts concepts/files as arrays (plugin skill format, #139)", async () => {+ it("memory_save accepts concepts/files as arrays (plugin skill format)", async () => {const kv = new InMemoryKV();const result = await handleToolCall("memory_save",@@ -263,7 +257,7 @@ describe("handleToolCall", () => {expect(mem?.files).toEqual(["src/auth.ts"]);});- it("memory_smart_search falls back to substring match in the standalone shim (#139)", async () => {+ it("memory_smart_search falls back to substring match in the standalone shim", async () => {const kv = new InMemoryKV();await handleToolCall("memory_save",@@ -285,7 +279,7 @@ describe("handleToolCall", () => {expect(parsed.results[0].content).toBe("Use bcrypt for password hashing");});- it("memory_smart_search rejects empty query to prevent match-all in forget flow (#139)", async () => {+ it("memory_smart_search rejects empty query to prevent match-all in forget flow", async () => {const kv = new InMemoryKV();await handleToolCall("memory_save", { content: "anything" }, kv);await expect(@@ -299,7 +293,7 @@ describe("handleToolCall", () => {).rejects.toThrow("query is required");});- it("memory_smart_search searches files and concepts, not just title/content (#139)", async () => {+ it("memory_smart_search searches files and concepts, not just title/content", async () => {const kv = new InMemoryKV();await handleToolCall("memory_save",@@ -338,7 +332,7 @@ describe("handleToolCall", () => {expect(byConcept.results).toHaveLength(1);});- it("memory_sessions honours the limit arg (#139)", async () => {+ it("memory_sessions honours the limit arg", async () => {const kv = new InMemoryKV();for (let i = 0; i < 5; i++) {await kv.set("mem:sessions", `ses_${i}`, {@@ -381,7 +375,7 @@ describe("handleToolCall", () => {expect(JSON.parse(huge.content[0].text).results).toHaveLength(100);});- it("memory_governance_delete removes memories by id array (#139)", async () => {+ it("memory_governance_delete removes memories by id array", async () => {const kv = new InMemoryKV();const a = JSON.parse((await handleToolCall("memory_save", { content: "one" }, kv)).content[0]diff --git a/test/mcp-surface-default.test.ts b/test/mcp-surface-default.test.tsindex 161d2f42..cb26cd27 100644--- a/test/mcp-surface-default.test.ts+++ b/test/mcp-surface-default.test.ts@@ -10,7 +10,7 @@ import {// at 8 essentials with no indication the other 46 existed. Default// flipped to "all"; the lean set is still accessible via// AGENTMEMORY_TOOLS=core.-describe("MCP tool surface default (#553)", () => {+describe("MCP tool surface default", () => {const ORIG = process.env["AGENTMEMORY_TOOLS"];beforeEach(() => {delete process.env["AGENTMEMORY_TOOLS"];@@ -50,7 +50,7 @@ describe("MCP tool surface default (#553)", () => {}});- it("plugin .mcp.json provides default env interpolation so CC parse never fails (#510)", () => {+ it("plugin .mcp.json provides default env interpolation so CC parse never fails", () => {const raw = readFileSync("plugin/.mcp.json", "utf-8");const cfg = JSON.parse(raw) as {mcpServers: { agentmemory: { env: Record<string, string> } };diff --git a/test/mcp-transport.test.ts b/test/mcp-transport.test.tsindex 006ecc9e..f7369601 100644--- a/test/mcp-transport.test.ts+++ b/test/mcp-transport.test.ts@@ -55,7 +55,7 @@ describe("processLine — request path", () => {});});-describe("processLine — notification path (#129)", () => {+describe("processLine — notification path", () => {it("does NOT emit a response for a notification (no id field)", async () => {const c = collector();const handlerCalled = vi.fn(async () => ({ shouldNotEscape: true }));diff --git a/test/memories-pagination.test.ts b/test/memories-pagination.test.tsindex de05d1d7..b5f151b0 100644--- a/test/memories-pagination.test.ts+++ b/test/memories-pagination.test.ts@@ -4,12 +4,11 @@ import { readFileSync } from "node:fs";// /memories and /export must support count + pagination so the// viewer and `agentmemory status` work on large corpora (8K+ memories)// without timing out at the iii engine boundary.-describe("memories + export pagination (#544)", () => {+describe("memories + export pagination", () => {const api = readFileSync("src/triggers/api.ts", "utf-8");it("api::memories accepts count=true and returns total + latestCount", () => {expect(api).toMatch(/req\.query_params\?\.\["count"\]\s*===\s*"true"/);- // count must report the SAME scope as the list path (#554 follow-up).expect(api).toMatch(/total:\s*filtered\.length/);expect(api).toMatch(/latestCount:\s*filtered\.filter/);});diff --git a/test/minimax-provider.test.ts b/test/minimax-provider.test.tsindex d3f002f3..47eb297d 100644--- a/test/minimax-provider.test.ts+++ b/test/minimax-provider.test.ts@@ -1,7 +1,7 @@import { describe, expect, it, afterEach } from "vitest";import { MinimaxProvider } from "../src/providers/minimax.js";-describe("MinimaxProvider — base URL resolution (#285)", () => {+describe("MinimaxProvider — base URL resolution", () => {const originalEnv = process.env["MINIMAX_BASE_URL"];afterEach(() => {diff --git a/test/multi-instance-port.test.ts b/test/multi-instance-port.test.tsindex 8c872326..20c8767b 100644--- a/test/multi-instance-port.test.ts+++ b/test/multi-instance-port.test.ts@@ -10,7 +10,7 @@ const PORT_ENVS = ["III_ENGINE_URL",] as const;-describe("multi-instance port auto-derive (#750)", () => {+describe("multi-instance port auto-derive", () => {const saved: Record<string, string | undefined> = {};beforeEach(() => {diff --git a/test/observe-dedup-prompt.test.ts b/test/observe-dedup-prompt.test.tsindex 0b12485f..a6949b70 100644--- a/test/observe-dedup-prompt.test.ts+++ b/test/observe-dedup-prompt.test.ts@@ -16,7 +16,7 @@ function observePayload(hookType: string, data: unknown) {};}-describe("observe dedup for hooks without tool_input (#1173)", () => {+describe("observe dedup for hooks without tool_input", () => {beforeEach(() => {vi.resetModules();});diff --git a/test/observe-implicit-session.test.ts b/test/observe-implicit-session.test.tsindex b0272bc7..c83a3fbf 100644--- a/test/observe-implicit-session.test.ts+++ b/test/observe-implicit-session.test.ts@@ -56,7 +56,7 @@ function mockSdk() {};}-describe("observe implicit session create (#638)", () => {+describe("observe implicit session create", () => {beforeEach(() => {vi.resetModules();});diff --git a/test/obsidian-export.test.ts b/test/obsidian-export.test.tsindex ba3d5142..87bedffa 100644--- a/test/obsidian-export.test.ts+++ b/test/obsidian-export.test.ts@@ -320,11 +320,6 @@ describe("Obsidian Export", () => {expect(result.errors).toBeUndefined();});- // #729: any record missing an id used to crash `sanitize(undefined.id)`- // outside the per-record try, escaping the handler entirely and- // returning HTTP 500 `{"error":"[object Object]"}` with zero files- // written. The hardened loops filter id-less records and the outer- // try/catch keeps thrown errors from ever reaching the HTTP serializer.it("skips records that are missing an id and keeps exporting the rest", async () => {await kv.set("mem:memories", "orphan-memory", { ...makeMemory("mem_missing"), id: undefined } as any);await kv.set("mem:lessons", "orphan-lesson", { ...makeLesson("lsn_missing"), id: undefined } as any);diff --git a/test/openai-shared.test.ts b/test/openai-shared.test.tsindex e3714c63..51e2942f 100644--- a/test/openai-shared.test.ts+++ b/test/openai-shared.test.ts@@ -150,8 +150,8 @@ describe("_openai-shared — buildEmbeddingUrl", () => {});});-describe("_openai-shared — non-OpenAI base URLs (#628, #646)", () => {- it("does not double /v1 when base URL already ends with /v1 (DeepSeek shape, #628)", () => {+describe("_openai-shared — non-OpenAI base URLs", () => {+ it("does not double /v1 when base URL already ends with /v1 (DeepSeek shape)", () => {expect(buildChatUrl("https://api.deepseek.com/v1", false, "2024-08-01-preview"),).toBe("https://api.deepseek.com/v1/chat/completions");@@ -160,7 +160,7 @@ describe("_openai-shared — non-OpenAI base URLs (#628, #646)", () => {).toBe("https://api.deepseek.com/v1/embeddings");});- it("does not inject /v1 when provider uses non-OpenAI version segment (Zhipu /api/paas/v4, #646)", () => {+ it("does not inject /v1 when provider uses non-OpenAI version segment (Zhipu /api/paas/v4)", () => {expect(buildChatUrl("https://open.bigmodel.cn/api/paas/v4",@@ -228,13 +228,7 @@ describe("_openai-shared — normalizeBaseUrl", () => {});});-// ─────────────────────────────────────────────────────────────-// OpenAIEmbeddingProvider — Azure transport (#371)-// Verifies the embedding path now uses the shared Azure helpers:-// hits /embeddings (not /v1/embeddings), includes api-version, uses-// api-key header instead of Authorization: Bearer.-// ─────────────────────────────────────────────────────────────-describe("OpenAIEmbeddingProvider — Azure auto-detection (#371)", () => {+describe("OpenAIEmbeddingProvider — Azure auto-detection", () => {const ORIGINAL_BASE = process.env["OPENAI_BASE_URL"];const ORIGINAL_VERSION = process.env["OPENAI_API_VERSION"];diff --git a/test/openclaw-plugin.test.ts b/test/openclaw-plugin.test.tsindex ed95d493..7313218b 100644--- a/test/openclaw-plugin.test.ts+++ b/test/openclaw-plugin.test.ts@@ -25,7 +25,7 @@ function makeApi(overrides: Partial<FakeApi> = {}): FakeApi {};}-describe("openclaw plugin — memory capability registration (closes #286 follow-up)", () => {+describe("openclaw plugin — memory capability registration", () => {it("calls api.registerMemoryCapability with a promptBuilder when the host supports it", async () => {const mod = await import("../integrations/openclaw/plugin.mjs");const plugin = (mod as unknown as { default: { register(api: FakeApi): void } }).default;diff --git a/test/opencode-auto-context.test.ts b/test/opencode-auto-context.test.tsindex dd59b041..3faa1d1e 100644--- a/test/opencode-auto-context.test.ts+++ b/test/opencode-auto-context.test.ts@@ -6,7 +6,7 @@ import { readFileSync } from "node:fs";// the /session/start context through a cache so injection happens// without a second /context fetch and is documented as the// SessionStart-equivalent behaviour.-describe("OpenCode plugin auto-context injection (#431)", () => {+describe("OpenCode plugin auto-context injection", () => {const plugin = readFileSync("plugin/opencode/agentmemory-capture.ts","utf-8",diff --git a/test/post-tool-use-capture.test.ts b/test/post-tool-use-capture.test.tsindex a4e48302..e4665934 100644--- a/test/post-tool-use-capture.test.ts+++ b/test/post-tool-use-capture.test.ts@@ -25,7 +25,7 @@ function runHook(});}-describe("post-tool-use hook — capture filter (#993)", () => {+describe("post-tool-use hook — capture filter", () => {let server: Server;let observeCalls = 0;let port = 0;diff --git a/test/remember-bm25-index.test.ts b/test/remember-bm25-index.test.tsindex 77ee8d12..2385ec7b 100644--- a/test/remember-bm25-index.test.ts+++ b/test/remember-bm25-index.test.ts@@ -50,7 +50,7 @@ describe("SearchIndex.has()", () => {});});-describe("memory indexing into SearchIndex (closes #257)", () => {+describe("memory indexing into SearchIndex", () => {it("makes a saved memory findable by keyword search", () => {const idx = new SearchIndex();idx.add(memoryAsIndexable(makeMemory({@@ -66,8 +66,6 @@ describe("memory indexing into SearchIndex (closes #257)", () => {});it("returns the memory when the issue's reproduction query is run", () => {- // From issue #257: user saved a memory containing 'BM25 test'- // keywords and the search returned empty — recall failure.const idx = new SearchIndex();idx.add(memoryAsIndexable(makeMemory({id: "mem_moy3u6ua_8c6962b668e7",diff --git a/test/remember-forget-audit.test.ts b/test/remember-forget-audit.test.tsindex 09d5e434..848391a4 100644--- a/test/remember-forget-audit.test.ts+++ b/test/remember-forget-audit.test.ts@@ -55,7 +55,7 @@ function mockSdk() {};}-describe("mem::forget audit coverage (issue #125)", () => {+describe("mem::forget audit coverage", () => {it("emits a single audit row when a memory is forgotten", async () => {const sdk = mockSdk();const kv = mockKV();@@ -127,9 +127,6 @@ describe("mem::forget audit coverage (issue #125)", () => {expect(auditRows).toHaveLength(0);});- // Regression coverage for issue #1120: mem::forget must not report a- // deletion for ids it never touches (e.g. lesson ids live in KV.lessons,- // not KV.memories).it("returns deleted: 0 for a nonexistent memoryId (lesson id)", async () => {const sdk = mockSdk();const kv = mockKV();@@ -303,7 +300,7 @@ describe("mem::forget search-index cleanup", () => {});});-describe("mem::forget counts only records that were really deleted (#1428)", () => {+describe("mem::forget counts only records that were really deleted", () => {type ForgetResult = {success: boolean;deleted: number;diff --git a/test/replay-import-key.test.ts b/test/replay-import-key.test.tsindex 4d238e1a..a7c97a41 100644--- a/test/replay-import-key.test.ts+++ b/test/replay-import-key.test.ts@@ -64,7 +64,7 @@ function mockSdk(kv: ReturnType<typeof mockKV>) {} as any;}-describe("import-jsonl re-key on parsed.sessionId (#775)", () => {+describe("import-jsonl re-key on parsed.sessionId", () => {let tmpRoot: string;beforeEach(() => {diff --git a/test/retention-access.test.ts b/test/retention-access.test.tsindex f6e28f71..1d43a9c0 100644--- a/test/retention-access.test.ts+++ b/test/retention-access.test.ts@@ -100,7 +100,7 @@ function makeSemantic(};}-describe("RetentionScoring with access log (issue #119)", () => {+describe("RetentionScoring with access log", () => {it("episodic memories with recorded reads get higher reinforcementBoost than untouched ones", async () => {const { registerRetentionFunctions } = await import("../src/functions/retention.js"diff --git a/test/retention.test.ts b/test/retention.test.tsindex d71112e4..04677334 100644--- a/test/retention.test.ts+++ b/test/retention.test.ts@@ -264,7 +264,7 @@ describe("RetentionScoring", () => {expect(sem1.score).toBeGreaterThan(sem2.score);});- it("scores tag rows with their source scope (#124)", async () => {+ it("scores tag rows with their source scope", async () => {const { registerRetentionFunctions } = await import("../src/functions/retention.js");@@ -297,15 +297,11 @@ describe("RetentionScoring", () => {expect(semStored).toMatchObject({ source: "semantic" });});- it("mem::retention-evict deletes semantic memories from mem:semantic, not mem:memories (#124)", async () => {+ it("mem::retention-evict deletes semantic memories from mem:semantic, not mem:memories", 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)],@@ -333,7 +329,7 @@ describe("RetentionScoring", () => {expect(remainingScores).toHaveLength(0);});- it("mem::retention-evict emits a single batched audit record on success (#124, audit policy)", async () => {+ it("mem::retention-evict emits a single batched audit record on success (audit policy)", async () => {const { registerRetentionFunctions } = await import("../src/functions/retention.js");@@ -399,7 +395,7 @@ describe("RetentionScoring", () => {expect(evictEntries).toHaveLength(0);});- it("mem::retention-score emits a batched audit row per rescore (#124, audit policy)", async () => {+ it("mem::retention-score emits a batched audit row per rescore (audit policy)", async () => {const { registerRetentionFunctions } = await import("../src/functions/retention.js");@@ -434,17 +430,11 @@ describe("RetentionScoring", () => {expect(entry.details.semantic).toBe(1);});- it("mem::retention-evict probes namespaces for legacy semantic rows (backwards-compat, #124)", async () => {+ it("mem::retention-evict probes namespaces for legacy semantic rows (backwards-compat)", 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);@@ -475,7 +465,7 @@ describe("RetentionScoring", () => {expect(remainingSem).toHaveLength(0);});- it("mem::retention-evict routes pre-0.8.10 episodic rows with missing source to mem:memories (#124)", async () => {+ it("mem::retention-evict routes pre-0.8.10 episodic rows with missing source to mem:memories", async () => {const { registerRetentionFunctions } = await import("../src/functions/retention.js");diff --git a/test/search.test.ts b/test/search.test.tsindex 99b7f4d6..6f69cc70 100644--- a/test/search.test.ts+++ b/test/search.test.ts@@ -156,7 +156,7 @@ describe("mem::search", () => {).rejects.toThrow("format must be one of");});- it("surfaces saved memories from KV.memories (#265)", async () => {+ it("surfaces saved memories from KV.memories", async () => {// mem::remember persists to KV.memories under a synthetic sessionId// ("memory") that has no corresponding KV.observations entry. mem::search// must fall back to KV.memories or memory_recall returns empty.diff --git a/test/session-end-triggers-graph.test.ts b/test/session-end-triggers-graph.test.tsindex 22a78043..39134cff 100644--- a/test/session-end-triggers-graph.test.ts+++ b/test/session-end-triggers-graph.test.ts@@ -1,15 +1,7 @@import { describe, it, expect } from "vitest";import { readFileSync } from "node:fs";-// #666: api::session::end must publish the session-stopped lifecycle so-// summarize + slot-reflect + graph extraction actually fire. Before this-// fix the `event::session::stopped` handler in events.ts was a dead-// subscriber — no code published `agentmemory.session.stopped`, so graph-// nodes / lessons / crystals never materialized despite the handler-// existing. Direct fire-and-forget trigger keeps the HTTP response fast-// (kv.update runs synchronously, downstream pipeline fan-outs without-// blocking).-describe("api::session::end → event::session::stopped (#666)", () => {+describe("api::session::end → event::session::stopped", () => {const api = readFileSync("src/triggers/api.ts", "utf-8");it("api::session::end fires event::session::stopped after kv.update", () => {@@ -31,11 +23,7 @@ describe("api::session::end → event::session::stopped (#666)", () => {});});-// #666: viewer's "Build Graph" button used to POST /agentmemory/graph/build-// which returned 404 because the endpoint was never registered. Backfill-// the knowledge graph from existing compressed observations across every-// session in batches.-describe("api::graph-build endpoint (#666)", () => {+describe("api::graph-build endpoint", () => {const api = readFileSync("src/triggers/api.ts", "utf-8");it("registers api::graph-build function", () => {@@ -69,11 +57,7 @@ describe("api::graph-build endpoint (#666)", () => {});});-// #666: `agentmemory status` showed Memories/Observations as 0 because it-// fetched /agentmemory/export which times out on iii-engine's file-based-// KV under concurrent kv.list() pressure. Switch to /memories for the-// memory count and derive observation count from sessions[].observationCount.-describe("agentmemory status no longer depends on /export (#666)", () => {+describe("agentmemory status no longer depends on /export", () => {const cli = readFileSync("src/cli.ts", "utf-8");it("status uses count-only memories endpoint instead of export", () => {diff --git a/test/slots-flag-gate.test.ts b/test/slots-flag-gate.test.tsindex 287bcbd8..52201c07 100644--- a/test/slots-flag-gate.test.ts+++ b/test/slots-flag-gate.test.ts@@ -3,14 +3,7 @@ import { mkdtempSync, mkdirSync, rmSync, writeFileSync } from "node:fs";import { tmpdir } from "node:os";import { join } from "node:path";-// Regression tests for #678:-// - isSlotsEnabled / isReflectEnabled must read from ~/.agentmemory/.env-// (not only process.env), so users who set AGENTMEMORY_SLOTS in the-// dotfile see the flag take effect.-// - HTTP triggers must return 503 with enableHow when the flag is off,-// not 500.--describe("isSlotsEnabled — reads merged env (#678)", () => {+describe("isSlotsEnabled — reads merged env", () => {let home: string;let ORIG_HOME: string | undefined;let ORIG_FLAG: string | undefined;@@ -57,7 +50,7 @@ describe("isSlotsEnabled — reads merged env (#678)", () => {});});-describe("isReflectEnabled — reads merged env (#678)", () => {+describe("isReflectEnabled — reads merged env", () => {let home: string;let ORIG_HOME: string | undefined;let ORIG_FLAG: string | undefined;diff --git a/test/smart-search.test.ts b/test/smart-search.test.tsindex 9d0c94e0..033998fb 100644--- a/test/smart-search.test.ts+++ b/test/smart-search.test.ts@@ -168,7 +168,7 @@ describe("Smart Search Function", () => {expect(result.results.length).toBe(0);});- it("compact mode records access for every returned observation id (#119)", async () => {+ it("compact mode records access for every returned observation id", async () => {await sdk.trigger("mem::smart-search", { query: "auth" });// recordAccessBatch is fire-and-forget — let the microtask queue drain.await new Promise((r) => setImmediate(r));@@ -184,7 +184,7 @@ describe("Smart Search Function", () => {expect(log2?.count).toBe(1);});- it("expand mode records access for expanded observation ids (#119)", async () => {+ it("expand mode records access for expanded observation ids", async () => {await sdk.trigger("mem::smart-search", { expandIds: ["obs_1"] });await new Promise((r) => setImmediate(r));diff --git a/test/stop-worker-pidfile.test.ts b/test/stop-worker-pidfile.test.tsindex fe018fca..f61f176d 100644--- a/test/stop-worker-pidfile.test.ts+++ b/test/stop-worker-pidfile.test.ts@@ -1,11 +1,7 @@import { describe, it, expect } from "vitest";import { readFileSync } from "node:fs";-// #640 + #474: stop must also kill the worker process, not just the-// iii engine. We expose the worker pidfile from src/index.ts and read it-// from src/cli.ts. Static check that both files use the resolved runtime-// metadata directory and that stop reads it.-describe("stop reaps the worker process (#640, #474)", () => {+describe("stop reaps the worker process", () => {it("src/index.ts writes worker.pid alongside iii.pid", () => {const source = readFileSync("src/index.ts", "utf-8");expect(source).toMatch(/workerPidfilePath\(\)/);diff --git a/test/summarize.test.ts b/test/summarize.test.tsindex f8f550e2..224bab21 100644--- a/test/summarize.test.ts+++ b/test/summarize.test.ts@@ -416,10 +416,6 @@ describe("mem::summarize chunking", () => {expect(maxInflight).toBe(2);});- // #783: markdown-wrapped XML used to silently fail parsing because- // the tag regex looked for <title> in the raw payload. stripXmlWrappers- // now peels ```xml ... ``` fences and conversational pre/postamble- // before the regex runs.it("parses a summary even when the LLM wraps XML in markdown fences", async () => {const wrappedXml = "Here's the summary:\n```xml\n" + summaryXml({title: "wrapped",diff --git a/test/vector-index.test.ts b/test/vector-index.test.tsindex 317f4f03..b5763806 100644--- a/test/vector-index.test.ts+++ b/test/vector-index.test.ts@@ -77,7 +77,7 @@ describe("VectorIndex", () => {expect(results[0].score).toBe(0);});- it("round-trip preserves dim + identity for pooled-Buffer sizes (#587)", () => {+ it("round-trip preserves dim + identity for pooled-Buffer sizes", () => {// 384-dim floats = 1536 bytes, comfortably inside Node's 8KB Buffer// pool. Without explicit byteOffset/byteLength in the base64 round-trip,// deserialise reads pool offset 0 and reports the entire pool as a@@ -102,7 +102,7 @@ describe("VectorIndex", () => {}});- it("preserves bytes when source Float32Array is itself a sliced view (#587)", () => {+ it("preserves bytes when source Float32Array is itself a sliced view", () => {// The encode side has the same risk: passing arr.buffer drops the// slice metadata if arr is a sub-view (subarray / typedArray.set).const backing = new Float32Array(8);diff --git a/test/viewer-dashboard-reliability.test.ts b/test/viewer-dashboard-reliability.test.tsindex e5a8e435..d2ceafb0 100644--- a/test/viewer-dashboard-reliability.test.ts+++ b/test/viewer-dashboard-reliability.test.ts@@ -254,7 +254,7 @@ describe("viewer navigation and shared components", () => {expect(estimate([], 2000)).toEqual({ percent: 0, saved: 0 });});- it("session summaries stored as objects render as text (#1229)", () => {+ it("session summaries stored as objects render as text", () => {const summaryText = load<(v: unknown) => string>("summaryText");expect(summaryText({ title: "Fix auth", narrative: "long" })).toBe("Fix auth");expect(summaryText({ narrative: "Only narrative" })).toBe("Only narrative");@@ -264,7 +264,7 @@ describe("viewer navigation and shared components", () => {expect(viewer).not.toMatch(/s\.firstPrompt \|\| s\.summary \|\|/);});- it("tags stored as a CSV string no longer break a tab (#906)", () => {+ it("tags stored as a CSV string no longer break a tab", () => {const asTags = load<(v: unknown) => string[]>("asTags");expect(asTags("analysis, run,streamed")).toEqual(["analysis", "run", "streamed"]);expect(asTags(["feat", "prompts"])).toEqual(["feat", "prompts"]);@@ -273,13 +273,13 @@ describe("viewer navigation and shared components", () => {expect(viewer).not.toMatch(/\(l\.tags \|\| \[\]\)/);});- it("live buffers are capped so a large sync backlog cannot freeze the tab (#609)", () => {+ it("live buffers are capped so a large sync backlog cannot freeze the tab", () => {expect(viewer).toMatch(/var LIVE_BUFFER_MAX = 200;/);expect(extractFunction("handleStreamEvent")).toMatch(/evt\.data\.slice\(-LIVE_BUFFER_MAX\)/);expect(extractFunction("routeWsMessage")).toMatch(/observations\.length > LIVE_BUFFER_MAX/);});- it("Rebuild Graph asks first, ignores repeat clicks, and reports the result (#1383)", () => {+ it("Rebuild Graph asks first, ignores repeat clicks, and reports the result", () => {const rebuild = extractFunction("rebuildGraph");expect(rebuild).toMatch(/if \(graphRebuilding\) return;/);expect(rebuild).toMatch(/window\.confirm\(/);diff --git a/test/viewer-host.test.ts b/test/viewer-host.test.tsindex b68ecec4..1349d12b 100644--- a/test/viewer-host.test.ts+++ b/test/viewer-host.test.ts@@ -184,7 +184,7 @@ describe("startViewerServer host binding", () => {expect(addr.address).toBe("127.0.0.1");});- it("binds to AGENTMEMORY_VIEWER_HOST when set — covers the deploy/fly fix for #434", async () => {+ it("binds to AGENTMEMORY_VIEWER_HOST when set — covers the deploy/fly fix", async () => {process.env.AGENTMEMORY_VIEWER_HOST = "::1";server = startViewerServer(0, null, null);await waitForListening(server);diff --git a/test/viewer-memories-sort.test.ts b/test/viewer-memories-sort.test.tsindex 2803bb2d..c0ea7d38 100644--- a/test/viewer-memories-sort.test.ts+++ b/test/viewer-memories-sort.test.ts@@ -1,7 +1,7 @@import { describe, it, expect } from "vitest";import { readFileSync } from "node:fs";-describe("viewer lists sort newest first (#674)", () => {+describe("viewer lists sort newest first", () => {const viewer = readFileSync("src/viewer/index.html", "utf-8");function extractFunction(name: string): string {diff --git a/test/viewer-security.test.ts b/test/viewer-security.test.tsindex 8db74b6d..f9e78d6d 100644--- a/test/viewer-security.test.ts+++ b/test/viewer-security.test.ts@@ -22,11 +22,7 @@ describe("viewer document security", () => {expect(rendered.html).not.toContain("__AGENTMEMORY_VIEWER_NONCE__");});- it("does not loosen img-src with bare data: URI allowance (#447)", () => {- // #313 added `data:` so an inline-SVG favicon could load. #447 reverts- // that by self-hosting the favicon at /favicon.svg — `data:` would- // also allow any data:image/png;base64,... and (in some browsers)- // data:text/html;base64,..., which the viewer never needs.+ it("does not loosen img-src with bare data: URI allowance", () => {const rendered = renderViewerDocument();expect(rendered.found).toBe(true);if (!rendered.found) return;@@ -210,7 +206,7 @@ describe("viewer request handler DNS rebinding defence (e2e)", () => {}});- it("serves /favicon.svg with image/svg+xml so the tight CSP can drop data: (#447)", async () => {+ it("serves /favicon.svg with image/svg+xml so the tight CSP can drop data:", async () => {const { port } = await spinUpViewer();const res = await request(port, `localhost:${port}`, "/favicon.svg");expect(res.status).toBe(200);diff --git a/test/viewer-session-id.test.ts b/test/viewer-session-id.test.tsindex 30f77481..60863dea 100644--- a/test/viewer-session-id.test.ts+++ b/test/viewer-session-id.test.ts@@ -53,9 +53,6 @@ function loadViewerSandbox() {setAttribute: (name: string, value: unknown) => {attributes.set(name, String(value));},- // Added in #313 — switchTab toggles aria-selected via removeAttribute- // on the non-active tab buttons. The mock previously only had- // get/setAttribute, so the new hash-routing path threw TypeError.removeAttribute: (name: string) => {attributes.delete(name);},@@ -128,10 +125,6 @@ function loadViewerSandbox() {matchMedia: () => ({ matches: false }),addEventListener: () => {},},- // Stubbed in #313 — the viewer now calls history.replaceState- // inside updateTabRoute → switchTab to drive the hash-route surface.- // The vm sandbox is otherwise zero-globals so the call would- // throw ReferenceError. No-op is fine for the rendering tests.history: { replaceState: () => {}, pushState: () => {} },location: {hash: "",