Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(usage): log query-expansion calls and give think rows a phase (#7176)
garrytan3dc9a24e59f5
diff --git a/docs/architecture/key-files/core-ai.md b/docs/architecture/key-files/core-ai.mdindex 44c6eceefa..06ef812970 100644--- a/docs/architecture/key-files/core-ai.md+++ b/docs/architecture/key-files/core-ai.md@@ -7,7 +7,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/ai/call-log.ts` + the observer half of `src/core/ai/invocation-guard.ts` — invocation observers and attribution. `observeAIInvocations(observer)` registers a process-level observer that `invokeAI` notifies once per call (guarded or not) with `{ call, outcome: ok | error | refused, usage, startedAt, ms, attribution }`; the unguarded branch of `guarded-generation.ts` routes through `invokeAI` only while an observer is installed and passes the caller's transport options unchanged, so observation never alters retries, token defaults or admission (pinned by `test/ai-invocation-observer.test.ts`). Observer throws are swallowed and counted (`aiInvocationObserverFailures`); adding the same function twice is a no-op. `withAIAttribution({ request_id, effect, job_id, job_name, phase }, fn)` merges into an async-local attribution read by observers: the persistence effect dispatcher (`effects.ts`), the in-process facts queue (`facts/queue.ts`, captured per entry at enqueue), the `facts-absorb` job handler (internal write-request id from `persistence_request_id`) and `timeContainedPhase` (`cycle:<phase>`) set it. `installAICallLogFromEnv` (called by `configureGateway`, idempotent per path) appends one JSON line per call to `GBRAIN_AI_CALL_LOG` (kind with multimodal counted as embedding, operation, model, outcome, ms, input/output/cache tokens or `unknown`, attribution; never prompt or response text; one warning on write failure). Pinned by `test/ai-call-log.test.ts`.-- `src/core/ai/chat-usage.ts` + `src/core/ops/usage.ts` — durable per-call chat usage accounting. `gateway.chat()` calls `recordChatUsage` at its SUCCESS boundary (production provider path AND test-transport path) with the answering model + token usage; the record lands in the `chat_usage_log` table (migration v140) via an injected sink (`setChatUsageSink` — no engine import here, so the gateway imports this leaf statically without deepening a cycle). Phase attribution is best-effort via AsyncLocalStorage (`withChatPhase`): the minion worker AND the cycle's inline drain (`inline-drain.ts`) both wrap handler execution in `job:<name>`, a cycle phase that meters its own spend wraps itself in `phase:<name>` (dream synthesize does), and direct callers record phase NULL. The innermost wrap wins, which is the point — a child drained INSIDE a wrapped phase must carry its own `job:` tag or the phase tag absorbs every child's spend and the ledger double-counts (one ledger per surface: `minion_jobs` stays the child-spend authority, the phase row is the orchestrator's own calls). Pricing resolves through `CANONICAL_PRICING` (`estimateChatCostUsd`, cache_read/cache_write at provider cache rates when the table carries them); unknown models record `cost_usd = NULL`, never a fake 0. Accounting is strictly fail-open + fire-and-forget: a sink error must never break a chat call. `withChatCallMeter` counts successful calls on a `ChatCallMeter` (phase containment's `{ calls }`); a meter that declares `cost_usd` (the nightly probe's) also prices each call with the budget tracker's resolver (`priceFor` with the meter's `pricing_overrides`; a table row uses the same cache-aware `estimateChatCostUsd` value the record carries), counts an unpriced call in `unpriced_calls` instead of as 0, and is priced even when no sink is registered. The `get_usage` op (admin scope, NOT read — `chat_usage_log` has no source dimension, so a source-restricted/federated token must not see brain-wide spend telemetry) returns per-model/per-phase aggregates only, plus an explicit `coverage` block stating what the ledger does NOT capture (subagent raw-SDK path, embeddings, pre-sink/pre-v140 calls, failed calls); `budget-tracker.ts` remains the pessimistic in-flight spend gate — this table is the after-the-fact ledger.+- `src/core/ai/chat-usage.ts` + `src/core/ops/usage.ts` — durable per-call chat usage accounting. `gateway.chat()` calls `recordChatUsage` at its SUCCESS boundary (production provider path AND test-transport path) with the answering model + token usage, and `gateway.expand()` does too on each successful expansion call with phase `expansion`, which wins over an ambient phase (#7176); think's synthesis call runs under `withDefaultChatPhase('think')`, so it records `think` unless a job or cycle phase already attributes it; the record lands in the `chat_usage_log` table (migration v140) via an injected sink (`setChatUsageSink` — no engine import here, so the gateway imports this leaf statically without deepening a cycle). Phase attribution is best-effort via AsyncLocalStorage (`withChatPhase`): the minion worker AND the cycle's inline drain (`inline-drain.ts`) both wrap handler execution in `job:<name>`, a cycle phase that meters its own spend wraps itself in `phase:<name>` (dream synthesize does), and direct callers record phase NULL. The innermost wrap wins, which is the point — a child drained INSIDE a wrapped phase must carry its own `job:` tag or the phase tag absorbs every child's spend and the ledger double-counts (one ledger per surface: `minion_jobs` stays the child-spend authority, the phase row is the orchestrator's own calls). Pricing resolves through `CANONICAL_PRICING` (`estimateChatCostUsd`, cache_read/cache_write at provider cache rates when the table carries them); unknown models record `cost_usd = NULL`, never a fake 0. Accounting is strictly fail-open + fire-and-forget: a sink error must never break a chat call. `withChatCallMeter` counts successful calls on a `ChatCallMeter` (phase containment's `{ calls }`); a meter that declares `cost_usd` (the nightly probe's) also prices each call with the budget tracker's resolver (`priceFor` with the meter's `pricing_overrides`; a table row uses the same cache-aware `estimateChatCostUsd` value the record carries), counts an unpriced call in `unpriced_calls` instead of as 0, and is priced even when no sink is registered. The `get_usage` op (admin scope, NOT read — `chat_usage_log` has no source dimension, so a source-restricted/federated token must not see brain-wide spend telemetry) returns per-model/per-phase aggregates only, plus an explicit `coverage` block stating what the ledger does NOT capture (subagent raw-SDK path, embeddings, pre-sink/pre-v140 calls, failed calls); `budget-tracker.ts` remains the pessimistic in-flight spend gate — this table is the after-the-fact ledger.- `src/core/ai/date-grounding.ts` — the time vocabulary every extraction prompt shares: observation time (when text was written or said), event/validity time (`facts.valid_from`), recording time (`created_at`). `resolveObservationDate` (filename / `date` / `published` / created keys via `computeEffectiveDate`; never `event_date`, row timestamps or now), `observationDateFrom` (turn/message timestamps), `observationDateRule` (static system-prompt rule: rewrite relative dates as absolute dates or bounds resolved against the observation date, never leaving the phrase beside its date; unknown → keep as written), `observationDateLine` (user-message date or `unknown`), `parseExtractedEventDate` (YYYY-MM-DD, 1900..now+1y), `resolveValidFrom` (extracted > caller > observation > now), `hasUnresolvedRelativeDate` (judge-free eval check). Fact extraction, dream synthesis, extract_atoms and propose_takes add the rule by default (`extraction.date_grounding` unset or true; `false` turns all off; held-out verdict and per-consumer checks in `docs/eval/decisions/p2-e2-heldout/`); the life chronicle judge adds it only when the setting is explicitly `true` (`isConsumerDateGroundingOn(engine, consumer)`). Page-body facts default to the page's observation date regardless. Pinned by `test/ai/date-grounding.test.ts`, `test/facts/extract-date-grounding.test.ts`, `test/facts/backstop-page-date.test.ts`.- `src/core/ai/defaults.ts` — leaf module for canonical embedding and reranker defaults, without a gateway import. Voyage `voyage:voyage-4` at 1024 dimensions is the new-install embedding default; `voyage:rerank-3-lite` is the runtime/mode-bundle reranker default (it applies only to brains with no `search.reranker.model` row). `renderCanonicalMigrationCommands` supplies an explicit-target cost preview and an OpenAI keep-width alternative where supported. These constants do not establish the identity of vectors in an existing database and must never authorize automatic provider conversion. Init preserves explicit choices, writes no reranker row when the Voyage key is available, disables reranking for keyed installs without that key, and preserves keyless setup.diff --git a/docs/architecture/key-files/core-search-2.md b/docs/architecture/key-files/core-search-2.mdindex 79c9813f10..578e3992f5 100644--- a/docs/architecture/key-files/core-search-2.md+++ b/docs/architecture/key-files/core-search-2.md@@ -35,7 +35,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/search/frontmatter-where.ts` + `src/core/ops/where-param.ts` — the `where` frontmatter equality filter on `search`, `query` and `list_pages` (#7159; CLI `--where key=value`, repeat for AND, `key=a,b` for any-of, parsed in `cli/op-param-values.ts`). `parseFrontmatterWhere` caps keys (8, `[A-Za-z_][A-Za-z0-9_-]{0,63}`), values (32 per key, 256 chars) and rejects nested values as `invalid_params`. Each value becomes OR'd `p.frontmatter @> $n::text::jsonb` containments (scalar, one-element list, and the number/boolean a string spells), keys ANDed, so the GIN index `idx_pages_frontmatter` serves it; keys and values travel only inside bound JSON. The clause is pushed into every SQL leg (keyword, title, vector, CJK, `listPages`), a filtered call skips the hybrid cache, and `keepFrontmatterMatches` re-checks the finished rows for arms outside those legs (exact lookup, alias fan-out, facts). Visibility, source and private filters are unchanged. Tests: `test/search-frontmatter-where.test.ts`, `test/e2e/search-frontmatter-where-parity.test.ts`.- `src/core/search/filter-hint.ts` — the one `search_filter_hint` info notice (deduped per session) a first-page `search`/`query` gets when it looks like it wanted a filter: the query names a page type the caller can see and under 80% of the top rows are that type (`types`), names a time (`since`/`until`; `search` points at `query`), or 90% of at least 8 top rows are one type it did not name. Never changes results, never throws. Test: `test/search-frontmatter-where.test.ts`.-- `src/core/search/search-cost.ts` — per-request model-call cost (`_meta.retrieval.cost`, #7158). `withSearchCost` wraps the `search`/`query` handlers (`metered` in ops/search.ts) and observes every `invokeAI` inside the request through `withAIInvocationMeter` (AsyncLocalStorage, so concurrent requests stay apart; `hasAIInvocationObservers` is true under a meter so unguarded SDK calls are seen too). Refused calls are not counted; USD from `usageCostUsd`. Test: `test/search-cost.serial.test.ts`.+- `src/core/search/search-cost.ts` — per-request model-call cost (`_meta.retrieval.cost`, #7158). `withSearchCost` wraps the `search`/`query` handlers (`metered` in ops/search.ts) and observes every `invokeAI` inside the request through `withAIInvocationMeter` (AsyncLocalStorage, so concurrent requests stay apart; `hasAIInvocationObservers` is true under a meter so unguarded SDK calls are seen too). Refused calls are not counted; USD from `usageCostUsd`; `gateway.expand` invocations get their own `expansion` line. Test: `test/search-cost.serial.test.ts`.- `src/core/search/stage-timings.ts` — per-request search stage timings. The `search`/`query` handlers create one `SearchTimings` and thread it into every hybrid call of the request (`HybridSearchOpts._timings`, `HybridRequest.timer`; absent = `UNTIMED`, a pass-through). `stage(name, work)` books critical-path blocked wall-clock time: one current stage at a time, a nested stage takes the clock and hands it back, so a fan-out or escalation hybrid call is booked once under its own stages, and retries accumulate. `overlap(label, promise)` times concurrent work (the keyword and title arms) into `overlapped_ms` without adding it to a stage. `branch()` returns a timer for stages run alongside the critical path (hybrid's vector side: modality, expansion, embed, vector arms); until `join(branch, promise)` its stage time goes to `overlapped_ms` under the stage name, and from the join the wait is booked to the branch's current stage (the stage key appears in `stages_ms` even at 0). `snapshot()` reads `total_ms` from its own monotonic start, apportions integer `stages_ms` + `other_ms` to sum to it exactly (`other_ms >= 0`); `searchOutput` takes it after the returned rows are assembled and emits it as `_meta.retrieval.timings` (never in content blocks); `formatTimingsSummary` is the `--explain` line. Stages: setup, lexical, relational, expansion, embed, vector, fuse, post_fusion, rerank, alias_fanout, anchoring, facts_arm, response. The gate (every bench query: `0 <= total - sum(stages) <= 10%`) is the `timings` phase of `scripts/bench-refactor-wave-1.ts`. Pinned by `test/search/stage-timings.test.ts` and `test/search/stage-timings-ops.test.ts`.- `src/core/search/sql-ranking.ts` — Pure SQL string builders. `buildSourceFactorCase(slugColumn, boostMap, detail)` emits a CASE with longest-prefix-match wins (returns literal `'1.0'` when `detail === 'high'` for temporal-bypass parity with COMPILED_TRUTH_BOOST). `buildHardExcludeClause(slugColumn, prefixes)` emits `NOT (col LIKE 'p1%' OR col LIKE 'p2%')` — OR-chain wrapped in NOT, NOT `NOT LIKE ALL/ANY` (those quantifiers don't express set-exclusion). LIKE meta-character escape covers all three of `%`, `_`, AND `\` (backslash is Postgres LIKE's default escape char). Single-quote doubling on SQL string literals so injection-style inputs are inert text. `buildBestPerPagePoolCte(...)` is the shared per-page max-pool CTE both engines' `searchVector` inject — instead of returning the single best chunk per page from an inner `ORDER BY embedding <=> vec LIMIT N` (which lets a page lose to a neighbor on ONE weak chunk while its strong chunk sits just below the inner cut), the CTE pools the BEST chunk score per `(source_id, slug)` composite key so a page surfaces on its strongest evidence; composite key (not bare slug) keeps multi-source brains correct; single source of truth so the two engines can't drift.diff --git a/docs/guides/search-explain.md b/docs/guides/search-explain.mdindex 8d83e89711..66c5e7e0f2 100644--- a/docs/guides/search-explain.md+++ b/docs/guides/search-explain.md@@ -80,7 +80,8 @@ phase that did not run is absent; `0` means it took under half amillisecond. On a thin client `op` and `stages` are the server's.`cost` (also `_meta.retrieval.cost` over MCP) counts every model call the-request made, by kind (`embedding`, `rerank`, `chat`, `decide`), each with+request made, by kind (`embedding`, `rerank`, `expansion`, `chat`, `decide`;+`expansion` is the same call `chat_usage_log` records with phase `expansion`), each with`calls`, `input_tokens`, `output_tokens` and `usd`, plus `calls` and`estimated_usd` in total. Tokens are what the provider reported; a call itreported none for counts its request estimate and is tallied indiff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsvindex 04e3186049..ec5788fd28 100644--- a/scripts/module-size-limits.tsv+++ b/scripts/module-size-limits.tsv@@ -11,7 +11,7 @@ src/commands/extract-conversation-facts.ts 2044 ratchet grown v0.46.x per-providsrc/commands/extract.ts 2677 ratchet +8 GBRA-130 A-1: extract --stale --retry-held flag, help lines and the managed result failure fields (logic in core/persistence/links-maintenance.ts and links-extraction-holds.ts); grown v0.46.26.0 megawave: FS-walk stamp snapshot + legacy timeline repair wiring (#3957 D4) + PR#4486 rebase onto current master; grown wave-g (#4542): --from-meetings zero-match warning + default-pass note; +29: #3478 federated-only gate on the cross-source 'default' link fallback; +44: #3908 cross_source opt-in — counted drops + deterministic cross-source pick; +36: #4611 configured-sources.default fallback (resolveLinkFallbackDefault); +14: #4890 extractStaleFromDB quiet opt + extractForSlugs jsonMode batch_error stderr fallback; +5: #4855 stroke-letter fold in link extraction; +5: #4793 by-mention scan honours link_resolution.cross_source; +18: wave review — ExtractOpts.quiet threaded through the fs-walk extractors (stdout silence decoupled from jsonMode); +77: shared buildSlugPathIndex — every per-slug extractor resolves the real on-disk path, and the sync hooks report which slugs they actually read; +10 #4999: includeFrontmatter default-resolved inside extractLinksForSlugs + extractStaleFromDB (resolveIncludeFrontmatter), --stale flag absent -> configured knob; +20: pre-landing review of #4967 — resolveSlugRelPath: index miss falls back to the legacy slug+'.md' path so admitted _-prefixed / include_hidden pages keep their edges; T2: source-qualified inference and atomic origin-scoped derived links; standard DB extraction fences captured endpoint revisions; shared authoritative attendance/source reconciliation moved to the core module; +7 A2 preview-bound attendance repair import, help and authority dispatch; bounded incomplete-attendance diagnostics and consistent basename resolution; fail closed before graph mutation when active ontology is unavailable; +16 source-selected ontology cache, type-scoped preflight and non-starving failed stale drain; +7 write-path wave: per-slug extractors replace page links + retract removed timeline rows + rename-alias resolution; +5 fw3 derived-sync: timeline --prune-orphans CLI (#4649) and full-walk page link replacement; +13 fw3 A16/A15: sync link hook reads scoped page metadata and reports per-page extraction errors; +1 fw3 managed-lifecycle: extract --stale dispatches managed brains to the coordinator-safe path; +4 fw3 integration: managed brains refuse the direct timeline orphan prune; +26 #5609: managed extract --stale publishes links, canonical timeline and watermark per page in one coordinated transaction; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +4 at the merge; +6 fix wave 3 lane B: a managed brain routes the extract phase file walk through extractManagedStaleLinks instead of the refused raw timeline batch, keeping the extract.links_fs progress phase; +6 #5761: the unmanaged extract --stale sweep marks unresolved-attendance skips attendance-blocked; +2 eval-wave N9-3/N12-7: a page-type-bound pack attended rule defers to canonical attendance on the filesystem path (ownsAttendanceInference); lowered to 2528 #5904: the DB timeline walk moved to commands/extract-timeline-db.ts (coordinated publication on managed brains, honest refusal + non-zero exit); +13 entity mention index: extract --stale runs the mention pass after link work (half the budget reserved while mention-due pages exist), dry-run and JSON report mention counts, and the help documents the pass and `extract mentions --explain` (logic in core/mentions/); cat40 entity wave merge with v0.60.61.0 (2541 measured); +6 fix wave 10 lane L1 #5556: quarantined pages skipped by the file walks, slug lists and DB walks (slug lookup in quarantine.ts quarantinedSlugs); +3 #5556: the abort check stays its own statement in each quarantine-aware scan loop (cycle-abort coverage pin); 2 P5 wanted pages: both DB extract paths record unresolved authored refs with each page's links; +5 P5 line grammar: stated relation types on the filesystem link scan; +3 PGLite stale link drains refresh planner statistics before and during the drain (logic in planner-stats.ts plannerStatsForLinkDrain); +10 fix wave 12 W2.1 S4 (#6228): extract --stale flushes and stamps the pages a batch finished before an aborting page; +12 P5 wanted pages: both DB extract paths record unresolved authored refs with each page's links; +9 Q2 parser gaps: both DB extract paths read the line-grammar settings once, publish through replaceDerivedLinksUnlessSettingsChanged and report pages a mid-run settings change left stale; +25 GBRA-69: extract --source db reads snapshots and publishes derived links BATCH_SIZE pages at a time (readPageSnapshotsBatch in core/page-snapshot-batch.ts, replay in derived-links.ts replaceDerivedLinksBatchOrReplay); +2 GBRA-75 w7: the --source db links walk refreshes planner statistics (logic in planner-stats.ts plannerStatsForLinkDrain); +10 fix wave 13 P2.16 (#6272): both unmanaged DB link drains defer and count a page a concurrent writer moved (skipped_concurrent_write) instead of aborting the run (classifier and skip line in core/derived-links.ts); +3 fix wave 13 P2.18 (S4): extract all --source db stamps the pages both phases completed at one revision, in a finally (stampCompletedIntersection), instead of every links-phase page; +1 fix wave 13 P2.15 (#6273): --from-meetings exits non-zero while managed entity pages are still pending; +7 fix wave 13 PR2: extractFromDB split out of runExtract so runExtract stays under its function-size baseline; Wave B PR 2 (kept at the master 4e29d0904 merge): +3 PR 2 fix lane J1: extract --stale reads a segmented page block by block (extractSegmentedPageLinks, segmentedTimelineText) now that the stale list includes it; integrated at the master 4e29d0904 merge: 2635 measured; +23 fix wave 20 #6954: the fs walks and the slug-scoped extract collect lost link/timeline writes, stamp only the pages whose writes landed and throw extract_write_lost (helpers in core/extract-watermark.ts); fix wave 20 integration: lane 1 (#6808, +11) and lane 2 (#6954, +23) compose at 2677 measuredsrc/commands/jobs.ts 666 ratchet refactor wave 1 split target (W4 jobs, cut line); ceiling rationale: docs/architecture/key-files/commands-4.md entry for src/commands/jobs.ts; help lines: authorize-legacy --select (#5157 T3) and jobs cancel --select (DX-T2); submit --queue-only + PGLite work drain note (agent-first operator wave E5); +2 spend authorization: jobs submit --yes/--max-usd and jobs list --group help lines; +4 fix wave 9: supervisor stop help documents the 45 s wait, --queue and the verified-drain exit codessrc/commands/serve-http.ts 937 ratchet refactor wave 1 W4 split into serve-http-<area>.ts modules; ceiling rationale: docs/architecture/key-files/commands-5.md entry for src/commands/serve-http.ts; +2 agent operator wave A6: ServeHttpContext.noticeLedger (import + field; logic in core/notice-ledger.ts); +2 agent contract F1/F2: ServeHttpContext.readinessCache (probed readiness for initialize tails + gbrain://capabilities); +5 Lane D facts drain: serve --http starts the drain scheduler and stops it before the engine disconnect (logic in core/facts/drain-scheduler.ts); +2 agent-operator follow-up Item 3: ServeHttpOptions.adoptServer (status-only recovery hands its bound listener to listenOrRefuse; logic in serve-http-status.ts); +5 #6317: managed-sync movement watch start/stop (watch in persistence/sync-movement.ts); +1 #6589: imports loadServeConfigs (operations see the DB-plane config read once at startup; logic in mcp/serve-config.ts); +5 #6858 ask 6: on-commit HEAD watcher start/stop (watcher in core/serve-head-watcher.ts)-src/core/ai/gateway.ts 4525 ratchet +2 #6997: ChatResult.fallbackReason (interface field + doc; recorded in ai/chat-fallback.ts); +17 #6607: lazy OpenAI model discovery (discoverBeforeOpenAICall, once per reconfigure, at the chat/expand/embed entry points; it re-resolves through the gateway-internal resolveGatewayModels, so it cannot move); +18 W11 item 3: embedQuery query-embedding cache lookup/store + clear at every model-cache clear site and the test transport seam (cache lives in ai/query-embed-cache.ts); +7 fix wave 5 (#5137): provider-key redactor on every upstream error path and the first embedding 401/403 report (logic in ai/key-redact.ts, ai/key-warnings.ts); +20 System One v1: decide() delegating export + transport seam, RerankInput.onMeta/RerankMeta, TypeSafe reranker delegation to ai/decide/rerank-adapter.ts; +3 #5585: reconfigureGatewayWithEngine records expansion/chat model provenance (ai/gateway-model-sources.ts) + clears it with gateway state; lowered #5585: tracker record sites collapsed onto ai/budget-record.ts (recordOnTracker + failedCallUsage) while adding ledger fields (requested model, purpose, failed, estimated, countsAsCall); +20: schema-rejection fallback in chat() (retry once schemaless on a json_schema 4xx, remember the recipe for the process — mirrors expand()); re-summed after merging master v0.50.0.0 with the wave (structured-output + pricing hunks); +48: #4863 ChatOpts.responseSchema → tolerant json_schema Output on the chat() generateText call for openai-compatible recipes that declare structured outputs (facts extraction on Ollama); +74: #3657 post-sunset rerank short-circuit (effective-model check, once-per-process audit row + stderr, injected-clock seam); grown v0.46.26.0 megawave: config-plane probes + halt telemetry (#3387 #4312); +21 lines (OpenAI Responses API reasoning-item echo: ChatBlock 'reasoning' variant, chat()/toModelMessages() round-trip); wave-k absorbs: OCR routing seam (#4107 class), config-snapshot reader block (#3980); +21: #4107 OCR-model routing (getImageOcrModel); +10: keyless OPENAI_BASE_URL embedding override (#4385); wave-k #3622 reimpl: GBRAIN_EMBED_MAX_BATCH_TOKENS env cap for no_batch_cap recipes; +9: DeepSeek judge thinking pin plumbed through chat opts (#4069); +master v0.48 merge true-up (reranker succession: no_key preflight, reranker_skipped stage, readiness); ranker wave v0.48.4.0: ChatOpts.temperature threaded to the transport (+15); +24: #4172 recipe-declared thinking headroom on the chat()/toolLoop() default — shared isThinkingModel predicate (Claude-5 regex || recipe thinking_by_default, fail-closed), also consumed by the subagent handler; +20: #4861 claude-cli expansion routed to the schemaless viaText path (the CLI adapter ignores responseFormat, so the native generateObject branch had no fallback); retired provider integration removed; safety wave: migration reranker input ceilings; lowered by fix wave 3 #5680 (embed request planning peeled to ai/embed-batch-plan.ts); +5 #4616: empty inputs skip the provider and every text/multimodal result is screened for zero-norm/NaN/Inf vectors (logic lives in ai/embedding-guard.ts); fix wave 3 integration: #4616 empty-input filtering feeds the shared #5680 batch planner; +3 #5691: embedQuery takes a per-request queryPrefix (no gateway state); +26 fix wave 7 (#5642): embed spend records bank provider-reported usage.tokens (all sub-batches reported → measured; chars-per-token estimate stays the fallback and the failure charge); +2 #5892: import + load-time call of installAiSdkWarningWriter (writer lives in ai/sdk-warnings.ts); +12 #5490: chat() delegation to ai/chat-fallback.ts when chat_fallback_chain is set (attempt loop lives there), ChatOpts.allowFallback + ToolLoopOpts.allowFallback fields and the toolLoop forward; +2 #5490 review: ChatResult.fallbackFrom (the call model a chat_fallback_chain answer replaced); +1 fix wave lane B3: configureGateway keeps chat_fallback_on_refusal (the refusal switch lives in ai/chat-fallback.ts); +18 fix wave 9 lane B: ChatOpts.thinking (#5331, per-route mapping lives in ai/thinking-off.ts), ChatOpts.timeoutMs + ToolLoopOpts.turnTimeoutMs and the turn forward (#4921); interface fields and their docs cannot move; +2 P8: GBRAIN_AI_CALL_LOG observer install in configureGateway (logic in ai/call-log.ts); +2 W9F item 5: thinkingOffOutputCap export shared by chat() and the judge preflight estimates (capability table lives in ai/thinking-off.ts); +3 A1 (wave 0): ChatResult.usage.reasoning_tokens (interface field + doc) and the chat() reasoning-subset read beside the cache counts; the ai-sdk importer allowlist is shrink-only, so the seam stays here); +9 GOOGLE_GENERATIVE_AI_BASE_URL: resolveNativeBaseUrl('google') + the three native-google construction sites (eval metering proxy); re-summed at the master 6ccf30c3e merge (4417 integration + 4423 master - 4408 base); lowered -5: the expand() prompt template peeled to ai/expansion-prompt.ts (buildExpansionPrompt) so the longmemeval call planner measures the same text+src/core/ai/gateway.ts 4530 ratchet +2 #6997: ChatResult.fallbackReason (interface field + doc; recorded in ai/chat-fallback.ts); +17 #6607: lazy OpenAI model discovery (discoverBeforeOpenAICall, once per reconfigure, at the chat/expand/embed entry points; it re-resolves through the gateway-internal resolveGatewayModels, so it cannot move); +18 W11 item 3: embedQuery query-embedding cache lookup/store + clear at every model-cache clear site and the test transport seam (cache lives in ai/query-embed-cache.ts); +7 fix wave 5 (#5137): provider-key redactor on every upstream error path and the first embedding 401/403 report (logic in ai/key-redact.ts, ai/key-warnings.ts); +20 System One v1: decide() delegating export + transport seam, RerankInput.onMeta/RerankMeta, TypeSafe reranker delegation to ai/decide/rerank-adapter.ts; +3 #5585: reconfigureGatewayWithEngine records expansion/chat model provenance (ai/gateway-model-sources.ts) + clears it with gateway state; lowered #5585: tracker record sites collapsed onto ai/budget-record.ts (recordOnTracker + failedCallUsage) while adding ledger fields (requested model, purpose, failed, estimated, countsAsCall); +20: schema-rejection fallback in chat() (retry once schemaless on a json_schema 4xx, remember the recipe for the process — mirrors expand()); re-summed after merging master v0.50.0.0 with the wave (structured-output + pricing hunks); +48: #4863 ChatOpts.responseSchema → tolerant json_schema Output on the chat() generateText call for openai-compatible recipes that declare structured outputs (facts extraction on Ollama); +74: #3657 post-sunset rerank short-circuit (effective-model check, once-per-process audit row + stderr, injected-clock seam); grown v0.46.26.0 megawave: config-plane probes + halt telemetry (#3387 #4312); +21 lines (OpenAI Responses API reasoning-item echo: ChatBlock 'reasoning' variant, chat()/toModelMessages() round-trip); wave-k absorbs: OCR routing seam (#4107 class), config-snapshot reader block (#3980); +21: #4107 OCR-model routing (getImageOcrModel); +10: keyless OPENAI_BASE_URL embedding override (#4385); wave-k #3622 reimpl: GBRAIN_EMBED_MAX_BATCH_TOKENS env cap for no_batch_cap recipes; +9: DeepSeek judge thinking pin plumbed through chat opts (#4069); +master v0.48 merge true-up (reranker succession: no_key preflight, reranker_skipped stage, readiness); ranker wave v0.48.4.0: ChatOpts.temperature threaded to the transport (+15); +24: #4172 recipe-declared thinking headroom on the chat()/toolLoop() default — shared isThinkingModel predicate (Claude-5 regex || recipe thinking_by_default, fail-closed), also consumed by the subagent handler; +20: #4861 claude-cli expansion routed to the schemaless viaText path (the CLI adapter ignores responseFormat, so the native generateObject branch had no fallback); retired provider integration removed; safety wave: migration reranker input ceilings; lowered by fix wave 3 #5680 (embed request planning peeled to ai/embed-batch-plan.ts); +5 #4616: empty inputs skip the provider and every text/multimodal result is screened for zero-norm/NaN/Inf vectors (logic lives in ai/embedding-guard.ts); fix wave 3 integration: #4616 empty-input filtering feeds the shared #5680 batch planner; +3 #5691: embedQuery takes a per-request queryPrefix (no gateway state); +26 fix wave 7 (#5642): embed spend records bank provider-reported usage.tokens (all sub-batches reported → measured; chars-per-token estimate stays the fallback and the failure charge); +2 #5892: import + load-time call of installAiSdkWarningWriter (writer lives in ai/sdk-warnings.ts); +12 #5490: chat() delegation to ai/chat-fallback.ts when chat_fallback_chain is set (attempt loop lives there), ChatOpts.allowFallback + ToolLoopOpts.allowFallback fields and the toolLoop forward; +2 #5490 review: ChatResult.fallbackFrom (the call model a chat_fallback_chain answer replaced); +1 fix wave lane B3: configureGateway keeps chat_fallback_on_refusal (the refusal switch lives in ai/chat-fallback.ts); +18 fix wave 9 lane B: ChatOpts.thinking (#5331, per-route mapping lives in ai/thinking-off.ts), ChatOpts.timeoutMs + ToolLoopOpts.turnTimeoutMs and the turn forward (#4921); interface fields and their docs cannot move; +2 P8: GBRAIN_AI_CALL_LOG observer install in configureGateway (logic in ai/call-log.ts); +2 W9F item 5: thinkingOffOutputCap export shared by chat() and the judge preflight estimates (capability table lives in ai/thinking-off.ts); +3 A1 (wave 0): ChatResult.usage.reasoning_tokens (interface field + doc) and the chat() reasoning-subset read beside the cache counts; the ai-sdk importer allowlist is shrink-only, so the seam stays here); +9 GOOGLE_GENERATIVE_AI_BASE_URL: resolveNativeBaseUrl('google') + the three native-google construction sites (eval metering proxy); re-summed at the master 6ccf30c3e merge (4417 integration + 4423 master - 4408 base); lowered -5: the expand() prompt template peeled to ai/expansion-prompt.ts (buildExpansionPrompt) so the longmemeval call planner measures the same text; +5 #7176: expand() writes its chat_usage_log row (phase expansion) beside the budget record, and the guardedExpansion instance that names its invocation gateway.expand (ledger in ai/chat-usage.ts)src/commands/sync.ts 548 ratchet refactor wave 1 split target (W4 sync); ceiling rationale: docs/architecture/key-files/commands-6.md entry for src/commands/sync.ts; +2 for the #5751 SyncResult.legacySkips interface field (fix wave 4); +2 fix wave 4 lane B: SyncResult.connectorHolds interface field (held counts for the sync summary); +1 fix wave 5 (#5032): SyncResult.fileRefusals interface field (named per-file Windows colon refusals); +13 #5984: SyncResult.drain / managedCursor and SyncOpts.drain / drainStartedAt interface fields (drain loop lives in persistence/sync-drain.ts); +1 #5984: SyncOpts.noBulk / bulk interface fields; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (510 measured); +2 #5984 lanes: SyncOpts.lanes field and the lanes progress-event field; +2 #6278: SyncResult.breaker interface field (the preparation-stall breaker verdict); +1 fix wave 13 P4.3 #6386: the JSON-output comment names writeJsonDocument for sync status/unblock; +2 fix wave 13 PR2: the transaction-pooler stderr line (P2.2) and the staged catch-up result field (P2.14, loop in commands/sync/perform.ts); +2 fix wave 15 P4.5 (#5459 adjacent): SyncResult.working_tree_kept interface field (the tree-walk keep lives in persistence/sync-discovery.ts); +4 #6643: SyncResult.retryWait / knockOns interface fields (recovery lives in persistence/sync-run.ts, sync-knock-on.ts); +2 #6696 (A7): SyncOpts.capacityPreflight interface field (preflight lives in persistence/sync-capacity-preflight.ts); +2 #6696 C1: SyncOpts.embedDeferred interface field (the cost gate's runtime embed deferral; an interface field cannot move), composed with PR A's SyncOpts.capacityPreflight; +2 #6693: SyncResult.replayedRemembers interface field (the post-sync replay lives in commands/sync/perform.ts and repair/failed-writes.ts); +12 #6712 PR 1: SyncResult.leaseHeld / inherited_options / cursorAdopted / cursorFanIn and SyncOpts.drainHolder / followDrainLease interface fields (the lease lives in persistence/sync-lease.ts, adoption in persistence/sync-cursor-key.ts and sync-admitted.ts); +2 #6712 PR 2 (L5): SyncResult.tail interface field (the tail lives in persistence/sync-tail.ts); +2 #6712 PR 2 integration: L4 ghostPages and L5 tail SyncResult interface fields both land (each lane raised 542->544 alone); +2 #6948: SyncResult.origin_twins_resolved interface field (the heal lives in repair/origin-twins-heal.ts); +5 #6712 PR 4b: SyncResult.pass / reconcile and SyncOpts.costApproved interface fields (an interface field cannot move; the pass summary and the pass reason union live in persistence/sync-pass-row.ts, the remote reconcile in sync-pass-apply.ts); lowered to 546 #6712 PR 4b lane C: SyncResult.cursorAdopted / cursorFanIn retired with the cursor enginesrc/core/cycle.ts 3332 ratchet +2 GBRA-130 C-2 (#6946): the sync phase reads an owned clone's pull block and reports it as pull_blocked (logic in url-clone.ts urlClonePullBlock/urlClonePullBlockSummary); +6 GBRA-130 A-1: the extract phase warns on failed or breaker-stopped stale drain pages (logic in cycle/connector-extract.ts staleDrainFailures); +1 W1 belief ledger: the extract phase runs the sampled belief drift reconcile (logic in belief/coverage-report.ts); +2 System One v1 S9: extract_facts phase tail runs the conflict sweep (ai/decide/sweep.ts) only when the slot is not off; +2 System One v1: purge phase prunes decision receipts (ai/decide/store.ts); grown v0.46.26.0 megawave (#4102 #2608) + master v0.46.26.0 cycle-start orphan recovery; +10 wave G #3974: cycle-sync uncommitted-drift warn; grown wave-g (#4416): synthesize_concepts source threading; grown wave-g (#4416): synthesize_concepts source threading (same fix absorbed as #4417 on wave-k); wave-k: ); +7: #4077 abort threading; +10: #4745 fullImplicitSourceCycle opt-in contract; +3: #4890 extract phase jsonMode/quiet + pages-not-links totals; +1: wave review — extract phase passes quiet:true + jsonMode:false; +1: extract_facts pagesFailed detail; +8 fix wave 3: one cycle date resolved in runCycle and threaded to synthesize/patterns/drift (C-15); +1 #5632: cycle sync resumes an unfinished managed cursor with its stored options; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +1 at the merge; -41 #5809: anyAbortSignal peeled to abort-signals.ts; +5 #5809: extract_atoms phase gets a real abort signal; +4 #5809: cycle_already_running names the lock holder; +7 #5255: cycle sync runs a managed pull request as no-pull and reports upstream_refresh; +1 #4578: a lock steal during the last selected phase reports lock_stolen, not aborted; +3 #5536: keyless embed phase clean-skips when embedding_disabled is set; +5 F4b: planner-stats refresh after the freshness phases (logic in planner-stats.ts); +2 agent operator wave A1: PhaseResult sibling code/fix; +20 #5876: Life Chronicle phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch block; v0.60.46.0 merge: re-summed to the merged line count (3224); +3 retrieval feedback retention in the purge phase (logic in feedback/store.ts pruneRetrievalFeedback); 12 Lane D: facts_drain phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch line (logic in cycle/facts-drain.ts); P3 x foundations-2 composition: deltas re-summed at the merge; 12 Lane D: facts_drain phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch line (logic in cycle/facts-drain.ts); +15 GBRA-49 temporal typed edges: edge_contradictions phase registration + dispatch block + extract-phase relationship sweep call (logic in cycle/edge-contradictions.ts, link-relationships.ts); P3 x P1 (v0.60.57.0) composition: deltas re-summed at the merge; +1 fix wave 9 lane P (#5151): extract_facts phase passes drain so the facts watermark drain runs (logic in facts/reconcile-watermark.ts); +10 #6188: fence_repair phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch block (logic in cycle/fence-repair.ts); +19 fix wave 12 #6242: source cycles with brain-wide phases also take the shared gbrain-cycle lease (acquireDbCycleLock lease set, needsMaintenanceLease, skipBrainWidePhases, all-skipped deriveStatus case; lease logic in cycle/lock-set.ts); +16 #6377: content_repair phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK), the REPAIR_LANE_PHASES dispatch helper shared with fence_repair (logic in cycle/content-repair.ts); +10 C4 pinned questions: standing_questions phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch block (logic in questions/phase.ts); +11 #6696 (A5, A4): runCycle becomes the background-origin wrapper over runCycleUnscoped and adds the capacity notices (logic in persistence/admission-origin.ts, capacity-snapshot.ts) plus the CycleReport.notices interface field; +2 #6297: CycleOpts.directPhases (operator-named phases skip the patterns cadence); +5 #6865: unindexed_files phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its line in the REPAIR_LANE_PHASES dispatch helper (logic in cycle/unindexed-files.ts); +2 fix wave 20 #6954: the extract phase warns on extract_write_lost and its stale drain retries the pages left duesrc/core/cycle/synthesize.ts 3230 ratchet +26 System One v1 S7/S8: triage and grounding decide delegation (triage-decide.ts, grounding-decide.ts); merged waves; grown v0.46.26.0 megawave + master rolling lease via shared throttled renewer; grown wave-g (#4506): cycle summaries can stay out of the source repo; +18: expired-verdict sweep + DeepSeek judge thinking pin (#4069); +47: #4077 cooperative-abort threading; +110: eval fix wave F6 spend surfacing (withChatPhase wrap, triage/child token telemetry, zero-page counter); +32: F1b quote-verify call site + kill switch; +2: F1a/F3/F4a OUTPUT POLICY rules; +59: F2 verified-segment rescue (gate at report construction, rescue knobs, telemetry); +19: rubric v2 peak-scoring + docblock rescue branch; +50: #4337 summary link-sample cap + dream_created_cycle_date preserve-on-rerun; +5: #4348 resolveCycleDate wiring (local-day summary bucketing); +3 round-3 rebase true-up; +55: #4805 synth-v2 completion skip (findSynthV2Completion + prefix-parameterized loadSuccessfulSynthesisKeys); +10: #4886 mode-aware buildSynthesisPrompt (oneshot children drop tool-use/final-prose guidance); #5105: small legacy writer/refusal and shared revision CAS delegates; +4: merge of #5666 durable synthesis completions with the v0.59.18.0 verify-epoch wiring; +7 #5413/#5471 discovery exclusions (self-capture session ids, dream output directories); +6 fix wave 2 (v0.60.5.0) integration: W7 paid-loop breaker check before submission and released-key daily-cap count on top of the W1b discovery exclusions; +6 v0.60.5.0 master-merge true-up: the wave-2 growth (+13 W1b, +6 W7) re-summed over master v0.59.18.0 at 3222 lines with no slack; +76 fix wave 3: per-run USD gate + fail-closed daily cap (C-13), child first-write ownership for stamp/reverse-write (C-8, #5685), cycle-date prompt hint (C-15), opt-in attribution rule (#5425); fix wave 3 x fix wave 2 (v0.60.5.0) composition: +19 at the merge; +2 #5806 triageNow clock seam forwarded to triage (interface field + call-site option); +4 #5854: a postprocess or summary publish still pending after its wait is deferred (publish_pending warn, no cooldown stamp; helper in synthesize-postprocess.ts); +14 #5490 review: a triage verdict a chat_fallback_chain model gave is used for the run but not cached (TriageResult.answeredBy, judge-client marker, guarded putDreamVerdict); Foundations 2 Lane C: maintenanceTransaction import (attributed summary page); +14 #5490 review: a triage verdict a chat_fallback_chain model gave is used for the run but not cached (TriageResult.answeredBy, judge-client marker, guarded putDreamVerdict); Foundations 2 Lane C: maintenanceTransaction import (attributed summary page); +14 #5490 review: a triage verdict a chat_fallback_chain model gave is used for the run but not cached (TriageResult.answeredBy, judge-client marker, guarded putDreamVerdict); lowered to 3200 by wave 9 lane W #5145: completion-key helpers (findLegacyCompletion, findSynthV2Completion, loadSuccessfulSynthesisKeys) peeled to synthesize-completion.ts with the new pre-triage partition; +13 P2 extraction.date_grounding: transcript observation date line instead of a run-date "Today's date" (config field + prompt arg); +1 fix wave 11 #6160: oneshot_task_prefixes on the child job data; +18 fix wave 12 #6069: unreliable-verdict backoff in runTriagePass (report code, pass backoff count, triage details entry; marker logic in triage-backoff.ts); +1 fix wave 12 #6242: SYNTH_PHASE_FAIL keeps an OperationError's suggestion and code (OperationError import); +3 wave 17 #6616: slug discovery and postprocessing share the canonical committed child outputs (loadCommittedSynthesisOutputs in synthesize-postprocess.ts; one call-site line, one parameter, one lookup line); lowered to 3224 by wave 17 #6642: the summary provenance section moved to summaryProvenanceLines in dream-provenance.ts; +6 GBRA-130 B-6 (#6860): surrogate-safe triage cuts (truncateUtf8) and the per-transcript verdict-cache write call site (logic in triage-backoff.ts VerdictCacheWrites)diff --git a/scripts/serial-files.tsv b/scripts/serial-files.tsvindex 9165ecfd6a..9a29f01a08 100644--- a/scripts/serial-files.tsv+++ b/scripts/serial-files.tsv@@ -437,3 +437,4 @@ test/coordination-lock.serial.test.ts global-state global-state: withEnv holds Gtest/context-assemble-load-warning.serial.test.ts R2 R2: mock.module(../src/core/engine-factory.ts) replaces modules for every file in the process; R1: mutates process.env (GBRAIN_HOME, DATABASE_URL, GBRAIN_DATABASE_URL)test/search-tune-apply-truthful.serial.test.ts R2 R2: mock.module(../src/core/search/tune-recommendations.ts) replaces modules for every file in the processtest/search-cost.serial.test.ts global-state global-state: process-wide test seams __setEmbedTransportForTests, __setRerankTransportForTests; configureGateway changes the process-wide AI gateway+test/chat-usage-phases.serial.test.ts global-state global-state: process-wide test seams __setChatTransportForTests, __setEmbedTransportForTests, __setGenerateObjectTransportForTests; configureGateway changes the process-wide AI gateway; setChatUsageSink replaces the process-wide ledger sink; R1: mutates process.env (ANTHROPIC_API_KEY)diff --git a/src/cli/search-timings.ts b/src/cli/search-timings.tsindex b7168d40e8..52f1907df3 100644--- a/src/cli/search-timings.ts+++ b/src/cli/search-timings.ts@@ -77,7 +77,7 @@ export function searchTimingsLine(meta: Record<string, unknown> | null): stringconst parts = (['startup', 'connect', 'context', 'remote', 'op'] as const).flatMap(k => t[k] === undefined ? [] : [`${k} ${t[k]}`]);const stages = Object.entries(t.stages ?? {}).map(([k, v]) => `${k} ${v}`);const cost = (meta?.cost as SearchCostMeta | undefined) ?? { calls: 0 };- const calls = (['embedding', 'rerank', 'chat', 'decide'] as const).flatMap(k => cost[k] ? [`${k} ${cost[k]!.calls} (${cost[k]!.input_tokens} tokens)`] : []);+ const calls = (['embedding', 'rerank', 'expansion', 'chat', 'decide'] as const).flatMap(k => cost[k] ? [`${k} ${cost[k]!.calls} (${cost[k]!.input_tokens} tokens)`] : []);return `timings: ${t.total}ms total — ${[...parts, `cli_other ${t.cli_other}`].join(', ')}`+ (stages.length ? ` | op stages: ${stages.join(', ')}` : '')+ ` | cost: ${calls.length ? calls.join(', ') : 'no model calls'}${cost.estimated_usd !== undefined && cost.calls > 0 ? `, ~$${cost.estimated_usd}` : ''}\n`;diff --git a/src/core/ai/chat-usage.ts b/src/core/ai/chat-usage.tsindex 9e37f91092..a73096fcfe 100644--- a/src/core/ai/chat-usage.ts+++ b/src/core/ai/chat-usage.ts@@ -7,9 +7,12 @@* model + token usage. This module:** - attributes a best-effort PHASE via AsyncLocalStorage (`withChatPhase`):- * the minion worker wraps handler execution in `job:<name>`; direct CLI /- * op callers record with phase NULL unless they opt in. Attribution is- * advisory — a missing phase never blocks the record.+ * the minion worker wraps handler execution in `job:<name>`; `think`+ * records as `think` when nothing outside set a phase+ * (`withDefaultChatPhase`); query expansion always records as+ * `expansion` (#7176); other direct CLI / op callers record with phase+ * NULL unless they opt in. Attribution is advisory — a missing phase never+ * blocks the record.* - prices the call from CANONICAL_PRICING (`estimateChatCostUsd`),* including cache_read/cache_write tokens at the provider's cache rates* when the table carries them (Anthropic), falling back to the input@@ -19,7 +22,7 @@* closed engine, disk pressure) must never break a chat call.** Coverage contract (surfaced verbatim by the `get_usage` op): only- * gateway.chat() calls are logged. The subagent raw-SDK path, embeddings+ * gateway.chat() and gateway.expand() calls are logged. The subagent raw-SDK path, embeddings* (embedding-pricing.ts owns those), and calls made before the sink was* registered or before migration v140 are NOT covered. Failed chat calls are* not logged either — the budget tracker (budget-tracker.ts) remains the@@ -57,6 +60,11 @@ export function withChatPhase<T>(phase: string, fn: () => T): T {return __chatPhaseStore.run(phase, fn);}+/** Like `withChatPhase`, but an enclosing phase (`job:<name>`, `phase:synthesize`) wins. */+export function withDefaultChatPhase<T>(phase: string, fn: () => T): T {+ return currentChatPhase() === null ? withChatPhase(phase, fn) : fn();+}+export function currentChatPhase(): string | null {return __chatPhaseStore.getStore() ?? null;}@@ -154,6 +162,8 @@ export function estimateChatCostUsd(export function recordChatUsage(input: {model: string;provider?: string | null;+ /** An operation's own phase (`expansion`), over the ambient one. */+ phase?: string;usage: {input_tokens: number;output_tokens: number;@@ -182,7 +192,7 @@ export function recordChatUsage(input: {const record: ChatUsageRecord = {model: input.model,provider: input.provider ?? null,- phase: currentChatPhase(),+ phase: input.phase ?? currentChatPhase(),input_tokens: Math.max(0, Math.round(input.usage.input_tokens || 0)),output_tokens: Math.max(0, Math.round(input.usage.output_tokens || 0)),cache_read_tokens: Math.max(0, Math.round(input.usage.cache_read_tokens || 0)),diff --git a/src/core/ai/gateway.ts b/src/core/ai/gateway.tsindex 19882b41ba..d05d85e6e8 100644--- a/src/core/ai/gateway.ts+++ b/src/core/ai/gateway.ts@@ -82,6 +82,7 @@ import { cachedQueryEmbedding, clearQueryEmbedCache, queryEmbedCacheKey, queryEmimport { createGuardedGeneration, chatInvocation } from './guarded-generation.ts';installAiSdkWarningWriter();const guardedGeneration = createGuardedGeneration(() => DEFAULT_MAX_OUTPUT_TOKENS);+const guardedExpansion = createGuardedGeneration(() => DEFAULT_MAX_OUTPUT_TOKENS, 'gateway.expand');// ---- Gateway-wide AI-HTTP timeout (v0.42.20.0, #1762/#1775) ----//@@ -2519,8 +2520,12 @@ export async function expand(query: string): Promise<string[]> {const requestedModelId = getExpansionModel();const { model, recipe, modelId } = await resolveExpansionProvider(requestedModelId);const modelLabel = `${recipe.id}:${modelId}`;- const recordExpansionUsage = (usage: unknown, countsAsCall: boolean): void =>- recordOnTracker(tracker, { modelId: modelLabel, requestedModelId, label: 'gateway.expand', countsAsCall, ...normalizeSdkUsage(usage) });+ // #7176: a successful expansion is also a chat_usage_log row, phase 'expansion'.+ const recordExpansionUsage = (usage: unknown, countsAsCall: boolean): void => {+ const { inputTokens, outputTokens } = normalizeSdkUsage(usage);+ recordOnTracker(tracker, { modelId: modelLabel, requestedModelId, label: 'gateway.expand', countsAsCall, inputTokens, outputTokens });+ recordChatUsage({ model: modelLabel, provider: recipe.id, phase: 'expansion', usage: { input_tokens: inputTokens, output_tokens: outputTokens } });+ };const recordExpansionFailure = (err: unknown, countsAsCall: boolean): void =>recordOnTracker(tracker, {modelId: modelLabel,@@ -2539,7 +2544,7 @@ export async function expand(query: string): Promise<string[]> {const viaText = async (countsAsCall = true): Promise<string[]> => {let textResult: Awaited<ReturnType<GenerateTextFn>>;try {- textResult = await guardedGeneration(modelLabel, _generateTextTransport, {+ textResult = await guardedExpansion(modelLabel, _generateTextTransport, {model,abortSignal: withDefaultTimeout(undefined, AI_CHAT_TIMEOUT_MS),prompt: expansionPrompt,@@ -2580,7 +2585,7 @@ export async function expand(query: string): Promise<string[]> {// generic, so `object` would be `{}`.)let result: { object?: unknown; usage?: unknown };try {- result = await guardedGeneration(modelLabel, _generateObjectTransport, {+ result = await guardedExpansion(modelLabel, _generateObjectTransport, {model,schema: ExpansionSchema,// Name the schema. On the native-anthropic path the SDK turns the schema@@ -2614,7 +2619,7 @@ export async function expand(query: string): Promise<string[]> {// schema (strict validation), and fall back to the text path if it is// rejected at call time so a mis-declared capability never drops expansion.try {- const result = await guardedGeneration(modelLabel, _generateObjectTransport, {+ const result = await guardedExpansion(modelLabel, _generateObjectTransport, {model,schema: ExpansionSchema,// Same schema name+description as the native branch above: andiff --git a/src/core/ai/guarded-generation.ts b/src/core/ai/guarded-generation.tsindex ac9f55a9ff..c73dffd8c2 100644--- a/src/core/ai/guarded-generation.ts+++ b/src/core/ai/guarded-generation.ts@@ -8,16 +8,16 @@ export function chatInvocation(operation: string, model: string, maxOutputTokens}/** Each SDK attempt has its own durable hold; local calls keep SDK retries. */-export function createGuardedGeneration(defaultMaxOutputTokens: () => number) {+export function createGuardedGeneration(defaultMaxOutputTokens: () => number, operation = 'gateway.generate') {return async function guardedGeneration<T>(model: string, transport: (opts: any) => Promise<T>, opts: any): Promise<T> {if (!hasAIInvocationGuard()) {if (!hasAIInvocationObservers()) return transport(opts);// Observed but unguarded: the transport sees the caller's options unchanged (SDK retries, token defaults).- return invokeAI({ ...chatInvocation('gateway.generate', model, opts.maxOutputTokens ?? defaultMaxOutputTokens()) },+ return invokeAI({ ...chatInvocation(operation, model, opts.maxOutputTokens ?? defaultMaxOutputTokens()) },() => transport(opts), sdkInvocationUsage);}const maxOutputTokens = opts.maxOutputTokens ?? defaultMaxOutputTokens();- return invokeAI({ ...chatInvocation('gateway.generate', model, maxOutputTokens),+ return invokeAI({ ...chatInvocation(operation, model, maxOutputTokens),cacheWriteTtl: opts.providerOptions?.anthropic?.cacheControl?.ttl ?? '5m' },() => transport({ ...opts, maxOutputTokens, maxRetries: 0 }), sdkInvocationUsage);};diff --git a/src/core/search/search-cost.ts b/src/core/search/search-cost.tsindex 35b9cb855c..270f432d55 100644--- a/src/core/search/search-cost.ts+++ b/src/core/search/search-cost.ts@@ -3,7 +3,9 @@* the CLI's `--timings` document). One meter per op call, scoped with* AsyncLocalStorage, so concurrent MCP requests never see each other's calls.*- * Every embedding, rerank, chat and decide call inside the request counts,+ * Every embedding, rerank, query-expansion, chat and decide call inside the+ * request counts (expansion is its own line, the calls chat_usage_log+ * records with phase `expansion`),* failed ones included (a provider can bill a failed call); a call a budget* guard refused was never sent and does not count. Tokens are the provider's* reported usage; a call whose provider reported none counts its request@@ -15,7 +17,7 @@ import { AsyncLocalStorage } from 'node:async_hooks';import { withAIInvocationMeter, type AIInvocationEvent } from '../ai/invocation-guard.ts';import { usageCostUsd, type BudgetKind } from '../budget/reservation-cost.ts';-export type SearchCostKind = 'embedding' | 'rerank' | 'chat' | 'decide';+export type SearchCostKind = 'embedding' | 'rerank' | 'expansion' | 'chat' | 'decide';export interface SearchCostLine {calls: number;@@ -47,7 +49,8 @@ class SearchCost {add(event: AIInvocationEvent): void {const kind = KIND[event.call.kind];if (!kind || event.outcome === 'refused') return;- const tally = this.tallies.get(kind.line) ?? { calls: 0, input_tokens: 0, output_tokens: 0, usd: 0, unpriced: false };+ const line = event.call.operation === 'gateway.expand' ? 'expansion' : kind.line;+ const tally = this.tallies.get(line) ?? { calls: 0, input_tokens: 0, output_tokens: 0, usd: 0, unpriced: false };const input = event.usage?.inputTokens ?? event.call.estimatedInputTokens ?? 0;const output = event.usage?.outputTokens ?? 0;tally.calls += 1;@@ -57,7 +60,7 @@ class SearchCost {const usd = usageCostUsd(event.call.model, input, output, kind.budget);if (usd === null) tally.unpriced = true;else tally.usd += usd;- this.tallies.set(kind.line, tally);+ this.tallies.set(line, tally);}snapshot(): SearchCostMeta {diff --git a/src/core/think/index.ts b/src/core/think/index.tsindex 98fb87f548..40c03b5d4e 100644--- a/src/core/think/index.ts+++ b/src/core/think/index.ts@@ -30,6 +30,7 @@ import { resolveCitations, type ParsedCitation } from './cite-render.ts';import { resolveOwnerHolder } from '../owner-holder.ts';import { resolveModel } from '../model-config.ts';import { chat as gatewayChat, probeChatModel, isThinkingModel, type ChatResult } from '../ai/gateway.ts';+import { withDefaultChatPhase } from '../ai/chat-usage.ts';import { AIConfigError } from '../ai/errors.ts';import { normalizeModelId } from '../model-id.ts';import { hasAnthropicKey } from '../ai/anthropic-key.ts';@@ -1285,14 +1286,15 @@ async function tryBuildGatewayClient(let result: ChatResult;try {- result = await gatewayChat({+ // #7176: chat_usage_log rows for think say so, unless a job or cycle phase already does.+ result = await withDefaultChatPhase('think', () => gatewayChat({model: modelStr,system,messages,maxTokens: params.max_tokens,// An explicit --model is a hard requirement (#1698), never a hop....(opts.explicitModel || opts.allowFallback === false ? { allowFallback: false } : {}),- });+ }));} catch (e) {// AIConfigError at chat time = e.g. key revoked mid-run. For an EXPLICIT// model the user typed, this is a hard error (rethrow) — the early gatediff --git a/test/chat-usage-phases.serial.test.ts b/test/chat-usage-phases.serial.test.tsnew file mode 100644index 0000000000..f01708fe08--- /dev/null+++ b/test/chat-usage-phases.serial.test.ts@@ -0,0 +1,130 @@+/**+ * #7176: every read-path model call lands in chat_usage_log with a phase.+ *+ * - query expansion (gateway.expand) writes a row with its model, tokens+ * and phase `expansion`, on every expand() path, even inside a job;+ * - think's synthesis call writes phase `think` unless a job or cycle+ * phase already attributes it;+ * - a query's `cost` meta (#7158) counts the same expansion call on its+ * own `expansion` line, with the tokens the ledger row carries.+ *+ * Serial: configureGateway and the transport seams are process-wide, and+ * withEnv sets ANTHROPIC_API_KEY.+ */+import { afterAll, afterEach, beforeAll, describe, expect, test } from 'bun:test';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import {+ __setChatTransportForTests,+ __setEmbedTransportForTests,+ __setGenerateObjectTransportForTests,+ configureGateway,+ expand,+ resetGateway,+ type ChatResult,+} from '../src/core/ai/gateway.ts';+import { setChatUsageSink, withChatPhase, type ChatUsageRecord } from '../src/core/ai/chat-usage.ts';+import { runThink } from '../src/core/think/index.ts';+import { operations } from '../src/core/operations.ts';+import { searchCtx, seedPage } from './helpers/keyword-paging-fixture.ts';+import { withEnv } from './helpers/with-env.ts';++const HAIKU = 'anthropic:claude-haiku-4-5-20251001';+let engine: PGLiteEngine;+let rows: ChatUsageRecord[] = [];++function chatResultOf(text: string): ChatResult {+ return {+ text, blocks: [{ type: 'text', text }], stopReason: 'end',+ usage: { input_tokens: 900, output_tokens: 60, cache_read_tokens: 0, cache_creation_tokens: 0 },+ model: 'anthropic:claude-sonnet-4-6', providerId: 'anthropic',+ };+}++function expansionGateway(): void {+ resetGateway();+ configureGateway({ expansion_model: HAIKU, env: { ANTHROPIC_API_KEY: 'sk-test-fake' } });+ __setGenerateObjectTransportForTests(async () => ({ object: { queries: ['widget cost', 'widget price list'] }, usage: { inputTokens: 120, outputTokens: 40 } }) as never);+}++beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+ await seedPage(engine, 'notes/widget-pricing', 'Widget pricing for acme-example is set per seat.');+}, 120_000);++afterEach(() => {+ rows = [];+ setChatUsageSink(null);+ __setChatTransportForTests(null);+ __setGenerateObjectTransportForTests(null);+ __setEmbedTransportForTests(null);+ resetGateway();+});++afterAll(async () => { await engine.disconnect(); });++const capture = () => setChatUsageSink(r => { rows.push(r); });++describe('query expansion in chat_usage_log', () => {+ test('a structured expansion writes one row: model, provider, tokens, phase expansion', async () => {+ expansionGateway();+ capture();+ expect(await expand('widget pricing')).toContain('widget cost');+ expect(rows).toHaveLength(1);+ expect(rows[0]).toMatchObject({ model: HAIKU, provider: 'anthropic', phase: 'expansion', input_tokens: 120, output_tokens: 40 });+ expect(rows[0]!.cost_usd).toBeGreaterThan(0);+ });++ test('a job phase does not hide that the call was expansion', async () => {+ expansionGateway();+ capture();+ await withChatPhase('job:example', () => expand('widget pricing'));+ expect(rows.map(r => r.phase)).toEqual(['expansion']);+ });++ test('a failed expansion writes no row (the ledger records successes only)', async () => {+ expansionGateway();+ __setGenerateObjectTransportForTests(async () => { throw new Error('simulated 503'); });+ capture();+ expect(await expand('widget pricing')).toEqual(['widget pricing']);+ expect(rows).toEqual([]);+ });+});++describe('think in chat_usage_log', () => {+ const answer = JSON.stringify({ answer: 'Per seat [notes/widget-pricing].', citations: [{ page_slug: 'notes/widget-pricing', row_num: null, citation_index: 1 }], gaps: [] });++ test('a direct think call records phase think', async () => {+ __setChatTransportForTests(async () => chatResultOf(answer));+ capture();+ await withEnv({ ANTHROPIC_API_KEY: 'sk-test-hermetic' }, () => runThink(engine, { question: 'How is widget pricing set?', withTrajectory: false }));+ expect(rows.length).toBeGreaterThan(0);+ expect(rows.every(r => r.phase === 'think')).toBe(true);+ });++ test('think inside a job keeps the job phase', async () => {+ __setChatTransportForTests(async () => chatResultOf(answer));+ capture();+ await withEnv({ ANTHROPIC_API_KEY: 'sk-test-hermetic' }, () => withChatPhase('job:example', () => runThink(engine, { question: 'How is widget pricing set?', withTrajectory: false })));+ expect(rows.length).toBeGreaterThan(0);+ expect(rows.every(r => r.phase === 'job:example')).toBe(true);+ });+});++describe('query cost counts expansion from the same call', () => {+ test('the expansion line matches the ledger row', async () => {+ expansionGateway();+ configureGateway({ expansion_model: HAIKU, embedding_model: 'openai:text-embedding-3-large', embedding_dimensions: 1536, env: { ANTHROPIC_API_KEY: 'sk-test-fake', OPENAI_API_KEY: 'sk-fake' } });+ __setEmbedTransportForTests((async (args: { values: string[] }) => ({ embeddings: args.values.map(() => Array.from({ length: 1536 }, () => 0.1)), usage: { tokens: 7 } })) as never);+ capture();+ const ctx = searchCtx(engine, false);+ await operations.find(o => o.name === 'query')!.handler(ctx, { query: 'how is widget pricing set', expand: true });+ const cost = (ctx.captured.retrieval as { cost: Record<string, any> }).cost;+ const expansion = rows.filter(r => r.phase === 'expansion');+ expect(expansion).toHaveLength(1);+ expect(cost.expansion).toMatchObject({ calls: 1, input_tokens: expansion[0]!.input_tokens, output_tokens: expansion[0]!.output_tokens });+ expect(cost.expansion.usd).toBeCloseTo(expansion[0]!.cost_usd!, 6);+ expect(cost.chat).toBeUndefined();+ });+});