#1 Persistent memory for AI coding agents based on real-world benchmarks
TypeScript agentmemoryagentsaiclaudeclaudecodecodexcopilotcursorgenaiharnesshermesmemoryompopenclawopencodepi
feat(scope): AGENT_ID multi-agent isolation; docs(cost,supply-chain) (#654)
Rohit Ghumare1aec56a88535
diff --git a/README.md b/README.mdindex 04137b75..e44ba0a5 100644--- a/README.md+++ b/README.md@@ -1092,6 +1092,51 @@ agentmemory auto-detects from your environment. By default, no LLM calls are mad| OpenRouter | `OPENROUTER_API_KEY` | Any model || Claude subscription fallback | `AGENTMEMORY_ALLOW_AGENT_SDK=true` | Opt-in only. Spawns `@anthropic-ai/claude-agent-sdk` sessions — used to cause unbounded Stop-hook recursion (#149 follow-up) so it is no longer the default. |+### Cost-aware model selection++Background compression runs on every observation, so model choice meaningfully changes monthly spend. Captured workload data: 635 requests / 888K tokens / 35 hours of active use, run against three OpenRouter models at 2026-05-23 pricing.++| Tier | Model | Input / 1M | Output / 1M | Cost for the captured 35h | Notes |+|------|-------|------------|-------------|---------------------------|-------|+| Recommended | `deepseek/deepseek-v4-pro` | $0.435 | $0.87 | ~$0.46 | Solid compression + summarization quality at ~10× lower cost than Sonnet. |+| Recommended | `deepseek/deepseek-chat` | $0.27 | $1.10 | ~$0.40 | Older but still fine for compression-only workloads. |+| Recommended | `qwen/qwen3-coder` | $0.45 | $1.80 | ~$0.55 | Strong code reasoning if your sessions are heavily code-shaped. |+| Premium | `anthropic/claude-sonnet-4.6` | $3.00 | $15.00 | ~$5.02 | High quality but expensive for always-on background work. |+| Premium | `openai/gpt-4o` | $2.50 | $10.00 | ~$4.20 | Similar tier to Sonnet. |+| Avoid | `anthropic/claude-opus-4.6` | $15.00 | $75.00 | ~$25+ | Reasoning-class model; massive overspend for compression. |++agentmemory prints a runtime warning when `OPENROUTER_MODEL` matches a premium-tier pattern. Set `AGENTMEMORY_SUPPRESS_COST_WARNING=1` to silence once you've made an informed choice.++Quality vs cost tradeoff for memory work: compression is a summarization task with relatively loose quality bars (the agent re-reads the summary, not the user). DeepSeek-V4-Pro / Qwen3-Coder land within rounding error of Sonnet on this task while costing ~10× less. Save the premium-tier models for queries you read directly.++Sources: [OpenRouter pricing for Sonnet 4.6](https://openrouter.ai/anthropic/claude-sonnet-4.6/pricing), [DeepSeek V4 Pro](https://openrouter.ai/deepseek/deepseek-v4-pro), [DeepSeek pricing notes](https://api-docs.deepseek.com/quick_start/pricing/).++### Multi-agent memory (`AGENT_ID` + `AGENTMEMORY_AGENT_SCOPE`)++In multi-agent setups where several roles share one agentmemory server (architect / developer / reviewer / researcher / support-agent), `AGENT_ID` tags every write with the role that made it. `AGENTMEMORY_AGENT_SCOPE` controls whether recall filters by that tag.++```env+TEAM_ID=company+USER_ID=engineering-team+AGENT_ID=architect+AGENTMEMORY_AGENT_SCOPE=isolated # optional; default "shared"+```++Two modes:++| Mode | Tag writes | Filter recall | When to use |+|------|------------|---------------|-------------|+| `shared` (default) | yes | no | Cross-agent context with audit trail. Architect can see what developer noted, but every row records who said it. |+| `isolated` | yes | yes | Strict separation. Architect never sees developer's observations / memories / sessions. |++What gets tagged when `AGENT_ID` is set: `Session.agentId`, `RawObservation.agentId`, `CompressedObservation.agentId`, `Memory.agentId`. The role flows from `api::session::start` → `mem::observe` → `mem::compress` → KV.++What gets filtered in isolated mode: `mem::smart-search`, `/agentmemory/memories`, `/agentmemory/observations`, `/agentmemory/sessions`. Each endpoint accepts `?agentId=<role>` to override per-request, and `?agentId=*` to opt out of the env scope entirely. `/memories` also accepts `?includeOrphans=true` to surface pre-AGENT_ID memories whose `agentId` is undefined.++Per-call override at the SDK / REST layer: every mutating endpoint (`/session/start`, `/remember`) accepts an `agentId` field in the request body that wins over the env. Useful for runtimes routing many roles through one server process.++When `AGENT_ID` is unset, memory remains unscoped (legacy behavior, no tags, no filters).+### Portsagentmemory + iii-engine bind four ports by default. If a restart fails with `port in use`, this table tells you which process to look for.diff --git a/SECURITY.md b/SECURITY.mdindex f5980ec3..a24b6e96 100644--- a/SECURITY.md+++ b/SECURITY.md@@ -50,6 +50,32 @@ Out of scope:- `iii-sdk` upstream — report to the iii project.- The marketing site under `website/` unless the issue affects user security (XSS against visitors, credential leak in build output).+## Supply-chain stance++agentmemory ships pre-built artifacts in the npm tarball — `dist/` is bundled at publish time, not built from `node_modules` at install time. The package's runtime dependency tree is intentionally small (6 production deps: `@anthropic-ai/sdk`, `@anthropic-ai/claude-agent-sdk`, `@clack/prompts`, `dotenv`, `iii-sdk`, `zod`) plus an optional set guarded behind `optionalDependencies` for embeddings.++**No lockfile is committed** (#540). The reasoning:++- The npm tarball ships pre-built `dist/` — fresh installs don't compile from source, so no lockfile is consulted at the user's install step.+- The lockfile only affects contributor-local builds. Pinning it would shift the supply-chain attack surface from "what npm resolves today" to "what was resolved when the lockfile was last regenerated," which is a different tradeoff, not strictly better.+- We use SemVer ranges (`^x.y.z`) on the published deps so security patches reach users without a re-release.++If you ship agentmemory inside a hardened pipeline that requires reproducible installs, the recommended path is:++1. `npm install --legacy-peer-deps` against the published tarball in a controlled environment.+2. `npm shrinkwrap` to produce a versioned `npm-shrinkwrap.json` that travels with your deployment.+3. Audit `node_modules/` once at that point and republish internally.++CI runs `npm install --package-lock-only --legacy-peer-deps --no-audit --no-fund` then `npm ci` against that generated lockfile, so every test job builds against a fully resolved tree. The lockfile is regenerated on each CI run rather than checked in, which keeps the published tarball aligned with whatever SemVer-compatible patch level was current at release time.++Supply-chain monitoring we already do:++- Dependabot opens PRs for every minor/patch bump on the production dep list (visible in the open PRs).+- Every PR runs the full test suite on ubuntu-latest + macos-latest, Node 20 + 22, before any merge.+- `optionalDependencies` (`@xenova/transformers`, `onnxruntime-node`, etc.) are guarded by `try { await import("...") } catch` so a missing or compromised optional dep cannot break the core runtime path.++If you find a malicious package in our dep tree, file via the GHSA flow at the top of this document — that's the fastest path to a fixed release on npm.+## Past advisoriesSee the [`.github/security-advisories/`](./.github/security-advisories) directory for advisory drafts. Published advisories (with assigned GHSA IDs) live at <https://github.com/rohitg00/agentmemory/security/advisories>.diff --git a/src/config.ts b/src/config.tsindex 004e7d0f..beaab034 100644--- a/src/config.ts+++ b/src/config.ts@@ -19,6 +19,8 @@ function safeParseInt(value: string | undefined, fallback: number): number {const DATA_DIR = join(homedir(), ".agentmemory");const ENV_FILE = join(DATA_DIR, ".env");+let warnPremiumModelShown = false;+function loadEnvFile(): Record<string, string> {if (!existsSync(ENV_FILE)) return {};const content = readFileSync(ENV_FILE, "utf-8");@@ -91,9 +93,32 @@ function detectProvider(env: Record<string, string>): ProviderConfig {};}if (hasRealValue(env["OPENROUTER_API_KEY"])) {+ const model =+ env["OPENROUTER_MODEL"] || "anthropic/claude-sonnet-4-20250514";+ // #613: warn when the configured OpenRouter model is in the+ // premium tier and likely to burn money on background compression.+ // Captured workload data shows ~$5/35h on claude-sonnet-4 vs+ // ~$0.46/35h on deepseek-v4-pro for the same compression mix.+ // Heuristic match avoids hard-coding a pricing table.+ if (+ !warnPremiumModelShown &&+ /sonnet|opus|gpt-4o(?!.*mini)|gpt-4-turbo/i.test(model) &&+ env["AGENTMEMORY_SUPPRESS_COST_WARNING"] !== "1" &&+ env["AGENTMEMORY_SUPPRESS_COST_WARNING"] !== "true"+ ) {+ warnPremiumModelShown = true;+ process.stderr.write(+ `[agentmemory] OPENROUTER_MODEL=${model} is in the premium tier. ` ++ `Background compression on this model can cost $5+/day under active use. ` ++ `Cheaper alternatives with comparable quality for memory compression: ` ++ `deepseek/deepseek-v4-pro, deepseek/deepseek-chat, qwen/qwen3-coder. ` ++ `See README "Cost-aware model selection" for the full table. ` ++ `Set AGENTMEMORY_SUPPRESS_COST_WARNING=1 to silence.\n`,+ );+ }return {provider: "openrouter",- model: env["OPENROUTER_MODEL"] || "anthropic/claude-sonnet-4-20250514",+ model,maxTokens,};}@@ -244,6 +269,38 @@ export function loadTeamConfig(): TeamConfig | null {return { teamId, userId, mode };}+// #554: optional AGENT_ID env for multi-agent memory isolation.+// Returns null when unset so memory stays unscoped (legacy behavior).+// Trimmed + length-capped to keep KV writes well-formed.+//+// Filtering is gated by AGENTMEMORY_AGENT_SCOPE:+// "shared" (default) — tag everything, do not filter recall paths+// "isolated" — tag everything AND filter recall paths+export function loadAgentScope(): {+ agentId: string;+ mode: "shared" | "isolated";+} | null {+ const env = getMergedEnv();+ const raw = env["AGENT_ID"];+ if (!raw) return null;+ const agentId = raw.trim().slice(0, 128);+ if (!agentId) return null;+ const mode = env["AGENTMEMORY_AGENT_SCOPE"] === "isolated"+ ? "isolated"+ : "shared";+ return { agentId, mode };+}++export function getAgentId(): string | undefined {+ return loadAgentScope()?.agentId;+}++// True only when AGENT_ID is set AND scope=isolated. Recall paths+// consult this to decide whether to filter.+export function isAgentScopeIsolated(): boolean {+ return loadAgentScope()?.mode === "isolated";+}+export function loadSnapshotConfig(): {enabled: boolean;interval: number;diff --git a/src/functions/compress-synthetic.ts b/src/functions/compress-synthetic.tsindex 93f5f902..8cfd0202 100644--- a/src/functions/compress-synthetic.ts+++ b/src/functions/compress-synthetic.ts@@ -101,5 +101,7 @@ export function buildSyntheticCompression(};if (raw.modality) result.modality = raw.modality;if (raw.imageData) result.imageData = raw.imageData;+ // #554: carry the role through synthetic compression too.+ if (raw.agentId) result.agentId = raw.agentId;return result;}diff --git a/src/functions/compress.ts b/src/functions/compress.tsindex af3973cb..38a7fdea 100644--- a/src/functions/compress.ts+++ b/src/functions/compress.ts@@ -165,6 +165,8 @@ export function registerCompressFunction(...(hasImage ? { modality: data.raw.modality } : {}),...(imageDescription ? { imageDescription } : {}),...(data.raw.imageData ? { imageRef: data.raw.imageData } : {}),+ // #554: carry the role through LLM compression too.+ ...(data.raw.agentId ? { agentId: data.raw.agentId } : {}),};await kv.set(diff --git a/src/functions/observe.ts b/src/functions/observe.tsindex 6994bdc5..c9aaa7aa 100644--- a/src/functions/observe.ts+++ b/src/functions/observe.ts@@ -8,6 +8,7 @@ import { withKeyedLock } from "../state/keyed-mutex.js";import { isAutoCompressEnabled } from "../config.js";import { buildSyntheticCompression } from "./compress-synthetic.js";import { getSearchIndex, vectorIndexAddGuarded } from "./search.js";+import { getAgentId } from "../config.js";import { logger } from "../logger.js";export function extractImage(d: unknown): string | undefined {@@ -133,6 +134,29 @@ export function registerObserveFunction(}}+ // #554: inherit agentId from the parent session so every+ // observation carries the role that wrote it. Pre-existing+ // session takes precedence (multi-agent runtime stamped at+ // session/start), env AGENT_ID is the fallback for the+ // implicit-create path (#638) where session doesn't exist yet.+ // We reuse this lookup later for observationCount/firstPrompt.+ const existingSession = await kv.get<{+ agentId?: string;+ observationCount?: number;+ firstPrompt?: string;+ }>(KV.sessions, payload.sessionId);+ // Existing session wins absolutely — even if its agentId is+ // undefined. env AGENT_ID only fires on the implicit-create+ // path where no session row exists yet (#638). Otherwise an+ // unscoped session would get retroactively scoped by whatever+ // AGENT_ID was set on the server later.+ const inheritedAgentId = existingSession+ ? existingSession.agentId+ : getAgentId();+ if (inheritedAgentId) {+ raw.agentId = inheritedAgentId;+ }+if (pendingImageData && (pendingImageData.startsWith("data:image/") || pendingImageData.startsWith("iVBORw0KGgo") || pendingImageData.startsWith("/9j/"))) {const { saveImageToDisk } = await import("../utils/image-store.js");const { filePath, bytesWritten } = await saveImageToDisk(pendingImageData);@@ -190,10 +214,7 @@ export function registerObserveFunction(action: TriggerAction.Void(),});- const session = await kv.get<{ observationCount?: number; firstPrompt?: string }>(- KV.sessions,- payload.sessionId,- );+ const session = existingSession;if (session) {const updates: Array<{ type: "set"; path: string; value: unknown }> = [{ type: "set", path: "updatedAt", value: new Date().toISOString() },@@ -241,6 +262,9 @@ export function registerObserveFunction(updatedAt: ts,status: "active",observationCount: 1,+ // #554: implicit-create path also stamps agentId so the+ // session row matches its child observations.+ ...(inheritedAgentId ? { agentId: inheritedAgentId } : {}),...(trimmedPrompt && trimmedPrompt.length > 0? { firstPrompt: trimmedPrompt }: {}),diff --git a/src/functions/remember.ts b/src/functions/remember.tsindex 30199ecd..247d927f 100644--- a/src/functions/remember.ts+++ b/src/functions/remember.ts@@ -7,6 +7,7 @@ import { memoryToObservation } from "../state/memory-utils.js";import { deleteAccessLog } from "./access-tracker.js";import { recordAudit } from "./audit.js";import { getSearchIndex, vectorIndexAddGuarded, vectorIndexRemove, flushIndexSave } from "./search.js";+import { getAgentId } from "../config.js";import { logger } from "../logger.js";export function registerRememberFunction(sdk: ISdk, kv: StateKV): void {@@ -18,6 +19,7 @@ export function registerRememberFunction(sdk: ISdk, kv: StateKV): void {files?: string[];ttlDays?: number;sourceObservationIds?: string[];+ agentId?: string;}) => {if (!data.content ||@@ -69,6 +71,14 @@ export function registerRememberFunction(sdk: ISdk, kv: StateKV): void {}}+ // #554: stamp the agent role on the memory so future recall can+ // filter by agent. Request body wins (multi-agent runtimes+ // explicitly tagging at write time), env AGENT_ID fallback,+ // none → memory is unscoped (legacy behavior).+ const callAgentId =+ typeof data.agentId === "string" && data.agentId.trim().length > 0+ ? data.agentId.trim().slice(0, 128)+ : getAgentId();const memory: Memory = {id: generateId("mem"),createdAt: now,@@ -87,6 +97,7 @@ export function registerRememberFunction(sdk: ISdk, kv: StateKV): void {(id): id is string => typeof id === "string" && id.length > 0,),isLatest: true,+ ...(callAgentId ? { agentId: callAgentId } : {}),};if (data.ttlDays && typeof data.ttlDays === "number" && data.ttlDays > 0) {diff --git a/src/functions/smart-search.ts b/src/functions/smart-search.tsindex c80b1f87..6ca6b828 100644--- a/src/functions/smart-search.ts+++ b/src/functions/smart-search.ts@@ -9,6 +9,7 @@ import type {import { KV } from "../state/schema.js";import { StateKV } from "../state/kv.js";import { recordAccessBatch } from "./access-tracker.js";+import { getAgentId, isAgentScopeIsolated } from "../config.js";import { logger } from "../logger.js";// Compact mode trims each lesson's content for at-a-glance display. The@@ -27,8 +28,25 @@ export function registerSmartSearchFunction(limit?: number;project?: string;includeLessons?: boolean;+ // #554: optional per-call agent filter for runtimes routing many+ // roles through one server. "*" opts out of the env-default+ // scope and returns hits from every agent.+ agentId?: 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).+ const isolated = isAgentScopeIsolated();+ const explicitAgentId =+ typeof data.agentId === "string" && data.agentId.trim().length > 0+ ? data.agentId.trim()+ : undefined;+ const wildcardAgent = explicitAgentId === "*";+ const filterAgentId = wildcardAgent+ ? undefined+ : explicitAgentId ?? (isolated ? getAgentId() : undefined);+if (data.expandIds && data.expandIds.length > 0) {const raw = data.expandIds.slice(0, 20);const items = raw.map((entry) => {@@ -56,19 +74,24 @@ export function registerSmartSearchFunction(if (r) expanded.push(r);}+ const scoped = filterAgentId+ ? expanded.filter((e) => e.observation.agentId === filterAgentId)+ : expanded;+void recordAccessBatch(kv,- expanded.map((e) => e.observation.id),+ scoped.map((e) => e.observation.id),);const truncated = data.expandIds.length > raw.length;logger.info("Smart search expanded", {requested: data.expandIds.length,attempted: raw.length,- returned: expanded.length,+ returned: scoped.length,+ filteredOutOfScope: expanded.length - scoped.length,truncated,});- return { mode: "expanded", results: expanded, truncated };+ return { mode: "expanded", results: scoped, truncated };}if (!data.query || typeof data.query !== "string" || !data.query.trim()) {@@ -76,23 +99,35 @@ export function registerSmartSearchFunction(}const limit = Math.max(1, Math.min(data.limit ?? 20, 100));- // Cap lesson results at a smaller number than observations: lessons- // are denser (curated insights) so 10 is usually plenty for a recall.+ // Lesson recall stays capped: lessons are denser than raw+ // observations so 10 covers most recall flows.const lessonLimit = Math.min(limit, 10);const includeLessons = data.includeLessons !== false;- // Run observation hybrid-search and lesson recall in parallel so the- // extra lesson lookup adds no wallclock when the underlying calls- // can overlap. Lesson recall is best-effort: if mem::lesson-recall- // fails or returns unexpected shape, log + fall back to empty.+ // Over-fetch when filtering. Hybrid search can't filter on+ // agentId (BM25/vector indexes don't carry it), so we ask the+ // searcher for more hits than we need and trim post-filter. 3×+ // is a defensible middle ground: enough headroom for a small+ // workload, capped at 300 so a 100-limit request never asks for+ // thousands of hits.+ const overFetchLimit = filterAgentId+ ? Math.min(limit * 3, 300)+ : limit;+const [hybridResults, lessons] = await Promise.all([- searchFn(data.query, limit),+ searchFn(data.query, overFetchLimit),includeLessons? recallLessons(sdk, data.query, lessonLimit, data.project): Promise.resolve([]),]);- const compact: CompactSearchResult[] = hybridResults.map((r) => ({+ const filteredHybrid = filterAgentId+ ? hybridResults+ .filter((r) => r.observation.agentId === filterAgentId)+ .slice(0, limit)+ : hybridResults.slice(0, limit);++ const compact: CompactSearchResult[] = filteredHybrid.map((r) => ({obsId: r.observation.id,sessionId: r.sessionId,title: r.observation.title,diff --git a/src/triggers/api.ts b/src/triggers/api.tsindex 57c28a86..fbef98c8 100644--- a/src/triggers/api.ts+++ b/src/triggers/api.ts@@ -18,6 +18,8 @@ import {isContextInjectionEnabled,detectEmbeddingProvider,detectLlmProviderKind,+ getAgentId,+ isAgentScopeIsolated,} from "../config.js";type Response = {@@ -536,6 +538,14 @@ export function registerApiTriggers(};}const title = typeof body.title === "string" ? body.title.trim() : undefined;+ // #554: allow session/start to override AGENT_ID from request body+ // (multi-agent runtimes that route many roles through one server+ // process). Falls back to the AGENT_ID env on the server.+ const requestAgentId =+ typeof body.agentId === "string" && body.agentId.trim().length > 0+ ? body.agentId.trim().slice(0, 128)+ : undefined;+ const agentId = requestAgentId ?? getAgentId();const session: Session = {id: sessionId,project,@@ -545,6 +555,7 @@ export function registerApiTriggers(observationCount: 0,...(title ? { summary: title.slice(0, 200) } : {}),...(title ? { firstPrompt: title.slice(0, 200) } : {}),+ ...(agentId ? { agentId } : {}),};await kv.set(KV.sessions, sessionId, session);const contextResult = await sdk.trigger<@@ -749,7 +760,21 @@ export function registerApiTriggers(const authErr = checkAuth(req, secret);if (authErr) return authErr;const sessions = await kv.list<Session>(KV.sessions);- return { status_code: 200, body: { sessions } };+ const normalizedAgentId =+ typeof req.query_params?.["agentId"] === "string"+ ? req.query_params["agentId"].trim()+ : undefined;+ const wildcardAgent = normalizedAgentId === "*";+ const explicitAgentId =+ normalizedAgentId && !wildcardAgent ? normalizedAgentId : undefined;+ const filterAgentId = wildcardAgent+ ? undefined+ : explicitAgentId ??+ (isAgentScopeIsolated() ? getAgentId() : undefined);+ const filtered = filterAgentId+ ? sessions.filter((s) => s.agentId === filterAgentId)+ : sessions;+ return { status_code: 200, body: { sessions: filtered } };},);sdk.registerTrigger({@@ -758,7 +783,7 @@ export function registerApiTriggers(config: { api_path: "/agentmemory/sessions", http_method: "GET" },});- sdk.registerFunction("api::observations",+ sdk.registerFunction("api::observations",async (req: ApiRequest): Promise<Response> => {const authErr = checkAuth(req, secret);if (authErr) return authErr;@@ -768,7 +793,21 @@ export function registerApiTriggers(const observations = await kv.list<CompressedObservation>(KV.observations(sessionId),);- return { status_code: 200, body: { observations } };+ const normalizedAgentId =+ typeof req.query_params?.["agentId"] === "string"+ ? req.query_params["agentId"].trim()+ : undefined;+ const wildcardAgent = normalizedAgentId === "*";+ const explicitAgentId =+ normalizedAgentId && !wildcardAgent ? normalizedAgentId : undefined;+ const filterAgentId = wildcardAgent+ ? undefined+ : explicitAgentId ??+ (isAgentScopeIsolated() ? getAgentId() : undefined);+ const filtered = filterAgentId+ ? observations.filter((o) => o.agentId === filterAgentId)+ : observations;+ return { status_code: 200, body: { observations: filtered } };},);sdk.registerTrigger({@@ -1491,7 +1530,31 @@ export function registerApiTriggers(if (authErr) return authErr;const memories = await kv.list<import("../types.js").Memory>(KV.memories);const latest = req.query_params?.["latest"] === "true";- const filtered = latest ? memories.filter((m) => m.isLatest) : memories;+ // #554: agentId filter. Request param wins, env AGENT_ID (when+ // scope=isolated) is the fallback. Shared mode keeps the tag but+ // does not restrict the list endpoint. Pass agentId=* to opt out+ // of the env scope entirely. includeOrphans=true surfaces+ // pre-AGENT_ID memories whose agentId is undefined.+ const normalizedAgentId =+ typeof req.query_params?.["agentId"] === "string"+ ? req.query_params["agentId"].trim()+ : undefined;+ const wildcardAgent = normalizedAgentId === "*";+ const explicitAgentId =+ normalizedAgentId && !wildcardAgent ? normalizedAgentId : undefined;+ const includeOrphans =+ req.query_params?.["includeOrphans"] === "true";+ const filterAgentId = wildcardAgent+ ? undefined+ : explicitAgentId ?? (isAgentScopeIsolated() ? getAgentId() : undefined);+ let filtered = latest ? memories.filter((m) => m.isLatest) : memories;+ if (filterAgentId) {+ filtered = filtered.filter(+ (m) =>+ m.agentId === filterAgentId ||+ (includeOrphans && m.agentId === undefined),+ );+ }// #544: viewer + `agentmemory status` were hitting this endpoint to// count memories. On a real corpus (8K+ memories) the unbounded@@ -1501,11 +1564,14 @@ export function registerApiTriggers(// ?count=true — totals only, no payload// ?limit=N&offset=M — page slice (default unlimited for back-compat)if (req.query_params?.["count"] === "true") {+ // Match the SAME scope that the list path applies — returning+ // unfiltered totals here would leak cross-agent counts to a+ // caller that's blocked from the underlying rows.return {status_code: 200,body: {- total: memories.length,- latestCount: memories.filter((m) => m.isLatest).length,+ total: filtered.length,+ latestCount: filtered.filter((m) => m.isLatest).length,},};}diff --git a/src/types.ts b/src/types.tsindex 72e347b3..967cf6d7 100644--- a/src/types.ts+++ b/src/types.ts@@ -11,6 +11,7 @@ export interface Session {firstPrompt?: string;summary?: string;commitShas?: string[];+ agentId?: string;}export interface CommitLink {@@ -39,6 +40,7 @@ export interface RawObservation {raw: unknown;modality?: "text" | "image" | "mixed";imageData?: string;+ agentId?: string;}export interface CompressedObservation {@@ -58,7 +60,7 @@ export interface CompressedObservation {imageData?: string;imageDescription?: string;modality?: "text" | "image" | "mixed";-+ agentId?: string;}export type ObservationType =@@ -98,6 +100,7 @@ export interface Memory {forgetAfter?: string;imageRef?: string;imageData?: string;+ agentId?: string;}export interface SessionSummary {@@ -477,6 +480,12 @@ export interface TeamConfig {mode: "shared" | "private";}+export type AgentScopeMode = "shared" | "isolated";+export interface AgentScope {+ agentId: string;+ mode: AgentScopeMode;+}+export interface TeamSharedItem {id: string;sharedBy: string;diff --git a/test/agent-id-scope.test.ts b/test/agent-id-scope.test.tsnew file mode 100644index 00000000..4539e213--- /dev/null+++ b/test/agent-id-scope.test.ts@@ -0,0 +1,269 @@+import { describe, it, expect, beforeEach, afterEach, vi } from "vitest";++vi.mock("../src/logger.js", () => ({+ logger: { info: vi.fn(), warn: vi.fn(), error: vi.fn() },+}));++// #554: AGENT_ID scope for multi-agent memory isolation.++describe("loadAgentScope (#554)", () => {+ const ORIG = process.env["AGENT_ID"];+ beforeEach(() => {+ vi.resetModules();+ delete process.env["AGENT_ID"];+ });+ afterEach(() => {+ if (ORIG === undefined) delete process.env["AGENT_ID"];+ else process.env["AGENT_ID"] = ORIG;+ });++ it("returns null when AGENT_ID is unset", async () => {+ const { loadAgentScope, getAgentId } = await import("../src/config.js");+ expect(loadAgentScope()).toBeNull();+ expect(getAgentId()).toBeUndefined();+ });++ it("returns the agentId + scope mode when AGENT_ID is set", async () => {+ process.env["AGENT_ID"] = "architect";+ const { loadAgentScope, getAgentId } = await import("../src/config.js");+ expect(loadAgentScope()).toEqual({ agentId: "architect", mode: "shared" });+ expect(getAgentId()).toBe("architect");+ });++ it("trims whitespace and rejects empty after trim", async () => {+ process.env["AGENT_ID"] = " ";+ const { loadAgentScope } = await import("../src/config.js");+ expect(loadAgentScope()).toBeNull();+ });++ it("caps length at 128 chars to keep KV writes well-formed", async () => {+ process.env["AGENT_ID"] = "x".repeat(500);+ const { getAgentId } = await import("../src/config.js");+ expect(getAgentId()!.length).toBe(128);+ });+});++describe("mem::remember stamps agentId on the Memory (#554)", () => {+ const ORIG = process.env["AGENT_ID"];+ beforeEach(() => {+ vi.resetModules();+ delete process.env["AGENT_ID"];+ });+ afterEach(() => {+ if (ORIG === undefined) delete process.env["AGENT_ID"];+ else process.env["AGENT_ID"] = ORIG;+ });++ function mockKV() {+ const store = new Map<string, Map<string, unknown>>();+ return {+ store,+ get: async <T>(scope: string, key: string): Promise<T | null> =>+ (store.get(scope)?.get(key) as T) ?? null,+ set: async <T>(scope: string, key: string, data: T): Promise<T> => {+ if (!store.has(scope)) store.set(scope, new Map());+ store.get(scope)!.set(key, data);+ return data;+ },+ delete: async (scope: string, key: string) => {+ store.get(scope)?.delete(key);+ },+ list: async <T>(scope: string): Promise<T[]> => {+ const m = store.get(scope);+ return m ? (Array.from(m.values()) as T[]) : [];+ },+ };+ }++ function mockSdk() {+ const fns = new Map<string, Function>();+ return {+ fns,+ registerFunction: (idOrOpts: string | { id: string }, fn: Function) => {+ const id = typeof idOrOpts === "string" ? idOrOpts : idOrOpts.id;+ fns.set(id, fn);+ },+ 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.payload;+ const fn = fns.get(id);+ if (fn) return fn(payload);+ return null;+ },+ };+ }++ it("stamps env AGENT_ID on Memory when no body override", async () => {+ process.env["AGENT_ID"] = "developer";+ const { registerRememberFunction } = await import(+ "../src/functions/remember.js"+ );+ const sdk = mockSdk();+ const kv = mockKV();+ registerRememberFunction(sdk as never, kv as never);++ const result = (await sdk.trigger("mem::remember", {+ content: "prefer async-std over tokio",+ type: "preference",+ })) as { memory: { id: string; agentId?: string } };++ expect(result.memory.agentId).toBe("developer");+ });++ it("body agentId overrides env AGENT_ID", async () => {+ process.env["AGENT_ID"] = "architect";+ const { registerRememberFunction } = await import(+ "../src/functions/remember.js"+ );+ const sdk = mockSdk();+ const kv = mockKV();+ registerRememberFunction(sdk as never, kv as never);++ const result = (await sdk.trigger("mem::remember", {+ content: "use http-cache for github API",+ agentId: "reviewer",+ })) as { memory: { id: string; agentId?: string } };++ expect(result.memory.agentId).toBe("reviewer");+ });++ it("no env, no body → no agentId on Memory (legacy)", async () => {+ const { registerRememberFunction } = await import(+ "../src/functions/remember.js"+ );+ const sdk = mockSdk();+ const kv = mockKV();+ registerRememberFunction(sdk as never, kv as never);++ const result = (await sdk.trigger("mem::remember", {+ content: "legacy unscoped memory",+ })) as { memory: { id: string; agentId?: string } };++ expect(result.memory.agentId).toBeUndefined();+ });++ it("body agentId is trimmed of leading/trailing whitespace", async () => {+ const { registerRememberFunction } = await import(+ "../src/functions/remember.js"+ );+ const sdk = mockSdk();+ const kv = mockKV();+ registerRememberFunction(sdk as never, kv as never);++ const result = (await sdk.trigger("mem::remember", {+ content: "trim me",+ agentId: " architect ",+ })) as { memory: { id: string; agentId?: string } };++ expect(result.memory.agentId).toBe("architect");+ });++ it("body agentId longer than 128 chars is truncated to 128", async () => {+ const { registerRememberFunction } = await import(+ "../src/functions/remember.js"+ );+ const sdk = mockSdk();+ const kv = mockKV();+ registerRememberFunction(sdk as never, kv as never);++ const long = "x".repeat(500);+ const result = (await sdk.trigger("mem::remember", {+ content: "cap length",+ agentId: long,+ })) as { memory: { id: string; agentId?: string } };++ expect(result.memory.agentId).toBeDefined();+ expect(result.memory.agentId!.length).toBe(128);+ expect(result.memory.agentId).toBe("x".repeat(128));+ });++ it("whitespace-only body agentId falls back to env AGENT_ID", async () => {+ process.env["AGENT_ID"] = "developer";+ const { registerRememberFunction } = await import(+ "../src/functions/remember.js"+ );+ const sdk = mockSdk();+ const kv = mockKV();+ registerRememberFunction(sdk as never, kv as never);++ const result = (await sdk.trigger("mem::remember", {+ content: "fall through to env",+ agentId: " ",+ })) as { memory: { id: string; agentId?: string } };++ expect(result.memory.agentId).toBe("developer");+ });++ it("empty-string body agentId with no env → no agentId stamped", async () => {+ const { registerRememberFunction } = await import(+ "../src/functions/remember.js"+ );+ const sdk = mockSdk();+ const kv = mockKV();+ registerRememberFunction(sdk as never, kv as never);++ const result = (await sdk.trigger("mem::remember", {+ content: "no env no usable body",+ agentId: "",+ })) as { memory: { id: string; agentId?: string } };++ expect(result.memory.agentId).toBeUndefined();+ });+});++describe("AGENTMEMORY_AGENT_SCOPE mode (#554)", () => {+ const ORIG_ID = process.env["AGENT_ID"];+ const ORIG_MODE = process.env["AGENTMEMORY_AGENT_SCOPE"];+ beforeEach(() => {+ vi.resetModules();+ delete process.env["AGENT_ID"];+ delete process.env["AGENTMEMORY_AGENT_SCOPE"];+ });+ afterEach(() => {+ if (ORIG_ID === undefined) delete process.env["AGENT_ID"];+ else process.env["AGENT_ID"] = ORIG_ID;+ if (ORIG_MODE === undefined) delete process.env["AGENTMEMORY_AGENT_SCOPE"];+ else process.env["AGENTMEMORY_AGENT_SCOPE"] = ORIG_MODE;+ });++ it("defaults to shared mode when AGENT_ID set but scope unset", async () => {+ process.env["AGENT_ID"] = "developer";+ const { loadAgentScope, isAgentScopeIsolated } = await import(+ "../src/config.js"+ );+ expect(loadAgentScope()).toEqual({+ agentId: "developer",+ mode: "shared",+ });+ expect(isAgentScopeIsolated()).toBe(false);+ });++ it("flips to isolated when AGENTMEMORY_AGENT_SCOPE=isolated", async () => {+ process.env["AGENT_ID"] = "developer";+ process.env["AGENTMEMORY_AGENT_SCOPE"] = "isolated";+ const { loadAgentScope, isAgentScopeIsolated } = await import(+ "../src/config.js"+ );+ expect(loadAgentScope()).toEqual({+ agentId: "developer",+ mode: "isolated",+ });+ expect(isAgentScopeIsolated()).toBe(true);+ });++ it("isolated requires AGENT_ID to also be set (no scope without id)", async () => {+ process.env["AGENTMEMORY_AGENT_SCOPE"] = "isolated";+ const { isAgentScopeIsolated } = await import("../src/config.js");+ expect(isAgentScopeIsolated()).toBe(false);+ });++ it("unknown scope values fall back to shared", async () => {+ process.env["AGENT_ID"] = "developer";+ process.env["AGENTMEMORY_AGENT_SCOPE"] = "weird";+ const { isAgentScopeIsolated } = await import("../src/config.js");+ expect(isAgentScopeIsolated()).toBe(false);+ });+});diff --git a/test/memories-pagination.test.ts b/test/memories-pagination.test.tsindex cd7eb3e7..c7ad7586 100644--- a/test/memories-pagination.test.ts+++ b/test/memories-pagination.test.ts@@ -9,8 +9,9 @@ describe("memories + export pagination (#544)", () => {it("api::memories accepts count=true and returns total + latestCount", () => {expect(api).toMatch(/req\.query_params\?\.\["count"\]\s*===\s*"true"/);- expect(api).toMatch(/total:\s*memories\.length/);- expect(api).toMatch(/latestCount:\s*memories\.filter/);+ // 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/);});it("api::memories accepts limit + offset query params", () => {