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
fix(openclaw): commit the generated shared runtime copies again (#5062)
t0saki31f017bc167a
diff --git a/.github/workflows/plugin-shared-sync.yml b/.github/workflows/plugin-shared-sync.ymlindex 39b5c091a..f7df41eaa 100644--- a/.github/workflows/plugin-shared-sync.yml+++ b/.github/workflows/plugin-shared-sync.yml@@ -1,8 +1,8 @@name: Plugin Shared Runtime Sync# The plugins a host installs by pointing at a directory in this repository —-# Claude Code, Codex, and the Agent Plugins package — can only load files git-# holds, so their copies of the shared runtime have to be committed. Generating+# Claude Code, Codex, the Agent Plugins package, and OpenClaw through+# ov-install's GitHub source — can only load files git holds, so their copies of the shared runtime have to be committed. Generating# them by hand is what let a copy go stale on main while the pull request that# changed the library looked complete. This regenerates them after the merge.#@@ -18,6 +18,7 @@ on:- "examples/skills/**"- "examples/claude-code-memory-plugin/**"- "examples/codex-memory-plugin/**"+ - "examples/openclaw-plugin/**"- "agent-plugins/**"workflow_dispatch:diff --git a/.gitignore b/.gitignoreindex 110d53d6e..456c4257a 100644--- a/.gitignore+++ b/.gitignore@@ -248,4 +248,3 @@ node_modules/examples/opencode-plugin/lib/shared/examples/dsh-memory-plugin/shared/examples/pi-coding-agent-extension/shared/-examples/openclaw-plugin/shared/diff --git a/docs/en/agent-integrations/16-capability-reference.md b/docs/en/agent-integrations/16-capability-reference.mdindex e61881c54..544dedc4a 100644--- a/docs/en/agent-integrations/16-capability-reference.md+++ b/docs/en/agent-integrations/16-capability-reference.md@@ -112,7 +112,7 @@ Supporting mechanisms:The `examples/memory-plugin-shared/lib/` directory contains 25 `.mjs` modules and serves as the single source of truth for all JS-based harnesses. These are consumed in two ways:-1. **Vendoring (copying)**: The `sync.mjs` script distributes these modules to 7 targets, prefixing every file with `// GENERATED FROM ... DO NOT EDIT.`. Because of this added line, a vendored copy's line number will be exactly one line greater than the library source. There is no hand-kept file list: each target gets the transitive closure of the modules its own code imports. Claude Code, Codex and agent-plugins are installed by pointing a host at a directory in this repository, so their generated copies are committed and a push to main regenerates them. OpenCode, DSH and OpenClaw publish as npm packages and pi is tarred by the installer, so those four generate their copies at pack time and keep none in git.+1. **Vendoring (copying)**: The `sync.mjs` script distributes these modules to 7 targets, prefixing every file with `// GENERATED FROM ... DO NOT EDIT.`. Because of this added line, a vendored copy's line number will be exactly one line greater than the library source. There is no hand-kept file list: each target gets the transitive closure of the modules its own code imports. Claude Code, Codex and agent-plugins are installed by pointing a host at a directory in this repository, and OpenClaw's `ov-install` can download the plugin file by file from a git ref, so these four commit their generated copies and a push to main regenerates them. OpenCode and DSH publish as npm packages and pi is tarred by the installer, so those three generate their copies at pack time and keep none in git.2. **Direct import via relative path (no copying)**: cursor, trae, trae-cn and zcode directly `import "../../memory-plugin-shared/lib/..."`. The installer copies the package alongside the shared modules those hooks transitively import into `~/.openviking/agent-integrations/{<client>,memory-plugin-shared}/`, preserving the relative folder layout. That installed set is closed under imports, including the workspace configuration layer the hook runtime reaches. At runtime, these harnesses share this directory, so reinstalling any one of them overwrites the shared directory wholesale.Core modules at a glance (detailed further in the per-dimension sections):diff --git a/docs/en/agent-integrations/18-plugin-development.md b/docs/en/agent-integrations/18-plugin-development.mdindex 51c6ef129..99a08f7b5 100644--- a/docs/en/agent-integrations/18-plugin-development.md+++ b/docs/en/agent-integrations/18-plugin-development.md@@ -319,8 +319,8 @@ Use explicit relative imports. Where shared modules have TypeScript consumers, k| Distribution | Current examples | Requirement || --- | --- | --- |-| Host loads a plugin directory directly from Git | Claude Code, Codex, `agent-plugins` | Commit shared copies so a checkout is loadable |-| npm package or installation archive | OpenCode, DSH, OpenClaw, Pi | Generate during prepack or staging; do not commit runtime copies |+| Host loads a plugin directory directly from Git | Claude Code, Codex, `agent-plugins`, OpenClaw (`ov-install` GitHub source) | Commit shared copies so a checkout is loadable |+| npm package or installation archive | OpenCode, DSH, Pi | Generate during prepack or staging; do not commit runtime copies || Installer assembles an adjacent runtime directory | Cursor, TRAE, TRAE CN, ZCode | Derive `lib/MANIFEST` from `ASSEMBLED_ROOTS` and copy runtime modules from it |Register these targets in [`sync.mjs`](https://github.com/volcengine/OpenViking/blob/main/examples/memory-plugin-shared/sync.mjs). For separate plugins, add the source root, output directory, and `committed` policy to `TARGETS`. Extend `ASSEMBLED_ROOTS` only for a new assembled root; ordinary thin hosts are usually covered already. Register skill delivery separately in `SKILL_TARGETS`. Do not maintain a manual list of runtime modules to copy.diff --git a/docs/zh/agent-integrations/16-capability-reference.md b/docs/zh/agent-integrations/16-capability-reference.mdindex fc1be2b2a..46fdcc76b 100644--- a/docs/zh/agent-integrations/16-capability-reference.md+++ b/docs/zh/agent-integrations/16-capability-reference.md@@ -113,7 +113,7 @@ per-harness 章节(档案卡)只写差异;所有共享事实均在本章`examples/memory-plugin-shared/lib/` 下共 25 个 `.mjs` 模块,是 JS 系 harness 的唯一事实源。两种消费形态:-1. **Vendoring(复制)**:由 `sync.mjs` 分发到 7 个目标,每个文件首行加 `// GENERATED FROM ... DO NOT EDIT.`(因此 vendored 副本行号 = lib 源行号 + 1)。分发清单不再手写:每个目标拿的是自身代码实际 import 的传递闭包。claude-code、codex、agent-plugins 由宿主直接指向仓库目录安装,所以生成副本提交进 git,并由 main 上的推送重新生成;opencode、dsh、openclaw 以 npm 包发布,pi 由安装脚本打包,这四个在打包时生成副本,git 中不保留。+1. **Vendoring(复制)**:由 `sync.mjs` 分发到 7 个目标,每个文件首行加 `// GENERATED FROM ... DO NOT EDIT.`(因此 vendored 副本行号 = lib 源行号 + 1)。分发清单不再手写:每个目标拿的是自身代码实际 import 的传递闭包。claude-code、codex、agent-plugins 由宿主直接指向仓库目录安装,openclaw 的 `ov-install` 可以按 git ref 逐个文件下载插件,所以这四个的生成副本提交进 git,并由 main 上的推送重新生成;opencode、dsh 以 npm 包发布,pi 由安装脚本打包,这三个在打包时生成副本,git 中不保留。2. **相对路径直接 import(不复制)**:cursor / trae / trae-cn / zcode 直接 `import "../../memory-plugin-shared/lib/..."`;安装器把包与这些 hook 传递 import 到的共享模块一起复制到 `~/.openviking/agent-integrations/{<client>,memory-plugin-shared}/`,保持相对层级。这份安装集合对 import 闭合,包括 hook 运行时所需的 workspace 配置层。运行期几个 harness 共用该目录,任一重装都会整体覆盖。核心模块速览(细节在各维度章展开):diff --git a/docs/zh/agent-integrations/18-plugin-development.md b/docs/zh/agent-integrations/18-plugin-development.mdindex 541f088d2..87898af1b 100644--- a/docs/zh/agent-integrations/18-plugin-development.md+++ b/docs/zh/agent-integrations/18-plugin-development.md@@ -319,8 +319,8 @@ examples/<host>-memory-plugin/ 独立原生插件需要时才创建| 交付方式 | 当前例子 | 生成要求 || --- | --- | --- |-| 宿主直接加载 Git 中的插件目录 | Claude Code、Codex、`agent-plugins` | 共享副本提交到 Git,checkout 后即可加载 |-| npm 包或安装归档 | OpenCode、DSH、OpenClaw、Pi | 在 prepack 或 staging 时生成;运行时副本不提交 Git |+| 宿主直接加载 Git 中的插件目录 | Claude Code、Codex、`agent-plugins`、OpenClaw(`ov-install` 的 GitHub 源) | 共享副本提交到 Git,checkout 后即可加载 |+| npm 包或安装归档 | OpenCode、DSH、Pi | 在 prepack 或 staging 时生成;运行时副本不提交 Git || 安装器组装相邻运行时目录 | Cursor、TRAE、TRAE CN、ZCode | 使用 `ASSEMBLED_ROOTS` 推导 `lib/MANIFEST`,按 manifest 复制共享运行时 |[`sync.mjs`](https://github.com/volcengine/OpenViking/blob/main/examples/memory-plugin-shared/sync.mjs) 是上述目标的登记处。新增独立插件登记 `TARGETS` 的 source root、目标目录和 `committed`;新增组装根才扩展 `ASSEMBLED_ROOTS`,普通薄宿主通常已被现有根覆盖。是否交付 Skill 另外登记 `SKILL_TARGETS`。不要维护一份“需要复制的 20 个模块”清单。diff --git a/examples/memory-plugin-shared/sync.mjs b/examples/memory-plugin-shared/sync.mjsindex 4612bfced..43d34bcf0 100644--- a/examples/memory-plugin-shared/sync.mjs+++ b/examples/memory-plugin-shared/sync.mjs@@ -52,10 +52,12 @@ export const TARGETS = [dir: join(ROOT, "examples", "pi-coding-agent-extension", "shared"),committed: false,},+ // Published as a package too, but ov-install's GitHub source downloads the+ // plugin file by file at a git ref, and it has no way to run this generator.{root: join(ROOT, "examples", "openclaw-plugin"),dir: join(ROOT, "examples", "openclaw-plugin", "shared"),- committed: false,+ committed: true,},];diff --git a/examples/openclaw-plugin/shared/recall-compress-core.mjs b/examples/openclaw-plugin/shared/recall-compress-core.mjsnew file mode 100644index 000000000..1ced4cf4d--- /dev/null+++ b/examples/openclaw-plugin/shared/recall-compress-core.mjs@@ -0,0 +1,206 @@+// GENERATED FROM examples/memory-plugin-shared/lib. DO NOT EDIT.+import { createHash } from "node:crypto";+import { mkdir, readFile, rename, writeFile } from "node:fs/promises";+import { dirname } from "node:path";++export const NO_RELEVANT_MEMORY = "NO_RELEVANT_MEMORY";+export const DIGEST_HEADER = "OpenViking memory digest:";+const COMPRESS_OK = "ok";+const COMPRESS_EMPTY = "empty";+const COMPRESS_FAILED = "failed";++// Medium-constraint prompt: state the goal and two structural floors, but no hard+// bullet-length contract. Hard per-bullet limits pin the digest to headline+// density; leaving it unconstrained lets small models rewrite long URIs into dead+// links, which the URI repair below cleans up.+export function buildRecallCompressionPrompt({ query, rendered, maxBullets = 6 }) {+ return `You are a memory relevance compressor utility.+Do not use any tools. Do not investigate. Only transform the given text.++User query:+${query}++Retrieved OpenViking context fragments:+${rendered}++Write a memory digest for a coding agent about to answer that query. Keep the+concrete facts (paths, identifiers, decisions, constraints); drop pleasantries+and conversational filler.++Format rules:+- Group related facts by topic, one bullet per topic, at most ${maxBullets} bullets.+- Start every bullet with "- ".+- End every bullet with its source, copied verbatim from the fragments above:+ "来源:viking://..." or "source: viking://...". Never edit, shorten, or invent a URI.+- Output the digest body only. No preamble, no closing remark.++If nothing above is relevant to the query, output exactly: ${NO_RELEVANT_MEMORY}`;+}++function editDistance(a, b) {+ if (a === b) return 0;+ const rows = a.length + 1;+ const cols = b.length + 1;+ let prev = Array.from({ length: cols }, (_, i) => i);+ for (let i = 1; i < rows; i += 1) {+ const cur = [i];+ for (let j = 1; j < cols; j += 1) {+ const cost = a[i - 1] === b[j - 1] ? 0 : 1;+ cur[j] = Math.min(cur[j - 1] + 1, prev[j] + 1, prev[j - 1] + cost);+ }+ prev = cur;+ }+ return prev[cols - 1];+}++function nearestUri(candidate, validUris) {+ let best = "";+ let bestDistance = Infinity;+ for (const uri of validUris) {+ const distance = editDistance(candidate, uri);+ if (distance < bestDistance) {+ best = uri;+ bestDistance = distance;+ }+ }+ // Only repair near-misses; an unrelated hallucination is dropped instead.+ const tolerance = Math.max(4, Math.floor(candidate.length * 0.25));+ return bestDistance <= tolerance ? best : "";+}++/**+ * Small models occasionally mangle long URIs. Snap every cited URI back onto the+ * set the server actually returned, and drop bullets whose citation cannot be+ * recovered so the digest never carries a dead link.+ */+export function repairDigestUris(digest, validUris = []) {+ const text = String(digest || "");+ if (!text) return "";+ const valid = validUris.map((uri) => String(uri || "").trim()).filter(Boolean);+ if (!valid.length) return text;+ const validSet = new Set(valid);++ const lines = [];+ for (const line of text.split(/\r?\n/)) {+ if (!line.trim().startsWith("- ")) {+ lines.push(line);+ continue;+ }+ let tokenized = line;+ for (const uri of [...valid].sort((a, b) => b.length - a.length)) {+ if (/\s/.test(uri)) tokenized = tokenized.split(uri).join(encodeURI(uri));+ }+ let dropped = false;+ const repaired = tokenized.replace(/viking:\/\/[^\s<>"')\]]+/g, (uri) => {+ let decoded = uri;+ try { decoded = decodeURI(uri); } catch { /* keep the original candidate */ }+ if (validSet.has(decoded)) return decoded;+ const nearest = nearestUri(decoded, valid);+ if (nearest) return nearest;+ dropped = true;+ return uri;+ });+ if (!dropped) lines.push(repaired);+ }+ return lines.join("\n").trim();+}++export function normalizeCompressedContext(raw, maxChars = 4000, maxBullets = 6) {+ const text = String(raw || "").trim();+ if (!text) return null;+ if (text.toUpperCase() === NO_RELEVANT_MEMORY) return "";+ const bullets = text.split(/\r?\n/)+ .map((line) => line.trim())+ .filter((line) => /^[-*]\s+/.test(line) && line.includes("viking://"))+ .slice(0, Math.max(1, maxBullets))+ .map((line) => `- ${line.replace(/^[-*]\s+/, "").slice(0, 500).trim()}`);+ if (!bullets.length) return null;+ return (`${DIGEST_HEADER}\n${bullets.join("\n")}`).slice(0, Math.max(100, maxChars));+}++export function recallDigestCacheKey({+ query = "",+ rendered = "",+ entries = [],+ maxInputChars = 18000,+ maxBullets = 6,+} = {}) {+ const uris = entries.map((entry) => String(entry?.uri || "").trim()).filter(Boolean).sort();+ const source = JSON.stringify({+ version: 2,+ query: String(query),+ rendered: String(rendered).slice(0, maxInputChars),+ uris,+ maxInputChars,+ maxBullets,+ });+ return createHash("sha256").update(source).digest("hex");+}++async function readCache(path) {+ if (!path) return null;+ try { return JSON.parse(await readFile(path, "utf8")); } catch { return null; }+}++async function writeCache(path, value) {+ if (!path) return;+ try {+ await mkdir(dirname(path), { recursive: true });+ const tmp = `${path}.tmp`;+ await writeFile(tmp, JSON.stringify(value));+ await rename(tmp, path);+ } catch { /* best effort */ }+}++export async function compressRecallContext({+ query,+ rendered,+ shortContext = rendered,+ entries = [],+ cfg = {},+ runCompressor,+ cachePath = "",+ now = 0,+}) {+ const input = String(rendered || "").trim();+ if (!input) return { status: COMPRESS_EMPTY, context: "" };+ const minChars = Math.max(0, Number(cfg.recallCompressMinInputChars ?? 1500));+ if (input.length < minChars) {+ return { status: COMPRESS_OK, context: String(shortContext ?? input).trim() };+ }++ const maxInputChars = Math.max(1000, Number(cfg.recallCompressMaxInputChars || 18000));+ const maxBullets = Math.max(1, Number(cfg.recallCompressMaxBullets || 6));+ const key = recallDigestCacheKey({+ query,+ rendered: input,+ entries,+ maxInputChars,+ maxBullets,+ });+ const cached = await readCache(cachePath);+ if (cached?.key === key && typeof cached.digest === "string") {+ const digest = normalizeCompressedContext(cached.digest, 4000, maxBullets);+ if (digest) return { status: COMPRESS_OK, context: digest };+ }++ const prompt = buildRecallCompressionPrompt({+ query,+ rendered: input.slice(0, maxInputChars),+ maxBullets,+ });+ const raw = await runCompressor(prompt);+ const normalized = normalizeCompressedContext(raw, 4000, maxBullets);+ if (normalized === null) return { status: COMPRESS_FAILED, context: "" };+ if (!normalized) return { status: COMPRESS_EMPTY, context: "" };++ const validUris = entries.map((entry) => entry?.uri).filter(Boolean);+ const repaired = repairDigestUris(normalized, validUris.length+ ? validUris+ : (input.match(/viking:\/\/[^\s<>"']+/g) || []));+ const digest = normalizeCompressedContext(repaired, 4000, maxBullets);+ if (!digest) return { status: COMPRESS_FAILED, context: "" };++ await writeCache(cachePath, { key, digest, updatedAt: now || 0 });+ return { status: COMPRESS_OK, context: digest };+}diff --git a/examples/openclaw-plugin/shared/recall-core.d.mts b/examples/openclaw-plugin/shared/recall-core.d.mtsnew file mode 100644index 000000000..ed28bc750--- /dev/null+++ b/examples/openclaw-plugin/shared/recall-core.d.mts@@ -0,0 +1,81 @@+// GENERATED FROM examples/memory-plugin-shared/lib. DO NOT EDIT.+import type { OvHttpRequestOptions } from "./ov-http.mjs";++export type ContextSearchBody = {+ query: string;+ mode: "context";+ purpose: "coding";+ score_threshold: number;+ quotas?: Record<string, number>;+ max_tokens?: number;+ peer_scope?: "actor";+ session_id?: string;+ query_expansion?: "off" | "auto";+ dedup_turns?: number;+ exclude_uris?: string[];+ rewrite?: boolean | "auto";+ rewrite_max_bullets?: number;+};++export type NormalizedContextEntry = {+ uri: string;+ category: string;+ detail: string;+ score: number;+ text: string;+};++export function buildContextSearchBody(+ cfg?: Record<string, unknown>,+ options?: {+ sessionId?: string;+ excludeUris?: string[];+ localCompressorAvailable?: boolean;+ },+): ContextSearchBody;++export function contextRequestTimeoutMs(+ cfg?: Record<string, unknown>,+ body?: Record<string, unknown>,+): number | undefined;++export function normalizeContextEntry(entry?: unknown): NormalizedContextEntry;++export type RecallFetchJSON = (+ path: string,+ init?: RequestInit,+ options?: OvHttpRequestOptions,+) => Promise<{ ok: boolean; status?: number; result?: any; error?: any }>;++export type RecallOptions = {+ actorPeerId?: string;+ legacyPeerId?: string;+ sessionId?: string;+ log?: (stage: string, data?: any) => void;+};++export type DetailedRecall = {+ block: string;+ contentCount: number;+ hintCount: number;+ budgetUsed: number;+ stage: "server_assembled" | "ranked" | "no_results" | "filtered_out";+};++export function buildRecallBlockDetailed(+ fetchJSON: RecallFetchJSON,+ cfg: Record<string, any>,+ query: string,+ options?: RecallOptions,+): Promise<DetailedRecall>;++export function buildRecallBlock(+ fetchJSON: RecallFetchJSON,+ cfg: Record<string, any>,+ query: string,+ options?: RecallOptions,+): Promise<string | null>;++export function buildRecallEndpointBody(cfg?: Record<string, any>): Record<string, any>;+export function estimateTokens(text: string): number;+export function isRecallEnabled(cfg?: Record<string, any>): boolean;diff --git a/examples/openclaw-plugin/shared/recall-core.mjs b/examples/openclaw-plugin/shared/recall-core.mjsnew file mode 100644index 000000000..4695a887b--- /dev/null+++ b/examples/openclaw-plugin/shared/recall-core.mjs@@ -0,0 +1,731 @@+// GENERATED FROM examples/memory-plugin-shared/lib. DO NOT EDIT.+import { mkdir, readFile, rename, writeFile } from "node:fs/promises";+import { homedir } from "node:os";+import { dirname, join } from "node:path";++import { compressRecallContext } from "./recall-compress-core.mjs";++const PREFERENCE_QUERY_RE = /prefer|preference|favorite|favourite|like|偏好|喜欢|爱好|更倾向/i;+const TEMPORAL_QUERY_RE = /when|what time|date|day|month|year|yesterday|today|tomorrow|last|next|什么时候|何时|哪天|几月|几年|昨天|今天|明天/i;+const QUERY_TOKEN_RE = /[a-z0-9一-龥]{2,}/gi;+const STOPWORDS = new Set([+ "what", "when", "where", "which", "who", "whom", "whose", "why", "how", "did", "does",+ "is", "are", "was", "were", "the", "and", "for", "with", "from", "that", "this", "your", "you",+]);+const USER_RESERVED_DIRS = new Set(["memories", "skills"]);+const SOURCES = [+ { type: "memory", uri: "viking://~/memories", bucket: "memories" },+ { type: "skill", uri: "viking://~/skills", bucket: "skills" },+];+const DEFAULT_CONTEXT_LIMIT = 10;+const DEFAULT_CONTEXT_MAX_TOKENS = 1600;+const DEFAULT_REWRITE_MAX_BULLETS = 6;+const CODING_QUOTA_WEIGHTS = {+ events: 1,+ entities: 2,+ preferences: 1,+ experiences: 1,+ resources: 3,+ skills: 2,+};++let userSpaceCache = "";++/**+ * Is recall on for this config?+ *+ * The switch has four spellings in the wild: a boolean `autoRecall`, opencode's+ * `{ enabled }` object, dsh and pi's `syncTurns`, and the global `enabled`+ * that turns the whole plugin off. Reading it here rather than in each loader+ * is what keeps it from drifting a fifth time — and any spelling that says off+ * wins, so a config that disables recall under an older name still disables it.+ */+export function isRecallEnabled(cfg = {}) {+ return isSwitchOn([cfg.enabled, cfg.autoRecall, cfg.recall, cfg.syncRecall]);+}++/** Any recognised spelling that says off wins; everything else means on. */+function isSwitchOn(values) {+ for (const value of values) {+ if (value === false) return false;+ if (value && typeof value === "object" && !Array.isArray(value) && value.enabled === false) return false;+ }+ return true;+}++export function estimateTokens(text) {+ return text ? Math.ceil(String(text).length / 4) : 0;+}++function scaleQuotas(limit, weights) {+ const slots = Math.max(1, Math.floor(Number(limit) || DEFAULT_CONTEXT_LIMIT));+ const order = Object.keys(weights);+ const quotas = Object.fromEntries(order.map((key) => [key, 0]));+ if (slots < order.length) {+ for (const key of order) quotas[key] = 1;+ return quotas;+ }++ for (const key of order) quotas[key] = 1;+ const totalWeight = Object.values(weights).reduce((sum, weight) => sum + weight, 0);+ const ideals = Object.fromEntries(+ order.map((key) => [key, slots * weights[key] / totalWeight]),+ );+ while (order.reduce((sum, key) => sum + quotas[key], 0) < slots) {+ const key = order.reduce((best, candidate) => (+ ideals[candidate] - quotas[candidate] > ideals[best] - quotas[best]+ ? candidate+ : best+ ));+ quotas[key] += 1;+ }+ return quotas;+}++function legacyMemoryQuotas(limit) {+ return {+ ...scaleQuotas(limit, { events: 10, entities: 10, preferences: 3 }),+ experiences: 0,+ };+}++function codingQuotas(limit) {+ return scaleQuotas(limit, CODING_QUOTA_WEIGHTS);+}++export function buildRecallEndpointBody(cfg = {}) {+ const limit = Math.max(Number(cfg.recallLimit || DEFAULT_CONTEXT_LIMIT), 1);+ const body = {+ query: "",+ quotas: legacyMemoryQuotas(limit),+ max_chars: Math.max(Number(cfg.recallMaxContentChars || 0) * limit, 1000),+ min_score: Number.isFinite(Number(cfg.scoreThreshold)) ? Number(cfg.scoreThreshold) : 0.35,+ render: true,+ };+ if (cfg.recallPeerScope === "actor") body.peer_scope = "actor";+ return body;+}++/**+ * Body for the server-side context face. The plugin declares intent (coding+ * purpose, budget, session) and leaves the mechanics — quota ratios, tier+ * degradation, cross-turn dedup — to the server's defaults.+ */+export function buildContextSearchBody(cfg = {}, options = {}) {+ const rewriteMode = String(cfg.recallRewrite || "off").toLowerCase();+ const limit = Math.max(1, Math.floor(Number(cfg.recallLimit || DEFAULT_CONTEXT_LIMIT)));+ const maxTokens = Math.max(+ 64,+ Math.floor(Number(cfg.recallMaxTokens || DEFAULT_CONTEXT_MAX_TOKENS)),+ );+ const body = {+ query: "",+ mode: "context",+ purpose: "coding",+ score_threshold: Number.isFinite(Number(cfg.scoreThreshold)) ? Number(cfg.scoreThreshold) : 0.35,+ };+ const limitConfigured = cfg.recallLimitConfigured === true;+ const maxTokensConfigured = cfg.recallMaxTokensConfigured === true;+ if (limitConfigured) body.quotas = codingQuotas(limit);+ if (maxTokensConfigured) body.max_tokens = maxTokens;+ if (cfg.recallPeerScope === "actor") body.peer_scope = "actor";++ const sessionId = String(options.sessionId || "").trim();+ if (sessionId) {+ body.session_id = sessionId;+ const queryExpansionConfigured = cfg.recallQueryExpansionConfigured === true;+ if (queryExpansionConfigured) {+ body.query_expansion = cfg.recallQueryExpansion === "off" ? "off" : "auto";+ }+ const dedupTurns = Number(cfg.recallDedupTurns);+ const resolvedDedupTurns = Number.isFinite(dedupTurns)+ ? Math.max(0, Math.floor(dedupTurns))+ : 5;+ if (resolvedDedupTurns > 0) body.dedup_turns = resolvedDedupTurns;+ }++ const excludeUris = Array.isArray(options.excludeUris) ? options.excludeUris.slice(0, 200) : [];+ if (excludeUris.length) body.exclude_uris = excludeUris;++ if (rewriteMode === "server") body.rewrite = true;+ else if (rewriteMode === "auto" && !options.localCompressorAvailable) body.rewrite = "auto";+ const rewriteMaxBullets = Math.max(+ 1,+ Math.floor(Number(cfg.recallCompressMaxBullets || DEFAULT_REWRITE_MAX_BULLETS)),+ );+ const rewriteMaxBulletsConfigured = cfg.recallCompressMaxBulletsConfigured === true;+ if (body.rewrite !== undefined && rewriteMaxBulletsConfigured) {+ body.rewrite_max_bullets = rewriteMaxBullets;+ }+ return body;+}++// The server pipeline is serial and each optional stage has its own fuse. A+// request is aborted client-side unless its deadline covers every stage it+// asked for, and aborting discards the whole response rather than just the+// stage that ran long.+//+// session_id -> query expansion (retrieval.recall_intent_timeout_s, 5s)+// always -> retrieval, body reads, budget planning+// rewrite -> digest (retrieval.recall_rewrite_timeout_s, 30s)+//+// Both budgets stay inside the 60s prompt-hook allowance, the rewrite one with+// a quarter to spare.+const EXPANSION_REQUEST_TIMEOUT_MS = 15000;+const SERVER_REWRITE_REQUEST_TIMEOUT_MS = 45000;++/**+ * HTTP deadline for one context request, or undefined to keep the caller's own.+ *+ * Derived from the request body, because the body is what states which server+ * stages will run: reading `cfg` alone cannot tell a bare retrieval from one+ * that also spends the expansion or rewrite fuse.+ */+export function contextRequestTimeoutMs(cfg = {}, body = {}) {+ const wantsRewrite = body.rewrite !== undefined;+ // `query_expansion` defaults to "auto" server-side, so only an explicit "off"+ // takes the expansion fuse back out of the budget.+ const wantsExpansion = Boolean(body.session_id) && body.query_expansion !== "off";+ const configured = Number(cfg.recallContextTimeoutMs);+ if (Number.isFinite(configured) && configured > 0) return Math.max(1000, Math.floor(configured));+ if (!wantsRewrite && !wantsExpansion) return undefined;+ const floor = wantsRewrite ? SERVER_REWRITE_REQUEST_TIMEOUT_MS : EXPANSION_REQUEST_TIMEOUT_MS;+ return Math.max(Number(cfg.timeoutMs) || 0, floor);+}++/**+ * Strip the context-face fields a pre-context server rejects, converting the+ * token budget back to v1's character budget.+ */+export function downgradeToRecallBody(contextBody = {}, cfg = {}) {+ const body = buildRecallEndpointBody(cfg);+ body.query = contextBody.query || "";+ body.max_chars = Math.max(1000, Math.floor(Number(contextBody.max_tokens || 1600) * 4));+ if (contextBody.peer_scope) body.peer_scope = contextBody.peer_scope;+ return body;+}++function clampScore(v) {+ if (typeof v !== "number" || Number.isNaN(v)) return 0;+ return Math.max(0, Math.min(1, v));+}++function buildQueryProfile(query) {+ const text = query.trim();+ const allTokens = text.toLowerCase().match(QUERY_TOKEN_RE) || [];+ return {+ tokens: allTokens.filter((t) => !STOPWORDS.has(t)),+ wantsPreference: PREFERENCE_QUERY_RE.test(text),+ wantsTemporal: TEMPORAL_QUERY_RE.test(text),+ };+}++function lexicalOverlapBoost(tokens, text) {+ if (tokens.length === 0 || !text) return 0;+ const haystack = ` ${text.toLowerCase()} `;+ let matched = 0;+ for (const token of tokens.slice(0, 8)) {+ if (haystack.includes(token)) matched += 1;+ }+ return Math.min(0.2, (matched / Math.min(tokens.length, 4)) * 0.2);+}++function rankItem(item, profile) {+ const base = clampScore(item.score);+ const abstract = (item.abstract || item.overview || "").trim();+ const cat = (item.category || "").toLowerCase();+ const uri = (item.uri || "").toLowerCase();+ const leafBoost = (item.level === 2 || uri.endsWith(".md")) ? 0.12 : 0;+ const eventBoost = profile.wantsTemporal && (cat === "events" || uri.includes("/events/")) ? 0.1 : 0;+ const prefBoost = profile.wantsPreference && (cat === "preferences" || uri.includes("/preferences/")) ? 0.08 : 0;+ const overlapBoost = lexicalOverlapBoost(profile.tokens, `${item.uri} ${abstract}`);+ return base + leafBoost + eventBoost + prefBoost + overlapBoost;+}++function isEventOrCaseItem(item) {+ const cat = (item.category || "").toLowerCase();+ const uri = (item.uri || "").toLowerCase();+ return cat === "events" || cat === "cases" || uri.includes("/events/") || uri.includes("/cases/");+}++function dedupeItems(items) {+ const seen = new Set();+ const out = [];+ for (const item of items) {+ const key = isEventOrCaseItem(item)+ ? `uri:${item.uri}`+ : ((item.abstract || item.overview || "").trim().toLowerCase() || `uri:${item.uri}`);+ if (seen.has(key)) continue;+ seen.add(key);+ out.push(item);+ }+ return out;+}++async function resolveUserSpace(fetchJSON, actorPeerId = "") {+ 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`,+ {},+ { actorPeerId },+ );+ 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;+}++async function resolveTargetUri(fetchJSON, targetUri, actorPeerId = "") {+ const trimmed = targetUri.trim().replace(/\/+$/, "");+ // viking://~ is the home alias: the server expands it to the caller's own user+ // space, so it needs no client-side rewrite.+ if (trimmed === "viking://~" || trimmed.startsWith("viking://~/")) return trimmed;+ // Legacy compat: uid-less viking://user/<reserved> URIs may still sit in plugin+ // configs. Newer servers reject them, so rewrite to an explicit-uid URI here.+ const m = trimmed.match(/^viking:\/\/user(?:\/(.*))?$/);+ if (!m) return trimmed;+ const rawRest = (m[1] ?? "").trim();+ if (!rawRest) return trimmed;+ const parts = rawRest.split("/").filter(Boolean);+ if (parts.length === 0) return trimmed;+ if (!USER_RESERVED_DIRS.has(parts[0])) return trimmed;+ const space = await resolveUserSpace(fetchJSON, actorPeerId);+ return `viking://user/${space}/${parts.join("/")}`;+}++async function searchOneSource(fetchJSON, query, source, limit, actorPeerId = "") {+ const resolvedUri = await resolveTargetUri(fetchJSON, source.uri, actorPeerId);+ const body = { query, target_uri: resolvedUri, limit, score_threshold: 0 };+ const res = await fetchJSON("/api/v1/search/find", {+ method: "POST",+ body: JSON.stringify(body),+ }, { actorPeerId });+ if (!res.ok) return [];+ const items = res.result?.[source.bucket] || [];+ return items.map((item) => ({ ...item, _sourceType: source.type }));+}++async function searchAllSources(fetchJSON, query, perSourceLimit, actorPeerId = "", log = () => {}) {+ const results = await Promise.all(+ SOURCES.map((src) => searchOneSource(fetchJSON, query, src, perSourceLimit, actorPeerId)),+ );+ const all = results.flat();+ log("recall_search_summary", {+ counts: SOURCES.map((src, i) => ({ type: src.type, uri: src.uri, count: results[i].length })),+ total: all.length,+ });+ return all;+}++async function resolveItemContent(fetchJSON, item, cfg, actorPeerId = "") {+ let content;++ if (cfg.recallPreferAbstract && (item.abstract || item.overview || "").trim()) {+ content = (item.abstract || item.overview).trim();+ } else if (item.level === 2) {+ try {+ const res = await fetchJSON(+ `/api/v1/content/read?uri=${encodeURIComponent(item.uri)}`,+ {},+ { actorPeerId },+ );+ const body = res.ok && typeof res.result === "string" ? res.result.trim() : "";+ content = body || (item.abstract || item.overview || "").trim() || item.uri;+ } catch {+ content = (item.abstract || item.overview || "").trim() || item.uri;+ }+ } else {+ content = (item.abstract || item.overview || "").trim() || item.uri;+ }++ const maxChars = Math.max(50, Number(cfg.recallMaxContentChars || 500));+ if (content.length > maxChars) content = `${content.slice(0, maxChars)}...`;+ return content;+}++async function buildFallbackInjectionBlock(fetchJSON, items, cfg, actorPeerId = "", log = () => {}) {+ const budgetTotal = Math.max(200, Number(cfg.recallTokenBudget || 2000));+ let budgetRemaining = budgetTotal;+ const lines = [+ "<openviking-context>",+ "Relevant context from OpenViking. Use the read MCP tool to expand URIs.",+ ];+ let contentCount = 0;+ let hintCount = 0;++ for (const item of items) {+ const score = (clampScore(item.score) * 100).toFixed(0);+ const uriLine = `- [${item._sourceType} ${score}%] ${item.uri}`;++ if (budgetRemaining > 0) {+ const content = await resolveItemContent(fetchJSON, item, cfg, actorPeerId);+ const contentLine = `- [${item._sourceType} ${score}%] ${content}`;+ const lineTokens = estimateTokens(contentLine);++ if (lineTokens > budgetRemaining && contentCount > 0) {+ lines.push(uriLine);+ hintCount++;+ } else {+ lines.push(contentLine);+ budgetRemaining -= lineTokens;+ contentCount++;+ }+ } else {+ lines.push(uriLine);+ hintCount++;+ }+ }++ lines.push("</openviking-context>");++ const budgetUsed = budgetTotal - budgetRemaining;+ log("recall_injection_built", {+ contentItems: contentCount,+ hintItems: hintCount,+ budgetUsed,+ budgetTotal,+ });++ return { block: lines.join("\n"), contentCount, hintCount, budgetUsed, stage: "ranked" };+}++const LEGACY_CACHE_TTL_MS = 6 * 60 * 60 * 1000;++function stateFile(name) {+ const override = String(process.env.OPENVIKING_STATE_DIR || "").trim();+ return override ? join(override, name) : join(homedir(), ".openviking", "state", name);+}++async function readJsonFile(path) {+ try { return JSON.parse(await readFile(path, "utf8")); } catch { return null; }+}++async function writeJsonFile(path, value) {+ try {+ await mkdir(dirname(path), { recursive: true });+ const tmp = `${path}.tmp`;+ await writeFile(tmp, JSON.stringify(value));+ await rename(tmp, path);+ } catch { /* best effort */ }+}++/**+ * Hooks are one-shot processes, so "this server has no context face" has to be+ * remembered on disk or every turn pays for a rejected request.+ */+export async function isContextFaceLegacy(path = stateFile("context-face.json"), now = Date.now()) {+ const cached = await readJsonFile(path);+ return Boolean(cached?.legacyUntil && Number(cached.legacyUntil) > now);+}++export async function markContextFaceLegacy(path = stateFile("context-face.json"), now = Date.now()) {+ await writeJsonFile(path, { legacyUntil: now + LEGACY_CACHE_TTL_MS });+}++/**+ * A `peer_scope` the server rejects is remembered the same way, but unlike the+ * context face this one is not a silent capability probe: dropping the field+ * widens recall from the caller's own peer to the whole user root, so doctor+ * reads this file back and warns.+ */+export function peerScopeMemoPath() {+ return stateFile("peer-scope.json");+}++export async function readPeerScopeDowngrade(path = peerScopeMemoPath(), now = Date.now()) {+ const cached = await readJsonFile(path);+ if (!cached?.legacyUntil || Number(cached.legacyUntil) <= now) return null;+ return cached;+}++export async function markPeerScopeDowngrade(scope, status, path = peerScopeMemoPath(), now = Date.now()) {+ await writeJsonFile(path, {+ legacyUntil: now + LEGACY_CACHE_TTL_MS,+ scope: String(scope || ""),+ status: Number(status) || 0,+ at: now,+ });+}++function looksLikeUnknownField(res) {+ const text = JSON.stringify(res?.error ?? res?.result ?? res?.detail ?? "").toLowerCase();+ return text.includes("extra") || text.includes("mode") || text.includes("unexpected");+}++function wrapContext(body) {+ return [+ "<openviking-context>",+ "Relevant memory from OpenViking. Use the search/read MCP tools to expand URIs.",+ body,+ "</openviking-context>",+ ].join("\n");+}++/**+ * Server-assembled context: the context face when the deployment has it, else+ * the deprecated /recall preset. Returns the injection block, "" when there was+ * nothing relevant, or null when no server-side path was usable at all.+ */+export async function buildServerAssembledBlock(fetchJSON, cfg, query, options = {}) {+ const actorPeerId = options.actorPeerId ?? cfg.peerId ?? "";+ const log = options.log || (() => {});++ const block = await recallViaContextFace(fetchJSON, cfg, query, { ...options, actorPeerId }, log);+ if (block !== null) return block;+ return recallViaEndpoint(fetchJSON, cfg, query, actorPeerId, log);+}++/**+ * Raw server-assembled context, or null when the deployment has no context face.+ * Returns `{ rendered, entries, digest, stats }` — callers that need the entries+ * (their own compression, their own envelope) use this instead of the block+ * builders below.+ */+export async function fetchAssembledContext(fetchJSON, cfg, query, options = {}) {+ const actorPeerId = options.actorPeerId || "";+ const log = options.log || (() => {});+ if (await isContextFaceLegacy(options.legacyCachePath)) return null;++ const body = buildContextSearchBody(cfg, options);+ body.query = query;+ const res = await fetchJSON("/api/v1/search/search", {+ method: "POST",+ body: JSON.stringify(body),+ }, { actorPeerId, timeoutMs: contextRequestTimeoutMs(cfg, body) });++ if (!res.ok) {+ const status = res.status || 0;+ if ((status === 400 || status === 422) && looksLikeUnknownField(res)) {+ await markContextFaceLegacy(options.legacyCachePath);+ log("recall_context_face_unsupported", { status });+ } else {+ log("recall_context_face_error", { status });+ }+ return null;+ }++ const result = res.result || {};+ const stats = result.stats || {};+ log("recall_context_assembled", {+ entries: Array.isArray(result.entries) ? result.entries.length : 0,+ usedTokens: stats.used_tokens || 0,+ tiers: stats.tier_counts || {},+ rewrite: stats.rewrite || "off",+ });+ return {+ rendered: String(result.rendered || "").trim(),+ entries: Array.isArray(result.entries) ? result.entries : [],+ digest: String(result.digest || "").trim(),+ stats,+ };+}++/**+ * Entry field compatibility: the context face returns `category`/`text`, while+ * the deprecated /recall v1 shape used `type` plus `content`/`summary`.+ */+export function normalizeContextEntry(entry = {}) {+ return {+ uri: String(entry.uri || "").trim(),+ category: String(entry.category || entry.type || "memory").trim() || "memory",+ detail: String(entry.detail || entry.mode || "").trim(),+ score: Number(entry.score) || 0,+ text: String(+ entry.text || entry.content || entry.summary || entry.abstract || entry.uri || "",+ ).trim(),+ };+}++async function recallViaContextFace(fetchJSON, cfg, query, options, log) {+ const assembled = await fetchAssembledContext(fetchJSON, cfg, query, { ...options, log });+ if (assembled === null) return null;++ const { rendered, entries } = assembled;+ let digest = assembled.digest;+ const mode = String(cfg.recallRewrite || "off").toLowerCase();+ if (String(assembled.stats?.rewrite || "").toLowerCase() === "no_relevant") {+ log("recall_server_compression", { status: "empty" });+ return "";+ }+ const wantsLocal = mode === "client" || (mode === "auto" && !digest);+ if (wantsLocal && rendered && typeof options.runCompressor === "function") {+ try {+ const compression = await compressRecallContext({+ query,+ rendered,+ entries,+ cfg,+ runCompressor: options.runCompressor,+ cachePath: options.digestCachePath || stateFile("recall-digest.json"),+ now: Date.now(),+ });+ log("recall_local_compression", { status: compression.status });+ if (compression.status === "ok") digest = compression.context;+ if (compression.status === "empty") return "";+ } catch (err) {+ log("recall_local_compression_failed", { error: String(err?.message || err) });+ }+ }++ const injected = digest || rendered;+ if (!injected) return "";+ return wrapContext(injected);+}++async function recallViaEndpoint(fetchJSON, cfg, query, actorPeerId = "", log = () => {}) {+ const body = buildRecallEndpointBody(cfg);+ body.query = query;+ const res = await postRecall(fetchJSON, body, { actorPeerId, log });+ if (!res.ok) {+ log("recall_endpoint_fallback", { status: res.status || 0 });+ return null;+ }+ const rendered = String(res.result?.rendered || "").trim();+ if (!rendered) return "";+ return wrapContext(rendered);+}++export async function postRecall(fetchJSON, body, opts = {}) {+ const actorPeerId = opts.actorPeerId || "";+ const log = opts.log || (() => {});+ const memoPath = opts.peerScopeMemoPath;+ const request = { ...body };++ // A remembered downgrade is still a downgrade: recall runs wider than the+ // caller asked for, so the memo doubles as the doctor's evidence.+ if (request.peer_scope && await readPeerScopeDowngrade(memoPath)) {+ delete request.peer_scope;+ }++ const res = await fetchJSON("/api/v1/search/recall", {+ method: "POST",+ body: JSON.stringify(request),+ }, { actorPeerId });+ if (!request.peer_scope || (res.status !== 400 && res.status !== 422)) {+ return res;+ }+ // Only an unknown-field rejection means "this server predates peer_scope".+ // Retrying every other 400/422 without it silently widens the search from+ // the caller's own peer to the whole user root.+ if (!looksLikeUnknownField(res)) {+ log("recall_peer_scope_error", { status: res.status || 0 });+ return res;+ }++ const downgraded = { ...request };+ delete downgraded.peer_scope;+ await markPeerScopeDowngrade(String(request.peer_scope), res.status || 0, memoPath);+ log("recall_peer_scope_downgrade", { status: res.status || 0 });+ return fetchJSON("/api/v1/search/recall", {+ method: "POST",+ body: JSON.stringify(downgraded),+ }, { actorPeerId });+}++/**+ * Recall, plus whatever is still filed under the peer this workspace used+ * before the identity rule changed.+ *+ * Under the default `peer_scope: "all"` this costs nothing: the server's own+ * sweep of `{user_root}/peers` already reaches the old peer's memories. Under+ * `"actor"` that sweep is off by definition, so the old peer is asked for+ * separately — as itself, which is both cheaper and wider than a bare+ * cross-peer read (that would need the user id, and reaches memories only).+ *+ * `stage` names the path the block came from, which is what a host needs to+ * tell "the server had nothing" (`no_results`) from "the score threshold+ * dropped everything" (`filtered_out`) when the block is empty, and a+ * `server_assembled` block from a `ranked` one when it is not.+ */+export async function buildRecallBlockDetailed(fetchJSON, cfg, query, options = {}) {+ const primary = await recallForPeer(fetchJSON, cfg, query, options);++ const legacyPeerId = String(options.legacyPeerId || "").trim();+ const actorPeerId = options.actorPeerId ?? cfg.peerId ?? "";+ if (cfg.recallPeerScope !== "actor" || !legacyPeerId || legacyPeerId === actorPeerId) return primary;++ const log = options.log || (() => {});+ const legacy = await recallForPeer(fetchJSON, cfg, query, { ...options, actorPeerId: legacyPeerId });+ if (!legacy.block) return primary;+ log("recall_legacy_peer_hit", { legacyPeerId });+ return {+ block: primary.block ? `${primary.block}\n${legacy.block}` : legacy.block,+ contentCount: primary.contentCount + legacy.contentCount,+ hintCount: primary.hintCount + legacy.hintCount,+ budgetUsed: primary.budgetUsed + legacy.budgetUsed,+ stage: primary.block ? primary.stage : legacy.stage,+ };+}++/** The block alone, or null when nothing was injectable. */+export async function buildRecallBlock(fetchJSON, cfg, query, options = {}) {+ const { block } = await buildRecallBlockDetailed(fetchJSON, cfg, query, options);+ return block || null;+}++function emptyRecall(stage) {+ return { block: "", contentCount: 0, hintCount: 0, budgetUsed: 0, stage };+}++async function recallForPeer(fetchJSON, cfg, query, options = {}) {+ const actorPeerId = options.actorPeerId ?? cfg.peerId ?? "";+ const log = options.log || (() => {});+ const trimmed = String(query || "").trim();+ if (!trimmed) return emptyRecall("no_results");++ // Assembly happens server-side when the deployment offers the context face;+ // older servers fall through to /recall, then to raw find.+ const serverBlock = await buildServerAssembledBlock(fetchJSON, cfg, trimmed, {+ ...options,+ actorPeerId,+ log,+ });+ if (serverBlock !== null) {+ if (!serverBlock) return emptyRecall("no_results");+ // The server rendered one budgeted unit, so nothing here degraded to a+ // URI-only hint and the block's own estimate is what it cost.+ return {+ block: serverBlock,+ contentCount: 1,+ hintCount: 0,+ budgetUsed: estimateTokens(serverBlock),+ stage: "server_assembled",+ };+ }++ const recallLimit = Math.max(1, Number(cfg.recallLimit || DEFAULT_CONTEXT_LIMIT));+ const perSourceLimit = Math.max(recallLimit * 2, 8);+ const raw = await searchAllSources(fetchJSON, trimmed, perSourceLimit, actorPeerId, log);+ if (raw.length === 0) return emptyRecall("no_results");++ const profile = buildQueryProfile(trimmed);+ const scoreThreshold = Number.isFinite(Number(cfg.scoreThreshold)) ? Number(cfg.scoreThreshold) : 0.35;+ const filtered = raw.filter((it) => clampScore(it.score) >= scoreThreshold);+ filtered.sort((a, b) => rankItem(b, profile) - rankItem(a, profile));+ const picked = dedupeItems(filtered).slice(0, recallLimit);+ log("recall_picked", {+ rawCount: raw.length,+ filteredCount: filtered.length,+ pickedCount: picked.length,+ items: picked.map((it) => ({ type: it._sourceType, uri: it.uri, score: clampScore(it.score) })),+ });++ if (picked.length === 0) return emptyRecall("filtered_out");+ return buildFallbackInjectionBlock(fetchJSON, picked, cfg, actorPeerId, log);+}