fix: treat Claude safeguards refusals as failures, reset the session

Claude Code returns "API Error: <model>'s safeguards flagged this message"
as a success-typed result. EJClaw delivered it as the owner's answer,
handed it to reviewer/arbiter, resumed the refused session (refused again)
and carried the banner forward into the next task.

Now it is a `safety-refusal` trigger: the raw banner is suppressed, the
Claude session is cleared, the paired task closes as
`claude_safety_refusal`, the room gets a short Korean notice, and refusal
banners are never carried forward. Global memory gains a rule not to read
thinking blocks from session transcripts (the reasoning_extraction trigger
of the 2026-10-12 incident).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Codex
2026-10-12 13:17:22 +09:00
parent e22feb0215
commit f579b4f406
11 changed files with 240 additions and 13 deletions

View File

@@ -32,6 +32,7 @@ Stored at `/home/claude/.config/ejclaw/secrets.json` (read with the Read tool wh
- All rooms are `tribunal` (owner + reviewer + arbiter) unless the user asks for single mode in that room ("리뷰어 끄자", "single로 바꿔줘"). Commands: `ops/ejclaw-ops.md`. - All rooms are `tribunal` (owner + reviewer + arbiter) unless the user asks for single mode in that room ("리뷰어 끄자", "single로 바꿔줘"). Commands: `ops/ejclaw-ops.md`.
- "채널 등록 해제 <id>" means a full purge with `bun scripts/deregister-room.ts` (dry-run first, DB backup first). Details: `ops/ejclaw-ops.md`. - "채널 등록 해제 <id>" means a full purge with `bun scripts/deregister-room.ts` (dry-run first, DB backup first). Details: `ops/ejclaw-ops.md`.
- A short stop-only message ("그만해", "멈춰", "중단", "stop") stops the room's running work; this is built in. - A short stop-only message ("그만해", "멈춰", "중단", "stop") stops the room's running work; this is built in.
- Resuming interrupted work: rebuild context from chat messages, `conversations/`, git state and visible tool results only. Never read or dump `thinking` blocks from Claude session transcripts (`data/sessions/**/*.jsonl`); that trips Opus safeguards (`reasoning_extraction`) and the whole turn is refused (incident 2026-10-12).
# CLAUDE.md # CLAUDE.md
@@ -44,6 +45,7 @@ Behavioral guidelines to reduce common LLM coding mistakes. Merge with project-s
**Don't assume. Don't hide confusion. Surface tradeoffs.** **Don't assume. Don't hide confusion. Surface tradeoffs.**
Before implementing: Before implementing:
- State your assumptions explicitly. If uncertain, ask. - State your assumptions explicitly. If uncertain, ask.
- If multiple interpretations exist, present them - don't pick silently. - If multiple interpretations exist, present them - don't pick silently.
- If a simpler approach exists, say so. Push back when warranted. - If a simpler approach exists, say so. Push back when warranted.
@@ -66,12 +68,14 @@ Ask yourself: "Would a senior engineer say this is overcomplicated?" If yes, sim
**Touch only what you must. Clean up only your own mess.** **Touch only what you must. Clean up only your own mess.**
When editing existing code: When editing existing code:
- Don't "improve" adjacent code, comments, or formatting. - Don't "improve" adjacent code, comments, or formatting.
- Don't refactor things that aren't broken. - Don't refactor things that aren't broken.
- Match existing style, even if you'd do it differently. - Match existing style, even if you'd do it differently.
- If you notice unrelated dead code, mention it - don't delete it. - If you notice unrelated dead code, mention it - don't delete it.
When your changes create orphans: When your changes create orphans:
- Remove imports/variables/functions that YOUR changes made unused. - Remove imports/variables/functions that YOUR changes made unused.
- Don't remove pre-existing dead code unless asked. - Don't remove pre-existing dead code unless asked.
@@ -82,11 +86,13 @@ The test: Every changed line should trace directly to the user's request.
**Define success criteria. Loop until verified.** **Define success criteria. Loop until verified.**
Transform tasks into verifiable goals: Transform tasks into verifiable goals:
- "Add validation" → "Write tests for invalid inputs, then make them pass" - "Add validation" → "Write tests for invalid inputs, then make them pass"
- "Fix the bug" → "Write a test that reproduces it, then make it pass" - "Fix the bug" → "Write a test that reproduces it, then make it pass"
- "Refactor X" → "Ensure tests pass before and after" - "Refactor X" → "Ensure tests pass before and after"
For multi-step tasks, state a brief plan: For multi-step tasks, state a brief plan:
``` ```
1. [Step] → verify: [check] 1. [Step] → verify: [check]
2. [Step] → verify: [check] 2. [Step] → verify: [check]

View File

@@ -6,9 +6,31 @@ import {
classifyCodexAuthError, classifyCodexAuthError,
detectClaudeProviderFailureMessage, detectClaudeProviderFailureMessage,
isClaudeOrgAccessDeniedMessage, isClaudeOrgAccessDeniedMessage,
isClaudeSafetyRefusalMessage,
} from './agent-error-detection.js'; } from './agent-error-detection.js';
describe('agent-error-detection', () => { describe('agent-error-detection', () => {
it('detects the Claude Code safeguards refusal banner', () => {
expect(
isClaudeSafetyRefusalMessage(
"API Error: Opus 5.5's safeguards flagged this message (https://www.anthropic.com/legal/aup). This sometimes happens with safe, normal conversations. Claude Code can't respond to this message with Opus 5.5.\n\nDetails: `[reasoning_extraction]`\n\nRequest ID: req_011Cfw4r8TmDHL1ppiVovmBr",
),
).toBe(true);
expect(
isClaudeSafetyRefusalMessage(
'API Error: Opus 5.5\u2019s safeguards flagged this message.',
),
).toBe(true);
});
it('does not treat an answer that quotes the refusal banner as a refusal', () => {
expect(
isClaudeSafetyRefusalMessage(
'TASK_DONE\n원인: "API Error: ... safeguards flagged this message" 가 반복됐습니다.',
),
).toBe(false);
});
it('detects Claude org access denied banners', () => { it('detects Claude org access denied banners', () => {
expect( expect(
isClaudeOrgAccessDeniedMessage( isClaudeOrgAccessDeniedMessage(

View File

@@ -80,6 +80,28 @@ export function detectClaudeProviderFailureMessage(
return ''; return '';
} }
/**
* Claude Code's synthetic refusal banner when the model's safeguards block a
* request ("API Error: Opus 5.5's safeguards flagged this message ...").
* The CLI reports it as a success-typed result, so without this check it is
* delivered to the room as if it were the agent's answer.
*/
export function isClaudeSafetyRefusalMessage(text: string): boolean {
const normalized = text
.trim()
.toLowerCase()
.replace(/[\u2018\u2019`]/g, "'")
.replace(/\s+/g, ' ');
const looksLikeApiError =
normalized.startsWith('api error:') ||
normalized.startsWith('error: api error:');
return (
looksLikeApiError &&
(normalized.includes('safeguards flagged this message') ||
normalized.includes("can't respond to this message with"))
);
}
export function isClaudeOrgAccessDeniedMessage(text: string): boolean { export function isClaudeOrgAccessDeniedMessage(text: string): boolean {
const normalized = text.trim().toLowerCase().replace(/\s+/g, ' '); const normalized = text.trim().toLowerCase().replace(/\s+/g, ' ');
const hasOrgAccessDeniedMarker = normalized.includes( const hasOrgAccessDeniedMarker = normalized.includes(
@@ -103,6 +125,7 @@ export type AgentTriggerReason =
| 'overloaded' | 'overloaded'
| 'network-error' | 'network-error'
| 'success-null-result' | 'success-null-result'
| 'safety-refusal'
| 'session-failure'; | 'session-failure';
export type CodexTriggerReason = Extract< export type CodexTriggerReason = Extract<

View File

@@ -143,11 +143,26 @@ class MessageAgentAttemptLifecycleRunner {
}); });
} }
/**
* A safeguards refusal stays in the resumed session and gets refused again
* on every later turn, so drop the session no matter which path reports it.
*/
private clearSessionAfterSafetyRefusal(reason: AgentTriggerReason): void {
if (reason !== 'safety-refusal' || !this.args.isClaudeCodeAgent) return;
this.args.clearStoredSession();
this.args.clearRoleSdkSessions();
this.args.log.warn(
{ sessionFolder: this.args.sessionFolder },
'Cleared Claude session after a safeguards refusal',
);
}
private async reportUsageLimitAfterError( private async reportUsageLimitAfterError(
reason: AgentTriggerReason, reason: AgentTriggerReason,
attempt: MessageAgentAttempt, attempt: MessageAgentAttempt,
errorText?: string | null, errorText?: string | null,
): Promise<AttemptResult> { ): Promise<AttemptResult> {
this.clearSessionAfterSafetyRefusal(reason);
const reported = await this.args.reportClaudeUsageLimit({ const reported = await this.args.reportClaudeUsageLimit({
reason, reason,
errorText: errorText ?? describeAttemptError(attempt), errorText: errorText ?? describeAttemptError(attempt),
@@ -409,6 +424,7 @@ class MessageAgentAttemptLifecycleRunner {
if (!attempt.streamedTriggerReason || !this.args.isClaudeCodeAgent) { if (!attempt.streamedTriggerReason || !this.args.isClaudeCodeAgent) {
return false; return false;
} }
this.clearSessionAfterSafetyRefusal(attempt.streamedTriggerReason.reason);
return this.args.reportClaudeUsageLimit({ return this.args.reportClaudeUsageLimit({
reason: attempt.streamedTriggerReason.reason, reason: attempt.streamedTriggerReason.reason,
errorText: describeAttemptError(attempt), errorText: describeAttemptError(attempt),

View File

@@ -213,7 +213,10 @@ import type { AgentOutput } from './agent-runner.js';
import * as db from './db.js'; import * as db from './db.js';
import { logger } from './logger.js'; import { logger } from './logger.js';
import { buildRoomMemoryBriefing } from './sqlite-memory-store.js'; import { buildRoomMemoryBriefing } from './sqlite-memory-store.js';
import { runAgentForGroup } from './message-agent-executor.js'; import {
CLAUDE_SAFETY_REFUSAL_NOTICE,
runAgentForGroup,
} from './message-agent-executor.js';
import { resetPairedFollowUpScheduleState } from './paired-follow-up-scheduler.js'; import { resetPairedFollowUpScheduleState } from './paired-follow-up-scheduler.js';
import * as pairedExecutionContext from './paired-execution-context.js'; import * as pairedExecutionContext from './paired-execution-context.js';
import * as pairedFinalize from './paired-finalize.js'; import * as pairedFinalize from './paired-finalize.js';
@@ -3155,6 +3158,86 @@ describe('runAgentForGroup Claude failure recovery', () => {
]); ]);
}); });
it('closes the task, clears the session and posts a notice on a safeguards refusal', async () => {
const outputs: string[] = [];
const refusal =
"API Error: Opus 5.5's safeguards flagged this message (https://www.anthropic.com/legal/aup). This sometimes happens with safe, normal conversations. Claude Code can't respond to this message with Opus 5.5.\n\nTry rephrasing the request in a new session or change your model.\n\nRequest ID: req_test";
const pairedTask = {
id: 'paired-task-safety-refusal',
chat_jid: 'group@test',
group_folder: 'test-claude',
owner_service_id: 'claude',
reviewer_service_id: 'codex-review',
title: null,
source_ref: 'HEAD',
plan_notes: null,
round_trip_count: 0,
review_requested_at: null,
status: 'active' as const,
arbiter_verdict: null,
arbiter_requested_at: null,
completion_reason: null,
created_at: '2026-04-06T00:00:00.000Z',
updated_at: '2026-04-06T00:00:00.000Z',
};
vi.mocked(
pairedExecutionContext.preparePairedExecutionContext,
).mockReturnValue({ task: pairedTask, workspace: null, envOverrides: {} });
vi.mocked(db.getPairedTaskById).mockReturnValue(pairedTask);
vi.mocked(db.updatePairedTaskIfUnchanged).mockReturnValue(true);
vi.mocked(agentRunner.runAgentProcess).mockImplementationOnce(
async (_group, _input, _onProcess, onOutput) => {
await onOutput?.({
status: 'success',
result: refusal,
phase: 'intermediate',
});
await onOutput?.({ status: 'success', result: refusal });
return {
status: 'success',
result: refusal,
newSessionId: 'session-refused',
};
},
);
const deps = makeDeps();
const result = await runAgentForGroup(deps, {
group: makeGroup(),
prompt: 'hello',
chatJid: 'group@test',
runId: 'run-safety-refusal',
onOutput: async (output) => {
const text =
output.output && 'text' in output.output
? output.output.text
: output.result;
if (typeof text === 'string') outputs.push(text);
},
});
expect(result).toBe('success');
expect(agentRunner.runAgentProcess).toHaveBeenCalledTimes(1);
expect(deps.clearSession).toHaveBeenCalled();
expect(db.updatePairedTaskIfUnchanged).toHaveBeenCalledWith(
'paired-task-safety-refusal',
'2026-04-06T00:00:00.000Z',
expect.objectContaining({
status: 'completed',
completion_reason: 'claude_safety_refusal',
}),
);
expect(
pairedExecutionContext.completePairedExecutionContext,
).toHaveBeenCalledWith(
expect.objectContaining({
taskId: 'paired-task-safety-refusal',
status: 'failed',
}),
);
expect(outputs).toEqual([CLAUDE_SAFETY_REFUSAL_NOTICE]);
});
it('returns error after repeated retryable Claude session failures', async () => { it('returns error after repeated retryable Claude session failures', async () => {
vi.mocked( vi.mocked(
sessionRecovery.shouldRetryFreshSessionOnAgentFailure, sessionRecovery.shouldRetryFreshSessionOnAgentFailure,

View File

@@ -33,6 +33,12 @@ import {
/** completion_reason of a paired task closed because Claude ran out of usage. */ /** completion_reason of a paired task closed because Claude ran out of usage. */
export const CLAUDE_USAGE_LIMIT_COMPLETION_REASON = 'claude_usage_limit'; export const CLAUDE_USAGE_LIMIT_COMPLETION_REASON = 'claude_usage_limit';
/** completion_reason of a paired task closed because Claude's safeguards refused it. */
export const CLAUDE_SAFETY_REFUSAL_COMPLETION_REASON = 'claude_safety_refusal';
export const CLAUDE_SAFETY_REFUSAL_NOTICE =
'Claude 안전 필터가 이 요청을 차단해서 처리하지 못했습니다. 이 방의 Claude 세션은 초기화했습니다. 요청을 조금 바꿔서 다시 보내 주세요. 에러 원문은 붙이지 말아 주세요.';
function buildPromptWithCompactRefresh(args: { function buildPromptWithCompactRefresh(args: {
prompt: string; prompt: string;
sessionFolder: string; sessionFolder: string;
@@ -69,9 +75,10 @@ interface ClaudeUsageLimitFailure {
} }
/** /**
* When a Claude run failed because the account is out of usage, close the * When a Claude run failed because the account is out of usage, or because
* paired task (nothing should retry against the exhausted account; the next * the model's safeguards refused the request, close the paired task (retrying
* user message starts a new task) and tell the room when Claude resets. * cannot help; the next user message starts a new task) and tell the room.
* The refusal is never handed to the reviewer/arbiter as if it were an answer.
* Returns false for any other failure. * Returns false for any other failure.
*/ */
async function reportClaudeUsageLimitToRoom( async function reportClaudeUsageLimitToRoom(
@@ -87,23 +94,34 @@ async function reportClaudeUsageLimitToRoom(
log: { warn: (obj: Record<string, unknown>, msg: string) => void }; log: { warn: (obj: Record<string, unknown>, msg: string) => void };
}, },
): Promise<boolean> { ): Promise<boolean> {
if (!args.isClaudeCodeAgent || !isClaudeUsageLimitReason(args.reason)) { if (!args.isClaudeCodeAgent) return false;
const isSafetyRefusal = args.reason === 'safety-refusal';
if (!isSafetyRefusal && !isClaudeUsageLimitReason(args.reason)) {
return false; return false;
} }
const notice = buildClaudeUsageLimitMessage(args.errorText); const notice = isSafetyRefusal
? CLAUDE_SAFETY_REFUSAL_NOTICE
: buildClaudeUsageLimitMessage(args.errorText);
const task = args.pairedTaskId const task = args.pairedTaskId
? getPairedTaskById(args.pairedTaskId) ? getPairedTaskById(args.pairedTaskId)
: undefined; : undefined;
if (task) { if (task) {
completePairedTaskWithReason(task, CLAUDE_USAGE_LIMIT_COMPLETION_REASON); completePairedTaskWithReason(
task,
isSafetyRefusal
? CLAUDE_SAFETY_REFUSAL_COMPLETION_REASON
: CLAUDE_USAGE_LIMIT_COMPLETION_REASON,
);
} }
args.log.warn( args.log.warn(
{ reason: args.reason, role: args.activeRole, notice }, { reason: args.reason, role: args.activeRole, errorText: args.errorText },
'Claude usage limit reached; told the room when it resets', isSafetyRefusal
? 'Claude safeguards refused the request; closed the task and told the room'
: 'Claude usage limit reached; told the room when it resets',
); );
await deliverNoticeAndFailExecution({ await deliverNoticeAndFailExecution({
notice, notice,
summary: args.errorText ?? notice, summary: isSafetyRefusal ? notice : (args.errorText ?? notice),
pairedExecutionLifecycle: args.pairedExecutionLifecycle, pairedExecutionLifecycle: args.pairedExecutionLifecycle,
onOutput: args.onOutput, onOutput: args.onOutput,
}); });

View File

@@ -246,6 +246,36 @@ describe('paired execution carry-forward attachments', () => {
); );
}); });
it('never carries a Claude safeguards refusal banner forward', () => {
vi.clearAllMocks();
const previousTask = buildTask({
id: 'task-refused',
status: 'completed',
completion_reason: 'claude_safety_refusal',
});
vi.mocked(db.getLatestOpenPairedTaskForChat).mockReturnValue(undefined);
vi.mocked(db.getLatestPairedTaskForChat).mockReturnValue(previousTask);
vi.mocked(db.getPairedTurnOutputs).mockReturnValue([
{
id: 1,
task_id: previousTask.id,
turn_number: 1,
role: 'owner',
output_text:
"API Error: Opus 5.5's safeguards flagged this message (https://www.anthropic.com/legal/aup). This sometimes happens with safe, normal conversations. Claude Code can't respond to this message with Opus 5.5.",
created_at: '2026-03-28T00:01:00.000Z',
},
]);
resolveOwnerTaskForHumanMessage({
group,
chatJid: 'dc:test',
roomRoleContext: ownerContext,
});
expect(db.insertPairedTurnOutput).not.toHaveBeenCalled();
});
it('carries the arbiter verdict forward when the previous task ended on an arbiter escalation', () => { it('carries the arbiter verdict forward when the previous task ended on an arbiter escalation', () => {
vi.clearAllMocks(); vi.clearAllMocks();
const previousTask = buildTask({ const previousTask = buildTask({

View File

@@ -16,6 +16,7 @@ import {
PAIRED_CARRY_FORWARD_LATEST_OWNER_FINAL, PAIRED_CARRY_FORWARD_LATEST_OWNER_FINAL,
REVIEWER_AGENT_TYPE, REVIEWER_AGENT_TYPE,
} from './config.js'; } from './config.js';
import { isClaudeSafetyRefusalMessage } from './agent-error-detection.js';
import { import {
cancelPairedTurn, cancelPairedTurn,
createPairedTask, createPairedTask,
@@ -262,9 +263,12 @@ function getLatestUserFacingFinalOutput(
// are internal). Whichever of those the previous task ended on is what the // are internal). Whichever of those the previous task ended on is what the
// user is replying to next — e.g. an arbiter ESCALATE asking them to choose. // user is replying to next — e.g. an arbiter ESCALATE asking them to choose.
// So carry the chronologically-latest owner/arbiter final forward. // So carry the chronologically-latest owner/arbiter final forward.
// A stored safeguards refusal banner is not context; carrying it into the
// next task only re-feeds the refused turn's error to the model.
const userFacingOutputs = [...getPairedTurnOutputs(taskId)] const userFacingOutputs = [...getPairedTurnOutputs(taskId)]
.reverse() .reverse()
.filter((output) => output.role === 'owner' || output.role === 'arbiter'); .filter((output) => output.role === 'owner' || output.role === 'arbiter')
.filter((output) => !isClaudeSafetyRefusalMessage(output.output_text));
return ( return (
userFacingOutputs.find( userFacingOutputs.find(
(output) => !isIntermediateStepOutput(output.output_text), (output) => !isIntermediateStepOutput(output.output_text),

View File

@@ -15,6 +15,9 @@ const SESSION_RESET_PATTERNS = [
// loops forever on the same error. Drop it so the next turn starts fresh. // loops forever on the same error. Drop it so the next turn starts fresh.
/prompt is too long/i, /prompt is too long/i,
/input length and .*exceed context limit/i, /input length and .*exceed context limit/i,
// Model safeguards refusal: the flagged content stays in the resumed
// session, so every later turn in it is refused again. Start fresh.
/safeguards flagged this message/i,
]; ];
const SESSION_RETRY_PATTERNS = [ const SESSION_RETRY_PATTERNS = [

View File

@@ -8,6 +8,7 @@ vi.mock('./agent-error-detection.js', () => ({
classifyClaudeTrigger: vi.fn(() => ({ shouldRetry: false, reason: '' })), classifyClaudeTrigger: vi.fn(() => ({ shouldRetry: false, reason: '' })),
detectClaudeProviderFailureMessage: vi.fn(() => ''), detectClaudeProviderFailureMessage: vi.fn(() => ''),
isClaudeUsageExhaustedMessage: vi.fn(() => false), isClaudeUsageExhaustedMessage: vi.fn(() => false),
isClaudeSafetyRefusalMessage: vi.fn(() => false),
isClaudeOrgAccessDeniedMessage: vi.fn(() => false), isClaudeOrgAccessDeniedMessage: vi.fn(() => false),
isClaudeAuthExpiredMessage: vi.fn(() => false), isClaudeAuthExpiredMessage: vi.fn(() => false),
isClaudeAuthError: vi.fn(() => false), isClaudeAuthError: vi.fn(() => false),
@@ -27,6 +28,7 @@ import {
classifyClaudeTrigger, classifyClaudeTrigger,
detectClaudeProviderFailureMessage, detectClaudeProviderFailureMessage,
isClaudeUsageExhaustedMessage, isClaudeUsageExhaustedMessage,
isClaudeSafetyRefusalMessage,
isClaudeOrgAccessDeniedMessage, isClaudeOrgAccessDeniedMessage,
isClaudeAuthExpiredMessage, isClaudeAuthExpiredMessage,
isClaudeAuthError, isClaudeAuthError,
@@ -75,6 +77,7 @@ function errorOutput(error: string): AgentOutput {
beforeEach(() => { beforeEach(() => {
vi.clearAllMocks(); vi.clearAllMocks();
vi.mocked(isClaudeSafetyRefusalMessage).mockReturnValue(false);
vi.mocked(classifyClaudeAuthError).mockReturnValue({ vi.mocked(classifyClaudeAuthError).mockReturnValue({
category: 'none', category: 'none',
reason: '', reason: '',
@@ -157,6 +160,22 @@ describe('evaluateStreamedOutput', () => {
}); });
}); });
describe('Claude safeguards refusal banner', () => {
it('suppresses the banner as a safety-refusal trigger, even after earlier output', () => {
vi.mocked(isClaudeSafetyRefusalMessage).mockReturnValue(true);
const result = evaluateStreamedOutput(
successOutput('API Error: safeguards flagged this message'),
{ ...freshState(), sawOutput: true },
claudeOpts,
);
expect(result.shouldForwardOutput).toBe(false);
expect(result.state.streamedTriggerReason).toMatchObject({
reason: 'safety-refusal',
});
});
});
describe('Claude usage-exhausted banner', () => { describe('Claude usage-exhausted banner', () => {
it('suppresses output and returns newTrigger', () => { it('suppresses output and returns newTrigger', () => {
vi.mocked(isClaudeUsageExhaustedMessage).mockReturnValue(true); vi.mocked(isClaudeUsageExhaustedMessage).mockReturnValue(true);

View File

@@ -7,6 +7,7 @@ import {
isClaudeAuthError, isClaudeAuthError,
isClaudeAuthExpiredMessage, isClaudeAuthExpiredMessage,
isClaudeOrgAccessDeniedMessage, isClaudeOrgAccessDeniedMessage,
isClaudeSafetyRefusalMessage,
isClaudeUsageExhaustedMessage, isClaudeUsageExhaustedMessage,
type AgentTriggerReason, type AgentTriggerReason,
} from './agent-error-detection.js'; } from './agent-error-detection.js';
@@ -68,8 +69,9 @@ export function evaluateStreamedOutput(
if ( if (
primaryAgent === 'claude' && primaryAgent === 'claude' &&
output.status === 'success' && output.status === 'success' &&
!state.sawOutput && typeof outputText === 'string' &&
typeof outputText === 'string' // A safeguards refusal is never a real answer, even after earlier output.
(!state.sawOutput || isClaudeSafetyRefusalMessage(outputText))
) { ) {
const triggerReason = classifyClaudeSuccessTrigger(outputText); const triggerReason = classifyClaudeSuccessTrigger(outputText);
if (triggerReason) { if (triggerReason) {
@@ -208,6 +210,7 @@ function suppressRetryableSessionFailure(
function classifyClaudeSuccessTrigger( function classifyClaudeSuccessTrigger(
outputText: string, outputText: string,
): AgentTriggerReason | undefined { ): AgentTriggerReason | undefined {
if (isClaudeSafetyRefusalMessage(outputText)) return 'safety-refusal';
if (isClaudeUsageExhaustedMessage(outputText)) return 'usage-exhausted'; if (isClaudeUsageExhaustedMessage(outputText)) return 'usage-exhausted';
const authClassification = classifyClaudeAuthError(outputText); const authClassification = classifyClaudeAuthError(outputText);