v4.3.25: 재시도 판단 3종을 retry-decisions.ts로 분리 + 테스트 23개

라운드 루프에 남아 있던 판단 로직 전부 추출. 세 검사 모두 "모델이 유창하게 답을
썼지만 그 답에 이르는 과정이 신뢰할 수 없다"를 잡는 같은 계열임:

- decideAutoRecover()            근거 도구 없이 검증 가능한 질문에 답한 경우
- shouldForceMessagingRetry()    전송 도구 없이 "보냈다"고 주장한 경우
- shouldForceEmptyGroundingRetry() 검색이 전부 비었는데 답한 경우

셋 다 fail-open이라 회귀해도 에러도 로그도 남지 않고 검증 안 된 답이 사실처럼
전달된다 — 정확히 이 저장소가 반복해서 겪은 실패 유형이라(07-29 로그 감사)
재시도해야 하는 경우와 하지 말아야 하는 경우를 양방향으로 고정함.

handle-chat.ts 2,908 → 2,872줄. 전체 102개 테스트 통과.

테스트 작성 중 확인한 경계(코드는 정상, 테스트가 틀렸던 케이스):
짧고 애매한 답변("음...")은 재시도 대상이 아님 — looksLikeReasoning은 300자
초과를 요구하고 거부 문구도 아니므로. 회복할 내용 자체가 없는 게 맞는 동작이라
그 경계를 별도 테스트로 남김.

배포 후 확인: "RTX 5090 VRAM 용량" 질문에서 web_search 선행 후 답변 정상.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
kimandClaude Opus 5 committed 2026-07-29 16:23:19 +09:00
1 parent 5eb47ca08b
commit 7a413f2388
3 files changed
+312 -50

No files matched your search

