Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(extract-atoms): tombstone pages the provider blocks at the prompt level (#5849)

garrytan78ddb65d005b
diff --git a/docs/architecture/key-files/core-cycle.md b/docs/architecture/key-files/core-cycle.md
index 6278fe729a..c545e03f1f 100644
--- a/docs/architecture/key-files/core-cycle.md
+++ b/docs/architecture/key-files/core-cycle.md
@@ -22,7 +22,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/cycle/extract-atoms.ts` — the extract_atoms lens phase: mines eligible pages into `atoms/<date>/<stem>-<hash>` pages. Transcript input is paste-stripped before the cut (#5812); discovery skips self-captures (#5820). Eligibility reads source-incarnation/page/full-hash-keyed derived scan state; scan and failure markers do not mutate canonical frontmatter. Managed extraction checks source-wide local authority and owner readiness before provider work, admits outputs plus a completion request together, and replays retained output without another model call. Managed atom files keep provisional source hashes; only the source-incarnation/page/full-hash durable completion receipt excludes an item from discovery and backlog counts. Unmanaged atom completion flips and their cardinality check share a transaction after provenance links persist, so a partial match rolls back and stays retryable. An undated source dates its atoms by the source page's creation date (`undated` for transcripts), never the run date. After an unmanaged item completes, `retireStaleAtoms` soft-deletes that source's atoms from earlier extractions (other or provisional `source_hash`) that this extraction did not re-produce. Hard `opts.signal` (chat call, pacing, checks before each item and commit) leaves no strike, receipt or rollup; soft `opts.stopSignal` stops before the next item.
Managed completion admits revision-pinned `managed_atom_delete` children alongside replacement pages, removes canonical files through the page deletion path, and commits its checkpoint only after every publication and retirement commits.
Both paths prevent LLM-chosen titles that drift between extractions from piling up.
- Atom identity: page-derived atoms fold the source-page slug into the slug hash (8 chars, NUL-separated) so two same-date pages emitting the same title get DISTINCT slugs; the source CONTENT hash is deliberately NOT folded (a reworded source still upserts rather than duping); transcript atoms keep the legacy title-only 6-char hash. `resolvePageAtomSlug` adopts a legacy-slug atom with a compatible binding in place on re-extraction (upgrade idempotency — no migration, no duplicate), while `assertAtomImportBinding` fail-closed refuses to reuse a slug bound to a DIFFERENT source locator. Both share `isCompatibleAtomBinding(frontmatter, sourcePageSlug)` — the ONE definition of compatible: bound to THIS source page, or carrying no `source_slug`/`source_path` at all (pre-binding-era adoption, not a clobber); a `source_path`-bound legacy transcript atom or a different `source_slug` is a different origin, and a non-atom page squatting on the slug is refused. `source_quote` is verified at extraction time against the exact `truncateUtf8` prompt prefix the model saw (`locateQuote` advances by full code points): located quotes persist original characters + [start,end) offsets + `source_quote_verified`; unlocatable quotes are dropped with the atom kept. Edges write before the completion flip; per-item drain failures stay typed (bounded, sanitized, reconcilable). Transcript items carry the same failure-count/tombstone machinery as pages, in the `extract_atoms_transcript_state` table (migration `extract_atoms_transcript_state_table`; keyed `(source_id, file_path, content_hash)` with the 16-char hash prefix, so an edit is a new row and re-eligibilizes): `recordItemFailureCount` counts a transcript's malformed output toward `MAX_DETERMINISTIC_FAILURES`, a zero-yield transcript tombstones immediately (the same zero-yield policy as pages), and `tombstonedTranscriptsForHashes` is the batch read-side gate mirroring `atomsExistingForHashes` (fail-open on error). Reported as `tombstoned_transcripts` (paths), separate from the page-slug `tombstoned_for_failures`. Malformed managed output requires a newly approved protected-job retry identity; publication retry reuses retained output and original/current grants.
+ Atom identity: page-derived atoms fold the source-page slug into the slug hash (8 chars, NUL-separated) so two same-date pages emitting the same title get DISTINCT slugs; the source CONTENT hash is deliberately NOT folded (a reworded source still upserts rather than duping); transcript atoms keep the legacy title-only 6-char hash. `resolvePageAtomSlug` adopts a legacy-slug atom with a compatible binding in place on re-extraction (upgrade idempotency — no migration, no duplicate), while `assertAtomImportBinding` fail-closed refuses to reuse a slug bound to a DIFFERENT source locator. Both share `isCompatibleAtomBinding(frontmatter, sourcePageSlug)` — the ONE definition of compatible: bound to THIS source page, or carrying no `source_slug`/`source_path` at all (pre-binding-era adoption, not a clobber); a `source_path`-bound legacy transcript atom or a different `source_slug` is a different origin, and a non-atom page squatting on the slug is refused. `source_quote` is verified at extraction time against the exact `truncateUtf8` prompt prefix the model saw (`locateQuote` advances by full code points): located quotes persist original characters + [start,end) offsets + `source_quote_verified`; unlocatable quotes are dropped with the atom kept. Edges write before the completion flip; per-item drain failures stay typed (bounded, sanitized, reconcilable). Transcript items carry the same failure-count/tombstone machinery as pages, in the `extract_atoms_transcript_state` table (keyed `(source_id, file_path, content_hash)`, 16-char hash prefix, so an edit is a new row): `recordItemFailureCount` counts a transcript's malformed output or prompt-level provider block (`providerContentBlockReason`; never feeds the outage halt) toward `MAX_DETERMINISTIC_FAILURES`, a zero-yield transcript tombstones immediately (as pages do), and `tombstonedTranscriptsForHashes` is the batch read-side gate mirroring `atomsExistingForHashes` (fail-open on error). Reported as `tombstoned_transcripts` (paths), separate from the page-slug `tombstoned_for_failures`. Malformed managed output requires a newly approved protected-job retry identity; publication retry reuses retained output and original/current grants.
- `src/core/cycle/extract-facts.ts` — source-scoped `## Facts` fence reconciliation. Rows are keyed by fence row number, never by claim text: a DB row whose `(row_num, claim)` is still in the fence keeps its id and has its other cells updated in place (ids from recall stay valid for forget; `source_session`, `created_at`, consolidation state and vectors survive), a row whose number left the fence or whose claim was rewritten is expired and detached (`row_num` NULL), never deleted, and only new row numbers insert. Duplicate ACTIVE rows with the same claim and source index once; a struck history row never collapses onto an active row with the same text, so a claim that reverts (NYC → SF → NYC) stays active. `superseded by #N` links resolve on every hop of a chain (`supersede-resolve.ts`; forgotten targets and cycles still resolve to NULL with a warning). Each run first expires (without detaching) the active fence-owned rows of soft-deleted pages in the source; restoring the page re-activates them on its next reconcile. Previously embedded fact rows and their text/provenance remain intact when a full valid replacement embedding batch is unavailable; old vectors are never transplanted to changed text/model. Restrictive fence changes still expire removed/withdrawn claims and tighten visibility before deferral. Provider cancellation within database writes rolls back rather than publishing half a replacement. Keyless initial fact insertion remains supported; conversation-origin facts without a fence are not wiped by fence reconciliation. Each page reconciles in isolation: a page whose writes the database rejects rolls back, is reported as `<slug>: FACTS_RECONCILE_FAILED: …` (counted in `pagesFailed`, booked as a halt in the rollup), and later pages still reconcile. `facts.superseded_by` is `ON DELETE SET NULL`. Tests: `test/e2e/fact-vector-repair-parity.test.ts`, `test/extract-facts-phase.test.ts`, `test/extract-facts-poison-page.test.ts`, `test/extract-facts-stable-identity.test.ts`. On a managed brain the same reconcile runs after `managedDerivedFactsPreflight` (local writer, active source, before any embedding call): each page transaction and the deleted-page expiry commit inside `withDerivedFactsWrite` (coordinator source capability, page key locked); the facts receipt page is skipped, the rollup is still booked. It is distinct from the coordinated `extract_facts` operation and durable page backstop. Tests: `test/managed-facts-writers.test.ts`.
diff --git a/src/core/ai/errors.ts b/src/core/ai/errors.ts
index b8a03aab6f..c83b035731 100644
--- a/src/core/ai/errors.ts
+++ b/src/core/ai/errors.ts
@@ -132,6 +132,33 @@ export function normalizeAIError(err: unknown, context?: string, redact?: (text:
return carryStatusFields(err, new AITransientError(`${ctxPrefix}${msg}`, err));
}
+/** A provider refusal tied to the prompt, even when the SDK wraps its response. */
+export function providerContentBlockReason(err: unknown): string | undefined {
+ for (let depth = 0; depth < 8 && err != null; depth++) {
+ try {
+ if (typeof err !== 'object') break;
+ const value = err as { responseBody?: unknown; statusCode?: unknown; status?: unknown; cause?: unknown };
+ if (typeof value.responseBody === 'string' &&
+ (value.statusCode == null || value.statusCode === 200) &&
+ (value.status == null || value.status === 200)) {
+ const body = JSON.parse(value.responseBody);
+ const reason = body?.promptFeedback?.blockReason;
+ if (typeof reason === 'string' && reason.trim()) return reason;
+ const candidate = body?.candidates?.[0];
+ if (['PROHIBITED_CONTENT', 'SAFETY', 'BLOCKLIST', 'SPII'].includes(candidate?.finishReason) &&
+ (!Array.isArray(candidate?.content?.parts) || candidate.content.parts.length === 0)) {
+ return candidate.finishReason;
+ }
+ }
+ err = value.cause;
+ } catch {
+ // Malformed provider bodies and hostile error objects are not content blocks.
+ break;
+ }
+ }
+ return undefined;
+}
+
/** Whole-run LLM failure classes — see classifyGlobalLlmError. */
export type GlobalLlmErrorClass = 'auth' | 'billing' | 'rate_limit';
diff --git a/src/core/cycle/extract-atoms.ts b/src/core/cycle/extract-atoms.ts
index 4c5dc90e6f..c00f59c491 100644
--- a/src/core/cycle/extract-atoms.ts
+++ b/src/core/cycle/extract-atoms.ts
@@ -64,7 +64,7 @@ import type { PhaseResult } from '../cycle.ts';
import type { GBrainConfig } from '../config.ts';
import type { ProgressReporter } from '../progress.ts';
import { chat as gatewayChat, withBudgetTracker, isAvailable } from '../ai/gateway.ts';
-import { createGlobalLlmHaltTracker, haltedClassOf, type GlobalLlmErrorClass } from '../ai/errors.ts';
+import { createGlobalLlmHaltTracker, haltedClassOf, providerContentBlockReason, type GlobalLlmErrorClass } from '../ai/errors.ts';
import { importFromContent } from '../import-file.ts';
import { serializeMarkdown } from '../markdown.ts';
import { truncateUtf8 } from '../text-safe.ts';
@@ -101,7 +101,7 @@ export const DEFAULT_EXTRACT_MAX_OUTPUT_TOKENS = 4096;
/**
* gbrain#4148: consecutive same-content failures of a content-deterministic
- * class (malformed model output) before the page is tombstoned so the
+ * class (malformed model output or provider content block) before the page is tombstoned so the
* backlog floor can clear. A content edit resets the streak.
*/
export const MAX_DETERMINISTIC_FAILURES = 3;
@@ -1093,6 +1093,21 @@ export async function runPhaseExtractAtoms(
}
}
+ // gbrain#4148 content-deterministic classes: hash-keyed bounded tombstone (v146: transcripts too).
+ async function recordDeterministicFailure(item: WorkItem, source: string, error: string): Promise<void> {
+ hardFailureCount++;
+ const failCount = await recordItemFailureCount(item);
+ failures.push({ source, error: error + (failCount != null ? ` (consecutive failure ${failCount} on this content)` : '') });
+ if (failCount == null || failCount < MAX_DETERMINISTIC_FAILURES || opts.dryRun) return;
+ if (item.kind === 'page') {
+ await stampAtomsScanHash(item);
+ tombstonedForFailures.push(item.slug);
+ } else {
+ await stampTranscriptTombstone(item.filePath, item.contentHash);
+ tombstonedTranscripts.push(item.filePath);
+ }
+ }
+
let stoppedEarly = false;
await withBudgetTracker(budgetTracker, async () => {
for (const item of work) {
@@ -1149,29 +1164,8 @@ export async function runPhaseExtractAtoms(
const parseOutcome = parseAtomsOutcome(result.text);
if (!parseOutcome.ok) {
malformedOutputs++;
- hardFailureCount++;
if (!opts.dryRun && managed && origin) writeRequests.push(...await publishManagedAtoms(engine, managed, origin, [], parseOutcome.reason));
- const failCount = await recordItemFailureCount(item);
- failures.push({
- source: originLabel,
- error: `malformed model output: ${parseOutcome.reason}` +
- (failCount != null ? ` (consecutive failure ${failCount} on this content)` : ''),
- });
- // Content-deterministic class: the same prose reliably produces
- // unparseable output. After N consecutive failures on the SAME
- // content hash, tombstone so the backlog floor clears; a content
- // edit re-eligibilizes (stamp is hash-keyed). Transient provider
- // errors never reach here — they throw and take the catch path.
- // v146: transcripts get the identical bound, via their own store.
- if (failCount != null && failCount >= MAX_DETERMINISTIC_FAILURES && !opts.dryRun) {
- if (item.kind === 'page') {
- await stampAtomsScanHash(item);
- tombstonedForFailures.push(item.slug);
- } else {
- await stampTranscriptTombstone(item.filePath, item.contentHash);
- tombstonedTranscripts.push(item.filePath);
- }
- }
+ await recordDeterministicFailure(item, originLabel, `malformed model output: ${parseOutcome.reason}`);
continue;
}
const atoms = parseOutcome.atoms;
@@ -1379,11 +1373,17 @@ export async function runPhaseExtractAtoms(
}
// gbrain#4148: classify. Transient provider/infra errors (timeouts,
// rate limits, 5xx, network) stay retryable and are NOT counted toward
- // any tombstone. Everything else gets a durable count for
- // observability, but only the malformed-output class (handled above)
- // ever tombstones — an unknown error class must never permanently
- // suppress a page's atoms.
+ // any tombstone. A provider content block (prompt-level refusal) is
+ // content-deterministic: it takes the bounded tombstone path before the
+ // outage check. Everything else gets a durable count for observability,
+ // but an unknown error class must never permanently suppress a page's atoms.
const message = err instanceof Error ? err.message : String(err);
+ const blockReason = providerContentBlockReason(err);
+ if (blockReason) {
+ llmHalt.reset();
+ await recordDeterministicFailure(item, originLabel, `provider blocked content: ${blockReason}`);
+ continue;
+ }
// #3044: a whole-run LLM outage halts the phase. No
// recordItemFailureCount here — a global outage says nothing about the
// content, so it must not pre-charge the per-page tombstone counter.
diff --git a/test/errors.test.ts b/test/errors.test.ts
index 1981c2c8bf..7c9fe184b8 100644
--- a/test/errors.test.ts
+++ b/test/errors.test.ts
@@ -1,5 +1,29 @@
import { describe, test, expect } from 'bun:test';
import { buildError, errorFor, serializeError, StructuredAgentError } from '../src/core/errors.ts';
+import { providerContentBlockReason, normalizeAIError } from '../src/core/ai/errors.ts';
+
+describe('providerContentBlockReason', () => {
+ const blocked = Object.assign(new Error('Invalid JSON response'), {
+ name: 'AI_APICallError', statusCode: 200,
+ responseBody: JSON.stringify({ promptFeedback: { blockReason: 'PROHIBITED_CONTENT' } }),
+ });
+
+ test('recognizes a blocked response through normalization', () => {
+ expect(providerContentBlockReason(blocked)).toBe('PROHIBITED_CONTENT');
+ expect(providerContentBlockReason(normalizeAIError(blocked, 'chat(google:x)'))).toBe('PROHIBITED_CONTENT');
+ expect(providerContentBlockReason({ responseBody: JSON.stringify({ candidates: [{ finishReason: 'SAFETY', content: { parts: [] } }] }) })).toBe('SAFETY');
+ });
+
+ test('ignores ordinary provider failures and malformed bodies', () => {
+ for (const err of [
+ { statusCode: 500, responseBody: blocked.responseBody },
+ new Error('timeout'),
+ { responseBody: 'not json' },
+ { statusCode: 200 },
+ { responseBody: JSON.stringify({ candidates: [{ finishReason: 'SAFETY', content: { parts: [{ text: 'answer' }] } }] }) },
+ ]) expect(providerContentBlockReason(err)).toBeUndefined();
+ });
+});
describe('buildError', () => {
test('returns envelope with required fields only', () => {
diff --git a/test/extract-atoms-failure-classes.test.ts b/test/extract-atoms-failure-classes.test.ts
index d6852fa64b..033bb4f767 100644
--- a/test/extract-atoms-failure-classes.test.ts
+++ b/test/extract-atoms-failure-classes.test.ts
@@ -23,6 +23,7 @@ import {
import { runPhaseWithStoredPageFixtures as runPhaseExtractAtoms } from './helpers/extract-atoms-page-fixtures.ts';
import { resetPgliteState } from './helpers/reset-pglite.ts';
import type { ChatResult, ChatOpts } from '../src/core/ai/gateway.ts';
+import { normalizeAIError } from '../src/core/ai/errors.ts';
let engine: PGLiteEngine;
@@ -98,6 +99,39 @@ describe('parseAtomsOutcome — typed parse (gbrain#4148)', () => {
});
describe('runPhaseExtractAtoms — failure classes (gbrain#4148)', () => {
+ test('provider content block counts by content and tombstones without stopping other pages', async () => {
+ await engine.putPage('meetings/blocked', {
+ title: 'blocked meeting', type: 'meeting', compiled_truth: 'blocked prose '.repeat(60),
+ } as never, { sourceId: 'default' });
+ await seedPage('note/healthy');
+ const blocked = normalizeAIError(Object.assign(new Error('Invalid JSON response'), {
+ name: 'AI_APICallError', statusCode: 200,
+ responseBody: JSON.stringify({ promptFeedback: { blockReason: 'PROHIBITED_CONTENT' } }),
+ }), 'chat(google:x)');
+ const opts = {
+ sourceId: 'default', _transcripts: [],
+ _pages: [
+ { slug: 'meetings/blocked', content: 'blocked prose '.repeat(60), contentHash: HASH_A },
+ { slug: 'note/healthy', content: 'healthy prose', contentHash: 'b'.repeat(16) },
+ ],
+ _chat: async (o: ChatOpts) => {
+ if (String(o.messages[0]?.content).includes('blocked prose')) throw blocked;
+ return okChatResult('[]');
+ },
+ };
+ for (let n = 1; n <= MAX_DETERMINISTIC_FAILURES; n++) {
+ const result = await runPhaseExtractAtoms(engine, opts);
+ expect(result.details.aborted_global_error).toBeUndefined();
+ expect(result.details.pages_processed).toBe(1);
+ expect((await stateOf('meetings/blocked'))?.fail_count).toBe(n);
+ expect(result.details.tombstoned_for_failures).toEqual(n === MAX_DETERMINISTIC_FAILURES ? ['meetings/blocked'] : []);
+ expect((await stateOf('meetings/blocked'))?.tombstoned).toBe(n === MAX_DETERMINISTIC_FAILURES);
+ expect((await discoverExtractablePages(engine, 'default')).map(p => p.slug).includes('meetings/blocked'))
+ .toBe(n < MAX_DETERMINISTIC_FAILURES);
+ expect((result.details.failures as Array<{ error: string }>)[0].error).toContain(`provider blocked content: PROHIBITED_CONTENT (consecutive failure ${n}`);
+ }
+ });
+
test('prompt truncation never splits a UTF-16 surrogate pair', async () => {
await seedPage('note/surrogate-boundary');
const content = `${'a'.repeat(49_999)}💡trailing prose`;
diff --git a/test/extract-atoms-transcript-failure-classes.test.ts b/test/extract-atoms-transcript-failure-classes.test.ts
index 116b486c47..e8d9a797a7 100644
--- a/test/extract-atoms-transcript-failure-classes.test.ts
+++ b/test/extract-atoms-transcript-failure-classes.test.ts
@@ -25,6 +25,7 @@ import {
} from '../src/core/cycle/extract-atoms.ts';
import { resetPgliteState } from './helpers/reset-pglite.ts';
import type { ChatResult, ChatOpts } from '../src/core/ai/gateway.ts';
+import { normalizeAIError } from '../src/core/ai/errors.ts';
let engine: PGLiteEngine;
@@ -80,6 +81,28 @@ async function stateRow(
}
describe('transcript failure counting (v146)', () => {
+ test('a provider content block tombstones the transcript at the deterministic bound', async () => {
+ const blocked = normalizeAIError(Object.assign(new Error('Invalid JSON response'), {
+ name: 'AI_APICallError', statusCode: 200,
+ responseBody: JSON.stringify({ promptFeedback: { blockReason: 'PROHIBITED_CONTENT' } }),
+ }), 'chat(google:x)');
+ const opts = {
+ sourceId: 'default', _pages: [], _transcripts: [transcript(FILE, HASH_A)],
+ _chat: async (_o: ChatOpts): Promise<ChatResult> => { throw blocked; },
+ };
+ for (let n = 1; n <= MAX_DETERMINISTIC_FAILURES; n++) {
+ const result = await runPhaseExtractAtoms(engine, opts);
+ expect((await stateRow(FILE, HASH_A))?.fail_count).toBe(n);
+ expect(result.details.tombstoned_transcripts).toEqual(n === MAX_DETERMINISTIC_FAILURES ? [FILE] : []);
+ }
+ let calls = 0;
+ const after = await runPhaseExtractAtoms(engine, {
+ ...opts, _chat: async (_o: ChatOpts): Promise<ChatResult> => { calls++; throw blocked; },
+ });
+ expect(calls).toBe(0);
+ expect(after.details.duplicates_skipped).toBe(1);
+ });
+
test('malformed output is a COUNTED failure for a transcript, not a silent retry-forever', async () => {
const result = await runPhaseExtractAtoms(engine, {
sourceId: 'default',