Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(migrations): a wedged migration is outstanding work, not up to date (#6696 C5)

garrytandd6bbdc81274
diff --git a/AGENTS.md b/AGENTS.md
index 4198f400b0..4f6cf6e692 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -29,6 +29,8 @@ start here.
only when the schema is at head; exit 1 with `migrations_pending` means the schema is still behind, and another
`--yes` repeats the failure, so run `gbrain doctor --json` and fall back to the deterministic install:
`git clone https://github.com/garrytan/gbrain.git ~/gbrain && cd ~/gbrain && bun install && bun link`.
+ `migrations_pending` with reason `wedged` is different: a migration failed three or more times in a row, so
+ relay its `fix` (ask the user) instead of reinstalling: fix the cause, then `gbrain apply-migrations --force-retry <version>`.
2. Init keyless memory: `gbrain init --pglite --no-embedding` (zero-config). For 1000+ files or
multi-machine sync, init suggests Postgres + pgvector via Supabase.
3. **STOP — ask the user about search mode.** `gbrain init` auto-applied a
diff --git a/INSTALL_FOR_AGENTS.md b/INSTALL_FOR_AGENTS.md
index 620c27a7f1..d2497e0caf 100644
--- a/INSTALL_FOR_AGENTS.md
+++ b/INSTALL_FOR_AGENTS.md
@@ -63,7 +63,9 @@ restart the shell or add the PATH export to the shell profile.
> [#218](https://github.com/garrytan/gbrain/issues/218). Run `gbrain apply-migrations --yes --no-autopilot-install`
> to recover. It exits 0 only when the schema is at head. Exit 1 with `migrations_pending` means the schema
> is still behind: another `--yes` repeats the failure, so run `gbrain doctor --json`, tell the user what it
-> reports, and fall back to the deterministic install path:
+> reports, and fall back to the deterministic install path (exit 1 with reason `wedged` instead means one migration
+> failed three or more times in a row: relay its `fix` to the user, who fixes the cause and clears it with
+> `gbrain apply-migrations --force-retry <version>`; reinstalling does not help):
>
> ```bash
> git clone https://github.com/garrytan/gbrain.git ~/gbrain && cd ~/gbrain
diff --git a/README.md b/README.md
index c96405fd19..13cedfeb45 100644
--- a/README.md
+++ b/README.md
@@ -101,7 +101,7 @@ before restarting services with this version.
> reinstall; `gbrain doctor` detects it.
> Schema not migrated ([#218](https://github.com/garrytan/gbrain/issues/218))?
> Run `gbrain apply-migrations --yes --no-autopilot-install`; exit 1 means it's still
-> behind: run `gbrain doctor --json`, not `--yes` again.
+> behind: run `gbrain doctor --json`, not `--yes` (`wedged`: relay its fix).
**Claude Code or Codex, fastest path:**
diff --git a/docs/architecture/key-files/commands-1.md b/docs/architecture/key-files/commands-1.md
index 3c11d5f95f..9b244a8c29 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; 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) 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-schema.ts` — #6089 schema half of the apply-migrations exit contract. `connectAtSchemaVersion` is the one place that connects the configured brain and reads `config.version` (pre-flight, `--force-schema`, post-orchestrator check). `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).
- `src/commands/agent-logs.ts` — `gbrain agent logs <job> [--follow] [--since]`. Merges JSONL heartbeat audit + `subagent_messages` into a chronological timeline. `parseSince` accepts ISO-8601 or relative (`5m`, `1h`, `2d`). Transcript tail renders only for terminal jobs.
diff --git a/docs/guides/error-codes.md b/docs/guides/error-codes.md
index 5c145491d9..c7c9457ec8 100644
--- a/docs/guides/error-codes.md
+++ b/docs/guides/error-codes.md
@@ -1895,9 +1895,9 @@ Reasons: `orchestrator_failed`, `orchestrator_threw`, `ledger_write_failed`, `pr
| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |
|---|---|---|---|---|---|---|
-| Schema migrations are behind (or could not be confirmed at head), so the command did not report success. | apply-migrations reasons: not_applied: the run had no --yes (or --non-interactive), so it did not apply the schema migrations; the fix applies them with --yes. still_behind: an authorized run tried them and they did not apply; another --yes repeats the failure, so run `gbrain doctor --json` and report. schema_unreadable: the schema version could not be read back after the orchestrators ran, so the run cannot confirm it reached head; report it. Each failure names the schema migrations still pending. | not_applied: apply them with `gbrain apply-migrations --yes`. still_behind or schema_unreadable: run `gbrain doctor --json` and report it to the user; another --yes repeats the failure. | agent | `repeat the read that failed` | 1 | no |
+| Schema migrations are behind (or could not be confirmed at head), or an orchestrator migration is wedged, so the command did not report success. | apply-migrations reasons: not_applied: the run had no --yes (or --non-interactive), so it did not apply the schema migrations; the fix applies them with --yes. still_behind: an authorized run tried them and they did not apply; another --yes repeats the failure, so run `gbrain doctor --json` and report. schema_unreadable: the schema version could not be read back after the orchestrators ran, so the run cannot confirm it reached head; report it. wedged: an orchestrator migration ended partial three or more times in a row, so runs skip it until a person fixes the cause and clears it with --force-retry. Each failure names the migrations still pending. | not_applied: apply them with `gbrain apply-migrations --yes`. still_behind or schema_unreadable: run `gbrain doctor --json` and report it to the user; another --yes repeats the failure. wedged: ask the user, fix the cause in ~/.gbrain/upgrade-errors.jsonl, then `gbrain apply-migrations --force-retry <version>` and `gbrain apply-migrations --yes`. | agent | `repeat the read that failed` | 1 | no |
-Reasons: `not_applied`, `still_behind`, `schema_unreadable`.
+Reasons: `not_applied`, `still_behind`, `schema_unreadable`, `wedged`.
### migrations_running
diff --git a/src/commands/apply-migrations.ts b/src/commands/apply-migrations.ts
index 3348f83cc2..45456963e7 100644
--- a/src/commands/apply-migrations.ts
+++ b/src/commands/apply-migrations.ts
@@ -187,7 +187,9 @@ Exit codes:
1 An orchestrator failed, the migration lease stopped matching this run
(migration_lease_lost), or the run left the schema behind
(migrations_pending: not_applied → apply them with --yes; still_behind or
- schema_unreadable → run gbrain doctor --json and report, not --yes again).
+ schema_unreadable → run gbrain doctor --json and report, not --yes again;
+ wedged → a migration ended partial 3+ times in a row: ask the user, fix
+ the cause, then --force-retry <version>).
An unreachable Postgres stays 0 (GBRAIN_DB_ACCESS on stderr) unless --require-db.
2 Invalid arguments.
3 confirmation_required: a migration installs the autopilot service and the
@@ -314,7 +316,8 @@ function printList(plan: Plan, installed: string, dbProbe: DbProbeOutcome): void
const 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`);
- if (needsWork === 0 && setup === 0) {
+ 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))}`);
+ if (needsWork === 0 && setup === 0 && plan.wedged.length === 0) {
console.log('All migrations up to date.');
return;
}
@@ -340,6 +343,7 @@ function listJson(plan: Plan, idx: CompletedIndex, installed: string, dbProbe: D
...(r.status === 'declined' && r.m.optOut ? { opt_out: { key: r.m.optOut.key } } : {}),
})),
needs_action: plan.pending.length + plan.partial.length,
+ ...(plan.wedged.length ? { wedged: plan.wedged.map(m => ({ version: m.version, fix: { argv: forceRetryArgv(m.version), command: shellQuote(forceRetryArgv(m.version)) } })) } : {}),
pending_fresh_install: plan.pending_fresh_install.length,
...(outstanding > 0 ? { next: { argv: FINISH_SETUP_ARGV, command: shellQuote(FINISH_SETUP_ARGV) } } : {}),
};
@@ -444,6 +448,8 @@ const COMMAND = 'apply-migrations';
interface RunReport {
doc: Record<string, unknown>;
failure?: OperationError;
+ /** #6696 C5: wedged migrations the run cannot clear itself; a run that otherwise succeeds fails `migrations_pending` reason `wedged`. */
+ wedged?: readonly Migration[];
}
function unknownMigrationError(version: string): OperationError {
@@ -670,6 +676,7 @@ async function runLockedMigrations(
doc.database = dbProbe;
doc.plan = Object.fromEntries(Object.entries(plan).map(([state, entries]) => [state, entries.map((migration: Migration) => migration.version)]));
reportWedgedMigrations(plan.wedged);
+ report.wedged = plan.wedged;
if (cli.specificMigration && plan.applied.length + plan.partial.length + plan.pending.length + plan.pending_fresh_install.length + plan.skippedFuture.length + plan.declined.length === 0) {
console.error(`No migration registered with version "${cli.specificMigration}". Run \`gbrain apply-migrations --list\` to see registered versions.`);
@@ -727,6 +734,7 @@ async function runLockedMigrations(
}
const toRun: Migration[] = [...pendingWork, ...plan.applied.filter(migration => migration.reconcile)]
.sort((left, right) => compareVersions(left.version, right.version));
+ if (toRun.length === 0 && plan.wedged.length) return failWedged(report);
if (toRun.length === 0) {
console.log('All migrations up to date.');
doc.status = 'up_to_date';
@@ -870,7 +878,7 @@ async function runLockedMigrations(
/** #6089: the run leaves the schema behind → `migrations_pending`, exit 1; undefined (success) when it does not. */
function failSchemaBehind(report: RunReport, args: readonly string[], pending: SchemaPending | null): number | undefined {
- if (!pending) return undefined;
+ if (!pending) return failWedged(report);
report.doc.status = 'schema_behind';
report.doc.schema_pending = pending;
report.failure = schemaPendingError(pending, rerunFix(args, 'Applies the pending schema migrations (no consent effect; it migrates the brain\'s own schema).', true));
@@ -938,6 +946,26 @@ async function preflightSchema(
return { schemaBehind, dbProbe };
}
+/** #6696 C5: the clearing step for a wedged migration; it needs the user, since the cause behind the partial runs must be fixed first. */
+function forceRetryArgv(version: string): string[] { return ['gbrain', COMMAND, '--force-retry', version]; }
+
+/** #6696 C5: a run that leaves a wedged migration fails `migrations_pending` (reason `wedged`, exit 1); undefined when none is wedged. */
+function failWedged(report: RunReport): number | undefined {
+ const wedged = report.wedged ?? [];
+ if (!wedged.length) return undefined;
+ const versions = wedged.map(m => `v${m.version}`).join(', ');
+ report.doc.status = 'wedged';
+ 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.`,
+ { 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?`,
+ verify: { argv: ['gbrain', COMMAND, '--list', '--json'] } } });
+ return 1;
+}
+
/** Bug 3 — surface wedged migrations as a loud, actionable error; the run continues (applied/partial/pending are still reported and run). */
function reportWedgedMigrations(wedged: readonly Migration[]): void {
for (const m of wedged) {
diff --git a/src/commands/upgrade.ts b/src/commands/upgrade.ts
index 8376b26501..b10faa0bcd 100644
--- a/src/commands/upgrade.ts
+++ b/src/commands/upgrade.ts
@@ -384,10 +384,11 @@ export async function describeMigrationFailure(error: unknown, newVersion: strin
+ 'Wait for it to finish; `gbrain doctor` shows migration progress.';
}
const wedged = newVersion ? migrationLedgerSummary(newVersion).wedged : [];
- const command = wedged.length > 0
- ? `${wedged.map(v => `gbrain apply-migrations --force-retry ${v}`).join(' && ')} && gbrain apply-migrations --yes`
- : 'gbrain apply-migrations --yes';
- return `Migrations: failed. Run: ${command}`;
+ 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: `
+ + `${wedged.map(v => `gbrain apply-migrations --force-retry ${v}`).join(' && ')} && gbrain apply-migrations --yes`;
+ }
+ return 'Migrations: failed. Run: gbrain apply-migrations --yes';
}
export function resolveBunGlobalRoot(): string {
diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.ts
index d0061fc116..1bf4e109a7 100644
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@ -563,6 +563,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText }
{ since: '0.60.223.0', text: 'On Linux, when the process holding write claims on this host is killed, another consumer on the same machine now reclaims those claims within about 5 s instead of waiting out their lease (up to `persistence.publication_ceiling_ms` plus about 65 s, so about 365 s by default). Only claims with no recovery record and no publication started are taken, the same guard an expired claim has. An owner that is alive, however slow, or on another host or container keeps its full lease.' },
// #6696 PR C (GBRA-93 lane C). `since` is a placeholder equal to the branch's VERSION until the merge-slot stamp.
{ since: '0.60.223.0', text: '`gbrain sources writer failures`, `gbrain write-request`, `gbrain sync status` and doctor `persistence_terminal_failures` now report a write refused because its page\'s canonical file is missing (a ghost page) as category `canonical_file_missing`, whose fix previews `gbrain repair ghost-pages --source <id>`, instead of a sync retry that refuses the same way. A `fence_unrenderable` fact-fence adoption refusal is its own category, and one written by a build older than 0.60.218.0 (the release that stopped the adoption loop) counts as historical and no longer warns.' },
+ { since: '0.60.223.0', text: '`gbrain apply-migrations` no longer prints "All migrations up to date" (exit 0) while a migration is wedged (3 or more consecutive partial runs). It exits 1 with `migrations_pending` reason `wedged` and a fix to ask the user about (`gbrain apply-migrations --force-retry <version>` after fixing the cause); `--list` names the wedged migration and its clearing command, `--list --json` adds a `wedged` list, `gbrain post-upgrade` exits non-zero and `gbrain upgrade` prints `Migrations: wedged` instead of `Migrations: complete`.' },
];
/** The newest disclosed change's release: the notice id moves only when a release adds rows. */
diff --git a/src/core/error-registry.ts b/src/core/error-registry.ts
index 68ecadaa30..67c3f24a5f 100644
--- a/src/core/error-registry.ts
+++ b/src/core/error-registry.ts
@@ -301,10 +301,10 @@ export const CODES = {
suggestion: 'Do not retry. Tell the user the migration is declined on this brain and give them the fix command (gbrain config set <key> true) if they want it to run; --list --json shows it declined.' },
migration_failed: { class: 'server', summary: "A migration orchestrator failed, so the migration chain stopped; finished migrations stay recorded.",
reasons: ['orchestrator_failed', 'orchestrator_threw', 'ledger_write_failed', 'preview_failed', 'schema_failed'] },
- migrations_pending: { class: 'caller', summary: "Schema migrations are behind (or could not be confirmed at head), so the command did not report success.",
- why: 'apply-migrations reasons: not_applied: the run had no --yes (or --non-interactive), so it did not apply the schema migrations; the fix applies them with --yes. still_behind: an authorized run tried them and they did not apply; another --yes repeats the failure, so run `gbrain doctor --json` and report. schema_unreadable: the schema version could not be read back after the orchestrators ran, so the run cannot confirm it reached head; report it. Each failure names the schema migrations still pending.',
- suggestion: 'not_applied: apply them with `gbrain apply-migrations --yes`. still_behind or schema_unreadable: run `gbrain doctor --json` and report it to the user; another --yes repeats the failure.',
- reasons: ['not_applied', 'still_behind', 'schema_unreadable'] },
+ migrations_pending: { class: 'caller', summary: "Schema migrations are behind (or could not be confirmed at head), or an orchestrator migration is wedged, so the command did not report success.",
+ why: 'apply-migrations reasons: not_applied: the run had no --yes (or --non-interactive), so it did not apply the schema migrations; the fix applies them with --yes. still_behind: an authorized run tried them and they did not apply; another --yes repeats the failure, so run `gbrain doctor --json` and report. schema_unreadable: the schema version could not be read back after the orchestrators ran, so the run cannot confirm it reached head; report it. wedged: an orchestrator migration ended partial three or more times in a row, so runs skip it until a person fixes the cause and clears it with --force-retry. Each failure names the migrations still pending.',
+ suggestion: 'not_applied: apply them with `gbrain apply-migrations --yes`. still_behind or schema_unreadable: run `gbrain doctor --json` and report it to the user; another --yes repeats the failure. wedged: ask the user, fix the cause in ~/.gbrain/upgrade-errors.jsonl, then `gbrain apply-migrations --force-retry <version>` and `gbrain apply-migrations --yes`.',
+ reasons: ['not_applied', 'still_behind', 'schema_unreadable', 'wedged'] },
migrations_running: { class: 'retryable', summary: "Another apply-migrations run holds the migration orchestration lock.", exit: 75 },
missing_source_scope: { class: 'server', summary: "A remote tool call reached dispatch without a resolved source scope; the shared default source is refused." },
missing_source_value: { class: 'caller', summary: "A source flag was given without a value." },
diff --git a/test/apply-migrations-wedged-6696.test.ts b/test/apply-migrations-wedged-6696.test.ts
new file mode 100644
index 0000000000..aac9c1a30b
--- /dev/null
+++ b/test/apply-migrations-wedged-6696.test.ts
@@ -0,0 +1,63 @@
+/**
+ * #6696 (PR C, C5): a wedged orchestrator migration (3+ consecutive partial
+ * runs with no completion) is outstanding work, not "All migrations up to
+ * date". The run reports `migrations_pending` with reason `wedged` and a fix
+ * the agent asks the user about (`--force-retry <v>`), `--list --json` lists
+ * it with that fix, and the human `--list` never prints "up to date".
+ *
+ * Spawns the CLI against a throwaway PGLite brain (HOME / GBRAIN_HOME per
+ * subprocess; process.env is never mutated).
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'fs';
+import { join } from 'path';
+import { tmpdir } from 'os';
+
+const REPO = new URL('..', import.meta.url).pathname.replace(/\/$/, '');
+const WEDGED = '0.22.4';
+let home: string;
+
+async function cli(args: string[]): Promise<{ exitCode: number; stdout: string; stderr: string }> {
+ const proc = Bun.spawn(['bun', 'run', `${REPO}/src/cli.ts`, ...args], {
+ cwd: REPO, env: { ...process.env, HOME: home, GBRAIN_HOME: home, GBRAIN_NO_AUTOPILOT_INSTALL: '1' }, stdout: 'pipe', stderr: 'pipe',
+ });
+ const [stdout, stderr, exitCode] = await Promise.all([new Response(proc.stdout).text(), new Response(proc.stderr).text(), proc.exited]);
+ return { exitCode, stdout, stderr };
+}
+
+beforeAll(async () => {
+ home = 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);
+ const ledger = join(home, '.gbrain', 'migrations', 'completed.jsonl');
+ const kept = readFileSync(ledger, 'utf8').split('\n').filter(line => line.trim() && JSON.parse(line).version !== WEDGED);
+ const partial = (n: number) => JSON.stringify({ ts: `2026-10-0${n}T00:00:00.000Z`, version: WEDGED, status: 'partial' });
+ writeFileSync(ledger, [...kept, partial(1), partial(2), partial(3)].join('\n') + '\n');
+}, 240_000);
+
+afterAll(() => { try { rmSync(home, { recursive: true, force: true }); } catch { /* best effort */ } });
+
+describe('apply-migrations with a wedged migration (#6696 C5)', () => {
+ test('a run reports migrations_pending reason wedged with an ask_user force-retry fix instead of up to date', async () => {
+ const run = await cli(['apply-migrations', '--yes', '--no-autopilot-install', '--json']);
+ expect(run.stdout).not.toContain('"status":"up_to_date"');
+ expect(run.exitCode).toBe(1);
+ const envelope = JSON.parse(run.stdout) as Record<string, any>;
+ expect(envelope).toMatchObject({ code: 'migrations_pending', reason: 'wedged' });
+ 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'] } });
+ }, 120_000);
+
+ test('--list --json lists the wedged migration with its fix; the human --list does not say up to date', async () => {
+ const list = await cli(['apply-migrations', '--list', '--json']);
+ expect(list.exitCode).toBe(0);
+ const doc = JSON.parse(list.stdout) as Record<string, any>;
+ expect(doc.migrations.find((m: { version: string }) => m.version === WEDGED)).toMatchObject({ status: 'wedged' });
+ expect(doc.wedged).toEqual([{ version: WEDGED, fix: { argv: ['gbrain', 'apply-migrations', '--force-retry', WEDGED],
+ command: `gbrain apply-migrations --force-retry ${WEDGED}` } }]);
+ 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}`);
+ }, 120_000);
+});