Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(migrations): v0.11.0 Phase F skips instead of wedging without a repo path (#6755)
garrytan5966f6ecdab7
diff --git a/docs/architecture/key-files/commands-1.md b/docs/architecture/key-files/commands-1.mdindex 00d32179f7..ca90dbe395 100644--- a/docs/architecture/key-files/commands-1.md+++ b/docs/architecture/key-files/commands-1.md@@ -3,7 +3,7 @@[Subsystem index](../KEY_FILES.md). Read only the entries relevant to your change.Current behavior and load-bearing invariants; history belongs in Git and CHANGELOG.-- `src/commands/apply-migrations.ts` and `src/commands/migrations/v0_11_0.ts` — forced dry-runs return a no-write action preview before opening a database or loading/copying the migration ledger. Any failed phase makes the migration partial, stops the chain and exits nonzero; ordinary pending-host-work partial results retain their resume behavior. Explicit `--force-retry` recovers a historical false-complete record. No-autopilot skips remain successful and do not install services. Every run except `--list` and `--dry-run` holds the orchestration lock (`src/core/migration-orchestration-lock.ts`) from before its first ledger write through its final status: a Postgres TTL lease row `gbrain-apply-migrations` in `gbrain_cycle_locks` (survives transaction-mode poolers; an unreachable database or a schema without the table runs unlocked until the preflight creates it), or on PGLite a native lock on `<datastore>.gbrain-migrations.lock`, separate from the datastore lock so orchestrators still open the datastore. A second runner prints `another apply-migrations is running (host …, pid …)` and exits 75; dead holders are taken over by the existing db-lock and kernel rules. The locked body returns its exit status so the lock is released before `process.exit`. Tests: `apply-migrations-safety.serial.test.ts`, `apply-migrations-orchestration-lock.test.ts`, `e2e/apply-migrations-orchestration-lock.test.ts` and `e2e/migration-preview-safety.test.ts`. D2 (`json: 'document'`): every `--json` path is one single-line document (`status` unconfigured/dry_run/listed/ok/partial/up_to_date, `plan`, `previews`, `results[]`, `retry_markers`, `schema`); a non-zero exit is one envelope leading with those keys (`invalid_params` exit 2, `migration_failed` with reasons, `migrations_pending` with `schema_pending`, `database_error` for `--require-db`, `migrations_running` exit 75, `migration_lease_lost` exit 1 with `lease`). #6089: the run never exits 0 with the schema behind (`src/commands/apply-migrations-schema.ts`); an applied reconcile re-check is not pending work, so with nothing else pending a schema the pre-flight left behind fails before the re-check, and after orchestrators the version is read again. #6028 diagnostic: `assertHeld` raises `MigrationLeaseLostError` (`migration_lease_lost`, details say whether the acquisition token and time still match, never the token) when the conflicting lease row names this pid and host, instead of `migrations_running`; tests `e2e/migration-lease-lost.test.ts`. A4: `Migration.effects` (v0.11.0: `persistent_install`, its Phase F autopilot install) is asked through `consentGate` before the orchestrator runs (skipped under `--no-autopilot-install` or on PGLite); `--yes`, `--non-interactive` (mapped to `persistent_install` only), a preapproval or a TTY yes authorize, otherwise exit 3. `applyMigrations()` returns `{exitCode, failure}` for in-process callers (post-upgrade); `runApplyMigrations()` exits. Child CLIs use `cliChildStdio()`. Tests: `test/cli-json-commands.test.ts`. the plan adds `pending_fresh_install` (unrun setup work on a brain `gbrain init` created; runs like `pending`, reported as expected work, never as a failed upgrade); `--list --json` prints one row per migration (`fresh_install: true` on init stamps) plus `next.argv` when work remains and a `wedged[]` entry (version, `fix.argv` `--force-retry <v>`) per wedged migration; a run that leaves a wedged migration (3+ consecutive partials) that no newer migration ran past (doctor's forward-progress rule, `forwardProgressPast` in `src/core/migration-ledger.ts`; a superseded wedge is listed as `wedged_superseded` in the plan and is history) never reports up to date: it fails `migrations_pending` reason `wedged` (exit 1, fix `next: ask_user`, verify `--list --json`), so `post-upgrade` exits non-zero and `gbrain upgrade` prints `Migrations: wedged`; tests `apply-migrations-wedged-6696.test.ts`; a phase's `argv` prints as its next step. Forced dry-runs return a no-write action preview before opening a database or loading/copying the migration ledger. Any failed phase makes the migration partial, stops the chain and exits nonzero; ordinary pending-host-work partial results retain their resume behavior. Explicit `--force-retry` recovers a historical false-complete record. No-autopilot skips remain successful and do not install services. Every run except `--list` and `--dry-run` holds the orchestration lock (`src/core/migration-orchestration-lock.ts`) from before its first ledger write through its final status: a Postgres TTL lease row `gbrain-apply-migrations` in `gbrain_cycle_locks` (survives transaction-mode poolers; an unreachable database or a schema without the table runs unlocked until the preflight creates it), or on PGLite a native lock on `<datastore>.gbrain-migrations.lock`, separate from the datastore lock so orchestrators still open the datastore. A second runner prints `another apply-migrations is running (host …, pid …)` and exits 75; dead holders are taken over by the existing db-lock and kernel rules. The locked body returns its exit status so the lock is released before `process.exit`. Tests: `apply-migrations-safety.serial.test.ts`, `apply-migrations-orchestration-lock.test.ts`, `e2e/apply-migrations-orchestration-lock.test.ts` and `e2e/migration-preview-safety.test.ts`.+- `src/commands/apply-migrations.ts` and `src/commands/migrations/v0_11_0.ts` — forced dry-runs return a no-write action preview before opening a database or loading/copying the migration ledger. Any failed phase makes the migration partial, stops the chain and exits nonzero; ordinary pending-host-work partial results retain their resume behavior. Explicit `--force-retry` recovers a historical false-complete record. No-autopilot skips remain successful and do not install services. Every run except `--list` and `--dry-run` holds the orchestration lock (`src/core/migration-orchestration-lock.ts`) from before its first ledger write through its final status: a Postgres TTL lease row `gbrain-apply-migrations` in `gbrain_cycle_locks` (survives transaction-mode poolers; an unreachable database or a schema without the table runs unlocked until the preflight creates it), or on PGLite a native lock on `<datastore>.gbrain-migrations.lock`, separate from the datastore lock so orchestrators still open the datastore. A second runner prints `another apply-migrations is running (host …, pid …)` and exits 75; dead holders are taken over by the existing db-lock and kernel rules. The locked body returns its exit status so the lock is released before `process.exit`. Tests: `apply-migrations-safety.serial.test.ts`, `apply-migrations-orchestration-lock.test.ts`, `e2e/apply-migrations-orchestration-lock.test.ts` and `e2e/migration-preview-safety.test.ts`. D2 (`json: 'document'`): every `--json` path is one single-line document (`status` unconfigured/dry_run/listed/ok/partial/up_to_date, `plan`, `previews`, `results[]`, `retry_markers`, `schema`); a non-zero exit is one envelope leading with those keys (`invalid_params` exit 2, `migration_failed` with reasons, `migrations_pending` with `schema_pending`, `database_error` for `--require-db`, `migrations_running` exit 75, `migration_lease_lost` exit 1 with `lease`). #6089: the run never exits 0 with the schema behind (`src/commands/apply-migrations-schema.ts`); an applied reconcile re-check is not pending work, so with nothing else pending a schema the pre-flight left behind fails before the re-check, and after orchestrators the version is read again. #6028 diagnostic: `assertHeld` raises `MigrationLeaseLostError` (`migration_lease_lost`, details say whether the acquisition token and time still match, never the token) when the conflicting lease row names this pid and host, instead of `migrations_running`; tests `e2e/migration-lease-lost.test.ts`. A4: `Migration.effects` (v0.11.0: `persistent_install`, its Phase F autopilot install) is asked through `consentGate` before the orchestrator runs (skipped under `--no-autopilot-install` or on PGLite); `--yes`, `--non-interactive` (mapped to `persistent_install` only), a preapproval or a TTY yes authorize, otherwise exit 3. `applyMigrations()` returns `{exitCode, failure}` for in-process callers (post-upgrade); `runApplyMigrations()` exits. Child CLIs use `cliChildStdio()`. Tests: `test/cli-json-commands.test.ts`. the plan adds `pending_fresh_install` (unrun setup work on a brain `gbrain init` created; runs like `pending`, reported as expected work, never as a failed upgrade); `--list --json` prints one row per migration (`fresh_install: true` on init stamps) plus `next.argv` when work remains and a `wedged[]` entry (version, `fix.argv` `--force-retry <v>`) per wedged migration; a run that leaves a wedged migration (3+ consecutive partials) that no newer migration ran past (doctor's forward-progress rule, `forwardProgressPast` in `src/core/migration-ledger.ts`; a superseded wedge is listed as `wedged_superseded` in the plan and is history) never reports up to date: it fails `migrations_pending` reason `wedged` (exit 1, fix `next: ask_user`, verify `--list --json`), so `post-upgrade` exits non-zero and `gbrain upgrade` prints `Migrations: wedged`; tests `apply-migrations-wedged-6696.test.ts`; every wedged-migration message (run envelope, `--list`, stderr, `gbrain upgrade`) points at the migration's partial rows in this brain's `migrations/completed.jsonl` (`phases[].detail`, if present) through `wedgedLedgerHint` (`src/core/migration-ledger.ts`); a phase's `argv` prints as its next step. v0.11.0 Phase F (`src/commands/migrations/v0_11_0-install.ts`) installs the autopilot only for the brain's `sync.repo_path`; without one it installs nothing, is `skipped` with the exact install command (the default source's `local_path`, else `<REPO_PATH>`), records an `autopilot-install-needs-repo` pending host-work item, and the migration completes; doctor's `minions_migration` line (`src/commands/doctor/checks/autopilot-install-pending.ts`) carries that argv (`persistent_install`) until an autopilot is installed for this brain. `clearRepoPathWedge` writes a `retry` marker (reason `phase_f_no_repo_path`) before the plan when every partial behind a v0.11.0 wedge failed only the install with the old bare command line; other wedges keep the `--force-retry` advice. Forced dry-runs return a no-write action preview before opening a database or loading/copying the migration ledger. Any failed phase makes the migration partial, stops the chain and exits nonzero; ordinary pending-host-work partial results retain their resume behavior. Explicit `--force-retry` recovers a historical false-complete record. No-autopilot skips remain successful and do not install services. Every run except `--list` and `--dry-run` holds the orchestration lock (`src/core/migration-orchestration-lock.ts`) from before its first ledger write through its final status: a Postgres TTL lease row `gbrain-apply-migrations` in `gbrain_cycle_locks` (survives transaction-mode poolers; an unreachable database or a schema without the table runs unlocked until the preflight creates it), or on PGLite a native lock on `<datastore>.gbrain-migrations.lock`, separate from the datastore lock so orchestrators still open the datastore. A second runner prints `another apply-migrations is running (host …, pid …)` and exits 75; dead holders are taken over by the existing db-lock and kernel rules. The locked body returns its exit status so the lock is released before `process.exit`. Tests: `apply-migrations-safety.serial.test.ts`, `apply-migrations-orchestration-lock.test.ts`, `e2e/apply-migrations-orchestration-lock.test.ts` and `e2e/migration-preview-safety.test.ts`.- `src/commands/migrations/run-engine.ts` — one PGLite engine for consecutive migrations of an apply-migrations run (each open starts an embedded Postgres, about 130 ms). `withRunEngineSession` wraps the locked run; `setRunEngineSharing` enables sharing for the opt-out read, each migration flagged `sharesRunEngine` (v0.11.0, v0.14.0, v0.22.4, v0.28.0, v0.53.0) and the post-orchestrator schema check, and disabling it (before an unflagged migration, `--list`, `--dry-run` or a consent prompt) closes the engine. `connectMigrationEngine` returns the shared engine with a no-op close while sharing, otherwise a new engine its caller closes (Postgres always). `releaseRunEngine` closes it before a `gbrain` child that needs the brain (v0.11.0's `jobs smoke`). A fresh setup's migration child opens the brain three times instead of eight (counting the `jobs smoke` child); the ledger it writes is pinned by `test/fixtures/goldens/setup/fresh-setup-migration-ledger.json`. Tests: `test/migrations-run-engine.test.ts`.- `src/commands/apply-migrations-schema.ts` — #6089 schema half of the apply-migrations exit contract. `connectAtSchemaVersion` connects the configured brain and reads `config.version` (pre-flight, `--force-schema`); the post-orchestrator check opens it through `connectMigrationEngine`. `checkSchemaAfterOrchestrators` re-reads the version after the orchestrators ran: on Postgres only when the pre-flight connected; on PGLite in-process once the orchestrators released the datastore (the pre-flight stays skipped, #1100; never a child process), applying the schema migrations under `--yes`/`--non-interactive`; a busy PGLite datastore is rethrown. `schemaPendingError` builds `migrations_pending` with reason `not_applied` (fix reruns with `--yes`), `still_behind` (after an authorized run) or `schema_unreadable` (both fix `next: report` with `gbrain doctor --json` as verify, never another `--yes`), each naming the pending schema versions. `reportDatabaseUnreachable` keeps an unreachable Postgres non-fatal but prints the `GBRAIN_DB_ACCESS <reason>` marker. Tests: `test/apply-migrations-schema-exit.test.ts` (PGLite, unreachable Postgres, post-upgrade, postinstall) and `test/e2e/apply-migrations-schema-exit.test.ts` (Postgres).@@ -18,7 +18,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/commands/auth.ts` — token management. `gbrain auth create/list/revoke/test` for legacy bearer tokens (`revoke-client` runs an atomic `DELETE...RETURNING` on `oauth_clients`; FK `ON DELETE CASCADE` on `oauth_tokens.client_id` and `oauth_codes.client_id` purges every active token + auth code in one transaction; `process.exit(1)` on no-such-client (idempotent). Legacy tokens stored as SHA-256 hashes in `access_tokens`; OAuth clients in `oauth_clients`; legacy tokens with no scopes grant grandfather to `read+write+admin` on the OAuth HTTP server (no migration); scoped tokens are honored at exactly their grant. Every SQL site routes through `sqlQueryForEngine(engine)` from `src/core/sql-query.ts` (and `executeRawJsonb` for the takes-holders `permissions` JSONB column) so `gbrain auth` works against PGLite; the takes-holders write goes through `executeRawJsonb(engine, sql, [name, hash], [{takes_holders:[...]}])` which round-trips with `jsonb_typeof = 'object'`. `register-client` accepts `--source <id>` (write authority, scalar), `--federated-read <S1,S2,...>` (read scope, array), and `--token-ttl <seconds>` (per-client access-token TTL persisted to `oauth_clients.token_ttl`, bounds `TOKEN_TTL_MIN_SECONDS`=60 to `TOKEN_TTL_MAX_SECONDS`=7,776,000/90d) and prints the resolved `Write source` + `Federated reads`; clients without a `source_id` backfill to `'default'` via migration v60. The registration core is the exported `registerScopedClient(sql, engine, name, parsed, opts)` — exit-free, print-free, injected-handle (engine-bound callers like `agent register` pass the dispatcher's engine; a second `withConfiguredSql` engine self-deadlocks PGLite's single-writer lock), returns a `RegisteredClient` data object and throws on failure; the thin CLI wrapper owns exit/print. Its printer `formatRegisterClientOutput` is a BYTE-PINNED contract (connect.ts's `defaultRegisterOAuthClient` regex-scrapes `Client ID:`/`Client Secret:` from it in production) — pinned by `test/auth-register-client-output-pin.test.ts`. `preflightOauthClientColumns(sql)` probes `information_schema.columns` for the optional columns (`token_ttl`, `surface`, `federated_read`, `source_id`, `deleted_at`) so statement shapes are decided BEFORE any transaction — Postgres/PGLite abort the whole tx on any statement error (25P02) and SqlQuery has no savepoint seam, so "catch 42703 and continue" inside a tx is impossible; skipped optional writes surface as `RegisteredClient.skipped` with an apply-migrations hint. `gbrain auth clients [--usage] [--days N] [--json]` lists clients with scopes, per-client surface, write source (`source_id`), federated reads (`federated_read`) and the operation snapshot — one projection-widened SELECT with a degrade ladder for pre-migration brains (drops the newest columns first, never errors); `clientOperationsView` reports four distinct operation states (SQL NULL = `operations: "all"` with `includes_future_operations: true` and a re-pin `fix` naming `auth rescope --client <id> --operations <list>` or `--profile`; `[]` = deny-all; an explicit list; `unavailable` when the schema predates `allowed_operations`) and marks soft-revoked clients (`deleted_at`) `revoked` with no fix (`test/auth-clients-operations.test.ts`, both engines); `tokenLifetimeClampedClients` reads the migration's `clamp_token_ttl` / `shorten_access_tokens` audit rows so the listing marks clients whose access-token lifetime an upgrade brought inside 90 days (`token_lifetime_clamped` in `--json`); the `TOKEN_TTL_*` bounds are re-exported from `src/core/grants/model.ts`; `--usage` joins per-client op-call counts via `src/core/mcp-usage.ts`. The bare `gbrain auth create <name>` form (no `--takes-holders`) mints a token via the exported pure `parseAuthCreateArgs(rest)`. Pinned by `test/auth-create-args.test.ts` + `test/auth-register-client-args.test.ts`. F3: `gbrain auth rescope` (`runRescope`) is the one grant editor for tokens (`--token`/`--id`) and OAuth clients (`--client`), with a bare-name resolver, `--migrate-legacy [--dry-run]`, and refusals printed as JSON on stdout under `--json`; `rescope-token`, `rescope-client` and `permissions set-takes-holders` are aliases routed through it.- `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`.+- `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`. `--install` without `--repo` uses `sync.repo_path`, else the default source's `local_path` (`src/commands/autopilot/install-repo.ts`), and refuses when neither is set; pinned by `test/autopilot-install-repo-fallback-6755.test.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; 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. `autopilot.git_pull` (#6451, wave 15 P7.2): `automaticGitPullDisabled` in `core/persistence/automatic-sync-policy.ts` is read first by `automaticSyncPull`, so a non-truthy value queues every remote source's sync with `pull: false` before any persistence read; `dispatchFreshnessSyncs` prints one `git_pull: off` line (`git_pull_disabled` NDJSON event under `--json`) per tick while it is off. Pinned by `test/autopilot-git-pull-optout-6451.test.ts`.diff --git a/skills/migrations/v0.11.0.md b/skills/migrations/v0.11.0.mdindex 43fef24492..df2af8caac 100644--- a/skills/migrations/v0.11.0.md+++ b/skills/migrations/v0.11.0.md@@ -167,6 +167,19 @@ the same shape + updated status. Or: edit the dispatcher, rerun`gbrain apply-migrations`, and let gbrain re-detect + updateautomatically (it dedupes on file path, so no duplicate rows).+## `type: autopilot-install-needs-repo`++The upgrade skipped the autopilot install (Phase F) because the brain has+no `sync.repo_path`: an upgrade installs no new background daemon on a+guess. The row's `install_argv` is the exact command; `repo` is the+default source's `local_path`, or null when the brain names no repo at+all (the argv then carries `<REPO_PATH>`; ask the user for the brain+repo's path). Installing a daemon is a persistent install, so ask the user+before you run it. `gbrain doctor` shows the same command as a+`minions_migration` line until an autopilot is installed for this brain;+an autopilot that is already installed clears it, and nothing else is+needed.+## When every TODO clears```bashdiff --git a/src/commands/apply-migrations.ts b/src/commands/apply-migrations.tsindex b273749c1c..76b2c25f6a 100644--- a/src/commands/apply-migrations.ts+++ b/src/commands/apply-migrations.ts@@ -35,7 +35,9 @@ import {forwardProgressPast,isPendingFreshInstall,MAX_CONSECUTIVE_PARTIALS,+ wedgedLedgerHint,} from '../core/migration-ledger.ts';+import { clearRepoPathWedge } from './migrations/v0_11_0-install.ts';import { shellQuote, type Effect } from '../core/agent-output.ts';import { writeJsonDocument } from '../core/cli-force-exit.ts';import { consentGate } from '../core/consent-cli.ts';@@ -321,7 +323,7 @@ function printList(plan: Plan, installed: string, dbProbe: DbProbeOutcome): voidconst needsWork = plan.pending.length + plan.partial.length;const setup = plan.pending_fresh_install.length;for (const m of plan.declined) console.log(`v${m.version} is declined by config (${m.optOut?.key} is false); turn it back on: gbrain config set ${m.optOut?.key} true`);- for (const m of plan.wedged) console.log(`v${m.version} is wedged (${MAX_CONSECUTIVE_PARTIALS}+ consecutive partial runs). Fix the cause in ~/.gbrain/upgrade-errors.jsonl, then: ${shellQuote(forceRetryArgv(m.version))}`);+ for (const m of plan.wedged) console.log(`v${m.version} is wedged (${MAX_CONSECUTIVE_PARTIALS}+ consecutive partial runs). Read ${wedgedLedgerHint()}, fix the cause, then: ${shellQuote(forceRetryArgv(m.version))}`);if (needsWork === 0 && setup === 0 && plan.wedged.length === 0) {console.log('All migrations up to date.');return;@@ -673,6 +675,7 @@ async function runLockedMigrations(// Pre-flight: schema drift (#1530) and the DB probe (#4364); see preflightSchema.const { schemaBehind, dbProbe } = await preflightSchema(cli, migrateSchema);+ if (!cli.list && !cli.dryRun) clearRepoPathWedge(loadCompletedMigrations());const completed = loadCompletedMigrations();const idx = indexCompleted(completed);await setRunEngineSharing(true);@@ -972,10 +975,10 @@ function failWedged(report: RunReport): number | undefined {report.doc.wedged = wedged.map(m => m.version);report.failure = opError('migrations_pending',`Migration ${versions} is wedged (${MAX_CONSECUTIVE_PARTIALS}+ consecutive partial runs with no completion), so the run did not complete every migration.`,- `Read ~/.gbrain/upgrade-errors.jsonl for the last failure, fix its cause, then clear it with \`${shellQuote(forceRetryArgv(wedged[0]!.version))}\` and run \`gbrain apply-migrations --yes\` again. Ask the user first.`,+ `Read ${wedgedLedgerHint()} for the last failure, fix its cause, then clear it with \`${shellQuote(forceRetryArgv(wedged[0]!.version))}\` and run \`gbrain apply-migrations --yes\` again. Ask the user first.`,{ reason: 'wedged', fix: { ask_user: true, argv: forceRetryArgv(wedged[0]!.version), consent: [], actor: 'agent', requires_exclusive: true,why: `Writes a 'retry' marker so the next run re-attempts v${wedged[0]!.version}; without fixing the cause the run partials again.`,- user_message: `gbrain migration ${versions} failed ${MAX_CONSECUTIVE_PARTIALS} or more times in a row. Fix the cause named in ~/.gbrain/upgrade-errors.jsonl, then clear it with ${shellQuote(forceRetryArgv(wedged[0]!.version))} and run gbrain apply-migrations --yes. Clear it now?`,+ user_message: `gbrain migration ${versions} failed ${MAX_CONSECUTIVE_PARTIALS} or more times in a row. Fix the cause recorded in ${wedgedLedgerHint()}, then clear it with ${shellQuote(forceRetryArgv(wedged[0]!.version))} and run gbrain apply-migrations --yes. Clear it now?`,verify: { argv: ['gbrain', COMMAND, '--list', '--json'] } } });return 1;}@@ -989,7 +992,7 @@ function reportWedgedMigrations(wedged: readonly Migration[], superseded: readonfor (const m of wedged) {console.error(`\nMigration v${m.version} is WEDGED (${MAX_CONSECUTIVE_PARTIALS}+ consecutive partials with no completion). ` +- `Check ~/.gbrain/upgrade-errors.jsonl for the last failure reasons, fix the underlying issue, then run:\n` ++ `Check ${wedgedLedgerHint()} for the last failure reasons, fix the underlying issue, then run:\n` +` gbrain apply-migrations --force-retry ${m.version}\n` +`Then run \`gbrain apply-migrations\` again (it asks for any approval the migration needs).`,);diff --git a/src/commands/autopilot.ts b/src/commands/autopilot.tsindex cfb325e05a..f8fb710aef 100644--- a/src/commands/autopilot.ts+++ b/src/commands/autopilot.ts@@ -52,6 +52,7 @@ import { detectInstallMethod, readInstallTargetFloor } from './upgrade.ts';import { evaluateQuietHours } from '../core/minions/quiet-hours.ts';import { inspectLock } from '../core/db-lock.ts';import { relativeSourceLocalPathSkipWarning } from '../core/sources-load.ts';+import { installRepoFallback } from './autopilot/install-repo.ts';// Path helpers live in a LEAF core module so other commands (gbrain migrate)// can read the daemon's state files without importing this one — a dynamic// import of a command module drags its whole flag surface into the importer's@@ -901,7 +902,7 @@ async function installDaemon(engine: BrainEngine, args: string[]) {console.error(guardMsg);process.exit(1);}- const rawRepoPath = parseArg(args, '--repo') || await engine.getConfig('sync.repo_path');+ const rawRepoPath = parseArg(args, '--repo') || await installRepoFallback(engine);if (!rawRepoPath) {console.error('No repo path. Use --repo or run gbrain sync --repo first.');process.exit(1);@@ -909,7 +910,7 @@ async function installDaemon(engine: BrainEngine, args: string[]) {// #3696: the daemon runs with an arbitrary cwd (launchd: `/`), so a// relative `--repo .` baked into the wrapper script resolves to a phantom// path at daemon runtime. Resolve NOW, against the installer's cwd.- // nosemgrep: javascript.lang.security.audit.path-traversal.path-join-resolve-traversal.path-join-resolve-traversal -- rawRepoPath is the local operator's own --repo CLI arg or the operator-written sync.repo_path config row; installDaemon is reachable only via `gbrain autopilot --install` on the trusted local CLI (never MCP/remote), and absolutizing it here IS the #3696 fix+ // nosemgrep: javascript.lang.security.audit.path-traversal.path-join-resolve-traversal.path-join-resolve-traversal -- rawRepoPath is the local operator's own --repo CLI arg, the operator-written sync.repo_path config row or the default source's local_path; installDaemon is reachable only via `gbrain autopilot --install` on the trusted local CLI (never MCP/remote), and absolutizing it here IS the #3696 fixconst repoPath = resolvePath(rawRepoPath);const forcedTarget = parseArg(args, '--target') as InstallTarget | undefined;diff --git a/src/commands/autopilot/install-repo.ts b/src/commands/autopilot/install-repo.tsnew file mode 100644index 0000000000..a57b86ed55--- /dev/null+++ b/src/commands/autopilot/install-repo.ts@@ -0,0 +1,18 @@+/**+ * The repo `gbrain autopilot --install` bakes into the daemon when no --repo+ * is given (#6755): sync.repo_path, else the default source's local_path. A+ * brain whose repo is a managed source keeps it only in sources.local_path,+ * so the config key alone refused an install the brain could name.+ */+import type { BrainEngine } from '../../core/engine.ts';++/** The default source's local_path, or null when it has none. */+export async function defaultSourceLocalPath(engine: BrainEngine): Promise<string | null> {+ const [row] = await engine.executeRaw<{ local_path: string | null }>(`SELECT local_path FROM sources WHERE id = 'default'`);+ return row?.local_path || null;+}++/** sync.repo_path, else the default source's local_path; null when neither is set. */+export async function installRepoFallback(engine: BrainEngine): Promise<string | null> {+ return (await engine.getConfig('sync.repo_path')) || defaultSourceLocalPath(engine);+}diff --git a/src/commands/doctor/checks/autopilot-install-pending.ts b/src/commands/doctor/checks/autopilot-install-pending.tsnew file mode 100644index 0000000000..002144bf8e--- /dev/null+++ b/src/commands/doctor/checks/autopilot-install-pending.ts@@ -0,0 +1,26 @@+/**+ * `minions_migration` line for a v0.11.0 Phase F the upgrade skipped because+ * the brain names no repo (#6755). Reads the pending host-work item Phase F+ * recorded and this brain's installed autopilot job (job files, crontab); no+ * engine. Quiet once an autopilot is installed for this brain.+ */+import type { Check } from '../../doctor.ts';+import { agentFix } from '../check-fix.ts';+import { autopilotInstallCommand, autopilotInstalledForBrain, pendingAutopilotInstall } from '../../migrations/v0_11_0-install.ts';++export function autopilotInstallPendingCheck(): Check | null {+ const todo = pendingAutopilotInstall();+ if (!todo || autopilotInstalledForBrain()) return null;+ const inputs = todo.repo === null+ ? [{ name: 'REPO_PATH', how: 'Ask the user for the path of the brain repo the autopilot should keep in sync (the directory gbrain sync imports).' }]+ : undefined;+ return {+ name: 'minions_migration',+ status: 'warn',+ message: `No autopilot is installed: the v0.11.0 upgrade skipped its install because sync.repo_path is unset. Install it: ${autopilotInstallCommand(todo.repo)}`,+ fix: agentFix(todo.install_argv,+ 'Installs the background maintenance daemon (sync, extract, embed) for this brain repo under the host supervisor; a persistent install, so ask the user first.',+ 'minions_migration', { consent: ['persistent_install'], ...(inputs ? { inputs } : {}) }),+ details: { pending_host_work: todo },+ };+}diff --git a/src/commands/doctor/checks/local-runtime.ts b/src/commands/doctor/checks/local-runtime.tsindex 02d097c41a..7a20d72781 100644--- a/src/commands/doctor/checks/local-runtime.ts+++ b/src/commands/doctor/checks/local-runtime.ts@@ -11,6 +11,7 @@ import { loadCompletedMigrations } from '../../../core/preferences.ts';import { MIGRATION_OPT_OUT_KEYS, declinedMigrations, indexCompletedEntries, isFreshInstallStamp, migrationLedgerSummary, trailingPartialCount } from '../../../core/migration-ledger.ts';import { VERSION } from '../../../version.ts';import { pendingFreshInstallCheck } from './pending-fresh-install.ts';+import { autopilotInstallPendingCheck } from './autopilot-install-pending.ts';import { compareVersions } from '../../migrations/index.ts';import { bootstrapDoctorChecks } from '../bootstrap-checks.ts';import { buildMemorableRelayCheck } from './integrations-memorable.ts';@@ -220,6 +221,8 @@ async function runMinionsMigration(ctx: DoctorContext): Promise<Check[]> {const setup = pendingFreshInstallCheck();if (setup) checks.push(setup);}+ const skippedInstall = autopilotInstallPendingCheck();+ if (skippedInstall) checks.push(skippedInstall);// Note: the "no preferences.json but schema is v7+" case is detected// in the DB section below (needs schema version).} catch (e) {diff --git a/src/commands/migrations/v0_11_0-install.ts b/src/commands/migrations/v0_11_0-install.tsnew file mode 100644index 0000000000..353c4120c8--- /dev/null+++ b/src/commands/migrations/v0_11_0-install.ts@@ -0,0 +1,161 @@+/**+ * v0.11.0 Phase F: the autopilot install, and an upgrade on a brain that names+ * no repo (#6755).+ *+ * Phase F installs the daemon only for the repo the brain names in+ * sync.repo_path, the same one `gbrain autopilot --install` resolves first.+ * Without it the phase installs nothing during an upgrade: it is skipped with+ * the exact install command (the default source's local_path when there is+ * one), a pending host-work item records that command, and doctor's+ * `minions_migration` line carries it until an autopilot is installed for+ * this brain. The migration completes instead of ending partial.+ *+ * The old Phase F ran the install anyway and wedged such brains after three+ * partials. `clearRepoPathWedge` writes the retry marker for a v0.11.0 wedge+ * whose partials all failed only the install with the old command line; the+ * new phase records its own failures with the repo it read, so it is cleared+ * at most once.+ */+import { appendFileSync, existsSync, mkdirSync, readFileSync } from 'fs';+import { dirname } from 'path';+import { shellQuote } from '../../core/agent-output.ts';+import { resolveAutopilotJob } from '../../core/autopilot-paths.ts';+import { cliChildStdio } from '../../core/cli-force-exit.ts';+import { gbrainPath, loadConfig, type GBrainConfig } from '../../core/config.ts';+import { indexCompletedEntries, statusForVersion, trailingPartialCount } from '../../core/migration-ledger.ts';+import { appendCompletedMigration, type CompletedMigrationEntry } from '../../core/preferences.ts';+import { execSync } from '../../core/spawn.ts';+import { detectInstalledJob } from '../autopilot/jobs.ts';+import { defaultSourceLocalPath } from '../autopilot/install-repo.ts';+import { gbrainChildCommand } from './in-process.ts';+import { connectMigrationEngine } from './run-engine.ts';+import type { OrchestratorOpts, OrchestratorPhaseResult } from './types.ts';++export const AUTOPILOT_INSTALL_TODO = 'autopilot-install-needs-repo';+const REPO_INPUT = 'REPO_PATH';+/** The old Phase F's failure detail: execSync's message for the bare install command. */+const OLD_REFUSAL_DETAIL = /^Command failed: .*\bautopilot --install --yes$/;++export interface AutopilotInstallTodo {+ type: typeof AUTOPILOT_INSTALL_TODO;+ status: 'pending' | 'complete';+ detected_at: string;+ repo: string | null;+ install_argv: string[];+ recommendation: string;+}++const pendingHostWorkPath = () => gbrainPath('migrations', 'pending-host-work.jsonl');++/** The install command for this brain; `<REPO_PATH>` when the brain names no repo at all. */+export function autopilotInstallArgv(repo: string | null): string[] {+ return ['gbrain', 'autopilot', '--install', '--yes', '--repo', repo ?? `<${REPO_INPUT}>`];+}++export function autopilotInstallCommand(repo: string | null): string {+ return repo ? shellQuote(autopilotInstallArgv(repo)) : autopilotInstallArgv(null).join(' ');+}++/** The newest pending install item Phase F recorded, or null. */+export function pendingAutopilotInstall(): AutopilotInstallTodo | null {+ if (!existsSync(pendingHostWorkPath())) return null;+ let found: AutopilotInstallTodo | null = null;+ for (const line of readFileSync(pendingHostWorkPath(), 'utf-8').split('\n')) {+ try {+ const row = JSON.parse(line) as AutopilotInstallTodo;+ if (row.type === AUTOPILOT_INSTALL_TODO && row.status === 'pending') found = row;+ } catch { /* blank or malformed line */ }+ }+ return found;+}++/** Record the skipped install as a pending host-work item, once per install command. */+export function recordSkippedAutopilotInstall(repo: string | null): void {+ const argv = autopilotInstallArgv(repo);+ if (pendingAutopilotInstall()?.install_argv.join('\0') === argv.join('\0')) return;+ const todo: AutopilotInstallTodo = {+ type: AUTOPILOT_INSTALL_TODO,+ status: 'pending',+ detected_at: new Date().toISOString(),+ repo,+ install_argv: argv,+ recommendation: repo+ ? `The upgrade installed no autopilot because sync.repo_path is unset. Install it for this brain's repo: ${autopilotInstallCommand(repo)}`+ : `The upgrade installed no autopilot because the brain names no repo (no sync.repo_path, no default source path). Install it with the brain repo's path: ${autopilotInstallCommand(null)}`,+ };+ mkdirSync(dirname(pendingHostWorkPath()), { recursive: true });+ appendFileSync(pendingHostWorkPath(), JSON.stringify(todo) + '\n');+}++/** Whether an autopilot job for this brain is installed under any supervisor target. */+export function autopilotInstalledForBrain(): boolean {+ try { return detectInstalledJob(resolveAutopilotJob()).installed !== null; } catch { return false; }+}++async function readRepoPaths(config: GBrainConfig | null): Promise<{ syncRepoPath: string | null; defaultSourcePath: string | null }> {+ if (!config) throw new Error('no brain configured');+ const { engine, close } = await connectMigrationEngine(config);+ try {+ const syncRepoPath = (await engine.getConfig('sync.repo_path')) || null;+ return { syncRepoPath, defaultSourcePath: syncRepoPath ? null : await defaultSourceLocalPath(engine) };+ } finally { await close(); }+}++function skipWithoutRepo(defaultSourcePath: string | null): OrchestratorPhaseResult {+ if (autopilotInstalledForBrain()) {+ return { name: 'install', status: 'skipped', detail: 'sync.repo_path is unset and an autopilot is already installed for this brain; left as is' };+ }+ recordSkippedAutopilotInstall(defaultSourcePath);+ const command = autopilotInstallCommand(defaultSourcePath);+ console.log(`No autopilot was installed: sync.repo_path is unset. Install it when you want background maintenance: ${command} `+ + `(recorded in ${pendingHostWorkPath()}; gbrain doctor shows it until an autopilot is installed)`);+ return {+ name: 'install', status: 'skipped', detail: `sync.repo_path is unset, so the upgrade installed no autopilot. Install it: ${command}`,+ ...(defaultSourcePath ? { argv: autopilotInstallArgv(defaultSourcePath) } : {}),+ };+}++export async function phaseFInstall(opts: OrchestratorOpts): Promise<OrchestratorPhaseResult> {+ if (opts.dryRun) return { name: 'install', status: 'skipped', detail: 'dry-run' };+ if (opts.noAutopilotInstall) return { name: 'install', status: 'skipped', detail: '--no-autopilot-install' };+ let repoNote = 'repo path not read';+ try {+ const config = loadConfig();+ if (config?.engine === 'pglite') {+ return { name: 'install', status: 'skipped', detail: 'PGLite is single-writer; use gbrain serve for background maintenance' };+ }+ try {+ const repo = await readRepoPaths(config);+ if (!repo.syncRepoPath) return skipWithoutRepo(repo.defaultSourcePath);+ repoNote = `sync.repo_path ${repo.syncRepoPath}`;+ } catch (e) {+ repoNote = `repo path unreadable (${e instanceof Error ? e.message : String(e)}); the install resolves it itself`;+ }+ execSync(gbrainChildCommand('gbrain autopilot --install --yes'), { stdio: cliChildStdio(), timeout: 60_000, env: process.env });+ return { name: 'install', status: 'complete' };+ } catch (e) {+ return { name: 'install', status: 'failed', detail: `${repoNote}: ${e instanceof Error ? e.message : String(e)}` };+ }+}++function failedOnlyOnOldRefusal(entry: CompletedMigrationEntry): boolean {+ const failed = (entry.phases ?? []).filter(phase => phase.status === 'failed');+ return failed.length === 1 && failed[0]!.name === 'install' && OLD_REFUSAL_DETAIL.test((failed[0]!.detail ?? '').trim());+}++/**+ * Un-wedge v0.11.0 when every partial behind the wedge failed only Phase F+ * with the old install command line: writes a `retry` marker (reason+ * `phase_f_no_repo_path`) and says so. Returns whether it wrote one. Any+ * other wedge keeps the runner's `--force-retry` advice.+ */+export function clearRepoPathWedge(completed: readonly CompletedMigrationEntry[]): boolean {+ const byVersion = indexCompletedEntries([...completed]);+ if (statusForVersion('0.11.0', byVersion) !== 'wedged') return false;+ const history = byVersion.get('0.11.0') ?? [];+ if (!history.slice(history.length - trailingPartialCount(history)).every(failedOnlyOnOldRefusal)) return false;+ appendCompletedMigration({ version: '0.11.0', status: 'retry', reason: 'phase_f_no_repo_path' });+ console.error('Cleared the v0.11.0 wedge: every partial run failed only on the autopilot install that had no repo path. '+ + 'This version skips that install, so the migration runs again now.');+ return true;+}diff --git a/src/commands/migrations/v0_11_0.ts b/src/commands/migrations/v0_11_0.tsindex d657350c2f..e9e2705c31 100644--- a/src/commands/migrations/v0_11_0.ts+++ b/src/commands/migrations/v0_11_0.ts@@ -15,7 +15,8 @@* ~/.gbrain/migrations/pending-host-work.jsonl so the host* agent can walk through its plugin-contract work per* skills/migrations/v0.11.0.md.- * F. Install — gbrain autopilot --install (env-aware).+ * F. Install — gbrain autopilot --install (env-aware); skipped with the+ * exact command when sync.repo_path is unset (v0_11_0-install.ts).* G. Record — append completed.jsonl (status: complete unless any* pending-host-work items remain).*/@@ -26,9 +27,10 @@ import { execSync } from '../../core/spawn.ts';import type { Migration, OrchestratorOpts, OrchestratorResult, OrchestratorPhaseResult } from './types.ts';import { gbrainChildCommand } from './in-process.ts';import { releaseRunEngine } from './run-engine.ts';+import { phaseFInstall } from './v0_11_0-install.ts';import { cliChildStdio } from '../../core/cli-force-exit.ts';import { savePreferences, loadPreferences } from '../../core/preferences.ts';-import { loadConfig, configPath, gbrainPath } from '../../core/config.ts';+import { configPath, gbrainPath } from '../../core/config.ts';// Bug 3 — appendCompletedMigration moved to the runner (apply-migrations.ts).import { promptLine } from '../../core/cli-util.ts';import { VERSION } from '../../version.ts';@@ -406,24 +408,6 @@ async function phaseEHost(opts: OrchestratorOpts): Promise<{};}-// ------------------------------------------------------------------------// Phase F — Autopilot install-// -------------------------------------------------------------------------function phaseFInstall(opts: OrchestratorOpts): OrchestratorPhaseResult {- if (opts.dryRun) return { name: 'install', status: 'skipped', detail: 'dry-run' };- if (opts.noAutopilotInstall) return { name: 'install', status: 'skipped', detail: '--no-autopilot-install' };- try {- if (loadConfig()?.engine === 'pglite') {- return { name: 'install', status: 'skipped', detail: 'PGLite is single-writer; use gbrain serve for background maintenance' };- }- execSync(gbrainChildCommand('gbrain autopilot --install --yes'), { stdio: cliChildStdio(), timeout: 60_000, env: process.env });- return { name: 'install', status: 'complete' };- } catch (e) {- return { name: 'install', status: 'failed', detail: e instanceof Error ? e.message : String(e) };- }-}-// -----------------------------------------------------------------------// Orchestrator// -----------------------------------------------------------------------@@ -459,7 +443,7 @@ async function orchestrator(opts: OrchestratorOpts): Promise<OrchestratorResult>const { phase: e, files_rewritten, pending_host_work } = await phaseEHost(opts);phases.push(e);- const f = phaseFInstall(opts);+ const f = await phaseFInstall(opts);phases.push(f);// Bug 3 — Phase G (record in completed.jsonl) moved to the runner. Thediff --git a/src/commands/upgrade.ts b/src/commands/upgrade.tsindex 8a4ec99c00..c84b496f9e 100644--- a/src/commands/upgrade.ts+++ b/src/commands/upgrade.ts@@ -8,7 +8,7 @@ import { opError, type OperationError } from '../core/ops/contract.ts';import { writeCliError } from '../cli/cli-error.ts';import { VERSION } from '../version.ts';import type { InteractiveProbe } from '../core/interaction.ts';-import { forwardProgressPast, migrationLedgerSummary } from '../core/migration-ledger.ts';+import { forwardProgressPast, migrationLedgerSummary, wedgedLedgerHint } from '../core/migration-ledger.ts';import { loadCompletedMigrations } from '../core/preferences.ts';import { MIGRATIONS_RUNNING_EXIT_CODE, readMigrationLockHolder } from '../core/migration-orchestration-lock.ts';import { loadConfig } from '../core/config.ts';@@ -412,7 +412,7 @@ export async function describeMigrationFailure(error: unknown, newVersion: strinconst ledger = newVersion ? loadCompletedMigrations() : [];const wedged = newVersion ? migrationLedgerSummary(newVersion).wedged.filter(v => forwardProgressPast(v, ledger) === null) : [];if (wedged.length > 0) {- return `Migrations: wedged (${wedged.map(v => `v${v}`).join(', ')} ended partial 3+ times in a row). Fix the cause in ~/.gbrain/upgrade-errors.jsonl, then run: `+ return `Migrations: wedged (${wedged.map(v => `v${v}`).join(', ')} ended partial 3+ times in a row). Fix the cause recorded in ${wedgedLedgerHint()}, then run: `+ `${wedged.map(v => `gbrain apply-migrations --force-retry ${v}`).join(' && ')} && gbrain apply-migrations --yes`;}return 'Migrations: failed. Run: gbrain apply-migrations --yes';diff --git a/src/core/migration-ledger.ts b/src/core/migration-ledger.tsindex 943b473876..826dd0a153 100644--- a/src/core/migration-ledger.ts+++ b/src/core/migration-ledger.ts@@ -14,7 +14,7 @@*/import type { BrainEngine } from './engine.ts';-import { loadCompletedMigrations, type CompletedMigrationEntry } from './preferences.ts';+import { loadCompletedMigrations, preferencesPaths, type CompletedMigrationEntry } from './preferences.ts';/*** Version strings of every registered host migration, in registry order.@@ -54,6 +54,11 @@ export async function declinedMigrations(engine: Pick<BrainEngine, 'getConfig'>)/** Bug 3 attempt cap — consecutive partials before a version counts wedged. */export const MAX_CONSECUTIVE_PARTIALS = 3;+/** Where a wedged migration's failure reasons are recorded: its partial rows in this brain's completion ledger (not every partial row carries phases). */+export function wedgedLedgerHint(): string {+ return `the migration's partial rows in ${preferencesPaths.completedJsonl()} (phases[].detail, if present)`;+}+/*** Compare two semver strings (MAJOR.MINOR.PATCH). Returns -1 / 0 / 1.* Canonical home (moved from src/commands/migrations/index.ts, whichdiff --git a/test/apply-migrations-safety.serial.test.ts b/test/apply-migrations-safety.serial.test.tsindex 4eec22c8c1..a657c2e94c 100644--- a/test/apply-migrations-safety.serial.test.ts+++ b/test/apply-migrations-safety.serial.test.ts@@ -242,3 +242,165 @@ await runApplyMigrations(process.argv.slice(2));});}});++/**+ * #6755: Phase F on a Postgres brain with no sync.repo_path. The child scripts+ * stub the schema step, the orchestration lock and the engine (sync.repo_path+ * and the default source's local_path are the fixture's), and a PATH shim+ * stands in for the gbrain child, logging every invocation.+ */+describe('v0.11.0 Phase F without a repo path (#6755)', () => {+ const OLD_REFUSAL = "Command failed: '/opt/bun' '/opt/gbrain/src/cli.ts' autopilot --install --yes";+ const phaseRows = (installDetail: string) => [+ { name: 'schema', status: 'complete' }, { name: 'smoke', status: 'complete' }, { name: 'mode', status: 'complete' },+ { name: 'prefs', status: 'complete' }, { name: 'host', status: 'complete' },+ { name: 'install', status: 'failed', detail: installDetail }, { name: 'record', status: 'complete' },+ ];++ async function postgresBrain(brain: { syncRepoPath?: string; defaultSourcePath?: string }, run: (h: {+ home: string; ledger: string; calls: () => string; apply: (args: string[]) => { exitCode: number | null; stdout: string; stderr: string };+ script: (body: string) => { exitCode: number | null; stdout: string; stderr: string };+ }) => Promise<void>): Promise<void> {+ await fixture(async (home, ledger) => {+ writeFileSync(join(home, '.gbrain/config.json'), JSON.stringify({ engine: 'postgres', database_url: 'postgresql://fixture:[email protected]:1/gbrain_test' }));+ const bin = join(home, 'bin');+ mkdirSync(bin);+ const callsPath = join(home, 'calls.log');+ writeFileSync(callsPath, '');+ writeFileSync(join(bin, 'gbrain'), `#!/bin/sh\nprintf '%s\\n' "$*" >> '${callsPath}'\nexit 0\n`, { mode: 0o755 });+ const env: Record<string, string> = { HOME: home, GBRAIN_HOME: home, PATH: `${bin}:${process.env.PATH ?? ''}` };+ const setup = `+import { mock } from 'bun:test';+import { LATEST_VERSION } from ${JSON.stringify(join(root, 'src/core/migrate.ts'))};+const migrationSetup = await import(${JSON.stringify(join(root, 'src/commands/migrations/in-process.ts'))});+mock.module(${JSON.stringify(join(root, 'src/commands/migrations/in-process.ts'))}, () => ({+ ...migrationSetup, runMigrateOnlyCore: async () => ({ engine: 'postgres' }),+}));+mock.module(${JSON.stringify(join(root, 'src/core/migration-orchestration-lock.ts'))}, () => ({+ acquireMigrationOrchestrationLock: async () => ({ assertHeld: async () => {}, release: async () => {} }),+ MIGRATIONS_RUNNING_EXIT_CODE: 75,+ MigrationsRunningError: class extends Error {},+ MigrationLeaseLostError: class extends Error {},+}));+const brain = ${JSON.stringify(brain)};+const factory = await import(${JSON.stringify(join(root, 'src/core/engine-factory.ts'))});+mock.module(${JSON.stringify(join(root, 'src/core/engine-factory.ts'))}, () => ({+ ...factory,+ createEngine: async () => ({+ kind: 'postgres', connect: async () => {}, disconnect: async () => {},+ getConfig: async (key) => key === 'version' ? String(LATEST_VERSION) : key === 'sync.repo_path' ? (brain.syncRepoPath ?? null) : null,+ executeRaw: async (sql) => /FROM sources WHERE id = 'default'/.test(sql) ? [{ local_path: brain.defaultSourcePath ?? null }] : [],+ }),+}));+`;+ const script = (body: string, args: string[] = []) => {+ const file = join(home, `script-${Math.random().toString(36).slice(2)}.ts`);+ writeFileSync(file, setup + body);+ const child = Bun.spawnSync([process.execPath, '--no-env-file', file, ...args], { cwd: home, env, stdout: 'pipe', stderr: 'pipe', timeout: 30_000 });+ return { exitCode: child.exitCode, stdout: child.stdout.toString(), stderr: child.stderr.toString() };+ };+ const apply = (args: string[]) => script(`+const { runApplyMigrations } = await import(${JSON.stringify(join(root, 'src/commands/apply-migrations.ts'))});+await runApplyMigrations(process.argv.slice(2));+`, args);+ await run({ home, ledger, calls: () => readFileSync(callsPath, 'utf8'), apply, script });+ });+ }++ const doctorLine = (script: (body: string) => { stdout: string; stderr: string }) => {+ const out = script(`+const { autopilotInstallPendingCheck } = await import(${JSON.stringify(join(root, 'src/commands/doctor/checks/autopilot-install-pending.ts'))});+console.log('CHECK=' + JSON.stringify(autopilotInstallPendingCheck()));+`);+ const line = out.stdout.split('\n').find(l => l.startsWith('CHECK='));+ expect(line, out.stderr).toBeDefined();+ return JSON.parse(line!.slice(6));+ };++ const pendingInstallItems = (home: string) => {+ const path = join(home, '.gbrain/migrations/pending-host-work.jsonl');+ if (!existsSync(path)) return [];+ return readFileSync(path, 'utf8').trim().split('\n').filter(Boolean).map(row => JSON.parse(row))+ .filter((row: { type: string }) => row.type === 'autopilot-install-needs-repo');+ };++ test('neither sync.repo_path nor a default-source path: an auto-update skips Phase F, completes, and leaves a host-work item plus a doctor line', async () => {+ await postgresBrain({}, async ({ home, ledger, calls, apply, script }) => {+ const run = apply(['--yes', '--non-interactive', '--migration', '0.11.0']);+ expect(run.exitCode, run.stderr).toBe(0);+ expect(calls()).not.toContain('autopilot');+ const record = entries(ledger).at(-1)!;+ expect(record).toMatchObject({ version: '0.11.0', status: 'complete', autopilot_installed: false });+ const install = record.phases!.find(phase => phase.name === 'install')!;+ expect(install.status).toBe('skipped');+ expect(install.detail).toContain('gbrain autopilot --install --yes --repo <REPO_PATH>');+ const items = pendingInstallItems(home);+ expect(items).toHaveLength(1);+ expect(items[0]).toMatchObject({ status: 'pending', install_argv: ['gbrain', 'autopilot', '--install', '--yes', '--repo', '<REPO_PATH>'] });+ const check = doctorLine(script);+ expect(check).toMatchObject({ name: 'minions_migration', status: 'warn',+ fix: { argv: ['gbrain', 'autopilot', '--install', '--yes', '--repo', '<REPO_PATH>'], consent: ['persistent_install'], actor: 'agent' } });+ expect(check.fix.inputs[0].name).toBe('REPO_PATH');+ expect(apply(['--yes', '--non-interactive', '--migration', '0.11.0']).exitCode).toBe(0);+ expect(pendingInstallItems(home)).toHaveLength(1);+ });+ }, 60_000);++ test('only a default-source path: Phase F still skips, prints the install command with that path, and installs nothing', async () => {+ const repo = '/srv/brain repo';+ await postgresBrain({ defaultSourcePath: repo }, async ({ home, ledger, calls, apply, script }) => {+ const run = apply(['--yes', '--migration', '0.11.0']);+ expect(run.exitCode, run.stderr).toBe(0);+ expect(calls()).not.toContain('autopilot');+ const record = entries(ledger).at(-1)!;+ expect(record.status).toBe('complete');+ expect(record.phases!.find(phase => phase.name === 'install')).toMatchObject({ status: 'skipped' });+ expect(run.stdout).toContain("gbrain autopilot --install --yes --repo '/srv/brain repo'");+ expect(pendingInstallItems(home)[0].install_argv).toEqual(['gbrain', 'autopilot', '--install', '--yes', '--repo', repo]);+ const check = doctorLine(script);+ expect(check.fix.argv).toEqual(['gbrain', 'autopilot', '--install', '--yes', '--repo', repo]);+ expect(check.fix.inputs).toBeUndefined();+ });+ }, 60_000);++ test('sync.repo_path set: Phase F installs as before', async () => {+ await postgresBrain({ syncRepoPath: '/srv/brain' }, async ({ home, ledger, calls, apply }) => {+ const run = apply(['--yes', '--migration', '0.11.0']);+ expect(run.exitCode, run.stderr).toBe(0);+ expect(calls()).toContain('autopilot --install --yes');+ expect(entries(ledger).at(-1)).toMatchObject({ status: 'complete', autopilot_installed: true });+ expect(pendingInstallItems(home)).toHaveLength(0);+ });+ }, 60_000);++ test('a brain wedged only by the old repo-path refusal is cleared automatically and completes', async () => {+ await postgresBrain({}, async ({ ledger, calls, apply }) => {+ const partial = (n: number) => JSON.stringify({ version: '0.11.0', ts: `2026-10-0${n}T00:00:00.000Z`, status: 'partial', phases: phaseRows(OLD_REFUSAL) });+ writeFileSync(ledger, [partial(1), partial(2), partial(3)].join('\n') + '\n');+ const run = apply(['--yes', '--migration', '0.11.0']);+ expect(run.exitCode, run.stderr).toBe(0);+ expect(run.stderr).toContain('Cleared the v0.11.0 wedge');+ expect(entries(ledger).map(row => row.status)).toEqual(['partial', 'partial', 'partial', 'retry', 'complete']);+ expect(entries(ledger)[3]).toMatchObject({ reason: 'phase_f_no_repo_path' });+ expect(calls()).not.toContain('autopilot');+ });+ }, 60_000);++ for (const [label, row] of [+ ['partials that carry no phases', { status: 'partial' }],+ ['partials that also failed another phase', { status: 'partial', phases: [...phaseRows(OLD_REFUSAL).slice(0, 4), { name: 'host', status: 'failed', detail: 'boom' }, ...phaseRows(OLD_REFUSAL).slice(5)] }],+ ['partials whose install failed for another reason', { status: 'partial', phases: phaseRows('sync.repo_path /srv/brain: Command failed: gbrain autopilot --install --yes') }],+ ] as const) {+ test(`a wedge from ${label} is not cleared; the run prints the exact --force-retry command`, async () => {+ await postgresBrain({}, async ({ ledger, apply }) => {+ const rows = [1, 2, 3].map(n => JSON.stringify({ version: '0.11.0', ts: `2026-10-0${n}T00:00:00.000Z`, ...row })).join('\n') + '\n';+ writeFileSync(ledger, rows);+ const run = apply(['--yes', '--migration', '0.11.0']);+ expect(run.exitCode).not.toBe(0);+ expect(run.stderr).toContain('gbrain apply-migrations --force-retry 0.11.0');+ expect(run.stderr).not.toContain('Cleared the v0.11.0 wedge');+ expect(readFileSync(ledger, 'utf8')).toBe(rows);+ });+ }, 60_000);+ }+});diff --git a/test/apply-migrations-wedged-6696.test.ts b/test/apply-migrations-wedged-6696.test.tsindex 5dd2c218b4..c7dd74c139 100644--- a/test/apply-migrations-wedged-6696.test.ts+++ b/test/apply-migrations-wedged-6696.test.ts@@ -11,7 +11,7 @@* subprocess; process.env is never mutated).*/import { afterAll, beforeAll, describe, expect, test } from 'bun:test';-import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'fs';+import { mkdtempSync, readFileSync, realpathSync, rmSync, writeFileSync } from 'fs';import { join } from 'path';import { tmpdir } from 'os';@@ -32,7 +32,7 @@ async function cli(args: string[]): Promise<{ exitCode: number; stdout: string;}beforeAll(async () => {- home = mkdtempSync(join(tmpdir(), 'gbrain-wedged-6696-'));+ home = realpathSync(mkdtempSync(join(tmpdir(), 'gbrain-wedged-6696-')));expect((await cli(['init', '--pglite', '--no-embedding', '--json'])).exitCode).toBe(0);expect((await cli(['apply-migrations', '--yes', '--no-autopilot-install'])).exitCode).toBe(0);base = readFileSync(ledgerPath(), 'utf8').split('\n').filter(line => line.trim());@@ -58,8 +58,28 @@ describe('apply-migrations with a wedged migration (#6696 C5)', () => {expect(envelope.message).toContain(`v${WEDGED}`);expect(envelope.fix).toMatchObject({ next: 'ask_user', argv: ['gbrain', 'apply-migrations', '--force-retry', WEDGED],verify: { argv: ['gbrain', 'apply-migrations', '--list', '--json'] } });+ // #6755: the advice names the ledger that records the failing phases, not upgrade-errors.jsonl.+ for (const text of [envelope.suggestion, envelope.fix.user_message, run.stderr]) {+ expect(text).toContain(ledgerPath());+ expect(text).toContain('phases[].detail, if present');+ expect(text).not.toContain('upgrade-errors.jsonl');+ }}, 120_000);+ test('upgrade names the completion ledger for a wedged migration (#6755)', async () => {+ wedge(WEDGED);+ const proc = Bun.spawn([process.execPath, '-e', `+ import { describeMigrationFailure } from './src/commands/upgrade.ts';+ console.log(await describeMigrationFailure({}, '${WEDGED}'));+ `], { cwd: REPO, env: { ...process.env, HOME: home, GBRAIN_HOME: home }, stdout: 'pipe', stderr: 'pipe' });+ const [stdout, stderr, code] = await Promise.all([new Response(proc.stdout).text(), new Response(proc.stderr).text(), proc.exited]);+ expect(code, stderr).toBe(0);+ expect(stdout).toContain(ledgerPath());+ expect(stdout).toContain('phases[].detail, if present');+ expect(stdout).toContain(`gbrain apply-migrations --force-retry ${WEDGED}`);+ expect(stdout).not.toContain('upgrade-errors.jsonl');+ }, 30_000);+test('--list --json lists the wedged migration with its fix; the human --list does not say up to date', async () => {wedge(WEDGED);const list = await cli(['apply-migrations', '--list', '--json']);@@ -71,6 +91,8 @@ describe('apply-migrations with a wedged migration (#6696 C5)', () => {const human = await cli(['apply-migrations', '--list']);expect(human.stdout).not.toContain('All migrations up to date');expect(human.stdout).toContain(`gbrain apply-migrations --force-retry ${WEDGED}`);+ expect(human.stdout).toContain(ledgerPath());+ expect(human.stdout).not.toContain('upgrade-errors.jsonl');}, 120_000);test('a wedge a newer migration ran past is history: the run succeeds and --list --json names no wedged fix', async () => {diff --git a/test/autopilot-install-repo-fallback-6755.test.ts b/test/autopilot-install-repo-fallback-6755.test.tsnew file mode 100644index 0000000000..adc67dfc14--- /dev/null+++ b/test/autopilot-install-repo-fallback-6755.test.ts@@ -0,0 +1,82 @@+/**+ * #6755: `gbrain autopilot --install` with neither --repo nor sync.repo_path+ * falls back to the default source's local_path (a managed source keeps its+ * repo there), then refuses as before when that is unset too. Runs the+ * installer in-process on the ephemeral-container target against a stub+ * engine; process.exit is replaced for the refusal case and restored.+ */+import { afterAll, describe, expect, test } from 'bun:test';+import { existsSync, mkdtempSync, readFileSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { emptyHome, withEnv } from './helpers/with-env.ts';+import { runAutopilot } from '../src/commands/autopilot.ts';+import { _resetCliExitVerdictForTests } from '../src/core/cli-force-exit.ts';++async function install(brain: { syncRepoPath?: string; defaultSourcePath?: string }, extra: string[] = []) {+ const gbrainHome = emptyHome();+ const home = mkdtempSync(join(tmpdir(), 'gbrain-ap-fallback-home-'));+ const bin = mkdtempSync(join(tmpdir(), 'gbrain-ap-fallback-bin-'));+ writeFileSync(join(bin, 'gbrain'), '#!/bin/sh\nexit 0\n', { mode: 0o755 });+ const stderr: string[] = [];+ let exitCode: number | undefined;+ await withEnv({ GBRAIN_HOME: gbrainHome, HOME: home, PATH: `${bin}:${process.env.PATH}`, GBRAIN_NON_INTERACTIVE: '1' }, async () => {+ const log = console.log;+ const error = console.error;+ const exit = process.exit;+ console.log = () => {};+ console.error = (...p: unknown[]) => { stderr.push(p.map(String).join(' ')); };+ process.exit = ((code?: number) => { exitCode = code ?? 0; throw new Error('process.exit'); }) as typeof process.exit;+ _resetCliExitVerdictForTests();+ try {+ const engine = {+ kind: 'postgres',+ getConfig: async (key: string) => key === 'sync.repo_path' ? brain.syncRepoPath ?? null : null,+ executeRaw: async (sql: string) => /FROM sources WHERE id = 'default'/.test(sql) ? [{ local_path: brain.defaultSourcePath ?? null }] : [],+ } as never;+ await runAutopilot(engine, ['--install', '--target', 'ephemeral-container', '--no-inject', '--yes', ...extra]);+ } catch (e) {+ if (!(e instanceof Error && e.message === 'process.exit')) throw e;+ } finally {+ console.log = log;+ console.error = error;+ process.exit = exit;+ }+ });+ const wrapper = join(gbrainHome, '.gbrain', 'autopilot-run.sh');+ return { exitCode, stderr: stderr.join('\n'), wrapper: existsSync(wrapper) ? readFileSync(wrapper, 'utf8') : null };+}++afterAll(() => {+ _resetCliExitVerdictForTests();+ process.exitCode = 0;+});++describe('autopilot --install repo resolution (#6755)', () => {+ test('no --repo and no sync.repo_path: installs against the default source local_path', async () => {+ const repo = mkdtempSync(join(tmpdir(), 'gbrain-ap-fallback-repo-'));+ const r = await install({ defaultSourcePath: repo });+ expect(r.exitCode).toBeUndefined();+ expect(r.wrapper).toContain(`autopilot --repo '${repo}'`);+ });++ test('sync.repo_path still wins over the default source local_path', async () => {+ const configured = mkdtempSync(join(tmpdir(), 'gbrain-ap-fallback-configured-'));+ const r = await install({ syncRepoPath: configured, defaultSourcePath: '/elsewhere' });+ expect(r.wrapper).toContain(`autopilot --repo '${configured}'`);+ expect(r.wrapper).not.toContain('/elsewhere');+ });++ test('--repo wins over both', async () => {+ const flag = mkdtempSync(join(tmpdir(), 'gbrain-ap-fallback-flag-'));+ const r = await install({ syncRepoPath: '/configured', defaultSourcePath: '/elsewhere' }, ['--repo', flag]);+ expect(r.wrapper).toContain(`autopilot --repo '${flag}'`);+ });++ test('no path anywhere: refuses with exit 1 and writes nothing', async () => {+ const r = await install({});+ expect(r.exitCode).toBe(1);+ expect(r.stderr).toContain('No repo path');+ expect(r.wrapper).toBeNull();+ });+});diff --git a/test/doctor-autopilot-install-pending-6755.test.ts b/test/doctor-autopilot-install-pending-6755.test.tsnew file mode 100644index 0000000000..68ae5aadd3--- /dev/null+++ b/test/doctor-autopilot-install-pending-6755.test.ts@@ -0,0 +1,69 @@+/**+ * #6755: a Phase F the v0.11.0 migration skipped for want of a repo path stays+ * visible. Its pending host-work item surfaces as a `minions_migration` doctor+ * line whose fix is the exact install argv (persistent_install, so the agent+ * asks first). Fixture journey through the real doctor CLI on a keyless PGLite+ * brain: render the envelope, run its argv (the installer in-process against a+ * stub Postgres engine on the ephemeral-container target, since the CLI refuses+ * a daemon on PGLite), run its verify, and the line is gone.+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { mkdirSync, mkdtempSync, realpathSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { gb, oneDocument } from './helpers/agent-journey.ts';+import { withEnv } from './helpers/with-env.ts';+import { recordSkippedAutopilotInstall } from '../src/commands/migrations/v0_11_0-install.ts';+import { runAutopilot } from '../src/commands/autopilot.ts';+import { _resetCliExitVerdictForTests } from '../src/core/cli-force-exit.ts';++let home: string;+let userHome: string;+let repo: string;+/** HOME apart from the brain home, so the brain is a non-default one in this process and in the CLI children alike. */+const cli = (args: string[]) => gb(home, args, { env: { HOME: userHome } });+const installLine = (doc: Record<string, any>) =>+ (doc.checks as Array<Record<string, any>>).find(c => c.name === 'minions_migration' && String(c.message).includes('autopilot'));++beforeAll(async () => {+ home = realpathSync(mkdtempSync(join(tmpdir(), 'gbrain-6755-doctor-')));+ userHome = realpathSync(mkdtempSync(join(tmpdir(), 'gbrain-6755-doctor-user-')));+ repo = join(home, 'brain-repo');+ mkdirSync(repo);+ expect((await cli(['init', '--pglite', '--no-embedding', '--json'])).exitCode).toBe(0);+ await withEnv({ HOME: userHome, GBRAIN_HOME: home }, async () => { recordSkippedAutopilotInstall(repo); });+}, 180_000);+afterAll(() => {+ _resetCliExitVerdictForTests();+ process.exitCode = 0;+ for (const dir of [home, userHome]) if (dir) rmSync(dir, { recursive: true, force: true });+});++describe('skipped Phase F: doctor line to verified clear', () => {+ test('warn with the install argv → run it → verify shows no install line', async () => {+ const warned = installLine(oneDocument(await cli(['doctor', '--only', 'minions_migration', '--json']), 'doctor warn'));+ expect(warned).toBeDefined();+ expect(warned!.status).toBe('warn');+ expect(warned!.fix).toMatchObject({ consent: ['persistent_install'], actor: 'agent', next: 'ask_user' });+ expect(warned!.fix.argv.slice(0, 6)).toEqual(['gbrain', 'autopilot', '--install', '--yes', '--repo', repo]);+ expect(warned!.fix.verify.argv.slice(0, 4)).toEqual(['gbrain', 'doctor', '--only', 'minions_migration']);++ // The user agreed: run the argv. cli.ts consumes the routing flag (--brain) before dispatch.+ const argv = warned!.fix.argv.slice(2) as string[];+ const brainAt = argv.indexOf('--brain');+ if (brainAt >= 0) argv.splice(brainAt, 2);+ const bin = join(home, 'bin');+ mkdirSync(bin);+ writeFileSync(join(bin, 'gbrain'), '#!/bin/sh\nexit 0\n', { mode: 0o755 });+ await withEnv({ HOME: userHome, GBRAIN_HOME: home, RENDER: '1', GBRAIN_NON_INTERACTIVE: '1', PATH: `${bin}:${process.env.PATH}` }, async () => {+ const log = console.log;+ console.log = () => {};+ try {+ await runAutopilot({ kind: 'postgres', getConfig: async () => null, executeRaw: async () => [] } as never, [...argv, '--no-inject']);+ } finally { console.log = log; }+ });++ const verified = oneDocument(await cli(warned!.fix.verify.argv.slice(1)), 'doctor verify');+ expect(installLine(verified)).toBeUndefined();+ }, 300_000);+});