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
23.0 KB
Raw Blame

Recall Lane Latency and Caller Control - overlapped hybrid lanes, opt-in packing policy, standing-instruction facets, rerank test fixture

Status: draft Author: claude-dev-agent (via feature-release-playbook) Audience: implementation

Problem statement

The recall lane costs more and tells callers less than it should. Hybrid search runs its semantic lane strictly after the keyword lane completes (runKeywordLane at src/core/search/pipeline/keyword-lane.ts:64 is synchronous; the await stands at src/core/search/search.ts:454-461), so every semantic query pays the full query-embed round trip after keyword retrieval, and nothing reports how much of that could be hidden. Callers also cannot steer what the reading budget buys: pages and facts-side candidates are packed in one fixed order, and standing instructions surface as bare pref-<slug> (scope) strings (src/core/brain/attention-flows.ts:196-221) with no first-mention provenance even though the provenance already exists in frontmatter. Finally, the rerank contract is tested by stubbing globalThis.fetch against a fake endpoint because the shared fixture (tests/helpers/fake-http.ts) serves only /embeddings. Four kanban cards, one spine: make the recall lane faster, and give callers honest, opt-in control and accounting over what it returns.

Premise verdicts (from recon, anchors re-verified at HEAD e239d323)

  • t_862b4d29 (semantic lane concurrency) - CONFIRMED. The serial await is real: keyword lane completes at search.ts:413-431 (hits bound at 429, warnings merged 430-431) before the semantic lane is started and awaited at 454-461 (await runSemanticLane at 456, awaitWithinDeadline arm at 457-460). The embed round trip is awaited inside the lane (semantic-phase.ts:185-189 embed, :232 semanticTopK). No start-early/join exists on the query path. Minor card drift recorded by recon: runKeywordLane is at search.ts:413 (card said 430); the await-chain anchor 456 is exact. Two risks folded into the design: a dangling in-flight embed when the keyword lane throws (new failure mode with start-early; mitigation in Design decisions), and keywordHitCount being read at lane-start time (semantic-lane.ts:32, consumed by detectHybridDegrade at semantic-lane.ts:109-113) which would silently drop hybrid_degraded under start-early - hence the lazy supplier. overlapped_ms must ride a per-call sink, not SearchOutcome: the query cache persists the whole outcome (persistCachedOutcome call at src/core/search/pipeline/cache-slot.ts:472, guarded at search.ts:402-410), so an outcome field would freeze stale timings into cached rows.
  • t_767a6bd3 (packing policy) - PARTLY FALSE, corrected scope honored and narrowed once more. The budget primitive and the queryMode opt-in precedent both exist (frozen tuple and guard at src/core/brain/context-pack.ts:113-121, option at :258, MCP coercion and refusals at src/mcp/brain/pack-tools.ts:186-204, schema enum at :1056-1062, dependentRequired at :1136-1141). But the premise of one budget to reorder is false: pages live under ContextPackOptions.maxTokens (context-pack.ts:245, loop at 726-765, applyCharBudget at 715 and 815) while the facts-side brief lives under the hook's own caps (RECALL_INJECT_MAX_NOTES/MAX_CHARS/TIME_BUDGET_MS at src/core/brain/recall-inject.ts:42-48). The two surfaces never run in one call, so a cross-surface packing order is not implementable without growing the hook past its 2,500 ms budget. Per the operator note the design scopes down: correlate the two candidate populations that DO share one budget - preference-derived candidates and page candidates inside packContext's single maxTokens - and make the knob strictly opt-in, MCP-only, omitted meaning byte-identical. The recall-inject option, the config key and the hook threading (recon task 4) are deferred, not stubbed.
  • t_4b2ffde5 (standing-instruction facets) - PARTLY FALSE, rescope honored. True: no standing-instruction facet mechanism and no first-mention surfacing exists. Overstated and corrected: provenance has a home - created_at/evidenced_by at src/core/brain/preference.ts:148/:151, dream-stamped valid_from at :248/:904, and the turn id one hop away in BrainSignal.session_ref typed as <path>#<turn-id> (src/core/brain/types.ts:877), baked in by import (src/core/brain/sessions/import.ts:445). The "zero facet symbols" claim is stale: ThreadFacet/ThreadFacetMention/ThreadFacetCluster shipped at src/core/brain/thread-topics.ts:38-59, so the new lane reuses that contract style with a distinct type name. Residual real gap: commitExtractedSignals persists a bare session:<id> ref (src/core/brain/extract-signals.ts:646), so auto-extracted preferences have no turn to join; the join reports no-provenance there honestly and the write-path fix is out of scope.
  • t_1b2b6932 (shared rerank fixture) - PARTLY FALSE, rescope honored. The consolidation the card asked for already exists: tests/helpers/fake-http.ts is the shared deterministic fixture and its default handler (lines 37-50) serves only /embeddings, 404ing everything else. The honest scope is the validator's: add a /rerank route to the default handler and migrate the cross-encoder tests onto the fixture. The byte-pinned degraded-warning risk is handled by leaving raw-body 503 cases at the fetch seam (the fixture JSON-encodes bodies, which would change the pinned rerank_degraded: strings).

