Skip to content

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

fix cross-project memory leakage (#662)

Abhinav Mahajane1d96bc04c53
diff --git a/src/functions/consolidate.ts b/src/functions/consolidate.ts
index 9ee0b14c..d394e176 100644
--- a/src/functions/consolidate.ts
+++ b/src/functions/consolidate.ts
@@ -152,12 +152,26 @@ export function registerConsolidateFunction(
const parsed = parseMemoryXml(response, sessionIds);
if (!parsed) continue;
+ const now = new Date().toISOString();
+ const obsIds = [...new Set(top.map((o) => o.id))];
+ const scopedProject =
+ typeof data.project === "string" && data.project.trim().length > 0
+ ? data.project.trim()
+ : undefined;
+
+ // A scoped consolidation run must only evolve memories that belong
+ // to the same project. Without this guard, two projects that happen
+ // to consolidate observations into an identically-titled memory would
+ // cause one project's memory to silently evolve the other's — the
+ // exact class of cross-project corruption this fix is designed to
+ // prevent. An unscoped run (no data.project, background cron path)
+ // preserves the pre-existing behavior and may evolve any memory.
const existingMatch = existingMemories.find(
- (m) => m.title.toLowerCase() === parsed.title.toLowerCase(),
+ (m) =>
+ m.title.toLowerCase() === parsed.title.toLowerCase() &&
+ (!scopedProject || !m.project || m.project === scopedProject),
);
- const now = new Date().toISOString();
- const obsIds = [...new Set(top.map((o) => o.id))];
if (existingMatch) {
existingMatch.isLatest = false;
await kv.set(KV.memories, existingMatch.id, existingMatch);
@@ -179,6 +193,7 @@ export function registerConsolidateFunction(
],
sourceObservationIds: obsIds,
isLatest: true,
+ ...(scopedProject !== undefined && { project: scopedProject }),
};
await kv.set(KV.memories, evolved.id, evolved);
await recordAudit(kv, "evolve", "mem::consolidate", [evolved.id], {
@@ -198,6 +213,7 @@ export function registerConsolidateFunction(
sourceObservationIds: obsIds,
version: 1,
isLatest: true,
+ ...(scopedProject !== undefined && { project: scopedProject }),
};
await kv.set(KV.memories, memory.id, memory);
await recordAudit(kv, "remember", "mem::consolidate", [memory.id], {
diff --git a/src/functions/diagnostics.ts b/src/functions/diagnostics.ts
index a63d7959..cc982883 100644
--- a/src/functions/diagnostics.ts
+++ b/src/functions/diagnostics.ts
@@ -355,12 +355,44 @@ export function registerDiagnosticsFunction(sdk: ISdk, kv: StateKV): void {
}
}
+ // Project-coverage check: unscoped memories (no project field) will
+ // appear in every project's context and search results until the
+ // infer-memory-projects migration runs. Surface a count so operators
+ // know the backfill is still pending and can trigger it explicitly.
+ const latestMemories = memories.filter((m) => m.isLatest);
+ const unscopedCount = latestMemories.filter((m) => !m.project).length;
+ if (unscopedCount === 0) {
+ checks.push({
+ name: "memory-project-coverage",
+ category: "memories",
+ status: "pass",
+ message: `All ${latestMemories.length} latest memories have a project scope`,
+ fixable: false,
+ });
+ } else if (unscopedCount <= 10) {
+ checks.push({
+ name: "memory-project-coverage",
+ category: "memories",
+ status: "warn",
+ message: `${unscopedCount} of ${latestMemories.length} latest memories have no project scope — run POST /agentmemory/migrate {"step":"infer-memory-projects"} to backfill`,
+ fixable: true,
+ });
+ } else {
+ checks.push({
+ name: "memory-project-coverage",
+ category: "memories",
+ status: "fail",
+ message: `${unscopedCount} of ${latestMemories.length} latest memories have no project scope — run POST /agentmemory/migrate {"step":"infer-memory-projects"} to backfill`,
+ fixable: true,
+ });
+ }
+
if (memoryIssues === 0) {
checks.push({
name: "memories-ok",
category: "memories",
status: "pass",
- message: `All ${memories.length} memories are consistent`,
+ message: `All ${memories.length} memories are structurally consistent`,
fixable: false,
});
}
diff --git a/src/functions/enrich.ts b/src/functions/enrich.ts
index 38b6aac2..032ec97b 100644
--- a/src/functions/enrich.ts
+++ b/src/functions/enrich.ts
@@ -16,13 +16,19 @@ function escapeXml(s: string): string {
}
export function registerEnrichFunction(sdk: ISdk, kv: StateKV): void {
- sdk.registerFunction("mem::enrich",
+ sdk.registerFunction("mem::enrich",
async (data: {
sessionId: string;
files: string[];
terms?: string[];
toolName?: string;
+ project?: string;
}) => {
+ const project =
+ typeof data.project === "string" && data.project.trim().length > 0
+ ? data.project.trim()
+ : undefined;
+
const parts: string[] = [];
const fileContextPromise = sdk
@@ -44,13 +50,14 @@ export function registerEnrichFunction(sdk: ISdk, kv: StateKV): void {
searchQueries.length > 0
? sdk
.trigger<
- { query: string; limit: number },
+ { query: string; limit: number; project?: string },
{ results: Array<{ observation: { narrative: string } }> }
>({
function_id: "mem::search",
payload: {
query: searchQueries.join(" "),
limit: 5,
+ ...(project !== undefined && { project }),
},
})
.catch(() => ({ results: [] }))
@@ -64,6 +71,8 @@ export function registerEnrichFunction(sdk: ISdk, kv: StateKV): void {
(m) =>
m.type === "bug" &&
m.isLatest &&
+ // Guard only when both sides have an explicit project; unscoped memories pass through.
+ (!project || !m.project || m.project === project) &&
m.files.some((f) =>
data.files.some((df) => f.includes(df) || df.includes(f)),
),
@@ -118,6 +127,7 @@ export function registerEnrichFunction(sdk: ISdk, kv: StateKV): void {
logger.info("Enrichment completed", {
sessionId: data.sessionId,
+ project,
fileCount: data.files.length,
contextLength: context.length,
truncated,
diff --git a/src/functions/migrate.ts b/src/functions/migrate.ts
index f9781500..c2039ea1 100644
--- a/src/functions/migrate.ts
+++ b/src/functions/migrate.ts
@@ -4,6 +4,7 @@ import { homedir } from "node:os";
import { KV, generateId } from "../state/schema.js";
import { StateKV } from "../state/kv.js";
import type {
+ Memory,
Session,
CompressedObservation,
SessionSummary,
@@ -17,9 +18,91 @@ function isAllowedPath(dbPath: string): boolean {
return ALLOWED_DIRS.some((dir) => resolved.startsWith(dir + "/"));
}
+// Infer memory project from the majority project of its associated sessions.
+// Returns { updated, skipped } — safe to run repeatedly (idempotent).
+export async function inferMemoryProjects(
+ kv: StateKV,
+ dryRun = false,
+): Promise<{ updated: number; skipped: number; ambiguous: number }> {
+ const memories = await kv.list<Memory>(KV.memories);
+ const sessionCache = new Map<string, Session | null>();
+
+ const loadSession = async (sid: string): Promise<Session | null> => {
+ if (sessionCache.has(sid)) return sessionCache.get(sid)!;
+ const s = await kv.get<Session>(KV.sessions, sid).catch(() => null);
+ sessionCache.set(sid, s);
+ return s;
+ };
+
+ let updated = 0;
+ let skipped = 0;
+ let ambiguous = 0;
+
+ for (const memory of memories) {
+ if (memory.project) {
+ skipped++;
+ continue;
+ }
+
+ const sessionIds = memory.sessionIds ?? [];
+ if (sessionIds.length === 0) {
+ ambiguous++;
+ continue;
+ }
+
+ const projects: string[] = [];
+ for (const sid of sessionIds) {
+ const session = await loadSession(sid);
+ if (session?.project) projects.push(session.project);
+ }
+
+ if (projects.length === 0) {
+ ambiguous++;
+ continue;
+ }
+
+ // Majority-vote: count frequency of each project value.
+ const freq = new Map<string, number>();
+ for (const p of projects) freq.set(p, (freq.get(p) ?? 0) + 1);
+ const sorted = [...freq.entries()].sort((a, b) => b[1] - a[1]);
+ const [topProject, topCount] = sorted[0];
+
+ // Require a strict majority (> 50%) to avoid misattributing a memory
+ // that was genuinely built from sessions across multiple projects.
+ if (topCount <= projects.length / 2 && sorted.length > 1) {
+ ambiguous++;
+ continue;
+ }
+
+ if (!dryRun) {
+ memory.project = topProject;
+ await kv.set(KV.memories, memory.id, memory);
+ }
+ updated++;
+ }
+
+ logger.info("inferMemoryProjects complete", { updated, skipped, ambiguous, dryRun });
+ return { updated, skipped, ambiguous };
+}
+
export function registerMigrateFunction(sdk: ISdk, kv: StateKV): void {
- sdk.registerFunction("mem::migrate",
- async (data: { dbPath: string }) => {
+ sdk.registerFunction("mem::migrate",
+ async (data: { dbPath?: string; step?: string; dryRun?: boolean }) => {
+ // In-place KV migration steps (no SQLite dependency).
+ if (data.step === "infer-memory-projects") {
+ const dryRun = data.dryRun ?? false;
+ logger.info("Migration step: infer-memory-projects", { dryRun });
+ const result = await inferMemoryProjects(kv, dryRun);
+ return { success: true, step: "infer-memory-projects", ...result };
+ }
+
+ if (!data.dbPath) {
+ return {
+ success: false,
+ error: "Either step or dbPath is required",
+ };
+ }
+
logger.info("Migration started", { dbPath: data.dbPath });
if (!isAllowedPath(data.dbPath)) {
diff --git a/src/functions/remember.ts b/src/functions/remember.ts
index 97440082..a19d6b0a 100644
--- a/src/functions/remember.ts
+++ b/src/functions/remember.ts
@@ -20,6 +20,7 @@ export function registerRememberFunction(sdk: ISdk, kv: StateKV): void {
ttlDays?: number;
sourceObservationIds?: string[];
agentId?: string;
+ project?: string;
}) => {
if (
!data.content ||
@@ -50,6 +51,13 @@ export function registerRememberFunction(sdk: ISdk, kv: StateKV): void {
: "fact";
const now = new Date().toISOString();
+ // Normalize project early so every subsequent comparison and storage
+ // operation uses the same cleaned value. Raw data.project must not be
+ // referenced below this point.
+ const project =
+ typeof data.project === "string" && data.project.trim().length > 0
+ ? data.project.trim()
+ : undefined;
return withKeyedLock("mem:remember", async () => {
const existingMemories = await kv.list<Memory>(KV.memories);
@@ -59,6 +67,13 @@ export function registerRememberFunction(sdk: ISdk, kv: StateKV): void {
const lowerContent = data.content.toLowerCase();
for (const existing of existingMemories) {
if (existing.isLatest === false) continue;
+ // Never supersede a memory that belongs to a different project.
+ // Both sides must have an explicit project for the guard to engage;
+ // an unscoped memory (legacy, no project field) is treated as a
+ // wildcard so pre-existing data is not stranded.
+ if (project && existing.project && existing.project !== project) {
+ continue;
+ }
const similarity = jaccardSimilarity(
lowerContent,
existing.content.toLowerCase(),
@@ -79,6 +94,7 @@ export function registerRememberFunction(sdk: ISdk, kv: StateKV): void {
typeof data.agentId === "string" && data.agentId.trim().length > 0
? data.agentId.trim().slice(0, 128)
: getAgentId();
+
const memory: Memory = {
id: generateId("mem"),
createdAt: now,
@@ -98,6 +114,7 @@ export function registerRememberFunction(sdk: ISdk, kv: StateKV): void {
),
isLatest: true,
...(callAgentId ? { agentId: callAgentId } : {}),
+ ...(project !== undefined && { project }),
};
if (data.ttlDays && typeof data.ttlDays === "number" && data.ttlDays > 0) {
@@ -143,6 +160,7 @@ export function registerRememberFunction(sdk: ISdk, kv: StateKV): void {
logger.info("Memory saved", {
memId: memory.id,
type: memory.type,
+ project: memory.project,
});
return { success: true, memory };
});
diff --git a/src/functions/search.ts b/src/functions/search.ts
index dc629d6d..ffe3bec5 100644
--- a/src/functions/search.ts
+++ b/src/functions/search.ts
@@ -344,8 +344,8 @@ export function registerSearchFunction(sdk: ISdk, kv: StateKV): void {
}
effectiveLimit = Math.min(data.limit, MAX_LIMIT)
}
- const projectFilter = typeof data.project === 'string' && data.project.length > 0 ? data.project : undefined
- const cwdFilter = typeof data.cwd === 'string' && data.cwd.length > 0 ? data.cwd : undefined
+ 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
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'")
@@ -378,15 +378,52 @@ export function registerSearchFunction(sdk: ISdk, kv: StateKV): void {
return s ?? null
}
+ // Cache for memory project lookups. Memories indexed via mem::remember
+ // use a synthetic sessionId ('memory' or the first real sessionId) that
+ // either has no KV.sessions entry or belongs to a different project.
+ // When loadSession returns null we fall through to a KV.memories probe
+ // so project-filtered search can include or exclude them correctly.
+ const memoryProjectCache = new Map<string, string | null>()
+ const loadMemoryProject = async (obsId: string): Promise<string | null> => {
+ if (memoryProjectCache.has(obsId)) return memoryProjectCache.get(obsId)!
+ const mem = await kv.get<Memory>(KV.memories, obsId).catch(() => null)
+ const proj = mem?.project ?? null
+ memoryProjectCache.set(obsId, proj)
+ return proj
+ }
+
// 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.
const candidates: typeof results = []
for (const r of results) {
if (candidates.length >= effectiveLimit) break
if (filtering) {
const s = await loadSession(r.sessionId)
- if (!s) continue
- if (projectFilter && s.project !== projectFilter) continue
- if (cwdFilter && s.cwd !== cwdFilter) continue
+ if (s) {
+ if (projectFilter && s.project !== projectFilter) continue
+ if (cwdFilter && s.cwd !== cwdFilter) continue
+ } else {
+ // Session not found. Two cases arrive here:
+ // 1. Synthetic sessionId — memories indexed via mem::remember use
+ // sessionIds[0] ?? 'memory'. The string 'memory' has no session
+ // entry; neither does a real sessionId when sessionIds[0] happens
+ // to be a session from a different lifecycle. Probe KV.memories
+ // directly to get the memory's own project field.
+ // 2. Deleted session — the session existed when the entry was indexed
+ // but was since evicted. The KV.memories probe returns null for
+ // these (they are observations, not memories), so memProject is
+ // null and the entry passes through as unscoped. This is the safe
+ // fallback: we lose the ability to filter but never incorrectly
+ // block a result whose session we can no longer verify.
+ // In both cases, a null memProject means "project unknown — treat as
+ // unscoped and let it through" to preserve backward-compatibility.
+ if (projectFilter) {
+ const memProject = await loadMemoryProject(r.obsId)
+ if (memProject !== null && memProject !== projectFilter) continue
+ }
+ // cwd filter does not apply to unbound entries.
+ }
}
candidates.push(r)
}
diff --git a/src/hooks/pre-tool-use.ts b/src/hooks/pre-tool-use.ts
index 61f6c443..38daefc0 100644
--- a/src/hooks/pre-tool-use.ts
+++ b/src/hooks/pre-tool-use.ts
@@ -77,12 +77,27 @@ async function main() {
}
const sessionId = (data.session_id as string) || "unknown";
+ // Only forward an explicit project field. cwd is an absolute filesystem path
+ // and must not be used as a project identifier — memories are scoped by short
+ // project names (e.g. "api", "web"), not paths. Sending a cwd-path as project
+ // would cause all scoped memories to be incorrectly filtered out on the server
+ // because the path never matches the stored project name.
+ const project =
+ typeof data.project === "string" && data.project.trim().length > 0
+ ? data.project.trim()
+ : undefined;
try {
const res = await fetch(`${REST_URL}/agentmemory/enrich`, {
method: "POST",
headers: authHeaders(),
- body: JSON.stringify({ sessionId, files, terms, toolName }),
+ body: JSON.stringify({
+ sessionId,
+ files,
+ terms,
+ toolName,
+ ...(project !== undefined && { project }),
+ }),
signal: AbortSignal.timeout(2000),
});
diff --git a/src/mcp/server.ts b/src/mcp/server.ts
index b3b0585d..e2144567 100644
--- a/src/mcp/server.ts
+++ b/src/mcp/server.ts
@@ -172,11 +172,17 @@ export function registerMcpEndpoints(
? args.files.split(",").map((f: string) => f.trim()).filter(Boolean)
: [];
+ const project =
+ typeof args.project === "string" && args.project.trim().length > 0
+ ? args.project.trim()
+ : undefined;
+
const result = await sdk.trigger({ function_id: "mem::remember", payload: {
content: args.content,
type,
concepts,
files,
+ ...(project !== undefined && { project }),
} });
return {
status_code: 200,
diff --git a/src/mcp/tools-registry.ts b/src/mcp/tools-registry.ts
index a8e64839..c86d899b 100644
--- a/src/mcp/tools-registry.ts
+++ b/src/mcp/tools-registry.ts
@@ -75,6 +75,14 @@ export const CORE_TOOLS: McpToolDef[] = [
type: "string",
description: "Comma-separated relevant file paths",
},
+ project: {
+ type: "string",
+ description:
+ "Stable canonical project identifier this memory belongs to (e.g. a slug, " +
+ "UUID, or registry key). Must match the value used when the session was " +
+ "started. Do not use filesystem paths or ad-hoc display names — those " +
+ "change across machines and will silently break project scoping.",
+ },
},
required: ["content"],
},
diff --git a/src/triggers/api.ts b/src/triggers/api.ts
index 06a29282..8f80379b 100644
--- a/src/triggers/api.ts
+++ b/src/triggers/api.ts
@@ -832,13 +832,14 @@ export function registerApiTriggers(
config: { api_path: "/agentmemory/file-context", http_method: "POST" },
});
- sdk.registerFunction("api::enrich",
+ sdk.registerFunction("api::enrich",
async (
req: ApiRequest<{
sessionId: string;
files: string[];
terms?: string[];
toolName?: string;
+ project?: string;
}>,
): Promise<Response> => {
const authErr = checkAuth(req, secret);
@@ -867,7 +868,25 @@ export function registerApiTriggers(
body: { error: "terms must be an array of strings" },
};
}
- const result = await sdk.trigger({ function_id: "mem::enrich", payload: req.body });
+ if (
+ req.body.project !== undefined &&
+ (typeof req.body.project !== "string" || !req.body.project.trim())
+ ) {
+ return {
+ status_code: 400,
+ body: { error: "project must be a non-empty string" },
+ };
+ }
+ const result = await sdk.trigger({
+ function_id: "mem::enrich",
+ payload: {
+ sessionId: req.body.sessionId,
+ files: req.body.files,
+ ...(req.body.terms !== undefined && { terms: req.body.terms }),
+ ...(req.body.toolName !== undefined && { toolName: req.body.toolName }),
+ ...(req.body.project !== undefined && { project: req.body.project }),
+ },
+ });
return { status_code: 200, body: result };
},
);
@@ -877,13 +896,16 @@ export function registerApiTriggers(
config: { api_path: "/agentmemory/enrich", http_method: "POST" },
});
- sdk.registerFunction("api::remember",
+ sdk.registerFunction("api::remember",
async (
req: ApiRequest<{
content: string;
type?: string;
concepts?: string[];
files?: string[];
+ ttlDays?: number;
+ sourceObservationIds?: string[];
+ project?: string;
}>,
): Promise<Response> => {
const authErr = checkAuth(req, secret);
@@ -895,7 +917,24 @@ export function registerApiTriggers(
) {
return { status_code: 400, body: { error: "content is required" } };
}
- const result = await sdk.trigger({ function_id: "mem::remember", payload: req.body });
+ if (
+ req.body.project !== undefined &&
+ (typeof req.body.project !== "string" || !req.body.project.trim())
+ ) {
+ return { status_code: 400, body: { error: "project must be a non-empty string" } };
+ }
+ const result = await sdk.trigger({
+ function_id: "mem::remember",
+ payload: {
+ content: req.body.content,
+ ...(req.body.type !== undefined && { type: req.body.type }),
+ ...(req.body.concepts !== undefined && { concepts: req.body.concepts }),
+ ...(req.body.files !== undefined && { files: req.body.files }),
+ ...(req.body.ttlDays !== undefined && { ttlDays: req.body.ttlDays }),
+ ...(req.body.sourceObservationIds !== undefined && { sourceObservationIds: req.body.sourceObservationIds }),
+ ...(req.body.project !== undefined && { project: req.body.project }),
+ },
+ });
return { status_code: 201, body: result };
},
);
@@ -975,14 +1014,30 @@ export function registerApiTriggers(
config: { api_path: "/agentmemory/generate-rules", http_method: "POST" },
});
- sdk.registerFunction("api::migrate",
- async (req: ApiRequest<{ dbPath: string }>): Promise<Response> => {
+ sdk.registerFunction("api::migrate",
+ async (
+ req: ApiRequest<{ dbPath?: string; step?: string; dryRun?: boolean }>,
+ ): Promise<Response> => {
const authErr = checkAuth(req, secret);
if (authErr) return authErr;
- if (!req.body?.dbPath || typeof req.body.dbPath !== "string") {
- return { status_code: 400, body: { error: "dbPath is required" } };
+ const hasStep =
+ typeof req.body?.step === "string" && req.body.step.trim().length > 0;
+ const hasDbPath =
+ typeof req.body?.dbPath === "string" && req.body.dbPath.trim().length > 0;
+ if (!hasStep && !hasDbPath) {
+ return {
+ status_code: 400,
+ body: { error: "Either step (string) or dbPath (string) is required" },
+ };
}
- const result = await sdk.trigger({ function_id: "mem::migrate", payload: req.body });
+ const result = await sdk.trigger({
+ function_id: "mem::migrate",
+ payload: {
+ ...(req.body.step !== undefined && { step: req.body.step }),
+ ...(req.body.dbPath !== undefined && { dbPath: req.body.dbPath }),
+ ...(req.body.dryRun !== undefined && { dryRun: req.body.dryRun }),
+ },
+ });
return { status_code: 200, body: result };
},
);
diff --git a/src/types.ts b/src/types.ts
index 97a7457b..b22f2188 100644
--- a/src/types.ts
+++ b/src/types.ts
@@ -101,6 +101,7 @@ export interface Memory {
imageRef?: string;
imageData?: string;
agentId?: string;
+ project?: string;
}
export interface SessionSummary {
diff --git a/test/consolidate-project-scope.test.ts b/test/consolidate-project-scope.test.ts
new file mode 100644
index 00000000..e8efc45c
--- /dev/null
+++ b/test/consolidate-project-scope.test.ts
@@ -0,0 +1,270 @@
+import { describe, it, expect, vi } from "vitest";
+
+vi.mock("../src/logger.js", () => ({
+ logger: { info: vi.fn(), warn: vi.fn(), error: vi.fn() },
+}));
+
+vi.mock("../src/functions/audit.js", () => ({
+ recordAudit: vi.fn(),
+}));
+
+import { registerConsolidateFunction } from "../src/functions/consolidate.js";
+import { KV } from "../src/state/schema.js";
+import type { CompressedObservation, Memory, MemoryProvider, Session } 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);
+ },
+ };
+}
+
+function makeProvider(title = "synthesized memory title"): MemoryProvider {
+ return {
+ name: "mock",
+ compress: vi.fn().mockResolvedValue(
+ `<memory>
+ <type>pattern</type>
+ <title>${title}</title>
+ <content>synthesized content about the concept</content>
+ <concepts><concept>auth</concept></concepts>
+ <files><file>src/auth.ts</file></files>
+ <strength>7</strength>
+ </memory>`,
+ ),
+ embed: vi.fn().mockResolvedValue(new Float32Array(384)),
+ embedBatch: vi.fn().mockResolvedValue([]),
+ dimensions: 384,
+ compressionModel: "mock-model",
+ };
+}
+
+function makeSession(id: string, project: string): Session {
+ return {
+ id,
+ project,
+ cwd: `/srv/${project}`,
+ startedAt: new Date().toISOString(),
+ status: "completed",
+ observationCount: 5,
+ };
+}
+
+function makeObs(id: string, sessionId: string, concept: string): CompressedObservation {
+ return {
+ id,
+ sessionId,
+ timestamp: new Date().toISOString(),
+ type: "decision",
+ title: `${concept} observation ${id}`,
+ facts: [`fact about ${concept}`],
+ narrative: `detailed narrative about ${concept} pattern usage`,
+ concepts: [concept],
+ files: ["src/auth.ts"],
+ importance: 8,
+ };
+}
+
+function makeExistingMemory(id: string, title: string, project?: string): Memory {
+ return {
+ id,
+ createdAt: new Date().toISOString(),
+ updatedAt: new Date().toISOString(),
+ type: "pattern",
+ title,
+ content: "existing content",
+ concepts: ["auth"],
+ files: ["src/auth.ts"],
+ sessionIds: [],
+ strength: 6,
+ version: 1,
+ isLatest: true,
+ ...(project !== undefined && { project }),
+ };
+}
+
+describe("mem::consolidate — cross-project existingMatch guard", () => {
+ it("does not evolve a memory from a different project even when titles match", async () => {
+ const sdk = makeMockSdk();
+ const kv = makeMockKV();
+ const provider = makeProvider("synthesized memory title");
+
+ // A memory scoped to "web" with the same title the provider will generate
+ const webMemory = makeExistingMemory("mem_web", "synthesized memory title", "web");
+ await kv.set(KV.memories, webMemory.id, webMemory);
+
+ // Session and observations for "api" project
+ const apiSession = makeSession("sess_api", "api");
+ await kv.set(KV.sessions, apiSession.id, apiSession);
+ for (let i = 0; i < 3; i++) {
+ await kv.set(
+ KV.observations(apiSession.id),
+ `obs_${i}`,
+ makeObs(`obs_${i}`, apiSession.id, "auth"),
+ );
+ }
+
+ registerConsolidateFunction(sdk as never, kv as never, provider as never);
+ await sdk.trigger("mem::consolidate", { project: "api", minObservations: 1 });
+
+ // The web memory must remain untouched — isLatest still true
+ const webStored = await kv.get<Memory>(KV.memories, webMemory.id);
+ expect(webStored?.isLatest).toBe(true);
+ expect(webStored?.project).toBe("web");
+
+ // A new "api" memory should have been created
+ const allMemories = await kv.list<Memory>(KV.memories);
+ const apiMemories = allMemories.filter((m) => m.project === "api" && m.isLatest);
+ expect(apiMemories).toHaveLength(1);
+ expect(apiMemories[0].title).toBe("synthesized memory title");
+ });
+
+ it("evolves an existing memory within the same project when titles match", async () => {
+ const sdk = makeMockSdk();
+ const kv = makeMockKV();
+ const provider = makeProvider("synthesized memory title");
+
+ // A memory already scoped to "api" with the same title
+ const apiMemory = makeExistingMemory("mem_api_old", "synthesized memory title", "api");
+ await kv.set(KV.memories, apiMemory.id, apiMemory);
+
+ const apiSession = makeSession("sess_api", "api");
+ await kv.set(KV.sessions, apiSession.id, apiSession);
+ for (let i = 0; i < 3; i++) {
+ await kv.set(
+ KV.observations(apiSession.id),
+ `obs_${i}`,
+ makeObs(`obs_${i}`, apiSession.id, "auth"),
+ );
+ }
+
+ registerConsolidateFunction(sdk as never, kv as never, provider as never);
+ await sdk.trigger("mem::consolidate", { project: "api", minObservations: 1 });
+
+ // The old api memory should have been marked non-latest (evolved)
+ const oldMemory = await kv.get<Memory>(KV.memories, apiMemory.id);
+ expect(oldMemory?.isLatest).toBe(false);
+
+ // A new evolved memory should exist
+ const allMemories = await kv.list<Memory>(KV.memories);
+ const latestApi = allMemories.filter((m) => m.project === "api" && m.isLatest);
+ expect(latestApi).toHaveLength(1);
+ expect(latestApi[0].id).not.toBe(apiMemory.id);
+ expect(latestApi[0].parentId).toBe(apiMemory.id);
+ });
+
+ it("unscoped consolidation may evolve any existing memory regardless of project (background cron behavior)", async () => {
+ const sdk = makeMockSdk();
+ const kv = makeMockKV();
+ const provider = makeProvider("synthesized memory title");
+
+ // A scoped memory that an unscoped consolidation run should be able to evolve
+ const scopedMemory = makeExistingMemory("mem_api_old", "synthesized memory title", "api");
+ await kv.set(KV.memories, scopedMemory.id, scopedMemory);
+
+ // Session with no project restriction — unscoped consolidation
+ const session = makeSession("sess_any", "any");
+ await kv.set(KV.sessions, session.id, session);
+ for (let i = 0; i < 3; i++) {
+ await kv.set(
+ KV.observations(session.id),
+ `obs_${i}`,
+ makeObs(`obs_${i}`, session.id, "auth"),
+ );
+ }
+
+ registerConsolidateFunction(sdk as never, kv as never, provider as never);
+ // No project passed — unscoped consolidation
+ await sdk.trigger("mem::consolidate", { minObservations: 1 });
+
+ // The existing scoped memory should have been evolved (unscoped run is unrestricted)
+ const old = await kv.get<Memory>(KV.memories, scopedMemory.id);
+ expect(old?.isLatest).toBe(false);
+
+ // The evolved successor should be latest and carry no project (unscoped run)
+ const allMemories = await kv.list<Memory>(KV.memories);
+ const successor = allMemories.find((m) => m.isLatest && m.id !== scopedMemory.id);
+ expect(successor).toBeDefined();
+ expect(successor?.isLatest).toBe(true);
+ expect(successor?.project).toBeUndefined();
+ });
+
+ it("stamps the correct project on newly created memories", async () => {
+ const sdk = makeMockSdk();
+ const kv = makeMockKV();
+ const provider = makeProvider("brand new memory");
+
+ const session = makeSession("sess_api", "api");
+ await kv.set(KV.sessions, session.id, session);
+ for (let i = 0; i < 3; i++) {
+ await kv.set(
+ KV.observations(session.id),
+ `obs_${i}`,
+ makeObs(`obs_${i}`, session.id, "auth"),
+ );
+ }
+
+ registerConsolidateFunction(sdk as never, kv as never, provider as never);
+ await sdk.trigger("mem::consolidate", { project: "api", minObservations: 1 });
+
+ const memories = await kv.list<Memory>(KV.memories);
+ expect(memories).toHaveLength(1);
+ expect(memories[0].project).toBe("api");
+ });
+
+ it("leaves project undefined on memories when consolidate is called without a project", async () => {
+ const sdk = makeMockSdk();
+ const kv = makeMockKV();
+ const provider = makeProvider("unscoped memory");
+
+ const session = makeSession("sess_any", "any");
+ await kv.set(KV.sessions, session.id, session);
+ for (let i = 0; i < 3; i++) {
+ await kv.set(
+ KV.observations(session.id),
+ `obs_${i}`,
+ makeObs(`obs_${i}`, session.id, "auth"),
+ );
+ }
+
+ registerConsolidateFunction(sdk as never, kv as never, provider as never);
+ await sdk.trigger("mem::consolidate", { minObservations: 1 });
+
+ const memories = await kv.list<Memory>(KV.memories);
+ expect(memories).toHaveLength(1);
+ expect(memories[0].project).toBeUndefined();
+ });
+});
diff --git a/test/cross-project-isolation.test.ts b/test/cross-project-isolation.test.ts
new file mode 100644
index 00000000..8fc37498
--- /dev/null
+++ b/test/cross-project-isolation.test.ts
@@ -0,0 +1,283 @@
+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(),
+}));
+
+vi.mock("../src/config.js", () => ({
+ getAgentId: () => undefined,
+}));
+
+import { registerRememberFunction } from "../src/functions/remember.js";
+import { registerSearchFunction, getSearchIndex, setIndexPersistence } from "../src/functions/search.js";
+import { registerEnrichFunction } from "../src/functions/enrich.js";
+import { KV } from "../src/state/schema.js";
+import type { Session } 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>();
+ const triggerOverrides = 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;
+ if (triggerOverrides.has(id)) return triggerOverrides.get(id)!(payload);
+ const fn = functions.get(id);
+ if (!fn) throw new Error(`No function registered: ${id}`);
+ return fn(payload);
+ },
+ overrideTrigger: (id: string, handler: Function) => {
+ triggerOverrides.set(id, handler);
+ },
+ };
+}
+
+async function seedSessions(kv: ReturnType<typeof makeMockKV>) {
+ const apiSession: Session = {
+ id: "sess-api",
+ project: "api",
+ cwd: "/srv/api",
+ startedAt: new Date().toISOString(),
+ status: "active",
+ observationCount: 0,
+ };
+ const webSession: Session = {
+ id: "sess-web",
+ project: "web",
+ cwd: "/srv/web",
+ startedAt: new Date().toISOString(),
+ status: "active",
+ observationCount: 0,
+ };
+ await kv.set(KV.sessions, apiSession.id, apiSession);
+ await kv.set(KV.sessions, webSession.id, webSession);
+}
+
+describe("cross-project isolation — end-to-end", () => {
+ let sdk: ReturnType<typeof makeMockSdk>;
+ let kv: ReturnType<typeof makeMockKV>;
+
+ beforeEach(async () => {
+ sdk = makeMockSdk();
+ kv = makeMockKV();
+
+ // Disable index persistence in tests so no file I/O occurs.
+ setIndexPersistence(null);
+
+ // Clear the singleton BM25 index between tests.
+ getSearchIndex().clear();
+
+ // Register all three functions against the shared KV.
+ registerRememberFunction(sdk as never, kv as never);
+ registerSearchFunction(sdk as never, kv as never);
+
+ // Enrich calls mem::search internally; wire the file-context trigger as a no-op.
+ registerEnrichFunction(sdk as never, kv as never);
+ sdk.overrideTrigger("mem::file-context", async () => ({ context: "" }));
+
+ await seedSessions(kv);
+ });
+
+ it("bug memory scoped to api does not appear in enrich context for web project", async () => {
+ await sdk.trigger("mem::remember", {
+ content: "express-jwt throws 401 when Authorization header has extra whitespace. Call .trim() before passing to middleware.",
+ type: "bug",
+ files: ["src/middleware/auth.ts"],
+ project: "api",
+ });
+
+ const result = await sdk.trigger("mem::enrich", {
+ sessionId: "sess-web",
+ files: ["src/middleware/auth.ts"],
+ project: "web",
+ }) as { context: string };
+
+ expect(result.context).not.toContain("agentmemory-past-errors");
+ expect(result.context).not.toContain("express-jwt");
+ });
+
+ it("bug memory scoped to api appears in enrich context for api project", async () => {
+ await sdk.trigger("mem::remember", {
+ content: "express-jwt throws 401 when Authorization header has extra whitespace. Call .trim() before passing to middleware.",
+ type: "bug",
+ files: ["src/middleware/auth.ts"],
+ project: "api",
+ });
+
+ const result = await sdk.trigger("mem::enrich", {
+ sessionId: "sess-api",
+ files: ["src/middleware/auth.ts"],
+ project: "api",
+ }) as { context: string };
+
+ expect(result.context).toContain("agentmemory-past-errors");
+ expect(result.context).toContain("express-jwt");
+ });
+
+ it("bug memory scoped to api is excluded from search results for web project", async () => {
+ await sdk.trigger("mem::remember", {
+ content: "express-jwt throws 401 when Authorization header has extra whitespace",
+ type: "bug",
+ files: ["src/middleware/auth.ts"],
+ project: "api",
+ });
+
+ // Force index rebuild so the freshly saved memory is indexed.
+ getSearchIndex().clear();
+
+ const result = await sdk.trigger("mem::search", {
+ query: "express-jwt whitespace",
+ project: "web",
+ }) as { results: Array<{ observation: { title: string; narrative?: string } }> };
+
+ const titles = result.results.map((r) => r.observation.title);
+ expect(titles.join(" ")).not.toContain("express-jwt");
+ });
+
+ it("bug memory scoped to api is included in search results for api project", async () => {
+ await sdk.trigger("mem::remember", {
+ content: "express-jwt throws 401 when Authorization header has extra whitespace",
+ type: "bug",
+ files: ["src/middleware/auth.ts"],
+ project: "api",
+ });
+
+ // Force index rebuild so the freshly saved memory is indexed.
+ getSearchIndex().clear();
+
+ const result = await sdk.trigger("mem::search", {
+ query: "express-jwt whitespace",
+ project: "api",
+ }) as { results: Array<{ observation: { title: string; narrative?: string } }> };
+
+ const combined = result.results
+ .map((r) => `${r.observation.title} ${r.observation.narrative ?? ""}`)
+ .join(" ");
+ expect(combined).toContain("express-jwt");
+ });
+
+ it("two projects with overlapping filenames see only their own bug memories", async () => {
+ await sdk.trigger("mem::remember", {
+ content: "express-jwt Authorization header whitespace causes 401",
+ type: "bug",
+ files: ["src/middleware/auth.ts"],
+ project: "api",
+ });
+ await sdk.trigger("mem::remember", {
+ content: "nextauth cookie domain mismatch breaks SSO on subdomains",
+ type: "bug",
+ files: ["src/middleware/auth.ts"],
+ project: "web",
+ });
+
+ const apiEnrich = await sdk.trigger("mem::enrich", {
+ sessionId: "sess-api",
+ files: ["src/middleware/auth.ts"],
+ project: "api",
+ }) as { context: string };
+
+ expect(apiEnrich.context).toContain("express-jwt");
+ expect(apiEnrich.context).not.toContain("nextauth");
+
+ const webEnrich = await sdk.trigger("mem::enrich", {
+ sessionId: "sess-web",
+ files: ["src/middleware/auth.ts"],
+ project: "web",
+ }) as { context: string };
+
+ expect(webEnrich.context).toContain("nextauth");
+ expect(webEnrich.context).not.toContain("express-jwt");
+ });
+
+ it("unscoped (legacy) bug memory is visible to both projects", async () => {
+ await sdk.trigger("mem::remember", {
+ content: "generic auth middleware always validates content-type header",
+ type: "bug",
+ files: ["src/middleware/auth.ts"],
+ // no project — legacy / unscoped
+ });
+
+ const apiResult = await sdk.trigger("mem::enrich", {
+ sessionId: "sess-api",
+ files: ["src/middleware/auth.ts"],
+ project: "api",
+ }) as { context: string };
+
+ const webResult = await sdk.trigger("mem::enrich", {
+ sessionId: "sess-web",
+ files: ["src/middleware/auth.ts"],
+ project: "web",
+ }) as { context: string };
+
+ expect(apiResult.context).toContain("generic auth middleware");
+ expect(webResult.context).toContain("generic auth middleware");
+ });
+
+ it("memories from different projects do not supersede each other via Jaccard dedup", async () => {
+ const sharedContent = "jwt token must be trimmed before validation in the middleware layer";
+
+ await sdk.trigger("mem::remember", {
+ content: sharedContent,
+ type: "bug",
+ files: ["src/middleware/auth.ts"],
+ project: "api",
+ });
+
+ // Save nearly identical content under a different project.
+ const result = await sdk.trigger("mem::remember", {
+ content: sharedContent,
+ type: "bug",
+ files: ["src/middleware/auth.ts"],
+ project: "web",
+ }) as { memory: { id: string; project: string } };
+
+ // Both memories must survive as independent latest entries.
+ const memories = await kv.list(KV.memories) as Array<{ isLatest: boolean; project: string }>;
+ const latestByProject = memories.filter((m) => m.isLatest);
+ const projects = latestByProject.map((m) => m.project);
+
+ expect(projects).toContain("api");
+ expect(projects).toContain("web");
+ expect(result.memory.project).toBe("web");
+ });
+});
diff --git a/test/diagnostics.test.ts b/test/diagnostics.test.ts
index 053e1c40..1e168767 100644
--- a/test/diagnostics.test.ts
+++ b/test/diagnostics.test.ts
@@ -195,10 +195,11 @@ describe("Diagnostics Functions", () => {
};
expect(result.success).toBe(true);
- // 14 = 8 original (actions, leases, sentinels, sketches, signals,
+ // 15 = 8 original (actions, leases, sentinels, sketches, signals,
// sessions, memories, mesh) + 6 added in #lesson-visibility
- // (lessons, summaries, semantic, procedural, crystals, insights).
- expect(result.summary.pass).toBe(14);
+ // (lessons, summaries, semantic, procedural, crystals, insights) +
+ // 1 added in #memory-project-scope (memory-project-coverage).
+ expect(result.summary.pass).toBe(15);
expect(result.summary.warn).toBe(0);
expect(result.summary.fail).toBe(0);
expect(result.summary.fixable).toBe(0);
diff --git a/test/enrich-project-isolation.test.ts b/test/enrich-project-isolation.test.ts
new file mode 100644
index 00000000..40016f13
--- /dev/null
+++ b/test/enrich-project-isolation.test.ts
@@ -0,0 +1,253 @@
+import { describe, it, expect, beforeEach, vi } from "vitest";
+
+vi.mock("../src/logger.js", () => ({
+ logger: { info: vi.fn(), warn: vi.fn(), error: vi.fn() },
+}));
+
+import { registerEnrichFunction } from "../src/functions/enrich.js";
+import type { Memory } from "../src/types.js";
+
+function mockKV() {
+ 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 mockSdk() {
+ const functions = new Map<string, Function>();
+ const triggerOverrides = 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;
+ if (triggerOverrides.has(id)) return triggerOverrides.get(id)!(payload);
+ const fn = functions.get(id);
+ if (!fn) throw new Error(`No function registered: ${id}`);
+ return fn(payload);
+ },
+ overrideTrigger: (id: string, handler: Function) => {
+ triggerOverrides.set(id, handler);
+ },
+ };
+}
+
+function makeBugMemory(overrides: Partial<Memory> = {}): Memory {
+ return {
+ id: "mem_bug_1",
+ createdAt: new Date().toISOString(),
+ updatedAt: new Date().toISOString(),
+ type: "bug",
+ title: "express-jwt whitespace bug",
+ content: "express-jwt throws 401 when Authorization header has extra whitespace after Bearer",
+ concepts: ["auth", "jwt"],
+ files: ["src/middleware/auth.ts"],
+ sessionIds: ["sess-api-001"],
+ strength: 8,
+ version: 1,
+ isLatest: true,
+ ...overrides,
+ };
+}
+
+describe("mem::enrich — project isolation for bug memories", () => {
+ let sdk: ReturnType<typeof mockSdk>;
+ let kv: ReturnType<typeof mockKV>;
+
+ beforeEach(() => {
+ sdk = mockSdk();
+ kv = mockKV();
+ registerEnrichFunction(sdk as never, kv as never);
+ sdk.overrideTrigger("mem::file-context", async () => ({ context: "" }));
+ sdk.overrideTrigger("mem::search", async () => ({ results: [] }));
+ });
+
+ it("does not surface a scoped bug memory when caller project differs", async () => {
+ await kv.set("mem:memories", "mem_bug_1", makeBugMemory({ project: "api" }));
+
+ const result = await sdk.trigger("mem::enrich", {
+ sessionId: "sess-web-001",
+ files: ["src/middleware/auth.ts"],
+ project: "web",
+ }) as { context: string };
+
+ expect(result.context).not.toContain("agentmemory-past-errors");
+ expect(result.context).not.toContain("express-jwt");
+ });
+
+ it("surfaces a scoped bug memory when caller project matches", async () => {
+ await kv.set("mem:memories", "mem_bug_1", makeBugMemory({ project: "api" }));
+
+ const result = await sdk.trigger("mem::enrich", {
+ sessionId: "sess-api-001",
+ files: ["src/middleware/auth.ts"],
+ project: "api",
+ }) as { context: string };
+
+ expect(result.context).toContain("agentmemory-past-errors");
+ expect(result.context).toContain("express-jwt");
+ });
+
+ it("surfaces an unscoped (legacy) bug memory regardless of caller project", async () => {
+ await kv.set("mem:memories", "mem_bug_1", makeBugMemory({ project: undefined }));
+
+ const result = await sdk.trigger("mem::enrich", {
+ sessionId: "sess-web-001",
+ files: ["src/middleware/auth.ts"],
+ project: "web",
+ }) as { context: string };
+
+ // Unscoped memories remain visible everywhere for backward-compat
+ expect(result.context).toContain("agentmemory-past-errors");
+ expect(result.context).toContain("express-jwt");
+ });
+
+ it("surfaces an unscoped bug memory when caller provides no project", async () => {
+ await kv.set("mem:memories", "mem_bug_1", makeBugMemory({ project: undefined }));
+
+ const result = await sdk.trigger("mem::enrich", {
+ sessionId: "sess-api-001",
+ files: ["src/middleware/auth.ts"],
+ }) as { context: string };
+
+ expect(result.context).toContain("agentmemory-past-errors");
+ });
+
+ it("surfaces a scoped bug memory when caller provides no project", async () => {
+ await kv.set("mem:memories", "mem_bug_1", makeBugMemory({ project: "api" }));
+
+ // No project on the caller — guard does not engage, memory is visible
+ const result = await sdk.trigger("mem::enrich", {
+ sessionId: "sess-api-001",
+ files: ["src/middleware/auth.ts"],
+ }) as { context: string };
+
+ expect(result.context).toContain("agentmemory-past-errors");
+ });
+
+ it("isolates multiple memories from different projects correctly", async () => {
+ await kv.set("mem:memories", "mem_api", makeBugMemory({
+ id: "mem_api",
+ project: "api",
+ title: "express-jwt whitespace",
+ content: "express-jwt whitespace issue",
+ files: ["src/middleware/auth.ts"],
+ }));
+ await kv.set("mem:memories", "mem_web", makeBugMemory({
+ id: "mem_web",
+ project: "web",
+ title: "nextauth cookie",
+ content: "nextauth cookie domain mismatch",
+ files: ["src/middleware/auth.ts"],
+ }));
+
+ const apiResult = await sdk.trigger("mem::enrich", {
+ sessionId: "sess-api-001",
+ files: ["src/middleware/auth.ts"],
+ project: "api",
+ }) as { context: string };
+
+ expect(apiResult.context).toContain("express-jwt");
+ expect(apiResult.context).not.toContain("nextauth");
+
+ const webResult = await sdk.trigger("mem::enrich", {
+ sessionId: "sess-web-001",
+ files: ["src/middleware/auth.ts"],
+ project: "web",
+ }) as { context: string };
+
+ expect(webResult.context).toContain("nextauth");
+ expect(webResult.context).not.toContain("express-jwt");
+ });
+
+ it("only includes latest bug memories, respecting project scope", async () => {
+ await kv.set("mem:memories", "mem_old", makeBugMemory({
+ id: "mem_old",
+ project: "api",
+ title: "old express bug",
+ content: "old express auth bug now fixed",
+ files: ["src/middleware/auth.ts"],
+ isLatest: false,
+ }));
+ await kv.set("mem:memories", "mem_new", makeBugMemory({
+ id: "mem_new",
+ project: "api",
+ title: "new express bug",
+ content: "new express auth edge case",
+ files: ["src/middleware/auth.ts"],
+ isLatest: true,
+ }));
+
+ const result = await sdk.trigger("mem::enrich", {
+ sessionId: "sess-api-001",
+ files: ["src/middleware/auth.ts"],
+ project: "api",
+ }) as { context: string };
+
+ expect(result.context).toContain("new express bug");
+ expect(result.context).not.toContain("old express auth bug");
+ });
+});
+
+describe("mem::enrich — project forwarded to mem::search", () => {
+ it("passes project to the search trigger when provided", async () => {
+ const sdk = mockSdk();
+ const kv = mockKV();
+ registerEnrichFunction(sdk as never, kv as never);
+
+ let capturedSearchPayload: Record<string, unknown> = {};
+ sdk.overrideTrigger("mem::file-context", async () => ({ context: "" }));
+ sdk.overrideTrigger("mem::search", async (payload: unknown) => {
+ capturedSearchPayload = payload as Record<string, unknown>;
+ return { results: [] };
+ });
+
+ await sdk.trigger("mem::enrich", {
+ sessionId: "sess-api-001",
+ files: ["src/middleware/auth.ts"],
+ project: "api",
+ });
+
+ expect(capturedSearchPayload.project).toBe("api");
+ });
+
+ it("does not pass project to search when caller provides none", async () => {
+ const sdk = mockSdk();
+ const kv = mockKV();
+ registerEnrichFunction(sdk as never, kv as never);
+
+ let capturedSearchPayload: Record<string, unknown> = {};
+ sdk.overrideTrigger("mem::file-context", async () => ({ context: "" }));
+ sdk.overrideTrigger("mem::search", async (payload: unknown) => {
+ capturedSearchPayload = payload as Record<string, unknown>;
+ return { results: [] };
+ });
+
+ await sdk.trigger("mem::enrich", {
+ sessionId: "sess-api-001",
+ files: ["src/middleware/auth.ts"],
+ });
+
+ expect(capturedSearchPayload.project).toBeUndefined();
+ });
+});
diff --git a/test/infer-memory-projects.test.ts b/test/infer-memory-projects.test.ts
new file mode 100644
index 00000000..ddd5e491
--- /dev/null
+++ b/test/infer-memory-projects.test.ts
@@ -0,0 +1,241 @@
+import { describe, it, expect, vi } from "vitest";
+
+vi.mock("../src/logger.js", () => ({
+ logger: { info: vi.fn(), warn: vi.fn(), error: vi.fn() },
+}));
+
+import { inferMemoryProjects } from "../src/functions/migrate.js";
+import { KV } from "../src/state/schema.js";
+import type { Memory, Session } 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 makeMemory(id: string, sessionIds: string[], project?: string): Memory {
+ return {
+ id,
+ createdAt: new Date().toISOString(),
+ updatedAt: new Date().toISOString(),
+ type: "bug",
+ title: `Memory ${id}`,
+ content: `Content for ${id}`,
+ concepts: [],
+ files: [],
+ sessionIds,
+ strength: 5,
+ version: 1,
+ isLatest: true,
+ ...(project !== undefined && { project }),
+ };
+}
+
+function makeSession(id: string, project: string): Session {
+ return {
+ id,
+ project,
+ cwd: `/srv/${project}`,
+ startedAt: new Date().toISOString(),
+ status: "completed",
+ observationCount: 0,
+ };
+}
+
+describe("inferMemoryProjects", () => {
+ it("skips memories that already have a project", async () => {
+ const kv = makeMockKV();
+ await kv.set(KV.memories, "mem_a", makeMemory("mem_a", [], "api"));
+
+ const result = await inferMemoryProjects(kv);
+
+ expect(result.skipped).toBe(1);
+ expect(result.updated).toBe(0);
+ expect(result.ambiguous).toBe(0);
+
+ const stored = await kv.get<Memory>(KV.memories, "mem_a");
+ expect(stored?.project).toBe("api");
+ });
+
+ it("marks a memory ambiguous when it has no sessionIds", async () => {
+ const kv = makeMockKV();
+ await kv.set(KV.memories, "mem_a", makeMemory("mem_a", []));
+
+ const result = await inferMemoryProjects(kv);
+
+ expect(result.ambiguous).toBe(1);
+ expect(result.updated).toBe(0);
+
+ const stored = await kv.get<Memory>(KV.memories, "mem_a");
+ expect(stored?.project).toBeUndefined();
+ });
+
+ it("marks a memory ambiguous when none of its sessions have a project", async () => {
+ const kv = makeMockKV();
+ const session: Session = {
+ id: "sess_a",
+ project: "",
+ cwd: "/tmp",
+ startedAt: new Date().toISOString(),
+ status: "completed",
+ observationCount: 0,
+ };
+ await kv.set(KV.sessions, "sess_a", session);
+ await kv.set(KV.memories, "mem_a", makeMemory("mem_a", ["sess_a"]));
+
+ const result = await inferMemoryProjects(kv);
+
+ expect(result.ambiguous).toBe(1);
+ expect(result.updated).toBe(0);
+ });
+
+ it("marks a memory ambiguous when all its sessions are missing from KV", async () => {
+ const kv = makeMockKV();
+ // Memory references sessions that don't exist (e.g. deleted)
+ await kv.set(KV.memories, "mem_a", makeMemory("mem_a", ["ghost_sess_1", "ghost_sess_2"]));
+
+ const result = await inferMemoryProjects(kv);
+
+ expect(result.ambiguous).toBe(1);
+ expect(result.updated).toBe(0);
+ });
+
+ it("infers project when all sessions belong to the same project", async () => {
+ const kv = makeMockKV();
+ await kv.set(KV.sessions, "sess_1", makeSession("sess_1", "api"));
+ await kv.set(KV.sessions, "sess_2", makeSession("sess_2", "api"));
+ await kv.set(KV.memories, "mem_a", makeMemory("mem_a", ["sess_1", "sess_2"]));
+
+ const result = await inferMemoryProjects(kv);
+
+ expect(result.updated).toBe(1);
+ expect(result.skipped).toBe(0);
+ expect(result.ambiguous).toBe(0);
+
+ const stored = await kv.get<Memory>(KV.memories, "mem_a");
+ expect(stored?.project).toBe("api");
+ });
+
+ it("infers the majority project when sessions span multiple projects", async () => {
+ const kv = makeMockKV();
+ await kv.set(KV.sessions, "sess_1", makeSession("sess_1", "api"));
+ await kv.set(KV.sessions, "sess_2", makeSession("sess_2", "api"));
+ await kv.set(KV.sessions, "sess_3", makeSession("sess_3", "web"));
+ // api appears 2 times, web 1 time — api wins strict majority
+ await kv.set(KV.memories, "mem_a", makeMemory("mem_a", ["sess_1", "sess_2", "sess_3"]));
+
+ const result = await inferMemoryProjects(kv);
+
+ expect(result.updated).toBe(1);
+ const stored = await kv.get<Memory>(KV.memories, "mem_a");
+ expect(stored?.project).toBe("api");
+ });
+
+ it("marks a memory ambiguous when sessions tie across two projects", async () => {
+ const kv = makeMockKV();
+ await kv.set(KV.sessions, "sess_1", makeSession("sess_1", "api"));
+ await kv.set(KV.sessions, "sess_2", makeSession("sess_2", "web"));
+ // exact 1-1 tie — no strict majority
+ await kv.set(KV.memories, "mem_a", makeMemory("mem_a", ["sess_1", "sess_2"]));
+
+ const result = await inferMemoryProjects(kv);
+
+ expect(result.ambiguous).toBe(1);
+ expect(result.updated).toBe(0);
+
+ const stored = await kv.get<Memory>(KV.memories, "mem_a");
+ expect(stored?.project).toBeUndefined();
+ });
+
+ it("counts correctly but does not write to KV in dry-run mode", async () => {
+ const kv = makeMockKV();
+ await kv.set(KV.sessions, "sess_1", makeSession("sess_1", "api"));
+ await kv.set(KV.memories, "mem_a", makeMemory("mem_a", ["sess_1"]));
+
+ const result = await inferMemoryProjects(kv, true);
+
+ expect(result.updated).toBe(1);
+
+ // KV must not have been written
+ const stored = await kv.get<Memory>(KV.memories, "mem_a");
+ expect(stored?.project).toBeUndefined();
+ });
+
+ it("handles a mix of already-scoped, updatable, and ambiguous memories in one pass", async () => {
+ const kv = makeMockKV();
+ await kv.set(KV.sessions, "sess_api", makeSession("sess_api", "api"));
+ await kv.set(KV.sessions, "sess_web", makeSession("sess_web", "web"));
+
+ // Already scoped
+ await kv.set(KV.memories, "mem_scoped", makeMemory("mem_scoped", [], "existing"));
+ // Will be updated
+ await kv.set(KV.memories, "mem_update", makeMemory("mem_update", ["sess_api"]));
+ // No sessionIds — ambiguous
+ await kv.set(KV.memories, "mem_no_sess", makeMemory("mem_no_sess", []));
+ // Tie — ambiguous
+ await kv.set(KV.memories, "mem_tie", makeMemory("mem_tie", ["sess_api", "sess_web"]));
+
+ const result = await inferMemoryProjects(kv);
+
+ expect(result.skipped).toBe(1);
+ expect(result.updated).toBe(1);
+ expect(result.ambiguous).toBe(2);
+
+ const updated = await kv.get<Memory>(KV.memories, "mem_update");
+ expect(updated?.project).toBe("api");
+
+ const scoped = await kv.get<Memory>(KV.memories, "mem_scoped");
+ expect(scoped?.project).toBe("existing");
+
+ const noSess = await kv.get<Memory>(KV.memories, "mem_no_sess");
+ expect(noSess?.project).toBeUndefined();
+
+ const tie = await kv.get<Memory>(KV.memories, "mem_tie");
+ expect(tie?.project).toBeUndefined();
+ });
+
+ it("ignores missing sessions when voting but still infers if remainder has majority", async () => {
+ const kv = makeMockKV();
+ await kv.set(KV.sessions, "sess_real", makeSession("sess_real", "api"));
+ // ghost_sess does not exist in KV — should be silently skipped in voting
+ await kv.set(KV.memories, "mem_a", makeMemory("mem_a", ["sess_real", "ghost_sess"]));
+
+ const result = await inferMemoryProjects(kv);
+
+ // Only one vote collected (api), which is a strict majority of 1 project out of 1
+ expect(result.updated).toBe(1);
+ const stored = await kv.get<Memory>(KV.memories, "mem_a");
+ expect(stored?.project).toBe("api");
+ });
+
+ it("is idempotent when run twice in succession", async () => {
+ const kv = makeMockKV();
+ await kv.set(KV.sessions, "sess_1", makeSession("sess_1", "api"));
+ await kv.set(KV.memories, "mem_a", makeMemory("mem_a", ["sess_1"]));
+
+ const first = await inferMemoryProjects(kv);
+ expect(first.updated).toBe(1);
+
+ const second = await inferMemoryProjects(kv);
+ expect(second.updated).toBe(0);
+ expect(second.skipped).toBe(1);
+
+ const stored = await kv.get<Memory>(KV.memories, "mem_a");
+ expect(stored?.project).toBe("api");
+ });
+});
diff --git a/test/remember-project-scope.test.ts b/test/remember-project-scope.test.ts
new file mode 100644
index 00000000..bda699f5
--- /dev/null
+++ b/test/remember-project-scope.test.ts
@@ -0,0 +1,258 @@
+import { describe, it, expect, beforeEach, afterEach } 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("iii-sdk", async (importOriginal) => {
+ const actual = await importOriginal<typeof import("iii-sdk")>();
+ return {
+ ...actual,
+ TriggerAction: {
+ ...actual.TriggerAction,
+ Void: vi.fn(() => ({ type: "void" })),
+ },
+ };
+});
+
+import { vi } from "vitest";
+import { registerRememberFunction } from "../src/functions/remember.js";
+import { getSearchIndex, setIndexPersistence } from "../src/functions/search.js";
+
+function mockKV() {
+ 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 mockSdk() {
+ const functions = new Map<string, Function>();
+ return {
+ registerFunction: (id: string, handler: Function) => {
+ functions.set(id, handler);
+ },
+ registerTrigger: () => {},
+ trigger: async (input: { function_id: string; payload: unknown; action?: unknown }) => {
+ const fn = functions.get(input.function_id);
+ if (!fn) return {};
+ return fn(input.payload);
+ },
+ };
+}
+
+describe("mem::remember — project field stamping", () => {
+ beforeEach(() => {
+ getSearchIndex().clear();
+ setIndexPersistence(null);
+ });
+
+ afterEach(() => {
+ setIndexPersistence(null);
+ });
+
+ it("persists project on the saved memory when provided", async () => {
+ const sdk = mockSdk();
+ const kv = mockKV();
+ registerRememberFunction(sdk as never, kv as never);
+
+ const result = await sdk.trigger({
+ function_id: "mem::remember",
+ payload: {
+ content: "express-jwt requires trimmed Bearer token",
+ type: "bug",
+ files: ["src/middleware/auth.ts"],
+ project: "api",
+ },
+ }) as { success: boolean; memory: { id: string; project?: string } };
+
+ expect(result.success).toBe(true);
+ expect(result.memory.project).toBe("api");
+
+ const stored = await kv.get<{ project?: string }>("mem:memories", result.memory.id);
+ expect(stored?.project).toBe("api");
+ });
+
+ it("leaves project undefined when not provided (backward-compat)", async () => {
+ const sdk = mockSdk();
+ const kv = mockKV();
+ registerRememberFunction(sdk as never, kv as never);
+
+ const result = await sdk.trigger({
+ function_id: "mem::remember",
+ payload: { content: "some unscoped memory" },
+ }) as { success: boolean; memory: { id: string; project?: string } };
+
+ expect(result.success).toBe(true);
+ expect(result.memory.project).toBeUndefined();
+ });
+
+ it("trims whitespace from the project value", async () => {
+ const sdk = mockSdk();
+ const kv = mockKV();
+ registerRememberFunction(sdk as never, kv as never);
+
+ const result = await sdk.trigger({
+ function_id: "mem::remember",
+ payload: { content: "padded project name", project: " api " },
+ }) as { success: boolean; memory: { project?: string } };
+
+ expect(result.memory.project).toBe("api");
+ });
+
+ it("treats a blank project string the same as no project", async () => {
+ const sdk = mockSdk();
+ const kv = mockKV();
+ registerRememberFunction(sdk as never, kv as never);
+
+ const result = await sdk.trigger({
+ function_id: "mem::remember",
+ payload: { content: "blank project string", project: " " },
+ }) as { success: boolean; memory: { project?: string } };
+
+ expect(result.memory.project).toBeUndefined();
+ });
+});
+
+describe("mem::remember — cross-project dedup isolation", () => {
+ beforeEach(() => {
+ getSearchIndex().clear();
+ setIndexPersistence(null);
+ });
+
+ afterEach(() => {
+ setIndexPersistence(null);
+ });
+
+ it("does not supersede a memory from a different project even when content is similar", async () => {
+ const sdk = mockSdk();
+ const kv = mockKV();
+ registerRememberFunction(sdk as never, kv as never);
+
+ // Save a memory in project "api"
+ const first = await sdk.trigger({
+ function_id: "mem::remember",
+ payload: {
+ content: "always use express-jwt middleware for token validation in this project",
+ type: "pattern",
+ project: "api",
+ },
+ }) as { memory: { id: string; isLatest: boolean; project?: string } };
+
+ // Save a near-identical memory in project "web" — should NOT supersede the api one
+ const second = await sdk.trigger({
+ function_id: "mem::remember",
+ payload: {
+ content: "always use express-jwt middleware for token validation in this project",
+ type: "pattern",
+ project: "web",
+ },
+ }) as { memory: { id: string; supersedes: string[]; project?: string } };
+
+ expect(second.memory.project).toBe("web");
+ expect(second.memory.supersedes).toHaveLength(0);
+
+ // The api memory must still be isLatest
+ const apiMemory = await kv.get<{ isLatest: boolean }>("mem:memories", first.memory.id);
+ expect(apiMemory?.isLatest).toBe(true);
+ });
+
+ it("still supersedes within the same project when content is similar", async () => {
+ const sdk = mockSdk();
+ const kv = mockKV();
+ registerRememberFunction(sdk as never, kv as never);
+
+ const first = await sdk.trigger({
+ function_id: "mem::remember",
+ payload: {
+ content: "always use express-jwt middleware for token validation in this project",
+ type: "pattern",
+ project: "api",
+ },
+ }) as { memory: { id: string } };
+
+ const second = await sdk.trigger({
+ function_id: "mem::remember",
+ payload: {
+ content: "always use express-jwt middleware for token validation in this project",
+ type: "pattern",
+ project: "api",
+ },
+ }) as { memory: { supersedes: string[] } };
+
+ expect(second.memory.supersedes).toContain(first.memory.id);
+
+ const original = await kv.get<{ isLatest: boolean }>("mem:memories", first.memory.id);
+ expect(original?.isLatest).toBe(false);
+ });
+
+ it("allows an unscoped memory to be superseded by a scoped one (legacy compat)", async () => {
+ const sdk = mockSdk();
+ const kv = mockKV();
+ registerRememberFunction(sdk as never, kv as never);
+
+ // Existing legacy memory with no project
+ const legacy = await sdk.trigger({
+ function_id: "mem::remember",
+ payload: {
+ content: "always use express-jwt middleware for token validation in this project",
+ type: "pattern",
+ },
+ }) as { memory: { id: string } };
+
+ // New scoped memory — should supersede the legacy unscoped one
+ const scoped = await sdk.trigger({
+ function_id: "mem::remember",
+ payload: {
+ content: "always use express-jwt middleware for token validation in this project",
+ type: "pattern",
+ project: "api",
+ },
+ }) as { memory: { supersedes: string[] } };
+
+ expect(scoped.memory.supersedes).toContain(legacy.memory.id);
+ });
+
+ it("allows a scoped memory to be superseded by an unscoped one (legacy compat)", async () => {
+ const sdk = mockSdk();
+ const kv = mockKV();
+ registerRememberFunction(sdk as never, kv as never);
+
+ const scoped = await sdk.trigger({
+ function_id: "mem::remember",
+ payload: {
+ content: "always use express-jwt middleware for token validation in this project",
+ type: "pattern",
+ project: "api",
+ },
+ }) as { memory: { id: string } };
+
+ // Unscoped write — should still supersede since one side has no project
+ const unscoped = await sdk.trigger({
+ function_id: "mem::remember",
+ payload: {
+ content: "always use express-jwt middleware for token validation in this project",
+ type: "pattern",
+ },
+ }) as { memory: { supersedes: string[] } };
+
+ expect(unscoped.memory.supersedes).toContain(scoped.memory.id);
+ });
+});