Files
variet-agent/core/task_pipeline.py
CD 752d851f9f 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 환경 경로 업데이트
2026-03-06 20:46:58 +09:00

257 lines
10 KiB
Python

"""Task Pipeline — Plan → Code(병렬) → Batch Review → 총평.
병렬 코드 실행, 단일 배치 리뷰, 파일 적용, 종합 총평을 수행합니다.
"""
import asyncio
import json
import re
from pathlib import Path
from core.project_indexer import ProjectIndex
from core.context_manager import ContextManager
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
self.index = ProjectIndex(project_path)
self.ctx = ContextManager(self.index, token_budget)
self.gemini = GeminiCaller(project_path)
self.log: list[dict] = []
def setup(self):
"""프로젝트 인덱싱."""
self.index.scan()
return self
# ──────────────────────────────────────────
# Plan
# ──────────────────────────────────────────
async def plan(self, user_request: str) -> dict:
"""Planner로 작업 분해."""
structure = self.index.get_structure_summary()
prompt = (
f"## User Request\n{user_request}\n\n"
f"## Project Structure\n{structure}\n\n"
f"Decompose this request into concrete tasks."
)
response = await self.gemini.call("planner", prompt, timeout=180)
self._log("plan", user_request, response)
plan = self._extract_json(response)
return plan or {"summary": response, "tasks": [], "raw": response}
# ──────────────────────────────────────────
# Code (개별 태스크)
# ──────────────────────────────────────────
async def code(self, task: dict) -> str:
"""Coder로 코드 수정 (단일 태스크)."""
context = self.ctx.gather(task.get("description", task.get("title", "")))
prompt = (
f"## Task\n{json.dumps(task, ensure_ascii=False, indent=2)}\n\n"
f"## Context\n{context}\n\n"
f"Implement the changes described in the task."
)
response = await self.gemini.call("coder", prompt, timeout=180)
self._log("code", task.get("title", ""), response)
return response
# ──────────────────────────────────────────
# 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"## 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("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,
"code_outputs": [],
"review": None,
"applied_files": [],
"summary": None,
}
# 1. Plan
plan = await self.plan(user_request)
result["plan"] = plan
tasks = plan.get("tasks", [])
if not tasks:
result["summary"] = {
"title": "태스크 없음",
"summary": "Planner가 실행할 태스크를 생성하지 못했습니다.",
"changes": [],
"warnings": ["요청을 더 구체적으로 해주세요."],
"next_steps": [],
}
return result
# 2. Code 병렬 실행
code_outputs = await self.code_parallel(tasks)
result["code_outputs"] = [o[:500] for o in code_outputs]
# 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
# 4. Batch Review (전체 1회)
review = await self.batch_review(tasks, code_outputs)
result["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 ... ``` 패턴
match = re.search(r"```json\s*\n(.*?)\n\s*```", text, re.DOTALL)
if match:
try:
return json.loads(match.group(1))
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
def _log(self, phase: str, input_summary: str, output: str):
self.log.append({
"phase": phase,
"input": input_summary[:200],
"output": output[:500],
})