Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
v0.60.116.0 feat(facts): default fact extraction to Claude Haiku 5.5 when no model is configured and the reasoning tier resolves through Anthropic
garrytan220406dd9481
diff --git a/docs/architecture/key-files/core-services-2.md b/docs/architecture/key-files/core-services-2.mdindex 9a905c5bf5..9b3e5d7e9d 100644--- a/docs/architecture/key-files/core-services-2.md+++ b/docs/architecture/key-files/core-services-2.md@@ -8,7 +8,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/facts/conversation-types.ts` — single-source conversation-type allowlist (`ALLOWED_TYPES`: conversation, meeting, slack, email, imessage, imessage-daily + `AllowedType`). It also owns the granular collector aliases (`ALLOWED_TYPE_ALIASES`, `pageTypesForAllowed`) and the one eligibility rule (#5330): `isConversationFactsEligiblePage` and its SQL twin `conversationFactsEligibleSql` admit an allowed concrete type unless frontmatter says `conversation_parseable: false`; with `cycle.conversation_facts_backfill.require_parseable_flag` on, only `type: conversation` or `conversation_parseable: true`. The extractor (slug, batch and enumeration paths), the doctor backlog SQL and its in-process verifier, and the format-coverage sample all use it, so the backlog can drain. Every consumer derives from this frozen leaf module — `extract-conversation-facts.ts` (which re-exports both names verbatim for its existing importers), the cycle backfill phase, `doctor.ts` + `doctor/checks/search-eval.ts`, `sources.ts`, `jobs.ts` — so no hand-copied list can drift. It lives under `src/core/facts/` (not `src/commands/`) because `scripts/generate-flag-registry.ts` scans option-shaped literals one relative-import level deep — importing the constant straight from `extract-conversation-facts.ts` would transitively attribute that command's whole option surface to doctor/jobs/sources in the generated CLI_ONLY registry. Drift-guarded by `test/conversation-facts-type-allowlist-drift.test.ts`. `isFrontmatterFlagOff` (the same off spellings) is shared with `facts/eligibility.ts`.- `src/core/facts/eligibility.ts` — `isFactsBackstopEligible`, the one automatic facts-extraction predicate (page-write outbox, its `body_unchanged` check, sync's post-import hook, the facts-absorb job's re-check). Skips `wiki/agents/`, `dream_generated: true`, `facts_backstop` set off (`opted_out`, #6232: a writer's opt-out for a page whose facts another page carries, such as a meeting's raw transcript; removing it re-offers the page even with an unchanged body), bodies under 80 characters, and types outside `ELIGIBLE_TYPES` unless the slug is under a rescue prefix. Receipt reasons are documented under `facts_backstop_skipped` in the error registry. Pinned by `test/facts-eligibility.test.ts`, `test/persistence-facts-backstop.test.ts`. #6259: a quarantined page (the gate's `quarantine` marker) is ineligible with reason `quarantined`, which the page-write receipt reports as `facts_backstop.skipped` (registered in `facts_backstop_skipped`).-- `src/core/facts/extract.ts` — the LLM facts extractor (`extractFactsFromTurnWithOutcome` and friends; the output cap, truncation retry, and salvage behavior are described under the trajectory entry). Deterministic junk gate: `isJunkFact(text, kind?)` tests `JUNK_FACT_PATTERNS` — assistant plan/offer narration, meta-narration about the conversation itself, provider billing/rate-limit strings captured verbatim — and is kind-aware: a candidate the extractor classified `commitment` is exempt from the plan-narration arm ONLY ("I'll send the deck by Friday" is a genuine commitment); meta-narration and provider-error strings are junk for every kind. `isJunkFilterEnabled(engine)` is the config kill switch (fail-open on a config read error); `getFactsExtractionPromptAppendix` supplies the config-driven prompt appendix. Entity gate at the candidate loop (the ONE seam where LLM-emitted entity tokens become `entity_slug`): `isUnknownSpeakerLabel` (anonymous diarizer labels — `Speaker A`, `SPEAKER_00`, `spk_0`, `other|unknown|guest`) and `isNullLikeEntity` (placeholder STRINGS `"null"`/`"None"`/`"n/a"` where the prompt asked for JSON null; shared with `write-single.ts`) both null the attribution and KEEP the fact, so no consumer can mint `entity_slug='null'` through the resolver's fallback slugify. The provider-error arm is start-anchored (`^\W*`, optional error/status token or a `<step> stopped|failed because …` prefix, then `(spend|rate) (limit|cap) … (hit|exceeded|reached)`), so a genuine fact that merely mentions a spend limit or rate limit mid-sentence survives; the verbatim provider strings still match. Two config keys: `facts.extraction_prompt_appendix` (non-empty text is appended to the extraction prompt) and `facts.extraction_junk_filter` (`false` disables the deterministic junk gate; default on), plus the opt-in `facts.extraction_missing_confidence` (stored when confidence is missing, null or non-numeric; unset keeps 1.0). A numeric-string confidence (`"0.3"`) is read as the stated value; unknown kinds are still stored as `fact` but counted in a stderr warning. Every extractor `chat()` call (first attempt, the #2113 truncation retry, the malformed-output retry) carries `responseSchema: FACTS_EXTRACTION_SCHEMA` (mirrors `RawExtracted`: `facts[]` of `{fact, kind ∈ ALL_EXTRACT_KINDS}` plus `entity/confidence/notability/metric/value/unit/period` — EVERY property in `required`, the optional ones nullable via type unions, `additionalProperties: false` at both levels, so the schema is OpenAI-strict-safe for proxies that honor the SDK's default `strict: true`); the gateway honors it only on openai-compatible recipes that declare structured outputs (Ollama's server-side grammar), so small local models cannot emit malformed JSON, while `parseExtractorJsonDetailed` still validates the reply text on every lane. Pinned by `test/facts-extract-structured-output.test.ts`.+- `src/core/facts/extract.ts` — the LLM facts extractor (`extractFactsFromTurnWithOutcome` and friends; the output cap, truncation retry, and salvage behavior are described under the trajectory entry). Model: `resolveFactsExtractionModel(engine)` returns the model and the setting that chose it (`facts.extraction_model`, then the `resolveModelDetailed` chain on the `reasoning` tier); when nothing chose one and the tier's key-aware default resolved through Anthropic, `FACTS_EXTRACTION_MEASURED_DEFAULTS` substitutes `anthropic:claude-haiku-5-5` (source `measured_default`; the facts-absorb quality gate, gbrain-evals `docs/benchmarks/2026-10-08-facts-extraction-model.md`), and `gbrain models` reports that row through the same resolver. `getFactsExtractionModel` is its string wrapper. Deterministic junk gate: `isJunkFact(text, kind?)` tests `JUNK_FACT_PATTERNS` — assistant plan/offer narration, meta-narration about the conversation itself, provider billing/rate-limit strings captured verbatim — and is kind-aware: a candidate the extractor classified `commitment` is exempt from the plan-narration arm ONLY ("I'll send the deck by Friday" is a genuine commitment); meta-narration and provider-error strings are junk for every kind. `isJunkFilterEnabled(engine)` is the config kill switch (fail-open on a config read error); `getFactsExtractionPromptAppendix` supplies the config-driven prompt appendix. Entity gate at the candidate loop (the ONE seam where LLM-emitted entity tokens become `entity_slug`): `isUnknownSpeakerLabel` (anonymous diarizer labels — `Speaker A`, `SPEAKER_00`, `spk_0`, `other|unknown|guest`) and `isNullLikeEntity` (placeholder STRINGS `"null"`/`"None"`/`"n/a"` where the prompt asked for JSON null; shared with `write-single.ts`) both null the attribution and KEEP the fact, so no consumer can mint `entity_slug='null'` through the resolver's fallback slugify. The provider-error arm is start-anchored (`^\W*`, optional error/status token or a `<step> stopped|failed because …` prefix, then `(spend|rate) (limit|cap) … (hit|exceeded|reached)`), so a genuine fact that merely mentions a spend limit or rate limit mid-sentence survives; the verbatim provider strings still match. Two config keys: `facts.extraction_prompt_appendix` (non-empty text is appended to the extraction prompt) and `facts.extraction_junk_filter` (`false` disables the deterministic junk gate; default on), plus the opt-in `facts.extraction_missing_confidence` (stored when confidence is missing, null or non-numeric; unset keeps 1.0). A numeric-string confidence (`"0.3"`) is read as the stated value; unknown kinds are still stored as `fact` but counted in a stderr warning. Every extractor `chat()` call (first attempt, the #2113 truncation retry, the malformed-output retry) carries `responseSchema: FACTS_EXTRACTION_SCHEMA` (mirrors `RawExtracted`: `facts[]` of `{fact, kind ∈ ALL_EXTRACT_KINDS}` plus `entity/confidence/notability/metric/value/unit/period` — EVERY property in `required`, the optional ones nullable via type unions, `additionalProperties: false` at both levels, so the schema is OpenAI-strict-safe for proxies that honor the SDK's default `strict: true`); the gateway honors it only on openai-compatible recipes that declare structured outputs (Ollama's server-side grammar), so small local models cannot emit malformed JSON, while `parseExtractorJsonDetailed` still validates the reply text on every lane. Pinned by `test/facts-extract-structured-output.test.ts`.- `src/core/facts/forget.ts` — `forgetFactInFence(engine, id, {reason?, sourceId?, worldOnly?, supersededBy?})` checks source and visibility before inspecting state, then commits a durable withdrawal through `facts/withdrawal.ts`. With `supersededBy: { rowNum }` (the `writeSingleFact` supersession path) it only expires the row and strikes it with a page-local `#N` supersession reference: no withdrawal, so the old claim stays rememberable and no other page is invalidated. A writable source fence is atomically struck with a date and reason; otherwise the DB-body mirror is best-effort. Both paths remain withdrawn on stale reimport while the withdrawal database is preserved. The file resolver and per-page lock match fence writes. The body-only mirror deliberately leaves a hash mismatch so the next import re-chunks. Forget is retraction, not deletion of original prose, files or backups. `strikeFenceRow` and `supersededFact` are exported for the S9 checked supersede (`facts/proposal-supersede.ts`). Pinned by `test/forget-reconcile-durability.test.ts`, `test/privacy-strip-and-forget.test.ts`, and `test/e2e/delegated-grants-withdrawal.test.ts`.diff --git a/docs/guides/facts-drain.md b/docs/guides/facts-drain.mdindex ead63299e4..a86ea448fa 100644--- a/docs/guides/facts-drain.md+++ b/docs/guides/facts-drain.md@@ -17,7 +17,11 @@ the brain:- the dream/autopilot cycle, as the `facts_drain` phase.No command is needed. This is **on by default**. Each extracted page is one-paid chat call to the configured facts model (`facts.extraction_model`).+paid chat call to the configured facts model (`facts.extraction_model`). Unset,+that is `anthropic:claude-haiku-5-5` when the reasoning tier resolves through+Anthropic, and the reasoning tier's default otherwise (`gbrain models` shows+which); `gbrain config set facts.extraction_model <provider:model>` picks+another.To turn it off:@@ -58,7 +62,7 @@ queued page count, the estimated spend, the caps and the opt-out command, onstderr and as a `facts_drain_first_run` notice on the next MCP call:```-[gbrain notice facts_drain] Automatic fact extraction is on: 12 queued page(s), about $0.21 with anthropic:claude-sonnet-4-6, at most $1.00 per run and $5.00 per day. To opt out: gbrain config set facts.extraction_enabled false+[gbrain notice facts_drain] Automatic fact extraction is on: 12 queued page(s), about $0.01 with anthropic:claude-haiku-5-5, at most $1.00 per run and $5.00 per day. To opt out: gbrain config set facts.extraction_enabled false```A model with no known price runs under the default caps with a warning. Oncediff --git a/src/commands/models.ts b/src/commands/models.tsindex 1ecb1b8279..46a00d748b 100644--- a/src/commands/models.ts+++ b/src/commands/models.ts@@ -44,6 +44,7 @@ import {} from '../core/model-config.ts';import { resolveExtractAtomsModelWithSource } from '../core/cycle/extract-atoms.ts';import { resolveFenceRepairModelWithSource } from '../core/fence-repair/model.ts';+import { resolveFactsExtractionModel } from '../core/facts/extract.ts';import {NIGHTLY_PROBE_EXTRACTOR_ROUTE,NIGHTLY_PROBE_READER_ROUTE,@@ -81,7 +82,7 @@ interface PerTaskModelRoute {* chain visible rather than implying full resolveModel() coverage — can* never disagree with the resolved value.*/- narrowResolver?: (engine: BrainEngine) => Promise<{ model: string; source: 'config' | 'tier_default' | 'measured' }>;+ narrowResolver?: (engine: BrainEngine) => Promise<{ model: string; source: 'config' | 'tier_default' | 'measured'; label?: string }>;}const PER_TASK_KEYS: PerTaskModelRoute[] = [@@ -110,7 +111,16 @@ const PER_TASK_KEYS: PerTaskModelRoute[] = [narrowResolver: async engine => { const r = await resolveFenceRepairModelWithSource(engine); return { model: r.model ?? 'none', source: r.source }; },},{ key: 'models.subagent', tier: 'subagent', description: '`gbrain agent run` subagent loop' },- { key: 'facts.extraction_model', tier: 'reasoning', description: 'Real-time facts extraction during sync' },+ {+ key: 'facts.extraction_model',+ tier: 'reasoning',+ description: 'Real-time facts extraction during sync; unset: claude-haiku-5-5 when the reasoning tier resolves through Anthropic',+ narrowResolver: async engine => {+ const r = await resolveFactsExtractionModel(engine);+ if (r.source === 'measured_default') return { model: r.model, source: 'measured' };+ return { model: r.model, source: r.source === 'config_key' ? 'config' : 'tier_default', label: sourceLabel(r.source, { configKey: 'facts.extraction_model', tier: 'reasoning' }, 'tier.reasoning') };+ },+ },{ key: 'models.eval.longmemeval', tier: 'reasoning', description: 'LongMemEval benchmark answer-gen' },{ key: 'models.eval.contradictions_judge', tier: 'utility', description: 'Contradiction probe judge (v0.34 temporal-aware)' },{ key: 'models.expansion', tier: 'utility', description: 'Query expansion for hybrid search' },@@ -229,8 +239,8 @@ async function buildReport(engine: BrainEngine): Promise<ModelsReport> {// ONE resolver call feeds both the resolved model and the attribution,// so the label can never disagree with what `resolved` actually// reflects (previously a separate getConfig truthiness re-check).- const { model: resolved, source: narrowSource } = await narrowResolver(engine);- const source = narrowSource === 'config' ? `config: ${key}` : narrowSource === 'measured' ? 'measured default' : `tier.${tier} (caller-specific)`;+ const { model: resolved, source: narrowSource, label } = await narrowResolver(engine);+ const source = label ?? (narrowSource === 'config' ? `config: ${key}` : narrowSource === 'measured' ? 'measured default' : `tier.${tier} (caller-specific)`);const newer = narrowSource === 'config' ? newerAvailable(resolved, key) : undefined;per_task.push({ key, tier, resolved, source, description, ...(newer ? { newer_available: newer } : {}) });continue;diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.tsindex 6ab9552823..daaa633708 100644--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@ -313,6 +313,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText }{ since: '0.60.108.0', text: 'A job error during worker shutdown now records `worker_shutdown: <handler error>` instead of bare `worker_shutdown`, and an `UnrecoverableError` thrown then dead-letters at once instead of running again.' },{ since: '0.60.108.0', text: '`gbrain jobs supervisor stop` can now report `unverified` (exit 1) and `stale_pid_file` (exit 0, nothing signaled), and on Linux the supervisor PID file has a second line with the process start time; read only its first line.' },{ since: '0.60.108.0', text: '`thinking: off` calls on native Google and OpenAI routes (eval judges, the synthesize triage judge, fence repair\'s model tier) now send the model\'s thinking switch (`thinkingBudget: 0`, `reasoningEffort: none`) and, where reasoning cannot be turned off (Gemini 2.5 Pro and 3.x, gpt-5/-mini/-nano, o-series), a 32,000-token reply cap; `eval takes-quality --budget-usd` and `eval cross-modal --max-usd` price that cap, so a budget that passed before can refuse earlier.' },+ { since: '0.60.110.0', text: 'Background fact extraction now uses claude-haiku-5-5 instead of claude-sonnet-4-6 when no model is set and the reasoning tier resolves through Anthropic (less than a tenth of the cost; it passed a facts-absorb quality gate against Sonnet 4.6, with 4.6 points fewer planted items covered on natural transcripts). `gbrain config set facts.extraction_model anthropic:claude-sonnet-4-6` keeps the previous model; installs that resolve through OpenAI, or set facts.extraction_model, models.tier.reasoning or models.default, are unchanged.' },];/** The newest disclosed change's release: the notice id moves only when a release adds rows. */diff --git a/src/core/facts/extract.ts b/src/core/facts/extract.tsindex c7f52e2fdd..4c533a1ac7 100644--- a/src/core/facts/extract.ts+++ b/src/core/facts/extract.ts@@ -27,8 +27,8 @@ import { classifyGlobalLlmError } from '../ai/errors.ts';import { stripReasoningBlocks } from '../llm-json.ts';import type { ChatResult } from '../ai/gateway.ts';import { INJECTION_PATTERNS } from '../think/sanitize.ts';-import { resolveModel } from '../model-config.ts';-import { normalizeModelId } from '../model-id.ts';+import { resolveModelDetailed, type ResolveSource } from '../model-config.ts';+import { normalizeModelId, splitProviderModelId } from '../model-id.ts';import type { BrainEngine, NewFact, FactKind, FactAttribution } from '../engine.ts';import { normalizeMetricLabel } from './extract-from-fence.ts';import { isNullLikeEntity } from './write-single.ts';@@ -53,15 +53,28 @@ export async function isFactsExtractionEnabled(engine: BrainEngine): Promise<boo}/**- * Get the configured model for facts extraction. Defaults to Sonnet since- * notability/salience judgment requires a sophisticated model, not Haiku.- * Configurable via `gbrain config set facts.extraction_model <model>`.+ * The measured default extraction model, by the provider the reasoning tier's+ * key-aware default resolved to. It applies only when nothing chose a model:+ * no `facts.extraction_model`, `models.tier.reasoning`, `models.default` or+ * `GBRAIN_MODEL`. Claude Haiku 5.5 passed the preregistered facts-absorb+ * quality gate against Sonnet 4.6 on 2026-10-08 (gbrain-evals+ * docs/benchmarks/2026-10-08-facts-extraction-model.md) at less than a tenth of+ * the cost; gpt-6-luna did not pass, so an install that resolves through+ * OpenAI keeps the tier default.*/-export async function getFactsExtractionModel(engine?: BrainEngine): Promise<string> {- // v0.31.12: route through resolveModel so models.default + models.tier.reasoning- // overrides reach facts extraction. Per-config-key facts.extraction_model still- // wins via configKey, preserving the prior behavior for existing users.- const resolved = await resolveModel(engine ?? null, {+export const FACTS_EXTRACTION_MEASURED_DEFAULTS: Readonly<Record<string, string>> = {+ anthropic: 'anthropic:claude-haiku-5-5',+};++export type FactsExtractionModelSource = ResolveSource | 'measured_default';++/**+ * The model facts extraction uses and which setting chose it. Configurable via+ * `gbrain config set facts.extraction_model <model>`; `models.tier.reasoning`,+ * `models.default` and `GBRAIN_MODEL` reach it through resolveModel (v0.31.12).+ */+export async function resolveFactsExtractionModel(engine?: BrainEngine): Promise<{ model: string; source: FactsExtractionModelSource }> {+ const resolved = await resolveModelDetailed(engine ?? null, {configKey: 'facts.extraction_model',tier: 'reasoning',fallback: 'anthropic:claude-sonnet-4-6',@@ -69,7 +82,16 @@ export async function getFactsExtractionModel(engine?: BrainEngine): Promise<str// resolveModel returns bare model ids when resolving via tier defaults; ensure// the result keeps a provider prefix so gateway.chat() can route it (and slash// form normalizes to colon — #1698).- return normalizeModelId(resolved);+ const model = normalizeModelId(resolved.model);+ if (resolved.source === 'tier_default' || resolved.source === 'fallback') {+ const measured = FACTS_EXTRACTION_MEASURED_DEFAULTS[splitProviderModelId(model).provider ?? ''];+ if (measured) return { model: measured, source: 'measured_default' };+ }+ return { model, source: resolved.source };+}++export async function getFactsExtractionModel(engine?: BrainEngine): Promise<string> {+ return (await resolveFactsExtractionModel(engine)).model;}/**diff --git a/src/core/model-pricing.ts b/src/core/model-pricing.tsindex 005d7fda88..3285aaacc6 100644--- a/src/core/model-pricing.ts+++ b/src/core/model-pricing.ts@@ -117,6 +117,11 @@ export const CANONICAL_PRICING: Record<string, ModelPricing> = {'anthropic:claude-sonnet-5-5': anthro( 2.00, 10.00),'anthropic:claude-sonnet-5': anthro( 2.00, 10.00),'anthropic:claude-sonnet-4-6': anthro( 3.00, 15.00),+ // Haiku 5.5: $0.10 in / $0.50 out for prompts up to 100,000 tokens+ // (platform.claude.com/docs/en/about-claude/pricing, checked 2026-10-08).+ // Longer prompts bill 5x ($0.50 / $2.50); that tier is not modeled. The+ // default facts extraction model on Anthropic-keyed installs.+ 'anthropic:claude-haiku-5-5': anthro( 0.10, 0.50),// Haiku 4.5 — both the dateless canonical id and the dated snapshot.'anthropic:claude-haiku-4-5': anthro( 1.00, 5.00),'anthropic:claude-haiku-4-5-20251001': anthro( 1.00, 5.00),diff --git a/src/eval/longmemeval/retrieval-arms.ts b/src/eval/longmemeval/retrieval-arms.tsindex 551e0618f4..3b5cd94626 100644--- a/src/eval/longmemeval/retrieval-arms.ts+++ b/src/eval/longmemeval/retrieval-arms.ts@@ -36,6 +36,7 @@ import { applyTimeScope, type TimeScopeMode } from '../../core/search/hybrid/timimport { extractEventDates } from '../../core/event-dates.ts';import type { DayRange } from '../../core/temporal-grammar.ts';import { resolveModel } from '../../core/model-config.ts';+import { getFactsExtractionModel } from '../../core/facts/extract.ts';import { rawSessionId, scoreRecall, type SlugToRawMap } from './metrics.ts';export type FactExtractor = 'paper' | 'production';@@ -290,7 +291,7 @@ export function armPins(o: RetrievalArmOptions): { retrieval_arms?: Record<strinexport async function resolveFactKeyArm(o: RetrievalArmOptions, client: ThinkLLMClient): Promise<{ arm: FactKeyArm; spend: FactKeySpend } | null> {if (!o.factKeys) return null;const model = o.factExtractor === 'production' && !o.factKeysModel- ? await resolveModel(null, { configKey: 'facts.extraction_model', tier: 'reasoning', fallback: 'anthropic:claude-sonnet-4-6' })+ ? await getFactsExtractionModel(): await resolveModel(null, { cliFlag: o.factKeysModel, tier: 'utility', fallback: 'haiku' });return { arm: { assignment: o.factKeys, extractor: o.factExtractor, model, client, maxUsd: o.factKeysMaxUsd }, spend: new FactKeySpend(o.factKeysMaxUsd) };}diff --git a/test/facts-extraction-model-default.test.ts b/test/facts-extraction-model-default.test.tsnew file mode 100644index 0000000000..e83150eac4--- /dev/null+++ b/test/facts-extraction-model-default.test.ts@@ -0,0 +1,56 @@+/**+ * The facts extraction default (R2 of the 10x plan, facts-absorb quality gate+ * 2026-10-08): with nothing set, an install whose reasoning tier resolves+ * through Anthropic extracts with claude-haiku-5-5; every explicit setting+ * still wins, and an install that resolves through OpenAI keeps the tier+ * default.+ */+import { describe, expect, test } from 'bun:test';+import { FACTS_EXTRACTION_MEASURED_DEFAULTS, getFactsExtractionModel, resolveFactsExtractionModel } from '../src/core/facts/extract.ts';+import { resolveTierDefault } from '../src/core/model-config.ts';+import { canonicalLookup } from '../src/core/model-pricing.ts';+import { withEnv } from './helpers/with-env.ts';++const engine = (cfg: Record<string, string> = {}) => ({ getConfig: async (k: string) => cfg[k] ?? null }) as never;+const HOME = { GBRAIN_HOME: '/nonexistent-gbrain-home-for-facts-default-tests', GBRAIN_MODEL: undefined };++describe('facts extraction default model', () => {+ test('Anthropic-keyed install with nothing set extracts with claude-haiku-5-5', async () => {+ await withEnv({ ...HOME, ANTHROPIC_API_KEY: 'sk-ant-test', OPENAI_API_KEY: undefined }, async () => {+ expect(await resolveFactsExtractionModel(engine())).toEqual({ model: 'anthropic:claude-haiku-5-5', source: 'measured_default' });+ expect(await getFactsExtractionModel(engine())).toBe('anthropic:claude-haiku-5-5');+ expect(await getFactsExtractionModel()).toBe('anthropic:claude-haiku-5-5');+ });+ });++ test('both keys: the Anthropic tier default wins the key walk, so Haiku 5.5 applies', async () => {+ await withEnv({ ...HOME, ANTHROPIC_API_KEY: 'sk-ant-test', OPENAI_API_KEY: 'sk-test' }, async () => {+ expect(await getFactsExtractionModel(engine())).toBe('anthropic:claude-haiku-5-5');+ });+ });++ test('OpenAI-only install keeps the reasoning tier default', async () => {+ await withEnv({ ...HOME, ANTHROPIC_API_KEY: undefined, OPENAI_API_KEY: 'sk-test' }, async () => {+ const r = await resolveFactsExtractionModel(engine());+ expect(r.source).toBe('tier_default');+ expect(r.model).toBe(resolveTierDefault('reasoning'));+ expect(r.model.startsWith('openai:')).toBe(true);+ });+ });++ test('explicit settings win over the measured default', async () => {+ await withEnv({ ...HOME, ANTHROPIC_API_KEY: 'sk-ant-test', OPENAI_API_KEY: undefined }, async () => {+ expect(await resolveFactsExtractionModel(engine({ 'facts.extraction_model': 'anthropic:claude-sonnet-4-6' })))+ .toEqual({ model: 'anthropic:claude-sonnet-4-6', source: 'config_key' });+ expect(await getFactsExtractionModel(engine({ 'models.tier.reasoning': 'anthropic:claude-sonnet-5-5' }))).toBe('anthropic:claude-sonnet-5-5');+ expect(await getFactsExtractionModel(engine({ 'models.default': 'openai:gpt-6-luna' }))).toBe('openai:gpt-6-luna');+ });+ await withEnv({ ...HOME, ANTHROPIC_API_KEY: 'sk-ant-test', GBRAIN_MODEL: 'anthropic:claude-opus-5-5' }, async () => {+ expect(await getFactsExtractionModel(engine())).toBe('anthropic:claude-opus-5-5');+ });+ });++ test('the default is priced, so extraction budget caps keep working', () => {+ for (const model of Object.values(FACTS_EXTRACTION_MEASURED_DEFAULTS)) expect(canonicalLookup(model)).toMatchObject({ input: 0.1, output: 0.5 });+ });+});diff --git a/test/models-per-task-facts-extraction.serial.test.ts b/test/models-per-task-facts-extraction.serial.test.tsnew file mode 100644index 0000000000..322ccb3386--- /dev/null+++ b/test/models-per-task-facts-extraction.serial.test.ts@@ -0,0 +1,53 @@+/**+ * `gbrain models` reports the facts extraction route through the same+ * resolver extraction uses (resolveFactsExtractionModel), so the measured+ * Haiku 5.5 default shows as `measured default` and every explicit setting+ * keeps its own label. Same StubConfigEngine + runModels(['--json']) pattern+ * as test/models-per-task-extract-atoms.serial.test.ts.+ */+import { describe, test, expect } from 'bun:test';+import { runModels } from '../src/commands/models.ts';+import { withEnv } from './helpers/with-env.ts';++class StubConfigEngine {+ private readonly config = new Map<string, string>();+ set(key: string, value: string): void { this.config.set(key, value); }+ async getConfig(key: string): Promise<string | null> { return this.config.get(key) ?? null; }+ async getPage(): Promise<{ source_id: string }> { return { source_id: 'default' }; }+}++async function factsRow(engine: StubConfigEngine) {+ let stdout = '';+ const originalWrite = process.stdout.write;+ process.stdout.write = ((chunk: string | Uint8Array) => {+ stdout += typeof chunk === 'string' ? chunk : Buffer.from(chunk).toString();+ return true;+ }) as typeof process.stdout.write;+ try {+ await runModels(engine as never, ['--json']);+ } finally {+ process.stdout.write = originalWrite;+ }+ return (JSON.parse(stdout) as { per_task: Array<{ key: string; resolved: string; source: string }> }).per_task.find(r => r.key === 'facts.extraction_model')!;+}++const ENV = { GBRAIN_HOME: '/nonexistent-gbrain-home-for-models-facts-tests', GBRAIN_MODEL: undefined, ANTHROPIC_API_KEY: 'sk-ant-test', OPENAI_API_KEY: undefined };++describe('gbrain models: facts.extraction_model route', () => {+ test('unset on an Anthropic-keyed install: claude-haiku-5-5, measured default', async () => {+ await withEnv(ENV, async () => {+ expect(await factsRow(new StubConfigEngine())).toMatchObject({ resolved: 'anthropic:claude-haiku-5-5', source: 'measured default' });+ });+ });++ test('explicit settings keep their labels', async () => {+ await withEnv(ENV, async () => {+ const own = new StubConfigEngine();+ own.set('facts.extraction_model', 'anthropic:claude-sonnet-4-6');+ expect(await factsRow(own)).toMatchObject({ resolved: 'anthropic:claude-sonnet-4-6', source: 'config: facts.extraction_model' });+ const tier = new StubConfigEngine();+ tier.set('models.tier.reasoning', 'anthropic:claude-sonnet-5-5');+ expect(await factsRow(tier)).toMatchObject({ resolved: 'anthropic:claude-sonnet-5-5', source: 'config: models.tier.reasoning' });+ });+ });+});