- workspace.py: 채널별 워크스페이스 모델 + JSON 영속 저장 - discord_bot.py: /workspace 슬래시 커맨드 (set/git/vikunja/info/remove/list) - 등록 채널만 자동 응답, 미등록 채널 무시 - Git/Vikunja 미설정 시 작업 차단 + 안내 - 통합 프롬프트 1회 호출 (router+planner+chat 통합) - docs_manager.py: Wiki 인덱스, 세션 기록, Changelog 자동 업데이트 - task_pipeline.py: 모든 Gemini 호출에 docs 컨텍스트 주입, 완료 시 기록 - unified.md: 분류+즉답/계획 통합 프롬프트
269 lines
10 KiB
Python
269 lines
10 KiB
Python
"""Task Pipeline — Plan → Code(병렬) → Review(배치) → 파일 적용 → 총평 → 기록.
|
|
|
|
docs/wiki를 프롬프트에 주입하고, 완료 시 세션 기록 + changelog 업데이트.
|
|
"""
|
|
|
|
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
|
|
from core.docs_manager import DocsManager
|
|
|
|
|
|
class TaskPipeline:
|
|
"""작업 파이프라인: Plan → Code(병렬) → Review(배치) → 기록."""
|
|
|
|
def __init__(self, project_path: str, token_budget: int = 50_000,
|
|
docs_subpath: str = "docs/wiki"):
|
|
self.project_path = project_path
|
|
self.index = ProjectIndex(project_path)
|
|
self.ctx = ContextManager(self.index, token_budget)
|
|
self.gemini = GeminiCaller(project_path)
|
|
self.docs = DocsManager(project_path, docs_subpath)
|
|
self.log: list[dict] = []
|
|
|
|
def setup(self):
|
|
"""프로젝트 인덱싱."""
|
|
self.index.scan()
|
|
return self
|
|
|
|
# ──────────────────────────────────────────
|
|
# Docs 컨텍스트 (모든 호출에 주입)
|
|
# ──────────────────────────────────────────
|
|
|
|
def _docs_context(self) -> str:
|
|
"""Gemini 호출에 주입할 프로젝트 문서 컨텍스트."""
|
|
index = self.docs.get_docs_index()
|
|
return (
|
|
f"\n{index}\n"
|
|
f"작업 완료 시 관련 문서가 있으면 업데이트하세요.\n"
|
|
f"docs 경로: {self.docs.docs_path}\n"
|
|
)
|
|
|
|
# ──────────────────────────────────────────
|
|
# Plan
|
|
# ──────────────────────────────────────────
|
|
|
|
async def plan(self, user_request: str) -> dict:
|
|
"""Planner로 작업 분해."""
|
|
structure = self.index.get_structure_summary()
|
|
docs_ctx = self._docs_context()
|
|
|
|
prompt = (
|
|
f"## User Request\n{user_request}\n\n"
|
|
f"## Project Structure\n{structure}\n\n"
|
|
f"## Project Docs\n{docs_ctx}\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", "")))
|
|
docs_ctx = self._docs_context()
|
|
|
|
prompt = (
|
|
f"## Task\n{json.dumps(task, ensure_ascii=False, indent=2)}\n\n"
|
|
f"## Context\n{context}\n\n"
|
|
f"## Project Docs\n{docs_ctx}\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"
|
|
)
|
|
|
|
prompt = (
|
|
f"## All Code Changes\n\n"
|
|
f"{'---'.join(combined)}\n\n"
|
|
f"Review ALL changes above as a whole."
|
|
)
|
|
|
|
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}
|
|
|
|
# ──────────────────────────────────────────
|
|
# 총평
|
|
# ──────────────────────────────────────────
|
|
|
|
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{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. 파일 적용
|
|
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
|
|
review = await self.batch_review(tasks, code_outputs)
|
|
result["review"] = review
|
|
|
|
# 5. 총평
|
|
summary = await self.summarize(
|
|
user_request, plan, code_outputs, review, all_applied
|
|
)
|
|
result["summary"] = summary
|
|
|
|
# 6. 기록
|
|
self.docs.record_session(user_request, summary, plan)
|
|
self.docs.append_changelog(
|
|
summary.get("title", user_request[:50])
|
|
)
|
|
|
|
return result
|
|
|
|
# ──────────────────────────────────────────
|
|
# 유틸리티
|
|
# ──────────────────────────────────────────
|
|
|
|
def _extract_json(self, text: str) -> dict | None:
|
|
"""텍스트에서 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],
|
|
})
|