Scope

  • Lane D - fixture substrate (lands first, test-only): a deterministic /rerank branch in the fake-http default handler (wrapped response shape, one item per document, whitespace-overlap scoring matches / (matches + 1), 400 on a body without an array documents, model echo) and migration of rerank.cross-encoder.test.ts plus the three pipeline rerank test files onto the fixture.
  • Lane A - lane concurrency: start the semantic lane before runKeywordLane, join where the await stands today under both deadline arms, lazy keywordHitCount supplier read at lane completion, preserved warning merge order, rejection handling for a lane in flight when the keyword step throws, overlapped_ms measured as the intersection of the embed and keyword intervals and threaded through a per-call timing sink into search --explain and the bench latency family.
  • Lane B - packing policy: a frozen PACKING_POLICIES vocabulary (facts_first, query_first) and a pure allocateRecallBudget helper in src/core/brain/recall-budget.ts; an optional packingPolicy on the context-pack options that reorders which candidate population claims the pack's existing single token budget; a packing accounting object on the report; the brain_context_pack MCP argument, schema enum and refusals mirroring query_mode; conditional receipt/telemetry/prompt-prefix metadata. Omitted everywhere means byte-identical.
  • Lane C - standing-instruction facets: a pure read-time provenance join (module src/core/brain/preference-provenance.ts) over evidenced_by links and producer-aware session_ref parsing; a StandingInstructionFacet projection offered as an additive option on the attention-flow standing_query evaluation; a standing_instruction bench category with an additive knob pin; conditional bench verb surfacing; zero writes end to end.
  • Docs and CHANGELOG hunks pinned per lane (see plan.md cross-lane contract).

Out of scope

  • Recall-inject hook packing (deferred, not stubbed): no packingPolicy on RecallInjectOptions, no recall_budget_policy config key, no hook change. The hook runs a single lane; a policy there is inert by the design's own refusal rule, and teaching it to fetch page bodies cannot fit the 2,500 ms budget. Its own card if wanted later.
  • CLI flag for the packing knob: o2b brain context-pack stays as is; MCP-first parity follows the query_mode precedent (ranked/semantic shipped MCP-only; the CLI flag was a separate parity change).
  • MCP surfacing of overlapped_ms: searchAcrossVaults merges per-origin outcomes and a per-call sink yields one value per origin; no honest single value exists for the merged payload. search --explain and the bench are the surfaces.
  • Extract-signals turn stamping: persisting source_turn onto signal frontmatter so auto-extracted preferences become joinable is a write-path change beyond the corrected scope.
  • fake-http rawBody/stall extension and chat-completions route: the three stream-level fetch stubs in rerank-failure.test.ts and the doctor tripwire stay at the fetch seam; no chat flow exists in this tree.
  • Standing-instruction facets over MCP or ContextPackOptions: the facet ships as an option on the attention-flow evaluation and is proven by the bench gate, matching the upstream discipline of measuring before exposing. A pack-tool argument would also collide with lane B's file ownership.

Chosen approach

