Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(autopilot): automatic sync never requests a git pull for a managed source (#5463)

time-attack9eac482f0fa3
diff --git a/src/commands/autopilot-dispatch.ts b/src/commands/autopilot-dispatch.ts
index 8d81b775c4..30b624bb7b 100644
--- a/src/commands/autopilot-dispatch.ts
+++ b/src/commands/autopilot-dispatch.ts
@@ -9,6 +9,7 @@ import type { MinionQueue } from '../core/minions/queue.ts';
import { loadAllSources, parseSourceConfig, sourceConfigHasRemoteUrl, sourceLocalPathSkipWarning, type SourceRow } from '../core/sources-load.ts';
import { isConnectorSourceKind } from '../core/persistence/connector-identity.ts';
import { attemptedConnectorSourceIds } from '../core/persistence/connector-state.ts';
+import { automaticSyncPull } from '../core/persistence/automatic-sync-policy.ts';
import { isSyncDisabledConfig } from '../core/sync-policy.ts';
import { loadActivationPendingSourceIds, skipActivationPendingSync } from '../core/sync-policy.ts';
import { resolveAutopilotDispatchTimeoutMs } from './autopilot-timeout.ts';
@@ -296,7 +297,7 @@ export async function dispatchFreshnessSyncs(
{
sourceId: src.id,
repoPath: src.local_path,
- pull: sourceConfigHasRemoteUrl(src.config),
+ pull: await automaticSyncPull(engine, src),
auto_embed_backfill: true,
embed_reason: 'autopilot_freshness',
},
diff --git a/src/commands/autopilot-fanout.ts b/src/commands/autopilot-fanout.ts
index 213ff5d751..5e6964baa6 100644
--- a/src/commands/autopilot-fanout.ts
+++ b/src/commands/autopilot-fanout.ts
@@ -10,8 +10,8 @@
* - P0-5: each per-source cycle writes `last_full_cycle_at` in its
* `sources.config` JSONB on success (handled in `runCycle` exit hook,
* not here — this module just READS it for freshness gating).
- * - P1-2: explicitly threads `pull: !!source.config.remote_url` so
- * local-only sources don't try to git-pull.
+ * - P1-2: automatic pull needs a remote and an unmanaged source
+ * (`automaticSyncPull`), so local-only and managed sources never git-pull.
* - P1-3: PGLite engines default `fanoutMax=1` (PGLite is single-writer;
* parallel fan-out would queue uselessly behind the file lock).
* - P1-4: enumeration keeps sources with a `local_path`, so pure-DB
@@ -42,7 +42,8 @@ import { SOURCE_FRESHNESS_PHASES, MAINTENANCE_PHASES, LAST_GLOBAL_AT_KEY } from
import { CONNECTOR_SOURCE_PHASES } from '../core/cycle/phase-scope.ts';
import { isConnectorSourceKind } from '../core/persistence/connector-identity.ts';
import { attemptedConnectorSourceIds } from '../core/persistence/connector-state.ts';
-import { parseSourceConfig, sourceConfigHasRemoteUrl, sourceLocalPathSkipWarning } from '../core/sources-load.ts';
+import { parseSourceConfig, sourceLocalPathSkipWarning } from '../core/sources-load.ts';
+import { automaticSyncPull } from '../core/persistence/automatic-sync-policy.ts';
import { isSyncDisabledConfig } from '../core/sync-policy.ts';
import { loadActivationPendingSourceIds, skipActivationPendingSync } from '../core/sync-policy.ts';
import { AUTOPILOT_FULL_CYCLE_FLOOR_MINUTES } from './autopilot-remediation-policy.ts';
@@ -580,7 +581,7 @@ export async function dispatchPerSource(
);
const syncDisabled = isSyncDisabledConfig(src.config) || pendingActivation;
const connector = connectorIds.has(src.id);
- const shouldPull = sourceConfigHasRemoteUrl(src.config) && !syncDisabled && !connector;
+ const shouldPull = !syncDisabled && !connector && await automaticSyncPull(engine, src);
const job = await queue.add(
'autopilot-cycle',
{
diff --git a/src/core/cli-flag-registry.generated.ts b/src/core/cli-flag-registry.generated.ts
index 3477181d02..68116800a9 100644
--- a/src/core/cli-flag-registry.generated.ts
+++ b/src/core/cli-flag-registry.generated.ts
@@ -19,7 +19,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'anomalies': ['--brain', '--help', '--json', '--lookback-days', '--mcp-only', '--sigma', '--since', '--source'],
'apply-migrations': ['--accept-reviewed-inventory', '--acknowledge-no-backup', '--apply', '--backup-confirmed', '--brain', '--break-lock', '--confirm-quiesced', '--content-root', '--dry-run', '--export-db-only', '--export-source', '--force', '--force-all', '--force-orchestrator', '--force-retry', '--force-schema', '--help', '--host-dir', '--http', '--json', '--list', '--locks', '--migrate-only', '--migration', '--mode', '--no-autopilot-install', '--non-interactive', '--probe', '--require-db', '--skip-verify', '--source', '--uninstall', '--yes'],
'auth': ['--add', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--all-new', '--allowed-operations', '--before', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--budget-usd-per-day', '--cleanup-dead-local-locks', '--client', '--confirm-quiesced', '--days', '--delegated-namespace', '--delegated-slug-prefixes', '--dry-run', '--enable-dcr-insecure', '--expected-epoch', '--expected-state', '--federated-read', '--fix', '--force', '--grant-types', '--help', '--id', '--if-version', '--json', '--limit', '--manifest', '--max-concurrent', '--migrate-legacy', '--no-pull', '--operations', '--path', '--probe', '--profile', '--read-sources', '--redirect-uri', '--refresh-operations', '--repair', '--replace', '--request-id', '--reset-default', '--retry-failed', '--scopes', '--self-transfer', '--shared-skills', '--slug-prefixes', '--source', '--source-ids', '--sources', '--surface', '--takes-holders', '--token', '--token-endpoint-auth-method', '--token-ttl', '--usage', '--yes'],
- 'autopilot': ['--apply', '--batch', '--brain', '--check', '--dimensions', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--expect', '--explain', '--ff-only', '--force', '--force-retry', '--from-pages', '--help', '--inject-bootstrap', '--inline', '--install', '--interval', '--json', '--markdown', '--max-cost', '--max-rss', '--max-runtime', '--max-usd', '--migrate-only', '--model', '--no-autopilot-install', '--no-bun-floor-check', '--no-embed-cache', '--no-inject', '--no-worker', '--non-interactive', '--now', '--once', '--only', '--output', '--params', '--path', '--pause', '--phase', '--reason', '--refresh-cache', '--remediation-plan', '--repo', '--resume', '--slot-a-model', '--slot-b-model', '--slot-c-model', '--source', '--stale', '--status', '--swap-only', '--target', '--trust', '--uninstall', '--user', '--verify', '--version', '--yes'],
+ 'autopilot': ['--apply', '--batch', '--brain', '--check', '--dimensions', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--expect', '--explain', '--ff-only', '--force', '--force-retry', '--from-pages', '--help', '--inject-bootstrap', '--inline', '--install', '--interval', '--json', '--markdown', '--max-cost', '--max-rss', '--max-runtime', '--max-usd', '--migrate-only', '--model', '--no-autopilot-install', '--no-bun-floor-check', '--no-embed-cache', '--no-inject', '--no-worker', '--non-interactive', '--now', '--once', '--only', '--output', '--params', '--path', '--pause', '--phase', '--probe', '--reason', '--refresh-cache', '--remediation-plan', '--repo', '--resume', '--slot-a-model', '--slot-b-model', '--slot-c-model', '--source', '--stale', '--status', '--swap-only', '--target', '--trust', '--uninstall', '--user', '--verify', '--version', '--yes'],
'backfill': ['--batch-size', '--brain', '--concurrency', '--dry-run', '--fresh', '--help', '--json', '--keep-index', '--list', '--max-errors', '--max-rows', '--resume', '--source'],
'backup': ['--accept-pending', '--background', '--brain', '--confirm-authority-reviewed', '--confirm-backup-compatible', '--confirm-quiesced', '--dir', '--explain', '--follow', '--full', '--help', '--into', '--json', '--mode', '--no-accept-pending', '--output', '--path', '--progress-interval', '--progress-json', '--quiet', '--restore-only', '--source', '--timeout', '--wait'],
'bench': ['--baseline', '--brain', '--force', '--from', '--help', '--json', '--label', '--limit', '--source', '--threshold-jaccard', '--threshold-latency-multiplier', '--threshold-top1', '--to', '--tool'],
diff --git a/src/core/persistence/automatic-sync-policy.ts b/src/core/persistence/automatic-sync-policy.ts
new file mode 100644
index 0000000000..c4d9143d48
--- /dev/null
+++ b/src/core/persistence/automatic-sync-policy.ts
@@ -0,0 +1,28 @@
+import { opError } from '../ops/contract.ts';
+import { readFix } from '../ops/op-fix.ts';
+import { sourceConfigHasRemoteUrl } from '../sources-load.ts';
+import type { SqlEngine } from './model.ts';
+import { getWorktreeBinding } from './ownership.ts';
+
+/**
+ * Whether an automatic sync (autopilot freshness or per-source fanout) may
+ * request a Git pull for `source`. It needs a remote URL plus positive proof of
+ * an unmanaged source: exactly one boolean persistence state that is off, and
+ * no worktree binding. A managed brain or a claimed source syncs local HEAD
+ * without pulling; missing or malformed persistence metadata refuses instead of
+ * granting a pull. Explicit `gbrain sync` intent is resolved elsewhere.
+ */
+export async function automaticSyncPull(engine: SqlEngine, source: { id: string; config: unknown }): Promise<boolean> {
+ if (!sourceConfigHasRemoteUrl(source.config)) return false;
+ const rows = await engine.executeRaw<{ enabled: unknown }>('SELECT enabled FROM persistence_brain WHERE singleton=1');
+ if (rows.length !== 1 || typeof rows[0]?.enabled !== 'boolean') {
+ throw opError('storage_error', 'Automatic sync requires exactly one known boolean persistence state.',
+ `Run the read-only probe in fix on the brain host and fix the persistence state it reports; automatic sync of ${source.id} resumes on the next tick.`, {
+ why: `The persistence_brain singleton is missing, duplicated or not a boolean, so gbrain cannot tell whether ${source.id} is a managed canonical checkout; automatic sync is not queued rather than risk a Git pull over it.`,
+ fix: { ...readFix('Shows the brain\'s persistence mode and each source\'s writer binding without changing anything.',
+ { argv: ['gbrain', 'sources', 'writer', 'status', '--probe', '--json'] }), verify: { argv: ['gbrain', 'doctor', '--json'] } },
+ });
+ }
+ if (rows[0].enabled) return false;
+ return await getWorktreeBinding(engine, source.id, null) === null;
+}
diff --git a/test/automatic-sync-pull-policy.test.ts b/test/automatic-sync-pull-policy.test.ts
new file mode 100644
index 0000000000..c72ad7ede0
--- /dev/null
+++ b/test/automatic-sync-pull-policy.test.ts
@@ -0,0 +1,145 @@
+/**
+ * #5463 (automatic-pull half): automatic sync never requests a Git pull for a
+ * managed canonical source, and missing or malformed persistence metadata
+ * refuses instead of granting one.
+ *
+ * Protects: autopilot freshness `sync` jobs and per-source fanout cycles on a
+ * managed brain, which managed sync refuses outright when they carry a pull.
+ * Fails when: the pull flag is derived from `remote_url` alone again.
+ * Why new: the fanout's #5255 cycle-side skip never covered the freshness
+ * `sync` job, and the activation-pending lookup fails open on bad metadata.
+ */
+import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';
+import { mkdtempSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { resetPgliteState } from './helpers/reset-pglite.ts';
+import { MinionQueue } from '../src/core/minions/queue.ts';
+import { LATEST_VERSION } from '../src/core/migrate.ts';
+import { dispatchFreshnessSyncs } from '../src/commands/autopilot-dispatch.ts';
+import { dispatchPerSource } from '../src/commands/autopilot-fanout.ts';
+import { automaticSyncPull } from '../src/core/persistence/automatic-sync-policy.ts';
+import { renderCliError } from '../src/core/agent-output.ts';
+import type { SqlEngine } from '../src/core/persistence/model.ts';
+
+const REMOTE = { remote_url: 'https://example.invalid/acme-example.git' };
+
+function stub(singleton: readonly unknown[], claimed = false, fail = false): SqlEngine {
+ return { executeRaw: async (sql: string) => {
+ if (fail) throw new Error('synthetic metadata unavailable');
+ if (sql.includes('FROM persistence_brain')) return singleton;
+ if (sql.includes('FROM persistence_source_bindings')) return claimed ? [{ source_id: 'example' }] : [];
+ throw new Error(`unexpected query: ${sql}`);
+ } } as unknown as SqlEngine;
+}
+
+describe('automaticSyncPull', () => {
+ test('pull needs a remote, an unmanaged brain and no binding; clone and immutable flags grant nothing', async () => {
+ for (const encoded of [false, true]) {
+ const config = { ...REMOTE, immutable: true, managed_clone: true, federated: false };
+ const source = { id: 'example', config: encoded ? JSON.stringify(config) : config };
+ expect(await automaticSyncPull(stub([{ enabled: false }]), source)).toBe(true);
+ expect(await automaticSyncPull(stub([{ enabled: false }], true), source)).toBe(false);
+ expect(await automaticSyncPull(stub([{ enabled: true }]), source)).toBe(false);
+ expect(await automaticSyncPull(stub([{ enabled: true }], true), source)).toBe(false);
+ }
+ expect(await automaticSyncPull(stub([], false, true), { id: 'example', config: {} })).toBe(false);
+ });
+
+ test('a metadata read failure propagates instead of falling back to a pull', async () => {
+ await expect(automaticSyncPull(stub([], false, true), { id: 'example', config: REMOTE })).rejects.toThrow('synthetic metadata unavailable');
+ });
+
+ for (const [label, singleton] of [
+ ['missing', []], ['null row', [null]], ['missing enabled', [{}]], ['null enabled', [{ enabled: null }]],
+ ['string false', [{ enabled: 'false' }]], ['numeric false', [{ enabled: 0 }]], ['ambiguous', [{ enabled: false }, { enabled: true }]],
+ ] as const) {
+ test(`refuses ${label} persistence metadata`, async () => {
+ await expect(automaticSyncPull(stub(singleton), { id: 'example', config: REMOTE })).rejects.toMatchObject({ code: 'storage_error' });
+ });
+ }
+
+ test('the refusal renders the agent contract with a read-only probe and verify', async () => {
+ const error = await automaticSyncPull(stub([]), { id: 'example', config: REMOTE }).catch((e: unknown) => e);
+ const json = renderCliError(error, { json: true, command: 'autopilot', tty: false });
+ const env = JSON.parse(json.stdout!);
+ expect(env.code).toBe('storage_error');
+ expect(env.message).toBe('Automatic sync requires exactly one known boolean persistence state.');
+ expect(env.why).toContain('rather than risk a Git pull');
+ expect(env.fix).toMatchObject({
+ next: 'run', command: 'gbrain sources writer status --probe --json', consent: [], actor: 'agent',
+ verify: { argv: ['gbrain', 'doctor', '--json'] },
+ });
+ expect(renderCliError(error, { json: false, command: 'autopilot', tty: false }).stderr)
+ .toContain('Fix: gbrain sources writer status --probe --json');
+ });
+});
+
+describe('automatic dispatch on a real brain', () => {
+ let engine: PGLiteEngine;
+ let dir: string;
+
+ beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+ });
+
+ afterAll(async () => {
+ await engine.disconnect();
+ });
+
+ beforeEach(async () => {
+ await resetPgliteState(engine);
+ await engine.setConfig('version', String(LATEST_VERSION));
+ dir = mkdtempSync(join(tmpdir(), 'gbrain-5463-'));
+ await engine.executeRaw('INSERT INTO sources (id, name, local_path, config) VALUES ($1, $1, $2, $3::text::jsonb)',
+ ['notes', dir, JSON.stringify(REMOTE)]);
+ });
+
+ const setManaged = (enabled: boolean) => engine.executeRaw('UPDATE persistence_brain SET enabled=$1 WHERE singleton=1', [enabled]);
+ const queued = () => engine.executeRaw<{ name: string; data: Record<string, unknown> }>('SELECT name, data FROM minion_jobs ORDER BY id');
+ const freshness = async () => {
+ const write = process.stderr.write.bind(process.stderr);
+ const log = console.log;
+ (process.stderr as { write: unknown }).write = () => true;
+ console.log = () => {};
+ try {
+ await dispatchFreshnessSyncs(engine, new MinionQueue(engine), { baseInterval: 60, slot: `slot-${Math.random()}`, timeoutMs: 60_000, jsonMode: true });
+ } finally {
+ (process.stderr as { write: unknown }).write = write;
+ console.log = log;
+ }
+ };
+ const fanout = (events: string[] = []) => dispatchPerSource(engine, new MinionQueue(engine),
+ { repoPath: dir, slot: 's', timeoutMs: 60_000, fanoutMax: 10, jsonMode: true, emit: (line) => events.push(line), log: () => {} });
+
+ test('an unmanaged brain still pulls a remote source in both loops', async () => {
+ await freshness();
+ await fanout();
+ const jobs = await queued();
+ expect(jobs.map(j => [j.name, j.data.pull])).toEqual([['sync', true], ['autopilot-cycle', true]]);
+ });
+
+ test('a managed brain still syncs the source in both loops, but never requests a pull', async () => {
+ await setManaged(true);
+ await freshness();
+ await fanout();
+ const jobs = await queued();
+ expect(jobs.map(j => [j.name, j.data.pull])).toEqual([['sync', false], ['autopilot-cycle', false]]);
+ expect(jobs[1].data.phases).toContain('sync');
+ });
+
+ test('missing persistence metadata queues nothing for the remote source and reports why', async () => {
+ await engine.executeRaw('DELETE FROM persistence_brain');
+ const events: string[] = [];
+ await freshness();
+ const result = await fanout(events);
+ expect(await queued()).toEqual([]);
+ expect(result.dispatched).toEqual([]);
+ expect(events.map(line => JSON.parse(line))).toContainEqual(expect.objectContaining({
+ event: 'fanout_submit_failed', source_id: 'notes', error: 'Automatic sync requires exactly one known boolean persistence state.',
+ }));
+ });
+});
diff --git a/test/autopilot-fanout-wiring.test.ts b/test/autopilot-fanout-wiring.test.ts
index 654920bf36..ca64c62f29 100644
--- a/test/autopilot-fanout-wiring.test.ts
+++ b/test/autopilot-fanout-wiring.test.ts
@@ -112,11 +112,11 @@ describe('autopilot.ts ↔ dispatchPerSource wiring', () => {
expect(DISPATCH_SRC).toMatch(/event: 'dispatch_coalesced',[\s\S]{0,80}mode: 'targeted'/);
});
- test('freshness sync dispatch uses the parsed source config for pull policy', () => {
+ test('freshness sync dispatch uses the automatic pull policy (#5463)', () => {
const freshnessIdx = DISPATCH_SRC.indexOf('idempotency_key: `autopilot-sync:');
expect(freshnessIdx).toBeGreaterThan(-1);
const freshnessBlock = DISPATCH_SRC.slice(Math.max(0, freshnessIdx - 700), freshnessIdx + 200);
- expect(freshnessBlock).toContain('pull: sourceConfigHasRemoteUrl(src.config)');
+ expect(freshnessBlock).toContain('pull: await automaticSyncPull(engine, src)');
});
test('freshness sync dispatch skips unavailable source paths before enqueueing', () => {
diff --git a/test/autopilot-fanout.test.ts b/test/autopilot-fanout.test.ts
index 465b132a9f..4ba8ff1c8d 100644
--- a/test/autopilot-fanout.test.ts
+++ b/test/autopilot-fanout.test.ts
@@ -229,6 +229,8 @@ describe('dispatchPerSource — integration with stubbed engine + queue', () =>
let nextId = 100;
const engine = {
kind: 'postgres' as const,
+ // An unmanaged brain with no worktree bindings: automatic pull follows remote_url (#5463).
+ executeRaw: async (sql: string) => (sql.includes('FROM persistence_brain') ? [{ enabled: false }] : []),
listAllSources: async () => {
if (opts?.listError) throw opts.listError;
if (opts?.listThrows) throw new Error('sources table missing');
@@ -445,7 +447,10 @@ describe('dispatchPerSource — integration with stubbed engine + queue', () =>
const claimed = src('claimed-5198', undefined, { remote_url: 'https://github.com/x/y' });
const normal = src('normal-5198', undefined, { remote_url: 'https://github.com/x/y' });
const { engine, queue, added, events, fanoutOpts } = makeStubs([claimed, normal]);
- (engine as unknown as { executeRaw: () => Promise<unknown[]> }).executeRaw = async () => [{ source_id: 'claimed-5198' }];
+ // Unmanaged brain; claimed-5198 is bound (activation pending), normal-5198 is not.
+ (engine as unknown as { executeRaw: (sql: string, params?: unknown[]) => Promise<unknown[]> }).executeRaw = async (sql, params) =>
+ sql.startsWith('SELECT enabled FROM persistence_brain') ? [{ enabled: false }]
+ : sql.includes('WHERE s.source_id=$1') && params?.[0] !== 'claimed-5198' ? [] : [{ source_id: 'claimed-5198' }];
await dispatchPerSource(engine, queue, fanoutOpts);
const byId = new Map<string, AddedJob>(
added.map(j => [(j.data as Record<string, unknown>).source_id as string, j]),