Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(migrations): report migration_lease_lost when the lease row still names this runner (#6028)
garrytan4244c7f184c4
diff --git a/docs/architecture/key-files/commands-1.md b/docs/architecture/key-files/commands-1.mdindex d7b7bd8ae1..6831d177f8 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). #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.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-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.mdindex 7a2fc220f9..f67f3f7b57 100644--- a/docs/guides/error-codes.md+++ b/docs/guides/error-codes.md@@ -1508,6 +1508,14 @@ More: [docs/guides/shared-brain-skills.md#troubleshoot-leave-and-recover](../../Reasons: `orchestrator_failed`, `orchestrator_threw`, `ledger_write_failed`, `preview_failed`, `schema_failed`.+### migration_lease_lost++<a id="migration_lease_lost"></a>++| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |+|---|---|---|---|---|---|---|+| This apply-migrations run's own migration lease no longer matched its fence, so it stopped before the next migration. | The lease row still names this process (pid and host), but the fenced refresh matched no row: the direct and main database connections may reach different databases, or the row was rewritten. The details say whether the acquisition token and acquisition time still match (never the token itself). Run `gbrain doctor --json` and report it (#6028). | Server-side failure, not a caller mistake. Run `gbrain doctor --json` on the brain host; if it repeats, report it to the user. | host_admin | `gbrain doctor --json` | 1 | no |+### migrations_pending<a id="migrations_pending"></a>diff --git a/src/commands/apply-migrations.ts b/src/commands/apply-migrations.tsindex 7208ac33b4..0899d2d9f5 100644--- a/src/commands/apply-migrations.ts+++ b/src/commands/apply-migrations.ts@@ -18,6 +18,7 @@ import { gbrainPath, loadConfig } from '../core/config.ts';import { LiveServeLockError, PgliteBusyError, peekLock } from '../core/pglite-lock.ts';import {acquireMigrationOrchestrationLock,+ MigrationLeaseLostError,MIGRATIONS_RUNNING_EXIT_CODE,MigrationsRunningError,type MigrationOrchestrationLock,@@ -182,7 +183,8 @@ Flags:Exit codes:0 Success (including "nothing to do").- 1 An orchestrator failed, or the run left the schema behind+ 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 → rerun with --yes; still_behind orschema_unreadable → run gbrain doctor --json and report, not --yes again).An unreachable Postgres stays 0 (GBRAIN_DB_ACCESS on stderr) unless --require-db.@@ -526,7 +528,17 @@ export async function applyMigrations(args: string[]): Promise<{ exitCode: numbeawait holdLock();exitCode = await runLockedMigrations(cli, installed, holdLock, () => held.lock, report, args);} catch (error) {- if (error instanceof MigrationsRunningError) {+ if (error instanceof MigrationLeaseLostError) {+ console.error(`apply-migrations stopped: ${error.message}`);+ report.doc.status = 'lease_lost';+ report.doc.lease = error.details;+ report.failure = opError('migration_lease_lost', error.message,+ 'Run `gbrain doctor --json` and report this to the user with the lease details; do not delete the lease row or rerun in a loop.',+ { why: 'The migration lease row still names this run, but its fenced refresh matched nothing, so mutual exclusion can no longer be proven (#6028).',+ fix: { consent: [], actor: 'agent', requires_exclusive: false, why: 'Tell the user the migration lease no longer matched its own fence and what doctor reports.',+ verify: { argv: ['gbrain', 'doctor', '--json'] } } });+ exitCode = 1;+ } else if (error instanceof MigrationsRunningError) {console.error(`apply-migrations refused: ${error.message}`);report.doc.status = 'refused';report.failure = opError('migrations_running', error.message,diff --git a/src/core/error-registry.ts b/src/core/error-registry.tsindex a6e934c2e9..313fee6414 100644--- a/src/core/error-registry.ts+++ b/src/core/error-registry.ts@@ -218,6 +218,8 @@ export const CODES = {membership_inactive: { class: 'caller', summary: "The shared-skills enrollment epoch was left or superseded.", docs: 'docs/guides/shared-brain-skills.md#membership-inactive-after-a-re-enrollment' },membership_not_found: { class: 'caller', summary: "This principal has no shared-skills membership with that installation id.", docs: 'docs/guides/shared-brain-skills.md#troubleshoot-leave-and-recover' },method_not_allowed: { class: 'caller', summary: "The HTTP method is not allowed on this endpoint." },+ migration_lease_lost: { class: 'server', summary: "This apply-migrations run's own migration lease no longer matched its fence, so it stopped before the next migration.",+ why: 'The lease row still names this process (pid and host), but the fenced refresh matched no row: the direct and main database connections may reach different databases, or the row was rewritten. The details say whether the acquisition token and acquisition time still match (never the token itself). Run `gbrain doctor --json` and report it (#6028).' },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.",diff --git a/src/core/migration-orchestration-lock.ts b/src/core/migration-orchestration-lock.tsindex 714c99222f..41104dab79 100644--- a/src/core/migration-orchestration-lock.ts+++ b/src/core/migration-orchestration-lock.ts@@ -48,10 +48,36 @@ export class MigrationsRunningError extends Error {}}+/** Which part of this runner's own lease row no longer matches its fence; values only, never the token itself. */+export interface MigrationLeaseLostDetails {+ holder_pid: number;+ holder_host: string;+ token_match: boolean;+ fence_match: boolean;+ expected_fence: string;+ observed_acquired_at: string;+}++/**+ * #6028 diagnostic: the fenced refresh of this runner's lease matched no row,+ * yet the row still names this process. No other runner holds it, so this is+ * not `migrations_running`. The refresh goes through the direct pool and the+ * holder read through the main pool; a mismatch can mean the two reach+ * different databases, or the row was rewritten. Root cause pending (#6028).+ */+export class MigrationLeaseLostError extends Error {+ readonly code = 'migration_lease_lost';+ constructor(readonly details: MigrationLeaseLostDetails) {+ super(`this apply-migrations run's own migration lease (pid ${details.holder_pid}, host ${details.holder_host}) no longer matches its fence `+ + `(acquisition token ${details.token_match ? 'matches' : 'differs'}, acquisition time ${details.fence_match ? 'matches' : 'differs'}); stopped before the next migration.`);+ this.name = 'MigrationLeaseLostError';+ }+}+export interface MigrationOrchestrationLock {/** Postgres lease acquisition token; quiescence checks exclude this runner's own row by it. */leaseToken?: string;- /** Throws MigrationsRunningError when the lease was lost to another runner. */+ /** Throws MigrationsRunningError when the lease was lost to another runner, MigrationLeaseLostError when the row still names this one. */assertHeld(): Promise<void>;release(): Promise<void>;}@@ -130,6 +156,16 @@ async function acquirePostgres(config: GBrainConfig): Promise<MigrationOrchestraassertHeld: async () => {if (await handle.refresh()) return;const snapshot = await inspectLock(engine, MIGRATION_ORCHESTRATION_LOCK_ID).catch(() => null);+ if (snapshot?.holder_pid === process.pid && snapshot.holder_host === hostname()) {+ throw new MigrationLeaseLostError({+ holder_pid: snapshot.holder_pid,+ holder_host: snapshot.holder_host,+ token_match: snapshot.acquisition_token === handle.acquisitionToken,+ fence_match: Math.abs(Number(handle.acquiredAt) * 1000 - new Date(snapshot.acquired_at).getTime()) < 1,+ expected_fence: handle.acquiredAt,+ observed_acquired_at: new Date(snapshot.acquired_at).toISOString(),+ });+ }throw new MigrationsRunningError({ host: snapshot?.holder_host ?? null, pid: snapshot?.holder_pid ?? null });},release: async () => {diff --git a/test/apply-migrations-safety.serial.test.ts b/test/apply-migrations-safety.serial.test.tsindex ed83b006f9..4eec22c8c1 100644--- a/test/apply-migrations-safety.serial.test.ts+++ b/test/apply-migrations-safety.serial.test.ts@@ -131,6 +131,7 @@ mock.module(${JSON.stringify(join(root, 'src/core/migration-orchestration-lock.tacquireMigrationOrchestrationLock: async () => ({ assertHeld: async () => {}, release: async () => {} }),MIGRATIONS_RUNNING_EXIT_CODE: 75,MigrationsRunningError: class extends Error {},+ MigrationLeaseLostError: class extends Error {},}));const factory = await import(${JSON.stringify(join(root, 'src/core/engine-factory.ts'))});mock.module(${JSON.stringify(join(root, 'src/core/engine-factory.ts'))}, () => ({diff --git a/test/e2e/migration-lease-lost.test.ts b/test/e2e/migration-lease-lost.test.tsnew file mode 100644index 0000000000..a2c519423e--- /dev/null+++ b/test/e2e/migration-lease-lost.test.ts@@ -0,0 +1,96 @@+/**+ * #6028 diagnostic: when the fenced refresh of a held migration lease matches+ * no row but the row still names this process (same pid and host), the+ * runner did not lose the lease to another runner, so it must not say+ * "another apply-migrations is running" naming its own pid. `assertHeld`+ * raises `migration_lease_lost` with which part of the fence no longer+ * matches (no token values), and the runner reports it (exit 1).+ * Run: DATABASE_URL=... bun test test/e2e/migration-lease-lost.test.ts+ */+import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';+import { hostname } from 'node:os';+import { rmSync } from 'node:fs';+import { hasDatabase, setupDB, teardownDB, getConn } from './helpers.ts';+import { collect, logHas, makeHome, spawnDriver, writeDriver } from '../helpers/apply-migrations-lock-driver.ts';+import {+ acquireMigrationOrchestrationLock,+ MIGRATION_ORCHESTRATION_LOCK_ID,+ MigrationsRunningError,+} from '../../src/core/migration-orchestration-lock.ts';++const describeE2E = hasDatabase() ? describe : describe.skip;+const config = () => ({ engine: 'postgres' as const, database_url: process.env.DATABASE_URL! });++async function heldLock() {+ const lock = await acquireMigrationOrchestrationLock(config());+ if (!lock) throw new Error('expected the Postgres migration lease');+ return lock;+}++type LeaseLost = Error & { code: string; details: Record<string, unknown> };++async function caught(promise: Promise<unknown>): Promise<unknown> {+ try { await promise; } catch (error) { return error; }+ throw new Error('expected assertHeld to throw');+}++describeE2E('migration lease lost under this runner (#6028, Postgres)', () => {+ beforeAll(async () => { await setupDB(); });+ afterAll(async () => { await teardownDB(); });+ beforeEach(async () => {+ await getConn().unsafe('DELETE FROM gbrain_cycle_locks WHERE id = $1', [MIGRATION_ORCHESTRATION_LOCK_ID]);+ });++ test('own row with a rewritten acquisition token: migration_lease_lost, token mismatch, fence match', async () => {+ const lock = await heldLock();+ try {+ await getConn().unsafe('UPDATE gbrain_cycle_locks SET acquisition_token = gen_random_uuid() WHERE id = $1', [MIGRATION_ORCHESTRATION_LOCK_ID]);+ const lost = await caught(lock.assertHeld()) as LeaseLost;+ expect(lost.code).toBe('migration_lease_lost');+ expect(lost.details).toMatchObject({ holder_pid: process.pid, holder_host: hostname(), token_match: false, fence_match: true });+ expect(lost.message).not.toContain('another apply-migrations is running');+ expect(JSON.stringify(lost.details)).not.toContain(lock.leaseToken!);+ } finally {+ await lock.release();+ }+ });++ test('own row with a moved acquisition time: migration_lease_lost, fence mismatch, token match', async () => {+ const lock = await heldLock();+ try {+ await getConn().unsafe(`UPDATE gbrain_cycle_locks SET acquired_at = acquired_at - interval '1 second' WHERE id = $1`, [MIGRATION_ORCHESTRATION_LOCK_ID]);+ const lost = await caught(lock.assertHeld()) as LeaseLost;+ expect(lost.code).toBe('migration_lease_lost');+ expect(lost.details).toMatchObject({ token_match: true, fence_match: false });+ } finally {+ await lock.release();+ }+ });++ test('a row that names another holder still refuses as migrations_running', async () => {+ const lock = await heldLock();+ try {+ await getConn().unsafe(`UPDATE gbrain_cycle_locks SET holder_pid = 4242, holder_host = 'host-b', acquisition_token = gen_random_uuid() WHERE id = $1`, [MIGRATION_ORCHESTRATION_LOCK_ID]);+ const error = await caught(lock.assertHeld());+ expect(error).toBeInstanceOf(MigrationsRunningError);+ expect((error as Error).message).toContain('host host-b, pid 4242');+ } finally {+ await lock.release();+ await getConn().unsafe('DELETE FROM gbrain_cycle_locks WHERE id = $1', [MIGRATION_ORCHESTRATION_LOCK_ID]);+ }+ });++ test('the runner reports migration_lease_lost (exit 1) and stops before the next migration', async () => {+ const home = makeHome({ engine: 'postgres', database_url: process.env.DATABASE_URL! });+ try {+ const run = await collect(spawnDriver(home, writeDriver(home, { holdMs: 0, openDatastore: false, rotateOwnToken: true })));+ expect(run.code, run.stderr + run.stdout).toBe(1);+ expect(run.stderr).toContain('Error [migration_lease_lost]');+ expect(run.stderr).not.toContain('another apply-migrations is running');+ expect(logHas(home, 'start')).toBe(false);+ } finally {+ await getConn().unsafe('DELETE FROM gbrain_cycle_locks WHERE id = $1', [MIGRATION_ORCHESTRATION_LOCK_ID]);+ rmSync(home, { recursive: true, force: true });+ }+ }, 120_000);+});diff --git a/test/helpers/apply-migrations-lock-driver.ts b/test/helpers/apply-migrations-lock-driver.tsindex 51d90c6e0f..f9db10aa05 100644--- a/test/helpers/apply-migrations-lock-driver.ts+++ b/test/helpers/apply-migrations-lock-driver.ts@@ -18,7 +18,11 @@ export function makeHome(engine: LockTestEngine): string {/** A runner whose single pending migration logs start/end and holds for `holdMs`. *//** `stealLease` adds an earlier migration that hands the Postgres lease to another holder; the probe migration then must not run. */-export function writeDriver(home: string, opts: { holdMs: number; openDatastore: boolean; fail?: boolean; stealLease?: boolean }): string {+/** `rotateOwnToken` instead rewrites only the lease's acquisition token, so the row still names this runner (#6028). */+export function writeDriver(home: string, opts: { holdMs: number; openDatastore: boolean; fail?: boolean; stealLease?: boolean; rotateOwnToken?: boolean }): string {+ const leaseUpdate = opts.rotateOwnToken+ ? "UPDATE gbrain_cycle_locks SET acquisition_token=gen_random_uuid() WHERE id='gbrain-apply-migrations'"+ : "UPDATE gbrain_cycle_locks SET holder_pid=4242, holder_host='host-b', acquisition_token=gen_random_uuid() WHERE id='gbrain-apply-migrations'";const driver = join(home, `driver-${Math.random().toString(36).slice(2)}.ts`);writeFileSync(driver, `import { mock } from 'bun:test';import { appendFileSync, readFileSync } from 'node:fs';@@ -42,7 +46,7 @@ mock.module(${JSON.stringify(join(REPO, 'src/commands/migrations/index.ts'))}, (appendFileSync(log, 'end ' + process.pid + '\\n');return { version: ${JSON.stringify(VERSION)}, status: ${JSON.stringify(opts.fail ? 'failed' : 'complete')}, phases: [] };},- }, ...(${opts.stealLease === true} ? [{+ }, ...(${opts.stealLease === true || opts.rotateOwnToken === true} ? [{version: '0.0.1',featurePitch: { headline: 'hands the lease to another holder' },orchestrator: async () => {@@ -50,7 +54,7 @@ mock.module(${JSON.stringify(join(REPO, 'src/commands/migrations/index.ts'))}, (const { createEngine } = await import(${JSON.stringify(join(REPO, 'src/core/engine-factory.ts'))});const engine = await createEngine(cfg);await engine.connect(cfg);- await engine.executeRaw("UPDATE gbrain_cycle_locks SET holder_pid=4242, holder_host='host-b', acquisition_token=gen_random_uuid() WHERE id='gbrain-apply-migrations'");+ await engine.executeRaw(${JSON.stringify(leaseUpdate)});await engine.disconnect();return { version: '0.0.1', status: 'complete', phases: [] };},