Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(graduation): verify-step doctor judges writer ownership from the source flag (#6331)

time-attack160d87d3faf8
diff --git a/docs/architecture/key-files/core-persistence-graduation.md b/docs/architecture/key-files/core-persistence-graduation.md
index 85d538bbe6..575c73f450 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 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/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`, plus `GBRAIN_GRADUATION_SOURCE_PERSISTENCE` naming the source's `persistence_brain.enabled`; #6331: `persistenceEnabledForHealth` in `ownership.ts` lets `sync_freshness` and `ownedContentFreshness` treat the fenced target as writer-owned only while its graduation row is this run's `verifying` target), 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/extraction-sync.ts b/src/commands/doctor/checks/extraction-sync.ts
index da16fd20b5..19df8e377e 100644
--- a/src/commands/doctor/checks/extraction-sync.ts
+++ b/src/commands/doctor/checks/extraction-sync.ts
@@ -27,7 +27,7 @@ import { resolveSourceLocalFilePath, sourceGitScope } from '../../../core/markdo
import { scannerSlugRootMode } from '../../../core/write-through.ts';
import { unverifiedExtractionFragment } from '../../../core/extraction-review.ts';
import { quarantineFilterFragment } from '../../../core/quarantine.ts';
-import { managedPersistenceEnabled } from '../../../core/persistence/ownership.ts';
+import { persistenceEnabledForHealth } from '../../../core/persistence/ownership.ts';
import { upstreamFreshness } from '../../../core/sync-upstream.ts';
import type { Check } from '../../doctor.ts';
import { ownedContentFreshness } from '../../../core/shared-skills/content-freshness.ts';
@@ -1293,7 +1293,7 @@ export async function checkSyncFreshness(
// machinery runs once, not once per source).
const stalenessCeilingSeconds = resolveStalenessCeilingSeconds();
let managed = false;
- try { managed = await managedPersistenceEnabled(engine); } catch { /* pre-persistence brain */ }
+ try { managed = await persistenceEnabledForHealth(engine); } catch { /* pre-persistence brain */ }
let upstream_unknown_count = 0;
let upstream_behind_count = 0;
for (const source of sources) {
diff --git a/src/core/persistence/engine-graduation.ts b/src/core/persistence/engine-graduation.ts
index dc174d7362..ed035bb95f 100644
--- a/src/core/persistence/engine-graduation.ts
+++ b/src/core/persistence/engine-graduation.ts
@@ -112,7 +112,7 @@ export interface GraduationDeps {
initTargetSchema(target: BrainEngine, source: BrainEngine): Promise<void>;
claimAutopilotPause(): Promise<(() => void) | null>;
/** Failing check names of `gbrain doctor --no-migrate --json` against the fenced target. */
- runTargetDoctor(runId: string, mainUrl: string): Promise<{ failing: readonly string[]; exempted: readonly string[] }>;
+ runTargetDoctor(runId: string, mainUrl: string, sourcePersistenceEnabled: boolean): Promise<{ failing: readonly string[]; exempted: readonly string[] }>;
/** Failing source checks, measured with the source open under the run's lock. */
runSourceDoctor(source: BrainEngine): Promise<readonly string[]>;
hostId(): string;
@@ -154,7 +154,7 @@ export function defaultGraduationDeps(): GraduationDeps {
await sized.initSchema(dimensions && model ? { embedding: { dimensions, model } } : {});
},
claimAutopilotPause: () => withStdoutOnStderr(() => quiesceAutopilot()),
- async runTargetDoctor(runId, mainUrl) { return spawnTargetDoctor(runId, mainUrl); },
+ async runTargetDoctor(runId, mainUrl, sourcePersistenceEnabled) { return spawnTargetDoctor(runId, mainUrl, sourcePersistenceEnabled); },
async runSourceDoctor(source) {
// In process, on the engine this run (or plan) already opened; GBRAIN_GRADUATION_RUN keeps doctor read-only.
const { buildChecks } = await import('../../commands/doctor.ts');
@@ -184,10 +184,11 @@ async function withStdoutOnStderr<T>(fn: () => Promise<T>): Promise<T> {
try { return await fn(); } finally { console.log = log; }
}
-function spawnTargetDoctor(runId: string, mainUrl: string): { failing: readonly string[]; exempted: readonly string[] } {
+function spawnTargetDoctor(runId: string, mainUrl: string, sourcePersistenceEnabled: boolean): { failing: readonly string[]; exempted: readonly string[] } {
const script = process.argv[1] && /\.(ts|js|mjs)$/.test(process.argv[1]) ? [process.argv[1]] : [];
const child = spawnSync(process.execPath, [...script, 'doctor', '--no-migrate', '--json', '--scope=brain'], {
- env: { ...process.env, GBRAIN_DATABASE_URL: mainUrl, GBRAIN_GRADUATION_RUN: runId },
+ env: { ...process.env, GBRAIN_DATABASE_URL: mainUrl, GBRAIN_GRADUATION_RUN: runId,
+ GBRAIN_GRADUATION_SOURCE_PERSISTENCE: sourcePersistenceEnabled ? 'enabled' : 'disabled' },
encoding: 'utf8', timeout: 600_000, maxBuffer: 64 * 1024 * 1024,
});
try {
@@ -881,7 +882,8 @@ async function stepVerify(run: Run): Promise<void> {
runId: run.m.runId, expectFence: true,
runDoctor: async () => {
phase(run, 'doctor');
- const doctor = await run.deps.runTargetDoctor(run.m.runId, run.m.targetUrls!.main);
+ const [brain] = await run.source!.executeRaw<{ enabled: boolean }>('SELECT enabled FROM persistence_brain WHERE singleton = 1');
+ const doctor = await run.deps.runTargetDoctor(run.m.runId, run.m.targetUrls!.main, brain?.enabled === true);
exempted = doctor.exempted;
return doctor.failing;
},
diff --git a/src/core/persistence/ownership.ts b/src/core/persistence/ownership.ts
index ef90fbf429..ef3af1f229 100644
--- a/src/core/persistence/ownership.ts
+++ b/src/core/persistence/ownership.ts
@@ -19,6 +19,7 @@ import { assertPhysicalRoot, claimPhysicalRoot, preparePhysicalRootTransfer, rea
import { readPhysicalRootStamp } from './physical-root-record.ts';
import { canonicalFilesystemPath, nativeFilesystemPath } from './root-registry.ts';
import { assertWriterAdminState } from './admin-intent.ts';
+import { readGraduationRow } from './graduation-schema.ts';
import { assertWriterAdminUnlocked } from './admin-lock.ts';
import { inspectPhysicalRootRecovery, repairPhysicalRoot, type PhysicalRootRecovery } from './physical-root-recovery.ts';
@@ -46,6 +47,21 @@ export async function managedPersistenceEnabled(engine: SqlEngine): Promise<bool
const [row] = await engine.executeRaw<{ enabled: boolean }>('SELECT enabled FROM persistence_brain WHERE singleton=1');
return row?.enabled === true;
}
+/**
+ * #6331: the verify-step doctor of an engine graduation runs on the fenced target before cutover sets
+ * `persistence_brain.enabled`. It judges writer ownership from the source's flag, which the parent passes in
+ * GBRAIN_GRADUATION_SOURCE_PERSISTENCE, honored only while the target's graduation row is this run's `verifying` target.
+ */
+export async function graduationVerifyInheritsPersistence(engine: BrainEngine): Promise<boolean> {
+ const runId = process.env.GBRAIN_GRADUATION_RUN;
+ if (process.env.GBRAIN_GRADUATION_SOURCE_PERSISTENCE !== 'enabled' || !runId) return false;
+ const row = await readGraduationRow(engine);
+ return row?.role === 'target' && row.state === 'verifying' && row.run_id === runId;
+}
+/** Whether health checks treat the brain as writer-owned: the brain's own flag, or a graduation verify inheriting the source's. */
+export async function persistenceEnabledForHealth(engine: BrainEngine): Promise<boolean> {
+ return await managedPersistenceEnabled(engine) || await graduationVerifyInheritsPersistence(engine);
+}
export async function getWorktreeBinding(engine: SqlEngine, sourceId: string, hostId: string | null = localHostId()): Promise<WorktreeBinding | null> {
const [row] = await engine.executeRaw<WorktreeBinding>(`SELECT s.source_id,s.source_incarnation,s.worktree_id,s.relative_path,
s.topology_generation::text AS topology_generation,w.owner_host_id,w.owner_epoch::text AS owner_epoch,w.state,
diff --git a/src/core/shared-skills/content-freshness.ts b/src/core/shared-skills/content-freshness.ts
index d9f919a9e3..1ba7785772 100644
--- a/src/core/shared-skills/content-freshness.ts
+++ b/src/core/shared-skills/content-freshness.ts
@@ -1,5 +1,6 @@
import { isAbsolute, resolve } from 'node:path';
import type { BrainEngine } from '../engine.ts';
+import { graduationVerifyInheritsPersistence } from '../persistence/ownership.ts';
export interface OwnedContentFreshness {
sourceId: string;
@@ -21,13 +22,13 @@ export async function ownedContentFreshness(engine: BrainEngine, sourceIds?: str
AND (r.state='recovering' OR r.recovery IS NOT NULL))
+(SELECT COUNT(*) FROM persistence_effects e WHERE e.source_id=s.id AND e.source_incarnation=s.incarnation
AND e.recovery IS NOT NULL))::integer AS recovering
- FROM sources s JOIN persistence_brain p ON p.singleton=1 AND p.enabled
+ FROM sources s JOIN persistence_brain p ON p.singleton=1 AND (p.enabled OR $2::boolean)
JOIN config c ON c.key='shared_skills.content.v1.'||s.id||'.'||s.incarnation::text
JOIN persistence_source_bindings b ON b.source_id=s.id AND b.source_incarnation=s.incarnation
JOIN persistence_worktrees w ON w.id=b.worktree_id AND w.state='active' AND w.owner_host_id IS NOT NULL
JOIN persistence_host_bindings h ON h.worktree_id=w.id AND h.host_id=w.owner_host_id
WHERE NOT s.archived AND s.local_path IS NOT NULL AND ($1::text[] IS NULL OR s.id=ANY($1::text[]))
- AND NOT EXISTS (SELECT 1 FROM source_ingestion_receipts r WHERE r.source_id=s.id AND r.source_incarnation=s.incarnation AND r.profile='company-brain')`, [sourceIds ?? null]);
+ AND NOT EXISTS (SELECT 1 FROM source_ingestion_receipts r WHERE r.source_id=s.id AND r.source_incarnation=s.incarnation AND r.profile='company-brain')`, [sourceIds ?? null, await graduationVerifyInheritsPersistence(engine)]);
const result: OwnedContentFreshness[] = [];
for (const row of rows) {
if (sourceIds && !sourceIds.includes(row.id)) continue;
diff --git a/test/graduation-verify-sync-freshness.test.ts b/test/graduation-verify-sync-freshness.test.ts
new file mode 100644
index 0000000000..30afa68cef
--- /dev/null
+++ b/test/graduation-verify-sync-freshness.test.ts
@@ -0,0 +1,71 @@
+/**
+ * #6331 (P2.13): graduation's verify-step doctor runs on the fenced target while `persistence_brain.enabled` is still
+ * false (cutover sets it), so a writer-owned content directory failed `sync_freshness` as "never been synced" and
+ * blocked the graduation. The parent passes the source's flag; the target honors it only while its graduation row is
+ * this run's `verifying` target. A missing row, another run id, another state or a `disabled` source still fail.
+ */
+import { afterAll, beforeAll, expect, test } from 'bun:test';
+import { randomUUID } from 'node:crypto';
+import { mkdirSync, mkdtempSync, rmSync } from 'node:fs';
+import { join } from 'node:path';
+import { tmpdir } from 'node:os';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import type { BrainEngine } from '../src/core/engine.ts';
+import { claimWorktree } from '../src/core/persistence/ownership.ts';
+import { registerLocalWriter } from '../src/core/persistence/identity.ts';
+import { checkSyncFreshness } from '../src/commands/doctor/checks/extraction-sync.ts';
+import { withEnv } from './helpers/with-env.ts';
+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
+
+const home = mkdtempSync(join(tmpdir(), 'graduation-verify-freshness-'));
+const engines: BrainEngine[] = [];
+let closePg: (() => Promise<void>) | undefined;
+beforeAll(async () => {
+ const lite = new PGLiteEngine(); await lite.connect({}); await lite.initSchema(); engines.push(lite);
+ if (process.env.DATABASE_URL) { const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL); engines.push(pg.engine); closePg = pg.close; }
+}, 120_000);
+afterAll(async () => {
+ for (const engine of engines) await engine.disconnect();
+ await closePg?.();
+ rmSync(home, { recursive: true, force: true });
+});
+
+/** A receipt-proven content directory on a target whose cutover has not happened yet (`enabled=false`). */
+async function fencedTarget(engine: BrainEngine) {
+ const sourceId = `content-${randomUUID().slice(0, 8)}`, root = join(home, sourceId); mkdirSync(root);
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');
+ await engine.executeRaw('INSERT INTO sources(id,name,local_path) VALUES($1,$1,$2)', [sourceId, root]);
+ await registerLocalWriter(engine, 'cli');
+ const binding = await claimWorktree(engine, sourceId, root);
+ const [brain] = await engine.executeRaw<{ brain_id: string }>('SELECT brain_id FROM persistence_brain WHERE singleton=1');
+ await engine.setConfig(`shared_skills.content.v1.${sourceId}.${binding.source_incarnation}`, JSON.stringify({ version: 1, brain_id: brain.brain_id,
+ source_id: sourceId, source_incarnation: binding.source_incarnation, root, owned_root: true, repository_kind: 'content_directory', status: 'ready', stage: 'complete' }));
+ await engine.executeRaw('DELETE FROM persistence_graduation');
+ const runId = randomUUID();
+ await engine.executeRaw("INSERT INTO persistence_graduation(role,run_id,state) VALUES('target',$1::uuid,'verifying')", [runId]);
+ return { sourceId, runId };
+}
+
+test('the verifying target of this run inherits the source flag; every other combination still fails never-synced', async () => withEnv({ GBRAIN_HOME: home }, async () => {
+ for (const engine of engines) {
+ const { sourceId, runId } = await fencedTarget(engine);
+ const freshness = (env: Record<string, string | undefined>) => withEnv({ GBRAIN_HOME: home, ...env }, () => checkSyncFreshness(engine));
+ expect(await freshness({ GBRAIN_GRADUATION_RUN: runId, GBRAIN_GRADUATION_SOURCE_PERSISTENCE: 'enabled' }))
+ .toMatchObject({ status: 'ok', details: { writer_owned_count: 1, stale_count: 0 } });
+ for (const env of [{ GBRAIN_GRADUATION_RUN: runId, GBRAIN_GRADUATION_SOURCE_PERSISTENCE: 'disabled' },
+ { GBRAIN_GRADUATION_RUN: runId, GBRAIN_GRADUATION_SOURCE_PERSISTENCE: undefined },
+ { GBRAIN_GRADUATION_RUN: randomUUID(), GBRAIN_GRADUATION_SOURCE_PERSISTENCE: 'enabled' },
+ { GBRAIN_GRADUATION_RUN: undefined, GBRAIN_GRADUATION_SOURCE_PERSISTENCE: 'enabled' }]) {
+ const check = await freshness(env);
+ expect(check.status).toBe('fail');
+ expect(check.message).toContain(`'${sourceId}' has never been synced`);
+ }
+ for (const row of ["state='verified'", "role='source'"]) {
+ await engine.executeRaw(`UPDATE persistence_graduation SET ${row}`);
+ expect((await freshness({ GBRAIN_GRADUATION_RUN: runId, GBRAIN_GRADUATION_SOURCE_PERSISTENCE: 'enabled' })).status).toBe('fail');
+ await engine.executeRaw("UPDATE persistence_graduation SET state='verifying',role='target'");
+ }
+ await engine.executeRaw('DELETE FROM persistence_graduation');
+ expect((await freshness({ GBRAIN_GRADUATION_RUN: runId, GBRAIN_GRADUATION_SOURCE_PERSISTENCE: 'enabled' })).status).toBe('fail');
+ }
+}), 120_000);