feat: Pipeline 전면 개선 — 병렬실행, Batch Review, 총평, 대화기억, 스마트라우팅
- GeminiCaller: cmd/c 제거, 인자 분리, Semaphore(4) 동시성 제어, GeminiCallError - TaskPipeline: asyncio.gather 병렬 코딩, batch_review 1회, summarize 총평 - FileApplier: Coder 출력 파싱 → 실제 파일 적용 (경로 보안 체크) - Discord Bot: on_message 자동채팅, 의도분류(chat/task/clarify), 대화기억(10메시지) - Prompts: router.md (의도분류), summarizer.md (총평) - Workflows: agent_chat 환경 경로 업데이트
This commit is contained in:
117
core/file_applier.py
Normal file
117
core/file_applier.py
Normal file
@@ -0,0 +1,117 @@
|
||||
"""File Applier — Coder 출력을 실제 파일에 적용.
|
||||
|
||||
Coder가 출력한 `=== FILE: path === ... === END FILE ===` 블록을
|
||||
파싱하여 프로젝트 파일에 실제로 쓰기.
|
||||
"""
|
||||
|
||||
import re
|
||||
import logging
|
||||
from pathlib import Path
|
||||
from dataclasses import dataclass
|
||||
|
||||
logger = logging.getLogger("variet.applier")
|
||||
|
||||
|
||||
@dataclass
|
||||
class FileChange:
|
||||
"""파일 변경 단위."""
|
||||
path: str # 상대 경로
|
||||
content: str # 전체 파일 내용
|
||||
is_new: bool # 신규 파일 여부
|
||||
|
||||
|
||||
def parse_code_output(raw: str) -> list[FileChange]:
|
||||
"""Coder 출력에서 파일 블록을 추출.
|
||||
|
||||
지원 형식:
|
||||
=== FILE: path/to/file.py ===
|
||||
(content)
|
||||
=== END FILE ===
|
||||
|
||||
또는 마크다운 방식:
|
||||
```python:path/to/file.py
|
||||
(content)
|
||||
```
|
||||
"""
|
||||
changes: list[FileChange] = []
|
||||
|
||||
# 패턴 1: === FILE: path === ... === END FILE ===
|
||||
pattern1 = re.compile(
|
||||
r'===\s*FILE:\s*(.+?)\s*===\s*\n(.*?)\n\s*===\s*END\s*FILE\s*===',
|
||||
re.DOTALL,
|
||||
)
|
||||
for match in pattern1.finditer(raw):
|
||||
path = match.group(1).strip()
|
||||
content = match.group(2)
|
||||
changes.append(FileChange(path=path, content=content, is_new=False))
|
||||
|
||||
# 패턴 2: ```lang:path/to/file.py\n...\n```
|
||||
if not changes:
|
||||
pattern2 = re.compile(
|
||||
r'```\w*:(.+?)\n(.*?)\n```',
|
||||
re.DOTALL,
|
||||
)
|
||||
for match in pattern2.finditer(raw):
|
||||
path = match.group(1).strip()
|
||||
content = match.group(2)
|
||||
changes.append(FileChange(path=path, content=content, is_new=False))
|
||||
|
||||
return changes
|
||||
|
||||
|
||||
def apply_changes(
|
||||
changes: list[FileChange],
|
||||
project_path: str | Path,
|
||||
dry_run: bool = False,
|
||||
) -> list[dict]:
|
||||
"""파일 변경사항을 프로젝트에 적용.
|
||||
|
||||
Args:
|
||||
changes: parse_code_output() 결과
|
||||
project_path: 프로젝트 루트 경로
|
||||
dry_run: True면 실제 파일 쓰기 없이 결과만 반환
|
||||
|
||||
Returns:
|
||||
적용 결과 리스트 [{"path": ..., "action": "created|modified|skipped", "lines": N}]
|
||||
"""
|
||||
root = Path(project_path).resolve()
|
||||
results = []
|
||||
|
||||
for change in changes:
|
||||
# 경로 정규화 + 보안: 프로젝트 밖 경로 차단
|
||||
target = (root / change.path).resolve()
|
||||
if not str(target).startswith(str(root)):
|
||||
logger.warning(f"경로 보안 위반 — 스킵: {change.path}")
|
||||
results.append({
|
||||
"path": change.path,
|
||||
"action": "skipped",
|
||||
"reason": "프로젝트 외부 경로",
|
||||
})
|
||||
continue
|
||||
|
||||
is_new = not target.exists()
|
||||
line_count = len(change.content.splitlines())
|
||||
|
||||
if dry_run:
|
||||
results.append({
|
||||
"path": change.path,
|
||||
"action": "would_create" if is_new else "would_modify",
|
||||
"lines": line_count,
|
||||
})
|
||||
continue
|
||||
|
||||
# 디렉토리 생성
|
||||
target.parent.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
# 파일 쓰기
|
||||
target.write_text(change.content, encoding="utf-8")
|
||||
action = "created" if is_new else "modified"
|
||||
logger.info(f"파일 {action}: {change.path} ({line_count}L)")
|
||||
|
||||
results.append({
|
||||
"path": change.path,
|
||||
"action": action,
|
||||
"lines": line_count,
|
||||
})
|
||||
|
||||
return results
|
||||
@@ -1,16 +1,25 @@
|
||||
"""GeminiCaller — gemini headless 호출.
|
||||
|
||||
stdin으로 시스템 프롬프트 + 컨텍스트를 직접 전달합니다.
|
||||
cmd /c 래핑으로 PowerShell 실행 정책 우회.
|
||||
인자 분리, 세마포어 기반 동시성 제어, 에러 처리 개선.
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import logging
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
logger = logging.getLogger("variet.gemini")
|
||||
|
||||
ROLE_PROMPTS_DIR = Path(__file__).parent.parent / "prompts"
|
||||
|
||||
# 동시 호출 제한 (Gemini AI Ultra 120RPM 고려)
|
||||
_semaphore = asyncio.Semaphore(4)
|
||||
|
||||
|
||||
class GeminiCallError(Exception):
|
||||
"""Gemini CLI 호출 실패."""
|
||||
pass
|
||||
|
||||
|
||||
class GeminiCaller:
|
||||
"""Gemini CLI headless 호출을 관리합니다."""
|
||||
@@ -23,8 +32,14 @@ class GeminiCaller:
|
||||
async def call(self, role: str, context: str, timeout: int = 120) -> str:
|
||||
"""역할별 프롬프트로 gemini 호출.
|
||||
|
||||
시스템 프롬프트와 컨텍스트를 하나로 합쳐 stdin으로 전달.
|
||||
세마포어로 동시 호출 수 제한.
|
||||
인자를 분리하여 안정적 subprocess 실행.
|
||||
"""
|
||||
async with _semaphore:
|
||||
return await self._call_impl(role, context, timeout)
|
||||
|
||||
async def _call_impl(self, role: str, context: str, timeout: int) -> str:
|
||||
"""실제 gemini 호출 구현."""
|
||||
# 시스템 프롬프트 로드
|
||||
prompt_file = ROLE_PROMPTS_DIR / f"{role}.md"
|
||||
if prompt_file.exists():
|
||||
@@ -42,14 +57,14 @@ class GeminiCaller:
|
||||
|
||||
try:
|
||||
proc = await asyncio.create_subprocess_exec(
|
||||
"cmd", "/c", "gemini --approval-mode yolo",
|
||||
"gemini", "--approval-mode", "yolo",
|
||||
stdin=asyncio.subprocess.PIPE,
|
||||
stdout=asyncio.subprocess.PIPE,
|
||||
stderr=asyncio.subprocess.PIPE,
|
||||
)
|
||||
stdout, stderr = await asyncio.wait_for(
|
||||
proc.communicate(input=full_input.encode("utf-8")),
|
||||
timeout=timeout
|
||||
timeout=timeout,
|
||||
)
|
||||
|
||||
self.call_count += 1
|
||||
@@ -57,23 +72,40 @@ class GeminiCaller:
|
||||
|
||||
output = stdout.decode("utf-8", errors="replace").strip()
|
||||
|
||||
# YOLO 모드 메시지 제거
|
||||
# 노이즈 라인 제거
|
||||
lines = output.splitlines()
|
||||
cleaned = []
|
||||
for line in lines:
|
||||
if "YOLO mode" in line or "Loaded cached" in line:
|
||||
if any(noise in line for noise in [
|
||||
"YOLO mode", "Loaded cached", "Welcome to Gemini",
|
||||
"Type /help", "Gemini CLI",
|
||||
]):
|
||||
continue
|
||||
cleaned.append(line)
|
||||
|
||||
return "\n".join(cleaned).strip()
|
||||
result = "\n".join(cleaned).strip()
|
||||
|
||||
if not result:
|
||||
logger.warning(f"Gemini [{role}] 빈 응답")
|
||||
if stderr:
|
||||
err = stderr.decode("utf-8", errors="replace").strip()
|
||||
logger.warning(f"Gemini stderr: {err[:200]}")
|
||||
|
||||
logger.info(
|
||||
f"Gemini [{role}] 호출 #{self.call_count} "
|
||||
f"— 입력 {len(full_input)}자 → 출력 {len(result)}자"
|
||||
)
|
||||
return result
|
||||
|
||||
except asyncio.TimeoutError:
|
||||
return f"[ERROR] Gemini CLI timeout after {timeout}s"
|
||||
raise GeminiCallError(f"Gemini CLI timeout ({timeout}s) — role={role}")
|
||||
except FileNotFoundError:
|
||||
raise GeminiCallError(
|
||||
"gemini CLI를 찾을 수 없습니다. PATH에 gemini가 있는지 확인하세요."
|
||||
)
|
||||
except Exception as e:
|
||||
return f"[ERROR] Gemini CLI call failed: {e}"
|
||||
raise GeminiCallError(f"Gemini CLI 호출 실패: {e}")
|
||||
|
||||
async def call_simple(self, prompt: str, timeout: int = 60) -> str:
|
||||
"""시스템 프롬프트 없이 단순 호출."""
|
||||
return await self.call("default", prompt, timeout)
|
||||
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
"""Task Pipeline — Plan → Code → Review → Ship.
|
||||
"""Task Pipeline — Plan → Code(병렬) → Batch Review → 총평.
|
||||
|
||||
E2E 파이프라인을 구성하고 실행합니다.
|
||||
병렬 코드 실행, 단일 배치 리뷰, 파일 적용, 종합 총평을 수행합니다.
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
@@ -9,11 +9,12 @@ import re
|
||||
from pathlib import Path
|
||||
from core.project_indexer import ProjectIndex
|
||||
from core.context_manager import ContextManager
|
||||
from core.gemini_caller import GeminiCaller
|
||||
from core.gemini_caller import GeminiCaller, GeminiCallError
|
||||
from core.file_applier import parse_code_output, apply_changes
|
||||
|
||||
|
||||
class TaskPipeline:
|
||||
"""작업 파이프라인: 사용자 요청을 분해하고 순차 실행합니다."""
|
||||
"""작업 파이프라인: Plan → Code(병렬) → Review(배치) → Summary."""
|
||||
|
||||
def __init__(self, project_path: str, token_budget: int = 50_000):
|
||||
self.project_path = project_path
|
||||
@@ -27,6 +28,10 @@ class TaskPipeline:
|
||||
self.index.scan()
|
||||
return self
|
||||
|
||||
# ──────────────────────────────────────────
|
||||
# Plan
|
||||
# ──────────────────────────────────────────
|
||||
|
||||
async def plan(self, user_request: str) -> dict:
|
||||
"""Planner로 작업 분해."""
|
||||
structure = self.index.get_structure_summary()
|
||||
@@ -39,13 +44,15 @@ class TaskPipeline:
|
||||
response = await self.gemini.call("planner", prompt, timeout=180)
|
||||
self._log("plan", user_request, response)
|
||||
|
||||
# JSON 추출
|
||||
plan = self._extract_json(response)
|
||||
return plan or {"summary": response, "tasks": [], "raw": response}
|
||||
|
||||
# ──────────────────────────────────────────
|
||||
# Code (개별 태스크)
|
||||
# ──────────────────────────────────────────
|
||||
|
||||
async def code(self, task: dict) -> str:
|
||||
"""Coder로 코드 수정."""
|
||||
# 관련 파일 컨텍스트 수집
|
||||
"""Coder로 코드 수정 (단일 태스크)."""
|
||||
context = self.ctx.gather(task.get("description", task.get("title", "")))
|
||||
|
||||
prompt = (
|
||||
@@ -58,27 +65,109 @@ class TaskPipeline:
|
||||
self._log("code", task.get("title", ""), response)
|
||||
return response
|
||||
|
||||
async def review(self, task: dict, code_output: str) -> dict:
|
||||
"""Reviewer로 코드 리뷰."""
|
||||
# ──────────────────────────────────────────
|
||||
# Code 병렬 실행
|
||||
# ──────────────────────────────────────────
|
||||
|
||||
async def code_parallel(self, tasks: list[dict]) -> list[str]:
|
||||
"""여러 태스크를 병렬로 코딩."""
|
||||
results = await asyncio.gather(
|
||||
*[self.code(task) for task in tasks],
|
||||
return_exceptions=True,
|
||||
)
|
||||
|
||||
# 예외를 문자열로 변환
|
||||
processed = []
|
||||
for i, result in enumerate(results):
|
||||
if isinstance(result, Exception):
|
||||
error_msg = f"[ERROR] Task {i+1} 실패: {result}"
|
||||
self._log("code_error", tasks[i].get("title", ""), error_msg)
|
||||
processed.append(error_msg)
|
||||
else:
|
||||
processed.append(result)
|
||||
|
||||
return processed
|
||||
|
||||
# ──────────────────────────────────────────
|
||||
# Batch Review (전체 한 번)
|
||||
# ──────────────────────────────────────────
|
||||
|
||||
async def batch_review(self, tasks: list[dict], code_outputs: list[str]) -> dict:
|
||||
"""모든 코드 출력을 한 번에 리뷰."""
|
||||
# 태스크별 코드 출력을 하나로 합침
|
||||
combined = []
|
||||
for i, (task, output) in enumerate(zip(tasks, code_outputs)):
|
||||
title = task.get("title", task.get("description", f"Task {i+1}"))
|
||||
combined.append(
|
||||
f"### Task {i+1}: {title}\n"
|
||||
f"{output[:2000]}\n" # 각 출력 2000자 제한
|
||||
)
|
||||
|
||||
prompt = (
|
||||
f"## Task\n{json.dumps(task, ensure_ascii=False, indent=2)}\n\n"
|
||||
f"## Code Output\n{code_output}\n\n"
|
||||
f"Review the code changes."
|
||||
f"## All Code Changes\n\n"
|
||||
f"{'---'.join(combined)}\n\n"
|
||||
f"Review ALL changes above as a whole. "
|
||||
f"Check for consistency, conflicts between tasks, and overall correctness."
|
||||
)
|
||||
|
||||
response = await self.gemini.call("reviewer", prompt, timeout=180)
|
||||
self._log("review", task.get("title", ""), response)
|
||||
self._log("batch_review", f"{len(tasks)} tasks", response)
|
||||
|
||||
review = self._extract_json(response)
|
||||
return review or {"passed": True, "summary": response, "raw": response}
|
||||
|
||||
# ──────────────────────────────────────────
|
||||
# 총평 (Summary)
|
||||
# ──────────────────────────────────────────
|
||||
|
||||
async def summarize(
|
||||
self,
|
||||
user_request: str,
|
||||
plan: dict,
|
||||
code_outputs: list[str],
|
||||
review: dict,
|
||||
applied_files: list[dict],
|
||||
) -> dict:
|
||||
"""전체 작업 결과 종합 총평."""
|
||||
file_changes = "\n".join(
|
||||
f"- {f['path']} ({f['action']}, {f.get('lines', '?')}L)"
|
||||
for f in applied_files
|
||||
) if applied_files else "파일 변경 없음"
|
||||
|
||||
prompt = (
|
||||
f"## 원래 요청\n{user_request}\n\n"
|
||||
f"## 계획\n{plan.get('summary', str(plan))[:500]}\n\n"
|
||||
f"## 태스크 수\n{len(plan.get('tasks', []))}개\n\n"
|
||||
f"## 리뷰 결과\n{review.get('summary', str(review))[:500]}\n\n"
|
||||
f"## 변경된 파일\n{file_changes}\n\n"
|
||||
f"위 정보를 바탕으로 총평을 작성하세요."
|
||||
)
|
||||
|
||||
response = await self.gemini.call("summarizer", prompt, timeout=60)
|
||||
self._log("summarize", user_request, response)
|
||||
|
||||
summary = self._extract_json(response)
|
||||
return summary or {
|
||||
"title": "작업 완료",
|
||||
"summary": response,
|
||||
"changes": [],
|
||||
"warnings": [],
|
||||
"next_steps": [],
|
||||
}
|
||||
|
||||
# ──────────────────────────────────────────
|
||||
# 전체 파이프라인 실행
|
||||
# ──────────────────────────────────────────
|
||||
|
||||
async def execute(self, user_request: str) -> dict:
|
||||
"""전체 파이프라인 실행."""
|
||||
"""전체 파이프라인: Plan → Code(병렬) → Review(배치) → 파일 적용 → 총평."""
|
||||
result = {
|
||||
"request": user_request,
|
||||
"plan": None,
|
||||
"tasks_completed": [],
|
||||
"reviews": [],
|
||||
"code_outputs": [],
|
||||
"review": None,
|
||||
"applied_files": [],
|
||||
"summary": None,
|
||||
}
|
||||
|
||||
# 1. Plan
|
||||
@@ -87,32 +176,50 @@ class TaskPipeline:
|
||||
|
||||
tasks = plan.get("tasks", [])
|
||||
if not tasks:
|
||||
result["error"] = "Planner returned no tasks"
|
||||
result["summary"] = {
|
||||
"title": "태스크 없음",
|
||||
"summary": "Planner가 실행할 태스크를 생성하지 못했습니다.",
|
||||
"changes": [],
|
||||
"warnings": ["요청을 더 구체적으로 해주세요."],
|
||||
"next_steps": [],
|
||||
}
|
||||
return result
|
||||
|
||||
# 2. Code + Review for each task
|
||||
for task in tasks:
|
||||
code_output = await self.code(task)
|
||||
# 2. Code 병렬 실행
|
||||
code_outputs = await self.code_parallel(tasks)
|
||||
result["code_outputs"] = [o[:500] for o in code_outputs]
|
||||
|
||||
review = await self.review(task, code_output)
|
||||
# 3. 파일 적용 (Coder 출력 파싱)
|
||||
all_applied = []
|
||||
for output in code_outputs:
|
||||
if output.startswith("[ERROR]"):
|
||||
continue
|
||||
changes = parse_code_output(output)
|
||||
if changes:
|
||||
applied = apply_changes(changes, self.project_path)
|
||||
all_applied.extend(applied)
|
||||
result["applied_files"] = all_applied
|
||||
|
||||
if not review.get("passed", True):
|
||||
# 리뷰 실패 시 한 번 재시도
|
||||
code_output = await self.code({
|
||||
**task,
|
||||
"description": task.get("description", "") +
|
||||
f"\n\n## Review Feedback\n{json.dumps(review.get('issues', []), ensure_ascii=False)}"
|
||||
})
|
||||
review = await self.review(task, code_output)
|
||||
# 4. Batch Review (전체 1회)
|
||||
review = await self.batch_review(tasks, code_outputs)
|
||||
result["review"] = review
|
||||
|
||||
result["tasks_completed"].append({
|
||||
"task": task,
|
||||
"output": code_output[:500], # 요약
|
||||
"review": review,
|
||||
})
|
||||
# 리뷰 실패 시 로그만 (재시도 없이 진행)
|
||||
if not review.get("passed", True):
|
||||
self._log("review_warning", "batch", "리뷰 이슈 있음 — 총평에 반영")
|
||||
|
||||
# 5. 총평
|
||||
summary = await self.summarize(
|
||||
user_request, plan, code_outputs, review, all_applied
|
||||
)
|
||||
result["summary"] = summary
|
||||
|
||||
return result
|
||||
|
||||
# ──────────────────────────────────────────
|
||||
# 유틸리티
|
||||
# ──────────────────────────────────────────
|
||||
|
||||
def _extract_json(self, text: str) -> dict | None:
|
||||
"""텍스트에서 JSON 블록 추출."""
|
||||
# ```json ... ``` 패턴
|
||||
@@ -123,13 +230,21 @@ class TaskPipeline:
|
||||
except json.JSONDecodeError:
|
||||
pass
|
||||
|
||||
# { ... } 직접 찾기
|
||||
match = re.search(r"\{.*\}", text, re.DOTALL)
|
||||
if match:
|
||||
try:
|
||||
return json.loads(match.group(0))
|
||||
except json.JSONDecodeError:
|
||||
pass
|
||||
# { ... } 직접 찾기 (중첩 지원)
|
||||
brace_depth = 0
|
||||
start = -1
|
||||
for i, ch in enumerate(text):
|
||||
if ch == '{':
|
||||
if brace_depth == 0:
|
||||
start = i
|
||||
brace_depth += 1
|
||||
elif ch == '}':
|
||||
brace_depth -= 1
|
||||
if brace_depth == 0 and start >= 0:
|
||||
try:
|
||||
return json.loads(text[start:i + 1])
|
||||
except json.JSONDecodeError:
|
||||
start = -1
|
||||
|
||||
return None
|
||||
|
||||
|
||||
Reference in New Issue
Block a user