Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix: pre-landing review fixes (pass 2)

garrytancd7052755251
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsv
index 34ae7067dc..020c59f723 100644
--- a/scripts/module-size-limits.tsv
+++ b/scripts/module-size-limits.tsv
@@ -41,7 +41,7 @@ src/core/persistence/sync-run.ts 1695 ratchet new row: crossed the 1500 unlisted
src/core/bootstrap/harness.ts 2630 ratchet +29 live-PGLite-serve lane: LIVE_SERVE refusal ahead of source resolution + unpinned --token hooks (CI e2e fix); +46 wave review: resolveHookSource dep (serve-parity resolver + federated grant), --source shape validation, loud SOURCE_UNRESOLVED instead of a silent 'default'; +10: #4574 parseCodexBlockBearer http_headers shape + legacy bearer_token fallback; +4 at megawave/wave-k merge; +codex hooks lane: step-7 codex hooks.json + config.toml trust pair, removeHarness arm; +234 ambient-writeback WP3: kind:'instructions' targets (plan/apply/converge-off/remove/status probes, OV-A4 override pre-check) — splice/render mechanics live in instructions-block.ts; +59 adversarial fix wave: registrar-mode block suppression, converge-failure receipt tracking, MCP-confirmed guard before block install; +26 round-3 fixes: codex-lane MCP-confirmed guard + smoke-rollback block strip; master: | merged v0.48.1.0 true-up; +41 #4897 resolveImplicitSource dep + defaultResolveImplicitSource: hooks/token/receipt bind to the serve's implicit default source when --source is omitted; +23 #4586 statusHarness live claude-code mcp verdict (URL mismatch or same-scope non-HTTP registration reads failed, receipt untouched); shared-skills integration on company-ingestion base; +18 #5671: logAmbientPostureNotes helper (registrar note moved out of applyHarness + pre-consent warning when an explicit private facts default meets the HTTP harness; text shared with doctor in facts/writeback-config.ts); +24 #5893: rotation grant carry wiring and its rotationCarry/withheldOperationsNote helpers (carry rules live in token-mint.ts carryLegacyGrant); +6 #5878: --refresh-skills flag and status epoch line (refresh logic lives in harness-skills.ts); +7 #4618 seat: HarnessFlags.seat field, --seat/--no-seat parse via hooks.ts parseSeatFlags, GBRAIN_SEAT in the hook env; -119 #6082: plugin-lane detectors moved to plugin-lanes.ts (re-exported); +18 #6092/#6171: hook ownership identity on write/remove/converge, permission ownership carry, --remove --dry-run and the --status hook census (logic in hooks.ts + harness-hooks.ts); +5 D8 Codex slice: the Codex SessionEnd capture hook obeys the recorded consent (wireCodexCapture: hooks on, capture accepted, never registrar mode) and is disclosed in the consent block; -31 #6743: cleanup gate moved to harness-cleanup.ts; +8 #6798: supersededEnrollments dep (interface field + default) and the --status epoch hint printed only for a superseded enrollment (the brain read lives in harness-skills.ts brainSupersededEnrollments); +13 brain-first block lane: --no-instructions flag field + parse, opencodeAgentsPath dep (field + default) and the step-10b / remove call sites (logic lives in harness-brain-first.ts); +7 GBRA-243 per-turn rule hook: consent-block interface field, step-10c call site, turn_hooks JSON field, exit code and the remove arm (writer, host list and consent text live in harness-brain-first.ts); +2 #8428: the harness lane Claude Code and Codex SessionEnd hooks start gbrain through the hook launcher; +16 GBRA-194 skills index lane: --skill-loading flag field + parse, step-10b and remove call sites, skills_index JSON field and exit-code wiring (logic lives in harness-skills-index.ts and setup/skills-block.ts)
src/core/oauth-provider.ts 1236 ratchet new row: crossed the 1500 unlisted cap absorbing #3819 (DCR 400 invalid_client_metadata + scope filtering + custom-scheme redirect_uris + pseudo-scheme guard); merged v0.49: transactional grant enforcement shared with hosted grant policies; +1 #5222 resourceUrl option
src/core/ops/pages.ts 732 ratchet crossed the unlisted 1500 cap in the fix wave: pack-vocabulary enforcement on capture (#4721) + get_page alias follow (#4275) landed together; next growth should peel a pages-ops submodule; +3: alias hop reads the canonical in the owning source (ship-review); +5: explicit source_id liveness check in get_page/list_pages (#4620); +3: #4857 total-order slug sort + list_pages source_id parse; +5: #4620 explicit removed-source id fails loudly; master integration: +4: authenticated delegated private-write boundary and auto-link suppression; #5105: canonical page mutations peeled into persistence modules; +2 v0.50.5.0 purge parameter and shared preflight call; preparation composes through the persistence modules; +7: source-qualified deep-research fetch authorization and ambiguity refusal (codec lives in deep-research-id.ts); +1 #5567: remote get_page keeps materialized markers; +1 #5622: trusted local capture file parameter; +5 #5709: get_page include_timeline_entries (rows via get_timeline's read policy); +8 GBRA-36 security wave: required outputRedaction policy on each pages op; +1 #5154: list_pages passes listColumnsOnly; +17 #5641: list_pages exposes the updated_after_slug keyset cursor and updated_at_iso; +8 agent operator wave A2: every op declares mutating + idempotent (tags only); +7 F3b (#5954): list_pages pagination meta + listing_truncated notice for MCP callers (logic in ops/list-pages-pagination.ts); +4 #5988: get_page file_held (one indexed hold lookup; logic in persistence/held-reads.ts); +6 #6103: list_pages maps an unreadable updated_after (SQLSTATE 22007/22008) to invalid_params; wave 10 collector: #6103 (+6) and #4807 (+2) compose; +1 wave 11 W4.3 (#5969 D3): put_page drop_timeline param; +1 wave 11 security review: purge_deleted_pages yes param + trusted-CLI guard (consent logic in persistence/purge-deleted.ts); +1 Q2 parser gaps: get_page grammar_diagnostics param (report logic in core/line-grammar-report.ts); master v0.60.136.0 merge into #5575 memory trust (both sides kept); +21 large pages (Wave A): get_page body-mode dispatch, fetch window branch, put_page large-page admission and allow_shrink param, description text (logic in ops/get-page-body.ts and persistence/large-page-guard.ts); +1 D8 funnel: committed put_page records a save when the opt-in funnel is on; +1 #6609: restore_page detach param (logic in persistence/detached-pages.ts); +1 Wave B gem A: post-batch auto-link reads a segmented page materialized (helpers in persistence/segmented-apply.ts); merge v0.60.249.0: composes at 707; +4 Wave B PR 2: get_page refuses a segmented page whole and fetch windows one (logic in ops/get-page-body.ts and page-window/segmented.ts); +2 Wave B PR 2 lane F: get_page and fetch pin segmented reads to the authorized snapshot (pin logic in ops/get-page-body.ts authorizedReadPin); +3 W2 page-at-time: get_page known_as_of param and dispatch (logic in ops/known-as-of.ts and belief/page-at-time.ts); GBRA-151 retrieval P0 x operability wave merge: both sides grew the file, re-summed (721 measured); GBRA-151 #7147 follow-up re-summed at the v0.60.334.0 merge (727 measured); +1 #7305: capture dry run applies the hyphen-run slug admission (logic in persistence/suffixed-slug.ts); +1 GST-687: get_page include_timeline_entries quotes rows for remote readers (import only; logic in ops/timeline-quote.ts); +2 #8384: the quoted_unverified_origin notice call in get_page and fetch (logic lives in get-page-projection.ts); +1 GBRA-218: put_page checks a remote readable_by before admission (logic in persistence/page-visibility.ts assertSubmittedReaders) (re-summed at the train M merge of master v0.60.539.0: 732 measured)
-src/core/search/mode.ts 1717 ratchet +53 W3 confidence-gated reranking: reranker_gate / reranker_gate_min_gap bundle fields, overrides, config parse and KNOB_CONFIG_KEY rows, knobsHash v=31 rrg=/rrgg=/ecf= parts (parse contracts in crag.ts); +10 System One v1: decide.* snapshot subset in loadSearchModeConfig, append-only dec= knobsHash part; +5 #3617 follow-up: v27 same-knobs behavioral-change note (relaxed-row fusion demotion rides the bump); new row: crossed the 1500 unlisted cap in the 2026-08 eval fix wave — KNOBS_HASH v=27 adaptive-return fold (ar/arem/arom/armk/ari parts + KnobsHashContext.adaptiveReturn field + contamination rationale comments) | merged v0.48.1.0 (+#4787) true-up; +master v0.48 merge true-up (reranker succession: no_key preflight, reranker_skipped stage, readiness); ranker wave v0.48.4.0: four knobs (expansion_variant_budget, relational_rerank_pin, keyword_arm_confidence_floor, metadata_boost_gate) + v29 hash parts + doc receipts (+218); #4781 loadSearchModeConfig reads the config table once via loadConfigSnapshot (+6); +4 #4359: update loadSearchModeConfig docstring — the cached path now reads config once (threaded snapshot), not twice; retired provider integration removed; +12 fw3-search: search.source_boosts + search.alias_token_hop read in the mode snapshot; +10 #5691: KnobsHashContext.queryPrefix and its append-only qp= part; P7 relational_planner / relational_orient_onehop knobs (interface docs, bundles, overrides, config parse, hash parts); +18 P7 relational_chain_slots knob (interface doc, bundles, override, config parse, rcs= hash part); +22 GBRA-60 S1 diverse_pool_depth knob (interface doc, bundles, overrides, pick, config parse, append-only dpd= hash part); +35 GBRA-154: collapse and rank_priors knobs (interface docs, bundles, overrides, pick, config parse, append-only col=/rpr= hash parts); GBRA-151 retrieval P0 x operability wave merge: both sides grew the file, re-summed (1704 measured); +5 GBRA-156 #7593: private-pages grant part in the cache key; +7 GBRA-218 A1: append-only xid=/xhp= knobsHash parts (member identity, operator privacy relaxation); +1 GBRA-231: append-only xau= knobsHash part (shared-agent audience identities) (re-summed at the train M .538 merge: 1717 measured)
+src/core/search/mode.ts 1718 ratchet +53 W3 confidence-gated reranking: reranker_gate / reranker_gate_min_gap bundle fields, overrides, config parse and KNOB_CONFIG_KEY rows, knobsHash v=31 rrg=/rrgg=/ecf= parts (parse contracts in crag.ts); +10 System One v1: decide.* snapshot subset in loadSearchModeConfig, append-only dec= knobsHash part; +5 #3617 follow-up: v27 same-knobs behavioral-change note (relaxed-row fusion demotion rides the bump); new row: crossed the 1500 unlisted cap in the 2026-08 eval fix wave — KNOBS_HASH v=27 adaptive-return fold (ar/arem/arom/armk/ari parts + KnobsHashContext.adaptiveReturn field + contamination rationale comments) | merged v0.48.1.0 (+#4787) true-up; +master v0.48 merge true-up (reranker succession: no_key preflight, reranker_skipped stage, readiness); ranker wave v0.48.4.0: four knobs (expansion_variant_budget, relational_rerank_pin, keyword_arm_confidence_floor, metadata_boost_gate) + v29 hash parts + doc receipts (+218); #4781 loadSearchModeConfig reads the config table once via loadConfigSnapshot (+6); +4 #4359: update loadSearchModeConfig docstring — the cached path now reads config once (threaded snapshot), not twice; retired provider integration removed; +12 fw3-search: search.source_boosts + search.alias_token_hop read in the mode snapshot; +10 #5691: KnobsHashContext.queryPrefix and its append-only qp= part; P7 relational_planner / relational_orient_onehop knobs (interface docs, bundles, overrides, config parse, hash parts); +18 P7 relational_chain_slots knob (interface doc, bundles, override, config parse, rcs= hash part); +22 GBRA-60 S1 diverse_pool_depth knob (interface doc, bundles, overrides, pick, config parse, append-only dpd= hash part); +35 GBRA-154: collapse and rank_priors knobs (interface docs, bundles, overrides, pick, config parse, append-only col=/rpr= hash parts); GBRA-151 retrieval P0 x operability wave merge: both sides grew the file, re-summed (1704 measured); +5 GBRA-156 #7593: private-pages grant part in the cache key; +7 GBRA-218 A1: append-only xid=/xhp= knobsHash parts (member identity, operator privacy relaxation); +1 GBRA-231: append-only xau= knobsHash part (shared-agent audience identities) (re-summed at the train M .538 merge: 1717 measured); +1 GBRA-283 B2: import of the embedded engine reranker model (engine-gateway.ts)
src/commands/eval-longmemeval.ts 1545 ratchet new row: crossed the 1500 unlisted cap in fw3-search (#5092 benchmark-brain recycling: configureBrain split + recycler wiring + test seams; the recycler itself lives in src/eval/longmemeval/harness.ts); +1 P6: tokenmax synopsis-tier wiring (logic in eval/longmemeval/synopsis-tier.ts); +13 GBRA-81 lane A: --via-operation query|search (flags, per-call expansion pin, the run's expectExpansion, the op branch in runOneQuestion, row field, via_operation_summary and its FAIL line; logic in eval/longmemeval/via-operation.ts); +12 --call-plan FILE / --call-plan-gate CMD: two LME_FLAGS entries (CLI help lines), two ParsedArgs fields, the parseArgs pairing check and the header invariant (planner lives in eval/longmemeval/call-plan.ts; runEvalLongMemEval is one line shorter); +1 #7619: parseArgs refuses a value on a switch (--judge=false turned the paid judge on)
src/commands/doctor/checks/extraction-sync.ts 1500 ratchet +7 GBRA-130 A-1: links_extraction_lag held bucket and its retry fix (logic in core/extraction-lag.ts heldExtractionReport); +1 undeclared_db_only_pages computes the source Git scope once per source (logic in core/markdown.ts sourceGitScope); new row: crossed the 1500 unlisted cap at the fix wave 9 merge: +7 lane W #5028 (extract_atoms freshness judged by the phase itself) and +3 lane F #5863 (extract_health dates a high halt rate by its last halt), each under the cap alone; +7 #5019: content_hash_duplicates fix pins the pairs' source (GBRAIN_SOURCE) and names a delete that runs; +1 fix wave 10 lane L1 #5556: links_extraction_lag denominator excludes quarantined pages (quarantineFilterFragment import); +11 fix wave 15 P2.8 (#5495): extract_health reads the 7-day halt reasons per kind (halt_reasons, top_halt_reason in details and the top reason in the warn line); the read, the unknown bucket and the ranking live in core/extract/rollup-writer.ts; +20 wave 18b lane 1: links_extraction_lag names the columns its pre-migration degrade reads (#6599 strict predicate), sync_freshness separates sync outcome from freshness for a source with no successful sync (#4960; verdict text, fixes and the attempt read live in doctor/sync-outcome.ts and core/sync-attempt.ts) and exempts read-only skill-pack catalogs (#6076; core/shared-skills/adopted-packs.ts); -51 #6803 (D1): links_extraction_lag reads its counts and verdict from core/extraction-lag.ts (shared with the sync nudge); +1 #7145: content_hash_duplicates reads one group past its list to report a floor ("at least 50")
src/core/search/evidence-delivery.ts 1759 ratchet +5 W5: EvidencePlan.rankCut resolved with the plan (logic in search/page-rank-cut.ts); +20 W5 whole_pages: wholeCost prices a block as delivery would emit it whole (needs the private Block/enrichBlock internals) and the cut is wired before allocate (cutWholePages lives in search/page-rank-cut.ts); new row: crossed the 1500 unlisted cap at the #6367 merge (master 1479, its explicit-budget cap) by the C1 date header threaded through every block path, cap included; pagePlanHits (search/page-plan-hits.ts) and the header loader (evidence-date.ts blockDateHeaders) were peeled first; peel candidate: allocateCapped; +8 at the #6396 merge: page evidence text cut through the fence-chunk trust overlay and the caller minTrust floor (re-summed: our 1504 + master +8); +119 Cat 40 next wave F2: the search.long_page_unit policy (withLongPagePolicy, selectLongPages size preflight with page/byte/deadline limits) and the long-page fetch and fallback in deliverEvidence, kept in the shared seam the plan names (gbrain-evals docs/plans/2026-10-11-cat40-next-wave, F2); +17 F2 rework to the frozen-comparison policy: search.long_page_min_chars (rendered-body characters, default 20,000) read in withLongPagePolicy, a character count in the preflight, the rendered-body confirmation in deliverEvidence, and the long-page row exemption in capDeliveredSnippets (re-summed at the 0.60.225.0 merge: master 1537 + F2 136); +39 Wave B PR 2 lane 2b: planSegmentedBlock joins the windows search/segmented-evidence.ts reads around a segmented page's hits into one run-marked document (needs the private Doc/Piece/buildDoc/locateAnchor internals), planBlock's unit cut split into blockFromDoc for both, sections bounded by their run, selectionCost counts a gap between runs, and the fetch skips the whole-body fence overlay for a segmented page; +4 segmented pages read at once before planning (segmentedReads; the read is search/segmented-evidence.ts, the statements page-body/read-range.ts); +17 GBRA-156: tail trim plan flag, DeliverOptions.query, DeliveryMeta.tail_trim, the trim call and the frozen-hit score/query library fields (logic in search/evidence-tail-trim.ts; interface fields cannot move); +7 GBRA-205: EvidencePlan.titleHeader and DeliveryMeta.title_header (interface fields cannot move) and the titles option on the header loader (logic in search/evidence-date.ts; the query budget key lives in search/evidence-packing.ts); +11 #7600: assemble_evidence quotes conversation rows and capEvidenceToBudget counts the quote fence (logic in search/transcript-quote.ts); +2 GBRA-156 /ship review: the cut-path admission and title room count the quote fence; +2 GBRA-156 /ship review pass 2: capEvidenceToBudget counts the fence only for the paths that fence (quote flag; recall counts the text as returned); +4 GST-687: page evidence and the extractive fallback quote below-owner-tier text for untrusted readers (untrusted flag; logic in search/transcript-quote.ts)
diff --git a/src/core/ai/engine-gateway.ts b/src/core/ai/engine-gateway.ts
index eb80ac951d..9e6f304cdf 100644
--- a/src/core/ai/engine-gateway.ts
+++ b/src/core/ai/engine-gateway.ts
@@ -88,6 +88,12 @@ export function scopedGatewayState(normalize: (config: AIGatewayConfig) => AIGat
return state;
}
+/** In an embedded engine's scope, its settings.ai.models.reranker; search uses it in place of the mode bundle's default. */
+export function engineRerankerModel(): string | undefined {
+ const engine = embeddedEngineInScope();
+ return engine ? embeddedSettingsRecord(engine)?.ai?.models?.reranker : undefined;
+}
+
/** The refusal for a call whose provider the engine was not given. Names the provider and touchpoint, never a key. */
export function engineScopeMissing(provider: string, touchpoint: string): Error {
return opError('engine_scope_missing', `This engine has no AI provider ${provider} for ${touchpoint}.`,
diff --git a/src/core/minions/handlers/subagent.ts b/src/core/minions/handlers/subagent.ts
index a01f705a1e..fab91778d1 100644
--- a/src/core/minions/handlers/subagent.ts
+++ b/src/core/minions/handlers/subagent.ts
@@ -52,6 +52,7 @@ import {
import { resolveModel, isAnthropicProvider, isOpenRouterSubagentFamily, TIER_DEFAULTS } from '../../model-config.ts';
import { splitProviderModelId, normalizeModelId } from '../../model-id.ts';
import { anthropicClientOptions } from '../../ai/anthropic-key.ts';
+import { withEngineScope } from '../../engine-scope.ts';
import { buildSystemPrompt, DEFAULT_SUBAGENT_SYSTEM } from '../system-prompt.ts';
import { toolLoop as gatewayToolLoop, isThinkingModel, THINKING_MODEL_MAX_OUTPUT_TOKENS } from '../../ai/gateway.ts';
import type { ChatToolDef, ChatMessage, ChatBlock, ChatResult, ToolHandler } from '../../ai/gateway.ts';
@@ -255,11 +256,11 @@ export function makeSubagentHandler(deps: SubagentDeps) {
// lives at sdk.messages.create. Assigning sdk.messages directly gets the
// right object; JS method-call semantics preserve `this` at the call
// site (subagent.ts invokes client.create(...) with client === sdk.messages).
- // Resolve the key env-first, then config (anthropic_api_key) — a bare
- // new Anthropic() only reads env, so launchd/MCP workers whose key lives
- // in the gbrain config file would fail auth (#2048).
- const makeAnthropic = deps.makeAnthropic ?? (() => new Anthropic(anthropicClientOptions()));
- const client: MessagesClient = deps.client ?? makeAnthropic().messages;
+ // #2048: the key resolves env, then config (anthropic_api_key); for an embedded engine, its own key and endpoint,
+ // in this handler's engine's scope (engine-scope.ts), when a job first calls the client.
+ const makeAnthropic = deps.makeAnthropic ?? (() => new Anthropic(withEngineScope(engine, anthropicClientOptions)));
+ let messages = deps.client;
+ const client: MessagesClient = { create: (params, opts) => (messages ??= makeAnthropic().messages).create(params, opts) };
const config = deps.config ?? loadConfig() ?? ({ engine: 'postgres' } as GBrainConfig);
const rateLeaseKey = deps.rateLeaseKey ?? DEFAULT_RATE_KEY;
const maxConcurrent = deps.maxConcurrent ?? DEFAULT_MAX_CONCURRENT;
diff --git a/src/core/search/mode.ts b/src/core/search/mode.ts
index 5020912219..d535bf7c7d 100644
--- a/src/core/search/mode.ts
+++ b/src/core/search/mode.ts
@@ -31,6 +31,7 @@ import { privateReadableSources, currentCallerAccess } from './private-visibilit
import { loadConfigSnapshot, type BulkConfigReader } from '../config-snapshot.ts';
import { pickDecideConfig } from '../ai/decide/config.ts';
import { getRecipe } from '../ai/recipes/index.ts';
+import { engineRerankerModel } from '../ai/engine-gateway.ts';
// #3657 seam: the runtime/mode-bundle reranker default has ONE code home
// (ai/defaults.ts — a leaf module, no SDK loads). The three bundles below
// resolve through DEFAULT_RERANKER_MODEL (voyage:rerank-3-lite, gbrain-evals #148).
@@ -879,7 +880,7 @@ export function resolveSearchMode(input: ResolveSearchModeInput): ResolvedSearch
return bundle[key];
};
- const resolvedRerankerModel = pick('reranker_model');
+ const resolvedRerankerModel = pc.reranker_model ?? ov.reranker_model ?? engineRerankerModel() ?? bundle.reranker_model;
const pickRerankerTimeoutMs = (): number => {
if (pc.reranker_timeout_ms !== undefined) return pc.reranker_timeout_ms;
if (ov.reranker_timeout_ms !== undefined) return ov.reranker_timeout_ms;
diff --git a/src/core/search/rerank.ts b/src/core/search/rerank.ts
index d1622e4b40..0d0ad69957 100644
--- a/src/core/search/rerank.ts
+++ b/src/core/search/rerank.ts
@@ -68,6 +68,8 @@ function hashQuery(query: string): string {
function classifyRerankFailure(err: unknown): RerankFailureReason {
if (err instanceof RerankError) return err.reason;
+ // An embedded engine given no provider for this reranker (engine-gateway.ts): nothing was sent, so a skip.
+ if ((err as { code?: unknown } | null)?.code === 'engine_scope_missing') return 'no_key';
if (
err instanceof BudgetExhausted ||
(err && typeof err === 'object' && (err as { tag?: unknown }).tag === 'BUDGET_EXHAUSTED')
diff --git a/test/engine-gateway.test.ts b/test/engine-gateway.test.ts
index 990d385e6d..ed82e1a3e4 100644
--- a/test/engine-gateway.test.ts
+++ b/test/engine-gateway.test.ts
@@ -15,6 +15,12 @@ import Anthropic from '@anthropic-ai/sdk';
import { anthropicClientOptions, resolveAnthropicKey } from '../src/core/ai/anthropic-key.ts';
import { embeddedEngineInScope } from '../src/core/engine-scope.ts';
import { PersistenceConsumer } from '../src/core/persistence/consumer.ts';
+import { makeSubagentHandler } from '../src/core/minions/handlers/subagent.ts';
+import { MinionQueue } from '../src/core/minions/queue.ts';
+import { applyReranker } from '../src/core/search/rerank.ts';
+import { resolveSearchMode } from '../src/core/search/mode.ts';
+import { DEFAULT_RERANKER_MODEL } from '../src/core/ai/defaults.ts';
+import type { MinionJobContext } from '../src/core/minions/types.ts';
import { startPersistenceConsumer, stopPersistenceConsumer } from '../src/core/persistence/service.ts';
import { embeddedSettings, openEngine, withEngineScope, type EngineSettings } from '../src/core/engine-open.ts';
import { createEngine } from '../src/core/engine-factory.ts';
@@ -235,6 +241,79 @@ describe('process base URLs never reach an engine', () => {
});
});
+describe('search reranking on an engine', () => {
+ test('search uses the engine\'s settings.ai.models.reranker unless the brain or the call names one', async () => {
+ const engine = await openEngine(settingsFor({ ai: { providers: { voyage: { apiKey: key('v') } }, models: { reranker: 'voyage:rerank-2.5' } } }));
+ try {
+ expect(withEngineScope(engine, () => resolveSearchMode({ mode: 'balanced' }).reranker_model)).toBe('voyage:rerank-2.5');
+ expect(withEngineScope(engine, () => resolveSearchMode({ mode: 'balanced', overrides: { reranker_model: 'voyage:rerank-3' } }).reranker_model)).toBe('voyage:rerank-3');
+ expect(withEngineScope(engine, () => resolveSearchMode({ mode: 'balanced', perCall: { reranker_model: 'voyage:rerank-3-lite' } }).reranker_model)).toBe('voyage:rerank-3-lite');
+ expect(resolveSearchMode({ mode: 'balanced' }).reranker_model).toBe(DEFAULT_RERANKER_MODEL);
+ } finally {
+ await engine.disconnect();
+ }
+ });
+
+ test('a reranker provider the engine was not given is a quiet no_key skip, not a provider failure', async () => {
+ installStubs();
+ const engine = await openEngine(settingsFor({ ai: { providers: { openai: { apiKey: key('a') } } } }));
+ try {
+ const results = [{ slug: 'a', chunk_text: 'alpha' }, { slug: 'b', chunk_text: 'beta' }] as never[];
+ const seen: string[] = [];
+ const out = await withEngineScope(engine, () => applyReranker('q', results, {
+ enabled: true, topNIn: 2, topNOut: 2, model: DEFAULT_RERANKER_MODEL, timeoutMs: 1000,
+ onSkip: (reason: string) => seen.push(`skip:${reason}`), onFailure: (reason: string) => seen.push(`failure:${reason}`),
+ } as never));
+ expect(out).toBe(results);
+ expect(seen).toEqual(['skip:no_key']);
+ expect(sent).toEqual([]);
+ } finally {
+ await engine.disconnect();
+ }
+ });
+});
+
+describe('the subagent handler\'s Anthropic client', () => {
+ const PROXY = 'https://process-proxy.invalid';
+ async function runJob(engine: BrainEngine) {
+ const handler = makeSubagentHandler({ engine, toolRegistry: [] });
+ const job = await new MinionQueue(engine).add('subagent', { prompt: 'hello' }, {}, { allowProtectedSubmit: true });
+ const ctx = {
+ id: job.id, name: job.name, data: { prompt: 'hello' }, attempts_made: 0, signal: new AbortController().signal, deadlineAtMs: null,
+ shutdownSignal: new AbortController().signal, async updateProgress() {}, async updateTokens() {}, async log() {}, async isActive() { return true; }, async readInbox() { return []; },
+ } as unknown as MinionJobContext;
+ return handler(ctx);
+ }
+
+ test('is built for the handler\'s engine, whatever scope built the handler, and only when a job calls it', async () => {
+ const calls: { url: string; key: string | null }[] = [];
+ const fetchSpy = spyOn(Anthropic.prototype as unknown as { fetchWithTimeout: (url: string, init: RequestInit) => Promise<Response> }, 'fetchWithTimeout').mockImplementation((async (url: string, init: RequestInit) => {
+ calls.push({ url, key: new Headers(init.headers as HeadersInit).get('x-api-key') });
+ return new Response(JSON.stringify({ id: 'msg_1', type: 'message', role: 'assistant', model: 'claude-sonnet-4-6', stop_reason: 'end_turn', stop_sequence: null,
+ content: [{ type: 'text', text: 'ok' }], usage: { input_tokens: 1, output_tokens: 1 } }), { status: 200, headers: { 'content-type': 'application/json' } });
+ }) as never);
+ try {
+ await withEnv({ ...ambient, ANTHROPIC_BASE_URL: PROXY }, async () => {
+ const keyA = key('a');
+ const named = await openEngine(settingsFor({ ai: { providers: { anthropic: { apiKey: keyA } } } }));
+ const without = await openEngine(settingsFor({ ai: { providers: { openai: { apiKey: keyA } } } }));
+ try {
+ await named.initSchema();
+ await without.initSchema();
+ expect((await runJob(named)).result).toBe('ok');
+ expect(calls).toEqual([{ url: 'https://api.anthropic.com/v1/messages', key: keyA }]);
+ expect((await failure(() => withEngineScope(named, () => runJob(without))))?.code).toBe('engine_scope_missing');
+ expect(calls).toHaveLength(1);
+ } finally {
+ await Promise.all([named.disconnect(), without.disconnect()]);
+ }
+ });
+ } finally {
+ fetchSpy.mockRestore();
+ }
+ }, 120_000);
+});
+
describe('the persistence consumer stays in its engine\'s scope', () => {
test('a wake from outside every scope still ticks for the consumer\'s engine', async () => {
const engine = await openEngine(settingsFor({ ai: { providers: { openai: { apiKey: key('a') } } } }));