Variant 2, "Substrate-First Opt-In Seams" (variants.md): the shared fixture grows its /rerank route first because every later lane's tests lean on it; then each recall improvement lands behind the seam it already owns, with byte-identical behavior whenever the new option is absent. Concurrency is start-early/join-late with the keyword lanes authoritative under the composite deadline; the packing policy is a pure allocation reorder inside the pack's single budget, opt-in per call; facets are a read-time join annotated only onto what recall already delivers, gated by a bench category so the lane ships measured; and overlapped_ms accounting rides a per-call timing sink so the query cache never sees it.

Design decisions

  • Start-early, join-late, keyword lanes authoritative. search() calls the semantic lane before runKeywordLane, holding the promise; the embed HTTP request leaves in that tick: the provider semaphore's synchronous fast path (tryAcquire) takes a free permit without yielding, so the dispatch precedes the keyword lanes; the pre-call await inside the provider would have deferred it past them, which the external review caught and the dispatch-order test now pins. The join happens where the await stands today (search.ts:454-461), keeping both arms: direct await when the deadline is null, the same awaitWithinDeadline semantics over the already-started promise otherwise (the helper gains an overload accepting a started promise). The post-join void (search.ts:469-473) and every later deadlineExpired checkpoint are untouched, so the keyword-only degrade contract stays exactly as shipped. The never-start rule (a deadline already expired at lane start does not start the embed) moves to the start site, mirroring awaitWithinDeadline's behavior at search.ts:225-229. Lane start stays after the cache probe so cached answers still cost nothing.
  • Lazy keywordHitCount. SemanticLaneInput.keywordHitCount becomes number | (() => number), read where detectHybridDegrade runs at lane completion (semantic-lane.ts:109-113). The union keeps the four numeric call sites in tests/core/search/semantic-phase-spend-gate.test.ts compiling. The value stays byte-identical: the lane cannot complete before the join, which is after keywordHits is assigned and before the second-pass reassignments - the same snapshot search.ts:451 evaluates today. The deadline's own closure (search.ts:329) is unchanged.
  • No dangling embed. Attaching the rejection handler at start time is mandatory: with a deadline, a lane rejection arriving after abandonment routes to noteAbandonedFailure (search.ts:196-201, prefix constant at :108); without one, the handler joins the lane into the existing error path so there is no unhandled rejection and no store.semanticTopK against a closed store (the hazard already documented at semantic-phase.ts:224).
  • Byte-identical results. Lane hit arrays are unchanged data, so fusion, MMR and the trail see identical inputs. Warning merge order is preserved: keyword warnings pushed synchronously right after runKeywordLane returns (today's 430-431), semantic warnings at the join (464-465). The regression harness is the resultShape projection (tests/core/search/hybrid-deadline.test.ts:110) plus new byte-shape assertions in tests/core/search/hybrid-overlap.test.ts.
  • overlapped_ms formula pinned: max(0, min(embedEndMs, keywordEndMs) - max(embedStartMs, keywordStartMs)), zero whenever the lane did not attempt the embed. Interval intersection is symmetric and measures actual overlap; upstream's "embed hidden past keyword end" variant is derivable later from the same timing record if a consumer wants it.
  • Per-call timing sink, not an outcome field. A SearchOptions hook in the freshenSpawn mold (src/core/search/types.ts:1131) receives one record (embed start/end, keyword start/end, overlapped, attempted) at the join. The query cache persists whole outcomes (cache-slot.ts:472), so nothing timing-shaped ever reaches SearchOutcome and cached rows cannot carry stale timings. Deadline-degraded answers are already never cached (search.ts:402-410).
  • Explain and bench projection. The --explain envelope gains the timing only when the flag is on (house rule: off means absent, bytes identical; envelope at src/core/search/explain-envelope.ts:122, projection in src/cli/search/outcome-render.ts:114-208) and the human transcript prints the overlapped line only under --explain. The bench passes the sink per question (retrieve loop around src/core/bench/phases.ts:405-414) and the aggregate latency family (phases.ts:775-805) gains overlapped_ms only when at least one question attempted the semantic lane; keyword-only suites keep their report bytes and the committed baseline unchanged. The human line (src/cli/brain/verbs/bench.ts:431) gains a conditional overlapped_ms line under the same rule.
  • Packing: correlate first, reorder second, inside one budget. allocateRecallBudget(totalTokens, pagesLane, factsLane, policy) is a pure helper beside applyCharBudget in recall-budget.ts - both lanes already denominate content with the same estimateTokens currency, and per-lane native caps (chars, note counts) stay lane-internal fit rules. Inside packContext, the facts lane is the preference-derived candidate population and the pages lane is the rest; facts_first (default member) reproduces the current outcome because tier gating already lets the distilled layer claim first; query_first lets the query-ordered page lane claim before the facts lane fills the remainder. Claiming is strictly sequential with no minimum-page floor, matching upstream's simple semantics; the empty-lane refusal covers the degenerate cases. The total never grows - the rule recall-inject already applies (recall-inject.ts:197). A policy against an empty lane is refused by name, never a silent no-op, mirroring pack-tools' "a mode with nothing to read is inert" refusal (pack-tools.ts:197). Naming follows the repo's option-naming style - packingPolicy / packing_policy - rather than upstream's budget_policy, because the option reorders packing under a fixed budget and never resizes the budget.
  • Packing knob strictly opt-in, omitted equals byte-identical. With packingPolicy absent the partition never runs and the existing code path executes unchanged, pinned the way context-pack-ranked-query.test.ts pins the absent queryMode. The report's packing accounting object, the MCP response member, the receipt/telemetry metadata and the prompt-prefix segment appear only when the caller named a policy (contextPackBudgetMetadata at context-pack.ts:1011 feeds the receipt path; the prefix segment mirrors the query_mode conditional at context-pack.ts:998). The synced telemetry carries the policy name as a closed enum member, which satisfies the names-nothing-sensitive rule. applyCharBudget's trimming and the attention block's reserved charge stay charged inside whichever lane draws them.
  • Facets: read-time join, thread-facet contract, honest gaps. StandingInstructionFacet follows the ThreadFacet shape (stable pref:<id> key, ordered establishing turns, pure function) with a distinct name and a doc-comment cross-reference so the two facet meanings do not blur. The join parses # fragments producer-aware - basename#turn from import-session (import.ts:445), session:<id>#<event> from the capture lifecycle (src/core/brain/session-lifecycle.ts:858, labeled origin event, not origin turn), bare session:<id> from extract-signals (extract-signals.ts:646, no provenance) - qualifies the fragment with its session key (the qualifiedTurnId lesson), orders by the preference's own evidence, and returns the earliest as first mention. Unknown, absent or unrecognized shapes yield no provenance, never a guess. With the option unset, pref-<slug> (scope) output is byte-identical; with it set, only resolving preferences gain annotations, the retirement exclusion applies before annotation (a retired preference is renamed out of preferences/, so the directory walk never sees it) while the lane applies no owner filter - owner-held preferences surface identically with the option on and off - and the lane performs zero writes (standing-rules opacity and assertStandingRulesNotTargeted stay the boundary).
  • Facets measured before exposure. The standing_instruction member joins BENCH_CATEGORIES (src/core/bench/types.ts:36-48); the retrieve phase drives the surfacing call with the facet option on for the new questions and evaluateQuestion asserts the preference id plus origin turn. BenchPinnedKnobs gains one additive field so lane-on runs get a distinct identity while DEFAULT_BENCH_KNOB_PIN (types.ts:260) and existing run ids stay untouched. The gate is two runs of the same suite (lane off asserts the default report is unchanged; lane on asserts the category passes); no comparison-report schema. The verb prints the category only when present, mirroring the conditional longmemeval block. Reports without the category serialize byte-identically.
  • Fixture: additive route, migration at the handler seam. The /rerank branch lives inside defaultHandler (tests/helpers/fake-http.ts:37-50); no exported API changes, all existing consumers untouched. Scoring is whitespace-token overlap matches / (matches + 1) - deterministic, in [0, 1), monotone, no clock or randomness; a test forces an ordering by planting the query token in one document. Degenerate bodies get 400 so a misdirected test fails visibly. The cross-encoder suite migrates wholesale (capturing setHandler for request-shape assertions, callCount() for the empty-documents short-circuit); the three pipeline suites replace their duplicated stubRerankFetch with doc.includes(winner) handlers, preserving winner selection exactly. Raw-body 503 pins stay at the fetch seam, so the pinned rerank_degraded: strings do not change.

File changes

New: src/core/brain/preference-provenance.ts (lane C join), tests/core/search/hybrid-overlap.test.ts (A), tests/core/search/outcome-shape-census.test.ts (A, the sanctioned outcome-key census), tests/core/brain/preference-provenance.test.ts and a standing-instruction facet/bench test file (C), a packing-policy test file for core plus one for the MCP surface (B).

Modified - lane A: src/core/search/search.ts (start-early/join, sink), src/core/search/pipeline/semantic-lane.ts (supplier type, timing record), src/core/search/semantic-phase.ts (embed timing), src/core/search/types.ts (sink option, timing record type), src/core/search/index.ts (SearchLaneTiming re-export), src/core/search/pipeline/request.ts (the readable clock port every lane-interval stamp reads through), src/core/search/explain-envelope.ts, src/cli/search/outcome-render.ts, src/cli/search/verbs/query.ts, src/core/bench/phases.ts, src/cli/brain/verbs/bench.ts, src/core/bench/types.ts (latency family only), CHANGELOG.md (creates the wave version section), docs/updating.md, plus tests/core/search/semantic-phase-spend-gate.test.ts and hybrid-deadline.test.ts extensions.

Modified - lane B: src/core/brain/recall-budget.ts (vocabulary, allocation), src/core/brain/context-pack.ts (option, partition, accounting), src/core/brain/belief-semantic.ts (spentQueryDisclosure extracted so the lane-empty refusal carries the spend sentence), src/mcp/brain/pack-tools.ts (argument, schema, response), docs/mcp.md, CHANGELOG.md, docs/updating.md.

Modified - lane C: src/core/brain/attention-flows.ts (additive option on the standing_query evaluation), src/core/bench/types.ts (category member, knob pin field), src/core/bench/phases.ts (category branches), src/cli/brain/verbs/bench.ts (conditional print; src/core/bench/fixture.ts needs no change - category validation already rides the tuple), CHANGELOG.md (appends facet bullets), docs/updating.md.

Modified - lane D: tests/helpers/fake-http.ts (default handler only), tests/helpers/fake-http.test.ts, tests/core/search/rerank.cross-encoder.test.ts, tests/core/search/rerank.search.test.ts, tests/core/search/relational-rerank-pin.test.ts, tests/core/search/rerank-sunset.test.ts.

Shared seams and hunk ownership are pinned in plan.md's cross-lane contract (bench files split between A and C; CHANGELOG section created by A, appended by B and C).

Risks and open questions

  • Unhandled rejection window (lane A, new failure mode): between lane start and join, a keyword-step throw can strand an in-flight embed. Mitigated by the attach-at-start rule above; the hybrid-overlap tests cover both deadline arms, and the existing stall and byte-shape tests in hybrid-deadline.test.ts must pass unchanged.
  • Windows timer clamping (lane A): small overlaps can flatten to 0 on CI; timing assertions stay lower-bounded with margins, mirroring the existing deadline wall-clock tests.
  • Bench report shape (lanes A and C): the aggregate JSON and the baseline fixture must stay byte-identical for keyword-only, lane-off runs. Both lanes' bench tasks pin this explicitly; the baseline (failure-mode rates) is verified unmoved.
  • Hook-side packing deferred (lane B): resolved per the operator note rather than left open - the knob stays pack-only until a shared budget owner exists. Revisit only if a caller asks for facts-brief correlation inside the hook's budget.
  • Provenance coverage honesty (lane C): most real preferences (auto-extracted, hand-authored) resolve no turn; the facet reports resolved counts honestly rather than implying provenance everywhere, and the bench fixtures state which population they annotate.
  • Fixture consumer breadth (lane D): 42 test files consume startFakeHttp; the route is additive to the default handler only, but the full bun test run before landing the substrate is the guard against any consumer relying on /rerank 404ing (none found in recon).
  • Overlapped_ms on multi-vault MCP payloads: intentionally unresolved; if a caller surfaces a need, the per-origin values can be exported per origin before any merged single-value decision is made. Owner: lane A follow-up card.
  • Query-first regression discipline: upstream kept facts-first default because a misrouted fact question regressed under query-first; the same caution holds here - the default member preserves current behavior and the bench gate pattern (two runs) is the template any future default change must follow.