Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

refactor(doctor): our own implementation of the #6045 fix (#6045)

time-attack27aded53da25
diff --git a/docs/architecture/key-files/commands-2.md b/docs/architecture/key-files/commands-2.md
index 38033ee8aa..724f8e6f93 100644
--- a/docs/architecture/key-files/commands-2.md
+++ b/docs/architecture/key-files/commands-2.md
@@ -22,7 +22,7 @@ Doctor's embedding-dimension warning treats existing chunks as existing data eve
- `src/commands/doctor/checks/git-holds.ts` + `checks/frontmatter-repairable.ts` + `checks/frontmatter-hook.ts` — the #5988 hold and frontmatter checks. `git_held_files` (wave, host-only, `resolution: 'repair'`): Git-source holds per source from `readHeldCoverage` (missing vs stale counts) and the first five paths from `readGitHoldListing` with each one's code and `gitHoldFix` step, the put_page read-only note, `gbrain sources status <id>` and `gbrain repair frontmatter --source <id>`; `fail` once a source holds more than `sync.hold_escalate_count`; connector holds stay on `connector_held_items`. `frontmatter_repairable` (registered inline: emitted by the `frontmatter_integrity` entry from the same `scanBrainSources` walk, whose `PerSourceReport.repairable` counts files by repairable cause: recoverable `YAML_PARSE`, `needs_interpretation`, `FRONTMATTER_COMMENT_VALUE` on title/name/description/summary, `NESTED_QUOTES`, `NULL_BYTES`, `MISSING_CLOSE`, `SLUG_MISMATCH`); a deadline-partial scan sets `details.partial`. Both list `details.source_ids` and belong to the explicit-only `frontmatter` kind, so remediation classifies them `explicit_kind_required` with `--source <id>` when one source is named. `frontmatter_hook` (wave, operator): installed gbrain pre-commit hooks older than `FRONTMATTER_HOOK_VERSION`, fix `gbrain frontmatter install-hook --source <id> --force`. `frontmatterHoldsBannerNote` (a `POST_UPGRADE_NOTES` entry) names sources whose unfinished managed cursor stopped on a failed content refusal: the next sync recovers them, `gbrain sync --source <id> --no-pull` does it now, plus the repair preview and the hook refresh. Test: `test/doctor-frontmatter-holds.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 previews that 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), `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.md
index 0566324479..350bc18048 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. A kind whose preview throws is reported through `onPreviewError` as `repair_preview_failures` (code `timeout` for SQLSTATE 57014, naming `GBRAIN_STATEMENT_TIMEOUT`, else `preview_failed`; message redacted and 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; `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.
diff --git a/docs/guides/repair.md b/docs/guides/repair.md
index f8a0389ebf..8136d0fe4f 100644
--- a/docs/guides/repair.md
+++ b/docs/guides/repair.md
@@ -908,18 +908,20 @@ read-only preview command (`stale-atoms: gbrain repair stale-atoms`), and
"explicit_kind_required"`, `preview_command`, `docs`). Run each by name after
the user agrees (see [Explicit-only repair kinds](#explicit-only-repair-kinds)).
-When one kind's preview fails (for example a statement timeout on a large
-brain), the rest of the plan still prints. The kind is not a repair step: a
-`Repair previews that failed` block lists it with its error code, its error
-and its preview command (`--json`: `repair_preview_failures[]`, present only
-when a preview failed, each `{kind, code, message, why, fix}`; `code` is
-`timeout` for a statement timeout, which `GBRAIN_STATEMENT_TIMEOUT` controls,
-and `preview_failed` otherwise; `fix` is the read-only preview). The error
-text is redacted and capped at 300 characters. `gbrain doctor --remediate`
-runs the other steps, lists the failed kinds with their errors, and exits 1.
-A plan approved while a preview failed binds the steps it showed, so once
-that preview succeeds the approval no longer matches and the run refuses with
-`preview_changed`: preview the plan again and ask the user.
+A repair kind whose preview errors (on a large brain this is usually a
+statement timeout) does not stop the plan. Every other kind is still
+previewed, and the failed kind is listed under `Repair kinds whose preview
+failed` with its error code, its error and the read-only command that
+repeats the preview. In `--json` it appears in `repair_preview_failures[]`,
+which is present only when a preview failed. Each entry is
+`{kind, code, message, why, fix}`: `code` is `timeout` for a statement
+timeout (raise `GBRAIN_STATEMENT_TIMEOUT`) and `preview_failed` for anything
+else, `message` is redacted and then capped at 300 characters, and `fix` is
+the read-only preview. A failed kind is never a step, so `gbrain doctor
+--remediate` runs the remaining steps, names the kinds it could not run and
+exits 1. An approval covers only the steps the user was shown: once the
+failed preview succeeds, the plan changes and the run refuses with
+`preview_changed`. Preview the plan again and ask the user.
`gbrain doctor --remediate --yes` runs job steps only. Repair steps run only
when you also pass `--include-repairs`, which records the user's agreement;
diff --git a/llms-full.txt b/llms-full.txt
index ba24414494..8a65f6aff9 100644
--- a/llms-full.txt
+++ b/llms-full.txt
@@ -11830,18 +11830,20 @@ read-only preview command (`stale-atoms: gbrain repair stale-atoms`), and
"explicit_kind_required"`, `preview_command`, `docs`). Run each by name after
the user agrees (see [Explicit-only repair kinds](#explicit-only-repair-kinds)).
-When one kind's preview fails (for example a statement timeout on a large
-brain), the rest of the plan still prints. The kind is not a repair step: a
-`Repair previews that failed` block lists it with its error code, its error
-and its preview command (`--json`: `repair_preview_failures[]`, present only
-when a preview failed, each `{kind, code, message, why, fix}`; `code` is
-`timeout` for a statement timeout, which `GBRAIN_STATEMENT_TIMEOUT` controls,
-and `preview_failed` otherwise; `fix` is the read-only preview). The error
-text is redacted and capped at 300 characters. `gbrain doctor --remediate`
-runs the other steps, lists the failed kinds with their errors, and exits 1.
-A plan approved while a preview failed binds the steps it showed, so once
-that preview succeeds the approval no longer matches and the run refuses with
-`preview_changed`: preview the plan again and ask the user.
+A repair kind whose preview errors (on a large brain this is usually a
+statement timeout) does not stop the plan. Every other kind is still
+previewed, and the failed kind is listed under `Repair kinds whose preview
+failed` with its error code, its error and the read-only command that
+repeats the preview. In `--json` it appears in `repair_preview_failures[]`,
+which is present only when a preview failed. Each entry is
+`{kind, code, message, why, fix}`: `code` is `timeout` for a statement
+timeout (raise `GBRAIN_STATEMENT_TIMEOUT`) and `preview_failed` for anything
+else, `message` is redacted and then capped at 300 characters, and `fix` is
+the read-only preview. A failed kind is never a step, so `gbrain doctor
+--remediate` runs the remaining steps, names the kinds it could not run and
+exits 1. An approval covers only the steps the user was shown: once the
+failed preview succeeds, the plan changes and the run refuses with
+`preview_changed`. Preview the plan again and ask the user.
`gbrain doctor --remediate --yes` runs job steps only. Repair steps run only
when you also pass `--include-repairs`, which records the user's agreement;
diff --git a/src/commands/doctor/remediate.ts b/src/commands/doctor/remediate.ts
index 6c3a009ef6..5633213aee 100644
--- a/src/commands/doctor/remediate.ts
+++ b/src/commands/doctor/remediate.ts
@@ -12,17 +12,18 @@
* consent and step manifest live in the local remediation checkpoint.
*
* Explicit-only repair kinds are never steps: the plan lists each with its
- * read-only preview command (`explicit_kind_required`). A kind whose preview
- * fails is listed with its error and preview command; the plan and the run go
- * on without it.
+ * read-only preview command (`explicit_kind_required`). An automatic kind
+ * whose preview threw is not a step either: plan and run list it under
+ * `repair_preview_failures` and carry on with every other kind.
*
* After a run, every wave check is classified (cleared, pending,
* consent_required, operator_required, explicit_kind_required, unsupported).
* Exit status: 0 when no automatically repairable finding remains and no step
* failed, even if operator-required, explicit-kind or unsupported findings
* remain (they are listed); 1
- * otherwise, on budget exhaustion and when a repair preview failed; 2 when the
- * target is unreachable and there is no repair step to run, or a resume is refused.
+ * otherwise, on budget exhaustion, and when any repair preview failed (that
+ * kind did not run); 2 when the target is unreachable and there is no repair
+ * step to run, or a resume is refused.
*/
import type { BrainEngine } from '../../core/engine.ts';
import { setCliExitVerdict, writeJsonDocument } from '../../core/cli-force-exit.ts';
@@ -228,21 +229,27 @@ interface RemediationPlanShape {
repair_preview_failures?: RepairPreviewFailure[];
}
+/** Human lines for failed repair previews: kind, error code, the redacted error, and the read-only command that repeats it. */
+function failedPreviewLines(failures: readonly RepairPreviewFailure[], indent: string): string[] {
+ return failures.map(f => `${indent}${f.kind} [${f.code}]: ${f.message}; to see it again run: ${f.fix.command}`);
+}
+
/**
* Human-render the remediation plan. "Brain is at target" prints only when
- * the score is at target AND no repair step is pending or failed its preview,
- * so an unreachable target never reads as "nothing to do".
+ * the score is at target, no repair step is pending and every repair kind
+ * previewed cleanly, so neither an unreachable target nor an unpreviewed
+ * kind ever reads as "nothing to do".
*/
export function renderRemediationPlanLines(plan: RemediationPlanShape, targetScore: number, opts: { noEmbed?: boolean; planHash?: string; paidSteps?: ReadonlySet<number> } = {}): string[] {
const lines: string[] = [];
const repairs = plan.repair_steps ?? [];
- const failedPreviews = plan.repair_preview_failures ?? [];
lines.push(`Brain score: ${plan.brain_score_current}/100 → target ${targetScore}`);
if (plan.target_unreachable) {
lines.push(`Target unreachable: max with autonomous remediation is ${plan.max_reachable_score}/100.`);
}
if (plan.plan.length === 0) {
- if (plan.brain_score_current >= targetScore && repairs.length === 0 && failedPreviews.length === 0) {
+ const unpreviewed = plan.repair_preview_failures?.length ?? 0;
+ if (plan.brain_score_current >= targetScore && repairs.length === 0 && unpreviewed === 0) {
lines.push('No remediations needed. Brain is at target.');
}
} else {
@@ -264,9 +271,9 @@ export function renderRemediationPlanLines(plan: RemediationPlanShape, targetSco
lines.push(` apply: ${step.command}`);
}
}
- if (failedPreviews.length > 0) {
- lines.push('\nRepair previews that failed (not planned; preview each by name on this host to retry):');
- for (const failure of failedPreviews) lines.push(` ${failure.kind} [${failure.code}]: ${failure.message} (preview: ${failure.fix.command})`);
+ if (plan.repair_preview_failures?.length) {
+ lines.push('\nRepair kinds whose preview failed (left out of this plan; nothing was changed):');
+ lines.push(...failedPreviewLines(plan.repair_preview_failures, ' '));
}
if (plan.explicit_repairs?.length) {
lines.push('\nExplicit-only repairs (never run by --remediate or gbrain repair --all; preview each by name on this host):');
@@ -341,9 +348,7 @@ export function remediationExitStatus(result: RemediationResult, findings: Remed
const jobFailed = result.submitted.some(s => s.status !== 'completed' && s.status !== 'submitted' && s.status !== 'dry_run');
// A stopped step (capacity, pending write, unfinished embeddings) left work behind.
const repairFailed = (result.repairs ?? []).some(r => r.status === 'failed' || r.status === 'stopped');
- // A repair kind whose preview failed was neither planned nor run.
- const previewFailed = (result.repair_preview_failures ?? []).length > 0;
- if (jobFailed || repairFailed || previewFailed) return 1;
+ if (jobFailed || repairFailed || result.repair_preview_failures?.length) return 1;
if (findings.some(f => f.class === 'pending' || f.class === 'consent_required')) return 1;
if (result.target_unreachable) return 2;
return 0;
@@ -467,10 +472,9 @@ export async function runRemediate(engine: BrainEngine, args: string[], complete
console.log(`${skipped.length} repair step${skipped.length === 1 ? '' : 's'} skipped (user agreement required): re-run with --include-repairs`);
for (const step of skipped) console.log(` - ${step.kind}: ${step.affected} item(s); ${step.command}`);
}
- const failedPreviews = result.repair_preview_failures ?? [];
- if (failedPreviews.length) {
- console.log(`${failedPreviews.length} repair preview${failedPreviews.length === 1 ? '' : 's'} failed, so ${failedPreviews.length === 1 ? 'that kind was' : 'those kinds were'} not run:`);
- for (const failure of failedPreviews) console.log(` - ${failure.kind} [${failure.code}]: ${failure.message} (preview: ${failure.fix.command})`);
+ if (result.repair_preview_failures?.length) {
+ console.log(`Not run, because the repair preview failed: ${result.repair_preview_failures.map(f => f.kind).join(', ')}`);
+ for (const line of failedPreviewLines(result.repair_preview_failures, ' - ')) console.log(line);
}
for (const f of findings.filter(f => f.class !== 'cleared')) {
console.log(`[${f.class}] ${f.check_id}: ${f.instruction ?? f.command ?? f.message}`);
diff --git a/src/core/remediation/plan.ts b/src/core/remediation/plan.ts
index d8584c2504..352cccb06e 100644
--- a/src/core/remediation/plan.ts
+++ b/src/core/remediation/plan.ts
@@ -11,7 +11,7 @@ import {
} from '../brain-score-recommendations.ts';
import { loadRecommendationContext } from './context.ts';
import type { RemediationPlan, RemediationPlanOpts } from './types.ts';
-import { planRepairSteps, type RepairPreviewFailure } from './repairs.ts';
+import { planRepairStepsReport, previewFailureField, type RepairPlanReport } from './repairs.ts';
import { explicitRepairNotices } from '../repair/registry.ts';
/**
@@ -65,9 +65,8 @@ export async function computeRemediationPlan(
.filter((c) => c.status === 'blocked')
.map((c) => ({ check: c.check, reason: c.reason ?? 'prerequisite missing' }));
- const repairPreviewFailures: RepairPreviewFailure[] = [];
- const repairSteps = opts.repairs
- ? await planRepairSteps(engine, { noEmbed: opts.repairs.noEmbed, onPreviewError: (failure) => repairPreviewFailures.push(failure) })
+ const repairReport: RepairPlanReport | undefined = opts.repairs
+ ? await planRepairStepsReport(engine, { noEmbed: opts.repairs.noEmbed })
: undefined;
return {
@@ -80,7 +79,10 @@ export async function computeRemediationPlan(
est_total_seconds: estTotalSeconds,
est_total_usd_cost: Number(estTotalUsd.toFixed(2)),
blocked,
- ...(repairSteps ? { repair_steps: repairSteps, explicit_repairs: explicitRepairNotices(),
- ...(repairPreviewFailures.length ? { repair_preview_failures: repairPreviewFailures } : {}) } : {}),
+ ...(repairReport ? {
+ repair_steps: repairReport.steps,
+ explicit_repairs: explicitRepairNotices(),
+ ...previewFailureField(repairReport.previewFailures),
+ } : {}),
};
}
diff --git a/src/core/remediation/repairs.ts b/src/core/remediation/repairs.ts
index 6e428b10ac..84e6319af0 100644
--- a/src/core/remediation/repairs.ts
+++ b/src/core/remediation/repairs.ts
@@ -10,13 +10,14 @@
* free steps still run. 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. A kind
- * whose preview fails (a statement timeout on a large brain, #6000) is
- * reported with its preview command and left out; the other kinds still plan.
+ * command, and `runRepairSteps` refuses a supplied step that names one.
+ * The remediation plan and run use `planRepairStepsReport`, which isolates
+ * preview errors per kind: a kind whose preview throws becomes a
+ * `RepairPreviewFailure` and the remaining kinds are still previewed.
*/
import type { BrainEngine } from '../engine.ts';
import { OperationError } from '../ops/contract.ts';
-import { resolveRepairScope, type RepairKind, type RepairResult } from '../repair/core.ts';
+import { resolveRepairScope, type RepairKind } from '../repair/core.ts';
import { AUTO_REPAIR_REGISTRY, explicitKindRequired, repairApplyCommand, repairMaySpend, repairRunner, repairSpec } from '../repair/registry.ts';
import { cliRenderContext, renderAction, type RenderedAction } from '../agent-output.ts';
import { readFix } from '../ops/op-fix.ts';
@@ -54,46 +55,55 @@ export interface RepairStepResult {
message?: string;
}
-/** A kind whose preview threw: it is not planned, and its preview command shows the error again. */
+/**
+ * An automatic kind whose read-only preview threw. It is not a step, so it is
+ * neither in the consent selection nor in the plan hash, and it never runs.
+ */
export interface RepairPreviewFailure { kind: RepairKind; code: 'timeout' | 'preview_failed'; message: string; why: string; fix: RenderedAction }
-function repairPreviewFailure(kind: RepairKind, error: unknown): RepairPreviewFailure {
- const timeout = isStatementTimeoutError(error);
+export interface RepairPlanReport { steps: RepairPlanStep[]; previewFailures: RepairPreviewFailure[] }
+
+const PREVIEW_ERROR_MAX_CHARS = 300;
+
+/** Redact before truncating, so a cut can never split a credential the redactor would have matched. */
+function describePreviewFailure(kind: RepairKind, error: unknown): RepairPreviewFailure {
+ const timedOut = isStatementTimeoutError(error);
+ const detail = redactConnectionInfo(error instanceof Error ? error.message : String(error));
+ const cause = timedOut ? 'hit the database statement timeout (GBRAIN_STATEMENT_TIMEOUT)' : 'raised an error';
return {
kind,
- code: timeout ? 'timeout' : 'preview_failed',
- message: redactConnectionInfo(error instanceof Error ? error.message : String(error)).slice(0, 300),
- why: timeout
- ? `The ${kind} preview ran past the database statement timeout (GBRAIN_STATEMENT_TIMEOUT), so this kind was neither planned nor run; the other kinds are unaffected.`
- : `The ${kind} preview failed, so this kind was neither planned nor run; the other kinds are unaffected.`,
+ code: timedOut ? 'timeout' : 'preview_failed',
+ message: detail.slice(0, PREVIEW_ERROR_MAX_CHARS),
+ why: `The read-only ${kind} preview ${cause}, so ${kind} is left out of this plan and does not run. Every other kind is planned normally.`,
fix: renderAction({
- ...readFix(`Re-runs the read-only ${kind} preview on the brain host; it changes nothing and shows the error again.`, { argv: ['gbrain', 'repair', kind] }),
+ ...readFix(`Repeats the ${kind} preview on the brain host to show the error; it writes nothing.`, { argv: ['gbrain', 'repair', kind] }),
verify: { argv: ['gbrain', 'doctor', '--remediation-plan', '--json'] },
}, cliRenderContext()),
};
}
-/**
- * Brain-wide preview of every kind `--all` runs; kinds with nothing pending are omitted.
- * With `onPreviewError`, a kind whose preview throws is reported there and left out, and the
- * rest still plan; without it the error propagates.
- */
-export async function planRepairSteps(engine: BrainEngine, opts: {
- noEmbed?: boolean; kinds?: readonly RepairKind[]; onPreviewError?: (failure: RepairPreviewFailure) => void;
-} = {}): Promise<RepairPlanStep[]> {
+/** `{ repair_preview_failures }` when any preview failed, else nothing, so a healthy plan's JSON is unchanged. */
+export function previewFailureField(failures: readonly RepairPreviewFailure[]): { repair_preview_failures?: RepairPreviewFailure[] } {
+ return failures.length === 0 ? {} : { repair_preview_failures: [...failures] };
+}
+
+async function collectRepairPlan(
+ engine: BrainEngine,
+ opts: { noEmbed?: boolean; kinds?: readonly RepairKind[] },
+ isolatePreviewErrors: boolean,
+): Promise<RepairPlanReport> {
const scope = await resolveRepairScope(engine);
const runner = await repairRunner(engine, { apply: false, noEmbed: opts.noEmbed, logger: { info() {}, warn() {}, error() {} } });
- const steps: RepairPlanStep[] = [];
+ const report: RepairPlanReport = { steps: [], previewFailures: [] };
+ const { steps } = report;
for (const spec of AUTO_REPAIR_REGISTRY) {
if (opts.kinds && !opts.kinds.includes(spec.kind)) continue;
- let preview: RepairResult;
- try {
- preview = await runner.run(spec.kind, scope);
- } catch (error) {
- if (!opts.onPreviewError) throw error;
- opts.onPreviewError(repairPreviewFailure(spec.kind, error));
- continue;
- }
+ const preview = await runner.run(spec.kind, scope).catch((error: unknown) => {
+ if (!isolatePreviewErrors) throw error;
+ report.previewFailures.push(describePreviewFailure(spec.kind, error));
+ return null;
+ });
+ if (preview === null) continue;
// 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;
@@ -103,7 +113,17 @@ export async function planRepairSteps(engine: BrainEngine, opts: {
est_usd_cost: paid ? preview.cost.embedding_usd : 0, 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 steps;
+ 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[]> {
+ 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> {
+ return collectRepairPlan(engine, opts, true);
}
/**
diff --git a/src/core/remediation/run.ts b/src/core/remediation/run.ts
index 086c20e54f..10fffbd53c 100644
--- a/src/core/remediation/run.ts
+++ b/src/core/remediation/run.ts
@@ -19,7 +19,7 @@ import {
import type { RemediationStep } from '../remediation-step.ts';
import { loadRecommendationContext } from './context.ts';
import { computeRemediationPlan } from './plan.ts';
-import { planRepairSteps, runRepairSteps, type RepairPlanStep, type RepairPreviewFailure, type RepairStepResult } from './repairs.ts';
+import { planRepairStepsReport, previewFailureField, runRepairSteps, type RepairPlanStep, type RepairPreviewFailure, type RepairStepResult } from './repairs.ts';
import { OperationError } from '../ops/contract.ts';
import type { RemediationCheckpoint } from '../remediation-checkpoint.ts';
import type {
@@ -96,11 +96,6 @@ async function runJobInline(
}
}
-/** A repair kind whose preview failed is reported in the result and left out; the run goes on with the rest (#6000). */
-function previewFailureFields(failures: RepairPreviewFailure[]): Partial<RemediationResult> {
- return failures.length ? { repair_preview_failures: failures } : {};
-}
-
export async function runRemediation(
engine: BrainEngine,
opts: RemediationOpts = {},
@@ -136,10 +131,10 @@ export async function runRemediation(
const ctx = await loadRecommendationContext(engine);
const extraRemediations = opts.extraRemediations ?? [];
const brainId = repairs ? (await (await import('../repair/core.ts')).resolveRepairScope(engine)).brain_id : undefined;
- const repairPreviewFailures: RepairPreviewFailure[] = [];
+ let previewFailures: RepairPreviewFailure[] = [];
const synthetic = (score: number, extra: Partial<RemediationResult> = {}): RemediationResult => ({
doctor_run_id: crypto.randomUUID(), brain_score_initial: score, brain_score_final: score, brain_score_target: targetScore,
- target_reached: false, submitted: [], aborted_count: 0, ...previewFailureFields(repairPreviewFailures), ...extra,
+ target_reached: false, submitted: [], aborted_count: 0, ...previewFailureField(previewFailures), ...extra,
});
// Resume loads its checkpoint first: a checkpoint that records a manifest
@@ -170,10 +165,9 @@ 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 });
- let repairSteps: RepairPlanStep[] = repairs
- ? await planRepairSteps(engine, { noEmbed: repairs.noEmbed, kinds: manifest ? manifest.repair_kinds as RepairPlanStep['kind'][] : undefined,
- onPreviewError: (failure) => repairPreviewFailures.push(failure) })
- : [];
+ const repairReport = repairs ? await planRepairStepsReport(engine, { noEmbed: repairs.noEmbed, kinds: manifest ? manifest.repair_kinds as RepairPlanStep['kind'][] : undefined }) : { 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.
let pendingEmbedSources = includeRepairs && manifest ? [...(cp?.pending_embed_sources ?? [])] : [];
const initialHealth = await engine.getHealth();
@@ -522,10 +516,10 @@ export async function runRemediation(
aborted_count: abortedIds.size,
budget_exhausted: budgetAbort,
...(jobStepsSkipped ? { job_steps_skipped: jobStepsSkipped } : {}),
- ...previewFailureFields(repairPreviewFailures),
...(repairs ? {
repairs: repairResults, repairs_skipped: skippedRepairs,
budget: { max_usd: maxUsd ?? null, spent_usd: settledUsd(), include_repairs: includeRepairs, plan_hash: planHash },
} : {}),
+ ...previewFailureField(previewFailures),
};
}
diff --git a/src/core/remediation/types.ts b/src/core/remediation/types.ts
index bd644c8e00..405269f353 100644
--- a/src/core/remediation/types.ts
+++ b/src/core/remediation/types.ts
@@ -55,7 +55,7 @@ export interface RemediationPlan {
repair_steps?: RepairPlanStep[];
/** Present with `repair_steps`: explicit-only kinds, never planned as steps; preview each by name. */
explicit_repairs?: ExplicitRepairNotice[];
- /** Present with `repair_steps` when a kind's preview failed: that kind is not planned; its preview command shows the error. */
+ /** Only when an automatic kind's preview threw: that kind is missing from `repair_steps`. */
repair_preview_failures?: RepairPreviewFailure[];
}
@@ -159,7 +159,7 @@ export interface RemediationResult {
repairs?: RepairStepResult[];
/** Repair steps planned but not run because the user's agreement was missing. */
repairs_skipped?: RepairPlanStep[];
- /** Repair kinds whose preview failed, so the run neither planned nor ran them (only when one failed). */
+ /** Only when an automatic kind's preview threw: this run neither planned nor applied that kind. */
repair_preview_failures?: RepairPreviewFailure[];
/** Cumulative cap and settled spend across the original run and its resumes. */
budget?: { max_usd: number | null; spent_usd: number; include_repairs: boolean; plan_hash: string };
diff --git a/test/doctor-remediation-plan-render.test.ts b/test/doctor-remediation-plan-render.test.ts
index 0f0c227157..47e1f8784b 100644
--- a/test/doctor-remediation-plan-render.test.ts
+++ b/test/doctor-remediation-plan-render.test.ts
@@ -51,21 +51,6 @@ describe('renderRemediationPlanLines', () => {
expect(text).not.toContain('Target unreachable');
});
- test('at target with a failed repair preview (#6000): lists the failure, never "at target"', () => {
- const plan = planFixture({
- brain_score_current: 95,
- plan: [],
- repair_steps: [],
- repair_preview_failures: [{ kind: 'attribution-backfill', code: 'timeout', message: 'canceling statement due to statement timeout',
- why: 'The attribution-backfill preview ran past the database statement timeout.',
- fix: { argv: ['gbrain', 'repair', 'attribution-backfill'], command: 'gbrain repair attribution-backfill', consent: [], actor: 'agent', next: 'run',
- why: 'Re-runs the read-only preview.', requires_exclusive: false } }],
- });
- const text = renderRemediationPlanLines(plan, 90).join('\n');
- expect(text).toContain('attribution-backfill [timeout]: canceling statement due to statement timeout (preview: gbrain repair attribution-backfill)');
- expect(text).not.toContain('Brain is at target');
- });
-
test('brain at exact target with empty plan — still "at target"', () => {
const plan = planFixture({
brain_score_current: 90,
diff --git a/test/remediation-preview-isolation.test.ts b/test/remediation-preview-isolation.test.ts
new file mode 100644
index 0000000000..deae12bd95
--- /dev/null
+++ b/test/remediation-preview-isolation.test.ts
@@ -0,0 +1,180 @@
+/**
+ * #6000 / #6045: `doctor --remediation-plan` and `doctor --remediate` preview
+ * every automatic repair kind. One kind's preview throwing (a statement
+ * timeout on a large Postgres brain) used to abort the whole plan and run.
+ *
+ * Protects: per-kind isolation (kinds before and after a failing preview are
+ * still planned and run), the reported failure contract (code, redacted and
+ * capped message, why, read-only fix + verify), exit 1 for a run that left a
+ * kind out, the unchanged strict planRepairSteps contract, and consent
+ * staying bound to the steps the user was shown.
+ * Fails when: a preview error aborts the plan or the run again, a failed kind
+ * vanishes from the output or turns into a step, the error text leaks a
+ * credential, or an approval made while a kind failed still matches once it
+ * previews cleanly.
+ * Seam: each registered handler's `plan` method, spied for one test and
+ * restored; no production code path is added for the test.
+ */
+import { afterAll, afterEach, beforeAll, describe, expect, spyOn, test, type Mock } from 'bun:test';
+import { mkdtempSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import type { RepairHandler, RepairKind } from '../src/core/repair/core.ts';
+import { AUTO_REPAIR_REGISTRY, repairSpec } from '../src/core/repair/registry.ts';
+import { planRepairSteps } from '../src/core/remediation/repairs.ts';
+import { computeRemediationPlan, runRemediation } from '../src/core/remediation/index.ts';
+import { remediationExitStatus, renderRemediationPlanLines, runRemediate } from '../src/commands/doctor/remediate.ts';
+import { remediationPlanHash } from '../src/commands/doctor/remediate-consent.ts';
+import { setCliExitVerdict } from '../src/core/cli-force-exit.ts';
+import { withEnv } from './helpers/with-env.ts';
+
+let engine: PGLiteEngine;
+const gbrainHome = mkdtempSync(join(tmpdir(), 'gbrain-preview-isolation-'));
+const spies: Mock<(...args: never[]) => unknown>[] = [];
+
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+}, 60_000);
+
+afterAll(async () => {
+ await engine.disconnect();
+ rmSync(gbrainHome, { recursive: true, force: true });
+});
+
+afterEach(() => {
+ while (spies.length) spies.pop()!.mockRestore();
+});
+
+type Behaviour = { pending: string } | { throws: Error };
+
+/** Overrides the named kinds' previews for one test; afterEach restores them. */
+function stubPreviews(behaviours: Partial<Record<RepairKind, Behaviour>>): void {
+ for (const [kind, behaviour] of Object.entries(behaviours) as [RepairKind, Behaviour][]) {
+ const spy = spyOn(repairSpec(kind).handler, 'plan').mockImplementation(async () => {
+ if ('throws' in behaviour) throw behaviour.throws;
+ const preview: Awaited<ReturnType<RepairHandler['plan']>> = {
+ items: [{ cursor: { phase: 0, id: 7 }, source_id: '(brain)', slug: behaviour.pending, chars: 0, action: 'fixture' }], residuals: {},
+ };
+ return preview;
+ });
+ spies.push(spy as unknown as Mock<(...args: never[]) => unknown>);
+ }
+}
+
+const inHome = <T>(fn: () => Promise<T>) => withEnv({ GBRAIN_HOME: gbrainHome, GBRAIN_NON_INTERACTIVE: '1' }, fn);
+
+const statementTimeout = () => Object.assign(new Error('canceling statement due to statement timeout'), { code: '57014' });
+const SECRET = 'hunter2-not-a-real-password';
+const credentialError = () => new Error(`could not connect: postgresql://alice-example:${SECRET}@db.acme-example.internal:5432/brain`);
+
+/** timeline (first) and planner-stats (last) have work; two kinds in between fail differently. */
+const MIXED: Partial<Record<RepairKind, Behaviour>> = {
+ timeline: { pending: 'notes/alpha' },
+ 'safe-chunks': { throws: credentialError() },
+ 'attribution-backfill': { throws: statementTimeout() },
+ 'planner-stats': { pending: 'pages' },
+};
+
+describe('repair preview isolation (#6000)', () => {
+ test('fixture order: a planned kind on each side of the failing ones', () => {
+ const order = AUTO_REPAIR_REGISTRY.map(spec => spec.kind);
+ const at = (k: RepairKind) => order.indexOf(k);
+ expect(at('timeline')).toBeLessThan(at('safe-chunks'));
+ expect(at('safe-chunks')).toBeLessThan(at('attribution-backfill'));
+ expect(at('attribution-backfill')).toBeLessThan(at('planner-stats'));
+ });
+
+ test('the plan keeps every kind that previewed and reports each failure through the contract', async () => {
+ stubPreviews(MIXED);
+ const plan = await inHome(() => computeRemediationPlan(engine, { repairs: { noEmbed: true } }));
+ expect(plan.repair_steps!.map(s => [s.step, s.kind])).toEqual([[1, 'timeline'], [2, 'planner-stats']]);
+ const failures = plan.repair_preview_failures!;
+ expect(failures.map(f => [f.kind, f.code])).toEqual([['safe-chunks', 'preview_failed'], ['attribution-backfill', 'timeout']]);
+ const [generic, timeout] = failures;
+ expect(timeout.message).toBe('canceling statement due to statement timeout');
+ expect(timeout.why).toContain('GBRAIN_STATEMENT_TIMEOUT');
+ expect(generic.why).not.toContain('GBRAIN_STATEMENT_TIMEOUT');
+ expect(timeout.fix.argv).toEqual(['gbrain', 'repair', 'attribution-backfill']);
+ expect(timeout.fix.consent).toEqual([]);
+ expect(timeout.fix.verify?.argv).toEqual(['gbrain', 'doctor', '--remediation-plan', '--json']);
+ expect(JSON.stringify(plan)).not.toContain(SECRET);
+ });
+
+ test('the message is redacted first and capped second: never over 300 characters, never a credential', async () => {
+ const manySecrets = new Error(Array.from({ length: 80 }, (_, i) => `pwd=k${i}`).join(' '));
+ stubPreviews({ 'attribution-backfill': { throws: manySecrets } });
+ const plan = await inHome(() => computeRemediationPlan(engine, { repairs: { noEmbed: true } }));
+ const [failure] = plan.repair_preview_failures ?? [];
+ expect(failure.code).toBe('preview_failed');
+ expect(failure.message.length).toBeLessThanOrEqual(300);
+ expect(failure.message).toContain('<REDACTED:password>');
+ expect(failure.message).not.toMatch(/pwd=k\d/);
+ });
+
+ test('negative control: with every preview clean the plan carries no failure field', async () => {
+ stubPreviews({ timeline: { pending: 'notes/alpha' } });
+ const plan = await inHome(() => computeRemediationPlan(engine, { repairs: { noEmbed: true } }));
+ expect(plan.repair_steps!.map(s => s.kind)).toEqual(['timeline']);
+ expect(Object.keys(plan)).not.toContain('repair_preview_failures');
+ const jobsOnly = await inHome(() => computeRemediationPlan(engine, {}));
+ expect(Object.keys(jobsOnly)).not.toContain('repair_preview_failures');
+ });
+
+ test('planRepairSteps keeps its strict contract: the original error propagates', async () => {
+ const original = statementTimeout();
+ stubPreviews({ timeline: { pending: 'notes/alpha' }, 'attribution-backfill': { throws: original } });
+ await expect(inHome(() => planRepairSteps(engine, { noEmbed: true }))).rejects.toBe(original);
+ });
+
+ test('the human plan lists the failed kinds and never claims the brain is at target', async () => {
+ stubPreviews({ 'attribution-backfill': { throws: statementTimeout() } });
+ const plan = await inHome(() => computeRemediationPlan(engine, { targetScore: 0, repairs: { noEmbed: true } }));
+ expect(plan.repair_steps).toEqual([]);
+ const text = renderRemediationPlanLines(plan, 0).join('\n');
+ expect(text).toContain('Repair kinds whose preview failed');
+ expect(text).toContain('attribution-backfill [timeout]: canceling statement due to statement timeout; to see it again run: gbrain repair attribution-backfill');
+ expect(text).not.toContain('Brain is at target');
+ });
+
+ test('a run plans and dry-runs the healthy kinds, reports the failed ones and exits 1', async () => {
+ stubPreviews(MIXED);
+ const result = await inHome(() => runRemediation(engine, { dryRun: true, repairs: { include: true, remote: false, noEmbed: true } }));
+ const ids = result.submitted.map(s => s.id);
+ expect(ids).toContain('repair:timeline');
+ expect(ids).toContain('repair:planner-stats');
+ expect(ids.filter(id => id === 'repair:safe-chunks' || id === 'repair:attribution-backfill')).toEqual([]);
+ expect(result.repair_preview_failures!.map(f => f.kind)).toEqual(['safe-chunks', 'attribution-backfill']);
+ expect(remediationExitStatus(result, [])).toBe(1);
+ expect(remediationExitStatus({ ...result, repair_preview_failures: undefined }, [])).toBe(0);
+ });
+
+ test('a run where the only repair kind failed takes the nothing-to-do return and still reports it', async () => {
+ stubPreviews({ 'attribution-backfill': { throws: statementTimeout() } });
+ const result = await inHome(() => runRemediation(engine, { targetScore: 0, dryRun: true, repairs: { include: true, remote: false, noEmbed: true } }));
+ expect(result.submitted).toEqual([]);
+ expect(result.repair_preview_failures!.map(f => [f.kind, f.code])).toEqual([['attribution-backfill', 'timeout']]);
+ expect(remediationExitStatus(result, [])).toBe(1);
+ });
+
+ test('an approval given while a kind failed no longer matches once it previews: preview_changed', async () => {
+ const args = ['--remediate', '--include-repairs', '--no-embed'];
+ stubPreviews({ 'planner-stats': { pending: 'pages' }, 'attribution-backfill': { throws: statementTimeout() } });
+ const approvedHash = await inHome(() => remediationPlanHash(engine, args));
+ while (spies.length) spies.pop()!.mockRestore();
+ stubPreviews({ 'planner-stats': { pending: 'pages' }, 'attribution-backfill': { pending: 'pages#1-1' } });
+ expect(await inHome(() => remediationPlanHash(engine, args))).not.toBe(approvedHash);
+ const muted = [spyOn(console, 'log').mockImplementation(() => {}), spyOn(console, 'error').mockImplementation(() => {}),
+ spyOn(process.stdout, 'write').mockImplementation((() => true) as never)];
+ setCliExitVerdict(0);
+ try {
+ await expect(inHome(() => runRemediate(engine, [...args, '--yes', '--expect', approvedHash, '--json'])))
+ .rejects.toMatchObject({ code: 'preview_changed' });
+ } finally {
+ for (const m of muted) m.mockRestore();
+ setCliExitVerdict(0);
+ }
+ });
+});
diff --git a/test/remediation-repair-preview-failure.test.ts b/test/remediation-repair-preview-failure.test.ts
deleted file mode 100644
index 906200acd2..0000000000
--- a/test/remediation-repair-preview-failure.test.ts
+++ /dev/null
@@ -1,127 +0,0 @@
-/**
- * #6000: the remediation plan previews every automatic repair kind, and one
- * kind's preview can fail on a large brain (a statement timeout). That kind is
- * reported through the agent contract (code, redacted and capped message,
- * why, the read-only preview as `fix` with a read-only `verify`), and every
- * other kind is still planned, by `doctor --remediation-plan` and by
- * `doctor --remediate`, which exits 1 because the failed kind did not run. A
- * caller that records nothing still gets the error. A plan approved while the
- * preview failed no longer matches once the preview succeeds, so the run
- * refuses with `preview_changed` (the safe direction).
- *
- * Protects: the plan and the run completing around one failing preview, the
- * failure staying visible (plan JSON, run result, exit status) without
- * leaking connection details, and consent staying bound to what was shown.
- * Fails when: one kind's preview aborts the plan or the run again, a failed
- * preview disappears from the output, or its error text is echoed raw.
- * Seams: none; the failing and the pending preview are the registered
- * handlers' own `plan` methods, replaced for the test.
- */
-import { afterAll, beforeAll, describe, expect, spyOn, test } from 'bun:test';
-import { mkdtempSync, rmSync } from 'node:fs';
-import { tmpdir } from 'node:os';
-import { join } from 'node:path';
-import { PGLiteEngine } from '../src/core/pglite-engine.ts';
-import type { RepairHandler, RepairKind } from '../src/core/repair/core.ts';
-import { AUTO_REPAIR_REGISTRY, repairSpec } from '../src/core/repair/registry.ts';
-import { planRepairSteps } from '../src/core/remediation/repairs.ts';
-import { computeRemediationPlan, runRemediation } from '../src/core/remediation/index.ts';
-import { remediationExitStatus, renderRemediationPlanLines, runRemediate } from '../src/commands/doctor/remediate.ts';
-import { remediationPlanHash } from '../src/commands/doctor/remediate-consent.ts';
-import { setCliExitVerdict } from '../src/core/cli-force-exit.ts';
-import { withEnv } from './helpers/with-env.ts';
-
-const TIMEOUT = 'canceling statement due to statement timeout';
-
-let engine: PGLiteEngine;
-const home = mkdtempSync(join(tmpdir(), 'gbrain-repair-preview-failure-'));
-
-beforeAll(async () => {
- engine = new PGLiteEngine();
- await engine.connect({});
- await engine.initSchema();
-}, 60_000);
-
-afterAll(async () => {
- await engine.disconnect();
- rmSync(home, { recursive: true, force: true });
-});
-
-/** Runs `fn` with the given kinds' previews replaced, restoring the registered ones afterwards. */
-async function withPreviews<T>(previews: Partial<Record<RepairKind, RepairHandler['plan']>>, fn: () => Promise<T>): Promise<T> {
- const originals = Object.keys(previews).map(kind => [repairSpec(kind as RepairKind).handler, repairSpec(kind as RepairKind).handler.plan] as const);
- for (const [kind, plan] of Object.entries(previews)) repairSpec(kind as RepairKind).handler.plan = plan!;
- try { return await withEnv({ GBRAIN_HOME: home, GBRAIN_NON_INTERACTIVE: '1' }, fn); } finally { for (const [handler, plan] of originals) handler.plan = plan; }
-}
-
-const pending = (slug: string): RepairHandler['plan'] =>
- async () => ({ items: [{ cursor: { phase: 0, id: 1 }, source_id: '(brain)', slug, chars: 0, action: 'analyze (fixture)' }], residuals: {} });
-
-/** attribution-backfill times out; planner-stats, which previews after it, has one table to analyze. */
-const PREVIEWS: Partial<Record<RepairKind, RepairHandler['plan']>> = {
- 'attribution-backfill': async () => { throw Object.assign(new Error(TIMEOUT), { code: '57014' }); },
- 'planner-stats': pending('pages'),
-};
-
-const expectTimeoutFailure = (failures: unknown) => expect(structuredClone(failures)).toMatchObject([{
- kind: 'attribution-backfill', code: 'timeout', message: TIMEOUT,
- why: expect.stringContaining('GBRAIN_STATEMENT_TIMEOUT'),
- fix: { argv: expect.arrayContaining(['gbrain', 'repair', 'attribution-backfill']), command: expect.stringContaining('gbrain repair attribution-backfill'),
- next: 'run', consent: [], verify: { argv: expect.arrayContaining(['gbrain', 'doctor', '--remediation-plan', '--json']) } },
-}]);
-
-describe('a repair preview that fails (#6000)', () => {
- test('the fixture previews planner-stats after attribution-backfill', () => {
- const order = AUTO_REPAIR_REGISTRY.map(spec => spec.kind);
- expect(order.indexOf('planner-stats')).toBeGreaterThan(order.indexOf('attribution-backfill'));
- });
-
- test('doctor --remediation-plan lists the failed kind through the contract and still plans the others', async () => {
- const plan = await withPreviews(PREVIEWS, () => computeRemediationPlan(engine, { repairs: {} }));
- expectTimeoutFailure(plan.repair_preview_failures);
- expect(plan.repair_steps!.map(step => [step.kind, step.affected])).toContainEqual(['planner-stats', 1]);
- expect(plan.repair_steps!.some(step => step.kind === 'attribution-backfill')).toBe(false);
- const text = renderRemediationPlanLines(plan, 90).join('\n');
- expect(text).toContain('Repair previews that failed');
- expect(text).toContain(` attribution-backfill [timeout]: ${TIMEOUT} (preview: gbrain repair attribution-backfill`);
- // A caller that records nothing still sees the error.
- await expect(withPreviews(PREVIEWS, () => planRepairSteps(engine))).rejects.toThrow(TIMEOUT);
- });
-
- test('a failed preview with no failures is absent, and an error that carries connection details is redacted and capped', async () => {
- const clean = await withPreviews({ 'planner-stats': pending('pages') }, () => computeRemediationPlan(engine, { repairs: {} }));
- expect('repair_preview_failures' in clean).toBe(false);
- const leaky = `connect failed: postgresql://alice-example:[email protected]:5432/brain password=hunter2-secret ${'x'.repeat(400)}`;
- const plan = await withPreviews({ 'attribution-backfill': async () => { throw new Error(leaky); } }, () => computeRemediationPlan(engine, { repairs: {} }));
- const [failure] = plan.repair_preview_failures!;
- expect(failure.code).toBe('preview_failed');
- expect(failure.message).not.toContain('hunter2-secret');
- expect(failure.message.length).toBeLessThanOrEqual(300);
- expect(JSON.stringify(plan)).not.toContain('hunter2-secret');
- });
-
- test('doctor --remediate plans the other repairs, reports the failed kind, and a run with one exits 1', async () => {
- const result = await withPreviews(PREVIEWS, () => runRemediation(engine, { dryRun: true, repairs: { include: true, remote: false, noEmbed: true } }));
- expectTimeoutFailure(result.repair_preview_failures);
- expect(result.submitted.map(step => step.id)).toContain('repair:planner-stats');
- expect(result.submitted.map(step => step.id)).not.toContain('repair:attribution-backfill');
- expect(remediationExitStatus(result, [])).toBe(1);
- });
-
- test('an approval bound while the preview failed is preview_changed once that preview succeeds', async () => {
- const args = ['--remediate', '--include-repairs', '--no-embed'];
- const approved = await withPreviews(PREVIEWS, () => remediationPlanHash(engine, args));
- const recovered = { ...PREVIEWS, 'attribution-backfill': pending('pages#1-1') };
- expect(await withPreviews(recovered, () => remediationPlanHash(engine, args))).not.toBe(approved);
- const quiet = [spyOn(console, 'log').mockImplementation(() => {}), spyOn(console, 'error').mockImplementation(() => {}),
- spyOn(process.stdout, 'write').mockImplementation((() => true) as never)];
- setCliExitVerdict(0);
- try {
- await expect(withPreviews(recovered, () => runRemediate(engine, [...args, '--yes', '--expect', approved, '--json'])))
- .rejects.toMatchObject({ code: 'preview_changed' });
- } finally {
- for (const spy of quiet) spy.mockRestore();
- setCliExitVerdict(0);
- }
- });
-});