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): session-start profile injection, /ov status command, tool-output capture cleanup (#1914)
t0saki31bcfd2bd72f
diff --git a/examples/claude-code-memory-plugin/commands/ov.md b/examples/claude-code-memory-plugin/commands/ov.mdnew file mode 100644index 000000000..8aeb0ad01--- /dev/null+++ b/examples/claude-code-memory-plugin/commands/ov.md@@ -0,0 +1,5 @@+---+description: Show OpenViking memory plugin status — server, identity, last injection / recall, toggles+---++!node ${CLAUDE_PLUGIN_ROOT}/scripts/ov-status.mjsdiff --git a/examples/claude-code-memory-plugin/scripts/auto-capture.mjs b/examples/claude-code-memory-plugin/scripts/auto-capture.mjsindex 69cdbf796..14278d16f 100644--- a/examples/claude-code-memory-plugin/scripts/auto-capture.mjs+++ b/examples/claude-code-memory-plugin/scripts/auto-capture.mjs@@ -176,27 +176,32 @@ function parseTranscript(content) {return messages;}-// Per-block cap for tool input / tool result snippets. Sized to keep most invocations-// (URLs, file paths, search queries, short results) verbatim while bounding worst-case-// blowup when an agent reads a large file or fetches a long page.-const TOOL_BLOCK_MAX_CHARS = 4096;--function truncateForLog(value) {- let s;- if (typeof value === "string") {- s = value;- } else {- try {- s = JSON.stringify(value, null, 2);- } catch {- s = String(value);- }+// Tool result (output) retention. 0 = drop tool_result blocks entirely; >0 = keep,+// truncated to that many chars. Default 0 — memory extraction signal lives in the+// agent's prose summary of what happened, not in the raw bytes the tool returned+// (file contents, web pages, command stdout). Operators who want replay-style+// archives can set this >0 to retain truncated results.+const TOOL_RESULT_MAX_CHARS = 0;++function formatToolInput(value) {+ // Tool inputs are agent-authored. We keep them verbatim — they're usually short+ // (URLs, file paths, queries) and a pathologically long input is itself signal+ // worth surfacing to the memory extractor.+ if (typeof value === "string") return value;+ try {+ return JSON.stringify(value, null, 2);+ } catch {+ return String(value);}- if (typeof s !== "string") s = "";- if (s.length <= TOOL_BLOCK_MAX_CHARS) return s;+}++function truncateToolResult(s) {+ if (TOOL_RESULT_MAX_CHARS <= 0) return null; // drop+ if (typeof s !== "string") s = String(s ?? "");+ if (s.length <= TOOL_RESULT_MAX_CHARS) return s;return (- s.slice(0, TOOL_BLOCK_MAX_CHARS) +- `\n... [truncated, ${s.length - TOOL_BLOCK_MAX_CHARS} more chars]`+ s.slice(0, TOOL_RESULT_MAX_CHARS) ++ `\n... [truncated, ${s.length - TOOL_RESULT_MAX_CHARS} more chars]`);}@@ -210,10 +215,10 @@ function extractToolResultText(content) {}/**- * Extract user/assistant turns. Captures plain text, tool_use input (server-side args),- * and tool_result content (tool output). Tool blocks are inlined into the per-turn text- * so the OV memory extractor sees "what happened" with substance, not just tool names.- * Each tool block is truncated to TOOL_BLOCK_MAX_CHARS to bound size.+ * Extract user/assistant turns. Captures plain text + tool_use input (verbatim) and,+ * if TOOL_RESULT_MAX_CHARS > 0, tool_result output (truncated). Tool blocks are inlined+ * into the per-turn text so the OV memory extractor sees what the agent did with+ * substance, not just tool names.*/function extractAllTurns(messages) {const turns = [];@@ -235,11 +240,12 @@ function extractAllTurns(messages) {parts.push(block.text);} else if (block.type === "tool_use" && typeof block.name === "string") {toolNames.push(block.name);- parts.push(`[tool: ${block.name}]\n${truncateForLog(block.input)}`);+ parts.push(`[tool: ${block.name}]\n${formatToolInput(block.input)}`);} else if (block.type === "tool_result") {const resultText = extractToolResultText(block.content);- if (resultText) {- parts.push(`[tool result]\n${truncateForLog(resultText)}`);+ const truncated = resultText ? truncateToolResult(resultText) : null;+ if (truncated) {+ parts.push(`[tool result]\n${truncated}`);}}}diff --git a/examples/claude-code-memory-plugin/scripts/config.mjs b/examples/claude-code-memory-plugin/scripts/config.mjsindex f21ac038c..000342014 100644--- a/examples/claude-code-memory-plugin/scripts/config.mjs+++ b/examples/claude-code-memory-plugin/scripts/config.mjs@@ -28,6 +28,8 @@* Lifecycle / behavior:* OPENVIKING_TIMEOUT_MS, OPENVIKING_CAPTURE_TIMEOUT_MS, OPENVIKING_WRITE_PATH_ASYNC,* OPENVIKING_BYPASS_SESSION, OPENVIKING_BYPASS_SESSION_PATTERNS (CSV)+ * Profile injection (session_start):+ * OPENVIKING_NO_AUTO_INJECT, OPENVIKING_PROFILE_TOKEN_BUDGET* Misc:* OPENVIKING_MEMORY_ENABLED, OPENVIKING_DEBUG, OPENVIKING_DEBUG_LOG,* OPENVIKING_CONFIG_FILE, OPENVIKING_CLI_CONFIG_FILE@@ -261,6 +263,16 @@ export function loadConfig() {num(cc.resumeContextBudget, 32000),))),+ // Session-start profile injection: pull profile.md + ls of preferences/+ // and entities/ on every session_start (startup/clear/resume/compact),+ // independent of UserPromptSubmit auto-recall. Subagents skip entirely+ // (handled by subagent-start.mjs not invoking buildProfileBlock).+ noAutoInject: envBool("OPENVIKING_NO_AUTO_INJECT") ?? (cc.noAutoInject === true),+ profileTokenBudget: Math.max(500, Math.floor(num(+ process.env.OPENVIKING_PROFILE_TOKEN_BUDGET,+ num(cc.profileTokenBudget, 10000),+ ))),+// P1-15: bypass patterns (glob) — when the CC session_id or cwd matches,// skip capture/recall entirely. Useful for one-off scratch sessions that// should not contaminate OV.diff --git a/examples/claude-code-memory-plugin/scripts/lib/profile-inject.mjs b/examples/claude-code-memory-plugin/scripts/lib/profile-inject.mjsnew file mode 100644index 000000000..c7ce3dc26--- /dev/null+++ b/examples/claude-code-memory-plugin/scripts/lib/profile-inject.mjs@@ -0,0 +1,287 @@+/**+ * Session-start profile injection helper.+ *+ * Builds a <user-profile> + <available-memories> block from+ * viking://user/<space>/memories/profile.md+ * viking://user/<space>/memories/preferences/ (ls with abstracts)+ * viking://user/<space>/memories/entities/ (ls with abstracts)+ *+ * Budget enforced via the CJK-aware estimateTokens() below — codepoint >=+ * 0x3000 counts at 1.5 tokens, else chars/4. The estimator is exported so+ * callers (e.g. session-start.mjs) can log token counts that match what+ * the budget logic actually sees.+ *+ * Returned block is the *inner* content only (no outer <openviking-context>);+ * session-start.mjs composes the outer wrapper so the archive block can sit+ * alongside in a single context envelope.+ */++const USER_RESERVED_DIRS = new Set(["memories"]);+let _userSpaceCache = null;++/**+ * Mirrors auto-recall.mjs resolveScopeSpace for scope="user" (lines 123-147).+ * Duplicated rather than imported to avoid coupling session-start to+ * auto-recall's module-level fetchJSON closure.+ */+async function resolveUserSpace(fetchJSON) {+ if (_userSpaceCache) return _userSpaceCache;++ let fallbackSpace = "default";+ const status = await fetchJSON("/api/v1/system/status");+ if (status.ok && typeof status.result?.user === "string" && status.result.user.trim()) {+ fallbackSpace = status.result.user.trim();+ }++ const lsRes = await fetchJSON(+ `/api/v1/fs/ls?uri=${encodeURIComponent("viking://user")}&output=original`,+ );+ if (lsRes.ok && Array.isArray(lsRes.result)) {+ const spaces = lsRes.result+ .filter((e) => e?.isDir)+ .map((e) => (typeof e.name === "string" ? e.name.trim() : ""))+ .filter((n) => n && !n.startsWith(".") && !USER_RESERVED_DIRS.has(n));+ if (spaces.length > 0) {+ if (spaces.includes(fallbackSpace)) { _userSpaceCache = fallbackSpace; return fallbackSpace; }+ if (spaces.includes("default")) { _userSpaceCache = "default"; return "default"; }+ if (spaces.length === 1) { _userSpaceCache = spaces[0]; return spaces[0]; }+ }+ }+ _userSpaceCache = fallbackSpace;+ return fallbackSpace;+}++/**+ * Token estimate that splits CJK from the rest. The rest of the plugin uses a+ * flat chars/4 heuristic, which silently undercounts CJK content by 4-6× and+ * makes a "5000 token budget" really worth ~1k real tokens for Chinese text.+ *+ * Rule:+ * - codepoint >= 0x3000 → CJK / Hiragana / Katakana / Hangul / CJK+ * punctuation / fullwidth ASCII; counted at 1.5 tokens/char (empirical+ * average for cl100k_base on Chinese; Claude's tokenizer is in the same+ * ballpark).+ * - everything else → chars/4 (the standard English-ish heuristic).+ *+ * Single linear pass, no dependencies. Errs on the side of overcounting CJK+ * by ~10-20% in the worst case (some common Chinese phrases compress better+ * than 1.5 tokens/char), which is the safe direction for budget enforcement.+ */+export function estimateTokens(text) {+ if (!text) return 0;+ let cjk = 0;+ for (let i = 0; i < text.length; i++) {+ if (text.charCodeAt(i) >= 0x3000) cjk++;+ }+ const other = text.length - cjk;+ return Math.ceil(cjk * 1.5 + other / 4);+}++/**+ * Convert a token budget to a max-chars budget that respects this content's+ * actual CJK density. Avoids the chars/4 trap where a "5000 token" sub-cap+ * yields 20000 chars of pure-CJK text → 30000 actual tokens (6× over).+ *+ * For an empty/missing string, returns 0.+ */+function tokensToCharsBudget(content, maxTokens) {+ if (!content) return 0;+ let cjk = 0;+ for (let i = 0; i < content.length; i++) {+ if (content.charCodeAt(i) >= 0x3000) cjk++;+ }+ const ratio = cjk / content.length;+ const tokensPerChar = ratio * 1.5 + (1 - ratio) * 0.25;+ return Math.floor(maxTokens / Math.max(tokensPerChar, 0.25));+}++async function readProfile(fetchJSON, profileUri) {+ const res = await fetchJSON(`/api/v1/content/read?uri=${encodeURIComponent(profileUri)}`);+ if (!res.ok || typeof res.result !== "string") return null;+ const trimmed = res.result.trim();+ return trimmed || null;+}++/**+ * Recursive ls of a memory directory, flattening to .md leaves.+ *+ * Memory layout under preferences/ and entities/ is two-level:+ * <dir>/<owner_name>/<topic>.md+ * so we use the server's recursive=true flag and filter to leaf .md files.+ * `rel_path` (e.g. "zhengxiao.wu/pr_workflow.md") is preserved as display name+ * to keep owner-namespacing visible and unambiguous when multiple owners exist.+ */+async function lsDir(fetchJSON, dirUri) {+ const url = `/api/v1/fs/ls?uri=${encodeURIComponent(dirUri)}&output=agent&recursive=true&abs_limit=512&node_limit=512`;+ const res = await fetchJSON(url);+ if (!res.ok || !Array.isArray(res.result)) return [];+ return res.result+ .filter((e) => !e.isDir)+ .map((e) => {+ const rel = typeof e.rel_path === "string" && e.rel_path+ ? e.rel_path+ : (typeof e.name === "string" ? e.name : "");+ return {+ name: rel,+ abstract: typeof e.abstract === "string" ? e.abstract.trim() : "",+ };+ })+ .filter((e) => e.name && e.name.endsWith(".md"))+ .sort((a, b) => a.name.localeCompare(b.name));+}++/**+ * When profile exceeds its sub-cap, keep the head (identity block + first+ * timeline events) and the tail (most-recent events), drop the middle. This+ * preserves both stable identity facts (top of file) and most-recent activity+ * (bottom of file) — only the noisy middle timeline is sacrificed.+ *+ * Layout:+ * <first HEAD_LINES lines>+ * ... [profile middle elided] ...+ * <as many trailing lines as fit in remaining budget>+ *+ * Falls back to head-only truncate when the file is too short to elide+ * meaningfully (<HEAD_LINES + 4 lines) or the budget is too tight to fit+ * both head and a useful tail.+ */+function elideProfile(content, maxTokens) {+ // Compute char budget from token budget using *this* content's CJK density,+ // not chars/4 — otherwise the truncated string can still blow the token cap+ // for CJK-heavy profiles (Copilot review point).+ const maxChars = Math.max(400, tokensToCharsBudget(content, maxTokens));+ if (estimateTokens(content) <= maxTokens) return content;++ const HEAD_LINES = 8;+ const ELLIPSIS = "\n... [profile middle elided] ...\n";+ const lines = content.split("\n");++ const fallbackHeadTruncate = () =>+ content.slice(0, maxChars).trimEnd() + "\n... [profile truncated]";++ if (lines.length <= HEAD_LINES + 4) return fallbackHeadTruncate();++ const head = lines.slice(0, HEAD_LINES).join("\n");+ const reserveForTail = maxChars - head.length - ELLIPSIS.length;+ if (reserveForTail < 200) return fallbackHeadTruncate();++ let tailChars = 0;+ let tailStart = lines.length;+ for (let i = lines.length - 1; i > HEAD_LINES; i--) {+ const lineLen = lines[i].length + 1;+ if (tailChars + lineLen > reserveForTail) break;+ tailChars += lineLen;+ tailStart = i;+ }+ if (tailStart >= lines.length - 1) return fallbackHeadTruncate();++ return `${head}${ELLIPSIS}${lines.slice(tailStart).join("\n")}`;+}++function formatListing(headerUri, entries, budgetTokens) {+ if (entries.length === 0) return { lines: [], used: 0, dropped: 0 };+ // Header is the full directory URI; child lines are relative paths so the+ // agent can reconstruct each leaf's full URI by concatenation while the+ // listing itself stays compact.+ const header = ` ${headerUri}/`;+ const headerTokens = estimateTokens(header);+ // If the header alone busts the budget, emit just a one-line stub instead+ // of silently violating the cap (Copilot review point).+ if (headerTokens > budgetTokens) {+ const stub = ` ${headerUri}/ (${entries.length} entries, budget too tight; use \`memory_recall\`)`;+ return { lines: [stub], used: estimateTokens(stub), dropped: entries.length };+ }+ const lines = [header];+ let used = headerTokens;+ for (let i = 0; i < entries.length; i++) {+ const e = entries[i];+ const desc = e.abstract+ ? ` — ${e.abstract.replace(/\s+/g, " ").slice(0, 200)}`+ : "";+ const line = ` - ${e.name}${desc}`;+ const tokens = estimateTokens(line);+ if (used + tokens > budgetTokens) {+ const remaining = entries.length - i;+ const tail = ` ... +${remaining} more, use \`memory_recall\``;+ const tailTokens = estimateTokens(tail);+ // Only emit the tail if it fits; otherwise the listing closes silently+ // rather than violating the cap to advertise its own truncation.+ if (used + tailTokens <= budgetTokens) {+ lines.push(tail);+ return { lines, used: used + tailTokens, dropped: remaining };+ }+ return { lines, used, dropped: remaining };+ }+ lines.push(line);+ used += tokens;+ }+ return { lines, used, dropped: 0 };+}++/**+ * Build the profile injection block.+ *+ * Returns null when neither profile.md nor either listing has any content.+ * The returned `block` is just the inner <user-profile>/<available-memories>+ * payload — the caller wraps it in <openviking-context source="...">.+ *+ * @param {Function} fetchJSON ov-session.mjs:makeFetchJSON closure+ * @param {number} totalBudgetTokens chars/4 budget, total for the whole block+ * @returns {Promise<null | {+ * block: string, chars: number, tokens: number, profileUri: string,+ * profileChars: number, prefCount: number, entCount: number,+ * droppedPref: number, droppedEnt: number,+ * }>}+ */+export async function buildProfileBlock(fetchJSON, totalBudgetTokens) {+ const space = await resolveUserSpace(fetchJSON);+ const profileUri = `viking://user/${space}/memories/profile.md`;+ const prefUri = `viking://user/${space}/memories/preferences`;+ const entUri = `viking://user/${space}/memories/entities`;++ const [profile, prefs, ents] = await Promise.all([+ readProfile(fetchJSON, profileUri),+ lsDir(fetchJSON, prefUri),+ lsDir(fetchJSON, entUri),+ ]);++ if (!profile && prefs.length === 0 && ents.length === 0) return null;++ // Profile gets up to half the total budget; listings split the rest.+ // Sub-cap protects against a runaway profile blowing the listing budget.+ const profileBudget = Math.floor(totalBudgetTokens / 2);+ const profileTrunc = profile ? elideProfile(profile, profileBudget) : null;+ const profileTokens = estimateTokens(profileTrunc || "");++ const listingBudget = Math.max(0, totalBudgetTokens - profileTokens);+ const halfListing = Math.floor(listingBudget / 2);+ const prefBlock = formatListing(prefUri, prefs, halfListing);+ const entBudget = Math.max(0, listingBudget - prefBlock.used);+ const entBlock = formatListing(entUri, ents, entBudget);++ const lines = [];+ if (profileTrunc) {+ lines.push(`<user-profile uri="${profileUri}">`);+ lines.push(profileTrunc);+ lines.push(`</user-profile>`);+ }+ if (prefBlock.lines.length > 0 || entBlock.lines.length > 0) {+ lines.push(`<available-memories>`);+ lines.push(...prefBlock.lines);+ lines.push(...entBlock.lines);+ lines.push(`</available-memories>`);+ }++ const block = lines.join("\n");+ return {+ block,+ chars: block.length,+ tokens: estimateTokens(block),+ profileUri,+ profileChars: profile?.length ?? 0,+ prefCount: prefs.length,+ entCount: ents.length,+ droppedPref: prefBlock.dropped,+ droppedEnt: entBlock.dropped,+ };+}diff --git a/examples/claude-code-memory-plugin/scripts/ov-status.mjs b/examples/claude-code-memory-plugin/scripts/ov-status.mjsnew file mode 100644index 000000000..bf162a1d8--- /dev/null+++ b/examples/claude-code-memory-plugin/scripts/ov-status.mjs@@ -0,0 +1,148 @@+#!/usr/bin/env node++/**+ * Status report for the OpenViking memory plugin — invoked by the `/ov`+ * slash command. Prints a tight human-readable summary covering:+ * - Server URL + /health probe+ * - Resolved identity (account/user/agent)+ * - Last session-start injection (size, age, audit path)+ * - Last auto-recall (item count, top score, token budget use)+ * - Toggle state for the three injection paths+ * - Auth source — which file/env actually drove url + api_key, mirroring+ * config.mjs's priority chain (env → ovcli.conf → ov.conf → default)+ *+ * Reads the same state files the statusline uses (~/.openviking/state/)+ * plus the audit file written by session-start.mjs.+ */++import { existsSync, readFileSync, statSync } from "node:fs";+import { homedir } from "node:os";+import { join, resolve as resolvePath } from "node:path";++import { isPluginEnabled, loadConfig } from "./config.mjs";+import { makeFetchJSON } from "./lib/ov-session.mjs";+import { readJsonState } from "./lib/state.mjs";++function expandHome(p) {+ return p ? resolvePath(p.replace(/^~(?=$|\/)/, homedir())) : p;+}++function tryReadJson(path) {+ try {+ return JSON.parse(readFileSync(path, "utf-8"));+ } catch {+ return null;+ }+}++function fmtBytes(n) {+ if (n == null) return "?";+ if (n < 1024) return `${n} B`;+ if (n < 1024 * 1024) return `${(n / 1024).toFixed(1)} KB`;+ return `${(n / 1024 / 1024).toFixed(1)} MB`;+}++function fmtAge(ts) {+ if (!ts) return "never";+ const sec = Math.floor((Date.now() - ts) / 1000);+ if (sec < 0) return "just now";+ if (sec < 60) return `${sec}s ago`;+ if (sec < 3600) return `${Math.floor(sec / 60)}m ago`;+ if (sec < 86400) return `${Math.floor(sec / 3600)}h ago`;+ return `${Math.floor(sec / 86400)}d ago`;+}++function homeShort(path) {+ const h = homedir();+ return path && path.startsWith(h) ? "~" + path.slice(h.length) : path;+}++async function main() {+ if (!isPluginEnabled()) {+ console.log("OpenViking plugin: DISABLED (OPENVIKING_MEMORY_ENABLED=0 or no config found)");+ return;+ }++ const cfg = loadConfig();+ const fetchJSON = makeFetchJSON(cfg, "timeoutMs");++ // 1. Server / identity+ const t0 = Date.now();+ const health = await fetchJSON("/health");+ const latency = Date.now() - t0;+ console.log(`OpenViking — ${cfg.baseUrl} (${health.ok ? "✓" : "✗"} /health ${latency}ms)`);+ console.log(+ `Identity: account=${cfg.accountId || "(unset)"} ` ++ `user=${cfg.userId || "(server-resolved)"} agent=${cfg.agentId}`,+ );+ console.log("");++ // 2. Last session-start injection+ const lastInjectPath = join(homedir(), ".openviking", "last_inject.md");+ let injSize = null, injMtime = null;+ try {+ const st = statSync(lastInjectPath);+ injSize = st.size; injMtime = st.mtimeMs;+ } catch { /* none yet */ }+ if (injMtime) {+ console.log(`Last session-start injection: ${fmtAge(injMtime)}, ${fmtBytes(injSize)}`);+ console.log(` audit: ${homeShort(lastInjectPath)}`);+ } else {+ console.log("Last session-start injection: (none yet)");+ }++ // 3. Last auto-recall+ const recall = readJsonState("last-recall.json");+ if (recall) {+ const top = typeof recall.top_score === "number" ? recall.top_score.toFixed(2) : "?";+ const used = recall.tokens_used ?? 0;+ const budget = recall.tokens_budget ?? 0;+ console.log(+ `Last auto-recall: ${fmtAge(recall.ts)} — ${recall.count ?? 0} items, ` ++ `top ${top}, ${used}/${budget} tokens (${recall.reason || "ok"})`,+ );+ } else {+ console.log("Last auto-recall: (none yet)");+ }+ console.log("");++ // 4. Toggles+ console.log("Toggles:");+ console.log(` auto-inject: ${cfg.noAutoInject ? "OFF" : "on"} (profile budget=${cfg.profileTokenBudget})`);+ console.log(` auto-recall: ${cfg.autoRecall ? "on" : "OFF"} (recall budget=${cfg.recallTokenBudget})`);+ console.log(` auto-capture: ${cfg.autoCapture ? "on" : "OFF"}`);+ if (cfg.bypassSession) console.log(` ⚠ session bypass: GLOBAL ON`);+ if (cfg.bypassSessionPatterns?.length) {+ console.log(` bypass patterns: ${cfg.bypassSessionPatterns.join(", ")}`);+ }+ console.log("");++ // 5. Auth source — which file/env actually drove each value, mirroring+ // config.mjs's priority chain (env → ovcli.conf → ov.conf → default).+ // Computed rather than file-listed so we never advertise a source that+ // isn't actually in play.+ const cliConfPath = expandHome(process.env.OPENVIKING_CLI_CONFIG_FILE+ || join(homedir(), ".openviking", "ovcli.conf"));+ const ovConfPath = expandHome(process.env.OPENVIKING_CONFIG_FILE+ || join(homedir(), ".openviking", "ov.conf"));+ const cliConf = tryReadJson(cliConfPath);+ const ovConf = tryReadJson(ovConfPath);+ const cliShort = homeShort(cliConfPath);+ const ovShort = homeShort(ovConfPath);++ const urlSrc = (process.env.OPENVIKING_URL || process.env.OPENVIKING_BASE_URL) ? "env"+ : (cliConf?.url) ? cliShort+ : (ovConf?.server?.url) ? ovShort+ : "default";+ const keySrc = (process.env.OPENVIKING_API_KEY || process.env.OPENVIKING_BEARER_TOKEN) ? "env"+ : (cliConf?.api_key) ? cliShort+ : (ovConf?.claude_code?.apiKey) ? ovShort+ : (ovConf?.server?.root_api_key) ? ovShort+ : "(none)";+ console.log(`Auth: url from ${urlSrc}, api_key from ${keySrc}`);+}++main().catch((err) => {+ console.error("ov-status failed:", err?.message || err);+ process.exit(1);+});diff --git a/examples/claude-code-memory-plugin/scripts/session-start.mjs b/examples/claude-code-memory-plugin/scripts/session-start.mjsindex 6e5be6af5..79e1b9393 100644--- a/examples/claude-code-memory-plugin/scripts/session-start.mjs+++ b/examples/claude-code-memory-plugin/scripts/session-start.mjs@@ -3,13 +3,27 @@/*** SessionStart Hook for Claude Code.*- * When source in {"resume","compact"}, fetches the persistent OV session's- * latest_archive_overview and injects it as additionalContext wrapped in- * <openviking-context>. For "compact", this supplies OV's canonical- * long-term record alongside CC's own compact summary; for "resume",- * it re-hydrates the context that was lost when CC restarted.+ * Two independently-gated injections, composed into a single+ * <openviking-context source="..."> envelope returned via additionalContext:+ *+ * 1. Profile injection (every source: startup/clear/resume/compact unless+ * OPENVIKING_NO_AUTO_INJECT=1): full profile.md + description-annotated+ * ls of preferences/ and entities/. Total capped at+ * OPENVIKING_PROFILE_TOKEN_BUDGET (default 10000 tokens, CJK-aware).+ *+ * 2. Archive injection (resume/compact only): OV's persistent session's+ * latest_archive_overview + pre-archive abstracts, fetched at+ * OPENVIKING_RESUME_CONTEXT_BUDGET tokens. For "compact" this is OV's+ * canonical long-term record alongside CC's own compact summary; for+ * "resume" it re-hydrates context lost when CC restarted.+ *+ * The composed payload is mirrored to ~/.openviking/last_inject.md for audit.*/+import { mkdirSync, writeFileSync } from "node:fs";+import { homedir } from "node:os";+import { dirname, join } from "node:path";+import { isPluginEnabled, loadConfig } from "./config.mjs";import { createLogger } from "./debug-log.mjs";import {@@ -18,6 +32,7 @@ import {isBypassed,makeFetchJSON,} from "./lib/ov-session.mjs";+import { buildProfileBlock, estimateTokens } from "./lib/profile-inject.mjs";import { writeJsonState } from "./lib/state.mjs";if (!isPluginEnabled()) {@@ -45,29 +60,39 @@ function approve(additionalContext) {}/**- * Build <openviking-context> block from session context.- * Pulls latest_archive_overview (pre-archive abstracts list if populated).+ * Build the inner <session-archive> block from session context.+ * Returns null when there is no archive content yet.*/-function formatArchiveContext(sessionCtx, source) {+function formatArchiveSection(sessionCtx) {if (!sessionCtx || typeof sessionCtx !== "object") return null;const overview = (sessionCtx.latest_archive_overview || "").trim();if (!overview) return null;const abstracts = Array.isArray(sessionCtx.pre_archive_abstracts)- ? sessionCtx.pre_archive_abstracts.filter(a => typeof a === "string" && a.trim())+ ? sessionCtx.pre_archive_abstracts.filter((a) => typeof a === "string" && a.trim()): [];const lines = [- `<openviking-context source="${source}">`,+ "<session-archive>",` <archive-overview>${overview}</archive-overview>`,];for (const abs of abstracts.slice(0, 5)) {lines.push(` <archive-abstract>${abs.trim()}</archive-abstract>`);}- lines.push("</openviking-context>");+ lines.push("</session-archive>");return lines.join("\n");}+function writeLastInject(content) {+ try {+ const path = join(homedir(), ".openviking", "last_inject.md");+ mkdirSync(dirname(path), { recursive: true });+ writeFileSync(path, content, "utf-8");+ } catch {+ /* best effort — last_inject.md is for audit only */+ }+}+async function main() {let input = {};try {@@ -81,19 +106,19 @@ async function main() {const cwd = input.cwd;log("start", { source, sessionId });- // Only inject archive context on resume/compact. startup/clear get nothing.- if (source !== "resume" && source !== "compact") {- approve();- return;- }- if (!sessionId) {- log("skip", { reason: "no session_id" });+ if (isBypassed(cfg, { sessionId, cwd })) {+ log("skip", { reason: "bypass_session_pattern" });approve();return;}- if (isBypassed(cfg, { sessionId, cwd })) {- log("skip", { reason: "bypass_session_pattern" });+ // Short-circuit before the network probe when neither injection path will+ // run for this source/config combination. Saves a /health call and avoids+ // misleading "server unreachable" log noise when injection is disabled.+ const willInjectProfile = !cfg.noAutoInject;+ const willInjectArchive = (source === "resume" || source === "compact") && !!sessionId;+ if (!willInjectProfile && !willInjectArchive) {+ log("skip", { reason: "no_injection_planned", source, noAutoInject: cfg.noAutoInject });approve();return;}@@ -105,30 +130,75 @@ async function main() {return;}- const ovSessionId = deriveOvSessionId(sessionId);- const sessionCtx = await getSessionContext(fetchJSON, ovSessionId, cfg.resumeContextBudget);- const block = formatArchiveContext(sessionCtx, source);+ // 1. Profile injection — every source unless explicitly disabled.+ let profile = null;+ if (!cfg.noAutoInject) {+ try {+ profile = await buildProfileBlock(fetchJSON, cfg.profileTokenBudget);+ } catch (err) {+ logError("profile_inject", err);+ }+ }- // 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),- });+ // 2. Archive injection — resume/compact only, requires session_id.+ let archiveSection = null;+ let ovSessionId = null;+ if ((source === "resume" || source === "compact") && sessionId) {+ ovSessionId = deriveOvSessionId(sessionId);+ const sessionCtx = await getSessionContext(fetchJSON, ovSessionId, cfg.resumeContextBudget);+ archiveSection = formatArchiveSection(sessionCtx);+ }++ // One-shot signal for the statusline (preserved from prior behavior:+ // statusline expects this on every resume/compact, regardless of whether+ // OV had archive content to inject).+ if (source === "resume" || source === "compact") {+ writeJsonState("last-session-event.json", {+ source,+ cc_session_id: sessionId,+ ov_session_id: ovSessionId,+ had_context: Boolean(archiveSection),+ });+ }- if (!block) {- log("no_archive", { ovSessionId, source });+ // Compose. If both halves are empty, return without injecting.+ const sections = [];+ if (profile?.block) sections.push(profile.block);+ if (archiveSection) sections.push(archiveSection);++ if (sections.length === 0) {+ log("no_inject", { source, profile: !!profile, archive: !!archiveSection });approve();return;}- log("inject", { ovSessionId, source, blockLength: block.length });- approve(block);+ const composed = `<openviking-context source="${source}">\n${sections.join("\n")}\n</openviking-context>`;+ writeLastInject(composed);++ if (cfg.debug) {+ process.stderr.write(+ `[ov] session-start injected ~${composed.length} chars / ~${estimateTokens(composed)} tokens` ++ (profile ? ` (profile=${profile.profileChars} chars, prefs=${profile.prefCount}${profile.droppedPref ? `(+${profile.droppedPref} dropped)` : ""}, entities=${profile.entCount}${profile.droppedEnt ? `(+${profile.droppedEnt} dropped)` : ""})` : "") ++ (archiveSection ? " +archive" : "") ++ "\n",+ );+ }++ log("inject", {+ source,+ chars: composed.length,+ tokens: estimateTokens(composed),+ profile: profile && {+ tokens: profile.tokens,+ profileChars: profile.profileChars,+ prefCount: profile.prefCount,+ entCount: profile.entCount,+ droppedPref: profile.droppedPref,+ droppedEnt: profile.droppedEnt,+ },+ archive: Boolean(archiveSection),+ });+ approve(composed);}main().catch((err) => { logError("uncaught", err); approve(); });diff --git a/examples/claude-code-memory-plugin/scripts/subagent-stop.mjs b/examples/claude-code-memory-plugin/scripts/subagent-stop.mjsindex a2b239122..7d2f5bb28 100644--- a/examples/claude-code-memory-plugin/scripts/subagent-stop.mjs+++ b/examples/claude-code-memory-plugin/scripts/subagent-stop.mjs@@ -68,26 +68,27 @@ function parseTranscript(content) {return out;}-// Per-block cap for tool input / tool result snippets. Sized to keep most invocations-// verbatim while bounding worst-case blowup. Mirrors auto-capture.mjs.-const TOOL_BLOCK_MAX_CHARS = 4096;--function truncateForLog(value) {- let s;- if (typeof value === "string") {- s = value;- } else {- try {- s = JSON.stringify(value, null, 2);- } catch {- s = String(value);- }+// Tool result (output) retention. 0 = drop tool_result entirely; >0 = keep, truncated.+// Default 0 — see auto-capture.mjs for rationale. Mirrors auto-capture.mjs.+const TOOL_RESULT_MAX_CHARS = 0;++function formatToolInput(value) {+ // Tool inputs are agent-authored; we keep them verbatim.+ if (typeof value === "string") return value;+ try {+ return JSON.stringify(value, null, 2);+ } catch {+ return String(value);}- if (typeof s !== "string") s = "";- if (s.length <= TOOL_BLOCK_MAX_CHARS) return s;+}++function truncateToolResult(s) {+ if (TOOL_RESULT_MAX_CHARS <= 0) return null; // drop+ if (typeof s !== "string") s = String(s ?? "");+ if (s.length <= TOOL_RESULT_MAX_CHARS) return s;return (- s.slice(0, TOOL_BLOCK_MAX_CHARS) +- `\n... [truncated, ${s.length - TOOL_BLOCK_MAX_CHARS} more chars]`+ s.slice(0, TOOL_RESULT_MAX_CHARS) ++ `\n... [truncated, ${s.length - TOOL_RESULT_MAX_CHARS} more chars]`);}@@ -103,8 +104,8 @@ function extractToolResultText(content) {/*** Tier-1 parts extraction — shared shape with auto-capture.mjs.* Kept inline here so SubagentStop does not import auto-capture's globals.- * Inlines tool_use input + tool_result content (truncated) so the memory extractor- * sees what the subagent actually fetched/read/searched, not just tool names.+ * Inlines tool_use input verbatim; tool_result content is dropped by default+ * (TOOL_RESULT_MAX_CHARS = 0) and retained only if explicitly enabled.*/function extractTurns(messages) {const turns = [];@@ -125,11 +126,12 @@ function extractTurns(messages) {parts.push(block.text);} else if (block.type === "tool_use" && typeof block.name === "string") {toolNames.push(block.name);- parts.push(`[tool: ${block.name}]\n${truncateForLog(block.input)}`);+ parts.push(`[tool: ${block.name}]\n${formatToolInput(block.input)}`);} else if (block.type === "tool_result") {const resultText = extractToolResultText(block.content);- if (resultText) {- parts.push(`[tool result]\n${truncateForLog(resultText)}`);+ const truncated = resultText ? truncateToolResult(resultText) : null;+ if (truncated) {+ parts.push(`[tool result]\n${truncated}`);}}}