From db1194019d700d790e110ed9fff070470b9f5ffc Mon Sep 17 00:00:00 2001 From: saya-ch Date: Fri, 6 Nov 2026 14:40:39 +0800 Subject: [PATCH] fix(plugin): confine turn-start recall to the calling session Automatic turn-start recall selected every trace visible to the profile. A trace stores its transcript verbatim, so a second Session's assistant text reached the first Session's prompt with nothing marking it as foreign (MemOS#1532). Add algorithm.retrieval.recallScope (default session). Only the turn-start injection path is pinned: explicit searches, decision repair and sub-agent retrieval keep profile-wide recall, because they deliberately look across history. The pin is pushed into the SQL WHERE so foreign rows cannot consume the LIMIT budget, and tier-2 drops the legacy same-session exclusion when pinned so the two predicates cannot AND into an always-empty result. L2/L3 stay unconfined. Session key comes from the existing RuntimeNamespace.sessionKey; no new config or runtime channel is introduced. A missing key fails open to profile-wide recall. --- .../core/config/defaults.ts | 4 + apps/memos-local-plugin/core/config/schema.ts | 15 + apps/memos-local-plugin/core/pipeline/deps.ts | 1 + .../core/pipeline/orchestrator.ts | 25 +- .../core/pipeline/retrieval-repos.ts | 55 ++- .../core/retrieval/tier2-trace.ts | 26 +- .../core/retrieval/types.ts | 8 + .../docs/CONFIG-ADVANCED.md | 18 + .../tests/unit/pipeline/recall-scope.test.ts | 395 ++++++++++++++++++ .../viewer/src/stores/i18n.ts | 6 + .../viewer/src/views/SettingsView.tsx | 20 + 11 files changed, 554 insertions(+), 19 deletions(-) create mode 100644 apps/memos-local-plugin/tests/unit/pipeline/recall-scope.test.ts diff --git a/apps/memos-local-plugin/core/config/defaults.ts b/apps/memos-local-plugin/core/config/defaults.ts index 093e06035..2d23d8df8 100644 --- a/apps/memos-local-plugin/core/config/defaults.ts +++ b/apps/memos-local-plugin/core/config/defaults.ts @@ -282,6 +282,10 @@ export const DEFAULT_CONFIG: ResolvedConfig = { bgLlmConcurrency: 2, }, retrieval: { + // Confine turn-start recall to the calling Session by default. A trace + // is a transcript, and injecting another Session's transcript makes the + // agent adopt that conversation as its own history (MemOS#1532). + recallScope: "session", tier1TopK: 3, tier2TopK: 5, tier3TopK: 2, diff --git a/apps/memos-local-plugin/core/config/schema.ts b/apps/memos-local-plugin/core/config/schema.ts index 49c6ad6e1..318f7f33b 100644 --- a/apps/memos-local-plugin/core/config/schema.ts +++ b/apps/memos-local-plugin/core/config/schema.ts @@ -463,6 +463,21 @@ const AlgorithmSchema = Type.Object({ bgLlmConcurrency: NumberInRange(2, 1, 8), }, { default: {} }), retrieval: Type.Object({ + /** + * Whether automatic (turn-start) recall may read traces written by other + * Sessions. A trace is a transcript (`[user] … / [assistant] …`), so + * injecting another Session's transcript makes the agent adopt that + * conversation as its own history (MemOS#1532). + * + * Only the turn-start injection path is confined. Explicit searches + * (`memos_search`), decision-repair and sub-agent retrieval stay + * profile-wide, because those paths deliberately look across history. + * L2/L3 artifacts are never confined by this switch either. + */ + recallScope: Type.Union([ + Type.Literal("session"), + Type.Literal("profile"), + ], { default: "session" }), /** How many Skill snippets to inject at turn start. */ tier1TopK: NumberInRange(3, 0, 100), /** How many trace/episode snippets to inject. */ diff --git a/apps/memos-local-plugin/core/pipeline/deps.ts b/apps/memos-local-plugin/core/pipeline/deps.ts index f3048fbbe..2fb5f0924 100644 --- a/apps/memos-local-plugin/core/pipeline/deps.ts +++ b/apps/memos-local-plugin/core/pipeline/deps.ts @@ -141,6 +141,7 @@ export function extractAlgorithmConfig( skill: alg.skill, feedback: alg.feedback, retrieval: { + recallScope: alg.retrieval.recallScope, tier1TopK: alg.retrieval.tier1TopK, tier2TopK: alg.retrieval.tier2TopK, tier3TopK: alg.retrieval.tier3TopK, diff --git a/apps/memos-local-plugin/core/pipeline/orchestrator.ts b/apps/memos-local-plugin/core/pipeline/orchestrator.ts index 17e444bd0..7283eef70 100644 --- a/apps/memos-local-plugin/core/pipeline/orchestrator.ts +++ b/apps/memos-local-plugin/core/pipeline/orchestrator.ts @@ -1093,11 +1093,30 @@ export function createPipeline(deps: PipelineDeps): PipelineHandle { const retrievalDeps = buildRetrievalDeps(deps, algorithm, foregroundResources); const turnStartRetrievalStats = new Map(); - function retrievalDepsFor(namespace = deps.namespace): typeof retrievalDeps { + /** + * Build the retrieval surface for one call. + * + * `recallScope` is only passed by the turn-start path. Every other entry + * point (tool-driven, skill-invoke, sub-agent, decision-repair) keeps + * profile-wide recall on purpose: decision-repair exists to find historical + * anti-patterns across Sessions, and `memos_search` is an explicit user + * request. Pinning them would turn a privacy fix into a functional + * regression. + * + * `config.recallScope` is narrowed in lockstep so tier-2 filter builders can + * suppress the same-session exclusions that would otherwise AND against the + * pin into an always-empty predicate. + */ + function retrievalDepsFor( + namespace = deps.namespace, + recallScope?: "session" | "profile", + ): typeof retrievalDeps { + const scope = recallScope ?? "profile"; return { ...retrievalDeps, + config: { ...retrievalDeps.config, recallScope: scope }, namespace, - repos: wrapRetrievalRepos(deps.repos, namespace), + repos: wrapRetrievalRepos(deps.repos, namespace, { recallScope: scope }), }; } @@ -1116,7 +1135,7 @@ export function createPipeline(deps: PipelineDeps): PipelineHandle { ts: input.ts, }; const result: RetrievalResult = await turnStartRetrieve( - retrievalDepsFor(input.namespace), + retrievalDepsFor(input.namespace, algorithm.retrieval.recallScope), ctx, { events: buses.retrieval, diff --git a/apps/memos-local-plugin/core/pipeline/retrieval-repos.ts b/apps/memos-local-plugin/core/pipeline/retrieval-repos.ts index 9a4773428..f80af24a5 100644 --- a/apps/memos-local-plugin/core/pipeline/retrieval-repos.ts +++ b/apps/memos-local-plugin/core/pipeline/retrieval-repos.ts @@ -12,7 +12,34 @@ import type { Repos } from "../storage/repos/index.js"; import type { RuntimeNamespace, TraceId } from "../../agent-contract/dto.js"; import { isVisibleTo, visibilityWhere } from "../runtime/namespace.js"; -export function wrapRetrievalRepos(repos: Repos, namespace: RuntimeNamespace): RetrievalRepos { +export interface RetrievalRepoOptions { + /** + * `session` confines L1 trace reads to `namespace.sessionKey`; anything else + * (the default) leaves recall profile-wide. + * + * A trace is a verbatim transcript (`[user] … / [assistant] …`). Injecting + * another Session's transcript makes the agent adopt that conversation as + * its own history, which is MemOS#1532. Only the turn-start injection path + * sets this; explicit searches, decision-repair and sub-agent retrieval + * deliberately keep looking across history. + */ + recallScope?: "session" | "profile"; +} + +export function wrapRetrievalRepos( + repos: Repos, + namespace: RuntimeNamespace, + options: RetrievalRepoOptions = {}, +): RetrievalRepos { + // Absent or non-string `sessionKey` fails open to profile-wide recall: a + // missing Session id must never silently confine recall to a Session that + // has no rows. + const sessionKey + = options.recallScope === "session" + && typeof namespace.sessionKey === "string" + && namespace.sessionKey.length > 0 + ? namespace.sessionKey + : undefined; return { skills: { searchByVector(query, k, opts) { @@ -47,21 +74,21 @@ export function wrapRetrievalRepos(repos: Repos, namespace: RuntimeNamespace): R return repos.traces.searchByVector( query, k, - mergeVisibility(opts, namespace), + mergeVisibility(opts, namespace, "", sessionKey), ); }, searchByText(ftsMatch, k, opts) { return repos.traces.searchByText( ftsMatch, k, - mergeVisibility(opts, namespace, "t"), + mergeVisibility(opts, namespace, "t", sessionKey), ); }, searchByPattern(terms, k, opts) { return repos.traces.searchByPattern( terms, k, - mergeVisibility(opts, namespace), + mergeVisibility(opts, namespace, "", sessionKey), ); }, getManyByIds(ids) { @@ -85,7 +112,7 @@ export function wrapRetrievalRepos(repos: Repos, namespace: RuntimeNamespace): R const rows = repos.traces.searchByErrorSignature( fragments, limit, - mergeVisibility(opts, namespace), + mergeVisibility(opts, namespace, "", sessionKey), ); return rows.filter((r) => isVisibleTo(r, namespace)).map((r) => ({ id: r.id, @@ -197,16 +224,29 @@ function mergeVisibility = {}; const includeLow = input.includeLowValue ?? deps.config.includeLowValue; if (!includeLow) parts.push("priority > 0"); + // When the caller pinned recall to one Session, the trace SQL already has + // `session_id = `. The `session_id != X` half of the predicates below + // would then AND into an always-empty result (`session_id = X AND + // session_id != X`), silently zeroing trace recall. Keep the other half of + // each OR — the time bound and the exact-text exclusion — so already-visible + // context is still filtered out. + const scoped = deps.config.recallScope === "session"; const visible = input.visibleContext; if ( visible && typeof visible.startTs === "number" && Number.isFinite(visible.startTs) ) { - parts.push( - "(session_id != @visible_context_session_id OR ts < @visible_context_start_ts)", - ); - params.visible_context_session_id = visible.sessionId; + parts.push(scoped + ? "ts < @visible_context_start_ts" + : "(session_id != @visible_context_session_id OR ts < @visible_context_start_ts)"); + if (!scoped) params.visible_context_session_id = visible.sessionId; params.visible_context_start_ts = visible.startTs; } else if (visible) { const texts = Array.from( @@ -370,12 +377,13 @@ function buildTraceSearchFilters( texts.forEach((text, index) => { params[`visible_user_text_${index}`] = text; }); - parts.push( - `(session_id != @visible_context_session_id OR user_text NOT IN (${placeholders.join(", ")}))`, - ); - params.visible_context_session_id = visible.sessionId; + const exclusion = `user_text NOT IN (${placeholders.join(", ")})`; + parts.push(scoped + ? exclusion + : `(session_id != @visible_context_session_id OR ${exclusion})`); + if (!scoped) params.visible_context_session_id = visible.sessionId; } - } else if (input.excludeSessionId) { + } else if (!scoped && input.excludeSessionId) { parts.push("session_id != @exclude_session_id"); params.exclude_session_id = input.excludeSessionId; } diff --git a/apps/memos-local-plugin/core/retrieval/types.ts b/apps/memos-local-plugin/core/retrieval/types.ts index fe700c611..015e26b99 100644 --- a/apps/memos-local-plugin/core/retrieval/types.ts +++ b/apps/memos-local-plugin/core/retrieval/types.ts @@ -222,6 +222,14 @@ export interface RankedSnippet { * build minimal configs without standing up the TypeBox defaults. */ export interface RetrievalConfig { + /** + * Runtime marker: whether this particular retrieval is pinned to its + * Session. `buildRetrievalDeps` seeds it from the on-disk preference; + * `orchestrator.retrievalDepsFor` then narrows it to `"profile"` for every + * path except turn-start automatic injection. Optional so hand-written + * configs in tests and embedders stay valid; absent means no pin. + */ + recallScope?: "session" | "profile"; tier1TopK: number; tier2TopK: number; tier3TopK: number; diff --git a/apps/memos-local-plugin/docs/CONFIG-ADVANCED.md b/apps/memos-local-plugin/docs/CONFIG-ADVANCED.md index e25743e34..3bdb570f6 100644 --- a/apps/memos-local-plugin/docs/CONFIG-ADVANCED.md +++ b/apps/memos-local-plugin/docs/CONFIG-ADVANCED.md @@ -169,6 +169,24 @@ algorithm: traceCharCap: 500 # chars per evidence trace in the decision-repair prompt evidenceLimit: 4 # max high-value / low-value traces per synthesis call retrieval: + recallScope: session # session (default) | profile — see note below + # `session` confines turn-start automatic recall to the calling Session: a + # trace is a transcript (`[user] … / [assistant] …`), and injecting another + # Session's transcript makes the agent adopt that conversation as its own + # history (MemOS#1532). `profile` restores the old behaviour, where every + # Session sharing this home AND `profileId` can recall the others' + # transcripts. + # + # Only the turn-start injection path is affected. Explicit `memos_search` + # calls, decision repair and sub-agent retrieval stay profile-wide: they + # deliberately look across history, and pinning them returns nothing. + # + # UPGRADE NOTE: existing installs have no `recallScope` on disk and + # therefore inherit `session`, losing cross-session transcript recall from + # automatic injection. Set `recallScope: profile` to opt back in. + # + # L2/L3 artifacts (`policies`, `world_model`) and skills are + # statement-shaped rather than transcript-shaped and are never confined. tier1TopK: 3 # skills injected at turn start tier2TopK: 5 # trace/episode snippets tier3TopK: 2 # world-model snippets diff --git a/apps/memos-local-plugin/tests/unit/pipeline/recall-scope.test.ts b/apps/memos-local-plugin/tests/unit/pipeline/recall-scope.test.ts new file mode 100644 index 000000000..1b780b3b2 --- /dev/null +++ b/apps/memos-local-plugin/tests/unit/pipeline/recall-scope.test.ts @@ -0,0 +1,395 @@ +/** + * Regression for cross-session transcript injection (MemOS#1532). + * + * A trace is a verbatim transcript (`[user] … / [assistant] …`). Injecting + * another Session's trace at turn start makes the agent adopt that + * conversation as its own history. Only the *automatic turn-start injection* + * path is confined here; explicit searches, decision-repair and sub-agent + * retrieval deliberately keep looking across history. + * + * Everything runs against a real temporary SQLite database through the real + * `wrapRetrievalRepos`. No spy-of-arguments, no empty-database assertions and + * no tautological predicates: every test asserts on rows that were actually + * seeded and returned. + */ + +import { afterEach, beforeEach, describe, expect, it } from "vitest"; + +import { + createMemoryCore, + createPipeline, + type PipelineDeps, + type PipelineHandle, +} from "../../../core/pipeline/index.js"; +import { wrapRetrievalRepos } from "../../../core/pipeline/retrieval-repos.js"; +import { DEFAULT_CONFIG } from "../../../core/config/defaults.js"; +import { resolveHome } from "../../../core/config/paths.js"; +import { rootLogger } from "../../../core/logger/index.js"; +import { makeTmpDb, type TmpDbHandle } from "../../helpers/tmp-db.js"; +import type { Embedder } from "../../../core/embedding/types.js"; +import type { + EmbeddingVector, + EpisodeId, + PolicyId, + RuntimeNamespace, + SessionId, + TraceId, + TraceRow, + WorldModelId, +} from "../../../core/types.js"; + +const NOW = 1_700_000_000_000; +const PROFILE_ID = "main"; +const NS: RuntimeNamespace = { agentKind: "openclaw", profileId: PROFILE_ID }; +const PINNED_NS: RuntimeNamespace = { ...NS, sessionKey: "session-a" }; + +const SESSION_A = "session-a" as SessionId; +const SESSION_B = "session-b" as SessionId; +const EPISODE_A = "episode-a" as EpisodeId; +const EPISODE_B = "episode-b" as EpisodeId; +const TRACE_A = "trace-a" as TraceId; +const TRACE_B = "trace-b" as TraceId; +const TRACE_FOREIGN = "trace-foreign-profile" as TraceId; +const WORLD_MODEL_ID = "wm-from-b" as WorldModelId; +const POLICY_ID = "po-from-b" as PolicyId; + +const KEYWORD = "recallscopemarker"; +const ERROR_SIG = "ERR-RECALLSCOPE-42"; +const DIMS = 384; + +/** One shared unit vector: every seeded row and every query matches. */ +const VEC = (() => { + const v = new Float32Array(DIMS); + v[0] = 1; + return v as EmbeddingVector; +})(); + +/** Deterministic embedder so end-to-end vector retrieval actually hits. */ +function fixedEmbedder(): Embedder { + const stats = { + hits: 0, misses: 0, requests: 0, roundTrips: 0, failures: 0, + lastOkAt: null, lastError: null, + }; + return { + embedOne: async () => VEC, + embedMany: async (texts: readonly string[]) => texts.map(() => VEC), + stats: () => stats, + } as unknown as Embedder; +} + +/** Full-width vector: the storage layer rejects mismatched dimensions. */ +function vec(first = 1, second = 0): EmbeddingVector { + const v = new Float32Array(DIMS); + v[0] = first; + v[1] = second; + return v as EmbeddingVector; +} + +function traceRow(args: { + id: TraceId; + sessionId: SessionId; + episodeId: EpisodeId; + userText: string; + vecSummary: EmbeddingVector; + ownerProfileId?: string; + ts?: number; +}): TraceRow { + return { + id: args.id, + episodeId: args.episodeId, + sessionId: args.sessionId, + ownerAgentKind: "openclaw", + ownerProfileId: args.ownerProfileId ?? PROFILE_ID, + ownerWorkspaceId: null, + ts: args.ts ?? NOW, + userText: args.userText, + agentText: "reply", + summary: null, + share: null, + toolCalls: [], + agentThinking: null, + reflection: null, + value: 0.8, + alpha: 0.5, + rHuman: null, + priority: 0.8, + tags: [], + errorSignatures: [ERROR_SIG], + vecSummary: args.vecSummary, + vecAction: null, + turnId: NOW, + schemaVersion: 1, + } as TraceRow; +} + +/** Two Sessions under the SAME profile — the exact shape of the bug. */ +function seed(repos: TmpDbHandle["repos"]): void { + for (const [sessionId, episodeId] of [ + [SESSION_A, EPISODE_A], + [SESSION_B, EPISODE_B], + ] as const) { + repos.sessions.upsert({ + id: sessionId, + agent: "openclaw", + ownerAgentKind: "openclaw", + ownerProfileId: PROFILE_ID, + ownerWorkspaceId: null, + startedAt: NOW, + lastSeenAt: NOW, + meta: {}, + }); + repos.episodes.upsert({ + id: episodeId, + sessionId, + ownerAgentKind: "openclaw", + ownerProfileId: PROFILE_ID, + ownerWorkspaceId: null, + startedAt: NOW, + endedAt: null, + traceIds: [], + rTask: null, + status: "open", + }); + } + + // session-b's vector is deliberately closer, so a post-filter would let it + // consume the whole Top-K budget and starve session-a (see the k=1 test). + repos.traces.insert(traceRow({ + id: TRACE_A, sessionId: SESSION_A, episodeId: EPISODE_A, + userText: `${KEYWORD} discussed in session a with ${ERROR_SIG}`, + vecSummary: vec(0.9, 0.1), + })); + repos.traces.insert(traceRow({ + id: TRACE_B, sessionId: SESSION_B, episodeId: EPISODE_B, + userText: `${KEYWORD} discussed in session b with ${ERROR_SIG}`, + vecSummary: vec(1, 0), + })); + // A row from a different profile: `getManyByIds` must still reject it. + repos.traces.insert(traceRow({ + id: TRACE_FOREIGN, sessionId: SESSION_A, episodeId: EPISODE_A, + userText: `${KEYWORD} private to another profile`, + vecSummary: vec(1, 0), + ownerProfileId: "other-profile", + })); + + // L2 / L3 are statement-shaped facts and must remain shareable even though + // they were distilled from the OTHER session's episode. + repos.worldModel.upsert({ + id: WORLD_MODEL_ID, + ownerAgentKind: "openclaw", + ownerProfileId: PROFILE_ID, + ownerWorkspaceId: null, + title: "l3-shared fact", + body: "l3-shared fact distilled from the other session", + structure: { environment: [], inference: [], constraints: [] }, + domainTags: ["l3-shared"], + confidence: 0.9, + policyIds: [], + sourceEpisodeIds: [EPISODE_B], + inducedBy: "unit", + vec: vec(1, 0), + createdAt: NOW, + updatedAt: NOW, + version: 1, + status: "active", + }); + repos.policies.insert({ + id: POLICY_ID, + ownerAgentKind: "openclaw", + ownerProfileId: PROFILE_ID, + ownerWorkspaceId: null, + title: "l2-shared policy", + trigger: "when the shared fact is needed", + procedure: "reuse the distilled fact", + verification: "the fact is reused", + boundary: "unit tests only", + support: 1, + gain: 0.7, + status: "active", + sourceEpisodeIds: [EPISODE_B], + inducedBy: "unit", + decisionGuidance: { preference: [], antiPattern: [] }, + vec: vec(1, 0), + createdAt: NOW, + updatedAt: NOW, + }); +} + +function pipelineDeps( + h: TmpDbHandle, + recallScope: "session" | "profile", + lightweight = true, +): PipelineDeps { + return { + agent: "openclaw", + home: resolveHome("openclaw", "/tmp/memos-recall-scope-test"), + config: { + ...DEFAULT_CONFIG, + algorithm: { + ...DEFAULT_CONFIG.algorithm, + lightweightMemory: { + ...DEFAULT_CONFIG.algorithm.lightweightMemory, + enabled: lightweight, + }, + retrieval: { ...DEFAULT_CONFIG.algorithm.retrieval, recallScope }, + }, + }, + db: h.db, + repos: h.repos, + llm: null, + reflectLlm: null, + l3Llm: null, + embedder: fixedEmbedder(), + log: rootLogger.child({ channel: "test.recall-scope" }), + namespace: PINNED_NS, + now: () => NOW, + }; +} + +describe("pipeline/recall-scope", () => { + let handle: TmpDbHandle | null = null; + let pipeline: PipelineHandle | null = null; + + beforeEach(() => { + handle = makeTmpDb(); + seed(handle.repos); + }); + + afterEach(async () => { + if (pipeline) { + try { await pipeline.shutdown("test.cleanup"); } catch { /* best effort */ } + pipeline = null; + } + handle?.cleanup(); + handle = null; + }); + + it("confines every trace search channel to the calling Session", () => { + const scoped = wrapRetrievalRepos(handle!.repos, PINNED_NS, { + recallScope: "session", + }); + + expect(scoped.traces.searchByVector(VEC, 10).map((h) => h.id)).toEqual([TRACE_A]); + // `RetrievalRepos` marks the text channels optional; the concrete wrapper + // always provides them, so the assertion below is safe. + expect(scoped.traces.searchByText!("recallscopemarker", 10).map((h) => h.id)).toEqual([TRACE_A]); + expect(scoped.traces.searchByPattern!(["recallscopemarker"], 10).map((h) => h.id)).toEqual([TRACE_A]); + expect( + scoped.traces.searchByErrorSignature([ERROR_SIG], 10).map((h) => h.id), + ).toEqual([TRACE_A]); + }); + + it("pins inside SQL so the foreign row cannot consume the k=1 budget", () => { + const scoped = wrapRetrievalRepos(handle!.repos, PINNED_NS, { + recallScope: "session", + }); + // Baseline: without the pin, the better-scored session-b wins the only slot. + const open = wrapRetrievalRepos(handle!.repos, PINNED_NS); + expect(open.traces.searchByVector(vec(1, 0), 1).map((h) => h.id)).toEqual([TRACE_B]); + expect(scoped.traces.searchByVector(vec(1, 0), 1).map((h) => h.id)).toEqual([TRACE_A]); + }); + + it("restores cross-session recall for scope=profile", () => { + const open = wrapRetrievalRepos(handle!.repos, PINNED_NS, { + recallScope: "profile", + }); + const ids = open.traces.searchByVector(VEC, 10).map((h) => h.id); + expect(ids).toContain(TRACE_A); + expect(ids).toContain(TRACE_B); + }); + + it("fails open when the namespace carries no sessionKey", () => { + const scoped = wrapRetrievalRepos(handle!.repos, NS, { + recallScope: "session", + }); + const ids = scoped.traces.searchByVector(VEC, 10).map((h) => h.id); + expect(ids).toContain(TRACE_A); + expect(ids).toContain(TRACE_B); + }); + + it("keeps the namespace boundary on getManyByIds without a session pin", () => { + const scoped = wrapRetrievalRepos(handle!.repos, PINNED_NS, { + recallScope: "session", + }); + const ids = scoped.traces.getManyByIds([TRACE_A, TRACE_B, TRACE_FOREIGN]) + .map((r) => r.id); + // Both same-profile Sessions' rows survive (L2/L3 evidence support), but a + // row from another profile is still rejected. + expect(ids).toContain(TRACE_A); + expect(ids).toContain(TRACE_B); + expect(ids).not.toContain(TRACE_FOREIGN); + }); + + it("leaves L2 policies and L3 world models unconfined", () => { + const scoped = wrapRetrievalRepos(handle!.repos, PINNED_NS, { + recallScope: "session", + }); + expect(scoped.worldModel.getById(WORLD_MODEL_ID)?.id).toBe(WORLD_MODEL_ID); + expect(scoped.policies!.getById(POLICY_ID)?.id).toBe(POLICY_ID); + }); + + it("confines the real turn-start injection path", async () => { + pipeline = createPipeline(pipelineDeps(handle!, "session")); + const core = createMemoryCore( + pipeline, + resolveHome("openclaw", "/tmp/memos-recall-scope-test"), + "test", + ); + await core.init(); + + const result = await core.onTurnStart({ + agent: "openclaw", + sessionId: "session-a", + userText: KEYWORD, + ts: NOW, + }); + const injected = String(result.injectedContext ?? ""); + expect(injected).toContain("session a"); + expect(injected).not.toContain("session b"); + }); + + it("does NOT pin explicit searches (decision-repair / memos_search stay cross-session)", async () => { + pipeline = createPipeline(pipelineDeps(handle!, "session")); + const core = createMemoryCore( + pipeline, + resolveHome("openclaw", "/tmp/memos-recall-scope-test"), + "test", + ); + await core.init(); + + const result = await core.searchMemory({ + agent: "openclaw", + query: KEYWORD, + topK: { tier1: 0, tier2: 5, tier3: 0 }, + }); + const body = result.hits.map((hit) => hit.snippet).join("\n"); + expect(body).toContain("session a"); + expect(body).toContain("session b"); + }); + + it("does not cancel the pin with the legacy same-session exclusion", async () => { + // With lightweight memory off, `retrieve.ts` passes + // `excludeSessionId = `, which emits + // `session_id != X`. AND-ed with the pin that is `session_id = X AND + // session_id != X` — always empty. tier-2 must drop the exclusion when + // pinned, or this test comes back with no context at all. + pipeline = createPipeline(pipelineDeps(handle!, "session", false)); + const core = createMemoryCore( + pipeline, + resolveHome("openclaw", "/tmp/memos-recall-scope-test"), + "test", + ); + await core.init(); + + const result = await core.onTurnStart({ + agent: "openclaw", + sessionId: "session-a", + userText: KEYWORD, + ts: NOW, + }); + const injected = String(result.injectedContext ?? ""); + expect(injected).toContain("session a"); + expect(injected).not.toContain("session b"); + }); +}); + diff --git a/apps/memos-local-plugin/viewer/src/stores/i18n.ts b/apps/memos-local-plugin/viewer/src/stores/i18n.ts index cf5564050..ff5c37134 100644 --- a/apps/memos-local-plugin/viewer/src/stores/i18n.ts +++ b/apps/memos-local-plugin/viewer/src/stores/i18n.ts @@ -959,6 +959,9 @@ const en = { "settings.general.lightweightMemory": "Enable memory self-evolution", "settings.general.lightweightMemory.desc": "Automatically distill tasks, experiences, environment knowledge and skills beyond basic summary memory. Uses more model calls and is best for heavy memory workflows. Save and restart to apply.", + "settings.general.crossSessionRecall": "Allow cross-session recall", + "settings.general.crossSessionRecall.desc": + "Off (default): turn-start automatic recall only injects traces written by the calling session. On: sessions sharing this home and profileId can recall each other's conversations — convenient, but the agent may mistake another session's words for its own history. Explicit searches and decision repair always stay cross-session. Save and restart to apply.", "settings.general.detailedLogs": "Show detailed debug logs", "settings.general.detailedLogs.desc": "Enable chain view, failure-only filtering, and task, experience, skill, environment and system log categories.", @@ -1835,6 +1838,9 @@ const zh: Record = { "settings.general.lightweightMemory": "启用记忆自进化", "settings.general.lightweightMemory.desc": "在基础摘要记忆之外,自动沉淀任务、经验、环境认知和技能。会调用更多模型能力,适合重度记忆使用场景。保存并重启后生效。", + "settings.general.crossSessionRecall": "允许跨会话召回", + "settings.general.crossSessionRecall.desc": + "关闭(默认):回合开始时的自动召回只注入本会话写入的对话记录。开启:共用同一目录且 profileId 相同的会话可以互相召回对方的对话——方便,但 AI 可能把别的会话里的话当成自己的历史。主动搜索和历史修复始终跨会话。保存并重启后生效。", "settings.general.detailedLogs": "显示详细调试日志", "settings.general.detailedLogs.desc": "开启后显示链路视图、仅看失败筛选,以及任务、经验、技能、环境认知和系统日志分类。", diff --git a/apps/memos-local-plugin/viewer/src/views/SettingsView.tsx b/apps/memos-local-plugin/viewer/src/views/SettingsView.tsx index 43d2efb1a..52c3e50d1 100644 --- a/apps/memos-local-plugin/viewer/src/views/SettingsView.tsx +++ b/apps/memos-local-plugin/viewer/src/views/SettingsView.tsx @@ -52,6 +52,13 @@ interface AlgorithmBlock { lightweightMemory?: { enabled?: boolean; }; + retrieval?: { + /** + * `session` (default) confines turn-start automatic recall to the calling + * Session; `profile` restores cross-session recall. See MemOS#1532. + */ + recallScope?: "session" | "profile"; + }; } interface ResolvedConfig { @@ -1006,6 +1013,19 @@ function GeneralTab({ +
+
+
+

{t("settings.general.crossSessionRecall")}

+

{t("settings.general.crossSessionRecall.desc")}

+
+ onPatchAlgorithm({ retrieval: { recallScope: v ? "profile" : "session" } })} + /> +
+
+