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:
132
core/docs_manager.py
Normal file
132
core/docs_manager.py
Normal file
@@ -0,0 +1,132 @@
|
||||
"""Docs Manager — 작업 기록 + Wiki 문서 관리.
|
||||
|
||||
모든 작업은 docs/에 기록되며, Gemini 호출 시
|
||||
문서 경로와 기존 문서 목록을 프롬프트에 주입합니다.
|
||||
"""
|
||||
|
||||
import logging
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
|
||||
logger = logging.getLogger("variet.docs")
|
||||
|
||||
|
||||
class DocsManager:
|
||||
"""프로젝트 문서 관리자."""
|
||||
|
||||
def __init__(self, project_path: str, docs_subpath: str = "docs/wiki"):
|
||||
self.project_path = Path(project_path)
|
||||
self.docs_path = self.project_path / docs_subpath
|
||||
self.sessions_path = self.project_path / "docs" / "sessions"
|
||||
self.changelog_path = self.project_path / "docs" / "changelog.md"
|
||||
|
||||
# 디렉토리 생성
|
||||
self.docs_path.mkdir(parents=True, exist_ok=True)
|
||||
self.sessions_path.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
def get_docs_index(self) -> str:
|
||||
"""docs/wiki 내 문서 목록을 문자열로 반환 (프롬프트 주입용)."""
|
||||
if not self.docs_path.exists():
|
||||
return "문서 없음"
|
||||
|
||||
files = sorted(self.docs_path.glob("*.md"))
|
||||
if not files:
|
||||
return "문서 없음"
|
||||
|
||||
lines = ["=== PROJECT DOCS ==="]
|
||||
for f in files:
|
||||
size = f.stat().st_size
|
||||
lines.append(f" - {f.name} ({size}B)")
|
||||
lines.append(f"경로: {self.docs_path}")
|
||||
lines.append("=== END DOCS ===")
|
||||
|
||||
return "\n".join(lines)
|
||||
|
||||
def get_doc_content(self, filename: str) -> str:
|
||||
"""특정 문서 내용 반환."""
|
||||
path = self.docs_path / filename
|
||||
if path.exists():
|
||||
return path.read_text(encoding="utf-8", errors="ignore")
|
||||
return ""
|
||||
|
||||
def get_all_docs_content(self, max_total_bytes: int = 30000) -> str:
|
||||
"""전체 문서 내용 반환 (예산 내에서)."""
|
||||
files = sorted(self.docs_path.glob("*.md"))
|
||||
parts = ["=== PROJECT KNOWLEDGE BASE ===\n"]
|
||||
total = 0
|
||||
|
||||
for f in files:
|
||||
content = f.read_text(encoding="utf-8", errors="ignore")
|
||||
if total + len(content.encode("utf-8")) > max_total_bytes:
|
||||
parts.append(f"\n--- {f.name} (예산 초과, 생략) ---")
|
||||
continue
|
||||
parts.append(f"\n--- {f.name} ---\n{content}")
|
||||
total += len(content.encode("utf-8"))
|
||||
|
||||
parts.append("\n=== END KNOWLEDGE BASE ===")
|
||||
return "\n".join(parts)
|
||||
|
||||
def record_session(self, request: str, summary: dict, plan: dict = None) -> str:
|
||||
"""작업 세션을 기록."""
|
||||
now = datetime.now()
|
||||
filename = f"{now.strftime('%Y-%m-%d_%H%M%S')}.md"
|
||||
filepath = self.sessions_path / filename
|
||||
|
||||
lines = [
|
||||
f"# 작업 기록 — {now.strftime('%Y-%m-%d %H:%M')}",
|
||||
"",
|
||||
f"## 요청",
|
||||
f"{request}",
|
||||
"",
|
||||
]
|
||||
|
||||
if plan:
|
||||
lines.extend([
|
||||
f"## 계획",
|
||||
f"{plan.get('summary', str(plan)[:300])}",
|
||||
"",
|
||||
])
|
||||
|
||||
if isinstance(summary, dict):
|
||||
lines.extend([
|
||||
f"## 결과",
|
||||
f"{summary.get('summary', str(summary)[:300])}",
|
||||
"",
|
||||
])
|
||||
|
||||
changes = summary.get("changes", [])
|
||||
if changes:
|
||||
lines.append("## 변경 파일")
|
||||
for c in changes:
|
||||
lines.append(f"- `{c.get('file', '?')}` — {c.get('description', '')}")
|
||||
lines.append("")
|
||||
|
||||
warnings = summary.get("warnings", [])
|
||||
if warnings:
|
||||
lines.append("## 주의사항")
|
||||
for w in warnings:
|
||||
lines.append(f"- {w}")
|
||||
lines.append("")
|
||||
|
||||
filepath.write_text("\n".join(lines), encoding="utf-8")
|
||||
logger.info(f"세션 기록: {filepath}")
|
||||
return str(filepath)
|
||||
|
||||
def append_changelog(self, entry: str):
|
||||
"""Changelog에 항목 추가."""
|
||||
now = datetime.now().strftime("%Y-%m-%d %H:%M")
|
||||
line = f"\n- [{now}] {entry}"
|
||||
|
||||
if self.changelog_path.exists():
|
||||
content = self.changelog_path.read_text(encoding="utf-8")
|
||||
else:
|
||||
content = "# Changelog\n"
|
||||
|
||||
content += line
|
||||
self.changelog_path.write_text(content, encoding="utf-8")
|
||||
|
||||
def update_wiki(self, filename: str, content: str):
|
||||
"""Wiki 문서 생성/수정."""
|
||||
path = self.docs_path / filename
|
||||
path.write_text(content, encoding="utf-8")
|
||||
logger.info(f"Wiki 업데이트: {path}")
|
||||
@@ -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):
|
||||
|
||||
180
core/workspace.py
Normal file
180
core/workspace.py
Normal file
@@ -0,0 +1,180 @@
|
||||
"""Workspace Manager — 채널별 프로젝트 설정 관리.
|
||||
|
||||
워크스페이스는 JSON 파일로 영속 저장됩니다.
|
||||
각 디스코드 채널은 하나의 워크스페이스에 바인딩됩니다.
|
||||
"""
|
||||
|
||||
import json
|
||||
import logging
|
||||
from pathlib import Path
|
||||
from dataclasses import dataclass, field, asdict
|
||||
from typing import Optional
|
||||
|
||||
logger = logging.getLogger("variet.workspace")
|
||||
|
||||
# 워크스페이스 설정 파일 경로
|
||||
WORKSPACES_FILE = Path(__file__).parent.parent / "workspaces.json"
|
||||
|
||||
|
||||
@dataclass
|
||||
class GitConfig:
|
||||
url: str = ""
|
||||
token: str = ""
|
||||
repo: str = "" # "Owner/RepoName"
|
||||
branch: str = "main"
|
||||
|
||||
@property
|
||||
def is_configured(self) -> bool:
|
||||
return bool(self.url and self.token)
|
||||
|
||||
|
||||
@dataclass
|
||||
class VikunjaConfig:
|
||||
url: str = ""
|
||||
token: str = ""
|
||||
project_id: int = 0
|
||||
|
||||
@property
|
||||
def is_configured(self) -> bool:
|
||||
return bool(self.url and self.token and self.project_id)
|
||||
|
||||
|
||||
@dataclass
|
||||
class Workspace:
|
||||
name: str
|
||||
path: str
|
||||
channel_id: int
|
||||
git: GitConfig = field(default_factory=GitConfig)
|
||||
vikunja: VikunjaConfig = field(default_factory=VikunjaConfig)
|
||||
docs_path: str = "docs/wiki"
|
||||
|
||||
@property
|
||||
def is_ready(self) -> bool:
|
||||
"""Git + Vikunja 모두 설정되었는지."""
|
||||
return self.git.is_configured and self.vikunja.is_configured
|
||||
|
||||
@property
|
||||
def missing_configs(self) -> list[str]:
|
||||
"""미설정 항목 목록."""
|
||||
missing = []
|
||||
if not self.git.is_configured:
|
||||
missing.append("Git")
|
||||
if not self.vikunja.is_configured:
|
||||
missing.append("Vikunja")
|
||||
return missing
|
||||
|
||||
@property
|
||||
def abs_docs_path(self) -> Path:
|
||||
return Path(self.path) / self.docs_path
|
||||
|
||||
def to_dict(self) -> dict:
|
||||
return {
|
||||
"name": self.name,
|
||||
"path": self.path,
|
||||
"channel_id": self.channel_id,
|
||||
"git": asdict(self.git),
|
||||
"vikunja": asdict(self.vikunja),
|
||||
"docs_path": self.docs_path,
|
||||
}
|
||||
|
||||
@classmethod
|
||||
def from_dict(cls, data: dict) -> "Workspace":
|
||||
return cls(
|
||||
name=data["name"],
|
||||
path=data["path"],
|
||||
channel_id=data["channel_id"],
|
||||
git=GitConfig(**data.get("git", {})),
|
||||
vikunja=VikunjaConfig(**data.get("vikunja", {})),
|
||||
docs_path=data.get("docs_path", "docs/wiki"),
|
||||
)
|
||||
|
||||
|
||||
class WorkspaceManager:
|
||||
"""워크스페이스 CRUD + 영속 저장."""
|
||||
|
||||
def __init__(self, config_path: Path = WORKSPACES_FILE):
|
||||
self.config_path = config_path
|
||||
self.workspaces: dict[int, Workspace] = {} # channel_id → Workspace
|
||||
self._load()
|
||||
|
||||
def _load(self):
|
||||
"""JSON에서 워크스페이스 로드."""
|
||||
if not self.config_path.exists():
|
||||
self.workspaces = {}
|
||||
return
|
||||
|
||||
try:
|
||||
data = json.loads(self.config_path.read_text(encoding="utf-8"))
|
||||
self.workspaces = {
|
||||
int(ch_id): Workspace.from_dict(ws)
|
||||
for ch_id, ws in data.items()
|
||||
}
|
||||
logger.info(f"워크스페이스 {len(self.workspaces)}개 로드됨")
|
||||
except Exception as e:
|
||||
logger.error(f"워크스페이스 로드 실패: {e}")
|
||||
self.workspaces = {}
|
||||
|
||||
def _save(self):
|
||||
"""JSON으로 워크스페이스 저장."""
|
||||
data = {
|
||||
str(ch_id): ws.to_dict()
|
||||
for ch_id, ws in self.workspaces.items()
|
||||
}
|
||||
self.config_path.write_text(
|
||||
json.dumps(data, ensure_ascii=False, indent=2),
|
||||
encoding="utf-8",
|
||||
)
|
||||
|
||||
def set_workspace(self, channel_id: int, name: str, path: str) -> Workspace:
|
||||
"""채널에 워크스페이스 등록."""
|
||||
ws = Workspace(name=name, path=path, channel_id=channel_id)
|
||||
self.workspaces[channel_id] = ws
|
||||
self._save()
|
||||
logger.info(f"워크스페이스 설정: #{channel_id} → {name} ({path})")
|
||||
return ws
|
||||
|
||||
def get_workspace(self, channel_id: int) -> Optional[Workspace]:
|
||||
"""채널의 워크스페이스 조회."""
|
||||
return self.workspaces.get(channel_id)
|
||||
|
||||
def is_workspace_channel(self, channel_id: int) -> bool:
|
||||
"""이 채널이 워크스페이스로 등록되어 있는지."""
|
||||
return channel_id in self.workspaces
|
||||
|
||||
def set_git(self, channel_id: int, url: str, token: str,
|
||||
repo: str = "", branch: str = "main") -> bool:
|
||||
"""워크스페이스에 Git 설정."""
|
||||
ws = self.workspaces.get(channel_id)
|
||||
if not ws:
|
||||
return False
|
||||
|
||||
ws.git = GitConfig(url=url, token=token, repo=repo, branch=branch)
|
||||
self._save()
|
||||
logger.info(f"Git 설정: {ws.name} → {url}")
|
||||
return True
|
||||
|
||||
def set_vikunja(self, channel_id: int, url: str, token: str,
|
||||
project_id: int) -> bool:
|
||||
"""워크스페이스에 Vikunja 설정."""
|
||||
ws = self.workspaces.get(channel_id)
|
||||
if not ws:
|
||||
return False
|
||||
|
||||
ws.vikunja = VikunjaConfig(url=url, token=token, project_id=project_id)
|
||||
self._save()
|
||||
logger.info(f"Vikunja 설정: {ws.name} → {url} (project {project_id})")
|
||||
return True
|
||||
|
||||
def remove_workspace(self, channel_id: int) -> bool:
|
||||
"""워크스페이스 제거."""
|
||||
if channel_id in self.workspaces:
|
||||
name = self.workspaces[channel_id].name
|
||||
del self.workspaces[channel_id]
|
||||
self._save()
|
||||
logger.info(f"워크스페이스 제거: {name}")
|
||||
return True
|
||||
return False
|
||||
|
||||
def list_all(self) -> list[Workspace]:
|
||||
"""전체 워크스페이스 목록."""
|
||||
return list(self.workspaces.values())
|
||||
Reference in New Issue
Block a user