Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

feat(doctor): --remediate asks through requireConsent before any work (C1)

garrytan79292eea4a35
diff --git a/docs/architecture/key-files/commands-2.md b/docs/architecture/key-files/commands-2.md
index c87373ab9f..40737b7ccc 100644
--- a/docs/architecture/key-files/commands-2.md
+++ b/docs/architecture/key-files/commands-2.md
@@ -18,7 +18,7 @@ Doctor's embedding-dimension warning treats existing chunks as existing data eve
- `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`, `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 / unsupported, from wave checks run before and after) and `remediationExitStatus` (0 when no repairable finding remains and no step failed; 1 otherwise or on budget exhaustion; 2 when the target is unreachable with no repair step, or a resume is refused), set through `setCliExitVerdict`.
+- `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`), `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 / unsupported, from wave checks run before and after) and `remediationExitStatus` (0 when no repairable finding remains and no step failed; 1 otherwise or on budget exhaustion; 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. Test: `test/doctor-legacy-job-authority.test.ts`.
diff --git a/src/cli/commands/doctor.ts b/src/cli/commands/doctor.ts
index a10542383d..7a3171e95c 100644
--- a/src/cli/commands/doctor.ts
+++ b/src/cli/commands/doctor.ts
@@ -37,8 +37,9 @@ export async function run(args: string[], ctx: CliDispatchContext): Promise<void
}
if (args.includes('--remediate')) {
const { runRemediate } = await import('../../commands/doctor.ts');
- const eng = await connectEngine();
- try { await runRemediate(eng, args); } finally { await finishCliTeardown({ engine: eng }); }
+ // A4/C1: observational startup; migrations run only after consent (ctx.completeStartup).
+ const eng = await connectEngine({ probeOnly: !args.includes('--dry-run') });
+ try { await runRemediate(eng, args, ctx.completeStartup); } finally { await finishCliTeardown({ engine: eng }); }
return;
}
diff --git a/src/commands/doctor/remediate-consent.ts b/src/commands/doctor/remediate-consent.ts
new file mode 100644
index 0000000000..e85421ab7a
--- /dev/null
+++ b/src/commands/doctor/remediate-consent.ts
@@ -0,0 +1,146 @@
+/**
+ * Consent for `gbrain doctor --remediate` (agent operator contract v1, C1).
+ *
+ * Remediation submits job steps that may spend (`paid`) and, with
+ * `--include-repairs`, applies repair steps that rewrite stored records
+ * (`destructive`). The consent request is built from the plan computed on
+ * the observational (probe-only) engine, before any migration or work runs:
+ *
+ * - `paid`: `--yes`, `--max-usd`, `spend.posture=tokenmax` or a per-run
+ * preapproval authorizes it. `--yes` without `--max-usd` runs under a
+ * derived cap (estimate × 1.5, floor $0.25; the default cap when there is
+ * no estimate), never uncapped.
+ * - `destructive` (repairs): `--yes --expect <plan_hash>`, where plan_hash
+ * binds the brain, the repair kinds and their pending counts, the job
+ * steps and the parameters. A changed plan re-asks (`preview_changed`).
+ *
+ * A resume reuses the checkpoint's manifest (brain, cap, steps), so it binds
+ * no new plan hash; it still needs `--yes` for the effects it continues.
+ */
+import type { Authorization, PlanSelection } from '../../core/consent.ts';
+import { computePlanHash } from '../../core/consent.ts';
+import { consentGate, engineConsentEnv } from '../../core/consent-cli.ts';
+import type { Effect } from '../../core/agent-output.ts';
+import type { BrainEngine } from '../../core/engine.ts';
+import type { RemediationPlan } from '../../core/remediation/types.ts';
+
+export interface RemediateFlags {
+ targetScore: number;
+ includeRepairs: boolean;
+ noEmbed: boolean;
+ resumeMode: boolean;
+ json: boolean;
+}
+
+export function remediateFlags(args: readonly string[]): RemediateFlags {
+ const i = args.indexOf('--target-score');
+ const target = i >= 0 ? parseInt(args[i + 1] ?? '', 10) : NaN;
+ return {
+ targetScore: Number.isNaN(target) ? 90 : target,
+ includeRepairs: args.includes('--include-repairs'),
+ noEmbed: args.includes('--no-embed'),
+ resumeMode: args.includes('--resume'),
+ json: args.includes('--json'),
+ };
+}
+
+/** The plan the consent request describes, or null when it cannot be computed before startup completes. */
+export async function previewRemediationPlan(engine: BrainEngine, flags: RemediateFlags): Promise<RemediationPlan | null> {
+ try {
+ const { computeRemediationPlan } = await import('../../core/remediation/index.ts');
+ return await computeRemediationPlan(engine, { targetScore: flags.targetScore, repairs: { noEmbed: flags.noEmbed } });
+ } catch {
+ return null;
+ }
+}
+
+/** Estimated spend for what this invocation would run; null when a paid step has no price. */
+export function remediationEstimateUsd(plan: RemediationPlan | null, includeRepairs: boolean): number | null {
+ if (!plan) return null;
+ const repairs = includeRepairs ? plan.repair_steps ?? [] : [];
+ if (repairs.some(step => step.paid && step.est_usd_cost === null)) return null;
+ const total = plan.est_total_usd_cost + repairs.reduce((sum, step) => sum + (step.est_usd_cost ?? 0), 0);
+ return Math.ceil(total * 100) / 100;
+}
+
+/** The persisted selection a `--include-repairs` approval binds. */
+export function remediationSelection(brainId: string, plan: RemediationPlan | null, flags: RemediateFlags): PlanSelection {
+ return {
+ brain: brainId,
+ source: null,
+ operation: 'doctor --remediate',
+ records: [
+ ...(plan?.plan ?? []).map(step => ({ id: `job:${step.id}` })),
+ ...(plan?.repair_steps ?? []).map(step => ({ id: step.id, revision: step.affected })),
+ ],
+ parameters: { target_score: flags.targetScore, include_repairs: true, no_embed: flags.noEmbed, plan_computed: plan !== null },
+ effects: ['paid', 'destructive'],
+ };
+}
+
+/** The approved command: the caller's own flags minus consent flags (consentFix adds `--yes [--expect]`). */
+export function remediateArgv(args: readonly string[]): string[] {
+ const out = ['gbrain', 'doctor'];
+ for (let i = 0; i < args.length; i++) {
+ const a = args[i]!;
+ if (a === '--yes') continue;
+ if (a === '--expect') { i++; continue; }
+ if (a.startsWith('--expect=')) continue;
+ out.push(a);
+ }
+ return out;
+}
+
+function planSummary(plan: RemediationPlan | null, flags: RemediateFlags, estUsd: number | null): string {
+ if (!plan) return 'the remediation plan (it could not be previewed before startup; preview it after approval with gbrain doctor --remediation-plan)';
+ const repairs = plan.repair_steps ?? [];
+ const cost = estUsd === null ? 'an unpriced amount' : `about $${estUsd.toFixed(2)}`;
+ const repairText = flags.includeRepairs && repairs.length
+ ? ` and ${repairs.length} repair step(s) (${repairs.map(r => `${r.kind}: ${r.affected}`).join(', ')})`
+ : '';
+ return `${plan.plan.length} job step(s)${repairText}, ${cost}, brain score ${plan.brain_score_current}/100 toward ${flags.targetScore}`;
+}
+
+async function boundSelection(engine: BrainEngine, plan: RemediationPlan | null, flags: RemediateFlags): Promise<PlanSelection> {
+ const { resolveRepairScope } = await import('../../core/repair/core.ts');
+ const brainId = await resolveRepairScope(engine).then(s => s.brain_id).catch(() => 'host');
+ return remediationSelection(brainId, plan, flags);
+}
+
+/** The plan_hash an `--include-repairs` run binds right now (what `--expect` must name). */
+export async function remediationPlanHash(engine: BrainEngine, args: readonly string[], plan?: RemediationPlan | null): Promise<string> {
+ const flags = remediateFlags(args);
+ return computePlanHash(await boundSelection(engine, plan === undefined ? await previewRemediationPlan(engine, flags) : plan, flags));
+}
+
+/**
+ * Ask for consent. Resolves the Authorization, or null after the refusal
+ * was printed (exit verdict 3). Read-only shortcuts (nothing to do, target
+ * unreachable) are the caller's, before this.
+ */
+export async function remediateConsent(engine: BrainEngine, args: readonly string[], flags: RemediateFlags, plan: RemediationPlan | null): Promise<Authorization | null> {
+ const effects: Effect[] = flags.includeRepairs ? ['paid', 'destructive'] : ['paid'];
+ const estUsd = remediationEstimateUsd(plan, flags.includeRepairs);
+ const selection = flags.includeRepairs && !flags.resumeMode ? await boundSelection(engine, plan, flags) : undefined;
+ const planHash = selection ? computePlanHash(selection) : undefined;
+ const summary = planSummary(plan, flags, estUsd);
+ const preview = ['gbrain', 'doctor', '--remediation-plan', '--target-score', String(flags.targetScore), ...(flags.noEmbed ? ['--no-embed'] : []), '--json'];
+ return consentGate({
+ command: 'doctor --remediate',
+ effects,
+ actor: 'agent',
+ what: flags.resumeMode ? 'Resume brain remediation' : 'Run brain remediation',
+ why: `doctor --remediate runs ${summary} to raise the brain's health score.`
+ + (flags.includeRepairs ? ' Repair steps rewrite stored records (re-seal chunks, restamp metadata) on this brain.' : ''),
+ risk: (estUsd === null ? 'Paid steps have no price estimate, so the default cost cap applies. ' : `Spends up to the cost cap (estimate $${estUsd.toFixed(2)}). `)
+ + (flags.includeRepairs ? 'Repairs change stored records in place; there is no automatic undo, so take a backup first if one matters (gbrain backup). ' : '')
+ + 'Job steps run model calls and may queue embeddings.',
+ user_message: `Run the brain remediation now (${summary})?`
+ + (flags.includeRepairs ? ' It includes repairs that rewrite stored records.' : ''),
+ argv: remediateArgv(args),
+ preview_argv: preview,
+ est_usd: estUsd,
+ ...(planHash ? { plan_hash: planHash, selection } : {}),
+ args,
+ }, { json: flags.json, env: engineConsentEnv(engine) });
+}
diff --git a/src/commands/doctor/remediate.ts b/src/commands/doctor/remediate.ts
index fdda05f0cc..c28834ffcb 100644
--- a/src/commands/doctor/remediate.ts
+++ b/src/commands/doctor/remediate.ts
@@ -29,9 +29,11 @@ import type { RemediationPlan, RemediationResult } from '../../core/remediation/
import type { RepairPlanStep } from '../../core/remediation/repairs.ts';
import { repairPreviewCommand, repairSpec, type ExplicitRepairNotice } from '../../core/repair/registry.ts';
import { runWaveChecks, waveRepairKind, type WaveFinding } from './wave-checks.ts';
+import { derivedCapExhaustedError, type CapSource } from '../../core/consent.ts';
+import { previewRemediationPlan, remediateConsent, remediateFlags, remediationPlanHash, type RemediateFlags } from './remediate-consent.ts';
export const REMEDIATE_HELP = `Usage: gbrain doctor --remediation-plan [--target-score <n>] [--no-embed] [--json]
- gbrain doctor --remediate [--yes] [--include-repairs] [--max-usd <n>] [--target-score <n>]
+ gbrain doctor --remediate [--yes [--expect <plan_hash>]] [--include-repairs] [--max-usd <n>] [--target-score <n>]
[--max-jobs <n>] [--no-embed] [--dry-run] [--resume [<plan_hash>]] [--json]
--remediation-plan previews job steps (driven by the brain score target) and,
@@ -41,7 +43,14 @@ plus one combined command. Read-only.
--remediate runs job steps; with --include-repairs it also runs the repair
steps (the user's agreement; local brain host only). Without it, repair steps
-are listed as skipped.
+are listed as skipped. It asks before any work (and before schema migrations):
+ --yes Authorizes the paid job steps. Without --max-usd the run is
+ capped at the estimate x1.5 (floor $0.25; $5 with no estimate).
+ --expect <hash> With --include-repairs, --yes must name the plan the user
+ approved (plan_hash from --remediation-plan or the refusal);
+ a changed plan re-asks.
+ Without authorization a non-interactive run changes nothing
+ and exits 3 (--json prints the consent payload).
--max-usd <n> Cumulative USD cap across the run and every --resume. A paid
step that would exceed it is not started; free steps still
run, then the run stops as budget-exhausted with a resume
@@ -55,7 +64,7 @@ are listed as skipped.
Exit status: 0 when no automatically repairable finding remains and no step
failed (operator-required and unsupported findings are listed but do not fail
the run); 1 otherwise and on budget exhaustion; 2 when the target is unreachable
-and no repair step runs, or a resume is refused.
+and no repair step runs, or a resume is refused; 3 when consent is required.
Recipe: docs/guides/repair.md#recover-after-upgrading-to-this-release`;
function parseIntFlag(args: string[], flag: string): number | null {
@@ -79,13 +88,18 @@ export function jobStepCommand(step: { job: string; params?: Record<string, unkn
return `gbrain jobs submit ${step.job}${step.params && Object.keys(step.params).length ? ` --params ${shellQuote(JSON.stringify(step.params))}` : ''} --follow`;
}
-/** `gbrain doctor --remediate --yes --include-repairs --max-usd <n>`, filled from the plan's estimates. */
-export function combinedRemediateCommand(plan: Pick<RemediationPlanShape, 'est_total_usd_cost' | 'repair_steps'>, targetScore = 90): string {
+/**
+ * `gbrain doctor --remediate --yes --include-repairs --max-usd <n>`, filled from the plan's estimates.
+ * With repair steps, `--expect <plan_hash>` binds the approval to this plan (C1).
+ */
+export function combinedRemediateCommand(plan: Pick<RemediationPlanShape, 'est_total_usd_cost' | 'repair_steps'>, targetScore = 90,
+ opts: { noEmbed?: boolean; planHash?: string } = {}): string {
const repairs = plan.repair_steps ?? [];
const unknown = repairs.some(step => step.paid && step.est_usd_cost === null);
const total = plan.est_total_usd_cost + repairs.reduce((sum, step) => sum + (step.est_usd_cost ?? 0), 0);
const cap = unknown ? '<n>' : String(Math.ceil(total * 100) / 100);
- return `gbrain doctor --remediate --yes${repairs.length ? ' --include-repairs' : ''} --max-usd ${cap}${targetScore !== 90 ? ` --target-score ${targetScore}` : ''}`;
+ return `gbrain doctor --remediate --yes${repairs.length ? ' --include-repairs' : ''} --max-usd ${cap}${targetScore !== 90 ? ` --target-score ${targetScore}` : ''}`
+ + `${opts.noEmbed ? ' --no-embed' : ''}${repairs.length && opts.planHash ? ` --expect ${opts.planHash}` : ''}`;
}
/**
@@ -97,13 +111,15 @@ export async function runRemediationPlan(engine: BrainEngine, args: string[]): P
if (args.includes('--help') || args.includes('-h')) { console.log(REMEDIATE_HELP); return; }
const { computeRemediationPlan } = await import('../../core/remediation/index.ts');
const targetScore = parseIntFlag(args, '--target-score') ?? 90;
- const plan = await computeRemediationPlan(engine, { targetScore, repairs: { noEmbed: args.includes('--no-embed') } });
+ const noEmbed = args.includes('--no-embed');
+ const plan = await computeRemediationPlan(engine, { targetScore, repairs: { noEmbed } });
+ const planHash = plan.repair_steps?.length ? await remediationPlanHash(engine, args, plan) : undefined;
if (args.includes('--json')) {
console.log(JSON.stringify({ ...plan, plan: plan.plan.map(step => ({ ...step, command: jobStepCommand(step) })),
- combined_command: combinedRemediateCommand(plan, targetScore) }, null, 2));
+ combined_command: combinedRemediateCommand(plan, targetScore, { noEmbed, planHash }), ...(planHash ? { plan_hash: planHash } : {}) }, null, 2));
return;
}
- for (const line of renderRemediationPlanLines(plan, targetScore)) console.log(line);
+ for (const line of renderRemediationPlanLines(plan, targetScore, { noEmbed, planHash })) console.log(line);
}
interface RemediationPlanShape {
@@ -131,7 +147,7 @@ interface RemediationPlanShape {
* the score is at target AND no repair step is pending, so an unreachable
* target never reads as "nothing to do".
*/
-export function renderRemediationPlanLines(plan: RemediationPlanShape, targetScore: number): string[] {
+export function renderRemediationPlanLines(plan: RemediationPlanShape, targetScore: number, opts: { noEmbed?: boolean; planHash?: string } = {}): string[] {
const lines: string[] = [];
const repairs = plan.repair_steps ?? [];
lines.push(`Brain score: ${plan.brain_score_current}/100 → target ${targetScore}`);
@@ -164,7 +180,7 @@ export function renderRemediationPlanLines(plan: RemediationPlanShape, targetSco
for (const notice of plan.explicit_repairs) lines.push(` ${notice.kind}: ${notice.preview_command}`);
}
if (plan.plan.length > 0 || repairs.length > 0) {
- lines.push(`\nApply everything${repairs.length ? ' after the user agrees' : ''}: ${combinedRemediateCommand(plan, targetScore)}`);
+ lines.push(`\nApply everything${repairs.length ? ' after the user agrees' : ''}: ${combinedRemediateCommand(plan, targetScore, opts)}`);
if (repairs.length) lines.push('Ask the user before applying any repair step.');
}
if (plan.blocked.length > 0) {
@@ -235,14 +251,14 @@ export function remediationExitStatus(result: RemediationResult, findings: Remed
* CLI wrapper around runRemediation. Default: submit-and-wait per job step,
* in-process repair steps with --include-repairs. --dry-run skips submission.
*/
-export async function runRemediate(engine: BrainEngine, args: string[]): Promise<void> {
+export async function runRemediate(engine: BrainEngine, args: string[], completeStartup?: (engine: BrainEngine) => Promise<void>): Promise<void> {
if (args.includes('--help') || args.includes('-h')) { console.log(REMEDIATE_HELP); return; }
const targetScore = parseIntFlag(args, '--target-score') ?? 90;
const maxJobs = parseIntFlag(args, '--max-jobs') ?? Infinity;
// --max-cost is an alias for --max-usd; both feed the pre-flight refusal
// and, via withBudgetTracker, the mid-run BudgetExhausted hard stop.
const maxUsdRaw = parseFloatFlag(args, '--max-usd') ?? parseFloatFlag(args, '--max-cost');
- const maxUsd = maxUsdRaw === null ? undefined : maxUsdRaw;
+ let maxUsd = maxUsdRaw === null ? undefined : maxUsdRaw;
const dryRun = args.includes('--dry-run');
const skipConfirm = args.includes('--yes');
const jsonOutput = args.includes('--json');
@@ -254,32 +270,38 @@ export async function runRemediate(engine: BrainEngine, args: string[]): Promise
const resumePlanHash = resumeArg && !resumeArg.startsWith('--') ? resumeArg : undefined;
const log = (line: string) => (jsonOutput ? console.error : console.log)(line);
- const { runRemediation, computeRemediationPlan } = await import('../../core/remediation/index.ts');
+ const { runRemediation } = await import('../../core/remediation/index.ts');
- // TTY confirmation gate (stays in CLI; library doesn't render).
- if (!skipConfirm && !dryRun && process.stdout.isTTY && !resumeMode) {
- const plan = await computeRemediationPlan(engine, { targetScore, repairs: { noEmbed } });
- const repairs = plan.repair_steps ?? [];
- if (plan.target_unreachable && !(includeRepairs && repairs.length)) {
- console.error(`[remediate] target ${targetScore} unreachable; max autonomous = ${plan.max_reachable_score}/100. `
- + `Configure missing prereqs (see --remediation-plan blocked output) or lower --target-score.`);
- process.exit(2);
+ // C1: consent before any work. The engine is observational (probe-only:
+ // no migrations) until consent is granted.
+ let capSource: CapSource | undefined = maxUsd === undefined ? undefined : 'user';
+ if (!dryRun) {
+ const flags: RemediateFlags = { ...remediateFlags(args), targetScore };
+ const plan = await previewRemediationPlan(engine, flags);
+ const repairs = includeRepairs ? plan?.repair_steps ?? [] : [];
+ // Nothing would run (no job step, or the target is out of reach, and no included repair):
+ // the run below only reports, so it needs no consent and no startup completion.
+ const nothingRuns = plan !== null && !resumeMode && repairs.length === 0 && (plan.target_unreachable || plan.plan.length === 0);
+ if (plan && !nothingRuns && !skipConfirm) {
+ log(`About to submit ${plan.plan.length} job(s), est ${plan.est_total_seconds}s, est $${plan.est_total_usd_cost.toFixed(2)}`
+ + ((plan.repair_steps ?? []).length ? `, and ${includeRepairs ? 'run' : 'skip (no --include-repairs)'} ${(plan.repair_steps ?? []).length} repair step(s)` : ''));
}
- if (plan.plan.length === 0 && repairs.length === 0) {
- console.log(`Brain at score ${plan.brain_score_current}/100, target ${targetScore}. Nothing to do.`);
- return;
+ if (!nothingRuns) {
+ const auth = await remediateConsent(engine, args, flags, plan);
+ if (!auth) return;
+ if (maxUsd === undefined && auth.cap_usd !== null && !resumeMode) {
+ maxUsd = auth.cap_usd;
+ capSource = auth.cap_source ?? undefined;
+ }
+ await completeStartup?.(engine);
}
- console.log(`About to submit ${plan.plan.length} job(s), est ${plan.est_total_seconds}s, est $${plan.est_total_usd_cost.toFixed(2)}`
- + (repairs.length ? `, and ${includeRepairs ? 'run' : 'skip (no --include-repairs)'} ${repairs.length} repair step(s)` : ''));
- console.log('Pass --yes to proceed (cron-friendly).');
- process.exit(1);
}
if (engine.kind === 'pglite') console.error('[remediate] PGLite engine: running inline (no durable queue).');
const before = dryRun ? [] : await runWaveChecks(engine);
const result = await runRemediation(engine,
- { targetScore, maxJobs, maxUsd, dryRun, resume: resumeMode, resumePlanHash, repairs: { include: includeRepairs, remote: false, noEmbed } },
+ { targetScore, maxJobs, maxUsd, capSource, dryRun, resume: resumeMode, resumePlanHash, repairs: { include: includeRepairs, remote: false, noEmbed } },
{
onTargetUnreachable: (target, ceiling) => {
console.error(`[remediate] target ${target} unreachable; max autonomous = ${ceiling}/100. `
@@ -301,7 +323,13 @@ export async function runRemediate(engine: BrainEngine, args: string[]): Promise
if (!dryRun) clearHealthMemo(engine);
- if (result.budget_exhausted) {
+ if (result.budget_exhausted && capSource !== 'user') {
+ const cap = result.budget?.max_usd ?? result.budget_exhausted.cap;
+ const e = derivedCapExhaustedError({ command: 'doctor --remediate', capUsd: cap, spentUsd: result.budget_exhausted.spent,
+ checkpoint: `plan_hash ${result.budget_exhausted.plan_hash}`,
+ argv: ['gbrain', 'doctor', '--remediate', '--yes', ...(result.budget?.include_repairs ? ['--include-repairs'] : []), '--resume', result.budget_exhausted.plan_hash] });
+ console.error(`${e.message}\n${e.suggestion}`);
+ } else if (result.budget_exhausted) {
const cap = result.budget?.max_usd ?? result.budget_exhausted.cap;
console.error(`Resume with:\n gbrain doctor --remediate --yes${result.budget?.include_repairs ? ' --include-repairs' : ''}`
+ `${cap !== null && cap !== undefined ? ` --max-usd ${cap}` : ''} --resume ${result.budget_exhausted.plan_hash}\n`
diff --git a/src/core/remediation/run.ts b/src/core/remediation/run.ts
index 5624178b96..7689b63603 100644
--- a/src/core/remediation/run.ts
+++ b/src/core/remediation/run.ts
@@ -207,7 +207,7 @@ export async function runRemediation(
// the throw propagates; the caller hook surfaces the actionable --resume hint.
// Repairs run first under their own tracker; job steps then get a tracker capped at what the repairs left,
// 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 });
+ 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.
let reservedUsd = 0;
@@ -279,7 +279,7 @@ export async function runRemediation(
const results = await runRepairSteps(engine, repairSteps, { remote: repairs.remote, noEmbed: repairs.noEmbed, remainingUsd,
charge: (usd) => { reservedUsd += usd; }, exhausted: () => trackerExhausted,
stepBudget: async (run) => {
- const tracker = new BudgetTracker({ label: 'remediation.repair-step', maxCostUsd: remainingUsd() });
+ const tracker = new BudgetTracker({ label: 'remediation.repair-step', maxCostUsd: remainingUsd(), capSource: opts.capSource });
stepTrackers.push(tracker);
watch(tracker);
return withBudgetTracker(tracker, run);
@@ -419,7 +419,7 @@ export async function runRemediation(
jobsBudgetRefused = true;
recs = [];
}
- jobTracker = new BudgetTracker({ label: 'remediation.run', maxCostUsd: afterRepairs });
+ jobTracker = new BudgetTracker({ label: 'remediation.run', maxCostUsd: afterRepairs, capSource: opts.capSource });
watch(jobTracker);
await withBudgetTracker(jobTracker, runLoop);
} catch (err) {
diff --git a/src/core/remediation/types.ts b/src/core/remediation/types.ts
index 3d591bece4..236e9b83df 100644
--- a/src/core/remediation/types.ts
+++ b/src/core/remediation/types.ts
@@ -11,6 +11,7 @@
import type { RemediationStep } from '../remediation-step.ts';
import type { RepairPlanStep, RepairStepResult } from './repairs.ts';
import type { ExplicitRepairNotice } from '../repair/registry.ts';
+import type { CapSource } from '../consent.ts';
/**
* Options for computeRemediationPlan. All fields are optional with
@@ -69,6 +70,8 @@ export interface RemediationOpts {
maxJobs?: number;
/** USD cap for total plan cost. Pre-flight refuse + mid-run BudgetExhausted gate. */
maxUsd?: number;
+ /** A4: where `maxUsd` came from (default `user`); a `derived` cap warns-and-runs an unpriced model and logs its exhaustion. */
+ capSource?: CapSource;
/** Read-only dry-run; submits no jobs; returns plan in result. */
dryRun?: boolean;
/** Resume from checkpoint matching this plan_hash, OR newest if undefined+resume=true. */
diff --git a/test/doctor-remediate-consent.test.ts b/test/doctor-remediate-consent.test.ts
new file mode 100644
index 0000000000..78eff2ded2
--- /dev/null
+++ b/test/doctor-remediate-consent.test.ts
@@ -0,0 +1,118 @@
+/**
+ * C1 (agent operator wave): `gbrain doctor --remediate` asks before any work.
+ *
+ * Protects: a non-interactive run without authorization changes nothing and
+ * exits 3 with the consent payload (`--json` never implies consent); with
+ * `--include-repairs` the approval binds the plan (`--yes --expect
+ * <plan_hash>`, the same hash `--remediation-plan` prints); a stale
+ * `--expect` refuses with `preview_changed`; `--yes` without `--max-usd`
+ * runs under a derived cap, never uncapped.
+ *
+ * Fails on the base: `--remediate --json` with no `--yes` ran the job steps
+ * for non-TTY callers, and `--yes --include-repairs` applied repairs with no
+ * plan binding. Seam: the real CLI handler (`runRemediate`) on a PGLite brain
+ * seeded with three repairable wave findings.
+ */
+import { expect, spyOn, test } from 'bun:test';
+import { runRemediate, runRemediationPlan } from '../src/commands/doctor/remediate.ts';
+import { remediationPlanHash } from '../src/commands/doctor/remediate-consent.ts';
+import { listRemediationCheckpoints } from '../src/core/remediation-checkpoint.ts';
+import { currentExitCode, setCliExitVerdict } from '../src/core/cli-force-exit.ts';
+import type { BrainEngine } from '../src/core/engine.ts';
+import { waveBrain } from './helpers/wave-fixture.ts';
+import { withEnv } from './helpers/with-env.ts';
+
+const KINDS = ['timeline', 'visibility', 'safe_index'] as const;
+
+async function run(engine: BrainEngine, args: string[], fn = runRemediate) {
+ let stdout = '';
+ let stderr = '';
+ const out = spyOn(process.stdout, 'write').mockImplementation(((c: string | Uint8Array) => { stdout += String(c); return true; }) as never);
+ const err = spyOn(process.stderr, 'write').mockImplementation(((c: string | Uint8Array) => { stderr += String(c); return true; }) as never);
+ const log = spyOn(console, 'log').mockImplementation((...p: unknown[]) => { stdout += `${p.join(' ')}\n`; });
+ const error = spyOn(console, 'error').mockImplementation((...p: unknown[]) => { stderr += `${p.join(' ')}\n`; });
+ setCliExitVerdict(0);
+ try {
+ await withEnv({ GBRAIN_NON_INTERACTIVE: '1' }, () => fn(engine, args));
+ } finally {
+ out.mockRestore(); err.mockRestore(); log.mockRestore(); error.mockRestore();
+ }
+ const exit = currentExitCode();
+ setCliExitVerdict(0);
+ return { stdout, stderr, exit };
+}
+
+const timeline = (engine: BrainEngine) => engine.executeRaw("SELECT timeline FROM pages WHERE slug='notes/history'");
+
+test('unauthorized and --json-only runs change nothing and exit 3 with the consent payload', async () => {
+ await waveBrain(async ({ engine }) => {
+ const before = await timeline(engine);
+ const hash = await remediationPlanHash(engine, ['--remediate', '--include-repairs']);
+ const r = await run(engine, ['--remediate', '--include-repairs', '--json']);
+ expect(r.exit).toBe(3);
+ const payload = JSON.parse(r.stdout);
+ expect(payload).toMatchObject({ status: 'confirmation_required', code: 'confirmation_required', effects: ['paid', 'destructive'], actor: 'agent', contract_version: 1 });
+ expect(payload.fix.argv).toEqual(['gbrain', 'doctor', '--remediate', '--include-repairs', '--json', '--yes', '--expect', hash]);
+ expect(payload.fix.next).toBe('ask_user');
+ expect(payload.preview.argv).toEqual(['gbrain', 'doctor', '--remediation-plan', '--target-score', '90', '--json']);
+ expect(payload.user_message).toContain('Run the brain remediation now');
+ expect(payload.user_message).toContain('timeline: 1');
+ expect(await timeline(engine)).toEqual(before);
+ expect(listRemediationCheckpoints()).toEqual([]);
+
+ const human = await run(engine, ['--remediate', '--include-repairs']);
+ expect(human.exit).toBe(3);
+ expect(human.stdout).toContain('[AGENT]');
+ expect(human.stdout).toContain('[SHOW USER]');
+ expect(human.stdout).toContain(`--expect ${hash}`);
+ expect(await timeline(engine)).toEqual(before);
+
+ // Nothing runnable without the repairs (no job step on this brain): the run only reports, no consent needed.
+ const report = await run(engine, ['--remediate', '--json']);
+ expect(report.stdout).not.toContain('confirmation_required');
+ expect(JSON.parse(report.stdout.slice(report.stdout.indexOf('{'))).repairs_skipped).toHaveLength(3);
+ expect(await timeline(engine)).toEqual(before);
+ }, { kinds: [...KINDS] });
+}, 120_000);
+
+test('--include-repairs binds the plan: --yes alone refuses, the fix and --remediation-plan carry the same --expect hash, a stale hash is preview_changed', async () => {
+ await waveBrain(async ({ engine }) => {
+ const before = await timeline(engine);
+ const hash = await remediationPlanHash(engine, ['--remediate', '--include-repairs', '--no-embed']);
+ const refused = await run(engine, ['--remediate', '--yes', '--include-repairs', '--no-embed', '--json']);
+ expect(refused.exit).toBe(3);
+ const payload = JSON.parse(refused.stdout);
+ expect(payload.effects).toEqual(['paid', 'destructive']);
+ expect(payload.plan_hash).toBe(hash);
+ expect(payload.fix.argv.slice(-2)).toEqual(['--expect', hash]);
+ expect(payload.preapprove_argv).toBeUndefined();
+ expect(payload.risk).toContain('no automatic undo');
+ expect(await timeline(engine)).toEqual(before);
+
+ const plan = await run(engine, ['--remediation-plan', '--no-embed', '--json'], runRemediationPlan);
+ const body = JSON.parse(plan.stdout);
+ expect(body.plan_hash).toBe(hash);
+ expect(body.combined_command).toEndWith(`--no-embed --expect ${hash}`);
+
+ await expect(run(engine, ['--remediate', '--yes', '--include-repairs', '--no-embed', '--expect', 'ph_stale', '--json']))
+ .rejects.toMatchObject({ code: 'preview_changed' });
+ expect(await timeline(engine)).toEqual(before);
+
+ const agreed = await run(engine, ['--remediate', '--yes', '--include-repairs', '--no-embed', '--max-usd', '1', '--expect', hash, '--json']);
+ const result = JSON.parse(agreed.stdout);
+ expect(result.repairs.map((r: { kind: string; status: string }) => [r.kind, r.status]))
+ .toEqual([['timeline', 'completed'], ['visibility', 'completed'], ['safe-chunks', 'completed']]);
+ expect(await timeline(engine)).not.toEqual(before);
+ }, { kinds: [...KINDS] });
+}, 120_000);
+
+test('--yes without --max-usd runs under a printed derived cap, never uncapped', async () => {
+ await waveBrain(async ({ engine }) => {
+ const hash = await remediationPlanHash(engine, ['--remediate', '--include-repairs', '--no-embed']);
+ const r = await run(engine, ['--remediate', '--yes', '--include-repairs', '--no-embed', '--expect', hash, '--json']);
+ expect(r.stderr).toMatch(/\[consent\] doctor --remediate: cost cap \$0\.25/);
+ const body = JSON.parse(r.stdout.slice(r.stdout.indexOf('{')));
+ expect(body.budget).toMatchObject({ max_usd: 0.25 });
+ expect(body.repairs_completed).toBe(3);
+ }, { kinds: [...KINDS] });
+}, 120_000);
diff --git a/test/fix-wave-3-integration.test.ts b/test/fix-wave-3-integration.test.ts
index 3d6290151d..2d251fac54 100644
--- a/test/fix-wave-3-integration.test.ts
+++ b/test/fix-wave-3-integration.test.ts
@@ -46,6 +46,7 @@ import { runWaveChecks, remoteWaveHandoff, WAVE_CHECKS } from '../src/commands/d
import { writerVersionCheck } from '../src/commands/doctor/checks/writer-version.ts';
import { checkUnboundSource } from '../src/commands/doctor/checks/unbound-source.ts';
import { runRemediate } from '../src/commands/doctor/remediate.ts';
+import { approvedRemediateArgs } from './helpers/remediate-approval.ts';
import { runPhaseSynthesizeConcepts } from '../src/core/cycle/synthesize-concepts.ts';
import { timeContainedPhase } from '../src/core/cycle/phase-containment.ts';
import { LockStolenError } from '../src/core/db-lock.ts';
@@ -258,7 +259,7 @@ test('check 4 (S1): a checkpoint orphaned by a content change is listed by the r
const steps = await planRepairSteps(engine, { noEmbed: true });
const step = steps.find(s => s.kind === 'connector-checkpoints');
expect(step).toMatchObject({ command: 'gbrain repair connector-checkpoints --apply', paid: false, embeds: 'none', lifetime_ids: 0, checks: ['connector_checkpoints'] });
- const run = await capture(() => runRemediate(engine, ['--remediate', '--yes', '--include-repairs', '--no-embed', '--max-usd', '0', '--json']));
+ const run = await capture(async () => runRemediate(engine, await approvedRemediateArgs(engine, ['--remediate', '--yes', '--include-repairs', '--no-embed', '--max-usd', '0', '--json'])));
const body = JSON.parse(run.out);
expect(body.repairs.find((r: { kind: string }) => r.kind === 'connector-checkpoints')).toMatchObject({ status: 'completed' });
expect(body.findings.find((r: { check_id: string }) => r.check_id === 'connector_checkpoints')).toMatchObject({ class: 'cleared' });
@@ -437,7 +438,7 @@ test('check 9: every registered repair kind reaches the remediation plan with it
expect(planned['connector-checkpoints']).toMatchObject({ paid: false, embeds: 'none' });
expect(planned['safe-chunks']).toBeDefined();
expect(planned['contextual-mode'].rationale).toContain('after safe-chunks re-seals them');
- const run = JSON.parse((await capture(() => runRemediate(engine, ['--remediate', '--yes', '--include-repairs', '--no-embed', '--max-usd', '0', '--json']))).out);
+ const run = JSON.parse((await capture(async () => runRemediate(engine, await approvedRemediateArgs(engine, ['--remediate', '--yes', '--include-repairs', '--no-embed', '--max-usd', '0', '--json'])))).out);
const byKind = Object.fromEntries(run.repairs.map((r: { kind: string }) => [r.kind, r]));
expect(byKind['contextual-mode']).toMatchObject({ status: 'completed' });
expect(byKind['connector-checkpoints']).toMatchObject({ status: 'completed' });
diff --git a/test/fix-wave-3-recovery-run.test.ts b/test/fix-wave-3-recovery-run.test.ts
index 1818efc95b..e978c4fd83 100644
--- a/test/fix-wave-3-recovery-run.test.ts
+++ b/test/fix-wave-3-recovery-run.test.ts
@@ -27,6 +27,7 @@ import { declarePersistenceProtocol } from '../src/core/persistence/protocol.ts'
import { migrateConnectorCheckpoints } from '../src/core/persistence/connector-checkpoint-migration.ts';
import { readConnectorSourceStatuses } from '../src/core/persistence/connector-status.ts';
import { runRemediate, runRemediationPlan } from '../src/commands/doctor/remediate.ts';
+import { approvedRemediateArgs } from './helpers/remediate-approval.ts';
import { postUpgradeRecoveryBanner } from '../src/commands/doctor/upgrade-banner.ts';
import { capture } from './helpers/wave-scenarios.ts';
import { waveBrain } from './helpers/wave-fixture.ts';
@@ -80,7 +81,7 @@ for (const backend of testBackends()) test(`${backend}: post-upgrade to a clean
expect(banner).not.toContain('--yes');
expect(banner).not.toContain('--apply');
- const run = await capture(() => runRemediate(engine, ['--remediate', '--yes', '--include-repairs', '--no-embed', '--max-usd', '1', '--json']));
+ const run = await capture(async () => runRemediate(engine, await approvedRemediateArgs(engine, ['--remediate', '--yes', '--include-repairs', '--no-embed', '--max-usd', '1', '--json'])));
commands.push('gbrain doctor --remediate --yes --include-repairs --no-embed --max-usd 1');
const body = JSON.parse(run.out);
expect(body.repairs.map((r: { kind: string; status: string }) => [r.kind, r.status])).toEqual([
diff --git a/test/fix-wave-4-integration.test.ts b/test/fix-wave-4-integration.test.ts
index 3a28fdae27..35027ab125 100644
--- a/test/fix-wave-4-integration.test.ts
+++ b/test/fix-wave-4-integration.test.ts
@@ -49,6 +49,7 @@ import { readAllSourceHolds } from '../src/core/connectors/item-holds-store.ts';
import { retryHeld } from '../src/commands/sources-retry-held.ts';
import { planRepairSteps } from '../src/core/remediation/repairs.ts';
import { runRemediate } from '../src/commands/doctor/remediate.ts';
+import { approvedRemediateArgs } from './helpers/remediate-approval.ts';
import { AUTO_REPAIR_REGISTRY } from '../src/core/repair/registry.ts';
import { capture } from './helpers/wave-scenarios.ts';
import { createConnectorFixture, contact, json, options, withGoogleAccount } from './helpers/connector-fixture.ts';
@@ -223,7 +224,7 @@ test('X11: the remediation run reaches every new repair kind, runs the free ones
const planned = Object.fromEntries((await planRepairSteps(engine, { noEmbed: true })).map(step => [step.kind, step]));
expect(planned['request-indexes']).toMatchObject({ paid: false, embeds: 'none', command: 'gbrain repair request-indexes --apply' });
expect(planned['orphan-bindings']).toMatchObject({ paid: false, embeds: 'none', command: 'gbrain repair orphan-bindings --apply' });
- const run = JSON.parse((await capture(() => runRemediate(engine, ['--remediate', '--yes', '--include-repairs', '--no-embed', '--max-usd', '0', '--json']))).out);
+ const run = JSON.parse((await capture(async () => runRemediate(engine, await approvedRemediateArgs(engine, ['--remediate', '--yes', '--include-repairs', '--no-embed', '--max-usd', '0', '--json'])))).out);
await disposePersistenceConsumer(engine);
const byKind = Object.fromEntries(run.repairs.map((r: { kind: string }) => [r.kind, r]));
expect(byKind['request-indexes']).toMatchObject({ status: 'completed' });
diff --git a/test/fix-wave-5-integration.test.ts b/test/fix-wave-5-integration.test.ts
index c5a16f80b0..bc26c5ac9f 100644
--- a/test/fix-wave-5-integration.test.ts
+++ b/test/fix-wave-5-integration.test.ts
@@ -49,6 +49,7 @@ import { runExtractConversationFactsCore } from '../src/commands/extract-convers
import { writeSingleFact } from '../src/core/facts/write-single.ts';
import { postUpgradeRecoveryBanner } from '../src/commands/doctor/upgrade-banner.ts';
import { runRemediate, runRemediationPlan } from '../src/commands/doctor/remediate.ts';
+import { approvedRemediateArgs } from './helpers/remediate-approval.ts';
import { AUTO_REPAIR_REGISTRY } from '../src/core/repair/registry.ts';
import { HOOK_EVENTS, runHook } from '../src/commands/hook.ts';
import { CORPUS_INGESTED_SUFFIX, runMaintenanceSweep } from '../src/core/sweep.ts';
@@ -220,7 +221,7 @@ for (const backend of testBackends()) {
expect(planText).not.toMatch(/gbrain repair (stale-atoms|extractor-facts) --apply/);
// gbrain doctor --remediate --include-repairs never runs them; each finding says explicit_kind_required with the preview.
- const run = JSON.parse((await capture(() => runRemediate(engine, ['--remediate', '--yes', '--include-repairs', '--no-embed', '--max-usd', '0', '--json']))).out) as {
+ const run = JSON.parse((await capture(async () => runRemediate(engine, await approvedRemediateArgs(engine, ['--remediate', '--yes', '--include-repairs', '--no-embed', '--max-usd', '0', '--json'])))).out) as {
repairs?: Array<{ kind: string }>; findings: Array<{ check_id: string; class: string; repair_kind?: string; command?: string }> };
expect((run.repairs ?? []).map(r => r.kind).filter(kind => kind in previews)).toEqual([]);
expect(run.findings.filter(f => f.class === 'explicit_kind_required').map(f => [f.check_id, f.repair_kind, f.command])).toEqual([
diff --git a/test/helpers/remediate-approval.ts b/test/helpers/remediate-approval.ts
new file mode 100644
index 0000000000..283b4031e4
--- /dev/null
+++ b/test/helpers/remediate-approval.ts
@@ -0,0 +1,13 @@
+/**
+ * `doctor --remediate --yes --include-repairs` binds the destructive repair
+ * steps to the current plan (C1): the approved command carries
+ * `--expect <plan_hash>`. Tests that drive an agreed run append the hash the
+ * refusal would have printed, computed by the same code path.
+ */
+import type { BrainEngine } from '../../src/core/engine.ts';
+import { remediationPlanHash } from '../../src/commands/doctor/remediate-consent.ts';
+
+export async function approvedRemediateArgs(engine: BrainEngine, args: string[]): Promise<string[]> {
+ if (!args.includes('--include-repairs') || args.includes('--resume') || args.includes('--expect')) return args;
+ return [...args, '--expect', await remediationPlanHash(engine, args)];
+}
diff --git a/test/helpers/wave-scenarios.ts b/test/helpers/wave-scenarios.ts
index 9cdce64030..9887d3b254 100644
--- a/test/helpers/wave-scenarios.ts
+++ b/test/helpers/wave-scenarios.ts
@@ -9,6 +9,7 @@ import { expect } from 'bun:test';
import type { BrainEngine } from '../../src/core/engine.ts';
import { doctorReportRemote } from '../../src/commands/doctor.ts';
import { remediationExitStatus, runRemediate, runRemediationPlan } from '../../src/commands/doctor/remediate.ts';
+import { approvedRemediateArgs } from './remediate-approval.ts';
import { REMOTE_HOST_ACTION, remoteWaveHandoff } from '../../src/commands/doctor/wave-checks.ts';
import { currentExitCode, setCliExitVerdict } from '../../src/core/cli-force-exit.ts';
import { configureGateway, resetGateway } from '../../src/core/ai/gateway.ts';
@@ -31,7 +32,8 @@ export async function capture(run: () => Promise<void>): Promise<{ out: string;
}
const json = async (engine: BrainEngine, args: string[], fn = runRemediate) => {
- const result = await capture(() => fn(engine, args));
+ const approved = fn === runRemediate ? await approvedRemediateArgs(engine, args) : args;
+ const result = await capture(() => fn(engine, approved));
return { ...result, body: JSON.parse(result.out) };
};