Skip to content

Local-first 🧠 memory for Hermes Agent that lives in your Obsidian vault and remembers project context. Nightly 😴 dream passes turn repeat corrections into confirmed preferences with measurable confidence. Adapters ship for Claude Code, Codex, and OpenClaw, with an MCP server for anything else.

TypeScript

fix(hermes): make prefetch recall query-aware (#181)

Yori940619c2e13f9d23bd
diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.json
index 887f7c0f..7cda86d0 100644
--- a/.claude-plugin/plugin.json
+++ b/.claude-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "open-second-brain",
- "version": "1.52.1",
+ "version": "1.53.0",
"description": "Plugin-first second brain package for AI agents and humans.",
"author": {
"name": "Open Second Brain contributors"
diff --git a/.codex-plugin/plugin.json b/.codex-plugin/plugin.json
index 42357253..be905bd4 100644
--- a/.codex-plugin/plugin.json
+++ b/.codex-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "open-second-brain",
- "version": "1.52.1",
+ "version": "1.53.0",
"description": "Plugin-first second brain package for Codex, Hermes, Claude Code, OpenClaw, and other agent runtimes.",
"skills": "./skills",
"hooks": "./hooks/hooks.json",
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 388f96d7..af246156 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -5,6 +5,23 @@ All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
+## [1.53.0] - 2026-08-27
+
+Hermes injected recall on every gated turn without ever telling the vault what the turn was about, and [@Yori940619](https://github.com/Yori940619) named it in [#181](https://github.com/itechmeat/open-second-brain/pull/181): the pack was query-blind, and the pages that would have mattered lost the budget to whichever confirmed preferences happened to sort first. The diagnosis is right and the preference-first ordering the pull request argued for is the right instinct. The mechanism it proposed is the part that changed. Recall would have moved onto raw `brain_search`, and that path is the one place a curated injection must not go: it runs no prompt-injection guard, post-filters a general ranker instead of enumerating the preference directory, returns retired and merely-demoted superseded pages, never consults owner-scope delivery, enforces no response-level token budget, and issues no receipt. The fix belongs one layer down, inside the lane, and that is where it landed.
+
+### Added
+
+- **`brain_context_pack` reads its query two ways, and the second one ranks.** The tool has always accepted a `query` and has always meant a case-insensitive SUBSTRING match against `topic + principle`, so a natural-language turn missed every candidate and came back with an empty pack and a `filter-miss` for each page. `query_mode: "ranked"` takes the query out of the filter and into the sort: the already-collected candidates are ORDERED by structural token overlap - the same deterministic, stopword-free, language-agnostic kernel the rated-decision matcher uses, with no model and no embedding, so it works on an install that has never indexed a vector - and none of them is excluded. The budget decides what is dropped, not a lexical accident. Relevance sits between session focus and density in the comparator and under tier, so a bound focus still dominates and a peripheral page still never outranks a core one. An omitted `query_mode` is byte-identical to every release before this one and a test pins it; the mode requires a query, stated in the schema as `dependentRequired` and refused by the handler rather than accepted as a silent no-op. Because the change is inside the lane, the containment guard, the curated pool, the tombstone and supersession-tip filters, owner-scope delivery, `max_tokens`, the named skip reasons, and the server-issued `receipt_id` are all inherited rather than bypassed.
+
+### Fixed
+
+- **Hermes recall is query-aware without leaving the lane that makes it safe.** `prefetch` calls one tool, `brain_context_pack`, and now carries the turn on it in ranked mode. The sample id in the injected metadata line is the server-issued `receipt_id` again rather than a locally hashed string: an id with no receipt behind it resolves `unresolved / sample_absent` on every outcome an agent posts, which would have undone what [#179](https://github.com/itechmeat/open-second-brain/pull/179) shipped one release earlier. The local character budget is gone with it - `max_tokens` is a TOKEN budget the server enforces against the bodies it emits, and re-spending it in Python at four bytes per token over-injected by two to four times on Cyrillic and CJK vaults and cut the joined output mid-string with no marker. The two helpers that formatted search rows are deleted; one of them scanned a whole result for a line beginning `principle:` and returned that line alone, so an ordinary note carrying such a line in its body was reduced to it.
+- **Two silences on the Hermes boundary, both named now.** `brain_context_pack` computed injection-time tension warnings and the owner-scope observation and its MCP projection discarded both, so the one surface that puts vault text in front of a model every turn was the one surface that could not say a memory it injected is contested; the tool forwards them as `brain_pre_compress_pack` always has, absent when empty. On the provider side those warnings reach the log, and a gated turn that recalls nothing states that rather than passing for a healthy injection. The correlation defaults `handle_tool_call` supplies for `brain_context_pack_outcome` are also scoped to `operation: "post"` - `host` and `session_id` are read filters for `list` and `summary`, and defaulting them there narrowed an agent's own query to this host's rows without telling it.
+
+### Notes
+
+- The three regression pins [#179](https://github.com/itechmeat/open-second-brain/pull/179) added still pass, but they were passing for the wrong reason while the search lane existed: the test bridge answers `{}` for an unregistered tool, which sent them down the fallback path instead of the shipped one. Each now asserts by name which lane ran, so a future rerouting fails them instead of sliding past.
+
## [1.52.1] - 2026-08-24
The context-pack outcome ledger shipped with receipts on the read side and nothing on the Hermes side to carry them, so a deployment that injected recall on every turn still recorded zero outcomes. Contributed by [@Yori940619](https://github.com/Yori940619) ([#179](https://github.com/itechmeat/open-second-brain/pull/179)), with one course correction along the way that is worth recording: the first revision inferred success and repair from hardcoded phrase lists in a single language, and the rework removed raw-text inference entirely - the honest shape, and now the pinned one.
@@ -7357,6 +7374,7 @@ plugin config (vault field)`, and exits with a clear
- Sandbox vault and plugin manifest fixtures for tests.
- GitHub release workflow for tag-based and manually dispatched releases.
+[1.53.0]: https://github.com/itechmeat/open-second-brain/compare/v1.52.1...v1.53.0
[1.52.1]: https://github.com/itechmeat/open-second-brain/compare/v1.52.0...v1.52.1
[1.52.0]: https://github.com/itechmeat/open-second-brain/compare/v1.51.0...v1.52.0
[1.51.0]: https://github.com/itechmeat/open-second-brain/compare/v1.50.3...v1.51.0
diff --git a/docs/mcp.md b/docs/mcp.md
index 28dec739..503705c6 100644
--- a/docs/mcp.md
+++ b/docs/mcp.md
@@ -1255,3 +1255,21 @@ log line is machine-composed rather than authored.
letter; `o2b state status` names the location and the records are listable
from core. Single-artifact lanes are deliberately excluded: their one
failure IS the response. No new tool - the surface stays at 113.
+- Since v1.53.0 `brain_context_pack` reads its `query` two ways. The default is
+ the substring filter it has always been - a case/Unicode-insensitive match
+ against `topic + principle`, every miss dropped with a `filter-miss` skip -
+ and an omitted `query_mode` keeps that reading byte-identical. `query_mode:
+ "ranked"` instead ORDERS the curated candidates by structural token overlap
+ (the same deterministic, stopword-free kernel the rated-decision matcher
+ uses - no model, no embedding, so it works on an install that has never
+ indexed a vector) and excludes none of them, so a natural-language turn
+ prioritises the budget rather than emptying the pack. `query_mode` requires
+ `query`; the schema states the pairing as `dependentRequired` and the
+ handler refuses a mode with nothing to read. Everything the lane exists for
+ - the containment guard, the curated preference pool, the tombstone and
+ supersession-tip filters, owner-scope delivery, `max_tokens`, the named skip
+ reasons, and the server-issued `receipt_id` - applies unchanged in both
+ modes. The tool also stops discarding the report's `warnings`: injection-time
+ tension warnings and the owner-scope observation now reach the caller as
+ `brain_pre_compress_pack` has always passed them, absent when empty. No new
+ tool - the surface stays at 113.
diff --git a/openclaw.plugin.json b/openclaw.plugin.json
index 14a20157..383a047b 100644
--- a/openclaw.plugin.json
+++ b/openclaw.plugin.json
@@ -2,7 +2,7 @@
"id": "open-second-brain",
"name": "Open Second Brain",
"description": "Second brain for AI agents using Obsidian-compatible Markdown vaults.",
- "version": "1.52.1",
+ "version": "1.53.0",
"activation": { "onStartup": true },
"skills": ["./skills"],
"contracts": {
diff --git a/package.json b/package.json
index 2342f55a..6095381e 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
{
"name": "open-second-brain",
- "version": "1.52.1",
+ "version": "1.53.0",
"private": false,
"description": "Second brain for AI agents using Obsidian-compatible Markdown vaults. Works with Hermes, Claude Code, Codex, and OpenClaw.",
"keywords": [
diff --git a/plugin.yaml b/plugin.yaml
index 4e44338d..a4a090c2 100644
--- a/plugin.yaml
+++ b/plugin.yaml
@@ -1,5 +1,5 @@
name: open-second-brain
-version: "1.52.1"
+version: "1.53.0"
description: "Open Second Brain - native Hermes memory provider backed by an Obsidian-compatible Markdown vault."
author: "Open Second Brain contributors"
memory_provider: true
diff --git a/plugins/codex/.codex-plugin/plugin.json b/plugins/codex/.codex-plugin/plugin.json
index dc2a7772..00e25eba 100644
--- a/plugins/codex/.codex-plugin/plugin.json
+++ b/plugins/codex/.codex-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "open-second-brain",
- "version": "1.52.1",
+ "version": "1.53.0",
"description": "Plugin-first second brain package for Codex, Hermes, Claude Code, OpenClaw, and other agent runtimes.",
"author": {
"name": "Open Second Brain contributors",
diff --git a/plugins/hermes/_schemas.py b/plugins/hermes/_schemas.py
index 702e7580..ad75957f 100644
--- a/plugins/hermes/_schemas.py
+++ b/plugins/hermes/_schemas.py
@@ -499,9 +499,18 @@ STATIC_TOOL_SCHEMAS: tuple[dict[str, Any], ...] = (
'description': 'Strict upper bound on the '
"returned slice's token count."},
'query': {'type': 'string',
- 'description': 'Optional case/Unicode-insensitive '
- 'substring filter on topic + '
- 'principle.'},
+ 'description': 'Optional query. Read as a '
+ 'case/Unicode-insensitive substring '
+ 'filter on topic + principle unless '
+ '`query_mode` says otherwise.'},
+ 'query_mode': {'type': 'string',
+ 'enum': ['substring', 'ranked'],
+ 'description': 'How `query` is read: '
+ '`substring` (default) filters, '
+ 'dropping misses as '
+ '`filter-miss`; `ranked` orders '
+ 'candidates by token overlap and '
+ 'excludes none.'},
'focus_session': {'type': 'string',
'minLength': 1,
'maxLength': 128,
@@ -600,7 +609,8 @@ STATIC_TOOL_SCHEMAS: tuple[dict[str, Any], ...] = (
'ownership filtering.'}},
'required': ['max_tokens'],
'dependentRequired': {'recall_scores': ['match_quality'],
- 'match_quality': ['recall_scores']},
+ 'match_quality': ['recall_scores'],
+ 'query_mode': ['query']},
'additionalProperties': False}},
{
"name": "brain_context_pack_outcome",
diff --git a/plugins/hermes/plugin.yaml b/plugins/hermes/plugin.yaml
index 4e44338d..a4a090c2 100644
--- a/plugins/hermes/plugin.yaml
+++ b/plugins/hermes/plugin.yaml
@@ -1,5 +1,5 @@
name: open-second-brain
-version: "1.52.1"
+version: "1.53.0"
description: "Open Second Brain - native Hermes memory provider backed by an Obsidian-compatible Markdown vault."
author: "Open Second Brain contributors"
memory_provider: true
diff --git a/plugins/hermes/provider.py b/plugins/hermes/provider.py
index 65a7aacd..73089e63 100644
--- a/plugins/hermes/provider.py
+++ b/plugins/hermes/provider.py
@@ -18,8 +18,8 @@ import logging
import os
import shutil
import threading
-from pathlib import Path
from collections.abc import Callable
+from pathlib import Path
from typing import TYPE_CHECKING, Any, NamedTuple
if TYPE_CHECKING:
@@ -142,9 +142,17 @@ def _resolved_config_values() -> dict[str, str]:
# Durable per-session transcript written under ``hermes_home``.
SESSION_TRANSCRIPT_FILENAME = "session-transcript.jsonl"
-# Token budget for the recall slice fetched on each prefetch.
+# Token budget for the recall slice fetched on each prefetch. Enforced
+# SERVER-side by `brain_context_pack`, which estimates tokens against the
+# bodies it emits; the provider never re-spends it as a character budget,
+# because the four-bytes-per-token heuristic that would take is wrong by two
+# to four times on Cyrillic and CJK vaults.
_PREFETCH_MAX_TOKENS = 1024
_PREFETCH_RECEIPT_HOST = "hermes"
+# How `brain_context_pack` reads the turn: order the curated candidates by
+# relevance rather than filtering them, so a natural-language turn spends the
+# budget on what matters instead of substring-missing every page.
+_PREFETCH_QUERY_MODE = "ranked"
# A provider instance is created per AIAgent, but the MCP server is a gateway
# resource rather than a session resource. Keep one bridge per effective server
@@ -492,7 +500,17 @@ class OpenSecondBrainMemoryProvider(MemoryProvider):
if tool_name not in MEMORY_TOOLS:
# Enforce the curated surface at execution time, not just discovery.
raise BridgeError(f"unsupported memory tool: {tool_name}")
- return self._as_tool_content(self._bridge.call_tool(tool_name, args or {}))
+ forward_args = dict(args or {})
+ # Correlation defaults for the outcome POST only. `host` and
+ # `session_id` are also READ filters on list/summary, so supplying
+ # them there would narrow an agent's query to this host's rows
+ # without ever telling it - the "narrowed without saying so" failure
+ # the architecture notes call out by name.
+ if tool_name == "brain_context_pack_outcome" and forward_args.get("operation") == "post":
+ forward_args.setdefault("host", _PREFETCH_RECEIPT_HOST)
+ if self._session_id:
+ forward_args.setdefault("session_id", self._session_id)
+ return self._as_tool_content(self._bridge.call_tool(tool_name, forward_args))
def get_config_schema(self) -> list[dict[str, Any]]:
"""The wizard's field list, derived from :data:`_CONFIG_FIELDS`.
@@ -604,6 +622,23 @@ class OpenSecondBrainMemoryProvider(MemoryProvider):
receipt_id = structured.get("receipt_id")
return str(receipt_id) if receipt_id else None
+ def _log_pack_warnings(self, pack: Any) -> None:
+ """Surface the pack's own warnings; a degraded recall must name itself.
+
+ `brain_context_pack` reports injection-time tension warnings and the
+ owner-scope observation. They describe the material about to enter the
+ prompt - a memory that is the subject of an unresolved contradiction,
+ for one - and are for the operator, not the model, so they go to the
+ log rather than into the injected text.
+ """
+ warnings = self._structured(pack).get("warnings")
+ if not isinstance(warnings, list):
+ return
+ for warning in warnings:
+ text = str(warning).strip()
+ if text:
+ logger.warning("%s: brain_context_pack: %s", self.PROVIDER_NAME, text)
+
def system_prompt_block(self) -> str:
"""Static provider context: the current active-preferences body."""
result = self._safe_call("brain_context", {})
@@ -615,22 +650,49 @@ class OpenSecondBrainMemoryProvider(MemoryProvider):
The recall gate decides whether a retrieval runs; the identity reminder
(the behaviour the retired ``pre_llm_call`` hook used to provide) is
always appended when an agent identity is configured.
+
+ Recall has exactly ONE lane, ``brain_context_pack``, and the turn's
+ query rides it in ranked mode. That lane is where the prompt-injection
+ guard, the curated preference pool, the tombstone and supersession-tip
+ filters, owner-scope delivery, the enforced token budget, and the
+ server-issued receipt live; a raw ``brain_search`` recall would have
+ query-awareness and none of them. There is no second lane and no
+ fallback: a lane that fails says so through ``_safe_call`` and this
+ turn is injected nothing.
"""
parts: list[str] = []
sid = session_id or self._session_id
- gate = self._structured(self._safe_call("brain_recall_gate", {"prompt": query}))
+ turn_id = str(_kwargs.get("turn_id") or "")
+ gate_args: dict[str, Any] = {
+ "prompt": query,
+ "telemetry_host": _PREFETCH_RECEIPT_HOST,
+ }
+ if sid:
+ gate_args["session_id"] = sid
+ if turn_id:
+ gate_args["turn_id"] = turn_id
+ gate = self._structured(self._safe_call("brain_recall_gate", gate_args))
if gate.get("retrieve"):
- pack = self._safe_call(
- "brain_context_pack",
- {
- "max_tokens": _PREFETCH_MAX_TOKENS,
- "receipt": True,
- "receipt_host": _PREFETCH_RECEIPT_HOST,
- "telemetry": True,
- "telemetry_host": _PREFETCH_RECEIPT_HOST,
- **({"session_id": sid} if sid else {}),
- },
- )
+ pack_args: dict[str, Any] = {
+ "max_tokens": _PREFETCH_MAX_TOKENS,
+ "receipt": True,
+ "receipt_host": _PREFETCH_RECEIPT_HOST,
+ "telemetry": True,
+ "telemetry_host": _PREFETCH_RECEIPT_HOST,
+ }
+ # Ranked mode ORDERS the curated candidates by relevance to this
+ # turn and excludes none, so the budget decides what is dropped.
+ # The server refuses a mode with no query, so both travel or
+ # neither does.
+ if query.strip():
+ pack_args["query"] = query
+ pack_args["query_mode"] = _PREFETCH_QUERY_MODE
+ if sid:
+ pack_args["session_id"] = sid
+ if turn_id:
+ pack_args["turn_id"] = turn_id
+ pack = self._safe_call("brain_context_pack", pack_args)
+ self._log_pack_warnings(pack)
recalled = self._context_pack_text(pack)
if recalled:
parts.append(recalled)
@@ -647,6 +709,15 @@ class OpenSecondBrainMemoryProvider(MemoryProvider):
ensure_ascii=False,
)
)
+ else:
+ # A gated turn that recalls nothing is a fact worth stating:
+ # on an empty vault it is normal, and after a failed bridge
+ # call it is the second half of the warning `_safe_call`
+ # already emitted. Either way it is not a silent no-op.
+ logger.info(
+ "%s: brain_context_pack returned no recall for a gated turn",
+ self.PROVIDER_NAME,
+ )
# Skill auto-attach (Agent Surface Suite): the TS side gates on the
# skill_auto_attach config key and returns an empty block when off,
# so the default injection stays byte-identical. Fail-soft like every
diff --git a/pyproject.toml b/pyproject.toml
index c3b4e964..32de7f82 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -10,7 +10,7 @@ build-backend = "setuptools.build_meta"
# CLI entry points (those moved to `package.json` `bin`).
[project]
name = "open-second-brain"
-version = "1.52.1"
+version = "1.53.0"
description = "Hermes Python shim for Open Second Brain. Most of the project (CLI, MCP server, OpenClaw plugin) is TypeScript on Bun; see package.json."
readme = "README.md"
requires-python = ">=3.11"
diff --git a/src/core/brain/context-pack.ts b/src/core/brain/context-pack.ts
index 90c3e0f5..bce0e55d 100644
--- a/src/core/brain/context-pack.ts
+++ b/src/core/brain/context-pack.ts
@@ -44,6 +44,7 @@ import {
import { estimateTokens } from "./text/tokenizer.ts";
import { densityScore } from "./context-density.ts";
import { normalizeForDedup } from "./text/normalize.ts";
+import { jaccard, tokenise } from "./similarity.ts";
import { applyCharBudget, type CharBudgetDegradationMode } from "./recall-budget.ts";
import { emitContextReceipt, type ContextReceiptOptions } from "./context-receipts.ts";
import type { RecallAdequacyVerdict } from "./recall-adequacy.ts";
@@ -82,6 +83,33 @@ const TIER_ORDER: ReadonlyArray<PageTier> = [
PAGE_TIER.peripheral,
];
+/**
+ * How {@link ContextPackOptions.query} is applied (v1.53.0).
+ *
+ * `substring` is the original meaning and the default: a
+ * case/Unicode-insensitive substring match of the whole query against
+ * `topic + principle`, and anything that misses is dropped with a
+ * `filter-miss` skip. That answers "give me the pages about X" and
+ * nothing else - a natural-language turn matches no page at all, so a
+ * caller that hands this argument a user prompt gets an empty pack.
+ *
+ * `ranked` answers the other question: "of the pages this lane would
+ * inject anyway, which ones does this turn make relevant?" It ORDERS the
+ * collected candidates by structural token overlap and excludes none, so
+ * the budget - not a lexical accident - decides what is dropped, and the
+ * curated pool, guard, tip preference, owner scope, and receipt the lane
+ * exists for all still apply.
+ */
+export const CONTEXT_PACK_QUERY_MODES = ["substring", "ranked"] as const;
+
+export type ContextPackQueryMode = (typeof CONTEXT_PACK_QUERY_MODES)[number];
+
+export function isContextPackQueryMode(value: unknown): value is ContextPackQueryMode {
+ return (
+ typeof value === "string" && (CONTEXT_PACK_QUERY_MODES as ReadonlyArray<string>).includes(value)
+ );
+}
+
export interface ContextPackItem extends ContextTransformAnnotations {
readonly id: string;
readonly path: string;
@@ -171,8 +199,19 @@ export interface PackStampOptions {
export interface ContextPackOptions {
readonly maxTokens: number;
- /** Optional case-insensitive substring filter on topic + principle. */
+ /**
+ * Optional query. Read as a case-insensitive substring filter on topic +
+ * principle by default; see {@link ContextPackOptions.queryMode} for the
+ * ranking reading.
+ */
readonly query?: string;
+ /**
+ * How {@link ContextPackOptions.query} is applied (v1.53.0). Omitted is
+ * `substring`, byte-identical to every release before this one. `ranked`
+ * orders instead of filtering - see {@link CONTEXT_PACK_QUERY_MODES}.
+ * Without a `query` the mode has nothing to act on and is inert.
+ */
+ readonly queryMode?: ContextPackQueryMode;
/**
* Per-memory character cap (v0.20.0): trim any single page's body to
* this many code points before it consumes the token budget, so one
@@ -414,7 +453,12 @@ export function packContext(vault: string, opts: ContextPackOptions): ContextPac
startedAtMs,
);
}
- const query = opts.query ? normalizeForDedup(opts.query) : null;
+ // One query argument, two readings (v1.53.0). `ranked` takes the query
+ // out of the filter and into the sort, so `query` below - the substring
+ // predicate - is null in that mode and no candidate is ever excluded for
+ // failing to contain the turn verbatim.
+ const rankedQuery = opts.queryMode === "ranked" && opts.query ? opts.query : null;
+ const query = rankedQuery === null && opts.query ? normalizeForDedup(opts.query) : null;
// Opt-in language-agnostic prompt-injection containment (Unit 1).
// Default off, so the surfaced bodies are byte-identical to the legacy
// blocklist guard unless the vault enables the flag.
@@ -448,6 +492,25 @@ export function packContext(vault: string, opts: ContextPackOptions): ContextPac
}
}
+ // Query relevance (v1.53.0), computed once per candidate ONLY in ranked
+ // mode. Structural token overlap - the same deterministic, stopword-free,
+ // language-agnostic kernel `matchRatedDecisions` ranks with; no model, no
+ // embedding, so it works on a default install that has never indexed a
+ // vector. Matched against topic + principle + body because the turn's
+ // vocabulary lands in the body as often as in the one-line principle.
+ // The map is empty when the mode is off, so both sides read 0 and the
+ // comparator falls straight through.
+ const relevanceById = new Map<string, number>();
+ if (rankedQuery !== null) {
+ const queryTokens = tokenise(rankedQuery);
+ for (const c of candidates) {
+ relevanceById.set(
+ c.id,
+ jaccard(queryTokens, tokenise(`${c.topic} ${c.principle} ${c.body}`)),
+ );
+ }
+ }
+
// Value-per-token density (impact-per-token allocation, t_affa3bd9):
// computed once per candidate ONLY when opted in, so with the flag off
// the map is empty, the density comparator is a no-op, and the sort
@@ -473,6 +536,14 @@ export function packContext(vault: string, opts: ContextPackOptions): ContextPac
const focusA = focusScore.get(a.id) ?? 0;
const focusB = focusScore.get(b.id) ?? 0;
if (focusA !== focusB) return focusB - focusA;
+ // Ranked-query relevance sits between focus and density: a bound
+ // session focus is a standing, operator-established target and still
+ // dominates, while density is a static content heuristic that an
+ // explicit per-call query outranks. Tier remains the coarse gate above
+ // all three - a peripheral page never outranks a core one on relevance.
+ const relA = relevanceById.get(a.id) ?? 0;
+ const relB = relevanceById.get(b.id) ?? 0;
+ if (relA !== relB) return relB - relA;
// Density breaks within-tier ties after focus, before recency. The
// map is empty when the flag is off, so both sides read 0 and the
// comparator falls straight through to recency → id.
@@ -741,6 +812,10 @@ function finalizeContextPackReport(
lanes: String(opts.includeLanes === true),
max_tokens: String(report.maxTokens),
query: opts.query ?? "",
+ // Added only when the caller named a mode: the same
+ // query read two ways is two different requests, but a
+ // caller that named none must keep the prefix it had.
+ ...(opts.queryMode !== undefined ? { query_mode: opts.queryMode } : {}),
}),
],
}),
diff --git a/src/mcp/brain/pack-tools.ts b/src/mcp/brain/pack-tools.ts
index 665db7b2..90ac8a81 100644
--- a/src/mcp/brain/pack-tools.ts
+++ b/src/mcp/brain/pack-tools.ts
@@ -16,7 +16,11 @@ import {
} from "../../core/config.ts";
import { resolveSearchConfig } from "../../core/search/index.ts";
import { readActiveSessionFocus } from "../../core/search/session-focus.ts";
-import { packContext } from "../../core/brain/context-pack.ts";
+import {
+ CONTEXT_PACK_QUERY_MODES,
+ isContextPackQueryMode,
+ packContext,
+} from "../../core/brain/context-pack.ts";
import { assessRecallAdequacy } from "../../core/brain/recall-adequacy.ts";
import { recordRecallAdequacyDemand } from "../../core/brain/query-demand.ts";
import { emitGatedTelemetry } from "../../core/brain/continuity/emit.ts";
@@ -93,6 +97,24 @@ async function toolBrainContextPack(
throw new MCPError(INVALID_PARAMS, "brain_context_pack: max_tokens must be a positive integer");
}
const query = typeof args["query"] === "string" ? (args["query"] as string) : undefined;
+ // Ranked query mode (v1.53.0). Enforced beside the `dependentRequired`
+ // that declares it: a mode with no query would otherwise be accepted and
+ // do nothing, which is the silent no-op this project refuses.
+ const queryMode = coerceStr(args, "query_mode", false);
+ if (queryMode !== null) {
+ if (!isContextPackQueryMode(queryMode)) {
+ throw new MCPError(
+ INVALID_PARAMS,
+ `brain_context_pack: query_mode must be one of ${CONTEXT_PACK_QUERY_MODES.join(", ")}`,
+ );
+ }
+ if (query === undefined) {
+ throw new MCPError(
+ INVALID_PARAMS,
+ "brain_context_pack: query_mode requires query; a mode with nothing to read is inert",
+ );
+ }
+ }
const includeLanes = coerceBool(args, "lanes");
const cacheStable = coerceBool(args, "cache_stable");
const dedupRepeated = coerceBool(args, "dedup_repeated");
@@ -175,6 +197,7 @@ async function toolBrainContextPack(
...(densityRanking ? { densityRanking: true } : {}),
...(sessionFocus !== null ? { sessionFocus } : {}),
...(query ? { query } : {}),
+ ...(queryMode !== null ? { queryMode } : {}),
...(includeLanes ? { includeLanes: true } : {}),
...(receipt !== undefined ? { receipt } : {}),
...(adequacy !== undefined ? { recallAdequacy: adequacy } : {}),
@@ -222,6 +245,13 @@ async function toolBrainContextPack(
...(report.receiptId ? { receipt_id: report.receiptId } : {}),
...(report.telemetryId ? { telemetry_id: report.telemetryId } : {}),
...(report.lanes ? { lanes: report.lanes } : {}),
+ // The core computes injection-time tension warnings and the
+ // owner-scope observation and this projection dropped both, so the one
+ // surface that puts vault text in front of a model every turn was the
+ // one surface that could not say a memory it injected is contested.
+ // `brain_pre_compress_pack` has forwarded them all along; absent when
+ // empty, so a warning-free pack stays byte-identical.
+ ...(report.warnings ? { warnings: report.warnings } : {}),
...(adequacy !== undefined
? {
adequacy: {
@@ -701,7 +731,14 @@ export const PACK_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([
},
query: {
type: "string",
- description: "Optional case/Unicode-insensitive substring filter on topic + principle.",
+ description:
+ "Optional query. Read as a case/Unicode-insensitive substring filter on topic + principle unless `query_mode` says otherwise.",
+ },
+ query_mode: {
+ type: "string",
+ enum: [...CONTEXT_PACK_QUERY_MODES],
+ description:
+ "How `query` is read: `substring` (default) filters, dropping misses as `filter-miss`; `ranked` orders candidates by token overlap and excludes none.",
},
focus_session: {
type: "string",
@@ -776,8 +813,12 @@ export const PACK_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([
// Both or neither, stated declaratively so a schema-driven client can
// discover the pairing instead of learning it from an INVALID_PARAMS
// at call time. Built beside the enforcement; see
- // `recallAdequacyPairing`.
- dependentRequired: recallAdequacyPairing(RECALL_SCORES_ARG_NAME),
+ // `recallAdequacyPairing`. `query_mode` joins it one-directionally:
+ // a mode needs a query, a query needs no mode.
+ dependentRequired: {
+ ...recallAdequacyPairing(RECALL_SCORES_ARG_NAME),
+ query_mode: ["query"],
+ },
additionalProperties: false,
},
handler: toolBrainContextPack,
diff --git a/tests/core/brain/context-pack-ranked-query.test.ts b/tests/core/brain/context-pack-ranked-query.test.ts
new file mode 100644
index 00000000..b1293f8c
--- /dev/null
+++ b/tests/core/brain/context-pack-ranked-query.test.ts
@@ -0,0 +1,175 @@
+/**
+ * Ranked query mode on the context-pack lane (v1.53.0).
+ *
+ * The lane's only query facility was a case-insensitive SUBSTRING match of
+ * the whole query against `topic + principle`, so a natural-language turn
+ * `filter-miss`ed every candidate and the pack came back empty. Ranked mode
+ * ORDERS the already-collected candidates by structural token overlap
+ * instead of excluding them, which keeps the guard, the curated pool, the
+ * tip preference, the owner scope, the budget, and the receipt that only
+ * exist on this lane.
+ *
+ * Claims pinned here:
+ * 1. `queryMode` absent is byte-identical to `queryMode: "substring"` -
+ * the substring filter, and its `filter-miss` skips, are untouched.
+ * 2. A natural-language turn substring-misses everything (the defect).
+ * 3. Ranked mode excludes nothing: no `filter-miss` skip is ever emitted.
+ * 4. Ranked mode orders the query-relevant candidate first WITHIN its tier.
+ * 5. Tier stays the coarse gate: a relevant peripheral page never outranks
+ * an irrelevant core one.
+ * 6. Under a budget that fits one page, ranked mode spends it on the
+ * relevant page and reports the rest as `over-budget`, not `filter-miss`.
+ * 7. `queryMode: "ranked"` with no query changes nothing.
+ * 8. Receipt emission and the character budget are unaffected by the mode.
+ */
+
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import { packContext } from "../../../src/core/brain/context-pack.ts";
+
+let vault: string;
+
+const PRICING_TURN = "which pricing rule applies to this enterprise quote";
+
+beforeEach(() => {
+ vault = mkdtempSync(join(tmpdir(), "o2b-pack-ranked-"));
+ mkdirSync(join(vault, "Brain", "preferences"), { recursive: true });
+ mkdirSync(join(vault, "Brain", "retired"), { recursive: true });
+});
+
+afterEach(() => {
+ rmSync(vault, { recursive: true, force: true });
+});
+
+function writePref(
+ slug: string,
+ fields: { topic: string; principle: string; tier?: string; created_at?: string; body?: string },
+): void {
+ const lines = [
+ "---",
+ `id: pref-${slug}`,
+ `topic: ${fields.topic}`,
+ `principle: ${fields.principle}`,
+ ];
+ if (fields.tier) lines.push(`tier: ${fields.tier}`);
+ lines.push(`created_at: ${fields.created_at ?? "2026-01-01T00:00:00Z"}`);
+ lines.push("---", "", fields.body ?? fields.principle);
+ writeFileSync(join(vault, "Brain", "preferences", `pref-${slug}.md`), lines.join("\n"));
+}
+
+/** Three core preferences, only one of which is about pricing. */
+function writeThreeCorePreferences(): void {
+ writePref("deploy", {
+ topic: "deployment window",
+ principle: "never ship on friday",
+ tier: "core",
+ created_at: "2026-01-03T00:00:00Z",
+ });
+ writePref("pricing", {
+ topic: "pricing rules",
+ principle: "quote the enterprise tier before applying any discount",
+ tier: "core",
+ created_at: "2026-01-02T00:00:00Z",
+ });
+ writePref("imports", {
+ topic: "module imports",
+ principle: "use explicit imports only",
+ tier: "core",
+ created_at: "2026-01-01T00:00:00Z",
+ });
+}
+
+describe("context pack ranked query mode", () => {
+ test("an absent queryMode is byte-identical to the substring default", () => {
+ writeThreeCorePreferences();
+ const absent = packContext(vault, { maxTokens: 10_000, query: "pricing" });
+ const explicit = packContext(vault, {
+ maxTokens: 10_000,
+ query: "pricing",
+ queryMode: "substring",
+ });
+ expect(JSON.stringify(explicit)).toBe(JSON.stringify(absent));
+ expect(absent.items.map((i) => i.id)).toEqual(["pref-pricing"]);
+ expect(absent.skipped.map((s) => s.reason)).toEqual(["filter-miss", "filter-miss"]);
+ });
+
+ test("substring mode misses every candidate on a natural-language turn", () => {
+ writeThreeCorePreferences();
+ const r = packContext(vault, { maxTokens: 10_000, query: PRICING_TURN });
+ expect(r.items).toEqual([]);
+ expect(r.skipped.every((s) => s.reason === "filter-miss")).toBe(true);
+ expect(r.skipped.length).toBe(3);
+ });
+
+ test("ranked mode excludes nothing and orders the relevant page first", () => {
+ writeThreeCorePreferences();
+ const r = packContext(vault, {
+ maxTokens: 10_000,
+ query: PRICING_TURN,
+ queryMode: "ranked",
+ });
+ expect(r.skipped).toEqual([]);
+ expect(r.items.map((i) => i.id)).toEqual(["pref-pricing", "pref-deploy", "pref-imports"]);
+ });
+
+ test("tier stays the coarse gate over relevance", () => {
+ writePref("pricing", {
+ topic: "pricing rules",
+ principle: "quote the enterprise tier before applying any discount",
+ tier: "peripheral",
+ });
+ writePref("deploy", {
+ topic: "deployment window",
+ principle: "never ship on friday",
+ tier: "core",
+ });
+ const r = packContext(vault, {
+ maxTokens: 10_000,
+ query: PRICING_TURN,
+ queryMode: "ranked",
+ });
+ expect(r.items.map((i) => i.id)).toEqual(["pref-deploy", "pref-pricing"]);
+ });
+
+ test("a budget that fits one page is spent on the relevant page", () => {
+ writeThreeCorePreferences();
+ const full = packContext(vault, {
+ maxTokens: 10_000,
+ query: PRICING_TURN,
+ queryMode: "ranked",
+ });
+ const pricingTokens = full.items.find((i) => i.id === "pref-pricing")!.tokens;
+ const r = packContext(vault, {
+ maxTokens: pricingTokens,
+ query: PRICING_TURN,
+ queryMode: "ranked",
+ });
+ expect(r.items.map((i) => i.id)).toEqual(["pref-pricing"]);
+ expect(r.skipped.map((s) => s.reason)).toEqual(["over-budget", "over-budget"]);
+ });
+
+ test("ranked mode with no query leaves the default ordering untouched", () => {
+ writeThreeCorePreferences();
+ const plain = packContext(vault, { maxTokens: 10_000 });
+ const ranked = packContext(vault, { maxTokens: 10_000, queryMode: "ranked" });
+ expect(JSON.stringify(ranked)).toBe(JSON.stringify(plain));
+ });
+
+ test("the receipt and the character budget survive ranked mode", () => {
+ writeThreeCorePreferences();
+ const r = packContext(vault, {
+ maxTokens: 10_000,
+ query: PRICING_TURN,
+ queryMode: "ranked",
+ maxCharsPerMemory: 12,
+ receipt: { trigger: "context_pack", host: "hermes" },
+ });
+ expect(typeof r.receiptId).toBe("string");
+ expect(r.receiptId!.length).toBeGreaterThan(0);
+ expect(r.items.every((i) => i.trimmed)).toBe(true);
+ expect(r.items.every((i) => i.body.length <= 12)).toBe(true);
+ });
+});
diff --git a/tests/mcp/context-pack-tool.test.ts b/tests/mcp/context-pack-tool.test.ts
index 348778a3..5a4840fd 100644
--- a/tests/mcp/context-pack-tool.test.ts
+++ b/tests/mcp/context-pack-tool.test.ts
@@ -13,6 +13,7 @@ import { JSONRPC_VERSION, MCPServer, PROTOCOL_VERSION } from "../../src/mcp/inde
import { buildToolTable } from "../../src/mcp/tools.ts";
import { atomicWriteFileSync } from "../../src/core/fs-atomic.ts";
import { CONTEXT_GUARD_PLACEHOLDER } from "../../src/core/brain/safety/context-guard.ts";
+import { persistTension } from "../../src/core/brain/tensions.ts";
let tmp: string;
let vault: string;
@@ -270,3 +271,173 @@ describe("brain_context_pack tool — round trip", () => {
);
});
});
+
+/**
+ * Ranked query mode over the MCP surface (v1.53.0).
+ *
+ * Claims pinned here:
+ * 1. `query_mode: "ranked"` reaches the core: the query-relevant page
+ * leads and nothing is dropped with `filter-miss`.
+ * 2. `query` alone keeps the substring reading, byte-identical to every
+ * release before this one.
+ * 3. `query_mode` without `query` is refused, not silently inert - the
+ * schema states the pairing and the handler enforces it.
+ * 4. An unknown mode is refused and the refusal names the accepted set.
+ * 5. The declaration is discoverable: closed schema, described property,
+ * declared pairing.
+ * 6. The receipt the lane issues is unaffected by the mode.
+ */
+describe("brain_context_pack tool — ranked query mode", () => {
+ const PRICING_TURN = "which pricing rule applies to this enterprise quote";
+
+ function writeTwoCorePreferences(): void {
+ writeFileSync(
+ join(vault, "Brain", "preferences", "pref-deploy.md"),
+ "---\nid: pref-deploy\ntopic: deployment window\nprinciple: never ship on friday\ntier: core\ncreated_at: 2026-05-01T00:00:00Z\n---\n",
+ );
+ writeFileSync(
+ join(vault, "Brain", "preferences", "pref-pricing.md"),
+ "---\nid: pref-pricing\ntopic: pricing rules\nprinciple: quote the enterprise tier before applying any discount\ntier: core\ncreated_at: 2026-04-01T00:00:00Z\n---\n",
+ );
+ }
+
+ async function callPackRaw(
+ server: MCPServer,
+ args: Record<string, unknown>,
+ ): Promise<{ error?: { code: number; message: string } }> {
+ return (await server.handleRequest({
+ jsonrpc: JSONRPC_VERSION,
+ id: 11,
+ method: "tools/call",
+ params: { name: "brain_context_pack", arguments: args },
+ })) as { error?: { code: number; message: string } };
+ }
+
+ test("ranked mode orders by relevance and excludes nothing", async () => {
+ writeTwoCorePreferences();
+ const server = new MCPServer({ vault, configPath });
+ await initialize(server);
+ const out = await callPack(server, {
+ max_tokens: 10_000,
+ query: PRICING_TURN,
+ query_mode: "ranked",
+ });
+ const items = out["items"] as Array<{ id: string }>;
+ expect(items.map((i) => i.id)).toEqual(["pref-pricing", "pref-deploy"]);
+ expect(out["skipped"]).toEqual([]);
+ });
+
+ test("query without a mode keeps the substring reading", async () => {
+ writeTwoCorePreferences();
+ const server = new MCPServer({ vault, configPath });
+ await initialize(server);
+ const out = await callPack(server, { max_tokens: 10_000, query: PRICING_TURN });
+ expect(out["items"]).toEqual([]);
+ const skipped = out["skipped"] as Array<{ reason: string }>;
+ expect(skipped.map((s) => s.reason)).toEqual(["filter-miss", "filter-miss"]);
+ });
+
+ test("query_mode without query is refused", async () => {
+ const server = new MCPServer({ vault, configPath });
+ await initialize(server);
+ const r = await callPackRaw(server, { max_tokens: 10_000, query_mode: "ranked" });
+ expect(r.error).toBeDefined();
+ expect(r.error!.message).toContain("query_mode");
+ expect(r.error!.message).toContain("query");
+ });
+
+ test("an unknown query_mode names the accepted set", async () => {
+ const server = new MCPServer({ vault, configPath });
+ await initialize(server);
+ const r = await callPackRaw(server, {
+ max_tokens: 10_000,
+ query: "x",
+ query_mode: "semantic",
+ });
+ expect(r.error).toBeDefined();
+ expect(r.error!.message).toContain("substring");
+ expect(r.error!.message).toContain("ranked");
+ });
+
+ test("the declaration is closed, described, and states the pairing", () => {
+ const tool = buildToolTable("full").find((t) => t.name === "brain_context_pack")!;
+ const schema = tool.inputSchema as {
+ properties: Record<string, { type?: string; enum?: string[]; description?: string }>;
+ dependentRequired?: Record<string, ReadonlyArray<string>>;
+ additionalProperties?: boolean;
+ };
+ const declared = schema.properties["query_mode"]!;
+ expect(declared.enum).toEqual(["substring", "ranked"]);
+ expect(declared.description!.length).toBeGreaterThan(0);
+ expect(schema.additionalProperties).toBe(false);
+ expect(schema.dependentRequired!["query_mode"]).toEqual(["query"]);
+ });
+
+ test("the receipt is issued in ranked mode exactly as in the default", async () => {
+ writeTwoCorePreferences();
+ const server = new MCPServer({ vault, configPath });
+ await initialize(server);
+ const out = await callPack(server, {
+ max_tokens: 10_000,
+ query: PRICING_TURN,
+ query_mode: "ranked",
+ receipt: true,
+ receipt_host: "hermes",
+ });
+ expect(typeof out["receipt_id"]).toBe("string");
+ expect((out["receipt_id"] as string).length).toBeGreaterThan(0);
+ });
+});
+
+/**
+ * Injection-time warnings reach the caller (v1.53.0).
+ *
+ * `packContext` computes tension warnings and the owner-scope observation
+ * and this tool's projection dropped both, so the primary injection surface
+ * could not tell an agent that a memory it just injected is contested.
+ */
+describe("brain_context_pack tool — warnings", () => {
+ test("an unresolved tension over an injected memory is reported, not dropped", async () => {
+ writeFileSync(
+ join(vault, "Brain", "preferences", "pref-tabs.md"),
+ "---\nid: pref-tabs\ntopic: t\nprinciple: always use tabs\ntier: core\n---\n\nAlways use tabs.\n",
+ );
+ writeFileSync(
+ join(vault, "Brain", "preferences", "pref-spaces.md"),
+ "---\nid: pref-spaces\ntopic: t\nprinciple: never use tabs\ntier: core\n---\n\nNever use tabs.\n",
+ );
+ const { record } = persistTension(
+ vault,
+ {
+ aId: "pref-tabs",
+ bId: "pref-spaces",
+ subject: "for indentation tabs use",
+ jaccard: 0.6,
+ aSign: "positive",
+ bSign: "negative",
+ aQuote: "Always use tabs.",
+ bQuote: "Never use tabs.",
+ action: "ask_user",
+ },
+ { agent: "tester" },
+ );
+
+ const server = new MCPServer({ vault, configPath });
+ await initialize(server);
+ const out = await callPack(server, { max_tokens: 10_000 });
+ const warnings = out["warnings"] as ReadonlyArray<string>;
+ expect(Array.isArray(warnings)).toBe(true);
+ expect(warnings.some((w) => w.includes(record.id))).toBe(true);
+ });
+
+ test("a tension-free vault carries no warnings key", async () => {
+ writeFileSync(
+ join(vault, "Brain", "preferences", "pref-tabs.md"),
+ "---\nid: pref-tabs\ntopic: t\nprinciple: always use tabs\ntier: core\n---\n\nAlways use tabs.\n",
+ );
+ const server = new MCPServer({ vault, configPath });
+ await initialize(server);
+ const out = await callPack(server, { max_tokens: 10_000 });
+ expect(out["warnings"]).toBeUndefined();
+ });
+});
diff --git a/tests/python/test_memory_provider.py b/tests/python/test_memory_provider.py
index 7213e687..18f98a2c 100644
--- a/tests/python/test_memory_provider.py
+++ b/tests/python/test_memory_provider.py
@@ -802,6 +802,178 @@ class ProviderLifecycleTests(unittest.TestCase):
self.assertIn("RECALLED", out)
self.assertIn("@pf-agent", out)
+ def test_prefetch_query_reaches_the_pack_lane(self):
+ # The turn's query rides the curated lane in ranked mode, so the
+ # guard, the preference pool, the budget and the receipt all still
+ # apply. Nothing is recalled through raw brain_search.
+ bridge = FakeBrainBridge(
+ results={
+ "brain_recall_gate": {"structuredContent": {"retrieve": True}},
+ "brain_context_pack": {
+ "structuredContent": {
+ "receipt_id": "receipt-ranked",
+ "items": [{"body": "quote the enterprise tier first"}],
+ }
+ },
+ }
+ )
+ provider = self._init(bridge, hermes_home="/tmp/hh")
+ out = provider.prefetch("which pricing rule applies", session_id="sess-1", turn_id="turn-7")
+
+ self.assertIn("quote the enterprise tier first", out)
+ self.assertNotIn("brain_search", [name for name, _ in bridge.calls])
+ pack_args = next(a for n, a in bridge.calls if n == "brain_context_pack")
+ self.assertEqual(pack_args["query"], "which pricing rule applies")
+ self.assertEqual(pack_args["query_mode"], "ranked")
+ self.assertEqual(pack_args["turn_id"], "turn-7")
+ self.assertEqual(pack_args["session_id"], "sess-1")
+ gate_args = next(a for n, a in bridge.calls if n == "brain_recall_gate")
+ self.assertEqual(gate_args["turn_id"], "turn-7")
+ self.assertEqual(gate_args["telemetry_host"], "hermes")
+
+ def test_prefetch_keeps_the_server_receipt_as_sample_id(self):
+ # The sample id an agent later posts an outcome against must be the
+ # id the server wrote a receipt under, never a locally hashed
+ # string: an id with no receipt behind it resolves to
+ # unresolved/sample_absent forever.
+ bridge = FakeBrainBridge(
+ results={
+ "brain_recall_gate": {"structuredContent": {"retrieve": True}},
+ "brain_context_pack": {
+ "structuredContent": {
+ "receipt_id": "receipt-server-issued",
+ "items": [{"body": "keep RRF"}],
+ }
+ },
+ }
+ )
+ provider = self._init(bridge, hermes_home="/tmp/hh")
+ out = provider.prefetch("what did we decide", session_id="sess-1")
+
+ metadata = json.loads(out.split("[O2B context-pack metadata] ", 1)[1].split("\n", 1)[0])
+ self.assertEqual(metadata["sample_id"], "receipt-server-issued")
+ self.assertNotIn("hermes-search-", out)
+
+ def test_prefetch_surfaces_a_pack_warning_instead_of_swallowing_it(self):
+ # An injected memory that is the subject of an unresolved tension is
+ # a degraded recall. The pack names it; the provider must not drop
+ # the name on the floor.
+ bridge = FakeBrainBridge(
+ results={
+ "brain_recall_gate": {"structuredContent": {"retrieve": True}},
+ "brain_context_pack": {
+ "structuredContent": {
+ "receipt_id": "receipt-warned",
+ "items": [{"body": "always use tabs"}],
+ "warnings": ["tension t-123 is unresolved for pref-tabs"],
+ }
+ },
+ }
+ )
+ provider = self._init(bridge, hermes_home="/tmp/hh")
+ with self.assertLogs("plugins.hermes.provider", level="WARNING") as logs:
+ provider.prefetch("indentation", session_id="sess-1")
+ self.assertTrue(
+ any("tension t-123 is unresolved" in line for line in logs.output), logs.output
+ )
+
+ def test_prefetch_has_one_recall_lane_and_names_an_empty_one(self):
+ # There is no second lane to fall back to, and an empty pack on a
+ # gated turn says so rather than passing for a healthy injection.
+ bridge = FakeBrainBridge(
+ results={
+ "brain_recall_gate": {"structuredContent": {"retrieve": True}},
+ "brain_context_pack": {"structuredContent": {"items": []}},
+ }
+ )
+ provider = self._init(bridge, hermes_home="/tmp/hh")
+ with self.assertLogs("plugins.hermes.provider", level="INFO") as logs:
+ out = provider.prefetch("what did we decide", session_id="sess-1")
+ self.assertNotIn("brain_search", [name for name, _ in bridge.calls])
+ self.assertNotIn("[O2B context-pack metadata]", out)
+ self.assertTrue(
+ any("brain_context_pack" in line for line in logs.output), logs.output
+ )
+
+ def test_prefetch_budget_holds_for_cyrillic_and_cjk(self):
+ # The budget is a TOKEN budget the server enforces, not a character
+ # budget guessed in Python at four bytes per token - a ratio that is
+ # wrong by 2x to 4x on Cyrillic and CJK. Nothing is cut locally, and
+ # the declared budget travels with the request.
+ for script, body in (
+ ("cyrillic", "\u043f\u0440\u0430\u0432\u0438\u043b\u043e " * 800),
+ ("cjk", "\u5b9a\u4ef7\u89c4\u5219" * 1200),
+ ):
+ with self.subTest(script=script):
+ bridge = FakeBrainBridge(
+ results={
+ "brain_recall_gate": {"structuredContent": {"retrieve": True}},
+ "brain_context_pack": {
+ "structuredContent": {
+ "receipt_id": "receipt-" + script,
+ "items": [{"body": body}],
+ }
+ },
+ }
+ )
+ provider = self._init(bridge, hermes_home="/tmp/hh")
+ out = provider.prefetch("q", session_id="sess-1")
+ self.assertIn(body, out)
+ pack_args = next(a for n, a in bridge.calls if n == "brain_context_pack")
+ self.assertEqual(pack_args["max_tokens"], 1024)
+
+ def test_prefetch_keeps_a_plain_note_body_intact(self):
+ # Regression for the deleted `_recall_body`: it scanned every line of
+ # a result for one beginning `principle:` and returned that value
+ # alone, so an ordinary note carrying such a line in its BODY was
+ # reduced to it and the rest was silently deleted.
+ body = (
+ "principle: never ship on friday\n"
+ "We tried it twice and both rollbacks landed on a weekend."
+ )
+ bridge = FakeBrainBridge(
+ results={
+ "brain_recall_gate": {"structuredContent": {"retrieve": True}},
+ "brain_context_pack": {
+ "structuredContent": {"receipt_id": "receipt-plain", "items": [{"body": body}]}
+ },
+ }
+ )
+ provider = self._init(bridge, hermes_home="/tmp/hh")
+ out = provider.prefetch("deployments", session_id="sess-1")
+ self.assertIn("We tried it twice and both rollbacks landed on a weekend.", out)
+
+ def test_outcome_list_is_not_silently_host_filtered(self):
+ # `host` is a READ filter for list/summary, so defaulting it there
+ # would narrow an agent's query to hermes rows without saying so.
+ # The correlation defaults belong to `post` alone.
+ bridge = FakeBrainBridge(
+ results={"brain_context_pack_outcome": {"structuredContent": {"rows": []}}}
+ )
+ provider = self._init(bridge, hermes_home="/tmp/hh")
+ provider.handle_tool_call("brain_context_pack_outcome", {"operation": "list"})
+ provider.handle_tool_call("brain_context_pack_outcome", {"operation": "summary"})
+ provider.handle_tool_call(
+ "brain_context_pack_outcome",
+ {"operation": "post", "sample_id": "s", "first_pass_success": True},
+ )
+ reads = [
+ a
+ for n, a in bridge.calls
+ if n == "brain_context_pack_outcome" and a["operation"] in ("list", "summary")
+ ]
+ self.assertEqual(len(reads), 2)
+ for args in reads:
+ self.assertNotIn("host", args)
+ self.assertNotIn("session_id", args)
+ posted = next(
+ a
+ for n, a in bridge.calls
+ if n == "brain_context_pack_outcome" and a["operation"] == "post"
+ )
+ self.assertEqual(posted["host"], "hermes")
+ self.assertEqual(posted["session_id"], "sess-1")
+
def test_prefetch_exposes_receipt_and_agent_posts_structured_outcome(self):
bridge = FakeBrainBridge(
results={
@@ -831,7 +1003,16 @@ class ProviderLifecycleTests(unittest.TestCase):
)
self.assertIn('"sample_id": "receipt-1"', out)
+ # Names the lane under test: an unregistered fake tool answers `{}`,
+ # so a pin that only asserts on the OUTPUT can keep passing while the
+ # provider quietly recalls through something else.
+ self.assertEqual(
+ [n for n, _ in bridge.calls if n in ("brain_context_pack", "brain_search")],
+ ["brain_context_pack"],
+ )
+ self.assertIn("[O2B context-pack metadata] ", out)
pack_args = next(a for n, a in bridge.calls if n == "brain_context_pack")
+ self.assertEqual(pack_args["query_mode"], "ranked")
self.assertIs(pack_args["receipt"], True)
self.assertEqual(pack_args["receipt_host"], "hermes")
self.assertIs(pack_args["telemetry"], True)
@@ -860,6 +1041,11 @@ class ProviderLifecycleTests(unittest.TestCase):
provider = self._init(bridge, hermes_home="/tmp/hh")
provider.prefetch("what did we decide", session_id="sess-1")
provider.prefetch("tell me something else", session_id="sess-1")
+ # Both turns recalled through the shipped lane, and neither posted.
+ self.assertEqual(
+ [n for n, _ in bridge.calls if n in ("brain_context_pack", "brain_search")],
+ ["brain_context_pack", "brain_context_pack"],
+ )
self.assertEqual(
[name for name, _ in bridge.calls if name == "brain_context_pack_outcome"], []
)
@@ -890,8 +1076,10 @@ class ProviderLifecycleTests(unittest.TestCase):
provider.prefetch("我之前说过,不对", session_id="sess-1")
self.assertEqual(gate_calls, 3)
+ # The one gated turn ran on the context-pack lane, and no search lane
+ # exists to absorb the multilingual turns instead.
self.assertEqual(
- [name for name, _ in bridge.calls if name == "brain_context_pack"],
+ [n for n, _ in bridge.calls if n in ("brain_context_pack", "brain_search")],
["brain_context_pack"],
)
self.assertEqual(