Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(migrate): refuse a rollback whose retained PGLite copy is gone (#6106)
time-attack375807102172
diff --git a/docs/architecture/key-files/core-persistence-graduation.md b/docs/architecture/key-files/core-persistence-graduation.mdindex fd577354f6..85d538bbe6 100644--- a/docs/architecture/key-files/core-persistence-graduation.md+++ b/docs/architecture/key-files/core-persistence-graduation.md@@ -10,7 +10,7 @@ Verified engine graduation, PGLite to Postgres ([operator guide](../../guides/mo- `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` — 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/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 requires the retained copy (checked before the fence and again under the kernel lock; gone refuses `not_found` via `retainedCopyMissingError` with nothing changed), 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/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.diff --git a/src/commands/doctor/checks/local-audits.ts b/src/commands/doctor/checks/local-audits.tsindex 455dbf3429..4987e919aa 100644--- a/src/commands/doctor/checks/local-audits.ts+++ b/src/commands/doctor/checks/local-audits.ts@@ -461,7 +461,7 @@ async function runHomeDirInWorktree(ctx: DoctorContext): Promise<Check[]> {fix: {argv: ['rm', '-rf', copy.path], consent: ['destructive'], actor: 'agent', requires_exclusive: false,verify: { argv: ['gbrain', 'doctor', '--only', 'pglite_leftovers', '--json'] }, docs: 'docs/guides/move-to-postgres.md#after-the-move',- why: `${copy.path} is the PGLite brain engine graduation moved to Postgres; it still holds private memory and token hashes. Deleting it frees the disk and ends the option to roll back.`,+ why: `${copy.path} is the PGLite brain engine graduation moved to Postgres; it still holds private memory and token hashes. Deleting it frees the disk and ends the option to roll back: afterwards a rollback to PGLite refuses with not_found and the brain stays on Postgres.`,user_message: `After moving your brain to Postgres, gbrain kept the old local copy at ${copy.path}. It still contains your private memory and access-token hashes. Should I delete it? You could then no longer roll back to it.`,},} : {}),diff --git a/src/core/persistence/engine-graduation.ts b/src/core/persistence/engine-graduation.tsindex c6e6427d73..1982e40b4d 100644--- a/src/core/persistence/engine-graduation.ts+++ b/src/core/persistence/engine-graduation.ts@@ -16,7 +16,7 @@* Graduation is CLI-only: no operations.ts entry, no remote caller.*/import { createHash, randomUUID } from 'node:crypto';-import { existsSync, mkdirSync, readFileSync, renameSync } from 'node:fs';+import { existsSync, lstatSync, mkdirSync, readFileSync, renameSync } from 'node:fs';import { homedir } from 'node:os';import { dirname, join } from 'node:path';import { spawnSync } from 'node:child_process';@@ -43,7 +43,7 @@ import {} from './graduation-custody.ts';import {drainTimeoutError, embeddingDimensionMismatchError, foreignHostBindingError, inProgressError, interruptedError, planArgv as planArgvOf,- resumeArgv, rollbackWritesLostError, runArgv as runArgvOf, sourceWriterHeldError, statusArgv, targetAuthFailedError, targetNotEmptyError,+ resumeArgv, retainedCopyMissingError, rollbackWritesLostError, runArgv as runArgvOf, sourceWriterHeldError, statusArgv, targetAuthFailedError, targetNotEmptyError,targetUnsupportedError, unsupportedPlatformError, verifyFailedError,} from './graduation-errors.ts';import { rollbackLosses, type RollbackLoss } from './graduation-losses.ts';@@ -1233,6 +1233,7 @@ async function rollbackBeforeCutover(run: Run): Promise<GraduationRollbackResultasync function rollbackAfterCutover(run: Run, opts: RunOptions): Promise<GraduationRollbackResult> {const from = run.m.state;+ assertRetainedCopy(run, from);const hadAuthority = from === 'authoritative' || from === 'graduated';await openTargets(run);if (hadAuthority) {@@ -1251,6 +1252,7 @@ async function rollbackAfterCutover(run: Run, opts: RunOptions): Promise<Graduattry {await claimPause(run);await takeKernelLock(run);+ assertRetainedCopy(run, from);if (hadAuthority) losses = await detectRollbackLosses(run);} catch (error) {if (hadAuthority) await returnToAuthority(run);@@ -1274,6 +1276,15 @@ async function rollbackAfterCutover(run: Run, opts: RunOptions): Promise<Graduatdropped: losses.filter(l => l.lossKind === 'operational').map(l => ({ relation: l.relation, rows: l.rows, lossKind: l.lossKind })) };}+/** Rollback after cutover restores the retained copy; with it gone, going on would open an empty brain at the old path and route this machine to it. */+function assertRetainedCopy(run: Run, from: ManifestState): void {+ const movedTo = graduatedPath(run.dataDir, run.m.runId);+ let unmoved = false;+ try { unmoved = from === 'cutover' && lstatSync(run.dataDir).isDirectory(); } catch { /* absent */ }+ if (existsSync(movedTo) || unmoved) return;+ throw retainedCopyMissingError({ runId: run.m.runId, retainedPath: movedTo });+}+async function approveAndRestore(run: Run): Promise<void> {const row = run.main ? await readGraduationRow(run.main) : null;if (row?.run_id === run.m.runId && row.state === 'rollback_fenced') {diff --git a/src/core/persistence/graduation-errors.ts b/src/core/persistence/graduation-errors.tsindex 2e473e0c61..75d1250778 100644--- a/src/core/persistence/graduation-errors.ts+++ b/src/core/persistence/graduation-errors.ts@@ -278,6 +278,17 @@ export function rollbackWritesLostError(opts: { losses: readonly { relation: struser_message: `Going back to PGLite would lose what changed on Postgres since the move: ${listed}. Should I go back anyway? If not, nothing changes and Postgres stays in use.` } });}+/** `not_found`: after cutover, the retained PGLite copy a rollback would restore is gone. */+export function retainedCopyMissingError(opts: { runId: string; retainedPath: string }): OperationError {+ const docs = `${GRADUATION_GUIDE}#check-resume-or-roll-back`;+ const why = `A rollback makes the PGLite brain kept by graduation run ${opts.runId} authoritative again, and that copy is no longer at ${opts.retainedPath}. Nothing was changed: the Postgres brain stays authoritative and this machine stays routed to it.`;+ return opError('not_found', `Rollback refused: the retained PGLite copy of graduation run ${opts.runId} is gone, so there is nothing to roll back to.`,+ 'Keep using the Postgres brain; nothing changed.',+ { why, docs,+ fix: { consent: [], actor: 'agent', requires_exclusive: false, docs, verify: STATUS_VERIFY, why,+ user_message: 'Your brain cannot go back to PGLite: the local copy a rollback would restore was deleted. It keeps working on Postgres.' } });+}+/** `graduation_target_auth_failed`: the recorded target URL no longer authenticates. */export function targetAuthFailedError(opts: { host: string; urlEnv?: string }): OperationError {const docs = GRADUATION_DOCS.graduation_target_auth_failed;diff --git a/test/graduation-rollback.test.ts b/test/graduation-rollback.test.tsindex 0ec59dcff3..9f6dbe3c35 100644--- a/test/graduation-rollback.test.ts+++ b/test/graduation-rollback.test.ts@@ -10,16 +10,20 @@* refusal; durable substeps reconcile after a crash (back to authority before* approval, forward to rolled_back after it). Regressions that fail it: a* timestamp-based security check (revocations delete rows), a refusal that- * strands the target fenced, a crash after approval that restores authority.+ * strands the target fenced, a crash after approval that restores authority,+ * a rollback that runs without its retained copy (it would open an empty+ * brain at the old path and route this machine to it).*/import { afterAll, beforeAll, describe, expect, test } from 'bun:test';-import { existsSync, lstatSync, readFileSync } from 'node:fs';+import { existsSync, lstatSync, readFileSync, rmSync } from 'node:fs';import { join } from 'node:path';import {planGraduation, readGraduationManifest, reconcileGraduation, rollbackGraduation, runGraduation, type GraduationOptions,} from '../src/core/persistence/engine-graduation.ts';import { assertGraduationConnectAllowed, readIntentMarker, readTombstone } from '../src/core/persistence/graduation-custody.ts';+import { retainedCopyMissingError } from '../src/core/persistence/graduation-errors.ts';import { graduationFenceStatus, readGraduationRow } from '../src/core/persistence/graduation-schema.ts';+import { cliRenderContext, toAgentError } from '../src/core/agent-output.ts';import { assertSafeE2eDatabaseUrl } from './helpers/db-guard.ts';import { crashAt, makeHarness, openPglite, probeRows, SOURCE_TOKEN_ID, TARGET_URL, type Harness } from './helpers/graduation-harness.ts';@@ -107,6 +111,39 @@ for (const [label, postgresUrl] of targets) {});}, 120_000);+ async function assertRetainedCopyRefusal(refused: { code?: string; message: string }, copy: string): Promise<void> {+ expect(refused.code).toBe('not_found');+ expect(refused.message).toContain('nothing to roll back to');+ expect(manifest().state).toBe('graduated');+ expect(config().engine).toBe('postgres');+ expect(existsSync(copy)).toBe(false);+ await assertTargetAuthoritative();+ }++ test('a retained copy deleted before the rollback: refused before the fence, nothing changes', async () => {+ await fresh();+ await h.inHome(async () => {+ await graduate();+ const copy = `${h.dataDir}.graduated-${manifest().runId}`;+ rmSync(copy, { recursive: true, force: true });+ let fenced = false;+ const refused = await refusal(rollbackGraduation(rollbackOpts({ pauseAt: 'rollback_fenced', pauseHook: async () => { fenced = true; } })));+ expect(fenced).toBe(false);+ await assertRetainedCopyRefusal(refused, copy);+ });+ }, 120_000);++ test('a retained copy removed between the fence and the kernel lock: refused under the lock, the target returns to authority', async () => {+ await fresh();+ await h.inHome(async () => {+ await graduate();+ const copy = `${h.dataDir}.graduated-${manifest().runId}`;+ const removeAtFence = async (step: string) => { if (step === 'rollback_fenced') rmSync(copy, { recursive: true, force: true }); };+ const refused = await refusal(rollbackGraduation(rollbackOpts({ pauseAt: 'rollback_fenced', pauseHook: removeAtFence })));+ await assertRetainedCopyRefusal(refused, copy);+ });+ }, 120_000);+test('a target page-style edit is listed and rolls back only with the expect hash; it is never written back', async () => {await fresh();await h.inHome(async () => {@@ -185,3 +222,16 @@ for (const [label, postgresUrl] of targets) {}, 120_000);});}++test('the missing-retained-copy refusal renders the agent contract without naming a discard flag', () => {+ const env = toAgentError(retainedCopyMissingError({ runId: 'run1', retainedPath: '/home/alice-example/.gbrain/brain.pglite.graduated-run1' }),+ { transport: 'cli', command: 'migrate', render: cliRenderContext() });+ expect(env.code).toBe('not_found');+ expect(env.why).toContain('Nothing was changed');+ expect(env.docs).toContain('#check-resume-or-roll-back');+ expect(env.fix?.next).toBe('report');+ expect(env.fix?.argv).toBeUndefined();+ expect(env.fix?.verify?.argv).toEqual(['gbrain', 'migrate', '--status', '--json']);+ expect(env.fix?.user_message).toContain('keeps working on Postgres');+ expect(JSON.stringify(env)).not.toContain('--discard-source');+});diff --git a/test/graduation-serve-guard.serial.test.ts b/test/graduation-serve-guard.serial.test.tsindex 9385466b01..243075917b 100644--- a/test/graduation-serve-guard.serial.test.ts+++ b/test/graduation-serve-guard.serial.test.ts@@ -22,6 +22,9 @@ import { probeStatus, statusPayload, initialStatusState } from '../src/mcp/statuimport { 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';+import { homeDirInWorktreeEntry } from '../src/commands/doctor/checks/local-audits.ts';+import type { DoctorContext } from '../src/commands/doctor/context.ts';+import type { Check } from '../src/commands/doctor.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' };@@ -142,6 +145,17 @@ describe('doctor and engine status', () => {expect(assessPgliteLeftovers('pglite', join(home, '.gbrain')).status).toBe('skip');});+ test('doctor pglite_leftovers says a rollback refuses once the copy is deleted, and names no discard flag', async () => {+ writeTombstone();+ writeConfig({ engine: 'postgres', database_url: 'postgresql://[email protected]:5432/brain' });+ const checks = (await inHome(() => homeDirInWorktreeEntry.run({} as DoctorContext))) as Check[];+ const leftovers = checks.find(c => c.name === 'pglite_leftovers')!;+ expect(leftovers.status).toBe('warn');+ expect(leftovers.fix).toMatchObject({ argv: ['rm', '-rf', `${dataDir}.graduated-run-1`], consent: ['destructive'] });+ expect(String((leftovers.fix as { why?: string }).why)).toContain('a rollback to PGLite refuses with not_found');+ expect(JSON.stringify(leftovers)).not.toContain('--discard-source');+ });+test('engine status --json carries the graduation block', async () => {writeTombstone();const proc = Bun.spawn(['bun', CLI, 'engine', 'status', '--json'], {