v2.2.299~307: 아키텍처 수렴 + 채팅 정리 + 벤치마킹 강화 + Claude 구독 엔진

- v2.2.299 아키텍처 수렴: coreChat 통일(엔진 휴리스틱 3벌 제거), 기업 모드
  검색 오케스트레이터 승격, lib/execUtil(실행 래퍼 6곳·Python 탐지 3벌 단일화),
  lib/kstSchedule(워처 4개 nowInKst 통합), estimateTokens 통합, 설정 접근 규칙 명문화
- v2.2.300 채팅 화면 정리: LiveReasoningFilter(스트리밍 중 <think>/Harmony 추론
  토큰 단위 차단), 확신도·검토요청 footer 기본 숨김(계산·Reflection 은 유지)
- v2.2.301 문맥·의도 이해: [답변 전 이해 원칙] 상시 주입, 워크플로우 의도 브리핑,
  Report QA 루프(규칙 레지스트리+실측치+회귀 게이트, 블로그_v3 개념 이식)
- v2.2.302 /benchmark 비즈니스 렌즈(가격·수익·운영)+빌드 프롬프트 모드+QA 연계
- v2.2.303 handoff 모드(측정치 무손실 인수인계 문서)+/claude(Claude Code 터미널 위임)
- v2.2.304 이식성: 지식 경로 두뇌-상대 규약(pickWikiDir 상대 해석), 이사 체크리스트
- v2.2.305 Claude 구독 엔진: claude: 프로바이더(CLI 위임, 모델 드롭다운 자동 노출,
  coreChat 지원 — 워크플로우·QA도 구독 모델 가능)
- v2.2.306 Tone Guard: AI 상투어 금지 레지스트리(상담사 화법 실사례 8종+대조 예시)
- v2.2.307 /benchmark 레이아웃 골격(sectionRoles 결정론 분석, 롤링 배너 즉답),
  파트별 실패 격리, 합성 타임아웃 120→300초

