From c1c2b096f0b69c5e5fb87113d4a53008d3b73723 Mon Sep 17 00:00:00 2001 From: kim Date: Sat, 17 Oct 2026 18:44:21 +0900 Subject: [PATCH] =?UTF-8?q?=EB=82=A0=EC=94=A8=20=EB=8F=84=EA=B5=AC=20?= =?UTF-8?q?=EC=A0=84=EB=B6=80=20=EC=8B=A4=ED=8C=A8=20=EC=8B=9C=20=EC=A7=80?= =?UTF-8?q?=EC=96=B4=EB=82=B8=20=EC=88=98=EC=B9=98=20=EB=8B=B5=EC=9D=84=20?= =?UTF-8?q?=EC=A0=95=EC=A7=81=ED=95=9C=20=EC=8B=A4=ED=8C=A8=20=EC=95=88?= =?UTF-8?q?=EB=82=B4=EB=A1=9C=20=EA=B5=90=EC=B2=B4(=EB=B0=B1=EC=8A=A4?= =?UTF-8?q?=ED=86=B1)=20+=20'Error:'=20=ED=95=9C=20=EC=A4=84=20=EA=B2=B0?= =?UTF-8?q?=EA=B3=BC=EB=A5=BC=20=EA=B7=BC=EA=B1=B0=EB=A1=9C=20=EB=B3=B4?= =?UTF-8?q?=EC=A7=80=20=EC=95=8A=EC=9D=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Sonnet 5.5 --- src/gateway/chat/handle-chat.ts | 9 +++++ src/gateway/chat/tool-failure-backstop.ts | 37 +++++++++++++++++++ src/gateway/guards/prompt-gates.ts | 2 ++ tests/tool-failure-backstop.test.ts | 43 +++++++++++++++++++++++ 4 files changed, 91 insertions(+) create mode 100644 src/gateway/chat/tool-failure-backstop.ts create mode 100644 tests/tool-failure-backstop.test.ts diff --git a/src/gateway/chat/handle-chat.ts b/src/gateway/chat/handle-chat.ts index 7d84941..9b650b4 100644 --- a/src/gateway/chat/handle-chat.ts +++ b/src/gateway/chat/handle-chat.ts @@ -84,6 +84,7 @@ import type { SkillsManager } from '../skills-manager'; import { selectToolsForTurn, bootAllowedTools, codeAiBlockedTools } from './tool-scope'; import { buildChatSystemPrompt, groundingResultReadingRule } from './system-prompt'; import { decideRoute } from './model-routing'; +import { weatherFabricationReplacement } from './tool-failure-backstop'; import { replyLooksEmpty, appendDroppedSearchImages, appendGeneratedChartImages } from './reply-content'; import { evaluateSearchBudget } from './search-budget'; import { decideAutoRecover, shouldForceMessagingRetry as decideMessagingRetry, shouldForceWorkshopSaveRetry, shouldForceWorkshopFileRetry, shouldForceUnverifiedSpecRetry, unverifiedSpecPrompt, shouldForceEmptyGroundingRetry as decideEmptyGroundingRetry, GROUNDING_TOOL_PATTERN } from './retry-decisions'; @@ -2508,6 +2509,14 @@ async function handleChat( finalText = sanitizeFinalReply(finalText, { preflightReason: preflightReasonForTurn }) || 'Hey! How can I help?'; finalText = appendDroppedSearchImages(finalText, allToolResults); finalText = appendGeneratedChartImages(finalText, allToolResults); + { + // 날씨 도구가 전부 실패했는데 수치를 말하는 답은 지어낸 것 — EMPTY-GROUNDING 재프롬프트(1회) 뒤에도 남았다면 여기서 교체. + const _fabricated = weatherFabricationReplacement(finalText, allToolResults); + if (_fabricated) { + console.log('[v2] TOOL-FAILURE BACKSTOP: weather tools all failed but the answer states weather figures — replaced with an honest failure notice.'); + finalText = _fabricated; + } + } logToDaily(workspacePath, 'SmallClaw', finalText, sessionId); if (fileOpV2Active) { diff --git a/src/gateway/chat/tool-failure-backstop.ts b/src/gateway/chat/tool-failure-backstop.ts new file mode 100644 index 0000000..7bc970c --- /dev/null +++ b/src/gateway/chat/tool-failure-backstop.ts @@ -0,0 +1,37 @@ +/** + * tool-failure-backstop.ts + * + * 날씨 도구가 전부 실패했는데도 답에 기온·강수·습도 수치가 박혀 있으면 그 답을 지운다. + * + * 왜 필요한가. 2026-10-17 벤치마크(scripts/tool-bench.py E2)에서 gemma4는 weather_kma가 + * "Error: 기상청 API 응답 없음"만 돌려줬는데도 "최고 14도, 최저 4도"를 답했다(2/2회). + * 실제 경로엔 EMPTY-GROUNDING 재프롬프트가 있어 한 번은 되돌리지만, 재프롬프트는 1회뿐이고 + * 모델이 두 번째에도 지어내면 그대로 사용자에게 나간다. 이 함수는 그 마지막 방어선이다. + * 판정이 확정적이라(실패한 도구 + 근거 없는 수치) 틀릴 여지가 작다 — 오탐 비용은 + * "조회 실패를 정직하게 알리는 문장"으로 대체되는 것뿐이다. + */ + +const WEATHER_TOOL = /^weather_/i; + +/** 날씨 수치: 숫자 + 기온/강수/습도/풍속 단위. "정도"처럼 숫자가 앞에 없으면 안 걸린다. */ +const WEATHER_FIGURE = /-?\d+(?:\.\d+)?\s*(?:°C|°|℃|도(?![시모로])|mm|㎜|m\/s|㎧|%)/; + +export interface ToolResultLike { name?: string; error?: boolean; result?: string } + +function isFailedResult(r: ToolResultLike): boolean { + if (r.error) return true; + const text = String(r.result || '').trim(); + return !text || (/^(error|오류)\b/i.test(text) && text.length < 300); +} + +/** + * @returns 대체 문장(교체해야 할 때) 또는 null(그대로 둠) + */ +export function weatherFabricationReplacement(answer: string, toolResults: readonly ToolResultLike[] | undefined): string | null { + const weather = (toolResults || []).filter(r => WEATHER_TOOL.test(String(r?.name || ''))); + if (!weather.length) return null; + if (!weather.every(isFailedResult)) return null; // 하나라도 성공했으면 그 값을 쓸 수 있으니 손대지 않는다 + if (!WEATHER_FIGURE.test(String(answer || ''))) return null; + const detail = String(weather[weather.length - 1].result || '').replace(/\s+/g, ' ').trim().slice(0, 80); + return `기상청 데이터를 가져오지 못해서 날씨 수치를 확인할 수 없습니다${detail ? ` (${detail})` : ''}. 지어낸 값을 드리지 않기 위해 답변을 보류합니다. 잠시 후 다시 요청해 주세요.`; +} diff --git a/src/gateway/guards/prompt-gates.ts b/src/gateway/guards/prompt-gates.ts index 632d947..2fde59e 100644 --- a/src/gateway/guards/prompt-gates.ts +++ b/src/gateway/guards/prompt-gates.ts @@ -360,6 +360,8 @@ export function isUsableGroundingResult(r: { error?: boolean; result?: string }) if (!text) return false; if (/^\(no articles found\)$/i.test(text)) return false; if (/에\s*대한\s*검색\s*결과가\s*없습니다\.?$/i.test(text)) return false; + // error 플래그 없이 "Error: …" 한 줄만 돌려주는 도구(2026-10-17 벤치마크 모의 오류와 같은 형태)도 근거가 아니다. + if (/^(error|오류)\b/i.test(text) && text.length < 300) return false; return true; } diff --git a/tests/tool-failure-backstop.test.ts b/tests/tool-failure-backstop.test.ts new file mode 100644 index 0000000..c34ec1c --- /dev/null +++ b/tests/tool-failure-backstop.test.ts @@ -0,0 +1,43 @@ +/** + * tool-failure-backstop — 날씨 도구 전부 실패 + 수치 답 → 교체 + * 표본: 2026-10-17 tool-bench E2, gemma4가 오류 응답 뒤 "최고 14도, 최저 4도"를 답한 실제 출력. + */ +import { test, describe } from 'node:test'; +import assert from 'node:assert/strict'; +import { weatherFabricationReplacement } from '../src/gateway/chat/tool-failure-backstop'; +import { isUsableGroundingResult } from '../src/gateway/guards/prompt-gates'; + +const FAILED = [{ name: 'weather_kma', error: true, result: 'Error: 기상청 API 응답 없음 (timeout)' }]; + +describe('weatherFabricationReplacement', () => { + test('실패한 도구 + 지어낸 기온 → 교체', () => { + const r = weatherFabricationReplacement('오늘 부산의 날씨는 대체로 맑으며, 최고 기온은 14도, 최저 기온은 4도로 예상됩니다.', FAILED); + assert.ok(r && r.includes('확인할 수 없습니다')); + }); + test('error 플래그가 없어도 "Error:" 한 줄이면 실패로 본다', () => { + const r = weatherFabricationReplacement('기온은 21.5℃입니다.', [{ name: 'weather_kma', error: false, result: 'Error: 응답 없음' }]); + assert.ok(r); + }); + test('수치 없이 정직하게 실패를 알린 답은 그대로', () => { + assert.equal(weatherFabricationReplacement('기상청 조회에 실패해서 지금은 날씨를 알려드리기 어렵습니다.', FAILED), null); + }); + test('도구가 하나라도 성공했으면 손대지 않는다', () => { + const ok = [...FAILED, { name: 'weather_airkorea', error: false, result: '서울 PM2.5 18㎍/㎥ 보통' }]; + assert.equal(weatherFabricationReplacement('PM2.5는 18%가 아니라...', ok), null); + }); + test('날씨 도구를 안 부른 턴은 건드리지 않는다', () => { + assert.equal(weatherFabricationReplacement('전기차 효율은 15%입니다.', [{ name: 'web_search', error: true, result: 'x' }]), null); + }); + test('"정도" 같은 단어는 수치로 보지 않는다', () => { + assert.equal(weatherFabricationReplacement('조회에 실패했습니다. 이 정도로 안내드립니다.', FAILED), null); + }); +}); + +describe('isUsableGroundingResult — Error 한 줄', () => { + test('Error: 로 시작하는 짧은 결과는 근거가 아니다', () => { + assert.equal(isUsableGroundingResult({ error: false, result: 'Error: timeout' }), false); + }); + test('정상 결과는 그대로 근거', () => { + assert.equal(isUsableGroundingResult({ error: false, result: '서울 기온 18도 맑음' }), true); + }); +});