Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(migrations): a wedge a newer migration ran past is history, not outstanding (#6696 C5)

garrytanf47d792d2b2a
diff --git a/docs/architecture/key-files/commands-1.md b/docs/architecture/key-files/commands-1.md
index 9b244a8c29..d41783b8cb 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) 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`; 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/src/commands/apply-migrations.ts b/src/commands/apply-migrations.ts
index 45456963e7..0c712c9224 100644
--- a/src/commands/apply-migrations.ts
+++ b/src/commands/apply-migrations.ts
@@ -31,6 +31,7 @@ import {
statusForVersion as ledgerStatusForVersion,
freshInstallVersion,
isFreshInstallStamp,
+ forwardProgressPast,
isPendingFreshInstall,
MAX_CONSECUTIVE_PARTIALS,
} from '../core/migration-ledger.ts';
@@ -226,6 +227,8 @@ interface Plan {
pending_fresh_install: Migration[];
skippedFuture: Migration[];
wedged: Migration[];
+ /** #6696 C5: wedged in the ledger, but a newer migration ran past it (doctor's forward-progress rule): history, not outstanding work. */
+ wedged_superseded: Migration[];
/** #6466: declined by the brain's config (`Migration.optOut`); never run, listed as `declined`. */
declined: Migration[];
}
@@ -248,7 +251,8 @@ interface Plan {
* skip v0.11.0 when running v0.11.1. Compare against completed.jsonl.
*/
function buildPlan(idx: CompletedIndex, installed: string, filterVersion?: string, declined: ReadonlySet<string> = new Set()): Plan {
- const plan: Plan = { applied: [], partial: [], pending: [], pending_fresh_install: [], skippedFuture: [], wedged: [], declined: [] };
+ const plan: Plan = { applied: [], partial: [], pending: [], pending_fresh_install: [], skippedFuture: [], wedged: [], wedged_superseded: [], declined: [] };
+ const ledger = [...idx.byVersion.values()].flat();
for (const m of migrations) {
if (filterVersion && m.version !== filterVersion) continue;
if (compareVersions(m.version, installed) > 0) {
@@ -259,7 +263,7 @@ function buildPlan(idx: CompletedIndex, installed: string, filterVersion?: strin
const status = statusForVersion(m.version, idx);
if (status === 'complete') plan.applied.push(m);
else if (status === 'partial') plan.partial.push(m);
- else if (status === 'wedged') plan.wedged.push(m);
+ else if (status === 'wedged') (forwardProgressPast(m.version, ledger) === null ? plan.wedged : plan.wedged_superseded).push(m);
else if (isPendingFreshInstall(m.version, idx.freshVersion)) plan.pending_fresh_install.push(m);
else plan.pending.push(m);
}
@@ -292,7 +296,7 @@ function listRows(plan: Plan): Array<{ status: string; m: Migration }> {
return [
...plan.applied.map(m => ({ status: 'applied', m })),
...plan.partial.map(m => ({ status: 'partial', m })),
- ...plan.wedged.map(m => ({ status: 'wedged', m })),
+ ...[...plan.wedged, ...plan.wedged_superseded].map(m => ({ status: 'wedged', m })),
...plan.pending.map(m => ({ status: 'pending', m })),
...plan.pending_fresh_install.map(m => ({ status: 'pending_fresh_install', m })),
...plan.declined.map(m => ({ status: 'declined', m })),
@@ -675,8 +679,8 @@ 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;
+ reportWedgedMigrations(plan.wedged, plan.wedged_superseded, completed);
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.`);
@@ -697,7 +701,7 @@ async function runLockedMigrations(
if (cli.list) { printList(plan, installed, dbProbe); return listExit; }
if (cli.dryRun) {
const previews: Array<{ version: string; preview?: unknown; error?: string }> = [];
- for (const migration of [...plan.applied, ...plan.partial, ...plan.pending, ...plan.pending_fresh_install, ...plan.wedged]) {
+ for (const migration of [...plan.applied, ...plan.partial, ...plan.pending, ...plan.pending_fresh_install, ...plan.wedged, ...plan.wedged_superseded]) {
if (!migration.preview) continue;
try { previews.push({ version: migration.version, preview: await migration.preview(orchestratorOptsFrom(cli)) }); }
catch (error) { previews.push({ version: migration.version, error: error instanceof Error ? error.message : 'Inventory unavailable.' }); }
@@ -967,7 +971,11 @@ function failWedged(report: RunReport): number | undefined {
}
/** 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 {
+function reportWedgedMigrations(wedged: readonly Migration[], superseded: readonly Migration[], completed: readonly CompletedMigrationEntry[]): void {
+ for (const m of superseded) {
+ console.error(`\nMigration v${m.version} has ${MAX_CONSECUTIVE_PARTIALS}+ consecutive partial runs, but v${forwardProgressPast(m.version, completed)} completed after it, `
+ + 'so it is history, not outstanding work. Nothing to do.');
+ }
for (const m of wedged) {
console.error(
`\nMigration v${m.version} is WEDGED (${MAX_CONSECUTIVE_PARTIALS}+ consecutive partials with no completion). ` +
diff --git a/src/commands/upgrade.ts b/src/commands/upgrade.ts
index b10faa0bcd..5b454eeb0e 100644
--- a/src/commands/upgrade.ts
+++ b/src/commands/upgrade.ts
@@ -8,7 +8,8 @@ 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 { migrationLedgerSummary } from '../core/migration-ledger.ts';
+import { forwardProgressPast, migrationLedgerSummary } from '../core/migration-ledger.ts';
+import { loadCompletedMigrations } from '../core/preferences.ts';
import { MIGRATIONS_RUNNING_EXIT_CODE, readMigrationLockHolder } from '../core/migration-orchestration-lock.ts';
import {
BUN_FLOOR_EXIT_CODE,
@@ -383,7 +384,8 @@ export async function describeMigrationFailure(error: unknown, newVersion: strin
return `Migrations: running (host ${holder?.host ?? 'unknown'}, pid ${holder?.pid ?? 'unknown'}) in another apply-migrations. `
+ 'Wait for it to finish; `gbrain doctor` shows migration progress.';
}
- const wedged = newVersion ? migrationLedgerSummary(newVersion).wedged : [];
+ const 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: `
+ `${wedged.map(v => `gbrain apply-migrations --force-retry ${v}`).join(' && ')} && gbrain apply-migrations --yes`;
diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.ts
index 3043d0ed66..ddb509d1b8 100644
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@ -563,7 +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`.' },
+ { 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) and no newer migration has run past it. 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`.' },
{ since: '0.60.223.0', text: '`gbrain repair file-drift` now takes `--only <path>` and `--skip <path>` (repeatable; source-relative canonical file paths, `*` within a segment and `**` across segments, so `--only \'concepts/**\'` selects every drifted page filed under concepts/). The globs narrow the selection before the mixed-class check, are bound into the preview hash and appear in the printed apply command, so running that command applies exactly the previewed pages; an apply under other globs refuses `preview_changed`. `--keep` on file-drift is now refused with a pointer at `--prefer database` (keep the database copy) or `--prefer file`, instead of the stuck-recovery value error.' },
{ since: '0.60.223.0', text: 'gbrain.yml `storage:` accepts an opt-in `keep_db:` list of directory prefixes. On the canonical owner host, the resident `gbrain serve`, `gbrain jobs` or `gbrain autopilot` consumer reconciles each drifted page under those prefixes with the database copy (the `gbrain repair file-drift --prefer database` resolution, inside reconcile\'s protections and backups), at most 10 requests every 10 minutes, never twice for the same drift and never past 90% of the write-quota stop line; other hosts and remote or caller writes are unchanged and keep refusing `source_changed`. Doctor `maintenance_write_drift` echoes each declared policy with how many drifted pages it matches and their receipt cost. An unknown key under `storage:` now prints a warning instead of being ignored silently.' },
{ since: '0.60.223.0', text: '`gbrain repair content` (the `slug-conflicts` kind) now judges a held `frontmatter_slug_conflict` file with the same screen managed sync froze it with. A held file sync would now import as it is (its `slug:` line names the file\'s own page, or it no longer conflicts) is listed as `import` and imported unchanged, clearing the hold only while it is still the observation the repair read; before, it was skipped as `already_exempt` or `already_clean` and the hold stayed. A file in a source that is a subdirectory of its Git repository now loses its stray `slug:` line instead of being held `still_invalid`. A file sync would hold whatever the repair writes is now held `slug_page_mismatch` naming both slugs, instead of the generic `still_invalid` or `already_exempt` (an alias to the file\'s own page is one).' },
diff --git a/src/core/migration-ledger.ts b/src/core/migration-ledger.ts
index 7d0b356517..943b473876 100644
--- a/src/core/migration-ledger.ts
+++ b/src/core/migration-ledger.ts
@@ -108,6 +108,14 @@ export function trailingPartialCount(entries: readonly CompletedMigrationEntry[]
return consecutive;
}
+/**
+ * Doctor's forward-progress rule (`minions_migration`): a partial or wedged version is history, not outstanding work, once a
+ * newer migration really ran (a `complete` entry that is not an init fresh-install stamp). Returns that newer version, or null.
+ */
+export function forwardProgressPast(version: string, entries: readonly CompletedMigrationEntry[]): string | null {
+ return entries.find(e => e.status === 'complete' && !isFreshInstallStamp(e) && compareVersions(e.version, version) > 0)?.version ?? null;
+}
+
/** A ledger entry `gbrain init` wrote for a `fresh_install_noop` migration (src/commands/migrations/fresh-install.ts). */
export function isFreshInstallStamp(entry: CompletedMigrationEntry): boolean {
return entry.fresh_install === true;
diff --git a/test/apply-migrations-wedged-6696.test.ts b/test/apply-migrations-wedged-6696.test.ts
index aac9c1a30b..5dd2c218b4 100644
--- a/test/apply-migrations-wedged-6696.test.ts
+++ b/test/apply-migrations-wedged-6696.test.ts
@@ -3,7 +3,9 @@
* 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".
+ * it with that fix, and the human `--list` never prints "up to date". A wedge
+ * a newer migration already ran past is history (doctor's forward-progress
+ * rule, `minions_migration`): the run succeeds and lists no wedged fix.
*
* Spawns the CLI against a throwaway PGLite brain (HOME / GBRAIN_HOME per
* subprocess; process.env is never mutated).
@@ -14,8 +16,12 @@ import { join } from 'path';
import { tmpdir } from 'os';
const REPO = new URL('..', import.meta.url).pathname.replace(/\/$/, '');
-const WEDGED = '0.22.4';
+/** The newest registered migration: nothing can run past it, so its wedge is outstanding. */
+const WEDGED = '0.60.31';
+/** Older than migrations that run on a fresh brain (v0.28.0 among them), so its wedge is superseded. */
+const SUPERSEDED = '0.22.4';
let home: string;
+let base: string[];
async function cli(args: string[]): Promise<{ exitCode: number; stdout: string; stderr: string }> {
const proc = Bun.spawn(['bun', 'run', `${REPO}/src/cli.ts`, ...args], {
@@ -29,16 +35,21 @@ 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');
+ base = readFileSync(ledgerPath(), 'utf8').split('\n').filter(line => line.trim());
}, 240_000);
+const ledgerPath = () => join(home, '.gbrain', 'migrations', 'completed.jsonl');
+/** The fresh brain's ledger with `version`'s entries replaced by three consecutive partial runs. */
+function wedge(version: string): void {
+ const partial = (n: number) => JSON.stringify({ ts: `2026-10-0${n}T00:00:00.000Z`, version, status: 'partial' });
+ writeFileSync(ledgerPath(), [...base.filter(line => JSON.parse(line).version !== version), partial(1), partial(2), partial(3)].join('\n') + '\n');
+}
+
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 () => {
+ wedge(WEDGED);
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);
@@ -50,6 +61,7 @@ describe('apply-migrations with a wedged migration (#6696 C5)', () => {
}, 120_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']);
expect(list.exitCode).toBe(0);
const doc = JSON.parse(list.stdout) as Record<string, any>;
@@ -60,4 +72,17 @@ describe('apply-migrations with a wedged migration (#6696 C5)', () => {
expect(human.stdout).not.toContain('All migrations up to date');
expect(human.stdout).toContain(`gbrain apply-migrations --force-retry ${WEDGED}`);
}, 120_000);
+
+ test('a wedge a newer migration ran past is history: the run succeeds and --list --json names no wedged fix', async () => {
+ wedge(SUPERSEDED);
+ expect(base.some(line => JSON.parse(line).version === '0.28.0' && JSON.parse(line).status === 'complete' && !JSON.parse(line).fresh_install)).toBe(true);
+ const run = await cli(['apply-migrations', '--yes', '--no-autopilot-install', '--json']);
+ expect(run.exitCode).toBe(0);
+ expect(JSON.parse(run.stdout)).not.toHaveProperty('code');
+ expect(run.stderr).toContain(`Migration v${SUPERSEDED} has 3+ consecutive partial runs, but v`);
+ expect(run.stderr).not.toContain(`Migration v${SUPERSEDED} is WEDGED`);
+ const doc = JSON.parse((await cli(['apply-migrations', '--list', '--json'])).stdout) as Record<string, any>;
+ expect(doc.migrations.find((m: { version: string }) => m.version === SUPERSEDED)).toMatchObject({ status: 'wedged' });
+ expect(doc).not.toHaveProperty('wedged');
+ }, 120_000);
});