메인 채팅 시스템 프롬프트 감사 정리 — 낡은 "SmallClaw 저장소 검색 금지" 문장 삭제, "브라우저·데스크톱 자동화 사전 허가"는 그 도구가 있을 때만, 간결함 규칙 1,116→약 560자로 압축(불확실성 면제 조항 유지), TEMPORAL에 붙어 있던 최신 세대·검색 재시도 규칙을 NEWEST VERSIONS·SEARCH PERSISTENCE 문단으로 분리, "살기 좋은 곳은 어디야?" 같은 추천 질문엔 MAPS·place_search(구미 기준)가 안 붙게(isRecommendationWhere), AGENTS.md의 치의학 사전 퀴즈 섹션은 퀴즈·치의학 질문에만 싣기. 같은 날 기억 파일(USER/AGENTS/IDENTITY/SOUL.md)도 정리(백업 prompts/.bak-20261025): 클로서버=ProDesk 오기·낡은 주가·잡다한 출시일·중복 줄·없는 도구 이름·"When in doubt, ask" 제거. 메인 채팅 프롬프트 10,579→7,653자

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
kimandClaude Opus 5.5 committed 2026-10-25 11:15:13 +09:00
1 parent 53fd41837c
commit bada967530
5 files changed
+62 -6

No files matched your search

