Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
sync: while a source's drain lease is live, only the lease holder publishes its managed-sync requests (Garry 2026-10-16, via GBRA-40)
garrytan76f12239c5b2
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 6ba5361706..5362623fe2 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -23,6 +23,7 @@ identifiers and attribution are available in the pre-removal Git revision| the tail fails, is cut short or the deadline left no time | silent | the run stays `synced` with one `[gbrain notice sync_tail_degraded]` and its fix (`gbrain extract --stale --source <id>`, or doctor for statistics); `sync --all` prints it per source and puts `tail` and `notices` in each source's JSON entry || a pass admits nothing with no unfinished request | `drain_stalled` / `no_admission`, a pooler warning, and a delegated run's one-time fallback | `drain_stalled` / `no_progress` with the same step and statement; `no_admission` is a retired reason || `gbrain sync status` on a large brain | every heavy read on every call | a plain status skips the terminal summary, blocker list and cursor join (`*_read: not_read`, fix `--detail`); `state`, `reason` and bounded oldest-blocker / recovery probes always run (an unfinished write is `resumable` / `request_pending`, never synced); under 30 ms on a 61k-request fixture |+| a short-lived command (`put`, `remember`, `import`) runs while a managed sync drains its source | its consumer could claim and publish the drainer's page requests whenever a lane group backed off | only the drain lease holder publishes them; the command's own write still passes the queued sync rows that do not name its page, and with no live lease nothing changes || a status whose probe timed out | could read as nothing pending | `state: resumable`, `reason: status_unknown`, never `synced` || a hold, `last_error`, a receipt, `managedWrite` or doctor `sync_failures` | internal codes only | `public_category` (drift, conflict, content_refused, file_missing, permission, storage, config, superseded, transient, defect) beside the unchanged `category` || a managed-sync file `write_gate.external_mode=reject` refuses | its receipt failed at preparation and the whole source stopped `blocked_by_failures` | the file is held `write_gate_rejected` (needs a person) and the rest syncs |@@ -54,6 +55,7 @@ identifiers and attribution are available in the pre-removal Git revision- **`sync status`** (`sync-status.ts`, `commands/sync/operator.ts`): `state`, `reason` (`SYNC_STATUS_REASONS`), `oldest_blocker`, `recovery`, `checkpoint_blockers_read`, `cursors_read`, `terminal_failures_read`, `--detail`; every existing field keeps its type. One text headline per state; the drain summary says `resumed run <id> and converged` when a drain finishes a run an earlier invocation started.- **`public_category`** (`public-category.ts`): a total mapping from `classifyTerminal`'s category and the fault code; `classifyRecordedFault` reads holds, failure rows and run stops as the failed receipt they stand for.- AGENTS.md and the sync-unblock runbook: the operator loop checks `*_read` and never reads a `not_read` field as "none".+- **One publisher per drained source** (`journal.ts` `claimNextWrite`, approved by Garry on 2026-10-16): while a source's drain lease is live, a non-resident consumer skips that source's managed-sync requests held by another process. Resident consumers (`serve`, `sync`, `jobs`, `autopilot`, `mcp`) and the lease holder claim as before. Test: `test/claim-lease-holder-only-6712.test.ts`.#### Hold exits and escalationdiff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.tsindex e66642a135..e7c001ba97 100644--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@ -708,6 +708,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText }// #6712 PR 2 lane L5 (truthful receipts, fast status). `since` is a placeholder until the merge-slot stamp.{ since: '0.60.265.0', text: 'A managed `gbrain sync` returns `synced` when its checkpoint commits: the tail after it (planner statistics, link extraction for the imported pages) now runs after the drain lease is released, bounded at 5 minutes, and a second sync can take the lease while it runs. A tail that fails, is cut short or gets no time keeps the run `synced` and adds a `[gbrain notice sync_tail_degraded]` with its fix (`gbrain extract --stale --source <id>`); a tail a crash skipped runs on the next sync of the source.' },{ since: '0.60.265.0', text: 'The `drain_stalled` cause `no_admission` is retired: a sync pass that admits nothing with no unfinished request stops `drain_stalled` / `no_progress` with the same step and statement, a delegated run no longer falls back to its own consumer for it, and the transaction-pooler warning line is gone. Scripts matching `no_admission` should match `no_progress`.' },+ { since: '0.60.265.0', text: 'While a managed sync holds a source\'s drain lease, short-lived commands (`put`, `remember`, `import` and other CLI writes) no longer publish that source\'s sync page requests; only the drainer does (#6712). A command whose own write names a page the sync is about to publish waits for the drainer, and returns its retryable writer-pending reply when the drainer does not finish in time. With no live lease, every consumer drains as before.' },{ since: '0.60.265.0', text: 'A plain `gbrain sync status` skips the terminal-failure summary, the checkpoint blocker list and the cursor list (their fields stay, empty or `unknown`, with `terminal_failures_read` / `checkpoint_blockers_read` / `cursors_read` set to `not_read` and a `--detail` fix); `gbrain sync status --detail` reads them. New fields: `state`, `reason`, `oldest_blocker`, `recovery`, and `public_category` on holds, `last_error`, receipts and doctor `sync_failures`.' },// #6712 PR 2 lane L4 (exits, escalation, soak counters): placeholder since; the fresh-install cases in behavior-change-notice.test.ts pass once VERSION is stamped.{ since: '0.60.265.0', text: 'A held file now asks for a person (`needs_human`) only after its safe action failed three times and at least 24 hours have passed since it was first held (#6712). Three re-holds within an hour stay the agent\'s to retry. A `worktree_dirty` file whose uncommitted bytes changed in the last day, and an image held while multimodal embedding is off, never escalate this way. A failed `sync unblock --apply` (still dirty) or a repair that holds the file again counts as an attempt.' },diff --git a/src/core/persistence/journal.ts b/src/core/persistence/journal.tsindex eed448f8bc..f302ca118e 100644--- a/src/core/persistence/journal.ts+++ b/src/core/persistence/journal.ts@@ -17,8 +17,10 @@ import { EFFECT_BYTES_SQL, RECEIPT_RESERVATION_FLOOR, receiptReservation, retainimport { writeHealth, type WriteHealthFacts } from './health.ts';import { writerStamp } from './writer-versions.ts';import { intentCarriesContent, intentCarriesPurgedContent, PURGE_PRESENCE_COLUMNS } from './purged-intent.ts';-import { claimOwner, claimPhaseStamp, startClaimPhase } from './claim-phase.ts';-import { consumerIdentity } from './consumer-heartbeat.ts';+import { hostname } from 'node:os';+import { claimOwner, claimOwnerKind, claimPhaseStamp, startClaimPhase } from './claim-phase.ts';+import { consumerIdentity, RESIDENT_CONSUMER_KINDS } from './consumer-heartbeat.ts';+import { syncLockId } from '../db-lock.ts';import { publicFailureDetail } from './publication-failure.ts';import { catalogueError } from '../error-catalogue.ts';import { ACTIVE_REFRESH_STATES_SQL, refreshFenceClear } from './worktree-refresh-schema.ts';@@ -624,9 +626,20 @@ export async function hasClaimableWrite(engine: SqlEngine, hostId: string, exclu* `fifoRoots` (#5984 Phase 4.5) are roots where this consumer owes the sync side a turn: a foreground write it* claimed ahead of a queued sync row (`passed_sync`) committed since it last claimed a sync row, so there the claim is plain FIFO.*/+/**+ * #6712 PR 2 (Garry, 2026-10-16, via GBRA-40): while a source's drain lease is live, only the lease holder publishes that+ * source's managed-sync requests. A non-resident consumer (a short-lived command such as `put` or `remember`, waiting on its+ * own write) skips a sync row whose source's lease another process holds, so it never publishes a drainer's pages or breaks+ * up its lane groups. With no live lease nothing changes: a crashed drainer's rows still drain through any consumer.+ * $5 pid, $6 host, $7 the sync lock id prefix.+ */+const LEASE_HOLDER_ONLY = `NOT (${SYNC_KIND('r')} AND EXISTS (SELECT 1 FROM gbrain_cycle_locks l WHERE l.id=$7::text||r.source_id+ AND l.ttl_expires_at>now() AND NOT (l.holder_pid=$5::integer AND l.holder_host IS NOT DISTINCT FROM $6::text)))`;+export async function claimNextWrite(engine: BrainEngine, hostId: string, leaseMs = 30_000, excludeRoots: string[] = [], fifoRoots: string[] = [],laneRoots: string[] = []): Promise<(WriteRequest & { passed_sync?: boolean }) | null> {const first = `(${foregroundPrioritySql()}) AND NOT (COALESCE(r.worktree_id::text,'db:'||r.source_incarnation::text)=ANY($3::text[]))`;+ const holderOnly = !RESIDENT_CONSUMER_KINDS.includes(claimOwnerKind());return engine.transactionDirect(async tx => {// The protocol declaration and the FIFO head read are sent together.const [, [row]] = await pipelined(tx, [@@ -635,8 +648,9 @@ export async function claimNextWrite(engine: BrainEngine, hostId: string, leaseMLEFT JOIN persistence_worktrees w ON w.id=r.worktree_idWHERE ${claimableWriteSql(`(${first})`, '$4::text[]')}-- On a root whose lane groups run in this process only a foreground write is claimed (beside them).- AND NOT (r.worktree_id::text=ANY($4::text[]) AND (${SYNC_KIND('r')} OR NOT (${first})))- ORDER BY ${CLAIM_ORDER(`(${first})`)} LIMIT 1 FOR UPDATE OF r SKIP LOCKED`, [hostId, excludeRoots, fifoRoots, laneRoots]),+ AND NOT (r.worktree_id::text=ANY($4::text[]) AND (${SYNC_KIND('r')} OR NOT (${first})))${holderOnly ? `+ AND ${LEASE_HOLDER_ONLY}` : ''}+ ORDER BY ${CLAIM_ORDER(`(${first})`)} LIMIT 1 FOR UPDATE OF r SKIP LOCKED`, [hostId, excludeRoots, fifoRoots, laneRoots, ...(holderOnly ? [process.pid, hostname(), syncLockId('')] : [])]),]) as [unknown, WriteRequest[]];if (!row) return null;// `passed_sync`: the claimed row went ahead of a queued sync row of its root.diff --git a/test/claim-lease-holder-only-6712.test.ts b/test/claim-lease-holder-only-6712.test.tsnew file mode 100644index 0000000000..36cc40661d--- /dev/null+++ b/test/claim-lease-holder-only-6712.test.ts@@ -0,0 +1,98 @@+/**+ * #6712 PR 2 (Garry, 2026-10-16, via GBRA-40): while a source's drain lease is live, only the lease holder publishes that+ * source's managed-sync requests. A non-resident consumer skips them; with no live lease, or for the holder itself or a+ * resident consumer, the claim is unchanged.+ */+import { afterAll, beforeAll, expect, test } from 'bun:test';+import { randomUUID } from 'node:crypto';+import { hostname } from 'node:os';+import type { BrainEngine } from '../src/core/engine.ts';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import type { OperationContext } from '../src/core/ops/contract.ts';+import { admitWrite, claimNextWrite, releaseUnpublishedClaim, type WriteAdmission } from '../src/core/persistence/journal.ts';+import type { WriteRequest } from '../src/core/persistence/model.ts';+import { submissionAuthority } from '../src/core/persistence/authority.ts';+import { registerLocalWriter } from '../src/core/persistence/identity.ts';+import { activatePersistence } from '../src/core/persistence/activation.ts';+import { claimOwner, setClaimOwnerForTest } from '../src/core/persistence/claim-phase.ts';+import { syncLockId } from '../src/core/db-lock.ts';+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';++const engines: BrainEngine[] = [];+const sourceId = 'lease-holder-only-example';+const hostId = randomUUID();+let closePostgres: (() => 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); closePostgres = pg.close;+ }+ for (const engine of engines) {+ await engine.executeRaw('INSERT INTO sources(id,name) VALUES($1,$1)', [sourceId]);+ await registerLocalWriter(engine, 'cli');+ expect((await activatePersistence(engine, { confirmQuiesced: true })).enabled).toBe(true);+ }+}, 120_000);+afterAll(async () => {+ setClaimOwnerForTest(undefined);+ await engines[0]?.disconnect(); await closePostgres?.();+});++async function admission(engine: BrainEngine, slug: string): Promise<WriteAdmission> {+ const [source] = await engine.executeRaw<{ incarnation: string }>('SELECT incarnation FROM sources WHERE id=$1', [sourceId]);+ const context: OperationContext = { engine, sourceId, remote: false, dryRun: false,+ config: { engine: engine.kind }, logger: { info() {}, warn() {}, error() {} } };+ const authority = await submissionAuthority(context, 'put_page', sourceId, source.incarnation, slug);+ const content = '---\ntitle: Lease holder example\ntype: note\n---\nA synthetic note.\n';+ return { principal: authority.principal, operation: 'put_page', sourceId, sourceIncarnation: source.incarnation,+ slug, pageId: null, requestId: randomUUID(), callerIntent: { slug, content }, intent: { slug, content }, authority };+}++/** A queued row standing in for a drainer's page request: only its intent kind marks it managed sync. */+async function syncRow(engine: BrainEngine): Promise<string> {+ const row = await admitWrite(engine, await admission(engine, `notes/synced-${randomUUID().slice(0, 8)}`));+ await engine.executeRaw(`UPDATE persistence_requests SET intent=jsonb_set(intent,'{kind}','"managed_sync_page"') WHERE id=$1::uuid`, [row.id]);+ return row.id;+}+const lease = (engine: BrainEngine, pid: number, ttl: string) => engine.executeRaw(`INSERT INTO gbrain_cycle_locks(id,holder_pid,holder_host,acquired_at,ttl_expires_at,last_refreshed_at)+ VALUES($1,$2,$3,now(),now()+$4::interval,now()) ON CONFLICT(id) DO UPDATE SET holder_pid=EXCLUDED.holder_pid,ttl_expires_at=EXCLUDED.ttl_expires_at`, [syncLockId(sourceId), pid, hostname(), ttl]);+const as = (kind: string) => setClaimOwnerForTest({ ...claimOwner(), kind });+async function claimed(engine: BrainEngine): Promise<WriteRequest | null> {+ const row = await claimNextWrite(engine, hostId);+ if (row) await releaseUnpublishedClaim(engine, row, 'consumer_stopping');+ return row;+}++test('a short-lived consumer never claims a sync row while another process holds the source\'s drain lease; the holder and resident consumers still do', async () => {+ for (const engine of engines) {+ const id = await syncRow(engine);+ const otherPid = process.pid + 100_000;+ try {+ as('put');+ expect((await claimed(engine))?.id).toBe(id);+ await lease(engine, otherPid, '2 minutes');+ expect(await claimed(engine)).toBeNull();+ as('cli');+ expect(await claimed(engine)).toBeNull();+ for (const kind of ['sync', 'serve', 'jobs']) { as(kind); expect((await claimed(engine))?.id).toBe(id); }+ as('put');+ await lease(engine, process.pid, '2 minutes');+ expect((await claimed(engine))?.id).toBe(id);+ await lease(engine, otherPid, '-1 second');+ expect((await claimed(engine))?.id).toBe(id);+ // A foreground write of the same source is claimed beside a live lease.+ await lease(engine, otherPid, '2 minutes');+ await engine.executeRaw('DELETE FROM persistence_requests WHERE id=$1::uuid', [id]);+ const own = await admitWrite(engine, await admission(engine, 'notes/foreground'));+ expect((await claimed(engine))?.id).toBe(own.id);+ } finally {+ setClaimOwnerForTest(undefined);+ await engine.executeRaw('DELETE FROM gbrain_cycle_locks WHERE id=$1', [syncLockId(sourceId)]);+ await engine.executeRaw('DELETE FROM persistence_requests WHERE source_id=$1', [sourceId]);+ }+ }+}, 120_000);diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txtindex 98333e70ff..f229b0c93c 100644--- a/test/postgres-unit-arms.txt+++ b/test/postgres-unit-arms.txt@@ -19,6 +19,7 @@ test/behavior-change-notice.test.tstest/capture-consent-admission.test.tstest/capture-dispatch-provenance-6524.test.tstest/chronicle-backfill-max-usd.test.ts+test/claim-lease-holder-only-6712.test.tstest/claude-cli-output-cap.test.tstest/colon-slug-windows-5032.test.tstest/company-brain-policy.test.ts