From f42a51e3df52dd77258931f64f761fd265f2f033 Mon Sep 17 00:00:00 2001 From: kim Date: Thu, 22 Oct 2026 17:55:05 +0900 Subject: [PATCH] =?UTF-8?q?AUTO-RECOVER=20=EC=98=A4=EB=B0=9C=EB=8F=99=20?= =?UTF-8?q?=EC=88=98=EC=A0=95=20+=20Claude=EC=9A=A9=20=EB=84=9B=EC=A7=80?= =?UTF-8?q?=20=EC=A0=95=EB=A6=AC=20=E2=80=94=20=EC=9E=A5=EC=86=8C=C2=B7?= =?UTF-8?q?=EA=B8=B8=EC=B0=BE=EA=B8=B0=C2=B7=EB=AA=A8=EB=8D=B8=20=EA=B2=80?= =?UTF-8?q?=EC=83=89=EC=9D=84=20=EA=B7=BC=EA=B1=B0=20=EB=8F=84=EA=B5=AC?= =?UTF-8?q?=EB=A1=9C=20=EC=9D=B8=EC=A0=95('=EC=9D=B8=EB=8F=99=20=EB=A7=9B?= =?UTF-8?q?=EC=A7=91'=20=EC=9E=AC=EA=B2=80=EC=83=89=20=EA=B0=95=EC=A0=9C?= =?UTF-8?q?=205=ED=9A=8C),=20'=EB=8F=84=EA=B5=AC=EB=8A=94=20=EC=93=B0?= =?UTF-8?q?=EC=A7=80=20=EB=A7=90=EA=B3=A0'=20=EB=B3=B4=EC=A1=B0=20?= =?UTF-8?q?=ED=98=B8=EC=B6=9C=C2=B7'=EC=A7=80=EA=B8=88=20=EC=96=B4?= =?UTF-8?q?=EB=96=A4=20=EB=AA=A8=EB=8D=B8=EC=9D=B4=EC=95=BC'=20=EC=9E=90?= =?UTF-8?q?=EA=B8=B0=EC=86=8C=EA=B0=9C=20=EC=A0=9C=EC=99=B8.=20Claude=20?= =?UTF-8?q?=EB=AA=A8=EB=8D=B8=EC=97=94=20=EA=B0=80=EC=A7=9C=20=EB=A7=9E?= =?UTF-8?q?=EC=9E=A5=EA=B5=AC=EB=A5=BC=20=EB=B9=BC=EA=B3=A0=20=EB=A7=88?= =?UTF-8?q?=EC=A7=80=EB=A7=89=20=EC=98=81=EC=96=B4=20=EB=84=9B=EC=A7=80?= =?UTF-8?q?=EC=97=90=20'=ED=95=9C=EA=B5=AD=EC=96=B4=EB=A1=9C=20=EB=8B=B5?= =?UTF-8?q?=ED=95=98=EB=9D=BC'=20=EB=A9=94=EB=AA=A8=EB=A5=BC=20=EB=B6=99?= =?UTF-8?q?=EC=9D=B8=20=EC=82=AC=EB=B3=B8=EC=9D=84=20=EB=B3=B4=EB=83=84(?= =?UTF-8?q?=EC=98=81=EC=96=B4=20=EB=8B=B5=C2=B7=EC=98=81=EC=96=B4=20?= =?UTF-8?q?=ED=98=BC=EC=9E=A3=EB=A7=90=20=EC=9B=90=EC=9D=B8)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 5.5 --- src/gateway/chat/claude-nudge-adapt.ts | 52 ++++++++++++++++++++++++++ src/gateway/chat/handle-chat.ts | 8 +++- src/gateway/chat/retry-decisions.ts | 13 ++++++- tests/claude-nudge-adapt.test.ts | 37 ++++++++++++++++++ tests/retry-decisions.test.ts | 18 +++++++++ 5 files changed, 126 insertions(+), 2 deletions(-) create mode 100644 src/gateway/chat/claude-nudge-adapt.ts create mode 100644 tests/claude-nudge-adapt.test.ts diff --git a/src/gateway/chat/claude-nudge-adapt.ts b/src/gateway/chat/claude-nudge-adapt.ts new file mode 100644 index 0000000..5844a4e --- /dev/null +++ b/src/gateway/chat/claude-nudge-adapt.ts @@ -0,0 +1,52 @@ +/** + * claude-nudge-adapt.ts — 가드 넛지를 Claude 모델에 맞게 손보기(2026-10-22). + * + * 가드들은 재생성시킬 때 가짜 assistant 맞장구("Got it — checking now.", "Understood.")를 넣고 그 뒤에 + * 영어 user 지시("Yes, use web_search right now…")를 붙인다. gemma 시절, 대화가 user/assistant로 번갈아야 + * 따라오던 버릇에 맞춘 것이다. Claude에서는 둘 다 해롭다: + * · 시스템 프롬프트의 "사용자의 마지막 메시지 언어로 답하라"를 Claude는 정확히 지킨다 → 마지막 메시지가 + * 영어 넛지라 영어로 답한다(Haiku 전환 후 로그: 영어 혼잣말 12건, LANGUAGE BACKSTOP 4건, "인동 맛집" 영어 답). + * · 가짜 맞장구는 모델이 한 적 없는 말을 입에 넣는다. Anthropic API는 연속된 user 메시지를 합쳐 주므로 필요 없다. + * 원본 messages 배열은 건드리지 않고(가드들이 그 배열을 계속 읽는다), 이번 호출에 보낼 사본만 만든다. + */ + +/** 가드들이 넣는 가짜 assistant 맞장구 — 정확히 이 문자열일 때만 뺀다(진짜 초안은 남긴다). */ +export const SYNTHETIC_ACKS: ReadonlySet = new Set([ + 'Got it — checking now.', + 'Got it — let me verify that first.', + 'Understood.', + 'Understood. Acting immediately.', + 'Let me check that now.', + 'Understood. Executing browser automation now.', + 'Understood. Checking desktop state now.', +]); + +export const KOREAN_REPLY_NOTE = '(위 지시는 시스템 메모입니다. 사용자에게는 반드시 한국어로 답하세요.)'; + +export function isClaudeModel(model: string): boolean { + return /claude|haiku|sonnet|opus/i.test(String(model || '')); +} + +/** + * @param userMsgIndex 이번 턴 사용자 메시지의 messages 인덱스. 그 뒤에 들어온 user 메시지만 넛지로 본다. + * @param userMessage 사용자 원문 — 한글이 있으면 마지막 넛지에 한국어로 답하라는 메모를 붙인다. + */ +export function adaptNudgesForClaude( + messages: T[], userMsgIndex: number, userMessage: string, +): T[] { + if (userMsgIndex < 0 || userMsgIndex >= messages.length) return messages; + const out: T[] = []; + messages.forEach((m, i) => { + if (i > userMsgIndex && m.role === 'assistant' && typeof m.content === 'string' + && SYNTHETIC_ACKS.has(m.content.trim()) && !(m as any).tool_calls?.length) return; + out.push(m); + }); + const last = out[out.length - 1]; + // 맞장구는 사용자 메시지 뒤에서만 뺐으므로 사용자 메시지의 위치는 out에서도 userMsgIndex 그대로다 + if (last && last.role === 'user' && out.length - 1 > userMsgIndex + && typeof last.content === 'string' + && /[가-힣]/.test(String(userMessage || '')) && !last.content.includes(KOREAN_REPLY_NOTE)) { + out[out.length - 1] = { ...last, content: `${last.content}\n\n${KOREAN_REPLY_NOTE}` }; + } + return out; +} diff --git a/src/gateway/chat/handle-chat.ts b/src/gateway/chat/handle-chat.ts index 0a20798..e2e68ed 100644 --- a/src/gateway/chat/handle-chat.ts +++ b/src/gateway/chat/handle-chat.ts @@ -93,6 +93,7 @@ import { replyIsWrongLanguage, TRANSLATE_TO_KOREAN_SYSTEM } from './language-bac import { lightChat } from '../../providers/light-chat'; import { replyLooksEmpty, appendDroppedSearchImages, appendGeneratedChartImages } from './reply-content'; import { evaluateSearchBudget } from './search-budget'; +import { adaptNudgesForClaude, isClaudeModel } from './claude-nudge-adapt'; import { decideAutoRecover, shouldForceMessagingRetry as decideMessagingRetry, shouldForceWorkshopSaveRetry, shouldForceWorkshopFileRetry, shouldForceUnverifiedSpecRetry, unverifiedSpecPrompt, shouldForceEmptyGroundingRetry as decideEmptyGroundingRetry, GROUNDING_TOOL_PATTERN } from './retry-decisions'; import { logToolSkip } from './tool-skip-log'; import { checkNumericGrounding } from './numeric-grounding'; @@ -909,6 +910,7 @@ async function handleChat( const content = role === 'user' ? resolveImageContent(foldedContent, workspacePath) : msg.content; messages.push({ role, content }); } + const userMsgIndex = messages.length; // adaptNudgesForClaude: 이 뒤의 user 메시지는 가드 넛지 messages.push({ role: 'user', content: resolveImageContent(message, workspacePath) }); // News/weather/prices/etc. must come from a live tool call, never training data — and @@ -1538,7 +1540,11 @@ async function handleChat( if (round > 0 && messages.length && (messages[messages.length - 1] as any)?.role === 'user') { try { sendSSE('draft_reset', {}); } catch {} } - const generationPromise = ollama.chatWithThinkingStream(messages, 'executor', (token: string) => { + // Claude: 가짜 맞장구 빼고 마지막 넛지에 '한국어로 답하라'를 붙인 사본을 보낸다(claude-nudge-adapt.ts) + const _messagesForModel = isClaudeModel(resolvedModelThisRound || getModelForRole('executor')) + ? adaptNudgesForClaude(messages, userMsgIndex, message) + : messages; + const generationPromise = ollama.chatWithThinkingStream(_messagesForModel, 'executor', (token: string) => { try { sendSSE('token', { text: token }); } catch {} }, { // Empty (not omitted) once toolsDisabledForRestOfTurn trips — a model with no diff --git a/src/gateway/chat/retry-decisions.ts b/src/gateway/chat/retry-decisions.ts index ab8142d..54e7b85 100644 --- a/src/gateway/chat/retry-decisions.ts +++ b/src/gateway/chat/retry-decisions.ts @@ -68,7 +68,7 @@ import { // verify a local file's dimensions, so the model just searched generic news instead and tacked a // non-sequitur onto an already-correct answer. /** 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|memory_stats|nhc_active_storms|eonet_events|pubmed_search|pubmed_fetch|pubmed_fulltext|openalex_search|korean_law_search|korean_law_fetch|us_case_search|sqlite_query|cms_hospital_compare|stl_cad|scad_to_stl)/i; +export const GROUNDING_TOOL_PATTERN = /^(web_search|web_fetch|place_search|route_search|model_search|weather_|ollama_web_|news_search|memory_stats|nhc_active_storms|eonet_events|pubmed_search|pubmed_fetch|pubmed_fulltext|openalex_search|korean_law_search|korean_law_fetch|us_case_search|sqlite_query|cms_hospital_compare|stl_cad|scad_to_stl)/i; export interface AutoRecoverInput { /** The user's message this turn. */ @@ -114,6 +114,17 @@ export function decideAutoRecover(input: AutoRecoverInput): AutoRecoverDecision return { shouldRetry: false, kind: 'search', reason: '' }; } + // 앱의 보조 호출(논문 검색어 만들기·저널 분류·PPTX 계획)은 "도구는 쓰지 말고 JSON 한 줄로"처럼 도구를 금지한다. + // 여기에 검색을 강제하면 지시가 서로 부딪쳐 9번 헛재생성했다(2026-10-22, Haiku 전환 후 로그). + if (/도구(는|를)?\s*(쓰지|사용하지|호출하지)\s*(말|마)|(?:without|don'?t|do not)\s+(?:using|use|call(?:ing)?)\s+(?:any\s+)?tools?/i.test(message)) { + return { shouldRetry: false, kind: 'search', reason: '' }; + } + // "지금 어떤 모델이야?" — 자기 자신(답하는 모델)을 묻는 질문. '지금' 때문에 실시간 조회로 잡혀 재검색을 강제당했다. + if (/(무슨|어떤|어느)\s*모델(이야|이니|이냐|야|이에요|예요|인가요|인가|이세요|써|쓰|돌아)/.test(message) + && !/(최신|출시|나온|신형|추천|비교|좋은)/.test(message)) { + return { shouldRetry: false, kind: 'search', reason: '' }; + } + 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) diff --git a/tests/claude-nudge-adapt.test.ts b/tests/claude-nudge-adapt.test.ts new file mode 100644 index 0000000..d581334 --- /dev/null +++ b/tests/claude-nudge-adapt.test.ts @@ -0,0 +1,37 @@ +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import { adaptNudgesForClaude, isClaudeModel, KOREAN_REPLY_NOTE } from '../src/gateway/chat/claude-nudge-adapt'; + +const base = [ + { role: 'system', content: 'sys' }, + { role: 'assistant', content: 'Understood.' }, // 이전 대화 기록 — 손대지 않음 + { role: 'user', content: '주말에 현풍 비오나?' }, +]; + +test('사용자 메시지 뒤 가짜 맞장구는 빼고 마지막 넛지에 한국어 메모를 붙인다', () => { + const msgs = [...base, { role: 'assistant', content: 'Got it — checking now.' }, { role: 'user', content: 'Reminder: call a tool first.' }]; + const out = adaptNudgesForClaude(msgs, 2, '주말에 현풍 비오나?'); + assert.deepEqual(out.map(m => m.role), ['system', 'assistant', 'user', 'user']); + assert.equal(out[1].content, 'Understood.'); + assert.ok(out[3].content.endsWith(KOREAN_REPLY_NOTE)); + assert.equal(msgs[4].content, 'Reminder: call a tool first.', '원본 배열은 그대로'); +}); + +test('진짜 초안(candidateText)과 도구 라운드는 그대로', () => { + const msgs = [...base, { role: 'assistant', content: '초안 답변입니다.' }, { role: 'user', content: 'Re-check the figures.' }]; + const out = adaptNudgesForClaude(msgs, 2, '주말에 현풍 비오나?'); + assert.equal(out.length, 5); + const tool = [...base, { role: 'assistant', content: '', tool_calls: [{}] } as any, { role: 'tool', content: 'r' }]; + assert.deepEqual(adaptNudgesForClaude(tool, 2, '비오나'), tool); +}); + +test('넛지가 없으면 사용자 메시지에 메모를 붙이지 않고, 영어 질문엔 붙이지 않는다', () => { + assert.equal(adaptNudgesForClaude(base, 2, '주말에 현풍 비오나?')[2].content, '주말에 현풍 비오나?'); + const msgs = [...base.slice(0, 2), { role: 'user', content: 'weather?' }, { role: 'user', content: 'Reminder' }]; + assert.equal(adaptNudgesForClaude(msgs, 2, 'weather?')[3].content, 'Reminder'); +}); + +test('isClaudeModel', () => { + assert.ok(isClaudeModel('claude-haiku-5-5')); + assert.ok(!isClaudeModel('gemma4:31b-cloud')); +}); diff --git a/tests/retry-decisions.test.ts b/tests/retry-decisions.test.ts index 257690a..5f955f9 100644 --- a/tests/retry-decisions.test.ts +++ b/tests/retry-decisions.test.ts @@ -498,3 +498,21 @@ describe('skillContext 길이 한도 — 모델 컨텍스트에 비례', () => { assert.equal(budgetFromNumCtx(1048576), SKILL_CTX_MAX_CHARS); }); }); + +describe('decideAutoRecover — Haiku 전환 후 오발동(2026-10-22)', () => { + const ans = '인동에는 한재촌, 미미관 마라탕 등이 있습니다. 카카오맵 기준 평점이 높은 곳 위주로 골랐습니다. '.repeat(3); + test('place_search를 이미 불렀으면 맛집 질문에 web_search를 강제하지 않는다', () => { + assert.equal(decideAutoRecover({ message: '구미 인동 맛집 추천해줘', content: ans, availableToolNames: ['web_search', 'place_search'], calledToolNames: ['place_search'] }).shouldRetry, false); + }); + test('"도구는 쓰지 말고" 보조 호출에는 검색을 강제하지 않는다', () => { + const msg = '아래 요청에 맞는 학술 논문을 PubMed·OpenAlex에서 찾으려 한다. 도구는 쓰지 말고, 검색어만 JSON 한 줄로 답하라.\n요청: 최신 복합레진 접착 RCT'; + assert.equal(decideAutoRecover({ message: msg, content: '{"pubmed":"composite adhesive RCT 2024"}', availableToolNames: ['web_search'], calledToolNames: [] }).shouldRetry, false); + }); + test('"지금 어떤 모델이야?"는 자기소개라 재검색하지 않는다', () => { + assert.equal(decideAutoRecover({ message: '안녕! 지금 어떤 모델이야?', content: '저는 SmallClaw이고 지금은 claude-haiku-5-5로 답하고 있습니다.', availableToolNames: ['web_search'], calledToolNames: [] }).shouldRetry, false); + }); + test('최신 모델을 묻는 사실 질문은 여전히 대상', () => { + const d = decideAutoRecover({ message: '지금 어떤 모델이 최신이야? 아이폰 최신 모델 알려줘', content: '최신 모델은 아이폰 15 Pro입니다. 가격은 155만원부터입니다.', availableToolNames: ['web_search'], calledToolNames: [] }); + assert.equal(d.shouldRetry, true); + }); +});