Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
feat(remediation): compose spends:'llm' repair steps with the doctor --max-usd budget (#6188)
garrytan06decd44e79c
diff --git a/docs/architecture/key-files/commands-2.md b/docs/architecture/key-files/commands-2.mdindex 4d26a1569a..bd19d11244 100644--- a/docs/architecture/key-files/commands-2.md+++ b/docs/architecture/key-files/commands-2.md@@ -24,7 +24,7 @@ Doctor's embedding-dimension warning treats existing chunks as existing data eve- `src/commands/doctor/checks/fence-integrity.ts` — `fence_integrity` (#6188, BRAIN, registered before `search_mode`). Each run advances the fence census within `GBRAIN_DOCTOR_FENCE_TIMEOUT_MS` (default 10 s), then reports per source the malformed facts/takes fences still waiting, each counted once (held file, stored page, unsynced file) and split by planned tier (deterministic, resolver, llm, manual), the oldest hold's age, the 7-day `fences_normalized` trend with top writers (warns at `FENCE_NORMALIZATION_WARN_7D` = 20), and the model-repair caps with today's ledger spend. `ok` only when nothing waits, every source's census is complete and no source reaches the trend threshold; a partial census warns with the resume command. The fix is the PR1/PR2 step: `gbrain sources status <id>` for holds (then edit the fence and `gbrain sync --source <id> --no-pull`), `gbrain get --source <id> -- <slug>` and a fresh put_page for stored pages, `gbrain sync --source <id> --no-pull` for unsynced files. Location only. Test: `test/doctor-fence-integrity.test.ts`.- `src/commands/doctor/wave-checks.ts` — `WAVE_CHECKS`, the table of managed-persistence wave checks (stable id, `resolution` `repair`/`operator`/`unsupported`, count-free remote `impact`, operator `instruction`, `count` for banners, `registration` inline-in-doctor.ts or from this table). `runWaveChecks` turns a throwing check into an `unknown` finding; `checkHealthUnknown` reads `details.health === 'unknown'`. `remoteWaveHandoff` returns one line per remotely offered check with `details.host_action` {`check_id`, `state` ok/action_required/unknown, `preview_command`} and no paths, rows, SQL, emails or installation ids. Consumers: doctor.ts, `report-remote.ts`, `remediate.ts`, `upgrade-banner.ts`. Tests: `test/recovery-layer.test.ts`, `test/e2e/recovery-layer.test.ts`.-- `src/commands/doctor/remediate.ts` — the `--remediation-plan` / `--remediate` CLI shell (re-exported from doctor.ts): per-step `command` (`gbrain jobs submit …` for job steps, `gbrain repair <kind> --apply` for repair steps), `combinedRemediateCommand` (with repair steps it ends `--expect <plan_hash>`, the same hash `--remediation-plan --json` reports as `plan_hash`), a `Repair kinds whose preview failed` block for `repair_preview_failures` (each `{kind, code, message, why, fix}`; such a kind is not planned, so a plan approved while it failed refuses `preview_changed` once it succeeds), `REMEDIATE_HELP`, `--include-repairs`/`--no-embed`/`--resume` handling, the resume command after budget exhaustion (repeats the recorded cap and consent), `classifyWaveFindings` (cleared / pending / consent_required / operator_required / explicit_kind_required / unsupported, from wave checks run before and after; `details.partial` is pending; an explicit-only kind's preview gets `--source <id>` via `findingSource` when the finding names one source; `--remediation-plan` runs the wave checks too and reports the same classification as `findings`) and `remediationExitStatus` (0 when no repairable finding remains and no step failed; 1 otherwise, on budget exhaustion or when a repair preview failed; 2 when the target is unreachable with no repair step, or a resume is refused), set through `setCliExitVerdict`; 3 when consent is required), set through `setCliExitVerdict`. Consent (agent operator wave C1) lives in `doctor/remediate-consent.ts`: the CLI connects probe-only (no migrations) and computes the plan; when anything would run it calls `requireConsent` (effects `paid`, plus `destructive` with `--include-repairs`, bound to a `plan_hash` over the brain id, job step ids, repair kinds and pending counts, and the parameters, and persisted with the approval). Non-TTY without authorization changes nothing and exits 3 with the consent payload; `--json` never implies consent; `--yes` without `--max-usd` runs under the derived cap (estimate ×1.5, floor $0.25; the default cap when unpriced), and derived-cap exhaustion prints the `--max-usd` resume command. Startup (migrations) completes only after consent. A `--resume` is bound by its checkpoint manifest, not a new plan hash. Pinned by `test/doctor-remediate-consent.test.ts`.+- `src/commands/doctor/remediate.ts` — the `--remediation-plan` / `--remediate` CLI shell (re-exported from doctor.ts): per-step `command` (`gbrain jobs submit …` for job steps, `gbrain repair <kind> --apply` for repair steps; a repair step with `llm_usd` names its paid chat model spend, and any embedding part, in its fix and plan line), `combinedRemediateCommand` (with repair steps it ends `--expect <plan_hash>`, the same hash `--remediation-plan --json` reports as `plan_hash`), a `Repair kinds whose preview failed` block for `repair_preview_failures` (each `{kind, code, message, why, fix}`; such a kind is not planned, so a plan approved while it failed refuses `preview_changed` once it succeeds), `REMEDIATE_HELP`, `--include-repairs`/`--no-embed`/`--resume` handling, the resume command after budget exhaustion (repeats the recorded cap and consent), `classifyWaveFindings` (cleared / pending / consent_required / operator_required / explicit_kind_required / unsupported, from wave checks run before and after; `details.partial` is pending; an explicit-only kind's preview gets `--source <id>` via `findingSource` when the finding names one source; `--remediation-plan` runs the wave checks too and reports the same classification as `findings`) and `remediationExitStatus` (0 when no repairable finding remains and no step failed; 1 otherwise, on budget exhaustion or when a repair preview failed; 2 when the target is unreachable with no repair step, or a resume is refused), set through `setCliExitVerdict`; 3 when consent is required), set through `setCliExitVerdict`. Consent (agent operator wave C1) lives in `doctor/remediate-consent.ts`: the CLI connects probe-only (no migrations) and computes the plan; when anything would run it calls `requireConsent` (effects `paid`, plus `destructive` with `--include-repairs`, bound to a `plan_hash` over the brain id, job step ids, repair kinds and pending counts, and the parameters, and persisted with the approval). Non-TTY without authorization changes nothing and exits 3 with the consent payload; `--json` never implies consent; `--yes` without `--max-usd` runs under the derived cap (estimate ×1.5, floor $0.25; the default cap when unpriced), and derived-cap exhaustion prints the `--max-usd` resume command. Startup (migrations) completes only after consent. A `--resume` is bound by its checkpoint manifest, not a new plan hash. Pinned by `test/doctor-remediate-consent.test.ts`.- `src/commands/doctor/checks/global-maintenance-timeouts.ts` — `global_maintenance_timeouts` (#4578): warns when the last three finished `autopilot-global-maintenance` jobs died at their deadline, or one phase was running in three consecutive job deaths (read from config `autopilot.global_maintenance.progress`). Details carry `code`, `cause`, `fix` (`gbrain dream --phase <name>`, else the deadline config key) and the `docs/guides/troubleshooting.md#global-maintenance-timeouts` anchor. Pinned by `test/autopilot-global-maintenance-resume-4578.test.ts`.- `src/commands/doctor/checks/legacy-job-authority.ts` — `legacy_job_authority` (#5157): the claim gate's population (`UNREVIEWED_LIVE_JOBS_WHERE`), split into authorizable SQL NULL and unsupported rows; terminal keyed SQL NULL rows are reported as `ok`. Live rows `fail` with the filled recovery. `legacyJobAuthorityBannerNote` feeds the banner. The same check counts queued paid jobs by spend basis (`details.queued_spend`) and warns, with the read-only fix `gbrain jobs list --status waiting --json`, when spend-authorized rows wait over 10 minutes while registered workers run (an un-upgraded worker is fenced off them); `legacyDefaultSpendBannerNote` names queued `legacy_default` rows after an upgrade. Tests: `test/doctor-legacy-job-authority.test.ts`, `test/doctor-queued-spend.test.ts`.diff --git a/docs/architecture/key-files/core-utilities-1.md b/docs/architecture/key-files/core-utilities-1.mdindex 350bc18048..e18be6a6e3 100644--- a/docs/architecture/key-files/core-utilities-1.md+++ b/docs/architecture/key-files/core-utilities-1.md@@ -62,4 +62,4 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/preferences.ts` — preferences.json + the migration ledger (`migrations/completed.jsonl` append/read helpers; `appendCompletedMigration`, `loadCompletedMigrations`). Path resolution delegates to `config.ts:gbrainPath()`, so GBRAIN_HOME follows the ONE canonical convention: it is a PARENT dir and `.gbrain` is appended (`GBRAIN_HOME=/tmp/x` → `/tmp/x/.gbrain/migrations/...`). `copyForwardLegacyFile` migrates a legacy layout that placed these files directly under `$GBRAIN_HOME` once per file on first touch: atomic (temp + linkSync, EEXIST = concurrent winner), JSON-validated for prefs, chmod 0600, copy-not-move for binary rollback, once-per-process warning; a valid-but-uncopyable legacy file (read-only home) is READ IN PLACE so a transient failure can't drop a `minion_mode` opt-out or migration history. One-shot by design — mixed-version writers diverging post-snapshot is an accepted, documented limitation.- `src/core/remediation-checkpoint.ts` — `doctor --remediate` checkpoint at `~/.gbrain/remediation/<plan_hash>.json`. `plan_hash = sha256(JSON.stringify(sorted recommendation ids)).slice(0,16)`. Schema-versioned, atomic `.tmp + rename`. `gbrain doctor --remediate --resume <plan_hash>` (no arg picks newest matching) loads it and skips completed steps. Mismatched plan_hash refuses with a paste-ready message. Cleared on clean completion. Optional resume-contract fields written by the doctor CLI: `brain_id` (a resume against another brain refuses), `max_usd` (reused by `--resume` without `--max-usd`), `include_repairs`, cumulative `spent_usd` and the original step `manifest` (`job_ids`, `repair_kinds`); a checkpoint without them keeps the legacy exact-plan-hash resume. Pinned by 13 unit cases plus `test/recovery-layer.test.ts`.-- `src/core/remediation/` — the doctor remediation library (`computeRemediationPlan`, `runRemediation`, shared by doctor, onboard and MCP `run_onboard`). `repairs.ts`: `planRepairSteps` previews every registered repair kind brain-wide and returns PROTECTED steps (`requires_user_agreement`, exact `command`, `paid`, `est_usd_cost`), independent of the score target; `runRepairSteps` applies them in-process for a trusted local caller only, refusing a paid step whose estimate exceeds the remaining cap before it starts and continuing with free steps; `effect` kinds reserve their estimate against the cap up front (the consumer embeds outside the tracker), and an `inline` step is marked `budget_exhausted` when the tracker fired even if a callee swallowed the throw. The plan hash includes the brain id so brains on one host never share a checkpoint file. `run.ts`: `opts.repairs` (doctor CLI only) plans the repair steps and runs them when `include` is set, even when the target is unreachable (job steps are skipped then); a remote `include` refuses `permission_denied`. The cap is cumulative (`spent_usd` from the checkpoint plus this run's tracker); a refused paid step ends the run budget-exhausted and saves the checkpoint. Callers that omit `repairs` keep the job-only behavior. Plan and run preview through `planRepairStepsReport` (the strict `planRepairSteps` still propagates the first error), so a kind whose preview throws is reported as `repair_preview_failures` (code `timeout` for SQLSTATE 57014, naming `GBRAIN_STATEMENT_TIMEOUT`, else `preview_failed`; message redacted, then capped at 300 characters; `fix` is the rendered read-only `gbrain repair <kind>` preview) and the other kinds still plan and run. Each executed job step whose job moves a tracked metric (`impactMetricForJob`: embed / embed-catch-up: `countStaleChunks`; extract: `findOrphanPages` under the orphan-reporting policy, equal to get_health's orphan_pages without running `getHealth()`; extract-ner / extract-timeline-from-meetings: the onboard coverage checks' `visibleEntityCoverageSql`; extract-takes-from-pages: takes) records it before submit and once the job is terminal as one `migration_impact_log` row (`src/core/onboard/impact-capture.ts` `openStepImpact` / `closeStepImpact`, best-effort: a failed capture records null, a failed write only logs, and neither changes the step result), which `gbrain onboard --history` reads; dry runs, steps that throw before their job is terminal and unmapped jobs record nothing.+- `src/core/remediation/` — the doctor remediation library (`computeRemediationPlan`, `runRemediation`, shared by doctor, onboard and MCP `run_onboard`). `repairs.ts`: `planRepairSteps` previews every registered repair kind brain-wide and returns PROTECTED steps (`requires_user_agreement`, exact `command`, `paid`, `est_usd_cost`), independent of the score target; a `spends: 'llm'` kind's step is `paid` and adds `llm_usd` (its paid-model estimate) to `est_usd_cost`, which is null when either part is unpriced; `runRepairSteps` applies them in-process for a trusted local caller only, refusing a paid step whose estimate exceeds the remaining cap before it starts and continuing with free steps; `effect` kinds reserve their embedding estimate against the cap up front (the consumer embeds outside the tracker), and an `inline` step is marked `budget_exhausted` when the tracker fired even if a callee swallowed the throw. A `spends: 'llm'` step never reserves its model estimate: it runs under the caller's tracker (never a nested `stepBudget` tracker) with what is left of the cap as `maxLlmUsd`, then `charge`s the part of its actual `cost.llm_usd` that `spentUsd()` did not already rise by during the step, so model spend counts once; a step its allowance stopped is `budget_exhausted`. `planRepairSteps`, `runRepairSteps` and `runRemediation`'s `repairs.registry` take stub specs for tests. The plan hash includes the brain id so brains on one host never share a checkpoint file. `run.ts`: `opts.repairs` (doctor CLI only) plans the repair steps and runs them when `include` is set, even when the target is unreachable (job steps are skipped then); a remote `include` refuses `permission_denied`. The cap is cumulative (`spent_usd` from the checkpoint plus this run's tracker, reservations and settled model spend); a refused paid step ends the run budget-exhausted and saves the checkpoint. Callers that omit `repairs` keep the job-only behavior. Plan and run preview through `planRepairStepsReport` (the strict `planRepairSteps` still propagates the first error), so a kind whose preview throws is reported as `repair_preview_failures` (code `timeout` for SQLSTATE 57014, naming `GBRAIN_STATEMENT_TIMEOUT`, else `preview_failed`; message redacted, then capped at 300 characters; `fix` is the rendered read-only `gbrain repair <kind>` preview) and the other kinds still plan and run. Each executed job step whose job moves a tracked metric (`impactMetricForJob`: embed / embed-catch-up: `countStaleChunks`; extract: `findOrphanPages` under the orphan-reporting policy, equal to get_health's orphan_pages without running `getHealth()`; extract-ner / extract-timeline-from-meetings: the onboard coverage checks' `visibleEntityCoverageSql`; extract-takes-from-pages: takes) records it before submit and once the job is terminal as one `migration_impact_log` row (`src/core/onboard/impact-capture.ts` `openStepImpact` / `closeStepImpact`, best-effort: a failed capture records null, a failed write only logs, and neither changes the step result), which `gbrain onboard --history` reads; dry runs, steps that throw before their job is terminal and unmapped jobs record nothing.diff --git a/src/commands/doctor/remediate.ts b/src/commands/doctor/remediate.tsindex 5633213aee..7940f08f92 100644--- a/src/commands/doctor/remediate.ts+++ b/src/commands/doctor/remediate.ts@@ -115,8 +115,13 @@ export async function jobStepFix(step: { job: string; params?: Record<string, un};}-export function repairStepFix(step: Pick<RepairPlanStep, 'kind' | 'command' | 'paid' | 'est_usd_cost' | 'affected' | 'checks'>): Action {- const cost = step.paid ? (step.est_usd_cost === null ? ' and calls the embedding provider (price unknown)' : ` and costs about $${step.est_usd_cost.toFixed(4)} in embeddings`) : '';+export function repairStepFix(step: Pick<RepairPlanStep, 'kind' | 'command' | 'paid' | 'est_usd_cost' | 'llm_usd' | 'affected' | 'checks'>): Action {+ const llm = step.llm_usd;+ const embedUsd = step.est_usd_cost !== null && typeof llm === 'number' ? step.est_usd_cost - llm : 0;+ const cost = !step.paid ? ''+ : llm === undefined ? (step.est_usd_cost === null ? ' and calls the embedding provider (price unknown)' : ` and costs about $${step.est_usd_cost.toFixed(4)} in embeddings`)+ : `${llm === null ? ' and may call a paid chat model (price unknown)' : ` and may spend about $${llm.toFixed(4)} on a paid chat model`}`+ + `${embedUsd > 0 ? ` plus about $${embedUsd.toFixed(4)} in embeddings` : ''}`;return {argv: step.command.split(' '),preview_argv: repairPreviewCommand(step.kind).split(' '),@@ -266,7 +271,11 @@ export function renderRemediationPlanLines(plan: RemediationPlanShape, targetScoif (repairs.length > 0) {lines.push(`\nRepair steps: ${repairs.length} (requires user agreement; PROTECTED, run on this host only; independent of the score target)`);for (const step of repairs) {- const cost = step.paid ? (step.est_usd_cost === null ? ' (paid embeddings, price unknown)' : ` (~$${step.est_usd_cost.toFixed(4)} embeddings)`) : ' (free)';+ const llm = step.llm_usd;+ const embedUsd = step.est_usd_cost !== null && typeof llm === 'number' ? step.est_usd_cost - llm : 0;+ const cost = !step.paid ? ' (free)'+ : llm === undefined ? (step.est_usd_cost === null ? ' (paid embeddings, price unknown)' : ` (~$${step.est_usd_cost.toFixed(4)} embeddings)`)+ : ` (${llm === null ? 'paid model, price unknown' : `~$${llm.toFixed(4)} paid model`}${embedUsd > 0 ? `, ~$${embedUsd.toFixed(4)} embeddings` : ''})`;lines.push(` R${step.step}. ${step.kind} — ${step.affected} item(s)${cost} [requires user agreement]`);lines.push(` apply: ${step.command}`);}diff --git a/src/core/remediation/repairs.ts b/src/core/remediation/repairs.tsindex 84e6319af0..1c0aa6d1a2 100644--- a/src/core/remediation/repairs.ts+++ b/src/core/remediation/repairs.ts@@ -6,8 +6,11 @@* agreement (`--include-repairs`). Repair steps are independent of the brain* score target: `--target-score` governs job steps only, and an included* repair step always runs to completion. A paid step (one that may queue- * embeddings) is not started when its estimate exceeds the remaining budget;- * free steps still run. Repairs run in-process on the brain host through the+ * embeddings or call a paid chat model) is not started when its estimate+ * exceeds the remaining budget; free steps still run. A `spends: 'llm'` step+ * runs with what is left of the cap as its paid-model allowance, under the+ * caller's own budget tracker, and its actual model spend is reconciled into+ * the caller's accounting once. Repairs run in-process on the brain host through the* same runner `gbrain repair` uses, never as Minion jobs. Explicit-only kinds* are never planned or run here: the plan lists them with their preview* command, and `runRepairSteps` refuses a supplied step that names one.@@ -18,7 +21,7 @@import type { BrainEngine } from '../engine.ts';import { OperationError } from '../ops/contract.ts';import { resolveRepairScope, type RepairKind } from '../repair/core.ts';-import { AUTO_REPAIR_REGISTRY, explicitKindRequired, repairApplyCommand, repairMaySpend, repairRunner, repairSpec } from '../repair/registry.ts';+import { AUTO_REPAIR_REGISTRY, explicitKindRequired, repairApplyCommand, repairMayEmbed, repairRunner, repairSpec, type RepairKindSpec } from '../repair/registry.ts';import { cliRenderContext, renderAction, type RenderedAction } from '../agent-output.ts';import { readFix } from '../ops/op-fix.ts';import { isStatementTimeoutError } from '../retry-matcher.ts';@@ -33,12 +36,14 @@ export interface RepairPlanStep {command: string;requires_user_agreement: true;protected: true;- /** May spend on embeddings (a model is configured and the kind embeds under these flags). */+ /** May spend: on embeddings (a model is configured and the kind embeds under these flags), or on a paid chat model (`spends: 'llm'`). */paid: boolean;/** `effect`: the persistence consumer embeds after publication, so the estimate is charged against the cap up front. `none`: never embeds. */embeds: 'effect' | 'inline' | 'none';- /** USD estimate; null when the step is paid and the model price is unknown. */+ /** USD estimate (embeddings plus `llm_usd`); null when the step is paid and a model price is unknown. */est_usd_cost: number | null;+ /** `spends: 'llm'` kinds only: the paid chat model part of `est_usd_cost` (null when that model is unpriced under a user-set cap). */+ llm_usd?: number | null;lifetime_ids: number;checks: string[];rationale: string;@@ -87,16 +92,19 @@ export function previewFailureField(failures: readonly RepairPreviewFailure[]):return failures.length === 0 ? {} : { repair_preview_failures: [...failures] };}+/** `registry` replaces the registered kinds (tests register stub specs). */+interface RepairPlanOpts { noEmbed?: boolean; kinds?: readonly RepairKind[]; registry?: readonly RepairKindSpec[] }+async function collectRepairPlan(engine: BrainEngine,- opts: { noEmbed?: boolean; kinds?: readonly RepairKind[] },+ opts: RepairPlanOpts,isolatePreviewErrors: boolean,): Promise<RepairPlanReport> {const scope = await resolveRepairScope(engine);- const runner = await repairRunner(engine, { apply: false, noEmbed: opts.noEmbed, logger: { info() {}, warn() {}, error() {} } });+ const runner = await repairRunner(engine, { apply: false, noEmbed: opts.noEmbed, logger: { info() {}, warn() {}, error() {} }, registry: opts.registry });const report: RepairPlanReport = { steps: [], previewFailures: [] };const { steps } = report;- for (const spec of AUTO_REPAIR_REGISTRY) {+ for (const spec of opts.registry?.filter(entry => !entry.explicit_only) ?? AUTO_REPAIR_REGISTRY) {if (opts.kinds && !opts.kinds.includes(spec.kind)) continue;const preview = await runner.run(spec.kind, scope).catch((error: unknown) => {if (!isolatePreviewErrors) throw error;@@ -107,22 +115,26 @@ async function collectRepairPlan(// contextual-mode stamps only sealed pages; pages the safe-chunks step re-seals become eligible during the run.const unlocked = spec.kind === 'contextual-mode' && steps.some(step => step.kind === 'safe-chunks') ? Number(preview.residuals.unsealed_projection ?? 0) : 0;if (!preview.affected && !unlocked) continue;- const paid = repairMaySpend(spec, opts.noEmbed) && runner.embeddingModel !== undefined;+ const embedPaid = repairMayEmbed(spec, opts.noEmbed) && runner.embeddingModel !== undefined;+ const embedUsd = embedPaid ? preview.cost.embedding_usd : 0;+ const llmUsd = spec.spends === 'llm' ? preview.cost.llm_usd ?? null : undefined;steps.push({ step: steps.length + 1, id: `repair:${spec.kind}`, kind: spec.kind, affected: preview.affected + unlocked,- command: repairApplyCommand(spec.kind, { noEmbed: opts.noEmbed }), requires_user_agreement: true, protected: true, paid, embeds: spec.embeds,- est_usd_cost: paid ? preview.cost.embedding_usd : 0, lifetime_ids: preview.cost.lifetime_ids, checks: spec.checks,+ command: repairApplyCommand(spec.kind, { noEmbed: opts.noEmbed }), requires_user_agreement: true, protected: true,+ paid: embedPaid || llmUsd !== undefined, embeds: spec.embeds,+ est_usd_cost: embedUsd === null || llmUsd === null ? null : embedUsd + (llmUsd ?? 0), ...(llmUsd !== undefined ? { llm_usd: llmUsd } : {}),+ lifetime_ids: preview.cost.lifetime_ids, checks: spec.checks,rationale: `${preview.affected} item(s) pending for gbrain repair ${spec.kind}${unlocked ? `, plus up to ${unlocked} after safe-chunks re-seals them` : ''}` });}return report;}/** Brain-wide preview of every kind `--all` runs; kinds with nothing pending are omitted. The first preview error propagates. */-export async function planRepairSteps(engine: BrainEngine, opts: { noEmbed?: boolean; kinds?: readonly RepairKind[] } = {}): Promise<RepairPlanStep[]> {+export async function planRepairSteps(engine: BrainEngine, opts: RepairPlanOpts = {}): Promise<RepairPlanStep[]> {return (await collectRepairPlan(engine, opts, false)).steps;}/** The same preview for the remediation plan and run: a failing kind is reported in `previewFailures` instead of aborting the rest. */-export async function planRepairStepsReport(engine: BrainEngine, opts: { noEmbed?: boolean; kinds?: readonly RepairKind[] } = {}): Promise<RepairPlanReport> {+export async function planRepairStepsReport(engine: BrainEngine, opts: RepairPlanOpts = {}): Promise<RepairPlanReport> {return collectRepairPlan(engine, opts, true);}@@ -135,21 +147,25 @@ export async function planRepairStepsReport(engine: BrainEngine, opts: { noEmbed*/export async function runRepairSteps(engine: BrainEngine, steps: RepairPlanStep[], opts: {remote: boolean; noEmbed?: boolean; remainingUsd: () => number | undefined;- /** Reserve spend the consumer will make after publication (effect kinds). */+ /** Reserve spend the consumer will make after publication (effect kinds), and settle paid-model spend no tracker metered. */charge?: (usd: number) => void;+ /** What the caller has accounted so far (tracker spend plus charges); without it, a step's whole model spend is charged. */+ spentUsd?: () => number;/** True once the run's budget tracker fired, even if a callee swallowed the throw. */exhausted?: () => boolean;/** Runs one in-process paid step under a tracker capped at what is left after reservations. */stepBudget?: <T>(run: () => Promise<T>) => Promise<T>;onStep?: (step: RepairPlanStep, result: RepairStepResult) => void;+ /** Replaces the registered kinds (tests). */+ registry?: readonly RepairKindSpec[];}): Promise<RepairStepResult[]> {if (opts.remote !== false) throw new OperationError('permission_denied', 'Repair steps are PROTECTED: only a trusted local caller on the brain host can run them.','On the brain host, run: gbrain doctor --remediation-plan');- const explicit = steps.find(step => repairSpec(step.kind)?.explicit_only);+ const explicit = steps.find(step => repairSpec(step.kind, opts.registry)?.explicit_only);if (explicit) throw explicitKindRequired(explicit.kind);const { BudgetExhausted } = await import('../budget/budget-tracker.ts');const scope = await resolveRepairScope(engine);- const runner = await repairRunner(engine, { apply: true, noEmbed: opts.noEmbed });+ const runner = await repairRunner(engine, { apply: true, noEmbed: opts.noEmbed, registry: opts.registry });const results: RepairStepResult[] = [];for (const step of steps) {const base = { id: step.id, kind: step.kind, applied: 0, skipped: 0 };@@ -157,17 +173,20 @@ export async function runRepairSteps(engine: BrainEngine, steps: RepairPlanStep[const remaining = opts.remainingUsd();if (step.paid && remaining !== undefined && (step.est_usd_cost === null || step.est_usd_cost > remaining)) {result = { ...base, status: 'budget_refused', message: step.est_usd_cost === null- ? `Not started: its embedding cost cannot be estimated and a --max-usd cap is set ($${remaining.toFixed(2)} remaining).`+ ? `Not started: its ${step.llm_usd === null ? 'paid-model' : 'embedding'} cost cannot be estimated and a --max-usd cap is set ($${remaining.toFixed(2)} remaining).`: `Not started: estimated $${step.est_usd_cost.toFixed(4)} exceeds the $${remaining.toFixed(4)} remaining under --max-usd.` };} else if (step.paid && opts.exhausted?.()) {result = { ...base, status: 'budget_refused', message: 'Not started: the --max-usd budget ran out earlier in this run.' };} else {- if (step.paid && step.embeds === 'effect' && step.est_usd_cost) opts.charge?.(step.est_usd_cost);+ const llm = step.llm_usd !== undefined;+ if (step.paid && step.embeds === 'effect' && step.est_usd_cost) opts.charge?.(step.est_usd_cost - (step.llm_usd ?? 0));+ const spentBefore = opts.spentUsd?.() ?? 0;try {- const applied = step.paid && step.embeds === 'inline' && opts.stepBudget- ? await opts.stepBudget(() => runner.run(step.kind, scope)) : await runner.run(step.kind, scope);+ const applied = llm ? await runner.run(step.kind, scope, { maxLlmUsd: opts.remainingUsd() })+ : step.paid && step.embeds === 'inline' && opts.stepBudget ? await opts.stepBudget(() => runner.run(step.kind, scope)) : await runner.run(step.kind, scope);+ if (llm) opts.charge?.(Math.max(0, (applied.cost.llm_usd ?? 0) - ((opts.spentUsd?.() ?? 0) - spentBefore)));result = { ...base, applied: applied.applied, skipped: applied.skipped,- status: applied.stopped ? 'stopped' : applied.complete ? 'completed' : 'stopped',+ status: applied.stopped?.reason === 'budget_exhausted' ? 'budget_exhausted' : applied.stopped ? 'stopped' : applied.complete ? 'completed' : 'stopped',...(applied.stopped ? { message: applied.stopped.message } : {}) };// A callee (for example the stale-embedding pass) may swallow BudgetExhausted; the tracker still knows.if (step.paid && step.embeds === 'inline' && opts.exhausted?.()) result = { ...result, status: 'budget_exhausted',diff --git a/src/core/remediation/run.ts b/src/core/remediation/run.tsindex 10fffbd53c..a53ca876fd 100644--- a/src/core/remediation/run.ts+++ b/src/core/remediation/run.ts@@ -165,7 +165,7 @@ export async function runRemediation(// Pre-flight ceiling check via the shared plan computation. The score target// governs job steps only; repair steps are planned independently of it.const initialPlan = await computeRemediationPlan(engine, { targetScore, extraRemediations });- const repairReport = repairs ? await planRepairStepsReport(engine, { noEmbed: repairs.noEmbed, kinds: manifest ? manifest.repair_kinds as RepairPlanStep['kind'][] : undefined }) : { steps: [], previewFailures: [] };+ const repairReport = repairs ? await planRepairStepsReport(engine, { noEmbed: repairs.noEmbed, kinds: manifest ? manifest.repair_kinds as RepairPlanStep['kind'][] : undefined, registry: repairs.registry }) : { steps: [], previewFailures: [] };let repairSteps: RepairPlanStep[] = repairReport.steps;previewFailures = repairReport.previewFailures;// Embeddings a budget stop left behind after re-sealing; the re-sealed pages no longer show up in a repair plan.@@ -265,7 +265,7 @@ export async function runRemediation(// so in-process spend, reserved effect estimates and job spend all draw on one cumulative cap.const repairTracker = new BudgetTracker({ label: 'remediation.repairs', maxCostUsd: remainingCap, capSource: opts.capSource });let jobTracker: InstanceType<typeof BudgetTracker> | undefined;- // Effect kinds embed in the persistence consumer, outside any tracker, so their estimate is reserved up front.+ // Effect kinds embed outside any tracker, so their estimate is reserved up front; paid-model spend no tracker here metered is charged once its step reports it.let reservedUsd = 0;let trackerExhausted = false;const stepTrackers: Array<InstanceType<typeof BudgetTracker>> = [];@@ -332,8 +332,8 @@ export async function runRemediation(}if (repairSteps.length === 0) return;for (const step of repairSteps) hooks.onRepairStepStart?.(step);- const results = await runRepairSteps(engine, repairSteps, { remote: repairs.remote, noEmbed: repairs.noEmbed, remainingUsd,- charge: (usd) => { reservedUsd += usd; }, exhausted: () => trackerExhausted,+ const results = await runRepairSteps(engine, repairSteps, { remote: repairs.remote, noEmbed: repairs.noEmbed, remainingUsd, registry: repairs.registry,+ charge: (usd) => { reservedUsd += usd; }, spentUsd: spentThisRun, exhausted: () => trackerExhausted,stepBudget: async (run) => {const tracker = new BudgetTracker({ label: 'remediation.repair-step', maxCostUsd: remainingUsd(), capSource: opts.capSource });stepTrackers.push(tracker);diff --git a/src/core/remediation/types.ts b/src/core/remediation/types.tsindex 405269f353..5216b857ee 100644--- a/src/core/remediation/types.ts+++ b/src/core/remediation/types.ts@@ -10,7 +10,7 @@import type { RemediationStep } from '../remediation-step.ts';import type { RepairPlanStep, RepairPreviewFailure, RepairStepResult } from './repairs.ts';-import type { ExplicitRepairNotice } from '../repair/registry.ts';+import type { ExplicitRepairNotice, RepairKindSpec } from '../repair/registry.ts';import type { CapSource } from '../consent.ts';/**@@ -100,9 +100,10 @@ export interface RemediationOpts {* Doctor CLI only. Plans the registered repair kinds as PROTECTED steps and* runs them when `include` is true (the user's `--include-repairs`* agreement) and the caller is trusted local (`remote === false`). A- * remote caller asking to include repairs is refused.+ * remote caller asking to include repairs is refused. `registry` replaces+ * the registered repair kinds (tests register stub specs).*/- repairs?: { include: boolean; remote: boolean; noEmbed?: boolean };+ repairs?: { include: boolean; remote: boolean; noEmbed?: boolean; registry?: readonly RepairKindSpec[] };}/**