Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(migrations): clear a v0.11.0 Phase F wedge by phase shape and sync.repo_path, record Phase F reason codes (#6755)
garrytan0ea6918afe64
diff --git a/docs/architecture/key-files/commands-1.md b/docs/architecture/key-files/commands-1.mdindex ca90dbe395..e6cf23c2c2 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`; 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/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. Phase F records a `reason` code on those outcomes (`no_repo_path`, `autopilot_already_installed`, `install_failed`). `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 phase (whatever its detail; the old child's stderr was never captured) and this Postgres brain's `sync.repo_path` is unset, so Phase F would now skip; with it set, or any other wedge, the `--force-retry` advice stands. 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).diff --git a/src/commands/apply-migrations.ts b/src/commands/apply-migrations.tsindex 76b2c25f6a..746eb12ddc 100644--- a/src/commands/apply-migrations.ts+++ b/src/commands/apply-migrations.ts@@ -675,7 +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());+ if (!cli.list && !cli.dryRun) await clearRepoPathWedge(loadCompletedMigrations());const completed = loadCompletedMigrations();const idx = indexCompleted(completed);await setRunEngineSharing(true);diff --git a/src/commands/migrations/types.ts b/src/commands/migrations/types.tsindex 9965989a42..de8b15feb6 100644--- a/src/commands/migrations/types.ts+++ b/src/commands/migrations/types.ts@@ -50,6 +50,8 @@ export interface OrchestratorPhaseResult {name: string;status: 'complete' | 'skipped' | 'failed';detail?: string;+ /** A stable code for why the phase ended this way (kept in the ledger), for readers that must not parse `detail`. */+ reason?: string;/** The exact command that resolves or inspects what this phase left open; printed by the runner and kept in the ledger. */argv?: string[];}diff --git a/src/commands/migrations/v0_11_0-install.ts b/src/commands/migrations/v0_11_0-install.tsindex 353c4120c8..eeaf08469f 100644--- a/src/commands/migrations/v0_11_0-install.ts+++ b/src/commands/migrations/v0_11_0-install.ts@@ -11,10 +11,13 @@* 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.+ * partials. Its ledger rows cannot say why the install failed (the child's+ * stderr is not captured; `phases[].detail` is only execSync's+ * `Command failed: <command>`), so `clearRepoPathWedge` keys on the shape+ * and the brain as it is now: every trailing partial failed only the install+ * phase, and the new phase would skip because sync.repo_path is unset. Phase F+ * now records a `reason` code on its outcomes (`no_repo_path`,+ * `autopilot_already_installed`, `install_failed`) for later readers.*/import { appendFileSync, existsSync, mkdirSync, readFileSync } from 'fs';import { dirname } from 'path';@@ -33,8 +36,6 @@ 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;@@ -103,14 +104,14 @@ async function readRepoPaths(config: GBrainConfig | null): Promise<{ syncRepoPatfunction 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' };+ return { name: 'install', status: 'skipped', reason: 'autopilot_already_installed', 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}`,+ name: 'install', status: 'skipped', reason: 'no_repo_path', detail: `sync.repo_path is unset, so the upgrade installed no autopilot. Install it: ${command}`,...(defaultSourcePath ? { argv: autopilotInstallArgv(defaultSourcePath) } : {}),};}@@ -134,28 +135,34 @@ export async function phaseFInstall(opts: OrchestratorOpts): Promise<OrchestratoexecSync(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)}` };+ return { name: 'install', status: 'failed', reason: 'install_failed', detail: `${repoNote}: ${e instanceof Error ? e.message : String(e)}` };}}-function failedOnlyOnOldRefusal(entry: CompletedMigrationEntry): boolean {+function failedOnlyInstall(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());+ return failed.length === 1 && failed[0]!.name === 'install';}/*** 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.+ * (whatever its detail says) and Phase F would now skip because this Postgres+ * brain's sync.repo_path is unset: writes a `retry` marker (reason+ * `phase_f_no_repo_path`) and says so. Returns whether it wrote one. With+ * sync.repo_path set, an unreadable one or any other wedge, the runner's+ * `--force-retry` advice stands.*/-export function clearRepoPathWedge(completed: readonly CompletedMigrationEntry[]): boolean {+export async function clearRepoPathWedge(completed: readonly CompletedMigrationEntry[]): Promise<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;+ if (!history.slice(history.length - trailingPartialCount(history)).every(failedOnlyInstall)) return false;+ const config = loadConfig();+ if (!config || config.engine === 'pglite') return false;+ const repo = await readRepoPaths(config).catch(() => null);+ if (!repo || repo.syncRepoPath) 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. '+ console.error('Cleared the v0.11.0 wedge: every partial run failed only the autopilot install, and sync.repo_path is unset. '+ 'This version skips that install, so the migration runs again now.');return true;}diff --git a/test/apply-migrations-safety.serial.test.ts b/test/apply-migrations-safety.serial.test.tsindex a657c2e94c..8edc2b7d47 100644--- a/test/apply-migrations-safety.serial.test.ts+++ b/test/apply-migrations-safety.serial.test.ts@@ -250,14 +250,16 @@ await runApplyMigrations(process.argv.slice(2));* 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";+ // What the old Phase F's refusal left in the ledger, reproduced on cadaf5cd7 with a PATH shim that prints the refusal+ // and exits 1: execSync's message only; the child's stderr ("No repo path. ...") went to the terminal, not the ledger.+ const OLD_REFUSAL = 'Command failed: gbrain 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: {+ async function postgresBrain(brain: { syncRepoPath?: string; defaultSourcePath?: string; autopilotExit?: number }, 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> {@@ -267,7 +269,7 @@ describe('v0.11.0 Phase F without a repo path (#6755)', () => {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 });+ writeFileSync(join(bin, 'gbrain'), `#!/bin/sh\nprintf '%s\\n' "$*" >> '${callsPath}'\nif [ "$1" = autopilot ]; then exit ${brain.autopilotExit ?? 0}; fi\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';@@ -332,7 +334,7 @@ console.log('CHECK=' + JSON.stringify(autopilotInstallPendingCheck()));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).toMatchObject({ status: 'skipped', reason: 'no_repo_path' });expect(install.detail).toContain('gbrain autopilot --install --yes --repo <REPO_PATH>');const items = pendingInstallItems(home);expect(items).toHaveLength(1);@@ -373,9 +375,17 @@ console.log('CHECK=' + JSON.stringify(autopilotInstallPendingCheck()));});}, 60_000);- test('a brain wedged only by the old repo-path refusal is cleared automatically and completes', async () => {+ test('a failing install with sync.repo_path set records reason install_failed', async () => {+ await postgresBrain({ syncRepoPath: '/srv/brain', autopilotExit: 1 }, async ({ ledger, apply }) => {+ const run = apply(['--yes', '--migration', '0.11.0']);+ expect(run.exitCode).toBe(1);+ expect(entries(ledger).at(-1)!.phases).toContainEqual(expect.objectContaining({ name: 'install', status: 'failed', reason: 'install_failed' }));+ });+ }, 60_000);++ for (const detail of [OLD_REFUSAL, 'Command failed']) test(`install-only partials (detail ${JSON.stringify(detail)}) on a brain with no sync.repo_path are cleared automatically and the migration 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) });+ const partial = (n: number) => JSON.stringify({ version: '0.11.0', ts: `2026-10-0${n}T00:00:00.000Z`, status: 'partial', phases: phaseRows(detail) });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);@@ -386,13 +396,13 @@ console.log('CHECK=' + JSON.stringify(autopilotInstallPendingCheck()));});}, 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') }],+ for (const [label, row, brain] 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)] }, {}],+ ['install-only partials on a brain whose sync.repo_path is set', { status: 'partial', phases: phaseRows(OLD_REFUSAL) }, { syncRepoPath: '/srv/brain' }],] as const) {test(`a wedge from ${label} is not cleared; the run prints the exact --force-retry command`, async () => {- await postgresBrain({}, async ({ ledger, apply }) => {+ await postgresBrain(brain, 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']);