+14 -50
View File
@@ -73,6 +73,7 @@ import type { SkillsManager } from '../skills-manager';
import { selectToolsForTurn, bootAllowedTools, codeAiBlockedTools } from './tool-scope';
import { buildChatSystemPrompt } from './system-prompt';
import { evaluateSearchBudget } from './search-budget';
import { decideAutoRecover, shouldForceMessagingRetry as decideMessagingRetry, shouldForceEmptyGroundingRetry as decideEmptyGroundingRetry, GROUNDING_TOOL_PATTERN } from './retry-decisions';
const MAX_TOOL_ROUNDS = 50;
type ExecutionMode = 'interactive' | 'background_task' | 'heartbeat' | 'cron';
@@ -1526,47 +1527,17 @@ async function handleChat(
// GPU spec question) must not permanently disarm this for the rest of the turn.
if ((!toolCalls || toolCalls.length === 0) && response.content && toolSkipForcedRetries < MAX_TOOL_SKIP_FORCED_RETRIES) {
const content = response.content;
const looksLikeReasoning = content.length > 300
&& (/\b(let me|I need to|I should|the user|first,|wait,|hmm|the rules say)\b/i.test(content));
const queryNeedsTools = /\b(search|find|look up|latest|news|info|open|browse|navigate|visit|click|type|fill|what happened|desktop|screen|window|vscode|vs code|codex|clipboard)\b/i.test(message)
|| /(검색|찾아|찾아줘|알아봐|알아봐줘|열어|들어가|접속|방문|클릭|눌러|입력|무슨\s*일|바탕화면|화면|창|클립보드)/.test(message);
// browser_* tools are excluded from the schema by default (dormantBrowserTools, parked
// since 07-09 — see the BROWSER RULE comment above). Forcing "call browser_open now" when
// the model was never given that tool definition is a dead end it can't act on — gate on
// actual availability so this naturally re-activates if browser tools are ever unparked.
const browserAutomationRequest = isBrowserAutomationRequest(message)
&& tools.some((t: any) => String(t?.function?.name || '').startsWith('browser_'));
const desktopAutomationRequest = isDesktopAutomationRequest(message);
const looksLikeRefusal = looksLikeSafetyRefusal(content);
// News/weather/prices — and now factual/product-info questions (specs, comparisons,
// "what models exist") — must never be answered from training data — force a tool call
// even when the model's reply looks like a confident final answer rather than stalled
// reasoning (a model that skips tools and answers fluently is more dangerous than one
// that visibly hesitates, since the fabrication reads as authoritative).
// Output-side catch-all: the input didn't match any known "factual question" phrasing,
// but the model went ahead and stated a spec/price/benchmark number anyway. Excludes
// execution-like requests (coding, file ops) so numbers in those contexts don't misfire.
// Same personal-infra exemption as isFactualInfoRequest (see PERSONAL_INFRA_NICKNAMES) —
// this is the OUTPUT-side counterpart and was missing it: a 지서버/클로서버 hardware answer
// legitimately contains GB/tok/s-shaped numbers, which would otherwise still force a
// pointless web_search retry even after the input-side gate was fixed for the same case.
const unverifiedSpecClaim = !isExecutionLikeRequest(message) && !isExemptFromVerification(message) && looksLikeUnverifiedSpecClaim(content);
const liveDataRequest = isLiveDataRequest(message) || isFactualInfoRequest(message) || unverifiedSpecClaim;
// Whether a tool that could actually ground THIS kind of request has already run —
// any other tool call (file listing, email check, etc.) doesn't count.
const groundingToolPattern = browserAutomationRequest
? /^browser_/i
: desktopAutomationRequest
? /^desktop_/i
: /^(web_search|web_fetch|weather_|ollama_web_|news_search)/i;
const hasGroundingToolCall = allToolResults.some((r) => groundingToolPattern.test(String(r?.name || '')));
if (((queryNeedsTools && (looksLikeReasoning || looksLikeRefusal)) || liveDataRequest) && !hasGroundingToolCall) {
const _recover = decideAutoRecover({
message,
content,
availableToolNames: tools.map((t: any) => String(t?.function?.name || '')),
calledToolNames: allToolResults.map((r) => String(r?.name || '')),
});
const browserAutomationRequest = _recover.kind === 'browser';
const desktopAutomationRequest = _recover.kind === 'desktop';
if (_recover.shouldRetry) {
toolSkipForcedRetries++;
const liveDataReason = unverifiedSpecClaim
? ' (unverified spec/price/benchmark number in the answer, no matching input phrasing)'
: liveDataRequest
? ' (live-data query answered without a grounding tool call)'
: '';
const liveDataReason = _recover.reason;
console.log(`[v2] AUTO-RECOVER (${toolSkipForcedRetries}/${MAX_TOOL_SKIP_FORCED_RETRIES}): Model dumped ${content.length} chars${liveDataReason || ' of reasoning instead of calling tools'}${allToolResults.length > 0 ? ` [${allToolResults.length} unrelated tool call(s) already made this turn]` : ''}. Re-prompting...`);
allThinking += (allThinking ? '\n\n' : '') + content;
sendSSE('thinking', { thinking: content.slice(0, 500) + '...' });
@@ -1650,13 +1621,8 @@ async function handleChat(
// A model claiming "sent!" without ever having called email_send/kakao_send_message is
// worse than a wrong info answer — the user believes a real message reached someone.
const sendToolCalled = allToolResults.some(
(r) => (r.name === 'email_send' || r.name === 'kakao_send_message') && !r.error,
);
const shouldForceMessagingRetry =
isMessagingRequest(message)
&& claimsMessageSent(candidateText)
&& !sendToolCalled
decideMessagingRetry({ message, candidateText, toolResults: allToolResults })
&& messagingForcedRetries < MAX_MESSAGING_FORCED_RETRIES;
if (shouldForceMessagingRetry) {
@@ -1672,12 +1638,10 @@ async function handleChat(
}
const groundingResultsThisTurn = allToolResults.filter((r) =>
/^(web_search|web_fetch|weather_|ollama_web_|news_search)/i.test(String(r?.name || '')),
GROUNDING_TOOL_PATTERN.test(String(r?.name || '')),
);
const shouldForceEmptyGroundingRetry =
(isLiveDataRequest(message) || isFactualInfoRequest(message))
&& groundingResultsThisTurn.length > 0
&& !groundingResultsThisTurn.some(isUsableGroundingResult)
decideEmptyGroundingRetry({ message, toolResults: allToolResults })
&& emptyGroundingForcedRetries < MAX_EMPTY_GROUNDING_FORCED_RETRIES;
if (shouldForceEmptyGroundingRetry) {
+139
View File
@@ -0,0 +1,139 @@
/**
* retry-decisions.ts
*
* Three post-generation checks that decide whether the model's answer must be thrown away and
* re-prompted. All three share a shape: the model produced fluent text that LOOKS finished, but
* something about how it got there makes the answer untrustworthy.
*
* 1. AUTO-RECOVER — answered a checkable question without ever calling a grounding tool
* 2. MESSAGING — claimed a message was sent without calling the send tool
* 3. EMPTY-GROUNDING — searched, got nothing usable, and answered anyway
*
* These are the highest-stakes decisions in the turn loop and the easiest to break silently:
* every one of them fails "open" (no error, no log, just an unverified answer delivered as
* fact). Extracted from handleChat() on 2026-07-29 so they can be tested — the loop around them
* is I/O and stays where it is; see project notes on why the loop itself was left alone.
*/
import {
isLiveDataRequest,
isFactualInfoRequest,
isExecutionLikeRequest,
isExemptFromVerification,
looksLikeUnverifiedSpecClaim,
looksLikeSafetyRefusal,
isBrowserAutomationRequest,
isDesktopAutomationRequest,
isMessagingRequest,
claimsMessageSent,
isUsableGroundingResult,
} from '../guards/prompt-gates';
/** Tools that can actually ground a factual/live-data answer. Anything else does not count. */
export const GROUNDING_TOOL_PATTERN = /^(web_search|web_fetch|weather_|ollama_web_|news_search)/i;
export interface AutoRecoverInput {
/** The user's message this turn. */
message: string;
/** The text the model just produced instead of calling a tool. */
content: string;
/** Names of tools offered this turn — browser retries are pointless if unavailable. */
availableToolNames: readonly string[];
/** Names of tools already executed this turn (in order). */
calledToolNames: readonly string[];
}
export type AutoRecoverKind = 'browser' | 'desktop' | 'search';
export interface AutoRecoverDecision {
shouldRetry: boolean;
/** Which kind of nudge to send — decides which tool the re-prompt demands. */
kind: AutoRecoverKind;
/** Human-readable cause, used in the [v2] AUTO-RECOVER log line. */
reason: string;
}
export function decideAutoRecover(input: AutoRecoverInput): AutoRecoverDecision {
const message = String(input.message || '');
const content = String(input.content || '');
const looksLikeReasoning = content.length > 300
&& (/\b(let me|I need to|I should|the user|first,|wait,|hmm|the rules say)\b/i.test(content));
const queryNeedsTools = /\b(search|find|look up|latest|news|info|open|browse|navigate|visit|click|type|fill|what happened|desktop|screen|window|vscode|vs code|codex|clipboard)\b/i.test(message)
|| /(검색|찾아|찾아줘|알아봐|알아봐줘|열어|들어가|접속|방문|클릭|눌러|입력|무슨\s*일|바탕화면|화면|창|클립보드)/.test(message);
// Demanding "call browser_open now" when browser_* was never put in the schema is a dead end
// the model cannot act on, so gate on actual availability. This re-activates by itself if the
// browser tools are ever un-parked.
const browserAutomationRequest = isBrowserAutomationRequest(message)
&& input.availableToolNames.some(n => n.startsWith('browser_'));
const desktopAutomationRequest = isDesktopAutomationRequest(message);
const looksLikeRefusal = looksLikeSafetyRefusal(content);
// Output-side catch-all: the question matched no known "factual" phrasing, but the model went
// ahead and stated a spec/price/benchmark number anyway. Execution requests (coding, file ops)
// are excluded so numeric literals there don't misfire, and the user's own infra nicknames are
// exempt because web_search cannot verify private hardware.
const unverifiedSpecClaim = !isExecutionLikeRequest(message)
&& !isExemptFromVerification(message)
&& looksLikeUnverifiedSpecClaim(content);
const liveDataRequest = isLiveDataRequest(message) || isFactualInfoRequest(message) || unverifiedSpecClaim;
const kind: AutoRecoverKind = browserAutomationRequest ? 'browser' : desktopAutomationRequest ? 'desktop' : 'search';
const groundingPattern = kind === 'browser' ? /^browser_/i : kind === 'desktop' ? /^desktop_/i : GROUNDING_TOOL_PATTERN;
// "no RELEVANT tool yet", not "no tool yet": a model that calls one decoy tool (coder_list_files
// while answering a GPU spec question) must not permanently disarm this for the rest of the turn.
const hasGroundingToolCall = input.calledToolNames.some(n => groundingPattern.test(String(n || '')));
const shouldRetry = ((queryNeedsTools && (looksLikeReasoning || looksLikeRefusal)) || liveDataRequest)
&& !hasGroundingToolCall;
const reason = unverifiedSpecClaim
? ' (unverified spec/price/benchmark number in the answer, no matching input phrasing)'
: liveDataRequest
? ' (live-data query answered without a grounding tool call)'
: '';
return { shouldRetry, kind, reason };
}
export interface MessagingRetryInput {
message: string;
/** The answer text the model is about to deliver. */
candidateText: string;
/** Tool results this turn, needed to confirm a send actually succeeded. */
toolResults: readonly { name?: string; error?: boolean }[];
}
/**
* A model claiming "보냈습니다" without ever calling email_send/kakao_send_message is worse than
* a wrong factual answer: the user believes a real message reached a real person and stops
* checking. A send that errored does not count as sent.
*/
export function shouldForceMessagingRetry(input: MessagingRetryInput): boolean {
const sendToolCalled = input.toolResults.some(
r => (r?.name === 'email_send' || r?.name === 'kakao_send_message') && !r?.error,
);
return isMessagingRequest(String(input.message || ''))
&& claimsMessageSent(String(input.candidateText || ''))
&& !sendToolCalled;
}
export interface EmptyGroundingInput {
message: string;
/** Tool results this turn; only grounding tools are considered. */
toolResults: readonly { name?: string; error?: boolean; result?: string }[];
}
/**
* The model ran grounding tools and every one came back empty or failed, then answered anyway.
* Without this it writes a fluent answer with invented headlines and cites the search it just
* ran — the failure looks identical to a successful one from the user's side.
*/
export function shouldForceEmptyGroundingRetry(input: EmptyGroundingInput): boolean {
const message = String(input.message || '');
const grounding = input.toolResults.filter(r => GROUNDING_TOOL_PATTERN.test(String(r?.name || '')));
return (isLiveDataRequest(message) || isFactualInfoRequest(message))
&& grounding.length > 0
&& !grounding.some(r => isUsableGroundingResult(r as any));
}
+159
View File
@@ -0,0 +1,159 @@
/**
* retry-decisions.test.ts
*
* These three checks decide whether an answer the model already wrote gets thrown away.
* They all fail OPEN — a regression produces no error and no log line, just an unverified
* answer delivered to the user as fact. That is precisely the class of bug this codebase has
* repeatedly shipped (see the 2026-07-29 log audit), so both directions are pinned:
* must-retry cases AND must-not-retry cases.
*/
import { test, describe } from 'node:test';
import assert from 'node:assert/strict';
import {
decideAutoRecover,
shouldForceMessagingRetry,
shouldForceEmptyGroundingRetry,
} from '../src/gateway/chat/retry-decisions';
const recover = (message: string, content: string, called: string[] = [], available: string[] = ['web_search']) =>
decideAutoRecover({ message, content, availableToolNames: available, calledToolNames: called });
describe('AUTO-RECOVER — 근거 없이 답한 경우 재시도', () => {
test('스펙 질문에 검색 없이 답하면 재시도', () => {
assert.equal(recover('RTX 5090 스펙 알려줘', 'VRAM은 32GB입니다.').shouldRetry, true);
});
test('[2026-07-29] 입력이 평범해도 답변에 지어낸 수치가 있으면 재시도', () => {
// 실제 사고 패턴: 질문은 캐주얼한데 답에 확정적 수치가 나옴.
const d = recover('이거 어떨까?', '초당 약 15~22 토큰 정도 나옵니다.');
assert.equal(d.shouldRetry, true);
assert.match(d.reason, /unverified spec/);
});
test('이미 검색했으면 재시도하지 않는다', () => {
assert.equal(recover('RTX 5090 스펙', 'VRAM 32GB입니다.', ['web_search']).shouldRetry, false);
});
test('무관한 도구를 불렀다고 무장해제되지 않는다', () => {
// 미끼 도구 하나로 남은 턴 전체가 풀리면 안 된다.
assert.equal(recover('RTX 5090 스펙', 'VRAM 32GB입니다.', ['coder_list_files']).shouldRetry, true);
});
test('개인 인프라 질문은 재시도 없음 — 검색해도 나올 수 없다', () => {
assert.equal(recover('지서버 사양이 어떻게 되지?', '3060 12GB 2장, 40GB RAM입니다.').shouldRetry, false);
});
test('코딩 요청 안의 숫자는 재시도를 유발하지 않는다', () => {
assert.equal(recover('파이썬 스크립트 만들어줘', '버퍼는 64GB로 잡았습니다.').shouldRetry, false);
});
test('숫자 없는 일반 대화는 재시도 없음', () => {
assert.equal(recover('안녕', '안녕하세요! 무엇을 도와드릴까요?').shouldRetry, false);
});
test('안전 거부 문구 + 도구 필요한 요청이면 재시도', () => {
const d = recover('이 사이트 좀 찾아줘', "I'm sorry, I can't help with that.");
assert.equal(d.shouldRetry, true);
});
});
describe('AUTO-RECOVER — 어떤 도구를 요구할지 (kind)', () => {
test('기본은 검색', () => {
assert.equal(recover('오늘 뉴스', '어제 이런 일이...').kind, 'search');
});
test('브라우저 도구가 스키마에 있을 때만 browser로 분기', () => {
const msg = 'github.com 열어서 확인해줘';
assert.equal(recover(msg, '음...', [], ['web_search']).kind, 'search');
assert.equal(recover(msg, '음...', [], ['web_search', 'browser_open']).kind, 'browser');
});
test('브라우저 분기면 web_search를 이미 불렀어도 재시도한다 — 근거 도구가 다르다', () => {
// 거부 문구여야 게이트가 성립한다. 짧고 무의미한 답("음...")은 재시도 대상이 아님 —
// 회복할 게 없기 때문. 아래 테스트가 그 경계를 따로 고정한다.
const refusal = "I'm sorry, I can't use your computer to do that.";
const d = recover('github.com 열어줘', refusal, ['web_search'], ['browser_open']);
assert.equal(d.kind, 'browser');
assert.equal(d.shouldRetry, true, 'web_search는 브라우저 요청의 근거가 되지 못한다');
});
test('짧고 애매한 답변은 재시도 대상이 아니다 — 회복할 내용이 없다', () => {
assert.equal(recover('github.com 열어줘', '음...', [], ['browser_open']).shouldRetry, false);
});
});
describe('MESSAGING — 보냈다는 거짓 주장 차단', () => {
const send = (name: string, error = false) => [{ name, error }];
test('전송 요청 + 보냈다 주장 + 도구 미호출 → 재시도', () => {
assert.equal(shouldForceMessagingRetry({
message: '이메일 보내줘', candidateText: '메일 보냈습니다.', toolResults: [],
}), true);
});
test('실제로 보냈으면 재시도 없음', () => {
assert.equal(shouldForceMessagingRetry({
message: '이메일 보내줘', candidateText: '메일 보냈습니다.', toolResults: send('email_send'),
}), false);
});
test('전송이 실패했으면 "보냈다"는 여전히 거짓 — 재시도', () => {
assert.equal(shouldForceMessagingRetry({
message: '이메일 보내줘', candidateText: '메일 보냈습니다.', toolResults: send('email_send', true),
}), true);
});
test('보냈다고 하지 않았으면 재시도 없음', () => {
assert.equal(shouldForceMessagingRetry({
message: '이메일 보내줘', candidateText: '어떤 내용으로 보낼까요?', toolResults: [],
}), false);
});
test('전송 요청이 아니면 재시도 없음', () => {
assert.equal(shouldForceMessagingRetry({
message: '메일 읽어줘', candidateText: '3통 있습니다.', toolResults: [],
}), false);
});
});
describe('EMPTY-GROUNDING — 빈 검색결과로 답한 경우', () => {
test('검색은 했지만 전부 빈 결과면 재시도', () => {
assert.equal(shouldForceEmptyGroundingRetry({
message: '오늘 뉴스',
toolResults: [{ name: 'news_search', result: '(no articles found)' }],
}), true);
});
test('쓸만한 결과가 하나라도 있으면 재시도 없음', () => {
assert.equal(shouldForceEmptyGroundingRetry({
message: '오늘 뉴스',
toolResults: [
{ name: 'news_search', result: '(no articles found)' },
{ name: 'web_search', result: '[1] 실제 기사 제목' },
],
}), false);
});
test('검색을 아예 안 했으면 이 검사 대상이 아니다 (AUTO-RECOVER 담당)', () => {
assert.equal(shouldForceEmptyGroundingRetry({ message: '오늘 뉴스', toolResults: [] }), false);
});
test('근거 도구가 아닌 것만 돌았으면 대상 아님', () => {
assert.equal(shouldForceEmptyGroundingRetry({
message: '오늘 뉴스', toolResults: [{ name: 'coder_list_files', result: '' }],
}), false);
});
test('라이브 데이터 질문이 아니면 대상 아님', () => {
assert.equal(shouldForceEmptyGroundingRetry({
message: '시 한 편 써줘', toolResults: [{ name: 'web_search', result: '' }],
}), false);
});
test('에러로 끝난 검색도 빈 결과로 친다', () => {
assert.equal(shouldForceEmptyGroundingRetry({
message: '내일 날씨', toolResults: [{ name: 'weather_kma', error: true, result: 'boom' }],
}), true);
});
});