Self-evolving Context Database for AI Agents. Unify Agent Memory, Knowledge RAG and Skills.
Python agent-contextagent-memoryagent-pluginsagentic-ragcontext-databasedsh-pluginknowledge-basememorymemory-managementself-evolvingvector-database
feat(claude-code-plugin): OpenViking statusline (opt-in) (#1890)
t0saki268147d11089
diff --git a/docs/en/agent-integrations/02-claude-code.md b/docs/en/agent-integrations/02-claude-code.mdindex 8378067e0..c54e4470d 100644--- a/docs/en/agent-integrations/02-claude-code.md+++ b/docs/en/agent-integrations/02-claude-code.md@@ -124,6 +124,25 @@ OPENVIKING_BYPASS_SESSION=1 claudeWhen bypass is active, every hook approves immediately without contacting OpenViking.+## Statusline++The plugin also renders a one-line OpenViking status under your Claude Code input box. The installer registers it in `~/.claude/settings.json` (CC's plugin manifest doesn't accept a `statusLine` field, so it has to live in user settings).++```text+OV ✓ │ ↩ 6 mem (0.92) · 50ms last turn injected 6 memories, top score 0.92+OV ⚠ slow probe missed the 1 s budget (server may be lagging)+OV ✗ offline server unreachable+OV ⚡ bypass OPENVIKING_BYPASS_SESSION* matched+OV ✓ │ ✎ 573/20k · 2 arch pending capture, two archives produced this session+OV ✓ │ 🔗 resumed │ +3 today session re-hydrated; 3 archives committed today+```++The hook scripts write small JSON snapshots to `~/.openviking/state/`; the statusline script reads those plus a 5 s shared cache of `GET /health`. The probe is bounded by a 1 s hard timeout; the cache is shared across sessions to prevent stampedes.++Set `OPENVIKING_STATUSLINE=off` to silence without removing the registration, or `jq 'del(.statusLine)' ~/.claude/settings.json` to remove. If you already had a custom statusline, the installer prompts replace / skip / manual compose.++For the full segment glossary (when each one shows, why one might be missing) and personalization recipes (hide segments, recolor, compose with another statusline, add a custom segment), see [`examples/claude-code-memory-plugin/STATUSLINE.md`](https://github.com/volcengine/OpenViking/blob/main/examples/claude-code-memory-plugin/STATUSLINE.md). The easiest path is to open Claude Code and ask it to read the doc, explain the segments, and tailor anything to your preference.+## Compared to Claude Code's built-in `MEMORY.md`This plugin **complements** Claude Code's native memory system, it doesn't replace it:diff --git a/docs/zh/agent-integrations/02-claude-code.md b/docs/zh/agent-integrations/02-claude-code.mdindex 0a5dd5a38..b098c68a8 100644--- a/docs/zh/agent-integrations/02-claude-code.md+++ b/docs/zh/agent-integrations/02-claude-code.md@@ -124,6 +124,25 @@ OPENVIKING_BYPASS_SESSION=1 claudebypass 启用时,所有 hook 立即返回 approve,不与 OpenViking 通信。+## Statusline 状态行++插件会在 Claude Code 输入框下方渲染一行 OpenViking 状态。安装脚本把它注册到 `~/.claude/settings.json`(CC 插件 manifest 不支持 `statusLine`,必须走用户 settings)。++```text+OV ✓ │ ↩ 6 mem (0.92) · 50ms 本轮注入 6 条记忆,最高分 0.92+OV ⚠ slow 探针超过 1s 预算(服务器可能在抽风)+OV ✗ offline 服务器不可达+OV ⚡ bypass 命中 OPENVIKING_BYPASS_SESSION*+OV ✓ │ ✎ 573/20k · 2 arch 待提交进度 + 本 session 已归档 2 次+OV ✓ │ 🔗 resumed │ +3 today session 已恢复上下文;今日累计归档 3 次+```++hook 脚本把每轮的小快照写到 `~/.openviking/state/`;statusline 脚本读快照,再加 5 秒共享缓存的 `GET /health`。探针 1s 硬超时,多 session 共享缓存避免风暴。++`OPENVIKING_STATUSLINE=off` 可静默不删;`jq 'del(.statusLine)' ~/.claude/settings.json` 彻底移除。已有自定义 statusline 时安装会询问替换 / 跳过 / 手动 compose。++完整的段位说明(每个 segment 何时出现、为什么有时不显示)以及个性化 recipe(隐藏段位、改色、与已有 statusline 组合、自定义段位),参见 [`examples/claude-code-memory-plugin/STATUSLINE.md`](https://github.com/volcengine/OpenViking/blob/main/examples/claude-code-memory-plugin/STATUSLINE.md)。最方便的方式是打开 Claude Code 把链接喂给它,让它读完文档既能解释你看到的内容,又能按你的偏好调整。+## 与 Claude Code 内置 `MEMORY.md` 的对比本插件**补充**Claude Code 原生记忆系统,不替代:diff --git a/examples/claude-code-memory-plugin/.claude-plugin/plugin.json b/examples/claude-code-memory-plugin/.claude-plugin/plugin.jsonindex fe96002bb..b6a897645 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.2.0",+ "version": "0.2.1","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/README.md b/examples/claude-code-memory-plugin/README.mdindex 29061b1d9..63b027363 100644--- a/examples/claude-code-memory-plugin/README.md+++ b/examples/claude-code-memory-plugin/README.md@@ -258,6 +258,36 @@ Defaults in `hooks/hooks.json`:Keep `claude_code.captureTimeoutMs` below the `Stop` timeout so the script can fail gracefully and still update its incremental state.+## Statusline++The plugin renders a one-line status of OpenViking under your Claude Code input box. The installer registers it in `~/.claude/settings.json` (CC's plugin manifest doesn't accept a `statusLine` field, so this is the only way to wire it in).++Examples:++```text+OV ✓ │ ↩ 6 mem (0.92) · 50ms last turn injected 6 memories, top score 0.92+OV ⚠ slow probe missed the 1 s budget (server may be lagging)+OV ✗ offline server unreachable+OV ⚡ bypass OPENVIKING_BYPASS_SESSION* matched+OV ✓ │ ✎ 573/20k · 2 arch pending capture, two archives produced this session+OV ✓ │ 🔗 resumed │ +3 today session re-hydrated; 3 archives committed today+```++For the full segment glossary and personalization recipes (hide segments, recolor, compose with another statusline, add a custom segment), see [`STATUSLINE.md`](./STATUSLINE.md).++Data flow:++- `auto-recall.mjs` / `auto-capture.mjs` / `session-start.mjs` write small snapshots to `~/.openviking/state/{last-recall,last-capture,last-session-event,daily-stats}.json` after each turn.+- `scripts/statusline.mjs` reads those snapshots plus a 5 s shared cache of `GET /health`.+- Network calls have a hard 1 s timeout. Cache is shared across CC sessions to prevent stampedes.++Disable / customize:++- `OPENVIKING_STATUSLINE=off` — silence without removing the registration.+- `NO_COLOR=1` (or non-TTY) — strip ANSI colors automatically.+- Remove entirely: `jq 'del(.statusLine)' ~/.claude/settings.json > t && mv t ~/.claude/settings.json`.+- Already had a custom statusline? The installer prompts replace / skip / manual-compose.+## Debug loggingSet `claude_code.debug: true` in `ov.conf` or `OPENVIKING_DEBUG=1` to write hook logs to `~/.openviking/logs/cc-hooks.log`.diff --git a/examples/claude-code-memory-plugin/README_CN.md b/examples/claude-code-memory-plugin/README_CN.mdindex a567231ed..75ef7a945 100644--- a/examples/claude-code-memory-plugin/README_CN.md+++ b/examples/claude-code-memory-plugin/README_CN.md@@ -258,6 +258,36 @@ bypass 命中时所有 hook 直接放行,不联系 OpenViking。`claude_code.captureTimeoutMs` 须低于 `Stop` hook 超时,让脚本能优雅失败并仍能更新增量 state。+## Statusline 状态行++插件会在 Claude Code 输入框下方渲染一行 OpenViking 状态。安装脚本会把它注册到 `~/.claude/settings.json`(CC 插件 manifest 不支持 `statusLine` 字段,必须走这条路)。++示例:++```text+OV ✓ │ ↩ 6 mem (0.92) · 50ms 本轮注入 6 条记忆,最高分 0.92+OV ⚠ slow 探针超过 1s 预算(服务器可能在抽风)+OV ✗ offline 服务器不可达+OV ⚡ bypass 命中 OPENVIKING_BYPASS_SESSION*+OV ✓ │ ✎ 573/20k · 2 arch 待提交进度 + 本 session 已归档 2 次+OV ✓ │ 🔗 resumed │ +3 today session 已恢复上下文;今日累计归档 3 次+```++完整段位说明 + 个性化 recipe(隐藏段位、改色、与已有 statusline 组合、自定义段位),见 [`STATUSLINE.md`](./STATUSLINE.md)。++数据来源:++- `auto-recall.mjs` / `auto-capture.mjs` / `session-start.mjs` 每轮写快照到 `~/.openviking/state/{last-recall,last-capture,last-session-event,daily-stats}.json`。+- `scripts/statusline.mjs` 读快照,再加 5 秒共享缓存的 `GET /health`。+- 网络调用 1s 硬超时;多个 CC session 共享缓存避免风暴。++关闭 / 调整:++- `OPENVIKING_STATUSLINE=off` ——不删注册,仅静默。+- `NO_COLOR=1` 或非 TTY ——自动去 ANSI 颜色。+- 彻底卸载:`jq 'del(.statusLine)' ~/.claude/settings.json > t && mv t ~/.claude/settings.json`。+- 已有自定义 statusline?安装时会询问替换 / 跳过 / 稍后手动 compose。+## 调试日志设置 `claude_code.debug: true` 或 `OPENVIKING_DEBUG=1`,hook 日志写到 `~/.openviking/logs/cc-hooks.log`。diff --git a/examples/claude-code-memory-plugin/STATUSLINE.md b/examples/claude-code-memory-plugin/STATUSLINE.mdnew file mode 100644index 000000000..fcd5ad96b--- /dev/null+++ b/examples/claude-code-memory-plugin/STATUSLINE.md@@ -0,0 +1,176 @@+# Reading and Personalizing the OpenViking Statusline++A guide for an AI assistant (or you) to read the OpenViking statusline and **customize** it beyond the defaults the installer sets up. The "What each segment means" section below is the canonical glossary; the rest covers personalization recipes that env vars don't cover. For the environment-variable reference, see `$REPO/docs/en/agent-integrations/02-claude-code.md`.++When a user asks for something the env vars don't cover, prefer the smallest local edit over inventing a new configurable knob.++---++## Where everything lives++The OpenViking repo and plugin code are checked out to a known location by the installer. Throughout this doc:++- **`$REPO`** = the OpenViking repo root. Default: `~/.openviking/openviking-repo` (override via `OPENVIKING_REPO_DIR` at install time). Verify with `ls "$REPO/examples/claude-code-memory-plugin"` — if that path is wrong, find the real one with `jq -r '.statusLine.command' ~/.claude/settings.json` (the registered command points into the plugin) or `find ~ -path '*/claude-code-memory-plugin/scripts/statusline.mjs' 2>/dev/null`.+- **`$PLUGIN`** = `$REPO/examples/claude-code-memory-plugin`. The plugin's own root.+- **`$STATE`** = `~/.openviking/state` (override via `OPENVIKING_HOME`). Where hook-written JSON snapshots live.++Resolve `$REPO` once before editing anything — every relative path below is anchored to it.++| Concern | File |+|--------------------------------------------|---------------------------------------------------|+| Composing the line / segment order | `$PLUGIN/scripts/statusline.mjs` |+| Server-reachability probe + cache | `$PLUGIN/scripts/lib/server-probe.mjs` |+| Atomic state read/write under `$STATE/` | `$PLUGIN/scripts/lib/state.mjs` |+| Recall summary (writes `last-recall.json`) | `$PLUGIN/scripts/auto-recall.mjs` |+| Capture summary (writes `last-capture.json`, `daily-stats.json`) | `$PLUGIN/scripts/auto-capture.mjs` |+| Resume/compact event marker (`last-session-event.json`) | `$PLUGIN/scripts/session-start.mjs` |+| Where CC actually invokes the script | `~/.claude/settings.json` `.statusLine.command` |+| Per-host / per-shell env overrides | `~/.zshrc` (or equivalent) — env vars beat config files |++State files live at `$STATE/`. They are small JSON snapshots written atomically (temp + rename); deleting them clears the corresponding segment until the next hook fires.++---++## What each segment means++The default composition runs left to right, joined by ` │ `. Segments are conditional — most only appear when their underlying signal is non-trivial, so a quiet line in a fresh session is normal, not a bug.++| Segment | Example | Color | Shows when |+|---------------|------------------------|--------|-----------------------------------------------------------------------------------------------------------------------|+| Health | `OV ✓` | green | server reachable in ≤1 s |+| | `OV ⚠ slow` | yellow | probe timed out (>1 s) — server may be alive but lagging |+| | `OV ✗ offline` | red | probe errored (refused, DNS fail, network down) |+| | `OV ⚡ bypass` | yellow | session matched `OPENVIKING_BYPASS_SESSION` or `*_PATTERNS` |+| Recall | `↩ 6 mem (0.92) · 50ms` | dim | last user prompt actually injected memories. `(0.92)` is the top similarity score among picked items; latency is the recall round-trip |+| Capture | `✎ 573/20k · 2 arch` | dim | tokens pending toward the next archive (sawtooth — resets on commit), `2 arch` = archives produced this session |+| | `✎ committed · 2 arch` | dim | the turn that just finished produced an archive |+| | `✎ 2 arch` | dim | nothing pending, but archives already exist this session |+| Failures | `✗ 1 dropped` | red | auto-capture failed N turns this batch — overwrites every Stop, so transient single-turn failures self-clear |+| Session event | `🔗 resumed` | cyan | SessionStart hook fired with `source: resume` within the last minute (1 min TTL) |+| | `🔗 compact` | cyan | same, with `source: compact` |+| Daily | `+3 today` | dim | archives committed across **all** sessions today (UTC date rollover) |++When a segment is **missing** but you'd expect it, the most common reasons are:++- **`✎` capture** — `cc_session_id` mismatch. After `/branch` or a freshly started CC session, no Stop hook has run yet for the new ID, so `last-capture.json` is from a different session and statusline filters it out. Self-resolves on the next assistant turn.+- **`🔗` session event** — only `resume` and `compact` write a marker; `startup` and `clear` don't. The 60 s TTL is intentional so the badge fades.+- **`+N today`** — no archives committed yet today, or `daily-stats.json` is missing entirely.+- **`↩` recall** — last prompt produced no usable memories (too-short query, score under threshold, or all results filtered out). The hook ran; it just had nothing worth showing.++The whole line is hard-capped at 80 visible chars and trailing-truncated with `…` if it overflows.++---++## Recipes++These are sketches, not scripts to copy verbatim. The composer in `$PLUGIN/scripts/statusline.mjs` is small enough that an assistant can read it end-to-end before editing.++### Drop a specific segment++Each segment in `$PLUGIN/scripts/statusline.mjs` is gated by an `if`. To make a segment user-suppressible, wrap its branch in an env-var check (e.g. `process.env.OPENVIKING_STATUSLINE_HIDE_DAILY === "1"`). To remove it permanently, delete the branch — the line keeps composing the rest.++### Reorder or change the separator++The output is `parts.join(dim(" │ "))`. Reorder the `parts.push(...)` calls to taste, or swap `│` for `·` / `—` / a colored separator. Width is bounded by `MAX_WIDTH` (default 80) — change there if your terminal is wider.++### Re-skin the colors++Helpers `green / red / yellow / cyan / dim` wrap an ANSI SGR code. Adjust the codes (e.g. swap `"32"` for `"92"` to get bright green), or build a new helper like `magenta = (s) => c("35", s)` and apply it to a chosen segment. Color is auto-disabled under `NO_COLOR`, `OPENVIKING_STATUSLINE_NO_COLOR`, or `TERM=dumb`.++### Compose with an existing statusline++The installer detects an existing `.statusLine.command` and offers replace / skip. To run **both**, write a small wrapper that fans the same JSON payload to each and concatenates the outputs (substitute the actual `$PLUGIN` path you resolved above):++```bash+#!/usr/bin/env bash+INPUT=$(cat)+ov=$(node "$PLUGIN/scripts/statusline.mjs" <<<"$INPUT")+mine=$(your_other_statusline <<<"$INPUT")+printf '%s %s\n' "$mine" "$ov"+```++Then point `.statusLine.command` at that wrapper. Keep the OV portion last so it gets truncated (not your line) when the terminal narrows.++### Tighten or relax the network timeout++`REQUEST_TIMEOUT_MS` in `$PLUGIN/scripts/lib/server-probe.mjs`. The default 1000 ms is generous for LAN and tight for transcontinental SaaS. The probe is cached for 5 s across processes (file-locked under `$STATE/`), so this only affects the first hit per cache window.++### Add a custom segment++Read the existing segments for the pattern: read state (or call a fast endpoint), guard with a condition, `parts.push(dim("⋯ ..."))`. Keep custom segments cheap — the whole script must finish in well under CC's statusline timeout (≈300 ms wall clock is the working budget). Anything that needs the network should go through the file-cached probe pattern in `$PLUGIN/scripts/lib/server-probe.mjs`.++### Reset stale state without restarting CC++```bash+rm -f "$STATE"/last-*.json+```++The next hook fire repopulates whichever segments are currently active. This is handy after testing or when a session ID got out of sync.++### Disable temporarily / permanently++- Off for one shell: `export OPENVIKING_STATUSLINE=off`+- Off everywhere (keep registration): set the env var in your shell rc+- Remove registration: `jq 'del(.statusLine)' ~/.claude/settings.json` (back up first)++---++## State file shapes++For an assistant adding a segment that consumes existing state. All files live under `$STATE/` and use the same atomic-write helper in `$PLUGIN/scripts/lib/state.mjs`; readers should pass `{ maxAgeMs }` to filter stale snapshots.++`last-recall.json`:+```jsonc+{+ "reason": "ok" | "bypass" | "offline" | "no_results" | "filtered_out" | "short_query" | ...,+ "count": 6, // memories actually injected+ "top_score": 0.92, // max score among picked items+ "latency_ms": 180,+ "cc_session_id": "ff875009-...",+ "ts": 1778139288759+}+```++`last-capture.json`:+```jsonc+{+ "turns_captured": 3,+ "turns_failed": 0,+ "pending_tokens": 12450, // sawtooth — resets to 0 on commit+ "commit_threshold": 20000,+ "committed": false, // true on the turn a commit happened+ "commit_count": 2, // total archives in this session+ "total_message_count": 412,+ "ov_session_id": "cc-62e5af67...",+ "cc_session_id": "ff875009-...", // statusline filters by exact match+ "ts": 1778139288759+}+```++`last-session-event.json` (1-minute TTL in the consumer):+```jsonc+{+ "source": "resume" | "compact",+ "had_context": true, // false when OV had no archive to inject+ "cc_session_id": "...",+ "ov_session_id": "cc-...",+ "ts": 1778139288759+}+```++`daily-stats.json` (UTC date rollover):+```jsonc+{ "date": "2026-05-07", "archives": 3 }+```++---++## When to ask the user++If a request can't be served by an env var or a small local edit (a custom backend, a domain-specific signal, deeper restyling), the cleanest path is:++1. Identify which segment block the change belongs near (or whether it warrants a new one).+2. Propose the smallest patch that delivers it.+3. Suggest a feature branch and a quick eyeball test: `node "$PLUGIN/scripts/statusline.mjs" <<<'{"session_id":"...","cwd":"/tmp"}'`.++Keep changes to `$PLUGIN/scripts/statusline.mjs` shallow; the value of this script is that it stays readable in one screen.diff --git a/examples/claude-code-memory-plugin/scripts/auto-capture.mjs b/examples/claude-code-memory-plugin/scripts/auto-capture.mjsindex 1d7c2128e..69cdbf796 100644--- a/examples/claude-code-memory-plugin/scripts/auto-capture.mjs+++ b/examples/claude-code-memory-plugin/scripts/auto-capture.mjs@@ -33,6 +33,7 @@ import {makeFetchJSON,} from "./lib/ov-session.mjs";import { maybeDetach, readHookStdin } from "./lib/async-writer.mjs";+import { readJsonState, writeJsonState } from "./lib/state.mjs";if (!isPluginEnabled()) {process.stdout.write(JSON.stringify({ decision: "approve" }) + "\n");@@ -443,17 +444,49 @@ async function main() {// OV's Session._auto_commit_threshold is not consumed by addMessage, so we// poll pending_tokens ourselves and commit when the threshold is crossed.let committed = false;+ let pendingTokens = 0;+ let commitCount = 0;+ let totalMessageCount = 0;if (result.ok > 0) {const meta = await getSession(fetchJSON, ovSessionId);- const pending = Number(meta?.pending_tokens || 0);- log("pending_tokens", { ovSessionId, pending, threshold: cfg.commitTokenThreshold });- if (pending >= cfg.commitTokenThreshold) {+ pendingTokens = Number(meta?.pending_tokens || 0);+ commitCount = Number(meta?.commit_count || 0);+ totalMessageCount = Number(meta?.total_message_count || 0);+ log("pending_tokens", { ovSessionId, pending: pendingTokens, threshold: cfg.commitTokenThreshold });+ if (pendingTokens >= cfg.commitTokenThreshold) {const commitRes = await commitSession(fetchJSON, ovSessionId);committed = commitRes.ok;- log("commit", { ovSessionId, ok: commitRes.ok, pending });+ if (committed) commitCount += 1;+ log("commit", { ovSessionId, ok: commitRes.ok, pending: pendingTokens });}}+ // Snapshot for the statusline. Lives across sessions; statusline reads it+ // alongside last-recall.json to show pending/committed counts. commit_count+ // is the running total of archives this session has produced — distinct+ // from `committed` (which is just whether THIS turn triggered a commit).+ writeJsonState("last-capture.json", {+ turns_captured: result.ok,+ turns_failed: result.failed,+ pending_tokens: pendingTokens,+ commit_threshold: cfg.commitTokenThreshold,+ committed,+ commit_count: commitCount,+ total_message_count: totalMessageCount,+ ov_session_id: ovSessionId,+ cc_session_id: sessionId,+ });++ // Cross-session daily counter — number of archives produced today across+ // all CC sessions. Cheap proxy for "how much OV digested today" without+ // hitting the server again. Resets on date rollover.+ if (committed) {+ const today = new Date().toISOString().slice(0, 10); // YYYY-MM-DD, UTC+ const prior = readJsonState("daily-stats.json") || {};+ const archives = prior.date === today ? Number(prior.archives || 0) + 1 : 1;+ writeJsonState("daily-stats.json", { date: today, archives });+ }+if (result.ok > 0) {approve(`captured ${result.ok} turns to ov session ${ovSessionId}` +diff --git a/examples/claude-code-memory-plugin/scripts/auto-recall.mjs b/examples/claude-code-memory-plugin/scripts/auto-recall.mjsindex 3a6b05616..0523c7a44 100644--- a/examples/claude-code-memory-plugin/scripts/auto-recall.mjs+++ b/examples/claude-code-memory-plugin/scripts/auto-recall.mjs@@ -17,6 +17,7 @@import { isPluginEnabled, loadConfig } from "./config.mjs";import { createLogger } from "./debug-log.mjs";import { isBypassed, makeFetchJSON } from "./lib/ov-session.mjs";+import { writeJsonState } from "./lib/state.mjs";if (!isPluginEnabled()) {process.stdout.write(JSON.stringify({ decision: "approve" }) + "\n");@@ -275,14 +276,15 @@ async function buildInjectionBlock(items) {lines.push("</openviking-context>");+ const budgetUsed = cfg.recallTokenBudget - budgetRemaining;log("injection_built", {contentItems: contentCount,hintItems: hintCount,- budgetUsed: cfg.recallTokenBudget - budgetRemaining,+ budgetUsed,budgetTotal: cfg.recallTokenBudget,});- return lines.join("\n");+ return { block: lines.join("\n"), contentCount, hintCount, budgetUsed };}// ---------------------------------------------------------------------------@@ -290,8 +292,19 @@ async function buildInjectionBlock(items) {// ---------------------------------------------------------------------------async function main() {+ const t0 = Date.now();+ // Snapshot state for the statusline. Always written, even on early-exit+ // branches, so the indicator reflects the latest turn rather than stale+ // data from the previous run.+ const writeRecallState = (extra) => writeJsonState("last-recall.json", {+ server_url: cfg.baseUrl,+ latency_ms: Date.now() - t0,+ ...extra,+ });+if (!cfg.autoRecall) {log("skip", { reason: "autoRecall disabled" });+ writeRecallState({ count: 0, reason: "disabled" });approve();return;}@@ -303,6 +316,7 @@ async function main() {input = JSON.parse(Buffer.concat(chunks).toString());} catch {log("skip", { reason: "invalid stdin" });+ writeRecallState({ count: 0, reason: "bad_stdin" });approve();return;}@@ -323,12 +337,14 @@ async function main() {if (isBypassed(cfg, { sessionId, cwd })) {log("skip", { reason: "bypass_session_pattern" });+ writeRecallState({ count: 0, reason: "bypass", cc_session_id: sessionId });approve();return;}if (!userPrompt || userPrompt.length < cfg.minQueryLength) {log("skip", { reason: "query too short or empty" });+ writeRecallState({ count: 0, reason: "short_query", cc_session_id: sessionId });approve();return;}@@ -336,6 +352,7 @@ async function main() {const health = await fetchJSON("/health");if (!health.ok) {logError("health_check", "server unreachable");+ writeRecallState({ count: 0, reason: "offline", cc_session_id: sessionId });approve();return;}@@ -344,6 +361,7 @@ async function main() {const raw = await searchAllSources(userPrompt, perSourceLimit);if (raw.length === 0) {log("skip", { reason: "no results" });+ writeRecallState({ count: 0, reason: "no_results", cc_session_id: sessionId });approve();return;}@@ -362,12 +380,24 @@ async function main() {});if (picked.length === 0) {+ writeRecallState({ count: 0, reason: "filtered_out", cc_session_id: sessionId });approve();return;}- const block = await buildInjectionBlock(picked);- approve(block);+ const built = await buildInjectionBlock(picked);+ const topScore = picked.reduce((m, it) => Math.max(m, clampScore(it.score)), 0);+ writeRecallState({+ count: picked.length,+ content_items: built?.contentCount ?? 0,+ hint_items: built?.hintCount ?? 0,+ tokens_used: built?.budgetUsed ?? 0,+ tokens_budget: cfg.recallTokenBudget,+ top_score: topScore,+ cc_session_id: sessionId,+ reason: "ok",+ });+ approve(built?.block);}main().catch((err) => { logError("uncaught", err); approve(); });diff --git a/examples/claude-code-memory-plugin/scripts/lib/server-probe.mjs b/examples/claude-code-memory-plugin/scripts/lib/server-probe.mjsnew file mode 100644index 000000000..f6d0e8fc5--- /dev/null+++ b/examples/claude-code-memory-plugin/scripts/lib/server-probe.mjs@@ -0,0 +1,99 @@+/**+ * Cached server-state probe for the statusline.+ *+ * The statusline command runs once per conversation update, fresh process,+ * across potentially many concurrent CC sessions. Each call could hit the+ * server; with N tabs that's N stampedes per turn. We cache the response+ * in a shared file under STATE_DIR and let any session within `ttlMs` reuse+ * it.+ *+ * Hard request timeout (see REQUEST_TIMEOUT_MS below) — the statusline has+ * its own outer budget and we never want a slow server to make the user's+ * terminal feel laggy.+ */++import { readFileSync, writeFileSync } from "node:fs";+import { join } from "node:path";+import { STATE_DIR } from "./state.mjs";++const CACHE_FILE = join(STATE_DIR, "server-probe.json");+const DEFAULT_TTL_MS = 5000;+// Per-request timeout. 1 s is loose enough that ordinary remote-server+// hiccups (TLS resumption, occasional GC pause) don't show up as a flapping+// "offline" badge, while still bounded so the statusline never blocks the+// terminal. Combined with the 5 s cache it amortises to one network round-+// trip per session per 5 s window.+const REQUEST_TIMEOUT_MS = 1000;++function readCache() {+ try {+ const raw = readFileSync(CACHE_FILE, "utf-8");+ return JSON.parse(raw);+ } catch {+ return null;+ }+}++function writeCache(payload) {+ try {+ writeFileSync(CACHE_FILE, JSON.stringify(payload));+ } catch { /* best effort */ }+}++async function fetchWithTimeout(url, headers, ms) {+ const controller = new AbortController();+ const timer = setTimeout(() => controller.abort(), ms);+ try {+ const res = await fetch(url, { headers, signal: controller.signal });+ return { ok: res.ok, status: res.status };+ } finally {+ clearTimeout(timer);+ }+}++/**+ * Probe the server for liveness and (best-effort) queue health. Result is+ * cached for `ttlMs`. Always resolves; never throws — failures map to+ * `{healthy: false, error: ...}`.+ */+export async function probeServer(cfg, { ttlMs = DEFAULT_TTL_MS } = {}) {+ const cached = readCache();+ if (cached && typeof cached.ts === "number" && Date.now() - cached.ts < ttlMs) {+ if (cached.base_url === cfg.baseUrl) return cached;+ }++ const headers = { "Content-Type": "application/json" };+ if (cfg.apiKey) headers["Authorization"] = `Bearer ${cfg.apiKey}`;+ if (cfg.accountId) headers["X-OpenViking-Account"] = cfg.accountId;+ if (cfg.userId) headers["X-OpenViking-User"] = cfg.userId;+ if (cfg.agentId) headers["X-OpenViking-Agent"] = cfg.agentId;++ const t0 = Date.now();+ let healthy = false;+ let error;++ try {+ const health = await fetchWithTimeout(`${cfg.baseUrl}/health`, headers, REQUEST_TIMEOUT_MS);+ healthy = health.ok;+ if (!healthy) error = `health_${health.status}`;+ } catch (err) {+ error = err?.name === "AbortError" ? "timeout" : (err?.message || "unreachable");+ }++ // Note: /api/v1/observer/queue was probed here in earlier iterations to+ // surface a "queue unhealthy" badge, but its `is_healthy` boolean is+ // derived from `QueueManager.has_errors()` — a lifetime cumulative counter+ // that flips to true on the first error and never resets. In practice+ // this means a server with 95%+ success rate still reports unhealthy+ // forever, producing a permanent false-alarm badge. Removed.++ const payload = {+ healthy,+ latency_ms: Date.now() - t0,+ base_url: cfg.baseUrl,+ error,+ ts: Date.now(),+ };+ writeCache(payload);+ return payload;+}diff --git a/examples/claude-code-memory-plugin/scripts/lib/state.mjs b/examples/claude-code-memory-plugin/scripts/lib/state.mjsnew file mode 100644index 000000000..844500ab5--- /dev/null+++ b/examples/claude-code-memory-plugin/scripts/lib/state.mjs@@ -0,0 +1,59 @@+/**+ * Shared runtime state files under ~/.openviking/state/.+ *+ * Hooks (auto-recall, auto-capture) write small JSON snapshots here so the+ * statusline script can render up-to-date info without making network calls+ * for things only the hook knows (last recall stats, pending capture count).+ *+ * Atomic write: temp file + rename, so the statusline never reads a half-+ * written file. Stale entries (older than maxAgeMs) read as null so the+ * statusline degrades to "idle" instead of showing day-old data.+ */++import { mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";+import { homedir } from "node:os";+import { join } from "node:path";++const OV_HOME = process.env.OPENVIKING_HOME && process.env.OPENVIKING_HOME.trim()+ ? process.env.OPENVIKING_HOME.replace(/^~(?=$|\/)/, homedir())+ : join(homedir(), ".openviking");+export const STATE_DIR = join(OV_HOME, "state");++function ensureDir() {+ try {+ mkdirSync(STATE_DIR, { recursive: true });+ } catch { /* best effort — caller will see write failure */ }+}++export function statePath(name) {+ return join(STATE_DIR, name);+}++export function writeJsonState(name, payload) {+ ensureDir();+ const target = statePath(name);+ const tmp = `${target}.${process.pid}.tmp`;+ try {+ writeFileSync(tmp, JSON.stringify({ ...payload, ts: payload?.ts ?? Date.now() }));+ renameSync(tmp, target);+ } catch { /* best effort: statusline tolerates missing files */ }+}++export function readJsonState(name, { maxAgeMs } = {}) {+ let raw;+ try {+ raw = readFileSync(statePath(name), "utf-8");+ } catch {+ return null;+ }+ let parsed;+ try {+ parsed = JSON.parse(raw);+ } catch {+ return null;+ }+ if (maxAgeMs && typeof parsed?.ts === "number" && Date.now() - parsed.ts > maxAgeMs) {+ return null;+ }+ return parsed;+}diff --git a/examples/claude-code-memory-plugin/scripts/session-start.mjs b/examples/claude-code-memory-plugin/scripts/session-start.mjsindex 783a30721..6e5be6af5 100644--- a/examples/claude-code-memory-plugin/scripts/session-start.mjs+++ b/examples/claude-code-memory-plugin/scripts/session-start.mjs@@ -18,6 +18,7 @@ import {isBypassed,makeFetchJSON,} from "./lib/ov-session.mjs";+import { writeJsonState } from "./lib/state.mjs";if (!isPluginEnabled()) {process.stdout.write(JSON.stringify({ decision: "approve" }) + "\n");@@ -107,6 +108,19 @@ async function main() {const ovSessionId = deriveOvSessionId(sessionId);const sessionCtx = await getSessionContext(fetchJSON, ovSessionId, cfg.resumeContextBudget);const block = formatArchiveContext(sessionCtx, source);++ // One-shot signal for the statusline: surface "🔗 resumed" / "🔗 compact"+ // briefly after the event, regardless of whether OV had archive context to+ // inject. Users expect the badge to reflect "the event happened", not "OV+ // had something to add" — early sessions with no archive yet still want+ // the indicator that compact occurred. Statusline applies a short TTL.+ writeJsonState("last-session-event.json", {+ source,+ cc_session_id: sessionId,+ ov_session_id: ovSessionId,+ had_context: Boolean(block),+ });+if (!block) {log("no_archive", { ovSessionId, source });approve();diff --git a/examples/claude-code-memory-plugin/scripts/statusline.mjs b/examples/claude-code-memory-plugin/scripts/statusline.mjsnew file mode 100755index 000000000..70762c80e--- /dev/null+++ b/examples/claude-code-memory-plugin/scripts/statusline.mjs@@ -0,0 +1,208 @@+#!/usr/bin/env node++/**+ * OpenViking statusline for Claude Code.+ *+ * Wired into ~/.claude/settings.json `.statusLine` by the plugin installer.+ * CC invokes this command on each conversation update, fresh process, with+ * a JSON payload on stdin (session_id, cwd, model, transcript_path, ...).+ *+ * We compose a one-line status from two sources:+ * - Local state files written by auto-recall / auto-capture hooks+ * (~/.openviking/state/last-recall.json, last-capture.json)+ * - A 5 s shared cache of GET /health (+ /observer/queue best-effort)+ *+ * Output budget: <300 ms wall clock. Caching, AbortController, and+ * fail-soft branches all serve that budget. Empty stdout is a valid+ * statusline (CC just renders nothing for OV that turn).+ */++import { isPluginEnabled, loadConfig } from "./config.mjs";+import { isBypassed } from "./lib/ov-session.mjs";+import { readJsonState } from "./lib/state.mjs";+import { probeServer } from "./lib/server-probe.mjs";++const STATE_MAX_AGE_MS = 30 * 60_000; // 30 min — older = "idle"+const SESSION_EVENT_MAX_AGE_MS = 60_000; // 1 min — "🔗 resumed" fades+const MAX_WIDTH = 80;+const ESC = "\x1b[";++function colorEnabled() {+ if (process.env.NO_COLOR) return false;+ if (process.env.OPENVIKING_STATUSLINE_NO_COLOR) return false;+ const term = process.env.TERM || "";+ if (term === "dumb") return false;+ return true;+}++const COLOR = colorEnabled();+const c = (code, s) => (COLOR ? `${ESC}${code}m${s}${ESC}0m` : s);+const dim = (s) => c("2", s);+const green = (s) => c("32", s);+const red = (s) => c("31", s);+const yellow = (s) => c("33", s);+const cyan = (s) => c("36", s);++function human(n) {+ if (typeof n !== "number" || !Number.isFinite(n)) return "?";+ if (n < 1000) return String(n);+ if (n < 10_000) return (n / 1000).toFixed(1) + "k";+ return Math.round(n / 1000) + "k";+}++async function readStdin() {+ if (process.stdin.isTTY) return {};+ return await new Promise((resolve) => {+ const chunks = [];+ let settled = false;+ const settle = (val) => {+ if (settled) return;+ settled = true;+ resolve(val);+ };+ // Hard cap: CC always writes stdin promptly. If we don't see EOF in 50 ms,+ // assume there's no payload and proceed — never block the render.+ const timer = setTimeout(() => settle({}), 50);+ process.stdin.on("data", (c) => chunks.push(c));+ process.stdin.on("end", () => {+ clearTimeout(timer);+ try {+ settle(JSON.parse(Buffer.concat(chunks).toString() || "{}"));+ } catch {+ settle({});+ }+ });+ process.stdin.on("error", () => {+ clearTimeout(timer);+ settle({});+ });+ });+}++function truncate(line) {+ // Strip ANSI for width measurement, then re-truncate the original.+ // Simple approximation: assume colors only at specific positions; for the+ // composer below this is fine because we never embed colored text mid-word.+ // eslint-disable-next-line no-control-regex+ const visible = line.replace(/\x1b\[[0-9;]*m/g, "");+ if (visible.length <= MAX_WIDTH) return line;+ // Cut visible to budget, replace tail with ellipsis. We append the reset+ // unconditionally so a truncated mid-color string doesn't bleed.+ let out = "";+ let visibleLen = 0;+ let i = 0;+ while (i < line.length && visibleLen < MAX_WIDTH - 1) {+ if (line[i] === "\x1b") {+ const m = line.slice(i).match(/^\x1b\[[0-9;]*m/);+ if (m) { out += m[0]; i += m[0].length; continue; }+ }+ out += line[i];+ visibleLen++;+ i++;+ }+ return out + "…" + (COLOR ? `${ESC}0m` : "");+}++async function main() {+ if (process.env.OPENVIKING_STATUSLINE === "off") return;+ if (!isPluginEnabled()) return;++ const cfg = loadConfig();+ const stdin = await readStdin();+ const sessionId = stdin.session_id;+ const cwd = stdin.cwd;++ // Bypass shortcut: don't even probe the server when the user has opted+ // this session out of OV.+ if (isBypassed(cfg, { sessionId, cwd })) {+ process.stdout.write(yellow("OV ⚡ bypass"));+ return;+ }++ const recall = readJsonState("last-recall.json", { maxAgeMs: STATE_MAX_AGE_MS });+ const capture = readJsonState("last-capture.json", { maxAgeMs: STATE_MAX_AGE_MS });+ const sessionEvent = readJsonState("last-session-event.json", { maxAgeMs: SESSION_EVENT_MAX_AGE_MS });+ const daily = readJsonState("daily-stats.json");+ const probe = await probeServer(cfg);++ const parts = [];++ if (probe.healthy) {+ parts.push(green("OV ✓"));+ } else if (probe.error === "timeout") {+ // "slow" means the probe missed its 1 s budget — the server might be alive+ // but lagging (remote SaaS, GC pause). Yellow keeps it advisory; reserving+ // red for actual unreachability (refused, DNS, etc.) makes the distinction+ // legible at a glance.+ parts.push(yellow("OV ⚠ slow"));+ } else {+ parts.push(red("OV ✗ offline"));+ }++ // Recall summary: only meaningful when we actually injected memories this+ // turn. Skip the segment for empty/bypass/no-results reasons to keep the+ // line tight. The (0.92) trailing parens is the top score among picked+ // items — quality hint without an extra segment. Token/char count is+ // omitted: the only number we have is a chars/4 heuristic, which is+ // misleading enough on CJK text that displaying it does more harm than+ // good. Count + score + latency convey the relevant signal.+ if (recall && recall.reason === "ok" && recall.count > 0) {+ const top = typeof recall.top_score === "number" && recall.top_score > 0+ ? ` (${recall.top_score.toFixed(2)})`+ : "";+ const seg = `↩ ${recall.count} mem${top}`+ + (typeof recall.latency_ms === "number" ? ` · ${recall.latency_ms}ms` : "");+ parts.push(dim(seg));+ }++ // Capture summary: pending-tokens progress toward the next archive, plus a+ // running total of archives this session has produced. The pending counter+ // is a sawtooth (climbs to commit_threshold, snaps back to 0 on commit), so+ // showing only "X/20k tok" of a long conversation can mislead — the+ // archived count makes the cumulative work visible.+ if (capture && capture.cc_session_id === sessionId) {+ const archived = Number(capture.commit_count || 0);+ const archivedTail = archived > 0 ? ` · ${archived} arch` : "";+ if (capture.committed) {+ parts.push(dim(`✎ committed${archivedTail}`));+ } else if (capture.pending_tokens > 0) {+ // No "tok" suffix: server-side counter is approximate (chars/N), and+ // mixing it with the recall side (which is a pure heuristic) under the+ // same label invites the wrong mental model. Pending/threshold ratio+ // is meaningful on its own.+ parts.push(dim(+ `✎ ${human(capture.pending_tokens)}/${human(capture.commit_threshold)}${archivedTail}`,+ ));+ } else if (archived > 0) {+ parts.push(dim(`✎ ${archived} arch`));+ }++ // Capture failure alert. turns_failed comes from THIS batch only —+ // auto-capture overwrites the state every Stop hook, so transient+ // single-turn failures clear themselves after the next successful+ // capture. Sustained failures stay visible (which is the point).+ if (Number(capture.turns_failed) > 0) {+ parts.push(red(`✗ ${capture.turns_failed} dropped`));+ }+ }++ // Resumed/compact indicator: 1-minute TTL so it shows once after the+ // SessionStart hook re-hydrated context, then fades.+ if (sessionEvent && sessionEvent.cc_session_id === sessionId) {+ const label = sessionEvent.source === "compact" ? "compact" : "resumed";+ parts.push(cyan(`🔗 ${label}`));+ }++ // Cross-session daily archive count. Tracks "how much OV digested today"+ // without hitting the server. Resets on date rollover. Hidden when 0 to+ // keep fresh-day mornings unobtrusive.+ const todayStr = new Date().toISOString().slice(0, 10);+ if (daily && daily.date === todayStr && Number(daily.archives) > 0) {+ parts.push(dim(`+${daily.archives} today`));+ }++ const line = parts.join(dim(" │ "));+ process.stdout.write(truncate(line));+}++main().catch(() => { /* statusline must never crash CC */ });diff --git a/examples/claude-code-memory-plugin/setup-helper/install.sh b/examples/claude-code-memory-plugin/setup-helper/install.shindex bc4ef305f..39f5b5af6 100755--- a/examples/claude-code-memory-plugin/setup-helper/install.sh+++ b/examples/claude-code-memory-plugin/setup-helper/install.sh@@ -310,6 +310,70 @@ install_modern() {claude plugin enable claude-code-memory-plugin@openviking-plugins-local >/dev/null 2>&1 || true}+# Statusline registration. CC's plugin manifest doesn't accept a statusLine+# field (only hooks/MCP/agents/skills are bundle-able), so we have to inject+# into the user's ~/.claude/settings.json. Always opt-in: we ask first, both+# because terminal real-estate is opinionated and because users often have+# their own statusline they don't want clobbered.+register_statusline() {+ local plugin_dir="$REPO_DIR/examples/claude-code-memory-plugin"+ # Quote the script path so install dirs containing spaces/metacharacters+ # don't break when CC invokes the command via /bin/sh -c.+ local cmd="node \"$plugin_dir/scripts/statusline.mjs\""+ local settings="$HOME/.claude/settings.json"++ heading 'Statusline (optional)'+ info 'OpenViking can show a one-line server/recall status under the input box.'+ info 'Sample: "OV ✓ │ ↩ 6 mem (0.92) · 50ms │ ✎ 573/20k · 2 arch │ +3 today"'++ mkdir -p "$HOME/.claude"+ [ -f "$settings" ] || echo '{}' > "$settings"++ local existing+ existing=$(jq -r '.statusLine.command // empty' "$settings" 2>/dev/null || echo "")++ if [ -n "$existing" ] && [ "$existing" = "$cmd" ]; then+ info 'Already registered. (Re-run this installer with no changes to refresh.)'+ return 0+ fi++ if [ -n "$existing" ]; then+ warn "Existing statusline detected:"+ warn " $existing"+ ask 'Replace it with OpenViking statusline? [y/N] '+ else+ ask 'Enable OpenViking statusline? [y/N] '+ fi+ local reply+ read -r reply || reply=""+ case "$reply" in+ y|Y|yes|Yes|YES) ;;+ *)+ info 'Skipped statusline registration. Run this installer again to enable it later.'+ return 0+ ;;+ esac++ local ts; ts=$(date +%Y%m%d-%H%M%S)+ cp -p "$settings" "$settings.bak.$ts"+ # mktemp inside the same directory as $settings so the final `mv` is a+ # rename within one filesystem (atomic). Using $TMPDIR risks crossing+ # filesystems on Linux (tmpfs vs $HOME), which makes `mv` non-atomic.+ local tmp+ tmp=$(mktemp "$settings.XXXXXX") || { err 'mktemp failed'; return 1; }+ if ! jq --arg cmd "$cmd" \+ '.statusLine = {type: "command", command: $cmd, padding: 0}' \+ "$settings" > "$tmp" 2>/dev/null; then+ err "writing statusline into $settings failed; original untouched"+ rm -f "$tmp"+ return 1+ fi+ mv "$tmp" "$settings"+ info "statusline registered (backup: $settings.bak.$ts)"+ info 'Disable later: jq "del(.statusLine)" '"$settings"' > t && mv t '"$settings"+ info 'Or silence only: export OPENVIKING_STATUSLINE=off'+}+USE_LEGACY=0if [ "$CLAUDE_AVAILABLE" -eq 1 ] && ! has_plugin_subcommand; thenwarn "This Claude Code build doesn't expose 'claude plugin' (introduced in 2.0)."@@ -330,6 +394,7 @@ if [ "$CLAUDE_AVAILABLE" -eq 1 ]; thenelseinstall_modernfi+ register_statusline || warn 'statusline registration skipped (continuing)'elsewarn "Run these manually after installing Claude Code:"warn " cd \"$REPO_DIR\""@@ -358,3 +423,6 @@ fiinfo 'Then:'info ' claude # start Claude Code'info ' /mcp # inside Claude Code, verify the OpenViking entry'+printf '\n'+printf '%sCurious what your statusline shows, or want to tweak it?%s Open Claude Code and paste:\n' "$BOLD" "$RESET"+printf ' %sRead %s/examples/claude-code-memory-plugin/STATUSLINE.md. Walk me through what each segment of my OpenViking statusline means, then ask me whether I want to personalize anything.%s\n' "$CYAN" "$REPO_DIR" "$RESET"