Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(onboard): automatic remediation runs never submit manual-only steps (#6248)

time-attack257d960c5973
diff --git a/INSTALL_FOR_AGENTS.md b/INSTALL_FOR_AGENTS.md
index 3e095fcb4f..1253d9cf77 100644
--- a/INSTALL_FOR_AGENTS.md
+++ b/INSTALL_FOR_AGENTS.md
@@ -630,7 +630,7 @@ gbrain onboard --check --json
The JSON envelope (`schema_version: 1`) carries `recommendations[]` with
`apply_policy` per item: `auto_apply` (safe to run unattended),
`prompt_required` (needs explicit user consent), or `manual_only`
-(LLM-bearing, user must run themselves).
+(the schema-pack upgrade or the paid takes bootstrap; the user runs it).
**After every `gbrain upgrade`:**
```bash
@@ -644,7 +644,9 @@ step regardless.
```bash
gbrain onboard --auto --max-usd 5
```
-Refuses without `--max-usd N`. Runs auto-eligible items only. The
+Refuses without `--max-usd N`. Never runs a `manual_only` item: the
+result lists each under `manual_only_skipped` with the command for the
+user to run (`fix.next` is `tell_user_to_run`). The
autopilot daemon also consults onboard recommendations on its tick — no
explicit agent action needed for the autonomous path.
diff --git a/docs/architecture/key-files/commands-1.md b/docs/architecture/key-files/commands-1.md
index 3080138ef0..f3cc6a7b11 100644
--- a/docs/architecture/key-files/commands-1.md
+++ b/docs/architecture/key-files/commands-1.md
@@ -18,7 +18,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/commands/autopilot-pause.ts` — engine-free `gbrain autopilot pause [--reason <text>]` / `resume`: writes or removes the operator marker `autopilot-operator-paused` (`autopilotOperatorPauseMarkerPath` in `src/core/autopilot-paths.ts`, with `autopilotPaused()` and `autopilotPauseReason()`). The daemon loop and job workers honor it like the migration hold; `--install` (and so `gbrain upgrade`) clears only a leaked migration hold, and resume never clears a migration or restore hold. Test: `test/autopilot-operator-pause.test.ts`.
- `src/commands/autopilot.ts` — `gbrain autopilot --install`: self-maintaining brain daemon (sync+extract+embed). Freshness sync jobs always send an explicit positive-polarity `pull` value from `automaticSyncPull` (`src/core/persistence/automatic-sync-policy.ts`): a parsed `remote_url` on an unmanaged, unbound source, so local-only and managed sources skip pull and PGLite JSON-string configs behave like Postgres objects. Consumes `detectTini()` from `src/core/minions/spawn-helpers.ts`, resolved once at startup. Composes a `ChildWorkerSupervisor` instance for spawn-and-respawn with `--max-rss 2048` and soft `maxCrashes: 5`, preferring the current source/compiled CLI over PATH. The child worker performs private-queue recovery only after its driver/selected-child readiness and schema check; autopilot does not duplicate that recovery before spawn. A configuration-blocked child leaves the owning daemon alive and heartbeating but gates dispatch, worker restarts and engine work until explicit owner restart after repair. `--status --json` adds processing readiness, reason and runtime identities without replacing existing freshness/exit semantics; see [the owner-specific repair guide](../../guides/minions-fix.md). `onMaxCrashesExceeded` routes through autopilot's own `shutdown('max_crashes')` so the autopilot lockfile gets cleaned up. `shutdown()` drains via `childSupervisor.killChild('SIGTERM')` + `awaitChildExit(35_000)`. Pinned by `test/autopilot-fanout-wiring.test.ts` and `test/autopilot-supervisor-wiring.test.ts` (6 static-shape guards: composes ChildWorkerSupervisor not legacy names, `--max-rss 2048` in argv, `maxCrashes: 5` literal, shutdown-via-callback, no workerProc reference). tick body invokes `runNightlyQualityProbe` when `cfg.autopilot.nightly_quality_probe.enabled === true` (default OFF — opt-in to protect API spend). NO scheduler-side rate-limit check — `runNightlyQualityProbe`'s internal `shouldRunNightly` (reading the audit JSONL) is the single source of truth. Probe call wrapped in try/catch that logs via `logError` and does NOT bump `consecutiveErrors` (probe failure is informational, never crashes the loop). Default `max_usd` cap = 5. Pinned by `test/autopilot-nightly-probe-wiring.test.ts`. per-source `extract_atoms` auto-drain. Postgres-only block after the freshness fan-out: gated on `autopilot.auto_drain.enabled` (default true) AND `!packDeclaresPhase(engine,'extract_atoms')` (the silent-backlog condition) AND per-source `countExtractAtomsBacklog > threshold` (default 25) AND a daily cap `floor(max_usd_per_day / ~$0.30)`. Enumerates `loadAllSources`. Submits the PROTECTED `extract-atoms-drain` job (`{allowProtectedSubmit:true}`) with a UTC-day time-sloted idempotency key `autopilot-extract-atoms-drain:<src.id>:<utcDay>` (a static key would block the source after the first job completed). `src/core/minions/protected-names.ts` lists `extract-atoms-drain`; `src/commands/jobs.ts` registers the handler (thin wrapper over `runExtractAtomsDrainForSource`, `LockUnavailableError` → `{deferred:true}`; a `provider_failure` result throws `formatDrainProviderFailure(result)` — batches/remaining plus the drain's sanitized `last_error` — so the dead-lettered job's `error_text` names the cause, e.g. a missing provider key); `src/core/config.ts` carries the `autopilot.auto_drain.*` config keys + the `autopilot.` key prefix. Pinned by `test/extract-atoms-drain-handler.test.ts`, `test/autopilot-auto-drain-wiring.test.ts`. federated-brain co-existence + launchd hygiene. (1) `LOCK_PATH` resolves via `gbrainPath('autopilot.lock')` so it honors `GBRAIN_HOME` (two brains can run autopilot simultaneously without lock-stealing); lock file stores PID; `src/core/autopilot-lock.ts` checks liveness and the process command before takeover. `looksLikeGbrainAutopilotCommand` recognizes quoted or unquoted `cli.ts` / `cli.js` / `cli.mjs` paths, including spaces and normalized Windows separators, so a live matching autopilot retains even an old lock. Synthetic command-line and lock-decision cases are pinned by `test/autopilot-lock.test.ts`; they are not native Windows process-probe validation. (2) exported `classifyReconnectError(err)` returns `'recoverable' | 'unrecoverable'`; unrecoverable causes `process.exit(0)` so launchd backs off instead of looping `config.database_url undefined`. (3) exported pure `generateLaunchdPlist(wrapperPath, home)` sets `ThrottleInterval=300` so launchd respects the exit-0 backoff. Pinned by `test/autopilot-lock-path.test.ts` + `test/autopilot-reconnect-classifier.test.ts`. targeted-submit loop instead of blanket `autopilot-cycle` dispatch. Each tick: cheap `engine.getHealth()` (single SQL count) + `computeRecommendations()`, then route by shape — `score >= 95 AND no plan AND <60min since last full` → sleep; `score >= 95 AND >=60min` → submit `autopilot-cycle` (60-min floor exercises phase-coupling invariants on healthy brains); `plan <= 3 steps AND est <5min` → submit individual handlers; `plan large OR score < 70` → submit full `autopilot-cycle`. The `gbrain-cycle` lock ensures targeted submissions and the full cycle can't run concurrently. `maxWaiting: 1` per submit closes the queue-fan-out vector. daemon env lane: `writeWrapperScript` additively sources `<gbrainDir>/env` (honors `GBRAIN_HOME`) after the shell profiles with a `set -a` wrap so dotenv-style `KEY=value` lines export too, and creates a fully-commented 0600 template on install (never overwritten, never chmod'd, never removed by uninstall; template excludes `GBRAIN_HOME` — the wrapper bakes it AFTER sourcing). Exported pure `chatBootWarning(chatAvailable, gbrainDir)` derives both remediation paths from the passed dir and prints via `console.log` at daemon boot (stdout is the autopilot.log sink on all four targets; stderr lands in the unsurfaced autopilot.err) using the bare global-model `isAvailable('chat')` probe on purpose (mirrors the bare-gated phases; facts extraction is model-aware and doctor owns it). Install is reload-safe so the warning's re-run-`--install` remediation is true: launchd unloads before load (bare load errors on a loaded agent), systemd `try-restart`s after `enable --now`, cron/container print a residual-process notice instead of auto-killing. Pinned by `test/autopilot-install.test.ts` (16 cases incl. real-bash wrapper execution). Once processing is configuration-blocked, `guardAutopilotEngine` refuses new engine calls (except disconnect), guards transaction callback engines, and rolls back a transaction whose callback finishes after the block; already committed work is not revoked. Pinned by `test/autopilot-transaction-fence.test.ts`. #5195: install, status and uninstall act on one brain's job, named by `resolveAutopilotJob()` in `src/core/autopilot-paths.ts` (default brain: the shared names; any other brain: `<name>-<suffix>` from the random install id in `<brain>/.gbrain/autopilot-install-id`, with move/copy semantics); crontab lines carry `# gbrain-autopilot:<suffix>`; every log sink writes under the brain's home; a pre-#5195 shared job that runs this brain is replaced on install and reported by `--status` as `needs_reinstall: legacy_shared_job`; replacing or removing a job whose wrapper runs another live brain is refused (`autopilot_job_owned_by_other_brain`). Job-definition reads, legacy replacement and the `--status` job report live in `src/commands/autopilot/jobs.ts`. Pinned by `test/autopilot-install-id.test.ts` and `test/e2e/autopilot-multi-brain.serial.test.ts`.
- Size ceiling: `scripts/module-size-limits.tsv` (per-change raise history: `git log -p` on that file). The ceiling covers launchd/systemd/cron/container install and reload paths, the wrapper script with its env-file lane and exec guard, status and the self-upgrade channel. `runAutopilot` is a mode table (`AUTOPILOT_MODES`: --install, --uninstall, --status, --pause/--resume; first match wins) that otherwise lazily imports the daemon: `autopilot-daemon.ts` (`runAutopilotDaemon`: boot, lock, managed worker, shutdown and the tick loop over an explicit `AutopilotDaemonState`; steps `probeDatabaseOrReconnect`, `probeNoWorkerPeer`, `runInlineCycle`, `adaptiveInterval`), `autopilot-dispatch.ts` (`dispatchAutopilotTick`: freshness syncs, extract_atoms auto-drain, remediation plan, full-cycle fan-out or targeted submits) and `autopilot-probes.ts` (nightly quality and conversation-parser probes; the quality probe's `resolveNightlyProbeModelRoutesForDaemon` runs `refreshGatewayForJob`'s two gateway calls (inlined: importing `jobs.ts` would grant its flags to `autopilot` in the flag registry) and then reads the probe's model routes from the brain, only on a run past the 24h gate; both probes take their fixtures from `NIGHTLY_PROBE_FIXTURES`, the embedded assets, and the quality probe passes its cap source and `pricing.overrides` as `resolveBudgetPolicy`). No injectable single-tick function exists yet (TODOS: testable autopilot tick), so the wiring guards read these modules as source.
+ Size ceiling: `scripts/module-size-limits.tsv` (per-change raise history: `git log -p` on that file). The ceiling covers launchd/systemd/cron/container install and reload paths, the wrapper script with its env-file lane and exec guard, status and the self-upgrade channel. `runAutopilot` is a mode table (`AUTOPILOT_MODES`: --install, --uninstall, --status, --pause/--resume; first match wins) that otherwise lazily imports the daemon: `autopilot-daemon.ts` (`runAutopilotDaemon`: boot, lock, managed worker, shutdown and the tick loop over an explicit `AutopilotDaemonState`; steps `probeDatabaseOrReconnect`, `probeNoWorkerPeer`, `runInlineCycle`, `adaptiveInterval`), `autopilot-dispatch.ts` (`dispatchAutopilotTick`: freshness syncs, extract_atoms auto-drain, remediation plan, full-cycle fan-out or targeted submits; targeted submits go through `autopilotTargetedSteps` in `autopilot-remediation-policy.ts`, which drops manual-only steps) and `autopilot-probes.ts` (nightly quality and conversation-parser probes; the quality probe's `resolveNightlyProbeModelRoutesForDaemon` runs `refreshGatewayForJob`'s two gateway calls (inlined: importing `jobs.ts` would grant its flags to `autopilot` in the flag registry) and then reads the probe's model routes from the brain, only on a run past the 24h gate; both probes take their fixtures from `NIGHTLY_PROBE_FIXTURES`, the embedded assets, and the quality probe passes its cap source and `pricing.overrides` as `resolveBudgetPolicy`). No injectable single-tick function exists yet (TODOS: testable autopilot tick), so the wiring guards read these modules as source.
- `src/commands/autopilot-dispatch.ts` — one autopilot tick's submissions (`dispatchAutopilotTick`): freshness syncs, the extract_atoms auto-drain, the remediation plan, and full-cycle fan-out or targeted submits. The auto-drain (`dispatchAutoDrain` → `submitAutoDrains`) runs on Postgres only, unless `autopilot.auto_drain.enabled` is `false`, and only when the active pack does not run extract_atoms in the routine cycle. It submits a bounded, protected `extract-atoms-drain` job per source with a backlog under a per-source UTC-day idempotency key, so a structural refusal costs at most one dead job per source per day. The daily cap (`autopilot.auto_drain.max_usd_per_day` / the per-attempt `cycle.extract_atoms.budget_usd` estimate) counts attempts, not jobs (`autoDrainUnitsToday`: a waiting job one, a retried job one per started attempt), and excludes a job whose only attempt dead-lettered with `structural_refusal:`. Checkout-backed and connector sources alternate for free slots, with the next kind persisted in `AUTO_DRAIN_NEXT_KIND_KEY` (`autopilot.auto_drain.next_kind`) across ticks and days; a source whose writer preflight would refuse (`atomDrainOwnerRefusal`) is skipped with a logged reason; connector sources need no `local_path` and submit no `repoPath`. Tests: `test/autopilot-auto-drain*.test.ts`, `test/e2e/autopilot-auto-drain-dispatch.test.ts`. #5028: the auto-drain no longer skips when the active pack declares extract_atoms (the daemon's per-source cycles run only SOURCE_FRESHNESS_PHASES, so the declaration never made the routine cycle drain it); extract_atoms runs stamp `sources.config.last_extract_atoms_at` (`stampExtractAtomsRun` in `src/core/cycle/extract-atoms-stamp.ts`, which also builds the doctor warning), and the `extract_atoms_backlog` doctor check's declared branch warns when a backlog source's stamp is missing or older than 48h even though cycles run.
diff --git a/docs/architecture/key-files/core-utilities-1.md b/docs/architecture/key-files/core-utilities-1.md
index 7268025c53..5d5d864a16 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; a `spends: 'llm'` kind's step is `paid` and adds `llm_usd` (its paid-model estimate) to `est_usd_cost`, which is null when either part is unpriced; `runRepairSteps` applies them in-process for a trusted local caller only, refusing a paid step whose estimate exceeds the remaining cap before it starts and continuing with free steps; `effect` kinds reserve their embedding estimate against the cap up front (the consumer embeds outside the tracker), and an `inline` step is marked `budget_exhausted` when the tracker fired even if a callee swallowed the throw. A `spends: 'llm'` step never reserves its model estimate: it runs under the caller's tracker (never a nested `stepBudget` tracker) with what is left of the cap as `maxLlmUsd`, then `charge`s the part of its actual `cost.llm_usd` that `spentUsd()` did not already rise by during the step, so model spend counts once; a step its allowance stopped is `budget_exhausted`. `planRepairSteps`, `runRepairSteps` and `runRemediation`'s `repairs.registry` take stub specs for tests. The plan hash includes the brain id so brains on one host never share a checkpoint file. `run.ts`: `opts.repairs` (doctor CLI only) plans the repair steps and runs them when `include` is set, even when the target is unreachable (job steps are skipped then); a remote `include` refuses `permission_denied`. The cap is cumulative (`spent_usd` from the checkpoint plus this run's tracker, reservations and settled model spend); a refused paid step ends the run budget-exhausted and saves the checkpoint. Callers that omit `repairs` keep the job-only behavior. Plan and run preview through `planRepairStepsReport` (the strict `planRepairSteps` still propagates the first error), so a kind whose preview throws is reported as `repair_preview_failures` (code `timeout` for SQLSTATE 57014, naming `GBRAIN_STATEMENT_TIMEOUT`, else `preview_failed`; message redacted, then capped at 300 characters; `fix` is the rendered read-only `gbrain repair <kind>` preview) and the other kinds still plan and run. Each executed job step whose job moves a tracked metric (`impactMetricForJob`: embed / embed-catch-up: `countStaleChunks`; extract: `findOrphanPages` under the orphan-reporting policy, equal to get_health's orphan_pages without running `getHealth()`; extract-ner / extract-timeline-from-meetings: the onboard coverage checks' `visibleEntityCoverageSql`; extract-takes-from-pages: takes) records it before submit and once the job is terminal as one `migration_impact_log` row (`src/core/onboard/impact-capture.ts` `openStepImpact` / `closeStepImpact`, best-effort: a failed capture records null, a failed write only logs, and neither changes the step result), which `gbrain onboard --history` reads; dry runs, steps that throw before their job is terminal and unmapped jobs record nothing.
+- `src/core/remediation/` — the doctor remediation library (`computeRemediationPlan`, `runRemediation`, shared by doctor, onboard and MCP `run_onboard`). `repairs.ts`: `planRepairSteps` previews every registered repair kind brain-wide and returns PROTECTED steps (`requires_user_agreement`, exact `command`, `paid`, `est_usd_cost`), independent of the score target; a `spends: 'llm'` kind's step is `paid` and adds `llm_usd` (its paid-model estimate) to `est_usd_cost`, which is null when either part is unpriced; `runRepairSteps` applies them in-process for a trusted local caller only, refusing a paid step whose estimate exceeds the remaining cap before it starts and continuing with free steps; `effect` kinds reserve their embedding estimate against the cap up front (the consumer embeds outside the tracker), and an `inline` step is marked `budget_exhausted` when the tracker fired even if a callee swallowed the throw. A `spends: 'llm'` step never reserves its model estimate: it runs under the caller's tracker (never a nested `stepBudget` tracker) with what is left of the cap as `maxLlmUsd`, then `charge`s the part of its actual `cost.llm_usd` that `spentUsd()` did not already rise by during the step, so model spend counts once; a step its allowance stopped is `budget_exhausted`. `planRepairSteps`, `runRepairSteps` and `runRemediation`'s `repairs.registry` take stub specs for tests. The plan hash includes the brain id so brains on one host never share a checkpoint file. `run.ts`: `opts.repairs` (doctor CLI only) plans the repair steps and runs them when `include` is set, even when the target is unreachable (job steps are skipped then); a remote `include` refuses `permission_denied`. The cap is cumulative (`spent_usd` from the checkpoint plus this run's tracker, reservations and settled model spend); a refused paid step ends the run budget-exhausted and saves the checkpoint. Callers that omit `repairs` keep the job-only behavior. `manual-only.ts`: `isManualOnlyStep` (by job name: `unify-types`, `extract-takes-from-pages`; fail-closed without `protected`) is the one predicate the onboard renderer's `manual_only` label, `runRemediation` and autopilot's targeted dispatch share; the runner never submits such a step, initially or after a recheck, keeps its cost out of the `--max-usd` estimate and returns `manual_only_skipped` entries (`code`, `why`, rendered `fix`: `gbrain jobs submit <job> [--params <json>] --follow`, actor `user`, `consent: ['paid']` when paid; `queued_jobs` names rows of that job still waiting or active). 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/architecture/pack-upgrade-mechanism.md b/docs/architecture/pack-upgrade-mechanism.md
index 2d9b288bd7..727ea2b512 100644
--- a/docs/architecture/pack-upgrade-mechanism.md
+++ b/docs/architecture/pack-upgrade-mechanism.md
@@ -138,18 +138,23 @@ The shipped onboard contract has 3 apply_policy values:
| Policy | Meaning |
|--------|---------|
| `auto_apply` | Autopilot runs unattended |
-| `prompt_required` | Autopilot in `--auto-with-prompt` mode prompts user |
-| `manual_only` | Autopilot NEVER auto-fires; user must explicitly submit |
+| `prompt_required` | MCP `run_onboard` mode `auto-with-prompt` runs it |
+| `manual_only` | No automatic run submits it; the user submits it |
`pack_upgrade_available` emits a `RemediationStep` with `protected:
-true` + `job: 'unify-types'`. `toOnboardRecommendation` in
-`src/core/onboard/render.ts` maps this to `manual_only` via the
-`MANUAL_ONLY_PROTECTED_JOBS` allowlist (which also contains
-`extract-takes-from-pages`).
+true` + `job: 'unify-types'`. `isManualOnlyStep` in
+`src/core/remediation/manual-only.ts` decides manual-only by job name
+(`unify-types` and `extract-takes-from-pages`), even for a step without
+`protected: true`. `toOnboardRecommendation` labels with it, and
+`runRemediation` (behind `gbrain onboard --auto`, `doctor --remediate`
+and MCP `run_onboard`) never submits such a step: it returns it in
+`manual_only_skipped` with the user's own `gbrain jobs submit <job>
+--params <json> --follow` command. Autopilot's targeted dispatch
+filters it too.
Rationale: pack upgrades change the brain's taxonomy. Taxonomy is a
-user judgment call — not autopilot's call. Even with `--auto-with-
-prompt`, prompting the user to confirm a pack upgrade mid-tick is the
+user judgment call — not autopilot's call. Even in `auto-with-prompt`
+mode, prompting the user to confirm a pack upgrade mid-tick is the
wrong UX (the user came to fix orphans, not to be interrupted with
"hey want to migrate your taxonomy?"). Explicit submission is the
right boundary.
diff --git a/src/commands/autopilot-dispatch.ts b/src/commands/autopilot-dispatch.ts
index 30b624bb7b..c1f1086dbd 100644
--- a/src/commands/autopilot-dispatch.ts
+++ b/src/commands/autopilot-dispatch.ts
@@ -15,6 +15,7 @@ import { loadActivationPendingSourceIds, skipActivationPendingSync } from '../co
import { resolveAutopilotDispatchTimeoutMs } from './autopilot-timeout.ts';
import {
autopilotRemediationIdempotencyKey,
+ autopilotTargetedSteps,
shouldRunAutopilotFullCycle,
shouldSleepHealthyAutopilot,
} from './autopilot-remediation-policy.ts';
@@ -182,7 +183,7 @@ export async function dispatchAutopilotTick(
// the remediation slot forever (#4046).
// maxWaiting:1 per submit per codex #17 bounds the cross-window
// backlog if a targeted handler runs longer than one interval.
- for (const step of plan) {
+ for (const step of autopilotTargetedSteps(plan)) {
try {
const isProtected = !!step.protected;
const submitOpts = {
diff --git a/src/commands/autopilot-remediation-policy.ts b/src/commands/autopilot-remediation-policy.ts
index 340126ffbd..652cceabbf 100644
--- a/src/commands/autopilot-remediation-policy.ts
+++ b/src/commands/autopilot-remediation-policy.ts
@@ -1,3 +1,8 @@
+import type { RemediationStep } from '../core/remediation-step.ts';
+import { isManualOnlyStep } from '../core/remediation/manual-only.ts';
+
+export { isManualOnlyStep };
+
export const AUTOPILOT_FULL_CYCLE_FLOOR_MINUTES = 60;
export interface AutopilotRemediationPlanShape {
@@ -44,3 +49,8 @@ export function shouldSleepHealthyAutopilot(
&& planLength === 0
&& minutesSinceLastFull < AUTOPILOT_FULL_CYCLE_FLOOR_MINUTES;
}
+
+/** The steps a targeted dispatch submits: never a manual-only step. */
+export function autopilotTargetedSteps<T extends Pick<RemediationStep, 'job'>>(plan: readonly T[]): T[] {
+ return plan.filter((step) => !isManualOnlyStep(step));
+}
diff --git a/src/commands/onboard.ts b/src/commands/onboard.ts
index 9eb83e2a30..cb7b4343a1 100644
--- a/src/commands/onboard.ts
+++ b/src/commands/onboard.ts
@@ -9,8 +9,10 @@
//
// Three modes:
// --check (default): print plan, no submission
-// --auto: submit auto_apply tier (requires --max-usd)
-// --auto --yes: also submit prompt_required tier
+// --auto: run the plan's job steps (requires --max-usd); a
+// manual-only step (unify-types, takes bootstrap) is
+// never submitted and is reported with the user's
+// own command instead
// --history: show recent migration_impact_log entries
//
// `--json` switches to the stable JSON envelope. No CLI mode → human render.
@@ -31,7 +33,6 @@ function parseInt10(args: string[], flag: string): number | null {
export async function runOnboard(engine: BrainEngine, args: string[]): Promise<void> {
const check = args.includes('--check') || (!args.includes('--auto') && !args.includes('--history'));
const auto = args.includes('--auto');
- const yes = args.includes('--yes');
const history = args.includes('--history');
const jsonOutput = args.includes('--json');
// v0.42 (T16): --explain extends --check with per-cluster narrative
@@ -152,20 +153,11 @@ export async function runOnboard(engine: BrainEngine, args: string[]): Promise<v
// summary). extraRemediations (gathered above from runAllOnboardChecks)
// is threaded into the runner so the onboard-check remediations
// (extract-ner, extract-timeline-from-meetings, etc.) reach the planner
- // — the same wiring the --check path uses above.
+ // — the same wiring the --check path uses above. The runner never submits
+ // a manual-only step; it returns them as `manual_only_skipped`.
const result = await runRemediation(
engine,
- {
- targetScore,
- maxUsd,
- extraRemediations,
- // --auto --yes opts into the prompt_required tier too; library
- // doesn't distinguish auto_apply vs prompt_required, it just runs
- // every remediation in the plan. The plan-building side (T12 render)
- // does the tier distinction; for --auto without --yes, the CLI shell
- // would pre-filter the extras to auto_apply only. For now: pass
- // everything; CLI documents this is "everything" behavior.
- },
+ { targetScore, maxUsd, extraRemediations },
{
onTargetUnreachable: (target, ceiling) => {
process.stderr.write(
@@ -174,7 +166,7 @@ export async function runOnboard(engine: BrainEngine, args: string[]): Promise<v
);
},
onNothingToDo: (score, target) => {
- process.stdout.write(
+ (jsonOutput ? process.stderr : process.stdout).write(
`Brain at score ${score}/100, target ${target}/100. Nothing to do.\n`,
);
},
@@ -198,17 +190,29 @@ export async function runOnboard(engine: BrainEngine, args: string[]): Promise<v
},
);
- if (result.target_unreachable) process.exit(2);
-
if (jsonOutput) {
process.stdout.write(JSON.stringify(result, null, 2) + '\n');
- } else if (result.submitted.length > 0) {
- process.stdout.write(
- `\nBrain score: ${result.brain_score_initial} → ${result.brain_score_final} (target ${targetScore})\n` +
- `Submitted: ${result.submitted.length} job(s), ${result.aborted_count} aborted/failed\n`,
- );
+ } else {
+ if (result.submitted.length > 0) {
+ process.stdout.write(
+ `\nBrain score: ${result.brain_score_initial} → ${result.brain_score_final} (target ${targetScore})\n` +
+ `Submitted: ${result.submitted.length} job(s), ${result.aborted_count} aborted/failed\n`,
+ );
+ }
+ const manual = result.manual_only_skipped ?? [];
+ if (manual.length > 0) {
+ process.stdout.write(`\nNot run: ${manual.length} manual-only step(s). Review them with gbrain onboard --check, then run the ones you want yourself:\n`);
+ for (const m of manual) {
+ process.stdout.write(` - ${m.job}${(m.est_usd_cost ?? 0) > 0 ? ` (~$${(m.est_usd_cost ?? 0).toFixed(2)})` : ''}: ${m.fix.command}\n`);
+ for (const q of m.queued_jobs ?? []) {
+ process.stdout.write(` job #${q.id} (${q.status}) was queued by an earlier run and still runs; cancel it with gbrain jobs cancel ${q.id}\n`);
+ }
+ }
+ }
}
+ if (result.target_unreachable) process.exit(2);
+
const anyFailed = result.submitted.some(
(s) => s.status !== 'completed' && s.status !== 'submitted' && s.status !== 'dry_run',
);
diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.ts
index 94860e2fae..bc785c5081 100644
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@ -294,6 +294,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText }
{ since: 'WAVE12', text: 'The dream patterns breaker now counts deaths per source (`dream:patterns:source:<id>`), including runs cancelled at their timeout after paid work, so a brain whose patterns runs keep dying is refused at once after the upgrade; fix the cause, then `gbrain dream reset-key \'dream:patterns:source:<id>\'`. Pattern pages store a quarantined claim\'s reflection list once per page (`unverified_claim_sources`); the first patterns run rewrites existing pages that way (frontmatter only, no model call) before it pays for a run.' },
{ since: 'WAVE12', text: 'Dream triage no longer re-judges a transcript every cycle after a truncated, refused or unparseable verdict: it waits 24 hours, doubling per repeat up to 7 days (`triage_unreliable_backoff`), and a content or triage-model change re-judges at once; `gbrain dream retriage --force` re-judges now and pays per file.' },
{ since: 'WAVE12', text: 'A `gbrain dream` scoped to a source, including a bare `gbrain dream` on the default source, now also takes the brain-wide `gbrain-cycle` lease for synthesize, patterns, embed and the other brain-wide phases: while autopilot maintenance holds it, those phases are skipped as `maintenance_lock_busy` and the source phases still run, and autopilot maintenance skips its window while a dream holds it. `gbrain status --section locks --json` shows the holder.' },
+ { since: 'WAVE12', text: '`gbrain onboard --auto` (including cron runs), `doctor --remediate` and MCP `run_onboard` never submit a manual-only step: the schema-pack upgrade (`unify-types`) and the paid takes bootstrap (`extract-takes-from-pages`) are listed under `manual_only_skipped` with the command to run them yourself. A job of either kind an earlier run already queued still runs: find it with `gbrain jobs list --status waiting` and cancel it with `gbrain jobs cancel <id>` if you did not want it.' },
];
/** The newest disclosed change's release: the notice id moves only when a release adds rows. */
diff --git a/src/core/error-registry.ts b/src/core/error-registry.ts
index 100925ec2f..2d44c7d2c7 100644
--- a/src/core/error-registry.ts
+++ b/src/core/error-registry.ts
@@ -222,6 +222,7 @@ export const CODES = {
lock_busy: { class: 'retryable', summary: "Another process holds the lock this command needs." },
maintenance_lock_busy: { class: 'retryable', summary: "A source-scoped dream cycle skipped its brain-wide phases because another cycle (usually autopilot maintenance) holds the shared gbrain-cycle lease; its source phases still ran.", why: 'Brain-wide phases (synthesize, patterns, embed, purge and the other mixed or global phases) must not run twice at once, so a cycle that cannot take gbrain-cycle runs only the phases its own source lease covers.', docs: 'docs/guides/cron-schedule.md#dream-beside-autopilot', suggestion: 'Nothing is lost: the holder runs those phases itself. To run one now, wait until the lease is released, then re-run `gbrain dream --phase <phase>` (LLM-backed phases spend; ask the user first).', fix: { argv: ['gbrain', 'status', '--section', 'locks', '--json'], consent: [], actor: 'agent', why: 'Shows who holds gbrain-cycle and when its lease expires, read-only.', requires_exclusive: false } },
managed_pull_skipped: { class: 'retryable', summary: "The managed pull was skipped." },
+ manual_only_skipped: { class: 'consent', summary: "An automatic remediation run (`gbrain onboard --auto`, `doctor --remediate`, MCP `run_onboard`, autopilot) did not submit a manual-only step: the schema-pack upgrade (`unify-types`) or the paid takes bootstrap (`extract-takes-from-pages`).", why: "A pack upgrade retypes pages and switches the brain's schema pack, and the takes bootstrap pays a model per page; both are the user's one-time decision, so only the user submits them. A job of that kind an earlier run already queued is listed in `queued_jobs` and still runs unless cancelled.", actor: 'user', suggestion: 'Show the user the step and its `fix.command` (`gbrain jobs submit <job> --follow`, with `--params` when the step has them); the user runs it after reviewing `gbrain onboard --check`. Cancel a listed queued job with `gbrain jobs cancel <id>` if the user does not want it.', fix: { argv: ['gbrain', 'onboard', '--check', '--json'], consent: [], actor: 'agent', requires_exclusive: false, why: 'Lists the plan with each step\'s apply policy; manual-only steps are labeled manual_only.' } },
membership_inactive: { class: 'caller', summary: "The shared-skills enrollment epoch was left or superseded.", docs: 'docs/guides/shared-brain-skills.md#membership-inactive-after-a-re-enrollment' },
membership_not_found: { class: 'caller', summary: "This principal has no shared-skills membership with that installation id.", docs: 'docs/guides/shared-brain-skills.md#troubleshoot-leave-and-recover' },
method_not_allowed: { class: 'caller', summary: "The HTTP method is not allowed on this endpoint." },
diff --git a/src/core/minions/protected-names.ts b/src/core/minions/protected-names.ts
index 2a7619c02b..5cefc3ed3d 100644
--- a/src/core/minions/protected-names.ts
+++ b/src/core/minions/protected-names.ts
@@ -48,11 +48,11 @@ export const PROTECTED_JOB_NAMES: ReadonlySet<string> = new Set([
// v0.42 type-unification (T11, plan D17). Pack-upgrade migration that
// retypes 25K+ pages, creates 5K+ alias rows, converts edge-shaped
// pages to link rows, AND flips the active schema pack. One-time
- // consenting user decision. PROTECTED + manual_only in
- // src/core/onboard/render.ts:toOnboardRecommendation ensures autopilot
- // can't auto-apply; user must run `gbrain onboard --auto-with-prompt`
- // or submit explicitly via `gbrain jobs submit unify-types` (the local CLI
- // submit path sets allowProtectedSubmit for protected names itself).
+ // consenting user decision. PROTECTED + manual-only
+ // (src/core/remediation/manual-only.ts) ensures no automatic run submits
+ // it; the user submits it explicitly via `gbrain jobs submit unify-types`
+ // (the local CLI submit path sets allowProtectedSubmit for protected names
+ // itself).
'unify-types',
// v0.42.0.0 — SkillOpt: optimizer Sonnet/Opus loops over a benchmark.
// Preemptive register entry (v1 is CLI-only foreground; future Minion
diff --git a/src/core/onboard/checks.ts b/src/core/onboard/checks.ts
index 581710f0eb..2daba9a506 100644
--- a/src/core/onboard/checks.ts
+++ b/src/core/onboard/checks.ts
@@ -603,7 +603,7 @@ export async function checkPackUpgradeAvailable(
severity: 'medium',
est_seconds: 600, // ~10min on 186K-page brain (production proxy)
est_usd_cost: 0, // pure SQL; no LLM spend
- protected: true, // PROTECTED handler + manual_only via render allowlist
+ protected: true, // PROTECTED handler; manual-only by job name (remediation/manual-only.ts)
rationale:
`Pack upgrade ${active.manifest.name} → ${successor.manifest.name}; ` +
`collapses redundant page types into the new canonical taxonomy. ` +
diff --git a/src/core/onboard/render.ts b/src/core/onboard/render.ts
index f77cea03f6..423fc15b2f 100644
--- a/src/core/onboard/render.ts
+++ b/src/core/onboard/render.ts
@@ -5,6 +5,7 @@
import type { RemediationStep } from '../remediation-step.ts';
import type { RemediationPlan } from '../remediation/types.ts';
+import { isManualOnlyStep } from '../remediation/manual-only.ts';
import type {
OnboardRecommendation,
OnboardReport,
@@ -14,36 +15,13 @@ import type {
* Translate a RemediationStep into an OnboardRecommendation. Layers the
* apply_policy + prompt_text + migration_id metadata.
*
- * Rules of thumb for apply_policy:
- * - protected job (LLM-bearing) → 'prompt_required' or 'manual_only'
- * based on job name (takes-bootstrap stays manual_only per A12).
- * - non-protected (regex, SQL, etc.) → 'auto_apply'.
+ * apply_policy: a manual-only job (`isManualOnlyStep`, decided by job name,
+ * the same predicate the runner enforces) is 'manual_only'; any other
+ * protected job is 'prompt_required'; everything else is 'auto_apply'.
*/
-/**
- * v0.42 (D17): jobs that stay manual_only — autopilot will NOT surface
- * these as auto-apply candidates; user must explicitly run
- * `gbrain onboard --auto-with-prompt` or submit the handler directly.
- *
- * Membership criteria: one-time consenting decisions OR LLM-bearing
- * handlers without a mature eval. Adding a new entry here is a load-
- * bearing choice — confirm the apply_policy posture before commit.
- */
-const MANUAL_ONLY_PROTECTED_JOBS: ReadonlySet<string> = new Set([
- // v0.41.18.0 (A12, A24): takes-bootstrap classifier stays manual_only
- // until v0.42.1 lands the 100+-case eval.
- 'extract-takes-from-pages',
- // v0.42 (D17): pack-upgrade migration. Taxonomy change is a one-time
- // consenting user decision; autopilot must not auto-flip the schema pack.
- 'unify-types',
-]);
-
export function toOnboardRecommendation(step: RemediationStep): OnboardRecommendation {
- let apply_policy: OnboardRecommendation['apply_policy'] = 'auto_apply';
- if (step.protected) {
- // Manual-only allowlist takes precedence; everything else protected
- // is prompt_required (needs --yes but can run via --auto --yes).
- apply_policy = MANUAL_ONLY_PROTECTED_JOBS.has(step.job) ? 'manual_only' : 'prompt_required';
- }
+ const apply_policy: OnboardRecommendation['apply_policy'] = isManualOnlyStep(step) ? 'manual_only'
+ : step.protected ? 'prompt_required' : 'auto_apply';
return {
...step,
apply_policy,
diff --git a/src/core/remediation/manual-only.ts b/src/core/remediation/manual-only.ts
new file mode 100644
index 0000000000..0930b9a40a
--- /dev/null
+++ b/src/core/remediation/manual-only.ts
@@ -0,0 +1,40 @@
+// src/core/remediation/manual-only.ts
+// The manual-only remediation policy: jobs an automatic run (onboard --auto,
+// doctor --remediate, MCP run_onboard, autopilot) never submits. Kept
+// dependency-light so the runner, the onboard renderer and autopilot's policy
+// module share one predicate without importing each other.
+
+import type { Action } from '../agent-output.ts';
+import type { RemediationStep } from '../remediation-step.ts';
+
+/**
+ * Membership is a one-time consenting decision or an LLM-bearing handler
+ * without a mature eval. `paid` marks the handler's model spend even when a
+ * producer omits a cost estimate.
+ */
+const MANUAL_ONLY_JOBS: ReadonlyMap<string, { paid: boolean }> = new Map([
+ // Takes bootstrap: per-page model classifier over concept/atom/lore pages.
+ ['extract-takes-from-pages', { paid: true }],
+ // Pack upgrade: retypes pages and switches the active schema pack.
+ ['unify-types', { paid: false }],
+]);
+
+/** Decided by job name, so a producer that forgets `protected: true` still fails closed. */
+export function isManualOnlyStep(step: Pick<RemediationStep, 'job'>): boolean {
+ return MANUAL_ONLY_JOBS.has(step.job);
+}
+
+/** The user's own command for a skipped manual-only step. */
+export function manualOnlyFix(step: Pick<RemediationStep, 'job' | 'params' | 'est_usd_cost'>): Action {
+ const paid = (step.est_usd_cost ?? 0) > 0 || MANUAL_ONLY_JOBS.get(step.job)?.paid === true;
+ const cost = (step.est_usd_cost ?? 0) > 0 ? ` (estimated $${(step.est_usd_cost ?? 0).toFixed(2)})` : '';
+ return {
+ argv: ['gbrain', 'jobs', 'submit', step.job, ...(Object.keys(step.params).length ? ['--params', JSON.stringify(step.params)] : []), '--follow'],
+ consent: paid ? ['paid'] : [],
+ actor: 'user',
+ why: `${step.job} is manual-only: automatic runs never submit it, so it runs only when the user submits it${paid ? `; it calls the model provider and costs money${cost}` : ''}.`,
+ user_message: `The ${step.job} step was not run automatically. Review it (gbrain onboard --check), then run the command yourself if you want it.`,
+ verify: { argv: ['gbrain', 'onboard', '--check', '--json'] },
+ requires_exclusive: false,
+ };
+}
diff --git a/src/core/remediation/run.ts b/src/core/remediation/run.ts
index a53ca876fd..776ad4c146 100644
--- a/src/core/remediation/run.ts
+++ b/src/core/remediation/run.ts
@@ -21,8 +21,10 @@ import { loadRecommendationContext } from './context.ts';
import { computeRemediationPlan } from './plan.ts';
import { planRepairStepsReport, previewFailureField, runRepairSteps, type RepairPlanStep, type RepairPreviewFailure, type RepairStepResult } from './repairs.ts';
import { OperationError } from '../ops/contract.ts';
+import { isManualOnlyStep, manualOnlyFix } from './manual-only.ts';
import type { RemediationCheckpoint } from '../remediation-checkpoint.ts';
import type {
+ ManualOnlySkippedStep,
RemediationHooks,
RemediationOpts,
RemediationResult,
@@ -59,6 +61,42 @@ function planJobSteps(planned: RemediationStep[], manifest: { job_ids: string[]
};
}
+/**
+ * Holds manual-only steps out of a run's job steps. `withoutManualOnly`
+ * returns the other steps and records each remediable manual-only one once
+ * (`manual_only_skipped`), naming the rows of its job an earlier run already
+ * queued: they still run once a worker picks them up.
+ */
+function manualOnlySkips(engine: BrainEngine) {
+ const skipped: ManualOnlySkippedStep[] = [];
+ const withoutManualOnly = async (steps: RemediationStep[]): Promise<RemediationStep[]> => {
+ const manual = steps.filter((s) => isManualOnlyStep(s) && s.status === 'remediable' && !skipped.some((m) => m.id === s.id));
+ if (manual.length) {
+ const { cliRenderContext, renderAction } = await import('../agent-output.ts');
+ const queued = await engine.executeRaw<{ id: number | string; name: string; status: string }>(
+ `SELECT id, name, status FROM minion_jobs
+ WHERE name = ANY($1::text[]) AND status NOT IN ('completed', 'failed', 'dead', 'cancelled')
+ ORDER BY id`,
+ [[...new Set(manual.map((s) => s.job))]],
+ ).catch(() => []);
+ for (const step of manual) {
+ const jobs = queued.filter((q) => q.name === step.job).map((q) => ({ id: Number(q.id), status: q.status }));
+ skipped.push({
+ code: 'manual_only_skipped',
+ id: step.id, job: step.job, params: step.params,
+ ...(step.est_usd_cost !== undefined ? { est_usd_cost: step.est_usd_cost } : {}),
+ why: `${step.job} is manual-only, so this automatic run did not submit it`
+ + (jobs.length ? `; ${jobs.length} ${step.job} job(s) an earlier run queued (${jobs.map((j) => `#${j.id} ${j.status}`).join(', ')}) still run when a worker picks them up unless cancelled with gbrain jobs cancel <id>.` : '.'),
+ fix: renderAction(manualOnlyFix(step), cliRenderContext()),
+ ...(jobs.length ? { queued_jobs: jobs } : {}),
+ });
+ }
+ }
+ return steps.filter((s) => !isManualOnlyStep(s));
+ };
+ return { withoutManualOnly, field: () => (skipped.length ? { manual_only_skipped: skipped } : {}) };
+}
+
/**
* How a submitted step is awaited. PGLite has no background worker, and a
* Postgres queue may have none running: when the caller allows it and no
@@ -132,9 +170,10 @@ export async function runRemediation(
const extraRemediations = opts.extraRemediations ?? [];
const brainId = repairs ? (await (await import('../repair/core.ts')).resolveRepairScope(engine)).brain_id : undefined;
let previewFailures: RepairPreviewFailure[] = [];
+ const manualOnly = manualOnlySkips(engine);
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, ...previewFailureField(previewFailures), ...extra,
+ target_reached: false, submitted: [], aborted_count: 0, ...previewFailureField(previewFailures), ...manualOnly.field(), ...extra,
});
// Resume loads its checkpoint first: a checkpoint that records a manifest
@@ -171,7 +210,7 @@ export async function runRemediation(
// 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();
- const { freeRecs, jobStepsSkipped, recs: plannedJobSteps } = planJobSteps(computeRecommendations(initialHealth, ctx, extraRemediations), manifest,
+ const { freeRecs, jobStepsSkipped, recs: plannedJobSteps } = planJobSteps(await manualOnly.withoutManualOnly(computeRecommendations(initialHealth, ctx, extraRemediations)), manifest,
initialPlan.target_unreachable ? { target: targetScore, ceiling: initialPlan.max_reachable_score } : undefined);
if (jobStepsSkipped && freeRecs.length === 0 && !(includeRepairs && (repairSteps.length || pendingEmbedSources.length))) {
hooks.onTargetUnreachable?.(targetScore, initialPlan.max_reachable_score);
@@ -456,7 +495,7 @@ export async function runRemediation(
// ids this run already processed (any terminal status), or the recheck
// would resubmit completed extras every iteration, forever.
const pendingExtras = extraRemediations.filter((r) => !attemptedIds.has(r.id));
- recs = computeRecommendations(freshHealth, ctx, pendingExtras)
+ recs = (await manualOnly.withoutManualOnly(computeRecommendations(freshHealth, ctx, pendingExtras)))
.filter((r) => r.status === 'remediable' && !attemptedIds.has(r.id) && (!manifest || manifest.job_ids.includes(r.id))
&& (!jobStepsSkipped || (r.est_usd_cost ?? 0) === 0));
}
@@ -520,6 +559,6 @@ export async function runRemediation(
repairs: repairResults, repairs_skipped: skippedRepairs,
budget: { max_usd: maxUsd ?? null, spent_usd: settledUsd(), include_repairs: includeRepairs, plan_hash: planHash },
} : {}),
- ...previewFailureField(previewFailures),
+ ...previewFailureField(previewFailures), ...manualOnly.field(),
};
}
diff --git a/src/core/remediation/types.ts b/src/core/remediation/types.ts
index 5216b857ee..4f35849b02 100644
--- a/src/core/remediation/types.ts
+++ b/src/core/remediation/types.ts
@@ -12,6 +12,7 @@ import type { RemediationStep } from '../remediation-step.ts';
import type { RepairPlanStep, RepairPreviewFailure, RepairStepResult } from './repairs.ts';
import type { ExplicitRepairNotice, RepairKindSpec } from '../repair/registry.ts';
import type { CapSource } from '../consent.ts';
+import type { RenderedAction } from '../agent-output.ts';
/**
* Options for computeRemediationPlan. All fields are optional with
@@ -124,6 +125,22 @@ export interface StepResult {
deduped_job_id?: number;
}
+/**
+ * A planned manual-only step the run did not submit (`manual-only.ts`).
+ * `queued_jobs` lists rows of that job an earlier run already queued: they
+ * still run when a worker picks them up, so the skip does not prevent them.
+ */
+export interface ManualOnlySkippedStep {
+ code: 'manual_only_skipped';
+ id: string;
+ job: string;
+ params: Record<string, unknown>;
+ est_usd_cost?: number;
+ why: string;
+ fix: RenderedAction;
+ queued_jobs?: Array<{ id: number; status: string }>;
+}
+
/**
* Result of a full runRemediation invocation. Stable shape for JSON
* emission and MCP envelope.
@@ -154,6 +171,8 @@ export interface RemediationResult {
* ids) were not run; free job steps and included repair steps still ran.
*/
job_steps_skipped?: { reason: 'target_unreachable'; target: number; ceiling: number; skipped?: string[] };
+ /** Manual-only steps the plan held; never submitted by this run, and their cost is outside the --max-usd estimate. */
+ manual_only_skipped?: ManualOnlySkippedStep[];
/** Set when `--resume` refused (a checkpoint for another brain). */
resume_refused?: { reason: string; checkpoint_brain_id: string; brain_id: string; plan_hash: string };
/** Repair steps the run applied or refused (only when `repairs` was passed). */
diff --git a/test/remediation-impact-capture.test.ts b/test/remediation-impact-capture.test.ts
index 79944dd1e5..9cef03cb5b 100644
--- a/test/remediation-impact-capture.test.ts
+++ b/test/remediation-impact-capture.test.ts
@@ -129,8 +129,8 @@ describe('remediation writes onboard history (#6109)', () => {
test("a step whose job moves no tracked metric records nothing, even once it is terminal", async () => {
await seedUnextractedNote();
const unmapped = makeRemediationStep({
- id: 'onboard.unmapped-example', job: 'unify-types', params: { apply: false },
- severity: 'low', est_seconds: 30, est_usd_cost: 0, protected: true, rationale: 'synthetic unmapped job',
+ id: 'onboard.unmapped-example', job: 'orphans', params: {},
+ severity: 'low', est_seconds: 30, est_usd_cost: 0, rationale: 'synthetic unmapped job',
});
const { result } = await withStderr(() => runRemediation(engine, { targetScore: 0, inlineJobs: true, extraRemediations: [unmapped] }));
const unmappedStep = result.submitted.find((s) => s.id === 'onboard.unmapped-example');
diff --git a/test/remediation-manual-only.test.ts b/test/remediation-manual-only.test.ts
new file mode 100644
index 0000000000..0d8276b3d7
--- /dev/null
+++ b/test/remediation-manual-only.test.ts
@@ -0,0 +1,216 @@
+/**
+ * Manual-only remediation steps are never submitted by an automatic run (#6248).
+ *
+ * Protects: `runRemediation` (behind `gbrain onboard --auto`, `doctor
+ * --remediate` and MCP `run_onboard`) skips every manual-only step
+ * (`unify-types`, `extract-takes-from-pages`, decided by job name) and returns
+ * it as `manual_only_skipped` with the user's own command, keeps its cost out
+ * of the --max-usd estimate, and reports a job of that kind an earlier run
+ * already queued instead of claiming the skip prevented it. The onboard
+ * renderer labels by the same predicate, and autopilot's targeted dispatch
+ * filters it too.
+ * Fails when: the runner submits a manual-only step (initially or after the
+ * per-step recheck), trusts `protected` instead of the job name, refuses free
+ * steps because of a manual-only step's cost, or the fix/queued report drifts.
+ * Seams: none; real remediation with inline jobs on PGLite. The onboard and MCP cases run
+ * a background worker with stub handlers so a regression completes instead of
+ * waiting out the step timeout.
+ */
+import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { runRemediation } from '../src/core/remediation/index.ts';
+import { makeRemediationStep } from '../src/core/remediation-step.ts';
+import { toOnboardRecommendation } from '../src/core/onboard/render.ts';
+import { autopilotTargetedSteps } from '../src/commands/autopilot-remediation-policy.ts';
+import { MinionQueue } from '../src/core/minions/queue.ts';
+import { MinionWorker } from '../src/core/minions/worker.ts';
+import { operations, type OperationContext } from '../src/core/operations.ts';
+import { runOnboard } from '../src/commands/onboard.ts';
+import { resetPgliteState } from './helpers/reset-pglite.ts';
+
+let engine: PGLiteEngine;
+let schemaVersion: string;
+
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+ schemaVersion = (await engine.getConfig('version'))!;
+});
+
+afterAll(async () => {
+ await engine.disconnect();
+});
+
+beforeEach(async () => {
+ await resetPgliteState(engine);
+ await engine.setConfig('version', schemaVersion);
+});
+
+function step(id: string, job: string, opts: { params?: Record<string, unknown>; usd?: number; protected?: boolean } = {}) {
+ return makeRemediationStep({
+ id, job, params: opts.params ?? {}, severity: 'medium', est_seconds: 5, est_usd_cost: opts.usd ?? 0,
+ rationale: 'synthetic onboard-check extra', ...(opts.protected === undefined ? {} : { protected: opts.protected }),
+ });
+}
+
+const PACK = () => step('onboard.pack_upgrade_example', 'unify-types', { params: { target_pack: 'example-pack', apply: true }, protected: true });
+const TAKES = () => step('onboard.takes_bootstrap', 'extract-takes-from-pages', { usd: 5, protected: true });
+
+async function jobNames(): Promise<string[]> {
+ const rows = await engine.executeRaw<{ name: string }>('SELECT name FROM minion_jobs ORDER BY id');
+ return rows.map((r) => r.name);
+}
+
+async function quiet<T>(fn: () => Promise<T>): Promise<T> {
+ const write = process.stderr.write;
+ process.stderr.write = (() => true) as typeof process.stderr.write;
+ try { return await fn(); } finally { process.stderr.write = write; }
+}
+
+describe('runRemediation never submits a manual-only step', () => {
+ test('auto steps run across the per-step recheck; manual-only steps are skipped and reported', async () => {
+ const result = await quiet(() => runRemediation(engine, {
+ targetScore: 0, inlineJobs: true, maxJobs: 6,
+ extraRemediations: [step('onboard.extract_ner', 'extract-ner'), PACK(), TAKES(), step('onboard.extract_timeline', 'extract-timeline-from-meetings')],
+ }));
+ expect(result.submitted.map((s) => s.id).sort()).toEqual(['onboard.extract_ner', 'onboard.extract_timeline']);
+ expect((await jobNames()).sort()).toEqual(['extract-ner', 'extract-timeline-from-meetings']);
+ expect(result.manual_only_skipped?.map((m) => m.id)).toEqual(['onboard.pack_upgrade_example', 'onboard.takes_bootstrap']);
+ });
+
+ test('a manual-only job without protected:true is still skipped (decided by job name)', async () => {
+ const unflagged = step('onboard.pack_upgrade_unflagged', 'unify-types', { params: { target_pack: 'example-pack', apply: true }, protected: false });
+ const result = await quiet(() => runRemediation(engine, { targetScore: 0, inlineJobs: true, extraRemediations: [unflagged] }));
+ expect(result.submitted).toEqual([]);
+ expect(await jobNames()).toEqual([]);
+ expect(result.manual_only_skipped?.map((m) => m.id)).toEqual(['onboard.pack_upgrade_unflagged']);
+ expect(toOnboardRecommendation(unflagged).apply_policy).toBe('manual_only');
+ });
+
+ test('a $1 cap still runs the free steps beside a $5 manual-only step', async () => {
+ let refused = false;
+ const result = await quiet(() => runRemediation(engine,
+ { targetScore: 0, inlineJobs: true, maxUsd: 1, extraRemediations: [step('onboard.extract_ner', 'extract-ner'), TAKES()] },
+ { onBudgetRefused: () => { refused = true; } }));
+ expect(refused).toBe(false);
+ expect(result.budget_exhausted).toBeUndefined();
+ expect(result.submitted.map((s) => [s.id, s.status])).toEqual([['onboard.extract_ner', 'completed']]);
+ expect(await jobNames()).toEqual(['extract-ner']);
+ expect(result.manual_only_skipped?.map((m) => m.id)).toEqual(['onboard.takes_bootstrap']);
+ });
+
+ test('each skipped step carries the user\'s own command, paid consent when it costs money', async () => {
+ const result = await quiet(() => runRemediation(engine, { targetScore: 0, inlineJobs: true, extraRemediations: [PACK(), TAKES()] }));
+ const [pack, takes] = result.manual_only_skipped!;
+ expect(pack).toMatchObject({
+ code: 'manual_only_skipped', id: 'onboard.pack_upgrade_example', job: 'unify-types', params: { target_pack: 'example-pack', apply: true },
+ fix: {
+ argv: ['gbrain', 'jobs', 'submit', 'unify-types', '--params', '{"target_pack":"example-pack","apply":true}', '--follow'],
+ consent: [], actor: 'user', next: 'tell_user_to_run', verify: { argv: ['gbrain', 'onboard', '--check', '--json'] },
+ },
+ });
+ expect(takes).toMatchObject({
+ code: 'manual_only_skipped', job: 'extract-takes-from-pages', est_usd_cost: 5,
+ fix: { argv: ['gbrain', 'jobs', 'submit', 'extract-takes-from-pages', '--follow'], consent: ['paid'], actor: 'user', next: 'tell_user_to_run' },
+ });
+ expect(takes!.fix.command).toBe('gbrain jobs submit extract-takes-from-pages --follow');
+ expect(pack!.queued_jobs).toBeUndefined();
+ expect(await jobNames()).toEqual([]);
+ });
+
+ test('a unify-types job an earlier run queued is reported as still queued, not as prevented', async () => {
+ const queued = await new MinionQueue(engine).add('unify-types', { target_pack: 'example-pack', apply: true },
+ { queue: 'default', idempotency_key: 'earlier-run' }, { allowProtectedSubmit: true });
+ const result = await quiet(() => runRemediation(engine, { targetScore: 0, inlineJobs: true, extraRemediations: [PACK()] }));
+ const [pack] = result.manual_only_skipped!;
+ expect(pack!.queued_jobs).toEqual([{ id: queued.id, status: 'waiting' }]);
+ expect(pack!.why).toContain(`#${queued.id} waiting`);
+ expect(pack!.why).toContain('gbrain jobs cancel <id>');
+ const rows = await engine.executeRaw<{ id: number; status: string }>('SELECT id, status FROM minion_jobs');
+ expect(rows.map((r) => [Number(r.id), r.status])).toEqual([[queued.id, 'waiting']]);
+ });
+
+ test("doctor --remediate's runner options (repairs planned, inline jobs) skip it too", async () => {
+ const result = await quiet(() => runRemediation(engine, {
+ targetScore: 0, inlineJobs: true, repairs: { include: false, remote: false, registry: [] },
+ extraRemediations: [step('onboard.extract_ner', 'extract-ner'), PACK()],
+ }));
+ expect(result.submitted.map((s) => s.id)).toEqual(['onboard.extract_ner']);
+ expect(await jobNames()).toEqual(['extract-ner']);
+ expect(result.manual_only_skipped?.map((m) => m.id)).toEqual(['onboard.pack_upgrade_example']);
+ });
+
+ test('a dry run lists manual-only steps as skipped, never as would-run', async () => {
+ const result = await runRemediation(engine, { targetScore: 0, dryRun: true, extraRemediations: [step('onboard.extract_ner', 'extract-ner'), TAKES()] });
+ expect(result.submitted.map((s) => [s.id, s.status])).toEqual([['onboard.extract_ner', 'dry_run']]);
+ expect(result.manual_only_skipped?.map((m) => m.id)).toEqual(['onboard.takes_bootstrap']);
+ });
+});
+
+/**
+ * A fresh brain's onboard checks emit both manual-only steps: the takes
+ * bootstrap (opted in here) and the pack upgrade off the unset schema pack.
+ * Stub handlers let a regression that submits them complete instead of
+ * waiting out their step timeout.
+ */
+async function withStubWorker<T>(fn: () => Promise<T>): Promise<T> {
+ await engine.setConfig('takes.bootstrap_enabled', 'true');
+ const worker = new MinionWorker(engine, { queue: 'default', pollInterval: 50, healthCheckInterval: 0 });
+ worker.register('extract-takes-from-pages', async () => ({ stub: true }));
+ worker.register('unify-types', async () => ({ stub: true }));
+ const running = worker.start();
+ try { return await quiet(fn); } finally {
+ worker.stop();
+ await running;
+ }
+}
+
+async function onboardStdout(args: string[]): Promise<string> {
+ let out = '';
+ const write = process.stdout.write;
+ process.stdout.write = ((chunk: string | Uint8Array) => { out += String(chunk); return true; }) as typeof process.stdout.write;
+ try { await withStubWorker(() => runOnboard(engine, args)); } finally { process.stdout.write = write; }
+ return out;
+}
+
+describe('gbrain onboard --auto', () => {
+ test('--json: the document lists the skipped pack upgrade and takes bootstrap and nothing else lands on stdout', async () => {
+ const doc = JSON.parse(await onboardStdout(['--auto', '--max-usd', '10', '--target-score', '0', '--json'])) as {
+ submitted: unknown[]; manual_only_skipped?: Array<{ job: string; fix: { next: string; command: string } }>;
+ };
+ expect(doc.submitted).toEqual([]);
+ expect(doc.manual_only_skipped?.map((m) => [m.job, m.fix.next]).sort()).toEqual([
+ ['extract-takes-from-pages', 'tell_user_to_run'], ['unify-types', 'tell_user_to_run']]);
+ expect(await jobNames()).toEqual([]);
+ });
+
+ test('human output names each skipped step with its command', async () => {
+ const out = await onboardStdout(['--auto', '--max-usd', '10', '--target-score', '0']);
+ expect(out).toContain('Not run: 2 manual-only step(s).');
+ expect(out).toContain(' - extract-takes-from-pages (~$5.00): gbrain jobs submit extract-takes-from-pages --follow');
+ expect(out).toMatch(/ - unify-types: gbrain jobs submit unify-types --params '\{"target_pack":"[^"]+","apply":true\}' --follow/);
+ expect(await jobNames()).toEqual([]);
+ });
+});
+
+describe('MCP run_onboard with run_protected_onboard scope', () => {
+ test('never submits the takes bootstrap the onboard checks emit', async () => {
+ const run_onboard = operations.find((o) => o.name === 'run_onboard')!;
+ const ctx = { engine, config: {} as never, logger: console as never, dryRun: false, remote: true,
+ auth: { scopes: ['admin', 'run_protected_onboard'] } as never } as unknown as OperationContext;
+ const result = await withStubWorker(() => run_onboard.handler(ctx, { mode: 'auto', max_usd: 10, target_score: 0 })) as {
+ manual_only_skipped?: Array<{ job: string }>; skipped_missing_scope: unknown[];
+ };
+ expect(result.skipped_missing_scope).toEqual([]);
+ expect(result.manual_only_skipped?.map((m) => m.job)).toContain('extract-takes-from-pages');
+ expect(await jobNames()).not.toContain('extract-takes-from-pages');
+ });
+});
+
+describe('autopilot targeted dispatch', () => {
+ test('filters manual-only steps out of the targeted submit list', () => {
+ const auto = step('extract.stale', 'extract');
+ expect(autopilotTargetedSteps([auto, PACK(), TAKES()])).toEqual([auto]);
+ });
+});
diff --git a/test/remediation-run-extras.serial.test.ts b/test/remediation-run-extras.serial.test.ts
index 2b809e3e31..6f50013f61 100644
--- a/test/remediation-run-extras.serial.test.ts
+++ b/test/remediation-run-extras.serial.test.ts
@@ -113,7 +113,7 @@ describe('runRemediation extraRemediations threading', () => {
const { runRemediation } = await import('../src/core/remediation/run.ts');
submittedJobs.length = 0;
const paid = makeRemediationStep({
- id: 'onboard.paid_step', job: 'extract-takes-from-pages', params: {}, severity: 'medium', est_seconds: 5,
+ id: 'onboard.paid_step', job: 'enrich', params: {}, severity: 'medium', est_seconds: 5,
est_usd_cost: 2, rationale: 'synthetic paid extra', status: 'remediable',
});
let unreachable = false;