Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(prb): verify findings (agent contract, test isolation, Postgres arm, function size, world reads); widen FOREGROUND_WAITING_ON to released deferred rows after #8679
garrytan1e20e14806f0
diff --git a/scripts/check-agent-contract.ts b/scripts/check-agent-contract.tsindex f16b25aec3..c242a6bdd1 100644--- a/scripts/check-agent-contract.ts+++ b/scripts/check-agent-contract.ts@@ -266,6 +266,8 @@ const READ_ONLY_SUBCOMMANDS = new Set(['config get', 'sources list', 'sources st'schema active',// #6317: trusted-local writer administration reads (owners, running claims, consumers, movement); `sources writer claim|transfer|deactivate` stay mutating.'sources writer status', 'sources writer movement',+ // #8662: the commit-push dry run resolves the checkout, branch and lock and prints them; it stages and commits nothing.+ 'git commit-push --dry-run',// #6650: the terminal-failure drill-down and the sync operator status only read receipts and cursors.'sources writer failures', 'sync status',// GBRA-218: the member listing only reads the members table (the verify step of access_member_* refusals).diff --git a/scripts/core-world-reads-baseline.tsv b/scripts/core-world-reads-baseline.tsvindex 2e07f2bd37..dbc628c90f 100644--- a/scripts/core-world-reads-baseline.tsv+++ b/scripts/core-world-reads-baseline.tsv@@ -436,6 +436,10 @@ src/core/git-visible-files.ts als_store 1 W2: engine scope (decision E) replacessrc/core/git-visible-files.ts fs_import 1 W7: filesystem boundary moves to the local appsrc/core/git-visible-files.ts spawn_import 1 W7: process-wide effects move to src/clisrc/core/git/commit-guard.ts fs_import 1 W7: filesystem boundary moves to the local app+src/core/git/commit-guard.ts spawn_import 1 W7: process-wide effects move to src/cli; PR B owner-path guard reads git version and hook paths of the worktree it installs into+src/core/git/commit-ledger.ts fs_import 1 W7: filesystem boundary moves to the local app; PR B commit ledger appends to <git common dir>/gbrain/commit-ledger.jsonl+src/core/git/commit-ledger.ts module_collection 1 W6: per-engine state; PR B ledger location cache keyed by checkout root (git common dir never changes for a root)+src/core/git/commit-ledger.ts spawn_import 1 W7: process-wide effects move to src/cli; PR B ledger resolves the git common dirsrc/core/git/commit-push.ts fs_import 1 W7: filesystem boundary moves to the local appsrc/core/git/commit-push.ts module_collection 1 W6: per-engine state, or mark as a constant tablesrc/core/git/commit-push.ts process_env 7 W6: settings plane out of the core@@ -719,6 +723,7 @@ src/core/persistence/reconcile-state.ts load_config 1 W6: settings plane out ofsrc/core/persistence/reconcile-state.ts process_env 1 W6: settings plane out of the coresrc/core/persistence/reconcile.ts load_config 1 W6: settings plane out of the coresrc/core/persistence/recovery-resolve.ts fs_import 1 W5: repo-less persistence for hosts+src/core/persistence/refresh-barrier.ts module_collection 1 W6: per-engine state; PR B bounded cache (32) of the paths each refresh changed, keyed by refresh id and root (an immutable git diff)src/core/persistence/resolve-paths.ts fs_import 1 W5: repo-less persistence for hostssrc/core/persistence/root-registry.ts fs_import 1 W5: repo-less persistence for hostssrc/core/persistence/root-registry.ts spawn_import 1 W7: process-wide effects move to src/clidiff --git a/src/core/git/commit-guard.ts b/src/core/git/commit-guard.tsindex fe5bbbed49..f2ea7beced 100644--- a/src/core/git/commit-guard.ts+++ b/src/core/git/commit-guard.ts@@ -178,7 +178,7 @@ export function installOwnerGuard(worktree: string, mode: GuardMode): OwnerGuardconst before = ownerGuardStatus(p.root);if (before.foreign.length) {throw opError('git_unavailable', `Another tool's hook(s) live at this worktree's hooks path ${p.effective}: ${before.foreign.join(', ')}; gbrain does not replace or silence them.`,- 'Move those hooks aside or chain them yourself, then rerun gbrain sources guard <source> --install. Nothing was changed.', { detail: before.foreign.join(',') });+ 'Move those hooks aside or chain them yourself, then rerun the same gbrain sources guard --install command. Nothing was changed.', { detail: before.foreign.join(',') });}const script = renderGuardHook(mode);const current = existsSync(p.hook) ? readFileSync(p.hook, 'utf8') : null;diff --git a/src/core/persistence/journal.ts b/src/core/persistence/journal.tsindex e7ca91b1af..534fe94e2d 100644--- a/src/core/persistence/journal.ts+++ b/src/core/persistence/journal.ts@@ -774,7 +774,7 @@ const LEASE_HELD = `EXISTS (SELECT 1 FROM gbrain_cycle_locks l WHERE ${SYNC_KIND* side one head, so a stream of writes cannot starve it. Uncorrelated with the candidate row, so a claim reads it once.* The FIFO claim holds back only sync rows the write would pass (sequence below it): an earlier unfinished write is the* head-of-root rules' business, and one stalled in another process must not stop the sync behind it. A write queued- * behind an earlier queued write that waits on a sync row naming its page cannot go first either (a write never passes+ * behind an earlier queued (or released deferred) write that waits on a sync row naming its page cannot go first either (a write never passes* an earlier one), so it holds back nothing: counting it held back the very sync row the earlier write waited on, and* the three rows waited on each other with no foreground commit left to earn the sync side a head.*/@@ -785,7 +785,7 @@ const FOREGROUND_WAITING_ON = (nonce: string, seen: string, worktree = 'TRUE') =AND NOT EXISTS (SELECT 1 FROM persistence_requests named WHERE named.worktree_id=f.worktree_id AND named.sequence<f.sequenceAND named.state IN ('queued','running','recovering') AND ${SYNC_KIND('named')} AND ${NAMES_PAGE('named', 'f')})AND NOT EXISTS (SELECT 1 FROM persistence_requests ahead WHERE ahead.worktree_id=f.worktree_id AND ahead.sequence<f.sequence- AND ahead.state='queued' AND NOT ${SYNC_KIND('ahead')}+ AND (ahead.state='queued' OR ${RELEASED_DEFERRED('ahead')}) AND NOT ${SYNC_KIND('ahead')}AND EXISTS (SELECT 1 FROM persistence_requests named WHERE named.worktree_id=ahead.worktree_id AND named.sequence<ahead.sequenceAND named.state IN ('queued','running','recovering') AND ${SYNC_KIND('named')} AND ${NAMES_PAGE('named', 'ahead')}))AND NOT EXISTS (SELECT 1 FROM persistence_requests c WHERE c.sequence>COALESCE(${seen},0) AND c.worktree_id=f.worktree_iddiff --git a/src/core/persistence/worktree-refresh.ts b/src/core/persistence/worktree-refresh.tsindex ffda595f05..1b9d6f4f91 100644--- a/src/core/persistence/worktree-refresh.ts+++ b/src/core/persistence/worktree-refresh.ts@@ -101,8 +101,8 @@ function refusal(name: CatalogueName, cause: string, fix: string, refreshId?: streturn error;}/** #8617: refusals a tick retries once from a fresh precheck: HEAD moved, or work reached the worktree after the drain check. */-const retriedInTick = new WeakSet<OperationError>();-const retryInTick = (error: OperationError) => { retriedInTick.add(error); return error; };+const RETRY_IN_TICK = Symbol('retry_in_tick');+const retryInTick = (error: OperationError) => Object.assign(error, { [RETRY_IN_TICK]: true });/*** GST-1457: members whose last_commit is past the refresh's start commit: set (null means never synced) and not old_head or an ancestor* of it. With HEAD back at old_head, lifting the fence would let their next sync diff that commit back to old_head and soft-delete what it@@ -708,7 +708,7 @@ async function runRefresh(engine: BrainEngine, sourceId: string, opts: RefreshOpif (recovered && recovered.status !== 'completed' && recovered.status !== 'abandoned') return recovered;const once = () => refreshOnce(engine, sourceId, opts, fetchTimeoutMs, waitDrainMs, syncBudgetMs);const tick = () => once().catch(error => {- if (!retriedInTick.has(error)) throw error;+ if (!(RETRY_IN_TICK in error)) throw error;return once().catch(again => {error.message += ` A retry in the same run was refused too (${again instanceof OperationError ? again.code : 'internal_error'}): ${again instanceof Error ? again.message : String(again)}`;throw error;diff --git a/src/core/workspace-push.ts b/src/core/workspace-push.tsindex 28028ad308..7f72cf5754 100644--- a/src/core/workspace-push.ts+++ b/src/core/workspace-push.ts@@ -317,6 +317,13 @@ function git(}).toString();}+/** PR B: the workspace push commit, with its commit-ledger intent and commit lines (src/core/git/commit-ledger.ts). */+function commitRecorded(root: string, message: string): void {+ recordIntent(root, { writer: 'workspace_push', head_before: tryGit(root, ['rev-parse', '--verify', '--quiet', 'HEAD']), message });+ git(root, ['commit', '-m', message], { timeoutMs: 60_000 });+ recordCommit(root, { sha: tryGit(root, ['rev-parse', 'HEAD']) ?? '', writer: 'workspace_push' });+}+function tryGit(root: string, args: string[], opts: { timeoutMs?: number; auth?: boolean } = {}): string | null {try {return git(root, args, opts).trim();@@ -1075,11 +1082,8 @@ export async function workspacePush(opts: WorkspacePushOpts): Promise<WorkspacePtry {const clean = tryGit(root, ['diff', '--cached', '--quiet']) !== null;if (!clean) {- const message = opts.commitMessage ?? 'gbrain: workspace push';- recordIntent(root, { writer: 'workspace_push', head_before: tryGit(root, ['rev-parse', '--verify', '--quiet', 'HEAD']), message });- git(root, ['commit', '-m', message], { timeoutMs: 60_000 });+ commitRecorded(root, opts.commitMessage ?? 'gbrain: workspace push');committed = true;- recordCommit(root, { sha: tryGit(root, ['rev-parse', 'HEAD']) ?? '', writer: 'workspace_push' });}} catch (e) {return finish({diff --git a/src/mcp/dispatch.ts b/src/mcp/dispatch.tsindex 7c7c150b6a..149a5e9fed 100644--- a/src/mcp/dispatch.ts+++ b/src/mcp/dispatch.ts@@ -1353,8 +1353,7 @@ async function dispatchResolvedCall(// never tells a mutating op with an unknown outcome to retry.notices.push(...await sessionSafetyNotices(engine, opts, ctx.config));notices.push(...await grantBlockedNotices(engine, opts, refusedByGrant(e)));- const deferred = deferredWriteResult(e);- if (deferred) return toolResultWithNotices(deferred, admitNotices(notices, opts), dispatchRenderContext(opts));+ const deferred = deferredWriteResult(e); if (deferred) return toolResultWithNotices(deferred, admitNotices(notices, opts), dispatchRenderContext(opts));return errorResult(e, opts, { op: name, mutating: op.mutating === true, idempotent: op.idempotent === true, notices: admitNotices(notices, opts) });}}diff --git a/test/claim-fifo-foreground-waiting.test.ts b/test/claim-fifo-foreground-waiting.test.tsindex 6b241386cb..a4ad7077f4 100644--- a/test/claim-fifo-foreground-waiting.test.ts+++ b/test/claim-fifo-foreground-waiting.test.ts@@ -155,3 +155,23 @@ test('a write queued behind an earlier write that waits on a sync row naming itsexpect(await s.claim()).toBe(behind);}}, 60_000);++// PR B: a write deferred behind a refresh that has been released is queued work again (RELEASED_DEFERRED), so a write+// behind it that waits on the same sync row is held the same way as one behind a queued write.+test('a write queued behind a released deferred write that waits on a sync row naming its page holds back no sync head', async () => {+ for (const engine of engines) {+ const s = await scene(engine);+ const head = await s.sync('notes/synced-e');+ const named = await s.add('notes/synced-e');+ const behind = await s.add('notes/foreground-e');+ const [refresh] = await engine.executeRaw<{ id: string }>(`INSERT INTO persistence_worktree_refreshes(worktree_id,source_ids,principal_id,owner_epoch,topology_generation,state,old_head,target_head,upstream_ref,released_at)+ VALUES($1::uuid,ARRAY[$2::text],$3::uuid,1,1,'completed','a','b','origin/main',now()) RETURNING id::text`, [s.worktree, sourceId, randomUUID()]);+ await engine.transaction(async tx => {+ await tx.executeRaw("SET LOCAL session_replication_role = replica");+ await tx.executeRaw("UPDATE persistence_requests SET state='deferred',deferred_refresh_id=$2::uuid WHERE id=$1::uuid", [named, refresh!.id]);+ });+ s.seen[s.worktree] = await s.maxSequence();+ expect(await s.claim()).toBe(head);+ await s.commit(head);+ }+}, 60_000);diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txtindex 356ecc0bd3..8361f98941 100644--- a/test/postgres-unit-arms.txt+++ b/test/postgres-unit-arms.txt@@ -455,6 +455,7 @@ test/reason-trailers-gbra217.test.tstest/recall-page-fill.test.tstest/receipt-compaction-newest-sync-gbra130.test.tstest/reconcile-clears-stalled-hold-7364.test.ts+test/refresh-write-barrier.test.tstest/remediation-manual-only.test.tstest/remember-batch-entity-7432.test.tstest/repair-apply-pending-6543.test.tsdiff --git a/test/refresh-write-barrier.test.ts b/test/refresh-write-barrier.test.tsindex 6588113d02..388d220010 100644--- a/test/refresh-write-barrier.test.ts+++ b/test/refresh-write-barrier.test.ts@@ -27,12 +27,12 @@ import { _resetRefreshBarrierCacheForTests, deferredBacklog, expireDeferredWriteimport type { WriteRequest } from '../src/core/persistence/model.ts';import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';import { testBackends } from './helpers/test-backends.ts';+import { withEnv } from './helpers/with-env.ts';import { page, withRefreshFixture, type RefreshFixture } from './helpers/worktree-refresh-fixture.ts';const backends = testBackends();const engines: BrainEngine[] = [];let closePostgres: (() => Promise<void>) | undefined;-const savedBarrier = process.env.GBRAIN_REFRESH_BARRIER;beforeAll(async () => {if (backends.includes('pglite')) {@@ -48,13 +48,14 @@ afterAll(async () => {for (const engine of engines) { await disposePersistenceConsumer(engine); if (engine.kind === 'pglite') await engine.disconnect(); }await closePostgres?.();});-beforeEach(() => { process.env.GBRAIN_REFRESH_BARRIER = '1'; resetWriteSwitches(); _setRefreshFenceWaitForTests(0); _resetRefreshBarrierCacheForTests(); });-afterEach(() => {- if (savedBarrier === undefined) delete process.env.GBRAIN_REFRESH_BARRIER; else process.env.GBRAIN_REFRESH_BARRIER = savedBarrier;- resetWriteSwitches(); _setRefreshFenceWaitForTests(null);-});+beforeEach(() => { _setRefreshFenceWaitForTests(0); _resetRefreshBarrierCacheForTests(); });+afterEach(() => { resetWriteSwitches(); _setRefreshFenceWaitForTests(null); });-const each = async (fn: (f: RefreshFixture) => Promise<void>) => { for (const engine of engines) await withRefreshFixture(engine, fn); };+/** Runs `fn` per engine with the barrier on (GBRAIN_REFRESH_BARRIER through withEnv). */+const each = (fn: (f: RefreshFixture) => Promise<void>) => withEnv({ GBRAIN_REFRESH_BARRIER: '1' }, async () => {+ resetWriteSwitches();+ for (const engine of engines) await withRefreshFixture(engine, fn);+});/** Runs `fn` while a real refresh of the checkout is paused at its drained boundary; the refresh changes alpha/two.md. */async function duringRefresh(f: RefreshFixture, fn: () => Promise<void>, change: [string, string] = ['alpha/two.md', page('Alpha two', 'An upstream observation.')]) {@@ -272,11 +273,13 @@ test('a deferred write whose token is revoked while it waits ends permission_den}), 180_000);test('with the barrier off a write during a refresh is still refused worktree_refreshing', () => each(async f => {- process.env.GBRAIN_REFRESH_BARRIER = '0'; resetWriteSwitches();- const refresh = await duringRefresh(f, async () => {- const out = await call(f, 'put_page', { slug: 'notes/off', content: page('Off', 'refused') });- expect(out.isError).toBe(true);- expect(out.body.code).toBe('worktree_refreshing');+ await withEnv({ GBRAIN_REFRESH_BARRIER: '0' }, async () => {+ resetWriteSwitches();+ const refresh = await duringRefresh(f, async () => {+ const out = await call(f, 'put_page', { slug: 'notes/off', content: page('Off', 'refused') });+ expect(out.isError).toBe(true);+ expect(out.body.code).toBe('worktree_refreshing');+ });+ expect((await refresh).status).toBe('completed');});- expect((await refresh).status).toBe('completed');}), 180_000);