Self-evolving Context Database for AI Agents. Unify Agent Memory, Knowledge RAG and Skills.
Python agent-contextagent-memoryagent-pluginsagentic-ragcontext-databasedsh-pluginknowledge-basememorymemory-managementself-evolvingvector-database
Add workspace peer mode for memory plugins (#3099)
t0saki2a81edc707c6
diff --git a/.github/workflows/pr.yml b/.github/workflows/pr.ymlindex d7e341a4e..eb284ff67 100644--- a/.github/workflows/pr.yml+++ b/.github/workflows/pr.yml@@ -44,6 +44,7 @@ jobs:examples/memory-plugin-shared/install-opencode-jsonc.test.mjs \examples/memory-plugin-shared/sync.test.mjs \examples/memory-plugin-shared/recall-core.test.mjs \+ examples/memory-plugin-shared/workspace-peer.test.mjs \examples/memory-plugin-shared/uri-guard.test.mjs \examples/opencode-plugin/tests/*.test.mjs \examples/opencode-plugin/servers/mcp-proxy.test.mjs \diff --git a/examples/claude-code-memory-plugin/README.md b/examples/claude-code-memory-plugin/README.mdindex 7b513a5f3..b91e2e2a3 100644--- a/examples/claude-code-memory-plugin/README.md+++ b/examples/claude-code-memory-plugin/README.md@@ -134,8 +134,9 @@ All plugin behavior can be set via env vars. Connection / identity vars affect b| `OPENVIKING_ACCOUNT` | Multi-tenant account (`X-OpenViking-Account` header) || `OPENVIKING_USER` | Multi-tenant user (`X-OpenViking-User` header) || `OPENVIKING_PEER_ID` | Optional stable peer for recall and captured session messages |+| `OPENVIKING_WORKSPACE_PEER` | Derive a peer from the current workspace by default; set `0` to disable |-When `OPENVIKING_PEER_ID` is set, data-plane recall/profile requests send it as `X-OpenViking-Actor-Peer`; captured session messages store it as body `peer_id`. Subagent capture falls back to Claude's `agent_id` when no explicit peer is configured, so different subagents can keep separate peer memory by default.+By default the plugin derives a peer from the workspace path using Claude's project-directory naming rule: every non-letter-or-digit character becomes `-`, with no path normalization. For example, `/Users/x/Dev/OpenViking` becomes `-Users-x-Dev-OpenViking`. Data-plane recall/profile requests send the effective peer as `X-OpenViking-Actor-Peer`; captured session messages store it as body `peer_id`. `OPENVIKING_PEER_ID` overrides the workspace-derived value. Set `OPENVIKING_WORKSPACE_PEER=0` to turn this off. Subagent capture uses the parent workspace peer when available, and falls back to Claude's `agent_id` only when no explicit or workspace peer exists.#### Recall tuning@@ -146,8 +147,11 @@ When `OPENVIKING_PEER_ID` is set, data-plane recall/profile requests send it as| `OPENVIKING_RECALL_TOKEN_BUDGET` | `2000` | Token budget for inline content; over-budget items degrade to URI hints || `OPENVIKING_RECALL_MAX_CONTENT_CHARS` | `500` | Per-item content cap || `OPENVIKING_RECALL_PREFER_ABSTRACT` | `true` | Prefer abstract over full body when available |+| `OPENVIKING_RECALL_PEER_SCOPE` | `all` | `all` can recall other project memories with a score penalty; `actor` only sees global plus the current project || `OPENVIKING_SCORE_THRESHOLD` | `0.35` | Min relevance score (0–1) || `OPENVIKING_MIN_QUERY_LENGTH` | `3` | Skip recall for very short queries |++Recall defaults to the broad mode: global memory, the current workspace, and other workspace memories can all be recalled, with other workspaces penalized and rendered later. Set `OPENVIKING_RECALL_PEER_SCOPE=actor` for the isolation mode, which only sees global memory plus the current workspace. In deployments where one bot serves multiple real people, such as zouk, vikingbot, or AstrBot, use the isolation mode with an explicit actor peer so one person's memories are not recalled into another person's session.| `OPENVIKING_LOG_RANKING_DETAILS` | `false` | Per-candidate scoring logs (verbose) |#### Capture tuningdiff --git a/examples/claude-code-memory-plugin/scripts/auto-capture.mjs b/examples/claude-code-memory-plugin/scripts/auto-capture.mjsindex bb54f30ff..bb2293fd8 100644--- a/examples/claude-code-memory-plugin/scripts/auto-capture.mjs+++ b/examples/claude-code-memory-plugin/scripts/auto-capture.mjs@@ -36,6 +36,7 @@ import {} from "./lib/ov-session.mjs";import { maybeDetach, readHookStdin } from "./lib/async-writer.mjs";import { readJsonState, writeJsonState } from "./lib/state.mjs";+import { getEffectivePeerId } from "./lib/workspace-peer.mjs";if (!isPluginEnabled()) {process.stdout.write(JSON.stringify({ decision: "approve" }) + "\n");@@ -391,12 +392,11 @@ function sanitizePartsForSend(parts) {return out;}-async function pushTurnsToOv(ovSessionId, turns) {+async function pushTurnsToOv(ovSessionId, turns, peerId = "") {let ok = 0;let queued = 0;let failed = 0;let enqueueFailed = 0;- const peerId = cfg.peerId || null;for (const turn of turns) {// Send structured parts: tool calls/results are dedicated `tool` parts, not// inlined into content, so the server can process them separately.@@ -414,10 +414,9 @@ async function pushTurnsToOv(ovSessionId, turns) {return { ok, queued, failed, enqueueFailed };}-async function enqueueTurnsToPending(ovSessionId, turns) {+async function enqueueTurnsToPending(ovSessionId, turns, peerId = "") {let queued = 0;let failed = 0;- const peerId = cfg.peerId || null;for (const turn of turns) {const parts = sanitizePartsForSend(turn.parts);if (parts.length === 0) continue;@@ -458,7 +457,8 @@ async function main() {const sessionId = input.session_id || "unknown";const cwd = input.cwd;const ovSessionId = sessionId !== "unknown" ? deriveOvSessionId(sessionId) : null;- log("start", { sessionId, ovSessionId, transcriptPath });+ const effectivePeer = getEffectivePeerId(cfg, { sessionId, cwd });+ log("start", { sessionId, ovSessionId, transcriptPath, peerSource: effectivePeer.source });if (isBypassed(cfg, { sessionId, cwd })) {log("skip", { reason: "bypass_session_pattern" });@@ -564,10 +564,10 @@ async function main() {const health = await fetchJSON("/health");let result;if (health.ok) {- result = await pushTurnsToOv(ovSessionId, captureTurns);+ result = await pushTurnsToOv(ovSessionId, captureTurns, effectivePeer.peerId);} else if (isRetryableFailure(health)) {logError("health_check", "server unreachable or unhealthy; enqueuing capture");- result = await enqueueTurnsToPending(ovSessionId, captureTurns);+ result = await enqueueTurnsToPending(ovSessionId, captureTurns, effectivePeer.peerId);log("push_turns", {ovSessionId,ok: result.ok,diff --git a/examples/claude-code-memory-plugin/scripts/auto-recall.mjs b/examples/claude-code-memory-plugin/scripts/auto-recall.mjsindex dcb64fee8..6dac20068 100644--- a/examples/claude-code-memory-plugin/scripts/auto-recall.mjs+++ b/examples/claude-code-memory-plugin/scripts/auto-recall.mjs@@ -18,6 +18,8 @@ import { isPluginEnabled, loadConfig } from "./config.mjs";import { createLogger } from "./debug-log.mjs";import { isBypassed, makeFetchJSON } from "./lib/ov-session.mjs";import { writeJsonState } from "./lib/state.mjs";+import { getEffectivePeerId } from "./lib/workspace-peer.mjs";+import { postRecall } from "./shared/recall-core.mjs";if (!isPluginEnabled()) {process.stdout.write(JSON.stringify({ decision: "approve" }) + "\n");@@ -119,7 +121,7 @@ function dedupeItems(items) {const USER_RESERVED_DIRS = new Set(["memories", "skills"]);let _userSpaceCache = "";-async function resolveUserSpace() {+async function resolveUserSpace(actorPeerId = "") {if (_userSpaceCache) return _userSpaceCache;let fallbackSpace = "default";@@ -131,7 +133,7 @@ async function resolveUserSpace() {const lsRes = await fetchJSON(`/api/v1/fs/ls?uri=${encodeURIComponent("viking://user")}&output=original`,{},- { actorPeerId: cfg.peerId },+ { actorPeerId },);if (lsRes.ok && Array.isArray(lsRes.result)) {const spaces = lsRes.result@@ -148,7 +150,7 @@ async function resolveUserSpace() {return fallbackSpace;}-async function resolveTargetUri(targetUri) {+async function resolveTargetUri(targetUri, actorPeerId = "") {const trimmed = targetUri.trim().replace(/\/+$/, "");const m = trimmed.match(/^viking:\/\/user(?:\/(.*))?$/);if (!m) return trimmed;@@ -157,7 +159,7 @@ async function resolveTargetUri(targetUri) {const parts = rawRest.split("/").filter(Boolean);if (parts.length === 0) return trimmed;if (!USER_RESERVED_DIRS.has(parts[0])) return trimmed;- const space = await resolveUserSpace();+ const space = await resolveUserSpace(actorPeerId);return `viking://user/${space}/${parts.join("/")}`;}@@ -171,20 +173,20 @@ const SOURCES = [{ type: "skill", uri: "viking://user/skills", bucket: "skills" },];-async function searchOneSource(query, source, limit) {- const resolvedUri = await resolveTargetUri(source.uri);+async function searchOneSource(query, source, limit, actorPeerId = "") {+ const resolvedUri = await resolveTargetUri(source.uri, actorPeerId);const body = { query, target_uri: resolvedUri, limit, score_threshold: 0 };const res = await fetchJSON("/api/v1/search/find", {method: "POST",body: JSON.stringify(body),- }, { actorPeerId: cfg.peerId });+ }, { actorPeerId });if (!res.ok) return [];const items = res.result?.[source.bucket] || [];return items.map(item => ({ ...item, _sourceType: source.type }));}-async function searchAllSources(query, perSourceLimit) {- const results = await Promise.all(SOURCES.map(src => searchOneSource(query, src, perSourceLimit)));+async function searchAllSources(query, perSourceLimit, actorPeerId = "") {+ const results = await Promise.all(SOURCES.map(src => searchOneSource(query, src, perSourceLimit, actorPeerId)));const all = results.flat();log("search_summary", {counts: SOURCES.map((src, i) => ({ type: src.type, uri: src.uri, count: results[i].length })),@@ -210,7 +212,7 @@ function estimateTokens(text) {* Resolve display content for a single item.* Ported from openclaw-plugin/index.ts:1822 resolveMemoryContent.*/-async function resolveItemContent(item) {+async function resolveItemContent(item, actorPeerId = "") {let content;if (cfg.recallPreferAbstract && (item.abstract || item.overview || "").trim()) {@@ -220,7 +222,7 @@ async function resolveItemContent(item) {const res = await fetchJSON(`/api/v1/content/read?uri=${encodeURIComponent(item.uri)}`,{},- { actorPeerId: cfg.peerId },+ { actorPeerId },);const body = res.ok && typeof res.result === "string" ? res.result.trim() : "";content = body || (item.abstract || item.overview || "").trim() || item.uri;@@ -243,7 +245,7 @@ async function resolveItemContent(item) {* Front items (within budget) get full content lines.* Remaining items (beyond budget) degrade to URI + score only.*/-async function buildInjectionBlock(items) {+async function buildInjectionBlock(items, actorPeerId = "") {if (items.length === 0) return null;let budgetRemaining = cfg.recallTokenBudget;@@ -259,7 +261,7 @@ async function buildInjectionBlock(items) {const uriLine = `- [${item._sourceType} ${score}%] ${item.uri}`;if (budgetRemaining > 0) {- const content = await resolveItemContent(item);+ const content = await resolveItemContent(item, actorPeerId);const contentLine = `- [${item._sourceType} ${score}%] ${content}`;const lineTokens = estimateTokens(contentLine);@@ -291,22 +293,21 @@ async function buildInjectionBlock(items) {return { block: lines.join("\n"), contentCount, hintCount, budgetUsed };}-async function recallViaTypeQuotaEndpoint(query) {- const res = await fetchJSON("/api/v1/search/recall", {- method: "POST",- body: JSON.stringify({- query,- quotas: {- events: Math.max(cfg.recallLimit, 1),- entities: Math.max(cfg.recallLimit, 1),- preferences: Math.max(1, Math.min(cfg.recallLimit, 3)),- experiences: 0,- },- max_chars: Math.max(cfg.recallMaxContentChars * Math.max(cfg.recallLimit, 1), 1000),- min_score: cfg.scoreThreshold,- render: true,- }),- }, { actorPeerId: cfg.peerId });+async function recallViaTypeQuotaEndpoint(query, actorPeerId = "") {+ const body = {+ query,+ quotas: {+ events: Math.max(cfg.recallLimit, 1),+ entities: Math.max(cfg.recallLimit, 1),+ preferences: Math.max(1, Math.min(cfg.recallLimit, 3)),+ experiences: 0,+ },+ max_chars: Math.max(cfg.recallMaxContentChars * Math.max(cfg.recallLimit, 1), 1000),+ min_score: cfg.scoreThreshold,+ render: true,+ };+ if (cfg.recallPeerScope === "actor") body.peer_scope = "actor";+ const res = await postRecall(fetchJSON, body, { actorPeerId, log });if (!res.ok) {log("recall_endpoint_fallback", { status: res.status || 0 });return null;@@ -358,6 +359,7 @@ async function main() {const userPrompt = (input.prompt || "").trim();const sessionId = input.session_id;const cwd = input.cwd;+ const effectivePeer = getEffectivePeerId(cfg, { sessionId, cwd });log("start", {query: userPrompt.slice(0, 200),queryLength: userPrompt.length,@@ -366,6 +368,8 @@ async function main() {scoreThreshold: cfg.scoreThreshold,recallMaxContentChars: cfg.recallMaxContentChars,recallTokenBudget: cfg.recallTokenBudget,+ peerSource: effectivePeer.source,+ recallPeerScope: cfg.recallPeerScope,},});@@ -391,7 +395,7 @@ async function main() {return;}- const endpointBlock = await recallViaTypeQuotaEndpoint(userPrompt);+ const endpointBlock = await recallViaTypeQuotaEndpoint(userPrompt, effectivePeer.peerId);if (endpointBlock !== null) {if (!endpointBlock) {log("skip", { reason: "recall_endpoint_no_results" });@@ -414,7 +418,7 @@ async function main() {}const perSourceLimit = Math.max(cfg.recallLimit * 2, 8);- const raw = await searchAllSources(userPrompt, perSourceLimit);+ const raw = await searchAllSources(userPrompt, perSourceLimit, effectivePeer.peerId);if (raw.length === 0) {log("skip", { reason: "no results" });writeRecallState({ count: 0, reason: "no_results", cc_session_id: sessionId });@@ -441,7 +445,7 @@ async function main() {return;}- const built = await buildInjectionBlock(picked);+ const built = await buildInjectionBlock(picked, effectivePeer.peerId);const topScore = picked.reduce((m, it) => Math.max(m, clampScore(it.score)), 0);writeRecallState({count: picked.length,diff --git a/examples/claude-code-memory-plugin/scripts/config.mjs b/examples/claude-code-memory-plugin/scripts/config.mjsindex 788aadb75..1dc3d29bb 100644--- a/examples/claude-code-memory-plugin/scripts/config.mjs+++ b/examples/claude-code-memory-plugin/scripts/config.mjs@@ -20,14 +20,16 @@* Recall tuning:* OPENVIKING_AUTO_RECALL, OPENVIKING_RECALL_LIMIT, OPENVIKING_RECALL_TOKEN_BUDGET,* OPENVIKING_RECALL_MAX_CONTENT_CHARS, OPENVIKING_RECALL_PREFER_ABSTRACT,- * OPENVIKING_SCORE_THRESHOLD, OPENVIKING_MIN_QUERY_LENGTH, OPENVIKING_LOG_RANKING_DETAILS+ * OPENVIKING_SCORE_THRESHOLD, OPENVIKING_MIN_QUERY_LENGTH, OPENVIKING_LOG_RANKING_DETAILS,+ * OPENVIKING_RECALL_PEER_SCOPE* Capture tuning:* OPENVIKING_AUTO_CAPTURE, OPENVIKING_CAPTURE_MODE, OPENVIKING_CAPTURE_MAX_LENGTH,* OPENVIKING_CAPTURE_ASSISTANT_TURNS, OPENVIKING_COMMIT_TOKEN_THRESHOLD,* OPENVIKING_RESUME_CONTEXT_BUDGET* Lifecycle / behavior:* OPENVIKING_TIMEOUT_MS, OPENVIKING_CAPTURE_TIMEOUT_MS, OPENVIKING_WRITE_PATH_ASYNC,- * OPENVIKING_BYPASS_SESSION, OPENVIKING_BYPASS_SESSION_PATTERNS (CSV)+ * OPENVIKING_BYPASS_SESSION, OPENVIKING_BYPASS_SESSION_PATTERNS (CSV),+ * OPENVIKING_WORKSPACE_PEER* Profile injection (session_start):* OPENVIKING_NO_AUTO_INJECT, OPENVIKING_PROFILE_TOKEN_BUDGET* Skill experience injection (PostToolUse Read):@@ -170,6 +172,12 @@ export function loadConfig() {const peerId = str(process.env.OPENVIKING_PEER_ID, null)|| str(cc.peerId, null)|| str(cc.peer_id, "");+ const workspacePeer = envBool("OPENVIKING_WORKSPACE_PEER") ?? (cc.workspacePeer !== false);+ const recallPeerScopeRaw = str(+ process.env.OPENVIKING_RECALL_PEER_SCOPE,+ str(cc.recallPeerScope, "all"),+ );+ const recallPeerScope = recallPeerScopeRaw === "actor" ? "actor" : "all";// Each tuning field follows env > ovcli.conf is N/A (CLI doesn't carry tuning) >// ov.conf cc.* > built-in default. Env var names are flat OPENVIKING_* (no CC@@ -208,6 +216,7 @@ export function loadConfig() {accountId,userId,peerId,+ workspacePeer,timeoutMs,// Recall@@ -236,6 +245,7 @@ export function loadConfig() {num(cc.recallTokenBudget, 2000),))),recallPreferAbstract: envBool("OPENVIKING_RECALL_PREFER_ABSTRACT") ?? (cc.recallPreferAbstract !== false),+ recallPeerScope,// CaptureautoCapture: envBool("OPENVIKING_AUTO_CAPTURE") ?? (cc.autoCapture !== false),diff --git a/examples/claude-code-memory-plugin/scripts/lib/workspace-peer.mjs b/examples/claude-code-memory-plugin/scripts/lib/workspace-peer.mjsnew file mode 100644index 000000000..ceb6553f6--- /dev/null+++ b/examples/claude-code-memory-plugin/scripts/lib/workspace-peer.mjs@@ -0,0 +1,32 @@+import { readJsonState, writeJsonState } from "./state.mjs";+import { resolveEffectivePeerId } from "../shared/workspace-peer.mjs";++function stateName(sessionId) {+ const safe = String(sessionId || "").replace(/[^a-zA-Z0-9_-]/g, "_");+ return `ws-peer-${safe}.json`;+}++export function getEffectivePeerId(cfg, { sessionId = "", cwd = "" } = {}) {+ if (!sessionId) return resolveEffectivePeerId({ cfg, cwd });++ const name = stateName(sessionId);+ const cached = readJsonState(name);+ if (cached?.peerId && cached?.source) {+ if (String(cfg.peerId || "").trim()) {+ return resolveEffectivePeerId({ cfg, cwd });+ }+ if (cached.source === "workspace" && cfg.workspacePeer !== false) {+ return { peerId: String(cached.peerId), source: "workspace" };+ }+ }++ const resolved = resolveEffectivePeerId({ cfg, cwd });+ if (resolved.source === "workspace") {+ writeJsonState(name, {+ peerId: resolved.peerId,+ source: resolved.source,+ cwd: String(cwd || ""),+ });+ }+ return resolved;+}diff --git a/examples/claude-code-memory-plugin/scripts/session-start.mjs b/examples/claude-code-memory-plugin/scripts/session-start.mjsindex 8273047a3..8ab5485a2 100644--- a/examples/claude-code-memory-plugin/scripts/session-start.mjs+++ b/examples/claude-code-memory-plugin/scripts/session-start.mjs@@ -35,6 +35,7 @@ import {import { replayPending } from "./lib/pending-queue.mjs";import { buildProfileBlock, estimateTokens } from "./lib/profile-inject.mjs";import { writeJsonState } from "./lib/state.mjs";+import { getEffectivePeerId } from "./lib/workspace-peer.mjs";if (!isPluginEnabled()) {process.stdout.write(JSON.stringify({ decision: "approve" }) + "\n");@@ -105,7 +106,8 @@ async function main() {const source = input.source || "startup";const sessionId = input.session_id;const cwd = input.cwd;- log("start", { source, sessionId });+ const effectivePeer = getEffectivePeerId(cfg, { sessionId, cwd });+ log("start", { source, sessionId, peerSource: effectivePeer.source });if (isBypassed(cfg, { sessionId, cwd })) {log("skip", { reason: "bypass_session_pattern" });@@ -145,7 +147,7 @@ async function main() {let profile = null;if (!cfg.noAutoInject) {try {- profile = await buildProfileBlock(fetchJSON, cfg.profileTokenBudget, cfg.peerId);+ profile = await buildProfileBlock(fetchJSON, cfg.profileTokenBudget, effectivePeer.peerId);} catch (err) {logError("profile_inject", err);}diff --git a/examples/claude-code-memory-plugin/scripts/shared/recall-core.mjs b/examples/claude-code-memory-plugin/scripts/shared/recall-core.mjsindex 445f00b1a..d65f62ba9 100644--- a/examples/claude-code-memory-plugin/scripts/shared/recall-core.mjs+++ b/examples/claude-code-memory-plugin/scripts/shared/recall-core.mjs@@ -20,7 +20,7 @@ export function estimateTokens(text) {export function buildRecallEndpointBody(cfg = {}) {const limit = Math.max(Number(cfg.recallLimit || 0), 1);- return {+ const body = {query: "",quotas: {events: limit,@@ -32,6 +32,8 @@ export function buildRecallEndpointBody(cfg = {}) {min_score: Number.isFinite(Number(cfg.scoreThreshold)) ? Number(cfg.scoreThreshold) : 0.35,render: true,};+ if (cfg.recallPeerScope === "actor") body.peer_scope = "actor";+ return body;}function clampScore(v) {@@ -233,10 +235,7 @@ async function buildFallbackInjectionBlock(fetchJSON, items, cfg, actorPeerId =async function recallViaEndpoint(fetchJSON, cfg, query, actorPeerId = "", log = () => {}) {const body = buildRecallEndpointBody(cfg);body.query = query;- const res = await fetchJSON("/api/v1/search/recall", {- method: "POST",- body: JSON.stringify(body),- }, { actorPeerId });+ const res = await postRecall(fetchJSON, body, { actorPeerId, log });if (!res.ok) {log("recall_endpoint_fallback", { status: res.status || 0 });return null;@@ -251,6 +250,27 @@ async function recallViaEndpoint(fetchJSON, cfg, query, actorPeerId = "", log =].join("\n");}+export async function postRecall(fetchJSON, body, opts = {}) {+ const actorPeerId = opts.actorPeerId || "";+ const log = opts.log || (() => {});+ const request = { ...body };+ const res = await fetchJSON("/api/v1/search/recall", {+ method: "POST",+ body: JSON.stringify(request),+ }, { actorPeerId });+ if (!request.peer_scope || (res.status !== 400 && res.status !== 422)) {+ return res;+ }++ const downgraded = { ...request };+ delete downgraded.peer_scope;+ log("recall_peer_scope_downgrade", { status: res.status || 0 });+ return fetchJSON("/api/v1/search/recall", {+ method: "POST",+ body: JSON.stringify(downgraded),+ }, { actorPeerId });+}+export async function buildRecallBlock(fetchJSON, cfg, query, options = {}) {const actorPeerId = options.actorPeerId ?? cfg.peerId ?? "";const log = options.log || (() => {});diff --git a/examples/claude-code-memory-plugin/scripts/shared/workspace-peer.mjs b/examples/claude-code-memory-plugin/scripts/shared/workspace-peer.mjsnew file mode 100644index 000000000..6b5cd45ec--- /dev/null+++ b/examples/claude-code-memory-plugin/scripts/shared/workspace-peer.mjs@@ -0,0 +1,16 @@+// GENERATED FROM examples/memory-plugin-shared/lib. DO NOT EDIT.+export function deriveWorkspacePeerId(cwd) {+ return String(cwd || "").replace(/[^A-Za-z0-9]/g, "-");+}++export function resolveEffectivePeerId({ cfg = {}, cwd = "" } = {}) {+ const explicit = String(cfg.peerId || "").trim();+ if (explicit) return { peerId: explicit, source: "explicit" };++ if (cfg.workspacePeer !== false) {+ const peerId = deriveWorkspacePeerId(cwd);+ if (peerId) return { peerId, source: "workspace" };+ }++ return { peerId: "", source: "none" };+}diff --git a/examples/claude-code-memory-plugin/scripts/subagent-start.mjs b/examples/claude-code-memory-plugin/scripts/subagent-start.mjsindex 25db99afe..a5804972f 100644--- a/examples/claude-code-memory-plugin/scripts/subagent-start.mjs+++ b/examples/claude-code-memory-plugin/scripts/subagent-start.mjs@@ -23,6 +23,7 @@ import { tmpdir } from "node:os";import { isPluginEnabled, loadConfig } from "./config.mjs";import { createLogger } from "./debug-log.mjs";import { deriveOvSessionId, isBypassed } from "./lib/ov-session.mjs";+import { getEffectivePeerId } from "./lib/workspace-peer.mjs";if (!isPluginEnabled()) {process.stdout.write(JSON.stringify({ decision: "approve" }) + "\n");@@ -63,6 +64,7 @@ async function main() {const subagentId = input.agent_id;const agentType = input.agent_type || "subagent";const cwd = input.cwd;+ const effectivePeer = getEffectivePeerId(cfg, { sessionId, cwd });if (!sessionId || !subagentId) {log("skip", { reason: "missing session_id or agent_id" });@@ -89,6 +91,8 @@ async function main() {subagentId,agentType,ovSessionId,+ peerId: effectivePeer.peerId,+ peerSource: effectivePeer.source,startedAt: Date.now(),}),);@@ -96,7 +100,7 @@ async function main() {logError("state_write", err);}- log("start", { subagentId, agentType, ovSessionId });+ log("start", { subagentId, agentType, ovSessionId, peerSource: effectivePeer.source });approve();}diff --git a/examples/claude-code-memory-plugin/scripts/subagent-stop.mjs b/examples/claude-code-memory-plugin/scripts/subagent-stop.mjsindex 5b24e111c..9b45ad6d4 100644--- a/examples/claude-code-memory-plugin/scripts/subagent-stop.mjs+++ b/examples/claude-code-memory-plugin/scripts/subagent-stop.mjs@@ -31,6 +31,7 @@ import {makeFetchJSON,} from "./lib/ov-session.mjs";import { maybeDetach, readHookStdin } from "./lib/async-writer.mjs";+import { getEffectivePeerId } from "./lib/workspace-peer.mjs";if (!isPluginEnabled()) {process.stdout.write(JSON.stringify({ decision: "approve" }) + "\n");@@ -51,8 +52,11 @@ function stateFile(subagentId) {return join(STATE_DIR, `${safe}.json`);}-function peerIdFromSubagent(subagentId) {+function peerIdFromSubagent(subagentId, state, sessionId, cwd) {if (cfg.peerId) return cfg.peerId;+ if (state?.peerId) return state.peerId;+ const effectivePeer = getEffectivePeerId(cfg, { sessionId, cwd });+ if (effectivePeer.peerId) return effectivePeer.peerId;return String(subagentId || "").replace(/[^A-Za-z0-9._-]/g, "-") || null;}@@ -330,7 +334,7 @@ async function main() {return;}- const peerId = peerIdFromSubagent(subagentId);+ const peerId = peerIdFromSubagent(subagentId, state, sessionId, cwd);const fetchJSON = makeFetchJSON(cfg);const health = await fetchJSON("/health");let result;diff --git a/examples/claude-code-memory-plugin/servers/mcp-proxy.mjs b/examples/claude-code-memory-plugin/servers/mcp-proxy.mjsindex 943cd0586..75fb2ff8d 100644--- a/examples/claude-code-memory-plugin/servers/mcp-proxy.mjs+++ b/examples/claude-code-memory-plugin/servers/mcp-proxy.mjs@@ -15,6 +15,7 @@ import { fileURLToPath } from "node:url";import { loadConfig } from "../scripts/config.mjs";import { createLogger } from "../scripts/debug-log.mjs";import { createOpenVikingMcpProxy } from "../scripts/shared/mcp-proxy-core.mjs";+import { resolveEffectivePeerId } from "../scripts/shared/workspace-peer.mjs";const DEFAULT_TIMEOUT_MS = 15000;@@ -36,12 +37,13 @@ function uniq(values) {function readProxyConfig() {const cfg = loadConfig();+ const effectivePeer = resolveEffectivePeerId({ cfg, cwd: process.cwd() });return {mcpUrl: `${trimSlash(cfg.baseUrl)}/mcp`,apiKey: cfg.apiKey || "",account: cfg.accountId || "",user: cfg.userId || "",- peerId: cfg.peerId || "",+ peerId: effectivePeer.peerId,timeoutMs: Math.max(1000, Number(cfg.timeoutMs) || DEFAULT_TIMEOUT_MS),debug: cfg.debug === true,debugLogPath: cfg.debugLogPath,diff --git a/examples/codex-memory-plugin/README.md b/examples/codex-memory-plugin/README.mdindex 516f3f85a..aa326f973 100644--- a/examples/codex-memory-plugin/README.md+++ b/examples/codex-memory-plugin/README.md@@ -103,7 +103,11 @@ Hooks and the MCP proxy call the same resolver directly, so the model tools andAuth is sent as `Authorization: Bearer <api_key>` to both the REST API (used by hooks) and the `/mcp` endpoint (used by the model).-Set `actor_peer_id` in `ovcli.conf` (or `OPENVIKING_PEER_ID` with `OPENVIKING_CREDENTIAL_SOURCE=env`) when multiple Codex peers share the same OpenViking user and should keep separate peer memory. Hooks pass it as `peer_id` for captured session messages and as `X-OpenViking-Actor-Peer` for retrieval/filesystem calls; MCP gets the same header mapping. The legacy `codex.peerId` / `codex.peer_id` fields in `ov.conf` still resolve as a fallback.+By default the plugin derives a peer from the current workspace path using Claude's project-directory naming rule: every non-letter-or-digit character becomes `-`, with no path normalization. For example, `/Users/x/Dev/OpenViking` becomes `-Users-x-Dev-OpenViking`. Hooks pass the effective peer as `peer_id` for captured session messages and as `X-OpenViking-Actor-Peer` for retrieval/filesystem calls; MCP gets the same header mapping.++Set `actor_peer_id` in `ovcli.conf` (or `OPENVIKING_PEER_ID` with `OPENVIKING_CREDENTIAL_SOURCE=env`) to override the workspace-derived peer. The legacy `codex.peerId` / `codex.peer_id` fields in `ov.conf` still resolve as a fallback. Set `OPENVIKING_WORKSPACE_PEER=0` or `codex.workspacePeer=false` to turn off workspace-derived peers.++Recall defaults to the broad mode: global memory, the current workspace, and other workspace memories can all be recalled, with other workspaces penalized and rendered later. Set `OPENVIKING_RECALL_PEER_SCOPE=actor` or `codex.recallPeerScope="actor"` for the isolation mode, which only sees global memory plus the current workspace. In deployments where one bot serves multiple real people, such as zouk, vikingbot, or AstrBot, use the isolation mode with an explicit actor peer so one person's memories are not recalled into another person's session.The checked-in `.mcp.json` contains only a stdio command. It never stores server URLs, bearer-token env mappings, or identity headers, so switching `ovcli.conf` changes the MCP target on the next Codex launch without cache rendering.diff --git a/examples/codex-memory-plugin/scripts/auto-capture.mjs b/examples/codex-memory-plugin/scripts/auto-capture.mjsindex 0e347d04e..c97e5f529 100644--- a/examples/codex-memory-plugin/scripts/auto-capture.mjs+++ b/examples/codex-memory-plugin/scripts/auto-capture.mjs@@ -32,9 +32,11 @@ import {import { loadConfig } from "./config.mjs";import { createLogger } from "./debug-log.mjs";import { loadState, resolveOvSessionId, saveState } from "./session-state.mjs";+import { resolveEffectivePeerId } from "./shared/workspace-peer.mjs";const cfg = loadConfig();const { log, logError } = createLogger("auto-capture");+let activePeerId = cfg.peerId || "";function output(obj) {process.stdout.write(JSON.stringify(obj) + "\n");@@ -55,7 +57,7 @@ async function fetchJSON(path, init = {}) {}if (cfg.sendIdentityHeaders && cfg.account) headers["X-OpenViking-Account"] = cfg.account;if (cfg.sendIdentityHeaders && cfg.user) headers["X-OpenViking-User"] = cfg.user;- if (cfg.peerId) headers["X-OpenViking-Actor-Peer"] = cfg.peerId;+ if (activePeerId) headers["X-OpenViking-Actor-Peer"] = activePeerId;const res = await fetch(`${cfg.baseUrl}${path}`, { ...init, headers, signal: controller.signal });const body = await res.json().catch(() => null);if (!body) return null;@@ -116,7 +118,7 @@ async function appendTurns(ovSessionId, turns, state) {const body = turn.parts?.length? { role: turn.role, parts: turn.parts }: { role: turn.role, content: turn.text };- if (cfg.peerId) body.peer_id = cfg.peerId;+ if (activePeerId) body.peer_id = activePeerId;const result = await fetchJSON(`/api/v1/sessions/${encodeURIComponent(ovSessionId)}/messages`, {method: "POST",body: JSON.stringify(body),@@ -182,7 +184,9 @@ async function main() {const sessionId = input.session_id || "unknown";const transcriptPath = input.transcript_path || null;- log("start", { sessionId, transcriptPath });+ const state = await loadState(sessionId);+ activePeerId = cfg.peerId || state.workspacePeerId || resolveEffectivePeerId({ cfg, cwd: process.cwd() }).peerId;+ log("start", { sessionId, transcriptPath, hasPeer: Boolean(activePeerId) });const health = await fetchJSON("/health");if (!health) {@@ -191,7 +195,6 @@ async function main() {return;}- const state = await loadState(sessionId);const allTurns = await readTranscriptTurns(transcriptPath);// Post-compact transcript-shrink defense: codex's /compact may rewrite ordiff --git a/examples/codex-memory-plugin/scripts/auto-recall.mjs b/examples/codex-memory-plugin/scripts/auto-recall.mjsindex 74298718b..f830103dc 100644--- a/examples/codex-memory-plugin/scripts/auto-recall.mjs+++ b/examples/codex-memory-plugin/scripts/auto-recall.mjs@@ -26,9 +26,12 @@ import {markRecallCompressorRuntimeFailed,} from "./recall-compressor-profile.mjs";import { deriveOvSessionId } from "./session-state.mjs";+import { postRecall } from "./shared/recall-core.mjs";+import { resolveEffectivePeerId } from "./shared/workspace-peer.mjs";const cfg = loadConfig();const { log, logError } = createLogger("auto-recall");+const effectivePeer = resolveEffectivePeerId({ cfg, cwd: process.cwd() });let emitted = false;let activeCompressor = null;@@ -94,7 +97,7 @@ async function fetchJSON(path, init = {}) {}if (cfg.sendIdentityHeaders && cfg.account) headers["X-OpenViking-Account"] = cfg.account;if (cfg.sendIdentityHeaders && cfg.user) headers["X-OpenViking-User"] = cfg.user;- if (cfg.peerId) headers["X-OpenViking-Actor-Peer"] = cfg.peerId;+ if (effectivePeer.peerId) headers["X-OpenViking-Actor-Peer"] = effectivePeer.peerId;const res = await fetch(`${cfg.baseUrl}${path}`, { ...init, headers, signal: controller.signal });const body = await res.json().catch(() => null);if (!body) return { ok: false, status: res.status };@@ -295,21 +298,20 @@ async function readMemoryContent(uri) {}async function recallViaTypeQuotaEndpoint(query) {- const result = await fetchJSON("/api/v1/search/recall", {- method: "POST",- body: JSON.stringify({- query,- quotas: {- events: Math.max(cfg.recallLimit, 1),- entities: Math.max(cfg.recallLimit, 1),- preferences: Math.max(1, Math.min(cfg.recallLimit, 3)),- experiences: 0,- },- max_chars: cfg.recallCompressMaxInputChars || 6500,- min_score: cfg.scoreThreshold,- render: true,- }),- });+ const body = {+ query,+ quotas: {+ events: Math.max(cfg.recallLimit, 1),+ entities: Math.max(cfg.recallLimit, 1),+ preferences: Math.max(1, Math.min(cfg.recallLimit, 3)),+ experiences: 0,+ },+ max_chars: cfg.recallCompressMaxInputChars || 6500,+ min_score: cfg.scoreThreshold,+ render: true,+ };+ if (cfg.recallPeerScope === "actor") body.peer_scope = "actor";+ const result = await postRecall(fetchJSON, body, { actorPeerId: effectivePeer.peerId, log });if (!result.ok) {log("recall_endpoint_fallback", { status: result.status || 0 });return null;@@ -531,7 +533,12 @@ async function main() {recallSessionId,query: userPrompt.slice(0, 200),queryLength: userPrompt.length,- config: { recallLimit: cfg.recallLimit, scoreThreshold: cfg.scoreThreshold },+ config: {+ recallLimit: cfg.recallLimit,+ scoreThreshold: cfg.scoreThreshold,+ peerSource: effectivePeer.source,+ recallPeerScope: cfg.recallPeerScope,+ },});if (!userPrompt || userPrompt.length < cfg.minQueryLength) {diff --git a/examples/codex-memory-plugin/scripts/config.mjs b/examples/codex-memory-plugin/scripts/config.mjsindex 724592856..efbabef5f 100644--- a/examples/codex-memory-plugin/scripts/config.mjs+++ b/examples/codex-memory-plugin/scripts/config.mjs@@ -33,6 +33,7 @@* OPENVIKING_RECALL_TIMEOUT_MS, OPENVIKING_RECALL_COMPRESS_TIMEOUT_MS* OPENVIKING_RECALL_COMPRESS_MODEL, OPENVIKING_RECALL_COMPRESS_THINKING* OPENVIKING_RECALL_LIMIT, OPENVIKING_SCORE_THRESHOLD+ * OPENVIKING_WORKSPACE_PEER, OPENVIKING_RECALL_PEER_SCOPE* OPENVIKING_DEBUG=1, OPENVIKING_DEBUG_LOG*/@@ -88,6 +89,12 @@ export function loadConfig() {const debug = envBool("OPENVIKING_DEBUG") ?? (cx.debug === true);const defaultLogPath = join(homedir(), ".openviking", "logs", "codex-hooks.log");const debugLogPath = str(process.env.OPENVIKING_DEBUG_LOG, defaultLogPath);+ const workspacePeer = envBool("OPENVIKING_WORKSPACE_PEER") ?? (cx.workspacePeer !== false);+ const recallPeerScopeRaw = str(+ process.env.OPENVIKING_RECALL_PEER_SCOPE,+ str(cx.recallPeerScope, "all"),+ );+ const recallPeerScope = recallPeerScopeRaw === "actor" ? "actor" : "all";const timeoutMs = Math.max(1000, Math.floor(num(process.env.OPENVIKING_TIMEOUT_MS,@@ -133,6 +140,7 @@ export function loadConfig() {account: creds.account,user: creds.user,peerId: creds.peerId,+ workspacePeer,timeoutMs,recallTimeoutMs,@@ -150,6 +158,7 @@ export function loadConfig() {num(cx.minQueryLength, 3),))),logRankingDetails: envBool("OPENVIKING_LOG_RANKING_DETAILS") ?? (cx.logRankingDetails === true),+ recallPeerScope,recallCompress: envBool("OPENVIKING_RECALL_COMPRESS") ?? (cx.recallCompress !== false),recallCompressModel,recallCompressThinking,diff --git a/examples/codex-memory-plugin/scripts/pre-compact-capture.mjs b/examples/codex-memory-plugin/scripts/pre-compact-capture.mjsindex 0288a5455..669b072ec 100644--- a/examples/codex-memory-plugin/scripts/pre-compact-capture.mjs+++ b/examples/codex-memory-plugin/scripts/pre-compact-capture.mjs@@ -27,9 +27,11 @@ import {import { loadConfig } from "./config.mjs";import { createLogger } from "./debug-log.mjs";import { loadState, resolveOvSessionId, saveState } from "./session-state.mjs";+import { resolveEffectivePeerId } from "./shared/workspace-peer.mjs";const cfg = loadConfig();const { log, logError } = createLogger("pre-compact");+let activePeerId = cfg.peerId || "";function output(obj) {process.stdout.write(JSON.stringify(obj) + "\n");@@ -50,7 +52,7 @@ async function fetchJSON(path, init = {}) {}if (cfg.sendIdentityHeaders && cfg.account) headers["X-OpenViking-Account"] = cfg.account;if (cfg.sendIdentityHeaders && cfg.user) headers["X-OpenViking-User"] = cfg.user;- if (cfg.peerId) headers["X-OpenViking-Actor-Peer"] = cfg.peerId;+ if (activePeerId) headers["X-OpenViking-Actor-Peer"] = activePeerId;const res = await fetch(`${cfg.baseUrl}${path}`, { ...init, headers, signal: controller.signal });const body = await res.json().catch(() => null);if (!body) return null;@@ -98,7 +100,7 @@ async function appendTurns(ovSessionId, turns) {const body = turn.parts?.length? { role: turn.role, parts: turn.parts }: { role: turn.role, content: turn.text };- if (cfg.peerId) body.peer_id = cfg.peerId;+ if (activePeerId) body.peer_id = activePeerId;const result = await fetchJSON(`/api/v1/sessions/${encodeURIComponent(ovSessionId)}/messages`, {method: "POST",body: JSON.stringify(body),@@ -130,7 +132,9 @@ async function main() {const sessionId = input.session_id || "unknown";const transcriptPath = input.transcript_path || null;const trigger = input.trigger || "auto";- log("start", { sessionId, transcriptPath, trigger });+ const state = await loadState(sessionId);+ activePeerId = cfg.peerId || state.workspacePeerId || resolveEffectivePeerId({ cfg, cwd: process.cwd() }).peerId;+ log("start", { sessionId, transcriptPath, trigger, hasPeer: Boolean(activePeerId) });const health = await fetchJSON("/health");if (!health) {@@ -139,7 +143,6 @@ async function main() {return;}- const state = await loadState(sessionId);const allTurns = await readTranscriptTurns(transcriptPath);const newTurns = allTurns.slice(state.capturedTurnCount);diff --git a/examples/codex-memory-plugin/scripts/session-start-commit.mjs b/examples/codex-memory-plugin/scripts/session-start-commit.mjsindex 48e99bc77..bc02d0bb8 100644--- a/examples/codex-memory-plugin/scripts/session-start-commit.mjs+++ b/examples/codex-memory-plugin/scripts/session-start-commit.mjs@@ -35,10 +35,12 @@import { loadConfig } from "./config.mjs";import { createLogger } from "./debug-log.mjs";import { detectRecallCompressorProfile } from "./recall-compressor-profile.mjs";-import { clearState, deriveOvSessionId, listStates, loadState } from "./session-state.mjs";+import { clearState, deriveOvSessionId, listStates, loadState, saveState } from "./session-state.mjs";+import { resolveEffectivePeerId } from "./shared/workspace-peer.mjs";const cfg = loadConfig();const { log, logError } = createLogger("session-start");+let activePeerId = cfg.peerId || "";const ACTIVE_WINDOW_MS = (() => {const v = Number(process.env.OPENVIKING_CODEX_ACTIVE_WINDOW_MS);@@ -87,7 +89,7 @@ async function fetchJSON(path, init = {}) {}if (cfg.sendIdentityHeaders && cfg.account) headers["X-OpenViking-Account"] = cfg.account;if (cfg.sendIdentityHeaders && cfg.user) headers["X-OpenViking-User"] = cfg.user;- if (cfg.peerId) headers["X-OpenViking-Actor-Peer"] = cfg.peerId;+ if (activePeerId) headers["X-OpenViking-Actor-Peer"] = activePeerId;const res = await fetch(`${cfg.baseUrl}${path}`, { ...init, headers, signal: controller.signal });const body = await res.json().catch(() => null);if (!body) return null;@@ -235,7 +237,22 @@ async function main() {const source = input.source || "unknown";const newSessionId = input.session_id || "unknown";- log("start", { source, newSessionId, activeWindowMs: ACTIVE_WINDOW_MS, idleTtlMs: IDLE_TTL_MS });+ const effectivePeer = resolveEffectivePeerId({ cfg, cwd: process.cwd() });+ activePeerId = effectivePeer.peerId;+ if (newSessionId !== "unknown") {+ const state = await loadState(newSessionId);+ await saveState({+ ...state,+ workspacePeerId: effectivePeer.source === "workspace" ? effectivePeer.peerId : "",+ });+ }+ log("start", {+ source,+ newSessionId,+ activeWindowMs: ACTIVE_WINDOW_MS,+ idleTtlMs: IDLE_TTL_MS,+ peerSource: effectivePeer.source,+ });try {await detectRecallCompressorProfile(cfg, { log, logError });diff --git a/examples/codex-memory-plugin/scripts/session-state.mjs b/examples/codex-memory-plugin/scripts/session-state.mjsindex 80bbee08a..9837c4768 100644--- a/examples/codex-memory-plugin/scripts/session-state.mjs+++ b/examples/codex-memory-plugin/scripts/session-state.mjs@@ -47,6 +47,7 @@ function defaultState(codexSessionId) {return {codexSessionId,ovSessionId: null,+ workspacePeerId: "",capturedTurnCount: 0,createdAt: now,lastUpdatedAt: now,diff --git a/examples/codex-memory-plugin/scripts/shared/recall-core.mjs b/examples/codex-memory-plugin/scripts/shared/recall-core.mjsindex 445f00b1a..d65f62ba9 100644--- a/examples/codex-memory-plugin/scripts/shared/recall-core.mjs+++ b/examples/codex-memory-plugin/scripts/shared/recall-core.mjs@@ -20,7 +20,7 @@ export function estimateTokens(text) {export function buildRecallEndpointBody(cfg = {}) {const limit = Math.max(Number(cfg.recallLimit || 0), 1);- return {+ const body = {query: "",quotas: {events: limit,@@ -32,6 +32,8 @@ export function buildRecallEndpointBody(cfg = {}) {min_score: Number.isFinite(Number(cfg.scoreThreshold)) ? Number(cfg.scoreThreshold) : 0.35,render: true,};+ if (cfg.recallPeerScope === "actor") body.peer_scope = "actor";+ return body;}function clampScore(v) {@@ -233,10 +235,7 @@ async function buildFallbackInjectionBlock(fetchJSON, items, cfg, actorPeerId =async function recallViaEndpoint(fetchJSON, cfg, query, actorPeerId = "", log = () => {}) {const body = buildRecallEndpointBody(cfg);body.query = query;- const res = await fetchJSON("/api/v1/search/recall", {- method: "POST",- body: JSON.stringify(body),- }, { actorPeerId });+ const res = await postRecall(fetchJSON, body, { actorPeerId, log });if (!res.ok) {log("recall_endpoint_fallback", { status: res.status || 0 });return null;@@ -251,6 +250,27 @@ async function recallViaEndpoint(fetchJSON, cfg, query, actorPeerId = "", log =].join("\n");}+export async function postRecall(fetchJSON, body, opts = {}) {+ const actorPeerId = opts.actorPeerId || "";+ const log = opts.log || (() => {});+ const request = { ...body };+ const res = await fetchJSON("/api/v1/search/recall", {+ method: "POST",+ body: JSON.stringify(request),+ }, { actorPeerId });+ if (!request.peer_scope || (res.status !== 400 && res.status !== 422)) {+ return res;+ }++ const downgraded = { ...request };+ delete downgraded.peer_scope;+ log("recall_peer_scope_downgrade", { status: res.status || 0 });+ return fetchJSON("/api/v1/search/recall", {+ method: "POST",+ body: JSON.stringify(downgraded),+ }, { actorPeerId });+}+export async function buildRecallBlock(fetchJSON, cfg, query, options = {}) {const actorPeerId = options.actorPeerId ?? cfg.peerId ?? "";const log = options.log || (() => {});diff --git a/examples/codex-memory-plugin/scripts/shared/workspace-peer.mjs b/examples/codex-memory-plugin/scripts/shared/workspace-peer.mjsnew file mode 100644index 000000000..6b5cd45ec--- /dev/null+++ b/examples/codex-memory-plugin/scripts/shared/workspace-peer.mjs@@ -0,0 +1,16 @@+// GENERATED FROM examples/memory-plugin-shared/lib. DO NOT EDIT.+export function deriveWorkspacePeerId(cwd) {+ return String(cwd || "").replace(/[^A-Za-z0-9]/g, "-");+}++export function resolveEffectivePeerId({ cfg = {}, cwd = "" } = {}) {+ const explicit = String(cfg.peerId || "").trim();+ if (explicit) return { peerId: explicit, source: "explicit" };++ if (cfg.workspacePeer !== false) {+ const peerId = deriveWorkspacePeerId(cwd);+ if (peerId) return { peerId, source: "workspace" };+ }++ return { peerId: "", source: "none" };+}diff --git a/examples/codex-memory-plugin/servers/mcp-proxy.mjs b/examples/codex-memory-plugin/servers/mcp-proxy.mjsindex 55460869d..f970d41b0 100644--- a/examples/codex-memory-plugin/servers/mcp-proxy.mjs+++ b/examples/codex-memory-plugin/servers/mcp-proxy.mjs@@ -15,6 +15,7 @@ import { loadConfig } from "../scripts/config.mjs";import { createLogger } from "../scripts/debug-log.mjs";import { resolveOpenVikingCredentials } from "../scripts/ov-credentials.mjs";import { createOpenVikingMcpProxy } from "../scripts/shared/mcp-proxy-core.mjs";+import { resolveEffectivePeerId } from "../scripts/shared/workspace-peer.mjs";export { createOpenVikingMcpProxy } from "../scripts/shared/mcp-proxy-core.mjs";@@ -39,13 +40,14 @@ function uniq(values) {function readProxyConfig() {const creds = resolveOpenVikingCredentials();const cfg = loadConfig();+ const effectivePeer = resolveEffectivePeerId({ cfg, cwd: process.cwd() });const mcpUrl = creds.mcpUrl || `${trimSlash(creds.baseUrl)}/mcp`;return {mcpUrl,apiKey: creds.apiKey || "",account: creds.account || "",user: creds.user || "",- peerId: creds.peerId || "",+ peerId: effectivePeer.peerId,timeoutMs: Math.max(1000, Number(cfg.timeoutMs) || DEFAULT_TIMEOUT_MS),debug: cfg.debug === true,debugLogPath: cfg.debugLogPath,diff --git a/examples/memory-plugin-shared/README.md b/examples/memory-plugin-shared/README.mdnew file mode 100644index 000000000..0706d7be3--- /dev/null+++ b/examples/memory-plugin-shared/README.md@@ -0,0 +1,38 @@+# Memory Plugin Shared Library++This directory contains shared JavaScript modules that are vendored into the+Claude Code, Codex, OpenCode, and pi memory plugins by `sync.mjs`.++## Workspace Peers++`lib/workspace-peer.mjs` derives the default actor peer from the current+workspace path. The rule matches Claude's project-directory naming: every+character outside `A-Z`, `a-z`, and `0-9` becomes `-`; paths are not normalized,+folded, or trimmed. For example, `/Users/x/Dev/OpenViking` becomes+`-Users-x-Dev-OpenViking`.++Resolution order is:++1. Explicit peer: `OPENVIKING_PEER_ID`, `actor_peer_id` / `peer_id` in+ `ovcli.conf`, or the harness-specific legacy peer config.+2. Workspace-derived peer when `workspacePeer` is not `false`.+3. No peer.++Set `OPENVIKING_WORKSPACE_PEER=0` or the harness config `workspacePeer=false`+to disable workspace-derived peers.++## Recall Peer Scope++`lib/recall-core.mjs` defaults to the broad recall mode and does not send a+`peer_scope` field. In that mode, the server can recall global memory, the+current workspace, and other workspace memories; other workspaces are penalized+and rendered later.++When `recallPeerScope` is `actor`, the helper sends `peer_scope:"actor"`. This+is the isolation mode: recall only sees global memory plus the current+workspace. If an older server rejects that field with 400 or 422, `postRecall`+removes `peer_scope` and retries once.++For deployments where one bot serves multiple real people, such as zouk,+vikingbot, or AstrBot, configure an explicit actor peer and use the isolation+mode so one person's memories are not recalled into another person's session.diff --git a/examples/memory-plugin-shared/lib/recall-core.mjs b/examples/memory-plugin-shared/lib/recall-core.mjsindex 0041c679c..7e4ce946d 100644--- a/examples/memory-plugin-shared/lib/recall-core.mjs+++ b/examples/memory-plugin-shared/lib/recall-core.mjs@@ -19,7 +19,7 @@ export function estimateTokens(text) {export function buildRecallEndpointBody(cfg = {}) {const limit = Math.max(Number(cfg.recallLimit || 0), 1);- return {+ const body = {query: "",quotas: {events: limit,@@ -31,6 +31,8 @@ export function buildRecallEndpointBody(cfg = {}) {min_score: Number.isFinite(Number(cfg.scoreThreshold)) ? Number(cfg.scoreThreshold) : 0.35,render: true,};+ if (cfg.recallPeerScope === "actor") body.peer_scope = "actor";+ return body;}function clampScore(v) {@@ -232,10 +234,7 @@ async function buildFallbackInjectionBlock(fetchJSON, items, cfg, actorPeerId =async function recallViaEndpoint(fetchJSON, cfg, query, actorPeerId = "", log = () => {}) {const body = buildRecallEndpointBody(cfg);body.query = query;- const res = await fetchJSON("/api/v1/search/recall", {- method: "POST",- body: JSON.stringify(body),- }, { actorPeerId });+ const res = await postRecall(fetchJSON, body, { actorPeerId, log });if (!res.ok) {log("recall_endpoint_fallback", { status: res.status || 0 });return null;@@ -250,6 +249,27 @@ async function recallViaEndpoint(fetchJSON, cfg, query, actorPeerId = "", log =].join("\n");}+export async function postRecall(fetchJSON, body, opts = {}) {+ const actorPeerId = opts.actorPeerId || "";+ const log = opts.log || (() => {});+ const request = { ...body };+ const res = await fetchJSON("/api/v1/search/recall", {+ method: "POST",+ body: JSON.stringify(request),+ }, { actorPeerId });+ if (!request.peer_scope || (res.status !== 400 && res.status !== 422)) {+ return res;+ }++ const downgraded = { ...request };+ delete downgraded.peer_scope;+ log("recall_peer_scope_downgrade", { status: res.status || 0 });+ return fetchJSON("/api/v1/search/recall", {+ method: "POST",+ body: JSON.stringify(downgraded),+ }, { actorPeerId });+}+export async function buildRecallBlock(fetchJSON, cfg, query, options = {}) {const actorPeerId = options.actorPeerId ?? cfg.peerId ?? "";const log = options.log || (() => {});diff --git a/examples/memory-plugin-shared/lib/workspace-peer.mjs b/examples/memory-plugin-shared/lib/workspace-peer.mjsnew file mode 100644index 000000000..6cee29155--- /dev/null+++ b/examples/memory-plugin-shared/lib/workspace-peer.mjs@@ -0,0 +1,15 @@+export function deriveWorkspacePeerId(cwd) {+ return String(cwd || "").replace(/[^A-Za-z0-9]/g, "-");+}++export function resolveEffectivePeerId({ cfg = {}, cwd = "" } = {}) {+ const explicit = String(cfg.peerId || "").trim();+ if (explicit) return { peerId: explicit, source: "explicit" };++ if (cfg.workspacePeer !== false) {+ const peerId = deriveWorkspacePeerId(cwd);+ if (peerId) return { peerId, source: "workspace" };+ }++ return { peerId: "", source: "none" };+}diff --git a/examples/memory-plugin-shared/recall-core.test.mjs b/examples/memory-plugin-shared/recall-core.test.mjsindex c60527b4c..2c6d66f76 100644--- a/examples/memory-plugin-shared/recall-core.test.mjs+++ b/examples/memory-plugin-shared/recall-core.test.mjs@@ -1,6 +1,6 @@import test from "node:test";import assert from "node:assert/strict";-import { buildRecallBlock, buildRecallEndpointBody } from "./lib/recall-core.mjs";+import { buildRecallBlock, buildRecallEndpointBody, postRecall } from "./lib/recall-core.mjs";test("buildRecallEndpointBody maps quotas and max chars", () => {const body = buildRecallEndpointBody({@@ -17,6 +17,12 @@ test("buildRecallEndpointBody maps quotas and max chars", () => {assert.equal(body.max_chars, 3000);assert.equal(body.min_score, 0.35);assert.equal(body.render, true);+ assert.equal(body.peer_scope, undefined);+});++test("buildRecallEndpointBody only sends actor peer scope when explicitly configured", () => {+ assert.equal(buildRecallEndpointBody({ recallPeerScope: "all" }).peer_scope, undefined);+ assert.equal(buildRecallEndpointBody({ recallPeerScope: "actor" }).peer_scope, "actor");});test("buildRecallBlock uses recall endpoint render when available", async () => {@@ -78,3 +84,47 @@ test("buildRecallBlock falls back to find and keeps first item over budget", asyassert.match(block, /\[memory 90%\]/);assert.match(block, /x{100}/);});++test("postRecall downgrades peer_scope on 400 and 422", async () => {+ for (const status of [400, 422]) {+ const bodies = [];+ const logs = [];+ const res = await postRecall(async (path, init, opts) => {+ bodies.push({ path, body: JSON.parse(init.body), opts });+ return bodies.length === 1+ ? { ok: false, status }+ : { ok: true, status: 200, result: { rendered: "ok" } };+ }, {+ query: "hello",+ peer_scope: "actor",+ }, {+ actorPeerId: "peer-a",+ log: (stage, data) => logs.push({ stage, data }),+ });++ assert.equal(res.ok, true);+ assert.equal(bodies.length, 2);+ assert.equal(bodies[0].body.peer_scope, "actor");+ assert.equal(bodies[1].body.peer_scope, undefined);+ assert.equal(bodies[0].opts.actorPeerId, "peer-a");+ assert.deepEqual(logs, [{ stage: "recall_peer_scope_downgrade", data: { status } }]);+ }+});++test("postRecall does not retry default body or server errors", async () => {+ const noScopeBodies = [];+ const noScope = await postRecall(async (path, init) => {+ noScopeBodies.push(JSON.parse(init.body));+ return { ok: false, status: 400 };+ }, { query: "hello" });+ assert.equal(noScope.ok, false);+ assert.equal(noScopeBodies.length, 1);++ const serverErrorBodies = [];+ const serverError = await postRecall(async (path, init) => {+ serverErrorBodies.push(JSON.parse(init.body));+ return { ok: false, status: 500 };+ }, { query: "hello", peer_scope: "actor" });+ assert.equal(serverError.ok, false);+ assert.equal(serverErrorBodies.length, 1);+});diff --git a/examples/memory-plugin-shared/sync.mjs b/examples/memory-plugin-shared/sync.mjsindex b4411e152..372ed5d5b 100644--- a/examples/memory-plugin-shared/sync.mjs+++ b/examples/memory-plugin-shared/sync.mjs@@ -14,6 +14,7 @@ const HARNESS_SHARED_FILES = ["debug-log.mjs","setup-wizard.mjs","recall-core.mjs",+ "workspace-peer.mjs","profile-inject.mjs","uri-guard.mjs",];diff --git a/examples/memory-plugin-shared/sync.test.mjs b/examples/memory-plugin-shared/sync.test.mjsindex 0405bec75..c6594a90c 100644--- a/examples/memory-plugin-shared/sync.test.mjs+++ b/examples/memory-plugin-shared/sync.test.mjs@@ -14,6 +14,7 @@ const HARNESS_SHARED_FILES = ["debug-log.mjs","setup-wizard.mjs","recall-core.mjs",+ "workspace-peer.mjs","profile-inject.mjs","uri-guard.mjs",];diff --git a/examples/memory-plugin-shared/workspace-peer.test.mjs b/examples/memory-plugin-shared/workspace-peer.test.mjsnew file mode 100644index 000000000..c90e55420--- /dev/null+++ b/examples/memory-plugin-shared/workspace-peer.test.mjs@@ -0,0 +1,36 @@+import test from "node:test";+import assert from "node:assert/strict";+import { deriveWorkspacePeerId, resolveEffectivePeerId } from "./lib/workspace-peer.mjs";++test("deriveWorkspacePeerId follows Claude project directory naming", () => {+ assert.equal(deriveWorkspacePeerId("/Users/x/Dev/OpenViking"), "-Users-x-Dev-OpenViking");+ assert.equal(deriveWorkspacePeerId("/tmp/a b/"), "-tmp-a--b-");+ assert.equal(deriveWorkspacePeerId("abc.DEF_123@x-y"), "abc-DEF-123-x-y");+ assert.equal(deriveWorkspacePeerId(""), "");+ assert.equal(deriveWorkspacePeerId(null), "");+});++test("resolveEffectivePeerId prefers explicit peer over workspace", () => {+ assert.deepEqual(+ resolveEffectivePeerId({ cfg: { peerId: " configured " }, cwd: "/tmp/project" }),+ { peerId: "configured", source: "explicit" },+ );+});++test("resolveEffectivePeerId derives workspace peer by default", () => {+ assert.deepEqual(+ resolveEffectivePeerId({ cfg: {}, cwd: "/tmp/project" }),+ { peerId: "-tmp-project", source: "workspace" },+ );+});++test("resolveEffectivePeerId can disable workspace peer", () => {+ assert.deepEqual(+ resolveEffectivePeerId({ cfg: { workspacePeer: false }, cwd: "/tmp/project" }),+ { peerId: "", source: "none" },+ );+ assert.deepEqual(+ resolveEffectivePeerId({ cfg: {}, cwd: "" }),+ { peerId: "", source: "none" },+ );+});diff --git a/examples/opencode-plugin/README.md b/examples/opencode-plugin/README.mdindex 96acb2d41..ae40ca426 100644--- a/examples/opencode-plugin/README.md+++ b/examples/opencode-plugin/README.md@@ -135,9 +135,23 @@ Create `~/.config/opencode/openviking-config.json`:API keys are resolved from environment variables or `~/.openviking/ovcli.conf` and sent as `Authorization: Bearer ...` by both hooks and the MCP proxy. `account` and `user` are trusted-mode identityheaders sent as `X-OpenViking-Account` and `X-OpenViking-User`; leave them emptywhen using API-key mode with user/admin API keys.-`peerId` is sent as `X-OpenViking-Actor-Peer` on data-plane memory/resource-requests; captured session messages store it as body `peer_id`. Configure-`peerId` explicitly when peer-scoped memory routing is needed.+By default the plugin derives a peer from the project directory using Claude's+project-directory naming rule: every non-letter-or-digit character becomes `-`,+with no path normalization. For example, `/Users/x/Dev/OpenViking` becomes+`-Users-x-Dev-OpenViking`. Data-plane memory/resource requests send the+effective peer as `X-OpenViking-Actor-Peer`; captured session messages store it+as body `peer_id`. Configure `peerId` or `OPENVIKING_PEER_ID` to override the+workspace-derived peer, or set `workspacePeer=false` /+`OPENVIKING_WORKSPACE_PEER=0` to turn workspace-derived peers off.++Recall defaults to the broad mode: global memory, the current workspace, and+other workspace memories can all be recalled, with other workspaces penalized+and rendered later. Set `recallPeerScope="actor"` or+`OPENVIKING_RECALL_PEER_SCOPE=actor` for the isolation mode, which only sees+global memory plus the current workspace. In deployments where one bot serves+multiple real people, such as zouk, vikingbot, or AstrBot, use the isolation mode+with an explicit actor peer so one person's memories are not recalled into+another person's session.`OPENVIKING_API_KEY`, `OPENVIKING_ACCOUNT`, `OPENVIKING_USER`,and `OPENVIKING_PEER_ID` take precedence over values in this file.diff --git a/examples/opencode-plugin/lib/config.mjs b/examples/opencode-plugin/lib/config.mjsindex 0a5723a9b..d253ae3d2 100644--- a/examples/opencode-plugin/lib/config.mjs+++ b/examples/opencode-plugin/lib/config.mjs@@ -2,6 +2,7 @@ import fs from "fs"import path from "path"import { homedir } from "os"import { resolveOpenVikingCredentials } from "./shared/credentials.mjs"+import { resolveEffectivePeerId } from "./shared/workspace-peer.mjs"const DEFAULT_CONFIG = {endpoint: "http://127.0.0.1:1933",@@ -9,6 +10,8 @@ const DEFAULT_CONFIG = {account: "",user: "",peerId: "",+ workspacePeer: true,+ recallPeerScope: "all",enabled: true,timeoutMs: 30000,runtime: {@@ -147,6 +150,8 @@ function applyBehaviorConfig(config, fileConfig = {}) {"bypassSessionPatterns","debug","debugLogPath",+ "workspacePeer",+ "recallPeerScope",]) {if (fileConfig[key] !== undefined) config[key] = fileConfig[key]}@@ -166,6 +171,10 @@ function applyEnv(config) {if (process.env.OPENVIKING_RECALL_PREFER_ABSTRACT !== undefined) {config.autoRecall.preferAbstract = envBool("OPENVIKING_RECALL_PREFER_ABSTRACT") ?? config.autoRecall.preferAbstract}+ if (process.env.OPENVIKING_RECALL_PEER_SCOPE) config.recallPeerScope = process.env.OPENVIKING_RECALL_PEER_SCOPE+ if (process.env.OPENVIKING_WORKSPACE_PEER !== undefined) {+ config.workspacePeer = envBool("OPENVIKING_WORKSPACE_PEER") ?? config.workspacePeer+ }if (process.env.OPENVIKING_MIN_QUERY_LENGTH) config.autoRecall.minQueryLength = process.env.OPENVIKING_MIN_QUERY_LENGTHif (process.env.OPENVIKING_AUTO_CAPTURE !== undefined) {config.autoCapture = envBool("OPENVIKING_AUTO_CAPTURE") ?? config.autoCapture@@ -220,6 +229,7 @@ function normalizeConfig(config) {config.autoRecall.tokenBudget = Math.max(200, Math.min(50000, Math.round(Number(config.autoRecall.tokenBudget) || 2000)))config.autoRecall.minQueryLength = Math.max(1, Math.min(64, Math.round(Number(config.autoRecall.minQueryLength) || 3)))config.captureMode = config.captureMode === "keyword" ? "keyword" : "semantic"+ config.recallPeerScope = config.recallPeerScope === "actor" ? "actor" : "all"config.captureMaxLength = Math.max(200, Math.min(100000, Math.round(Number(config.captureMaxLength) || 24000)))config.captureToolMaxChars = Math.max(200, Math.min(20000, Math.round(Number(config.captureToolMaxChars) || 2000)))config.commitTokenThreshold = Math.max(1000, Math.round(Number(config.commitTokenThreshold) || 20000))@@ -262,7 +272,9 @@ export function loadConfig(pluginRoot, projectDirectory) {applyEnv(config)config.configPath = configPathconfig.legacyCredentialsUsed = legacyUsed && creds.credentialSource !== "env"- return normalizeConfig(config)+ const normalized = normalizeConfig(config)+ normalized.effectivePeer = resolveEffectivePeerId({ cfg: normalized, cwd: projectDirectory })+ return normalized}export function resolveDataDir(pluginRoot, config) {diff --git a/examples/opencode-plugin/lib/shared/recall-core.mjs b/examples/opencode-plugin/lib/shared/recall-core.mjsindex 445f00b1a..d65f62ba9 100644--- a/examples/opencode-plugin/lib/shared/recall-core.mjs+++ b/examples/opencode-plugin/lib/shared/recall-core.mjs@@ -20,7 +20,7 @@ export function estimateTokens(text) {export function buildRecallEndpointBody(cfg = {}) {const limit = Math.max(Number(cfg.recallLimit || 0), 1);- return {+ const body = {query: "",quotas: {events: limit,@@ -32,6 +32,8 @@ export function buildRecallEndpointBody(cfg = {}) {min_score: Number.isFinite(Number(cfg.scoreThreshold)) ? Number(cfg.scoreThreshold) : 0.35,render: true,};+ if (cfg.recallPeerScope === "actor") body.peer_scope = "actor";+ return body;}function clampScore(v) {@@ -233,10 +235,7 @@ async function buildFallbackInjectionBlock(fetchJSON, items, cfg, actorPeerId =async function recallViaEndpoint(fetchJSON, cfg, query, actorPeerId = "", log = () => {}) {const body = buildRecallEndpointBody(cfg);body.query = query;- const res = await fetchJSON("/api/v1/search/recall", {- method: "POST",- body: JSON.stringify(body),- }, { actorPeerId });+ const res = await postRecall(fetchJSON, body, { actorPeerId, log });if (!res.ok) {log("recall_endpoint_fallback", { status: res.status || 0 });return null;@@ -251,6 +250,27 @@ async function recallViaEndpoint(fetchJSON, cfg, query, actorPeerId = "", log =].join("\n");}+export async function postRecall(fetchJSON, body, opts = {}) {+ const actorPeerId = opts.actorPeerId || "";+ const log = opts.log || (() => {});+ const request = { ...body };+ const res = await fetchJSON("/api/v1/search/recall", {+ method: "POST",+ body: JSON.stringify(request),+ }, { actorPeerId });+ if (!request.peer_scope || (res.status !== 400 && res.status !== 422)) {+ return res;+ }++ const downgraded = { ...request };+ delete downgraded.peer_scope;+ log("recall_peer_scope_downgrade", { status: res.status || 0 });+ return fetchJSON("/api/v1/search/recall", {+ method: "POST",+ body: JSON.stringify(downgraded),+ }, { actorPeerId });+}+export async function buildRecallBlock(fetchJSON, cfg, query, options = {}) {const actorPeerId = options.actorPeerId ?? cfg.peerId ?? "";const log = options.log || (() => {});diff --git a/examples/opencode-plugin/lib/shared/workspace-peer.mjs b/examples/opencode-plugin/lib/shared/workspace-peer.mjsnew file mode 100644index 000000000..6b5cd45ec--- /dev/null+++ b/examples/opencode-plugin/lib/shared/workspace-peer.mjs@@ -0,0 +1,16 @@+// GENERATED FROM examples/memory-plugin-shared/lib. DO NOT EDIT.+export function deriveWorkspacePeerId(cwd) {+ return String(cwd || "").replace(/[^A-Za-z0-9]/g, "-");+}++export function resolveEffectivePeerId({ cfg = {}, cwd = "" } = {}) {+ const explicit = String(cfg.peerId || "").trim();+ if (explicit) return { peerId: explicit, source: "explicit" };++ if (cfg.workspacePeer !== false) {+ const peerId = deriveWorkspacePeerId(cwd);+ if (peerId) return { peerId, source: "workspace" };+ }++ return { peerId: "", source: "none" };+}diff --git a/examples/opencode-plugin/lib/utils.mjs b/examples/opencode-plugin/lib/utils.mjsindex 8ad5202ff..6dd8996c0 100644--- a/examples/opencode-plugin/lib/utils.mjs+++ b/examples/opencode-plugin/lib/utils.mjs@@ -65,7 +65,7 @@ export function normalizeEndpoint(endpoint) {}export function effectivePeerId(config) {- return String(config.peerId || "").trim() || null+ return String(config.effectivePeer?.peerId || config.peerId || "").trim() || null}export async function fetchJSON(config, endpoint, init = {}, options = {}) {diff --git a/examples/opencode-plugin/servers/mcp-proxy.mjs b/examples/opencode-plugin/servers/mcp-proxy.mjsindex 9fae6d0f0..180dee656 100644--- a/examples/opencode-plugin/servers/mcp-proxy.mjs+++ b/examples/opencode-plugin/servers/mcp-proxy.mjs@@ -14,6 +14,7 @@ import { fileURLToPath } from "node:url"import { loadConfig } from "../lib/config.mjs"import { createLogger } from "../lib/shared/debug-log.mjs"import { createOpenVikingMcpProxy } from "../lib/shared/mcp-proxy-core.mjs"+import { resolveEffectivePeerId } from "../lib/shared/workspace-peer.mjs"export { createOpenVikingMcpProxy } from "../lib/shared/mcp-proxy-core.mjs"@@ -37,13 +38,14 @@ function uniq(values) {function readProxyConfig() {const cfg = loadConfig(resolvePath(fileURLToPath(import.meta.url), "..", ".."))+ const effectivePeer = resolveEffectivePeerId({ cfg, cwd: process.cwd() })const mcpUrl = cfg.mcpUrl || `${trimSlash(cfg.endpoint)}/mcp`return {mcpUrl,apiKey: cfg.apiKey || "",account: cfg.account || "",user: cfg.user || "",- peerId: cfg.peerId || "",+ peerId: effectivePeer.peerId,timeoutMs: Math.max(1000, Number(cfg.timeoutMs) || DEFAULT_TIMEOUT_MS),debug: cfg.debug === true,debugLogPath: cfg.debugLogPath,diff --git a/examples/opencode-plugin/tests/config.test.mjs b/examples/opencode-plugin/tests/config.test.mjsindex 373b7683c..3f2bd690d 100644--- a/examples/opencode-plugin/tests/config.test.mjs+++ b/examples/opencode-plugin/tests/config.test.mjs@@ -60,6 +60,7 @@ test("loadConfig prefers env credentials over ovcli and legacy config", async ()assert.equal(cfg.account, "env-account")assert.equal(cfg.user, "env-user")assert.equal(cfg.peerId, "env-peer")+ assert.deepEqual(cfg.effectivePeer, { peerId: "env-peer", source: "explicit" })assert.equal(cfg.legacyCredentialsUsed, false)} finally {restoreOpenVikingEnv(snapshot)@@ -92,9 +93,51 @@ test("loadConfig reads legacy credentials as fallback and marks deprecation", asassert.equal(cfg.account, "legacy-account")assert.equal(cfg.user, "legacy-user")assert.equal(cfg.peerId, "legacy-peer")+ assert.deepEqual(cfg.effectivePeer, { peerId: "legacy-peer", source: "explicit" })assert.equal(cfg.legacyCredentialsUsed, true)} finally {restoreOpenVikingEnv(snapshot)}})})++test("loadConfig derives workspace peer by default", async () => {+ const snapshot = { ...process.env }+ await withTempDir("ov-oc-ws-", async (dir) => {+ try {+ for (const key of Object.keys(process.env)) {+ if (key.startsWith("OPENVIKING_")) delete process.env[key]+ }+ process.env.OPENVIKING_CREDENTIAL_SOURCE = "env"+ process.env.OPENVIKING_URL = "https://env.example.com"+ const project = join(dir, "Project A")++ const cfg = loadConfig(dir, project)+ assert.deepEqual(cfg.effectivePeer, {+ peerId: project.replace(/[^A-Za-z0-9]/g, "-"),+ source: "workspace",+ })+ } finally {+ restoreOpenVikingEnv(snapshot)+ }+ })+})++test("loadConfig can disable workspace peer", async () => {+ const snapshot = { ...process.env }+ await withTempDir("ov-oc-ws-off-", async (dir) => {+ try {+ for (const key of Object.keys(process.env)) {+ if (key.startsWith("OPENVIKING_")) delete process.env[key]+ }+ process.env.OPENVIKING_CREDENTIAL_SOURCE = "env"+ process.env.OPENVIKING_URL = "https://env.example.com"+ process.env.OPENVIKING_WORKSPACE_PEER = "0"++ const cfg = loadConfig(dir, join(dir, "project"))+ assert.deepEqual(cfg.effectivePeer, { peerId: "", source: "none" })+ } finally {+ restoreOpenVikingEnv(snapshot)+ }+ })+})diff --git a/examples/pi-coding-agent-extension/README.md b/examples/pi-coding-agent-extension/README.mdindex 490de3b51..2dc03384a 100644--- a/examples/pi-coding-agent-extension/README.md+++ b/examples/pi-coding-agent-extension/README.md@@ -72,8 +72,12 @@ Credential environment variables:| `OPENVIKING_ACCOUNT` | Trusted-mode account || `OPENVIKING_USER` | Trusted-mode user || `OPENVIKING_PEER_ID` | Actor peer id |+| `OPENVIKING_WORKSPACE_PEER` | Derive an actor peer from the current workspace by default; set `0` to disable |+| `OPENVIKING_RECALL_PEER_SCOPE` | `all` recalls other project memories with a score penalty; `actor` only sees global plus the current project |-API keys are sent as `Authorization: Bearer ...`. `OPENVIKING_PEER_ID` is sent as `X-OpenViking-Actor-Peer` and stored as `peer_id` on captured session messages.+API keys are sent as `Authorization: Bearer ...`. By default the extension derives a peer from the process workspace path using Claude's project-directory naming rule: every non-letter-or-digit character becomes `-`, with no path normalization. For example, `/Users/x/Dev/OpenViking` becomes `-Users-x-Dev-OpenViking`. The effective peer is sent as `X-OpenViking-Actor-Peer` and stored as `peer_id` on captured session messages. `OPENVIKING_PEER_ID` overrides the workspace-derived value.++Recall defaults to the broad mode: global memory, the current workspace, and other workspace memories can all be recalled, with other workspaces penalized and rendered later. Set `OPENVIKING_RECALL_PEER_SCOPE=actor` for the isolation mode, which only sees global memory plus the current workspace. In deployments where one bot serves multiple real people, such as zouk, vikingbot, or AstrBot, use the isolation mode with an explicit actor peer so one person's memories are not recalled into another person's session.### 4. Start Pidiff --git a/examples/pi-coding-agent-extension/config.ts b/examples/pi-coding-agent-extension/config.tsindex 3a962ca4d..d6fd0ab56 100644--- a/examples/pi-coding-agent-extension/config.ts+++ b/examples/pi-coding-agent-extension/config.ts@@ -1,6 +1,7 @@import { readFileSync, existsSync } from "node:fs";import { join, dirname } from "node:path";import { resolveOpenVikingCredentials } from "./shared/credentials.mjs";+import { resolveEffectivePeerId } from "./shared/workspace-peer.mjs";export interface OVConfig {enabled: boolean;@@ -9,6 +10,8 @@ export interface OVConfig {account: string;user: string;peerId: string;+ workspacePeer: boolean;+ recallPeerScope: "actor" | "all";syncTurns: boolean;recallTokenBudget: number;recallMaxContentChars: number;@@ -42,6 +45,8 @@ const DEFAULT_CONFIG: OVConfig = {account: "",user: "",peerId: "",+ workspacePeer: true,+ recallPeerScope: "all",syncTurns: true,recallTokenBudget: 2000,recallMaxContentChars: 500,@@ -104,6 +109,12 @@ export function loadConfig(extensionDir: string): OVConfig {if (process.env.OPENVIKING_ACCOUNT) config.account = creds.account;if (process.env.OPENVIKING_USER) config.user = creds.user;if (process.env.OPENVIKING_PEER_ID) config.peerId = creds.peerId;+ if (process.env.OPENVIKING_WORKSPACE_PEER !== undefined) {+ config.workspacePeer = envBool(process.env.OPENVIKING_WORKSPACE_PEER, config.workspacePeer);+ }+ if (process.env.OPENVIKING_RECALL_PEER_SCOPE) {+ config.recallPeerScope = process.env.OPENVIKING_RECALL_PEER_SCOPE === "actor" ? "actor" : "all";+ }config.recallLimit = clampInt(config.recallLimit, 1, 50, DEFAULT_CONFIG.recallLimit);config.recallMaxContentChars = clampInt(config.recallMaxContentChars, 100, 5000, DEFAULT_CONFIG.recallMaxContentChars);@@ -123,10 +134,19 @@ export function loadConfig(extensionDir: string): OVConfig {config.captureMaxLength = clampInt(config.captureMaxLength, 200, 100000, DEFAULT_CONFIG.captureMaxLength);config.captureToolMaxChars = clampInt(config.captureToolMaxChars, 200, 20000, DEFAULT_CONFIG.captureToolMaxChars);config.captureMode = config.captureMode === "keyword" ? "keyword" : "semantic";+ config.recallPeerScope = config.recallPeerScope === "actor" ? "actor" : "all";if (!Array.isArray(config.bypassPatterns)) config.bypassPatterns = [];+ config.peerId = resolveEffectivePeerId({ cfg: config as any, cwd: process.cwd() }).peerId;return config;}+function envBool(value: string, fallback: boolean): boolean {+ const lower = String(value || "").trim().toLowerCase();+ if (lower === "0" || lower === "false" || lower === "no" || lower === "off") return false;+ if (lower === "1" || lower === "true" || lower === "yes" || lower === "on") return true;+ return fallback;+}+function clampInt(value: unknown, min: number, max: number, fallback: number): number {const next = Math.round(Number(value));if (!Number.isFinite(next)) return fallback;diff --git a/examples/pi-coding-agent-extension/shared/recall-core.mjs b/examples/pi-coding-agent-extension/shared/recall-core.mjsindex 445f00b1a..d65f62ba9 100644--- a/examples/pi-coding-agent-extension/shared/recall-core.mjs+++ b/examples/pi-coding-agent-extension/shared/recall-core.mjs@@ -20,7 +20,7 @@ export function estimateTokens(text) {export function buildRecallEndpointBody(cfg = {}) {const limit = Math.max(Number(cfg.recallLimit || 0), 1);- return {+ const body = {query: "",quotas: {events: limit,@@ -32,6 +32,8 @@ export function buildRecallEndpointBody(cfg = {}) {min_score: Number.isFinite(Number(cfg.scoreThreshold)) ? Number(cfg.scoreThreshold) : 0.35,render: true,};+ if (cfg.recallPeerScope === "actor") body.peer_scope = "actor";+ return body;}function clampScore(v) {@@ -233,10 +235,7 @@ async function buildFallbackInjectionBlock(fetchJSON, items, cfg, actorPeerId =async function recallViaEndpoint(fetchJSON, cfg, query, actorPeerId = "", log = () => {}) {const body = buildRecallEndpointBody(cfg);body.query = query;- const res = await fetchJSON("/api/v1/search/recall", {- method: "POST",- body: JSON.stringify(body),- }, { actorPeerId });+ const res = await postRecall(fetchJSON, body, { actorPeerId, log });if (!res.ok) {log("recall_endpoint_fallback", { status: res.status || 0 });return null;@@ -251,6 +250,27 @@ async function recallViaEndpoint(fetchJSON, cfg, query, actorPeerId = "", log =].join("\n");}+export async function postRecall(fetchJSON, body, opts = {}) {+ const actorPeerId = opts.actorPeerId || "";+ const log = opts.log || (() => {});+ const request = { ...body };+ const res = await fetchJSON("/api/v1/search/recall", {+ method: "POST",+ body: JSON.stringify(request),+ }, { actorPeerId });+ if (!request.peer_scope || (res.status !== 400 && res.status !== 422)) {+ return res;+ }++ const downgraded = { ...request };+ delete downgraded.peer_scope;+ log("recall_peer_scope_downgrade", { status: res.status || 0 });+ return fetchJSON("/api/v1/search/recall", {+ method: "POST",+ body: JSON.stringify(downgraded),+ }, { actorPeerId });+}+export async function buildRecallBlock(fetchJSON, cfg, query, options = {}) {const actorPeerId = options.actorPeerId ?? cfg.peerId ?? "";const log = options.log || (() => {});diff --git a/examples/pi-coding-agent-extension/shared/workspace-peer.d.mts b/examples/pi-coding-agent-extension/shared/workspace-peer.d.mtsnew file mode 100644index 000000000..9a920fcc5--- /dev/null+++ b/examples/pi-coding-agent-extension/shared/workspace-peer.d.mts@@ -0,0 +1,5 @@+export function deriveWorkspacePeerId(cwd: unknown): string;+export function resolveEffectivePeerId(input?: {+ cfg?: { peerId?: string; workspacePeer?: boolean };+ cwd?: string;+}): { peerId: string; source: "explicit" | "workspace" | "none" };diff --git a/examples/pi-coding-agent-extension/shared/workspace-peer.mjs b/examples/pi-coding-agent-extension/shared/workspace-peer.mjsnew file mode 100644index 000000000..6b5cd45ec--- /dev/null+++ b/examples/pi-coding-agent-extension/shared/workspace-peer.mjs@@ -0,0 +1,16 @@+// GENERATED FROM examples/memory-plugin-shared/lib. DO NOT EDIT.+export function deriveWorkspacePeerId(cwd) {+ return String(cwd || "").replace(/[^A-Za-z0-9]/g, "-");+}++export function resolveEffectivePeerId({ cfg = {}, cwd = "" } = {}) {+ const explicit = String(cfg.peerId || "").trim();+ if (explicit) return { peerId: explicit, source: "explicit" };++ if (cfg.workspacePeer !== false) {+ const peerId = deriveWorkspacePeerId(cwd);+ if (peerId) return { peerId, source: "workspace" };+ }++ return { peerId: "", source: "none" };+}diff --git a/examples/pi-coding-agent-extension/tests/config.test.mjs b/examples/pi-coding-agent-extension/tests/config.test.mjsindex e63c4d1f1..9c5bc1165 100644--- a/examples/pi-coding-agent-extension/tests/config.test.mjs+++ b/examples/pi-coding-agent-extension/tests/config.test.mjs@@ -5,7 +5,7 @@ import { join } from "node:path";import { tmpdir } from "node:os";import { loadConfig } from "../config.ts";-async function withConfigFile(body, fn) {+async function withConfigFile(body, fn, env = {}) {const dir = await mkdtemp(join(tmpdir(), "ov-pi-config-"));const oldEnv = {OPENVIKING_URL: process.env.OPENVIKING_URL,@@ -13,6 +13,8 @@ async function withConfigFile(body, fn) {OPENVIKING_ACCOUNT: process.env.OPENVIKING_ACCOUNT,OPENVIKING_USER: process.env.OPENVIKING_USER,OPENVIKING_PEER_ID: process.env.OPENVIKING_PEER_ID,+ OPENVIKING_WORKSPACE_PEER: process.env.OPENVIKING_WORKSPACE_PEER,+ OPENVIKING_RECALL_PEER_SCOPE: process.env.OPENVIKING_RECALL_PEER_SCOPE,OPENVIKING_CREDENTIAL_SOURCE: process.env.OPENVIKING_CREDENTIAL_SOURCE,OPENVIKING_CLI_CONFIG_FILE: process.env.OPENVIKING_CLI_CONFIG_FILE,OPENVIKING_CONFIG_FILE: process.env.OPENVIKING_CONFIG_FILE,@@ -23,8 +25,14 @@ async function withConfigFile(body, fn) {delete process.env.OPENVIKING_ACCOUNT;delete process.env.OPENVIKING_USER;delete process.env.OPENVIKING_PEER_ID;+ delete process.env.OPENVIKING_WORKSPACE_PEER;+ delete process.env.OPENVIKING_RECALL_PEER_SCOPE;delete process.env.OPENVIKING_CLI_CONFIG_FILE;delete process.env.OPENVIKING_CONFIG_FILE;+ for (const [key, value] of Object.entries(env)) {+ if (value === undefined) delete process.env[key];+ else process.env[key] = value;+ }try {await writeFile(join(dir, "config.json"), JSON.stringify(body), "utf8");@@ -98,3 +106,23 @@ test("loadConfig clamps invalid takeover values", async () => {assert.equal(cfg.takeoverOverviewPollMax, 1);});});++test("loadConfig derives workspace peer by default", async () => {+ const oldCwd = process.cwd();+ await withConfigFile({}, (cfg) => {+ assert.equal(cfg.peerId, oldCwd.replace(/[^A-Za-z0-9]/g, "-"));+ assert.equal(cfg.workspacePeer, true);+ assert.equal(cfg.recallPeerScope, "all");+ });+});++test("loadConfig keeps explicit peer and actor recall scope", async () => {+ await withConfigFile({+ recallPeerScope: "actor",+ workspacePeer: false,+ }, (cfg) => {+ assert.equal(cfg.peerId, "explicit-peer");+ assert.equal(cfg.workspacePeer, false);+ assert.equal(cfg.recallPeerScope, "actor");+ }, { OPENVIKING_PEER_ID: "explicit-peer" });+});diff --git a/openviking/retrieve/type_quota_recall.py b/openviking/retrieve/type_quota_recall.pyindex dd5c07c77..a657f27c2 100644--- a/openviking/retrieve/type_quota_recall.py+++ b/openviking/retrieve/type_quota_recall.py@@ -10,7 +10,7 @@ block that degrades from full content to summary to URI-only entries.from __future__ import annotationsimport re-from dataclasses import dataclass, field+from dataclasses import dataclass, field, replacefrom typing import Any, Mappingfrom openviking.core.namespace import canonical_user_root@@ -18,10 +18,23 @@ from openviking.server.identity import RequestContextTYPE_ORDER = ("events", "entities", "preferences", "experiences")DEFAULT_QUOTAS = {"events": 10, "entities": 10, "preferences": 3, "experiences": 0}+DEFAULT_OTHER_PEER_PENALTIES = {+ "events": 0.1,+ "entities": 0.1,+ "preferences": 0.02,+ "experiences": 0.02,+}DEFAULT_MAX_CHARS = 6500DEFAULT_MIN_SCORE = 0.1EVENTS_BUDGET_RATIO = 0.75PREFERENCE_FULL_LIMIT = 3+OTHER_PEER_OVERFETCH = 4+ORIGIN_ORDER = ("actor_peer", "self", "other_peer")+ORIGIN_LABEL = {+ "actor_peer": "current-project",+ "self": "global",+ "other_peer": "other-projects",+}@dataclass@@ -30,6 +43,7 @@ class RecallEntry:score: floattype: strmode: str+ origin: str = ""content: str = ""summary: str = ""rank: int = 0@@ -49,6 +63,8 @@ class RecallEntry:data["summary"] = self.summaryif self.abstract:data["abstract"] = self.abstract+ if self.origin:+ data["origin"] = self.originreturn data@@ -78,6 +94,29 @@ def normalize_quotas(quotas: Mapping[str, Any] | None) -> dict[str, int]:return merged+def _clamp_penalty(value: Any, fallback: float) -> float:+ try:+ penalty = float(value)+ except (TypeError, ValueError):+ penalty = fallback+ return min(1.0, max(0.0, penalty))+++def normalize_penalties(value: Any = None) -> dict[str, float]:+ """Normalize other-peer recall penalties by memory type."""+ if value is None:+ return dict(DEFAULT_OTHER_PEER_PENALTIES)+ if isinstance(value, Mapping):+ merged = dict(DEFAULT_OTHER_PEER_PENALTIES)+ for key, penalty in value.items():+ if key not in DEFAULT_OTHER_PEER_PENALTIES:+ continue+ merged[key] = _clamp_penalty(penalty, merged[key])+ return merged+ penalty = _clamp_penalty(value, 0.0)+ return dict.fromkeys(TYPE_ORDER, penalty)++def memory_target_roots(ctx: RequestContext) -> list[str]:user_root = canonical_user_root(ctx)targets = [f"{user_root}/memories"]@@ -90,6 +129,23 @@ def _type_target(root: str, memory_type: str) -> str:return f"{root.rstrip('/')}/{memory_type}"+def _is_under(uri: str, root: str) -> bool:+ uri = uri.rstrip("/")+ root = root.rstrip("/")+ return uri == root or uri.startswith(f"{root}/")+++def _origin_for_uri(uri: str, actor_peer_id: str | None, user_root: str) -> str:+ peers_root = f"{user_root.rstrip('/')}/peers"+ if _is_under(uri, peers_root):+ suffix = uri[len(peers_root) :].strip("/")+ peer_id = suffix.split("/", 1)[0] if suffix else ""+ if actor_peer_id and peer_id == actor_peer_id:+ return "actor_peer"+ return "other_peer"+ return "self"++def _get_attr(obj: Any, name: str, default: Any = None) -> Any:if isinstance(obj, Mapping):return obj.get(name, default)@@ -135,6 +191,26 @@ def _limit(items: list[Any], limit: int) -> list[Any]:return sorted(items, key=_score, reverse=True)[: max(0, limit)]+def _limit_with_peer_penalties(+ items: list[Any],+ *,+ memory_type: str,+ limit: int,+ penalties: Mapping[str, float],+ actor_peer_id: str | None,+ user_root: str,+) -> list[tuple[Any, str]]:+ origin_rank = {origin: index for index, origin in enumerate(ORIGIN_ORDER)}++ def sort_key(item: Any) -> tuple[float, int]:+ origin = _origin_for_uri(_uri(item), actor_peer_id, user_root)+ penalty = penalties.get(memory_type, 0.0) if origin == "other_peer" else 0.0+ return (_score(item) - penalty, -origin_rank.get(origin, len(origin_rank)))++ limited = sorted(items, key=sort_key, reverse=True)[: max(0, limit)]+ return [(item, _origin_for_uri(_uri(item), actor_peer_id, user_root)) for item in limited]++def _filename_from_uri(uri: str) -> str:return uri.rstrip("/").rsplit("/", 1)[-1] if uri else ""@@ -201,6 +277,14 @@ def _group_fragment(memory_type: str, fragments: list[str]) -> str:)+def _section_fragment(origin: str, groups: list[str]) -> str:+ return (+ f'<memory_section source="{ORIGIN_LABEL.get(origin, origin)}">\n'+ + "\n".join(groups)+ + "\n</memory_section>"+ )++async def search_type_quota_recall(*,service: Any,@@ -210,11 +294,17 @@ async def search_type_quota_recall(max_chars: int = DEFAULT_MAX_CHARS,min_score: float = DEFAULT_MIN_SCORE,render: bool = True,+ peer_scope: str = "all",+ other_peer_penalty: Any = None,) -> RecallResult:normalized_quotas = normalize_quotas(quotas)+ normalized_penalties = normalize_penalties(other_peer_penalty)+ peer_scope = "actor" if peer_scope == "actor" else "all"+ user_root = canonical_user_root(ctx)roots = memory_target_roots(ctx)+ open_ctx = replace(ctx, actor_peer_id=None, legacy_agent_id=None)raw_by_type: dict[str, list[Any]] = {}- selected: list[tuple[str, Any, int]] = []+ selected: list[tuple[str, Any, int, str, RequestContext]] = []for memory_type in TYPE_ORDER:quota = normalized_quotas.get(memory_type, 0)@@ -232,12 +322,52 @@ async def search_type_quota_recall(level=None,)found.extend(_extract_memories(result))- found = _limit(_dedupe(found), quota)- raw_by_type[memory_type] = found- selected.extend((memory_type, item, rank) for rank, item in enumerate(found, start=1))+ if peer_scope == "all":+ result = await service.search.find(+ query=query,+ ctx=open_ctx,+ target_uri=f"{user_root}/peers",+ limit=max(quota * OTHER_PEER_OVERFETCH, quota),+ score_threshold=min_score,+ level=None,+ )+ found.extend(+ item+ for item in _extract_memories(result)+ if f"/memories/{memory_type}/" in _uri(item)+ and _origin_for_uri(_uri(item), ctx.actor_peer_id, user_root) == "other_peer"+ )+ found = _dedupe(found)+ raw_by_type[memory_type] = found+ ranked = _limit_with_peer_penalties(+ found,+ memory_type=memory_type,+ limit=quota,+ penalties=normalized_penalties,+ actor_peer_id=ctx.actor_peer_id,+ user_root=user_root,+ )+ else:+ found = _limit(_dedupe(found), quota)+ raw_by_type[memory_type] = found+ ranked = [+ (item, _origin_for_uri(_uri(item), ctx.actor_peer_id, user_root)) for item in found+ ]++ selected.extend(+ (+ memory_type,+ item,+ rank,+ origin,+ open_ctx if origin == "other_peer" else ctx,+ )+ for rank, (item, origin) in enumerate(ranked, start=1)+ )entries: list[RecallEntry] = []fragments_by_type: dict[str, list[str]] = {key: [] for key in TYPE_ORDER}+ fragments_by_origin_type: dict[tuple[str, str], list[str]] = {}budgets = type_char_budgets(max_chars)used_by_type = dict.fromkeys(TYPE_ORDER, 0)total_chars = 0@@ -245,7 +375,7 @@ async def search_type_quota_recall(dropped = 0seen_content: set[int] = set()- for index, (memory_type, item, rank) in enumerate(selected, start=1):+ for index, (memory_type, item, rank, origin, read_ctx) in enumerate(selected, start=1):uri = _uri(item)if not uri or uri.rstrip("/").endswith("/profile.md"):continue@@ -253,7 +383,7 @@ async def search_type_quota_recall(abstract = _abstract(item)content = ""try:- content = await service.fs.read(uri, ctx=ctx)+ content = await service.fs.read(uri, ctx=read_ctx)except Exception:content = ""@@ -315,6 +445,7 @@ async def search_type_quota_recall(score=score,type=memory_type,mode=mode,+ origin=origin,content=entry_content,summary=summary,rank=rank,@@ -322,15 +453,32 @@ async def search_type_quota_recall())fragments_by_type.setdefault(memory_type, []).append(fragment)+ fragments_by_origin_type.setdefault((origin, memory_type), []).append(fragment)rendered = ""if render:- rendered_groups = [- _group_fragment(memory_type, fragments_by_type[memory_type])- for memory_type in TYPE_ORDER- if fragments_by_type.get(memory_type)- ]- rendered = "\n".join(rendered_groups)+ if peer_scope == "actor":+ rendered_groups = [+ _group_fragment(memory_type, fragments_by_type[memory_type])+ for memory_type in TYPE_ORDER+ if fragments_by_type.get(memory_type)+ ]+ rendered = "\n".join(rendered_groups)+ else:+ rendered_sections: list[str] = []+ for origin in ORIGIN_ORDER:+ groups = [+ _group_fragment(memory_type, fragments_by_origin_type[(origin, memory_type)])+ for memory_type in TYPE_ORDER+ if fragments_by_origin_type.get((origin, memory_type))+ ]+ if groups:+ rendered_sections.append(_section_fragment(origin, groups))+ rendered = "\n".join(rendered_sections)++ origins = dict.fromkeys(ORIGIN_ORDER, 0)+ for entry in entries:+ origins[entry.origin] = origins.get(entry.origin, 0) + 1return RecallResult(entries=entries,@@ -343,5 +491,8 @@ async def search_type_quota_recall("dropped": dropped,"max_chars": max_chars,"min_score": min_score,+ "peer_scope": peer_scope,+ "other_peer_penalties": normalized_penalties,+ "origins": origins,},)diff --git a/openviking/server/mcp_endpoint.py b/openviking/server/mcp_endpoint.pyindex 1798d0b5b..a5c93c83a 100644--- a/openviking/server/mcp_endpoint.py+++ b/openviking/server/mcp_endpoint.py@@ -305,9 +305,12 @@ async def recall(quotas: Optional[dict[str, int]] = None,max_chars: int = DEFAULT_MAX_CHARS,min_score: float = DEFAULT_MIN_SCORE,+ peer_scope: str = "all",+ other_peer_penalty: Optional[Any] = None,) -> str:"""Type-quota memory recall. Searches events, entities, preferences, and experiences separately, then returns a bounded memory_group block."""service = get_service()+ effective_peer_scope = "actor" if peer_scope == "actor" else "all"result = await search_type_quota_recall(service=service,ctx=_get_ctx(),@@ -315,6 +318,8 @@ async def recall(quotas=quotas or DEFAULT_QUOTAS,max_chars=max(1, int(max_chars)),min_score=min_score,+ peer_scope=effective_peer_scope,+ other_peer_penalty=other_peer_penalty,render=True,)if result.rendered.strip():diff --git a/openviking/server/routers/search.py b/openviking/server/routers/search.pyindex 9b49dbfbc..17db948fa 100644--- a/openviking/server/routers/search.py+++ b/openviking/server/routers/search.py@@ -13,6 +13,7 @@ from openviking.pyagfs.exceptions import AGFSClientError, AGFSNotFoundErrorfrom openviking.retrieve.type_quota_recall import (DEFAULT_MAX_CHARS,DEFAULT_MIN_SCORE,+ DEFAULT_OTHER_PEER_PENALTIES,DEFAULT_QUOTAS,search_type_quota_recall,)@@ -150,6 +151,8 @@ class RecallRequest(BaseModel):quotas: Dict[str, int] = DEFAULT_QUOTAS.copy()max_chars: int = DEFAULT_MAX_CHARSmin_score: float = DEFAULT_MIN_SCORE+ peer_scope: Literal["actor", "all"] = "all"+ other_peer_penalty: Optional[Union[float, Dict[str, float]]] = Nonerender: bool = Truetelemetry: TelemetryRequest = False@@ -284,6 +287,10 @@ async def recall(max_chars=max(1, int(request.max_chars)),min_score=request.min_score,render=request.render,+ peer_scope=request.peer_scope,+ other_peer_penalty=request.other_peer_penalty+ if request.other_peer_penalty is not None+ else DEFAULT_OTHER_PEER_PENALTIES,),)return Response(diff --git a/tests/server/test_recall_endpoint.py b/tests/server/test_recall_endpoint.pyindex 7227a37d7..76d59875a 100644--- a/tests/server/test_recall_endpoint.py+++ b/tests/server/test_recall_endpoint.py@@ -84,7 +84,12 @@ async def test_recall_endpoint_searches_by_type_quota_and_renders(assert '<memory_group type="events"' in result["rendered"]assert "<summary>Ship stdio MCP proxy.</summary>" in result["rendered"]assert "viking://user/test_user/memories/entities/openviking.md" in result["rendered"]- assert [call["target_uri"].rsplit("/", 1)[-1] for call in calls] == ["events", "entities"]+ assert [call["target_uri"].rsplit("/", 1)[-1] for call in calls] == [+ "events",+ "peers",+ "entities",+ "peers",+ ]async def test_recall_endpoint_respects_max_chars_budget(diff --git a/tests/server/test_recall_peer_scope.py b/tests/server/test_recall_peer_scope.pynew file mode 100644index 000000000..bd23df8d0--- /dev/null+++ b/tests/server/test_recall_peer_scope.py@@ -0,0 +1,314 @@+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.+# SPDX-License-Identifier: AGPL-3.0++from types import SimpleNamespace++import httpx++from openviking.retrieve.type_quota_recall import normalize_penalties+from openviking.server.dependencies import set_service+from openviking.server.identity import RequestContext, Role+from openviking.server.mcp_endpoint import _mcp_ctx+from openviking_cli.retrieve import ContextType, MatchedContext+from openviking_cli.session.user_id import UserIdentifier+++class _FakeFindResult:+ def __init__(self, memories):+ self.memories = memories+++def _memory(uri: str, score: float = 0.9, abstract: str = ""):+ return MatchedContext(+ uri=uri,+ context_type=ContextType.MEMORY,+ level=2,+ score=score,+ abstract=abstract,+ category=uri.split("/memories/", 1)[-1].split("/", 1)[0],+ )+++def _self_memory_target(target_uri: str, memory_type: str) -> bool:+ return target_uri.endswith(f"/memories/{memory_type}") and "/peers/" not in target_uri+++def test_normalize_penalties_defaults_scalar_dict_and_clamp():+ assert normalize_penalties() == {+ "events": 0.1,+ "entities": 0.1,+ "preferences": 0.02,+ "experiences": 0.02,+ }+ assert normalize_penalties(0.2) == {+ "events": 0.2,+ "entities": 0.2,+ "preferences": 0.2,+ "experiences": 0.2,+ }+ assert normalize_penalties({"events": 2, "preferences": -1, "unknown": 0.5}) == {+ "events": 1.0,+ "entities": 0.1,+ "preferences": 0.0,+ "experiences": 0.02,+ }+++async def test_recall_default_all_searches_other_peers_and_reads_with_open_ctx(+ client: httpx.AsyncClient,+ service,+ monkeypatch,+):+ calls = []+ read_calls = []++ async def fake_find(**kwargs):+ calls.append(kwargs)+ target_uri = kwargs["target_uri"]+ if _self_memory_target(target_uri, "events"):+ return _FakeFindResult([_memory(f"{target_uri}/global.md", 0.8, "global")])+ if target_uri.endswith("/peers/current/memories/events"):+ return _FakeFindResult(+ [+ _memory(+ f"{target_uri}/current.md",+ 0.91,+ "current",+ )+ ]+ )+ if target_uri.endswith("/peers"):+ return _FakeFindResult(+ [+ _memory(+ f"{target_uri}/other/memories/events/other.md",+ 0.89,+ "other",+ ),+ _memory(+ f"{target_uri}/other/resources/doc.md",+ 0.99,+ "resource ignored",+ ),+ _memory(+ f"{target_uri}/current/memories/events/current-dup.md",+ 0.99,+ "actor ignored from open peers",+ ),+ ]+ )+ return _FakeFindResult([])++ async def fake_read(uri, **kwargs):+ read_calls.append((uri, kwargs.get("ctx")))+ return f"content for {uri}"++ monkeypatch.setattr(service.search, "find", fake_find)+ monkeypatch.setattr(service.fs, "read", fake_read)++ resp = await client.post(+ "/api/v1/search/recall",+ headers={"X-OpenViking-Actor-Peer": "current"},+ json={+ "query": "peer memory",+ "quotas": {"events": 3, "entities": 0, "preferences": 0, "experiences": 0},+ "max_chars": 5000,+ },+ )++ assert resp.status_code == 200+ result = resp.json()["result"]+ assert [entry["origin"] for entry in result["entries"]] == [+ "actor_peer",+ "self",+ "other_peer",+ ]+ assert result["stats"]["peer_scope"] == "all"+ assert result["stats"]["origins"] == {"actor_peer": 1, "self": 1, "other_peer": 1}+ assert '<memory_section source="current-project">' in result["rendered"]+ assert '<memory_section source="global">' in result["rendered"]+ assert '<memory_section source="other-projects">' in result["rendered"]++ peer_root_call = next(call for call in calls if call["target_uri"].endswith("/peers"))+ assert peer_root_call["ctx"].actor_peer_id is None+ other_read_ctx = next(ctx for uri, ctx in read_calls if uri.endswith("/other.md"))+ assert other_read_ctx.actor_peer_id is None+++async def test_recall_actor_scope_keeps_legacy_rendering(+ client: httpx.AsyncClient,+ service,+ monkeypatch,+):+ calls = []++ async def fake_find(**kwargs):+ calls.append(kwargs)+ if kwargs["target_uri"].endswith("/events"):+ return _FakeFindResult(+ [_memory("viking://user/test_user/peers/current/memories/events/current.md")]+ )+ return _FakeFindResult([])++ async def fake_read(uri, **kwargs):+ del uri, kwargs+ return "Summary: actor only.\n2026-07-09 ChatLog: details"++ monkeypatch.setattr(service.search, "find", fake_find)+ monkeypatch.setattr(service.fs, "read", fake_read)++ resp = await client.post(+ "/api/v1/search/recall",+ headers={"X-OpenViking-Actor-Peer": "current"},+ json={+ "query": "peer memory",+ "peer_scope": "actor",+ "quotas": {"events": 1, "entities": 0, "preferences": 0, "experiences": 0},+ "max_chars": 300,+ },+ )++ assert resp.status_code == 200+ result = resp.json()["result"]+ assert '<memory_group type="events"' in result["rendered"]+ assert "<memory_section" not in result["rendered"]+ assert all(not call["target_uri"].endswith("/peers") for call in calls)+++async def test_recall_other_peer_penalty_is_type_aware(+ client: httpx.AsyncClient,+ service,+ monkeypatch,+):+ async def fake_find(**kwargs):+ target_uri = kwargs["target_uri"]+ if target_uri.endswith("/peers/current/memories/events"):+ return _FakeFindResult([_memory(f"{target_uri}/actor-event.md", 0.86)])+ if target_uri.endswith("/peers/current/memories/experiences"):+ return _FakeFindResult(+ [+ _memory(+ f"{target_uri}/actor-exp.md",+ 0.86,+ )+ ]+ )+ if target_uri.endswith("/peers"):+ return _FakeFindResult(+ [+ _memory(+ f"{target_uri}/other/memories/events/other-event.md",+ 0.90,+ ),+ _memory(+ f"{target_uri}/other/memories/experiences/other-exp.md",+ 0.90,+ ),+ ]+ )+ return _FakeFindResult([])++ async def fake_read(uri, **kwargs):+ del kwargs+ return f"content {uri}"++ monkeypatch.setattr(service.search, "find", fake_find)+ monkeypatch.setattr(service.fs, "read", fake_read)++ resp = await client.post(+ "/api/v1/search/recall",+ headers={"X-OpenViking-Actor-Peer": "current"},+ json={+ "query": "ranking",+ "quotas": {"events": 1, "entities": 0, "preferences": 0, "experiences": 1},+ "max_chars": 5000,+ },+ )++ assert resp.status_code == 200+ entries = resp.json()["result"]["entries"]+ assert [entry["uri"].rsplit("/", 1)[-1] for entry in entries] == [+ "actor-event.md",+ "other-exp.md",+ ]+ assert [entry["origin"] for entry in entries] == ["actor_peer", "other_peer"]+++async def test_recall_accepts_scalar_penalty_override(+ client: httpx.AsyncClient,+ service,+ monkeypatch,+):+ async def fake_find(**kwargs):+ target_uri = kwargs["target_uri"]+ if target_uri.endswith("/peers/current/memories/events"):+ return _FakeFindResult([_memory(f"{target_uri}/actor.md", 0.86)])+ if target_uri.endswith("/peers"):+ return _FakeFindResult([_memory(f"{target_uri}/other/memories/events/other.md", 0.90)])+ return _FakeFindResult([])++ async def fake_read(uri, **kwargs):+ del kwargs+ return f"content {uri}"++ monkeypatch.setattr(service.search, "find", fake_find)+ monkeypatch.setattr(service.fs, "read", fake_read)++ resp = await client.post(+ "/api/v1/search/recall",+ headers={"X-OpenViking-Actor-Peer": "current"},+ json={+ "query": "ranking",+ "quotas": {"events": 1, "entities": 0, "preferences": 0, "experiences": 0},+ "other_peer_penalty": 0.0,+ },+ )++ assert resp.status_code == 200+ result = resp.json()["result"]+ assert result["entries"][0]["uri"].endswith("/other.md")+ assert result["stats"]["other_peer_penalties"]["events"] == 0.0+++async def test_recall_rejects_unknown_peer_scope(client: httpx.AsyncClient):+ resp = await client.post(+ "/api/v1/search/recall",+ json={"query": "hello", "peer_scope": "bogus"},+ )++ assert resp.status_code == 400+++async def test_mcp_recall_tool_passes_peer_scope_and_penalty(service, monkeypatch):+ captured = {}+ set_service(service)+ ctx = RequestContext(+ user=UserIdentifier.the_default_user("test_user"),+ role=Role.ROOT,+ )+ token = _mcp_ctx.set(ctx)++ async def fake_search_type_quota_recall(**kwargs):+ captured.update(kwargs)+ return SimpleNamespace(rendered='<memory_section source="other-projects"></memory_section>')++ monkeypatch.setattr(+ "openviking.server.mcp_endpoint.search_type_quota_recall",+ fake_search_type_quota_recall,+ )++ from openviking.server.mcp_endpoint import recall++ try:+ result = await recall(+ query="hello",+ quotas={"events": 1},+ peer_scope="actor",+ other_peer_penalty={"events": 0.5},+ )+ finally:+ _mcp_ctx.reset(token)++ assert "other-projects" in result+ assert captured["peer_scope"] == "actor"+ assert captured["other_peer_penalty"] == {"events": 0.5}