Skip to content

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

fix(release): v0.9.28 hotfix wave (#843, #825, #817, iii pin) (#849)

Rohit Ghumarea6e22fa9c7c4
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 99ce1061..0d0fe669 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -6,6 +6,33 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
## [Unreleased]
+## [0.9.28] — 2026-06-07
+
+Hotfix wave on top of v0.9.27. Three real-world bug reports against the freshly-shipped release plus a security regression on agent-scope isolation.
+
+### Security
+
+- **`AGENTMEMORY_AGENT_SCOPE=isolated` not enforced on `mem::search` / `POST /agentmemory/search` / `memory_recall` / `recall_context`** ([#817](https://github.com/rohitg00/agentmemory/issues/817)). The PR #654 isolation work covered `mem::smart-search`, `/memories`, `/observations`, and `/sessions` but missed the BM25-only recall path. An isolated worker booted with `AGENT_ID=B` could read agent A's memories via the standard MCP `memory_recall` tool. `mem::search` now applies the same `getAgentId()` / `isAgentScopeIsolated()` filter the smart-search path uses (wildcard `agentId: "*"` bypasses, explicit `agentId` pins, isolated mode falls back to env `AGENT_ID`). `recall_context` prompt also filters its kv.list memory feed by the active agent.
+
+### Fixed
+
+- **All data lost on `agentmemory stop` followed by restart** ([#843](https://github.com/rohitg00/agentmemory/issues/843)). `runStop()` killed the iii engine first, then the worker. The worker's shutdown handler flushes BM25/vector snapshots and audit rows via `indexPersistence.save() -> kv.set() -> state::set`, which all routed through an iii engine that was already dead. Stop order inverted: worker first with a bumped 5s SIGTERM grace (gives a large index a real chance to commit), engine second. The "Memories persisted to disk" message now reflects actual disk state.
+- **`mem::graph-snapshot-rebuild` and `mem::graph-reset` heartbeat-crashed on legacy >25K-node corpora** ([#825](https://github.com/rohitg00/agentmemory/issues/825)). v0.9.27 shipped both endpoints with a `kv.list` call up front. At 75K nodes the response payload blocks the event loop in `JSON.parse` and the iii heartbeat starves before the wall-clock budget timer can fire (the budget was never reachable). `mem::graph-snapshot-rebuild` now refuses pre-flight when no prior snapshot exists, returning `{ legacyCorpus: true }` with operator guidance unless an explicit `force: true` flag is set. `mem::graph-reset` no longer enumerates anything — it writes an empty snapshot and returns. Legacy rows remain on disk as orphans but are never read by any post-#816 hot-path code. This is the recovery escape hatch for the corpus class Allan reported in #814.
+- **iii console install pulled latest engine instead of the pinned v0.11.2** (audit). `III_CONSOLE_INSTALL_CMD` ran `curl -fsSL https://install.iii.dev/iii/main/install.sh | sh` with no version pin. A fresh first-run prompt could install a console build that talks a different protocol than the engine agentmemory pins. The install script reads a `VERSION` env var (`engine_version="${VERSION:-}"` in install.sh), so the command now passes `VERSION=${IIPINNED_VERSION}`. Mismatch error text also updated from "reinstall the latest binary" to reference the pinned version explicitly.
+
+### Docs
+
+- **README "New in vX.Y.Z" callout block removed.** That pattern needed a per-release bump every wave and went stale fast. Latest release notes link points at CHANGELOG.md instead.
+- **`import-jsonl` users warned about Claude Code's `cleanupPeriodDays`.** Default 30-day auto-deletion of `~/.claude/projects/*.jsonl` doesn't affect anyone running the standard hook-wired install (each turn lands in iii state while the session is live), but fresh installs on months-old Claude Code histories silently lost anything older than 30 days. README now flags this with the three workarounds: cron the import, raise `cleanupPeriodDays`, or wire hooks.
+
+### Known limitations carried into 0.9.28
+
+- `mem::graph-query` BFS (`startNodeId`) and text-search (`query`) paths still call `kv.list` and degrade past ~25K nodes on fresh corpora ([#828](https://github.com/rohitg00/agentmemory/issues/828)). The hot path stays safe (snapshot-only). A per-node adjacency index that lets BFS walk via targeted `kv.get` is the right next fix; deferred to the milestone for the structured graph migration ([#309](https://github.com/rohitg00/agentmemory/issues/309)).
+- `/agentmemory:forget` skill still calls `memory_governance_delete` which only touches `KV.memories` and never observations ([#833](https://github.com/rohitg00/agentmemory/issues/833)). The skill rewrite + new `memory_forget` MCP tool are tracked separately.
+- `crypto.randomUUID()` global-only on Node <19 ([#715](https://github.com/rohitg00/agentmemory/issues/715)). Drop-in import fix tracked.
+
+[0.9.28]: https://github.com/rohitg00/agentmemory/compare/v0.9.27...v0.9.28
+
## [0.9.27] — 2026-06-04
Two real-world bug fixes reported against v0.9.26 plus a benchmark scorecard correction. No breaking changes; drop-in upgrade.
diff --git a/README.md b/README.md
index af019002..87e6b3f0 100644
--- a/README.md
+++ b/README.md
@@ -226,9 +226,7 @@ You explain the same architecture every session. You re-discover the same bugs.
npx @agentmemory/agentmemory
```
-> **New in v0.9.26** — Hotfix: first-boot crash on missing index manifest ([#797](https://github.com/rohitg00/agentmemory/issues/797)) now self-heals instead of throwing on `manifest.v`.
->
-> **v0.9.25** — Eleven breaking regressions closed (cross-provider fallback 404, `triggerVoid` removal in iii-sdk 0.11.2, summarize XML in markdown fences, pi `tool_input/tool_output` field mismatch, viewer graph 500 on 11k+ nodes, agent-sdk recursion guard race under `Promise.all`, obsidian-export missing-id crash, iii runtime pin auto-fallback, import-jsonl legacy session re-key). Added: sharded BM25/vector index persistence with manifest commit/rollback ([@Rokurolize](https://github.com/Rokurolize) [#762](https://github.com/rohitg00/agentmemory/issues/762)), smart-search followup-rate diagnostic ([#771](https://github.com/rohitg00/agentmemory/issues/771)). Drop-in upgrade, no breaking changes. Full notes in [CHANGELOG.md](CHANGELOG.md).
+Latest release notes: [CHANGELOG.md](CHANGELOG.md).
---
@@ -429,6 +427,8 @@ npx @agentmemory/agentmemory import-jsonl ~/.claude/projects/-my-project/abc123.
Imported sessions show up in the Replay picker alongside native ones. Under the hood each entry routes through the `mem::replay::load`, `mem::replay::sessions`, and `mem::replay::import-jsonl` iii functions — no side-channel servers.
+> **Heads-up if you rely on `import-jsonl` as your primary capture path:** Claude Code's `cleanupPeriodDays` (in `~/.claude/settings.json`, default **30**) auto-deletes JSONL transcripts older than that window from `~/.claude/projects/`. If you install agentmemory fresh on a months-old Claude Code history, anything older than 30 days is already gone before the first import. Either run `import-jsonl` on a cron, raise `cleanupPeriodDays` to something higher, or wire the auto-capture hooks (the default plugin install path) so each turn lands in agentmemory while the session is live and the JSONL cleanup stops mattering.
+
### Upgrade / Maintenance
Use the maintenance command when you intentionally want to update your local runtime:
diff --git a/package.json b/package.json
index 3a4fb950..e0a3b741 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
{
"name": "@agentmemory/agentmemory",
- "version": "0.9.27",
+ "version": "0.9.28",
"description": "Persistent memory for AI coding agents, powered by iii-engine's three primitives",
"type": "module",
"main": "dist/index.mjs",
diff --git a/packages/mcp/package.json b/packages/mcp/package.json
index e918d9cb..bdc31203 100644
--- a/packages/mcp/package.json
+++ b/packages/mcp/package.json
@@ -1,6 +1,6 @@
{
"name": "@agentmemory/mcp",
- "version": "0.9.27",
+ "version": "0.9.28",
"description": "Standalone MCP server for agentmemory — thin shim that re-exposes @agentmemory/agentmemory's MCP entrypoint",
"type": "module",
"bin": {
diff --git a/plugin/.claude-plugin/plugin.json b/plugin/.claude-plugin/plugin.json
index cb4e6df7..49d4bacb 100644
--- a/plugin/.claude-plugin/plugin.json
+++ b/plugin/.claude-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "agentmemory",
- "version": "0.9.27",
+ "version": "0.9.28",
"description": "Persistent memory for AI coding agents -- captures tool usage, compresses via LLM, injects context into future sessions. 12 hooks, 53 MCP tools, 8 skills, real-time viewer.",
"author": {
"name": "Rohit Ghumare",
diff --git a/plugin/.codex-plugin/plugin.json b/plugin/.codex-plugin/plugin.json
index 7c42f130..9d350289 100644
--- a/plugin/.codex-plugin/plugin.json
+++ b/plugin/.codex-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "agentmemory",
- "version": "0.9.27",
+ "version": "0.9.28",
"description": "Persistent memory for AI coding agents -- captures tool usage, compresses via LLM, injects context into future sessions. 6 hooks, 53 MCP tools, 8 skills, real-time viewer.",
"author": {
"name": "Rohit Ghumare",
diff --git a/plugin/plugin.json b/plugin/plugin.json
index 5cb13fe8..1af9b1c0 100644
--- a/plugin/plugin.json
+++ b/plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "agentmemory",
- "version": "0.9.27",
+ "version": "0.9.28",
"description": "Persistent memory for AI coding agents -- captures tool usage, compresses via LLM, injects context into future sessions. 12 hooks, 53 MCP tools, 8 skills, real-time viewer.",
"author": {
"name": "Rohit Ghumare",
diff --git a/src/cli.ts b/src/cli.ts
index 4a52e684..acac3d97 100644
--- a/src/cli.ts
+++ b/src/cli.ts
@@ -653,8 +653,30 @@ function detectIiiConsole(): IiiConsoleState {
return { kind: "missing" };
}
+// The upstream install script reads `VERSION` as an env var (see
+// install.iii.dev/iii/main/install.sh: `engine_version="${VERSION:-}"`).
+// Pin to IIPINNED_VERSION so a fresh boot can never pull a newer iii
+// console that talks a different protocol than our pinned engine
+// (root cause of #712-class drift).
const III_CONSOLE_INSTALL_CMD =
- "curl -fsSL https://install.iii.dev/iii/main/install.sh | sh";
+ `curl -fsSL https://install.iii.dev/iii/main/install.sh | VERSION=${IIPINNED_VERSION} sh`;
+
+// Display-only renderer. The internal `runCommand(shBin, ["-c", ...])`
+// path uses III_CONSOLE_INSTALL_CMD verbatim (POSIX shell). Anywhere
+// that PRINTS the command to a user has to handle Windows separately
+// since `VERSION=X sh` and the pipe-to-sh idiom aren't valid in
+// cmd.exe / PowerShell.
+function iiiConsoleInstallHint(): string {
+ if (!IS_WINDOWS) return III_CONSOLE_INSTALL_CMD;
+ return (
+ `# PowerShell:\n` +
+ ` $env:VERSION = "${IIPINNED_VERSION}"\n` +
+ ` iwr -useb https://install.iii.dev/iii/main/install.sh -OutFile install.sh\n` +
+ ` bash install.sh # WSL or Git Bash required\n` +
+ `# Or grab the pinned release directly:\n` +
+ ` https://github.com/iii-hq/iii/releases/tag/iii%2Fv${IIPINNED_VERSION}`
+ );
+}
async function ensureIiiConsole(): Promise<IiiConsoleState> {
const state = detectIiiConsole();
@@ -680,7 +702,7 @@ async function ensureIiiConsole(): Promise<IiiConsoleState> {
const curlBin = whichBinary("curl");
if (!shBin || !curlBin) {
p.log.warn(
- `curl or sh not found. Install manually:\n ${III_CONSOLE_INSTALL_CMD}`,
+ `curl or sh not found. Install manually:\n ${iiiConsoleInstallHint()}`,
);
return state;
}
@@ -689,7 +711,7 @@ async function ensureIiiConsole(): Promise<IiiConsoleState> {
});
if (!ok) {
p.log.warn(
- `iii console install failed. Re-run manually:\n ${III_CONSOLE_INSTALL_CMD}`,
+ `iii console install failed. Re-run manually:\n ${iiiConsoleInstallHint()}`,
);
return state;
}
@@ -1099,7 +1121,7 @@ function printReadyHint(consoleState: IiiConsoleState): void {
// is, even when the binary isn't on PATH under the bare
// name `iii-console`.
`iii console ${consoleState.binPath} (run: ${consoleState.binPath} -p <port>)`
- : `iii console (install: ${III_CONSOLE_INSTALL_CMD})`;
+ : `iii console (install: ${iiiConsoleInstallHint()})`;
const lines = [
`REST API ${restUrl}`,
@@ -1232,7 +1254,7 @@ async function main() {
p.note(
[
"Common causes:",
- " - iii-engine version mismatch — reinstall the latest binary",
+ ` - iii-engine version mismatch — reinstall the pinned v${IIPINNED_VERSION} binary`,
" (sh script on macOS/Linux, GitHub release zip on Windows)",
" - Docker Desktop not running (if you're using the Docker path)",
" - Port already in use (see below)",
@@ -2453,19 +2475,26 @@ async function runStop(): Promise<void> {
}
let allStopped = true;
- for (const pid of candidates) {
+ // #843: stop worker first, then engine. The worker's shutdown
+ // handler calls indexPersistence.save() -> kv.set() -> iii state::set
+ // to flush BM25/vector snapshots + audit rows. Killing iii first
+ // leaves those writes with no engine to land on, and the index +
+ // observations end up as in-memory state the iii process never
+ // persists. Worker SIGTERM grace bumped 3s -> 5s to give a large
+ // index a real chance to commit before the engine goes away.
+ for (const pid of workerCandidates) {
const s = p.spinner();
- s.start(`Stopping iii-engine (pid ${pid})...`);
- const ok = await signalAndWait(pid, "SIGTERM", 3000);
- s.stop(ok ? `Stopped pid ${pid}` : `Failed to stop pid ${pid}`);
+ s.start(`Stopping agentmemory worker (pid ${pid})... [flushing state]`);
+ const ok = await signalAndWait(pid, "SIGTERM", 5000);
+ s.stop(ok ? `Stopped worker pid ${pid}` : `Failed to stop worker pid ${pid}`);
if (!ok) allStopped = false;
}
- for (const pid of workerCandidates) {
- if (candidates.has(pid)) continue;
+ for (const pid of candidates) {
+ if (workerCandidates.has(pid)) continue;
const s = p.spinner();
- s.start(`Stopping agentmemory worker (pid ${pid})...`);
+ s.start(`Stopping iii-engine (pid ${pid})...`);
const ok = await signalAndWait(pid, "SIGTERM", 3000);
- s.stop(ok ? `Stopped worker pid ${pid}` : `Failed to stop worker pid ${pid}`);
+ s.stop(ok ? `Stopped pid ${pid}` : `Failed to stop pid ${pid}`);
if (!ok) allStopped = false;
}
diff --git a/src/functions/export-import.ts b/src/functions/export-import.ts
index 327117b2..8b3bc7cc 100644
--- a/src/functions/export-import.ts
+++ b/src/functions/export-import.ts
@@ -176,7 +176,7 @@ export function registerExportImportFunction(sdk: ISdk, kv: StateKV): void {
const strategy = data.strategy || "merge";
const importData = data.exportData;
- const supportedVersions = new Set(["0.3.0", "0.4.0", "0.5.0", "0.6.0", "0.6.1", "0.7.0", "0.7.2", "0.7.3", "0.7.4", "0.7.5", "0.7.6", "0.7.7", "0.7.9", "0.8.0", "0.8.1", "0.8.2", "0.8.3", "0.8.4", "0.8.5", "0.8.6", "0.8.7", "0.8.8", "0.8.9", "0.8.10", "0.8.11", "0.8.12", "0.8.13", "0.9.0", "0.9.1", "0.9.2", "0.9.3", "0.9.4", "0.9.5", "0.9.6", "0.9.7", "0.9.8", "0.9.9", "0.9.10", "0.9.11", "0.9.12", "0.9.13", "0.9.14", "0.9.15", "0.9.16", "0.9.17", "0.9.18", "0.9.19", "0.9.20", "0.9.21", "0.9.22", "0.9.23", "0.9.24", "0.9.25", "0.9.26", "0.9.27"]);
+ const supportedVersions = new Set(["0.3.0", "0.4.0", "0.5.0", "0.6.0", "0.6.1", "0.7.0", "0.7.2", "0.7.3", "0.7.4", "0.7.5", "0.7.6", "0.7.7", "0.7.9", "0.8.0", "0.8.1", "0.8.2", "0.8.3", "0.8.4", "0.8.5", "0.8.6", "0.8.7", "0.8.8", "0.8.9", "0.8.10", "0.8.11", "0.8.12", "0.8.13", "0.9.0", "0.9.1", "0.9.2", "0.9.3", "0.9.4", "0.9.5", "0.9.6", "0.9.7", "0.9.8", "0.9.9", "0.9.10", "0.9.11", "0.9.12", "0.9.13", "0.9.14", "0.9.15", "0.9.16", "0.9.17", "0.9.18", "0.9.19", "0.9.20", "0.9.21", "0.9.22", "0.9.23", "0.9.24", "0.9.25", "0.9.26", "0.9.27", "0.9.28"]);
if (!supportedVersions.has(importData.version)) {
return {
success: false,
diff --git a/src/functions/graph.ts b/src/functions/graph.ts
index 9493674d..bb0d7272 100644
--- a/src/functions/graph.ts
+++ b/src/functions/graph.ts
@@ -501,6 +501,19 @@ export function registerGraphFunction(
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 &&
+ typeof existing.createdAt === "string" &&
+ existing.createdAt < snap.resetAt
+ ) {
+ existing = null;
+ }
}
if (existing) {
@@ -540,6 +553,15 @@ export function registerGraphFunction(
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 &&
+ typeof existing.createdAt === "string" &&
+ existing.createdAt < snap.resetAt
+ ) {
+ existing = null;
+ }
}
if (existing) {
@@ -798,17 +820,60 @@ export function registerGraphFunction(
// 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 () => {
- const started = Date.now();
- try {
- const [nodes, edges] = await withTimeout(
- Promise.all([
- kv.list<GraphNode>(KV.graphNodes),
- kv.list<GraphEdge>(KV.graphEdges),
- ]),
- LIVE_ENUMERATION_BUDGET_MS,
- "graph-snapshot-rebuild enumeration",
- );
+ 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);
+ if (!existing && !forceRebuild) {
+ logger.warn("Graph snapshot rebuild refused: no prior snapshot", {
+ hint: "legacy corpus or empty store",
+ });
+ return {
+ success: false,
+ legacyCorpus: true,
+ error:
+ "No prior snapshot found. Rebuild would call kv.list on " +
+ "KV.graphNodes/Edges, which heartbeat-crashes the worker " +
+ "on corpora past the iii state response budget (~25K nodes). " +
+ "Either (a) call POST /agentmemory/graph/reset to drop into " +
+ "incremental-only mode and rebuild from new extracts, or " +
+ "(b) re-send with `force: true` if you're certain the " +
+ "corpus is small.",
+ };
+ }
+ } catch (err) {
+ const msg = err instanceof Error ? err.message : String(err);
+ logger.warn("Graph snapshot pre-flight read failed", { error: msg });
+ // Fall through; the user passed force=true or the snapshot
+ // read itself failed (separate problem).
+ }
+
+ try {
+ const [nodes, edges] = await withTimeout(
+ Promise.all([
+ kv.list<GraphNode>(KV.graphNodes),
+ kv.list<GraphEdge>(KV.graphEdges),
+ ]),
+ LIVE_ENUMERATION_BUDGET_MS,
+ "graph-snapshot-rebuild enumeration",
+ );
if (nodes.length > REBUILD_SAFE_NODE_CEILING) {
logger.warn("Graph snapshot rebuild aborted: corpus too large", {
@@ -888,104 +953,43 @@ export function registerGraphFunction(
}
});
- // #814 v2: clean-restart escape hatch for legacy corpora too large
- // for safe rebuild. Wipes every graph KV scope and writes an empty
- // snapshot. Observations are NOT touched, so recall + history stay
- // intact; the graph rebuilds incrementally from future
- // mem::graph-extract calls (or a one-shot api::graph-build replay
- // from existing observations).
+ // #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. Future
+ // mem::graph-extract calls compare each name-index lookup's
+ // existing node `createdAt` against this timestamp; anything
+ // older counts as an orphan and is dropped from the merge path,
+ // forcing extract to write a fresh row instead of reconnecting
+ // to a pre-reset entry.
+ const resetSnapshot: GraphSnapshot = {
+ ...emptySnapshot(),
+ resetAt: new Date().toISOString(),
+ };
+ await kv.set(KV.graphSnapshot, SNAPSHOT_KEY, resetSnapshot);
const counts: Record<string, number> = {
- [KV.graphNodes]: 0,
- [KV.graphEdges]: 0,
- [KV.graphNameIndex]: 0,
- [KV.graphEdgeKey]: 0,
- [KV.graphNodeDegree]: 0,
- [KV.graphEdgeHistory]: 0,
- [KV.graphSnapshot]: 0,
+ [KV.graphSnapshot]: 1,
};
-
- // Composite-key scopes (graphNameIndex / graphEdgeKey /
- // graphNodeDegree) store primitives, not objects, so we can't
- // recover their keys via kv.list (which returns values only). The
- // only reliable wipe path is to walk the canonical object scopes
- // (graphNodes / graphEdges) and reconstruct the composite keys
- // from each node/edge's fields, deleting both the canonical row
- // AND every derived index entry in lock-step.
- try {
- const nodes = await withTimeout(
- kv.list<GraphNode>(KV.graphNodes),
- LIVE_ENUMERATION_BUDGET_MS,
- "graph-reset list graphNodes",
- );
- counts[KV.graphNodes] = nodes.length;
- for (const node of nodes) {
- if (!node?.id) continue;
- await Promise.all([
- kv.delete(KV.graphNodes, node.id).catch(() => undefined),
- kv
- .delete(KV.graphNameIndex, nameIndexKey(node.type, node.name))
- .catch(() => undefined),
- kv.delete(KV.graphNodeDegree, node.id).catch(() => undefined),
- ]);
- counts[KV.graphNameIndex] += 1;
- counts[KV.graphNodeDegree] += 1;
- }
- } catch (err) {
- const msg = err instanceof Error ? err.message : String(err);
- logger.warn("graph-reset: graphNodes list failed", { error: msg });
- counts[KV.graphNodes] = -1;
- }
-
- try {
- const edges = await withTimeout(
- kv.list<GraphEdge>(KV.graphEdges),
- LIVE_ENUMERATION_BUDGET_MS,
- "graph-reset list graphEdges",
- );
- counts[KV.graphEdges] = edges.length;
- for (const edge of edges) {
- if (!edge?.id) continue;
- await Promise.all([
- kv.delete(KV.graphEdges, edge.id).catch(() => undefined),
- kv
- .delete(
- KV.graphEdgeKey,
- edgeIndexKey(edge.sourceNodeId, edge.targetNodeId, edge.type),
- )
- .catch(() => undefined),
- ]);
- counts[KV.graphEdgeKey] += 1;
- }
- } catch (err) {
- const msg = err instanceof Error ? err.message : String(err);
- logger.warn("graph-reset: graphEdges list failed", { error: msg });
- counts[KV.graphEdges] = -1;
- }
-
- // graphEdgeHistory entries also key by id (audit row shape). Best
- // effort — failures here don't block the reset.
- try {
- const history = await withTimeout(
- kv.list<{ id?: string }>(KV.graphEdgeHistory),
- LIVE_ENUMERATION_BUDGET_MS,
- "graph-reset list graphEdgeHistory",
- );
- counts[KV.graphEdgeHistory] = history.length;
- for (const row of history) {
- if (row?.id) {
- await kv.delete(KV.graphEdgeHistory, row.id).catch(() => undefined);
- }
- }
- } catch (err) {
- const msg = err instanceof Error ? err.message : String(err);
- logger.warn("graph-reset: graphEdgeHistory list failed", { error: msg });
- counts[KV.graphEdgeHistory] = -1;
- }
-
- await kv.set(KV.graphSnapshot, SNAPSHOT_KEY, emptySnapshot());
- counts[KV.graphSnapshot] = 1;
const tookMs = Date.now() - started;
logger.info("Graph state reset", { counts, tookMs });
return { success: true, cleared: counts, tookMs };
diff --git a/src/functions/search.ts b/src/functions/search.ts
index 655ea93d..df699a1a 100644
--- a/src/functions/search.ts
+++ b/src/functions/search.ts
@@ -8,6 +8,7 @@ import type { EmbeddingProvider } from '../types.js'
import { memoryToObservation } from '../state/memory-utils.js'
import { recordAccessBatch } from './access-tracker.js'
import { logger } from "../logger.js";
+import { getAgentId, isAgentScopeIsolated } from "../config.js";
let index: SearchIndex | null = null
let vectorIndex: VectorIndex | null = null
@@ -328,6 +329,7 @@ export function registerSearchFunction(sdk: ISdk, kv: StateKV): void {
cwd?: string
format?: string
token_budget?: number
+ agentId?: string
}) => {
const idx = getSearchIndex()
@@ -346,6 +348,42 @@ export function registerSearchFunction(sdk: ISdk, kv: StateKV): void {
}
const projectFilter = typeof data.project === 'string' && data.project.trim().length > 0 ? data.project.trim() : undefined
const 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
+ ? data.agentId.trim()
+ : undefined;
+ const wildcardAgent = explicitAgentId === "*";
+ const envAgentId = isolated ? getAgentId() : undefined;
+ const filterAgentId = wildcardAgent
+ ? undefined
+ : explicitAgentId ?? envAgentId;
+ if (
+ isolated &&
+ !wildcardAgent &&
+ !explicitAgentId &&
+ !envAgentId
+ ) {
+ throw new Error(
+ "mem::search: AGENTMEMORY_AGENT_SCOPE=isolated is set but no " +
+ "agent id is available (env AGENT_ID unset and no explicit " +
+ "agentId in the call). Refusing to read cross-agent rows. " +
+ 'Pass agentId: "*" to opt in to a wildcard read.',
+ );
+ }
const format = typeof data.format === 'string' ? data.format : 'full'
if (!['full', 'compact', 'narrative'].includes(format)) {
throw new Error("mem::search: format must be one of 'full', 'compact', or 'narrative'")
@@ -365,7 +403,12 @@ export function registerSearchFunction(sdk: ISdk, kv: StateKV): void {
// When filtering by project/cwd, over-fetch from the index so the
// post-filter still has a chance of returning `effectiveLimit` results.
- const filtering = !!(projectFilter || cwdFilter)
+ // Over-fetch whenever ANY post-index filter is active. agentId
+ // is dropped after the observation/memory is loaded (BM25 index
+ // doesn't carry it), so without the over-fetch isolated-mode
+ // queries return underfilled pages when same-agent matches
+ // rank lower than cross-agent ones in the hybrid score.
+ const filtering = !!(projectFilter || cwdFilter || filterAgentId)
const fetchLimit = filtering ? Math.max(effectiveLimit * 10, 100) : effectiveLimit
const results = idx.search(query, fetchLimit)
@@ -395,9 +438,16 @@ export function registerSearchFunction(sdk: ISdk, kv: StateKV): void {
// First pass: filter by session (sequential — benefits from session cache).
// Memory entries with a synthetic sessionId take a secondary KV.memories
// path so project filtering works correctly for them too.
+ //
+ // When agentId filtering is active we can't cap at effectiveLimit
+ // here — the second pass (post-load) is what drops cross-agent
+ // rows, and capping early would underfill the result page. Use
+ // fetchLimit as the upper bound in that case; the final
+ // truncation lives at the end of the second pass.
+ const earlyCap = filterAgentId ? fetchLimit : effectiveLimit
const candidates: typeof results = []
for (const r of results) {
- if (candidates.length >= effectiveLimit) break
+ if (candidates.length >= earlyCap) break
if (filtering) {
const s = await loadSession(r.sessionId)
if (s) {
@@ -447,13 +497,18 @@ export function registerSearchFunction(sdk: ISdk, kv: StateKV): void {
const enriched: SearchResult[] = []
for (let i = 0; i < candidates.length; i++) {
const obs = obsResults[i]
- if (obs) {
- enriched.push({
- observation: obs,
- score: candidates[i].score,
- sessionId: candidates[i].sessionId,
- })
- }
+ 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) continue
+ if (enriched.length >= effectiveLimit) break
+ enriched.push({
+ observation: obs,
+ score: candidates[i].score,
+ sessionId: candidates[i].sessionId,
+ })
}
void recordAccessBatch(
diff --git a/src/functions/smart-search.ts b/src/functions/smart-search.ts
index 10a0a77c..5d0147d9 100644
--- a/src/functions/smart-search.ts
+++ b/src/functions/smart-search.ts
@@ -100,15 +100,34 @@ export function registerSmartSearchFunction(
// 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
? data.agentId.trim()
: undefined;
const wildcardAgent = explicitAgentId === "*";
+ const envAgentId = isolated ? getAgentId() : undefined;
const filterAgentId = wildcardAgent
? undefined
- : explicitAgentId ?? (isolated ? getAgentId() : undefined);
+ : explicitAgentId ?? envAgentId;
+ if (
+ isolated &&
+ !wildcardAgent &&
+ !explicitAgentId &&
+ !envAgentId
+ ) {
+ throw new Error(
+ "mem::smart-search: AGENTMEMORY_AGENT_SCOPE=isolated is set but " +
+ "no agent id is available (env AGENT_ID unset and no explicit " +
+ "agentId in the call). Refusing to read cross-agent rows. " +
+ 'Pass agentId: "*" to opt in to a wildcard read.',
+ );
+ }
if (data.expandIds && data.expandIds.length > 0) {
const raw = data.expandIds.slice(0, 20);
diff --git a/src/mcp/server.ts b/src/mcp/server.ts
index e2144567..dbca07d9 100644
--- a/src/mcp/server.ts
+++ b/src/mcp/server.ts
@@ -10,6 +10,7 @@ import type {
} from "../types.js";
import { getVisibleTools } from "./tools-registry.js";
import { timingSafeCompare } from "../auth.js";
+import { getAgentId, isAgentScopeIsolated } from "../config.js";
type McpResponse = {
status_code: number;
@@ -112,11 +113,20 @@ 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()
+ : undefined;
const result = await sdk.trigger({ function_id: "mem::search", payload: {
query: args.query,
limit: typeof args.limit === "number" ? args.limit : 10,
format,
token_budget: tokenBudget,
+ agentId: recallAgentId,
} });
const text =
format === "narrative" &&
@@ -1635,6 +1645,9 @@ 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",
@@ -1642,7 +1655,31 @@ export function registerMcpEndpoints(
})
.catch(() => ({ results: [] }));
const memories = await kv.list<Memory>(KV.memories);
- const relevant = memories.filter((m) => m.isLatest).slice(0, 5);
+ // #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 =
+ isolated && activeAgentId === undefined
+ ? []
+ : memories
+ .filter((m) => m.isLatest)
+ .filter(
+ (m) =>
+ activeAgentId === undefined ||
+ m.agentId === activeAgentId,
+ )
+ .slice(0, 5);
return {
status_code: 200,
body: {
diff --git a/src/triggers/api.ts b/src/triggers/api.ts
index 43468c02..4a214a3a 100644
--- a/src/triggers/api.ts
+++ b/src/triggers/api.ts
@@ -361,7 +361,7 @@ export function registerApiTriggers(
},
});
- sdk.registerFunction("api::search",
+ sdk.registerFunction("api::search",
async (
req: ApiRequest<{
query: string;
@@ -370,9 +370,16 @@ export function registerApiTriggers(
cwd?: string;
format?: string;
token_budget?: number;
+ agentId?: string;
}>,
): Promise<Response> => {
const body = (req.body ?? {}) as Record<string, unknown>;
+ const queryAgentId =
+ typeof (req as { query_params?: Record<string, string> })
+ .query_params?.["agentId"] === "string"
+ ? (req as { query_params: Record<string, string> })
+ .query_params["agentId"]
+ : undefined;
if (typeof body.query !== "string" || !body.query.trim()) {
return { status_code: 400, body: { error: "query is required and must be a non-empty string" } };
}
@@ -407,6 +414,14 @@ 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()
+ : undefined;
const payload = {
query: body.query.trim(),
limit: body.limit as number | undefined,
@@ -417,6 +432,7 @@ export function registerApiTriggers(
? body.format.trim().toLowerCase()
: undefined,
token_budget: body.token_budget as number | undefined,
+ agentId: bodyAgentId ?? queryAgentId,
};
const result = await sdk.trigger({ function_id: "mem::search", payload: payload });
return { status_code: 200, body: result };
diff --git a/src/types.ts b/src/types.ts
index 8b0232b8..113daeae 100644
--- a/src/types.ts
+++ b/src/types.ts
@@ -307,7 +307,7 @@ export interface ExportPagination {
}
export interface ExportData {
- version: "0.3.0" | "0.4.0" | "0.5.0" | "0.6.0" | "0.6.1" | "0.7.0" | "0.7.2" | "0.7.3" | "0.7.4" | "0.7.5" | "0.7.6" | "0.7.7" | "0.7.9" | "0.8.0" | "0.8.1" | "0.8.2" | "0.8.3" | "0.8.4" | "0.8.5" | "0.8.6" | "0.8.7" | "0.8.8" | "0.8.9" | "0.8.10" | "0.8.11" | "0.8.12" | "0.8.13" | "0.9.0" | "0.9.1" | "0.9.2" | "0.9.3" | "0.9.4" | "0.9.5" | "0.9.6" | "0.9.7" | "0.9.8" | "0.9.9" | "0.9.10" | "0.9.11" | "0.9.12" | "0.9.13" | "0.9.14" | "0.9.15" | "0.9.16" | "0.9.17" | "0.9.18" | "0.9.19" | "0.9.20" | "0.9.21" | "0.9.22" | "0.9.23" | "0.9.24" | "0.9.25" | "0.9.26" | "0.9.27";
+ version: "0.3.0" | "0.4.0" | "0.5.0" | "0.6.0" | "0.6.1" | "0.7.0" | "0.7.2" | "0.7.3" | "0.7.4" | "0.7.5" | "0.7.6" | "0.7.7" | "0.7.9" | "0.8.0" | "0.8.1" | "0.8.2" | "0.8.3" | "0.8.4" | "0.8.5" | "0.8.6" | "0.8.7" | "0.8.8" | "0.8.9" | "0.8.10" | "0.8.11" | "0.8.12" | "0.8.13" | "0.9.0" | "0.9.1" | "0.9.2" | "0.9.3" | "0.9.4" | "0.9.5" | "0.9.6" | "0.9.7" | "0.9.8" | "0.9.9" | "0.9.10" | "0.9.11" | "0.9.12" | "0.9.13" | "0.9.14" | "0.9.15" | "0.9.16" | "0.9.17" | "0.9.18" | "0.9.19" | "0.9.20" | "0.9.21" | "0.9.22" | "0.9.23" | "0.9.24" | "0.9.25" | "0.9.26" | "0.9.27" | "0.9.28";
exportedAt: string;
sessions: Session[];
observations: Record<string, CompressedObservation[]>;
@@ -483,6 +483,12 @@ 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;
}
export type ConsolidationTier =
diff --git a/src/version.ts b/src/version.ts
index 92784609..6d09f4f4 100644
--- a/src/version.ts
+++ b/src/version.ts
@@ -1 +1 @@
-export const VERSION = "0.9.27";
+export const VERSION = "0.9.28";
diff --git a/test/agent-isolation-search.test.ts b/test/agent-isolation-search.test.ts
new file mode 100644
index 00000000..929407b5
--- /dev/null
+++ b/test/agent-isolation-search.test.ts
@@ -0,0 +1,203 @@
+import { describe, it, expect, beforeEach, vi } from "vitest";
+
+vi.mock("../src/logger.js", () => ({
+ logger: { info: vi.fn(), warn: vi.fn(), error: vi.fn() },
+}));
+
+vi.mock("../src/state/keyed-mutex.js", () => ({
+ withKeyedLock: <T>(_key: string, fn: () => Promise<T>) => fn(),
+}));
+
+vi.mock("../src/functions/audit.js", () => ({
+ recordAudit: vi.fn(),
+}));
+
+vi.mock("../src/functions/access-tracker.js", () => ({
+ recordAccessBatch: vi.fn(),
+ deleteAccessLog: vi.fn(),
+}));
+
+const configState = {
+ agentId: undefined as string | undefined,
+ isolated: false,
+};
+
+vi.mock("../src/config.js", () => ({
+ getAgentId: () => configState.agentId,
+ isAgentScopeIsolated: () => configState.isolated,
+}));
+
+import {
+ registerSearchFunction,
+ getSearchIndex,
+ setIndexPersistence,
+} from "../src/functions/search.js";
+import { KV } from "../src/state/schema.js";
+import type { CompressedObservation, Session, SearchResult } from "../src/types.js";
+
+function makeMockKV() {
+ const store = new Map<string, Map<string, unknown>>();
+ return {
+ get: async <T>(scope: string, key: string): Promise<T | null> =>
+ (store.get(scope)?.get(key) as T) ?? null,
+ set: async <T>(scope: string, key: string, data: T): Promise<T> => {
+ if (!store.has(scope)) store.set(scope, new Map());
+ store.get(scope)!.set(key, data);
+ return data;
+ },
+ delete: async (scope: string, key: string): Promise<void> => {
+ store.get(scope)?.delete(key);
+ },
+ list: async <T>(scope: string): Promise<T[]> => {
+ const entries = store.get(scope);
+ return entries ? (Array.from(entries.values()) as T[]) : [];
+ },
+ };
+}
+
+function makeMockSdk() {
+ const functions = new Map<string, Function>();
+ return {
+ registerFunction: (id: string, handler: Function) => {
+ functions.set(id, handler);
+ },
+ registerTrigger: () => {},
+ trigger: async (
+ idOrInput: string | { function_id: string; payload: unknown },
+ data?: unknown,
+ ) => {
+ const id =
+ typeof idOrInput === "string" ? idOrInput : idOrInput.function_id;
+ const payload =
+ typeof idOrInput === "string" ? data : (idOrInput as { payload: unknown }).payload;
+ const fn = functions.get(id);
+ if (!fn) throw new Error(`No function registered: ${id}`);
+ return fn(payload);
+ },
+ };
+}
+
+async function seedTwoAgents(kv: ReturnType<typeof makeMockKV>) {
+ const sessionA: Session = {
+ id: "sess-a",
+ project: "shared",
+ cwd: "/work",
+ startTime: "2026-01-01T00:00:00Z",
+ type: "code",
+ } as Session;
+ const sessionB: Session = {
+ id: "sess-b",
+ project: "shared",
+ cwd: "/work",
+ startTime: "2026-01-01T00:00:00Z",
+ type: "code",
+ } as Session;
+ await kv.set(KV.sessions, sessionA.id, sessionA);
+ await kv.set(KV.sessions, sessionB.id, sessionB);
+
+ const obsA: CompressedObservation = {
+ id: "obs-a-secret",
+ sessionId: "sess-a",
+ timestamp: "2026-01-01T01:00:00Z",
+ type: "user_prompt",
+ title: "agent A private",
+ facts: ["SECRET_MARKER value AAA"],
+ narrative: "agent A wrote a secret",
+ concepts: ["secret", "private"],
+ files: [],
+ importance: 8,
+ agentId: "agent_a",
+ } as CompressedObservation;
+ const obsB: CompressedObservation = {
+ id: "obs-b-public",
+ sessionId: "sess-b",
+ timestamp: "2026-01-01T02:00:00Z",
+ type: "user_prompt",
+ title: "agent B note",
+ facts: ["SECRET_MARKER value BBB"],
+ narrative: "agent B wrote about the same marker",
+ concepts: ["secret"],
+ files: [],
+ importance: 6,
+ agentId: "agent_b",
+ } as CompressedObservation;
+ await kv.set(KV.observations("sess-a"), obsA.id, obsA);
+ await kv.set(KV.observations("sess-b"), obsB.id, obsB);
+
+ // Mirror the indexer's behavior so the BM25 path returns both rows.
+ const idx = getSearchIndex();
+ idx.add(obsA);
+ idx.add(obsB);
+}
+
+describe("mem::search agent-scope isolation (#817 follow-up)", () => {
+ let sdk: ReturnType<typeof makeMockSdk>;
+ let kv: ReturnType<typeof makeMockKV>;
+
+ beforeEach(() => {
+ sdk = makeMockSdk();
+ kv = makeMockKV();
+ setIndexPersistence(null);
+ // Reset index between tests.
+ const idx = getSearchIndex();
+ (idx as unknown as { clear?: () => void }).clear?.();
+ configState.agentId = undefined;
+ configState.isolated = false;
+ registerSearchFunction(sdk as never, kv as never);
+ });
+
+ it("isolated mode + env AGENT_ID excludes other agent's observations", async () => {
+ configState.isolated = true;
+ configState.agentId = "agent_a";
+ await seedTwoAgents(kv);
+
+ const result = (await sdk.trigger("mem::search", {
+ query: "SECRET_MARKER",
+ limit: 10,
+ })) as { results: SearchResult[] };
+ expect(result.results.length).toBeGreaterThan(0);
+ for (const r of result.results) {
+ expect(r.observation.agentId).toBe("agent_a");
+ }
+ expect(result.results.find((r) => r.observation.id === "obs-b-public")).toBeUndefined();
+ });
+
+ it('isolated mode + agentId: "*" wildcard bypasses and returns both agents', async () => {
+ configState.isolated = true;
+ configState.agentId = "agent_a";
+ await seedTwoAgents(kv);
+
+ const result = (await sdk.trigger("mem::search", {
+ query: "SECRET_MARKER",
+ limit: 10,
+ agentId: "*",
+ })) as { results: SearchResult[] };
+ const ids = result.results.map((r) => r.observation.id);
+ expect(ids).toContain("obs-a-secret");
+ expect(ids).toContain("obs-b-public");
+ });
+
+ it("isolated mode with no AGENT_ID fails closed (throws), does not leak", async () => {
+ configState.isolated = true;
+ configState.agentId = undefined;
+ await seedTwoAgents(kv);
+
+ await expect(
+ sdk.trigger("mem::search", { query: "SECRET_MARKER", limit: 10 }),
+ ).rejects.toThrow(/AGENTMEMORY_AGENT_SCOPE=isolated/);
+ });
+
+ it("non-isolated mode (default) returns all rows regardless of agentId", async () => {
+ configState.isolated = false;
+ configState.agentId = undefined;
+ await seedTwoAgents(kv);
+
+ const result = (await sdk.trigger("mem::search", {
+ query: "SECRET_MARKER",
+ limit: 10,
+ })) as { results: SearchResult[] };
+ const ids = result.results.map((r) => r.observation.id);
+ expect(ids).toContain("obs-a-secret");
+ expect(ids).toContain("obs-b-public");
+ });
+});
diff --git a/test/cross-project-isolation.test.ts b/test/cross-project-isolation.test.ts
index 8fc37498..6d76da3e 100644
--- a/test/cross-project-isolation.test.ts
+++ b/test/cross-project-isolation.test.ts
@@ -19,6 +19,7 @@ vi.mock("../src/functions/access-tracker.js", () => ({
vi.mock("../src/config.js", () => ({
getAgentId: () => undefined,
+ isAgentScopeIsolated: () => false,
}));
import { registerRememberFunction } from "../src/functions/remember.js";
diff --git a/test/export-import.test.ts b/test/export-import.test.ts
index 39498626..39c17cab 100644
--- a/test/export-import.test.ts
+++ b/test/export-import.test.ts
@@ -119,7 +119,7 @@ describe("Export/Import Functions", () => {
it("export produces valid ExportData structure", async () => {
const result = (await sdk.trigger("mem::export", {})) as ExportData;
- expect(result.version).toBe("0.9.27");
+ expect(result.version).toBe("0.9.28");
expect(result.exportedAt).toBeDefined();
expect(result.sessions.length).toBe(1);
expect(result.sessions[0].id).toBe("ses_1");
diff --git a/test/graph.test.ts b/test/graph.test.ts
index 3d0472af..da8b2665 100644
--- a/test/graph.test.ts
+++ b/test/graph.test.ts
@@ -254,7 +254,7 @@ describe("Graph Functions", () => {
// 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", {});
+ await sdk.trigger("mem::graph-snapshot-rebuild", { force: true });
const unbounded = (await sdk.trigger(
"mem::graph-query",
@@ -286,7 +286,7 @@ describe("Graph Functions", () => {
await kv.set("mem:graph:nodes", node.id, node);
}
- await sdk.trigger("mem::graph-snapshot-rebuild", {});
+ await sdk.trigger("mem::graph-snapshot-rebuild", { force: true });
const page1 = (await sdk.trigger("mem::graph-query", {
limit: 10,
@@ -322,7 +322,7 @@ describe("Graph Functions", () => {
});
}
- await sdk.trigger("mem::graph-snapshot-rebuild", {});
+ await sdk.trigger("mem::graph-snapshot-rebuild", { force: true });
const huge = (await sdk.trigger("mem::graph-query", {
limit: 999999,
@@ -373,7 +373,7 @@ describe("Graph Functions", () => {
lastSeen: "2026-01-01T00:00:00Z",
});
- await sdk.trigger("mem::graph-snapshot-rebuild", {});
+ await sdk.trigger("mem::graph-snapshot-rebuild", { force: true });
const page = (await sdk.trigger("mem::graph-query", {
limit: 10,
@@ -427,7 +427,7 @@ describe("Graph Functions", () => {
it("snapshot-rebuild persists top-degree subgraph + aggregate stats", async () => {
await seed(50, 100);
- const result = (await sdk.trigger("mem::graph-snapshot-rebuild", {})) as {
+ const result = (await sdk.trigger("mem::graph-snapshot-rebuild", { force: true })) as {
success: boolean;
totalNodes: number;
totalEdges: number;
@@ -456,7 +456,7 @@ describe("Graph Functions", () => {
it("graph-query empty-body branch serves from snapshot once it exists", async () => {
await seed(20, 30);
- await sdk.trigger("mem::graph-snapshot-rebuild", {});
+ await sdk.trigger("mem::graph-snapshot-rebuild", { force: true });
const result = (await sdk.trigger("mem::graph-query", {})) as GraphQueryResult;
expect(result.fromSnapshot).toBe(true);
@@ -466,7 +466,7 @@ describe("Graph Functions", () => {
it("graph-query nodeType filter respects snapshot type counts", async () => {
await seed(30, 0);
- await sdk.trigger("mem::graph-snapshot-rebuild", {});
+ await sdk.trigger("mem::graph-snapshot-rebuild", { force: true });
const fileQuery = (await sdk.trigger("mem::graph-query", {
nodeType: "file",
@@ -481,7 +481,7 @@ describe("Graph Functions", () => {
it("graph-stats returns from snapshot when not dirty", async () => {
await seed(15, 25);
- await sdk.trigger("mem::graph-snapshot-rebuild", {});
+ await sdk.trigger("mem::graph-snapshot-rebuild", { force: true });
const stats = (await sdk.trigger("mem::graph-stats", {})) as {
totalNodes: number;
@@ -559,31 +559,27 @@ describe("Graph Functions", () => {
expect(snap?.stats.totalNodes).toBe(0);
});
- it("graph-reset also wipes composite-key index scopes", async () => {
+ it("graph-reset writes empty snapshot; legacy rows stay as orphans (#825)", async () => {
await sdk.trigger("mem::graph-extract", { observations: [testObs] });
- // Index entries exist after the extract — name-index keyed by
- // type|name; degree keyed by nodeId; edge-key by composite
- // src|tgt|type.
+ // Index entries exist after the extract.
const nameBefore = await kv.get(
"mem:graph:name-index",
"file|src/index.ts",
);
expect(nameBefore).not.toBeNull();
- const edgeKeyBefore = await kv.list("mem:graph:edge-key");
- expect(edgeKeyBefore.length).toBeGreaterThan(0);
await sdk.trigger("mem::graph-reset", {});
- const nameAfter = await kv.get(
- "mem:graph:name-index",
- "file|src/index.ts",
- );
- expect(nameAfter).toBeNull();
- const edgeKeyAfter = await kv.list("mem:graph:edge-key");
- expect(edgeKeyAfter.length).toBe(0);
- // Same for the per-node degree counter.
- const degree = await kv.list("mem:graph:node-degree");
- expect(degree.length).toBe(0);
+ // 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");
+ expect(snap?.stats.totalNodes).toBe(0);
+ expect(snap?.stats.totalEdges).toBe(0);
});
});
@@ -679,11 +675,58 @@ describe("Graph Functions", () => {
const result = (await localSdk.trigger(
"mem::graph-snapshot-rebuild",
- {},
+ { force: true },
)) as { success: boolean; tooLarge?: boolean; totalNodes?: number };
expect(result.success).toBe(false);
expect(result.tooLarge).toBe(true);
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",
+ name: "legacy",
+ properties: {},
+ sourceObservationIds: [],
+ createdAt: "2026-01-01T00:00:00Z",
+ stale: false,
+ });
+ const localSdk = mockSdk();
+ registerGraphFunction(localSdk as never, localKv as never, mockProvider as never);
+
+ const result = (await localSdk.trigger(
+ "mem::graph-snapshot-rebuild",
+ {},
+ )) as { success: boolean; legacyCorpus?: boolean; error?: string };
+ expect(result.success).toBe(false);
+ expect(result.legacyCorpus).toBe(true);
+ expect(result.error).toMatch(/graph\/reset|force/);
+ });
+
+ it("graph-reset is enumeration-free (does not call kv.list)", async () => {
+ // Wrap the mock kv.list with a counter; assert it stays at 0
+ // across a full reset cycle.
+ const localKv = mockKV();
+ let listCalls = 0;
+ const baseList = localKv.list;
+ localKv.list = async <T,>(scope: string): Promise<T[]> => {
+ listCalls += 1;
+ return baseList.call(localKv, scope) as Promise<T[]>;
+ };
+ const localSdk = mockSdk();
+ registerGraphFunction(localSdk as never, localKv as never, mockProvider as never);
+
+ const result = (await localSdk.trigger("mem::graph-reset", {})) as {
+ success: boolean;
+ };
+ expect(result.success).toBe(true);
+ expect(listCalls).toBe(0);
+ });
});
});