Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
perf(setup): one PGLite open shared across a run's setup migrations; install docs lead with gbrain setup
garrytan141285e2c2a3
diff --git a/AGENTS.md b/AGENTS.mdindex 707571d959..fd2a710320 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -29,7 +29,10 @@ start here.only when the schema is at head; exit 1 with `migrations_pending` means the schema is still behind, and another`--yes` repeats the failure, so run `gbrain doctor --json` and fall back to the deterministic install:`git clone https://github.com/garrytan/gbrain.git ~/gbrain && cd ~/gbrain && bun install && bun link`.-2. Init keyless memory: `gbrain init --pglite --no-embedding` (zero-config). For 1000+ files or+ Bun blocks gbrain's postinstall on `bun install -g` (`Blocked 1 postinstall`); a new install can skip it: the script only repeats the refusal every gbrain command prints on a Bun below the floor and runs `gbrain apply-migrations --yes --non-interactive`, which has nothing to migrate before a brain exists, and `gbrain setup` creates the brain and applies its setup migrations.+2. Set up keyless memory for the harness: `gbrain setup claude-code` (on Codex, `gbrain setup codex`)+ creates the brain if none exists, wires MCP and verifies it. Otherwise, or for any other harness, init keyless+ memory: `gbrain init --pglite --no-embedding` (zero-config). For 1000+ files ormulti-machine sync, init suggests Postgres + pgvector via Supabase.3. **STOP — ask the user about search mode.** `gbrain init` auto-applied adefault but printed a 9-cell cost matrix (mode × downstream model)diff --git a/INSTALL_FOR_AGENTS.md b/INSTALL_FOR_AGENTS.mdindex 620c27a7f1..1ee091db19 100644--- a/INSTALL_FOR_AGENTS.md+++ b/INSTALL_FOR_AGENTS.md@@ -57,6 +57,9 @@ bun install -g github:garrytan/gbrainVerify: `gbrain --version` should print a version number. If `gbrain` is not found,restart the shell or add the PATH export to the shell profile.+Next, on Claude Code or Codex: `gbrain setup claude-code` (or `gbrain setup codex`), which needs no API+key ([Step 3](#step-3-create-the-brain)). On any other harness, `gbrain init --pglite --no-embedding` (Step 3).+> **If `bun install -g` aborts or `gbrain doctor` reports `schema_version: 0`** (Bun> occasionally blocks the top-level postinstall hook on global installs, so schema> migrations don't run automatically), the CLI prints a recovery hint pointing at@@ -69,6 +72,8 @@ restart the shell or add the PATH export to the shell profile.> git clone https://github.com/garrytan/gbrain.git ~/gbrain && cd ~/gbrain> bun install && bun link> ```+>+> Bun blocks gbrain's postinstall on `bun install -g` (`Blocked 1 postinstall`); a new install can skip it: the script only repeats the refusal every gbrain command prints on a Bun below the floor and runs `gbrain apply-migrations --yes --non-interactive`, which has nothing to migrate before a brain exists, and `gbrain setup` creates the brain and applies its setup migrations.## Step 2: API Keysdiff --git a/docs/architecture/key-files/commands-1.md b/docs/architecture/key-files/commands-1.mdindex 3c11d5f95f..b4e4191876 100644--- a/docs/architecture/key-files/commands-1.md+++ b/docs/architecture/key-files/commands-1.md@@ -4,7 +4,8 @@Current behavior and load-bearing invariants; history belongs in Git and CHANGELOG.- `src/commands/apply-migrations.ts` and `src/commands/migrations/v0_11_0.ts` — forced dry-runs return a no-write action preview before opening a database or loading/copying the migration ledger. Any failed phase makes the migration partial, stops the chain and exits nonzero; ordinary pending-host-work partial results retain their resume behavior. Explicit `--force-retry` recovers a historical false-complete record. No-autopilot skips remain successful and do not install services. Every run except `--list` and `--dry-run` holds the orchestration lock (`src/core/migration-orchestration-lock.ts`) from before its first ledger write through its final status: a Postgres TTL lease row `gbrain-apply-migrations` in `gbrain_cycle_locks` (survives transaction-mode poolers; an unreachable database or a schema without the table runs unlocked until the preflight creates it), or on PGLite a native lock on `<datastore>.gbrain-migrations.lock`, separate from the datastore lock so orchestrators still open the datastore. A second runner prints `another apply-migrations is running (host …, pid …)` and exits 75; dead holders are taken over by the existing db-lock and kernel rules. The locked body returns its exit status so the lock is released before `process.exit`. Tests: `apply-migrations-safety.serial.test.ts`, `apply-migrations-orchestration-lock.test.ts`, `e2e/apply-migrations-orchestration-lock.test.ts` and `e2e/migration-preview-safety.test.ts`. D2 (`json: 'document'`): every `--json` path is one single-line document (`status` unconfigured/dry_run/listed/ok/partial/up_to_date, `plan`, `previews`, `results[]`, `retry_markers`, `schema`); a non-zero exit is one envelope leading with those keys (`invalid_params` exit 2, `migration_failed` with reasons, `migrations_pending` with `schema_pending`, `database_error` for `--require-db`, `migrations_running` exit 75, `migration_lease_lost` exit 1 with `lease`). #6089: the run never exits 0 with the schema behind (`src/commands/apply-migrations-schema.ts`); an applied reconcile re-check is not pending work, so with nothing else pending a schema the pre-flight left behind fails before the re-check, and after orchestrators the version is read again. #6028 diagnostic: `assertHeld` raises `MigrationLeaseLostError` (`migration_lease_lost`, details say whether the acquisition token and time still match, never the token) when the conflicting lease row names this pid and host, instead of `migrations_running`; tests `e2e/migration-lease-lost.test.ts`. A4: `Migration.effects` (v0.11.0: `persistent_install`, its Phase F autopilot install) is asked through `consentGate` before the orchestrator runs (skipped under `--no-autopilot-install` or on PGLite); `--yes`, `--non-interactive` (mapped to `persistent_install` only), a preapproval or a TTY yes authorize, otherwise exit 3. `applyMigrations()` returns `{exitCode, failure}` for in-process callers (post-upgrade); `runApplyMigrations()` exits. Child CLIs use `cliChildStdio()`. Tests: `test/cli-json-commands.test.ts`. the plan adds `pending_fresh_install` (unrun setup work on a brain `gbrain init` created; runs like `pending`, reported as expected work, never as a failed upgrade); `--list --json` prints one row per migration (`fresh_install: true` on init stamps) plus `next.argv` when work remains; a phase's `argv` prints as its next step. Forced dry-runs return a no-write action preview before opening a database or loading/copying the migration ledger. Any failed phase makes the migration partial, stops the chain and exits nonzero; ordinary pending-host-work partial results retain their resume behavior. Explicit `--force-retry` recovers a historical false-complete record. No-autopilot skips remain successful and do not install services. Every run except `--list` and `--dry-run` holds the orchestration lock (`src/core/migration-orchestration-lock.ts`) from before its first ledger write through its final status: a Postgres TTL lease row `gbrain-apply-migrations` in `gbrain_cycle_locks` (survives transaction-mode poolers; an unreachable database or a schema without the table runs unlocked until the preflight creates it), or on PGLite a native lock on `<datastore>.gbrain-migrations.lock`, separate from the datastore lock so orchestrators still open the datastore. A second runner prints `another apply-migrations is running (host …, pid …)` and exits 75; dead holders are taken over by the existing db-lock and kernel rules. The locked body returns its exit status so the lock is released before `process.exit`. Tests: `apply-migrations-safety.serial.test.ts`, `apply-migrations-orchestration-lock.test.ts`, `e2e/apply-migrations-orchestration-lock.test.ts` and `e2e/migration-preview-safety.test.ts`.-- `src/commands/apply-migrations-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/migrations/run-engine.ts` — one PGLite engine for consecutive migrations of an apply-migrations run (each open starts an embedded Postgres, about 130 ms). `withRunEngineSession` wraps the locked run; `setRunEngineSharing` enables sharing for the opt-out read, each migration flagged `sharesRunEngine` (v0.11.0, v0.14.0, v0.22.4, v0.28.0, v0.53.0) and the post-orchestrator schema check, and disabling it (before an unflagged migration, `--list`, `--dry-run` or a consent prompt) closes the engine. `connectMigrationEngine` returns the shared engine with a no-op close while sharing, otherwise a new engine its caller closes (Postgres always). `releaseRunEngine` closes it before a `gbrain` child that needs the brain (v0.11.0's `jobs smoke`). A fresh setup's migration child opens the brain three times instead of eight (counting the `jobs smoke` child); the ledger it writes is pinned by `test/fixtures/goldens/setup/fresh-setup-migration-ledger.json`. Tests: `test/migrations-run-engine.test.ts`.+- `src/commands/apply-migrations-schema.ts` — #6089 schema half of the apply-migrations exit contract. `connectAtSchemaVersion` connects the configured brain and reads `config.version` (pre-flight, `--force-schema`); the post-orchestrator check opens it through `connectMigrationEngine`. `checkSchemaAfterOrchestrators` re-reads the version after the orchestrators ran: on Postgres only when the pre-flight connected; on PGLite in-process once the orchestrators released the datastore (the pre-flight stays skipped, #1100; never a child process), applying the schema migrations under `--yes`/`--non-interactive`; a busy PGLite datastore is rethrown. `schemaPendingError` builds `migrations_pending` with reason `not_applied` (fix reruns with `--yes`), `still_behind` (after an authorized run) or `schema_unreadable` (both fix `next: report` with `gbrain doctor --json` as verify, never another `--yes`), each naming the pending schema versions. `reportDatabaseUnreachable` keeps an unreachable Postgres non-fatal but prints the `GBRAIN_DB_ACCESS <reason>` marker. Tests: `test/apply-migrations-schema-exit.test.ts` (PGLite, unreachable Postgres, post-upgrade, postinstall) and `test/e2e/apply-migrations-schema-exit.test.ts` (Postgres).- `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/llms-full.txt b/llms-full.txtindex 239366b3fb..750f39ce8c 100644--- a/llms-full.txt+++ b/llms-full.txt@@ -1734,7 +1734,10 @@ start here.only when the schema is at head; exit 1 with `migrations_pending` means the schema is still behind, and another`--yes` repeats the failure, so run `gbrain doctor --json` and fall back to the deterministic install:`git clone https://github.com/garrytan/gbrain.git ~/gbrain && cd ~/gbrain && bun install && bun link`.-2. Init keyless memory: `gbrain init --pglite --no-embedding` (zero-config). For 1000+ files or+ Bun blocks gbrain's postinstall on `bun install -g` (`Blocked 1 postinstall`); a new install can skip it: the script only repeats the refusal every gbrain command prints on a Bun below the floor and runs `gbrain apply-migrations --yes --non-interactive`, which has nothing to migrate before a brain exists, and `gbrain setup` creates the brain and applies its setup migrations.+2. Set up keyless memory for the harness: `gbrain setup claude-code` (on Codex, `gbrain setup codex`)+ creates the brain if none exists, wires MCP and verifies it. Otherwise, or for any other harness, init keyless+ memory: `gbrain init --pglite --no-embedding` (zero-config). For 1000+ files ormulti-machine sync, init suggests Postgres + pgvector via Supabase.3. **STOP — ask the user about search mode.** `gbrain init` auto-applied adefault but printed a 9-cell cost matrix (mode × downstream model)@@ -2605,6 +2608,9 @@ bun install -g github:garrytan/gbrainVerify: `gbrain --version` should print a version number. If `gbrain` is not found,restart the shell or add the PATH export to the shell profile.+Next, on Claude Code or Codex: `gbrain setup claude-code` (or `gbrain setup codex`), which needs no API+key ([Step 3](#step-3-create-the-brain)). On any other harness, `gbrain init --pglite --no-embedding` (Step 3).+> **If `bun install -g` aborts or `gbrain doctor` reports `schema_version: 0`** (Bun> occasionally blocks the top-level postinstall hook on global installs, so schema> migrations don't run automatically), the CLI prints a recovery hint pointing at@@ -2617,6 +2623,8 @@ restart the shell or add the PATH export to the shell profile.> git clone https://github.com/garrytan/gbrain.git ~/gbrain && cd ~/gbrain> bun install && bun link> ```+>+> Bun blocks gbrain's postinstall on `bun install -g` (`Blocked 1 postinstall`); a new install can skip it: the script only repeats the refusal every gbrain command prints on a Bun below the floor and runs `gbrain apply-migrations --yes --non-interactive`, which has nothing to migrate before a brain exists, and `gbrain setup` creates the brain and applies its setup migrations.## Step 2: API Keysdiff --git a/src/commands/apply-migrations-schema.ts b/src/commands/apply-migrations-schema.tsindex 832b8696f9..9238a21602 100644--- a/src/commands/apply-migrations-schema.ts+++ b/src/commands/apply-migrations-schema.ts@@ -22,6 +22,7 @@ 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 { connectMigrationEngine } from './migrations/run-engine.ts';import { DB_ACCESS_MARKER_PREFIX, shouldEmitDbAccessMarker } from '../core/pg-access-classify.ts';export type SchemaPendingReason = 'not_applied' | 'still_behind' | 'schema_unreadable';@@ -87,9 +88,10 @@ export async function checkSchemaAfterOrchestrators(opts: {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;+ const { engine, close } = await connectMigrationEngine(cfg);+ let current: number;try {+ current = parseInt(await engine.getConfig('version') || '1', 10);const { latest } = await pendingAbove(current);if (pglite && authorized && current < latest) {console.error(`Schema v${current} is behind v${latest}; applying schema migrations in-process...`);@@ -97,7 +99,7 @@ export async function checkSchemaAfterOrchestrators(opts: {current = parseInt(await engine.getConfig('version') || '1', 10);}} finally {- await engine.disconnect();+ await close();}lastRead = current;const { latest, pending } = await pendingAbove(current);diff --git a/src/commands/apply-migrations.ts b/src/commands/apply-migrations.tsindex 3348f83cc2..e17478c806 100644--- a/src/commands/apply-migrations.ts+++ b/src/commands/apply-migrations.ts@@ -25,6 +25,7 @@ import {} from '../core/migration-orchestration-lock.ts';import { loadCompletedMigrations, appendCompletedMigration, type CompletedMigrationEntry } from '../core/preferences.ts';import { migrations, compareVersions, type Migration, type OrchestratorOpts } from './migrations/index.ts';+import { setRunEngineSharing, withRunEngineSession } from './migrations/run-engine.ts';import { migrationDeclinedError, readDeclinedMigrations } from './migrations/opt-out.ts';import {indexCompletedEntries,@@ -540,7 +541,7 @@ export async function applyMigrations(args: string[]): Promise<{ exitCode: numbelet exitCode: number | undefined;try {await holdLock();- exitCode = await runLockedMigrations(cli, installed, holdLock, () => held.lock, report, args);+ exitCode = await withRunEngineSession(() => runLockedMigrations(cli, installed, holdLock, () => held.lock, report, args));} catch (error) {if (error instanceof MigrationLeaseLostError) {console.error(`apply-migrations stopped: ${error.message}`);@@ -664,6 +665,7 @@ async function runLockedMigrations(const completed = loadCompletedMigrations();const idx = indexCompleted(completed);+ await setRunEngineSharing(true);const declined = await readDeclinedMigrations(loadConfig()!);const plan = buildPlan(idx, installed, cli.specificMigration, declined);@@ -686,6 +688,7 @@ async function runLockedMigrations(// of a filesystem-only plan that renders identically to a clean database.const listExit = cli.requireDb && dbProbe.status === 'unreachable' ? 1 : 0;if (listExit) fail('database_unreachable', requireDbError(dbProbe));+ if (cli.list || cli.dryRun) await setRunEngineSharing(false);if (cli.list && cli.json) { Object.assign(doc, listJson(plan, idx, installed, dbProbe)); doc.status = listExit ? doc.status : 'listed'; return listExit; }if (cli.list) { printList(plan, installed, dbProbe); return listExit; }if (cli.dryRun) {@@ -741,6 +744,7 @@ async function runLockedMigrations(// --non-interactive mapping (persistent_install only), a preapproval, or a// TTY prompt. Refused: nothing runs, exit 3 with the consent payload.const consent = migrationConsentRequest(cli, toRun, args);+ if (consent) await setRunEngineSharing(false);if (consent && !(await consentGate(consent, { json: cli.json }))) {doc.status = 'confirmation_required';return 3;@@ -772,6 +776,7 @@ async function runLockedMigrations(for (const m of toRun) {// A lease lost while an earlier orchestrator ran stops the chain here.await holdLock();+ await setRunEngineSharing(m.sharesRunEngine === true);const recordCheckpoint = !m.reconcile || !plan.applied.includes(m);console.log(`\n=== Applying migration v${m.version}: ${m.featurePitch.headline} ===`);try {@@ -862,6 +867,7 @@ async function runLockedMigrations(}if (failed) return 1;+ await setRunEngineSharing(true);// #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,diff --git a/src/commands/migrations/in-process.ts b/src/commands/migrations/in-process.tsindex 50a13e3c47..d762546c9f 100644--- a/src/commands/migrations/in-process.ts+++ b/src/commands/migrations/in-process.ts@@ -24,9 +24,9 @@import { execSync } from 'child_process';import { resolveChildCliInvocation } from '../../core/minions/job-isolation.ts';-import { loadConfig, toEngineConfig } from '../../core/config.ts';+import { loadConfig } from '../../core/config.ts';import { buildGatewayConfig } from '../../core/ai/build-gateway-config.ts';-import { createEngine } from '../../core/engine-factory.ts';+import { connectMigrationEngine } from './run-engine.ts';/** Default wall-clock guard for in-process initSchema. Matches the 600s cap* the old `execSync('gbrain init --migrate-only', { timeout: 600_000 })` used,@@ -73,9 +73,8 @@ export async function runMigrateOnlyCore(opts?: { timeoutMs?: number }): PromiseconfigureGateway(buildGatewayConfig(config));const timeoutMs = opts?.timeoutMs ?? MIGRATE_ONLY_TIMEOUT_MS;- const engine = await createEngine(toEngineConfig(config));+ const { engine, close } = await connectMigrationEngine(config);try {- await engine.connect(toEngineConfig(config));const { runInitSchemaWithRetry } = await import('../../core/init-schema-retry.ts');await withTimeout(runInitSchemaWithRetry(engine).then(() => undefined),@@ -83,7 +82,7 @@ export async function runMigrateOnlyCore(opts?: { timeoutMs?: number }): Promise`schema init timed out after ${Math.round(timeoutMs / 1000)}s`,);} finally {- try { await engine.disconnect(); } catch { /* best-effort */ }+ try { await close(); } catch { /* best-effort */ }}return { engine: config.engine };diff --git a/src/commands/migrations/opt-out.ts b/src/commands/migrations/opt-out.tsindex c1d8d0e217..68eedd61d1 100644--- a/src/commands/migrations/opt-out.ts+++ b/src/commands/migrations/opt-out.ts@@ -10,11 +10,11 @@* shared by every machine on that database, so one machine's explicit run* does not override what the owner set for all of them.*/-import { createEngine } from '../../core/engine-factory.ts';-import { isThinClient, toEngineConfig, type GBrainConfig } from '../../core/config.ts';+import { isThinClient, type GBrainConfig } from '../../core/config.ts';import { declinedMigrations } from '../../core/migration-ledger.ts';import { opError, type OperationError } from '../../core/ops/contract.ts';import type { Migration } from './types.ts';+import { connectMigrationEngine } from './run-engine.ts';export { declinedMigrations, isMigrationDeclinedValue } from '../../core/migration-ledger.ts';@@ -26,9 +26,8 @@ export { declinedMigrations, isMigrationDeclinedValue } from '../../core/migratiexport async function readDeclinedMigrations(config: GBrainConfig): Promise<Set<string>> {if (isThinClient(config)) return new Set();try {- const engine = await createEngine(toEngineConfig(config));- await engine.connect(toEngineConfig(config));- try { return await declinedMigrations(engine); } finally { await engine.disconnect(); }+ const { engine, close } = await connectMigrationEngine(config);+ try { return await declinedMigrations(engine); } finally { await close(); }} catch {return new Set();}diff --git a/src/commands/migrations/run-engine.ts b/src/commands/migrations/run-engine.tsnew file mode 100644index 0000000000..e7aa4fafb0--- /dev/null+++ b/src/commands/migrations/run-engine.ts@@ -0,0 +1,74 @@+/**+ * One PGLite engine for consecutive migrations of one apply-migrations run.+ *+ * Each orchestrator used to open and close the brain itself, and a PGLite open+ * starts a new embedded Postgres (about 130 ms each). Inside a run session the+ * runner enables sharing only for a migration flagged `sharesRunEngine`+ * (types.ts): its opens through `connectMigrationEngine` return the run's one+ * engine and its close is deferred. Before a migration that is not flagged,+ * before a `gbrain` child that needs the brain (`releaseRunEngine`), and when+ * the session ends, the engine is closed, so nothing else ever finds the+ * datastore lock held. Outside a session, or on Postgres, every open is a new+ * engine closed by its caller, exactly as before.+ */+import type { GBrainConfig } from '../../core/config.ts';+import { toEngineConfig } from '../../core/config.ts';+import type { BrainEngine } from '../../core/engine.ts';+import { createEngine } from '../../core/engine-factory.ts';++interface RunSession { sharing: boolean; engine: BrainEngine | null; path: string | undefined }+let session: RunSession | null = null;++/** Opened brain plus its close: a no-op for the shared engine, which the session closes. */+export interface MigrationEngine { engine: BrainEngine; close: () => Promise<void> }++async function openEngine(config: GBrainConfig): Promise<BrainEngine> {+ const engineConfig = toEngineConfig(config);+ const engine = await createEngine(engineConfig);+ try { await engine.connect(engineConfig); }+ catch (error) { await engine.disconnect().catch(() => {}); throw error; }+ return engine;+}++/** Connect the configured brain (the run's shared engine when sharing is enabled on PGLite). */+export async function connectMigrationEngine(config: GBrainConfig): Promise<MigrationEngine> {+ if (!session?.sharing || config.engine !== 'pglite' || !config.database_path) {+ const engine = await openEngine(config);+ return { engine, close: () => engine.disconnect() };+ }+ if (session.engine && session.path !== config.database_path) await releaseRunEngine();+ if (!session.engine) {+ session.engine = await openEngine(config);+ session.path = config.database_path;+ }+ return { engine: session.engine, close: async () => {} };+}++/**+ * Close the shared engine now (a later shared open reopens it). Call before+ * spawning a `gbrain` child. Best-effort like the orchestrators' own closes: a+ * close that fails leaves the next open to report the held lock.+ */+export async function releaseRunEngine(): Promise<void> {+ const engine = session?.engine;+ if (!session || !engine) return;+ session.engine = null;+ await engine.disconnect().catch(() => {});+}++/** Enable or disable sharing for what runs next; disabling closes the shared engine first. */+export async function setRunEngineSharing(sharing: boolean): Promise<void> {+ if (!session) return;+ if (!sharing) await releaseRunEngine();+ session.sharing = sharing;+}++/** Run `fn` as one apply-migrations run session; the shared engine is closed when it ends. */+export async function withRunEngineSession<T>(fn: () => Promise<T>): Promise<T> {+ session = { sharing: false, engine: null, path: undefined };+ try { return await fn(); }+ finally {+ await releaseRunEngine();+ session = null;+ }+}diff --git a/src/commands/migrations/shared-content.ts b/src/commands/migrations/shared-content.tsindex b0f372b6df..bf58c218cf 100644--- a/src/commands/migrations/shared-content.ts+++ b/src/commands/migrations/shared-content.ts@@ -1,5 +1,5 @@-import { createEngine } from '../../core/engine-factory.ts';-import { isThinClient, loadConfig, toEngineConfig } from '../../core/config.ts';+import { isThinClient, loadConfig } from '../../core/config.ts';+import { connectMigrationEngine } from './run-engine.ts';import { runSharedSkillsMigration, type SharedMigrationReport } from '../../core/shared-skills/migration.ts';import type { Migration } from './types.ts';import type { OrchestratorOpts } from './types.ts';@@ -23,9 +23,8 @@ export async function inspectSharedContentMigration(dryRun: boolean, exportOptioversion: 1, brain_id: null, dry_run: dryRun, status: 'action_required', sources: [], permission_changes: [],pending_actions: ['Run content migration on the host brain, then reconnect with an upgraded shared-skills adapter. No client-side host repository was created.'],};- const engine = await createEngine(toEngineConfig(config));+ const { engine, close } = await connectMigrationEngine(config);try {- await engine.connect(toEngineConfig(config));const ctx = { engine, config, sourceId: exportOptions?.sourceId ?? 'default', remote: false, dryRun,logger: { info: console.error, warn: console.error, error: console.error } };const exported = exportOptions ? await exportDatabaseContent(ctx, { ...exportOptions, dryRun }) : undefined;@@ -36,7 +35,7 @@ export async function inspectSharedContentMigration(dryRun: boolean, exportOptioreport.pending_actions.push(...exported.pending_actions);}return report;- } finally { await engine.disconnect(); }+ } finally { await close(); }}export const sharedContentMigration: Migration = {@@ -48,6 +47,7 @@ export const sharedContentMigration: Migration = {preview: options => inspectSharedContentMigration(true, options.dbOnlyExport, options.acceptReviewedInventory),reconcile: true,optOut: { key: SHARED_CONTENT_MIGRATION_OPT_OUT_KEY },+ sharesRunEngine: true,orchestrator: async options => {try {const report = await inspectSharedContentMigration(options.dryRun, options.dbOnlyExport, options.acceptReviewedInventory);diff --git a/src/commands/migrations/types.ts b/src/commands/migrations/types.tsindex bcf538a1cf..9965989a42 100644--- a/src/commands/migrations/types.ts+++ b/src/commands/migrations/types.ts@@ -94,4 +94,11 @@ export interface Migration {* migration is proven by test/migrations-fresh-install-audit.serial.test.ts.*/fresh_install_noop?: true;+ /**+ * The orchestrator opens the brain only through `connectMigrationEngine`+ * (`./run-engine.ts`) and calls `releaseRunEngine` before any `gbrain` child+ * that needs the brain, so consecutive flagged migrations of one run share+ * one PGLite open.+ */+ sharesRunEngine?: true;}diff --git a/src/commands/migrations/v0_11_0.ts b/src/commands/migrations/v0_11_0.tsindex fef3bbeb73..63334f0b9e 100644--- a/src/commands/migrations/v0_11_0.ts+++ b/src/commands/migrations/v0_11_0.ts@@ -25,6 +25,7 @@ import { join, resolve, dirname } from 'path';import { execSync } from 'child_process';import type { Migration, OrchestratorOpts, OrchestratorResult, OrchestratorPhaseResult } from './types.ts';import { gbrainChildCommand } from './in-process.ts';+import { releaseRunEngine } from './run-engine.ts';import { cliChildStdio } from '../../core/cli-force-exit.ts';import { savePreferences, loadPreferences } from '../../core/preferences.ts';import { loadConfig, configPath, gbrainPath } from '../../core/config.ts';@@ -437,6 +438,7 @@ async function orchestrator(opts: OrchestratorOpts): Promise<OrchestratorResult>return { version: '0.11.0', status: 'failed', phases };}+ await releaseRunEngine();const b = phaseBSmoke(opts);phases.push(b);if (b.status === 'failed') {@@ -502,6 +504,7 @@ export const v0_11_0: Migration = {'user might ask about later.',},orchestrator,+ sharesRunEngine: true,effects: ['persistent_install'],};diff --git a/src/commands/migrations/v0_14_0.ts b/src/commands/migrations/v0_14_0.tsindex cc5135222c..3428cf9759 100644--- a/src/commands/migrations/v0_14_0.ts+++ b/src/commands/migrations/v0_14_0.ts@@ -26,9 +26,8 @@ import { existsSync, readFileSync, mkdirSync, appendFileSync } from 'fs';import { join } from 'path';import type { Migration, OrchestratorOpts, OrchestratorResult, OrchestratorPhaseResult } from './types.ts';-import { loadConfig, toEngineConfig, gbrainPath } from '../../core/config.ts';-import { createEngine } from '../../core/engine-factory.ts';-import type { BrainEngine } from '../../core/engine.ts';+import { loadConfig, gbrainPath } from '../../core/config.ts';+import { connectMigrationEngine, type MigrationEngine } from './run-engine.ts';// gbrainPath() honors GBRAIN_HOME at call time (not module-load) and routes// through the centralized config dir, so the prior resolveHome()/HOME-env@@ -40,7 +39,7 @@ function pendingHostWorkPath(): string { return join(pendingHostWorkDir(), 'pend// Phase A — schema: bump minion_jobs.max_stalled default 1 → 3// ----------------------------------------------------------------------------async function phaseASchema(opts: OrchestratorOpts): Promise<{ result: OrchestratorPhaseResult; engine: BrainEngine | null }> {+async function phaseASchema(opts: OrchestratorOpts): Promise<{ result: OrchestratorPhaseResult; engine: MigrationEngine | null }> {if (opts.dryRun) {return { result: { name: 'schema', status: 'skipped', detail: 'dry-run' }, engine: null };}@@ -52,22 +51,22 @@ async function phaseASchema(opts: OrchestratorOpts): Promise<{ result: Orchestraengine: null,};}- const engine = await createEngine(toEngineConfig(config));- await engine.connect(toEngineConfig(config));+ const opened = await connectMigrationEngine(config);+ const { engine } = opened;// Only a default below 3 is raised: schema migration v15 later set 5,// which a fresh brain already has, and lowering it would undo that fix.const [column] = await engine.executeRaw<{ column_default: string | null }>(`SELECT column_default FROM information_schema.columnsWHERE table_schema = current_schema() AND table_name = 'minion_jobs' AND column_name = 'max_stalled'`);if (!column) {- return { result: { name: 'schema', status: 'skipped', detail: 'minion_jobs not yet created (fresh install)' }, engine };+ return { result: { name: 'schema', status: 'skipped', detail: 'minion_jobs not yet created (fresh install)' }, engine: opened };}const current = parseInt(column.column_default ?? '', 10);if (current >= 3) {- return { result: { name: 'schema', status: 'skipped', detail: `max_stalled default already ${current}` }, engine };+ return { result: { name: 'schema', status: 'skipped', detail: `max_stalled default already ${current}` }, engine: opened };}await engine.executeRaw('ALTER TABLE minion_jobs ALTER COLUMN max_stalled SET DEFAULT 3');- return { result: { name: 'schema', status: 'complete' }, engine };+ return { result: { name: 'schema', status: 'complete' }, engine: opened };} catch (e) {return {result: { name: 'schema', status: 'failed', detail: e instanceof Error ? e.message : String(e) },@@ -141,7 +140,7 @@ async function orchestrator(opts: OrchestratorOpts): Promise<OrchestratorResult>phases.push(hostRes);} finally {if (engine) {- try { await engine.disconnect(); } catch { /* best-effort */ }+ try { await engine.close(); } catch { /* best-effort */ }}}@@ -172,4 +171,5 @@ export const v0_14_0: Migration = {'Host-specific skill doc: skills/migrations/v0.14.0.md.',},orchestrator,+ sharesRunEngine: true,};diff --git a/src/commands/migrations/v0_22_4.ts b/src/commands/migrations/v0_22_4.tsindex e2d963d3fc..4291712dd4 100644--- a/src/commands/migrations/v0_22_4.ts+++ b/src/commands/migrations/v0_22_4.ts@@ -25,8 +25,8 @@ import { existsSync, mkdirSync, writeFileSync, readFileSync, appendFileSync } frimport { join } from 'path';import type { Migration, OrchestratorOpts, OrchestratorResult, OrchestratorPhaseResult } from './types.ts';import type { BrainEngine } from '../../core/engine.ts';-import { loadConfig, toEngineConfig, gbrainPath } from '../../core/config.ts';-import { createEngine } from '../../core/engine-factory.ts';+import { loadConfig, gbrainPath } from '../../core/config.ts';+import { connectMigrationEngine } from './run-engine.ts';import { scanBrainSources, type AuditReport } from '../../core/brain-writer.ts';/** Test-only injection point for the audit phase. When set, phaseBAudit uses@@ -78,13 +78,11 @@ async function phaseBAudit(opts: OrchestratorOpts): Promise<{ phase: Orchestratoreport: null,};}- const engineConfig = toEngineConfig(config);- const engine = await createEngine(engineConfig);- await engine.connect(engineConfig);+ const { engine, close } = await connectMigrationEngine(config);try {report = await scanBrainSources(engine);} finally {- await engine.disconnect();+ await close();}}if (report.per_source.length === 0) {@@ -220,6 +218,7 @@ export const v0_22_4: Migration = {},},orchestrator,+ sharesRunEngine: true,};/** Exported for unit tests. */diff --git a/src/commands/migrations/v0_28_0.ts b/src/commands/migrations/v0_28_0.tsindex 4c5d129ae4..0797534e03 100644--- a/src/commands/migrations/v0_28_0.ts+++ b/src/commands/migrations/v0_28_0.ts@@ -31,8 +31,8 @@ import type {Migration, OrchestratorOpts, OrchestratorResult, OrchestratorPhaseResult,} from './types.ts';import type { BrainEngine } from '../../core/engine.ts';-import { loadConfig, toEngineConfig, gbrainPath } from '../../core/config.ts';-import { createEngine } from '../../core/engine-factory.ts';+import { loadConfig, gbrainPath } from '../../core/config.ts';+import { connectMigrationEngine } from './run-engine.ts';let testEngineOverride: BrainEngine | null = null;export function __setTestEngineOverride(engine: BrainEngine | null): void {@@ -190,18 +190,13 @@ async function orchestrator(opts: OrchestratorOpts): Promise<OrchestratorResult>// Acquire engine for phases that need it. Skip cleanly when none configured.let engine: BrainEngine | null = null;- let ownsEngine = false;+ let close: (() => Promise<void>) | null = null;try {if (testEngineOverride) {engine = testEngineOverride;} else {const config = loadConfig();- if (config) {- const engineConfig = toEngineConfig(config);- engine = await createEngine(engineConfig);- await engine.connect(engineConfig);- ownsEngine = true;- }+ if (config) ({ engine, close } = await connectMigrationEngine(config));}phases.push(await phaseASchema(engine, opts));@@ -212,8 +207,8 @@ async function orchestrator(opts: OrchestratorOpts): Promise<OrchestratorResult>phases.push(await phaseBBackfill(engine, opts));phases.push(phaseCRechunkTodo(opts));} finally {- if (ownsEngine && engine) {- try { await engine.disconnect(); } catch { /* ignore */ }+ if (close) {+ try { await close(); } catch { /* ignore */ }}}@@ -239,6 +234,7 @@ export const v0_28_0: Migration = {'chunks where the per-token allow-list cannot reach) catches up on legacy pages.',},orchestrator,+ sharesRunEngine: true,};/** Exported for unit tests. */diff --git a/test/fixtures/goldens/README.md b/test/fixtures/goldens/README.mdindex 645e9efa8a..8b9aea529e 100644--- a/test/fixtures/goldens/README.md+++ b/test/fixtures/goldens/README.md@@ -122,3 +122,13 @@ reproduce byte for byte. Each file is written by `test/helpers/golden.ts` asstores `fence_integrity.details.trend[].by_day[].day` as `<sync-day>` only after`stampSyncDay` checks it equals the day the fixture's sync stamped (one of the daysread around the sync). Regenerating writes the marker again.++## Setup migration ledger++- `setup/fresh-setup-migration-ledger.json` (`test/setup.test.ts`, `setup-migration-ledger-v1`):+ the files a fresh `gbrain setup claude-code` leaves in `migrations/` (`completed.jsonl`,+ `pending-host-work.jsonl`, `v0.22.4-audit.json`), line by line, with timestamps, the temp+ home, the brain id and the release stamp scrubbed. Captured on master `95b1ad61c`+ (v0.60.220.0) before the setup migration child shared one PGLite engine across+ migrations, and captured twice to prove the normalizer stable. A new setup migration or+ a changed phase detail regenerates it.diff --git a/test/fixtures/goldens/setup/fresh-setup-migration-ledger.json b/test/fixtures/goldens/setup/fresh-setup-migration-ledger.jsonnew file mode 100644index 0000000000..ba20b6f5bb--- /dev/null+++ b/test/fixtures/goldens/setup/fresh-setup-migration-ledger.json@@ -0,0 +1,62 @@+{+ "golden": {+ "completed.jsonl": [+ "{\"ts\":\"<ts>\",\"version\":\"0.12.0\",\"status\":\"complete\",\"fresh_install\":true,\"installed_version\":\"<version>\",\"phases\":[{\"name\":\"fresh_install\",\"status\":\"skipped\",\"detail\":\"No-op on a brain gbrain init created at v<version>: schema current, nothing to backfill or install.\"}]}",+ "{\"ts\":\"<ts>\",\"version\":\"0.12.2\",\"status\":\"complete\",\"fresh_install\":true,\"installed_version\":\"<version>\",\"phases\":[{\"name\":\"fresh_install\",\"status\":\"skipped\",\"detail\":\"No-op on a brain gbrain init created at v<version>: schema current, nothing to backfill or install.\"}]}",+ "{\"ts\":\"<ts>\",\"version\":\"0.13.0\",\"status\":\"complete\",\"fresh_install\":true,\"installed_version\":\"<version>\",\"phases\":[{\"name\":\"fresh_install\",\"status\":\"skipped\",\"detail\":\"No-op on a brain gbrain init created at v<version>: schema current, nothing to backfill or install.\"}]}",+ "{\"ts\":\"<ts>\",\"version\":\"0.13.1\",\"status\":\"complete\",\"fresh_install\":true,\"installed_version\":\"<version>\",\"phases\":[{\"name\":\"fresh_install\",\"status\":\"skipped\",\"detail\":\"No-op on a brain gbrain init created at v<version>: schema current, nothing to backfill or install.\"}]}",+ "{\"ts\":\"<ts>\",\"version\":\"0.16.0\",\"status\":\"complete\",\"fresh_install\":true,\"installed_version\":\"<version>\",\"phases\":[{\"name\":\"fresh_install\",\"status\":\"skipped\",\"detail\":\"No-op on a brain gbrain init created at v<version>: schema current, nothing to backfill or install.\"}]}",+ "{\"ts\":\"<ts>\",\"version\":\"0.18.0\",\"status\":\"complete\",\"fresh_install\":true,\"installed_version\":\"<version>\",\"phases\":[{\"name\":\"fresh_install\",\"status\":\"skipped\",\"detail\":\"No-op on a brain gbrain init created at v<version>: schema current, nothing to backfill or install.\"}]}",+ "{\"ts\":\"<ts>\",\"version\":\"0.18.1\",\"status\":\"complete\",\"fresh_install\":true,\"installed_version\":\"<version>\",\"phases\":[{\"name\":\"fresh_install\",\"status\":\"skipped\",\"detail\":\"No-op on a brain gbrain init created at v<version>: schema current, nothing to backfill or install.\"}]}",+ "{\"ts\":\"<ts>\",\"version\":\"0.21.0\",\"status\":\"complete\",\"fresh_install\":true,\"installed_version\":\"<version>\",\"phases\":[{\"name\":\"fresh_install\",\"status\":\"skipped\",\"detail\":\"No-op on a brain gbrain init created at v<version>: schema current, nothing to backfill or install.\"}]}",+ "{\"ts\":\"<ts>\",\"version\":\"0.29.1\",\"status\":\"complete\",\"fresh_install\":true,\"installed_version\":\"<version>\",\"phases\":[{\"name\":\"fresh_install\",\"status\":\"skipped\",\"detail\":\"No-op on a brain gbrain init created at v<version>: schema current, nothing to backfill or install.\"}]}",+ "{\"ts\":\"<ts>\",\"version\":\"0.31.0\",\"status\":\"complete\",\"fresh_install\":true,\"installed_version\":\"<version>\",\"phases\":[{\"name\":\"fresh_install\",\"status\":\"skipped\",\"detail\":\"No-op on a brain gbrain init created at v<version>: schema current, nothing to backfill or install.\"}]}",+ "{\"ts\":\"<ts>\",\"version\":\"0.32.2\",\"status\":\"complete\",\"fresh_install\":true,\"installed_version\":\"<version>\",\"phases\":[{\"name\":\"fresh_install\",\"status\":\"skipped\",\"detail\":\"No-op on a brain gbrain init created at v<version>: schema current, nothing to backfill or install.\"}]}",+ "{\"ts\":\"<ts>\",\"version\":\"0.43.0\",\"status\":\"complete\",\"fresh_install\":true,\"installed_version\":\"<version>\",\"phases\":[{\"name\":\"fresh_install\",\"status\":\"skipped\",\"detail\":\"No-op on a brain gbrain init created at v<version>: schema current, nothing to backfill or install.\"}]}",+ "{\"ts\":\"<ts>\",\"version\":\"0.46.3\",\"status\":\"complete\",\"fresh_install\":true,\"installed_version\":\"<version>\",\"phases\":[{\"name\":\"fresh_install\",\"status\":\"skipped\",\"detail\":\"No-op on a brain gbrain init created at v<version>: schema current, nothing to backfill or install.\"}]}",+ "{\"ts\":\"<ts>\",\"version\":\"0.60.31\",\"status\":\"complete\",\"fresh_install\":true,\"installed_version\":\"<version>\",\"phases\":[{\"name\":\"fresh_install\",\"status\":\"skipped\",\"detail\":\"No-op on a brain gbrain init created at v<version>: schema current, nothing to backfill or install.\"}]}",+ "{\"ts\":\"<ts>\",\"version\":\"0.11.0\",\"status\":\"complete\",\"phases\":[{\"name\":\"schema\",\"status\":\"complete\"},{\"name\":\"smoke\",\"status\":\"complete\"},{\"name\":\"mode\",\"status\":\"complete\",\"detail\":\"mode=pain_triggered (default)\"},{\"name\":\"prefs\",\"status\":\"complete\"},{\"name\":\"host\",\"status\":\"complete\",\"detail\":\"rewrote 0 entries; 0 host-work TODOs emitted\"},{\"name\":\"install\",\"status\":\"skipped\",\"detail\":\"--no-autopilot-install\"},{\"name\":\"record\",\"status\":\"complete\",\"detail\":\"status=complete (ledger write in runner)\"}],\"files_rewritten\":0,\"autopilot_installed\":false}",+ "{\"ts\":\"<ts>\",\"version\":\"0.14.0\",\"status\":\"complete\",\"phases\":[{\"name\":\"schema\",\"status\":\"skipped\",\"detail\":\"max_stalled default already 5\"},{\"name\":\"host-work\",\"status\":\"complete\",\"detail\":\"<home>/.gbrain/migrations/pending-host-work.jsonl\"}],\"apply_migrations_pending\":true}",+ "{\"ts\":\"<ts>\",\"version\":\"0.22.4\",\"status\":\"complete\",\"phases\":[{\"name\":\"schema\",\"status\":\"complete\",\"detail\":\"no schema changes in v0.22.4\"},{\"name\":\"audit\",\"status\":\"complete\",\"detail\":\"0 issue(s) across 1 source(s); report at <home>/.gbrain/migrations/v0.22.4-audit.json\"},{\"name\":\"emit-todo\",\"status\":\"complete\",\"detail\":\"no issues; nothing to queue\"}]}",+ "{\"ts\":\"<ts>\",\"version\":\"0.28.0\",\"status\":\"complete\",\"phases\":[{\"name\":\"schema\",\"status\":\"complete\",\"detail\":\"schema v38 applied; takes + synthesis_evidence present\"},{\"name\":\"backfill\",\"status\":\"complete\",\"detail\":\"extract-takes scanned 0 pages; 0 had fenced takes; upserted 0 rows\"},{\"name\":\"rechunk-todo\",\"status\":\"complete\",\"detail\":\"queued re-chunk TODO at <home>/.gbrain/migrations/pending-host-work.jsonl (read skills/migrations/v0.28.0.md for the playbook)\"}]}",+ "{\"ts\":\"<ts>\",\"version\":\"0.53.0\",\"status\":\"complete\",\"phases\":[{\"name\":\"content-checkpoints\",\"status\":\"complete\",\"detail\":\"Mechanical inventory is durable; publication and enrollment are NOT complete. Per-source actions remain in shared_skills.migration.v1.\",\"argv\":[\"gbrain\",\"apply-migrations\",\"--migration\",\"0.53.0\",\"--dry-run\",\"--json\"]}],\"apply_migrations_pending\":true}",+ ""+ ],+ "pending-host-work.jsonl": [+ "{\"migration\":\"0.14.0\",\"ts\":\"<ts>\",\"skill\":\"skills/migrations/v0.14.0.md\",\"reason\":\"shell-jobs adoption + autopilot cooperative wiring\"}",+ "{\"migration\":\"0.28.0\",\"ts\":\"<ts>\",\"skill\":\"skills/migrations/v0.28.0.md\",\"reason\":\"Pages with pre-v0.28 chunks still contain fenced takes content. Re-chunk so the new chunker strip rule is applied (Codex P0 #3 fix).\",\"command\":\"gbrain reindex --markdown\",\"_key\":\"rechunk-pages-with-takes\"}",+ ""+ ],+ "v0.22.4-audit.json": [+ "{",+ " \"ok\": true,",+ " \"total\": 0,",+ " \"errors_by_code\": {},",+ " \"recoverability_by_code\": {},",+ " \"per_source\": [",+ " {",+ " \"source_id\": \"default\",",+ " \"source_path\": \"<home>/.gbrain/content/<uuid>/default\",",+ " \"total\": 0,",+ " \"errors_by_code\": {},",+ " \"recoverability_by_code\": {},",+ " \"repairable\": {",+ " \"files\": 0,",+ " \"by_code\": {},",+ " \"sample\": []",+ " },",+ " \"sample\": [],",+ " \"ignoredMissingOpen\": 0,",+ " \"status\": \"scanned\",",+ " \"files_scanned\": 3,",+ " \"db_page_count\": null",+ " }",+ " ],",+ " \"scanned_at\": \"<ts>\",",+ " \"partial\": false,",+ " \"aborted_at_source\": null",+ "}"+ ]+ },+ "normalizer": "setup-migration-ledger-v1"+}diff --git a/test/migrations-run-engine.test.ts b/test/migrations-run-engine.test.tsnew file mode 100644index 0000000000..b6f323efda--- /dev/null+++ b/test/migrations-run-engine.test.ts@@ -0,0 +1,83 @@+/**+ * src/commands/migrations/run-engine.ts: consecutive migrations of one+ * apply-migrations run share one PGLite open, and the datastore lock is never+ * held when anything else needs it.+ *+ * Authoring gate:+ * 1. Protects: sharing only while enabled; release before a non-sharing step,+ * before a `gbrain` child, and at the end of the session; every open outside+ * a session is a new engine closed by its caller.+ * 2. Fails on: a shared engine left open past the session or a disabled step+ * (a second process could not open the brain), or a shared open that starts+ * a second embedded Postgres instead of reusing the first.+ * 3. The setup ledger golden in test/setup.test.ts pins that the shared runs+ * write the same records as before.+ * 4. No seams: real PGLite datastores in temp directories.+ */+import { afterAll, describe, expect, test } from 'bun:test';+import { mkdtempSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import type { GBrainConfig } from '../src/core/config.ts';+import { peekLock } from '../src/core/pglite-lock.ts';+import { connectMigrationEngine, releaseRunEngine, setRunEngineSharing, withRunEngineSession } from '../src/commands/migrations/run-engine.ts';++const roots: string[] = [];+afterAll(() => { for (const r of roots) rmSync(r, { recursive: true, force: true }); });++function brain(): GBrainConfig {+ const root = mkdtempSync(join(tmpdir(), 'gbrain-run-engine-'));+ roots.push(root);+ return { engine: 'pglite', database_path: join(root, 'brain.pglite') } as GBrainConfig;+}++/** True when nothing holds the datastore lock, so another process could open the brain now. */+const lockFree = (config: GBrainConfig): boolean => !peekLock(config.database_path).held;++describe('migration run engine', () => {+ test('outside a session every open is its own engine and close releases it', async () => {+ const config = brain();+ const first = await connectMigrationEngine(config);+ await first.close();+ const second = await connectMigrationEngine(config);+ expect(second.engine).not.toBe(first.engine);+ await second.close();+ });++ test('with sharing enabled the run reuses one engine; release, disabling and the session end all close it', async () => {+ const config = brain();+ await withRunEngineSession(async () => {+ await setRunEngineSharing(true);+ const a = await connectMigrationEngine(config);+ await a.close();+ const b = await connectMigrationEngine(config);+ expect(b.engine).toBe(a.engine);+ expect(await b.engine.executeRaw<{ one: number }>('SELECT 1 AS one')).toEqual([{ one: 1 }]);+ expect(lockFree(config)).toBe(false);++ await releaseRunEngine();+ await setRunEngineSharing(false);+ expect(lockFree(config)).toBe(true);++ await setRunEngineSharing(true);+ const c = await connectMigrationEngine(config);+ expect(c.engine).not.toBe(a.engine);+ await setRunEngineSharing(false);+ expect(lockFree(config)).toBe(true);++ await setRunEngineSharing(true);+ await connectMigrationEngine(config);+ });+ expect(lockFree(config)).toBe(true);+ });++ test('a session that throws still closes the shared engine', async () => {+ const config = brain();+ await expect(withRunEngineSession(async () => {+ await setRunEngineSharing(true);+ await connectMigrationEngine(config);+ throw new Error('orchestrator failed');+ })).rejects.toThrow('orchestrator failed');+ expect(lockFree(config)).toBe(true);+ });+});diff --git a/test/setup.test.ts b/test/setup.test.tsindex 2c6712cc2d..c0acaa41f7 100644--- a/test/setup.test.ts+++ b/test/setup.test.ts@@ -27,6 +27,8 @@ import { hookEntryHash, removeClaudeHooksAt, writeClaudeHooksAt } from '../src/cimport { GBRAIN_HOOK_MARKER_VALUE } from '../src/core/bootstrap/host-specs.ts';import { codexHookTrustHash, codexTrustHash, removeCodexHooks, writeCodexHooks } from '../src/core/bootstrap/codex-hooks.ts';import { appendCodexTomlTable, removeCodexTomlTable } from '../src/core/bootstrap/codex-toml.ts';+import { defineNormalizer, expectGolden, scrubTimestamps } from './helpers/golden.ts';+import { VERSION } from '../src/version.ts';const CLI = resolve(import.meta.dir, '..', 'src', 'cli.ts');const roots: string[] = [];@@ -253,6 +255,12 @@ describe('gbrain setup claude-code: install lifecycle', () => {});describe('gbrain setup: setup migrations on the brain it creates (Cat 41 run 4)', () => {+ /** The migration records a fresh setup leaves, byte for byte apart from timestamps, the temp home, the brain id and the release stamp (captured on master). */+ const ledgerFiles = ['completed.jsonl', 'pending-host-work.jsonl', 'v0.22.4-audit.json'];+ const UUID = /[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/g;+ const migrationLedger = defineNormalizer<{ home: string; files: Record<string, string> }>('setup-migration-ledger-v1', ({ home, files }) =>+ Object.fromEntries(Object.entries(files).map(([name, text]) =>+ [name, scrubTimestamps(text.split(home).join('<home>').split(VERSION).join('<version>')).replace(UUID, '<uuid>').split('\n')])));const pendingSetupMigrations = async (b: Box): Promise<string[]> => {const r = await runCli(['apply-migrations', '--list', '--json'], { env: { ...CLEAN, HOME: b.home, GBRAIN_HOME: b.gbrainHome } });return JSON.parse(r.stdout).plan.pending_fresh_install;@@ -268,6 +276,8 @@ describe('gbrain setup: setup migrations on the brain it creates (Cat 41 run 4)'expect(await pendingSetupMigrations(b)).toEqual([]);const doctor = await runCli(['doctor', '--json'], { env: { ...CLEAN, HOME: b.home, GBRAIN_HOME: b.gbrainHome } });expect(JSON.parse(doctor.stdout).checks.map((c: any) => c.name)).not.toContain('minions_migration');+ const dir = join(b.gbrainHome, '.gbrain', 'migrations');+ expectGolden('setup/fresh-setup-migration-ledger', { home: b.home, files: Object.fromEntries(ledgerFiles.map(name => [name, readFileSync(join(dir, name), 'utf8')])) }, migrationLedger);});test('an existing brain is left as it is: setup runs no migrations and prints no migrations line', async () => {