Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
graduation(g2a): E2E fixes — sanctioned datastore move for managed brains, quiet DDL pool notices, autopilot resume off stdout, plan refuses during an interrupted run, awaitable batch boundary, resume finishes interrupted rollbacks; G4 test fixes (hosted role provisioned like a managed provider, bigint-safe counters, poll filter)
garrytan91529783f7cd
diff --git a/src/core/connection-manager.ts b/src/core/connection-manager.tsindex 32dea22461..028b4a264c 100644--- a/src/core/connection-manager.ts+++ b/src/core/connection-manager.ts@@ -351,6 +351,7 @@ export class ConnectionManager {// Explicit (matches the postgres.js implicit default; GBRAIN_POOL_MAX_LIFETIME_S overrides).max_lifetime: resolveMaxLifetimeSeconds(),types: { bigint: postgres.BigInt },+ onnotice: process.env.GBRAIN_PG_NOTICES === '1' ? undefined : () => {},onpoisoned: (status: string) => this.opts.onpoisoned?.('read', status),};const timeouts = resolveSessionTimeouts();@@ -501,6 +502,7 @@ export class ConnectionManager {// Always use prepared statements on the direct pool — no PgBouncer// here, so the prepare-cache invalidation issue doesn't apply.prepare: true,+ onnotice: process.env.GBRAIN_PG_NOTICES === '1' ? undefined : () => {},onpoisoned: (status: string) => this.opts.onpoisoned?.('direct', status),// Apply DDL session GUCs as connection startup parameters (durable// through any intermediary pooling layer, same trick asdiff --git a/src/core/persistence/engine-graduation.ts b/src/core/persistence/engine-graduation.tsindex 1cee83296c..7513aacaf8 100644--- a/src/core/persistence/engine-graduation.ts+++ b/src/core/persistence/engine-graduation.ts@@ -38,7 +38,7 @@ import {} from './engine-graduation.types.ts';import {currentProcessIdentity, engineGraduatedFor, fsyncParent, graduatedPath, graduationDataDir, inspectGraduationPath, markerLiveness,- allowGraduationInspection, moveAsideHeld, readIntentMarker, readTombstone, registerGraduationRunInProcess, removeIntentMarker, removeTombstone, splitBrainFor,+ allowGraduationInspection, moveAsideHeld, moveHeldDatastore, readIntentMarker, readTombstone, registerGraduationRunInProcess, removeIntentMarker, removeTombstone, splitBrainFor,TERMINAL_STATES, TombstonePathOccupiedError, writeFileDurably, writeIntentMarker, writeTombstone,} from './graduation-custody.ts';import {@@ -50,7 +50,6 @@ import {dropGraduationFence, graduationFenceStatus, installGraduationFence, readGraduationRow, setSourceState, setTargetState,withGraduationRun,} from './graduation-schema.ts';-import { moveHeldPglite } from './maintenance.ts';import { assertRelationSet, copyOrder, fkClosure, GRADUATION_INVENTORY } from './graduation-inventory.ts';import { digestTable } from './graduation-digest.ts';import { verifyGraduation } from './graduation-verify.ts';@@ -173,6 +172,12 @@ export function defaultGraduationDeps(): GraduationDeps {};}+function withStdoutOnStderrSync(fn: () => void): void {+ const log = console.log;+ console.log = (...args: unknown[]) => console.error(...args);+ try { fn(); } finally { console.log = log; }+}+async function withStdoutOnStderr<T>(fn: () => Promise<T>): Promise<T> {const log = console.log;console.log = (...args: unknown[]) => console.error(...args);@@ -540,6 +545,8 @@ export async function planGraduation(opts: GraduationOptions): Promise<Graduatioconst input = planInputs(deps, opts);const dataDir = sourceDataDir(input.config);phase({ opts }, 'plan');+ const recorded = readGraduationManifest(opts.manifestPath ?? graduationManifestPath());+ if (recorded && !TERMINAL_STATES.has(recorded.state)) throw existingRunError(recorded);refuseOnPathState(inspectGraduationPath(dataDir));let source: GraduationSourceEngine | null = null;let targets: { main: BrainEngine; close(): Promise<void> } | null = null;@@ -614,7 +621,7 @@ async function claimPause(run: Run): Promise<void> {if (run.resumePause) return;const resume = await run.deps.claimAutopilotPause();if (!resume) throw inProgressError({ runId: run.m.runId, state: run.m.state, dataDir: run.dataDir });- run.resumePause = resume;+ run.resumePause = () => withStdoutOnStderrSync(resume);}function recordedRoutes(run: Run): Routes {@@ -828,11 +835,11 @@ async function stepCopy(run: Run): Promise<void> {run.opts.progress?.table(entry.relation, sourceRows.get(entry.relation) ?? 0);let batches = 0;await run.deps.copyTable(engines, entry, { bypass: run.m.triggerBypass, batchBytes: run.m.batchSize, runId: run.m.runId,- onBatch: rows => {+ onBatch: async rows => {batches += 1;run.opts.progress?.batch(entry.relation, rows);progress(run, { phase: 'copy', relation: entry.relation, rows, done, total: order.length });- void graduationBoundary('batch_copied', { runId: run.m.runId, relation: entry.relation, batch: batches });+ await graduationBoundary('batch_copied', { runId: run.m.runId, relation: entry.relation, batch: batches });checkInterrupt(run);} });setCheckpoint(run, entry.relation, { state: 'copied', batches });@@ -904,7 +911,7 @@ async function stepCutover(run: Run): Promise<void> {run.source = null;await source.disconnect();await boundary(run, 'source_closed');- moveAsideHeld(run.dataDir, run.lock, run.m.runId);+ await moveAsideHeld(run.dataDir, run.lock, run.m.runId);await boundary(run, 'moved_aside');await tombstoneUnderLock(run);}@@ -1124,7 +1131,13 @@ export async function resumeGraduation(opts: RunOptions = {}): Promise<Graduatioconst run = loadRun(opts);try {await reconcileRun(run);- if (run.m.state === 'graduated') return await receiptOf(run);+ // Reconciliation finishes an interrupted rollback (rolled_back) or returns the target to authority (graduated).+ if (run.m.state === 'graduated' || run.m.state === 'rolled_back') return await receiptOf(run);+ if (run.m.state === 'abandoned') {+ throw opError('not_found', `Graduation run ${run.m.runId} was abandoned; there is nothing to resume.`,+ 'Start a new move from the plan (fix); the PGLite brain is authoritative.',+ { fix: { argv: planArgv(run), consent: [], actor: 'agent', requires_exclusive: false, why: 'Shows a fresh read-only plan.' } });+ }if (STATE_RANK[run.m.state] >= STATE_RANK.rollback_fenced) throw existingRunError(run.m);return await continueRun(run, { force: run.m.force });} finally { await cleanup(run); }@@ -1294,7 +1307,7 @@ async function finishRollback(run: Run): Promise<void> {if (readTombstone(run.dataDir)) { removeTombstone(run.dataDir, run.m.runId); await boundary(run, 'tombstone_removed'); }if (existsSync(movedTo)) {if (existsSync(run.dataDir)) throw splitBrainFor(inspectGraduationPath(run.dataDir));- moveHeldPglite(movedTo, run.dataDir, run.lock!);+ await moveHeldDatastore(movedTo, run.dataDir, run.lock!);await boundary(run, 'renamed_back');}const source = await run.deps.newSourceEngine();diff --git a/src/core/persistence/graduation-copy.ts b/src/core/persistence/graduation-copy.tsindex 4f1eee720b..1f1ba54375 100644--- a/src/core/persistence/graduation-copy.ts+++ b/src/core/persistence/graduation-copy.ts@@ -144,7 +144,7 @@ async function readSourceBatch(source: BrainEngine, plan: DigestPlan, extraWhere* happen before any transaction opens (PGLite serializes its one connection).*/export async function copyTable(e: GraduationEngines, entry: InventoryEntry,- opts: { bypass: TriggerBypass; batchBytes?: number; onBatch?: (rows: number) => void; runId: string }): Promise<{ rows: number }> {+ opts: { bypass: TriggerBypass; batchBytes?: number; onBatch?: (rows: number) => void | Promise<void>; runId: string }): Promise<{ rows: number }> {if (entry.class !== 'carry' && entry.class !== 'rebind') throw new Error(`copyTable: ${entry.relation} is ${entry.class}, not carried`);const relation = entry.relation;const plan = await digestPlan(e.source, entry, true);@@ -189,7 +189,7 @@ export async function copyTable(e: GraduationEngines, entry: InventoryEntry,await scan(null, async batch => {await tx.executeRaw(insertSql, [JSON.stringify(batch)]);rows += batch.length;- opts.onBatch?.(batch.length);+ await opts.onBatch?.(batch.length);});if (selfFk.length) {const fk = selfFk.map(name => ({ c: plan.columns.find(c => c.name === name)!, i: plan.columns.findIndex(c => c.name === name) }));diff --git a/src/core/persistence/graduation-custody.ts b/src/core/persistence/graduation-custody.tsindex d4efd9d41e..652ce6d20e 100644--- a/src/core/persistence/graduation-custody.ts+++ b/src/core/persistence/graduation-custody.ts@@ -16,6 +16,7 @@ import type { OperationError } from '../ops/contract.ts';import { engineGraduatedError, inProgressError, interruptedError, splitBrainError } from './graduation-errors.ts';import { inspectLockHolder, isProcessAlive, readBootId, readPidNs, type LockHandle } from '../pglite-lock.ts';import { moveHeldPglite } from './maintenance.ts';+import { withFilesystemPublication } from './filesystem-guard.ts';import { flushDirectory } from '../fs-durable.ts';import type { BrainEngine } from '../engine.ts';import { GRADUATION_RUN_SETTING, graduationTablePresent, readGraduationRow } from './graduation-schema.ts';@@ -309,12 +310,21 @@ export function splitBrainFor(state: Pick<GraduationPathState, 'dataDir' | 'move* already-held kernel lock (no release, no gap) and retarget the lock* metadata into the moved dir. Returns the moved path.*/-export function moveAsideHeld(dataDir: string, lock: LockHandle, runId: string): string {+export async function moveAsideHeld(dataDir: string, lock: LockHandle, runId: string): Promise<string> {const movedTo = graduatedPath(dataDir, runId);- moveHeldPglite(graduationDataDir(dataDir), movedTo, lock);+ await moveHeldDatastore(graduationDataDir(dataDir), movedTo, lock);return movedTo;}+/**+ * The held-lock rename as a sanctioned filesystem publication: a managed+ * brain registers its own datastore path as a managed root, and graduation+ * (or its rollback) is the custody operation allowed to move it.+ */+export async function moveHeldDatastore(fromDir: string, toDir: string, lock: LockHandle): Promise<void> {+ await withFilesystemPublication([fromDir, toDir], async () => { moveHeldPglite(fromDir, toDir, lock); });+}+// ── database connect and admission checks ──────────────────────────────────diff --git a/test/e2e/graduation-cli.test.ts b/test/e2e/graduation-cli.test.tsindex ba25bbe57b..d9a0225bcb 100644--- a/test/e2e/graduation-cli.test.ts+++ b/test/e2e/graduation-cli.test.ts@@ -121,7 +121,9 @@ describe.skipIf(!DATABASE_URL)('graduation: --plan and --status are zero-mutatioconst status = await gbrain(['migrate', '--status', '--json'], { home: c.fx.home });expect({ label, code: status.code }).toEqual({ label, code: 0 });await gbrain(['migrate', '--to', 'postgres', '--url-env', TARGET_ENV, '--plan', '--json'], { home: c.fx.home, env });- const changes = digestChanges(before, await stateDigest(c.fx.dir, c.target.url)).filter(change => !change.includes('boundary-events.jsonl'));+ // Not the poll's writes: the paused run's own kernel-lock heartbeat (.gbrain-lock/lock, every 30 s) and Bun's runtime install cache under the test HOME.+ const changes = digestChanges(before, await stateDigest(c.fx.dir, c.target.url))+ .filter(change => !change.includes('boundary-events.jsonl') && !change.includes('.gbrain-lock/lock') && !change.includes('/.bun/install/cache/'));expect({ label, changes }).toEqual({ label, changes: [] });};for (let ordinal = 1; ; ordinal++) {diff --git a/test/e2e/graduation-clients.test.ts b/test/e2e/graduation-clients.test.tsindex 045897998f..c3aafff8f9 100644--- a/test/e2e/graduation-clients.test.ts+++ b/test/e2e/graduation-clients.test.ts@@ -28,7 +28,7 @@ import { chmodSync, closeSync, existsSync, fsyncSync, mkdirSync, openSync, readFimport { dirname, join } from 'node:path';import type { Tombstone } from '../../src/core/persistence/engine-graduation.types.ts';import {- codeOf, custodyPaths, DATABASE_URL, digestChanges, fixOf, freePort, gbrain, GRADUATION_LANDED, graduationTest, mcpStdioSession, olderReleaseBinary,+ codeOf, custodyPaths, DATABASE_URL, digestChanges, fixOf, freePort, gbrain, graduationTest, mcpStdioSession, olderReleaseBinary,previousReleaseTags, release, REPO, startGbrain, stateDigest, TARGET_ENV, waitForEvent, type GbrainResult,} from '../helpers/graduation-e2e.ts';import { configuredEngine, expectGraduated, legacyCase, planAndRun, scratchRoot, targetRowState, withTarget, type Case } from '../helpers/graduation-scenarios.ts';@@ -82,18 +82,6 @@ async function runFix(fix: Record<string, any>, home: string, c: Case): Promise<}/** The Tombstone contract written by hand (O_EXCL, 0600, fsync file + parent), for the pre-integration half. */-function handTombstone(c: Case, runId: string): void {- const movedTo = `${c.fx.dataDir}.graduated-${runId}`;- renameSync(c.fx.dataDir, movedTo);- const tombstone: Tombstone = { kind: 'gbrain-engine-graduated', runId, brainId: c.before.brainId, movedTo,- target: { id: 'hand-written', host: '127.0.0.1', port: 5432, database: 'gbrain_test', user: 'postgres' },- targetDisplayUrl: 'postgresql://[email protected]:5432/gbrain_test', graduatedAt: new Date().toISOString(),- fixArgv: ['gbrain', 'config', 'set', 'database_url', '$GBRAIN_TARGET_URL'] };- const fd = openSync(c.fx.dataDir, constants.O_CREAT | constants.O_EXCL | constants.O_WRONLY, 0o600);- try { writeSync(fd, JSON.stringify(tombstone)); fsyncSync(fd); } finally { closeSync(fd); }- const parent = openSync(dirname(c.fx.dataDir), 'r');- try { fsyncSync(parent); } finally { closeSync(parent); }-}async function olderRun(binary: string, home: string, argv: string[], stdin?: string): Promise<GbrainResult> {return gbrain(argv, { home, binary, stdin, timeoutMs: 120_000 });@@ -104,12 +92,8 @@ describe.skipIf(!DATABASE_URL)('graduation: older released binaries', () => {expect(olderError).toBeNull();expect(older.length).toBe(2);const c = await fresh('older-tombstone');- if (GRADUATION_LANDED) {- const { argv, env } = await planAndRun(c);- expect((await gbrain(argv, { home: c.fx.home, env, timeoutMs: 900_000 })).code).toBe(0);- } else {- handTombstone(c, 'hand-run');- }+ const { argv, env } = await planAndRun(c);+ expect((await gbrain(argv, { home: c.fx.home, env, timeoutMs: 900_000 })).code).toBe(0);const home = staleHome(c);const tombstoneBytes = readFileSync(c.fx.dataDir);const retained = custodyPaths(c.fx.dataDir).graduated;diff --git a/test/graduation-custody.test.ts b/test/graduation-custody.test.tsindex 752325be2b..915445e8e1 100644--- a/test/graduation-custody.test.ts+++ b/test/graduation-custody.test.ts@@ -132,7 +132,7 @@ describe('lock-retaining close and held-lock move-aside', () => {await engine.disconnect();expect(lock.acquired).toBe(true);await Bun.sleep(30);- const movedTo = moveAsideHeld(dataDir, lock, 'run-c');+ const movedTo = await moveAsideHeld(dataDir, lock, 'run-c');expect(lock.lockDir).toBe(join(movedTo, '.gbrain-lock'));expect(existsSync(dataDir)).toBe(false);await Bun.sleep(30);diff --git a/test/helpers/graduation-e2e.ts b/test/helpers/graduation-e2e.tsindex 5fd79c2e08..80b4c57f63 100644--- a/test/helpers/graduation-e2e.ts+++ b/test/helpers/graduation-e2e.ts@@ -20,19 +20,11 @@ import { gbrain, planHashOf, REPO, type GbrainChild, type GbrainOpts, type Gbraiexport * from '../../scripts/persistence/graduation-process.ts';-/**- * Graduation lands in parallel lanes (G2a orchestrator, G3 CLI). Until the- * orchestrator module exists, suites that need it register as `test.todo`- * (visible in every report, never silently skipped). Infrastructure checks- * that need only Postgres run either way.- */-const ORCHESTRATOR = join(REPO, 'src', 'core', 'persistence', 'engine-graduation.ts');-/** The CLI lane ships a throwing stub at this path until the orchestrator merges; the stub does not count as landed. */-export const GRADUATION_LANDED = existsSync(ORCHESTRATOR) && !readFileSync(ORCHESTRATOR, 'utf8').includes('STUB (G3 CLI lane)');-export const graduationTest: typeof test = GRADUATION_LANDED ? test : (test.todo as unknown as typeof test);+/** Graduation E2E tests: plain `test`, kept as a named alias so suites read the same. */+export const graduationTest: typeof test = test;/** `graduationTest` with an extra visible skip condition (e.g. Docker unavailable). */export function graduationTestIf(skip: boolean): typeof test {- return GRADUATION_LANDED ? test.skipIf(skip) as typeof test : graduationTest;+ return test.skipIf(skip) as typeof test;}export const DATABASE_URL = process.env.DATABASE_URL;@@ -103,7 +95,8 @@ export async function hostedRoleTarget(adminUrl = DATABASE_URL!): Promise<Targetlet password = `hosted-${randomUUID()}`;const admin = postgres(adminUrl, { max: 1, prepare: false, onnotice: () => {} });try {- await admin.unsafe(`CREATE ROLE ${role} LOGIN NOSUPERUSER NOCREATEDB NOCREATEROLE PASSWORD '${password}'`);+ // BYPASSRLS like a managed provider's application role (Supabase `postgres`): the schema's RLS backfill needs it.+ await admin.unsafe(`CREATE ROLE ${role} LOGIN NOSUPERUSER NOCREATEDB NOCREATEROLE BYPASSRLS PASSWORD '${password}'`);await admin.unsafe(`CREATE DATABASE ${database} OWNER ${role}`);} finally { await admin.end(); }const owned = postgres(withDatabase(adminUrl, database), { max: 1, prepare: false, onnotice: () => {} });@@ -111,6 +104,12 @@ export async function hostedRoleTarget(adminUrl = DATABASE_URL!): Promise<Targetawait owned.unsafe('CREATE EXTENSION IF NOT EXISTS vector');await owned.unsafe('CREATE EXTENSION IF NOT EXISTS pg_trgm');await owned.unsafe(`GRANT ALL ON SCHEMA public TO ${role}`);+ // The auto-RLS event trigger is superuser-only; managed providers pre-create it with the function owned by the app role.+ await owned.unsafe(`CREATE OR REPLACE FUNCTION public.auto_enable_rls() RETURNS event_trigger LANGUAGE plpgsql AS $f$ DECLARE obj record; BEGIN+ FOR obj IN SELECT * FROM pg_event_trigger_ddl_commands() WHERE object_type = 'table' AND schema_name = 'public' LOOP+ EXECUTE format('ALTER TABLE %s ENABLE ROW LEVEL SECURITY', obj.object_identity); END LOOP; END; $f$`);+ await owned.unsafe(`ALTER FUNCTION public.auto_enable_rls() OWNER TO ${role}`);+ await owned.unsafe(`CREATE EVENT TRIGGER auto_rls_on_create_table ON ddl_command_end WHEN TAG IN ('CREATE TABLE', 'CREATE TABLE AS', 'SELECT INTO') EXECUTE FUNCTION public.auto_enable_rls()`);} finally { await owned.end(); }return {role, database, admin: adminUrl,diff --git a/test/helpers/graduation-scenarios.ts b/test/helpers/graduation-scenarios.tsindex e0e7aa233e..8ef24c3361 100644--- a/test/helpers/graduation-scenarios.ts+++ b/test/helpers/graduation-scenarios.ts@@ -142,7 +142,7 @@ export async function expectGraduated(c: Case, label: string): Promise<void> {/** Resubmit the queued request (recorded with its callerIntent) on the target: stored outcome back, no new row, counters unchanged. */export async function expectReplayReturnsStored(target: PostgresEngine, fx: GraduationFixture): Promise<void> {const admission = readQueuedAdmission(fx.root);- const counters = async () => (await target.executeRaw<Record<string, unknown>>('SELECT * FROM persistence_counters ORDER BY key COLLATE "C"')).map(r => JSON.stringify(r));+ const counters = async () => (await target.executeRaw<Record<string, unknown>>('SELECT * FROM persistence_counters ORDER BY key COLLATE "C"')).map(r => JSON.stringify(r, (_k, v) => typeof v === 'bigint' ? v.toString() : v));const rows = async () => Number((await target.executeRaw<{ n: number }>('SELECT count(*)::int AS n FROM persistence_requests'))[0].n);const [stored] = await target.executeRaw<{ id: string; state: string; outcome: Record<string, unknown> | null }>('SELECT id::text AS id,state,outcome FROM persistence_requests WHERE request_id=$1::uuid', [admission.requestId]);