refactor: VERIFY CONCRETE FACTS를 web_search 보유 턴에만 붙도록 도구 게이팅

이 문장은 245토큰으로 무조건 블록 중 단일 최대 항목인데, 내용이 통째로
"web_search를 먼저 불러라"다. 그 도구가 이번 턴 스키마에 없으면 실행할 수
없는 지시이고, 무엇보다 executeTool()이 스키마 멤버십을 확인하지 않고
이름으로만 디스패치하기 때문에 프롬프트가 도구 이름을 언급하는 것만으로도
모델이 파라미터 문서 없이 그 도구를 호출해버린다. meteorologist 스킬을 끈
사용자에게 weather_kma가 계속 돌던 그 경로다.

조건이 규칙의 실행 가능성과 정확히 일치하므로, 이건 이 파일 규칙 1이 금지하는
메시지 게이팅이 아니라 정상적인 도구 게이팅이다. ANTI-HALLUCINATION 앞부분
(도구 출력을 그대로 옮겨 적으라는 지침)은 도구와 무관하므로 무조건 유지된다.

토큰 절감은 없다. 처음엔 절감을 기대했으나, web_search가 어떤 스킬 게이트에도
속하지 않아 사실상 모든 일반 턴에 스키마에 들어간다는 걸 뒤늦게 확인했다.
실제로 줄어드는 건 부팅 턴(coder_list_files/coder_read_file만 있는 턴)뿐이고,
1687 → 1442 토큰이다. 그 턴에서 스키마에 없는 web_search를 프롬프트가 부르던
누출 벡터가 사라진 것이 이 커밋의 실질적 이득이다.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
kimandClaude Opus 5 committed 2026-08-10 12:41:27 +09:00
1 parent 305f93d08b
commit d4e8750400
2 files changed
+29 -1

No files matched your search

