From 4db75d46cdcad62192997a781b0ace099ac2c20e Mon Sep 17 00:00:00 2001 From: lacvet Date: Sun, 12 Apr 2026 22:15:26 +0900 Subject: [PATCH] =?UTF-8?q?=EC=BD=94=EC=9B=8C=ED=81=AC=20=EB=AC=B8?= =?UTF-8?q?=EC=84=9C=20=EC=83=9D=EC=84=B1=20=EA=B2=8C=EC=9D=B4=ED=8A=B8?= =?UTF-8?q?=EC=99=80=20=EC=BD=94=EB=93=9C=20=ED=9B=84=EC=86=8D=20=EA=B2=80?= =?UTF-8?q?=EC=A6=9D=20=EA=B2=8C=EC=9D=B4=ED=8A=B8=EB=A5=BC=20claw-code=20?= =?UTF-8?q?=EA=B8=B0=EC=A4=80=EC=9C=BC=EB=A1=9C=20=EA=B2=BD=EB=9F=89?= =?UTF-8?q?=ED=99=94?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - balanced/tool_call_strict 프로필의 document_plan 재시도와 공격적 문서 fallback 개입을 줄여 Cowork 루프를 더 얇게 정리함 - document_plan 성공 직후 강제 user follow-up 주입을 제거하고 terminal 문서 도구 성공 시 Cowork에서 바로 종료할 수 있게 조정함 - CodeDiffGate, RecentExecutionGate, ExecutionSuccessGate를 review 작업 중심으로 제한해 일반 코드 수정의 과검증을 완화함 - TaskTypePolicy, SystemPromptBuilder, cowork preset을 함께 맞춰 문서 생성/분석형 요청의 종료 조건을 일관되게 정리함 - README.md 및 docs/DEVELOPMENT.md를 2026-04-12 23:05 (KST) 기준으로 갱신함 - 검증: dotnet build src/AxCopilot/AxCopilot.csproj -c Release -v minimal -p:OutputPath=bin\\verify\\ -p:IntermediateOutputPath=obj\\verify\\ (경고 0, 오류 0) --- README.md | 6 ++++ docs/DEVELOPMENT.md | 27 ++++++++++++++ .../Assets/Presets/cowork_문서작성.json | 4 +-- .../Assets/Presets/cowork_보고서.json | 4 +-- .../Services/Agent/AgentLoopService.cs | 11 ++++-- .../Agent/AgentLoopTransitions.Documents.cs | 36 +++++-------------- .../AgentLoopTransitions.Verification.cs | 10 ++++++ .../Agent/ModelExecutionProfileCatalog.cs | 8 ++--- .../Services/Agent/TaskTypePolicy.cs | 28 +++++++-------- .../Views/ChatWindow.SystemPromptBuilder.cs | 6 ++-- 10 files changed, 86 insertions(+), 54 deletions(-) diff --git a/README.md b/README.md index 598ca46..eb6aeb5 100644 --- a/README.md +++ b/README.md @@ -1659,3 +1659,9 @@ MIT License - OpenAI/vLLM 호환 경로의 tool history 직렬화를 더 가볍게 만들어, 최근 구간만 구조화된 `tool_calls/tool` 형식을 유지하고 오래된 구간은 평탄한 transcript로 낮췄습니다. - [LlmService.ToolUse.cs](/E:/AX%20Copilot%20-%20Codex/src/AxCopilot/Services/LlmService.ToolUse.cs)는 최근 비-system 메시지 8개만 구조화된 tool history로 유지하고, 그 이전의 `_tool_use_blocks`와 `tool_result`는 plain assistant/user transcript로 변환해 재전송합니다. - 이로써 strict provider에서 오래된 `tool_calls/tool` 이력이 계속 누적되던 부담과 pairing 위험을 함께 줄였습니다. +- 업데이트: 2026-04-12 23:05 (KST) + - `claw-code`와 비교했을 때 여전히 무겁던 Cowork 문서 생성 게이트와 Code 후속 검증 게이트를 한 단계 더 줄였습니다. + - [AgentLoopService.cs](/E:/AX%20Copilot%20-%20Codex/src/AxCopilot/Services/Agent/AgentLoopService.cs) 는 `document_plan` 뒤의 강제 재시도/자동 HTML fallback을 공격적인 실행 프로파일에서만 동작하도록 제한했습니다. + - [AgentLoopTransitions.Documents.cs](/E:/AX%20Copilot%20-%20Codex/src/AxCopilot/Services/Agent/AgentLoopTransitions.Documents.cs) 는 `document_plan` 성공 직후 추가 user 압박 메시지를 넣지 않고, terminal 문서 도구 성공 시 Cowork에서 바로 종료할 수 있게 정리했습니다. + - [AgentLoopTransitions.Verification.cs](/E:/AX%20Copilot%20-%20Codex/src/AxCopilot/Services/Agent/AgentLoopTransitions.Verification.cs) 는 `CodeDiffGate`, `RecentExecutionGate`, `ExecutionSuccessGate`를 review 작업 중심으로 제한해 일반 코드 수정의 과검증을 줄였습니다. + - [TaskTypePolicy.cs](/E:/AX%20Copilot%20-%20Codex/src/AxCopilot/Services/Agent/TaskTypePolicy.cs), [ChatWindow.SystemPromptBuilder.cs](/E:/AX%20Copilot%20-%20Codex/src/AxCopilot/Views/ChatWindow.SystemPromptBuilder.cs), [cowork_문서작성.json](/E:/AX%20Copilot%20-%20Codex/src/AxCopilot/Assets/Presets/cowork_%EB%AC%B8%EC%84%9C%EC%9E%91%EC%84%B1.json), [cowork_보고서.json](/E:/AX%20Copilot%20-%20Codex/src/AxCopilot/Assets/Presets/cowork_%EB%B3%B4%EA%B3%A0%EC%84%9C.json) 도 같은 기준으로 문서 생성/텍스트 종료 조건을 더 얇게 맞췄습니다. diff --git a/docs/DEVELOPMENT.md b/docs/DEVELOPMENT.md index b9767ee..c3e8fc0 100644 --- a/docs/DEVELOPMENT.md +++ b/docs/DEVELOPMENT.md @@ -679,3 +679,30 @@ owKindCounts를 함께 남겨 %APPDATA%\\AxCopilot\\perf 기준으로 transcript - OpenAI/vLLM 호환 서버에 오래된 구조화 tool history를 계속 실어 보내던 부담이 줄어듭니다. - strict tool sequence 검사에 걸릴 가능성을 낮추면서도 최근 실행 흐름은 그대로 유지할 수 있습니다. +## Cowork 문서 생성 게이트 / Code 검증 게이트 경량화 (2026-04-12 23:05 KST) + +- `claw-code`와 비교했을 때 AX는 `document_plan` 후속 재시도와 Code 후속 증거 게이트가 여전히 더 무거웠습니다. +- `src/AxCopilot/Services/Agent/ModelExecutionProfileCatalog.cs` + - `balanced` 프로필의 `ForceToolCallAfterPlan`을 끄고 `DocumentPlanRetryMax`를 0으로 낮췄습니다. + - `tool_call_strict`도 `DocumentPlanRetryMax`를 0으로 낮추고 `PreferAggressiveDocumentFallback`을 꺼, 강제 문서 fallback이 기본 경로로 개입하지 않게 했습니다. +- `src/AxCopilot/Services/Agent/AgentLoopService.cs` + - `document_plan` 후 `html_create` 미호출 재시도와 자동 HTML 저장 fallback은 공격적 문서 fallback 프로필에서만 실행되도록 제한했습니다. + - 따라서 일반 Cowork 문서 생성은 `claw-code`처럼 모델의 정상적인 다음 선택을 더 많이 허용합니다. +- `src/AxCopilot/Services/Agent/AgentLoopTransitions.Documents.cs` + - `document_plan` 성공 직후 강제로 다음 도구 호출을 재촉하는 user 메시지를 제거했습니다. + - terminal 문서 도구가 성공하면 Cowork에서는 추가 반복 없이 바로 완료할 수 있게 정리했습니다. +- `src/AxCopilot/Services/Agent/AgentLoopTransitions.Verification.cs` + - `CodeDiffGate`, `RecentExecutionGate`, `ExecutionSuccessGate`를 review 작업 중심으로 제한해, 일반 bugfix/feature/refactor 작업에서는 과한 후속 검증 턴을 줄였습니다. +- `src/AxCopilot/Services/Agent/TaskTypePolicy.cs` + - docs 작업은 산출물이 분명한 경우 파일 생성을 우선하되, 분석/자문 성격 요청에는 텍스트 마무리도 허용하도록 정책 문구를 조정했습니다. +- `src/AxCopilot/Views/ChatWindow.SystemPromptBuilder.cs` + - `document_plan`은 멀티 섹션 구조화가 실제로 도움이 될 때만 쓰도록 톤을 낮췄습니다. + - Code 최종 보고도 review/high-impact가 아닐 때는 남은 리스크를 과하게 언급하지 않도록 정리했습니다. +- `src/AxCopilot/Assets/Presets/cowork_문서작성.json` +- `src/AxCopilot/Assets/Presets/cowork_보고서.json` + - Cowork preset에서 “무조건 파일 생성” 압력을 낮추고, 새 문서/새 보고서 요청은 생성 도구 우선, 기존 자료 참조 요청은 탐색 우선, 분석형 요청은 텍스트 종료 허용으로 기준을 분리했습니다. +- 기대 효과 + - Cowork는 문서 생성 요청에서 불필요한 재시도와 앱 강제 fallback이 줄어듭니다. + - Code는 일반 수정 작업에서 review 수준의 무거운 follow-up gate가 덜 개입합니다. + - 프롬프트, preset, runtime policy가 같은 방향으로 정렬되어 `claw-code`와 더 비슷한 얇은 루프를 유지합니다. + diff --git a/src/AxCopilot/Assets/Presets/cowork_문서작성.json b/src/AxCopilot/Assets/Presets/cowork_문서작성.json index be5a2f4..8169d58 100644 --- a/src/AxCopilot/Assets/Presets/cowork_문서작성.json +++ b/src/AxCopilot/Assets/Presets/cowork_문서작성.json @@ -1,4 +1,4 @@ -{ +{ "category": "문서", "tab": "Cowork", "order": 60, @@ -6,6 +6,6 @@ "symbol": "\uE8A5", "color": "#F59E0B", "description": "Word, Markdown, HTML 문서를 작성합니다", - "systemPrompt": "당신은 AX Copilot Agent입니다. 사용자가 요청한 문서를 작성합니다.\n\n## 핵심 원칙\n- 문서 내용을 **상세하고 완결성 있게** 작성합니다.\n- 목차, 소제목, 번호 매기기를 활용하여 구조화합니다.\n- 전문 용어에는 간단한 설명을 병기합니다.\n- 결과물은 Word(.docx), Markdown(.md), HTML(.html) 중 적합한 형식을 선택합니다.\n- 필요할 때만 계획을 드러내고, 도구를 사용하여 실제 파일을 생성합니다.\n- 파일 탐색은 glob/grep과 document_read/file_read를 우선하고, folder_map은 폴더 구조 확인이 필요할 때만 사용합니다.\n\n## 문서 품질 가이드\n\n### HTML 문서 (html_create)\n- **toc: true** 로 목차 자동 생성. **numbered: true** 로 섹션 번호 자동 부여.\n- **cover** 파라미터로 커버 페이지 추가: {\"title\": \"...\", \"subtitle\": \"...\", \"author\": \"...\"}.\n- 콜아웃:
핵심 내용
(info/warning/tip/danger/note).\n- 배지: 완료.\n- 타임라인:
...
.\n- mood 추천: professional(공식), elegant(격식), minimal(학술), magazine(뉴스레터).\n\n### Word 문서 (docx_create)\n- **header** 파라미터로 머리글 추가. **footer** 에 {page}로 페이지 번호 삽입.\n- sections에서 type: \"table\" 로 스타일 테이블 (파란 헤더, 줄무늬).\n- type: \"pagebreak\" 로 섹션 간 페이지 구분.\n- type: \"list\" 로 번호/불릿 목록: {\"type\": \"list\", \"style\": \"number\", \"items\": [...]}.\n- 본문에 **볼드**, *이탤릭*, `코드` 인라인 서식 지원.\n- level: 1(대제목) / 2(소제목) 로 제목 크기 구분.\n\n## 사용 가능한 도구\n- docx_create: Word 문서 생성 (테이블, 서식, 머리글/바닥글, 페이지 나누기 지원)\n- markdown_create: Markdown 문서 생성\n- html_create: HTML 문서 생성 (목차, 커버, 콜아웃, 차트, 배지 지원)\n- document_read: 기존 문서(PDF, DOCX) 읽기\n- folder_map: 작업 폴더 구조 탐색\n- file_read: 텍스트 파일 읽기\n- file_write: 파일 생성\n- glob/grep: 파일 및 내용 검색\n- document_plan: 문서 개요 구조화 (멀티패스 생성)\n- document_assemble: 섹션별 내용을 하나의 문서로 조립\n- document_review: 생성된 문서 품질 검증\n- pptx_create: PowerPoint 프레젠테이션 생성\n- template_render: 템플릿 기반 문서 렌더링\n- text_summarize: 긴 텍스트 요약\n\n## 중요: 반드시 도구를 사용하여 파일을 생성하세요\n\n문서 요청을 받으면 텍스트로만 답변하지 마세요. 반드시 html_create, docx_create 등 도구를 호출하여 실제 파일을 생성해야 합니다.\n\n### 기본 전략 (빠른 생성)\n- html_create 또는 docx_create를 직접 호출하여 완성된 문서를 한 번에 생성합니다.\n- 문서 내용을 모두 포함하여 도구를 호출하세요. 개요만 텍스트로 작성하고 끝내지 마세요.\n\n### 멀티패스 전략 (고품질 설정 ON 시, 3페이지 이상)\n1단계 — 필요할 때만 document_plan으로 문서 구조를 설계합니다.\n2단계 — 각 섹션을 개별적으로 상세하게 작성합니다.\n3단계 — document_assemble으로 하나의 문서로 결합합니다.", + "systemPrompt": "당신은 AX Copilot Agent입니다. 사용자가 요청한 문서를 작성합니다.\n\n## 핵심 원칙\n- 문서 내용을 **상세하고 완결성 있게** 작성합니다.\n- 목차, 소제목, 번호 매기기를 활용하여 구조화합니다.\n- 전문 용어에는 간단한 설명을 병기합니다.\n- 결과물은 Word(.docx), Markdown(.md), HTML(.html) 중 적합한 형식을 선택합니다.\n- 필요할 때만 계획을 드러내고, 도구를 사용하여 실제 파일을 생성합니다.\n- 파일 탐색은 glob/grep과 document_read/file_read를 우선하고, folder_map은 폴더 구조 확인이 필요할 때만 사용합니다.\n- 새 문서를 바로 작성하는 요청이면 탐색보다 생성 도구를 우선합니다.\n\n## 문서 품질 가이드\n\n### HTML 문서 (html_create)\n- **toc: true** 로 목차 자동 생성. **numbered: true** 로 섹션 번호 자동 부여.\n- **cover** 파라미터로 커버 페이지 추가: {\"title\": \"...\", \"subtitle\": \"...\", \"author\": \"...\"}.\n- 콜아웃:
핵심 내용
(info/warning/tip/danger/note).\n- 배지: 완료.\n- 타임라인:
...
.\n- mood 추천: professional(공식), elegant(격식), minimal(학술), magazine(뉴스레터).\n\n### Word 문서 (docx_create)\n- **header** 파라미터로 머리글 추가. **footer** 에 {page}로 페이지 번호 삽입.\n- sections에서 type: \"table\" 로 스타일 테이블 (파란 헤더, 줄무늬).\n- type: \"pagebreak\" 로 섹션 간 페이지 구분.\n- type: \"list\" 로 번호/불릿 목록: {\"type\": \"list\", \"style\": \"number\", \"items\": [...]}.\n- 본문에 **볼드**, *이탤릭*, `코드` 인라인 서식 지원.\n- level: 1(대제목) / 2(소제목) 로 제목 크기 구분.\n\n## 사용 가능한 도구\n- docx_create: Word 문서 생성 (테이블, 서식, 머리글/바닥글, 페이지 나누기 지원)\n- markdown_create: Markdown 문서 생성\n- html_create: HTML 문서 생성 (목차, 커버, 콜아웃, 차트, 배지 지원)\n- document_read: 기존 문서(PDF, DOCX) 읽기\n- folder_map: 작업 폴더 구조 탐색\n- file_read: 텍스트 파일 읽기\n- file_write: 파일 생성\n- glob/grep: 파일 및 내용 검색\n- document_plan: 문서 개요 구조화 (멀티패스 생성)\n- document_assemble: 섹션별 내용을 하나의 문서로 조립\n- document_review: 생성된 문서 품질 검증\n- pptx_create: PowerPoint 프레젠테이션 생성\n- template_render: 템플릿 기반 문서 렌더링\n- text_summarize: 긴 텍스트 요약\n\n## 기본 전략\n- 새 문서를 작성하는 요청이면 html_create 또는 docx_create를 직접 호출하여 완성된 문서를 한 번에 생성합니다.\n- 기존 자료를 참고하라는 요청일 때만 glob/grep/document_read/file_read를 먼저 사용합니다.\n- 분석이나 조언이 목적이고 파일 생성이 핵심이 아니라면 텍스트 응답으로 마무리할 수 있습니다.\n\n### 멀티패스 전략 (고품질 설정 ON 시, 3페이지 이상)\n1단계 — 필요할 때만 document_plan으로 문서 구조를 설계합니다.\n2단계 — 각 섹션을 개별적으로 상세하게 작성합니다.\n3단계 — document_assemble으로 하나의 문서로 결합합니다.", "placeholder": "어떤 문서를 작성할까요? (예: 프로젝트 기획서 작성)" } diff --git a/src/AxCopilot/Assets/Presets/cowork_보고서.json b/src/AxCopilot/Assets/Presets/cowork_보고서.json index 0f20f94..e9d2e77 100644 --- a/src/AxCopilot/Assets/Presets/cowork_보고서.json +++ b/src/AxCopilot/Assets/Presets/cowork_보고서.json @@ -1,4 +1,4 @@ -{ +{ "category": "보고서", "tab": "Cowork", "order": 10, @@ -6,6 +6,6 @@ "symbol": "\uE9F9", "color": "#3B82F6", "description": "Excel, Word, HTML 보고서를 상세하게 작성합니다", - "systemPrompt": "당신은 AX Copilot Agent입니다. 사용자가 요청한 보고서를 작성합니다.\n\n## 핵심 원칙\n- 데이터를 **상세하고 구체적으로** 작성합니다. 항목을 생략하지 않습니다.\n- 표(테이블)는 가능한 많은 행과 열을 포함합니다.\n- 수치 데이터는 단위를 명확히 표기합니다.\n- 결과물은 Excel(.xlsx), Word(.docx), HTML(.html) 중 가장 적합한 형식을 선택합니다.\n- 필요할 때만 계획을 드러내고, 도구를 사용하여 실제 파일을 생성합니다.\n- 파일 탐색은 glob/grep과 document_read/file_read를 우선하고, folder_map은 폴더 구조 확인이 필요할 때만 사용합니다.\n\n## 문서 품질 가이드\n\n### HTML 보고서 (html_create)\n- **toc: true** 로 목차를 자동 생성하세요.\n- **numbered: true** 로 섹션 번호(1., 1-1.)를 자동 부여하세요.\n- **cover** 파라미터로 커버 페이지를 추가하세요: {\"title\": \"...\", \"subtitle\": \"...\", \"author\": \"...\"}.\n- 콜아웃을 활용하세요:
중요 정보
(info/warning/tip/danger/note).\n- 배지를 활용하세요: 완료 (blue/green/red/yellow/purple/gray/orange).\n- CSS 바 차트:
항목
75%
.\n- 그리드 레이아웃:
또는 grid-3, grid-4로 카드 배치.\n- mood 파라미터: professional(비즈니스), dashboard(KPI), corporate(공식), magazine(매거진) 등 선택.\n\n### Excel (excel_create)\n- 기본 style: 'styled' — 파란 헤더, 줄무늬, 테두리 자동 적용.\n- **freeze_header: true** 로 헤더 행 틀 고정.\n- **summary_row** 로 합계/평균 행 자동 생성: {\"label\": \"합계\", \"columns\": {\"B\": \"SUM\", \"C\": \"AVERAGE\"}}.\n- 수식은 셀 값에 '=SUM(B2:B10)' 형태로 입력.\n- **col_widths** 로 열 너비 지정: [20, 15, 12].\n\n### Word (docx_create)\n- **header/footer** 파라미터로 머리글/바닥글 추가. {page}로 페이지 번호.\n- sections에서 type: \"table\" 로 스타일 테이블 삽입 (파란 헤더, 줄무늬).\n- type: \"pagebreak\" 로 페이지 나누기.\n- type: \"list\" 로 번호/불릿 목록: {\"type\": \"list\", \"style\": \"number\", \"items\": [...]}.\n- 본문 텍스트에 **볼드**, *이탤릭*, `코드` 인라인 서식 사용 가능.\n\n## 사용 가능한 도구\n- excel_create: Excel 문서 생성 (서식, 수식, 틀 고정, 요약행 지원)\n- docx_create: Word 문서 생성 (테이블, 서식, 머리글/바닥글, 페이지 나누기 지원)\n- html_create: HTML 보고서 생성 (목차, 커버, 콜아웃, 차트, 배지 지원)\n- markdown_create: Markdown 문서 생성\n- csv_create: CSV 파일 생성\n- document_read: 기존 문서(PDF, DOCX, XLSX) 읽기\n- folder_map: 작업 폴더 구조 탐색\n- file_read: 텍스트 파일 읽기\n- file_write: 파일 생성\n- glob/grep: 파일 및 내용 검색\n- document_plan: 문서 개요 구조화 (멀티패스 생성 1단계)\n- document_assemble: 섹션별 내용을 하나의 문서로 조립 (멀티패스 생성 3단계)\n- document_review: 생성된 문서 품질 검증\n- pptx_create: PowerPoint 프레젠테이션 생성\n- data_pivot: CSV/JSON 데이터 집계/피벗\n- text_summarize: 긴 텍스트 요약\n\n## 중요: 반드시 도구를 사용하여 파일을 생성하세요\n\n보고서 요청을 받으면 텍스트로만 답변하지 마세요. 반드시 html_create, docx_create, excel_create 등 도구를 호출하여 실제 파일을 생성해야 합니다.\n\n### 기본 전략 (빠른 생성)\n- html_create 또는 docx_create를 직접 호출하여 완성된 보고서를 한 번에 생성합니다.\n- 보고서 내용을 모두 포함하여 도구를 호출하세요. 개요만 텍스트로 작성하고 끝내지 마세요.\n\n### 멀티패스 전략 (고품질 설정 ON 시, 3페이지 이상)\n1단계 — 필요할 때만 document_plan 도구로 문서 구조를 설계합니다.\n2단계 — 각 섹션을 개별적으로 상세하게 작성합니다.\n3단계 — document_assemble 도구로 하나의 문서로 결합합니다.", + "systemPrompt": "당신은 AX Copilot Agent입니다. 사용자가 요청한 보고서를 작성합니다.\n\n## 핵심 원칙\n- 데이터를 **상세하고 구체적으로** 작성합니다. 항목을 생략하지 않습니다.\n- 표(테이블)는 가능한 많은 행과 열을 포함합니다.\n- 수치 데이터는 단위를 명확히 표기합니다.\n- 결과물은 Excel(.xlsx), Word(.docx), HTML(.html) 중 가장 적합한 형식을 선택합니다.\n- 필요할 때만 계획을 드러내고, 도구를 사용하여 실제 파일을 생성합니다.\n- 파일 탐색은 glob/grep과 document_read/file_read를 우선하고, folder_map은 폴더 구조 확인이 필요할 때만 사용합니다.\n- 새 보고서를 바로 작성하는 요청이면 탐색보다 생성 도구를 우선합니다.\n\n## 문서 품질 가이드\n\n### HTML 보고서 (html_create)\n- **toc: true** 로 목차를 자동 생성하세요.\n- **numbered: true** 로 섹션 번호(1., 1-1.)를 자동 부여하세요.\n- **cover** 파라미터로 커버 페이지를 추가하세요: {\"title\": \"...\", \"subtitle\": \"...\", \"author\": \"...\"}.\n- 콜아웃을 활용하세요:
중요 정보
(info/warning/tip/danger/note).\n- 배지를 활용하세요: 완료 (blue/green/red/yellow/purple/gray/orange).\n- CSS 바 차트:
항목
75%
.\n- 그리드 레이아웃:
또는 grid-3, grid-4로 카드 배치.\n- mood 파라미터: professional(비즈니스), dashboard(KPI), corporate(공식), magazine(매거진) 등 선택.\n\n### Excel (excel_create)\n- 기본 style: 'styled' — 파란 헤더, 줄무늬, 테두리 자동 적용.\n- **freeze_header: true** 로 헤더 행 틀 고정.\n- **summary_row** 로 합계/평균 행 자동 생성: {\"label\": \"합계\", \"columns\": {\"B\": \"SUM\", \"C\": \"AVERAGE\"}}.\n- 수식은 셀 값에 '=SUM(B2:B10)' 형태로 입력.\n- **col_widths** 로 열 너비 지정: [20, 15, 12].\n\n### Word (docx_create)\n- **header/footer** 파라미터로 머리글/바닥글 추가. {page}로 페이지 번호.\n- sections에서 type: \"table\" 로 스타일 테이블 삽입 (파란 헤더, 줄무늬).\n- type: \"pagebreak\" 로 페이지 나누기.\n- type: \"list\" 로 번호/불릿 목록: {\"type\": \"list\", \"style\": \"number\", \"items\": [...]}.\n- 본문 텍스트에 **볼드**, *이탤릭*, `코드` 인라인 서식 사용 가능.\n\n## 사용 가능한 도구\n- excel_create: Excel 문서 생성 (서식, 수식, 틀 고정, 요약행 지원)\n- docx_create: Word 문서 생성 (테이블, 서식, 머리글/바닥글, 페이지 나누기 지원)\n- html_create: HTML 보고서 생성 (목차, 커버, 콜아웃, 차트, 배지 지원)\n- markdown_create: Markdown 문서 생성\n- csv_create: CSV 파일 생성\n- document_read: 기존 문서(PDF, DOCX, XLSX) 읽기\n- folder_map: 작업 폴더 구조 탐색\n- file_read: 텍스트 파일 읽기\n- file_write: 파일 생성\n- glob/grep: 파일 및 내용 검색\n- document_plan: 문서 개요 구조화 (멀티패스 생성 1단계)\n- document_assemble: 섹션별 내용을 하나의 문서로 조립 (멀티패스 생성 3단계)\n- document_review: 생성된 문서 품질 검증\n- pptx_create: PowerPoint 프레젠테이션 생성\n- data_pivot: CSV/JSON 데이터 집계/피벗\n- text_summarize: 긴 텍스트 요약\n\n## 기본 전략\n- 새 보고서를 작성하는 요청이면 html_create, docx_create, excel_create 중 적합한 도구로 완성된 결과를 바로 생성합니다.\n- 기존 자료를 참고하라는 요청일 때만 glob/grep/document_read/file_read를 먼저 사용합니다.\n- 분석이나 설명이 목적이고 파일 생성이 핵심이 아니라면 텍스트 응답으로 마무리할 수 있습니다.\n\n### 멀티패스 전략 (고품질 설정 ON 시, 3페이지 이상)\n1단계 — 필요할 때만 document_plan 도구로 문서 구조를 설계합니다.\n2단계 — 각 섹션을 개별적으로 상세하게 작성합니다.\n3단계 — document_assemble 도구로 하나의 문서로 결합합니다.", "placeholder": "어떤 보고서를 작성할까요? (예: 삼성디스플레이 연혁 보고서)" } diff --git a/src/AxCopilot/Services/Agent/AgentLoopService.cs b/src/AxCopilot/Services/Agent/AgentLoopService.cs index 6367c2b..241eec5 100644 --- a/src/AxCopilot/Services/Agent/AgentLoopService.cs +++ b/src/AxCopilot/Services/Agent/AgentLoopService.cs @@ -600,7 +600,10 @@ public partial class AgentLoopService } // ── 2단계: document_plan 직접 생성 폴백 ── - if (documentPlanCalled && !string.IsNullOrEmpty(documentPlanScaffold) && !_docFallbackAttempted) + if (executionPolicy.PreferAggressiveDocumentFallback + && documentPlanCalled + && !string.IsNullOrEmpty(documentPlanScaffold) + && !_docFallbackAttempted) { _docFallbackAttempted = true; EmitEvent(AgentEventType.Thinking, "", "앱에서 직접 문서를 생성합니다..."); @@ -870,6 +873,7 @@ public partial class AgentLoopService // document_plan은 호출됐지만 terminal 문서 도구(html_create 등)가 미호출인 경우 → 프로파일 기준 재시도 if (requiresConcreteArtifactOrEdit + && executionPolicy.DocumentPlanRetryMax > 0 && documentPlanCalled && postDocumentPlanRetry < documentPlanRetryMax) { postDocumentPlanRetry++; @@ -886,6 +890,7 @@ public partial class AgentLoopService // 재시도도 모두 소진 → 앱이 직접 본문 생성 후 html_create 강제 실행 if (requiresConcreteArtifactOrEdit + && executionPolicy.PreferAggressiveDocumentFallback && documentPlanCalled && !string.IsNullOrEmpty(documentPlanScaffold) && !_docFallbackAttempted) { _docFallbackAttempted = true; @@ -949,7 +954,8 @@ public partial class AgentLoopService // LLM이 도구를 한 번도 호출하지 않고 텍스트만 반환 + 문서 생성 요청이면 → 앱이 직접 HTML 파일로 저장 // 주의: 이미 도구가 실행된 경우(totalToolCalls > 0)에는 폴백하지 않음 (중복 파일 방지) - if (!_docFallbackAttempted && totalToolCalls == 0 + if (executionPolicy.PreferAggressiveDocumentFallback + && !_docFallbackAttempted && totalToolCalls == 0 && !string.IsNullOrEmpty(textResponse) && IsDocumentCreationRequest(userQuery)) { @@ -986,6 +992,7 @@ public partial class AgentLoopService if (TryApplyCodeDiffEvidenceGateTransition( messages, textResponse, + taskPolicy, runState, executionPolicy)) continue; diff --git a/src/AxCopilot/Services/Agent/AgentLoopTransitions.Documents.cs b/src/AxCopilot/Services/Agent/AgentLoopTransitions.Documents.cs index 3756663..b174a4f 100644 --- a/src/AxCopilot/Services/Agent/AgentLoopTransitions.Documents.cs +++ b/src/AxCopilot/Services/Agent/AgentLoopTransitions.Documents.cs @@ -28,16 +28,7 @@ public partial class AgentLoopService return; var toolHint = ResolveDocumentPlanFollowUpTool(po); - messages.Add(new ChatMessage - { - Role = "user", - Content = - "document_plan이 완료되었습니다. " + - "방금 생성된 골격의 [내용...] 자리와 각 섹션 내용을 실제 상세 본문으로 모두 채운 뒤 " + - $"{toolHint} 도구를 지금 즉시 호출하세요. " + - "설명만 하지 말고 실제 문서 생성 도구 호출로 바로 이어가세요." - }); - EmitEvent(AgentEventType.Thinking, "", $"문서 개요 완료 · {toolHint} 실행 유도"); + EmitEvent(AgentEventType.Thinking, "", $"Document structure ready · next creation candidate {toolHint}"); } private static string? ExtractDocumentPlanScaffold(string output) @@ -47,7 +38,6 @@ public partial class AgentLoopService var markers = new (string Start, string End)[] { - ("--- body 시작 ---", "--- body 끝 ---"), ("--- body start ---", "--- body end ---"), ("", ""), }; @@ -76,10 +66,10 @@ public partial class AgentLoopService if (string.IsNullOrWhiteSpace(output)) return false; - return output.Contains("즉시 실행", StringComparison.OrdinalIgnoreCase) - || output.Contains("immediate next step", StringComparison.OrdinalIgnoreCase) + return output.Contains("immediate next step", StringComparison.OrdinalIgnoreCase) || output.Contains("call html_create", StringComparison.OrdinalIgnoreCase) - || output.Contains("call document_assemble", StringComparison.OrdinalIgnoreCase); + || output.Contains("call document_assemble", StringComparison.OrdinalIgnoreCase) + || output.Contains("call docx_create", StringComparison.OrdinalIgnoreCase); } private static string ResolveDocumentPlanFollowUpTool(string output) @@ -109,11 +99,6 @@ public partial class AgentLoopService if (!result.Success || !IsTerminalDocumentTool(call.ToolName) || toolCalls.Count != 1) return (false, false); - // document_plan 없이 바로 문서 도구가 호출된 경우 — 아직 LLM이 추가 반복을 할 수 있음. - // 한 번에 생성된 문서는 내용이 부실할 수 있으므로 조기 종료하지 않고 LLM에 판단을 맡긴다. - if (!_docFallbackAttempted && !documentPlanWasCalled) - return (false, false); - if (!string.Equals(ActiveTab, "Code", StringComparison.OrdinalIgnoreCase)) { EmitEvent(AgentEventType.Complete, "", "에이전트 작업 완료"); @@ -165,15 +150,12 @@ public partial class AgentLoopService if (!string.Equals(ActiveTab, "Code", StringComparison.OrdinalIgnoreCase)) return false; - if (string.Equals(ActiveTab, "Code", StringComparison.OrdinalIgnoreCase)) - { - var highImpactCodeChange = IsHighImpactCodeModification(ActiveTab ?? "", call.ToolName, result); - var hasDiffEvidence = HasDiffEvidenceAfterLastModification(messages); - var hasRecentBuildOrTestEvidence = HasBuildOrTestEvidenceAfterLastModification(messages); + var highImpactCodeChange = IsHighImpactCodeModification(ActiveTab ?? "", call.ToolName, result); + var hasDiffEvidence = HasDiffEvidenceAfterLastModification(messages); + var hasRecentBuildOrTestEvidence = HasBuildOrTestEvidenceAfterLastModification(messages); - if (!highImpactCodeChange || (hasDiffEvidence && hasRecentBuildOrTestEvidence)) - return false; - } + if (!highImpactCodeChange || (hasDiffEvidence && hasRecentBuildOrTestEvidence)) + return false; await RunPostToolVerificationAsync(messages, call.ToolName, result, context, ct); return true; diff --git a/src/AxCopilot/Services/Agent/AgentLoopTransitions.Verification.cs b/src/AxCopilot/Services/Agent/AgentLoopTransitions.Verification.cs index 38cadbc..4a79602 100644 --- a/src/AxCopilot/Services/Agent/AgentLoopTransitions.Verification.cs +++ b/src/AxCopilot/Services/Agent/AgentLoopTransitions.Verification.cs @@ -123,12 +123,16 @@ public partial class AgentLoopService private bool TryApplyCodeDiffEvidenceGateTransition( List messages, string? textResponse, + TaskTypePolicy taskPolicy, RunState runState, ModelExecutionProfileCatalog.ExecutionPolicy executionPolicy) { if (!string.Equals(ActiveTab, "Code", StringComparison.OrdinalIgnoreCase)) return false; + if (!taskPolicy.IsReviewTask) + return false; + if (executionPolicy.CodeDiffGateMaxRetries <= 0 || runState.CodeDiffGateRetry >= executionPolicy.CodeDiffGateMaxRetries) return false; @@ -157,6 +161,9 @@ public partial class AgentLoopService if (!string.Equals(ActiveTab, "Code", StringComparison.OrdinalIgnoreCase)) return false; + if (!taskPolicy.IsReviewTask) + return false; + if (executionPolicy.RecentExecutionGateMaxRetries <= 0 || runState.RecentExecutionGateRetry >= executionPolicy.RecentExecutionGateMaxRetries) return false; @@ -191,6 +198,9 @@ public partial class AgentLoopService if (!string.Equals(ActiveTab, "Code", StringComparison.OrdinalIgnoreCase)) return false; + if (!taskPolicy.IsReviewTask) + return false; + if (executionPolicy.ExecutionSuccessGateMaxRetries <= 0 || runState.ExecutionSuccessGateRetry >= executionPolicy.ExecutionSuccessGateMaxRetries) return false; diff --git a/src/AxCopilot/Services/Agent/ModelExecutionProfileCatalog.cs b/src/AxCopilot/Services/Agent/ModelExecutionProfileCatalog.cs index afefc0a..21ef62d 100644 --- a/src/AxCopilot/Services/Agent/ModelExecutionProfileCatalog.cs +++ b/src/AxCopilot/Services/Agent/ModelExecutionProfileCatalog.cs @@ -58,8 +58,8 @@ public static class ModelExecutionProfileCatalog NoToolResponseThreshold: 1, NoToolRecoveryMaxRetries: 4, // IBM/Qwen 등 chatty 모델: 재시도 횟수 늘려 도구 호출 강제 PlanExecutionRetryMax: 2, - DocumentPlanRetryMax: 2, - PreferAggressiveDocumentFallback: true, + DocumentPlanRetryMax: 0, + PreferAggressiveDocumentFallback: false, ReduceEarlyMemoryPressure: true, EnablePostToolVerification: false, EnableCodeQualityGates: true, @@ -154,12 +154,12 @@ public static class ModelExecutionProfileCatalog "balanced", "균형", ForceInitialToolCall: true, - ForceToolCallAfterPlan: true, + ForceToolCallAfterPlan: false, ToolTemperatureCap: 0.35, NoToolResponseThreshold: 2, NoToolRecoveryMaxRetries: 2, PlanExecutionRetryMax: 2, - DocumentPlanRetryMax: 2, + DocumentPlanRetryMax: 0, PreferAggressiveDocumentFallback: false, ReduceEarlyMemoryPressure: false, EnablePostToolVerification: false, diff --git a/src/AxCopilot/Services/Agent/TaskTypePolicy.cs b/src/AxCopilot/Services/Agent/TaskTypePolicy.cs index c54fdd9..5a898f3 100644 --- a/src/AxCopilot/Services/Agent/TaskTypePolicy.cs +++ b/src/AxCopilot/Services/Agent/TaskTypePolicy.cs @@ -23,10 +23,10 @@ internal sealed class TaskTypePolicy GuidanceMessage = "[System:TaskType] This is a bug-fix task. Prioritize reproduction evidence, root cause linkage, smallest safe fix, and regression verification. " + "Preferred tool order: targeted file_read or grep/glob/lsp -> file_edit -> build_run/test_loop as needed -> git_tool(diff) when it helps confirm the final change.", - FailurePatternFocus = "재현 조건과 원인 연결을 먼저 확인하세요. Check reproduction conditions and root-cause linkage first.", - FollowUpTaskLine = "작업 유형: bugfix. Task type: bugfix. Verify the fix is directly linked to the symptom and confirm non-regression.\n", - FailureInvestigationTaskLine = "추가 점검: 재현 조건 기준으로 증상이 재현되지 않는지와 원인 연결이 타당한지 확인하세요. Extra check: confirm the symptom is no longer reproducible and root-cause linkage is valid.\n", - FinalReportTaskLine = "버그 수정은 원인, 수정 내용, 재현/회귀 검증 근거를 포함하세요. For bug fixes, include root cause, change summary, and reproduction/regression evidence.\n", + FailurePatternFocus = "Check reproduction conditions and root-cause linkage first.", + FollowUpTaskLine = "Task type: bugfix. Verify the fix is directly linked to the symptom and confirm non-regression.\n", + FailureInvestigationTaskLine = "Extra check: confirm the symptom is no longer reproducible and root-cause linkage is valid.\n", + FinalReportTaskLine = "For bug fixes, include root cause, change summary, and reproduction/regression evidence.\n", }, "feature" => new TaskTypePolicy { @@ -36,8 +36,8 @@ internal sealed class TaskTypePolicy "Preferred tool order: targeted file_read or grep/glob/lsp -> file_edit/file_write -> build_run/test_loop as needed -> git_tool(diff). " + "Use folder_map only when the user explicitly needs folder structure or file listing.", FailurePatternFocus = "Check new behavior flow and caller linkage first.", - FollowUpTaskLine = "작업 유형: feature. Task type: feature. Verify behavior flow, input/output path, caller impact, and test additions.\n", - FailureInvestigationTaskLine = "추가 점검: 새 기능 경로와 호출부 연결이 의도대로 동작하는지 확인하세요. Extra check: confirm feature path and caller linkage behave as intended.\n", + FollowUpTaskLine = "Task type: feature. Verify behavior flow, input/output path, caller impact, and test additions.\n", + FailureInvestigationTaskLine = "Extra check: confirm feature path and caller linkage behave as intended.\n", FinalReportTaskLine = "For features, include behavior flow, impacted files/callers, and verification evidence.\n", }, "refactor" => new TaskTypePolicy @@ -47,8 +47,8 @@ internal sealed class TaskTypePolicy "[System:TaskType] This is a refactor task. Prioritize behavior preservation, reference impact, diff review, and non-regression evidence. " + "Preferred tool order: targeted file_read or grep/glob/lsp -> file_edit -> build_run/test_loop as needed -> git_tool(diff).", FailurePatternFocus = "Check behavior preservation and impact scope first.", - FollowUpTaskLine = "작업 유형: refactor. Task type: refactor. Prioritize behavior-preservation evidence over cosmetic cleanup.\n", - FailureInvestigationTaskLine = "추가 점검: 동작 보존 관점에서 기존 호출 흐름이 동일하게 유지되는지 확인하세요. Extra check: validate existing call flow remains behavior-compatible.\n", + FollowUpTaskLine = "Task type: refactor. Prioritize behavior-preservation evidence over cosmetic cleanup.\n", + FailureInvestigationTaskLine = "Extra check: validate existing call flow remains behavior-compatible.\n", FinalReportTaskLine = "For refactors, include behavior-preservation evidence and impact scope.\n", }, "review" => new TaskTypePolicy @@ -59,8 +59,8 @@ internal sealed class TaskTypePolicy "Report findings with P0-P3 severity and file evidence, then separate Fixed vs Unfixed status. " + "Preferred tool order: targeted file_read or grep/glob/lsp -> git_tool(diff) when available -> evidence-first findings.", FailurePatternFocus = "Review focus: severity accuracy (P0-P3), file-grounded evidence, and unresolved-risk clarity.", - FollowUpTaskLine = "작업 유형: review-follow-up. Task type: review-follow-up. For each finding, state status as Fixed or Unfixed with verification evidence.\n", - FailureInvestigationTaskLine = "추가 점검: 리뷰에서 지적된 위험은 반드시 수정 근거나 미해결 사유/영향을 남기세요. Extra check: every risk must have either a concrete fix or an explicit unresolved rationale and impact.\n", + FollowUpTaskLine = "Task type: review-follow-up. For each finding, state status as Fixed or Unfixed with verification evidence.\n", + FailureInvestigationTaskLine = "Extra check: every risk must have either a concrete fix or an explicit unresolved rationale and impact.\n", FinalReportTaskLine = "For review, list P0-P3 findings with file evidence and split into Fixed vs Unfixed with residual risk.\n", IsReviewTask = true }, @@ -69,10 +69,10 @@ internal sealed class TaskTypePolicy TaskType = "docs", GuidanceMessage = "[System:TaskType] This is a document/content task. " + - "If the user asks you to CREATE/WRITE a new document, skip file exploration entirely — " + - "go directly to the creation tool (docx_create, html_create, excel_create, etc.) and use document_plan only when it materially helps structure a multi-section document. " + - "to produce a REAL FILE on disk. Do NOT respond with text only — the output MUST be a file. " + - "If the user asks you to READ/ANALYZE existing documents, use: glob/grep -> document_read/file_read -> analysis. " + + "If the user asks you to create or write a new document, skip file exploration entirely and go directly to the creation tool (docx_create, html_create, excel_create, etc.). " + + "Use document_plan only when it materially helps structure a multi-section document. " + + "Prefer producing a real file on disk when the request is clearly for a deliverable, but do not force file creation for analysis-only or advisory requests. " + + "If the user asks you to read or analyze existing documents, use: glob/grep -> document_read/file_read -> analysis. " + "Use folder_map only when the user explicitly asks for folder contents or directory structure.", FailurePatternFocus = "Check source evidence and document completeness first.", FollowUpTaskLine = "", diff --git a/src/AxCopilot/Views/ChatWindow.SystemPromptBuilder.cs b/src/AxCopilot/Views/ChatWindow.SystemPromptBuilder.cs index ed23d72..1199542 100644 --- a/src/AxCopilot/Views/ChatWindow.SystemPromptBuilder.cs +++ b/src/AxCopilot/Views/ChatWindow.SystemPromptBuilder.cs @@ -64,7 +64,7 @@ public partial class ChatWindow sb.AppendLine("\nWhen the user explicitly asks for a plan (계획, 계획 수립, 계획 먼저, plan), present a step-by-step plan FIRST and wait for approval before executing."); sb.AppendLine("For ordinary Cowork requests where no plan is requested, proceed directly with the work and focus on producing the requested result."); sb.AppendLine("If the user asks for a brand-new report, proposal, analysis, manual, or other document and does not explicitly ask to reference workspace files, do NOT start with glob, grep, document_read, or folder_map."); - sb.AppendLine("In that case, go straight to the creation tool. Use document_plan when creating multi-section documents (3+ pages) or when the user explicitly requests a plan."); + sb.AppendLine("In that case, go straight to the creation tool. Use document_plan only when multi-section structure work clearly improves the result or when the user explicitly requests a plan."); sb.AppendLine("After creating files, summarize what was created and include the actual output path."); sb.AppendLine("IMPORTANT: In your FINAL response after ALL work is done, provide a structured completion summary in this format:"); sb.AppendLine(" - 작업 유형: (e.g., report/analysis/proposal)"); @@ -78,7 +78,7 @@ public partial class ChatWindow sb.AppendLine("IMPORTANT: When creating documents with dates, always use today's actual date above. Never use placeholder or fictional dates."); sb.AppendLine("IMPORTANT: For reports, proposals, analyses, and manuals with multiple sections:"); sb.AppendLine(" 1. Decide the document structure internally first."); - sb.AppendLine(" 2. Use document_plan for multi-section documents or when the user explicitly asks for a plan. When the user requests a plan, present it for approval before proceeding."); + sb.AppendLine(" 2. Use document_plan only when multi-section structure work clearly improves the result or when the user explicitly asks for a plan. When the user requests a plan, present it for approval before proceeding."); sb.AppendLine(" 3. Then immediately create the real output file with html_create, docx_create, markdown_create, or file_write."); sb.AppendLine(" 4. Fill every section with real content. Do not stop at an outline or plan only."); sb.AppendLine(" 5. The task is complete only after the actual document file has been created or updated."); @@ -250,7 +250,7 @@ public partial class ChatWindow sb.AppendLine("3. IMPLEMENT: Apply the smallest safe edit. Use file_edit for existing files and file_write for new files."); sb.AppendLine("4. VERIFY: Run build_run/test_loop when the change affects buildable or testable behavior, or when the user explicitly asks for verification."); sb.AppendLine(" - Use git_tool(diff) when it helps confirm the final change set or explain what changed."); - sb.AppendLine("5. REPORT: Summarize what changed and what was verified. Mention remaining risk only when something is actually unresolved."); + sb.AppendLine("5. REPORT: Summarize what changed and what was verified. Mention remaining risk only when something is actually unresolved, especially for review or high-impact changes."); sb.AppendLine("\n## Development Environment"); sb.AppendLine("Use dev_env_detect to check installed IDEs, runtimes, and build tools before running commands.");