v2.2.311~312: 응답 지연 근본 개선(KV 캐시 분리·제2뇌 상주 캐시) + 보고 품질 수술
v2.2.311 — 응답 지연 (실측: 출력 22토큰에 94.7초, 원인은 매 턴 13k+ 토큰 전체 재프리필) - KV 캐시 친화 프롬프트 분리(kvCachePromptSplit, 기본 ON): message[0]을 불변 정적 본문으로 고정, 날짜/RAG/[CONTEXT]/동적 블록을 마지막 user 메시지 직전의 internal system 메시지로 이동 — llama.cpp prompt cache 프리픽스 재사용으로 턴당 재프리필을 "직전 교환 + 동적 컨텍스트"로 축소. truncation 도 tail 적용. - 검색 토큰 예산 현실화(retrievalTokenBudget, 0=자동): 창의 25%(8k~80k) → 12%(2.5k~6k 클램프). - continuation 은 depth-0 memoryCtx 재사용: 라운드당 재검색 3~8초 제거 + 빈 쿼리 재검색으로 청크가 갈리던 문제 제거 + 턴 내 프롬프트 안정화. - 제2뇌 상주 캐시(신규 brainWatch.ts): 재귀 fs.watch 세대 카운터로 변경 없으면 디렉터리 워크·파일별 statSync 전면 생략. 수정 직후 3초 창은 신뢰 제외(이벤트 지연 레이스 가드), 워처 불가 시 종전 폴백, 활성화 시 백그라운드 워밍, 유휴 해제 30분→2시간. v2.2.312 — 보고 품질 (실사례: "## 4."부터 시작하는 7줄 일반론 보고서) - 중간 라운드 본문 표시 버그 수정: 액션과 함께 작성된 섹션(1~3)이 화면에 한 번도 안 나가고 최종 라운드만 표시되던 근본 원인 제거 — stripForDisplay.ts 로 액션 태그만 걷어내고 라운드 순서대로 버블에 표시. - '분석 보고' 업무 유형 신설(requirementGraph): 보고 개요(첫 줄 자기선언)·파일 근거(주장마다 실제 읽은 파일 인용, 일반론 금지)·구조·발견·다음 단계 강제, 유형 감지 시 "최대 3섹션" 규칙보다 필수 요소 커버 우선. - 근거 없는 분석 감지: 파일을 읽고도 인용 2개 미만인 장문 분석에 "근거 인용 없음" footer 경고 (헛조사 감지의 반대 방향). 검증: 전체 테스트 954건 통과(신규 28), tsc 무오류, vsix 패키징·설치 확인. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,98 @@
|
||||
/**
|
||||
* [v2.2.311] 제2뇌 상주 캐시 계층 — 워처 세대 기반 stat 생략 + 파일 목록 캐시.
|
||||
*
|
||||
* 핵심 계약:
|
||||
* 1. 워처 세대가 그대로면 getBrainTokenIndex 는 파일별 statSync 를 생략한다.
|
||||
* 2. 세대가 바뀌면(파일시스템 변경) 다시 stat 을 거쳐 변경분을 재색인한다.
|
||||
* 3. 부분(스코프) 목록으로 검증된 상태에서 전체 목록 질의가 와도, 검증 안 된
|
||||
* 파일은 신뢰 경로로 새지 않는다 (파일 단위 검증 장부).
|
||||
* 4. 워처 불가 환경(gen === -1)에서는 종전과 동일하게 매번 stat.
|
||||
*/
|
||||
import * as fs from 'fs';
|
||||
import * as os from 'os';
|
||||
import * as path from 'path';
|
||||
|
||||
// brainWatch 를 결정적으로 제어 — 실제 fs.watch 이벤트 타이밍에 의존하지 않는다.
|
||||
let mockGen = 0;
|
||||
jest.mock('../src/retrieval/brainWatch', () => ({
|
||||
ensureBrainWatcher: jest.fn(),
|
||||
getBrainGeneration: jest.fn(() => mockGen),
|
||||
listBrainFilesCached: jest.fn(),
|
||||
warmBrainCache: jest.fn(),
|
||||
disposeBrainWatcher: jest.fn(),
|
||||
}));
|
||||
|
||||
import { getBrainTokenIndex } from '../src/retrieval/brainIndex';
|
||||
|
||||
function makeBrain(files: Record<string, string>): { root: string; paths: string[] } {
|
||||
const root = fs.mkdtempSync(path.join(os.tmpdir(), 'astra-brain-'));
|
||||
const paths: string[] = [];
|
||||
for (const [name, content] of Object.entries(files)) {
|
||||
const p = path.join(root, name);
|
||||
fs.writeFileSync(p, content, 'utf8');
|
||||
// RECENT_MTIME_GUARD(3초): 갓 수정된 파일은 신뢰 명부에 오르지 않으므로,
|
||||
// "변경 없음" 시나리오를 테스트하려면 mtime 을 과거로 되돌린다.
|
||||
const past = new Date(Date.now() - 60_000);
|
||||
fs.utimesSync(p, past, past);
|
||||
paths.push(p);
|
||||
}
|
||||
return { root, paths };
|
||||
}
|
||||
|
||||
function countStatsFor(paths: string[], spy: jest.SpyInstance): number {
|
||||
return spy.mock.calls.filter((c) => paths.includes(String(c[0]))).length;
|
||||
}
|
||||
|
||||
describe('getBrainTokenIndex — 워처 세대 기반 stat 생략', () => {
|
||||
afterEach(() => jest.restoreAllMocks());
|
||||
|
||||
test('같은 세대의 2번째 호출은 statSync 0회 (캐시 신뢰)', () => {
|
||||
mockGen = 0;
|
||||
const { root, paths } = makeBrain({ 'a.md': '알파 내용', 'b.md': '베타 내용' });
|
||||
expect(getBrainTokenIndex(root, paths)).toHaveLength(2);
|
||||
|
||||
const spy = jest.spyOn(fs, 'statSync');
|
||||
const r2 = getBrainTokenIndex(root, paths);
|
||||
expect(r2).toHaveLength(2);
|
||||
expect(countStatsFor(paths, spy)).toBe(0);
|
||||
expect(r2.map((d) => d.title).sort()).toEqual(['a', 'b']);
|
||||
});
|
||||
|
||||
test('세대가 바뀌면 재-stat 후 변경 내용을 재색인한다', () => {
|
||||
mockGen = 0;
|
||||
const { root, paths } = makeBrain({ 'a.md': '원본 토큰들' });
|
||||
getBrainTokenIndex(root, paths);
|
||||
|
||||
// 파일 변경 + 세대 bump (mtime 차이를 보장하기 위해 utimesSync 로 강제)
|
||||
fs.writeFileSync(paths[0], '완전히 새로운 내용입니다', 'utf8');
|
||||
const future = new Date(Date.now() + 5000);
|
||||
fs.utimesSync(paths[0], future, future);
|
||||
mockGen = 1;
|
||||
|
||||
const spy = jest.spyOn(fs, 'statSync');
|
||||
const r = getBrainTokenIndex(root, paths);
|
||||
expect(countStatsFor(paths, spy)).toBeGreaterThan(0);
|
||||
expect(r[0].tokens).toEqual(expect.arrayContaining(['새로운']));
|
||||
});
|
||||
|
||||
test('스코프 검증 후 전체 질의 — 미검증 파일은 신뢰 경로로 새지 않는다', () => {
|
||||
mockGen = 0;
|
||||
const { root, paths } = makeBrain({ 'in-scope.md': '스코프 안', 'out-scope.md': '스코프 밖' });
|
||||
const [inScope, outScope] = paths;
|
||||
getBrainTokenIndex(root, [inScope]); // 부분 목록만 검증됨
|
||||
|
||||
const spy = jest.spyOn(fs, 'statSync');
|
||||
getBrainTokenIndex(root, paths); // 전체 질의
|
||||
expect(countStatsFor([inScope], spy)).toBe(0); // 검증된 파일은 생략
|
||||
expect(countStatsFor([outScope], spy)).toBeGreaterThan(0); // 미검증 파일은 stat
|
||||
});
|
||||
|
||||
test('워처 불가(gen=-1) 환경은 매번 stat (종전 동작)', () => {
|
||||
mockGen = -1;
|
||||
const { root, paths } = makeBrain({ 'a.md': '내용' });
|
||||
getBrainTokenIndex(root, paths);
|
||||
const spy = jest.spyOn(fs, 'statSync');
|
||||
getBrainTokenIndex(root, paths);
|
||||
expect(countStatsFor(paths, spy)).toBeGreaterThan(0);
|
||||
});
|
||||
});
|
||||
@@ -56,3 +56,92 @@ describe('computeBudgetedRequest — real-window alignment', () => {
|
||||
expect(run({ actualContextLength: NaN }).effectiveContextLength).toBe(32768);
|
||||
});
|
||||
});
|
||||
|
||||
// ────────────────────────────────────────────────────────────────────────────
|
||||
// [v2.2.311] KV 캐시 분리 — dynamicContextTail 삽입 계약.
|
||||
// message[0] 은 불변 정적 프롬프트로 남고, 동적 컨텍스트는 마지막 user 메시지
|
||||
// 직전의 internal system 메시지로 들어가야 프롬프트 프리픽스 캐시가 산다.
|
||||
// ────────────────────────────────────────────────────────────────────────────
|
||||
describe('computeBudgetedRequest — dynamicContextTail (KV cache split)', () => {
|
||||
const HEAD = 'STATIC HEAD PROMPT';
|
||||
const TAIL = '[CURRENT DATE/TIME]\nToday: 2026-07-20\n\n[CONTEXT]\nRAG chunk A\n[/CONTEXT]';
|
||||
|
||||
// 주의: default parameter 는 명시적 undefined 에도 적용되므로 쓰지 않는다 —
|
||||
// "tail 없음" 케이스를 정확히 표현하기 위해 항상 명시적으로 넘긴다.
|
||||
function runSplit(reqMessages: ChatMessage[], tail: string | undefined) {
|
||||
return computeBudgetedRequest({
|
||||
fullSystemPrompt: HEAD,
|
||||
dynamicContextTail: tail,
|
||||
reqMessages,
|
||||
actualModel: 'some-13b-model',
|
||||
config: baseConfig,
|
||||
imageCount: 0,
|
||||
});
|
||||
}
|
||||
|
||||
test('tail 은 마지막 user 메시지 직전에 internal system 으로 삽입된다', () => {
|
||||
const msgs: ChatMessage[] = [
|
||||
{ role: 'user', content: '첫 질문' },
|
||||
{ role: 'assistant', content: '첫 답' },
|
||||
{ role: 'user', content: '두번째 질문' },
|
||||
];
|
||||
const r = runSplit(msgs, TAIL);
|
||||
expect(r.messagesForRequest[0]).toMatchObject({ role: 'system', content: HEAD });
|
||||
const idx = r.messagesForRequest.findIndex((m) => m.content === TAIL);
|
||||
expect(idx).toBeGreaterThan(0);
|
||||
expect(r.messagesForRequest[idx].role).toBe('system');
|
||||
expect(r.messagesForRequest[idx + 1]).toMatchObject({ role: 'user', content: '두번째 질문' });
|
||||
});
|
||||
|
||||
test('continuation(마지막 user 뒤 액션 결과 system)이 있어도 tail 은 user 앞', () => {
|
||||
const msgs: ChatMessage[] = [
|
||||
{ role: 'user', content: '조사해줘' },
|
||||
{ role: 'system', content: '[Result of read_file] ...', internal: true },
|
||||
];
|
||||
const r = runSplit(msgs, TAIL);
|
||||
const tailIdx = r.messagesForRequest.findIndex((m) => m.content === TAIL);
|
||||
const userIdx = r.messagesForRequest.findIndex((m) => m.role === 'user');
|
||||
const actionIdx = r.messagesForRequest.findIndex((m) => String(m.content).startsWith('[Result of'));
|
||||
expect(tailIdx).toBeLessThan(userIdx);
|
||||
expect(actionIdx).toBeGreaterThan(userIdx);
|
||||
});
|
||||
|
||||
test('user 메시지가 없으면 tail 을 히스토리 끝에 붙인다', () => {
|
||||
const msgs: ChatMessage[] = [{ role: 'system', content: 'internal only', internal: true }];
|
||||
const r = runSplit(msgs, TAIL);
|
||||
const last = r.messagesForRequest[r.messagesForRequest.length - 1];
|
||||
expect(last.content).toBe(TAIL);
|
||||
});
|
||||
|
||||
test('tail 미지정이면 종전 단일-시스템 동작 그대로', () => {
|
||||
const msgs: ChatMessage[] = [{ role: 'user', content: 'hello' }];
|
||||
const r = runSplit(msgs, undefined);
|
||||
expect(r.messagesForRequest).toHaveLength(2);
|
||||
expect(r.messagesForRequest[0].content).toBe(HEAD);
|
||||
});
|
||||
|
||||
test('예산 초과 시 [CONTEXT] truncation 은 tail 에 적용되고 head 는 보존', () => {
|
||||
const hugeTail = `[CONTEXT]\n${'긴 배경 지식 청크. '.repeat(20000)}\n[/CONTEXT]`;
|
||||
const msgs: ChatMessage[] = [{ role: 'user', content: 'hello' }];
|
||||
const r = computeBudgetedRequest({
|
||||
fullSystemPrompt: HEAD,
|
||||
dynamicContextTail: hugeTail,
|
||||
reqMessages: msgs,
|
||||
actualModel: 'some-13b-model',
|
||||
config: { ...baseConfig, contextLength: 8192 },
|
||||
imageCount: 0,
|
||||
});
|
||||
expect(r.systemTruncated).toBe(true);
|
||||
expect(r.messagesForRequest[0].content).toBe(HEAD);
|
||||
const tailMsg = r.messagesForRequest.find((m) => String(m.content).includes('[CONTEXT]'));
|
||||
expect(tailMsg).toBeDefined();
|
||||
expect(String(tailMsg!.content).length).toBeLessThan(hugeTail.length);
|
||||
});
|
||||
|
||||
test('systemTokens 는 head+tail 합산으로 보고된다', () => {
|
||||
const msgs: ChatMessage[] = [{ role: 'user', content: 'hello' }];
|
||||
const withTail = runSplit(msgs, TAIL);
|
||||
const withoutTail = runSplit(msgs, undefined);
|
||||
expect(withTail.systemTokens).toBeGreaterThan(withoutTail.systemTokens);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -165,3 +165,29 @@ describe('detectHollowInvestigation — 헛조사 감지', () => {
|
||||
expect(footer).toContain('investigate_files');
|
||||
});
|
||||
});
|
||||
|
||||
// [v2.2.312] 근거 없는 분석 감지 — 파일을 읽고도 인용이 없는 일반론 보고.
|
||||
import { detectUngroundedAnalysis, formatUngroundedAnalysisFooter } from '../src/intelligence/investigationPipeline';
|
||||
|
||||
describe('detectUngroundedAnalysis — 일반론 분석 감지', () => {
|
||||
const generic = '이 프로젝트는 로컬 LLM과 RAG 기술의 결합 시도가 매우 인상적입니다. '.repeat(10);
|
||||
|
||||
test('read 를 하고도 파일 인용 없는 장문 = ungrounded', () => {
|
||||
const r = detectUngroundedAnalysis(generic, { reads: 3, lists: 1, investigates: 0 });
|
||||
expect(r.ungrounded).toBe(true);
|
||||
expect(r.readCount).toBe(3);
|
||||
});
|
||||
test('파일 근거를 2개 이상 인용하면 정상', () => {
|
||||
const grounded = `${generic} 근거: agent.ts 의 handlePrompt 와 memoryContext.ts 의 buildMemoryContext 를 확인함.`;
|
||||
expect(detectUngroundedAnalysis(grounded, { reads: 3, lists: 1, investigates: 0 }).ungrounded).toBe(false);
|
||||
});
|
||||
test('read 가 없으면 판정 대상 아님 (hollow 감지의 영역)', () => {
|
||||
expect(detectUngroundedAnalysis(generic, { reads: 0, lists: 1, investigates: 0 }).ungrounded).toBe(false);
|
||||
});
|
||||
test('짧은 확인형 응답은 오탐 방지로 제외', () => {
|
||||
expect(detectUngroundedAnalysis('네, 서버 정상입니다.', { reads: 1, lists: 0, investigates: 0 }).ungrounded).toBe(false);
|
||||
});
|
||||
test('footer 에 읽은 횟수 포함', () => {
|
||||
expect(formatUngroundedAnalysisFooter(3)).toContain('3회');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
/**
|
||||
* [v2.2.311] KV 캐시 친화 프롬프트 분리 — 정적/동적 경계 계약.
|
||||
*
|
||||
* 정적 프롬프트(getStaticSystemPrompt)에 분 단위 시각 같은 가변 요소가 섞이는 순간
|
||||
* llama.cpp prompt cache 는 요청 첫 토큰부터 무효화된다 (실측: 13k 토큰 전체 재프리필
|
||||
* ≈ 90초/턴). 이 테스트는 그 회귀를 막는 가드레일이다.
|
||||
*/
|
||||
import { getStaticSystemPrompt, getDateTimeContextBlock, getSystemPrompt } from '../src/utils';
|
||||
import { buildAstraModeSystemPrompt } from '../src/agent/handlePrompt/buildAstraModeSystemPrompt';
|
||||
|
||||
describe('정적/동적 시스템 프롬프트 분리', () => {
|
||||
test('정적 프롬프트에는 날짜/시각이 없다 (캐시 무효화 가드)', () => {
|
||||
const s = getStaticSystemPrompt();
|
||||
expect(s).not.toContain('[CURRENT DATE/TIME]');
|
||||
// 오늘 날짜 문자열이 어떤 형태로도 들어있으면 안 된다.
|
||||
const iso = new Date().toISOString().split('T')[0];
|
||||
expect(s).not.toContain(iso);
|
||||
});
|
||||
|
||||
test('정적 프롬프트는 연속 호출에서 동일하다 (프리픽스 불변)', () => {
|
||||
expect(getStaticSystemPrompt()).toBe(getStaticSystemPrompt());
|
||||
});
|
||||
|
||||
test('날짜 블록은 오늘 날짜를 포함한다', () => {
|
||||
const block = getDateTimeContextBlock();
|
||||
expect(block).toContain('[CURRENT DATE/TIME]');
|
||||
expect(block).toContain(new Date().toISOString().split('T')[0]);
|
||||
});
|
||||
|
||||
test('레거시 getSystemPrompt 는 정적 본문 + 날짜 블록을 모두 포함 (호환)', () => {
|
||||
const s = getSystemPrompt();
|
||||
expect(s).toContain('[CURRENT DATE/TIME]');
|
||||
expect(s).toContain('[출력 위생 규칙 — 반드시 준수]');
|
||||
});
|
||||
|
||||
test('빌더에 systemPrompt="" 를 넘겨도 [CONTEXT] 골격은 유지된다 (tail 생성 경로)', () => {
|
||||
const tail = buildAstraModeSystemPrompt({
|
||||
prompt: '질문',
|
||||
systemPrompt: '',
|
||||
modeBridgeCtx: '',
|
||||
priorConclusionCtx: '',
|
||||
designerCtx: '',
|
||||
projectArchitectureCtx: '',
|
||||
secondBrainTraceCtx: '',
|
||||
memoryCtx: 'RAG 본문',
|
||||
knowledgeContextForPrompt: '',
|
||||
contextBlock: '열린 파일 내용',
|
||||
negativeCtx: '',
|
||||
isCasualConversation: false,
|
||||
localPathContext: '',
|
||||
knowledgeMix: null,
|
||||
dynamicBlocks: new Map([['behavior-constraints', '[GROUNDING] 근거 강도: 보통']]),
|
||||
});
|
||||
expect(tail).toContain('[CONTEXT]');
|
||||
expect(tail).toContain('RAG 본문');
|
||||
expect(tail).toContain('열린 파일 내용');
|
||||
expect(tail).toContain('[GROUNDING]');
|
||||
expect(tail.startsWith('You are Astra')).toBe(false); // 정적 본문이 섞이면 안 됨
|
||||
});
|
||||
});
|
||||
@@ -124,3 +124,23 @@ describe('DEFAULT_TASK_REQUIREMENTS 무결성', () => {
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
// [v2.2.312] 분석 보고 유형 — "프로젝트 분석하고 보고해줘" 실사례가 유형 미감지로
|
||||
// 일반론 총평이 되던 갭을 막는다.
|
||||
describe('detectTaskType — analysis-report (v2.2.312)', () => {
|
||||
test('실사례 문장을 정확히 감지한다', () => {
|
||||
expect(detectTaskType('E:\Wiki\connectai 프로젝트를 분석하고 어떻게 되어 있는지 보고해줘')?.id).toBe('analysis-report');
|
||||
expect(detectTaskType('진행 현황 보고 부탁해')?.id).toBe('analysis-report');
|
||||
expect(detectTaskType('이 코드 검토해서 보고해줘')?.id).toBe('analysis-report');
|
||||
});
|
||||
test('더 구체적인 유형이 우선한다 (회의록·시장조사)', () => {
|
||||
expect(detectTaskType('회의록으로 정리해서 보고해줘')?.id).toBe('meeting-minutes');
|
||||
expect(detectTaskType('시장조사 결과 보고해줘')?.id).toBe('market-research');
|
||||
});
|
||||
test('블록에 파일 근거 요소와 섹션 규칙 오버라이드가 포함된다', () => {
|
||||
const block = buildRequirementGraphBlock('프로젝트 분석하고 보고해줘');
|
||||
expect(block).toContain('파일 근거');
|
||||
expect(block).toContain('보고 개요');
|
||||
expect(block).toContain('최대 3섹션');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
/**
|
||||
* [v2.2.312] 중간 라운드 표시용 액션 태그 제거 — "## 4.부터 시작하는 보고서" 버그의
|
||||
* 표시 경로 헬퍼. 태그는 걷어내되 본문 섹션은 보존해야 한다.
|
||||
*/
|
||||
import { stripActionTagsForDisplay } from '../src/agent/actions/stripForDisplay';
|
||||
|
||||
describe('stripActionTagsForDisplay', () => {
|
||||
test('자기닫힘 태그 제거 + 본문 보존', () => {
|
||||
const input = '## 1. 프로젝트 개요\n구조를 확인한다.\n<read_file path="src/agent.ts"/>\n<list_files path="src"/>';
|
||||
const out = stripActionTagsForDisplay(input);
|
||||
expect(out).toContain('## 1. 프로젝트 개요');
|
||||
expect(out).not.toContain('<read_file');
|
||||
expect(out).not.toContain('<list_files');
|
||||
});
|
||||
test('블록 태그(내용 포함) 제거', () => {
|
||||
const input = '분석 시작.\n<run_command>cd x; npm test</run_command>\n<create_file path="a.md">본문</create_file>\n끝.';
|
||||
const out = stripActionTagsForDisplay(input);
|
||||
expect(out).toContain('분석 시작.');
|
||||
expect(out).toContain('끝.');
|
||||
expect(out).not.toContain('npm test');
|
||||
expect(out).not.toContain('<create_file');
|
||||
});
|
||||
test('잔재 여는/닫는 태그도 정리', () => {
|
||||
const out = stripActionTagsForDisplay('앞 <edit_file path="x.ts"> 뒤');
|
||||
expect(out).not.toContain('<edit_file');
|
||||
expect(out).toContain('앞');
|
||||
expect(out).toContain('뒤');
|
||||
});
|
||||
test('태그 없는 본문은 그대로', () => {
|
||||
expect(stripActionTagsForDisplay('## 2. 구조\n- src/agent.ts')).toBe('## 2. 구조\n- src/agent.ts');
|
||||
});
|
||||
test('빈 입력 안전', () => {
|
||||
expect(stripActionTagsForDisplay('')).toBe('');
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user