Skip to content

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

fix(openclaw): inject the user profile into automatic context (#5676)

t0saki1c990085c83a
diff --git a/docs/en/agent-integrations/03-openclaw.md b/docs/en/agent-integrations/03-openclaw.md
index 84393a756..98bb79867 100644
--- a/docs/en/agent-integrations/03-openclaw.md
+++ b/docs/en/agent-integrations/03-openclaw.md
@@ -95,7 +95,7 @@ The main branch calls `getSessionContext(tokenBudget)` and builds:
```text
summaryMessage = { role: "user", content: "[Session History Summary]\n" + latest_archive_overview }
messages = [summaryMessage] + OV active messages
-systemPromptAddition = Session Context Guide (when archives exist) + recalled context (when available)
+systemPromptAddition = Session Context Guide (when archives exist) + user profile (when profile.md exists) + recalled context (when available)
```
`latest_archive_overview` is the summary text returned by the server; `[Session History Summary]` is the literal heading prepended by the plugin. This synthetic user message is inserted only when the overview is nonempty. Active messages provide recent uncompressed conversation. The host adds the pending `prompt` to the turn. The plugin uses it for recall without appending a second copy to the returned history. Recalled context belongs to this request and is not directly captured as new conversation in OV.
diff --git a/docs/en/agent-integrations/16-capability-reference.md b/docs/en/agent-integrations/16-capability-reference.md
index 6d0242c06..ef9502383 100644
--- a/docs/en/agent-integrations/16-capability-reference.md
+++ b/docs/en/agent-integrations/16-capability-reference.md
@@ -56,13 +56,13 @@ Long-term memories are extracted from a session only after a **commit**. Capture
| OpenCode | Yes, session-aware | Profile, memory index, skills, indexed repositories | At 20,000 pending tokens, when idle | Yes, within the host's cleanup time | Commits around compaction |
| DSH | Yes, session-aware | Profile, memory index, skills, once per session | At 20,000 pending tokens | Yes, with a 3-second budget | Not observed |
| pi | Yes, session-aware | Profile, memory index, skills, every turn | Takeover on: about 30,000 tokens; off: 20,000 | Takeover on: no; off: yes | Takeover replaces pi's summary |
-| OpenClaw | Yes, not session-aware | None | At half the token budget (64,000 by default) | No | The plugin owns compaction |
+| OpenClaw | Yes, session-aware | Profile, every turn | At half the token budget (64,000 by default) | No | The plugin owns compaction |
| Hermes (bundled) | Yes, session-aware with a fallback | Profile and memory listings | No; only at session boundaries | Yes, if pending uploads finish within 10 seconds | Commits at fork-style compaction |
| ov CLI | No | No | Only `ov session commit` | Not applicable | Not applicable |
How to read this table:
-- **Session-aware recall** sends the session ID so the server can use the conversation to interpret the query. The shared plugins’ context mode also expands the query and tracks recently injected memories to avoid repeating them. Hermes uses list mode, which has no injection ledger; OpenClaw uses `/find`, which has no session field. See [How recall reaches the server](#how-recall-reaches-the-server) for the request paths and fallbacks.
+- **Session-aware recall** sends the session ID so the server can use the conversation to interpret the query. The shared plugins’ context mode also expands the query and tracks recently injected memories to avoid repeating them. Hermes uses list mode, which has no injection ledger. OpenClaw uses context search with the session ID but turns deduplication off, because its injected context is rebuilt every turn and never stored in the history. See [How recall reaches the server](#how-recall-reaches-the-server) for the request paths and fallbacks.
- **Pending tokens** are server-side counts of captured but uncommitted messages. Most thresholds are client settings; [the commit table](#when-each-integration-commits) lists them.
- **Commits at a normal exit** means the integration sends a commit request. Network errors, host exit budgets, or process termination can still interrupt it. [What happens at exit](#what-happens-at-exit) covers Ctrl+C, signals, and crashes.
@@ -186,7 +186,7 @@ The table shows the default path. Turning on [recall digests](#recall-digest) ch
| OpenCode | v1: every `chat.message`; v2: every prompt | Text parts of the message | v1 prepends a synthetic part. v2 stores the result in message metadata and injects it before that message at each model step, without a new request |
| DSH | `agent/pre-step` | Every message in the claimed batch, minus its own injected content | Appended as a user message |
| pi | Queued at `before_agent_start`, run in the `context` event | The prompt | Prepended to the last real user message, so this turn's prompt gets this turn's memories |
-| OpenClaw | Context assembly | Last user message, cleaned and cut to 4,000 characters | `<relevant-memories>` prepended to the last user message |
+| OpenClaw | Context assembly | The incoming prompt, cleaned and cut to 4,000 characters | `<relevant-memories>` in the system prompt, rebuilt every turn. On hosts that do not pass the prompt, it is prepended to the last user message |
| Hermes | Before every model call | User input of 5 characters or more, with skill scaffolding removed | `<memory-context>` appended to the current user message in the request only; never stored |
<a id="_3-2-3-profile-opening-injection"></a>
@@ -220,7 +220,7 @@ When each integration injects it:
| OpenCode | The first message of each session; not retried after a failure, and skipped for subagent sessions. The list of indexed repositories also goes into the system prompt |
| DSH | Once per session; not sent again after compaction |
| pi | In the system prompt, rebuilt every turn |
-| OpenClaw | Not injected |
+| OpenClaw | In the system prompt, rebuilt every turn: `<user-profile>` for the user's profile and, with `peer_role`, the actor peer's profile. No memory index or skill catalog |
| Hermes | Its own reader loads the profile and the preferences and entities listings, with a 6,000-token default budget |
Budgets and limits:
@@ -246,7 +246,7 @@ The server stops query expansion after 5 seconds (`retrieval.recall_intent_timeo
| OpenCode | 30 seconds |
| DSH | 10 seconds, raised to at least 15 with query expansion. Recall blocks the pre-step |
| pi | 15 seconds |
-| OpenClaw | 5 seconds for the whole recall, including a 500 ms health check. With the default `recallPreferAbstract=false`, each memory costs an extra read, which allows at most one find and six reads |
+| OpenClaw | 15 seconds by default for the context search (`autoRecallTimeoutMs`), after a 500 ms health check |
| Hermes | 4 seconds in total and 3 seconds per request; configurable |
OpenClaw and Hermes limit injected recall to 4,000 characters and skip an entry that does not fit instead of cutting it.
diff --git a/docs/zh/agent-integrations/03-openclaw.md b/docs/zh/agent-integrations/03-openclaw.md
index 1b8845f2f..f07bd5823 100644
--- a/docs/zh/agent-integrations/03-openclaw.md
+++ b/docs/zh/agent-integrations/03-openclaw.md
@@ -95,7 +95,7 @@ openclaw openviking setup --base-url https://openviking.example.com --api-key sk
```text
summaryMessage = { role: "user", content: "[Session History Summary]\n" + latest_archive_overview }
messages = [summaryMessage] + OV active messages
-systemPromptAddition = Session Context Guide(有归档时)+ 本轮召回结果(有命中时)
+systemPromptAddition = Session Context Guide(有归档时)+ 用户 profile(profile.md 存在时)+ 本轮召回结果(有命中时)
```
`latest_archive_overview` 是服务端返回的摘要正文,`[Session History Summary]` 是插件加在正文前的固定文本标题。仅在 overview 非空时插入这条合成 user 消息;active messages 保留近期未压缩对话。当前 `prompt` 由宿主加入本轮;插件只用它查询记忆,不把它重复追加到返回的历史中。召回结果属于本次请求的上下文,不直接作为新对话写回 OV。
diff --git a/docs/zh/agent-integrations/16-capability-reference.md b/docs/zh/agent-integrations/16-capability-reference.md
index 1405b48ba..ba949aad2 100644
--- a/docs/zh/agent-integrations/16-capability-reference.md
+++ b/docs/zh/agent-integrations/16-capability-reference.md
@@ -56,13 +56,13 @@
| OpenCode | 是,带会话 | profile、记忆索引、skill、已索引的仓库 | 空闲时,待提交 token 达到 20,000 | 是,在宿主的清理时限内 | 在压缩前后提交 |
| DSH | 是,带会话 | profile、记忆索引、skill,每个会话一次 | 待提交 token 达到 20,000 | 是,预算 3 秒 | 未观察到 |
| pi | 是,带会话 | profile、记忆索引、skill,每轮 | takeover 开:约 30,000 token;关:20,000 | takeover 开:否;关:是 | takeover 替换 pi 的摘要 |
-| OpenClaw | 是,不带会话 | 无 | token 预算的一半(默认 64,000) | 否 | 插件接管压缩 |
+| OpenClaw | 是,带会话 | profile,每轮 | token 预算的一半(默认 64,000) | 否 | 插件接管压缩 |
| Hermes(内置) | 是,带会话,有回退路径 | profile 与记忆清单 | 否;只在会话边界 | 是,前提是待上传内容在 10 秒内完成 | fork 型压缩时提交 |
| ov CLI | 否 | 否 | 只有 `ov session commit` | 不适用 | 不适用 |
表格说明:
-- **带会话的召回**会发送会话 ID,服务端借助对话内容理解查询。共享插件的 context 模式还会扩写查询,并记录最近注入过的记忆,避免重复注入。Hermes 用 list 模式,没有注入台账;OpenClaw 用 `/find`,该接口没有会话字段。请求路径和回退见[召回请求如何到达服务端](#召回请求如何到达服务端)。
+- **带会话的召回**会发送会话 ID,服务端借助对话内容理解查询。共享插件的 context 模式还会扩写查询,并记录最近注入过的记忆,避免重复注入。Hermes 用 list 模式,没有注入台账。OpenClaw 用 context search 并发送会话 ID,但关闭去重,因为它注入的上下文每轮重建,不写入历史。请求路径和回退见[召回请求如何到达服务端](#召回请求如何到达服务端)。
- **待提交 token** 是服务端统计的、已捕获但未提交的消息量。多数阈值是客户端设置,见[各集成何时提交](#各集成何时提交)。
- **正常退出时提交**指集成会发出提交请求。网络错误、宿主的退出时限或进程被终止仍可能打断它。Ctrl+C、信号和崩溃见[退出时会发生什么](#退出时会发生什么)。
@@ -186,7 +186,7 @@ skill 走单独的路径。创建、安装或替换 skill 用 MCP `add_skill`
| OpenCode | v1:每次 `chat.message`;v2:每次提问 | 消息的文本部分 | v1 在消息前插入一个合成 part。v2 把结果存进消息 metadata,每个模型 step 在该消息前注入,不发新请求 |
| DSH | `agent/pre-step` | 本批认领的所有消息,去掉自身注入的内容 | 追加为一条用户消息 |
| pi | 在 `before_agent_start` 排队,在 `context` 事件中执行 | 提问 | 前置到最后一条真实用户消息,本轮提问拿到本轮的记忆 |
-| OpenClaw | 上下文组装时 | 最后一条用户消息,清洗后截到 4,000 字符 | `<relevant-memories>`,前置到最后一条用户消息 |
+| OpenClaw | 上下文组装时 | 传入的提问,清洗后截到 4,000 字符 | `<relevant-memories>`,放在 system prompt 中,每轮重建。宿主不传提问时前置到最后一条用户消息 |
| Hermes | 每次模型调用前 | 5 个字符及以上的用户输入,去掉 skill 脚手架 | `<memory-context>`,只追加到本次请求中的当前用户消息,不写入存储 |
<a id="_3-2-3-profile-开场注入"></a>
@@ -220,7 +220,7 @@ skill 走单独的路径。创建、安装或替换 skill 用 MCP `add_skill`
| OpenCode | 每个会话的第一条消息;失败后不重试,子代理会话跳过。已索引仓库的列表同时进入 system prompt |
| DSH | 每个会话一次;压缩后不再发送 |
| pi | 放在 system prompt 中,每轮重建 |
-| OpenClaw | 不注入 |
+| OpenClaw | 放在 system prompt 中,每轮重建:`<user-profile>` 包含用户的 profile,设置了 `peer_role` 时还包含当前 actor peer 的 profile。不注入记忆索引和 skill 清单 |
| Hermes | 用自己的读取逻辑加载 profile 及 preferences、entities 清单,默认预算 6,000 token |
预算与限制:
@@ -246,7 +246,7 @@ skill 走单独的路径。创建、安装或替换 skill 用 MCP `add_skill`
| OpenCode | 30 秒 |
| DSH | 10 秒,开启查询扩写时至少 15 秒。召回会阻塞 pre-step |
| pi | 15 秒 |
-| OpenClaw | 整个召回 5 秒,含 500 ms 健康检查。默认 `recallPreferAbstract=false` 时每条记忆多一次 read,预算内最多一次 find 和六次 read |
+| OpenClaw | context search 默认 15 秒(`autoRecallTimeoutMs`),之前有一次 500 ms 健康检查 |
| Hermes | 总计 4 秒,单请求 3 秒;可配置 |
OpenClaw 和 Hermes 把注入的召回内容限制在 4,000 字符,放不下的条目整条跳过,不截断。
diff --git a/examples/openclaw-plugin/client.ts b/examples/openclaw-plugin/client.ts
index c330e34df..d90cb1a97 100644
--- a/examples/openclaw-plugin/client.ts
+++ b/examples/openclaw-plugin/client.ts
@@ -554,11 +554,11 @@ export class OpenVikingClient {
};
}
- async read(uri: string, actorPeerId?: string): Promise<string> {
+ async read(uri: string, actorPeerId?: string, requestTimeoutMs?: number): Promise<string> {
return this.request<string>(
`/api/v1/content/read?uri=${encodeURIComponent(uri)}`,
{},
- undefined,
+ requestTimeoutMs,
actorPeerId,
);
}
diff --git a/examples/openclaw-plugin/services/context-lifecycle-service.ts b/examples/openclaw-plugin/services/context-lifecycle-service.ts
index 0cb2644e3..ecd2be3d1 100644
--- a/examples/openclaw-plugin/services/context-lifecycle-service.ts
+++ b/examples/openclaw-plugin/services/context-lifecycle-service.ts
@@ -428,14 +428,13 @@ function isSessionNotFoundError(err: unknown): boolean {
return errorMessage.includes("[NOT_FOUND]") && errorMessage.includes("Session not found");
}
-async function recallForAssemble(
- params: AssembleOpenVikingSessionParams,
- recallQuery: ReturnType<typeof prepareRecallQuery>,
-) {
- const { sessionId, sessionKey, cfg, getClient, resolveAgentId, queryConfigStore, logger, traceRecorder } = params;
+const PROFILE_MAX_CHARS = 8000;
+const PROFILE_READ_TIMEOUT_MS = 3000;
+
+function resolveAssembleRouting(params: AssembleOpenVikingSessionParams) {
+ const { sessionId, sessionKey, cfg, resolveAgentId, logger } = params;
const ovSessionId = openClawSessionToOvStorageId(sessionId, sessionKey);
const sender = extractRuntimeSenderId(params.runtimeContext);
- const client = await getClient();
const routingRef = sessionId ?? sessionKey ?? ovSessionId;
const agentId = resolveAgentId(routingRef, sessionKey, ovSessionId);
const actorPeerId = resolveOpenVikingActorPeerId({
@@ -444,6 +443,44 @@ async function recallForAssemble(
assistantPeerId: agentId,
warn: (message) => logger.warn?.(message),
});
+ return { ovSessionId, agentId, actorPeerId };
+}
+
+// Server-side context assembly leaves profile.md out on the assumption that the
+// client injects it, so read it here: the user's profile and, with peer scope, the actor's.
+async function readProfileBlock(
+ client: OpenVikingClient,
+ actorPeerId: string | undefined,
+ timeoutMs: number,
+ logger: ContextEngineLifecycleLogger,
+): Promise<string> {
+ const uris = ["viking://~/memories/profile.md"];
+ if (actorPeerId) uris.push(`viking://~/peers/${actorPeerId}/memories/profile.md`);
+ const reads = await Promise.allSettled(uris.map((uri) => client.read(uri, actorPeerId, timeoutMs)));
+ return reads
+ .map((read, i) => {
+ if (read.status === "rejected" && !String(read.reason).includes("[NOT_FOUND]")) {
+ logger.warn?.(`openviking: profile read failed (uri=${uris[i]}): ${String(read.reason)}`);
+ }
+ const text = read.status === "fulfilled" && typeof read.value === "string" ? read.value.trim() : "";
+ if (!text) return "";
+ const capped = text.length > PROFILE_MAX_CHARS
+ ? `${text.slice(0, PROFILE_MAX_CHARS).trimEnd()}\n... [profile truncated]`
+ : text;
+ return `<user-profile uri="${uris[i]}">\n${capped}\n</user-profile>`;
+ })
+ .filter(Boolean)
+ .join("\n\n");
+}
+
+async function recallForAssemble(
+ params: AssembleOpenVikingSessionParams,
+ recallQuery: ReturnType<typeof prepareRecallQuery>,
+ client: OpenVikingClient,
+ routing: ReturnType<typeof resolveAssembleRouting>,
+) {
+ const { sessionId, sessionKey, cfg, queryConfigStore, logger, traceRecorder } = params;
+ const { ovSessionId, agentId, actorPeerId } = routing;
const queryConfig = await queryConfigStore?.getEffective({
agentId,
sessionId,
@@ -476,24 +513,36 @@ export async function assembleOpenVikingSession(
const assembled = await assembleSessionContext(params);
// Current OpenClaw supplies the pending turn separately from history. Keep
// recalled context out of persisted messages and let the host own that turn.
- if (
- !params.isMainAssemble || !params.cfg.autoRecall || !params.prompt ||
- params.isBypassedSession(params)
- ) {
+ if (!params.isMainAssemble || !params.cfg.autoRecall || params.isBypassedSession(params)) {
return assembled;
}
- const query = prepareRecallQuery(params.prompt);
- if (query.query.length < 5) return assembled;
+ const query = prepareRecallQuery(params.prompt ?? "");
try {
- const recall = await recallForAssemble(params, query);
- if (!recall.block) return assembled;
- const systemPromptAddition = [assembled.systemPromptAddition, recall.block].filter(Boolean).join("\n\n");
- const estimatedTokens = assembled.estimatedTokens
- + estimateTextTokens(systemPromptAddition)
- - estimateTextTokens(assembled.systemPromptAddition ?? "");
- if (estimatedTokens > params.tokenBudget) return assembled;
- return { ...assembled, systemPromptAddition, estimatedTokens };
+ const routing = resolveAssembleRouting(params);
+ const client = await params.getClient();
+ const [profileBlock, recallBlock] = await Promise.all([
+ readProfileBlock(
+ client,
+ routing.actorPeerId,
+ Math.min(params.cfg.autoRecallTimeoutMs ?? PROFILE_READ_TIMEOUT_MS, PROFILE_READ_TIMEOUT_MS),
+ params.logger,
+ ),
+ query.query.length < 5 ? "" : recallForAssemble(params, query, client, routing)
+ .then((recall) => recall.block)
+ .catch((err) => {
+ params.logger.warn?.(`openviking: auto-recall failed: ${String(err)}`);
+ return "";
+ }),
+ ]);
+ const baseTokens = estimateTextTokens(assembled.systemPromptAddition ?? "");
+ for (const blocks of [[profileBlock, recallBlock], [profileBlock], [recallBlock]]) {
+ if (!blocks.some(Boolean)) continue;
+ const systemPromptAddition = [assembled.systemPromptAddition, ...blocks].filter(Boolean).join("\n\n");
+ const estimatedTokens = assembled.estimatedTokens + estimateTextTokens(systemPromptAddition) - baseTokens;
+ if (estimatedTokens <= params.tokenBudget) return { ...assembled, systemPromptAddition, estimatedTokens };
+ }
+ return assembled;
} catch (err) {
params.logger.warn?.(`openviking: auto-recall failed: ${String(err)}`);
return assembled;
@@ -573,7 +622,7 @@ async function assembleSessionContext(params: AssembleOpenVikingSessionParams):
}
try {
- const recall = await recallForAssemble(params, recallQuery);
+ const recall = await recallForAssemble(params, recallQuery, await getClient(), resolveAssembleRouting(params));
if (!recall.block) {
return assemblePassthrough({
@@ -707,7 +756,7 @@ async function assembleSessionContext(params: AssembleOpenVikingSessionParams):
if (isSessionNotFoundError(err)) {
const errorMessage = String(err);
logger.info(
- `openviking: assemble skipped because OV session does not exist ` +
+ `openviking: session history not assembled because OV session does not exist ` +
`(session=${ovSessionId}, tokenBudget=${tokenBudget}, agentId=${resolveAgentId(ovSessionId)})`,
);
return assemblePassthrough({
diff --git a/examples/openclaw-plugin/tests/ut/client.test.ts b/examples/openclaw-plugin/tests/ut/client.test.ts
index 7c9c3965a..0117b739c 100644
--- a/examples/openclaw-plugin/tests/ut/client.test.ts
+++ b/examples/openclaw-plugin/tests/ut/client.test.ts
@@ -674,6 +674,31 @@ describe("OpenVikingClient canonical namespace policy", () => {
await rejection;
});
+ it("aborts a read at its own request timeout", async () => {
+ vi.useFakeTimers();
+ let requestSignal: AbortSignal | undefined;
+ const transport = vi.fn((_url: string, init: RequestInit) => {
+ requestSignal = init.signal ?? undefined;
+ return new Promise<Response>((_resolve, reject) => {
+ requestSignal?.addEventListener("abort", () => {
+ reject(new DOMException("The operation was aborted", "AbortError"));
+ });
+ });
+ });
+ const client = new OpenVikingClient(
+ "http://127.0.0.1:1933", "", "agent", 15000,
+ "", "", undefined, false, true, { transport },
+ );
+
+ const pending = client.read("viking://~/memories/profile.md", undefined, 3000);
+ const rejection = expect(pending).rejects.toMatchObject({ name: "AbortError" });
+ await vi.advanceTimersByTimeAsync(2999);
+ expect(requestSignal?.aborted).toBe(false);
+ await vi.advanceTimersByTimeAsync(1);
+ expect(requestSignal?.aborted).toBe(true);
+ await rejection;
+ });
+
it("keeps user memory alias unchanged and routes by actor peer by default", async () => {
const transport = vi.fn(async (url: string) => {
if (url.endsWith("/api/v1/system/status")) {
diff --git a/examples/openclaw-plugin/tests/ut/context-engine-assemble.test.ts b/examples/openclaw-plugin/tests/ut/context-engine-assemble.test.ts
index ae574ca38..864ed5492 100644
--- a/examples/openclaw-plugin/tests/ut/context-engine-assemble.test.ts
+++ b/examples/openclaw-plugin/tests/ut/context-engine-assemble.test.ts
@@ -201,6 +201,177 @@ describe("context-engine assemble()", () => {
});
});
+ describe("user profile injection", () => {
+ const prompt = "what are my project alias and theme color?";
+ const userProfileUri = "viking://~/memories/profile.md";
+ const profile = "# User\n- Project alias: Basalt-x\n- Preferred theme color: marigold";
+ const memory = "User prefers Rust for backend tasks.";
+
+ function mockProfile(client: ReturnType<typeof makeEngine>["client"], profiles: Record<string, string> = { [userProfileUri]: profile }) {
+ client.read.mockImplementation(async (uri: string) => {
+ if (uri in profiles) return profiles[uri];
+ throw new Error("[NOT_FOUND] File not found");
+ });
+ }
+
+ function mockRecall(client: ReturnType<typeof makeEngine>["client"], text = memory) {
+ client.searchContext.mockResolvedValue({
+ entries: [{ uri: "viking://user/default/memories/preferences/rust", category: "preferences", text, score: 0.93 }],
+ rendered: `<memory>${text}</memory>`,
+ stats: {},
+ });
+ }
+
+ it.each([false, true])("injects profile.md when recall finds nothing (missing session: %s)", async (missing) => {
+ const { engine, client } = makeEngine(undefined, { cfgOverrides: { autoRecall: true } });
+ if (missing) client.getSessionContext.mockRejectedValue(new Error("[NOT_FOUND] Session not found"));
+ mockProfile(client);
+ const messages: [] = [];
+ const result = await engine.assemble({ sessionId: "new-session", messages, prompt });
+ expect(client.read).toHaveBeenCalledWith(userProfileUri, undefined, 3000);
+ expect(result.messages).toBe(messages);
+ expect(result.systemPromptAddition).toContain(`<user-profile uri="${userProfileUri}">`);
+ expect(result.systemPromptAddition).toContain("Basalt-x");
+ expect(result.estimatedTokens).toBeGreaterThanOrEqual(systemPromptTokens(result.systemPromptAddition));
+ });
+
+ it("places the profile between the archive guide and recalled memories on every main turn", async () => {
+ const { engine, client } = makeEngine({
+ latest_archive_overview: "Previously discussed repository setup.",
+ pre_archive_abstracts: [], messages: [], estimatedTokens: 10, stats: makeStats(),
+ }, { cfgOverrides: { autoRecall: true } });
+ mockProfile(client);
+ mockRecall(client);
+ for (const turnPrompt of [prompt, "and which backend language?"]) {
+ const result = await engine.assemble({ sessionId: "archived-session", messages: [], prompt: turnPrompt });
+ const addition = result.systemPromptAddition ?? "";
+ const guideAt = addition.indexOf("Session Context Guide");
+ const profileAt = addition.indexOf("<user-profile");
+ const recallAt = addition.indexOf(memory);
+ expect(guideAt).toBeGreaterThanOrEqual(0);
+ expect(profileAt).toBeGreaterThan(guideAt);
+ expect(recallAt).toBeGreaterThan(profileAt);
+ }
+ });
+
+ it("injects the profile for prompts too short to recall", async () => {
+ const { engine, client } = makeEngine(undefined, { cfgOverrides: { autoRecall: true } });
+ mockProfile(client);
+ const result = await engine.assemble({ sessionId: "session", messages: [], prompt: "hi" });
+ expect(client.searchContext).not.toHaveBeenCalled();
+ expect(result.systemPromptAddition).toContain("Basalt-x");
+ });
+
+ it("keeps recall when the profile is missing, and the profile when recall fails", async () => {
+ const { engine, client } = makeEngine(undefined, { cfgOverrides: { autoRecall: true } });
+ mockProfile(client, {});
+ mockRecall(client);
+ const recallOnly = await engine.assemble({ sessionId: "session", messages: [], prompt });
+ expect(recallOnly.systemPromptAddition).toContain(memory);
+ expect(recallOnly.systemPromptAddition).not.toContain("<user-profile");
+
+ mockProfile(client);
+ client.searchContext.mockRejectedValue(new Error("unavailable"));
+ const profileOnly = await engine.assemble({ sessionId: "session", messages: [], prompt });
+ expect(profileOnly.systemPromptAddition).toContain("Basalt-x");
+ expect(profileOnly.systemPromptAddition).not.toContain(memory);
+ });
+
+ it("reads the actor peer's profile too under peer_role=sender", async () => {
+ const peerProfileUri = "viking://~/peers/telegram_12345/memories/profile.md";
+ const { engine, client } = makeEngine(undefined, { cfgOverrides: { autoRecall: true, peer_role: "sender" } });
+ mockProfile(client, { [userProfileUri]: profile, [peerProfileUri]: "# Peer\n- Timezone: UTC+8" });
+ const result = await engine.assemble({
+ sessionId: "session", messages: [], prompt, runtimeContext: { senderId: "telegram:12345" },
+ });
+ expect(client.read).toHaveBeenCalledWith(userProfileUri, "telegram_12345", 3000);
+ expect(client.read).toHaveBeenCalledWith(peerProfileUri, "telegram_12345", 3000);
+ expect(result.systemPromptAddition).toContain("Basalt-x");
+ expect(result.systemPromptAddition).toContain(`<user-profile uri="${peerProfileUri}">`);
+ expect(result.systemPromptAddition).toContain("Timezone: UTC+8");
+ });
+
+ it("bounds the profile read by the auto-recall timeout", async () => {
+ const { engine, client } = makeEngine(undefined, { cfgOverrides: { autoRecall: true, autoRecallTimeoutMs: 1000 } });
+ mockProfile(client);
+ await engine.assemble({ sessionId: "session", messages: [], prompt: "hi" });
+ expect(client.read).toHaveBeenCalledWith(userProfileUri, undefined, 1000);
+ });
+
+ it("warns when the profile read fails for a reason other than a missing file", async () => {
+ const { engine, client, logger } = makeEngine(undefined, { cfgOverrides: { autoRecall: true } });
+ mockRecall(client);
+ client.read.mockRejectedValue(new Error("OpenViking request failed [PERMISSION_DENIED]: forbidden"));
+ const result = await engine.assemble({ sessionId: "session", messages: [], prompt });
+ expect(result.systemPromptAddition).toContain(memory);
+ expect(logger.warn).toHaveBeenCalledWith(expect.stringContaining(`profile read failed (uri=${userProfileUri})`));
+ expect(logger.warn).toHaveBeenCalledWith(expect.stringContaining("PERMISSION_DENIED"));
+
+ logger.warn.mockClear();
+ mockProfile(client, {});
+ await engine.assemble({ sessionId: "session", messages: [], prompt });
+ expect(logger.warn).not.toHaveBeenCalledWith(expect.stringContaining("profile read failed"));
+ });
+
+ it("caps a long profile", async () => {
+ const { engine, client } = makeEngine(undefined, { cfgOverrides: { autoRecall: true } });
+ mockProfile(client, { [userProfileUri]: `${"x".repeat(9000)}TAIL` });
+ const result = await engine.assemble({ sessionId: "session", messages: [], prompt });
+ expect(result.systemPromptAddition).toContain("[profile truncated]");
+ expect(result.systemPromptAddition).not.toContain("TAIL");
+ });
+
+ it("drops recall before the profile when the budget is tight", async () => {
+ const { engine, client } = makeEngine(undefined, { cfgOverrides: { autoRecall: true } });
+ mockProfile(client);
+ const profileOnly = await engine.assemble({ sessionId: "session", messages: [], prompt });
+ mockRecall(client, "long recalled memory ".repeat(200));
+ const tight = await engine.assemble({ sessionId: "session", messages: [], prompt, tokenBudget: profileOnly.estimatedTokens });
+ expect(tight.systemPromptAddition).toBe(profileOnly.systemPromptAddition);
+ const tighter = await engine.assemble({ sessionId: "session", messages: [], prompt, tokenBudget: profileOnly.estimatedTokens - 1 });
+ expect(tighter.systemPromptAddition).toBeUndefined();
+ });
+
+ it("keeps recall when the profile alone does not fit the budget", async () => {
+ const { engine, client } = makeEngine(undefined, { cfgOverrides: { autoRecall: true } });
+ mockProfile(client, {});
+ mockRecall(client);
+ const recallOnly = await engine.assemble({ sessionId: "session", messages: [], prompt });
+ mockProfile(client, { [userProfileUri]: "画像".repeat(3950) });
+ const result = await engine.assemble({ sessionId: "session", messages: [], prompt, tokenBudget: recallOnly.estimatedTokens });
+ expect(result.systemPromptAddition).toBe(recallOnly.systemPromptAddition);
+ expect(result.systemPromptAddition).not.toContain("<user-profile");
+ });
+
+ it.each([
+ { name: "autoRecall off", cfgOverrides: { autoRecall: false }, sessionKey: undefined },
+ { name: "bypassed session", cfgOverrides: { autoRecall: true, bypassSessionPatterns: ["agent:*:cron:**"] }, sessionKey: "agent:main:cron:task" },
+ ])("does not read the profile when $name", async ({ cfgOverrides, sessionKey }) => {
+ const { engine, client } = makeEngine(undefined, { cfgOverrides });
+ mockProfile(client);
+ const result = await engine.assemble({ sessionId: "session", sessionKey, messages: [], prompt });
+ expect(client.read).not.toHaveBeenCalled();
+ expect(result.systemPromptAddition).toBeUndefined();
+ });
+
+ it("does not inject the profile during transformContext", async () => {
+ const { engine, client } = makeEngine(undefined, { cfgOverrides: { autoRecall: true } });
+ mockProfile(client);
+ const result = await engine.assemble({ sessionId: "session", messages: [{ role: "user", content: prompt }] });
+ expect(client.read.mock.calls.some(([uri]) => uri === userProfileUri)).toBe(false);
+ expect(JSON.stringify(result)).not.toContain("Basalt-x");
+ });
+
+ it("logs a missing OV session as skipped history, not a skipped assemble", async () => {
+ const { engine, client, logger } = makeEngine(undefined, { cfgOverrides: { autoRecall: true } });
+ client.getSessionContext.mockRejectedValue(new Error("[NOT_FOUND] Session not found"));
+ await engine.assemble({ sessionId: "new-session", messages: [], prompt });
+ const logged = logger.info.mock.calls.map(([line]) => String(line));
+ expect(logged.some((line) => line.includes("session history not assembled because OV session does not exist"))).toBe(true);
+ expect(logged.some((line) => line.includes("assemble skipped"))).toBe(false);
+ });
+ });
+
it("prepends auto-recall to the latest user message during transformContext", async () => {
const { engine, client } = makeEngine(
{