Skip to content

Self-evolving Context Database for AI Agents. Unify Agent Memory, Knowledge RAG and Skills.

fix(plugins): read profile and memory listings from peer scope (#5246)

Alec Chen196e58201a65
diff --git a/docs/en/agent-integrations/16-capability-reference.md b/docs/en/agent-integrations/16-capability-reference.md
index 1d4cbf2d5..a10388fc7 100644
--- a/docs/en/agent-integrations/16-capability-reference.md
+++ b/docs/en/agent-integrations/16-capability-reference.md
@@ -200,7 +200,7 @@ The table shows the default path. Turning on [recall digests](#recall-digest) ch
### Session-start context
-Integrations that use the shared plugin code inject one `<openviking-context>` block at session start. It holds the user profile (`viking://user/<space>/memories/profile.md`), an index of the `preferences/` and `entities/` memories, and an `<available-skills>` catalog:
+Integrations that use the shared plugin code inject one `<openviking-context>` block at session start. It holds the user profile (`viking://user/<space>/memories/profile.md`), an index of the `preferences/` and `entities/` memories, and an `<available-skills>` catalog. When the session has an actor peer, the same files under `viking://user/<space>/peers/<peer>/memories/` are added: the profile, preferences, and entities have no message range, so extraction writes the user's own facts to the user root even in a peer session. The user root comes first; the peer profile is a second `<user-profile>` element without the lines it shares with the user profile, and both roots share one budget:
```text
<openviking-context source="startup">
@@ -233,7 +233,7 @@ When each integration injects it:
Budgets and limits:
-- `profileTokenBudget` (default 10,000 tokens) covers the profile and the memory index. The profile gets half. An oversized profile keeps its first 8 lines and its end; an oversized listing ends with `... +N more`. Token estimates count CJK characters as 1.5 tokens and other text as four characters per token.
+- `profileTokenBudget` (default 10,000 tokens) covers the profiles and the memory index. The profiles get half: the user profile first, the peer profile what is left, or a one-line pointer to its URI when less than 200 tokens remain. The two roots split the index budget. An oversized profile keeps its first 8 lines and its end; an oversized listing ends with `... +N more`. Token estimates count CJK characters as 1.5 tokens and other text as four characters per token.
- `skillCatalogTokenBudget` (default 1,200 tokens, `OPENVIKING_SKILL_CATALOG_TOKEN_BUDGET`) is a separate budget for the skill catalog. `skillCatalog` (`OPENVIKING_SKILL_CATALOG`) or a budget of 0 turns the catalog off.
- The catalog comes from one `GET /api/v1/skills` request. The user's own skills come first, and an account skill with the same name as a user skill is left out. Each description is cut to about 40 tokens. If descriptions do not fit, the catalog lists names only; if names do not fit, it ends with `... +N more`, or shrinks to a one-line count. Servers without that endpoint get no catalog.
- `sessionStartMaxBytes` caps the whole block in UTF-8 bytes: 9,500 for Claude Code and Codex, whose hosts move hook output above about 10,000 characters into a file and show only a preview; 20,000 for ZCode, which drops output above 32 KB; no cap elsewhere. Above the cap, the memory index is dropped first, then the skill catalog.
diff --git a/docs/zh/agent-integrations/16-capability-reference.md b/docs/zh/agent-integrations/16-capability-reference.md
index 22e310d4d..2c80d99f6 100644
--- a/docs/zh/agent-integrations/16-capability-reference.md
+++ b/docs/zh/agent-integrations/16-capability-reference.md
@@ -199,7 +199,7 @@ skill 走单独的路径。创建、安装或替换 skill 用 MCP `add_skill`
### 会话开场上下文
-使用共享插件代码的集成会在会话开始时注入一个 `<openviking-context>` 块,包含用户 profile(`viking://user/<space>/memories/profile.md`)、`preferences/` 和 `entities/` 记忆的索引,以及 `<available-skills>` skill 清单:
+使用共享插件代码的集成会在会话开始时注入一个 `<openviking-context>` 块,包含用户 profile(`viking://user/<space>/memories/profile.md`)、`preferences/` 和 `entities/` 记忆的索引,以及 `<available-skills>` skill 清单。会话带有 actor peer 时,还会加入 `viking://user/<space>/peers/<peer>/memories/` 下的同名文件:profile、preferences 和 entities 没有消息范围,所以即使在 peer 会话中,抽取也会把用户本人的事实写到用户根目录。用户根目录在前;peer profile 是第二个 `<user-profile>` 元素,并去掉与用户 profile 相同的行;两个根目录共用同一份预算:
```text
<openviking-context source="startup">
@@ -232,7 +232,7 @@ skill 走单独的路径。创建、安装或替换 skill 用 MCP `add_skill`
预算与限制:
-- `profileTokenBudget`(默认 10,000 token)覆盖 profile 和记忆索引,profile 占一半。profile 超长时保留前 8 行和结尾;清单超长时以 `... +N more` 结尾。token 估算中,CJK 字符按 1.5 token 计,其他文本按每 4 个字符 1 token 计。
+- `profileTokenBudget`(默认 10,000 token)覆盖 profile 和记忆索引,profile 占一半:先放用户 profile,peer profile 使用剩余部分,剩余不足 200 token 时只放一行指向其 URI 的提示。两个根目录分摊索引预算。profile 超长时保留前 8 行和结尾;清单超长时以 `... +N more` 结尾。token 估算中,CJK 字符按 1.5 token 计,其他文本按每 4 个字符 1 token 计。
- `skillCatalogTokenBudget`(默认 1,200 token,`OPENVIKING_SKILL_CATALOG_TOKEN_BUDGET`)是 skill 清单的独立预算。`skillCatalog`(`OPENVIKING_SKILL_CATALOG`)或把预算设为 0 都会关闭清单。
- 清单来自一次 `GET /api/v1/skills` 请求。用户自己的 skill 排在前面,与用户 skill 同名的账户 skill 不再列出。每条描述截到约 40 token。描述放不下时只列名称;名称也放不下时以 `... +N more` 结尾,或缩成一行数量。服务端没有该接口时不注入清单。
- `sessionStartMaxBytes` 按 UTF-8 字节限制整个块:Claude Code 和 Codex 为 9,500,因为这两个宿主会把超过约 10,000 字符的 hook 输出存成文件,只显示预览;ZCode 为 20,000,因为它会丢弃超过 32 KB 的输出;其他集成不设上限。超出上限时,先去掉记忆索引,再去掉 skill 清单。
diff --git a/examples/agent-hook-plugin/hosts/codebuddy/plugin.json b/examples/agent-hook-plugin/hosts/codebuddy/plugin.json
index 4f25d3481..8d39f1fb0 100644
--- a/examples/agent-hook-plugin/hosts/codebuddy/plugin.json
+++ b/examples/agent-hook-plugin/hosts/codebuddy/plugin.json
@@ -1,6 +1,6 @@
{
"name": "openviking-memory",
- "version": "0.5.26",
+ "version": "0.5.27",
"description": "Long-term semantic memory for the CodeBuddy Code CLI, powered by OpenViking. Injects relevant context at session start and on each prompt, and captures the conversation back into OpenViking.",
"author": {
"name": "OpenViking",
diff --git a/examples/agent-hook-plugin/hosts/cursor/openviking.integration.json b/examples/agent-hook-plugin/hosts/cursor/openviking.integration.json
index 178ef8b95..e3b6b9ddf 100644
--- a/examples/agent-hook-plugin/hosts/cursor/openviking.integration.json
+++ b/examples/agent-hook-plugin/hosts/cursor/openviking.integration.json
@@ -1,7 +1,7 @@
{
"schemaVersion": 1,
"id": "openviking-memory",
- "version": "0.5.26",
+ "version": "0.5.27",
"clients": [
"cursor"
],
diff --git a/examples/agent-hook-plugin/hosts/kimicode/kimi.plugin.json b/examples/agent-hook-plugin/hosts/kimicode/kimi.plugin.json
index 99c90929d..825f9fec1 100644
--- a/examples/agent-hook-plugin/hosts/kimicode/kimi.plugin.json
+++ b/examples/agent-hook-plugin/hosts/kimicode/kimi.plugin.json
@@ -1,6 +1,6 @@
{
"name": "openviking-memory",
- "version": "0.5.26",
+ "version": "0.5.27",
"description": "Long-term semantic memory for Kimi Code CLI, powered by OpenViking.",
"author": {
"name": "OpenViking",
diff --git a/examples/agent-hook-plugin/hosts/kimicode/openviking.integration.json b/examples/agent-hook-plugin/hosts/kimicode/openviking.integration.json
index a82476529..0cf1ff3e3 100644
--- a/examples/agent-hook-plugin/hosts/kimicode/openviking.integration.json
+++ b/examples/agent-hook-plugin/hosts/kimicode/openviking.integration.json
@@ -1,7 +1,7 @@
{
"schemaVersion": 1,
"id": "openviking-memory",
- "version": "0.5.26",
+ "version": "0.5.27",
"clients": [
"kimicode"
],
diff --git a/examples/agent-hook-plugin/hosts/trae/openviking.integration.json b/examples/agent-hook-plugin/hosts/trae/openviking.integration.json
index e25e143cd..18663daab 100644
--- a/examples/agent-hook-plugin/hosts/trae/openviking.integration.json
+++ b/examples/agent-hook-plugin/hosts/trae/openviking.integration.json
@@ -1,7 +1,7 @@
{
"schemaVersion": 1,
"id": "openviking-memory",
- "version": "0.5.26",
+ "version": "0.5.27",
"clients": [
"trae",
"trae-cn"
diff --git a/examples/agent-hook-plugin/hosts/zcode/openviking.integration.json b/examples/agent-hook-plugin/hosts/zcode/openviking.integration.json
index d280b6aea..5034f473d 100644
--- a/examples/agent-hook-plugin/hosts/zcode/openviking.integration.json
+++ b/examples/agent-hook-plugin/hosts/zcode/openviking.integration.json
@@ -1,7 +1,7 @@
{
"schemaVersion": 1,
"id": "openviking-memory",
- "version": "0.5.26",
+ "version": "0.5.27",
"clients": [
"zcode"
],
diff --git a/examples/agent-hook-plugin/plugin.json b/examples/agent-hook-plugin/plugin.json
index bd9a726d5..a612b83be 100644
--- a/examples/agent-hook-plugin/plugin.json
+++ b/examples/agent-hook-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "agent-hook-plugin",
- "version": "0.5.26",
+ "version": "0.5.27",
"description": "Long-term semantic memory for Cursor, TRAE, TRAE CN, ZCode, Kimi Code and CodeBuddy Code — powered by OpenViking. Auto-recall relevant memories and capture the conversation as it happens.",
"author": {
"name": "OpenViking",
diff --git a/examples/claude-code-memory-plugin/.claude-plugin/plugin.json b/examples/claude-code-memory-plugin/.claude-plugin/plugin.json
index 1a2e04dda..69958e7b2 100644
--- a/examples/claude-code-memory-plugin/.claude-plugin/plugin.json
+++ b/examples/claude-code-memory-plugin/.claude-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "openviking-memory",
- "version": "0.7.19",
+ "version": "0.7.20",
"description": "Long-term semantic memory for Claude Code, powered by OpenViking. Auto-recall relevant memories at session start and capture important information during conversations.",
"author": {
"name": "OpenViking",
diff --git a/examples/claude-code-memory-plugin/package.json b/examples/claude-code-memory-plugin/package.json
index d3f15421f..e947bbb57 100644
--- a/examples/claude-code-memory-plugin/package.json
+++ b/examples/claude-code-memory-plugin/package.json
@@ -1,6 +1,6 @@
{
"name": "claude-code-openviking-memory",
- "version": "0.7.19",
+ "version": "0.7.20",
"description": "OpenViking memory plugin for Claude Code — semantic long-term memory",
"type": "module",
"scripts": {
diff --git a/examples/claude-code-memory-plugin/scripts/shared/profile-inject.mjs b/examples/claude-code-memory-plugin/scripts/shared/profile-inject.mjs
index 510f1feb4..aa8e1a1bd 100644
--- a/examples/claude-code-memory-plugin/scripts/shared/profile-inject.mjs
+++ b/examples/claude-code-memory-plugin/scripts/shared/profile-inject.mjs
@@ -8,6 +8,10 @@
* viking://user/<space>/memories/entities/ (ls with abstracts)
* GET /api/v1/skills (own + account-shared skills)
*
+ * With an actorPeerId the same three paths under
+ * viking://user/<space>/peers/<peer>/memories/ are read too, and each section
+ * lists the user root first, then the peer root, under one shared budget.
+ *
* Budget enforced via the CJK-aware estimateTokens() below — codepoint >=
* 0x3000 counts at 1.5 tokens, else chars/4. The estimator is exported so
* callers (e.g. session-start.mjs) can log token counts that match what
@@ -240,6 +244,57 @@ function formatListing(headerUri, entries, budgetTokens, moreHint = MEMORY_MORE_
return { lines, used, dropped: 0 };
}
+/**
+ * Preferences and entities of each root in order, user root first. A root
+ * with any entry takes its fair share of what is left, and within a root the
+ * preferences get half and the entities the rest. With one root this is the
+ * single-scope split unchanged.
+ */
+function formatListingGroups(scopes, budgetTokens) {
+ const populated = scopes.filter((s) => s.prefs.length > 0 || s.ents.length > 0);
+ const lines = [];
+ let used = 0;
+ let droppedPref = 0;
+ let droppedEnt = 0;
+ for (let i = 0; i < populated.length; i++) {
+ const s = populated[i];
+ const share = Math.floor(Math.max(0, budgetTokens - used) / (populated.length - i));
+ const prefBlock = formatListing(s.prefUri, s.prefs, Math.floor(share / 2));
+ const entBlock = formatListing(s.entUri, s.ents, Math.max(0, share - prefBlock.used));
+ lines.push(...prefBlock.lines, ...entBlock.lines);
+ used += prefBlock.used + entBlock.used;
+ droppedPref += prefBlock.dropped;
+ droppedEnt += entBlock.dropped;
+ }
+ return { lines, used, droppedPref, droppedEnt };
+}
+
+// Below this a trimmed peer profile is mostly elision markers; point at it instead.
+const PEER_PROFILE_MIN_TOKENS = 200;
+const PEER_PROFILE_POINTER = "Omitted for length; read this uri with the read tool.";
+
+/**
+ * Drop peer-profile lines that already appear in the user profile, so the
+ * shared budget is not spent twice on the same fact. Returns null when no
+ * non-empty line is left.
+ */
+function dedupeProfileLines(peerProfile, userProfile) {
+ const seen = new Set(
+ String(userProfile || "").split("\n").map((l) => l.trim()).filter(Boolean),
+ );
+ const kept = [];
+ for (const line of peerProfile.split("\n")) {
+ const trimmed = line.trim();
+ if (trimmed && seen.has(trimmed)) continue;
+ // Removed lines must not leave runs of blank lines behind.
+ if (!trimmed && (kept.length === 0 || !kept[kept.length - 1].trim())) continue;
+ kept.push(line);
+ }
+ // Headings alone carry nothing worth a second <user-profile> element.
+ const hasContent = kept.some((l) => l.trim() && !/^#{1,6}\s/.test(l.trim()));
+ return hasContent ? kept.join("\n").trim() : null;
+}
+
const AGENT_SKILLS_ROOT = "viking://agent/skills";
// The server caps each skill root at node_limit, so the two roots together
// can return twice this many; the token budget below decides what fits.
@@ -349,24 +404,26 @@ function formatSkillCatalog(groups, budgetTokens) {
/**
* Build the profile injection block.
*
- * Returns null when neither profile.md, either listing, nor the skill catalog
- * has any content. The returned `block` is just the inner
+ * Returns null when no profile, no listing, and no skill catalog has any
+ * content. The returned `block` is just the inner
* <user-profile>/<available-memories>/<available-skills> payload — the caller
* wraps it in <openviking-context source="...">.
*
* @param {Function} fetchJSON ov-session.mjs:makeFetchJSON closure
- * @param {number} totalBudgetTokens budget for the profile and memory listings
- * @param {string} [actorPeerId]
+ * @param {number} totalBudgetTokens budget for the profiles and memory listings
+ * @param {string} [actorPeerId] adds the peer root alongside the user root
* @param {{ skillCatalog?: boolean, skillCatalogTokenBudget?: number, sessionStartMaxBytes?: number }} [options]
* callers pass their resolved plugin config: its skillCatalog knob adds
* <available-skills>, budgeted separately by skillCatalogTokenBudget.
* Without it the block is unchanged.
* @returns {Promise<null | {
* block: string, chars: number, tokens: number, profileUri: string,
- * profileChars: number, prefCount: number, entCount: number,
+ * profileChars: number, peerProfileUri: string, peerProfileChars: number,
+ * prefCount: number, entCount: number,
* droppedPref: number, droppedEnt: number,
* skillCount: number, droppedSkill: number, skillTokens: number,
* }>}
+ * Counts are summed across both roots; profileChars covers both raw profiles.
*/
export async function buildProfileBlock(fetchJSON, totalBudgetTokens, actorPeerId = "", options = {}) {
const { skillCatalog = false, skillCatalogTokenBudget = 0, sessionStartMaxBytes = 0 } = options;
@@ -378,42 +435,79 @@ export async function buildProfileBlock(fetchJSON, totalBudgetTokens, actorPeerI
: Infinity;
const skillBudget = Math.min(skillCatalogTokenBudget, Math.floor(capTokens / 4));
const space = await resolveUserSpace(fetchJSON, actorPeerId);
- const profileUri = `viking://user/${space}/memories/profile.md`;
- const prefUri = `viking://user/${space}/memories/preferences`;
- const entUri = `viking://user/${space}/memories/entities`;
-
- const [profile, prefs, ents, skillGroups] = await Promise.all([
- readProfile(fetchJSON, profileUri, actorPeerId),
- lsDir(fetchJSON, prefUri, actorPeerId),
- lsDir(fetchJSON, entUri, actorPeerId),
+
+ // Profile, preferences and entities carry no message range, so extraction
+ // writes the user's own facts to the user root even inside a peer session:
+ // with an actor peer both roots hold memories, and both are read.
+ const roots = [`viking://user/${space}/memories`];
+ if (actorPeerId) roots.push(`viking://user/${space}/peers/${actorPeerId}/memories`);
+ const scopes = roots.map((root) => ({
+ profileUri: `${root}/profile.md`,
+ prefUri: `${root}/preferences`,
+ entUri: `${root}/entities`,
+ }));
+
+ // Every read is independent, and a hook on the SessionStart path pays for
+ // every round trip.
+ const reads = await Promise.all([
+ ...scopes.flatMap((s) => [
+ readProfile(fetchJSON, s.profileUri, actorPeerId),
+ lsDir(fetchJSON, s.prefUri, actorPeerId),
+ lsDir(fetchJSON, s.entUri, actorPeerId),
+ ]),
skillCatalog && skillBudget > 0
? fetchSkillCatalog(fetchJSON, actorPeerId)
: [],
]);
+ const skillGroups = reads.pop();
+ scopes.forEach((s, i) => {
+ [s.profile, s.prefs, s.ents] = reads.slice(i * 3, i * 3 + 3);
+ });
+ const [user, peer] = scopes;
const skills = formatSkillCatalog(skillGroups, skillBudget);
- if (!profile && prefs.length === 0 && ents.length === 0 && skills.lines.length === 0) {
+ const peerProfile = peer?.profile ? dedupeProfileLines(peer.profile, user.profile) : null;
+ if (
+ !user.profile && !peerProfile
+ && scopes.every((s) => s.prefs.length === 0 && s.ents.length === 0)
+ && skills.lines.length === 0
+ ) {
return null;
}
const memoryBudget = Math.min(totalBudgetTokens, Math.max(0, capTokens - skills.used));
- // Profile gets up to half the total budget; listings split the rest.
+ // The profiles get up to half the total budget; listings split the rest.
// Sub-cap protects against a runaway profile blowing the listing budget.
+ // The user profile comes first; the peer profile only gets what it leaves.
const profileBudget = Math.floor(memoryBudget / 2);
- const profileTrunc = profile ? elideProfile(profile, profileBudget) : null;
+ const profileTrunc = user.profile ? elideProfile(user.profile, profileBudget) : null;
const profileTokens = estimateTokens(profileTrunc || "");
-
- const listingBudget = Math.max(0, memoryBudget - profileTokens);
- const halfListing = Math.floor(listingBudget / 2);
- const prefBlock = formatListing(prefUri, prefs, halfListing);
- const entBudget = Math.max(0, listingBudget - prefBlock.used);
- const entBlock = formatListing(entUri, ents, entBudget);
-
const profileLines = profileTrunc
- ? [`<user-profile uri="${profileUri}">`, profileTrunc, `</user-profile>`]
+ ? [`<user-profile uri="${user.profileUri}">`, profileTrunc, `</user-profile>`]
: [];
- let memoryLines = prefBlock.lines.length > 0 || entBlock.lines.length > 0
- ? [`<available-memories>`, ...prefBlock.lines, ...entBlock.lines, `</available-memories>`]
+ let peerProfileTokens = 0;
+ if (peerProfile) {
+ const peerBudget = profileBudget - profileTokens;
+ // elideProfile keeps at least 400 chars (~600 tokens of CJK), so a trim
+ // that still overruns the peer's share falls back to the pointer.
+ const peerTrunc = estimateTokens(peerProfile) <= peerBudget || peerBudget >= PEER_PROFILE_MIN_TOKENS
+ ? elideProfile(peerProfile, peerBudget)
+ : null;
+ if (peerTrunc !== null && estimateTokens(peerTrunc) <= peerBudget) {
+ profileLines.push(`<user-profile uri="${peer.profileUri}">`, peerTrunc, `</user-profile>`);
+ peerProfileTokens = estimateTokens(peerTrunc);
+ } else {
+ const pointer = `<user-profile uri="${peer.profileUri}">${PEER_PROFILE_POINTER}</user-profile>`;
+ profileLines.push(pointer);
+ peerProfileTokens = estimateTokens(pointer);
+ }
+ }
+
+ const listingBudget = Math.max(0, memoryBudget - profileTokens - peerProfileTokens);
+ const listings = formatListingGroups(scopes, listingBudget);
+
+ let memoryLines = listings.lines.length > 0
+ ? [`<available-memories>`, ...listings.lines, `</available-memories>`]
: [];
let skillLines = skills.lines;
const render = () => [...profileLines, ...memoryLines, ...skillLines].join("\n");
@@ -430,16 +524,20 @@ export async function buildProfileBlock(fetchJSON, totalBudgetTokens, actorPeerI
}
if (!block) return null;
+ const prefCount = scopes.reduce((n, s) => n + s.prefs.length, 0);
+ const entCount = scopes.reduce((n, s) => n + s.ents.length, 0);
return {
block,
chars: block.length,
tokens: estimateTokens(block),
- profileUri,
- profileChars: profile?.length ?? 0,
- prefCount: prefs.length,
- entCount: ents.length,
- droppedPref: memoryLines.length ? prefBlock.dropped : prefs.length,
- droppedEnt: memoryLines.length ? entBlock.dropped : ents.length,
+ profileUri: user.profileUri,
+ profileChars: (user.profile?.length ?? 0) + (peer?.profile?.length ?? 0),
+ peerProfileUri: peer?.profileUri ?? "",
+ peerProfileChars: peer?.profile?.length ?? 0,
+ prefCount,
+ entCount,
+ droppedPref: memoryLines.length ? listings.droppedPref : prefCount,
+ droppedEnt: memoryLines.length ? listings.droppedEnt : entCount,
skillCount: skills.count,
droppedSkill: skillLines.length ? skills.dropped : skills.count,
skillTokens: skillLines.length ? skills.used : 0,
diff --git a/examples/codex-memory-plugin/.codex-plugin/plugin.json b/examples/codex-memory-plugin/.codex-plugin/plugin.json
index b9c7125a7..6f135d8d4 100644
--- a/examples/codex-memory-plugin/.codex-plugin/plugin.json
+++ b/examples/codex-memory-plugin/.codex-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "openviking-memory",
- "version": "0.11.16",
+ "version": "0.11.17",
"description": "Long-term semantic memory for Codex, powered by OpenViking. Recall on UserPromptSubmit, incremental add_message on Stop (per turn), commit on SessionEnd (Codex >= 0.145) and on PreCompact, with an idle/ended sweep on SessionStart as the fallback for signals, crashes and older Codex builds. Includes a local stdio MCP proxy that reads OpenViking credentials from env/ovcli.conf.",
"author": {
"name": "OpenViking",
diff --git a/examples/codex-memory-plugin/scripts/session-start-commit.test.mjs b/examples/codex-memory-plugin/scripts/session-start-commit.test.mjs
index 08771219e..c640a266b 100644
--- a/examples/codex-memory-plugin/scripts/session-start-commit.test.mjs
+++ b/examples/codex-memory-plugin/scripts/session-start-commit.test.mjs
@@ -86,10 +86,26 @@ function profileHandler(requests, { archiveOverview = "" } = {}) {
return;
}
if (req.method === "GET" && url.pathname === "/api/v1/content/read") {
- writeJson(res, {
- status: "ok",
- result: "# Zeus\nWorks on OpenViking integrations.\nPrefers concise implementation notes.",
- });
+ const uri = url.searchParams.get("uri");
+ // Both scopes carry a profile, with different bodies, so the block can
+ // show that each is injected: extraction writes the user's own facts to
+ // the user root even inside a peer session.
+ if (uri === "viking://user/zeus/peers/github.com-acme-codex-profile/memories/profile.md") {
+ writeJson(res, {
+ status: "ok",
+ result: "# Zeus\nPeer-scoped profile for the codex profile repository.",
+ });
+ return;
+ }
+ if (uri === "viking://user/zeus/memories/profile.md") {
+ writeJson(res, {
+ status: "ok",
+ result: "# Zeus\nWorks on OpenViking integrations.\nPrefers concise implementation notes.",
+ });
+ return;
+ }
+ res.writeHead(404, { "Content-Type": "application/json" });
+ res.end(JSON.stringify({ status: "error", error: "not found" }));
return;
}
if (req.method === "GET" && url.pathname === "/api/v1/fs/ls") {
@@ -188,8 +204,10 @@ test("startup injects the shared profile block with workspace peer routing", asy
assert.equal(output.hookSpecificOutput.hookEventName, "SessionStart");
assert.match(output.hookSpecificOutput.additionalContext, /source="session-start"/);
- assert.match(output.hookSpecificOutput.additionalContext, /<user-profile uri="viking:\/\/user\/zeus\/memories\/profile\.md">/);
- assert.match(output.hookSpecificOutput.additionalContext, /Works on OpenViking integrations/);
+ assert.match(
+ output.hookSpecificOutput.additionalContext,
+ /<user-profile uri="viking:\/\/user\/zeus\/memories\/profile\.md">\n# Zeus\nWorks on OpenViking integrations\.[\s\S]*<\/user-profile>\n<user-profile uri="viking:\/\/user\/zeus\/peers\/github\.com-acme-codex-profile\/memories\/profile\.md">\nPeer-scoped profile for the codex profile repository\.\n<\/user-profile>/,
+ );
assert.match(output.hookSpecificOutput.additionalContext, /zeus\/workflow\.md/);
assert.match(output.hookSpecificOutput.additionalContext, /software\/openviking\.md/);
assert.match(
diff --git a/examples/codex-memory-plugin/scripts/shared/profile-inject.mjs b/examples/codex-memory-plugin/scripts/shared/profile-inject.mjs
index 510f1feb4..aa8e1a1bd 100644
--- a/examples/codex-memory-plugin/scripts/shared/profile-inject.mjs
+++ b/examples/codex-memory-plugin/scripts/shared/profile-inject.mjs
@@ -8,6 +8,10 @@
* viking://user/<space>/memories/entities/ (ls with abstracts)
* GET /api/v1/skills (own + account-shared skills)
*
+ * With an actorPeerId the same three paths under
+ * viking://user/<space>/peers/<peer>/memories/ are read too, and each section
+ * lists the user root first, then the peer root, under one shared budget.
+ *
* Budget enforced via the CJK-aware estimateTokens() below — codepoint >=
* 0x3000 counts at 1.5 tokens, else chars/4. The estimator is exported so
* callers (e.g. session-start.mjs) can log token counts that match what
@@ -240,6 +244,57 @@ function formatListing(headerUri, entries, budgetTokens, moreHint = MEMORY_MORE_
return { lines, used, dropped: 0 };
}
+/**
+ * Preferences and entities of each root in order, user root first. A root
+ * with any entry takes its fair share of what is left, and within a root the
+ * preferences get half and the entities the rest. With one root this is the
+ * single-scope split unchanged.
+ */
+function formatListingGroups(scopes, budgetTokens) {
+ const populated = scopes.filter((s) => s.prefs.length > 0 || s.ents.length > 0);
+ const lines = [];
+ let used = 0;
+ let droppedPref = 0;
+ let droppedEnt = 0;
+ for (let i = 0; i < populated.length; i++) {
+ const s = populated[i];
+ const share = Math.floor(Math.max(0, budgetTokens - used) / (populated.length - i));
+ const prefBlock = formatListing(s.prefUri, s.prefs, Math.floor(share / 2));
+ const entBlock = formatListing(s.entUri, s.ents, Math.max(0, share - prefBlock.used));
+ lines.push(...prefBlock.lines, ...entBlock.lines);
+ used += prefBlock.used + entBlock.used;
+ droppedPref += prefBlock.dropped;
+ droppedEnt += entBlock.dropped;
+ }
+ return { lines, used, droppedPref, droppedEnt };
+}
+
+// Below this a trimmed peer profile is mostly elision markers; point at it instead.
+const PEER_PROFILE_MIN_TOKENS = 200;
+const PEER_PROFILE_POINTER = "Omitted for length; read this uri with the read tool.";
+
+/**
+ * Drop peer-profile lines that already appear in the user profile, so the
+ * shared budget is not spent twice on the same fact. Returns null when no
+ * non-empty line is left.
+ */
+function dedupeProfileLines(peerProfile, userProfile) {
+ const seen = new Set(
+ String(userProfile || "").split("\n").map((l) => l.trim()).filter(Boolean),
+ );
+ const kept = [];
+ for (const line of peerProfile.split("\n")) {
+ const trimmed = line.trim();
+ if (trimmed && seen.has(trimmed)) continue;
+ // Removed lines must not leave runs of blank lines behind.
+ if (!trimmed && (kept.length === 0 || !kept[kept.length - 1].trim())) continue;
+ kept.push(line);
+ }
+ // Headings alone carry nothing worth a second <user-profile> element.
+ const hasContent = kept.some((l) => l.trim() && !/^#{1,6}\s/.test(l.trim()));
+ return hasContent ? kept.join("\n").trim() : null;
+}
+
const AGENT_SKILLS_ROOT = "viking://agent/skills";
// The server caps each skill root at node_limit, so the two roots together
// can return twice this many; the token budget below decides what fits.
@@ -349,24 +404,26 @@ function formatSkillCatalog(groups, budgetTokens) {
/**
* Build the profile injection block.
*
- * Returns null when neither profile.md, either listing, nor the skill catalog
- * has any content. The returned `block` is just the inner
+ * Returns null when no profile, no listing, and no skill catalog has any
+ * content. The returned `block` is just the inner
* <user-profile>/<available-memories>/<available-skills> payload — the caller
* wraps it in <openviking-context source="...">.
*
* @param {Function} fetchJSON ov-session.mjs:makeFetchJSON closure
- * @param {number} totalBudgetTokens budget for the profile and memory listings
- * @param {string} [actorPeerId]
+ * @param {number} totalBudgetTokens budget for the profiles and memory listings
+ * @param {string} [actorPeerId] adds the peer root alongside the user root
* @param {{ skillCatalog?: boolean, skillCatalogTokenBudget?: number, sessionStartMaxBytes?: number }} [options]
* callers pass their resolved plugin config: its skillCatalog knob adds
* <available-skills>, budgeted separately by skillCatalogTokenBudget.
* Without it the block is unchanged.
* @returns {Promise<null | {
* block: string, chars: number, tokens: number, profileUri: string,
- * profileChars: number, prefCount: number, entCount: number,
+ * profileChars: number, peerProfileUri: string, peerProfileChars: number,
+ * prefCount: number, entCount: number,
* droppedPref: number, droppedEnt: number,
* skillCount: number, droppedSkill: number, skillTokens: number,
* }>}
+ * Counts are summed across both roots; profileChars covers both raw profiles.
*/
export async function buildProfileBlock(fetchJSON, totalBudgetTokens, actorPeerId = "", options = {}) {
const { skillCatalog = false, skillCatalogTokenBudget = 0, sessionStartMaxBytes = 0 } = options;
@@ -378,42 +435,79 @@ export async function buildProfileBlock(fetchJSON, totalBudgetTokens, actorPeerI
: Infinity;
const skillBudget = Math.min(skillCatalogTokenBudget, Math.floor(capTokens / 4));
const space = await resolveUserSpace(fetchJSON, actorPeerId);
- const profileUri = `viking://user/${space}/memories/profile.md`;
- const prefUri = `viking://user/${space}/memories/preferences`;
- const entUri = `viking://user/${space}/memories/entities`;
-
- const [profile, prefs, ents, skillGroups] = await Promise.all([
- readProfile(fetchJSON, profileUri, actorPeerId),
- lsDir(fetchJSON, prefUri, actorPeerId),
- lsDir(fetchJSON, entUri, actorPeerId),
+
+ // Profile, preferences and entities carry no message range, so extraction
+ // writes the user's own facts to the user root even inside a peer session:
+ // with an actor peer both roots hold memories, and both are read.
+ const roots = [`viking://user/${space}/memories`];
+ if (actorPeerId) roots.push(`viking://user/${space}/peers/${actorPeerId}/memories`);
+ const scopes = roots.map((root) => ({
+ profileUri: `${root}/profile.md`,
+ prefUri: `${root}/preferences`,
+ entUri: `${root}/entities`,
+ }));
+
+ // Every read is independent, and a hook on the SessionStart path pays for
+ // every round trip.
+ const reads = await Promise.all([
+ ...scopes.flatMap((s) => [
+ readProfile(fetchJSON, s.profileUri, actorPeerId),
+ lsDir(fetchJSON, s.prefUri, actorPeerId),
+ lsDir(fetchJSON, s.entUri, actorPeerId),
+ ]),
skillCatalog && skillBudget > 0
? fetchSkillCatalog(fetchJSON, actorPeerId)
: [],
]);
+ const skillGroups = reads.pop();
+ scopes.forEach((s, i) => {
+ [s.profile, s.prefs, s.ents] = reads.slice(i * 3, i * 3 + 3);
+ });
+ const [user, peer] = scopes;
const skills = formatSkillCatalog(skillGroups, skillBudget);
- if (!profile && prefs.length === 0 && ents.length === 0 && skills.lines.length === 0) {
+ const peerProfile = peer?.profile ? dedupeProfileLines(peer.profile, user.profile) : null;
+ if (
+ !user.profile && !peerProfile
+ && scopes.every((s) => s.prefs.length === 0 && s.ents.length === 0)
+ && skills.lines.length === 0
+ ) {
return null;
}
const memoryBudget = Math.min(totalBudgetTokens, Math.max(0, capTokens - skills.used));
- // Profile gets up to half the total budget; listings split the rest.
+ // The profiles get up to half the total budget; listings split the rest.
// Sub-cap protects against a runaway profile blowing the listing budget.
+ // The user profile comes first; the peer profile only gets what it leaves.
const profileBudget = Math.floor(memoryBudget / 2);
- const profileTrunc = profile ? elideProfile(profile, profileBudget) : null;
+ const profileTrunc = user.profile ? elideProfile(user.profile, profileBudget) : null;
const profileTokens = estimateTokens(profileTrunc || "");
-
- const listingBudget = Math.max(0, memoryBudget - profileTokens);
- const halfListing = Math.floor(listingBudget / 2);
- const prefBlock = formatListing(prefUri, prefs, halfListing);
- const entBudget = Math.max(0, listingBudget - prefBlock.used);
- const entBlock = formatListing(entUri, ents, entBudget);
-
const profileLines = profileTrunc
- ? [`<user-profile uri="${profileUri}">`, profileTrunc, `</user-profile>`]
+ ? [`<user-profile uri="${user.profileUri}">`, profileTrunc, `</user-profile>`]
: [];
- let memoryLines = prefBlock.lines.length > 0 || entBlock.lines.length > 0
- ? [`<available-memories>`, ...prefBlock.lines, ...entBlock.lines, `</available-memories>`]
+ let peerProfileTokens = 0;
+ if (peerProfile) {
+ const peerBudget = profileBudget - profileTokens;
+ // elideProfile keeps at least 400 chars (~600 tokens of CJK), so a trim
+ // that still overruns the peer's share falls back to the pointer.
+ const peerTrunc = estimateTokens(peerProfile) <= peerBudget || peerBudget >= PEER_PROFILE_MIN_TOKENS
+ ? elideProfile(peerProfile, peerBudget)
+ : null;
+ if (peerTrunc !== null && estimateTokens(peerTrunc) <= peerBudget) {
+ profileLines.push(`<user-profile uri="${peer.profileUri}">`, peerTrunc, `</user-profile>`);
+ peerProfileTokens = estimateTokens(peerTrunc);
+ } else {
+ const pointer = `<user-profile uri="${peer.profileUri}">${PEER_PROFILE_POINTER}</user-profile>`;
+ profileLines.push(pointer);
+ peerProfileTokens = estimateTokens(pointer);
+ }
+ }
+
+ const listingBudget = Math.max(0, memoryBudget - profileTokens - peerProfileTokens);
+ const listings = formatListingGroups(scopes, listingBudget);
+
+ let memoryLines = listings.lines.length > 0
+ ? [`<available-memories>`, ...listings.lines, `</available-memories>`]
: [];
let skillLines = skills.lines;
const render = () => [...profileLines, ...memoryLines, ...skillLines].join("\n");
@@ -430,16 +524,20 @@ export async function buildProfileBlock(fetchJSON, totalBudgetTokens, actorPeerI
}
if (!block) return null;
+ const prefCount = scopes.reduce((n, s) => n + s.prefs.length, 0);
+ const entCount = scopes.reduce((n, s) => n + s.ents.length, 0);
return {
block,
chars: block.length,
tokens: estimateTokens(block),
- profileUri,
- profileChars: profile?.length ?? 0,
- prefCount: prefs.length,
- entCount: ents.length,
- droppedPref: memoryLines.length ? prefBlock.dropped : prefs.length,
- droppedEnt: memoryLines.length ? entBlock.dropped : ents.length,
+ profileUri: user.profileUri,
+ profileChars: (user.profile?.length ?? 0) + (peer?.profile?.length ?? 0),
+ peerProfileUri: peer?.profileUri ?? "",
+ peerProfileChars: peer?.profile?.length ?? 0,
+ prefCount,
+ entCount,
+ droppedPref: memoryLines.length ? listings.droppedPref : prefCount,
+ droppedEnt: memoryLines.length ? listings.droppedEnt : entCount,
skillCount: skills.count,
droppedSkill: skillLines.length ? skills.dropped : skills.count,
skillTokens: skillLines.length ? skills.used : 0,
diff --git a/examples/dsh-memory-plugin/package-lock.json b/examples/dsh-memory-plugin/package-lock.json
index e30fd735d..9a754715f 100644
--- a/examples/dsh-memory-plugin/package-lock.json
+++ b/examples/dsh-memory-plugin/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "@openviking/dsh-memory-plugin",
- "version": "0.5.30",
+ "version": "0.5.31",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "@openviking/dsh-memory-plugin",
- "version": "0.5.30",
+ "version": "0.5.31",
"license": "Apache-2.0",
"devDependencies": {
"@deepseek-ai/dsh-llm": "0.1.0-rc.6",
diff --git a/examples/dsh-memory-plugin/package.json b/examples/dsh-memory-plugin/package.json
index afb1ebe8b..e89255f0e 100644
--- a/examples/dsh-memory-plugin/package.json
+++ b/examples/dsh-memory-plugin/package.json
@@ -1,6 +1,6 @@
{
"name": "@openviking/dsh-memory-plugin",
- "version": "0.5.30",
+ "version": "0.5.31",
"description": "OpenViking memory and context bundle for DeepSeek Harness",
"icon": "./icon.svg",
"type": "module",
diff --git a/examples/memory-plugin-shared/lib/profile-inject.mjs b/examples/memory-plugin-shared/lib/profile-inject.mjs
index 1015a2c53..251b2e113 100644
--- a/examples/memory-plugin-shared/lib/profile-inject.mjs
+++ b/examples/memory-plugin-shared/lib/profile-inject.mjs
@@ -7,6 +7,10 @@
* viking://user/<space>/memories/entities/ (ls with abstracts)
* GET /api/v1/skills (own + account-shared skills)
*
+ * With an actorPeerId the same three paths under
+ * viking://user/<space>/peers/<peer>/memories/ are read too, and each section
+ * lists the user root first, then the peer root, under one shared budget.
+ *
* Budget enforced via the CJK-aware estimateTokens() below — codepoint >=
* 0x3000 counts at 1.5 tokens, else chars/4. The estimator is exported so
* callers (e.g. session-start.mjs) can log token counts that match what
@@ -239,6 +243,57 @@ function formatListing(headerUri, entries, budgetTokens, moreHint = MEMORY_MORE_
return { lines, used, dropped: 0 };
}
+/**
+ * Preferences and entities of each root in order, user root first. A root
+ * with any entry takes its fair share of what is left, and within a root the
+ * preferences get half and the entities the rest. With one root this is the
+ * single-scope split unchanged.
+ */
+function formatListingGroups(scopes, budgetTokens) {
+ const populated = scopes.filter((s) => s.prefs.length > 0 || s.ents.length > 0);
+ const lines = [];
+ let used = 0;
+ let droppedPref = 0;
+ let droppedEnt = 0;
+ for (let i = 0; i < populated.length; i++) {
+ const s = populated[i];
+ const share = Math.floor(Math.max(0, budgetTokens - used) / (populated.length - i));
+ const prefBlock = formatListing(s.prefUri, s.prefs, Math.floor(share / 2));
+ const entBlock = formatListing(s.entUri, s.ents, Math.max(0, share - prefBlock.used));
+ lines.push(...prefBlock.lines, ...entBlock.lines);
+ used += prefBlock.used + entBlock.used;
+ droppedPref += prefBlock.dropped;
+ droppedEnt += entBlock.dropped;
+ }
+ return { lines, used, droppedPref, droppedEnt };
+}
+
+// Below this a trimmed peer profile is mostly elision markers; point at it instead.
+const PEER_PROFILE_MIN_TOKENS = 200;
+const PEER_PROFILE_POINTER = "Omitted for length; read this uri with the read tool.";
+
+/**
+ * Drop peer-profile lines that already appear in the user profile, so the
+ * shared budget is not spent twice on the same fact. Returns null when no
+ * non-empty line is left.
+ */
+function dedupeProfileLines(peerProfile, userProfile) {
+ const seen = new Set(
+ String(userProfile || "").split("\n").map((l) => l.trim()).filter(Boolean),
+ );
+ const kept = [];
+ for (const line of peerProfile.split("\n")) {
+ const trimmed = line.trim();
+ if (trimmed && seen.has(trimmed)) continue;
+ // Removed lines must not leave runs of blank lines behind.
+ if (!trimmed && (kept.length === 0 || !kept[kept.length - 1].trim())) continue;
+ kept.push(line);
+ }
+ // Headings alone carry nothing worth a second <user-profile> element.
+ const hasContent = kept.some((l) => l.trim() && !/^#{1,6}\s/.test(l.trim()));
+ return hasContent ? kept.join("\n").trim() : null;
+}
+
const AGENT_SKILLS_ROOT = "viking://agent/skills";
// The server caps each skill root at node_limit, so the two roots together
// can return twice this many; the token budget below decides what fits.
@@ -348,24 +403,26 @@ function formatSkillCatalog(groups, budgetTokens) {
/**
* Build the profile injection block.
*
- * Returns null when neither profile.md, either listing, nor the skill catalog
- * has any content. The returned `block` is just the inner
+ * Returns null when no profile, no listing, and no skill catalog has any
+ * content. The returned `block` is just the inner
* <user-profile>/<available-memories>/<available-skills> payload — the caller
* wraps it in <openviking-context source="...">.
*
* @param {Function} fetchJSON ov-session.mjs:makeFetchJSON closure
- * @param {number} totalBudgetTokens budget for the profile and memory listings
- * @param {string} [actorPeerId]
+ * @param {number} totalBudgetTokens budget for the profiles and memory listings
+ * @param {string} [actorPeerId] adds the peer root alongside the user root
* @param {{ skillCatalog?: boolean, skillCatalogTokenBudget?: number, sessionStartMaxBytes?: number }} [options]
* callers pass their resolved plugin config: its skillCatalog knob adds
* <available-skills>, budgeted separately by skillCatalogTokenBudget.
* Without it the block is unchanged.
* @returns {Promise<null | {
* block: string, chars: number, tokens: number, profileUri: string,
- * profileChars: number, prefCount: number, entCount: number,
+ * profileChars: number, peerProfileUri: string, peerProfileChars: number,
+ * prefCount: number, entCount: number,
* droppedPref: number, droppedEnt: number,
* skillCount: number, droppedSkill: number, skillTokens: number,
* }>}
+ * Counts are summed across both roots; profileChars covers both raw profiles.
*/
export async function buildProfileBlock(fetchJSON, totalBudgetTokens, actorPeerId = "", options = {}) {
const { skillCatalog = false, skillCatalogTokenBudget = 0, sessionStartMaxBytes = 0 } = options;
@@ -377,42 +434,79 @@ export async function buildProfileBlock(fetchJSON, totalBudgetTokens, actorPeerI
: Infinity;
const skillBudget = Math.min(skillCatalogTokenBudget, Math.floor(capTokens / 4));
const space = await resolveUserSpace(fetchJSON, actorPeerId);
- const profileUri = `viking://user/${space}/memories/profile.md`;
- const prefUri = `viking://user/${space}/memories/preferences`;
- const entUri = `viking://user/${space}/memories/entities`;
-
- const [profile, prefs, ents, skillGroups] = await Promise.all([
- readProfile(fetchJSON, profileUri, actorPeerId),
- lsDir(fetchJSON, prefUri, actorPeerId),
- lsDir(fetchJSON, entUri, actorPeerId),
+
+ // Profile, preferences and entities carry no message range, so extraction
+ // writes the user's own facts to the user root even inside a peer session:
+ // with an actor peer both roots hold memories, and both are read.
+ const roots = [`viking://user/${space}/memories`];
+ if (actorPeerId) roots.push(`viking://user/${space}/peers/${actorPeerId}/memories`);
+ const scopes = roots.map((root) => ({
+ profileUri: `${root}/profile.md`,
+ prefUri: `${root}/preferences`,
+ entUri: `${root}/entities`,
+ }));
+
+ // Every read is independent, and a hook on the SessionStart path pays for
+ // every round trip.
+ const reads = await Promise.all([
+ ...scopes.flatMap((s) => [
+ readProfile(fetchJSON, s.profileUri, actorPeerId),
+ lsDir(fetchJSON, s.prefUri, actorPeerId),
+ lsDir(fetchJSON, s.entUri, actorPeerId),
+ ]),
skillCatalog && skillBudget > 0
? fetchSkillCatalog(fetchJSON, actorPeerId)
: [],
]);
+ const skillGroups = reads.pop();
+ scopes.forEach((s, i) => {
+ [s.profile, s.prefs, s.ents] = reads.slice(i * 3, i * 3 + 3);
+ });
+ const [user, peer] = scopes;
const skills = formatSkillCatalog(skillGroups, skillBudget);
- if (!profile && prefs.length === 0 && ents.length === 0 && skills.lines.length === 0) {
+ const peerProfile = peer?.profile ? dedupeProfileLines(peer.profile, user.profile) : null;
+ if (
+ !user.profile && !peerProfile
+ && scopes.every((s) => s.prefs.length === 0 && s.ents.length === 0)
+ && skills.lines.length === 0
+ ) {
return null;
}
const memoryBudget = Math.min(totalBudgetTokens, Math.max(0, capTokens - skills.used));
- // Profile gets up to half the total budget; listings split the rest.
+ // The profiles get up to half the total budget; listings split the rest.
// Sub-cap protects against a runaway profile blowing the listing budget.
+ // The user profile comes first; the peer profile only gets what it leaves.
const profileBudget = Math.floor(memoryBudget / 2);
- const profileTrunc = profile ? elideProfile(profile, profileBudget) : null;
+ const profileTrunc = user.profile ? elideProfile(user.profile, profileBudget) : null;
const profileTokens = estimateTokens(profileTrunc || "");
-
- const listingBudget = Math.max(0, memoryBudget - profileTokens);
- const halfListing = Math.floor(listingBudget / 2);
- const prefBlock = formatListing(prefUri, prefs, halfListing);
- const entBudget = Math.max(0, listingBudget - prefBlock.used);
- const entBlock = formatListing(entUri, ents, entBudget);
-
const profileLines = profileTrunc
- ? [`<user-profile uri="${profileUri}">`, profileTrunc, `</user-profile>`]
+ ? [`<user-profile uri="${user.profileUri}">`, profileTrunc, `</user-profile>`]
: [];
- let memoryLines = prefBlock.lines.length > 0 || entBlock.lines.length > 0
- ? [`<available-memories>`, ...prefBlock.lines, ...entBlock.lines, `</available-memories>`]
+ let peerProfileTokens = 0;
+ if (peerProfile) {
+ const peerBudget = profileBudget - profileTokens;
+ // elideProfile keeps at least 400 chars (~600 tokens of CJK), so a trim
+ // that still overruns the peer's share falls back to the pointer.
+ const peerTrunc = estimateTokens(peerProfile) <= peerBudget || peerBudget >= PEER_PROFILE_MIN_TOKENS
+ ? elideProfile(peerProfile, peerBudget)
+ : null;
+ if (peerTrunc !== null && estimateTokens(peerTrunc) <= peerBudget) {
+ profileLines.push(`<user-profile uri="${peer.profileUri}">`, peerTrunc, `</user-profile>`);
+ peerProfileTokens = estimateTokens(peerTrunc);
+ } else {
+ const pointer = `<user-profile uri="${peer.profileUri}">${PEER_PROFILE_POINTER}</user-profile>`;
+ profileLines.push(pointer);
+ peerProfileTokens = estimateTokens(pointer);
+ }
+ }
+
+ const listingBudget = Math.max(0, memoryBudget - profileTokens - peerProfileTokens);
+ const listings = formatListingGroups(scopes, listingBudget);
+
+ let memoryLines = listings.lines.length > 0
+ ? [`<available-memories>`, ...listings.lines, `</available-memories>`]
: [];
let skillLines = skills.lines;
const render = () => [...profileLines, ...memoryLines, ...skillLines].join("\n");
@@ -429,16 +523,20 @@ export async function buildProfileBlock(fetchJSON, totalBudgetTokens, actorPeerI
}
if (!block) return null;
+ const prefCount = scopes.reduce((n, s) => n + s.prefs.length, 0);
+ const entCount = scopes.reduce((n, s) => n + s.ents.length, 0);
return {
block,
chars: block.length,
tokens: estimateTokens(block),
- profileUri,
- profileChars: profile?.length ?? 0,
- prefCount: prefs.length,
- entCount: ents.length,
- droppedPref: memoryLines.length ? prefBlock.dropped : prefs.length,
- droppedEnt: memoryLines.length ? entBlock.dropped : ents.length,
+ profileUri: user.profileUri,
+ profileChars: (user.profile?.length ?? 0) + (peer?.profile?.length ?? 0),
+ peerProfileUri: peer?.profileUri ?? "",
+ peerProfileChars: peer?.profile?.length ?? 0,
+ prefCount,
+ entCount,
+ droppedPref: memoryLines.length ? listings.droppedPref : prefCount,
+ droppedEnt: memoryLines.length ? listings.droppedEnt : entCount,
skillCount: skills.count,
droppedSkill: skillLines.length ? skills.dropped : skills.count,
skillTokens: skillLines.length ? skills.used : 0,
diff --git a/examples/memory-plugin-shared/profile-inject.test.mjs b/examples/memory-plugin-shared/profile-inject.test.mjs
index 9f053df34..fcd41dc9e 100644
--- a/examples/memory-plugin-shared/profile-inject.test.mjs
+++ b/examples/memory-plugin-shared/profile-inject.test.mjs
@@ -7,7 +7,7 @@ import { buildProfileBlock, estimateTokens, isRepeatInjection, truncateToBytes }
const CATALOG = { skillCatalog: true, skillCatalogTokenBudget: 1200 };
-function fakeServer({ profile = "", skills = [], skillsResponse, memories = [] } = {}) {
+function fakeServer({ profile = "", skills = [], skillsResponse, memories = [], profilesByUri, memoriesByUri = {} } = {}) {
const calls = [];
const fetchJSON = async (path) => {
calls.push(path);
@@ -15,8 +15,13 @@ function fakeServer({ profile = "", skills = [], skillsResponse, memories = [] }
return skillsResponse ?? { ok: true, result: { skills, total: skills.length } };
}
if (path === "/api/v1/system/status") return { ok: true, result: { user: "default" } };
+ const uri = new URL(path, "http://localhost").searchParams.get("uri");
if (path.startsWith("/api/v1/content/read")) {
- return profile ? { ok: true, result: profile } : { ok: false, status: 404 };
+ const body = profilesByUri ? profilesByUri[uri] : profile;
+ return body ? { ok: true, result: body } : { ok: false, status: 404 };
+ }
+ if (path.startsWith("/api/v1/fs/ls") && Object.hasOwn(memoriesByUri, uri)) {
+ return { ok: true, result: memoriesByUri[uri] };
}
if (path.startsWith("/api/v1/fs/ls") && path.includes("preferences")) return { ok: true, result: memories };
return { ok: true, result: [] };
@@ -212,6 +217,201 @@ test("the two roots share no client-side cap, so shared skills survive a full pr
assert.match(result.block, /deploy-runbook/);
});
+const PEER = "github.com-acme-app";
+const USER_ROOT = "viking://user/default/memories";
+const PEER_ROOT = `viking://user/default/peers/${PEER}/memories`;
+const entries = (...names) => names.map((name) => ({ name, rel_path: name, isDir: false, abstract: `${name} abstract` }));
+const memoryUris = (calls) => calls
+ .filter((path) => path.startsWith("/api/v1/content/read") || path.startsWith("/api/v1/fs/ls"))
+ .map((path) => new URL(path, "http://localhost").searchParams.get("uri"))
+ .filter((uri) => uri.includes("/memories/"));
+
+test("without an actor peer only the user root is read and the block keeps its shape", async () => {
+ const { calls, fetchJSON } = fakeServer({
+ profilesByUri: { [`${USER_ROOT}/profile.md`]: "# Alice\n- prefers small PRs" },
+ memoriesByUri: { [`${USER_ROOT}/preferences`]: entries("alice/style.md") },
+ });
+
+ const result = await buildProfileBlock(fetchJSON, 2000, "");
+
+ assert.deepEqual(memoryUris(calls), [`${USER_ROOT}/profile.md`, `${USER_ROOT}/preferences`, `${USER_ROOT}/entities`]);
+ assert.equal(result.block, [
+ `<user-profile uri="${USER_ROOT}/profile.md">`,
+ "# Alice\n- prefers small PRs",
+ "</user-profile>",
+ "<available-memories>",
+ ` ${USER_ROOT}/preferences/`,
+ " - alice/style.md — alice/style.md abstract",
+ "</available-memories>",
+ ].join("\n"));
+ assert.equal(result.profileUri, `${USER_ROOT}/profile.md`);
+ assert.equal(result.peerProfileUri, "");
+});
+
+test("with an actor peer both roots are read at once, user root first", async () => {
+ let inFlight = 0;
+ let maxInFlight = 0;
+ const { calls, fetchJSON: inner } = fakeServer({ skills: [skill(OWN, "pr-review")] });
+ const fetchJSON = async (path, ...rest) => {
+ inFlight++;
+ maxInFlight = Math.max(maxInFlight, inFlight);
+ await new Promise((resolve) => setTimeout(resolve, 5));
+ inFlight--;
+ return inner(path, ...rest);
+ };
+
+ await buildProfileBlock(fetchJSON, 2000, PEER, CATALOG);
+
+ assert.deepEqual(memoryUris(calls), [
+ `${USER_ROOT}/profile.md`, `${USER_ROOT}/preferences`, `${USER_ROOT}/entities`,
+ `${PEER_ROOT}/profile.md`, `${PEER_ROOT}/preferences`, `${PEER_ROOT}/entities`,
+ ]);
+ // Six memory reads plus the skill catalog, after the space lookup.
+ assert.equal(maxInFlight, 7);
+});
+
+test("a peer session with only peer memories injects the peer root", async () => {
+ const { fetchJSON } = fakeServer({
+ profilesByUri: { [`${PEER_ROOT}/profile.md`]: "# app\n- uses pnpm" },
+ memoriesByUri: { [`${PEER_ROOT}/entities`]: entries("app/db.md") },
+ });
+
+ const result = await buildProfileBlock(fetchJSON, 2000, PEER);
+
+ assert.equal(result.block, [
+ `<user-profile uri="${PEER_ROOT}/profile.md">`,
+ "# app\n- uses pnpm",
+ "</user-profile>",
+ "<available-memories>",
+ ` ${PEER_ROOT}/entities/`,
+ " - app/db.md — app/db.md abstract",
+ "</available-memories>",
+ ].join("\n"));
+ assert.equal(result.entCount, 1);
+ assert.equal(result.peerProfileUri, `${PEER_ROOT}/profile.md`);
+});
+
+test("a peer session with only user memories still injects the user root", async () => {
+ const { fetchJSON } = fakeServer({
+ profilesByUri: { [`${USER_ROOT}/profile.md`]: "# Alice\n- prefers small PRs" },
+ memoriesByUri: { [`${USER_ROOT}/preferences`]: entries("alice/style.md") },
+ });
+
+ const result = await buildProfileBlock(fetchJSON, 2000, PEER);
+ const plain = await buildProfileBlock(fetchJSON, 2000, "");
+
+ assert.equal(result.block, plain.block);
+ assert.equal(result.prefCount, 1);
+ assert.equal(result.peerProfileChars, 0);
+});
+
+test("both profiles render as their own elements, user first, sharing the profile budget", async () => {
+ const userProfile = "# Alice\n- prefers small PRs";
+ const peerProfile = "# app\n- deploys with helm";
+ const { fetchJSON } = fakeServer({
+ profilesByUri: { [`${USER_ROOT}/profile.md`]: userProfile, [`${PEER_ROOT}/profile.md`]: peerProfile },
+ });
+
+ const result = await buildProfileBlock(fetchJSON, 2000, PEER);
+
+ assert.equal(result.block, [
+ `<user-profile uri="${USER_ROOT}/profile.md">`, userProfile, "</user-profile>",
+ `<user-profile uri="${PEER_ROOT}/profile.md">`, peerProfile, "</user-profile>",
+ ].join("\n"));
+ assert.equal(result.profileChars, userProfile.length + peerProfile.length);
+ assert.equal(result.peerProfileChars, peerProfile.length);
+});
+
+test("a byte cap keeps the user profile whole and trims or points at the peer profile", async () => {
+ const userProfile = HEAVY_PROFILE.split("\n").slice(0, 12).join("\n");
+ const peerProfile = HEAVY_PROFILE.replace(/feat\/x-/g, "feat/peer-");
+ for (const [userBody, label] of [[userProfile, "fits"], [HEAVY_PROFILE, "over"]]) {
+ const { fetchJSON } = fakeServer({
+ profilesByUri: { [`${USER_ROOT}/profile.md`]: userBody, [`${PEER_ROOT}/profile.md`]: peerProfile },
+ memoriesByUri: { [`${USER_ROOT}/preferences`]: HEAVY_MEMORIES, [`${PEER_ROOT}/preferences`]: HEAVY_MEMORIES },
+ skills: HEAVY_SKILLS,
+ });
+ const result = await buildProfileBlock(fetchJSON, 10000, PEER, { ...CATALOG, sessionStartMaxBytes: 9500 });
+
+ assert.ok(Buffer.byteLength(result.block) <= 9500, `${label}: ${Buffer.byteLength(result.block)} bytes`);
+ const peerElement = result.block.slice(result.block.indexOf(`<user-profile uri="${PEER_ROOT}/profile.md">`));
+ assert.ok(result.block.indexOf(`${USER_ROOT}/profile.md`) < result.block.indexOf(`${PEER_ROOT}/profile.md`), label);
+ if (label === "fits") {
+ assert.ok(result.block.includes(userProfile), "user profile kept whole");
+ assert.match(peerElement, /profile (middle elided|truncated)|Omitted for length/);
+ } else {
+ assert.match(result.block, /profile (middle elided|truncated)/);
+ assert.match(peerElement, /^<user-profile uri="[^"]+">Omitted for length; read this uri with the read tool\.<\/user-profile>/);
+ }
+ for (const tag of ["<available-memories>", "<available-skills>"]) assert.ok(result.block.includes(tag), `${label}: ${tag}`);
+ }
+});
+
+test("a CJK peer profile never renders past what the user profile leaves it", async () => {
+ const cjkLine = (i) => `- 第${i}条:喜欢在提交前运行全部测试并检查格式`;
+ const userProfile = Array.from({ length: 5 }, (_, i) => cjkLine(`甲${i}`)).join("\n");
+ const peerProfile = Array.from({ length: 400 }, (_, i) => cjkLine(i)).join("\n");
+ for (const total of [800, 1000, 1200]) {
+ const { fetchJSON } = fakeServer({
+ profilesByUri: { [`${USER_ROOT}/profile.md`]: userProfile, [`${PEER_ROOT}/profile.md`]: peerProfile },
+ });
+ const result = await buildProfileBlock(fetchJSON, total, PEER);
+ const peerBudget = Math.floor(total / 2) - estimateTokens(userProfile);
+ assert.ok(peerBudget >= 200 && peerBudget < 550, `${total}: peer budget ${peerBudget}`);
+ assert.ok(result.block.includes(userProfile), `${total}: user profile kept whole`);
+ const start = result.block.indexOf(`<user-profile uri="${PEER_ROOT}/profile.md">`);
+ const peerElement = result.block.slice(start, result.block.indexOf("</user-profile>", start) + "</user-profile>".length);
+ const body = peerElement.replace(/^<user-profile uri="[^"]+">\n?/, "").replace(/\n?<\/user-profile>$/, "");
+ assert.ok(
+ estimateTokens(body) <= peerBudget || /Omitted for length/.test(peerElement),
+ `${total}: peer body ${estimateTokens(body)} tokens over ${peerBudget}`,
+ );
+ }
+});
+
+test("peer profile lines already in the user profile are not repeated", async () => {
+ const { fetchJSON } = fakeServer({
+ profilesByUri: {
+ [`${USER_ROOT}/profile.md`]: "# Alice\n- prefers small PRs\n- writes Go",
+ [`${PEER_ROOT}/profile.md`]: "# Alice\n\n - prefers small PRs\n\n- owns the billing service",
+ },
+ });
+ const result = await buildProfileBlock(fetchJSON, 2000, PEER);
+ assert.ok(result.block.endsWith(`<user-profile uri="${PEER_ROOT}/profile.md">\n- owns the billing service\n</user-profile>`), result.block);
+
+ const duplicate = fakeServer({
+ profilesByUri: {
+ [`${USER_ROOT}/profile.md`]: "# Alice\n- prefers small PRs",
+ [`${PEER_ROOT}/profile.md`]: "# Alice\n\n- prefers small PRs\n",
+ },
+ });
+ const only = await buildProfileBlock(duplicate.fetchJSON, 2000, PEER);
+ assert.doesNotMatch(only.block, /peers\//);
+});
+
+test("listings put the user root before the peer root under one shared budget", async () => {
+ const many = (prefix) => entries(...Array.from({ length: 200 }, (_, i) => `${prefix}/item-${String(i).padStart(3, "0")}.md`));
+ const memoriesByUri = {
+ [`${USER_ROOT}/preferences`]: many("alice"),
+ [`${USER_ROOT}/entities`]: many("alice"),
+ [`${PEER_ROOT}/preferences`]: many("app"),
+ [`${PEER_ROOT}/entities`]: many("app"),
+ };
+ const { fetchJSON } = fakeServer({ memoriesByUri });
+ const result = await buildProfileBlock(fetchJSON, 2000, PEER);
+
+ const order = [`${USER_ROOT}/preferences/`, `${USER_ROOT}/entities/`, `${PEER_ROOT}/preferences/`, `${PEER_ROOT}/entities/`]
+ .map((header) => result.block.indexOf(` ${header}`));
+ assert.ok(order.every((index, i) => index >= 0 && (i === 0 || index > order[i - 1])), order.join(","));
+ // Two roots split the budget one root would get alone instead of doubling it.
+ const single = await buildProfileBlock(fetchJSON, 2000, "");
+ assert.ok(Math.abs(result.tokens - single.tokens) <= 20, `${result.tokens} vs ${single.tokens} tokens`);
+ assert.equal(result.prefCount, 400);
+ assert.equal(result.entCount, 400);
+ assert.ok(result.droppedPref > 0 && result.droppedEnt > 0);
+ assert.equal((result.block.match(/\.\.\. \+\d+ more/g) || []).length, 4);
+});
+
test("truncateToBytes cuts on a line boundary and marks the cut", () => {
const text = ["第一行", "second line", "第三行内容"].join("\n");
assert.equal(truncateToBytes(text, 0), text);
@@ -229,3 +429,20 @@ test("isRepeatInjection reports an unchanged block for the same session only", (
assert.equal(isRepeatInjection(path, "s1", "block B"), false);
assert.equal(isRepeatInjection(path, "s1", "block B"), true);
});
+
+test("a peer profile left with only headings after dedup is omitted", async () => {
+ const user = "# Alice\n- a\n- b";
+ const peer = "# Alice (app)\n## Notes\n- a\n- b";
+ const fetchJSON = async (path) => {
+ const uri = decodeURIComponent((path.match(/uri=([^&]+)/) || [])[1] || "");
+ if (path.startsWith("/api/v1/content/read")) {
+ if (uri.endsWith("/peers/p1/memories/profile.md")) return { ok: true, result: peer };
+ if (uri.endsWith("/memories/profile.md")) return { ok: true, result: user };
+ }
+ if (path.startsWith("/api/v1/system/status")) return { ok: true, result: { user: "alice" } };
+ return { ok: true, result: [] };
+ };
+ const out = await buildProfileBlock(fetchJSON, 4000, "p1");
+ assert.ok(out.block.includes("- a"));
+ assert.equal((out.block.match(/<user-profile /g) || []).length, 1);
+});
diff --git a/examples/opencode-plugin/package.json b/examples/opencode-plugin/package.json
index 7663ee3f1..ec390ea20 100644
--- a/examples/opencode-plugin/package.json
+++ b/examples/opencode-plugin/package.json
@@ -1,6 +1,6 @@
{
"name": "@openviking/opencode-plugin",
- "version": "0.5.22",
+ "version": "0.5.23",
"author": "@openviking",
"description": "Unified OpenCode plugin for OpenViking repository retrieval and long-term memory",
"type": "module",
diff --git a/examples/pi-coding-agent-extension/package-lock.json b/examples/pi-coding-agent-extension/package-lock.json
index 95995fafc..99ce17b5a 100644
--- a/examples/pi-coding-agent-extension/package-lock.json
+++ b/examples/pi-coding-agent-extension/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "openviking-pi-extension",
- "version": "0.4.24",
+ "version": "0.4.25",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "openviking-pi-extension",
- "version": "0.4.24",
+ "version": "0.4.25",
"dependencies": {
"@modelcontextprotocol/client": "2.0.0"
},
diff --git a/examples/pi-coding-agent-extension/package.json b/examples/pi-coding-agent-extension/package.json
index 4253f7f89..15deb625c 100644
--- a/examples/pi-coding-agent-extension/package.json
+++ b/examples/pi-coding-agent-extension/package.json
@@ -1,6 +1,6 @@
{
"name": "openviking-pi-extension",
- "version": "0.4.24",
+ "version": "0.4.25",
"description": "OpenViking memory and context extension for the pi coding agent",
"private": true,
"type": "module",