Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(global-maintenance): per-phase blocker streaks; stamp past a persistent typed failure; phase back-off (GBRA-130 A-10, #6837)
garrytan427424592a0e
diff --git a/src/commands/autopilot-fanout.ts b/src/commands/autopilot-fanout.tsindex e24f7c3838..e7d490bd40 100644--- a/src/commands/autopilot-fanout.ts+++ b/src/commands/autopilot-fanout.ts@@ -39,6 +39,7 @@ import { existsSync } from 'fs';import type { BrainEngine, SourceRow } from '../core/engine.ts';import type { MinionQueue } from '../core/minions/queue.ts';import { SOURCE_FRESHNESS_PHASES, MAINTENANCE_PHASES, LAST_GLOBAL_AT_KEY } from '../core/cycle.ts';+import { GLOBAL_FLOOR_MIN, resolveGlobalFloorMin } from '../core/minions/handlers/autopilot-global-maintenance.ts';import { CONNECTOR_SOURCE_PHASES } from '../core/cycle/phase-scope.ts';import { isConnectorSourceKind } from '../core/persistence/connector-identity.ts';import { attemptedConnectorSourceIds, type ConnectorAccountMismatch } from '../core/persistence/connector-state.ts';@@ -688,8 +689,6 @@ export async function dispatchPerSource(};}-const GLOBAL_FLOOR_MIN = 60;-/** Is the brain-wide maintenance overdue? Null/unparseable → overdue. */export function isGlobalMaintenanceStale(lastGlobalAtIso: string | null, now = Date.now(), floorMin = GLOBAL_FLOOR_MIN): boolean {if (!lastGlobalAtIso) return true;@@ -732,12 +731,7 @@ export async function dispatchGlobalMaintenance(const emit = opts.emit ?? ((line) => process.stderr.write(line + '\n'));const log = opts.log ?? ((line) => console.log(line));- let floorMin = GLOBAL_FLOOR_MIN;- const floorCfg = await engine.getConfig('autopilot.global_floor_min');- if (floorCfg) {- const n = parseInt(floorCfg, 10);- if (Number.isFinite(n) && n >= 1) floorMin = n;- }+ const floorMin = await resolveGlobalFloorMin(engine);const lastGlobalAt = await engine.getConfig(LAST_GLOBAL_AT_KEY);if (!isGlobalMaintenanceStale(lastGlobalAt, Date.now(), floorMin)) {return { dispatched: false, reason: 'fresh' };diff --git a/src/core/item-failure.ts b/src/core/item-failure.tsindex d6c6afddac..9185985d6f 100644--- a/src/core/item-failure.ts+++ b/src/core/item-failure.ts@@ -27,6 +27,7 @@ import { acceptedPendingReceipt } from './persistence/accepted-pending.ts';/** Every per-item loop that isolates its items, with the inventory row it fixes (reports/GBRA-130-inventory.md). */export const ISOLATE_SITES = {+ 'autopilot.global_maintenance': 'A-10',} as const satisfies Record<string, string>;export type IsolateSite = keyof typeof ISOLATE_SITES;diff --git a/src/core/minions/handlers/autopilot-global-maintenance.ts b/src/core/minions/handlers/autopilot-global-maintenance.tsindex 7983f14bcb..9ffd9bc8bc 100644--- a/src/core/minions/handlers/autopilot-global-maintenance.ts+++ b/src/core/minions/handlers/autopilot-global-maintenance.ts@@ -4,6 +4,10 @@import type { BrainEngine } from '../../engine.ts';import type { MinionHandler } from '../types.ts';import type { CycleReport, PhaseResult } from '../../cycle.ts';+import { CODES } from '../../error-registry.ts';+import { ItemRun } from '../../item-failure.ts';+import { OperationError } from '../../ops/contract.ts';+import { VERSION } from '../../../version.ts';/*** #4578: one pass over the maintenance phases may span several jobs. The@@ -14,10 +18,39 @@ import type { CycleReport, PhaseResult } from '../../cycle.ts';* is skipped for the rest of that pass so later phases still run; doctor's* `global_maintenance_timeouts` check reports it and names* `gbrain dream --phase <name>` to run it without the job deadline.+ *+ * GBRA-130 A-10 (#6837): a phase that blocks the stamp records a streak in the+ * same progress row (`failures[phase]`), counted once per pass. A typed+ * failure (`fail:<code>`) seen in STREAK_BYPASS_PASSES earlier passes stops+ * withholding `last_global_at`; budget, deferral and child blockers never do.+ * Failing and child kinds back off from their third pass. A streak recorded+ * by another gbrain version is dropped, a new blocker key starts a new streak,+ * and `gbrain autopilot --retry-global` ends the back-off. A job whose+ * failures look systemic (ItemRun breaker) persists no streak.*/export const GLOBAL_MAINTENANCE_PROGRESS_KEY = 'autopilot.global_maintenance.progress';/** A phase is not started when its last measured duration would end within this reserve of the job deadline. */const DEADLINE_RESERVE_MS = 60_000;+/** Minutes between brain-wide passes (config `autopilot.global_floor_min` overrides). */+export const GLOBAL_FLOOR_MIN = 60;+/** Earlier passes with one typed failure before the pass stamps past that phase; also where back-off starts. */+export const STREAK_BYPASS_PASSES = 3;+const MAX_BACKOFF_MS = 24 * 60 * 60_000;++/** One phase's consecutive passes blocked by the same kind of blocker. */+export interface PhaseStreak {+ /** `fail:<code>` (the phase failed), `budget`, `child:<outcome>` or `deferred`. */+ key: string;+ count: number;+ first_at: string;+ last_at: string;+ /** The gbrain version that recorded it; another running version drops the streak. */+ version: string;+ /** The pass that last counted it, so a phase rerun within one pass counts once. */+ pass: string;+ /** The phase is not run before this time. */+ retry_at?: string;+}export interface GlobalMaintenanceProgress {/** Phase the next job starts at; absent at the start of a pass. */@@ -31,8 +64,14 @@ export interface GlobalMaintenanceProgress {timeouts?: Record<string, { count: number; last_at: string }>;/** Phases skipped in the current pass because they killed a job. */skip_this_pass?: string[];- /** A phase in the current pass failed; the pass does not stamp last_global_at. */+ /** A phase in the current pass blocked the stamp; the pass does not stamp last_global_at. */pass_failed?: boolean;+ /** Identity of the current pass. */+ pass_id?: string;+ /** Phases the current pass stamps past (a typed failure with a long enough streak). */+ pass_bypassed?: string[];+ /** Blocker streak per phase; cleared when the phase passes. */+ failures?: Record<string, PhaseStreak>;}export async function readGlobalMaintenanceProgress(engine: BrainEngine): Promise<GlobalMaintenanceProgress> {@@ -43,19 +82,44 @@ export async function readGlobalMaintenanceProgress(engine: BrainEngine): Promis} catch { return {}; }}-/** The stamp gate: a phase result that means this pass did not finish its work. */-function phaseBlocksStamp(phase: PhaseResult): boolean {- if (phase.status === 'fail') return true;- if (phase.phase !== 'synthesize' && phase.phase !== 'patterns') return false;- if (phase.details.reason === 'insufficient_cycle_budget') return true;+export async function resolveGlobalFloorMin(engine: BrainEngine): Promise<number> {+ const n = parseInt((await engine.getConfig('autopilot.global_floor_min')) ?? '', 10);+ return Number.isFinite(n) && n >= 1 ? n : GLOBAL_FLOOR_MIN;+}++/** The command that ends a phase's back-off so the next pass runs it. */+export function phaseRetryCommand(phase: string): string {+ return `gbrain autopilot --retry-global --phase ${phase}`;+}++/** The stamp gate: the blocker kind when this phase result means the pass did not finish its work, else null. */+function phaseBlocker(phase: PhaseResult): string | null {+ if (phase.status === 'fail') return `fail:${phase.code ?? phase.error?.code ?? 'unknown'}`;+ if (phase.phase !== 'synthesize' && phase.phase !== 'patterns') return null;+ if (phase.details.reason === 'insufficient_cycle_budget') return 'budget';if (phase.phase === 'patterns') {- return typeof phase.details.child_outcome === 'string' && phase.details.child_outcome !== 'completed';+ const outcome = phase.details.child_outcome;+ return typeof outcome === 'string' && outcome !== 'completed' ? `child:${outcome}` : null;}const synthesis = phase.details.synthesis as { non_completed_jobs?: number } | undefined;const triage = phase.details.triage as { deferred?: number } | undefined;- return (synthesis?.non_completed_jobs ?? 0) > 0- || (triage?.deferred ?? 0) > 0- || (Array.isArray(phase.details.budget_deferred_transcripts) && phase.details.budget_deferred_transcripts.length > 0);+ if ((synthesis?.non_completed_jobs ?? 0) > 0) return 'child:non_completed';+ if (Array.isArray(phase.details.budget_deferred_transcripts) && phase.details.budget_deferred_transcripts.length > 0) return 'budget';+ return (triage?.deferred ?? 0) > 0 ? 'deferred' : null;+}++/** A failed phase result as the error the item classifier reads. */+function phaseFailureError(result: PhaseResult): Error {+ const code = result.code ?? result.error?.code;+ const message = result.error?.message ?? result.summary;+ if (code && code in CODES) return new OperationError(code as never, message);+ return Object.assign(new Error(message), code ? { code } : {});+}++function backoffUntil(key: string, count: number, lastAt: string, floorMin: number): string | undefined {+ if (!(key.startsWith('fail:') || key.startsWith('child:')) || count < STREAK_BYPASS_PASSES) return undefined;+ const ms = Math.min(MAX_BACKOFF_MS, floorMin * 60_000 * 2 ** (count - STREAK_BYPASS_PASSES + 1));+ return new Date(Date.parse(lastAt) + ms).toISOString();}/**@@ -64,9 +128,11 @@ function phaseBlocksStamp(phase: PhaseResult): boolean {* No source_id → uses the legacy global cycle lock; stamps autopilot.last_global_at* when a pass completes without a blocking phase so the dispatch gate backs off.*/-export function makeAutopilotGlobalMaintenanceHandler(engine: BrainEngine): MinionHandler {+export function makeAutopilotGlobalMaintenanceHandler(engine: BrainEngine, deps: { runCycle?: typeof import('../../cycle.ts').runCycle } = {}): MinionHandler {return async (job) => {- const { runCycle, MAINTENANCE_PHASES, LAST_GLOBAL_AT_KEY } = await import('../../cycle.ts');+ const cycle = await import('../../cycle.ts');+ const { MAINTENANCE_PHASES, LAST_GLOBAL_AT_KEY } = cycle;+ const runCycle = deps.runCycle ?? cycle.runCycle;const repoPath: string | null = typeof job.data.repoPath === 'string'? job.data.repoPath: (await engine.getConfig('sync.repo_path')) ?? null;@@ -89,6 +155,12 @@ export function makeAutopilotGlobalMaintenanceHandler(engine: BrainEngine): Miniprogress.durations ??= {};progress.timeouts ??= {};progress.skip_this_pass ??= [];+ progress.failures ??= {};+ for (const [phase, streak] of Object.entries(progress.failures)) {+ if (streak.version !== VERSION) delete progress.failures[phase];+ }+ const failuresAtStart = JSON.stringify(progress.failures);+ const floorMin = await resolveGlobalFloorMin(engine);const runToken = `${job.id}:${job.attempts_made ?? 0}`;const recordTimeout = (phase: string) => {const prev = progress.timeouts![phase];@@ -102,7 +174,41 @@ export function makeAutopilotGlobalMaintenanceHandler(engine: BrainEngine): Mini}const resumeAt = progress.next_phase ? phases.indexOf(progress.next_phase as never) : -1;const start = resumeAt >= 0 ? resumeAt : 0;- if (start === 0) progress.pass_failed = false;+ if (start === 0) {+ progress.pass_failed = false;+ progress.pass_id = `${runToken}@${new Date().toISOString()}`;+ progress.pass_bypassed = [];+ }+ progress.pass_bypassed ??= [];+ const passId = progress.pass_id ?? runToken;++ const itemRun = new ItemRun('autopilot.global_maintenance');+ /** Stops the job: a run-scoped error, or (breaker) a job whose failures look systemic, which records no streak. */+ const stopRun = async (error: unknown, phase: string | undefined): Promise<never> => {+ if (error instanceof OperationError && error.code === 'item_failures_systemic') progress.failures = JSON.parse(failuresAtStart);+ progress.running_phase = undefined;+ progress.running_job = undefined;+ progress.next_phase = phase;+ progress.pass_failed = true;+ await save();+ throw error;+ };+ const recordBlocker = (phase: string, key: string): PhaseStreak => {+ const prev = progress.failures![phase];+ const same = prev?.key === key;+ if (same && prev.pass === passId) return prev;+ const now = new Date().toISOString();+ const count = same ? prev.count + 1 : 1;+ const retryAt = backoffUntil(key, count, now, floorMin);+ const streak: PhaseStreak = { key, count, first_at: same ? prev.first_at : now, last_at: now, version: VERSION, pass: passId,+ ...(retryAt ? { retry_at: retryAt } : {}) };+ progress.failures![phase] = streak;+ return streak;+ };+ const blockStamp = (phase: string, streak: PhaseStreak, earlierPasses: number) => {+ if (!streak.key.startsWith('fail:') || earlierPasses < STREAK_BYPASS_PASSES) { progress.pass_failed = true; return; }+ if (!progress.pass_bypassed!.includes(phase)) progress.pass_bypassed!.push(phase);+ };const deadline = typeof job.deadlineAtMs === 'number' ? job.deadlineAtMs : null;const phaseDeadline = deadline !== null ? deadline - DEADLINE_RESERVE_MS : null;@@ -119,6 +225,14 @@ export function makeAutopilotGlobalMaintenanceHandler(engine: BrainEngine): Minidetails: { reason: 'timed_out_previous_job', recovery: `gbrain dream --phase ${phase}` } });continue;}+ const streak = progress.failures[phase];+ if (streak?.retry_at && Date.parse(streak.retry_at) > Date.now()) {+ blockStamp(phase, streak, streak.count);+ ran.push({ phase, status: 'skipped', duration_ms: 0,+ summary: `skipped: blocked ${streak.count} passes in a row (${streak.key}); backing off until ${streak.retry_at}. Retry it now with: ${phaseRetryCommand(phase)}`,+ details: { reason: 'phase_backoff', blocker: streak.key, count: streak.count, retry_at: streak.retry_at, recovery: phaseRetryCommand(phase) } });+ continue;+ }const estimate = progress.durations[phase] ?? 0;if (i > start && phaseDeadline !== null && Date.now() + estimate > phaseDeadline) {deferred = phases.slice(i);@@ -146,12 +260,15 @@ export function makeAutopilotGlobalMaintenanceHandler(engine: BrainEngine): MiniyieldBetweenPhases: async () => { await new Promise<void>((r) => setImmediate(r)); },});} catch (e) {+ let failure;+ try { failure = itemRun.fail(phase, e); } catch (stop) { return stopRun(stop, phase); }progress.running_phase = undefined;progress.running_job = undefined;- progress.next_phase = phase;- progress.pass_failed = true;- await save();- throw e;+ ran.push({ phase, status: 'fail', duration_ms: 0, summary: `error: ${failure.message}`, details: {},+ error: { class: 'InternalError', code: failure.code, message: failure.message } });+ const blocked = recordBlocker(phase, `fail:${failure.code}`);+ blockStamp(phase, blocked, blocked.count - 1);+ continue;}reports.push(report);progress.running_phase = undefined;@@ -172,9 +289,17 @@ export function makeAutopilotGlobalMaintenanceHandler(engine: BrainEngine): Miniif (result.phase !== phase) continue;progress.durations[phase] = result.duration_ms;delete progress.timeouts[phase];- if (phaseBlocksStamp(result)) progress.pass_failed = true;+ if (result.status === 'fail') {+ try { itemRun.fail(phase, phaseFailureError(result)); } catch (stop) { return stopRun(stop, phase); }+ } else itemRun.succeed();+ const key = phaseBlocker(result);+ if (!key) { delete progress.failures[phase]; continue; }+ const blocked = recordBlocker(phase, key);+ blockStamp(phase, blocked, blocked.count - 1);}}+ const systemic = itemRun.systemic();+ if (systemic) return stopRun(systemic, undefined);const passComplete = deferred.length === 0;if (passComplete) {@@ -210,20 +335,26 @@ export function makeAutopilotGlobalMaintenanceHandler(engine: BrainEngine): Miniconsole.warn(`[autopilot-global-maintenance] stopping before the job deadline; ${deferred.length} phase(s) resume at ${progress.next_phase} on the next run`);}+ let stamped = false;if (passComplete && !progress.pass_failed && reports.length > 0&& (status === 'ok' || status === 'clean' || status === 'partial')&& report.reason !== 'aborted' && report.reason !== 'lock_stolen') {try {await engine.setConfig(LAST_GLOBAL_AT_KEY, new Date().toISOString());+ stamped = true;} catch (e) {console.warn(`[autopilot-global-maintenance] failed to stamp last_global_at: ${e instanceof Error ? e.message : String(e)}`);}}+ const streaks = Object.entries(progress.failures).map(([phase, s]) => ({ phase, ...s, fix: phaseRetryCommand(phase) }));+ const stampedPast = stamped ? streaks.filter(s => progress.pass_bypassed!.includes(s.phase)) : [];return {partial: report.status === 'partial' || report.status === 'failed',status: report.status,report,+ ...(streaks.length > 0 ? { phase_streaks: streaks } : {}),+ ...(stampedPast.length > 0 ? { pass_completed_with_failing_phase: stampedPast } : {}),};};}diff --git a/test/pathological/catalogue.ts b/test/pathological/catalogue.tsindex 038e54eda2..dc35e8b25b 100644--- a/test/pathological/catalogue.ts+++ b/test/pathological/catalogue.ts@@ -18,4 +18,9 @@ export interface SiteCases {}export const CATALOGUE: Record<IsolateSite, SiteCases> = {+ 'autopilot.global_maintenance': {+ file: 'test/pathological/a10-global-maintenance-stamp.test.ts',+ item: 'a phase failing the same way in three passes stops withholding the stamp',+ run: 'a run-scoped failure at the phase loop stops the job and records no streak',+ },};