검증: tsc 무오류 + jest 888 통과 + esbuild 정상

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
2026-07-11 21:02:15 +09:00
parent 98d533f045
commit 47b3b9f93a
66 changed files with 2421 additions and 459 deletions
+28 -52
View File
@@ -1,6 +1,10 @@
import { execFile } from 'child_process';
import { detectPython, execFileCapture, _resetPythonCache } from '../../lib/execUtil';
import type { HandlerContext } from './types';
// [코어 수렴] 실행 래퍼·Python 탐지는 lib/execUtil 단일 구현을 사용한다.
// 기존 소비자(runCode·테스트) 호환을 위해 재수출.
export { detectPython, _resetPythonCache };
/**
* <calculate> — 수학·논리·수치 계산을 Python 에 위임하는 액션 (ACTION 16).
*
@@ -24,35 +28,6 @@ const MAX_CALC_PER_TURN = 4; // 한 턴에 과도한 실행 방지
const MAX_CODE_CHARS = 4_000;
const MAX_OUTPUT_CHARS = 4_000; // 모델 컨텍스트 보호
/** 감지된 Python 실행 파일 캐시 (프로세스 생존 동안 유지, null = 미탐지/없음). */
let _pythonCmd: string | null | undefined;
function execFileP(cmd: string, args: string[], timeout: number): Promise<{ stdout: string; stderr: string }> {
return new Promise((resolve, reject) => {
execFile(cmd, args, { timeout, maxBuffer: 512 * 1024 }, (err, stdout, stderr) => {
if (err) reject(Object.assign(err, { stdout: String(stdout || ''), stderr: String(stderr || '') }));
else resolve({ stdout: String(stdout || ''), stderr: String(stderr || '') });
});
});
}
/** python3 → python → py 순으로 실행 가능한 인터프리터 탐지 (OS 자동 대응, run_code 도 공유). */
export async function detectPython(): Promise<string | null> {
if (_pythonCmd !== undefined) return _pythonCmd;
for (const cmd of ['python3', 'python', 'py']) {
try {
await execFileP(cmd, ['--version'], 3_000);
_pythonCmd = cmd;
return cmd;
} catch { /* 다음 후보 */ }
}
_pythonCmd = null;
return null;
}
/** 테스트용 — 캐시 초기화. */
export function _resetPythonCache(): void { _pythonCmd = undefined; }
export async function applyCalculateActions(ctx: HandlerContext): Promise<void> {
const { aiMessage, report } = ctx;
const calcRegex = /<calculate>([\s\S]*?)<\/calculate>/gi;
@@ -83,32 +58,33 @@ export async function applyCalculateActions(ctx: HandlerContext): Promise<void>
}
const label = code.replace(/\s+/g, ' ').slice(0, 60);
try {
const { stdout } = await execFileP(python, ['-I', '-c', code], CALC_TIMEOUT_MS);
const out = stdout.trim();
if (!out) {
// print 누락 — 모델이 스스로 고치도록 힌트를 재주입한다.
report.push(`⚠️ Calculated (no output): ${label}`);
ctx.chatHistory.push({
role: 'system', internal: true,
content: '[Result of calculate — EMPTY OUTPUT]\n코드는 실행됐지만 출력이 없습니다. 결과는 반드시 print(...) 로 출력해야 합니다. print 를 추가해 <calculate> 를 다시 emit 하십시오.',
});
} else {
const capped = out.length > MAX_OUTPUT_CHARS ? out.slice(0, MAX_OUTPUT_CHARS) + '\n… (truncated)' : out;
report.push(`🧮 Calculated: ${label}`);
ctx.chatHistory.push({
role: 'system', internal: true,
content: `[Result of calculate]\n\`\`\`\n${capped}\n\`\`\`\n이 실행 결과를 신뢰하고 그대로 사용해 답하십시오 (임의로 다시 암산하지 말 것).`,
});
}
} catch (err: any) {
const r = await execFileCapture(python, ['-I', '-c', code], { timeoutMs: CALC_TIMEOUT_MS, maxBuffer: 512 * 1024 });
if (r.timedOut || r.code !== 0) {
// 에러도 재주입 — 모델이 코드를 고쳐 재시도하는 자가수정 루프.
const tail = String(err?.stderr || err?.message || err).trim().split('\n').slice(-8).join('\n').slice(0, 1200);
const timedOut = err?.killed || /ETIMEDOUT|timed? ?out/i.test(String(err?.message || ''));
const tail = (r.stderr || r.stdout || `exit ${r.code}`).trim().split('\n').slice(-8).join('\n').slice(0, 1200);
report.push(`❌ Calculate failed: ${label}`);
ctx.chatHistory.push({
role: 'system', internal: true,
content: `[Result of calculate — ERROR]\n${timedOut ? `실행이 ${CALC_TIMEOUT_MS / 1000}초 안에 끝나지 않아 중단되었습니다. 더 효율적인 방법으로 다시 시도하십시오.` : `\`\`\`\n${tail}\n\`\`\`\n에러를 참고해 코드를 고친 뒤 <calculate> 를 다시 emit 하십시오. (표준 라이브러리만 사용 가능)`}`,
content: `[Result of calculate — ERROR]\n${r.timedOut ? `실행이 ${CALC_TIMEOUT_MS / 1000}초 안에 끝나지 않아 중단되었습니다. 더 효율적인 방법으로 다시 시도하십시오.` : `\`\`\`\n${tail}\n\`\`\`\n에러를 참고해 코드를 고친 뒤 <calculate> 를 다시 emit 하십시오. (표준 라이브러리만 사용 가능)`}`,
});
continue;
}
const out = r.stdout.trim();
if (!out) {
// print 누락 — 모델이 스스로 고치도록 힌트를 재주입한다.
report.push(`⚠️ Calculated (no output): ${label}`);
ctx.chatHistory.push({
role: 'system', internal: true,
content: '[Result of calculate — EMPTY OUTPUT]\n코드는 실행됐지만 출력이 없습니다. 결과는 반드시 print(...) 로 출력해야 합니다. print 를 추가해 <calculate> 를 다시 emit 하십시오.',
});
} else {
const capped = out.length > MAX_OUTPUT_CHARS ? out.slice(0, MAX_OUTPUT_CHARS) + '\n… (truncated)' : out;
report.push(`🧮 Calculated: ${label}`);
ctx.chatHistory.push({
role: 'system', internal: true,
content: `[Result of calculate]\n\`\`\`\n${capped}\n\`\`\`\n이 실행 결과를 신뢰하고 그대로 사용해 답하십시오 (임의로 다시 암산하지 말 것).`,
});
}
}