Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
wip: #7514 write-failure classification, strike hold, slug dedupe
garrytan7e26094a061b
diff --git a/src/core/cycle/extract-atoms-drain.ts b/src/core/cycle/extract-atoms-drain.tsindex adfb582c0a..923d2075bc 100644--- a/src/core/cycle/extract-atoms-drain.ts+++ b/src/core/cycle/extract-atoms-drain.ts@@ -55,6 +55,9 @@ export interface ExtractAtomsDrainFailure {source: string;/** Bounded, sanitized failure reason (secrets/connection info redacted). */reason: string;+ /** #7514: a write that did not commit: its request id (`gbrain write-request` explains it) and the refusal's own code. */+ request_id?: string;+ code?: string;}/**@@ -111,7 +114,9 @@ export interface ExtractAtomsDrainDeps {providerFailure?: boolean;failureCount?: number;firstError?: string;- failures?: Array<{ source: string; reason: string }>;+ failures?: Array<{ source: string; reason: string; request_id?: string; code?: string }>;+ /** #7514: write failures that recorded a strike toward their hold this batch; a batch of them is progress, not a stall. */+ writeStrikes?: number;budgetSkipped?: number;budget?: { spentUsd: number; capUsd: number };/** #6503: items the batch cut at `cycle.extract_atoms.max_input_chars` (partial disposition, not complete). */@@ -367,6 +372,8 @@ export async function runExtractAtomsDrain(batch: batches,source: sanitizeFailureText(f.source, MAX_DRAIN_FAILURE_SOURCE_CHARS),reason: sanitizeFailureText(f.reason, MAX_DRAIN_FAILURE_REASON_CHARS),+ ...(typeof f.request_id === 'string' ? { request_id: sanitizeFailureText(f.request_id, 64) } : {}),+ ...(typeof f.code === 'string' ? { code: sanitizeFailureText(f.code, 64) } : {}),});}const representative = batchFailures[0];@@ -417,7 +424,7 @@ export async function runExtractAtomsDrain(const after = await count();if (hard.signal.aborted) break;if (after !== null) lastCount = after;- if (after === null || before === null || after >= before) { stopped = 'no_progress'; break; }+ if (after === null || before === null || (after >= before && !((r.writeStrikes ?? 0) > 0))) { stopped = 'no_progress'; break; }}}@@ -552,20 +559,25 @@ export async function runExtractAtomsDrainForSource(// three-failure batch used to be unrecoverable from `--json`.const typedFailures = failures.filter(- (f): f is { source: string; error: string } =>+ (f): f is { source: string; error: string; request_id?: unknown; code?: unknown; strikes?: unknown } =>f != null &&typeof f === 'object' &&typeof (f as { source?: unknown }).source === 'string' &&typeof (f as { error?: unknown }).error === 'string',)- .map(({ source, error }) => ({ source, reason: error }));+ .map(({ source, error, request_id, code, strikes }) => ({ source, reason: error,+ ...(typeof request_id === 'string' ? { request_id, code: typeof code === 'string' ? code : undefined, strikes } : {}) }));+ // #7514: a write that did not commit never reached a provider, so it neither makes nor classes a provider failure.+ const writeFailures = typedFailures.filter(f => f.request_id !== undefined);+ const providerFailures = typedFailures.filter(f => f.request_id === undefined);return {extracted: Number(d.atoms_extracted ?? 0),skipped: Number(d.duplicates_skipped ?? 0),- providerFailure: failures.length > 0 && itemsSucceeded === 0,- providerFailureClass: batchProviderFailureClass(d.aborted_global_error, typedFailures),+ providerFailure: failures.length > writeFailures.length && itemsSucceeded === 0,+ providerFailureClass: batchProviderFailureClass(d.aborted_global_error, providerFailures),failureCount: failures.length,failures: typedFailures,+ writeStrikes: writeFailures.filter(f => typeof f.strikes === 'number').length,budgetSkipped: Number(d.pages_skipped_budget ?? 0) + Number(d.transcripts_skipped_budget ?? 0),budget: { spentUsd: Number(d.estimated_spend_usd ?? 0), capUsd: Number(d.budget_usd ?? 0) },inputTruncated: Number(d.input_truncated ?? 0),diff --git a/src/core/cycle/extract-atoms.ts b/src/core/cycle/extract-atoms.tsindex 2de17b9640..613a1bc63c 100644--- a/src/core/cycle/extract-atoms.ts+++ b/src/core/cycle/extract-atoms.ts@@ -87,7 +87,7 @@ import { utcDate } from './cycle-date.ts';import { atomSourceDate } from './atom-source-date.ts';import { normalizeForGrounding } from './synthesize-verify.ts';import type { TranscriptPageIndex } from '../transcripts/discover.ts';-import { atomOriginPin, managedAtomSession, readAtomOrigin, resumeManagedAtoms, publishManagedAtoms, publishManagedAtomGeneration, resumeManagedGenerationMembers,+import { atomOriginPin, atomWriteFailure, type AtomWriteFailure, managedAtomSession, readAtomOrigin, resumeManagedAtoms, publishManagedAtoms, publishManagedAtomGeneration, resumeManagedGenerationMembers,MANAGED_ATOM_DISCOVERY_SQL, managedAtomDiscoverySql, type AtomOrigin } from '../persistence/atom-maintenance.ts';import { effectiveVisibility } from '../search/private-visibility.ts';import { OperationError } from '../ops/contract.ts';@@ -901,7 +901,7 @@ export async function runPhaseExtractAtoms(let pagesProcessed = 0;let transcriptsSkipped = 0;let pagesSkipped = 0;- const failures: Array<{ source: string; error: string }> = [];+ const failures: Array<{ source: string; error: string } & Partial<Omit<AtomWriteFailure, 'error'>>> = [];let estimatedSpendUsd = 0;let budgetExhausted = false;// #3813: key-aware tier default, not a hardcoded Anthropic model — an@@ -1098,8 +1098,9 @@ export async function runPhaseExtractAtoms(// disposition instead of a completion stamp (extract-atoms-input.ts).const input = extractAtomsInput(item, maxInputChars, item.kind === 'page' ? (await readPageWatermark(engine, sourceId, item.slug, 'extract_atoms')).stored : null);const { promptContent, truncated } = input;+ let origin: AtomOrigin | null = null;try {- const origin: AtomOrigin | null = managed ? { ...await readAtomOrigin(engine, managed, item), ...(truncated ? { partialInputChars: maxInputChars } : {}) } : null;+ origin = managed ? { ...await readAtomOrigin(engine, managed, item), ...(truncated ? { partialInputChars: maxInputChars } : {}) } : null;const sourcePage = item.kind === 'page' ? await engine.getPage(item.slug, { sourceId }) : null;const contentDate = await atomSourceDate(engine, sourcePage); // #6720: captured with the input, before inferenceconst visibility = origin?.visibility ?? effectiveVisibility(item.kind === 'transcript' ? { kind: 'transcript' } // #5525@@ -1199,6 +1200,7 @@ export async function runPhaseExtractAtoms(item.kind === 'page'? await resolvePageAtomSlug(engine, atom.title, item.slug, sourceId, undatedDate, pageAtomTitles): await resolveTranscriptAtomSlug(engine, sourceId, atom.title, item, undatedDate, atomSlug);+ if (importedSlugs.includes(slug)) continue; // #7514: a repeated title is one atom; a second item at its slug cannot publishconst originFrontmatter =item.kind === 'transcript'? { source_path: item.filePath }@@ -1337,6 +1339,9 @@ export async function runPhaseExtractAtoms(else pagesSkipped++;continue;}+ // #7514: a batch whose write did not commit is a write failure (request id, refusal code, strike), never a provider error.+ const written = managed && origin ? await atomWriteFailure(engine, managed, origin, err) : null;+ if (written) { hardFailureCount++; failures.push({ source: originLabel, ...written }); continue; }// gbrain#4148: classify. Transient provider/infra errors (timeouts,// rate limits, 5xx, network) stay retryable and are NOT counted toward// any tombstone. A provider content block (prompt-level refusal) isdiff --git a/src/core/persistence/atom-maintenance.ts b/src/core/persistence/atom-maintenance.tsindex 2fcface1ce..b0aaa65b27 100644--- a/src/core/persistence/atom-maintenance.ts+++ b/src/core/persistence/atom-maintenance.ts@@ -77,6 +77,8 @@ export interface AtomIntent extends Record<string, unknown> {retiredBy?: DerivedRetiredBy;/** The generation key the batch publishes, so a retry republishes under the same key. */generationKey?: GenerationKey;+ /** #7514: a hold completion records the strike count it holds at instead of counting one more failure. */+ attempts?: number;}const ownerStatusFix = (sourceId: string): Action => readFix(@@ -561,7 +563,7 @@ export interface ManagedAtomRetirement {export async function publishManagedAtoms(engine: BrainEngine, session: ManagedAtomSession, origin: AtomOrigin,atoms: Array<{ slug: string; content: string; links: LinkBatchInput[]; expectedTarget?: { pageId: number | null; revision: string | null } }>,- failure?: string, reviewedRetirements?: ManagedAtomRetirement[]): Promise<WriteReceipt[]> {+ failure?: string, reviewedRetirements?: ManagedAtomRetirement[], heldAttempts?: number): Promise<WriteReceipt[]> {const claim = atomClaim(session, origin);const key = claim.runKey;const advance = claim.checkpointKey ? { checkpointKey: claim.checkpointKey, expectedCheckpoint: claim.expectedCheckpoint ?? null } : {};@@ -608,7 +610,7 @@ export async function publishManagedAtoms(engine: BrainEngine, session: ManagedAconst children: string[] = [];const accepted: WriteRequest[] = [];for (const input of [...inputs, { slug: '__managed_atom_complete__', pageId: null,- intent: { kind: 'managed_atom_complete', runKey: key, origin, children, ...(failure ? { failure } : {}), ...advance } as AtomIntent }]) {+ intent: { kind: 'managed_atom_complete', runKey: key, origin, children, ...(failure ? { failure } : {}), ...(heldAttempts ? { attempts: heldAttempts } : {}), ...advance } as AtomIntent }]) {const requestId = atomRequestId(key, input.slug);const row = await admitWriteInTransaction(tx, { principal: session.authority.principal, authority: session.authority,operation: 'submit_job', sourceId: session.sourceId, sourceIncarnation: session.incarnation,@@ -635,6 +637,39 @@ export async function publishManagedAtoms(engine: BrainEngine, session: ManagedAreturn receipts;}+const UNCOMMITTED_OP = 'managed-atoms-uncommitted';+export interface AtomWriteFailure { error: string; request_id: string; code: string; strikes?: number; held?: boolean }++/**+ * #7514: an atom batch whose write ended without committing (conflict, failed, cancelled) is a write failure with+ * the request id and refusal code of that write, never a provider failure. On the drain (not an explicit retry) each+ * time it is met counts one strike for the failed batch, with no model call: a failed batch is not re-extracted on+ * its own. At MAX_DETERMINISTIC_FAILURES strikes a journaled failure completion holds the origin (held_failed), so it+ * leaves the backlog and doctor lists it with its receipt and the reviewed retry. Null for any other error.+ */+export async function atomWriteFailure(engine: BrainEngine, session: ManagedAtomSession, origin: AtomOrigin, error: unknown): Promise<AtomWriteFailure | null> {+ const receipt = error instanceof OperationError ? error.writeRequest : undefined;+ if (!(error instanceof OperationError) || !receipt || !['conflict', 'failed', 'cancelled'].includes(receipt.state)) return null;+ const failure: AtomWriteFailure = { error: error.message, request_id: receipt.request_id, code: error.code };+ if (session.retry) return failure;+ const runKey = atomClaim(session, origin).runKey;+ const [strike] = await engine.executeRaw<{ strikes: number }>(`INSERT INTO op_checkpoints(op,fingerprint,completed_keys)+ VALUES('${UNCOMMITTED_OP}',$1,jsonb_build_array(jsonb_build_object('requestId',$2::text,'code',$3::text,'strikes',1)))+ ON CONFLICT(op,fingerprint) DO UPDATE SET updated_at=now(), completed_keys=jsonb_build_array(jsonb_build_object('requestId',$2::text,'code',$3::text,+ 'strikes',COALESCE((op_checkpoints.completed_keys->0->>'strikes')::integer,0)+1))+ RETURNING (completed_keys->0->>'strikes')::integer AS strikes`, [runKey, receipt.request_id, failure.code]);+ const strikes = Number(strike?.strikes ?? 1);+ if (strikes < MAX_DETERMINISTIC_FAILURES) return { ...failure, strikes, error: `${failure.error} (write did not commit: strike ${strikes} of ${MAX_DETERMINISTIC_FAILURES} on this content)` };+ const key = drainKey(session, origin);+ const checkpoint = await readAtomCheckpoint(engine, key);+ (session.attempts ??= new Map()).set(key, { runKey: digest([runKey, 'uncommitted-hold', checkpoint]), checkpointKey: key, expectedCheckpoint: checkpoint });+ const receipts = await publishManagedAtoms(engine, session, origin, [],+ `write did not commit: ${failure.code} (request ${receipt.request_id}): ${failure.error}`.slice(0, 500), undefined, strikes);+ const held = receipts.every(row => row.state === 'committed');+ if (held) await engine.executeRaw(`DELETE FROM op_checkpoints WHERE op='${UNCOMMITTED_OP}' AND fingerprint=$1`, [runKey]);+ return { ...failure, strikes, held, error: `${failure.error} (write did not commit ${strikes} times on this content${held ? '; held: doctor extract_atoms_held_failed lists it' : ''})` };+}+export async function prepareManagedAtomMutation(engine: BrainEngine, row: WriteRequest, config: GBrainConfig): Promise<PreparedMutation> {const p = row.intent as AtomIntent | null;if (!p || !['managed_atom_page', 'managed_atom_delete', 'managed_atom_complete'].includes(p.kind) || !p.origin || row.authority.remote) {@@ -727,7 +762,7 @@ export async function prepareManagedAtomMutation(engine: BrainEngine, row: Write}// #6325: one strike per completed failure of this content, counted on the checkpoint it advances.const prior = Array.isArray(p.expectedCheckpoint) ? p.expectedCheckpoint[0] as AtomCheckpoint | undefined : undefined;- const attempts = (prior?.failure ? Number(prior.attempts ?? 1) : 0) + 1;+ const attempts = p.attempts ?? (prior?.failure ? Number(prior.attempts ?? 1) : 0) + 1;const checkpoint = JSON.stringify([{ sourceId: row.source_id, incarnation: row.source_incarnation, requestId: row.request_id,kind: p.origin.kind, locator: p.origin.locator, pageId: p.origin.pageId, contentHash: p.origin.contentHash,...(p.failure ? { failure: p.failure, attempts, ...(attempts >= MAX_DETERMINISTIC_FAILURES ? { held: true } : {}) }