Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
graduation(g2a): E2E round 2 — route cross-check before the plan comparison, exit 3 for a confirmable rollback loss; G4 test fixes (refused source open counts as not a writer, graduated-boundary status, stale-client fix fills <target_url> from inputs, MCP fix extraction, live serve may finish derived work before hand-off)
garrytan20e6ab57f018
diff --git a/src/commands/migrate-graduation.ts b/src/commands/migrate-graduation.tsindex b2ab04b4ed..2cfd318ade 100644--- a/src/commands/migrate-graduation.ts+++ b/src/commands/migrate-graduation.ts@@ -410,6 +410,11 @@ function writeGraduationError(e: unknown, aborted: boolean, json: boolean,why: 'Continues from the recorded checkpoint.', user_message: 'The move to Postgres was paused. Should I continue it?' } });return write(err, { json, ...(json ? { legacy: { resume_command: resumeArgv() } } : {}) });}+ if (e instanceof OperationError && e.code === 'graduation_rollback_writes_lost' && e.reason === 'user_data') {+ // A confirmable loss asks the user (fix.next ask_user, like confirmation_required): exit 3. A final refusal stays 1.+ write(e, { json });+ return 3;+ }if (e instanceof OperationError && e.code === 'graduation_drain_timeout') {const code = write(e, { json, ...(json ? { legacy: { resume_command: e.fix?.argv ?? resumeArgv() } } : {}) });return e.reason === 'blocked' ? 1 : code;diff --git a/src/core/persistence/engine-graduation.ts b/src/core/persistence/engine-graduation.tsindex 7513aacaf8..97d2c0d99f 100644--- a/src/core/persistence/engine-graduation.ts+++ b/src/core/persistence/engine-graduation.ts@@ -644,6 +644,7 @@ async function quiesceFresh(run: Run, input: PlanInputs, expect: string): Promisawait claimPause(run);await openSourceUnderLock(run);await openTargets(run);+ await run.deps.crossCheckRoutes(run.main!, run.ddl!, run.m.runId);const plan = await assemblePlan(run.deps, input, run.source, run.main, false);if (plan.planHash !== expect) throw previewChanged(run, hatchArgs(input), plan.planHash);const blocker = plan.blockers.find(refusesRun);diff --git a/test/e2e/graduation-clients.test.ts b/test/e2e/graduation-clients.test.tsindex c3aafff8f9..01e4f4a805 100644--- a/test/e2e/graduation-clients.test.ts+++ b/test/e2e/graduation-clients.test.ts@@ -71,9 +71,21 @@ function shimPath(c: Case): string {}/** Run a refusal's fix once: `fix.argv` through the CLI, or the shell `fix.command`. */+/** The first rendered fix (`next` run or tell_user_to_run) anywhere in an MCP reply, including JSON-encoded text content. */+function findFix(value: unknown): Record<string, any> | null {+ if (typeof value === 'string') { try { return findFix(JSON.parse(value)); } catch { return null; } }+ if (!value || typeof value !== 'object') return null;+ const record = value as Record<string, any>;+ if ((record.next === 'run' || record.next === 'tell_user_to_run') && Array.isArray(record.argv)) return record;+ for (const child of Object.values(record)) { const found = findFix(child); if (found) return found; }+ return null;+}+async function runFix(fix: Record<string, any>, home: string, c: Case): Promise<GbrainResult> {const env = { [TARGET_ENV]: c.target.url, PATH: shimPath(c) };- if (Array.isArray(fix.argv) && fix.argv[0] === 'gbrain') return gbrain(fix.argv.slice(1), { home, env });+ // An agent fills `<name>` argv placeholders from fix.inputs (the user supplies the target URL).+ const filled = Array.isArray(fix.argv) ? (fix.argv as string[]).map(a => a === '<target_url>' ? c.target.url : a) : null;+ if (filled && filled[0] === 'gbrain') return gbrain(filled.slice(1), { home, env });expect(typeof fix.command).toBe('string');const child = Bun.spawn(['sh', '-c', fix.command], { env: { ...process.env, ...env, HOME: home, GBRAIN_HOME: home, DATABASE_URL: '', GBRAIN_DATABASE_URL: '' }, stdout: 'pipe', stderr: 'pipe' });const [stdout, stderr] = await Promise.all([new Response(child.stdout).text(), new Response(child.stderr).text()]);@@ -235,7 +247,7 @@ describe.skipIf(!DATABASE_URL)('graduation: serve processes', () => {expect(served).not.toBeNull();expect(`${served!.stdout}${served!.stderr}`).toContain('graduation_in_progress');expect(JSON.stringify(run.json)).toMatch(/restart|mcp/i);- await expectGraduated(c, 'after live-serve hand-off');+ await expectGraduated(c, 'after live-serve hand-off', { liveWork: true });const relaunched = await mcpStdioSession({ home: c.fx.home });const after = await relaunched.call('get_page', { slug: 'people/alice-example', source_id: 'default' });await relaunched.close();@@ -272,9 +284,9 @@ describe.skipIf(!DATABASE_URL)('graduation: stale clients recover in one step',const exited = await stale.close();const text = `${JSON.stringify(reply)}${exited.stdout}${exited.stderr}`;expect(text).toContain('engine_graduated');- const match = /\{[^{}]*"next"\s*:\s*"(?:run|tell_user_to_run)"[^{}]*\}/.exec(text.replace(/\\"/g, '"'));- expect(match).not.toBeNull();- const fixed = await runFix(JSON.parse(match![0]), home, c);+ const fix = findFix(reply);+ expect(fix).not.toBeNull();+ const fixed = await runFix(fix!, home, c);expect(fixed.code).toBe(0);const relaunched = await mcpStdioSession({ home });const after = await relaunched.call('get_page', { slug: 'people/alice-example', source_id: 'default' });diff --git a/test/e2e/graduation-crash.test.ts b/test/e2e/graduation-crash.test.tsindex f8c3f05ea0..c8fe4eef04 100644--- a/test/e2e/graduation-crash.test.ts+++ b/test/e2e/graduation-crash.test.ts@@ -90,7 +90,8 @@ describe.skipIf(!DATABASE_URL)('graduation: SIGKILL at every custody boundary',const status = await gbrain(['migrate', '--status', '--json'], { home: c.fx.home });expect(status.code).toBe(0);- expect(stateOf(status.json)).not.toBe('graduated');+ // `graduated` is announced after its own durable write, so a kill there already reads graduated.+ if (pause !== 'graduated') expect(stateOf(status.json)).not.toBe('graduated');// No target URL in the environment: resume reads the 0600 manifest's recorded identities.const resumed = await gbrain(['migrate', '--resume', '--json'], { home: c.fx.home, env: { [TARGET_ENV]: undefined }, timeoutMs: 900_000 });diff --git a/test/helpers/graduation-scenarios.ts b/test/helpers/graduation-scenarios.tsindex 8ef24c3361..b9abc0ec5e 100644--- a/test/helpers/graduation-scenarios.ts+++ b/test/helpers/graduation-scenarios.ts@@ -87,9 +87,14 @@ export async function authority(c: Case): Promise<{ source: boolean; target: booconst paths = custodyPaths(c.fx.dataDir);let sourceState: string | null = null;if (paths.dataDirIsDirectory) {+ // A source fenced past cutover refuses to open at all (graduation_interrupted until resume): it is not a writer.sourceState = await withSource(c.fx, async engine => {try { return (await engine.executeRaw<{ state: string }>('SELECT state FROM persistence_graduation LIMIT 1'))[0]?.state ?? null; }catch { return null; }+ }).catch(error => {+ const code = (error as { code?: string }).code;+ if (code === 'graduation_interrupted' || code === 'graduation_in_progress' || code === 'engine_graduated') return 'cutover';+ throw error;});}const source = paths.dataDirIsDirectory && sourceState !== 'cutover' && !existsSync(paths.marker);@@ -118,7 +123,7 @@ export async function doctorFailures(home: string): Promise<{ result: GbrainResu* expected.json target expectation, one row per request id, a replay of the* queued request returning the stored outcome, and a green target doctor.*/-export async function expectGraduated(c: Case, label: string): Promise<void> {+export async function expectGraduated(c: Case, label: string, opts: { liveWork?: boolean } = {}): Promise<void> {const status = await gbrain(['migrate', '--status', '--json'], { home: c.fx.home });expect({ label, code: status.code, state: stateOf(status.json) }).toEqual({ label, code: 0, state: 'graduated' });expect(configuredEngine(c.fx).engine).toBe('postgres');@@ -129,7 +134,10 @@ export async function expectGraduated(c: Case, label: string): Promise<void> {expect(await targetFenceTriggers(c.target.url)).toBe(0);await withTarget(c.target.url, async target => {const provider = new GBrainOAuthProvider({ sql: sqlQueryForEngine(target) });- expect({ label, mismatches: await legacyTargetMismatches(target, c.before, token => provider.verifyAccessToken(token)) }).toEqual({ label, mismatches: [] });+ // A resident serve that owned the source before the hand-off legitimately finished queued effects and projection jobs.+ const mismatches = (await legacyTargetMismatches(target, c.before, token => provider.verifyAccessToken(token)))+ .filter(m => !(opts.liveWork && (m.startsWith('target effect ') || m.startsWith('target projection job '))));+ expect({ label, mismatches }).toEqual({ label, mismatches: [] });const duplicates = await target.executeRaw<{ n: number }>(`SELECT count(*)::int AS n FROM (SELECT principal_kind,principal_id,request_idFROM persistence_requests GROUP BY 1,2,3 HAVING count(*) > 1) d`);expect(Number(duplicates[0].n)).toBe(0);