Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix: one checkout's unexpected error no longer stops git-reconcile for the other checkouts
garrytan5ccd5233b064
diff --git a/src/commands/sources-git-reconcile.ts b/src/commands/sources-git-reconcile.tsindex a0b356517a..708d719ec9 100644--- a/src/commands/sources-git-reconcile.ts+++ b/src/commands/sources-git-reconcile.ts@@ -20,6 +20,7 @@ import { gitTopLevel } from '../core/persistence/git-gap.ts';import { sourceConfigHasRemoteUrl } from '../core/sources-load.ts';import { isSyncDisabledConfig } from '../core/sync-policy.ts';import { OperationError } from '../core/ops/contract.ts';+import { classifyItemFailure, type ClassifiedItemFailure } from '../core/item-failure.ts';import { existingHostIdFor } from '../core/persistence/identity.ts';import { getWorktreeBinding, managedPersistenceEnabled } from '../core/persistence/ownership.ts';import { REFRESH_PUBLISH_DIVERGED_KEY, refreshWorktree } from '../core/persistence/worktree-refresh.ts';@@ -38,6 +39,14 @@ export interface SourceReconcile {export interface ReconcileOptions { sourceIds?: string[]; dryRun?: boolean; waitMs?: number; sleep?: (ms: number) => Promise<void>; childTimeoutMs?: number }+const refreshBusy = (error: unknown) => error instanceof OperationError && error.code === 'refresh_in_progress';++function groupRefusal(error: unknown, failure: ClassifiedItemFailure): Pick<SourceReconcile, 'status' | 'error'> {+ if (!(error instanceof OperationError)) return { status: failure.class === 'transient' ? 'failed' : 'needs_user', error: { code: failure.code, message: failure.message } };+ return { status: RETRYABLE.has(error.code) ? 'failed' : 'needs_user',+ error: { code: error.code, message: error.message, ...(error.suggestion ? { suggestion: error.suggestion } : {}), ...(error.fix ? { fix: error.fix } : {}) } };+}+async function reconcileManaged(engine: BrainEngine, sourceId: string, root: string, publish: boolean, opts: ReconcileOptions): Promise<Omit<SourceReconcile, 'sources' | 'root' | 'managed'>> {const level = await fetchLevel(root, gitReader(root));if (!level) return { status: 'no_upstream', ahead: 0, behind: 0 };@@ -52,7 +61,7 @@ async function reconcileManaged(engine: BrainEngine, sourceId: string, root: strreturn { status: done.published ? 'published' : 'fast_forwarded', ahead: level.ahead, behind: level.behind, sha: done.target_head ?? undefined, refresh_id: done.refresh_id,...(done.published ? { integrated: done.published.integrated } : {}) };} catch (error) {- if (!(error instanceof OperationError) || error.code !== 'refresh_in_progress' || Date.now() >= deadline) throw error;+ if (!refreshBusy(error) || Date.now() >= deadline) throw error;await sleep(2000);const again = await fetchLevel(root, gitReader(root));if (again && !again.ahead && !again.behind) return { status: 'in_sync', ahead: 0, behind: 0, sha: again.target };@@ -94,10 +103,10 @@ export async function reconcileSources(engine: BrainEngine, opts: ReconcileOptio...(publishSetting === null && !cloned ? { unpublishedReason: `gbrain did not clone this checkout for the source (no recorded remote, or the source folder is not the repository root); publish it with gbrain git commit-push --push-only --scan-secrets --path ${group.root}, or set ${REFRESH_PUBLISH_DIVERGED_KEY} true to publish such checkouts automatically` } : {}) });out.push({ ...entry, ...result });} catch (error) {- if (!(error instanceof OperationError)) throw error;+ const failure = classifyItemFailure(error);+ if (!(error instanceof OperationError) && failure.scope === 'run') throw error;const { cloned: _cloned, ...entry } = group;- out.push({ ...entry, status: RETRYABLE.has(error.code) ? 'failed' : 'needs_user', ahead: 0, behind: 0,- error: { code: error.code, message: error.message, ...(error.suggestion ? { suggestion: error.suggestion } : {}), ...(error.fix ? { fix: error.fix } : {}) } });+ out.push({ ...entry, ahead: 0, behind: 0, ...groupRefusal(error, failure) });}}return out;diff --git a/src/core/git/reconcile.ts b/src/core/git/reconcile.tsindex d4aea0255d..a14e4884e7 100644--- a/src/core/git/reconcile.ts+++ b/src/core/git/reconcile.ts@@ -101,6 +101,8 @@ export async function commitPushChild(root: string, args: string[], timeoutMs ='Retry: a reconcile of a level checkout reports in_sync.', { retryable: true });}+const remoteMovedUnderPush = (error: unknown) => error instanceof OperationError && error.code === 'push_unconfirmed' && /after --expect-remote/.test(error.message);+export async function reconcileCheckout(root: string, opts: ReconcileCheckoutOptions = {}): Promise<CheckoutReconcile> {if (classifyGitCheckout(root) === 'not_git') return { root, status: 'no_repo', ahead: 0, behind: 0 };return withReconcileLock(root, opts.waitMs ?? 300_000, () => reconcileLocked(root, opts));@@ -131,7 +133,7 @@ async function reconcileLocked(root: string, opts: ReconcileCheckoutOptions): Prreturn { root, status: pushed.checkout === 'lagging' ? 'lagging' : 'published', ahead, behind, ...(typeof pushed.sha === 'string' ? { sha: pushed.sha } : {}),integrated: Number(pushed.integrated) || 0, ...(typeof pushed.lagging_reason === 'string' ? { reason: pushed.lagging_reason } : {}) };} catch (error) {- if (attempt >= MOVED_REMOTE_ATTEMPTS || !(error instanceof OperationError) || error.code !== 'push_unconfirmed' || !/after --expect-remote/.test(error.message)) throw error;+ if (attempt >= MOVED_REMOTE_ATTEMPTS || !remoteMovedUnderPush(error)) throw error;}}}diff --git a/test/cli-flag-equals.test.ts b/test/cli-flag-equals.test.tsindex 7503061a5a..42b9968edf 100644--- a/test/cli-flag-equals.test.ts+++ b/test/cli-flag-equals.test.ts@@ -407,6 +407,8 @@ describe('#7619 split rules', () => {'src/core/git-remote.ts': 'git child argv','src/core/git/commit-push.ts': 'git child argv','src/core/git/range-secret-scan.ts': 'git child argv',+ 'src/core/git/reconcile.ts': 'git child argv',+ 'src/core/git/upstream-history.ts': 'git child argv','src/core/hardened-git.ts': 'git child argv (the reason-trailer log options)','src/core/persistence/checkout-state.ts': 'git child argv','src/core/persistence/effect-git.ts': 'git child argv',diff --git a/test/sources-git-reconcile.test.ts b/test/sources-git-reconcile.test.tsindex 3d583dcdc8..5ff844b95b 100644--- a/test/sources-git-reconcile.test.ts+++ b/test/sources-git-reconcile.test.ts@@ -203,9 +203,16 @@ test('managed worktree: Git durability on publishes through refresh and a repeat}})(), 240_000);+let plain: PGLiteEngine;+beforeAll(async () => { plain = new PGLiteEngine(); await plain.connect({}); await plain.initSchema(); }, 60_000);+afterAll(async () => { await plain.disconnect(); });+const resetPlain = async () => {+ await plain.executeRaw(`DELETE FROM sources WHERE id <> 'default'`);+ await plain.unsetConfig(REFRESH_PUBLISH_DIVERGED_KEY);+};+test('a brain whose sources have no Git checkout reports no_repo', async () => {- const engine = new PGLiteEngine();- await engine.connect({}); await engine.initSchema();+ const engine = plain;try {const path = join(dir, 'plain-source');mkdirSync(path, { recursive: true });@@ -217,12 +224,11 @@ test('a brain whose sources have no Git checkout reports no_repo', async () => {console.log = (...args: unknown[]) => { printed.push(args.join(' ')); };try { await runSources(engine, ['git-reconcile', 'plain-source', '--json']); } finally { console.log = log; }expect(JSON.parse(printed.join('\n'))).toEqual({ results: [{ sources: [], root: '', managed: false, status: 'no_repo', ahead: 0, behind: 0 }], exit: 0 });- } finally { await engine.disconnect(); }+ } finally { await resetPlain(); }}, 60_000);test('with automatic publishing turned off, local commits stay unpublished while a checkout behind still fast-forwards', async () => {- const engine = new PGLiteEngine();- await engine.connect({}); await engine.initSchema();+ const engine = plain;try {const r = repo('optout');await engine.executeRaw('INSERT INTO sources(id,name,local_path,config) VALUES($1,$1,$2,$3::jsonb)', ['optout-source', r.root, JSON.stringify({ remote_url: r.remote })]);@@ -236,12 +242,11 @@ test('with automatic publishing turned off, local commits stay unpublished whileawait engine.setConfig(REFRESH_PUBLISH_DIVERGED_KEY, '');expect(await reconcileAll(engine)).toMatchObject([{ sources: ['optout-source'], status: 'published', ahead: 1 }]);expect(tip(r)).toBe(local);- } finally { await engine.disconnect(); }+ } finally { await resetPlain(); }}, 120_000);test('a checkout gbrain did not clone for the source is never published by default; a sync-disabled or missing source is skipped', async () => {- const engine = new PGLiteEngine();- await engine.connect({}); await engine.initSchema();+ const engine = plain;try {const r = repo('foreign');mkdirSync(join(r.root, 'notes'), { recursive: true });@@ -259,5 +264,24 @@ test('a checkout gbrain did not clone for the source is never published by defauawait engine.setConfig(REFRESH_PUBLISH_DIVERGED_KEY, 'true');expect(await reconcileAll(engine, ['inside-a-repo'])).toMatchObject([{ status: 'published', ahead: 1 }]);expect(tip(r)).not.toBe(before);- } finally { await engine.disconnect(); }+ } finally { await resetPlain(); }+}, 120_000);++test('a checkout that fails with a plain error is reported for that checkout and the other checkouts still reconcile', async () => {+ const engine = plain;+ const broken = repo('plain-error'), healthy = repo('plain-healthy');+ try {+ await engine.executeRaw('INSERT INTO sources(id,name,local_path,config) VALUES($1,$1,$2,$4::jsonb),($3,$3,$5,$6::jsonb)',+ ['broken-source', broken.root, 'healthy-source', JSON.stringify({ remote_url: broken.remote }), healthy.root, JSON.stringify({ remote_url: healthy.remote })]);+ commit(broken.root, 'notes/stuck.md', 'stuck\n');+ const local = commit(healthy.root, 'notes/mine.md', 'mine\n');+ chmodSync(join(broken.root, '.git'), 0o555);+ const results = await reconcileAll(engine);+ expect(results.find(r => r.sources.includes('broken-source'))).toMatchObject({ status: 'failed', error: { message: expect.stringContaining('EACCES') } });+ expect(results.find(r => r.sources.includes('healthy-source'))).toMatchObject({ status: 'published', ahead: 1 });+ expect(tip(healthy)).toBe(local);+ } finally {+ chmodSync(join(broken.root, '.git'), 0o755);+ await resetPlain();+ }}, 120_000);