feat: 워크스페이스 시스템 + 통합 프롬프트 + Docs 기록 관리
- 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: 분류+즉답/계획 통합 프롬프트
This commit is contained in:
@@ -1,6 +1,6 @@
|
||||
"""Task Pipeline — Plan → Code(병렬) → Batch Review → 총평.
|
||||
"""Task Pipeline — Plan → Code(병렬) → Review(배치) → 파일 적용 → 총평 → 기록.
|
||||
|
||||
병렬 코드 실행, 단일 배치 리뷰, 파일 적용, 종합 총평을 수행합니다.
|
||||
docs/wiki를 프롬프트에 주입하고, 완료 시 세션 기록 + changelog 업데이트.
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
@@ -11,16 +11,19 @@ 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(배치) → Summary."""
|
||||
"""작업 파이프라인: Plan → Code(병렬) → Review(배치) → 기록."""
|
||||
|
||||
def __init__(self, project_path: str, token_budget: int = 50_000):
|
||||
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):
|
||||
@@ -28,6 +31,19 @@ class TaskPipeline:
|
||||
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
|
||||
# ──────────────────────────────────────────
|
||||
@@ -35,9 +51,12 @@ class TaskPipeline:
|
||||
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."
|
||||
)
|
||||
|
||||
@@ -54,10 +73,12 @@ class TaskPipeline:
|
||||
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."
|
||||
)
|
||||
|
||||
@@ -76,7 +97,6 @@ class TaskPipeline:
|
||||
return_exceptions=True,
|
||||
)
|
||||
|
||||
# 예외를 문자열로 변환
|
||||
processed = []
|
||||
for i, result in enumerate(results):
|
||||
if isinstance(result, Exception):
|
||||
@@ -89,25 +109,23 @@ class TaskPipeline:
|
||||
return processed
|
||||
|
||||
# ──────────────────────────────────────────
|
||||
# Batch Review (전체 한 번)
|
||||
# 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자 제한
|
||||
f"{output[:2000]}\n"
|
||||
)
|
||||
|
||||
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."
|
||||
f"Review ALL changes above as a whole."
|
||||
)
|
||||
|
||||
response = await self.gemini.call("reviewer", prompt, timeout=180)
|
||||
@@ -117,17 +135,12 @@ class TaskPipeline:
|
||||
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:
|
||||
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)"
|
||||
@@ -136,7 +149,6 @@ class TaskPipeline:
|
||||
|
||||
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"
|
||||
@@ -156,11 +168,11 @@ class TaskPipeline:
|
||||
}
|
||||
|
||||
# ──────────────────────────────────────────
|
||||
# 전체 파이프라인 실행
|
||||
# 전체 파이프라인
|
||||
# ──────────────────────────────────────────
|
||||
|
||||
async def execute(self, user_request: str) -> dict:
|
||||
"""전체 파이프라인: Plan → Code(병렬) → Review(배치) → 파일 적용 → 총평."""
|
||||
"""Plan → Code(병렬) → 파일 적용 → Review → 총평 → 기록."""
|
||||
result = {
|
||||
"request": user_request,
|
||||
"plan": None,
|
||||
@@ -178,7 +190,7 @@ class TaskPipeline:
|
||||
if not tasks:
|
||||
result["summary"] = {
|
||||
"title": "태스크 없음",
|
||||
"summary": "Planner가 실행할 태스크를 생성하지 못했습니다.",
|
||||
"summary": "Planner가 태스크를 생성하지 못했습니다.",
|
||||
"changes": [],
|
||||
"warnings": ["요청을 더 구체적으로 해주세요."],
|
||||
"next_steps": [],
|
||||
@@ -189,7 +201,7 @@ class TaskPipeline:
|
||||
code_outputs = await self.code_parallel(tasks)
|
||||
result["code_outputs"] = [o[:500] for o in code_outputs]
|
||||
|
||||
# 3. 파일 적용 (Coder 출력 파싱)
|
||||
# 3. 파일 적용
|
||||
all_applied = []
|
||||
for output in code_outputs:
|
||||
if output.startswith("[ERROR]"):
|
||||
@@ -200,20 +212,22 @@ class TaskPipeline:
|
||||
all_applied.extend(applied)
|
||||
result["applied_files"] = all_applied
|
||||
|
||||
# 4. Batch Review (전체 1회)
|
||||
# 4. Batch Review
|
||||
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
|
||||
|
||||
# 6. 기록
|
||||
self.docs.record_session(user_request, summary, plan)
|
||||
self.docs.append_changelog(
|
||||
summary.get("title", user_request[:50])
|
||||
)
|
||||
|
||||
return result
|
||||
|
||||
# ──────────────────────────────────────────
|
||||
@@ -222,7 +236,6 @@ class TaskPipeline:
|
||||
|
||||
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:
|
||||
@@ -230,7 +243,6 @@ class TaskPipeline:
|
||||
except json.JSONDecodeError:
|
||||
pass
|
||||
|
||||
# { ... } 직접 찾기 (중첩 지원)
|
||||
brace_depth = 0
|
||||
start = -1
|
||||
for i, ch in enumerate(text):
|
||||
|
||||
Reference in New Issue
Block a user