Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
docs(eval): nightly probe is a synthetic smoke test; run cap, collapsed panel, receipts, skipped (#5506, #5187); wave 9 lane C notes
time-attackc08a304dd552
diff --git a/docs/architecture/key-files/commands-1.md b/docs/architecture/key-files/commands-1.mdindex b6e57a8287..10f6ba95a2 100644--- a/docs/architecture/key-files/commands-1.md+++ b/docs/architecture/key-files/commands-1.md@@ -17,7 +17,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/commands/autopilot-pause.ts` — engine-free `gbrain autopilot pause [--reason <text>]` / `resume`: writes or removes the operator marker `autopilot-operator-paused` (`autopilotOperatorPauseMarkerPath` in `src/core/autopilot-paths.ts`, with `autopilotPaused()` and `autopilotPauseReason()`). The daemon loop and job workers honor it like the migration hold; `--install` (and so `gbrain upgrade`) clears only a leaked migration hold, and resume never clears a migration or restore hold. Test: `test/autopilot-operator-pause.test.ts`.- `src/commands/autopilot.ts` — `gbrain autopilot --install`: self-maintaining brain daemon (sync+extract+embed). Freshness sync jobs always send an explicit positive-polarity `pull` value derived from the source's parsed `remote_url`, so local-only sources skip pull and PGLite JSON-string configs behave like Postgres objects. Consumes `detectTini()` from `src/core/minions/spawn-helpers.ts`, resolved once at startup. Composes a `ChildWorkerSupervisor` instance for spawn-and-respawn with `--max-rss 2048` and soft `maxCrashes: 5`, preferring the current source/compiled CLI over PATH. The child worker performs private-queue recovery only after its driver/selected-child readiness and schema check; autopilot does not duplicate that recovery before spawn. A configuration-blocked child leaves the owning daemon alive and heartbeating but gates dispatch, worker restarts and engine work until explicit owner restart after repair. `--status --json` adds processing readiness, reason and runtime identities without replacing existing freshness/exit semantics; see [the owner-specific repair guide](../../guides/minions-fix.md). `onMaxCrashesExceeded` routes through autopilot's own `shutdown('max_crashes')` so the autopilot lockfile gets cleaned up. `shutdown()` drains via `childSupervisor.killChild('SIGTERM')` + `awaitChildExit(35_000)`. Pinned by `test/autopilot-fanout-wiring.test.ts` and `test/autopilot-supervisor-wiring.test.ts` (6 static-shape guards: composes ChildWorkerSupervisor not legacy names, `--max-rss 2048` in argv, `maxCrashes: 5` literal, shutdown-via-callback, no workerProc reference). tick body invokes `runNightlyQualityProbe` when `cfg.autopilot.nightly_quality_probe.enabled === true` (default OFF — opt-in to protect API spend). NO scheduler-side rate-limit check — `runNightlyQualityProbe`'s internal `shouldRunNightly` (reading the audit JSONL) is the single source of truth. Probe call wrapped in try/catch that logs via `logError` and does NOT bump `consecutiveErrors` (probe failure is informational, never crashes the loop). Default `max_usd` cap = 5. Pinned by `test/autopilot-nightly-probe-wiring.test.ts`. per-source `extract_atoms` auto-drain. Postgres-only block after the freshness fan-out: gated on `autopilot.auto_drain.enabled` (default true) AND `!packDeclaresPhase(engine,'extract_atoms')` (the silent-backlog condition) AND per-source `countExtractAtomsBacklog > threshold` (default 25) AND a daily cap `floor(max_usd_per_day / ~$0.30)`. Enumerates `loadAllSources`. Submits the PROTECTED `extract-atoms-drain` job (`{allowProtectedSubmit:true}`) with a UTC-day time-sloted idempotency key `autopilot-extract-atoms-drain:<src.id>:<utcDay>` (a static key would block the source after the first job completed). `src/core/minions/protected-names.ts` lists `extract-atoms-drain`; `src/commands/jobs.ts` registers the handler (thin wrapper over `runExtractAtomsDrainForSource`, `LockUnavailableError` → `{deferred:true}`; a `provider_failure` result throws `formatDrainProviderFailure(result)` — batches/remaining plus the drain's sanitized `last_error` — so the dead-lettered job's `error_text` names the cause, e.g. a missing provider key); `src/core/config.ts` carries the `autopilot.auto_drain.*` config keys + the `autopilot.` key prefix. Pinned by `test/extract-atoms-drain-handler.test.ts`, `test/autopilot-auto-drain-wiring.test.ts`. federated-brain co-existence + launchd hygiene. (1) `LOCK_PATH` resolves via `gbrainPath('autopilot.lock')` so it honors `GBRAIN_HOME` (two brains can run autopilot simultaneously without lock-stealing); lock file stores PID; `src/core/autopilot-lock.ts` checks liveness and the process command before takeover. `looksLikeGbrainAutopilotCommand` recognizes quoted or unquoted `cli.ts` / `cli.js` / `cli.mjs` paths, including spaces and normalized Windows separators, so a live matching autopilot retains even an old lock. Synthetic command-line and lock-decision cases are pinned by `test/autopilot-lock.test.ts`; they are not native Windows process-probe validation. (2) exported `classifyReconnectError(err)` returns `'recoverable' | 'unrecoverable'`; unrecoverable causes `process.exit(0)` so launchd backs off instead of looping `config.database_url undefined`. (3) exported pure `generateLaunchdPlist(wrapperPath, home)` sets `ThrottleInterval=300` so launchd respects the exit-0 backoff. Pinned by `test/autopilot-lock-path.test.ts` + `test/autopilot-reconnect-classifier.test.ts`. targeted-submit loop instead of blanket `autopilot-cycle` dispatch. Each tick: cheap `engine.getHealth()` (single SQL count) + `computeRecommendations()`, then route by shape — `score >= 95 AND no plan AND <60min since last full` → sleep; `score >= 95 AND >=60min` → submit `autopilot-cycle` (60-min floor exercises phase-coupling invariants on healthy brains); `plan <= 3 steps AND est <5min` → submit individual handlers; `plan large OR score < 70` → submit full `autopilot-cycle`. The `gbrain-cycle` lock ensures targeted submissions and the full cycle can't run concurrently. `maxWaiting: 1` per submit closes the queue-fan-out vector. daemon env lane: `writeWrapperScript` additively sources `<gbrainDir>/env` (honors `GBRAIN_HOME`) after the shell profiles with a `set -a` wrap so dotenv-style `KEY=value` lines export too, and creates a fully-commented 0600 template on install (never overwritten, never chmod'd, never removed by uninstall; template excludes `GBRAIN_HOME` — the wrapper bakes it AFTER sourcing). Exported pure `chatBootWarning(chatAvailable, gbrainDir)` derives both remediation paths from the passed dir and prints via `console.log` at daemon boot (stdout is the autopilot.log sink on all four targets; stderr lands in the unsurfaced autopilot.err) using the bare global-model `isAvailable('chat')` probe on purpose (mirrors the bare-gated phases; facts extraction is model-aware and doctor owns it). Install is reload-safe so the warning's re-run-`--install` remediation is true: launchd unloads before load (bare load errors on a loaded agent), systemd `try-restart`s after `enable --now`, cron/container print a residual-process notice instead of auto-killing. Pinned by `test/autopilot-install.test.ts` (16 cases incl. real-bash wrapper execution). Once processing is configuration-blocked, `guardAutopilotEngine` refuses new engine calls (except disconnect), guards transaction callback engines, and rolls back a transaction whose callback finishes after the block; already committed work is not revoked. Pinned by `test/autopilot-transaction-fence.test.ts`. #5195: install, status and uninstall act on one brain's job, named by `resolveAutopilotJob()` in `src/core/autopilot-paths.ts` (default brain: the shared names; any other brain: `<name>-<suffix>` from the random install id in `<brain>/.gbrain/autopilot-install-id`, with move/copy semantics); crontab lines carry `# gbrain-autopilot:<suffix>`; every log sink writes under the brain's home; a pre-#5195 shared job that runs this brain is replaced on install and reported by `--status` as `needs_reinstall: legacy_shared_job`; replacing or removing a job whose wrapper runs another live brain is refused (`autopilot_job_owned_by_other_brain`). Job-definition reads, legacy replacement and the `--status` job report live in `src/commands/autopilot/jobs.ts`. Pinned by `test/autopilot-install-id.test.ts` and `test/e2e/autopilot-multi-brain.serial.test.ts`.- Size ceiling: `scripts/module-size-limits.tsv` (per-change raise history: `git log -p` on that file). The ceiling covers launchd/systemd/cron/container install and reload paths, the wrapper script with its env-file lane and exec guard, status and the self-upgrade channel. `runAutopilot` is a mode table (`AUTOPILOT_MODES`: --install, --uninstall, --status, --pause/--resume; first match wins) that otherwise lazily imports the daemon: `autopilot-daemon.ts` (`runAutopilotDaemon`: boot, lock, managed worker, shutdown and the tick loop over an explicit `AutopilotDaemonState`; steps `probeDatabaseOrReconnect`, `probeNoWorkerPeer`, `runInlineCycle`, `adaptiveInterval`), `autopilot-dispatch.ts` (`dispatchAutopilotTick`: freshness syncs, extract_atoms auto-drain, remediation plan, full-cycle fan-out or targeted submits) and `autopilot-probes.ts` (nightly quality and conversation-parser probes; the quality probe's `resolveNightlyProbeModelRoutesForDaemon` runs `refreshGatewayForJob`'s two gateway calls (inlined: importing `jobs.ts` would grant its flags to `autopilot` in the flag registry) and then reads the probe's model routes from the brain, only on a run past the 24h gate). No injectable single-tick function exists yet (TODOS: testable autopilot tick), so the wiring guards read these modules as source.+ Size ceiling: `scripts/module-size-limits.tsv` (per-change raise history: `git log -p` on that file). The ceiling covers launchd/systemd/cron/container install and reload paths, the wrapper script with its env-file lane and exec guard, status and the self-upgrade channel. `runAutopilot` is a mode table (`AUTOPILOT_MODES`: --install, --uninstall, --status, --pause/--resume; first match wins) that otherwise lazily imports the daemon: `autopilot-daemon.ts` (`runAutopilotDaemon`: boot, lock, managed worker, shutdown and the tick loop over an explicit `AutopilotDaemonState`; steps `probeDatabaseOrReconnect`, `probeNoWorkerPeer`, `runInlineCycle`, `adaptiveInterval`), `autopilot-dispatch.ts` (`dispatchAutopilotTick`: freshness syncs, extract_atoms auto-drain, remediation plan, full-cycle fan-out or targeted submits) and `autopilot-probes.ts` (nightly quality and conversation-parser probes; the quality probe's `resolveNightlyProbeModelRoutesForDaemon` runs `refreshGatewayForJob`'s two gateway calls (inlined: importing `jobs.ts` would grant its flags to `autopilot` in the flag registry) and then reads the probe's model routes from the brain, only on a run past the 24h gate; both probes take their fixtures from `NIGHTLY_PROBE_FIXTURES`, the embedded assets, and the quality probe passes its cap source and `pricing.overrides` as `resolveBudgetPolicy`). No injectable single-tick function exists yet (TODOS: testable autopilot tick), so the wiring guards read these modules as source.- `src/commands/autopilot-dispatch.ts` — one autopilot tick's submissions (`dispatchAutopilotTick`): freshness syncs, the extract_atoms auto-drain, the remediation plan, and full-cycle fan-out or targeted submits. The auto-drain (`dispatchAutoDrain` → `submitAutoDrains`) runs on Postgres only, unless `autopilot.auto_drain.enabled` is `false`, and only when the active pack does not run extract_atoms in the routine cycle. It submits a bounded, protected `extract-atoms-drain` job per source with a backlog under a per-source UTC-day idempotency key, so a structural refusal costs at most one dead job per source per day. The daily cap (`autopilot.auto_drain.max_usd_per_day` / the per-attempt `cycle.extract_atoms.budget_usd` estimate) counts attempts, not jobs (`autoDrainUnitsToday`: a waiting job one, a retried job one per started attempt), and excludes a job whose only attempt dead-lettered with `structural_refusal:`. Checkout-backed and connector sources alternate for free slots, with the next kind persisted in `AUTO_DRAIN_NEXT_KIND_KEY` (`autopilot.auto_drain.next_kind`) across ticks and days; a source whose writer preflight would refuse (`atomDrainOwnerRefusal`) is skipped with a logged reason; connector sources need no `local_path` and submit no `repoPath`. Tests: `test/autopilot-auto-drain*.test.ts`, `test/e2e/autopilot-auto-drain-dispatch.test.ts`.diff --git a/docs/architecture/key-files/commands-3.md b/docs/architecture/key-files/commands-3.mdindex ba8e681e59..bd91ffb139 100644--- a/docs/architecture/key-files/commands-3.md+++ b/docs/architecture/key-files/commands-3.md@@ -9,7 +9,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/commands/eval-compare.ts` — `gbrain eval compare [--suite S] [--modes ...] [--runs ...] [--baseline RUN_ID --candidate RUN_ID] [--draws N] [--seed N] [--md|--json] [--input PATH]`. Reads the run ledger `<repo>/.gbrain-evals/eval-results.jsonl`, keeps the newest record per (suite, mode) and renders the mode table plus any aggregate `metrics`. Paired statistics come only from per-query rows: a record whose `params.output` names its per-question JSONL (`gbrain eval longmemeval --record --output`) is joined with its pair on `question_id`, and each per-query metric both rows carry (`recall_all@k`, `recall_any@k`, `qa_accuracy` from `judge_correct`) gets a paired cluster bootstrap 95% CI, a two-sided sign-flip p-value and a Holm p-value across the report's comparisons (`src/core/eval/paired-bootstrap.ts`). Pairs are every mode pair in a suite, or exactly `--baseline`/`--candidate`. Significant means Holm p ≤ 0.05 and a CI that excludes 0. A `params.output` path must resolve inside the repository root after following symlinks (`pathWithinRoot`); a `..`, absolute or symlinked path outside it is refused and never read. Runs without rows are listed in `paired_unavailable`, and a report with no comparisons says it is aggregate-only; `_meta.methodology` describes only what was computed. Pinned by `test/eval-compare.test.ts`.-- `src/commands/eval-cross-modal.ts` — multi-model quality gate. Three different-provider frontier models score the OUTPUT against the TASK on a 5-dim list. Verdict `pass` (exit 0) / `fail` (exit 1) / `inconclusive` (exit 2; <2/3 model successes). Reuses `src/core/ai/gateway.ts:chat()` so config/auth/aliasing comes from the gateway recipe registry — no parallel provider stack. Self-configures the gateway (`configureGateway(loadConfig() + process.env)`) since the cli.ts dispatch bypasses `connectEngine()`; `opts.useConfiguredGateway` (the nightly probe) keeps the caller's brain-resolved gateway instead. Unkeyed slot defaults take the chat model (`substituteUnavailableDefaultSlots`, #4636; `--slot-*-model` wins). Default cycles 3 in TTY, 1 in non-TTY (partial cost guardrail) via the shared `resolveCycleDefault(explicit, isTty)` in `src/core/eval/cycle-default.ts`; the cost-estimate banner appends `cycleDefaultSuffix(...)` (`for 1 cycle(s) (non-interactive default; --cycles N for more)`) when the value is the silent non-TTY fallback, so the 1-vs-3 difference isn't hidden. Receipts land at `gbrainPath('eval-receipts')/<slug>-<sha8-of-output>.json`. `--batch <jsonl> [--limit N] [--concurrent N] [--max-usd FLOAT] [--yes]` fans out cross-modal scoring across a LongMemEval-shape JSONL; mutually exclusive with `--task` (fail-fast usage error if both set); filters `kind: "by_type_summary"` rows; pre-flight cost estimate refuses if `> --max-usd` without `--yes` (default cap 5.00 USD). Fan-out through the shared `runWithLimit` (re-exported): max N questions in flight × 3 slots = 3N parallel API calls (default `--concurrent 3` → 9). Per-question receipts live in a per-batch tempdir deleted at end of run; the summary inlines per-question verdicts and slot-indexed `slot_scores`, plus the judge `panel` (distinct models and providers of the slots that scored, per-slot `slot_scored_questions`); stderr names a model holding 2+ of them, a slot that scored nothing and a panel under 3 providers, verdict unchanged. Exit precedence (batch-level policy, NOT inherited from aggregate.ts): ERROR > FAIL > INCONCLUSIVE > PASS. DI seam: `runEvalCrossModal(args, opts?: {runEval?: typeof runEval})` mirrors `runEvalLongMemEval(args, {client?})`; tests pass `opts.runEval` to bypass real LLM calls AND, without `useConfiguredGateway`, the gateway availability check. Pinned by `test/eval-cross-modal-batch.test.ts`.+- `src/commands/eval-cross-modal.ts` — multi-model quality gate. Three different-provider models score the OUTPUT against the TASK on 5 dims. Verdict `pass` (exit 0) / `fail` (exit 1) / `inconclusive` (exit 2; <2/3 model successes). Reuses gateway `chat()` (recipe-registry auth/aliasing, no parallel provider stack). Self-configures the gateway from `loadConfig()` + env (cli.ts skips `connectEngine()`); `opts.useConfiguredGateway` (the nightly probe) keeps the caller's brain-resolved gateway instead. Unkeyed slot defaults take the chat model (`substituteUnavailableDefaultSlots`, #4636; `--slot-*-model` wins). Default cycles 3 in TTY, 1 in non-TTY via `resolveCycleDefault` (`src/core/eval/cycle-default.ts`); the cost banner appends `cycleDefaultSuffix(...)` on that silent fallback. Receipts: `gbrainPath('eval-receipts')/<slug>-<sha8>.json`. `--batch <jsonl> [--limit N] [--max-usd F] [--yes]` scores a LongMemEval-shape JSONL; exclusive with `--task` (usage error); filters `kind: "by_type_summary"` rows; pre-flight estimate refuses over `--max-usd` (default 5) without `--yes`. Shared `runWithLimit` fan-out: `--concurrent N` questions × 3 slots (default 3 → 9 calls). Per-question receipts live in a tempdir deleted at run end; the summary inlines per-question verdicts, slot-indexed `slot_scores` and the judge `panel` (distinct models/providers of the slots that scored, per-slot `slot_scored_questions`); stderr names a shared model, a silent slot and a panel under 3 providers, verdict unchanged (the nightly probe, not the batch, turns a collapsed panel inconclusive). Batch exit precedence (not aggregate.ts's): ERROR > FAIL > INCONCLUSIVE > PASS. DI seam: `opts.runEval` (like LongMemEval's `client`) bypasses real LLM calls and, without `useConfiguredGateway`, the gateway availability check. Pinned by `test/eval-cross-modal-batch.test.ts`.- `src/commands/eval-export.ts` — streams `eval_candidates` rows as NDJSON to stdout with `schema_version: 1` prefix on every line. EPIPE-safe, progress heartbeats on stderr, stable id-desc tiebreaker so `--since` windows never dupe/miss rows. D2: `eval` declares `jsonSubcommands` {export, replay, gate: 'ndjson'}; under `--json` each row is a `writeNdjsonLine` and argv errors are one `{status:'error'}` envelope line (`invalid_params`, exit 2).diff --git a/docs/architecture/key-files/core-cycle.md b/docs/architecture/key-files/core-cycle.mdindex d47ec032fc..43c87881b2 100644--- a/docs/architecture/key-files/core-cycle.md+++ b/docs/architecture/key-files/core-cycle.md@@ -28,11 +28,13 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/cycle/link-manifest.ts` — pre-retrieval LINK CANDIDATES manifest. `buildManifestContext(engine, sourceId?)` snapshots the source's slugs + basename index once per phase; `buildLinkManifest(engine, ctx, verdict, basename, {outputRoot, sourceId})` resolves wikilink candidates ZERO-EMBED from the triage verdict's cached entities/segment notes (basename-index exact/slugified matches first, bounded `searchKeyword` FTS second), excludes dream-output prefixes (self-consumption guard), renders `- [[slug]] — <deterministic first-two-sentence one-liner>` under hard caps (20 pages / 2400 chars) with buildTriageMapBlock's injection posture (whitespace-collapse + length caps + a 'data, not instructions' header). Best-effort everywhere — any failure degrades to the manifest-less prompt. Pinned by `test/cycle-link-manifest.test.ts`.-- `src/core/cycle/nightly-probe-adapters.ts` — bridges the autopilot's object-shape `NightlyProbeDeps` to the argv-shape `runEvalLongMemEval` + `runEvalCrossModal` CLI functions. Cross-modal adapter argv MUST include `--output summaryPath` (without it the summary lands at the default receipt path and the adapter reads nothing from `summaryPath`). In-process invocation (NOT subprocess) avoids gbrain-version-drift for source-tree CI. The LongMemEval adapter passes `exitOnError: false`: failures throw into the nightly audit/rate-limit boundary instead of exiting the host process, with resolved chat providers checked before embedding work. The pure builders `buildLongMemEvalProbeCall` / `buildCrossModalProbeCall` carry the brain-resolved `modelRoutes`: the reader as `--model`, the extractor as `RunOpts.extractorModel`, each set judge slot as `--slot-<x>-model`, and `{ useConfiguredGateway: true }` so the batch keeps the daemon's gateway; with no routes both calls are the pre-routing ones. The summary parse keeps `total`, `malformed_count`, `judge_models` (slot order), `panel` (with per-slot `slot_scored_questions`) and every non-passing question as `failures`: scores come from the batch's slot-indexed `slot_scores`, a failing dimension outside `PROBE_QA_DIMENSIONS` is recorded as `unrecognized`, error text is cut at the `--- raw ---` model-output marker, redacted and cut to 200 characters, and a malformed entry yields what can be read instead of a throw. Pinned by `test/cycle/nightly-probe-adapters.test.ts` (incl. the argv-shape guard for the `--output` requirement, the builder cases with and without routes, and the summary parse over a canned summary).+- `src/core/cycle/nightly-probe-adapters.ts` — bridges the autopilot's object-shape `NightlyProbeDeps` to the argv-shape `runEvalLongMemEval` + `runEvalCrossModal` CLI functions. Cross-modal adapter argv MUST include `--output summaryPath` (without it the summary lands at the default receipt path and the adapter reads nothing from `summaryPath`). In-process invocation (NOT subprocess) avoids gbrain-version-drift for source-tree CI. The LongMemEval adapter passes `exitOnError: false`: failures throw into the nightly audit/rate-limit boundary instead of exiting the host process, with resolved chat providers checked before embedding work. The LongMemEval argv always carries `--no-embed-cache` (C-N5: the eval cache swaps the gateway's process-global embed transport, which inside the daemon would catch every other embed call). The pure builders `buildLongMemEvalProbeCall` / `buildCrossModalProbeCall` carry the brain-resolved `modelRoutes`: the reader as `--model`, the extractor as `RunOpts.extractorModel`, each set judge slot as `--slot-<x>-model`, and `{ useConfiguredGateway: true }` so the batch keeps the daemon's gateway; with no routes both calls are the pre-routing ones. The summary parse keeps `total`, `malformed_count`, `judge_models` (slot order), `panel` (with per-slot `slot_scored_questions`) and every non-passing question as `failures`: scores come from the batch's slot-indexed `slot_scores`, a failing dimension outside `PROBE_QA_DIMENSIONS` is recorded as `unrecognized`, error text is cut at the `--- raw ---` model-output marker, redacted and cut to 200 characters, and a malformed entry yields what can be read instead of a throw. Pinned by `test/cycle/nightly-probe-adapters.test.ts` (incl. the argv-shape guard for the `--output` requirement, the builder cases with and without routes, and the summary parse over a canned summary) and `test/nightly-probe-gateway-isolation.test.ts` (the real adapters leave the daemon's embed transport, chat model, provider chat options and env unchanged).++- `src/core/cycle/nightly-probe-fixtures.ts` — `NIGHTLY_PROBE_FIXTURES`: the LongMemEval nightly fixture and the conversation-parser probe's two fixture files, embedded with `import ... with { type: 'file' }` (types in `src/types/jsonl-assets.d.ts`). A source checkout resolves them to `test/fixtures/...`, a compiled binary to a `/$bunfs/` path `readFileSync` reads, so both installs run the probes (#5187, C-N6). Pinned by `test/nightly-probe-compiled-binary.serial.test.ts` (a `bun build --compile` harness copied to an empty dir runs both autopilot probe steps on a hermetic provider, plus a source-mode run).- `src/core/cycle/nightly-probe-routes.ts` — the nightly probe's model routes, resolved against the live brain by the caller that holds the engine (the search-config-snapshot shape). `resolveNightlyProbeModelRoutes(engine)`: reader through `NIGHTLY_PROBE_READER_ROUTE` (`models.eval.longmemeval` → `models.tier.reasoning` → `models.default` → `GBRAIN_MODEL` → key-aware default, the chain `gbrain models` reports for that key), extractor through `NIGHTLY_PROBE_EXTRACTOR_ROUTE` (utility tier), and the optional `models.eval.cross_modal.slot_{a,b,c}` keys (`NIGHTLY_PROBE_SLOT_KEYS`; alias-expanded, blank = unset). Any read failure rethrows as `NightlyProbeModelRoutesError`, whose message names the routes. Consumed by `autopilot-probes.ts` (after a gateway refresh) and `gbrain models`. Pinned by `test/cycle/nightly-probe-routes.test.ts`.-- `src/core/cycle/nightly-quality-probe.ts` + `src/core/audit-quality-probe.ts` + `test/fixtures/longmemeval-nightly.jsonl` + `test/nightly-quality-probe.test.ts` — opt-in nightly cross-modal quality probe. The phase runs `gbrain eval longmemeval --by-type` against the committed 10-question placeholder fixture, pipes output through `gbrain eval cross-modal --batch --max-usd 5 --yes`, and writes one event per run to `~/.gbrain/audit/quality-probe-YYYY-Www.jsonl` (ISO-week-rotated, mirrors `audit-slug-fallback.ts`; honors `GBRAIN_AUDIT_DIR`). Default DISABLED — opt-in via `gbrain config set autopilot.nightly_quality_probe.enabled true` (prevents surprise API spend). 24h rate limit (pure `shouldRunNightly(now, recentEvents, windowMs?)`) skips with audit row `outcome: rate_limited`. Embedding-key short-circuit: longmemeval needs `gateway.embedQuery()`, so the phase exits early with `outcome: no_embedding_key` + stderr warn when no provider configured. Full DI surface via `NightlyProbeDeps` (`isEnabled`, `hasEmbeddingProvider`, `resolveMaxUsd`, `resolveRepoRoot`, optional `resolveSearchConfigSnapshot` and `resolveModelRoutes`, `runLongMemEval`, `runCrossModalBatch`, `now`) so the unit test stubs every external effect. `resolveModelRoutes` runs inside the run's `try` before LongMemEval and its routes reach both adapters; a rejection becomes an `error` audit row naming the model routes and LongMemEval never starts. Rows also carry the evidence behind the verdict (#5506), every field optional so older rows read unchanged (`logQualityProbeEvent` copies them from one explicit list): `reader_model` / `extractor_model` once the routes resolved; `judge_models` in slot order, `judge_scored_questions` per slot, and `distinct_judge_models` / `distinct_judge_providers` over the slots that scored, from a completed batch; on a non-pass row, up to 10 `failures` (failing dimensions with mean, slot-indexed scores and fail reason, or redacted error text) and a one-line digest `detail` counting every question that did not pass, malformed rows included, and naming a slot that scored none. One pricing `withChatCallMeter` meter wraps LongMemEval and the batch, so every row of a run that reached its model calls, a part-way failure included, records `chat_calls`, `chat_cost_usd` (reader, extractor and judges) and `unpriced_chat_calls`; `est_cost_usd` stays the batch's pre-flight estimate for its judge calls only, 0 without a summary. No per-run cap: `--yes` skips the batch's `--max-usd` refusal. The `nightly_quality_probe_health` doctor check (`computeNightlyQualityProbeHealthCheck` in `src/commands/doctor/checks/search-eval.ts`, registered right after `slug_fallback_audit` by `src/commands/doctor/checks/local-audits.ts`) reads last 7 days: SKIPPED when flag off (with enable command); OK when enabled + all PASS; WARN on any FAIL / ERROR / BUDGET_EXCEEDED with per-outcome counts. OK and WARN append the latest row's judge panel and name a slot that scored no question; among the slots that scored, a model holding two or more gets the remedy (three different models in `models.eval.cross_modal.slot_a` / `slot_b` / `slot_c`), fewer than three providers get the not-cross-modal information; a row without valid panel fields keeps the plain message. Pinned by `test/nightly-quality-probe.test.ts`.+- `src/core/cycle/nightly-quality-probe.ts` + `src/core/audit-quality-probe.ts` + `test/fixtures/longmemeval-nightly.jsonl` + `test/nightly-quality-probe.test.ts` — opt-in nightly cross-modal quality probe. The phase runs `gbrain eval longmemeval --by-type` against the committed 10-question placeholder fixture, pipes output through `gbrain eval cross-modal --batch --max-usd 5 --yes`, and writes one event per run to `~/.gbrain/audit/quality-probe-YYYY-Www.jsonl` (ISO-week-rotated, mirrors `audit-slug-fallback.ts`; honors `GBRAIN_AUDIT_DIR`). Default DISABLED — opt-in via `gbrain config set autopilot.nightly_quality_probe.enabled true` (prevents surprise API spend). 24h rate limit (pure `shouldRunNightly(now, recentEvents, windowMs?)`) skips without an audit row. An unreadable fixture writes `outcome: skipped` with `reason: fixture_unavailable` (exit 0, no model call; the row also holds the 24h gate). Embedding-key short-circuit: longmemeval needs `gateway.embedQuery()`, so the phase exits early with `outcome: no_embedding_key` + stderr warn when no provider configured. Full DI surface via `NightlyProbeDeps` (`isEnabled`, `hasEmbeddingProvider`, `resolveMaxUsd`, optional `resolveBudgetPolicy`, `resolveFixturePath` (wins) / `resolveRepoRoot`, `resolveSearchConfigSnapshot` and `resolveModelRoutes`, `runLongMemEval`, `runCrossModalBatch`, `now`) so the unit test stubs every external effect. `resolveModelRoutes` runs inside the run's `try` before LongMemEval and its routes reach both adapters; a rejection becomes an `error` audit row naming the model routes and LongMemEval never starts. Rows also carry the evidence behind the verdict (#5506), every field optional so older rows read unchanged (`logQualityProbeEvent` copies them from one explicit list): `reader_model` / `extractor_model` once the routes resolved; `judge_models` in slot order, `judge_scored_questions` per slot, and `distinct_judge_models` / `distinct_judge_providers` over the slots that scored, from a completed batch; on a non-pass row, up to 10 `failures` (failing dimensions with mean, slot-indexed scores and fail reason, or redacted error text) and a one-line digest `detail` counting every question that did not pass, malformed rows included, and naming a slot that scored none. One pricing `withChatCallMeter` meter wraps LongMemEval and the batch, so every row of a run that reached its model calls, a part-way failure included, records `chat_calls`, `chat_cost_usd` (reader, extractor and judges) and `unpriced_chat_calls`; `est_cost_usd` stays the batch's pre-flight estimate for its judge calls only, 0 without a summary. Run-level budget (CEO B4): one `BudgetTracker` (`withBudgetTracker`) wraps both stages with `max_usd` as the cap (`resolveProbeCap`: a configured value is a `user` cap, else the $5 `default`; `pricing.overrides` from the brain), so every gateway chat/embed call of LongMemEval and the judges reserves first. A refusal is kept by the `ProbeBudgetTracker` subclass even when LongMemEval records it as a per-question error: exhausted after LongMemEval → `budget_exceeded`, no judge call; exhausted while judging → `budget_exceeded` whatever the batch said; a user cap refuses an unpriced model with the shared no_pricing text (`reason: no_pricing`), a default cap warns and runs it. Rows carry `cap_usd` / `cap_source`. A pass or fail from a collapsed panel (one model holding two judged slots, or fewer than two models judged) becomes `inconclusive` with `reason: panel_collapsed`, the batch verdict and the slot-key remedy in `detail` (D12). A non-pass run copies `summary.json` / `lme-output.jsonl` to `<audit dir>/nightly-probe/<ts>/` (newest 7) and names it in `receipt_dir`. The `nightly_quality_probe_health` doctor check (`computeNightlyQualityProbeHealthCheck` in `src/commands/doctor/checks/search-eval.ts`, registered right after `slug_fallback_audit` by `src/commands/doctor/checks/local-audits.ts`) reads last 7 days: SKIPPED when flag off (with enable command); OK when enabled + all PASS; WARN on any non-PASS outcome with per-outcome counts (`skipped=N` appended when a run skipped), so a skipped run is never OK. OK and WARN append the latest row's judge panel and name a slot that scored no question; among the slots that scored, a model holding two or more gets the remedy (three different models in `models.eval.cross_modal.slot_a` / `slot_b` / `slot_c`), fewer than three providers get the not-cross-modal information; a row without valid panel fields keeps the plain message. Pinned by `test/nightly-quality-probe.test.ts`.- `src/core/cycle/dream-breaker.ts` — dream paid-loop circuit breaker. `countDeadDreamSubmissions` is the one counting rule shared by synthesize, patterns, `gbrain dream reset-key` and the `dream_paid_loop` doctor check: dead `subagent` rows finished in the last 24 h (partial index `idx_minion_jobs_dead_subagent_finished`, migration 173), keyed by the live or released idempotency key with the `:c<i>of<n>` chunk suffix stripped, counted as distinct queues (one per run), ignoring deaths before the key's persisted reset (`dream.breaker.resets` config JSON, database clock). A key at `dream.breaker.max_dead_submissions` (default 3; 0 disables) is refused before synthesis submission; a failed count leaves the breaker off for that run with a warning. Completed jobs, including legitimate zero-write completions, never count. Growing transcripts change their content-hashed key and unkeyed patterns runs are not covered. Contained cycle-phase failures after paid model calls (`recordContainedPaidFailure`, `dream.breaker.contained_failures` config JSON, 24 h window, database clock) are counted under `dream:phase:<phase>:<source>` keys; the breaker never refuses those phases, doctor reports them and `gbrain dream reset-key` clears them. Tests: `test/dream-breaker.test.ts`, `test/cycle-synthesize-breaker.test.ts`, `test/e2e/dream-breaker-postgres.test.ts`.diff --git a/docs/architecture/key-files/core-services-2.md b/docs/architecture/key-files/core-services-2.mdindex 797e47b70e..a02d2e6814 100644--- a/docs/architecture/key-files/core-services-2.md+++ b/docs/architecture/key-files/core-services-2.md@@ -3,7 +3,7 @@[Subsystem index](../KEY_FILES.md). Read only the entries relevant to your change.Current behavior and load-bearing invariants; history belongs in Git and CHANGELOG.-- `src/core/conversation-parser/` — 19-pattern built-in chat-format registry + opt-in LLM fallback. Modules: `types.ts` (PatternEntry + ParseResult + DateContext + CaptureMap + TimezonePolicy), `builtins.ts` (19 hand-vetted patterns sourced from public format docs — iMessage/Slack, Telegram bracket + text-export, bold-paren-time, bold-time-dash, bold-name-no-time, chatgpt-export-you-chatgpt, Discord classic + export, WhatsApp ISO + US, Signal, Matrix/Element, IRC classic + weechat, Teams export, markdown-heading-turn; module-load validation runs every `test_positive[]` + `test_negative[]` sample at startup so a typo in any built-in regex makes gbrain refuse to start; `DEFAULT_SPEAKER_CLEAN` exported as a module-level default), `parse.ts` (orchestrator with pattern-priority scoring across the first 10 lines + date derivation chain `explicit > frontmatter.date > effective_date > '1970-01-01'` + multi-line continuation + timezone warning; also populates `ParseResult.unrecognized_headings` — when the WINNING pattern is heading-anchored, heading-shaped lines whose label is outside the pattern's speaker set FOLD into the previous turn's body (or drop before the first anchor) while the parse still returns `regex_match`, silently crediting one speaker with another's words; detection is diagnostic-only and unconditional (not behind `opts.diagnostic` — the extractor's decline gate depends on it), fence-aware (a fence closes only on ITS OWN marker; an unclosed fence suppresses detection below it), labels deduped/capped at 10 entries ≤48 chars, undefined when empty so healthy-page JSON stays byte-identical; `gbrain conversation-parser scan` surfaces the field in both human and JSON output; `applyPattern` never DROPS a matched anchor whose date it cannot reconstruct (a localized month name, malformed digits) — dropping it would fold that speaker's body into the previous turn on a multi_line pattern, so the message opens anyway, inheriting the previous anchor's timestamp (page fallback date at midnight for the first), and the count surfaces as `ParseResult.date_fallback_count`, undefined when zero), `llm-base.ts` (shared `runLlmCall<T>` with content-hash cache in-process + DB-persistent via migration v97 + 4-strategy JSON repair + Anthropic-key probe; fallback is a thin wrapper), `llm-fallback.ts` (opt-IN; NO regex inference + NO persistence), `eval.ts` (`scoreFixture` + `aggregateScores` + `parseFixtureJsonl` for the fixture-corpus CI gate), `nightly-probe.ts` (DI-stubbed; mode-gated default tokenmax=ON, conservative/balanced opt-in; adversarial false-positive detection). Pattern `bold-name-no-time` (regex `/^\*\*(?!\[)(.+?):\*\*\s*(.*)$/`, ordered after the time-bearing bold patterns) parses `**Speaker:** text` with NO per-line timestamp (Circleback/Granola/Zoom), anchoring every message at `T00:00:00Z` of the frontmatter date (line order preserves sequence, same no-time convention as `irc-classic`); the `(?!\[)` lookahead rejects telegram-bracket `**[18:37] Name:**`; non-shadow is the colon-INSIDE-bold regex (NOT declaration order — `parse.ts` scores every candidate independently, order is only the tie-break). Because `**Label:** text` is a common prose idiom, the pattern sets optional `PatternEntry.score_full_body: true` so `parse.ts` recomputes the winner's acceptance score over the FULL body before the `SCORING_MIN_ACCEPTANCE` floor, keeping a bold-label notes page at `no_match`. Pattern `chatgpt-export-you-chatgpt` (regex `/^\*\*(You|ChatGPT):\*\*\s*(.*)$/`, declared just before `bold-name-no-time` so it wins the score tie on the two literal ChatGPT-export labels) parses ChatGPT's web-export → Markdown shape, where each turn's `**You:**` / `**ChatGPT:**` anchor is followed by a blank line and a multi-paragraph reply; `bold-name-no-time` alone cannot absorb that shape (`multi_line: false` scores a long reply's density near zero and falls below `SCORING_MIN_ACCEPTANCE`), so this pattern sets `multi_line: true` + `score_continuations_as_body: true` (excludes non-`**`-prefixed reply lines from the density denominator) + `score_full_body: true`. The speaker capture is a closed two-value enumeration (`You` or `ChatGPT` exactly, never an arbitrary `(.+?)` label), so it cannot reopen `bold-name-no-time`'s BROAD-REGEX GUARD against notes pages. Because a bare `**You:**`/`**ChatGPT:**` heading is plausible in prose ABOUT ChatGPT, the pattern also sets the optional `PatternEntry.score_continuations_min_distinct_speakers: 2`: `scoreFromLines` only grants the continuation-density-exclusion score when the anchor lines that fully match `regex` collectively capture at least that many DISTINCT `speaker_group` values, so a page with only one role falls back to the ordinary flat-density score. It ALSO sets `PatternEntry.score_continuations_max_preamble_lines: 5`, because one genuine pair embedded deep in an unrelated long document would otherwise pass: `scoreFromLines` tracks the index of the FIRST fully-matching anchor line and only grants the immunity when that index is at or before the bound (a short title preamble is tolerated). Pattern `bold-paren-time` parses `**Speaker** (HH:MM): text` and `(HH:MM:SS)` (date_source: frontmatter). Fallback gates: `SCORING_HEAD_TRIGGER_THRESHOLD = 0.3` triggers a full-body re-score when the head pass scores below that; `SCORING_MIN_ACCEPTANCE = 0.05` blocks essay false-positives. Exported `scorePatternFull(body, entry)`; private `getNonBlankLines(body, headCap?)` + `scoreFromLines(lines, entry)` DRY the quick_reject+regex loop. CLI surfaces at `src/commands/eval-conversation-parser.ts` (`gbrain eval conversation-parser <fixture.jsonl>` exit 0/1/2, wired into `bun run verify` via `check:conversation-parser`) and `src/commands/conversation-parser.ts` (`scan <slug>` debug, `list-builtins`, `validate <file>`). Doctor checks: `conversation_format_coverage`, `progressive_batch_audit_health`, `conversation_parser_probe_health`. Pinned by `test/conversation-parser/{parse,llm-base,llm-fallback,nightly-probe}.test.ts` + the 27-case baseline at `test/extract-conversation-facts.test.ts` (back-compat invariant). Migration v97 (`conversation_parser_llm_cache_table`). Fixtures at `test/fixtures/conversation-formats/{imessage,imessage-time-only-12h,telegram-bracket,whatsapp-iso,whatsapp-us,signal-export,irc-classic,irc-weechat,matrix-element,teams-export,all,adversarial,bold-name-no-time,bold-time-dash,chatgpt-export-you-chatgpt}.jsonl` with `scripts/check-fixture-privacy.sh` banning real-name leaks. Maintainer guidance: [conversation parser patterns](../conversation-parser-patterns.md).+- `src/core/conversation-parser/` — 19-pattern built-in chat-format registry + opt-in LLM fallback. Modules: `types.ts` (PatternEntry + ParseResult + DateContext + CaptureMap + TimezonePolicy), `builtins.ts` (19 hand-vetted patterns sourced from public format docs — iMessage/Slack, Telegram bracket + text-export, bold-paren-time, bold-time-dash, bold-name-no-time, chatgpt-export-you-chatgpt, Discord classic + export, WhatsApp ISO + US, Signal, Matrix/Element, IRC classic + weechat, Teams export, markdown-heading-turn; module-load validation runs every `test_positive[]` + `test_negative[]` sample at startup so a typo in any built-in regex makes gbrain refuse to start; `DEFAULT_SPEAKER_CLEAN` exported as a module-level default), `parse.ts` (orchestrator with pattern-priority scoring across the first 10 lines + date derivation chain `explicit > frontmatter.date > effective_date > '1970-01-01'` + multi-line continuation + timezone warning; also populates `ParseResult.unrecognized_headings` — when the WINNING pattern is heading-anchored, heading-shaped lines whose label is outside the pattern's speaker set FOLD into the previous turn's body (or drop before the first anchor) while the parse still returns `regex_match`, silently crediting one speaker with another's words; detection is diagnostic-only and unconditional (not behind `opts.diagnostic` — the extractor's decline gate depends on it), fence-aware (a fence closes only on ITS OWN marker; an unclosed fence suppresses detection below it), labels deduped/capped at 10 entries ≤48 chars, undefined when empty so healthy-page JSON stays byte-identical; `gbrain conversation-parser scan` surfaces the field in both human and JSON output; `applyPattern` never DROPS a matched anchor whose date it cannot reconstruct (a localized month name, malformed digits) — dropping it would fold that speaker's body into the previous turn on a multi_line pattern, so the message opens anyway, inheriting the previous anchor's timestamp (page fallback date at midnight for the first), and the count surfaces as `ParseResult.date_fallback_count`, undefined when zero), `llm-base.ts` (shared `runLlmCall<T>` with content-hash cache in-process + DB-persistent via migration v97 + 4-strategy JSON repair + Anthropic-key probe; fallback is a thin wrapper), `llm-fallback.ts` (opt-IN; NO regex inference + NO persistence), `eval.ts` (`scoreFixture` + `aggregateScores` + `parseFixtureJsonl` for the fixture-corpus CI gate), `nightly-probe.ts` (DI-stubbed; mode-gated default tokenmax=ON, conservative/balanced opt-in; adversarial false-positive detection; an unreadable fixture returns `skipped` with `fixture_unavailable`, which the autopilot wiring audits, and the wiring reads the embedded fixtures from `cycle/nightly-probe-fixtures.ts`). Pattern `bold-name-no-time` (regex `/^\*\*(?!\[)(.+?):\*\*\s*(.*)$/`, ordered after the time-bearing bold patterns) parses `**Speaker:** text` with NO per-line timestamp (Circleback/Granola/Zoom), anchoring every message at `T00:00:00Z` of the frontmatter date (line order preserves sequence, same no-time convention as `irc-classic`); the `(?!\[)` lookahead rejects telegram-bracket `**[18:37] Name:**`; non-shadow is the colon-INSIDE-bold regex (NOT declaration order — `parse.ts` scores every candidate independently, order is only the tie-break). Because `**Label:** text` is a common prose idiom, the pattern sets optional `PatternEntry.score_full_body: true` so `parse.ts` recomputes the winner's acceptance score over the FULL body before the `SCORING_MIN_ACCEPTANCE` floor, keeping a bold-label notes page at `no_match`. Pattern `chatgpt-export-you-chatgpt` (regex `/^\*\*(You|ChatGPT):\*\*\s*(.*)$/`, declared just before `bold-name-no-time` so it wins the score tie on the two literal ChatGPT-export labels) parses ChatGPT's web-export → Markdown shape, where each turn's `**You:**` / `**ChatGPT:**` anchor is followed by a blank line and a multi-paragraph reply; `bold-name-no-time` alone cannot absorb that shape (`multi_line: false` scores a long reply's density near zero and falls below `SCORING_MIN_ACCEPTANCE`), so this pattern sets `multi_line: true` + `score_continuations_as_body: true` (excludes non-`**`-prefixed reply lines from the density denominator) + `score_full_body: true`. The speaker capture is a closed two-value enumeration (`You` or `ChatGPT` exactly, never an arbitrary `(.+?)` label), so it cannot reopen `bold-name-no-time`'s BROAD-REGEX GUARD against notes pages. Because a bare `**You:**`/`**ChatGPT:**` heading is plausible in prose ABOUT ChatGPT, the pattern also sets the optional `PatternEntry.score_continuations_min_distinct_speakers: 2`: `scoreFromLines` only grants the continuation-density-exclusion score when the anchor lines that fully match `regex` collectively capture at least that many DISTINCT `speaker_group` values, so a page with only one role falls back to the ordinary flat-density score. It ALSO sets `PatternEntry.score_continuations_max_preamble_lines: 5`, because one genuine pair embedded deep in an unrelated long document would otherwise pass: `scoreFromLines` tracks the index of the FIRST fully-matching anchor line and only grants the immunity when that index is at or before the bound (a short title preamble is tolerated). Pattern `bold-paren-time` parses `**Speaker** (HH:MM): text` and `(HH:MM:SS)` (date_source: frontmatter). Fallback gates: `SCORING_HEAD_TRIGGER_THRESHOLD = 0.3` triggers a full-body re-score when the head pass scores below that; `SCORING_MIN_ACCEPTANCE = 0.05` blocks essay false-positives. Exported `scorePatternFull(body, entry)`; private `getNonBlankLines(body, headCap?)` + `scoreFromLines(lines, entry)` DRY the quick_reject+regex loop. CLI surfaces at `src/commands/eval-conversation-parser.ts` (`gbrain eval conversation-parser <fixture.jsonl>` exit 0/1/2, wired into `bun run verify` via `check:conversation-parser`) and `src/commands/conversation-parser.ts` (`scan <slug>` debug, `list-builtins`, `validate <file>`). Doctor checks: `conversation_format_coverage`, `progressive_batch_audit_health`, `conversation_parser_probe_health`. Pinned by `test/conversation-parser/{parse,llm-base,llm-fallback,nightly-probe}.test.ts` + the 27-case baseline at `test/extract-conversation-facts.test.ts` (back-compat invariant). Migration v97 (`conversation_parser_llm_cache_table`). Fixtures at `test/fixtures/conversation-formats/{imessage,imessage-time-only-12h,telegram-bracket,whatsapp-iso,whatsapp-us,signal-export,irc-classic,irc-weechat,matrix-element,teams-export,all,adversarial,bold-name-no-time,bold-time-dash,chatgpt-export-you-chatgpt}.jsonl` with `scripts/check-fixture-privacy.sh` banning real-name leaks. Maintainer guidance: [conversation parser patterns](../conversation-parser-patterns.md).- `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`.diff --git a/docs/eval-bench.md b/docs/eval-bench.mdindex ba9129ba8c..de44e1e2fe 100644--- a/docs/eval-bench.md+++ b/docs/eval-bench.md@@ -1152,6 +1152,15 @@ callable in isolation, and the test harness exercises it via DI stubs.bun test test/nightly-quality-probe.test.ts```+**What it measures.** The probe is a synthetic smoke test, not a health+score for your brain. It answers the 10 committed questions in+`test/fixtures/longmemeval-nightly.jsonl` from an isolated in-memory+benchmark brain, with your search mode, reranker and model routes, and has+three judges grade the answers. A PASS says the retrieval-plus-answer+pipeline and the judges work end to end tonight; it says nothing about the+pages in your own brain. The fixture is embedded in the gbrain binary, so+source checkouts and compiled installs run the same probe.+#### Model routesThe probe runs inside the autopilot daemon, which holds your brain. Right@@ -1206,7 +1215,7 @@ and checks the result with `gbrain models`).Observability:- `~/.gbrain/audit/quality-probe-YYYY-Www.jsonl` — one event per run withoutcome (pass / fail / inconclusive / error / budget_exceeded /- rate_limited / no_embedding_key), pass/fail/inconclusive/error counts,+ no_embedding_key / skipped), pass/fail/inconclusive/error counts,est_cost_usd, fixture_sha8. ISO-week rotation (mirrors slug-fallbackaudit). The row also carries the evidence behind its verdict, in theoptional fields below (rows written by older releases lack them and@@ -1215,8 +1224,11 @@ Observability:- SKIPPED (disabled) — with paste-ready enable command.- OK (enabled, no events yet) — autopilot hasn't fired its first run.- OK (last 7d all PASS) — with timestamp of latest run.- - WARN — any FAIL / ERROR / BUDGET_EXCEEDED in the window, with outcome- counts and the latest run's reason (the digest in `detail`).+ - WARN — any run that did not pass in the window (FAIL, ERROR,+ INCONCLUSIVE, BUDGET_EXCEEDED, NO_EMBEDDING_KEY or SKIPPED), with+ outcome counts and the latest run's reason (the digest in `detail`).+ SKIPPED means the probe could not run (its fixture was unreadable), so+ it gave no quality signal; it is never reported as OK.- The OK and WARN messages name the latest run's judge panel and anyslot that scored no question (it did not judge). When one model holdstwo or more of the slots that judged, its votes count more than once:@@ -1225,6 +1237,18 @@ Observability:is enough, for example three claude-cli models). Judges from fewerthan three providers are reported as not cross-modal, as information;the check's status does not change.+- **Collapsed panel → inconclusive.** When one model holds two or more of+ the slots that judged (for example the sonnet/opus/sonnet panel an+ Anthropic-only brain gets from the #4636 substitute), or fewer than two+ models judged, the run is `inconclusive` with `reason: panel_collapsed`,+ whatever the batch's verdict was: one model voting twice is not a cross+ check. The `detail` names the model and slots, keeps the batch verdict,+ and gives the next step (`gbrain config set+ models.eval.cross_modal.slot_a <model>`, and `slot_b`, `slot_c`).+- **Receipts.** A run that did not pass keeps its batch summary and+ LongMemEval output under `~/.gbrain/audit/nightly-probe/<timestamp>/`+ (newest 7 runs) and names the directory in `receipt_dir`. The fixture is+ synthetic, so receipts hold no user data.| Audit field | Written on | Meaning ||---|---|---|@@ -1235,6 +1259,9 @@ Observability:| `failures` | fail, inconclusive and error rows from a batch | Up to 10 non-passing questions in summary order: `question_id`, `verdict`, then either `dimensions` (each failing dimension with its `mean`, its per-slot `scores` in slot order, `null` for a slot that gave no score, and its `fail_reason`, `mean_below_7` or `min_below_5`; a dimension name the probe does not ask for reads `unrecognized`) or the `error` text, cut before any raw model output, redacted and cut to 200 characters. An inconclusive question lists the `slot_errors` of the judges that did not score. || `detail` | the same rows | A one-line digest, for example `6/10 questions did not pass (directness mean_below_7 x6); judges: 2 distinct models from 1 provider`. It counts every question that did not pass, also past the 10 listed, and malformed batch rows (`malformed xN`), and names a slot that scored no question. || `chat_calls`, `chat_cost_usd`, `unpriced_chat_calls` | rows of a run that reached its model calls, including a run that failed part-way | The run's metered chat spend: successful chat calls (reader, extractor, judges), their USD cost from canonical pricing, and the calls with no price on file, whose cost is unknown and never counted as 0. |+| `cap_usd`, `cap_source` | rows of a run that reached its model calls | The run-level cap and where it came from: `user` (a configured `max_usd`) or `default` ($5). |+| `reason` | skipped, collapsed-panel inconclusive and budget_exceeded rows | `fixture_unavailable`, `panel_collapsed`, or the budget's `cost` / `runtime` / `no_pricing`. |+| `receipt_dir` | rows of a run that did not pass and got as far as writing output | Where its `summary.json` and `lme-output.jsonl` were kept. |**Say to your agent:** *"Why did last night's quality probe fail?"* (theagent reads the `detail` and `failures` of the latest@@ -1257,10 +1284,18 @@ Cost: two numbers that cover different calls, so neither bounds the other.estimated $2.80; with unpriced judges and a priced reader the meteredcost can exceed the estimate.-No per-run cap applies to the probe: it passes `--yes`, which skips the-batch's `--max-usd` refusal, so `autopilot.nightly_quality_probe.max_usd`-does not bound its spend. The opt-in default keeps the spend from starting-unasked; watch `chat_cost_usd` on the audit rows.+**Run cap.** `autopilot.nightly_quality_probe.max_usd` (default $5) caps+every paid call of a run as one budget: the LongMemEval reader, extractor+and query embeddings, then the judges. Each call is reserved against the cap+before it is sent. When the cap runs out the run stops, makes no further+paid call (no judging when LongMemEval used it up), and records+`budget_exceeded` with the reason, never `fail`. Pricing follows the+spend-control rule: under the default cap a model with no price on file+warns and runs (counted in `unpriced_chat_calls`); once you set `max_usd`+yourself, an unpriced model is refused with the `no_pricing` guidance, which+names the `gbrain pricing set` command that registers its rate (or add it to+`pricing.overrides`). A typical run on priced API models costs well under a+dollar of metered chat (`chat_cost_usd`), plus query embeddings.## Local benchmark scriptsdiff --git a/docs/wave9/lane-c.md b/docs/wave9/lane-c.mdnew file mode 100644index 0000000000..075ca74d7d--- /dev/null+++ b/docs/wave9/lane-c.md@@ -0,0 +1,24 @@+# Wave 9 lane C: the nightly quality probe tells the truth++For the integrator: CHANGELOG lines and upgrade-note rows for this lane. No+version header, no migration.++## CHANGELOG lines++- **The nightly quality probe uses your models.** The reader follows `models.eval.longmemeval` and then the reasoning tier, the trajectory extractor follows the utility tier, and the three judges follow the new `models.eval.cross_modal.slot_a` / `slot_b` / `slot_c` keys. Before, the probe ignored every brain-side model setting and paid for `anthropic:claude-sonnet-4-6`, `claude-haiku-4-5` and `claude-opus-4-7` even on brains routed to `claude-cli`. `gbrain models` now prints the probe's routes under "Nightly quality probe". (#5872, contributed by @andreineacsu, #6005)+- **`autopilot.nightly_quality_probe.max_usd` is a real cap now.** One budget covers every paid call of a run: the LongMemEval reader, extractor and query embeddings, then the judges. Before, the LongMemEval stage ran uncapped and the judges' cap was skipped by `--yes`. A run that hits the cap stops, makes no further paid call and records `budget_exceeded`, never `fail`. Under the default $5 cap a model with no price on file warns and runs; once you set `max_usd`, it is refused with the `no_pricing` guidance (`gbrain pricing set ...`).+- **A judge panel that is one model voting twice no longer reports pass or fail.** When one model holds two of the slots that judged (the sonnet/opus/sonnet panel an Anthropic-only brain got by default), or fewer than two models judged, the run is `inconclusive` with `reason: panel_collapsed` and the slot-key command to fix it. (#5506)+- **A probe run that did not pass keeps its evidence.** The audit row names the judge panel, each failing question with per-judge scores, the reader and extractor, metered chat spend (`chat_cost_usd`) and the run cap; the batch summary and LongMemEval output are kept under `~/.gbrain/audit/nightly-probe/<timestamp>/` (newest 7). (#5506, contributed by @andreineacsu, #6005)+- **Compiled installs run both nightly probes.** The quality probe and the conversation-parser probe now carry their fixtures inside the binary. Before, the quality probe failed every night with `nightly fixture not found at <your brain repo>/test/fixtures/...` and the parser probe skipped silently while doctor said ok. If a fixture is ever unreadable, the run records `skipped` with the reason and doctor warns instead of reporting ok. (#5187, C-N6; skip reporting reworked from @Masashi-Ono0611's #5257)+- **The probe no longer disturbs the autopilot daemon's AI gateway.** It keeps the daemon's brain-resolved gateway and no longer swaps the process-wide embedding transport for its run (the LongMemEval embedding cache is off for the probe). (C-N5)+- **Docs:** the probe is described as what it is, a synthetic 10-question smoke test of retrieval, answering and judging, not a health score for your brain; the cost section now uses metered spend.++## Upgrade-note rows (behavior changes)++| Change | Who notices | What to do |+|---|---|---|+| The nightly probe's reader, extractor and judges follow your brain's model settings | Brains with the probe enabled and `models.tier.*` / `models.eval.longmemeval` set | Nothing; check the routes with `gbrain models`. To keep the judges off metered APIs, set `models.eval.cross_modal.slot_a/b/c` to three different models. |+| A collapsed judge panel reports `inconclusive` instead of pass/fail | Anthropic-only brains with no slot keys (panel sonnet/opus/sonnet) | `gbrain config set models.eval.cross_modal.slot_a <model>` (and `slot_b`, `slot_c`) with three different models; one provider is enough. |+| `max_usd` caps the whole run, and a set value refuses unpriced models | Brains that set `autopilot.nightly_quality_probe.max_usd` and route the probe through a model with no price on file (for example a local or proxy model with no `pricing.overrides` entry) | Register the rate with the `gbrain pricing set` command the audit row names, or unset `max_usd` to go back to the warn-and-run default cap. A `max_usd` of 0 now means a $0 cap. |+| Compiled installs start running the nightly probes | Binary installs with the quality probe enabled, or `search.mode=tokenmax` (parser probe default-on) | Nothing; the first real run happens within 24h. Doctor's `nightly_quality_probe_health` / `conversation_parser_probe_health` show the result. |+| New audit outcome `skipped` | Anyone reading `quality-probe-*.jsonl` / `parser-probe-*.jsonl` | Treat it as "no signal": the probe could not run; the row's `reason`/`detail` says why. |