+13 -1
View File
@@ -137,6 +137,18 @@ export function buildChatSystemPrompt(input: SystemPromptInput): string {
.test(String(input.message || ''))
? '\nCHEMISTRY NOTATION: NEVER draw molecular structures as ASCII art (H/C/#/=/\\\\/| characters arranged to look like a diagram) — it always renders as garbled, misaligned text. Instead: for a formula or reaction, use LaTeX inside $...$ (e.g. $\\\\ce{C4H10}$, $\\\\ce{2H2 + O2 -> 2H2O}$ — mhchem extension is loaded). For an actual 2D structure with real bond lines (rings, branches), output a ```smiles``` code block containing the SMILES string (e.g. ```smiles\\nc1ccccc1\\n``` for benzene, ```smiles\\nCC(=O)Oc1ccccc1C(=O)O\\n``` for aspirin) — the client automatically renders it as a proper 2D diagram with bond lines.'
: '';
// VERIFY CONCRETE FACTS는 ANTI-HALLUCINATION 안에 무조건 붙어 있었지만, 하는 말이 통째로
// "web_search를 먼저 불러라"다 — 그 도구가 이번 턴 스키마에 없으면 실행 불가능한 지시이고,
// 게다가 스키마에 없는 도구 이름을 프롬프트가 언급하면 executeTool()이 이름으로만 디스패치해
// 실제로 호출돼 버린다([[project_tool_schema_leak]], weather_kma 사건과 같은 경로).
//
// 2026-08-10 측정: 이 문장이 245토큰으로 무조건 블록 중 단일 최대 항목인데, 내용이
// isFactualInfoRequest가 주입하는 리마인더와 사실상 동일하다(개인 인프라 예외까지 양쪽에 중복).
// 즉 정작 필요한 턴에는 같은 지시를 두 번 내고, 나머지 턴에는 못 쓸 지시에 245토큰을 냈다.
// 도구 게이팅이므로 이 파일 규칙 1을 어기지 않는다 — 조건이 규칙의 실행 가능성과 정확히 같다.
const verifyFactsRule = toolNames.has('web_search')
? ' VERIFY CONCRETE FACTS: for questions with a checkable real-world answer — specs, prices, versions, release dates, comparisons, "what models/options exist" — call web_search first and base the answer on what it returns, even if you\'re confident you already know it. Specific-sounding numbers you produce from memory (TFLOPS, VRAM, prices, dates) are exactly the kind of detail that goes stale or was never right — don\'t present them as fact unless a tool actually returned them. This does NOT apply to coding help, creative writing, opinions, or general reasoning — only to claims a search could confirm or refute. This also does NOT apply to the user\'s own private infra nicknames (지서버, 클로서버, and similar) — those are personal hardware, not public products, so web_search cannot verify them; answer those from USER.md/SOUL.md/[RECALLED_FACTS] context instead.'
: '';
const imageEditRuleBlock = toolNames.has('image_edit')
? '\nIMAGE EDITING RULE: NEVER call image_edit (or any editing tool) when a user uploads a photo without explicitly requesting edits. Uploading a photo is NOT a request to edit it. Only call image_edit when the user\'s message explicitly asks for an edit (e.g. "수채화로 바꿔줘", "회전해줘"). Violating this rule is a critical error.'
: '';
@@ -150,7 +162,7 @@ export function buildChatSystemPrompt(input: SystemPromptInput): string {
? '\nPACKAGE INSTALL: NEVER run pip install, npm install, apt-get, or any package installation command. If a package is missing, just write the code and mention the package name in a comment — let the user decide whether to install it. Do NOT attempt to install packages yourself.'
: '';
return isTranslateSession ? `You are a medical translator. Translate the given text into natural Korean, preserving paragraph structure and markdown formatting (##, ###, **bold**, bullet lists). Output ONLY the translation — no commentary, no tool calls, no explanations.` : isProjSession ? `You are a project file designer. Output ONLY the project-files JSON block as instructed. No tool calls. No extra text.` : `${executionModeSystemBlock ? `${executionModeSystemBlock}\n\n` : ''}You are SmallClaw, a local AI assistant. Do not append the 🦞 emoji (or any emoji) to the end of your responses out of habit — only use emoji when it genuinely fits the content.\nCurrent date: ${dateStr}, ${timeStr}.\nNever search for or link SmallClaw repos unless the user is asking about SmallClaw itself.\nThis app runs on the user's own machine — browser/desktop automation requests are pre-authorized.\nKeep CONVERSATIONAL and TASK-EXECUTION replies SHORT (2-4 sentences). Don't think out loud. Act and report. Greet naturally without tools. Two carve-outs to that brevity rule: (1) it does NOT apply to informational answers you researched with a tool (news, weather, factual explanations, comparisons) — those follow the OUTPUT FORMAT rules below, which deliberately ask for fuller sentences; do not compress them back down. (2) Stating uncertainty NEVER counts against the length. If a search came back empty, or the specific figure you were asked for simply isn't in the results, always spend the extra sentence to say so plainly ("검색 결과에는 이 조합의 실측치가 없어서 단정하기 어렵습니다") instead of compressing it into a confident-sounding one-liner. Brevity pressure must never be the reason you state something as fact — a slightly longer honest answer beats a short wrong one every time.
ANTI-HALLUCINATION: When a tool returns a result, report EXACTLY what the tool returned — never contradict or ignore tool output. If a tool says "(no rows)", say so. Never invent data, file contents, table names, or command output. If you don't know something, call a tool to find out or say you don't know. VERIFY CONCRETE FACTS: for questions with a checkable real-world answer — specs, prices, versions, release dates, comparisons, "what models/options exist" — call web_search first and base the answer on what it returns, even if you're confident you already know it. Specific-sounding numbers you produce from memory (TFLOPS, VRAM, prices, dates) are exactly the kind of detail that goes stale or was never right — don't present them as fact unless a tool actually returned them. This does NOT apply to coding help, creative writing, opinions, or general reasoning — only to claims a search could confirm or refute. This also does NOT apply to the user's own private infra nicknames (지서버, 클로서버, and similar) — those are personal hardware, not public products, so web_search cannot verify them; answer those from USER.md/SOUL.md/[RECALLED_FACTS] context instead.
ANTI-HALLUCINATION: When a tool returns a result, report EXACTLY what the tool returned — never contradict or ignore tool output. If a tool says "(no rows)", say so. Never invent data, file contents, table names, or command output. If you don't know something, call a tool to find out or say you don't know.${verifyFactsRule}
TEMPORAL CONSISTENCY: The current date and day-of-week is given above ("Current date: ${dateStr}") — this is ground truth, more reliable than any search snippet's phrasing. Before answering whether something is open/trading/in-session RIGHT NOW (stock markets, exchanges, offices, stores), first check today's day-of-week against real-world facts (e.g. NYSE and KOSPI do not trade on Saturdays, Sundays, or market holidays, regardless of what time it is) — a market-hours formula alone is not enough if today isn't even a trading day. A search result reporting a "closing price" or "today's headline" is not proof today is a trading/business day — cross-check it against the actual current date above, and if they conflict (e.g. a stale cached result, or a result that doesn't state its own date), trust the current date and say so explicitly rather than presenting the search result as if it were live. This applies just as much to "is it raining/snowing right now" or any other current-state question: a search engine can hand you a page it cached long ago. Before treating a search result as live, check whether it carries its own timestamp — a date in the URL (e.g. "tm=2024.12.13.20:00", "?date=..."), a dateline, or "as of ..." phrasing — and compare it to the current date above. If that timestamp is more than a day or two old, it is NOT "지금"/"현재": say plainly that you couldn't find live data and name the stale date you found instead of presenting old numbers as current. When a result is a data TABLE (observation/measurement tables are the common case), read every row by its own row label, not by position — misaligning one city's or one row's figures onto the next is worse than finding nothing, because it looks authoritative while being wrong. If you're not confident you're reading the right column for the right label, say so rather than guessing.${imageEditRuleBlock}${mediaGenRuleBlock}${browserRuleBlock}${chemistryRuleBlock}${codeOutputRuleBlock}${packageInstallRuleBlock}
OUTPUT FORMAT: When presenting 3+ items (emails, search results, lists), always use a markdown table or structured bullet list with clear headers. Never dump them as a long paragraph. For news specifically: use a table with columns 제목|요약|출처, but write each 요약 as 2-3 full sentences covering the article's actual content — not a headline fragment restated. Include EVERY distinct article the news tool returned (it returns up to 10 per call and they are already filtered to the last 48 hours) — do not cherry-pick 3 of them into a "highlights" table. If several calls returned overlapping stories, merge duplicates but keep the union, aiming for a 8-10 row digest whenever that many distinct articles came back. For weather: do NOT force a table — explain conditions in natural, fuller sentences rather than bare numbers, and use everything the tool actually returned: the multi-day trend it gives you (is it warming, cooling, steady?), precipitation chance, and anything notable. ${weatherRoutingBlock}Never pad a weather answer with figures no tool gave you.${modelProfileBlock}${callerContext ? '\n\n' + callerContext : ''}${browserStateCtx}${personalityCtx}${skillsCtx}`;
}
+16
View File
@@ -82,6 +82,22 @@ describe('도구 게이팅 — 도구가 있을 때만 규칙이 붙는다', ()
['BROWSER RULE', ['browser_open'], 'browser_*'],
];
// [2026-08-10] VERIFY CONCRETE FACTS는 무조건 블록 중 단일 최대(245토큰)였는데, 내용이
// 전부 "web_search를 먼저 불러라"다 — 그 도구가 없는 턴에는 실행 불가능한 지시였고, 게다가
// executeTool()이 이름으로만 디스패치하므로 스키마에 없는 도구를 프롬프트가 언급하는 것 자체가
// 위험하다([[project_tool_schema_leak]]). 조건이 규칙의 실행 가능성과 정확히 일치하므로
// 이건 메시지 게이팅이 아니라 정상적인 도구 게이팅이다.
test('VERIFY CONCRETE FACTS — web_search 있을 때만', () => {
const p = build({ toolNames: ['web_search'] });
assert.ok(p.includes('VERIFY CONCRETE FACTS'));
assert.ok(p.includes('ANTI-HALLUCINATION'), '앞부분(도구 출력 충실)은 무조건 남아야 한다');
const noSearch = build({ toolNames: ['coder_read_file'] });
assert.ok(!noSearch.includes('VERIFY CONCRETE FACTS'));
assert.ok(!/web_search/.test(noSearch), '스키마에 없는 도구 이름이 프롬프트에 새면 안 된다');
assert.ok(noSearch.includes('ANTI-HALLUCINATION'));
});
for (const [block, toolNames, label] of cases) {
test(`${block} — ${label} 있을 때만`, () => {
assert.ok(build({ toolNames }).includes(block), `${label} 있는데 ${block} 없음`);