feat: Task Pipeline + Planner E2E 성공 — stdin기반 GeminiCaller 확정 #task-189 #task-190

This commit is contained in:
quantlab
2026-03-06 17:37:06 +09:00
parent 9192770300
commit 57c9cb6143
7 changed files with 357 additions and 26 deletions

View File

@@ -1,10 +1,10 @@
"""GeminiCaller — gemini -p 역할별 headless 호출.
"""GeminiCaller — gemini headless 호출.
stdin으로 시스템 프롬프트 + 컨텍스트를 직접 전달합니다.
cmd /c 래핑으로 PowerShell 실행 정책 우회.
"""
import asyncio
import json
import time
from pathlib import Path
@@ -21,12 +21,9 @@ class GeminiCaller:
self.last_call_time = 0.0
async def call(self, role: str, context: str, timeout: int = 120) -> str:
"""역할별 프롬프트로 gemini -p 호출.
"""역할별 프롬프트로 gemini 호출.
Args:
role: 프롬프트 파일명 (planner, coder, reviewer, tester)
context: 전달할 컨텍스트
timeout: 최대 대기 시간 (초)
시스템 프롬프트와 컨텍스트를 하나로 합쳐 stdin으로 전달.
"""
# 시스템 프롬프트 로드
prompt_file = ROLE_PROMPTS_DIR / f"{role}.md"
@@ -35,31 +32,24 @@ class GeminiCaller:
else:
system_prompt = f"You are a {role}. Respond in Korean."
# cmd 구성
cmd_parts = ["gemini", "-p", context]
if system_prompt:
cmd_parts.extend(["--system", system_prompt])
cmd_parts.extend(["--approval-mode", "yolo"])
if self.project_path:
cmd_parts.extend(["--include-directories", self.project_path])
# cmd /c 래핑 (PowerShell 실행 정책 우회)
escaped_context = context.replace('"', '\\"')
cmd_str = f'gemini -p "{escaped_context}" --approval-mode yolo'
if self.project_path:
cmd_str += f' --include-directories "{self.project_path}"'
# 시스템 프롬프트 + 컨텍스트를 하나의 입력으로 합침
full_input = (
f"=== SYSTEM INSTRUCTIONS ===\n"
f"{system_prompt}\n\n"
f"=== USER INPUT ===\n"
f"{context}"
)
try:
proc = await asyncio.create_subprocess_shell(
f'cmd /c {cmd_str}',
proc = await asyncio.create_subprocess_exec(
"cmd", "/c", "gemini --approval-mode yolo",
stdin=asyncio.subprocess.PIPE,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE,
)
stdout, stderr = await asyncio.wait_for(
proc.communicate(), timeout=timeout
proc.communicate(input=full_input.encode("utf-8")),
timeout=timeout
)
self.call_count += 1
@@ -85,3 +75,5 @@ class GeminiCaller:
async def call_simple(self, prompt: str, timeout: int = 60) -> str:
"""시스템 프롬프트 없이 단순 호출."""
return await self.call("default", prompt, timeout)

141
core/task_pipeline.py Normal file
View File

@@ -0,0 +1,141 @@
"""Task Pipeline — Plan → Code → Review → Ship.
E2E 파이프라인을 구성하고 실행합니다.
"""
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
class TaskPipeline:
"""작업 파이프라인: 사용자 요청을 분해하고 순차 실행합니다."""
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
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=90)
self._log("plan", user_request, response)
# JSON 추출
plan = self._extract_json(response)
return plan or {"summary": response, "tasks": [], "raw": response}
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=120)
self._log("code", task.get("title", ""), response)
return response
async def review(self, task: dict, code_output: str) -> dict:
"""Reviewer로 코드 리뷰."""
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."
)
response = await self.gemini.call("reviewer", prompt, timeout=90)
self._log("review", task.get("title", ""), response)
review = self._extract_json(response)
return review or {"passed": True, "summary": response, "raw": response}
async def execute(self, user_request: str) -> dict:
"""전체 파이프라인 실행."""
result = {
"request": user_request,
"plan": None,
"tasks_completed": [],
"reviews": [],
}
# 1. Plan
plan = await self.plan(user_request)
result["plan"] = plan
tasks = plan.get("tasks", [])
if not tasks:
result["error"] = "Planner returned no tasks"
return result
# 2. Code + Review for each task
for task in tasks:
code_output = await self.code(task)
review = await self.review(task, code_output)
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)
result["tasks_completed"].append({
"task": task,
"output": code_output[:500], # 요약
"review": review,
})
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
# { ... } 직접 찾기
match = re.search(r"\{.*\}", text, re.DOTALL)
if match:
try:
return json.loads(match.group(0))
except json.JSONDecodeError:
pass
return None
def _log(self, phase: str, input_summary: str, output: str):
self.log.append({
"phase": phase,
"input": input_summary[:200],
"output": output[:500],
})