Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(doctor): one failing repair preview no longer aborts the remediation plan or run (#6045)
time-attack0ec1a640adc0
diff --git a/docs/guides/repair.md b/docs/guides/repair.mdindex f952f15980..a5e6f22996 100644--- a/docs/guides/repair.md+++ b/docs/guides/repair.md@@ -908,6 +908,19 @@ read-only preview command (`stale-atoms: gbrain repair stale-atoms`), and"explicit_kind_required"`, `preview_command`, `docs`). Run each by name afterthe 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.+`gbrain doctor --remediate --yes` runs job steps only. Repair steps run onlywhen you also pass `--include-repairs`, which records the user's agreement;without it they are listed as `N repair steps skipped (user agreement required):diff --git a/src/commands/doctor/remediate.ts b/src/commands/doctor/remediate.tsindex 3004282b25..6c3a009ef6 100644--- a/src/commands/doctor/remediate.ts+++ b/src/commands/doctor/remediate.ts@@ -12,21 +12,23 @@* 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`).+ * 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.** 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 and on budget exhaustion; 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 a repair preview failed; 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';import { clearHealthMemo } from '../../core/health-memo.ts';import type { RemediationPlan, RemediationResult } from '../../core/remediation/types.ts';-import type { RepairPlanStep } from '../../core/remediation/repairs.ts';+import type { RepairPlanStep, RepairPreviewFailure } from '../../core/remediation/repairs.ts';import { repairPreviewCommand, repairSpec, type ExplicitRepairNotice } from '../../core/repair/registry.ts';import { findingSource, runWaveChecks, waveRepairKind, type WaveFinding } from './wave-checks.ts';import { derivedCapExhaustedError, type CapSource } from '../../core/consent.ts';@@ -223,22 +225,24 @@ interface RemediationPlanShape {blocked: Array<{ check: string; reason: string }>;repair_steps?: RepairPlanStep[];explicit_repairs?: ExplicitRepairNotice[];+ repair_preview_failures?: RepairPreviewFailure[];}/*** Human-render the remediation plan. "Brain is at target" prints only when- * the score is at target AND no repair step is pending, so an unreachable- * target never reads as "nothing to do".+ * 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".*/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) {+ if (plan.brain_score_current >= targetScore && repairs.length === 0 && failedPreviews.length === 0) {lines.push('No remediations needed. Brain is at target.');}} else {@@ -260,6 +264,10 @@ export function renderRemediationPlanLines(plan: RemediationPlanShape, targetScolines.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.explicit_repairs?.length) {lines.push('\nExplicit-only repairs (never run by --remediate or gbrain repair --all; preview each by name on this host):');for (const notice of plan.explicit_repairs) lines.push(` ${notice.kind}: ${notice.preview_command}`);@@ -333,7 +341,9 @@ export function remediationExitStatus(result: RemediationResult, findings: Remedconst 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');- if (jobFailed || repairFailed) return 1;+ // 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 (findings.some(f => f.class === 'pending' || f.class === 'consent_required')) return 1;if (result.target_unreachable) return 2;return 0;@@ -457,6 +467,11 @@ export async function runRemediate(engine: BrainEngine, args: string[], completeconsole.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})`);+ }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.tsindex ed638cbd41..d8584c2504 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 } from './repairs.ts';+import { planRepairSteps, type RepairPreviewFailure } from './repairs.ts';import { explicitRepairNotices } from '../repair/registry.ts';/**@@ -65,6 +65,11 @@ 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) })+ : undefined;+return {schema_version: 2,brain_score_current: health.brain_score,@@ -75,6 +80,7 @@ export async function computeRemediationPlan(est_total_seconds: estTotalSeconds,est_total_usd_cost: Number(estTotalUsd.toFixed(2)),blocked,- ...(opts.repairs ? { repair_steps: await planRepairSteps(engine, { noEmbed: opts.repairs.noEmbed }), explicit_repairs: explicitRepairNotices() } : {}),+ ...(repairSteps ? { repair_steps: repairSteps, explicit_repairs: explicitRepairNotices(),+ ...(repairPreviewFailures.length ? { repair_preview_failures: repairPreviewFailures } : {}) } : {}),};}diff --git a/src/core/remediation/repairs.ts b/src/core/remediation/repairs.tsindex ca1e274bce..6e428b10ac 100644--- a/src/core/remediation/repairs.ts+++ b/src/core/remediation/repairs.ts@@ -10,12 +10,18 @@* 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.+ * 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.*/import type { BrainEngine } from '../engine.ts';import { OperationError } from '../ops/contract.ts';-import { resolveRepairScope, type RepairKind } from '../repair/core.ts';+import { resolveRepairScope, type RepairKind, type RepairResult } 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';+import { isStatementTimeoutError } from '../retry-matcher.ts';+import { redactConnectionInfo } from '../audit/redact-connection-info.ts';export interface RepairPlanStep {step: number;@@ -48,14 +54,46 @@ export interface RepairStepResult {message?: string;}-/** Brain-wide preview of every kind `--all` runs; kinds with nothing pending are omitted. */-export async function planRepairSteps(engine: BrainEngine, opts: { noEmbed?: boolean; kinds?: readonly RepairKind[] } = {}): Promise<RepairPlanStep[]> {+/** A kind whose preview threw: it is not planned, and its preview command shows the error again. */+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);+ 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.`,+ 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] }),+ 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[]> {const scope = await resolveRepairScope(engine);const runner = await repairRunner(engine, { apply: false, noEmbed: opts.noEmbed, logger: { info() {}, warn() {}, error() {} } });const steps: RepairPlanStep[] = [];for (const spec of AUTO_REPAIR_REGISTRY) {if (opts.kinds && !opts.kinds.includes(spec.kind)) continue;- const preview = await runner.run(spec.kind, scope);+ 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;+ }// 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;diff --git a/src/core/remediation/run.ts b/src/core/remediation/run.tsindex ed6b671351..bd1e59866d 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 RepairStepResult } from './repairs.ts';+import { planRepairSteps, 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,6 +96,11 @@ 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 = {},@@ -131,9 +136,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[] = [];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, ...extra,+ target_reached: false, submitted: [], aborted_count: 0, ...previewFailureFields(repairPreviewFailures), ...extra,});// Resume loads its checkpoint first: a checkpoint that records a manifest@@ -165,7 +171,8 @@ export async function runRemediation(// 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 })+ ? await planRepairSteps(engine, { noEmbed: repairs.noEmbed, kinds: manifest ? manifest.repair_kinds as RepairPlanStep['kind'][] : undefined,+ onPreviewError: (failure) => repairPreviewFailures.push(failure) }): [];// 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 ?? [])] : [];@@ -514,6 +521,7 @@ 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 },diff --git a/src/core/remediation/types.ts b/src/core/remediation/types.tsindex 248d6d1254..bd644c8e00 100644--- a/src/core/remediation/types.ts+++ b/src/core/remediation/types.ts@@ -9,7 +9,7 @@// - src/core/operations.ts (MCP op run_onboard, admin scope)import type { RemediationStep } from '../remediation-step.ts';-import type { RepairPlanStep, RepairStepResult } from './repairs.ts';+import type { RepairPlanStep, RepairPreviewFailure, RepairStepResult } from './repairs.ts';import type { ExplicitRepairNotice } from '../repair/registry.ts';import type { CapSource } from '../consent.ts';@@ -55,6 +55,8 @@ 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. */+ repair_preview_failures?: RepairPreviewFailure[];}/**@@ -157,6 +159,8 @@ 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). */+ 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.tsindex 47e1f8784b..0f0c227157 100644--- a/test/doctor-remediation-plan-render.test.ts+++ b/test/doctor-remediation-plan-render.test.ts@@ -51,6 +51,21 @@ 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-repair-preview-failure.test.ts b/test/remediation-repair-preview-failure.test.tsnew file mode 100644index 0000000000..906200acd2--- /dev/null+++ b/test/remediation-repair-preview-failure.test.ts@@ -0,0 +1,127 @@+/**+ * #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);+ }+ });+});