Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(migrations): apply-migrations never exits 0 with the schema behind (#6089)

garrytanc0dae6fcf971
diff --git a/docs/architecture/key-files/commands-1.md b/docs/architecture/key-files/commands-1.md
index 417ffd4333..d7b7bd8ae1 100644
--- a/docs/architecture/key-files/commands-1.md
+++ b/docs/architecture/key-files/commands-1.md
@@ -3,7 +3,8 @@
[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`, `database_error` for `--require-db`, `migrations_running` exit 75). 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). #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. 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-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 4643e946af..7a2fc220f9 100644
--- a/docs/guides/error-codes.md
+++ b/docs/guides/error-codes.md
@@ -1514,7 +1514,9 @@ Reasons: `orchestrator_failed`, `orchestrator_threw`, `ledger_write_failed`, `pr
| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |
|---|---|---|---|---|---|---|
-| Schema migrations are behind and this run did not apply them. | apply-migrations applies schema migrations only with --yes (or --non-interactive); without it the run reports the drift instead of claiming the brain is up to date. | Correct the request using the message above, then retry. | agent | `repeat the read that failed` | 1 | no |
+| 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 reruns 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. | Correct the request using the message above, then retry. | agent | `repeat the read that failed` | 1 | no |
+
+Reasons: `not_applied`, `still_behind`, `schema_unreadable`.
### migrations_running
diff --git a/scripts/structural-suites.tsv b/scripts/structural-suites.tsv
index c372fb7b52..189460da25 100644
--- a/scripts/structural-suites.tsv
+++ b/scripts/structural-suites.tsv
@@ -9,7 +9,6 @@ test/agent-register.test.ts resolvePreset 7 readFileSync
test/agent-register.test.ts structural guards 2 readFileSync
test/ai/silent-drop-regression.test.ts (file-level) 3 source-surface-helper
test/apply-migrations.test.ts failed migration prints phase detail (#921) 1 readFileSync
-test/apply-migrations.test.ts resolveSchemaBehind (#1530) 5 readFileSync
test/apply-migrations.test.ts runApplyMigrations exit codes (v0.36.1.x #1062) 1 readFileSync
test/archived-source-scoping.test.ts #3880 structural pins — all-source local_path selections filter archived 2 readFileSync
test/auto-link-targeted-probe-2544.test.ts #2544 — auto-link behavior through put_page (targeted probe) 6 readFileSync
diff --git a/src/commands/apply-migrations-schema.ts b/src/commands/apply-migrations-schema.ts
new file mode 100644
index 0000000000..832b8696f9
--- /dev/null
+++ b/src/commands/apply-migrations-schema.ts
@@ -0,0 +1,151 @@
+/**
+ * #6089: the schema-version half of the `gbrain apply-migrations` exit
+ * contract. The runner never exits 0 while it leaves the schema behind.
+ *
+ * - One helper connects the configured brain and reads `config.version`; the
+ * Postgres pre-flight, `--force-schema` and the check after orchestrators
+ * all go through it.
+ * - After the orchestrators ran, the version is read again. On Postgres only
+ * when the pre-flight connected (an unreachable database stays non-fatal,
+ * with the GBRAIN_DB_ACCESS marker). On PGLite this check replaces the
+ * pre-flight, which stays skipped (#1100 lock race): it runs in-process once
+ * the orchestrators released the datastore, never in a child process, and an
+ * authorized run applies the schema migrations here.
+ * - A schema still behind, or a version that cannot be read back, is
+ * `migrations_pending` (exit 1) with a reason and the schema migrations
+ * still pending. After an authorized run the fix is a report (doctor, then
+ * tell the user), never another `--yes` that would repeat the failure.
+ */
+import { existsSync } from 'node:fs';
+import type { GBrainConfig } from '../core/config.ts';
+import type { BrainEngine } from '../core/engine.ts';
+import type { Action } from '../core/agent-output.ts';
+import { opError, type OperationError } from '../core/ops/contract.ts';
+import { PgliteBusyError } from '../core/pglite-lock.ts';
+import { DB_ACCESS_MARKER_PREFIX, shouldEmitDbAccessMarker } from '../core/pg-access-classify.ts';
+
+export type SchemaPendingReason = 'not_applied' | 'still_behind' | 'schema_unreadable';
+
+export interface SchemaPending {
+ reason: SchemaPendingReason;
+ /** The version read back, or null when it could not be read. */
+ current: number | null;
+ latest: number;
+ /** Schema migration versions above the last version this run read. */
+ pending: number[];
+ /** Redacted read error (`schema_unreadable` only). */
+ read_error?: string;
+}
+
+/** Connect the configured brain and read its schema version. The caller disconnects; a failed read disconnects here. */
+export async function connectAtSchemaVersion(cfg: GBrainConfig): Promise<{ engine: BrainEngine; version: number }> {
+ const { toEngineConfig } = await import('../core/config.ts');
+ const { createEngine } = await import('../core/engine-factory.ts');
+ const engine = await createEngine(toEngineConfig(cfg));
+ try {
+ await engine.connect(toEngineConfig(cfg));
+ return { engine, version: parseInt(await engine.getConfig('version') || '1', 10) };
+ } catch (err) {
+ await engine.disconnect().catch(() => {});
+ throw err;
+ }
+}
+
+/** A connection error with URLs and connection details redacted: safe for stderr, issues and CI logs. */
+export async function redactDbError(err: unknown): Promise<string> {
+ const { redactUrlsInText } = await import('../core/url-redact.ts');
+ const { redactConnectionInfo } = await import('../core/audit/redact-connection-info.ts');
+ return redactConnectionInfo(redactUrlsInText(err instanceof Error ? err.message : String(err)));
+}
+
+async function pendingAbove(version: number | null): Promise<{ latest: number; pending: number[] }> {
+ const { MIGRATIONS, LATEST_VERSION } = await import('../core/migrate.ts');
+ const pending = version === null ? [] : MIGRATIONS.map(m => m.version).filter(v => v > version).sort((a, b) => a - b);
+ return { latest: LATEST_VERSION, pending };
+}
+
+/** The pre-flight's finding when it saw the schema behind and did not bring it to head. */
+export async function schemaBehindAtPreflight(version: number, authorized: boolean): Promise<SchemaPending> {
+ return { reason: authorized ? 'still_behind' : 'not_applied', current: version, ...(await pendingAbove(version)) };
+}
+
+/**
+ * Read the schema version after the orchestrators ran; null when it is at
+ * head or there is nothing to check (no PGLite datastore yet, or Postgres was
+ * unreachable at the pre-flight, or a PGLite datastore that was never
+ * initialized). `apply` brings a PGLite schema to head on an authorized run.
+ * A busy PGLite datastore is rethrown like an orchestrator's.
+ */
+export async function checkSchemaAfterOrchestrators(opts: {
+ cfg: GBrainConfig;
+ authorized: boolean;
+ preflightVersion: number | null;
+ apply: (engine: BrainEngine, from: number) => Promise<unknown>;
+}): Promise<SchemaPending | null> {
+ const { cfg, authorized } = opts;
+ const pglite = cfg.engine === 'pglite';
+ if (pglite ? !cfg.database_path || !existsSync(cfg.database_path) : opts.preflightVersion === null) return null;
+ let lastRead = opts.preflightVersion;
+ try {
+ const { engine, version } = await connectAtSchemaVersion(cfg);
+ let current = version;
+ try {
+ const { latest } = await pendingAbove(current);
+ if (pglite && authorized && current < latest) {
+ console.error(`Schema v${current} is behind v${latest}; applying schema migrations in-process...`);
+ try { await opts.apply(engine, current); } catch (err) { console.error(`Schema migration failed: ${await redactDbError(err)}`); }
+ current = parseInt(await engine.getConfig('version') || '1', 10);
+ }
+ } finally {
+ await engine.disconnect();
+ }
+ lastRead = current;
+ const { latest, pending } = await pendingAbove(current);
+ if (current >= latest) return null;
+ return { reason: authorized ? 'still_behind' : 'not_applied', current, latest, pending };
+ } catch (err) {
+ if (err instanceof PgliteBusyError) throw err;
+ // A PGLite datastore without the config table was never initialized: `gbrain init` creates a brain, not this run.
+ if (pglite && /relation "config" does not exist/i.test(err instanceof Error ? err.message : String(err))) {
+ console.error('The PGLite datastore has no gbrain schema yet, so there is no schema version to check; `gbrain init` creates it.');
+ return null;
+ }
+ return { reason: 'schema_unreadable', current: null, ...(await pendingAbove(lastRead)), read_error: await redactDbError(err) };
+ }
+}
+
+/** Tell the user, then show doctor's view: the same run again would fail the same way. */
+function reportFix(why: string): Action {
+ return { consent: [], actor: 'agent', requires_exclusive: false, why, verify: { argv: ['gbrain', 'doctor', '--json'] } };
+}
+
+const REPORT_SUGGESTION = 'Run `gbrain doctor --json` and tell the user what it reports, with the schema error from stderr. '
+ + 'If the gbrain install itself is broken, the deterministic clone install in README.md recovers it (issue #218).';
+
+/** `migrations_pending` for a run that leaves the schema behind. `rerunWithYes` is the fix when the run was not authorized. */
+export function schemaPendingError(p: SchemaPending, rerunWithYes: Action): OperationError {
+ const ids = p.pending.length ? p.pending.map(v => `v${v}`).join(', ') : 'unknown';
+ const where = `schema v${p.current}, latest v${p.latest}; pending: ${ids}`;
+ if (p.reason === 'not_applied') {
+ return opError('migrations_pending', `Schema migrations are behind (${where}); this run did not apply them.`,
+ 'Apply them with `gbrain apply-migrations --yes` (or `--force-schema`).',
+ { reason: p.reason, fix: rerunWithYes });
+ }
+ if (p.reason === 'still_behind') {
+ return opError('migrations_pending', `Schema migrations are still behind after an authorized run (${where}); the schema migration did not apply, and running --yes again repeats that.`,
+ REPORT_SUGGESTION,
+ { reason: p.reason, why: 'apply-migrations --yes tried the schema migrations and they did not apply; stderr names the failing migration.',
+ fix: reportFix('Tell the user the schema migrations did not apply and what doctor reports; another --yes run repeats the failure.') });
+ }
+ return opError('migrations_pending', `The schema version could not be read after the orchestrators ran (${p.read_error ?? 'unknown error'}); latest v${p.latest}, pending since the last version read: ${ids}.`,
+ REPORT_SUGGESTION,
+ { reason: p.reason, why: 'The run cannot confirm the schema reached head, so it does not report success.',
+ fix: reportFix('Tell the user the schema version could not be confirmed and what doctor reports.') });
+}
+
+/** Postgres unreachable without --require-db: still non-fatal, but never silent. */
+export function reportDatabaseUnreachable(probe: { reason: string; access?: string }): void {
+ if (shouldEmitDbAccessMarker()) process.stderr.write(`${DB_ACCESS_MARKER_PREFIX} ${probe.access ?? 'unknown'}\n`);
+ console.error(`Database unreachable (${probe.reason}): the schema version was not checked; orchestrators run their filesystem-only phases. `
+ + 'Diagnose it with `gbrain db-repair`; pass --require-db to fail instead.');
+}
diff --git a/src/commands/apply-migrations.ts b/src/commands/apply-migrations.ts
index 4fc05e8ae6..7208ac33b4 100644
--- a/src/commands/apply-migrations.ts
+++ b/src/commands/apply-migrations.ts
@@ -37,6 +37,15 @@ import { writeJsonDocument } from '../core/cli-force-exit.ts';
import { consentGate } from '../core/consent-cli.ts';
import { opError, type OperationError } from '../core/ops/contract.ts';
import { exitCliError, usageError, writeCliError } from '../cli/cli-error.ts';
+import {
+ checkSchemaAfterOrchestrators,
+ connectAtSchemaVersion,
+ redactDbError,
+ reportDatabaseUnreachable,
+ schemaBehindAtPreflight,
+ schemaPendingError,
+ type SchemaPending,
+} from './apply-migrations-schema.ts';
interface ApplyMigrationsArgs {
list: boolean;
@@ -173,7 +182,10 @@ Flags:
Exit codes:
0 Success (including "nothing to do").
- 1 An orchestrator failed, or schema migrations are pending (apply them with --yes).
+ 1 An orchestrator failed, or the run left the schema behind
+ (migrations_pending: not_applied → rerun with --yes; still_behind or
+ schema_unreadable → run gbrain doctor --json and report, not --yes again).
+ 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
user has not approved it (--yes, --non-interactive or a preapproval).
@@ -251,7 +263,7 @@ function buildPlan(idx: CompletedIndex, installed: string, filterVersion?: strin
*/
type DbProbeOutcome =
| { status: 'connected'; schemaVer: number; latest: number }
- | { status: 'unreachable'; reason: string }
+ | { status: 'unreachable'; reason: string; access?: string }
| { status: 'skipped'; reason: string };
function formatDbProbeLine(probe: DbProbeOutcome): string {
@@ -514,12 +526,15 @@ export async function applyMigrations(args: string[]): Promise<{ exitCode: numbe
await holdLock();
exitCode = await runLockedMigrations(cli, installed, holdLock, () => held.lock, report, args);
} catch (error) {
- if (!(error instanceof MigrationsRunningError)) throw error;
- console.error(`apply-migrations refused: ${error.message}`);
- report.doc.status = 'refused';
- report.failure = opError('migrations_running', error.message,
- 'Wait for the other apply-migrations run to finish, then run `gbrain apply-migrations` again (it resumes where that run stopped).');
- exitCode = MIGRATIONS_RUNNING_EXIT_CODE;
+ if (error instanceof MigrationsRunningError) {
+ console.error(`apply-migrations refused: ${error.message}`);
+ report.doc.status = 'refused';
+ report.failure = opError('migrations_running', error.message,
+ 'Wait for the other apply-migrations run to finish, then run `gbrain apply-migrations` again (it resumes where that run stopped).');
+ exitCode = MIGRATIONS_RUNNING_EXIT_CODE;
+ } else {
+ throw error;
+ }
} finally {
await held.lock?.release();
}
@@ -596,18 +611,15 @@ async function runLockedMigrations(
// recovery path.
if (cli.forceSchema || cli.forceAll) {
try {
- const { loadConfig: lc, toEngineConfig } = await import('../core/config.ts');
- const { createEngine } = await import('../core/engine-factory.ts');
- const cfg = lc();
+ const cfg = loadConfig();
if (!cfg) {
console.error('No brain configured for --force-schema.');
fail('failed', opError('no_brain', 'No brain configured for --force-schema.', 'Create a brain first: `gbrain init` (`gbrain init --help` lists the options).'));
return 2;
}
- const eng = await createEngine(toEngineConfig(cfg));
- await eng.connect(toEngineConfig(cfg));
+ const { engine: eng, version } = await connectAtSchemaVersion(cfg);
console.log('Running schema migrations from current config.version...');
- const result = await migrateSchema(eng, parseInt(await eng.getConfig('version') || '1', 10));
+ const result = await migrateSchema(eng, version);
console.log(`Applied ${result.applied} schema migration(s); now at v${result.current}.`);
doc.schema = result;
await eng.disconnect();
@@ -678,27 +690,28 @@ async function runLockedMigrations(
console.error('--require-db: database is unreachable; aborting before orchestrators run.');
return 1;
}
+ if (dbProbe.status === 'unreachable') reportDatabaseUnreachable(dbProbe);
// A Postgres schema without gbrain_cycle_locks had no lease yet; the
// preflight above created the table, so take the lease before orchestrating.
await holdLock();
- const toRun: Migration[] = [...plan.partial, ...plan.pending, ...plan.pending_fresh_install, ...plan.applied.filter(migration => migration.reconcile)]
+ // #6089: an applied reconcile re-check is not pending work. With nothing
+ // else pending, a schema the pre-flight left behind fails the run here; the
+ // re-check runs on the next run, once the schema is current.
+ const pendingWork = [...plan.partial, ...plan.pending, ...plan.pending_fresh_install];
+ const authorized = cli.yes || cli.nonInteractive;
+ if (schemaBehind && pendingWork.length === 0 && dbProbe.status === 'connected') {
+ return failSchemaBehind(report, args, await schemaBehindAtPreflight(dbProbe.schemaVer, authorized));
+ }
+ const toRun: Migration[] = [...pendingWork, ...plan.applied.filter(migration => migration.reconcile)]
.sort((left, right) => compareVersions(left.version, right.version));
if (toRun.length === 0) {
- if (schemaBehind) {
- console.error(
- 'Orchestrator migrations are up to date, but schema migrations are behind. ' +
- 'Run `gbrain apply-migrations --yes` (or `--force-schema`) to apply them.',
- );
- fail('schema_behind', schemaBehindError(args));
- return 1;
- }
console.log('All migrations up to date.');
doc.status = 'up_to_date';
return 0;
}
- if (!schemaBehind && plan.pending.length === 0 && plan.pending_fresh_install.length === 0 && plan.partial.length === 0) {
+ if (!schemaBehind && pendingWork.length === 0) {
console.log('All migrations up to date. This covers orchestrator checkpoints only; host publication and client activation are being rechecked.');
}
@@ -827,8 +840,20 @@ async function runLockedMigrations(
}
}
- if (!failed && schemaBehind) doc.schema_behind = true;
- return failed ? 1 : undefined;
+ if (failed) return 1;
+ // #6089: an orchestrator may migrate the schema itself, so read it again.
+ return failSchemaBehind(report, args, await checkSchemaAfterOrchestrators({
+ cfg: loadConfig()!, authorized, preflightVersion: dbProbe.status === 'connected' ? dbProbe.schemaVer : null, apply: migrateSchema,
+ }));
+}
+
+/** #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;
+ 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));
+ return 1;
}
/**
@@ -848,27 +873,23 @@ async function preflightSchema(
// to handle everything (Issue 1 from v0.18.0 field report; #1530). With
// --yes/--non-interactive we apply them here; otherwise we warn and make
// sure the run does NOT report "All migrations up to date" with exit 0.
+ const cfg = loadConfig();
try {
const { LATEST_VERSION } = await import('../core/migrate.ts');
- const { loadConfig: lc, toEngineConfig } = await import('../core/config.ts');
- const { createEngine } = await import('../core/engine-factory.ts');
- const cfg = lc();
if (cfg) {
// v0.36.x #1100: skip the pre-flight warning on PGLite. The probe
// briefly holds the single-writer lock; if a downstream orchestrator
// phase spawns `gbrain init --migrate-only` as a subprocess (the
// legacy v0.11.0 phase A path), the child can race the parent's
// lock release and hit a 30s timeout. The orchestrators handle
- // schema lifecycle internally on PGLite (phase A routes in-process),
- // so the warning here adds no information for PGLite users.
+ // schema lifecycle internally on PGLite (phase A routes in-process).
+ // #6089: PGLite's schema version is checked in-process after the
+ // orchestrators released the datastore (checkSchemaAfterOrchestrators).
const skipPreflight = cfg.engine === 'pglite';
if (skipPreflight) {
dbProbe = { status: 'skipped', reason: 'pglite manages schema in-process' };
} else {
- const eng = await createEngine(toEngineConfig(cfg));
- await eng.connect(toEngineConfig(cfg));
- const verStr = await eng.getConfig('version');
- const schemaVer = parseInt(verStr || '1', 10);
+ const { engine: eng, version: schemaVer } = await connectAtSchemaVersion(cfg);
dbProbe = { status: 'connected', schemaVer, latest: LATEST_VERSION };
schemaBehind = await resolveSchemaBehind({
schemaVer,
@@ -886,11 +907,11 @@ async function preflightSchema(
// still run their filesystem-only phases. #4364: keep the (redacted)
// reason so --list/--dry-run say UNREACHABLE and --require-db fails hard —
// connect errors are exactly what users paste into issues and CI logs.
- const { redactUrlsInText } = await import('../core/url-redact.ts');
- const { redactConnectionInfo } = await import('../core/audit/redact-connection-info.ts');
+ const { classifyPgAccessError } = await import('../core/pg-access-classify.ts');
dbProbe = {
status: 'unreachable',
- reason: redactConnectionInfo(redactUrlsInText(err instanceof Error ? err.message : String(err))),
+ reason: await redactDbError(err),
+ access: classifyPgAccessError(err, { url: cfg?.database_url ?? null }).reason,
};
}
return { schemaBehind, dbProbe };
@@ -902,12 +923,6 @@ function requireDbError(dbProbe: DbProbeOutcome): OperationError {
{ fix: { argv: ['gbrain', 'db-repair', '--json'], consent: [], actor: 'agent', requires_exclusive: false, why: 'Diagnoses the database access failure and names the repair.' } });
}
-function schemaBehindError(args: readonly string[]): OperationError {
- return opError('migrations_pending', 'Orchestrator migrations are up to date, but schema migrations are behind; this run did not apply them.',
- 'Apply them with `gbrain apply-migrations --yes` (or `--force-schema`).',
- { fix: rerunFix(args, 'Applies the pending schema migrations (no consent effect; it migrates the brain\'s own schema).', true) });
-}
-
/**
* The consent request for the effects `toRun`'s orchestrators perform, or
* null when none apply (dry runs never reach here). `persistent_install` is
diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.ts
index 9a1ca0e7b4..5c56bcf6f5 100644
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@ -258,6 +258,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText }
{ since: '0.60.98.0', text: 'Managed sync now holds a file whose facts or takes fence cannot be imported (code `invalid_fence`; `gbrain sources status <id>` names the fence, section and rows) instead of blocking the whole source, and a source such a fence blocked before recovers on its next sync. Coordinated writes refuse such a fence with `invalid_fence` (wire `error` stays `invalid_params`, or `take_row_collision`). `gbrain config set sync.holds fail` keeps fail-closed blocking.' },
{ since: '0.60.99.0', text: 'Fixable facts and takes fences are now rewritten instead of held or refused: managed sync, put_page and the fact and take writers normalize a fence whose meaning is unambiguous (a missing end marker after the table, two-dash takes markers, zero or duplicate row numbers, header aliases, invented kinds and enum synonyms, assistant holders, percent confidences) without changing a claim or an existing row number, and managed sync commits the rewritten file. Results report `fences_normalized`; `gbrain sync --dry-run` lists `would_normalize`. `gbrain config set fences.normalize false` turns it off (such fences are then held or refused).' },
{ since: '0.0.0-wave11', text: '`gbrain pages purge-deleted`, `cache clear|prune`, `schema use|downgrade|init|remove-*`, `integrity auto|reset-progress` and `search modes --reset` refuse an argument they would ignore (exit 2) instead of running; `pages purge-deleted --source <id>` used to purge every source. Preview with `gbrain pages purge-deleted --dry-run --json`.' },
+ { since: '0.0.0-wave11', text: '`gbrain apply-migrations` now exits 1 (`migrations_pending`) whenever it leaves the schema behind, which most runs used to report as exit 0; run `gbrain apply-migrations --yes`, or after a failed `--yes` run, `gbrain doctor --json`.' },
{ since: '0.0.0-wave11', text: '`gbrain pages purge-deleted` asks before a hard purge: without a terminal it exits 3 with the consent payload, and the `--yes` command it names runs only after the user agrees. The autopilot purge is unchanged.' },
];
diff --git a/src/core/error-registry.ts b/src/core/error-registry.ts
index c035264c34..a6e934c2e9 100644
--- a/src/core/error-registry.ts
+++ b/src/core/error-registry.ts
@@ -220,8 +220,9 @@ export const CODES = {
method_not_allowed: { class: 'caller', summary: "The HTTP method is not allowed on this endpoint." },
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 and this run did not apply them.",
- why: 'apply-migrations applies schema migrations only with --yes (or --non-interactive); without it the run reports the drift instead of claiming the brain is up to date.' },
+ 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 reruns 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.',
+ reasons: ['not_applied', 'still_behind', 'schema_unreadable'] },
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-schema-exit.test.ts b/test/apply-migrations-schema-exit.test.ts
new file mode 100644
index 0000000000..597298ad6b
--- /dev/null
+++ b/test/apply-migrations-schema-exit.test.ts
@@ -0,0 +1,149 @@
+/**
+ * #6089 exit matrix off Postgres. PGLite keeps skipping the pre-flight (#1100)
+ * and checks the schema version in-process after the orchestrators released
+ * the datastore; an unreachable Postgres stays non-fatal (apply-migrations,
+ * in-process `gbrain post-upgrade`, package postinstall) and says so with the
+ * GBRAIN_DB_ACCESS marker. The Postgres cases live in
+ * test/e2e/apply-migrations-schema-exit.test.ts.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { spawnSync } from 'node:child_process';
+import { cpSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join, resolve } from 'node:path';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { LATEST_VERSION } from '../src/core/migrate.ts';
+import { collect, makeHome, spawnDriver } from './helpers/apply-migrations-lock-driver.ts';
+import { parseDocument, writeSchemaDriver, type SchemaDriverOpts } from './helpers/apply-migrations-schema-driver.ts';
+
+const REPO = resolve(import.meta.dir, '..');
+const UNREACHABLE = { engine: 'postgres' as const, database_url: 'postgresql://postgres:[email protected]:1/gbrain_unreachable_6089' };
+const work = mkdtempSync(join(tmpdir(), 'gbrain-schema-exit-'));
+const AT_HEAD = join(work, 'at-head.pglite');
+const BEHIND = join(work, 'behind.pglite');
+const homes: string[] = [];
+
+let engine: PGLiteEngine;
+let behindEngine: PGLiteEngine;
+
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({ database_path: AT_HEAD });
+ await engine.initSchema();
+ await engine.disconnect();
+ cpSync(AT_HEAD, BEHIND, { recursive: true });
+ behindEngine = new PGLiteEngine();
+ await behindEngine.connect({ database_path: BEHIND });
+ await behindEngine.setConfig('version', String(LATEST_VERSION - 1));
+ await behindEngine.disconnect();
+}, 180_000);
+
+afterAll(async () => {
+ await engine.disconnect();
+ await behindEngine.disconnect();
+ for (const home of homes) rmSync(home, { recursive: true, force: true });
+ rmSync(work, { recursive: true, force: true });
+});
+
+function pgliteHome(template: string): { home: string; datastore: string } {
+ const home = makeHome({ engine: 'pglite' });
+ homes.push(home);
+ const datastore = join(home, 'brain.pglite');
+ cpSync(template, datastore, { recursive: true });
+ return { home, datastore };
+}
+
+function postgresHome(): string {
+ const home = makeHome(UNREACHABLE);
+ homes.push(home);
+ return home;
+}
+
+async function run(home: string, opts: SchemaDriverOpts) {
+ const result = await collect(spawnDriver(home, writeSchemaDriver(home, opts)));
+ const logPath = join(home, 'orchestrator.log');
+ return { ...result, log: existsSync(logPath) ? readFileSync(logPath, 'utf8') : '', out: result.stderr + result.stdout };
+}
+
+function readPgliteVersion(datastore: string): number {
+ const script = `const { PGLiteEngine } = await import(${JSON.stringify(join(REPO, 'src/core/pglite-engine.ts'))});
+const e = new PGLiteEngine(); await e.connect({ database_path: ${JSON.stringify(datastore)} });
+console.log(await e.getConfig('version')); await e.disconnect();`;
+ const r = spawnSync(process.execPath, ['--no-env-file', '-e', script], { encoding: 'utf8', timeout: 120_000 });
+ return Number(r.stdout.trim().split('\n').pop());
+}
+
+describe('apply-migrations schema check on PGLite (#6089)', () => {
+ test('schema behind, --yes: checked after the orchestrators and brought to head in-process, exit 0', async () => {
+ const { home, datastore } = pgliteHome(BEHIND);
+ const r = await run(home, { migrations: ['reconcile'], args: ['--yes', '--non-interactive', '--no-autopilot-install'] });
+ expect(r.code, r.out).toBe(0);
+ expect(r.log).toBe('ran reconcile\n');
+ expect(readPgliteVersion(datastore)).toBe(LATEST_VERSION);
+ }, 180_000);
+
+ test('schema behind, no --yes: exit 1 migrations_pending not_applied, the datastore is left as it was', async () => {
+ const { home, datastore } = pgliteHome(BEHIND);
+ const r = await run(home, { migrations: ['reconcile'], args: ['--json', '--no-autopilot-install'] });
+ expect(r.code, r.out).toBe(1);
+ const doc = parseDocument(r.stdout);
+ expect(doc.code).toBe('migrations_pending');
+ expect(doc.reason).toBe('not_applied');
+ expect(doc.schema_pending).toMatchObject({ current: LATEST_VERSION - 1, latest: LATEST_VERSION, pending: [LATEST_VERSION] });
+ expect(doc.fix.argv).toContain('--yes');
+ expect(readPgliteVersion(datastore)).toBe(LATEST_VERSION - 1);
+ }, 180_000);
+
+ test('schema at head: exit 0', async () => {
+ const { home } = pgliteHome(AT_HEAD);
+ const r = await run(home, { migrations: ['reconcile', 'noop'], args: ['--no-autopilot-install'] });
+ expect(r.code, r.out).toBe(0);
+ expect(r.log).toBe('ran reconcile\nran noop\n');
+ }, 180_000);
+});
+
+describe('apply-migrations with Postgres unreachable stays non-fatal and says so (#6089)', () => {
+ test('apply-migrations --yes: filesystem-only orchestrators run, exit 0, GBRAIN_DB_ACCESS marker', async () => {
+ const home = postgresHome();
+ const r = await run(home, { migrations: ['noop'], args: ['--yes', '--non-interactive', '--json'] });
+ expect(r.code, r.out).toBe(0);
+ expect(r.log).toBe('ran noop\n');
+ expect(r.stderr).toMatch(/^GBRAIN_DB_ACCESS \w+$/m);
+ expect(r.stderr).toContain('schema version was not checked');
+ expect(parseDocument(r.stdout).database.status).toBe('unreachable');
+ }, 120_000);
+
+ test('--require-db keeps failing hard', async () => {
+ const home = postgresHome();
+ const r = await run(home, { migrations: ['noop'], args: ['--yes', '--non-interactive', '--require-db'] });
+ expect(r.code, r.out).toBe(1);
+ expect(r.log).toBe('');
+ }, 120_000);
+
+ test('gbrain post-upgrade (in-process apply-migrations) is not failed by it', async () => {
+ const home = postgresHome();
+ const r = await run(home, { migrations: ['noop'], args: ['--json', '--no-autopilot-install'], entry: 'post-upgrade' });
+ expect(r.code, r.out).toBe(0);
+ expect(r.log).toBe('ran noop\n');
+ expect(r.stderr).toMatch(/^GBRAIN_DB_ACCESS \w+$/m);
+ expect(parseDocument(r.stdout).apply_migrations).toEqual({ exit_code: 0 });
+ }, 180_000);
+
+ test('package postinstall runs apply-migrations, which exits 0, so no recovery hint is printed', async () => {
+ const home = postgresHome();
+ const driver = writeSchemaDriver(home, { migrations: ['noop'], args: [], entry: 'argv' });
+ const bin = join(home, 'bin');
+ mkdirSync(bin);
+ writeFileSync(join(bin, 'gbrain'), `#!/bin/sh\nexec ${JSON.stringify(process.execPath)} --no-env-file ${JSON.stringify(driver)} "$@"\n`, { mode: 0o755 });
+ const r = spawnSync(process.execPath, ['--no-env-file', join(REPO, 'scripts/postinstall.ts')], {
+ cwd: home,
+ env: { HOME: home, GBRAIN_HOME: home, PATH: `${bin}:/usr/bin:/bin`, GBRAIN_SKIP_REFERENCE_SWEEP: '1' },
+ encoding: 'utf8', timeout: 120_000,
+ });
+ const out = r.stdout + r.stderr;
+ expect(r.status, out).toBe(0);
+ expect(readFileSync(join(home, 'orchestrator.log'), 'utf8')).toBe('ran noop\n');
+ expect(r.stderr).toMatch(/^GBRAIN_DB_ACCESS \w+$/m);
+ expect(out).not.toContain('postinstall skipped');
+ }, 120_000);
+});
diff --git a/test/apply-migrations.test.ts b/test/apply-migrations.test.ts
index eea8106c8e..8f1baa02bf 100644
--- a/test/apply-migrations.test.ts
+++ b/test/apply-migrations.test.ts
@@ -284,9 +284,6 @@ describe('resolveSchemaBehind (#1530)', () => {
expect(behind).toBe(true);
});
- test('up-to-date branch exits 1 when schemaBehind (source shape)', async () => {
- const { readFileSync } = await import('fs');
- const src = readFileSync('src/commands/apply-migrations.ts', 'utf8');
- expect(src).toMatch(/if \(schemaBehind\)[\s\S]{0,300}return 1;[\s\S]{0,120}All migrations up to date/);
- });
+ // The exit when the schema stays behind is pinned by behavior (#6089):
+ // test/e2e/apply-migrations-schema-exit.test.ts and test/apply-migrations-schema-exit.test.ts.
});
diff --git a/test/e2e/apply-migrations-schema-exit.test.ts b/test/e2e/apply-migrations-schema-exit.test.ts
new file mode 100644
index 0000000000..5274081160
--- /dev/null
+++ b/test/e2e/apply-migrations-schema-exit.test.ts
@@ -0,0 +1,166 @@
+/**
+ * #6089 on Postgres: apply-migrations never exits 0 while the schema stays
+ * behind. An applied reconcile re-check is not pending work, so with nothing
+ * else pending a schema that is behind fails the run before the re-check; when
+ * orchestrators did run, the schema version is read again afterwards. The
+ * failure is `migrations_pending` (exit 1) with a reason that says which case
+ * it was and the schema migrations still pending. After an authorized run the
+ * fix is a report, never another `--yes`.
+ *
+ * Each case runs the real runner in a child process (stubbed orchestrator
+ * registry) against one scratch database created for this file.
+ * Run: DATABASE_URL=... bun test test/e2e/apply-migrations-schema-exit.test.ts
+ */
+import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';
+import { randomUUID } from 'node:crypto';
+import { existsSync, readFileSync, rmSync } from 'node:fs';
+import { join } from 'node:path';
+import postgres from '#postgres';
+import { assertSafeE2eDatabaseUrl } from '../helpers/db-guard.ts';
+import { collect, makeHome, spawnDriver } from '../helpers/apply-migrations-lock-driver.ts';
+import { parseDocument, writeSchemaDriver, type StubMigration } from '../helpers/apply-migrations-schema-driver.ts';
+import { PostgresEngine } from '../../src/core/postgres-engine.ts';
+import { LATEST_VERSION } from '../../src/core/migrate.ts';
+
+const DATABASE_URL = process.env.DATABASE_URL;
+const describeE2E = DATABASE_URL ? describe : describe.skip;
+
+let scratchUrl = '';
+let scratchName = '';
+let admin: ReturnType<typeof postgres> | null = null;
+let conn: ReturnType<typeof postgres> | null = null;
+const homes: string[] = [];
+
+async function setVersion(version: number): Promise<void> {
+ await conn!.unsafe(`INSERT INTO config (key, value) VALUES ('version', $1) ON CONFLICT (key) DO UPDATE SET value = EXCLUDED.value`, [String(version)]);
+}
+
+async function readVersion(): Promise<number> {
+ const rows = await conn!.unsafe(`SELECT value FROM config WHERE key = 'version'`);
+ return Number(rows[0]?.value);
+}
+
+async function run(migrations: StubMigration[], args: string[], extra: { failSchemaMigrations?: boolean; entry?: 'post-upgrade' } = {}) {
+ const home = makeHome({ engine: 'postgres', database_url: scratchUrl });
+ homes.push(home);
+ const result = await collect(spawnDriver(home, writeSchemaDriver(home, { migrations, args: [...args, '--json', '--no-autopilot-install'], ...extra })));
+ const log = existsSync(join(home, 'orchestrator.log')) ? readFileSync(join(home, 'orchestrator.log'), 'utf8') : '';
+ return { ...result, log, doc: parseDocument(result.stdout), out: result.stderr + result.stdout };
+}
+
+describeE2E('apply-migrations exit when the schema stays behind (#6089, Postgres)', () => {
+ beforeAll(async () => {
+ assertSafeE2eDatabaseUrl(DATABASE_URL!);
+ scratchName = `gbrain_test_schema_exit_${randomUUID().replaceAll('-', '')}`;
+ admin = postgres(DATABASE_URL!, { max: 1, prepare: false });
+ await admin.unsafe(`CREATE DATABASE ${scratchName}`);
+ const url = new URL(DATABASE_URL!);
+ url.pathname = `/${scratchName}`;
+ scratchUrl = url.toString();
+ const engine = new PostgresEngine();
+ await engine.connect({ database_url: scratchUrl });
+ await engine.initSchema();
+ await engine.disconnect();
+ conn = postgres(scratchUrl, { max: 1, prepare: false });
+ }, 180_000);
+
+ afterAll(async () => {
+ await conn?.end();
+ if (admin) {
+ await admin.unsafe(`DROP DATABASE IF EXISTS ${scratchName} WITH (FORCE)`);
+ await admin.end();
+ }
+ for (const home of homes) rmSync(home, { recursive: true, force: true });
+ });
+
+ beforeEach(async () => {
+ await conn!.unsafe(`DO $$ BEGIN IF to_regclass('config_hidden_6089') IS NOT NULL THEN ALTER TABLE config_hidden_6089 RENAME TO config; END IF; END $$`);
+ await conn!.unsafe(`DELETE FROM gbrain_cycle_locks WHERE id = 'gbrain-apply-migrations'`);
+ });
+
+ test('only the reconcile re-check left, schema behind, no --yes: exit 1 not_applied, re-check not run', async () => {
+ await setVersion(LATEST_VERSION - 1);
+ const r = await run(['reconcile'], []);
+ expect(r.code, r.out).toBe(1);
+ expect(r.doc.code).toBe('migrations_pending');
+ expect(r.doc.reason).toBe('not_applied');
+ expect(r.doc.schema_pending).toMatchObject({ current: LATEST_VERSION - 1, latest: LATEST_VERSION, pending: [LATEST_VERSION] });
+ expect(r.doc.fix.argv).toContain('--yes');
+ expect(r.log).toBe('');
+ expect(await readVersion()).toBe(LATEST_VERSION - 1);
+ }, 120_000);
+
+ test('only the re-check left, --yes, the schema migration fails: exit 1 still_behind, the fix is a report, not another --yes', async () => {
+ await setVersion(LATEST_VERSION - 1);
+ const r = await run(['reconcile'], ['--yes', '--non-interactive'], { failSchemaMigrations: true });
+ expect(r.code, r.out).toBe(1);
+ expect(r.doc.code).toBe('migrations_pending');
+ expect(r.doc.reason).toBe('still_behind');
+ expect(r.doc.schema_pending.pending).toEqual([LATEST_VERSION]);
+ expect(r.doc.fix.next).toBe('report');
+ expect(r.doc.fix.argv).toBeUndefined();
+ expect(r.doc.fix.verify.argv).toEqual(['gbrain', 'doctor', '--json']);
+ expect(r.log).toBe('');
+ }, 120_000);
+
+ test('only the re-check left, --yes: the schema is migrated, the re-check runs, exit 0', async () => {
+ await setVersion(LATEST_VERSION - 1);
+ const r = await run(['reconcile'], ['--yes', '--non-interactive']);
+ expect(r.code, r.out).toBe(0);
+ expect(r.log).toBe('ran reconcile\n');
+ expect(await readVersion()).toBe(LATEST_VERSION);
+ }, 120_000);
+
+ test('schema current, no --yes: the re-check runs, exit 0', async () => {
+ await setVersion(LATEST_VERSION);
+ const r = await run(['reconcile'], []);
+ expect(r.code, r.out).toBe(0);
+ expect(r.doc.status).toBe('ok');
+ expect(r.log).toBe('ran reconcile\n');
+ }, 120_000);
+
+ test('a pending orchestrator that leaves the schema behind runs, then exit 1', async () => {
+ await setVersion(LATEST_VERSION - 1);
+ const r = await run(['reconcile', 'noop'], []);
+ expect(r.code, r.out).toBe(1);
+ expect(r.log).toContain('ran noop');
+ expect(r.doc.code).toBe('migrations_pending');
+ expect(r.doc.reason).toBe('not_applied');
+ expect(r.doc.schema_pending.pending).toEqual([LATEST_VERSION]);
+ }, 120_000);
+
+ test('a pending orchestrator that migrates the schema itself: exit 0', async () => {
+ await setVersion(LATEST_VERSION - 1);
+ const r = await run(['reconcile', 'migrate_schema'], []);
+ expect(r.code, r.out).toBe(0);
+ expect(r.log).toContain('ran migrate_schema');
+ }, 120_000);
+
+ test('the schema version cannot be read back after orchestrators: exit 1 schema_unreadable with the read error', async () => {
+ await setVersion(LATEST_VERSION);
+ const r = await run(['reconcile', 'hide_version'], ['--yes', '--non-interactive']);
+ expect(r.code, r.out).toBe(1);
+ expect(r.doc.code).toBe('migrations_pending');
+ expect(r.doc.reason).toBe('schema_unreadable');
+ expect(r.doc.message).toContain('could not be read');
+ expect(r.doc.schema_pending).toMatchObject({ current: null, latest: LATEST_VERSION });
+ expect(r.doc.fix.next).toBe('report');
+ }, 120_000);
+
+ test('gbrain post-upgrade (in-process apply-migrations --yes) stops on a schema that stays behind', async () => {
+ await setVersion(LATEST_VERSION - 1);
+ const r = await run(['reconcile'], [], { failSchemaMigrations: true, entry: 'post-upgrade' });
+ expect(r.code, r.out).toBe(1);
+ expect(r.doc.code).toBe('migrations_pending');
+ expect(r.doc.reason).toBe('still_behind');
+ expect(r.doc.apply_migrations).toEqual({ exit_code: 1 });
+ expect(r.doc.fix.next).toBe('report');
+ }, 120_000);
+
+ test('a failed orchestrator reports migration_failed ahead of the schema check', async () => {
+ await setVersion(LATEST_VERSION - 1);
+ const r = await run(['reconcile', 'fail'], []);
+ expect(r.code, r.out).toBe(1);
+ expect(r.doc.code).toBe('migration_failed');
+ }, 120_000);
+});
diff --git a/test/helpers/apply-migrations-schema-driver.ts b/test/helpers/apply-migrations-schema-driver.ts
new file mode 100644
index 0000000000..a808e37386
--- /dev/null
+++ b/test/helpers/apply-migrations-schema-driver.ts
@@ -0,0 +1,99 @@
+/**
+ * #6089 driver: the real apply-migrations runner in a child process against a
+ * stubbed orchestrator registry, so a test controls which orchestrator work is
+ * pending while the schema-version check runs for real (PGLite or Postgres).
+ */
+import { appendFileSync, mkdirSync, writeFileSync } from 'node:fs';
+import { join, resolve } from 'node:path';
+
+const REPO = resolve(import.meta.dir, '..', '..');
+
+/**
+ * `reconcile` is an applied re-check that runs on every pass (like the
+ * shared-content migration); the others are pending. `migrate_schema` stamps
+ * the schema at head; `hide_version` renames the config table so the version
+ * cannot be read back; `fail` reports a failed orchestrator.
+ */
+export type StubMigration = 'reconcile' | 'noop' | 'migrate_schema' | 'hide_version' | 'fail';
+
+export interface SchemaDriverOpts {
+ args: string[];
+ /**
+ * `apply-migrations` (default) runs the runner with `args`; `post-upgrade`
+ * runs `gbrain post-upgrade` in-process with `args`; `argv` runs the runner
+ * with the driver's own arguments after a leading `apply-migrations`, so a
+ * `gbrain` shim on PATH can stand in for the CLI.
+ */
+ entry?: 'apply-migrations' | 'post-upgrade' | 'argv';
+ migrations: StubMigration[];
+ /** Make the schema migration runner throw (a schema migration that cannot apply). */
+ failSchemaMigrations?: boolean;
+}
+
+/** Writes the driver into `home` and marks the reconcile migration applied in the ledger. */
+export function writeSchemaDriver(home: string, opts: SchemaDriverOpts): string {
+ const ledgerDir = join(home, '.gbrain', 'migrations');
+ mkdirSync(ledgerDir, { recursive: true });
+ if (opts.migrations.includes('reconcile')) {
+ appendFileSync(join(ledgerDir, 'completed.jsonl'), `${JSON.stringify({ version: '0.0.1', status: 'complete' })}\n`);
+ }
+ const stubs = opts.migrations.map((kind, i) => ({ kind, version: kind === 'reconcile' ? '0.0.1' : `0.0.${i + 2}` }));
+ const driver = join(home, `schema-driver-${Math.random().toString(36).slice(2)}.ts`);
+ writeFileSync(driver, `import { mock } from 'bun:test';
+import { appendFileSync, readFileSync } from 'node:fs';
+const log = ${JSON.stringify(join(home, 'orchestrator.log'))};
+const configPath = ${JSON.stringify(join(home, '.gbrain', 'config.json'))};
+const migratePath = ${JSON.stringify(join(REPO, 'src/core/migrate.ts'))};
+const realMigrate = { ...(await import(migratePath)) };
+if (${opts.failSchemaMigrations === true}) {
+ mock.module(migratePath, () => ({ ...realMigrate, runMigrations: async () => { throw new Error('stub schema migration failure'); } }));
+}
+async function withEngine(fn) {
+ const { createEngine } = await import(${JSON.stringify(join(REPO, 'src/core/engine-factory.ts'))});
+ const cfg = JSON.parse(readFileSync(configPath, 'utf8'));
+ const engine = await createEngine(cfg);
+ await engine.connect(cfg);
+ try { await fn(engine); } finally { await engine.disconnect(); }
+}
+const actions = {
+ reconcile: async () => {},
+ noop: async () => {},
+ migrate_schema: () => withEngine(engine => engine.setConfig('version', String(realMigrate.LATEST_VERSION))),
+ hide_version: () => withEngine(engine => engine.executeRaw('ALTER TABLE config RENAME TO config_hidden_6089')),
+ fail: async () => {},
+};
+mock.module(${JSON.stringify(join(REPO, 'src/commands/migrations/index.ts'))}, () => ({
+ compareVersions: (a, b) => a.localeCompare(b, undefined, { numeric: true }),
+ migrations: ${JSON.stringify(stubs)}.map(({ kind, version }) => ({
+ version,
+ ...(kind === 'reconcile' ? { reconcile: true } : {}),
+ featurePitch: { headline: 'schema exit probe ' + kind },
+ orchestrator: async () => {
+ appendFileSync(log, 'ran ' + kind + '\\n');
+ await actions[kind]();
+ return { version, status: kind === 'fail' ? 'failed' : 'complete', phases: [] };
+ },
+ })),
+}));
+${entryCode(opts)}
+process.exit(0);
+`);
+ return driver;
+}
+
+function entryCode(opts: SchemaDriverOpts): string {
+ if (opts.entry === 'post-upgrade') {
+ return `const { runPostUpgrade } = await import(${JSON.stringify(join(REPO, 'src/commands/upgrade.ts'))});
+await runPostUpgrade(${JSON.stringify(opts.args)});`;
+ }
+ const args = opts.entry === 'argv' ? "process.argv.slice(2).filter((a, i) => i > 0 || a !== 'apply-migrations')" : JSON.stringify(opts.args);
+ return `const { runApplyMigrations } = await import(${JSON.stringify(join(REPO, 'src/commands/apply-migrations.ts'))});
+await runApplyMigrations(${args});`;
+}
+
+/** The `--json` failure envelope (or success document) a run printed on stdout. */
+export function parseDocument(stdout: string): Record<string, any> {
+ const line = stdout.trim().split('\n').filter(l => l.startsWith('{')).pop();
+ if (!line) throw new Error(`no JSON document on stdout: ${stdout}`);
+ return JSON.parse(line);
+}
diff --git a/test/test-reads-source-smell.test.ts b/test/test-reads-source-smell.test.ts
index 1223f6ad68..f75b4c6314 100644
--- a/test/test-reads-source-smell.test.ts
+++ b/test/test-reads-source-smell.test.ts
@@ -53,7 +53,7 @@ const GRANDFATHERED: Record<string, number> = {
'admin-sse-eventsource.test.ts': 1,
'agent-register.test.ts': 2,
'ai/silent-drop-regression.test.ts': 1,
- 'apply-migrations.test.ts': 3,
+ 'apply-migrations.test.ts': 2,
'archived-source-scoping.test.ts': 1,
'autopilot-cycle-failure-classification.test.ts': 1,
'autopilot-fanout-wiring.test.ts': 1,