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:
@@ -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