Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(repair): a provider refusal raised as an error consumes the attempt memo as llm_refused
garrytan01924df9727e
diff --git a/src/core/content-repair/judgment.ts b/src/core/content-repair/judgment.tsindex 59d6321066..54dbdbd565 100644--- a/src/core/content-repair/judgment.ts+++ b/src/core/content-repair/judgment.ts@@ -22,7 +22,8 @@* holds and receipts carry codes and slugs (Codex #11). Failure classes* mirror fence-repair/llm.ts: `llm_unavailable` (the provider threw;* transient, the attempt memo is not consumed), `llm_empty`, `llm_refused`- * (a refusal or content-filter stop, or a prose refusal), `llm_malformed`+ * (a refusal or content-filter stop, a prose refusal, or a provider error+ * that refuses the request's own input), `llm_malformed`* (no single object, an unknown action, a canonical that is neither slug),* `llm_truncated` (any stop other than a normal end) and `llm_declined` (the* single word HOLD; the prompt asks for `needs_human` instead, but a modeldiff --git a/src/core/content-repair/llm.ts b/src/core/content-repair/llm.tsindex 17bbbc861f..a9f510e4ee 100644--- a/src/core/content-repair/llm.ts+++ b/src/core/content-repair/llm.ts@@ -24,12 +24,14 @@* `JUDGMENT_PROMPT_VERSION`: a verdict already given for these exact inputs* (rejected: `merge_into`, `needs_human`, an unusable answer) is returned at* $0 until one of them changes; `llm_unavailable` is transient and does not- * consume it. A published `remove_slug` changes the bytes, so its memo never+ * consume it, while a provider error that refuses this request's own input+ * (`providerItemRefusal`) is `llm_refused` and does. A published `remove_slug` changes the bytes, so its memo never* matches again.** Messages carry reason codes, slugs, hashes and dollar amounts only.*/import type { BrainEngine } from '../engine.ts';+import { providerItemRefusal } from '../ai/errors.ts';import { chat, isThinkingModel, THINKING_MODEL_MAX_OUTPUT_TOKENS, type ChatResult } from '../ai/gateway.ts';import { thinkingOffControl, thinkingOffMaxOutputTokens } from '../ai/thinking-off.ts';import { mergedProviderEnv } from '../ai/provider-env.ts';@@ -121,7 +123,7 @@ export async function askJudgment(input: JudgmentInput, opts: { model: string; tresult = await chat({ model: opts.model, system: typeof system!.content === 'string' ? system!.content : '', messages, maxTokens: budget.maxOutputTokens, allowFallback: false,thinking: 'off', purpose: 'content_repair', ...(opts.timeoutMs ? { timeoutMs: opts.timeoutMs } : {}), ...(opts.signal ? { abortSignal: opts.signal } : {}) });} catch (error) {- return { ok: false, reason: 'llm_unavailable', error: error instanceof Error ? error.name : 'Error' };+ return { ok: false, reason: providerItemRefusal(error) ? 'llm_refused' : 'llm_unavailable', error: error instanceof Error ? error.name : 'Error' };}const parsed = parseJudgmentAnswer(result, { held: input.held.slug, named: input.named?.slug ?? null });if (!parsed.ok) return { ok: false, reason: parsed.reason, text: result.text, result };diff --git a/src/core/fence-repair/llm-tail.ts b/src/core/fence-repair/llm-tail.tsindex 4e834edb7d..0fbad2ee06 100644--- a/src/core/fence-repair/llm-tail.ts+++ b/src/core/fence-repair/llm-tail.ts@@ -26,6 +26,7 @@*/import { chat, isThinkingModel, THINKING_MODEL_MAX_OUTPUT_TOKENS, type ChatMessage, type ChatResult } from '../ai/gateway.ts';import { thinkingOffControl, thinkingOffMaxOutputTokens } from '../ai/thinking-off.ts';+import { providerItemRefusal } from '../ai/errors.ts';import { extractRawRows, primaryFence } from './raw-rows.ts';import { sectionsOf } from './page-checks.ts';import { tailAmbiguous, trailingLines } from './structure.ts';@@ -144,7 +145,7 @@ export async function callTailClassifier(req: TailRequest, opts: { model: stringresult = await chat({ model: opts.model, system: prompt.system, messages, maxTokens: budget.maxOutputTokens, allowFallback: false,thinking: 'off', purpose: 'fence_repair', ...(opts.timeoutMs ? { timeoutMs: opts.timeoutMs } : {}), ...(opts.signal ? { abortSignal: opts.signal } : {}) });} catch (error) {- return { ok: false, reason: 'llm_unavailable', error: error instanceof Error ? error.name : 'Error' };+ return { ok: false, reason: providerItemRefusal(error) ? 'llm_refused' : 'llm_unavailable', error: error instanceof Error ? error.name : 'Error' };}if (result.stopReason === 'refusal' || result.stopReason === 'content_filter') return { ok: false, reason: 'llm_refused', text: result.text, result };if (result.stopReason !== 'end') return { ok: false, reason: result.text.trim() ? 'llm_truncated' : 'llm_empty', text: result.text, result };diff --git a/src/core/fence-repair/llm.ts b/src/core/fence-repair/llm.tsindex fb8f9b31d7..167da5d1e0 100644--- a/src/core/fence-repair/llm.ts+++ b/src/core/fence-repair/llm.ts@@ -15,8 +15,9 @@* wrapping code fence is tolerated; any other text outside the table is* `llm_malformed`. Failure classes: `llm_unavailable` (the provider threw:* timeout, rate limit, server error; transient, the attempt memo is not- * consumed), `llm_empty`, `llm_refused` (refusal or content-filter stop, or a- * prose refusal), `llm_malformed` (no single table, wrong header, prose),+ * consumed), `llm_empty`, `llm_refused` (refusal or content-filter stop, a+ * prose refusal, or a provider error that refuses this request's own input,+ * `providerItemRefusal`: it fails the same way until the bytes change), `llm_malformed` (no single table, wrong header, prose),* `llm_truncated` (any stop other than a normal end, rejected even if the* text parses), `llm_declined` (the single word HOLD: a row has more than one* reasonable reading, so the model declines instead of guessing). A table@@ -34,6 +35,7 @@* `spliceTier3`) do no I/O; `callTier3` is the one gateway call, testable* through the gateway's chat transport seam (`__setChatTransportForTests`).*/+import { providerItemRefusal } from '../ai/errors.ts';import { chat, isThinkingModel, THINKING_MODEL_MAX_OUTPUT_TOKENS, type ChatMessage, type ChatResult } from '../ai/gateway.ts';import { thinkingOffControl, thinkingOffMaxOutputTokens } from '../ai/thinking-off.ts';import { isSeparatorRow, parseRowCells } from '../fence-shared.ts';@@ -285,7 +287,7 @@ export async function callTier3(req: Tier3Request, opts: Tier3CallOptions): Promresult = await chat({ model: opts.model, system: prompt.system, messages, maxTokens: budget.maxOutputTokens, allowFallback: false,thinking: 'off', purpose: 'fence_repair', ...(opts.timeoutMs ? { timeoutMs: opts.timeoutMs } : {}), ...(opts.signal ? { abortSignal: opts.signal } : {}) });} catch (error) {- return { ok: false, reason: 'llm_unavailable', error: error instanceof Error ? error.name : 'Error' };+ return { ok: false, reason: providerItemRefusal(error) ? 'llm_refused' : 'llm_unavailable', error: error instanceof Error ? error.name : 'Error' };}if (result.stopReason === 'refusal' || result.stopReason === 'content_filter') return { ok: false, reason: 'llm_refused', text: result.text, result };if (result.stopReason !== 'end') return { ok: false, reason: result.text.trim() ? 'llm_truncated' : 'llm_empty', text: result.text, result };diff --git a/test/content-repair-llm.test.ts b/test/content-repair-llm.test.tsnew file mode 100644index 0000000000..a837c153e0--- /dev/null+++ b/test/content-repair-llm.test.ts@@ -0,0 +1,84 @@+/**+ * The content-repair judgment call's attempt memo (src/core/content-repair/llm.ts callJudgment).+ *+ * Protects: a provider refusal of the prompt raised as an error (a+ * content-policy 400, a prompt block, a context overflow) is a verdict on+ * these exact bytes: it is held as `llm_refused` and consumes the memo, so+ * the next pass on unchanged inputs spends $0 and sends nothing; a plain+ * provider error (429, timeout) stays `llm_unavailable` and the next pass+ * asks again.+ * Fails when: the catch in askJudgment folds a refusal into+ * `llm_unavailable`, so every maintenance pass re-sends the same bytes and+ * the ledger settles the full estimate again.+ * Why new: repair-slug-conflicts.test.ts covers the transient 429 end to end+ * but no test raised a refusal as an error through callJudgment.+ * Seams: the gateway's chat transport seam (__setChatTransportForTests).+ */+import { afterAll, afterEach, beforeAll, describe, expect, test } from 'bun:test';+import { __setChatTransportForTests, configureGateway, resetGateway, type ChatOpts, type ChatResult } from '../src/core/ai/gateway.ts';+import { judgmentParticipant, type JudgmentInput } from '../src/core/content-repair/judgment.ts';+import { callJudgment, judgmentCandidate } from '../src/core/content-repair/llm.ts';+import { attemptStore } from '../src/core/fence-repair/attempts.ts';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';++const model = 'anthropic:claude-opus-5-5';+const answer = (text: string): ChatResult => ({ text, blocks: [], stopReason: 'end', usage: { input_tokens: 400, output_tokens: 30, cache_read_tokens: 0, cache_creation_tokens: 0 },+ model, providerId: 'anthropic' });+const policyRefusal = () => Object.assign(new Error('Bad Request'), { name: 'AI_APICallError', statusCode: 400,+ responseBody: JSON.stringify({ error: { code: 'content_policy_violation', message: 'flagged' } }) });++const input = (): JudgmentInput => ({+ held: judgmentParticipant({ path: 'people/alice-example-2.md', slug: 'people/alice-example-2', content: '---\ntitle: Alice Example\ntype: person\nslug: people/alice-example\n---\nA synthetic founder.\n', otherSlug: 'people/alice-example' }),+ named: judgmentParticipant({ path: 'people/alice-example.md', slug: 'people/alice-example', content: '---\ntitle: Alice Example\ntype: person\n---\nA synthetic founder.\n', otherSlug: 'people/alice-example-2', type: 'person' }),+ reason: 'frontmatter_slug_conflict',+});++let engine: PGLiteEngine;+let incarnation: string;+let calls: ChatOpts[] = [];++function transport(reply: () => ChatResult | Error) {+ calls = [];+ __setChatTransportForTests(async opts => { calls.push(opts); const out = reply(); if (out instanceof Error) throw out; return out; });+}++const judge = (path: string) => callJudgment(engine, model, input(), { sourceId: 'default', incarnation, path,+ memo: { heldSha256: 'a'.repeat(64), namedSha256: 'b'.repeat(64), heldPageId: null, namedPageId: null },+ capSource: 'default', perPageUsd: 1, perDayUsd: 10, timeoutMs: 30_000 });++beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+ const [src] = await engine.executeRaw<{ incarnation: string }>("SELECT incarnation::text AS incarnation FROM sources WHERE id='default'");+ incarnation = src!.incarnation;+ configureGateway({ providers: { anthropic: { apiKey: 'test' } } } as never);+});+afterEach(() => __setChatTransportForTests(null));+afterAll(async () => {+ resetGateway();+ await engine.disconnect();+});++describe('callJudgment: a provider refusal raised as an error', () => {+ test('a content-policy 400 is held as llm_refused and consumes the memo: the same inputs are never sent again', async () => {+ transport(policyRefusal);+ const first = await judge('people/alice-example-2.md');+ expect(calls).toHaveLength(1);+ expect(first).toMatchObject({ ok: false, reason: 'llm_refused' });+ expect(await attemptStore(engine).read(judgmentCandidate('default', incarnation, 'people/alice-example-2.md'))).toMatchObject({ state: 'rejected', reason: 'llm_refused' });+ transport(() => answer('{"action":"needs_human"}'));+ const again = await judge('people/alice-example-2.md');+ expect(calls).toHaveLength(0);+ expect(again).toMatchObject({ ok: false, reason: 'llm_refused', memoHit: true, spentUsd: 0 });+ });++ test('a rate limit stays llm_unavailable and leaves the memo open, so the next pass asks again', async () => {+ transport(() => Object.assign(new Error('rate limited'), { status: 429 }));+ expect(await judge('people/bob-example-2.md')).toMatchObject({ ok: false, reason: 'llm_unavailable' });+ expect((await attemptStore(engine).read(judgmentCandidate('default', incarnation, 'people/bob-example-2.md')))?.state).not.toBe('rejected');+ transport(() => answer('{"action":"needs_human"}'));+ expect(await judge('people/bob-example-2.md')).toMatchObject({ ok: true, verdict: { action: 'needs_human' } });+ expect(calls).toHaveLength(1);+ });+});diff --git a/test/fence-repair-llm-tail.test.ts b/test/fence-repair-llm-tail.test.tsindex 3fa397c70c..312d0b498c 100644--- a/test/fence-repair-llm-tail.test.ts+++ b/test/fence-repair-llm-tail.test.ts@@ -169,4 +169,15 @@ describe('the tail tier through runTier3 (#6377)', () => {const memo = await attemptStore(engine).read({ sourceId: 'default', incarnation, key: 'slug:tail/down' });expect(memo?.state).not.toBe('rejected');});++ test('a provider refusal raised as an error is held as llm_refused and consumes the memo: the same bytes are never sent again', async () => {+ const refusal = Object.assign(new Error('Bad Request'), { name: 'AI_APICallError', statusCode: 400, responseBody: JSON.stringify({ error: { code: 'content_policy_violation', message: 'flagged' } }) });+ const first = await attempt('tail/policy', 'private', [refusal]);+ expect(first.calls).toHaveLength(1);+ expect(first.out).toMatchObject({ ok: false, reason: 'llm_refused' });+ expect(await attemptStore(engine).read(attemptCandidate(first.target, incarnation))).toMatchObject({ state: 'rejected', reason: 'llm_refused' });+ const again = await attempt('tail/policy', 'private', [result('{"tail":"prose"}')]);+ expect(again.calls).toHaveLength(0);+ expect(again.out).toMatchObject({ ok: false, reason: 'llm_refused', memoHit: true, spentUsd: 0 });+ });});diff --git a/test/fence-repair-llm.test.ts b/test/fence-repair-llm.test.tsindex 13f139868a..1b716cdd5c 100644--- a/test/fence-repair-llm.test.ts+++ b/test/fence-repair-llm.test.ts@@ -207,7 +207,7 @@ describe('runTier3: the re-ask and the decline', () => {});afterAll(async () => { await engine.disconnect(); });- async function attempt(slug: string, answers: ChatResult[]) {+ async function attempt(slug: string, answers: Array<ChatResult | Error>) {const page = { compiled_truth: rowLevel, timeline: '' };const target: FenceTarget = { mode: 'db', sourceId: 'default', key: slug, slug, path: null, sourcePath: null, page, content: null, before: pageSha(page), snapshot: null, hold: null,ctx: { pageVisibility: 'private' } } as FenceTarget;@@ -246,8 +246,26 @@ describe('runTier3: the re-ask and the decline', () => {expect(again.calls).toHaveLength(0);expect(again.out).toMatchObject({ ok: false, reason: 'llm_declined', memoHit: true, spentUsd: 0 });});++ test('a provider refusal raised as an error is held as llm_refused and consumes the memo; a plain provider error stays transient', async () => {+ const first = await attempt('t3/policy', [policyRefusal()]);+ expect(first.calls).toHaveLength(1);+ expect(first.out).toMatchObject({ ok: false, reason: 'llm_refused' });+ const again = await attempt('t3/policy', [result(fixed)]);+ expect(again.calls).toHaveLength(0);+ expect(again.out).toMatchObject({ ok: false, reason: 'llm_refused', memoHit: true, spentUsd: 0 });+ expect((await attempt('t3/down', [Object.assign(new Error('rate limited'), { status: 429 })])).out).toMatchObject({ ok: false, reason: 'llm_unavailable' });+ const retried = await attempt('t3/down', [result(fixed)]);+ expect(retried.calls).toHaveLength(1);+ expect(retried.out.ok).toBe(true);+ expect(await reasonOf(residualOf(rowLevel).requests[0]!, Object.assign(new Error('This model maximum context length is 8192 tokens'), { status: 400 }))).toBe('llm_refused');+ });});+function policyRefusal(): Error {+ return Object.assign(new Error('Bad Request'), { name: 'AI_APICallError', statusCode: 400, responseBody: JSON.stringify({ error: { code: 'content_policy_violation', message: 'flagged' } }) });+}+async function reasonOf(req: Parameters<typeof callTier3>[0], answer: ChatResult | Error): Promise<string> {stub([answer]);const out = await callTier3(req, { model: 'anthropic:claude-opus-4-7' });