+5 -1
View File
@@ -285,7 +285,11 @@ return async function buildPersonalityContext(
if (!fileCache.has(filename)) {
fileCache.set(filename, loadWorkspaceFile(workspacePath, filename, 99999));
}
const raw = fileCache.get(filename) ?? '';
let raw = fileCache.get(filename) ?? '';
// AGENTS.md의 "## 치의학 …" 섹션(사전 DB 퀴즈 규칙)은 그런 요청에만 싣는다 — 매 턴 600자를 내던 것(2026-10-25 프롬프트 감사).
if (filename === 'AGENTS.md' && !/퀴즈|플래시\s*카드|치의학|치과\s*용어|dental|quiz|flash\s*card/i.test(`${messageText}\n${recentContextText}`)) {
raw = raw.replace(/\n## 치의학[\s\S]*?(?=\n## |\n---|$)/, '');
}
if (!raw) return '';
if (raw.length > maxChars) {
console.warn(`[Prompt] ${filename} truncated: ${raw.length} > ${maxChars} chars`);
+14 -3
View File
@@ -73,6 +73,16 @@ export function groundingResultReadingRule(dateStr: string): string {
- If the results describe an older generation of a product than the user implies, say so and search again rather than reporting the old model as new.`;
}
/**
* "살기 좋은 곳은 어디야?", "가볼 만한 데 어디야?" — '어디'가 들어가도 장소 추천이지 지도·주소 요청이 아니다.
* 지도·위치·주소·근처·길 어휘가 함께 있으면 지도 요청으로 본다. (2026-10-25 프롬프트 감사: 몬태나 추천 질문에
* 지도 규칙과 구미시 기준 장소검색 규칙이 붙던 것.) tool-scope.ts의 place_search 게이트도 같은 함수를 쓴다.
*/
export function isRecommendationWhere(message: string): boolean {
return /(?:좋은|좋을|괜찮은|추천|싼|저렴한|살기|가볼|놀기|여행하기|휴양하기)[^\n]{0,8}(?:곳|데|도시|지역|동네|나라)/.test(message)
&& !/지도|위치|주소|근처|주변|가까운|인근|가는\s*길|길\s*찾|맛집|약국|식당|카페/.test(message);
}
export function buildChatSystemPrompt(input: SystemPromptInput): string {
const backendLabel = getActiveBackendLabel();
const executionMode = String(input.executionMode || '');
@@ -169,7 +179,7 @@ export function buildChatSystemPrompt(input: SystemPromptInput): string {
// 만들어지고, 중간에 바꾸면 프리픽스가 달라져 KV 캐시가 통째로 무효화된다 — 라운드마다 7K
// 토큰을 다시 계산하게 된다. 뒤에 **덧붙이면** 프리픽스는 그대로다.
const searchReadingRule = hasGroundingTools
? ` When the user asks about the "newest"/"latest"/"신형"/"최신" version of a product WITHOUT naming a specific generation, do NOT put a generation you remember (e.g. "M4", "RTX 4090", "iPhone 15") into your search query — whatever was newest when you were trained is probably not newest now. Search with the current year and neutral terms ("Mac mini ${new Date().getFullYear()}", "latest Mac mini") and let the results tell you which generation is current.`
? `\nNEWEST VERSIONS: When the user asks about the "newest"/"latest"/"신형"/"최신" version of a product WITHOUT naming a specific generation, do NOT put a generation you remember (e.g. "M4", "RTX 4090", "iPhone 15") into your search query — whatever was newest when you were trained is probably not newest now. Search with the current year and neutral terms ("Mac mini ${new Date().getFullYear()}", "latest Mac mini") and let the results tell you which generation is current.`
: '';
// SEARCH PERSISTENCE (2026-09-21). Distilled from watching a thorough manual search session
@@ -180,7 +190,7 @@ export function buildChatSystemPrompt(input: SystemPromptInput): string {
// difference: reformulate and re-search instead of stopping at one phrasing, and reach for
// web_fetch on a promising URL instead of guessing from a truncated snippet.
const searchPersistenceRule = (hasGroundingTools && toolNames.has('web_fetch'))
? ` One search call is a first pass, not the final answer. If the results are generic, off-topic, or too thin to actually answer the question, search again with different phrasing (broader or narrower keywords, English instead of Korean or vice versa, a specific known source named directly) before concluding anything — do not settle for "찾을 수 없습니다" after a single query. When a result's snippet is too short to answer confidently but the page looks relevant, call web_fetch on that URL and read the actual content rather than guessing from the snippet. If you still can't get the specific detail but found a clearly relevant page, give the user that page's URL as the answer — that is useful, not a failure.`
? `\nSEARCH PERSISTENCE: One search call is a first pass, not the final answer. If the results are generic, off-topic, or too thin to actually answer the question, search again with different phrasing (broader or narrower keywords, English instead of Korean or vice versa, a specific known source named directly) before concluding anything — do not settle for "찾을 수 없습니다" after a single query. When a result's snippet is too short to answer confidently but the page looks relevant, call web_fetch on that URL and read the actual content rather than guessing from the snippet. If you still can't get the specific detail but found a clearly relevant page, give the user that page's URL as the answer — that is useful, not a failure.`
: '';
// 2026-10-23: 뉴스·날씨의 "더 길게" 문구(07-24, gemma4가 너무 짧게 답하던 때)를 낮췄다. Haiku는 원래 길게 쓰는
@@ -237,6 +247,7 @@ export function buildChatSystemPrompt(input: SystemPromptInput): string {
: '';
const mapsRuleBlock = /지도|맵으로|위치(를|가|는)?|주소|어디(에|야|예요|에요|입니까|인가|니|냐|쯤|메)|어디\s*(있|찾|가|계|위치|살|사는|근처)|길\s*찾|가는\s*길|찾아가|찾아오|약도|도로명|지번|좌표|경위도|근처|인근|부근|가까운|\bmap\b|\baddress\b|directions|navigate|where\s+is|how\s+(do\s+i\s+|to\s+)get\s+to|nearby|landmark/i
.test(`${input.prevUserMessage || ''}\n${input.message || ''}`)
&& !isRecommendationWhere(String(input.message || ''))
? '\nMAPS: When the user asks where a place is, for its address, or to see a map of a location, output the map URL on its own line — the client turns that standalone line into an inline map. For places IN KOREA use 카카오맵: `https://map.kakao.com/link/map/<URL-encoded name>,<lat>,<lon>` when you have coordinates (e.g. from place_search), otherwise `https://map.kakao.com/link/search/<URL-encoded query>`. Use Google only for places OUTSIDE Korea: `https://www.google.com/maps/search/<query>` (URL-encode, add city/country when ambiguous). Do NOT call browser_open for it and do NOT wrap it in `![](...)`. If the user asks for a map without naming a place ("지도 열어줘"), use the place the conversation is already about instead of asking which one. The map URL line must be bare — no bullet, no label in front. Do not use image search for a map. Still answer in text as well — the map is an addition, not a replacement. For driving routes in Korea use the route_search 길찾기 link instead (it renders as a route map); Google route links do not render.'
: '';
// VERIFY CONCRETE FACTS는 ANTI-HALLUCINATION 안에 무조건 붙어 있었지만, 하는 말이 통째로
@@ -287,7 +298,7 @@ export function buildChatSystemPrompt(input: SystemPromptInput): string {
const packageInstallRuleBlock = (toolNames.has('shell') || toolNames.has('run_command'))
? '\nPACKAGE INSTALL: Do not 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. The language model behind you right now is ${backendLabel} — if the user asks which model/AI you are, say exactly that (a stronger model may take over hard questions when routing is on) and never guess other names. Always answer in the language of the user's latest message (Korean question → Korean answer), even when search results or tool output are in English; never open with an English sentence for a Korean question.\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) informational answers you researched with a tool (news, weather, factual explanations, comparisons) are not held to 2-4 sentences, but size them to the question: lead with the answer, and leave out background, caveats and closing offers ("더 필요하시면…") the user did not ask for. (2) Stating uncertainty never counts against the length — but only when it is about what was asked: if a search came back empty, or the specific figure or fact you were asked for simply isn't in the results, 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. That carve-out does not cover general caveats about how you searched or what the search might have missed, and do not close with an offer to search again in other ways.
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. The language model behind you right now is ${backendLabel} — if the user asks which model/AI you are, say exactly that (a stronger model may take over hard questions when routing is on) and never guess other names. Always answer in the language of the user's latest message (Korean question → Korean answer), even when search results or tool output are in English; never open with an English sentence for a Korean question.\nCurrent date: ${dateStr}, ${timeStr}.\n${hasBrowserTools || hasToolPrefix('desktop_') ? "This app runs on the user's own machine — browser/desktop automation requests are pre-authorized.\\n" : ''}LENGTH: Conversational and task replies: 2-4 sentences — act and report, don't think out loud, greet without tools. Answers researched with a tool (news, weather, facts, comparisons) may be longer, but lead with the answer and skip background, generic caveats and closing offers ("더 필요하시면…"). Stating uncertainty never counts against the length: if the specific thing asked for isn't in the results, say so plainly in one sentence instead of compressing it into a confident one-liner — a slightly longer honest answer beats a short wrong one.
${continuityRule}
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.${marketDayRule}${searchReadingRule}${searchPersistenceRule}${fileSearchRule}${imageEditRuleBlock}${mediaGenRuleBlock}${browserRuleBlock}${chemistryRuleBlock}${mapsRuleBlock}${placeSearchRuleBlock}${routeSearchRuleBlock}${codeOutputRuleBlock}${packageInstallRuleBlock}
+2 -1
View File
@@ -22,6 +22,7 @@
* because a missed keyword there would drop a suppression rule.
*/
import { isRecommendationWhere } from './system-prompt';
import { DISASTER_PATTERN } from '../guards/prompt-gates';
export interface ToolScopeInput {
@@ -191,7 +192,7 @@ export function buildSkillToolFilter(input: ToolScopeInput): (toolName: string)
// place_search — 카카오맵 장소검색(2026-10-14). "근처·맛집·약국·주소·전화번호·길찾기" 류에만 연다.
// 후속 발화("거기 전화번호는?")가 앞 턴의 주제를 물려받으므로 topicText로 검사한다. 스테일 매치 비용은
// 스키마 토큰뿐. "병원"은 CMS 병원 성과 질문과 겹쳐서 단독으로는 넣지 않고 근처·위치 어휘와 함께만 본다.
const hasPlaceKeyword = /근처|주변|가까운|인근|맛집|약국|식당|카페|편의점|주유소|마트|주차장|지도|길\s*찾|가는\s*길|어디(?:에|야|예요|있)|전화\s*번호|영업\s*시간|몇\s*시까지|주소|위치/i.test(topicText);
const hasPlaceKeyword = /근처|주변|가까운|인근|맛집|약국|식당|카페|편의점|주유소|마트|주차장|지도|길\s*찾|가는\s*길|어디(?:에|야|예요|있)|전화\s*번호|영업\s*시간|몇\s*시까지|주소|위치/i.test(topicText) && !isRecommendationWhere(message);
// exchange_rate — 환율 조회·환산(2026-10-25). 환율·통화 어휘가 최근 사용자 발화에 있거나, 직전 답에 외화
// 금액이 있고 이번 말이 원화 금액·환산을 물을 때("한달에 300만 원 정도란 거지?" ← 직전 답 "$1,600~2,400").
const FX_WORDS = /환율|환전|환산|원화로|달러|엔화|유로|위안|파운드|바트|페소|\$\s?\d|\d\s?(?:엔|위안)(?!진)|\b(?:USD|JPY|EUR|CNY|GBP|AUD|CAD|HKD|TWD|VND|THB)\b|exchange\s*rate|currency/i;
+40
View File
@@ -0,0 +1,40 @@
/**
* 2026-10-25 메인 채팅 시스템 프롬프트 감사 — 정리한 규칙이 되살아나지 않게.
*/
import { describe, test } from 'node:test';
import assert from 'node:assert/strict';
import { buildChatSystemPrompt, isRecommendationWhere } from '../src/gateway/chat/system-prompt';
const build = (message: string, toolNames: string[] = ['web_search', 'web_fetch', 'place_search', 'python_eval']) =>
buildChatSystemPrompt({ toolNames, dateStr: 'Sunday, October 25, 2026', timeStr: '11:00 AM', message } as any);
describe('isRecommendationWhere', () => {
test('장소 추천은 지도 요청이 아니다', () => {
assert.equal(isRecommendationWhere('몬태나 주 살기 좋은 곳은 어디야?'), true);
assert.equal(isRecommendationWhere('휴양하기 좋은 저렴한 곳 어디야'), true);
});
test('지도·위치·근처 어휘가 있으면 지도 요청', () => {
assert.equal(isRecommendationWhere('구미역 어디야?'), false);
assert.equal(isRecommendationWhere('근처 괜찮은 곳 어디야'), false);
assert.equal(isRecommendationWhere('살기 좋은 곳 지도로 보여줘'), false);
});
});
describe('시스템 프롬프트 정리', () => {
test('추천 질문엔 MAPS가 안 붙고, 위치 질문엔 붙는다', () => {
assert.doesNotMatch(build('몬태나 주 살기 좋은 곳은 어디야?'), /\nMAPS:/);
assert.match(build('구미역 어디야?'), /\nMAPS:/);
});
test('낡은 문장은 없고, 자동화 허가 문구는 브라우저·데스크톱 도구가 있을 때만', () => {
const p = build('안녕');
assert.doesNotMatch(p, /SmallClaw repos/);
assert.doesNotMatch(p, /pre-authorized/);
assert.match(build('안녕', ['browser_open']), /pre-authorized/);
});
test('검색 규칙은 각자 문단', () => {
const p = build('최신 맥미니 가격');
assert.match(p, /\nNEWEST VERSIONS: /);
assert.match(p, /\nSEARCH PERSISTENCE: /);
assert.match(p, /\nLENGTH: /);
});
});
+1 -1
View File
@@ -66,7 +66,7 @@ describe('무조건 들어가는 블록', () => {
test('불확실성 표현은 길이 제한에서 면제된다는 조항이 살아있다', () => {
// 이 조항이 빠지면 1-2문장 압박이 "모른다"를 밀어내고 환각을 확신형 한 줄로 포장한다.
const p = build();
assert.ok(/Stating uncertainty NEVER counts against the length/i.test(p));
assert.ok(/Stating uncertainty never counts against the length/i.test(p)); // 10-25 LENGTH로 압축하며 대소문자만 바뀜
});
// [2026-08-10] 실제 사고(세션 papa@2d4f3f6e): "지금 비오는 곳이 있나?"에 web_search를 부르긴