Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(persistence): carry connector holds through sources writer deactivate

garrytand23ce4459233
diff --git a/docs/architecture/topologies.md b/docs/architecture/topologies.md
index 88215f8596..66d4a407e0 100644
--- a/docs/architecture/topologies.md
+++ b/docs/architecture/topologies.md
@@ -558,11 +558,14 @@ dry run first."*
recovery, `gbrain repair embedding-effects --source <id>` for a stuck
embedding effect, `gbrain sources writer retry-effects <source> --request-id <id> --dry-run`
for a failed Git or withdrawal effect, and `gbrain sources writer unlock` for
- the writer admin lock. A held Google or GitHub item is resolved first:
- `gbrain sources status <id>` names its error; fix the cause, then run
- `gbrain sources retry-held <id>` and `gbrain sync --source <id>` (a
- successful re-attempt clears the hold), because classic mode does not read
- managed holds. A live connector or maintenance
+ the writer admin lock. Held Google or GitHub items do not block: deactivate
+ copies each source's managed holds into its classic state file
+ (`.google-source.json` or `.github-source.json`), so they stay held, retried
+ and reported in classic mode; the dry run lists them as `carried_holds`. Only
+ a source with no state directory, or with a classic state file that does not
+ parse, blocks; its exit is to move that file aside, or to resolve the holds
+ (`gbrain sources status <id>`, fix the cause, `gbrain sources retry-held <id>`,
+ `gbrain sync --source <id>`). A live connector or maintenance
lease means waiting for that run. A clean dry run prints `apply_command`,
the deactivate command bound to the state it reviewed.
4. Deactivate: run the printed `apply_command`, or `gbrain sources writer status --json`
diff --git a/src/core/connectors/item-holds-store.ts b/src/core/connectors/item-holds-store.ts
index 22d0bd2caa..a8bf6d84e2 100644
--- a/src/core/connectors/item-holds-store.ts
+++ b/src/core/connectors/item-holds-store.ts
@@ -15,8 +15,10 @@
* writes (op `managed-connector-retry`), so the re-attempt is admitted under a
* new request identity.
*/
-import { existsSync, readFileSync } from 'node:fs';
-import { join } from 'node:path';
+import { existsSync, mkdirSync, readFileSync } from 'node:fs';
+import { dirname, join } from 'node:path';
+import { atomicWriteFileSync } from '../atomic-write.ts';
+import { withFilesystemPublication } from '../persistence/filesystem-guard.ts';
import type { BrainEngine } from '../engine.ts';
import { digest } from '../persistence/digest.ts';
import { connectorCheckpointKey, connectorIdentity, isConnectorSourceKind, type ConnectorKind } from '../persistence/connector-identity.ts';
@@ -35,6 +37,14 @@ export async function managedBrain(engine: Exec): Promise<boolean> {
return brain?.enabled === true;
}
+/** The classic-mode state file of a connector source, or null when it has no state directory. */
+export function classicConnectorStateFile(source: ConnectorSourceRow): string | null {
+ const kind = source.config.kind;
+ if (!isConnectorSourceKind(kind)) return null;
+ const dir = (connectorIdentity(kind, source.config, source.local_path).config as { dir?: string }).dir;
+ return dir ? join(dir, kind === 'google' ? '.google-source.json' : '.github-source.json') : null;
+}
+
/** The connector's cursor state, wherever this brain keeps it. */
export async function readConnectorCursorState(engine: Exec, source: ConnectorSourceRow, managed?: boolean): Promise<Record<string, unknown> | null> {
const kind = source.config.kind;
@@ -46,10 +56,8 @@ export async function readConnectorCursorState(engine: Exec, source: ConnectorSo
[connectorCheckpointKey(source.id, source.incarnation, identity)]);
return row?.completed_keys?.[0]?.state ?? null;
}
- const dir = (identity.config as { dir?: string }).dir;
- if (!dir) return null;
- const file = join(dir, kind === 'google' ? '.google-source.json' : '.github-source.json');
- if (!existsSync(file)) return null;
+ const file = classicConnectorStateFile(source);
+ if (!file || !existsSync(file)) return null;
// A corrupt state file is unknown hold state, not "no holds": the caller reports it.
return JSON.parse(readFileSync(file, 'utf-8')) as Record<string, unknown>;
}
@@ -72,6 +80,59 @@ export async function readAllSourceHolds(engine: Exec, opts: { sourceIds?: strin
return out;
}
+export interface HoldCarry { source_id: string; items: number; state_file: string | null; unreadable?: string }
+
+/**
+ * Managed holds and where classic mode will read them after `sources writer
+ * deactivate`: each source's classic state file (`.google-source.json` /
+ * `.github-source.json`). A source with no state directory, or whose existing
+ * classic state file does not parse, cannot take its holds (`state_file` null
+ * or `unreadable` set). Read-only.
+ */
+export async function planHoldCarry(engine: Exec): Promise<HoldCarry[]> {
+ const sources = await engine.executeRaw<ConnectorSourceRow>(
+ "SELECT id,incarnation::text AS incarnation,local_path,config FROM sources WHERE archived IS NOT TRUE AND config->>'kind' IN ('google','github') ORDER BY id");
+ const out: HoldCarry[] = [];
+ for (const source of sources) {
+ const held = heldItems((await readConnectorCursorState(engine, source, true))?.item_holds);
+ if (!held.length) continue;
+ const file = classicConnectorStateFile(source);
+ let unreadable: string | undefined;
+ if (file && existsSync(file)) {
+ try { JSON.parse(readFileSync(file, 'utf-8')); } catch (e) { unreadable = e instanceof Error ? e.message : String(e); }
+ }
+ out.push({ source_id: source.id, items: held.length, state_file: file, ...(unreadable ? { unreadable } : {}) });
+ }
+ return out;
+}
+
+/**
+ * Copy each source's managed `item_holds` into its classic state file, keeping
+ * every other field of that file, so a held item stays held (and keeps being
+ * retried and reported) after deactivation. Throws for a source planHoldCarry
+ * reports as uncarriable; deactivation refuses those first.
+ */
+export async function carryHoldsToClassicState(engine: Exec): Promise<HoldCarry[]> {
+ const sources = await engine.executeRaw<ConnectorSourceRow>(
+ "SELECT id,incarnation::text AS incarnation,local_path,config FROM sources WHERE archived IS NOT TRUE AND config->>'kind' IN ('google','github') ORDER BY id");
+ const carried: HoldCarry[] = [];
+ for (const source of sources) {
+ const holds = (await readConnectorCursorState(engine, source, true))?.item_holds;
+ const held = heldItems(holds);
+ if (!held.length) continue;
+ const file = classicConnectorStateFile(source);
+ if (!file) throw new Error(`connector source ${source.id} has no state directory for its held items`);
+ const existing = existsSync(file) ? JSON.parse(readFileSync(file, 'utf-8')) as Record<string, unknown> : {};
+ mkdirSync(dirname(file), { recursive: true });
+ // Deactivation holds the worktree locks and the sources rows, so this write is
+ // its publication into a root that is still registered as managed.
+ await withFilesystemPublication([dirname(file)], async () =>
+ atomicWriteFileSync(file, JSON.stringify({ ...existing, item_holds: holds }, null, 2)));
+ carried.push({ source_id: source.id, items: held.length, state_file: file });
+ }
+ return carried;
+}
+
export async function readHoldRetryKeys(engine: Exec, sourceId: string, incarnation: string): Promise<string[]> {
const [row] = await engine.executeRaw<{ completed_keys: Array<{ keys?: unknown }> }>(
'SELECT completed_keys FROM op_checkpoints WHERE op=$1 AND fingerprint=$2', [HOLD_RETRY_OP, connectorStateKey(sourceId, incarnation)]);
diff --git a/src/core/persistence/deactivation.ts b/src/core/persistence/deactivation.ts
index c713c17c03..b9e9cf06bd 100644
--- a/src/core/persistence/deactivation.ts
+++ b/src/core/persistence/deactivation.ts
@@ -37,7 +37,7 @@ import { managedFilesystemDatastorePath, refreshManagedFilesystemRoots } from '.
import { recordTopologyChange } from './topology-receipts.ts';
import { lockTopologyPrincipal, topologyPrincipal } from './topology-locks.ts';
import { canonicalFilesystemPath } from './root-registry.ts';
-import { readAllSourceHolds } from '../connectors/item-holds-store.ts';
+import { carryHoldsToClassicState, planHoldCarry, type HoldCarry } from '../connectors/item-holds-store.ts';
import { PHYSICAL_ROOT_MARKER, physicalRootReservationPath } from './physical-root-record.ts';
export const DEACTIVATE_DOCS = 'docs/architecture/topologies.md#deactivate-runbook';
@@ -68,6 +68,8 @@ export interface DeactivationReport {
source_bindings: number;
kept: { skill_bundles_enabled: boolean; writer_protocol_floor: number; writer_protocol_registrations: number };
blockers: DeactivationBlocker[];
+ /** Held connector items copied (or, on a dry run, to be copied) into each source's classic state file. */
+ carried_holds?: HoldCarry[];
local_markers?: LocalMarkerReport;
}
@@ -113,11 +115,16 @@ export async function deactivationBlockers(engine: BrainEngine): Promise<Deactiv
: e.state === 'failed' ? `gbrain sources writer retry-effects ${e.source_id} --request-id ${e.request_id} --dry-run`
: 'wait for the owner to drain it, then rerun deactivate' });
}
- // Managed connector holds live in the managed checkpoint, which classic mode does not read: a held item outside
- // the classic backfill window would drop out of retries and coverage warnings, so it is resolved first.
- for (const source of await readAllSourceHolds(engine)) {
- blockers.push({ kind: 'connector_holds', id: source.sourceId, source_id: source.sourceId, detail: `${source.held.length} held ${source.kind} item(s)`,
- exit: `gbrain sources status ${source.sourceId} names each item's error; fix its cause, then gbrain sources retry-held ${source.sourceId} and gbrain sync --source ${source.sourceId} (a successful re-attempt clears the hold)` });
+ // Managed connector holds live in the managed checkpoint, which classic mode does not read. Deactivation copies
+ // them into each source's classic state file; only a source whose holds have nowhere to go blocks it.
+ for (const carry of await planHoldCarry(engine)) {
+ if (carry.state_file && !carry.unreadable) continue;
+ const resolve = `gbrain sources status ${carry.source_id} names each item's error; fix its cause, then gbrain sources retry-held ${carry.source_id} and gbrain sync --source ${carry.source_id} (a successful re-attempt clears the hold)`;
+ blockers.push({ kind: 'connector_holds', id: carry.source_id, source_id: carry.source_id,
+ detail: carry.state_file
+ ? `${carry.items} held item(s); the classic state file ${carry.state_file} does not parse (${carry.unreadable})`
+ : `${carry.items} held item(s) and no classic state directory to carry them into`,
+ exit: carry.state_file ? `move ${carry.state_file} aside, then rerun deactivate; or ${resolve}` : resolve });
}
const leases = await engine.executeRaw<{ id: string; holder_host: string; holder_pid: number }>(
'SELECT id, holder_host, holder_pid FROM gbrain_cycle_locks WHERE ttl_expires_at > now() ORDER BY id');
@@ -164,7 +171,10 @@ export async function deactivatePersistence(engine: BrainEngine, opts: { dryRun?
...(opts.dryRun ? {} : { local_markers: await cleanupRetiredManagedMarkers(engine) }) };
}
const blockers = await deactivationBlockers(engine);
- if (opts.dryRun) return { ...base, mode: 'managed', deactivated: false, mode_epoch: Number(brain.mode_epoch), blockers };
+ if (opts.dryRun) {
+ const carried_holds = (await planHoldCarry(engine)).filter(c => c.state_file && !c.unreadable);
+ return { ...base, mode: 'managed', deactivated: false, mode_epoch: Number(brain.mode_epoch), blockers, carried_holds };
+ }
if (blockers.length) throw blockedError(blockers);
const principal = await topologyPrincipal(engine);
const requestId = opts.requestId ?? randomUUID();
@@ -196,6 +206,8 @@ export async function deactivatePersistence(engine: BrainEngine, opts: { dryRun?
await opts.hooks?.afterLocks?.();
const inside = await deactivationBlockers(tx);
if (inside.length) throw blockedError(inside);
+ // Written before commit: if the transaction then fails, the brain stays managed and ignores these files.
+ const carried_holds = await carryHoldsToClassicState(tx);
const retired = await retiredTopology(tx);
const [epoch] = await tx.executeRaw<{ mode_epoch: string }>(
'UPDATE persistence_brain SET enabled=false, mode_epoch=mode_epoch+1 WHERE singleton=1 RETURNING mode_epoch::text');
@@ -210,7 +222,7 @@ export async function deactivatePersistence(engine: BrainEngine, opts: { dryRun?
incarnation: null, worktrees: retired.worktrees.map(w => w.id) }, outcome);
await refreshManagedFilesystemRoots(tx, managedFilesystemDatastorePath(engine));
return { ...base, mode: 'classic' as const, deactivated: true, mode_epoch: Number(epoch.mode_epoch), retired_mode_epoch: Number(current.mode_epoch),
- retired_worktrees: retired.worktrees, source_bindings: retired.bindings, blockers: [] };
+ retired_worktrees: retired.worktrees, source_bindings: retired.bindings, blockers: [], carried_holds };
});
} finally { for (const lock of locks.reverse()) await lock.release(); }
return { ...report, local_markers: await cleanupRetiredManagedMarkers(engine) };
diff --git a/test/fix-wave-4-integration.test.ts b/test/fix-wave-4-integration.test.ts
index 696948d0f0..2853a78d9d 100644
--- a/test/fix-wave-4-integration.test.ts
+++ b/test/fix-wave-4-integration.test.ts
@@ -149,7 +149,7 @@ test('X4: the v0.32.2 facts adoption on a connector page publishes above the tim
}
}), 240_000);
-test('X6: deactivate refuses while a connector item is held (classic mode cannot read managed holds); after the printed exit it succeeds and the dispatch gate stays open', async () => withEnv(env, async () => {
+test('X6: deactivate carries a held connector item into classic state (wave 5): it stays held after the mode change, the retry-held exit still clears it, and the dispatch gate stays open', async () => withEnv(env, async () => {
const account = '[email protected]';
const gmailConfig = { kind: 'google', g_account: account, g_services: 'gmail', g_access: 'env', g_token_env: 'CONNECTOR_TEST_TOKEN' };
for (const engine of engines) {
@@ -166,27 +166,29 @@ test('X6: deactivate refuses while a connector item is held (classic mode cannot
const settle = () => engine.transaction(async tx => { await declarePersistenceProtocol(tx); await tx.executeRaw("UPDATE persistence_effects SET state='committed' WHERE state<>'committed'"); });
await settle();
- const dry = await runPersistenceAdministration(engine, 'writer_deactivate', { dry_run: true }) as { blockers: Array<{ kind: string; source_id?: string; exit: string }>; apply_command?: string };
- const held = dry.blockers.find(b => b.kind === 'connector_holds');
- expect(held).toMatchObject({ source_id: f.id, exit: expect.stringContaining(`gbrain sources retry-held ${f.id}`) });
- expect(dry.apply_command).toBeUndefined();
- await expect(runPersistenceAdministration(engine, 'writer_deactivate', { admin_intent: 'writer_deactivate', expected_state: await writerAdminState(engine) }))
- .rejects.toMatchObject({ code: 'writer_not_quiesced' });
+ // The held item no longer blocks: the dry run names where it will be carried and prints the apply command.
+ const dry = await runPersistenceAdministration(engine, 'writer_deactivate', { dry_run: true }) as {
+ blockers: Array<{ kind: string; source_id?: string }>; apply_command?: string; carried_holds?: Array<{ source_id: string; items: number; state_file: string }> };
+ expect(dry.blockers.filter(b => b.kind === 'connector_holds' && b.source_id === f.id)).toEqual([]);
+ expect(dry.carried_holds).toContainEqual({ source_id: f.id, items: 1, state_file: join(f.dir, '.google-source.json') });
+ const expected = /--expected-state ([a-f0-9]{64})$/.exec(dry.apply_command ?? '')?.[1];
+ expect(expected).toBeDefined();
+ const done = await runPersistenceAdministration(engine, 'writer_deactivate', { admin_intent: 'writer_deactivate', expected_state: expected }) as Record<string, unknown>;
+ expect(done).toMatchObject({ mode: 'classic', deactivated: true });
+ expect(done.carried_holds).toContainEqual({ source_id: f.id, items: 1, state_file: join(f.dir, '.google-source.json') });
+
+ // Classic mode reads the carried hold, and a classic run keeps it held while the upstream error persists.
+ expect((await readAllSourceHolds(engine, { sourceIds: [f.id] }))[0]?.held.map(h => h.key)).toEqual(['a1b2c3d4e5f60302']);
+ await run();
+ expect((await readAllSourceHolds(engine, { sourceIds: [f.id] }))[0]?.held.map(h => h.key)).toEqual(['a1b2c3d4e5f60302']);
- // The printed exit: retry the held thread (recovered upstream) and sync; the hold clears and deactivate proceeds.
+ // The printed exit still works in classic mode: retry the held thread (recovered upstream) and sync; the hold clears.
await retryHeld(engine, f.id);
fx.failThreads.delete('a1b2c3d4e5f60302');
fx.fetched.length = 0;
expect((await run()).status).not.toBe('partial');
- await disposePersistenceConsumer(engine);
expect(fx.fetched).toContain('a1b2c3d4e5f60302');
expect(await readAllSourceHolds(engine, { sourceIds: [f.id] })).toEqual([]);
- await settle();
- const clean = await runPersistenceAdministration(engine, 'writer_deactivate', { dry_run: true }) as { apply_command?: string };
- const expected = /--expected-state ([a-f0-9]{64})$/.exec(clean.apply_command ?? '')?.[1];
- expect(expected).toBeDefined();
- const done = await runPersistenceAdministration(engine, 'writer_deactivate', { admin_intent: 'writer_deactivate', expected_state: expected }) as Record<string, unknown>;
- expect(done).toMatchObject({ mode: 'classic', deactivated: true });
// Lane B's gate survives Lane D's mode change: autopilot keeps dispatching the connector.
expect((await attemptedConnectorSourceIds(engine)).has(f.id)).toBe(true);