Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

graduation: renumber the persistence_graduation migration to v201; a resume that finishes a rollback renders as a rollback

garrytan758056fd2b0a
diff --git a/docs/architecture/key-files/core-persistence-graduation.md b/docs/architecture/key-files/core-persistence-graduation.md
index 29281c7e28..fd577354f6 100644
--- a/docs/architecture/key-files/core-persistence-graduation.md
+++ b/docs/architecture/key-files/core-persistence-graduation.md
@@ -12,7 +12,7 @@ Verified engine graduation, PGLite to Postgres ([operator guide](../../guides/mo
- `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` — the orchestrator behind `gbrain migrate --to postgres`: `planGraduation` (zero mutations: probe-only source open, one read-only target session, refuses while a run is recorded non-terminal), `runGraduation` (needs `yes` plus `expectPlanHash`; a changed plan throws `preview_changed`), `resumeGraduation`, `rollbackGraduation`, `reconcileGraduation` and `graduationStatus` (files plus a read-only target-row read; split brain opens both datastores for counts). The kernel lock is held from step 1 to the routing flip: intent marker before the lock, autopilot pause marker, source open (waits up to 30 s for a resident serve's hand-off, else `graduation_source_writer_held`), in-process source doctor, route cross-check, drain and freeze, target fence, per-table copy with manifest checkpoints, deferred index build on the DDL route, verify (doctor child under `GBRAIN_GRADUATION_RUN`), then fence both and grant authority (source row `cutover`, lock-retaining close, move-aside, `O_EXCL` tombstone, one target transaction that sets `persistence_brain.enabled` and drops the fence) and flip routing (config, mounts). Every state change follows the transition tables and is mirrored into the 0600 manifest (`<GBRAIN_HOME>/.gbrain/graduation-manifest.json`, the only file holding target URLs) and the marker; each step announces its `graduationBoundary`. Resume continues from the recorded state with recorded identities; a resume after a lock gap recomputes source digests and re-drains and re-copies changed tables with their FK closure. Rollback before cutover abandons the target (fence kept); after cutover it fences first, takes the kernel lock, compares (`graduation-losses.ts`) and returns the target to authority on any refusal; `rollback_approved` onward only rolls forward. `--resume --yes` moves a stray datastore at the old path to `<path>.stray-<run_id>`. All refusals come from `graduation-errors.ts`. Tests: `test/graduation-state.test.ts`, `test/graduation-rollback.test.ts`, `test/e2e/graduation-*.test.ts`.
- `src/core/persistence/graduation-custody.ts` — filesystem custody and the open-path checks: the sibling intent marker (atomic replace, 0600, fsync), the `O_CREAT|O_EXCL` tombstone at the old data dir path, `inspectGraduationPath` (`none`, `in_progress`, `interrupted`, `graduated`, `split_brain`; marker liveness from pid, boot id, pid namespace and process start time), `assertPgliteGraduationOpenable` (called by `PGLiteEngine` before `acquireLock`, so a tombstone refuses `engine_graduated` and a live run `graduation_in_progress` without touching the path, and again after the lock, refusing `graduation_interrupted` past cutover), `assertGraduationConnectAllowed` (every CLI connect: a non-authoritative target or a cut-over source refuses unless the session is the run's) and `assertGraduationAdmission` (writer admission). `moveAsideHeld` renames under the already-held kernel lock as a sanctioned filesystem publication (a managed brain's datastore is a managed root). Test: `test/graduation-custody.test.ts`.
-- `src/core/persistence/graduation-schema.ts` + `src/core/schema-migrations/v203-persistence-graduation.ts` — the `persistence_graduation` singleton (each engine's own custody row; schema-owned, never copied) and `gbrain_graduation_fence()`. `installGraduationFence` puts a statement-level `ENABLE ALWAYS` trigger on every table that refuses writes unless `gbrain.graduation_run` equals the row's run id; `dropGraduationFence`, `setTargetState`/`setSourceState` (transition-table driven) and `withGraduationRun`.
+- `src/core/persistence/graduation-schema.ts` + `src/core/schema-migrations/v201-persistence-graduation.ts` — the `persistence_graduation` singleton (each engine's own custody row; schema-owned, never copied) and `gbrain_graduation_fence()`. `installGraduationFence` puts a statement-level `ENABLE ALWAYS` trigger on every table that refuses writes unless `gbrain.graduation_run` equals the row's run id; `dropGraduationFence`, `setTargetState`/`setSourceState` (transition-table driven) and `withGraduationRun`.
- `src/core/persistence/graduation-losses.ts` — rollback write detection: per carried table, the target digest against the verified receipt (`persistence_brain.enabled` through its transform), requests after the cutover sequence, and the security tables plus `fact_withdrawals` against the retained PGLite copy by identity and content (`last_used_at` ignored, expired OAuth tokens may disappear). Missing or changed security rows and new withdrawals are final.
- `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/src/commands/migrate-graduation.ts b/src/commands/migrate-graduation.ts
index 2cfd318ade..937f62ce34 100644
--- a/src/commands/migrate-graduation.ts
+++ b/src/commands/migrate-graduation.ts
@@ -389,6 +389,11 @@ export async function runMigrateGraduation(args: readonly string[], deps: Gradua
}
const receipt = a.mode === 'resume' ? await api.resumeGraduation(opts) : await api.runGraduation(opts);
done();
+ if (receipt.state === 'rolled_back') {
+ emit({ schema_version: 1, status: 'rolled_back', state: 'rolled_back', run_id: receipt.runId, receipt },
+ `Rolled back (run ${receipt.runId}): the interrupted rollback finished and the PGLite brain is authoritative again.\n`);
+ return 0;
+ }
emit(successDoc(receipt), successLines(receipt));
return 0;
} catch (e) {
diff --git a/src/core/schema-migrations/registry.generated.ts b/src/core/schema-migrations/registry.generated.ts
index 154a8c3fd2..36586eea84 100644
--- a/src/core/schema-migrations/registry.generated.ts
+++ b/src/core/schema-migrations/registry.generated.ts
@@ -201,7 +201,7 @@ import { v197 } from './v197-managed-guard-null-source-fallback.ts';
import { v198 } from './v198-publication-failure-detail.ts';
import { v199 } from './v199-chronicle-page-state.ts';
import { v200 } from './v200-sync-hold-page-index.ts';
-import { v203 } from './v203-persistence-graduation.ts';
+import { v201 } from './v201-persistence-graduation.ts';
// Array order is historical (see HISTORICAL_ARRAY_ORDER in the generator); the
// runner sorts by version before applying.
@@ -401,5 +401,5 @@ export const MIGRATIONS: Migration[] = [
v198,
v199,
v200,
- v203,
+ v201,
];
diff --git a/src/core/schema-migrations/v203-persistence-graduation.ts b/src/core/schema-migrations/v201-persistence-graduation.ts
similarity index 93%
rename from src/core/schema-migrations/v203-persistence-graduation.ts
rename to src/core/schema-migrations/v201-persistence-graduation.ts
index 4803bdf7ce..db9cb149df 100644
--- a/src/core/schema-migrations/v203-persistence-graduation.ts
+++ b/src/core/schema-migrations/v201-persistence-graduation.ts
@@ -8,8 +8,8 @@ import { PERSISTENCE_GRADUATION_SCHEMA_SQL } from '../persistence/graduation-sch
// target table until the authority transaction. DDL in
// src/core/persistence/graduation-schema.ts. The table is schema-owned: never
// copied, digested or compared.
-export const v203: Migration = {
- version: 203,
+export const v201: Migration = {
+ version: 201,
name: 'persistence_graduation',
idempotent: true,
sql: PERSISTENCE_GRADUATION_SCHEMA_SQL,