Skip to content

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

feat(plugins): add ov-usage cards showing OpenViking sources per answer (#5653)

Zayn Jarvisba7ca660ec6c
diff --git a/.claude-plugin/marketplace.json b/.claude-plugin/marketplace.json
index ed9ae6c1c..351d59855 100644
--- a/.claude-plugin/marketplace.json
+++ b/.claude-plugin/marketplace.json
@@ -15,6 +15,17 @@
"ref": "main"
},
"category": "productivity"
+ },
+ {
+ "name": "ov-usage",
+ "description": "Shows which OpenViking sources each Claude Code answer consulted, as a card under the answer",
+ "source": {
+ "source": "git-subdir",
+ "url": "https://github.com/volcengine/OpenViking.git",
+ "path": "examples/claude-code-usage-plugin",
+ "ref": "main"
+ },
+ "category": "productivity"
}
]
}
diff --git a/.github/scripts/check-plugin-version-bumps.sh b/.github/scripts/check-plugin-version-bumps.sh
index f2a62728b..6b60d129e 100755
--- a/.github/scripts/check-plugin-version-bumps.sh
+++ b/.github/scripts/check-plugin-version-bumps.sh
@@ -22,6 +22,7 @@ cd "$ROOT"
# <plugin directory>:<manifest holding the version>
PLUGINS=(
"examples/claude-code-memory-plugin:examples/claude-code-memory-plugin/.claude-plugin/plugin.json"
+ "examples/claude-code-usage-plugin:examples/claude-code-usage-plugin/.claude-plugin/plugin.json"
"examples/codex-memory-plugin:examples/codex-memory-plugin/.codex-plugin/plugin.json"
"examples/agent-hook-plugin:examples/agent-hook-plugin/plugin.json"
"examples/opencode-plugin:examples/opencode-plugin/package.json"
diff --git a/docs/en/agent-integrations/02-claude-code.md b/docs/en/agent-integrations/02-claude-code.md
index 30dc3413e..f075912c6 100644
--- a/docs/en/agent-integrations/02-claude-code.md
+++ b/docs/en/agent-integrations/02-claude-code.md
@@ -111,6 +111,16 @@ Change it with `OPENVIKING_PEER_SOURCE`, with `plugin.peerSource` in `ovcli.conf
The plugin renders an OpenViking status indicator beneath your Claude Code input box, allowing you to check connection health, recall count, capture progress, and session state at a glance. See [STATUSLINE.md](https://github.com/volcengine/OpenViking/blob/main/examples/claude-code-memory-plugin/STATUSLINE.md) for a complete glossary of segments and personalization recipes.
+## Optional: see what OpenViking contributed (OV-Usage)
+
+OV-Usage is a separate, opt-in plugin. It adds a card under each answer listing the OpenViking sources the answer used: what auto-recall added, and what Claude searched for and read on its own. The card is one line by default and expands to the full list. It needs Claude Code 2.1.286 or newer, and openviking-memory installed.
+
+```bash
+claude plugin install ov-usage@openviking
+```
+
+See the [OV-Usage README](https://github.com/volcengine/OpenViking/blob/main/examples/claude-code-usage-plugin/README.md) for details.
+
## Troubleshooting
| Issue | Cause | Solution |
diff --git a/docs/zh/agent-integrations/02-claude-code.md b/docs/zh/agent-integrations/02-claude-code.md
index d138ae0c4..ecf68498a 100644
--- a/docs/zh/agent-integrations/02-claude-code.md
+++ b/docs/zh/agent-integrations/02-claude-code.md
@@ -111,6 +111,16 @@ skill 清单就是 `<available-skills>` 块,列出存放在 OpenViking 中的
插件会在 Claude Code 的输入框下方显示一行 OpenViking 状态栏,用于指示:连接状态、召回条数、捕获进度以及当前会话状态。关于状态栏各部分的详细含义与自定义配置方法,请参阅 [STATUSLINE.md](https://github.com/volcengine/OpenViking/blob/main/examples/claude-code-memory-plugin/STATUSLINE.md)。
+## 可选:查看 OpenViking 的贡献(OV-Usage)
+
+OV-Usage 是一个独立的可选插件,在每次回答下方加一张卡片,列出这次回答用到的 OpenViking 来源:自动召回加入了什么,Claude 自己搜索、读取了什么。卡片默认只占一行,展开后显示完整列表。需要 Claude Code 2.1.286 或更高版本,并已安装 openviking-memory。
+
+```bash
+claude plugin install ov-usage@openviking
+```
+
+详见 [OV-Usage README](https://github.com/volcengine/OpenViking/blob/main/examples/claude-code-usage-plugin/README_CN.md)。
+
## 故障排查
| 现象 | 原因 | 修复 |
diff --git a/examples/claude-code-usage-plugin/.claude-plugin/plugin.json b/examples/claude-code-usage-plugin/.claude-plugin/plugin.json
new file mode 100644
index 000000000..fdc278a80
--- /dev/null
+++ b/examples/claude-code-usage-plugin/.claude-plugin/plugin.json
@@ -0,0 +1,13 @@
+{
+ "name": "ov-usage",
+ "version": "0.1.0",
+ "description": "Shows which OpenViking sources each Claude Code answer consulted, as a card under the answer",
+ "types": "./types/index.d.ts",
+ "author": {
+ "name": "OpenViking",
+ "url": "https://github.com/volcengine/OpenViking"
+ },
+ "repository": "https://github.com/volcengine/OpenViking",
+ "license": "Apache-2.0",
+ "keywords": ["openviking", "memory", "observability", "context-engine"]
+}
diff --git a/examples/claude-code-usage-plugin/.gitignore b/examples/claude-code-usage-plugin/.gitignore
new file mode 100644
index 000000000..6ba649ab4
--- /dev/null
+++ b/examples/claude-code-usage-plugin/.gitignore
@@ -0,0 +1,2 @@
+# Generated by Claude Code when it loads the plugin
+.claude-plugin/types/
diff --git a/examples/claude-code-usage-plugin/README.md b/examples/claude-code-usage-plugin/README.md
new file mode 100644
index 000000000..aa7590441
--- /dev/null
+++ b/examples/claude-code-usage-plugin/README.md
@@ -0,0 +1,61 @@
+# OV-Usage
+
+English / [中文](./README_CN.md)
+
+OV-Usage adds a card under each Claude Code answer that lists the OpenViking sources the answer used. That covers what auto-recall added to the prompt, plus what Claude searched for and read on its own.
+
+The card is collapsed by default, so it takes one line:
+
+```
+OV · 14 sources · 6 past events · 5 work memories · 2 team docs · 1 skill · 1 read in full [Expand]
+```
+
+Expand it to see every source and Claude's own lookups:
+
+```
+OV · 14 sources · … · 1 read in full [Collapse]
+ ◷ 10/3 发版检查清单补充 · found by Claude · read in full
+ ⚙ openviking-release · auto-recalled
+ ▤ lark-daemon · auto-recalled
+ …
+Claude's own lookups
+ ⌕ Searched “lark-daemon release” · 6 results
+ ▤ Read 10/3 发版检查清单补充
+```
+
+- Groups: ★ preferences, ◷ past events, ◆ work memories (notes, lessons, your agents' memories), ▤ team docs, ⚙ skills.
+- **read in full**: Claude opened the file with `read`, either through the MCP tool or `ov read`. A search hit doesn't count.
+- An answer that used nothing from OpenViking gets no card.
+
+Expand or collapse a card with its `[Expand]` / `[Collapse]` button. You can also expand or collapse every card with `/openviking-usage expand` or `/openviking-usage collapse`.
+
+Labels are in English only.
+
+## Requirements
+
+- Claude Code 2.1.286 or newer. The plugin uses Claude Code's plugin hooks (`hooks.json` with `modules`), which are still early access. Without them, the plugin installs but shows nothing.
+- The OpenViking memory plugin (`openviking-memory@openviking`).
+
+## Install
+
+```bash
+claude plugin marketplace add https://raw.githubusercontent.com/volcengine/OpenViking/main/.claude-plugin/marketplace.json
+claude plugin install ov-usage@openviking
+```
+
+If you already added the marketplace, run `claude plugin marketplace update openviking` first. Then start a new session.
+
+## What it reads and stores
+
+- **Auto-recall**: the `<openviking-context>` block that openviking-memory's `UserPromptSubmit` hook adds to the prompt. OV-Usage reads the `uri` and `score` of each `<memory>` item, or the `viking://` URI on each line of the digest form. It reads no openviking-memory files or config. If openviking-memory changes this block's format, auto-recalled items stop showing.
+- **Claude's lookups**: OpenViking MCP tool calls (`read`, `search`, `find`, `grep`, `glob`, `list`, `tree`) and `ov` CLI calls through Bash (`read`, `cat`, `abstract`, `overview`, `find`, `search`, `grep`, `glob`, `ls`, `tree`). Writes and other commands are ignored.
+- **Stored** in Claude Code's plugin store, for the last 20 sessions: each answer's source URIs and scores, search queries (redacted, first 80 characters), and the transcript row id each card belongs to. That keeps cards in place after `claude --continue`. Shell commands and prompt text are not stored.
+
+The plugin makes no network calls and writes nothing to OpenViking. The card isn't sent to Claude, so it costs no tokens.
+
+## Development
+
+- `hooks/register.tsx`: the hooks and the card.
+- `hooks/sources.ts`: pure parsing: recall blocks, URIs in tool output, which tool calls are lookups, and what an answer consulted.
+- `tests/`: `claude plugin test examples/claude-code-usage-plugin`. These run on Claude Code's plugin test runner, not in the repository's Node CI.
+- `claude plugin validate examples/claude-code-usage-plugin` checks the plugin. After `claude --plugin-dir examples/claude-code-usage-plugin` has generated `.claude-plugin/types/`, `tsc -p examples/claude-code-usage-plugin` type-checks it.
diff --git a/examples/claude-code-usage-plugin/README_CN.md b/examples/claude-code-usage-plugin/README_CN.md
new file mode 100644
index 000000000..e01ade8a4
--- /dev/null
+++ b/examples/claude-code-usage-plugin/README_CN.md
@@ -0,0 +1,61 @@
+# OV-Usage
+
+[English](./README.md) / 中文
+
+OV-Usage 在 Claude Code 每次回答下方加一张卡片,列出这次回答用到的 OpenViking 来源,包括自动召回加进提示的内容,以及 Claude 自己搜索、读取的内容。
+
+卡片默认折叠,只占一行:
+
+```
+OV · 14 sources · 6 past events · 5 work memories · 2 team docs · 1 skill · 1 read in full [Expand]
+```
+
+展开后列出全部来源和 Claude 自己的查询:
+
+```
+OV · 14 sources · … · 1 read in full [Collapse]
+ ◷ 10/3 发版检查清单补充 · found by Claude · read in full
+ ⚙ openviking-release · auto-recalled
+ ▤ lark-daemon · auto-recalled
+ …
+Claude's own lookups
+ ⌕ Searched “lark-daemon release” · 6 results
+ ▤ Read 10/3 发版检查清单补充
+```
+
+- 分组:★ 偏好,◷ 过往事件,◆ 工作记忆(笔记、经验、你的 agent 的记忆),▤ 团队文档,⚙ Skill。
+- **read in full**:Claude 用 `read`(MCP 工具或 `ov read`)打开了这个文件。只出现在搜索结果里的不算。
+- 没用到任何 OpenViking 内容的回答不显示卡片。
+
+用卡片上的 `[Expand]` / `[Collapse]` 按钮展开或折叠单张卡片;也可以用 `/openviking-usage expand` 或 `/openviking-usage collapse` 一次展开或折叠全部卡片。
+
+界面文字只有英文。
+
+## 前提
+
+- Claude Code 2.1.286 或更高版本。插件依赖 Claude Code 的插件 hooks(`hooks.json` 里的 `modules`),目前仍是 early access。没有这个能力时,插件能装上,但不显示任何内容。
+- 已安装 OpenViking 记忆插件(`openviking-memory@openviking`)。
+
+## 安装
+
+```bash
+claude plugin marketplace add https://raw.githubusercontent.com/volcengine/OpenViking/main/.claude-plugin/marketplace.json
+claude plugin install ov-usage@openviking
+```
+
+如果之前已经添加过这个 marketplace,先运行 `claude plugin marketplace update openviking`。装好后开一个新会话。
+
+## 读取和保存的内容
+
+- **自动召回**:openviking-memory 的 `UserPromptSubmit` hook 加进提示的 `<openviking-context>` 块。读取每个 `<memory>` 的 `uri` 和 `score`;digest 格式则读取每行里的 `viking://` URI。不读 openviking-memory 的任何文件或配置。如果 openviking-memory 改了这个块的格式,自动召回的条目就不会再显示。
+- **Claude 的查询**:OpenViking MCP 工具调用(`read`、`search`、`find`、`grep`、`glob`、`list`、`tree`),以及通过 Bash 调用的 `ov` CLI(`read`、`cat`、`abstract`、`overview`、`find`、`search`、`grep`、`glob`、`ls`、`tree`)。写入和其他命令不计入。
+- **保存**在 Claude Code 的插件存储里,保留最近 20 个会话:每次回答的来源 URI 和分数、搜索词(已脱敏,最多 80 字符)、卡片所在的对话行 id,这样 `claude --continue` 之后卡片还在原位。不保存 shell 命令和提示原文。
+
+插件不发网络请求,不向 OpenViking 写任何内容。卡片不会发给 Claude,不消耗 token。
+
+## 开发
+
+- `hooks/register.tsx`:hooks 和卡片。
+- `hooks/sources.ts`:纯解析逻辑,包括召回块、工具输出里的 URI、哪些工具调用算查询,以及一次回答用到了什么。
+- `tests/`:`claude plugin test examples/claude-code-usage-plugin`。这些测试跑在 Claude Code 的插件测试器上,不在仓库的 Node CI 里。
+- `claude plugin validate examples/claude-code-usage-plugin` 校验插件。用 `claude --plugin-dir examples/claude-code-usage-plugin` 启动一次、生成 `.claude-plugin/types/` 后,可以用 `tsc -p examples/claude-code-usage-plugin` 做类型检查。
diff --git a/examples/claude-code-usage-plugin/hooks/hooks.json b/examples/claude-code-usage-plugin/hooks/hooks.json
new file mode 100644
index 000000000..5a63f6495
--- /dev/null
+++ b/examples/claude-code-usage-plugin/hooks/hooks.json
@@ -0,0 +1 @@
+{ "modules": ["./register.tsx"] }
diff --git a/examples/claude-code-usage-plugin/hooks/register.tsx b/examples/claude-code-usage-plugin/hooks/register.tsx
new file mode 100644
index 000000000..74ec8ac57
--- /dev/null
+++ b/examples/claude-code-usage-plugin/hooks/register.tsx
@@ -0,0 +1,223 @@
+import type { EngineInterface, Register, ResolveInput } from "claude-code";
+import type { Lookup, Turn } from "../types";
+import {
+ ICON,
+ classifyCall,
+ consulted,
+ groupOf,
+ parseRecall,
+ summaryLine,
+ titleOf,
+ urisIn,
+} from "./sources";
+
+const turnsRef = { plugin: "ov-usage", key: "turns" } as const;
+const repliesRef = { plugin: "ov-usage", key: "replies" } as const;
+const expandedRef = { plugin: "ov-usage", key: "expanded" } as const;
+
+const MAX_TURNS = 50;
+const MAX_SESSIONS = 20;
+const ACCENT = "cyan";
+
+// Read, change, write back against the version read: tool calls run in parallel.
+async function editTurns($: EngineInterface, fn: (turns: Turn[]) => Turn[]) {
+ for (let i = 0; i < 10; i++) {
+ const held = await $.state.get(turnsRef);
+ const { isSet } = await $.state.set(turnsRef, fn(held.value ?? []), {
+ ifVersion: held.version,
+ });
+ if (isSet) return;
+ }
+}
+
+async function lastTurn($: EngineInterface): Promise<Turn | undefined> {
+ const { value = [] } = await $.state.get(turnsRef);
+ return value.at(-1);
+}
+
+// $.state is lost when the process restarts; $.store keeps each session's cards
+// so `claude --continue` draws them again.
+async function save($: EngineInterface) {
+ const id = await $.session.id();
+ if (!id) return;
+ await $.store.set(`session:${id}`, {
+ turns: (await $.state.get(turnsRef)).value ?? [],
+ replies: (await $.state.get(repliesRef)).value ?? [],
+ expanded: (await $.state.get(expandedRef)).value ?? [],
+ });
+ const index = ((await $.store.get("sessions")) as string[] | undefined) ?? [];
+ const next = [...index.filter((k) => k !== id), id];
+ for (const old of next.slice(0, -MAX_SESSIONS)) await $.store.delete(`session:${old}`);
+ await $.store.set("sessions", next.slice(-MAX_SESSIONS));
+}
+
+async function restore($: EngineInterface) {
+ if ((await $.state.get(turnsRef)).value?.length) return; // a hot reload keeps $.state
+ const id = await $.session.id();
+ const snap = id
+ ? ((await $.store.get(`session:${id}`)) as Record<string, never> | undefined)
+ : undefined;
+ if (!snap) return;
+ await $.state.set(turnsRef, snap.turns ?? []);
+ await $.state.set(repliesRef, snap.replies ?? []);
+ await $.state.set(expandedRef, snap.expanded ?? []);
+}
+
+async function setExpanded($: EngineInterface, n: number | "all", isOpen: boolean) {
+ const { value: turns = [] } = await $.state.get(turnsRef);
+ const { value: list = [] } = await $.state.get(expandedRef);
+ const which = n === "all" ? turns.map((t) => t.n) : [n];
+ await $.state.set(
+ expandedRef,
+ isOpen ? [...new Set([...list, ...which])] : list.filter((x) => !which.includes(x)),
+ );
+ await save($);
+}
+
+// The card under an answer: one line of totals, or that line plus every source
+// and Claude's own lookups. Nothing when the answer drew on nothing.
+async function card($: EngineInterface, e: ResolveInput, turn: Turn) {
+ const { Box, Text, Button } = $.ui.resolve(e);
+ const c = consulted(turn);
+ const lookups = turn.lookups;
+ if (c.rows.length === 0 && lookups.length === 0) return null;
+ const { value: expanded = [] } = await $.state.get(expandedRef);
+ const isOpen = expanded.includes(turn.n);
+ return (
+ <Box flexDirection="column" marginLeft={2} marginTop={1}>
+ <Box flexWrap="wrap" columnGap={2}>
+ <Text color={ACCENT} wrap="wrap">
+ {summaryLine(c)}
+ </Text>
+ <Button
+ key={`ov-toggle-${turn.n}`}
+ label={isOpen ? "[Collapse]" : "[Expand]"}
+ plain
+ onPress={() => setExpanded($, turn.n, !isOpen)}
+ />
+ </Box>
+ {isOpen &&
+ c.rows.map((r) => (
+ <Text key={`ov-src-${turn.n}-${r.uri}`} wrap="wrap">
+ {" "}
+ {ICON[groupOf(r.uri)]} {titleOf(r.uri)}
+ <Text dimColor>
+ {r.from === "recall"
+ ? ` · auto-recalled${r.score > 0 ? ` ${r.score.toFixed(2)}` : ""}`
+ : " · found by Claude"}
+ {r.isOpened ? " · read in full" : ""}
+ </Text>
+ </Text>
+ ))}
+ {isOpen && lookups.length > 0 && <Text bold>Claude's own lookups</Text>}
+ {isOpen &&
+ lookups.map((l) => (
+ <Text key={`ov-lookup-${l.id}`} wrap="wrap">
+ {" "}
+ {l.query !== null ? `⌕ Searched “${l.query}” · ${l.found.length} results` : ""}
+ {l.query !== null && l.opened.length ? " · " : ""}
+ {l.opened.length ? `▤ Read ${l.opened.map(titleOf).join(", ")}` : ""}
+ {l.isError && <Text color="red"> · failed</Text>}
+ </Text>
+ ))}
+ </Box>
+ );
+}
+
+export const register: Register = (on) => {
+ on("session.start", async ($, e, next) => {
+ await restore($);
+ await $.command.register({
+ name: "openviking-usage",
+ description: "Expand or collapse the OpenViking cards under answers",
+ argumentHint: "expand | collapse",
+ });
+ return next(e);
+ });
+
+ on("command.run", { command: "openviking-usage" }, async ($, e) => {
+ const verb = e.args.trim().toLowerCase();
+ if (verb === "expand" || verb === "collapse") {
+ await setExpanded($, "all", verb === "expand");
+ return {};
+ }
+ return { text: "Usage: /openviking-usage expand | collapse" };
+ });
+
+ // Each prompt starts an answer; openviking-memory's recall block says what it injected.
+ on("classic.UserPromptSubmit", async ($, e, next) => {
+ const res = await next(e);
+ const block = (res.additionalContext ?? []).find(
+ (c) =>
+ c.includes("<openviking-context") &&
+ !/source="(startup|resume|compact|skill-experience)"/.test(c),
+ );
+ const prev = await lastTurn($);
+ const turn: Turn = {
+ n: (prev?.n ?? 0) + 1,
+ recalled: block ? parseRecall(block) : [],
+ lookups: [],
+ };
+ await editTurns($, (list) => [...list, turn].slice(-MAX_TURNS));
+ await save($);
+ return res;
+ });
+
+ // Claude's own OpenViking reads and searches, through MCP or the `ov` CLI.
+ on("tool.call", async ($, e, next) => {
+ const call = classifyCall(e.tool, { ...e } as Record<string, unknown>);
+ const turn = call ? await lastTurn($) : undefined;
+ if (!call || !turn) return next(e);
+ const ran = await next(e);
+ const text = "text" in ran && typeof ran.text === "string" ? ran.text : "";
+ const lookup: Lookup = {
+ id: e.tool_use_id,
+ query: call.query,
+ opened: call.opened,
+ found: call.query !== null ? urisIn(text).filter((u) => !call.opened.includes(u)) : [],
+ isError: ran.deny !== undefined || ran.isError === true,
+ };
+ await editTurns($, (list) =>
+ list.map((t) => (t.n === turn.n ? { ...t, lookups: [...t.lookups, lookup] } : t)),
+ );
+ return ran;
+ });
+
+ // The last text row of an answer carries its card.
+ on("session.append", async ($, e, next) => {
+ const res = await next(e);
+ if (res.deny !== undefined || e.agentId || e.door !== "response") return res;
+ const hasText = (res.message.content ?? []).some(
+ (b) => b && typeof b === "object" && "type" in b && b.type === "text",
+ );
+ const turn = hasText ? await lastTurn($) : undefined;
+ if (turn) {
+ const { value: list = [] } = await $.state.get(repliesRef);
+ const kept = [...list.filter((r) => r.n !== turn.n), { id: res.uuid, n: turn.n }];
+ await $.state.set(repliesRef, kept.slice(-MAX_TURNS));
+ }
+ return res;
+ });
+
+ on("turn.complete", async ($, e, next) => {
+ const done = await next(e);
+ await save($);
+ return done;
+ });
+
+ on("ui.render", { component: "AssistantMessage" }, async ($, e, next) => {
+ const { value: replies = [] } = await $.state.get(repliesRef);
+ const n = replies.find((r) => r.id === e.requestId)?.n;
+ const { value: turns = [] } = await $.state.get(turnsRef);
+ const turn = n === undefined ? undefined : turns.find((t) => t.n === n);
+ const below = turn ? await card($, e, turn) : null;
+ if (!below) return next(e);
+ const { Box } = $.ui.resolve(e);
+ return (
+ <Box flexDirection="column">
+ {await next(e)}
+ {below}
+ </Box>
+ );
+ });
+};
diff --git a/examples/claude-code-usage-plugin/hooks/sources.ts b/examples/claude-code-usage-plugin/hooks/sources.ts
new file mode 100644
index 000000000..255675f6c
--- /dev/null
+++ b/examples/claude-code-usage-plugin/hooks/sources.ts
@@ -0,0 +1,193 @@
+// Pure helpers: which viking:// URIs a recall block or a tool call names, which
+// tool calls are OpenViking lookups, and what one answer consulted.
+
+import type { Lookup, Turn } from "../types";
+
+// A viking:// URI stops at whitespace, quotes, brackets or CJK punctuation.
+const URI = /viking:\/\/(?:~|[A-Za-z][\w.-]*)(?:\/[^\s"'<>)\]`,,。;:!?、()《》“”]*)?/g;
+
+// Top-level directories: a URI ending in one of them is a directory, not a source.
+const DIRS = new Set(["resources", "user", "agent", "session", "memories", "skills", "peers"]);
+
+// A URI that names something an answer could draw on, not a scope or directory.
+export function isSource(uri: string): boolean {
+ if (uri.endsWith("/")) return false;
+ const parts = uri.slice("viking://".length).split("/").filter(Boolean);
+ return parts.length >= 2 && !DIRS.has(parts.at(-1) ?? "");
+}
+
+// The source URIs a tool's output names, in order. The `ov` CLI wraps a long URI
+// onto the next line at the same indent; that continuation is joined back.
+export function urisIn(text: string): string[] {
+ const lines = text.split("\n");
+ const found: string[] = [];
+ for (let i = 0; i < lines.length; i++) {
+ const line = lines[i] ?? "";
+ const whole = /^(\s*)(viking:\/\/\S+)\s*$/.exec(line);
+ const next = lines[i + 1] ?? "";
+ if (whole && !/\.\w{1,5}$/.test(whole[2] ?? "")) {
+ const tail = new RegExp(`^${whole[1]}(\\S+\\.\\w{1,5})\\s*$`).exec(next);
+ if (tail && !/^[#*-]/.test(tail[1] ?? "")) {
+ found.push(`${whole[2]}${tail[1]}`);
+ i++;
+ continue;
+ }
+ }
+ found.push(...(line.match(URI) ?? []));
+ }
+ return [...new Set(found)].filter(isSource);
+}
+
+export type Recalled = { uri: string; score: number };
+
+// What auto-recall injected for a prompt: <memory uri score> items, or the
+// digest form's "- summary 来源:viking://..." lines.
+export function parseRecall(text: string): Recalled[] {
+ const items: Recalled[] = [];
+ for (const m of text.matchAll(/<memory\s([^>]*?)\/?>/g)) {
+ const uri = /uri="([^"]+)"/.exec(m[1] ?? "")?.[1];
+ if (uri) items.push({ uri, score: Number(/score="([\d.]+)"/.exec(m[1] ?? "")?.[1] ?? 0) });
+ }
+ if (!items.length) {
+ for (const line of text.split("\n")) {
+ const uri = /^\s*-/.test(line) ? line.match(URI)?.[0] : undefined;
+ if (uri) items.push({ uri, score: 0 });
+ }
+ }
+ const seen = new Set<string>();
+ return items.filter((it) => isSource(it.uri) && !seen.has(it.uri) && !!seen.add(it.uri));
+}
+
+// Secrets never reach storage: JWT-like tokens, Bearer headers, sk- keys, key=value.
+export function redact(text: string): string {
+ return text
+ .replace(/[A-Za-z0-9_-]{6,}\.[A-Za-z0-9_-]{4,}\.[A-Za-z0-9_-]{40,}/g, "[REDACTED]")
+ .replace(/Bearer\s+[A-Za-z0-9._~+/-]{16,}/gi, "Bearer [REDACTED]")
+ .replace(/sk-[A-Za-z0-9_-]{20,}/g, "[REDACTED]")
+ .replace(
+ /((?:api[_-]?key|token|secret|password|authorization)["']?\s*[:=]\s*["']?|--(?:api-key|token|password)[=\s]+)[^\s"',;&|]+/gi,
+ "$1[REDACTED]",
+ );
+}
+
+const MCP_TOOL = /^mcp__.*openviking.*__(\w+)$/;
+const MCP_SEARCH = new Set(["search", "find", "grep", "glob", "list", "tree"]);
+
+// `ov` CLI subcommands that open the files they name, and those that list matches.
+const CLI_READ = new Set(["read", "cat", "abstract", "overview"]);
+const CLI_SEARCH = new Set(["find", "search", "grep", "glob", "ls", "tree"]);
+
+// One `ov` / `openviking` invocation at the start of a command or after ; & | (
+const CLI_CALL = /(?:^|[;&|(]\s*)(?:\S+=\S+\s+)*(?:ov|openviking)\s+([a-z][\w-]*)([^;&|\n]*)/g;
+
+// How one tool call reads OpenViking: the URIs it opens in full, and what it
+// searched for. Null when the call is not an OpenViking lookup (writes and
+// status checks included). A shell command itself is never kept.
+export function classifyCall(
+ tool: string,
+ input: Record<string, unknown>,
+): { opened: string[]; query: string | null } | null {
+ const mcp = MCP_TOOL.exec(tool)?.[1];
+ if (mcp === "read") {
+ const raw = Array.isArray(input.uris)
+ ? input.uris.join(" ")
+ : String(input.uri ?? input.uris ?? "");
+ return { opened: (raw.match(URI) ?? []).filter(isSource), query: null };
+ }
+ if (mcp && MCP_SEARCH.has(mcp)) {
+ const q = input.query ?? input.pattern ?? input.uri ?? input.path ?? "";
+ return { opened: [], query: redact(String(q)).slice(0, 80) };
+ }
+ if (tool !== "Bash" || typeof input.command !== "string") return null;
+ const opened: string[] = [];
+ let query: string | null = null;
+ for (const m of input.command.matchAll(CLI_CALL)) {
+ const sub = m[1] ?? "";
+ const rest = m[2] ?? "";
+ if (CLI_READ.has(sub)) opened.push(...(rest.match(URI) ?? []).filter(isSource));
+ else if (CLI_SEARCH.has(sub) && query === null) {
+ const quoted = /["']([^"']+)["']/.exec(rest)?.[1];
+ const words = rest.replace(/\s-{1,2}\w[\w-]*(?:[=\s]\S+)?/g, " ").replace(/\s\d?>.*$/, "");
+ query = redact((quoted ?? words).trim()).slice(0, 80);
+ }
+ }
+ return opened.length || query !== null ? { opened: [...new Set(opened)], query } : null;
+}
+
+export type Group = "prefs" | "history" | "work" | "docs" | "skill";
+
+// What a source is to the person, from where it lives.
+export function groupOf(uri: string): Group {
+ if (/^viking:\/\/user\/[^/]+\/memories\/(preferences|profile|identity|soul)/.test(uri))
+ return "prefs";
+ if (/\/memories\/events\//.test(uri)) return "history";
+ if (/\/skills?\//.test(uri)) return "skill";
+ if (/^viking:\/\/user\/[^/]+\/(memories|peers)\//.test(uri)) return "work";
+ return "docs";
+}
+
+export const ICON: Record<Group, string> = {
+ prefs: "★",
+ history: "◷",
+ work: "◆",
+ docs: "▤",
+ skill: "⚙",
+};
+
+const NOUN: Record<Group, [string, string]> = {
+ prefs: ["preference", "preferences"],
+ history: ["past event", "past events"],
+ work: ["work memory", "work memories"],
+ docs: ["team doc", "team docs"],
+ skill: ["skill", "skills"],
+};
+
+const plural = (n: number, [one, many]: [string, string]) => `${n} ${n === 1 ? one : many}`;
+
+// A short name for a source: its file name, with the date of a dated event.
+export function titleOf(uri: string): string {
+ const parts = decodeURIComponent(uri).split("/").filter(Boolean);
+ let name = (parts.at(-1) ?? uri).replace(/\.md$/, "");
+ if (/^(\.|summary$|index$|prompts$)/i.test(name)) name = `${parts.at(-2) ?? ""}/${name}`;
+ const d = /\/(\d{4})\/(\d{2})\/(\d{2})\//.exec(uri);
+ return d ? `${Number(d[2])}/${Number(d[3])} ${name}` : name;
+}
+
+export type Row = { uri: string; from: "recall" | "lookup"; score: number; isOpened: boolean };
+
+// What one answer consulted: auto-recall's items and what Claude's own reads and
+// searches returned, files Claude opened first, then by recall score.
+export function consulted(turn: Turn) {
+ const opened = new Set(turn.lookups.flatMap((l: Lookup) => (l.isError ? [] : l.opened)));
+ const rows = new Map<string, Row>();
+ for (const it of turn.recalled)
+ rows.set(it.uri, { uri: it.uri, from: "recall", score: it.score, isOpened: false });
+ for (const l of turn.lookups) {
+ if (l.isError) continue;
+ for (const uri of [...l.opened, ...l.found]) {
+ if (!rows.has(uri)) rows.set(uri, { uri, from: "lookup", score: 0, isOpened: false });
+ }
+ }
+ for (const r of rows.values()) r.isOpened = opened.has(r.uri);
+ const list = [...rows.values()].sort(
+ (a, b) => Number(b.isOpened) - Number(a.isOpened) || b.score - a.score,
+ );
+ const byGroup: Record<Group, number> = { prefs: 0, history: 0, work: 0, docs: 0, skill: 0 };
+ for (const r of list) byGroup[groupOf(r.uri)] += 1;
+ return { rows: list, byGroup, readInFull: list.filter((r) => r.isOpened).length };
+}
+
+// The collapsed card: "OV · 8 sources · 4 past events · 3 work memories · 1 read in full".
+export function summaryLine(c: ReturnType<typeof consulted>): string {
+ const groups = (Object.keys(NOUN) as Group[])
+ .filter((g) => c.byGroup[g] > 0)
+ .map((g) => plural(c.byGroup[g], NOUN[g]));
+ return [
+ "OV",
+ plural(c.rows.length, ["source", "sources"]),
+ ...groups,
+ c.readInFull ? `${c.readInFull} read in full` : "",
+ ]
+ .filter(Boolean)
+ .join(" · ");
+}
diff --git a/examples/claude-code-usage-plugin/package.json b/examples/claude-code-usage-plugin/package.json
new file mode 100644
index 000000000..66f8f0e98
--- /dev/null
+++ b/examples/claude-code-usage-plugin/package.json
@@ -0,0 +1,11 @@
+{
+ "name": "ov-usage",
+ "private": true,
+ "description": "Opt-in Claude Code plugin showing which OpenViking sources each answer consulted",
+ "license": "Apache-2.0",
+ "scripts": {
+ "check": "claude plugin validate . && tsc -p .",
+ "format": "prettier --no-config --print-width 100 --write \"hooks/*.ts\" \"hooks/*.tsx\" \"tests/*.ts\" \"types/*.ts\"",
+ "test": "claude plugin test ."
+ }
+}
diff --git a/examples/claude-code-usage-plugin/tests/sources.test.ts b/examples/claude-code-usage-plugin/tests/sources.test.ts
new file mode 100644
index 000000000..ca005dd32
--- /dev/null
+++ b/examples/claude-code-usage-plugin/tests/sources.test.ts
@@ -0,0 +1,91 @@
+import { describe, expect, test } from "claude-code/testing";
+import {
+ classifyCall,
+ consulted,
+ parseRecall,
+ redact,
+ summaryLine,
+ titleOf,
+ urisIn,
+} from "../hooks/sources";
+
+const EVENT = "viking://user/t/memories/events/2026/10/03/web版本未更新排查请求.md";
+const PREF = "viking://user/t/memories/preferences/me/按钮状态.md";
+const DOC = "viking://resources/team/release-checklist.md";
+
+describe("recall", () => {
+ test("memory items and the digest form, without directories or repeats", () => {
+ const block = `<openviking-context>
+<memory uri="${PREF}" score="0.62" detail="abstract">- x</memory>
+<memory uri="${DOC}" score="0.31" detail="uri" />
+<memory uri="viking://resources/" score="0.9" />
+</openviking-context>`;
+ expect(parseRecall(block)).toEqual([
+ { uri: PREF, score: 0.62 },
+ { uri: DOC, score: 0.31 },
+ ]);
+ expect(parseRecall(`- 发布流程 来源:${DOC}\n- 同上 来源:${DOC}`)).toEqual([
+ { uri: DOC, score: 0 },
+ ]);
+ });
+});
+
+describe("tool calls", () => {
+ test("ov find is a search, ov read opens files, writes and other commands are not lookups", () => {
+ expect(
+ classifyCall("Bash", {
+ command: `ls ~/.openviking; ov find "lark web port" -n 3 2>&1 | head`,
+ }),
+ ).toEqual({
+ opened: [],
+ query: "lark web port",
+ });
+ expect(classifyCall("Bash", { command: `ov read ${DOC}` })).toEqual({
+ opened: [DOC],
+ query: null,
+ });
+ expect(classifyCall("Bash", { command: `ov add-memory "x"` })).toBeNull();
+ expect(classifyCall("Bash", { command: `echo ${DOC} >> notes.md` })).toBeNull();
+ const mcp = "mcp__plugin_openviking-memory_openviking__";
+ expect(classifyCall(`${mcp}read`, { uris: [DOC] })).toEqual({ opened: [DOC], query: null });
+ expect(classifyCall(`${mcp}search`, { query: "api_key=abc123 release" })).toEqual({
+ opened: [],
+ query: "api_key=[REDACTED] release",
+ });
+ expect(classifyCall(`${mcp}remember`, { text: "x" })).toBeNull();
+ });
+
+ test("output URIs: wrapped CLI lines are joined, scopes and directories dropped", () => {
+ const out = `1. memory · score 0.43
+ viking://user/t/memories/events/2026/10/03/web版本
+ 未更新排查请求.md
+ see viking://resources and viking://resources/team/
+2. ${DOC}`;
+ expect(urisIn(out)).toEqual([EVENT, DOC]);
+ });
+});
+
+describe("one answer", () => {
+ test("search hits are not read in full; reads are; failed lookups count nothing", () => {
+ const c = consulted({
+ n: 1,
+ recalled: [{ uri: PREF, score: 0.62 }],
+ lookups: [
+ { id: "a", query: "release", opened: [], found: [DOC, EVENT], isError: false },
+ { id: "b", query: null, opened: [EVENT], found: [], isError: false },
+ { id: "c", query: "x", opened: [], found: ["viking://resources/other.md"], isError: true },
+ ],
+ });
+ expect(c.rows.map((r) => r.uri)).toEqual([EVENT, PREF, DOC]);
+ expect(summaryLine(c)).toBe(
+ "OV · 3 sources · 1 preference · 1 past event · 1 team doc · 1 read in full",
+ );
+ expect(titleOf(EVENT)).toBe("10/3 web版本未更新排查请求");
+ });
+
+ test("secrets are redacted", () => {
+ expect(redact("Bearer abcdefghijklmnopqrstuvwxyz sk-abcdefghijklmnopqrstuvwx")).toBe(
+ "Bearer [REDACTED] [REDACTED]",
+ );
+ });
+});
diff --git a/examples/claude-code-usage-plugin/tsconfig.json b/examples/claude-code-usage-plugin/tsconfig.json
new file mode 100644
index 000000000..8681ec01d
--- /dev/null
+++ b/examples/claude-code-usage-plugin/tsconfig.json
@@ -0,0 +1,3 @@
+{
+ "extends": "./.claude-plugin/types/tsconfig.json"
+}
diff --git a/examples/claude-code-usage-plugin/types/index.d.ts b/examples/claude-code-usage-plugin/types/index.d.ts
new file mode 100644
index 000000000..ecefaa8c0
--- /dev/null
+++ b/examples/claude-code-usage-plugin/types/index.d.ts
@@ -0,0 +1,31 @@
+// One OpenViking lookup Claude made while answering. opened: files it read in
+// full; found: what a search returned; query: what it searched for (null for a read).
+export type Lookup = {
+ id: string;
+ query: string | null;
+ opened: string[];
+ found: string[];
+ isError: boolean;
+};
+
+// One answer: what auto-recall injected for its prompt, and Claude's own lookups.
+export type Turn = {
+ n: number;
+ recalled: { uri: string; score: number }[];
+ lookups: Lookup[];
+};
+
+// The transcript row an answer's card is drawn under, by its row id.
+export type Reply = { id: string; n: number };
+
+declare module "claude-code" {
+ interface PluginState {
+ "ov-usage": {
+ // this session's answers, oldest first (last 50)
+ turns: Turn[];
+ replies: Reply[];
+ // answers whose card is expanded
+ expanded: number[];
+ };
+ }
+}