From eb94be3045e7554574444a77139c313ac5a15ca0 Mon Sep 17 00:00:00 2001 From: "zhengxiao.wu" Date: Fri, 8 May 2026 17:18:33 +0800 Subject: [PATCH 1/4] feat(claude-code-plugin): inject user profile + memory listings on session start MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Previously, profile/preferences/entities only reached the agent when the user's prompt happened to trigger semantic auto-recall (UserPromptSubmit). Trivial first prompts (e.g. `git status`) left the agent with no identity context. Session-start hook now always builds a profile injection block — profile.md plus a description-annotated recursive ls of preferences/ and entities/ — composed into the same envelope that already carries archive context on resume/compact. Subagents are unaffected (they go through subagent-start.mjs). Budget enforcement uses a CJK-aware token estimate (codepoint >= 0x3000 counts at 1.5 tokens, else chars/4) so a "10k token budget" reflects real tokenizer cost for Chinese content rather than the 4-6× undercount the flat chars/4 heuristic produces. Profile truncation on overflow keeps the head (identity facts) and tail (most-recent timeline events), eliding the noisy middle, instead of hard-cutting at the head. Each invocation mirrors the composed payload to ~/.openviking/last_inject.md for user-facing audit. New env vars / config (config.mjs): - OPENVIKING_NO_AUTO_INJECT (bool, default false) — kill switch for the new injection; auto-recall is unaffected. - OPENVIKING_PROFILE_TOKEN_BUDGET (int, default 10000) — total cap for the block; profile gets up to half, listings split the remainder. --- .../scripts/config.mjs | 12 + .../scripts/lib/profile-inject.mjs | 252 ++++++++++++++++++ .../scripts/session-start.mjs | 143 +++++++--- 3 files changed, 367 insertions(+), 40 deletions(-) create mode 100644 examples/claude-code-memory-plugin/scripts/lib/profile-inject.mjs diff --git a/examples/claude-code-memory-plugin/scripts/config.mjs b/examples/claude-code-memory-plugin/scripts/config.mjs index f21ac038c79..00034201415 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.mjs new file mode 100644 index 00000000000..2366cb1e73b --- /dev/null +++ b/examples/claude-code-memory-plugin/scripts/lib/profile-inject.mjs @@ -0,0 +1,252 @@ +/** + * Session-start profile injection helper. + * + * Builds a + block from + * viking://user//memories/profile.md + * viking://user//memories/preferences/ (ls with abstracts) + * viking://user//memories/entities/ (ls with abstracts) + * + * Budget enforced via chars/4 token estimate (matches auto-recall.mjs:205-207). + * + * Returned block is the *inner* content only (no outer ); + * 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. + */ +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); +} + +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: + * //.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: + * + * ... [profile middle elided] ... + * + * + * Falls back to head-only truncate when the file is too short to elide + * meaningfully ( + 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 lines = [header]; + let used = estimateTokens(header); + let included = 0; + 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 && included > 0) { + const remaining = entries.length - i; + const tail = ` ... +${remaining} more, use \`memory_recall\``; + lines.push(tail); + return { lines, used: used + estimateTokens(tail), dropped: remaining }; + } + lines.push(line); + used += tokens; + included++; + } + 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 / + * payload — the caller wraps it in . + * + * @param {Function} fetchJSON ov-session.mjs:makeFetchJSON closure + * @param {number} totalBudgetTokens chars/4 budget, total for the whole block + * @returns {Promise} + */ +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(``); + lines.push(profileTrunc); + lines.push(``); + } + if (prefBlock.lines.length > 0 || entBlock.lines.length > 0) { + lines.push(``); + lines.push(...prefBlock.lines); + lines.push(...entBlock.lines); + lines.push(``); + } + + const block = lines.join("\n"); + return { + block, + chars: block.length, + tokens: estimateTokens(block), + profileUri, + profileBytes: profile?.length ?? 0, + prefCount: prefs.length, + entCount: ents.length, + droppedPref: prefBlock.dropped, + droppedEnt: entBlock.dropped, + }; +} diff --git a/examples/claude-code-memory-plugin/scripts/session-start.mjs b/examples/claude-code-memory-plugin/scripts/session-start.mjs index 6e5be6af595..936ba5fdc41 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 - * . 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 + * 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 5000 tokens). + * + * 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 } from "./lib/profile-inject.mjs"; import { writeJsonState } from "./lib/state.mjs"; if (!isPluginEnabled()) { @@ -44,30 +59,44 @@ function approve(additionalContext) { output(out); } +function estimateTokens(text) { + return text ? Math.ceil(text.length / 4) : 0; +} + /** - * Build block from session context. - * Pulls latest_archive_overview (pre-archive abstracts list if populated). + * Build the inner 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 = [ - ``, + "", ` ${overview}`, ]; for (const abs of abstracts.slice(0, 5)) { lines.push(` ${abs.trim()}`); } - lines.push(""); + lines.push(""); 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,17 +110,6 @@ 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" }); - approve(); - return; - } - if (isBypassed(cfg, { sessionId, cwd })) { log("skip", { reason: "bypass_session_pattern" }); approve(); @@ -105,30 +123,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), + }); + } + + // Compose. If both halves are empty, return without injecting. + const sections = []; + if (profile?.block) sections.push(profile.block); + if (archiveSection) sections.push(archiveSection); - if (!block) { - log("no_archive", { ovSessionId, source }); + 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 = `\n${sections.join("\n")}\n`; + writeLastInject(composed); + + if (cfg.debug) { + process.stderr.write( + `[ov] session-start injected ~${composed.length} chars / ~${estimateTokens(composed)} tokens` + + (profile ? ` (profile=${profile.profileBytes}B, 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, + profileBytes: profile.profileBytes, + prefCount: profile.prefCount, + entCount: profile.entCount, + droppedPref: profile.droppedPref, + droppedEnt: profile.droppedEnt, + }, + archive: Boolean(archiveSection), + }); + approve(composed); } main().catch((err) => { logError("uncaught", err); approve(); }); From a4b5d4096dc386ab42e3a39c0048559cfff02f3e Mon Sep 17 00:00:00 2001 From: "zhengxiao.wu" Date: Fri, 8 May 2026 17:18:42 +0800 Subject: [PATCH 2/4] feat(claude-code-plugin): add /ov slash command for plugin status MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Tight five-section status report covering: server URL + /health latency, resolved identity (account/user/agent), last session-start injection (size, age, audit-file path), last auto-recall (item count, top score, token budget use), and toggle state for the three injection paths (auto-inject / auto-recall / auto-capture). Final line shows where url + api_key were actually resolved from (env vs ovcli.conf vs default), per the same priority chain config.mjs uses — rather than enumerating every file on disk that *could have* contributed. Reuses existing ~/.openviking/state/ files (last-recall.json, last-session-event.json) and the audit file written by session-start.mjs; no new server-side state. --- .../claude-code-memory-plugin/commands/ov.md | 5 + .../scripts/ov-status.mjs | 129 ++++++++++++++++++ 2 files changed, 134 insertions(+) create mode 100644 examples/claude-code-memory-plugin/commands/ov.md create mode 100644 examples/claude-code-memory-plugin/scripts/ov-status.mjs diff --git a/examples/claude-code-memory-plugin/commands/ov.md b/examples/claude-code-memory-plugin/commands/ov.md new file mode 100644 index 00000000000..8aeb0ad0165 --- /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.mjs diff --git a/examples/claude-code-memory-plugin/scripts/ov-status.mjs b/examples/claude-code-memory-plugin/scripts/ov-status.mjs new file mode 100644 index 00000000000..ccb8611c133 --- /dev/null +++ b/examples/claude-code-memory-plugin/scripts/ov-status.mjs @@ -0,0 +1,129 @@ +#!/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 + * - Active config file + env overrides currently in effect + * + * Reads the same state files the statusline uses (~/.openviking/state/) + * plus the audit file written by session-start.mjs. + */ + +import { existsSync, 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 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 — single source of truth for url+api_key. We compute which + // file/env actually drove each value rather than listing every file on disk + // that "could have" contributed: that gives the false impression of competing + // sources when there's just one chain (env → ovcli.conf → ov.conf → default, + // first hit wins per field). + const cliConfPath = expandHome(process.env.OPENVIKING_CLI_CONFIG_FILE + || join(homedir(), ".openviking", "ovcli.conf")); + const cliExists = existsSync(cliConfPath); + const urlSrc = process.env.OPENVIKING_URL || process.env.OPENVIKING_BASE_URL + ? "env" : (cliExists ? homeShort(cliConfPath) : "default"); + const keySrc = process.env.OPENVIKING_API_KEY || process.env.OPENVIKING_BEARER_TOKEN + ? "env" : (cliExists ? homeShort(cliConfPath) : "(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); +}); From 0014879ac691465e64bdf8855f1b78dc8d703a71 Mon Sep 17 00:00:00 2001 From: "zhengxiao.wu" Date: Tue, 5 May 2026 11:26:00 +0800 Subject: [PATCH 3/4] fix(cc-memory-plugin): drop tool output by default; keep tool input verbatim MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit After #1849 / #1850 the plugin captured tool I/O at a 4 KB-per-block cap under one knob (TOOL_BLOCK_MAX_CHARS = 4096). Field thinking surfaced two refinements: 1. **Tool *output* (tool_result content) is mostly noise for memory extraction.** Memory extraction cares about user preferences, project context, decisions, and what the agent did — not about the bytes a tool happened to return. The agent's prose around the tool call almost always summarizes the meaningful bit ("I checked the docs and confirmed X"); the raw 4 KB of fetched markdown adds nothing the prose doesn't already cover. Storing it just inflates session size and extraction token cost. Renamed TOOL_BLOCK_MAX_CHARS → TOOL_RESULT_MAX_CHARS and changed default to 0. When 0, tool_result blocks are dropped entirely. Operators wanting replay-style archives can set >0 to retain truncated output. 2. **Tool *input* should not be truncated.** Inputs are agent-authored (URLs, file paths, queries, commands). They're usually short, and a pathologically long input is itself signal worth surfacing — a memory extractor seeing "agent ran `bash` with a 10 KB script" learns something the truncated form would hide. Replaced truncateForLog(block.input) with formatToolInput(block.input), which JSON-serializes structured inputs but applies no length cap. Both changes apply symmetrically to auto-capture.mjs and subagent-stop.mjs. --- .../scripts/auto-capture.mjs | 58 ++++++++++--------- .../scripts/subagent-stop.mjs | 48 +++++++-------- 2 files changed, 57 insertions(+), 49 deletions(-) diff --git a/examples/claude-code-memory-plugin/scripts/auto-capture.mjs b/examples/claude-code-memory-plugin/scripts/auto-capture.mjs index 69cdbf79609..14278d16ff7 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/subagent-stop.mjs b/examples/claude-code-memory-plugin/scripts/subagent-stop.mjs index a2b23912260..7d2f5bb28a0 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}`); } } } From 50cb40a4516de55d1825b57e454f5ac66b2bf3fd Mon Sep 17 00:00:00 2001 From: "zhengxiao.wu" Date: Fri, 8 May 2026 18:44:50 +0800 Subject: [PATCH 4/4] fix(claude-code-plugin): address Copilot review on PR #1914 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Nine review comments, all valid: profile-inject.mjs: - header doc said chars/4 but estimateTokens is CJK-aware → fixed - estimateTokens now exported so callers can log token counts that match the budget logic - elideProfile derived maxChars from maxTokens*4, but the estimator counts CJK at 1.5 tokens/char → for CJK profiles the truncated string could still bust the token cap. New tokensToCharsBudget() converts using the content's actual CJK density - formatListing always included header + first entry, so very small budgets silently violated the cap. Now: stub-out when header alone exceeds budget; only emit "+N more" tail when it fits; close silently otherwise - profileBytes was UTF-16 char count, labeled "B" → renamed to profileChars session-start.mjs: - header doc said budget=5000, code default is 10000 → doc fix - local estimateTokens was flat chars/4 while injection enforces CJK-aware budget → import the shared estimator from profile-inject so logs match reality - /health probe ran even when no injection path would fire (e.g. NO_AUTO_INJECT=1 + startup) → short-circuit before the network call - profileBytes references updated to profileChars ov-status.mjs: - header doc said "Active config file + env overrides" but the bottom block was removed earlier → header fixed to describe Auth source - auth source detection only considered env + ovcli.conf; could misreport "(none)" when key was actually coming from ov.conf claude_code.apiKey or server.root_api_key. Now mirrors config.mjs's full priority chain (env → ovcli.conf → ov.conf → default) --- .../scripts/lib/profile-inject.mjs | 59 +++++++++++++++---- .../scripts/ov-status.mjs | 43 ++++++++++---- .../scripts/session-start.mjs | 23 +++++--- 3 files changed, 93 insertions(+), 32 deletions(-) diff --git a/examples/claude-code-memory-plugin/scripts/lib/profile-inject.mjs b/examples/claude-code-memory-plugin/scripts/lib/profile-inject.mjs index 2366cb1e73b..c7ce3dc266f 100644 --- a/examples/claude-code-memory-plugin/scripts/lib/profile-inject.mjs +++ b/examples/claude-code-memory-plugin/scripts/lib/profile-inject.mjs @@ -6,7 +6,10 @@ * viking://user//memories/preferences/ (ls with abstracts) * viking://user//memories/entities/ (ls with abstracts) * - * Budget enforced via chars/4 token estimate (matches auto-recall.mjs:205-207). + * 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 ); * session-start.mjs composes the outer wrapper so the archive block can sit @@ -64,7 +67,7 @@ async function resolveUserSpace(fetchJSON) { * 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. */ -function estimateTokens(text) { +export function estimateTokens(text) { if (!text) return 0; let cjk = 0; for (let i = 0; i < text.length; i++) { @@ -74,6 +77,24 @@ function estimateTokens(text) { 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; @@ -125,8 +146,11 @@ async function lsDir(fetchJSON, dirUri) { * both head and a useful tail. */ function elideProfile(content, maxTokens) { - const maxChars = Math.max(400, maxTokens * 4); - if (content.length <= maxChars) return content; + // 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"; @@ -160,9 +184,15 @@ function formatListing(headerUri, entries, budgetTokens) { // 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 = estimateTokens(header); - let included = 0; + let used = headerTokens; for (let i = 0; i < entries.length; i++) { const e = entries[i]; const desc = e.abstract @@ -170,15 +200,20 @@ function formatListing(headerUri, entries, budgetTokens) { : ""; const line = ` - ${e.name}${desc}`; const tokens = estimateTokens(line); - if (used + tokens > budgetTokens && included > 0) { + if (used + tokens > budgetTokens) { const remaining = entries.length - i; const tail = ` ... +${remaining} more, use \`memory_recall\``; - lines.push(tail); - return { lines, used: used + estimateTokens(tail), dropped: remaining }; + 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; - included++; } return { lines, used, dropped: 0 }; } @@ -194,7 +229,7 @@ function formatListing(headerUri, entries, budgetTokens) { * @param {number} totalBudgetTokens chars/4 budget, total for the whole block * @returns {Promise} */ @@ -243,7 +278,7 @@ export async function buildProfileBlock(fetchJSON, totalBudgetTokens) { chars: block.length, tokens: estimateTokens(block), profileUri, - profileBytes: profile?.length ?? 0, + profileChars: profile?.length ?? 0, prefCount: prefs.length, entCount: ents.length, droppedPref: prefBlock.dropped, diff --git a/examples/claude-code-memory-plugin/scripts/ov-status.mjs b/examples/claude-code-memory-plugin/scripts/ov-status.mjs index ccb8611c133..bf162a1d8fc 100644 --- a/examples/claude-code-memory-plugin/scripts/ov-status.mjs +++ b/examples/claude-code-memory-plugin/scripts/ov-status.mjs @@ -8,13 +8,14 @@ * - 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 - * - Active config file + env overrides currently in effect + * - 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, statSync } from "node:fs"; +import { existsSync, readFileSync, statSync } from "node:fs"; import { homedir } from "node:os"; import { join, resolve as resolvePath } from "node:path"; @@ -26,6 +27,14 @@ 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`; @@ -108,18 +117,28 @@ async function main() { } console.log(""); - // 5. Auth source — single source of truth for url+api_key. We compute which - // file/env actually drove each value rather than listing every file on disk - // that "could have" contributed: that gives the false impression of competing - // sources when there's just one chain (env → ovcli.conf → ov.conf → default, - // first hit wins per field). + // 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 cliExists = existsSync(cliConfPath); - const urlSrc = process.env.OPENVIKING_URL || process.env.OPENVIKING_BASE_URL - ? "env" : (cliExists ? homeShort(cliConfPath) : "default"); - const keySrc = process.env.OPENVIKING_API_KEY || process.env.OPENVIKING_BEARER_TOKEN - ? "env" : (cliExists ? homeShort(cliConfPath) : "(none)"); + 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}`); } diff --git a/examples/claude-code-memory-plugin/scripts/session-start.mjs b/examples/claude-code-memory-plugin/scripts/session-start.mjs index 936ba5fdc41..79e1b939386 100644 --- a/examples/claude-code-memory-plugin/scripts/session-start.mjs +++ b/examples/claude-code-memory-plugin/scripts/session-start.mjs @@ -9,7 +9,7 @@ * 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 5000 tokens). + * 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 @@ -32,7 +32,7 @@ import { isBypassed, makeFetchJSON, } from "./lib/ov-session.mjs"; -import { buildProfileBlock } from "./lib/profile-inject.mjs"; +import { buildProfileBlock, estimateTokens } from "./lib/profile-inject.mjs"; import { writeJsonState } from "./lib/state.mjs"; if (!isPluginEnabled()) { @@ -59,10 +59,6 @@ function approve(additionalContext) { output(out); } -function estimateTokens(text) { - return text ? Math.ceil(text.length / 4) : 0; -} - /** * Build the inner block from session context. * Returns null when there is no archive content yet. @@ -116,6 +112,17 @@ async function main() { return; } + // 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; + } + const health = await fetchJSON("/health"); if (!health.ok) { logError("health_check", "server unreachable"); @@ -171,7 +178,7 @@ async function main() { if (cfg.debug) { process.stderr.write( `[ov] session-start injected ~${composed.length} chars / ~${estimateTokens(composed)} tokens` + - (profile ? ` (profile=${profile.profileBytes}B, prefs=${profile.prefCount}${profile.droppedPref ? `(+${profile.droppedPref} dropped)` : ""}, entities=${profile.entCount}${profile.droppedEnt ? `(+${profile.droppedEnt} dropped)` : ""})` : "") + + (profile ? ` (profile=${profile.profileChars} chars, prefs=${profile.prefCount}${profile.droppedPref ? `(+${profile.droppedPref} dropped)` : ""}, entities=${profile.entCount}${profile.droppedEnt ? `(+${profile.droppedEnt} dropped)` : ""})` : "") + (archiveSection ? " +archive" : "") + "\n", ); @@ -183,7 +190,7 @@ async function main() { tokens: estimateTokens(composed), profile: profile && { tokens: profile.tokens, - profileBytes: profile.profileBytes, + profileChars: profile.profileChars, prefCount: profile.prefCount, entCount: profile.entCount, droppedPref: profile.droppedPref,