Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
#6712 PR 4b lane F: a storage_error two runs repeat on one file needs a person (GBRA-133 S-60)
garrytanbe6d2191e68d
diff --git a/docs/guides/sync-unblock-runbook.md b/docs/guides/sync-unblock-runbook.mdindex 136a929c1e..d1c1a8c26f 100644--- a/docs/guides/sync-unblock-runbook.md+++ b/docs/guides/sync-unblock-runbook.md@@ -109,6 +109,11 @@ Every hold and error has three fields, from one tableuser raises), and a slug-conflict hold the lane decided a person must settle([`merge_recommended`](write-refusals.md#merge_recommended),[`content_repair_needs_human`](write-refusals.md#content_repair_needs_human)).+ A recorded `storage_error` is `connection` and `retry` the first time; when+ two runs in a row stop on the same path with the same code and message+ (`last_error.repeats` 2 or more), it is deterministic, so `last_error` turns+ `needs_human` (class `page`, or `systemic` for a phase path such as+ `<discovery>`) and `human_reason` names the file.## Decision tablediff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.tsindex 7afea9963c..d74f320bea 100644--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@ -931,6 +931,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;{ since: '0.60.300.0', text: 'A managed sync no longer stops a whole source at a Markdown file whose text holds NUL bytes (U+0000: a UTF-16 "Unicode" save, a binary file named .md, a crash-padded file). Before, every run failed at that file with `storage_error` (SQLSTATE 22P05) and nothing after it synced; now the file alone is held `content_null_bytes`, its message names the file and the first NUL\'s line (and says to save it as UTF-8 when it starts with a UTF-16 byte order mark), and the rest of the source syncs. With `sync.holds=fail` the run stops with `content_null_bytes` instead. Classic (unmanaged) sync is unchanged.' },{ since: '0.60.300.0', text: 'A managed sync no longer stops a whole source at a committed file whose Git object the checkout lost (an interrupted gc, a partial clone): it imports the working-tree bytes when they hash to the committed blob id, and otherwise holds that file `git_object_missing` (run `git fsck`, restore the object with `git fetch` or from a backup; every sync re-tests it). An imported file that became a directory (`notes/a.md` turned into `notes/a.md/x.md`) no longer stops the source with `page_identity_changed`: its page is deleted and the new file imports.' },{ since: '0.60.300.0', text: 'When managed sync hits an unexpected error while preparing one file (before anything is admitted), it now holds that file `page_write_failed` with `meta.write_failure.origin` `freeze` and the error in the hold message, and the rest of the source syncs; before, the source stopped on that file on every run. The next syncs re-test the file on their own until it has been held 3 times, so a passing fault clears without help. A deliberate refusal still stops the run, and so does a run in which most files fail that way (5 or more, and at least as many as prepared cleanly), which looks systemic. In a bulk group (Postgres) the failure is reported on the file that failed, not on the group\'s first file.' },+ { since: '0.60.300.0', text: '`gbrain sync status --json` no longer tells an agent to rerun a managed sync forever when every run stops on the same file with the same unclassified `storage_error`: the first such stop is still `connection` with `next` = rerun, but once two runs in a row stop on the same path with the same code and message, `last_error` is `needs_human` (class `page`, `safe_actions` `none`, new field `repeats`), the state is `blocked` / `needs_human`, and `human_reason` names the file. A message that changes between runs stays a rerun.' },];/** The newest disclosed change's release: the notice id moves only when a release adds rows. */diff --git a/src/core/persistence/sync-failures.ts b/src/core/persistence/sync-failures.tsindex af80956399..9df5b418b5 100644--- a/src/core/persistence/sync-failures.ts+++ b/src/core/persistence/sync-failures.ts@@ -25,6 +25,13 @@ export interface ManagedSyncFailure {observation_id: string;first_seen: string;attempts: number;+ /**+ * GBRA-133 S-60: how many runs in a row stopped on this path with this code and message (1 on the first); a different+ * path, code or message starts over. Absent on failures recorded before it was kept.+ */+ repeats?: number;+ /** GBRA-133 S-60: the invocation that recorded it, so a resumed cursor's same observation still counts a new run. */+ invocation?: string;/** The cursor-selecting options of the failed run; absent on failures recorded before they were kept. */syncOptions?: SyncCursorOptions;processingOptions?: Partial<SyncProcessingOptions>;@@ -43,20 +50,26 @@ export interface ManagedSyncRootCause { request_id: string | null; slug: string/** The cursor fence cause when the root is a cursor refusal (`outside_fence`, `run_replaced`, `window_dropped`). */cause?: string; unknown?: true }-export async function recordManagedSyncFailure(engine: BrainEngine, value: Omit<ManagedSyncFailure, 'first_seen' | 'attempts'> & { first_seen?: string }): Promise<{ failure: ManagedSyncFailure; ledgerRecorded: boolean }> {- const failure = { ...value, gbrain_version: VERSION, first_seen: value.first_seen ?? new Date().toISOString(), attempts: 1 };+export async function recordManagedSyncFailure(engine: BrainEngine, value: Omit<ManagedSyncFailure, 'first_seen' | 'attempts' | 'repeats'> & { first_seen?: string }): Promise<{ failure: ManagedSyncFailure; ledgerRecorded: boolean }> {+ const failure = { ...value, gbrain_version: VERSION, first_seen: value.first_seen ?? new Date().toISOString(), attempts: 1, repeats: 1 };const recorded = await engine.transaction(async tx => {await tx.executeRaw("SELECT set_config('synchronous_commit','on',true)");const [row] = await tx.executeRaw<{ completed_keys: [ManagedSyncFailure] }>(`+ WITH pair AS (SELECT completed_keys->0 AS was, $2::text::jsonb->0 AS incoming FROM op_checkpoints WHERE op='managed-sync-failure' AND fingerprint=$1),+ same AS (SELECT was, incoming, was->>'path'=incoming->>'path' AND was->>'code'=incoming->>'code' AND was->>'message'=incoming->>'message' AS same,+ COALESCE((was->>'repeats')::int,1)+1 AS repeats FROM pair)INSERT INTO op_checkpoints(op,fingerprint,completed_keys) VALUES('managed-sync-failure',$1,$2::text::jsonb)ON CONFLICT(op,fingerprint) DO UPDATE SET completed_keys=CASEWHEN op_checkpoints.completed_keys->0->>'observation_id'=EXCLUDED.completed_keys->0->>'observation_id'- THEN op_checkpoints.completed_keys+ THEN CASE WHEN (SELECT same AND incoming->>'invocation' IS NOT NULL AND was->>'invocation' IS DISTINCT FROM incoming->>'invocation' FROM same)+ THEN jsonb_build_array(op_checkpoints.completed_keys->0 || jsonb_build_object('repeats',(SELECT repeats FROM same),'invocation',EXCLUDED.completed_keys->0->>'invocation'))+ ELSE op_checkpoints.completed_keys ENDWHEN op_checkpoints.completed_keys->0->>'target' IS DISTINCT FROM EXCLUDED.completed_keys->0->>'target'THEN EXCLUDED.completed_keysELSE jsonb_build_array(EXCLUDED.completed_keys->0 || jsonb_build_object('first_seen',op_checkpoints.completed_keys->0->>'first_seen',- 'attempts',COALESCE((op_checkpoints.completed_keys->0->>'attempts')::int,0)+1)) END,+ 'attempts',COALESCE((op_checkpoints.completed_keys->0->>'attempts')::int,0)+1,+ 'repeats',(SELECT CASE WHEN same THEN repeats ELSE 1 END FROM same))) END,updated_at=now()RETURNING completed_keys`, [value.cursor_key, JSON.stringify([failure])]);return row.completed_keys[0];diff --git a/src/core/persistence/sync-fault-class.ts b/src/core/persistence/sync-fault-class.tsindex bd6b780b2b..f94565ba9f 100644--- a/src/core/persistence/sync-fault-class.ts+++ b/src/core/persistence/sync-fault-class.ts@@ -47,6 +47,8 @@ export const HOLD_ATTEMPTS_NEEDS_HUMAN = 3;* (three syncs in ten minutes) never pages a person; a live `worktree_dirty` editor and image holds never escalate.*/export const HOLD_ESCALATE_MS = 24 * 60 * 60 * 1000;+/** GBRA-133 S-60: a recorded `storage_error` this many runs in a row repeat (same path, code and message) needs a person. */+export const STORAGE_ERROR_REPEATS = 2;const ESCALATE_AFTER = `${HOLD_ATTEMPTS_NEEDS_HUMAN} failed attempts over ${HOLD_ESCALATE_MS / 3_600_000} h`;export const SYNC_FAULT_TABLE: ReadonlyArray<SyncFaultRule> = [@@ -253,12 +255,14 @@ export interface SyncFaultVerdict { class: SyncFaultClass; safe_actions: SyncSaf* `reason` (for example `pinned_git_worktree_conflict` under `source_changed`) or a drain stop's `cause`; it refines the code* when the table knows it. `content_repair` is a slug-conflict hold's recorded verdict: a recommended merge or an* undecidable pair names a person. An unknown code is systemic and human: an agent must not guess at it.+ * GBRA-133 S-60: `repeated` is a recorded run failure's path and the runs in a row that stopped there with the same code and+ * message; a `storage_error` that `STORAGE_ERROR_REPEATS` runs repeat is deterministic, not a dropped connection, so a person is named.*/export function classifySyncFault(input: { code: string; detail?: string | null; attempts?: number | null; message?: string | null; content_repair?: ContentRepairHoldInput | null;/** #6712 PR 2: how long ago the path was first held with this code (`holdEscalation`); escalation needs `HOLD_ESCALATE_MS`. */held_for_ms?: number | null;/** #6712 PR 2: a `worktree_dirty` hold whose uncommitted bytes changed within `HOLD_ESCALATE_MS`: someone is still editing. */- live_editor?: boolean }): SyncFaultVerdict {+ live_editor?: boolean; repeated?: { path: string; runs: number } | null }): SyncFaultVerdict {const slugRepair = input.code === 'frontmatter_slug_conflict' ? input.content_repair : undefined;const judged = slugRepair && contentRepairLaneCurrent(slugRepair) ? contentRepairHumanReason(slugRepair) : undefined;if (judged) return { class: 'page', safe_actions: ['none'], needs_human: true, human_reason: judged };@@ -266,6 +270,13 @@ export function classifySyncFault(input: { code: string; detail?: string | null;const rule = (input.detail ? BY_CODE.get(input.detail) : undefined) ?? BY_CODE.get(input.code)?? (/ECONN|ETIMEDOUT|EPIPE|connection.*closed|CONNECTION_ENDED/i.test(input.message ?? '') ? BY_CODE.get('connection_lost') : undefined);if (!rule) return { class: 'systemic', safe_actions: ['none'], needs_human: true, human_reason: `Unknown code ${input.code}; run gbrain doctor --json and read gbrain errors ${input.code}.` };+ const repeated = rule.code === 'storage_error' && input.repeated && input.repeated.runs >= STORAGE_ERROR_REPEATS ? input.repeated : undefined;+ if (repeated) {+ const phase = /^<(.+)>$/.exec(repeated.path)?.[1];+ return { class: phase ? 'systemic' : 'page', safe_actions: ['none'], needs_human: true, human_reason: `${phase ? `The sync's ${phase} phase` : repeated.path} stopped the last ${repeated.runs} syncs with `+ + `the same storage_error, so it is not a dropped connection and another rerun will not clear it; read last_error.message, ${phase ? 'run gbrain doctor --json' : 'fix, move or remove the file and commit'}, then sync again, `+ + 'and report it to the gbrain maintainers if the cause is not clear.' };+ }const exhausted = !rule.needs_human && (input.attempts ?? 0) >= HOLD_ATTEMPTS_NEEDS_HUMAN && (input.held_for_ms ?? 0) >= HOLD_ESCALATE_MS && !input.live_editor&& rule.safe_actions[0] !== 'none' && rule.class === 'page' && (input.code !== 'frontmatter_slug_conflict' || slugHuman !== undefined);if (!exhausted) return { class: rule.class, safe_actions: rule.safe_actions, needs_human: rule.needs_human, ...(rule.needs_human && rule.human_reason ? { human_reason: rule.human_reason } : {}) };diff --git a/src/core/persistence/sync-run.ts b/src/core/persistence/sync-run.tsindex 1a151ec3a2..62b826484d 100644--- a/src/core/persistence/sync-run.ts+++ b/src/core/persistence/sync-run.ts@@ -1367,7 +1367,7 @@ async function recordRunFailure(engine: BrainEngine, error: unknown, run: { cursconst failedCursor = cursor ?? stored?.completed_keys?.[0];const { failure } = await recordManagedSyncFailure(engine, { source_id: context.sourceId, source_incarnation: context.incarnation, path: cursor?.entries[cursor.index]?.path ?? failedCursor?.pending?.intent.path ?? `<${phase}>`, code,message: error instanceof Error ? error.message : String(error), request_id: failedCursor?.pending?.requestId ?? null,- run_id: failedCursor?.runId ?? discoveryRun, target: failedCursor?.target ?? discoveryTarget, cursor_key: cursor?.failureKey ?? key,+ run_id: failedCursor?.runId ?? discoveryRun, invocation: discoveryRun, target: failedCursor?.target ?? discoveryTarget, cursor_key: cursor?.failureKey ?? key,syncOptions: failedCursor?.syncOptions ?? syncOptions, processingOptions: failedCursor?.processingOptions ?? processingOptions, phase, state: 'failed',observation_id: failedCursor ? `${failedCursor.runId}:${failedCursor.index}:${phase}:${code}` : `${key}:discovery:${discoveryTarget}:${code}` });if (error instanceof Error) error.message = run.remote ? 'Managed sync is blocked; ask the host operator to inspect doctor.' : `${formatManagedSyncFailure(failure)} Fix the cause, then run: ${managedSyncRetryCommand(failure, run.repoPath)}`;diff --git a/src/core/persistence/sync-status.ts b/src/core/persistence/sync-status.tsindex 4dd2cbb4e9..3ccf108172 100644--- a/src/core/persistence/sync-status.ts+++ b/src/core/persistence/sync-status.ts@@ -80,6 +80,8 @@ export interface SyncStatusError extends SyncFaultVerdict {phase: ManagedSyncFailure['phase'];first_seen: string;attempts: number;+ /** GBRA-133 S-60: the runs in a row that stopped on this path with this code and message (`ManagedSyncFailure.repeats`). */+ repeats?: number;/** #6643: what caused this failure (a knock-on's root request, or the receipt blocking a checkpoint). */root_cause?: ManagedSyncFailure['root_cause'];}@@ -295,7 +297,8 @@ export async function readSyncStatus(engine: BrainEngine, sourceId: string, opts...(laneFault ? { detail: laneFault } : {}), message: failure.message, ...(failure.write_error_detail ? { write_error_detail: failure.write_error_detail } : {}),path: failure.path, phase: failure.phase, first_seen: failure.first_seen, attempts: failure.attempts,...(failure.request_id ? { request_id: failure.request_id } : {}), ...(rootCause ? { root_cause: rootCause } : {}),- ...classifySyncFault({ code: failure.code, detail: laneFault, message: failure.message }) }+ ...(failure.repeats ? { repeats: failure.repeats } : {}),+ ...classifySyncFault({ code: failure.code, detail: laneFault, message: failure.message, repeated: failure.repeats ? { path: failure.path, runs: failure.repeats } : null }) }: retired ? { code: 'cursor_incarnation_retired', category: 'sync_fault', public_category: 'superseded', message: `An unfinished sync cursor of ${sourceId} was recorded under an incarnation the source no longer has; no current sync selects it, and it says nothing about whether the current files are imported. `+ `Retire it with ${repairPreview.argv!.join(' ')} (preview, then --apply with the printed hash).`, phase: 'resume', first_seen: retired.first_seen, attempts: 1, ...classifySyncFault({ code: 'cursor_incarnation_retired' }) } : null;const unfinished = !!header && !header.done;diff --git a/test/behavior-change-notice-6712-block.test.ts b/test/behavior-change-notice-6712-block.test.tsindex 19236a6ed9..6a5815f285 100644--- a/test/behavior-change-notice-6712-block.test.ts+++ b/test/behavior-change-notice-6712-block.test.ts@@ -12,7 +12,7 @@ import { join } from 'node:path';import { BEHAVIOR_CHANGES, compareReleases } from '../src/core/behavior-change-notice.ts';const MARKER = '// #6712 PR 4b (the level-triggered sync pass';-const ROWS = 27;+const ROWS = 28;const NOTICE_CAP = 2_000;/** The array literal's row lines in order, and where the block's rows start and how many there are. */diff --git a/test/sync-entry-faults-6712.test.ts b/test/sync-entry-faults-6712.test.tsindex b410b34536..c4bf9e501a 100644--- a/test/sync-entry-faults-6712.test.ts+++ b/test/sync-entry-faults-6712.test.ts@@ -15,7 +15,10 @@* most freezes throw is systemic and stops without holding (guards).* - S-64: on Postgres, where bulk groups are on, the same throw in a group follower is held on the follower's own path,* and with `sync.holds=fail` the run stops naming the follower (the group head's path before).- * The deliberate-refusal and systemic guards pass before and after.+ * - S-60: a `storage_error` that two syncs in a row record on one file with the same message stayed `connection` / `retry`+ * with `next` = rerun the same sync forever; it is now `page` class and `needs_human`, naming the file. A message that+ * changes between runs stays a rerun, and the count survives a resumed cursor's repeated observation.+ * The deliberate-refusal, systemic and changing-message guards pass before and after.** PGLite here; Postgres through test/e2e/sync-entry-faults-6712-postgres.test.ts.*/@@ -27,8 +30,10 @@ import type { BrainEngine } from '../src/core/engine.ts';import { opError } from '../src/core/ops/contract.ts';import { installFaultHook } from '../src/core/persistence/fault-points.ts';import { resolveBulkSettings } from '../src/core/persistence/sync-group.ts';+import { recordManagedSyncFailure } from '../src/core/persistence/sync-failures.ts';import { readGitSourceHolds } from '../src/core/persistence/sync-holds.ts';import { performManagedSync } from '../src/core/persistence/sync-run.ts';+import { readSyncStatus } from '../src/core/persistence/sync-status.ts';import { managedBrain } from './helpers/managed-brain.ts';import { testBackends } from './helpers/test-backends.ts';@@ -165,4 +170,43 @@ for (const backend of testBackends()) describe(`[${backend}] GBRA-133: one odd fawait expect(performManagedSync(engine, OPTS)).rejects.toThrow('synthetic systemic fault');expect((await holds(engine)).length).toBeLessThan(8);}), 240_000);+ test('S-60: a storage_error two syncs in a row record on one file with the same message names a person instead of rerunning', () => brain(async ({ engine, root }) => {+ expect((await performManagedSync(engine, OPTS)).status).toBe('first_sync');+ writeFileSync(join(root, 'notes/odd.md'), note('notes/odd')); commit(root, 'odd');+ installFaultHook(point => { if (point === 'sync:mid_checkpoint') throw new Error('synthetic deterministic fault'); });+ await expect(performManagedSync(engine, OPTS)).rejects.toThrow('synthetic deterministic fault');+ const once = await readSyncStatus(engine, 'default');+ expect(once.last_error).toMatchObject({ code: 'storage_error', path: 'notes/odd.md', class: 'connection', safe_actions: ['retry'], needs_human: false });+ expect(once.next?.argv?.slice(0, 2)).toEqual(['gbrain', 'sync']);+ await expect(performManagedSync(engine, OPTS)).rejects.toThrow('synthetic deterministic fault');+ const twice = await readSyncStatus(engine, 'default');+ expect(twice.last_error).toMatchObject({ code: 'storage_error', path: 'notes/odd.md', repeats: 2, class: 'page', safe_actions: ['none'], needs_human: true });+ expect(twice.last_error!.human_reason).toContain('notes/odd.md stopped the last 2 syncs with the same storage_error');+ expect([twice.state, twice.reason]).toEqual(['blocked', 'needs_human']);+ expect(twice.next?.argv?.slice(0, 2)).not.toEqual(['gbrain', 'sync']);+ expect(twice.next?.user_message).toContain('notes/odd.md');+ installFaultHook(undefined);+ expect((await performManagedSync(engine, OPTS)).status).toBe('synced');+ expect(await atHead(engine, root)).toBe(true);+ expect((await readSyncStatus(engine, 'default')).last_error).toBeNull();+ }), 240_000);++ test('S-60 guard: a storage_error whose message changes between runs stays a rerun', () => brain(async ({ engine, root }) => {+ expect((await performManagedSync(engine, OPTS)).status).toBe('first_sync');+ writeFileSync(join(root, 'notes/odd.md'), note('notes/odd')); commit(root, 'odd');+ let run = 0;+ installFaultHook(point => { if (point === 'sync:mid_checkpoint') throw new Error(`synthetic fault number ${run}`); });+ for (run = 1; run <= 3; run++) await expect(performManagedSync(engine, OPTS)).rejects.toThrow(`synthetic fault number ${run}`);+ expect((await readSyncStatus(engine, 'default')).last_error).toMatchObject({ code: 'storage_error', attempts: 3, class: 'connection', safe_actions: ['retry'], needs_human: false });+ }), 240_000);++ test('S-60: a resumed run recording the same observation counts a new run; one invocation recording it twice does not', () => brain(async ({ engine }) => {+ const base = { source_id: 'default', source_incarnation: '00000000-0000-4000-8000-000000000000', path: 'notes/odd.md', code: 'storage_error', message: 'synthetic',+ request_id: null, run_id: 'run-1', target: 'a'.repeat(40), cursor_key: 'lanef-s60-key', phase: 'freeze' as const, state: 'failed', observation_id: 'run-1:0:freeze:storage_error' };+ expect((await recordManagedSyncFailure(engine, { ...base, invocation: 'one' })).failure.repeats).toBe(1);+ expect((await recordManagedSyncFailure(engine, { ...base, invocation: 'one' })).failure.repeats).toBe(1);+ expect((await recordManagedSyncFailure(engine, { ...base, invocation: 'two' })).failure.repeats).toBe(2);+ expect((await recordManagedSyncFailure(engine, { ...base, invocation: 'three', observation_id: 'run-2:0:freeze:storage_error' })).failure).toMatchObject({ repeats: 3, attempts: 2 });+ expect((await recordManagedSyncFailure(engine, { ...base, invocation: 'four', observation_id: 'run-3:0:freeze:storage_error', path: 'notes/other.md' })).failure).toMatchObject({ repeats: 1, attempts: 3 });+ }), 240_000);});