Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

graduation(G3): merge G1 follow-ups (drop RegistryCode cast, align unclassified reasons), key-files entries, serve hand-off on real timer, goldens, pglite_scale test

garrytan4a97f28443b6
diff --git a/docs/architecture/KEY_FILES.md b/docs/architecture/KEY_FILES.md
index 2efc5ebe76..9f47ae86b9 100644
--- a/docs/architecture/KEY_FILES.md
+++ b/docs/architecture/KEY_FILES.md
@@ -44,6 +44,7 @@ boundary and add its link here rather than raising the cap.
| [Core Minions (2/2)](key-files/core-minions-2.md) | `src/core/minions/run-child.ts` through `src/core/minions/worker.ts` |
| [Core Persistence](key-files/core-persistence.md) | `src/core/persistence/` write journal, coordinator, effects, canonical projections and managed sync |
| [Core Persistence (continued)](key-files/core-persistence-continued.md) | `src/core/persistence/connector-*.ts`, `src/core/connectors/item-holds*.ts`, checkpoint validation, no-op kernel and accepted-pending receipts |
+| [Core Persistence (engine graduation)](key-files/core-persistence-graduation.md) | `engine-graduation*.ts`, `graduation-*.ts`, `src/commands/migrate-graduation.ts`, the graduation doctor finding |
| [Core Search (1/2)](key-files/core-search-1.md) | `src/core/search/` through `src/core/search/rerank.ts` |
| [Core Search (2/2)](key-files/core-search-2.md) | `src/core/search/return-policy.ts` through `src/core/search/vector-pool.ts` |
| [Core Services (1/3)](key-files/core-services-1.md) | `src/core/advisor/{types,run,render,recommended-set,history,apply,collect-*}.ts` through `src/core/context/ipc-path.ts` |
diff --git a/docs/architecture/key-files/core-persistence-graduation.md b/docs/architecture/key-files/core-persistence-graduation.md
new file mode 100644
index 0000000000..4862d97f8a
--- /dev/null
+++ b/docs/architecture/key-files/core-persistence-graduation.md
@@ -0,0 +1,15 @@
+# Key files: Core Persistence (engine graduation)
+
+[Subsystem index](../KEY_FILES.md) · [Core Persistence](core-persistence.md). Read only the entries relevant to your change.
+Current behavior and load-bearing invariants; history belongs in Git and CHANGELOG.
+Verified engine graduation, PGLite to Postgres ([operator guide](../../guides/move-to-postgres.md)).
+
+- `src/core/persistence/engine-graduation.types.ts` — the shared contract every graduation module codes against: manifest, source-row and target-row states with their allowed transitions (`assertTransition` throws on an illegal one), inventory classes and loss kinds, target identity (host, port, database, user; never the password), batch and table receipts, plan, verify result, receipt, intent marker, tombstone, blockers, `GRADUATION_ERROR_CODES`, and the CLI-to-orchestrator surface (`GraduationCommandOptions`, `GraduationStatusDoc`, `GraduationPathState`, `GraduationProgressSink`, `GraduationRollbackResult`). Changes are additive.
+- `src/core/persistence/graduation-inventory.ts` — `GRADUATION_INVENTORY`: every public relation on either engine mapped to exactly one class (carry, rebind, rebuild, discard, schema-owned) with an engine-presence flag, a loss kind and the permitted column transforms. `assertRelationSet` refuses `graduation_unclassified_table` (reason `newer_schema` when the database is ahead of this binary, `missing_inventory_row` otherwise); `copyOrder` and `fkClosure` derive the FK topological order from `pg_constraint` at run time (self-FKs allowed, cycles throw). Test: `test/graduation-inventory.test.ts` fails when a migration adds a relation without a row.
+- `src/core/persistence/graduation-digest.ts` — canonical engine-independent digests: every value read as text under fixed session settings (`TimeZone=UTC`, `DateStyle=ISO`, `extra_float_digits=3`, hex bytea), primary-key keyset batches ordered `COLLATE "C"`, sha256 computed client-side per batch and rolled into a per-table root independent of batch size; identifiers are always quoted from the catalog. Test: `test/graduation-digest.test.ts`.
+- `src/core/persistence/graduation-verify.ts` — `verifyGraduation`, the cutover gate: relation set, column contract, counts and digests (source side transformed by the inventory's transforms), sequence positions, an anti-join per FK, trigger state (`gbrain_graduation_fence` present until cutover), derived side tables, the target doctor, and `replayProbe` (resubmits a carried request through `admitWriteInTransaction` inside a rolled-back transaction; `not_available` with a reason when no caller input exists). Test: `test/graduation-verify.test.ts`.
+- `src/core/persistence/graduation-errors.ts` — one builder per graduation code (`sourceWriterHeldError` … `engineGraduatedError`) so the orchestrator, CLI, serve and doctor render each refusal one way: `why`, a filled `fix` with real argv (none only for `report`), a read-only verify (`gbrain migrate --status --json`, the `--plan` form, or doctor), `GRADUATION_DOCS` anchors, and the command helpers `planArgv`/`runArgv`/`resumeArgv`/`rollbackArgv`/`statusArgv`, which echo the user's `--to` spelling and name the URL only through `--url-env`. Test: `test/graduation-errors.test.ts` (table-driven over every code; each emitted argv names a real command with accepted flags and parses to its graduation mode).
+- `src/core/persistence/graduation-serve-guard.ts` — file reads only (marker, tombstone, config, manifest summary; never a lock attempt): `serveGraduationStartRefusal` (a serve launched while another live run owns the host brain exits 75 with `graduation_in_progress`, called from `connectCliOnlyEngine` in `src/cli.ts`), `graduationStatusReason` (a tombstoned path is status-only `engine_graduated`), `exitOnEngineIdentityChange` (status-only and degraded reconnect gates exit 75 for relaunch when the config names another engine, a tombstone appears or a run starts; a serve started with no config keeps recovering in place), `graduationHandoffRequested` (the resident stdio serve's 2 s marker poll in `installStdioLifecycle`), and `readGraduationManifestSummary` (the redacted view of the 0600 manifest). Test: `test/graduation-serve-guard.serial.test.ts` (includes a real `gbrain serve` child exiting 75 and `engine status --json`).
+- `src/core/persistence/engine-graduation.ts`, `src/core/persistence/graduation-custody.ts` — the orchestrator (`planGraduation`, `runGraduation`, `graduationStatus`, `resumeGraduation`, `rollbackGraduation`, `reconcileGraduation`) and custody (intent marker, tombstone, `inspectGraduationPath`, lock-retaining close, move-aside). Their entries follow the custody lane.
+- `src/commands/migrate-graduation.ts` — the `gbrain migrate` graduation CLI, routed before connect from `routeEngineFreeSubcommands` in `src/cli.ts` when `routesToGraduation` holds (run-scoped verbs and `--plan` always; a bare `--to postgres|supabase` on a durable PGLite config unless `migrate.graduation` is false or the host is Windows). Without `--yes --expect` it plans and returns the `confirmation_required` payload (effects egress and destructive, what moves and what stays, `plan_hash`, the `--plan` preview; no stdin prompt); `--plan`/`--dry-run` prints the plan; the run reports the receipt, retained copy, target doctor, `gbrain mcp expose` and the MCP restart note. Exit codes 0/1/2/3, 11 for a progressing drain stop (1 when a blocker needs a person), 75 for `graduation_in_progress`, 130 after SIGINT (stops at the next batch boundary). `--json` prints one document; progress goes to stderr per table and batch. Test: `test/migrate-graduation-cli.serial.test.ts`.
+- `src/commands/doctor/checks/engine-graduation.ts` — `graduationStateCheck`, emitted from the filesystem lane of `local-audits.ts`: `graduation_interrupted` fails when a manifest or marker is non-terminal with no live owner (fix `gbrain migrate --resume`, rollback named) or a stray brain sits at the old path, is `ok` while a live run owns it, exempts the run named by `GBRAIN_GRADUATION_RUN`, and emits nothing on a brain that never graduated. The retained `.graduated-*` copy is reported by `pglite_leftovers` (`src/core/pglite-leftovers-check.ts`), silent while a manifest is non-terminal.
diff --git a/docs/guides/error-codes.md b/docs/guides/error-codes.md
index 99d9e6b6cb..ef059adc21 100644
--- a/docs/guides/error-codes.md
+++ b/docs/guides/error-codes.md
@@ -969,7 +969,7 @@ More: [docs/guides/move-to-postgres.md#target-requirements](../../docs/guides/mo
|---|---|---|---|---|---|---|
| A database has a relation the graduation inventory does not classify, so moving it could lose data. | The server failed; this is not a caller mistake. | 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 |
-Reasons: `newer_target`, `missing_row`.
+Reasons: `newer_schema`, `missing_inventory_row`.
More: [docs/guides/move-to-postgres.md#inventory](../../docs/guides/move-to-postgres.md#inventory)
diff --git a/src/commands/serve.ts b/src/commands/serve.ts
index 3baf51128d..74028cf8dc 100644
--- a/src/commands/serve.ts
+++ b/src/commands/serve.ts
@@ -502,7 +502,7 @@ function installStdioLifecycle(
let shuttingDown = false;
let parentWatchdog: unknown = null;
let idleSweepTimer: unknown = null;
- let graduationHandoffTimer: unknown = null;
+ let graduationHandoffTimer: ReturnType<typeof setInterval> | null = null;
let shutdownExitCode = 0;
let activateIdleActivityTracking = (): void => {};
const beginShutdown = (reason: string): void => {
@@ -524,7 +524,7 @@ function installStdioLifecycle(
idleSweepTimer = null;
}
if (graduationHandoffTimer !== null) {
- deps.clearInterval(graduationHandoffTimer);
+ clearInterval(graduationHandoffTimer);
graduationHandoffTimer = null;
}
@@ -582,9 +582,10 @@ function installStdioLifecycle(
// Engine graduation hand-off (§13): a live run's intent marker asks the PGLite
// serve that holds the brain to finish, release the lock and exit 75 so the
- // run can take the brain; a relaunched serve then exits the same way.
+ // run can take the brain; a relaunched serve then exits the same way. A real
+ // unref'd timer (a stat per tick), separate from the injectable lifecycle timers.
if (engine.kind === 'pglite') {
- graduationHandoffTimer = deps.setInterval(() => {
+ graduationHandoffTimer = setInterval(() => {
if (shuttingDown || isEngineDegradedForServe(engine)) return;
const request = graduationHandoffRequested();
if (!request) return;
@@ -592,7 +593,7 @@ function installStdioLifecycle(
shutdownExitCode = writeServeGraduationEnvelope(request, (s) => deps.log(s.trimEnd()));
drainThenShutdown('graduation-handoff');
}, GRADUATION_HANDOFF_POLL_MS);
- (graduationHandoffTimer as { unref?: () => void } | null)?.unref?.();
+ graduationHandoffTimer.unref?.();
}
// Signal-based termination. SIGTERM: daemon ask. SIGINT: user Ctrl-C.
diff --git a/src/core/error-registry.ts b/src/core/error-registry.ts
index 9c8ac0e2b0..9555eecf96 100644
--- a/src/core/error-registry.ts
+++ b/src/core/error-registry.ts
@@ -154,7 +154,7 @@ export const CODES = {
graduation_target_ddl_unreachable: { class: 'unavailable', summary: "The target's direct (schema) connection is unreachable or names a different database than its main URL.", docs: 'docs/guides/move-to-postgres.md#ddl-connection' },
graduation_target_not_empty: { class: 'caller', summary: "The target database already holds data that is not this move's.", docs: 'docs/guides/move-to-postgres.md#target-not-empty' },
graduation_target_unsupported: { class: 'caller', summary: "The target database is missing a prerequisite (server version, vector extension with halfvec, CREATE privilege or a matching column).", docs: 'docs/guides/move-to-postgres.md#target-requirements', reasons: ['server_version', 'vector', 'halfvec', 'create_privilege', 'column', 'env_override'] },
- graduation_unclassified_table: { class: 'server', summary: "A database has a relation the graduation inventory does not classify, so moving it could lose data.", docs: 'docs/guides/move-to-postgres.md#inventory', reasons: ['newer_target', 'missing_row'] },
+ graduation_unclassified_table: { class: 'server', summary: "A database has a relation the graduation inventory does not classify, so moving it could lose data.", docs: 'docs/guides/move-to-postgres.md#inventory', reasons: ['newer_schema', 'missing_inventory_row'] },
graduation_unsupported_platform: { class: 'host_only', summary: "Moving a brain with write history to Postgres is not available on this platform yet.", docs: 'docs/guides/move-to-postgres.md#platforms' },
graduation_verify_failed: { class: 'server', summary: "The moved copy did not verify against the source; the target stays fenced and the source stays authoritative.", docs: 'docs/guides/move-to-postgres.md#verify', reasons: ['count', 'digest', 'sequence', 'fk', 'trigger', 'relation_set', 'replay', 'doctor'] },
graph_incomplete: { class: 'server', summary: "Source relationship reconciliation is incomplete." },
diff --git a/src/core/persistence/graduation-errors.ts b/src/core/persistence/graduation-errors.ts
index 53e5ae59b0..d8c1cf2a37 100644
--- a/src/core/persistence/graduation-errors.ts
+++ b/src/core/persistence/graduation-errors.ts
@@ -92,14 +92,14 @@ export function sourceWriterHeldError(opts: { owner: LockOwner | null; pid?: num
}
/** `graduation_unclassified_table`: a relation the built-in inventory does not list. */
-export function unclassifiedTableError(opts: { relations: readonly string[]; side: 'source' | 'target'; cause: 'newer_target' | 'missing_row'; spelling?: GraduationCommandSpelling }): OperationError {
+export function unclassifiedTableError(opts: { relations: readonly string[]; side: 'source' | 'target'; cause: 'newer_schema' | 'missing_inventory_row'; spelling?: GraduationCommandSpelling }): OperationError {
const list = opts.relations.join(', ');
const docs = GRADUATION_DOCS.graduation_unclassified_table;
- if (opts.cause === 'newer_target') {
+ if (opts.cause === 'newer_schema') {
const why = `The ${opts.side} database has relations this gbrain does not know (${list}); it was created by a newer gbrain, and copying unknown tables could lose data.`;
return opError('graduation_unclassified_table', `The ${opts.side} has relations this gbrain version does not classify: ${list}.`,
'Ask the user to upgrade gbrain on this machine (fix), then preview the move again.',
- { why, reason: 'newer_target', docs,
+ { why, reason: 'newer_schema', docs,
fix: { argv: ['gbrain', 'upgrade'], consent: [], actor: 'user', requires_exclusive: false, docs, verify: planVerify(opts.spelling ?? {}),
why: `${why} Upgrading this binary gives it the newer inventory.`,
user_message: `The Postgres database was set up by a newer gbrain than this one. Can you upgrade gbrain here (gbrain upgrade)? Then I'll check the move again. ${NOTHING_CHANGED}` } });
@@ -107,7 +107,7 @@ export function unclassifiedTableError(opts: { relations: readonly string[]; sid
const why = `This gbrain's own migrations created relations its graduation inventory does not list (${list}). Moving without a classification for every table could drop data, so the move refuses; this is a gbrain bug.`;
return opError('graduation_unclassified_table', `The graduation inventory has no row for: ${list}.`,
'Report this to the gbrain maintainers with `gbrain doctor --json` output; nothing changed and the brain keeps working on PGLite.',
- { why, reason: 'missing_row', docs,
+ { why, reason: 'missing_inventory_row', docs,
fix: { consent: [], actor: 'agent', requires_exclusive: false, docs, verify: planVerify(opts.spelling ?? {}),
why, user_message: `gbrain found a table it does not know how to move (${list}), which is a gbrain bug. Your brain stays on PGLite and keeps working; I can report it to the maintainers.` } });
}
diff --git a/src/core/persistence/graduation-inventory.ts b/src/core/persistence/graduation-inventory.ts
index 8b25be1152..806a455d57 100644
--- a/src/core/persistence/graduation-inventory.ts
+++ b/src/core/persistence/graduation-inventory.ts
@@ -7,7 +7,6 @@
*/
import type { BrainEngine } from '../engine.ts';
import { opError } from '../ops/contract.ts';
-import type { RegistryCode } from '../error-registry.ts';
import { LATEST_VERSION } from '../migrate.ts';
import type { ColumnTransform, Inventory, InventoryClass, InventoryEntry, LossKind } from './engine-graduation.types.ts';
@@ -198,7 +197,7 @@ export async function assertRelationSet(engine: BrainEngine, kind: EngineKind, i
wrongKind.length ? `wrong kind: ${wrongKind.join(', ')}` : '',
].filter(Boolean).join('; ');
const verify = { argv: ['gbrain', 'migrate', '--to', 'postgres', '--plan', '--url-env', 'GBRAIN_TARGET_URL', '--json'] };
- throw opError('graduation_unclassified_table' as RegistryCode,
+ throw opError('graduation_unclassified_table',
`The ${kind} schema does not match this gbrain's graduation inventory (${parts}).`,
newer
? `The ${kind} brain is at schema v${version}, newer than this gbrain (v${LATEST_VERSION}). Ask the user to upgrade gbrain on this machine (gbrain upgrade), then plan the move again. --force never bypasses this.`
diff --git a/test/doctor-engine-fit.serial.test.ts b/test/doctor-engine-fit.serial.test.ts
index c551210ff8..f50eb80c93 100644
--- a/test/doctor-engine-fit.serial.test.ts
+++ b/test/doctor-engine-fit.serial.test.ts
@@ -13,6 +13,7 @@
* hermetic; rows are written through the real writeReceipt seam.
*/
+import { parseGraduationArgs, routesToGraduation } from '../src/commands/migrate-graduation.ts';
import { describe, test, expect, beforeEach, afterEach } from 'bun:test';
import { mkdirSync, mkdtempSync, rmSync } from 'node:fs';
import { tmpdir } from 'node:os';
@@ -120,15 +121,21 @@ describe('pgliteScaleCheck', () => {
expect(await pgliteScaleCheck(engine)).toBeNull();
});
- test('pglite at 1500 pages → warn mentioning migrate --to supabase', async () => {
+ test('pglite at 1500 pages → warn whose fix is the read-only graduation plan, naming mcp expose', async () => {
const engine = { kind: 'pglite', getStats: async () => ({ page_count: 1500 }) } as unknown as BrainEngine;
const check = await pgliteScaleCheck(engine);
expect(check).not.toBeNull();
expect(check!.name).toBe('pglite_scale');
expect(check!.status).toBe('warn');
expect(check!.message).toContain('1500');
- expect(check!.message).toContain('migrate --to supabase');
+ expect(check!.message).toContain('migrate --to postgres --plan');
+ expect(check!.message).toContain('gbrain mcp expose');
expect(check!.message).toContain(String(PGLITE_SCALE_PAGE_THRESHOLD));
+ const fix = check!.fix as { argv: string[]; consent: string[] };
+ expect(fix.argv).toEqual(['gbrain', 'migrate', '--to', 'postgres', '--plan', '--json']);
+ expect(fix.consent).toEqual([]);
+ expect(parseGraduationArgs(fix.argv.slice(2)).mode).toBe('plan');
+ expect(routesToGraduation(fix.argv.slice(2), { engine: 'pglite' }, 'linux')).toBe(true);
});
test('pglite at 10 pages → ok, comfortable below the threshold', async () => {
diff --git a/test/fixtures/goldens/cli/dispatch-phase.json b/test/fixtures/goldens/cli/dispatch-phase.json
index 384db9576e..e69877c3c1 100644
--- a/test/fixtures/goldens/cli/dispatch-phase.json
+++ b/test/fixtures/goldens/cli/dispatch-phase.json
@@ -1100,7 +1100,19 @@
"migrate": {
"hasSwitchCase": true,
"phase": "post-connect",
- "preConnectRules": [],
+ "preConnectRules": [
+ {
+ "condition": "command === 'migrate'",
+ "connectsEngine": false,
+ "refusesThinClient": false,
+ "routesThinClient": false,
+ "terminates": false,
+ "thinClientCheck": false,
+ "unconditionalFor": [
+ "migrate"
+ ]
+ }
+ ],
"thinClient": "refuse",
"thinClientRoutedSubcommands": []
},
@@ -1574,7 +1586,17 @@
"serve": {
"hasSwitchCase": true,
"phase": "post-connect",
- "preConnectRules": [],
+ "preConnectRules": [
+ {
+ "condition": "command === 'serve' && (dbMarkerBrainId() ?? 'host') === 'host'",
+ "connectsEngine": false,
+ "refusesThinClient": false,
+ "routesThinClient": false,
+ "terminates": false,
+ "thinClientCheck": false,
+ "unconditionalFor": []
+ }
+ ],
"thinClient": "refuse",
"thinClientRoutedSubcommands": []
},
diff --git a/test/fixtures/goldens/cli/literal-imports.json b/test/fixtures/goldens/cli/literal-imports.json
index 12ad2b1202..819a59c689 100644
--- a/test/fixtures/goldens/cli/literal-imports.json
+++ b/test/fixtures/goldens/cli/literal-imports.json
@@ -100,6 +100,7 @@
],
"migrate": [
"./commands/migrate-embeddings.ts",
+ "./commands/migrate-graduation.ts",
"./commands/migrate-engine.ts"
],
"models": [
diff --git a/test/fixtures/goldens/doctor/registry-build-checks.json b/test/fixtures/goldens/doctor/registry-build-checks.json
index ff1428fea1..68d85c26eb 100644
--- a/test/fixtures/goldens/doctor/registry-build-checks.json
+++ b/test/fixtures/goldens/doctor/registry-build-checks.json
@@ -189,6 +189,10 @@
"category": "ops",
"name": "pglite_leftovers"
},
+ {
+ "category": "ops",
+ "name": "graduation_interrupted"
+ },
{
"category": "meta",
"name": "default_source_local_path"
diff --git a/test/graduation-errors.test.ts b/test/graduation-errors.test.ts
index 4e80a63119..59aa4a8c0f 100644
--- a/test/graduation-errors.test.ts
+++ b/test/graduation-errors.test.ts
@@ -44,9 +44,9 @@ const ROWS: Row[] = [
{ code: 'graduation_source_writer_held', label: 'daemon, no serve owner', next: 'tell_user_to_run', exit: 1, mode: 'run',
build: () => sourceWriterHeldError({ owner: null, pid: 99, subcommand: 'autopilot', rerun: ['gbrain', 'migrate', '--to', 'supabase', '--url-env', 'GBRAIN_TARGET_URL'] }) },
{ code: 'graduation_unclassified_table', label: 'newer target', next: 'tell_user_to_run', exit: 1,
- build: () => unclassifiedTableError({ relations: ['future_table'], side: 'target', cause: 'newer_target' }) },
+ build: () => unclassifiedTableError({ relations: ['future_table'], side: 'target', cause: 'newer_schema' }) },
{ code: 'graduation_unclassified_table', label: 'missing inventory row', next: 'report', exit: 1,
- build: () => unclassifiedTableError({ relations: ['new_table'], side: 'source', cause: 'missing_row' }) },
+ build: () => unclassifiedTableError({ relations: ['new_table'], side: 'source', cause: 'missing_inventory_row' }) },
{ code: 'graduation_embedding_dimension_mismatch', label: 'existing target', next: 'ask_user', exit: 1, mode: 'plan',
build: () => embeddingDimensionMismatchError({ column: 'content_chunks.embedding', source: 'vector(1536)', target: 'vector(768)', host: 'db.acme-example.test' }) },
{ code: 'graduation_drain_timeout', label: 'blockers progressing', next: 'run', exit: 11, mode: 'resume',
diff --git a/test/graduation-serve-guard.serial.test.ts b/test/graduation-serve-guard.serial.test.ts
index 521383f50a..9385466b01 100644
--- a/test/graduation-serve-guard.serial.test.ts
+++ b/test/graduation-serve-guard.serial.test.ts
@@ -21,6 +21,7 @@ import {
import { probeStatus, statusPayload, initialStatusState } from '../src/mcp/status-mode.ts';
import { graduationStateCheck } from '../src/commands/doctor/checks/engine-graduation.ts';
import { assessPgliteLeftovers } from '../src/core/pglite-leftovers-check.ts';
+import { inspectLockHolder } from '../src/core/pglite-lock.ts';
const CLI = join(import.meta.dir, '..', 'src', 'cli.ts');
const target = { id: 'tid', host: 'db.acme-example.test', port: 5432, database: 'brain', user: 'alice' };
@@ -152,3 +153,23 @@ describe('doctor and engine status', () => {
expect(JSON.stringify(report)).not.toContain(':pw@');
}, 60_000);
});
+
+describe('resident serve hand-off', () => {
+ test('a stdio serve holding a real PGLite brain releases it and exits 75 when a live run writes its marker', async () => {
+ const env = { ...process.env, GBRAIN_HOME: home, GBRAIN_DATABASE_URL: '', DATABASE_URL: '', GBRAIN_NO_UPDATE_CHECK: '1', GBRAIN_SWEEP: '0' };
+ rmSync(dataDir, { recursive: true, force: true });
+ rmSync(join(home, '.gbrain', 'config.json'));
+ const init = Bun.spawnSync(['bun', CLI, 'init', '--pglite', '--no-embedding', '--path', dataDir, '--json'], { env, stdout: 'pipe', stderr: 'pipe' });
+ expect(init.exitCode, init.stderr.toString()).toBe(0);
+ const serve = Bun.spawn(['bun', CLI, 'serve'], { env, stdin: 'pipe', stdout: 'pipe', stderr: 'pipe' });
+ const deadline = Date.now() + 45_000;
+ while (!inspectLockHolder(dataDir).held && Date.now() < deadline) await Bun.sleep(100);
+ expect(inspectLockHolder(dataDir).held).toBe(true);
+ writeMarker({ pid: process.pid, state: 'quiesced' });
+ const code = await Promise.race([serve.exited, Bun.sleep(20_000).then(() => 'timeout' as const)]);
+ if (code === 'timeout') serve.kill();
+ expect(code).toBe(75);
+ expect(await new Response(serve.stderr).text()).toContain('graduation_in_progress');
+ expect(inspectLockHolder(dataDir).held).toBe(false);
+ }, 90_000);
+});