diff --git a/AGENT.ko.md b/AGENT.ko.md new file mode 100644 index 0000000..1e297c7 --- /dev/null +++ b/AGENT.ko.md @@ -0,0 +1,126 @@ +# AGENT.md + +본 문서는 새로운 프로젝트에 **MQTT 메시징 백플레인 및 Tmux 기반 멀티 에이전트 오케스트레이션 워크플로우**를 도입하고, 협업하는 에이전트들이 일관된 규칙과 아키텍처에 따라 안전하고 견고하게 작업을 수행할 수 있도록 정의한 공통 지침 및 규약입니다. + +새로운 프로젝트에서 작업하는 모든 에이전트는 작업을 시작하기 전 이 문서를 반드시 정독하고 규약을 준수해야 합니다. + +--- + +## 1. 에이전트의 역할 정의 (Agent Roles) + +역할군 간의 책임 및 권한을 명확히 분리하여 병목을 줄이고 작업의 완성도를 높입니다. + +### 👤 Project Manager (PM / Orchestrator) +- **주요 책무**: 사용자 요구사항 접수, 상세 작업 계획 수립, 작업자 할당/지시, 전체 워크플로우 통제 및 최종 결과 보고. +- **모호성 제거**: 사용자의 요구사항에 모호한 부분이 있다면 작업을 추측하여 진행하지 말고, 즉시 사용자에게 질문하여 명확히 해야 합니다 (`/grill-me` 슬래시 명령어 권장). +- **피드백 루프 조정**: Reviewer들의 검증 의견을 분석하여 개선 방향을 의사결정합니다. 결정하기 까다로운 기술적 난제는 Worker 및 Reviewer들의 조사를 거쳐 PM 본인의 판단을 더한 최종 보고서를 작성해 사용자에게 제시하고 프로젝트의 방향을 결정합니다. +- **자가 치유 (Hermes Fallback Fix)**: Reviewer가 지적한 결함이 아주 경미하거나 단순 오탈자/설정 누락인 경우, Worker에게 재할당하지 않고 PM이 직접 소스코드를 수정하여 전체 왕복(Round-trip) 비용을 최소화합니다. + +### 🛠️ Worker (Implementation Agent) +- **주요 책무**: PM으로부터 위임받은 구체적인 비즈니스 로직 설계 및 소스코드 구현. +- **협업 및 소통**: 할당받은 업무 범위에서 구현 방향이 모호하거나 인터페이스 설계 변경이 필요한 경우 PM에게 질문하여 합의를 이룬 후 수술적(Surgical) 변경을 적용합니다. +- **계약 준수**: PM이 전달한 단일 작업 지침(Brief) 및 고유 Job ID 규약을 준수하며, 작업 시작 시 `started`, 종료 시 `completed`/`error` 이벤트를 백플레인에 발행해야 합니다. + +### 🔍 Reviewer (Verification Agent) +- **주요 책무**: Worker가 제출한 소스코드 변경 사항(Diff)과 구현 명세를 검증하고, 보안 결함 탐지, 성능 개선안 도출 및 설계 일관성을 심사하는 조력자. +- **구체적 대안 제시**: 단순한 반려(`NOT PASS`) 통보를 금지하며, 문제를 제기할 때는 **안정적이고 검증된 구체적인 코드 대안(Alternative Code)이나 해결 방안을 반드시 함께 제시**해야 합니다. +- **교차 검증의 상호보완성**: 에이전트의 모델 특성(예: Flash 계열은 의미론적 셸 결함 포착에 강하고, Opus/Sonnet 계열은 API 서명 및 논리 회귀 분석에 강함)을 살려 병렬로 상호보완적 심사를 수행합니다. + +--- + +## 2. 메시징 백플레인 & 레지스트리 규약 + +에이전트 간의 비동기 소통과 상태 관리는 분산 이벤트 채널 및 파일/DB 레지스트리를 통해 제어됩니다. + +### 📡 MQTT 백플레인 (MQTT Backplane) +- **이벤트 라이프사이클**: + - `started` (작업 개시) ➡️ `progress`/`permission_required` (진행 상황 공유) ➡️ `completed` (성공 종료) 또는 `error` (실패 종료) + - `completed` 및 `error`는 단 한 번만 발행되는 단말(Terminal) 이벤트입니다. +- **메시지 발행/구독 규칙**: + - MQTT는 영속 큐를 보장하지 않으므로, 에이전트 구동 전 **반드시 구독자(`job_subscriber.py`)가 먼저 백그라운드에서 대기**해야 합니다 (Subscribe-before-Publish 원칙). + - 단말 이벤트 발행 시 브로커에 `retain=True`로 영속화하여 늦게 합류한 구독자도 최종 상태를 읽을 수 있도록 조치합니다. + - 전송 데이터에는 비밀번호, 개인키 등의 중요 비밀 정보나 절대 경로가 포함되지 않도록 보편화(Generalised)해야 합니다. + +### 🗃️ 레지스트리 및 상태 관리 +- 본 아키텍처는 목적에 따라 두 가지 레지스트리를 분리하여 운영합니다: + - **잡 레지스트리 (Job Registry)**: 각 비동기 잡의 메타데이터와 생명주기는 개별 JSON 파일(`.hermes/jobs/.json`)로 기록되며, 다중 세션 간의 동시 청구(claiming) 경합은 파일 단위의 `fcntl` advisory lock(`registry_lock` via `registry.py`)을 통해 방어합니다. + - **세션 레지스트리 (Session Registry)**: TMUX 모니터링 상태 및 에이전트 구동 정보는 SQLite WAL 데이터베이스(`.hermes/agent-sessions.db`)를 통해 단일 호스트 내에서 안정적인 동시 트랜잭션으로 일관되게 제어합니다. 단, SQLite WAL 모드는 NFS(네트워크 파일 시스템) 환경에서는 완전한 파일 락이 보장되지 않으므로 로컬 파일 시스템 사용을 권장합니다. + +### 🛡️ 보안 프로토콜 (HMAC-SHA256) +- **무인증 PoC 모드**: 잡 레지스트리 생성 시 `auth_token`이 `null`로 지정된 경우(PoC 기본 모드), 별도의 서명 검증을 생략하고 모든 이벤트를 수용합니다 (`verify_hmac`이 항상 `True`를 반환). +- **인증 Production 모드**: 실배포 환경이나 인증이 필요한 연동 단계에서는 각 잡마다 고유 암호화 토큰(`auth_token`)을 발급합니다. 퍼블리셔는 이 토큰을 키로 삼아 `hmac_sig` 서명을 페이로드에 동반해야 하며, 수신단(`verify_hmac`)에서 서명이 없거나 일치하지 않는 메시지는 즉시 드랍하여 다운그레이드 공격을 원천 차단합니다. +- **롤아웃 전략**: 보안 스킴 갱신 시 송수신 노드 간 불일치로 인한 이벤트 드랍을 피하기 위해, 과도기적 하이브리드 포맷 전송(평문 유출 위험 있음)을 배제하고 **모든 노드를 일제히 업데이트하는 "동시 롤아웃(Simultaneous Rollout)"**을 채택해야 합니다. + +--- + +## 3. 협업 워크플로우 실행 절차 (Workflow Loop) + +```mermaid +sequenceDiagram + autonumber + actor User as 사용자 + participant PM as Project Manager + participant W as Worker + participant R as Reviewers + participant M as MQTT Backplane + + User->>PM: 요구사항 전달 + Note over PM: grill-me 및 계획 수립 + PM->>M: Job 등록 및 Subscriber 구동 + PM->>W: 작업 위임 (Job ID & Brief 전달) + W->>M: 'started' 이벤트 발행 + Note over W: 코드 변경 및 구현 + W->>M: 'completed' (혹은 'error') 발행 + PM->>R: 병렬 리뷰 요청 (Diff 전달) + Note over R: 교차 분석 & 검증 + alt 결함 발견 + R->>PM: NOT PASS (대안 포함 피드백) + Note over PM: 경미한 결함은 PM이 직접 수정 + PM->>W: 피드백 반영 및 재할당 + else 검증 통과 + R->>PM: PASS + end + PM->>User: 최종 검증 통과 보고 & 커밋 +``` + +1. **계획 수립 및 할당**: PM은 사용자 요청을 구체화하고 의존성이 겹치지 않는 범위에서 잡을 정의합니다. +2. **작업 개시 및 통보**: PM은 구독자를 띄운 뒤 Worker 세션에 잡을 인가하며, Worker는 로직을 수행하고 단말 이벤트를 전송해 세션을 자동 종료합니다. +3. **교차 검수 반복 (Review Loop)**: PM은 작업 완료 후 변경분을 Reviewer 에이전트들에게 병렬 회람시킵니다. 리뷰어 전원이 `PASS` 의견을 낼 때까지 수정-반려 주기를 무한 반복(Loop)하여 코드 완성도를 보증합니다. +4. **릴리즈 및 정리**: 검증이 완료된 코드는 Git에 커밋하고, 임시 세션 리소스를 회수합니다. + +--- + +## 4. 분석 인프라 패턴 & 실무 가이드 (Infra Patterns) + +장기 실행 에이전트 분석 중 발생하는 유실 및 인프라적 장애를 예방하기 위한 중요 지침입니다. + +### 📸 TUI 뷰포트 절단 방지 (Pane Snapshotting 3대 규칙) +TMUX 환경에서 실행되는 에이전트가 화면 스크롤 한계로 인해 이전 출력이나 장문의 디버깅 로그를 잃지 않도록 아래의 **스냅샷 패턴을 의무적으로 수행**합니다. +1. **Pre-brief Capture**: 작업 지침(Brief)을 전송한 직후, 즉시 해당 세션의 pane을 캡처(`capture-pane -S -200`)해두어 입력 기록의 시작점을 백업합니다. +2. **Loop Snapshot**: 장기 실행(5분 이상) 중인 에이전트 세션의 경우, 주기적으로(예: 30초마다) 뷰포트를 스캔하여 증분 데이터를 `/tmp/pane-snap.txt`에 계속 누적(append) 기록합니다. +3. **Post-job Capture**: 잡 완료/에러 반환 즉시 전체 pane 상태를 마지막으로 캡처하여 전체 작업 궤적을 보존합니다. + +### 📄 장문 브리핑 전달 방식 +- TMUX `send-keys`나 입력 버퍼를 통해 수백 줄의 장문 지시나 프롬프트를 직렬로 입력하면, 에이전트의 TUI가 이를 모두 온전히 소화하지 못하고 일부 문자나 문단이 탈취/누락될 수 있습니다. +- **해결 지침**: 지시 사항이 긴 경우, 반드시 `/tmp/brief-.md` 등의 파일 경로로 지시문을 별도 작성해 전달하고, 에이전트에는 `"Read /tmp/brief-... and execute"` 라는 단순화된 실행 명령만 전달하십시오. + +### ⏱️ 타임아웃 구성 및 정렬 규칙 +- **잡 실행 제한 (`timeout_sec` & `idle_timeout_sec`)**: 각 잡은 전체 실행 만료 시간(`timeout_sec`, 기본 3600s)과 메세지 미수신 유휴 시간(`idle_timeout_sec`, 기본 120s)을 독립적으로 가집니다. +- **모니터 유휴 대기 (`SUB_IDLE_TIMEOUT`)**: 모니터 스크립트(`reconcile.sh`)의 유휴 대기 시간(`SUB_IDLE_TIMEOUT`) 기본값은 잡 최대 예산에 맞춰 `3600s`(1시간) 이상으로 항상 넉넉히 설정해야 합니다. 모니터가 작업 완료 전에 유휴 감지로 조기 자동 종료되어 백그라운드 태스크 관리를 소실하는 문제를 방지하기 위함입니다. + +--- + +## 5. 새 프로젝트 적용 체크리스트 (Setup Checklist) + +새 프로젝트에 이 에이전트 오케스트레이션 모델을 구축할 때의 체크리스트입니다. + +- [ ] **가상환경 의존성**: `pyyaml`, `paho-mqtt` 등 필요한 Python 패키지가 `.venv` 또는 `requirements.txt`에 포함되었는가? +- [ ] **환경 설정 파일**: MQTT 브로커 주소 및 보안 Credential이 `.env` 파일에 안전하게 로드되고 공유되는가? +- [ ] **디렉토리 규약**: 레지스트리 경로(`.hermes/jobs/`) 및 로깅 경로(`.hermes/delegate_job_logs/`)가 `.gitignore`에 등록되었는가? +- [ ] **스크립트 구비**: `mqtt_common.py`, `publish_event.py`, `job_subscriber.py`, `registry.py` 등의 핵심 모듈이 배치되었는가? +- [ ] **HMAC 활성화**: 새로운 레지스트리 잡 발급 시 난수 기반의 `auth_token`이 정상적으로 주입되고, 서명 기반의 상호 인증이 활성화되는가? +- [ ] **운영 헌장 배치**: 본 규약 파일(`AGENT.md`)이 새 프로젝트의 **최상위 루트(Root) 디렉터리**에 배치되었는가? (협업을 수행하는 에이전트들이 온보딩 시 규칙을 가장 먼저 인지할 수 있도록 루트 경로 배치가 필수적입니다.) + +--- + +*본 가이드는 협업 효율성과 코드 보안의 엄격한 균형을 유지하기 위한 규범입니다. 변경 사항이 필요한 경우 PM 및 Reviewer의 전원 합의를 거쳐 본 문서를 업데이트해야 합니다.* \ No newline at end of file diff --git a/AGENT.md b/AGENT.md index 1e297c7..6a4dc96 100644 --- a/AGENT.md +++ b/AGENT.md @@ -1,126 +1,126 @@ # AGENT.md -본 문서는 새로운 프로젝트에 **MQTT 메시징 백플레인 및 Tmux 기반 멀티 에이전트 오케스트레이션 워크플로우**를 도입하고, 협업하는 에이전트들이 일관된 규칙과 아키텍처에 따라 안전하고 견고하게 작업을 수행할 수 있도록 정의한 공통 지침 및 규약입니다. +This document serves as the common guidelines and protocol for introducing the **MQTT messaging backplane and Tmux-based multi-agent orchestration workflow** to a new project. It defines the rules and architecture to ensure collaborating agents perform tasks safely, robustly, and consistently. -새로운 프로젝트에서 작업하는 모든 에이전트는 작업을 시작하기 전 이 문서를 반드시 정독하고 규약을 준수해야 합니다. +All agents working on a new project must read this document thoroughly and comply with the defined protocols before starting any tasks. --- -## 1. 에이전트의 역할 정의 (Agent Roles) +## 1. Agent Roles Definition (Agent Roles) -역할군 간의 책임 및 권한을 명확히 분리하여 병목을 줄이고 작업의 완성도를 높입니다. +We clearly separate responsibilities and permissions between roles to reduce bottlenecks and enhance the quality of execution. ### 👤 Project Manager (PM / Orchestrator) -- **주요 책무**: 사용자 요구사항 접수, 상세 작업 계획 수립, 작업자 할당/지시, 전체 워크플로우 통제 및 최종 결과 보고. -- **모호성 제거**: 사용자의 요구사항에 모호한 부분이 있다면 작업을 추측하여 진행하지 말고, 즉시 사용자에게 질문하여 명확히 해야 합니다 (`/grill-me` 슬래시 명령어 권장). -- **피드백 루프 조정**: Reviewer들의 검증 의견을 분석하여 개선 방향을 의사결정합니다. 결정하기 까다로운 기술적 난제는 Worker 및 Reviewer들의 조사를 거쳐 PM 본인의 판단을 더한 최종 보고서를 작성해 사용자에게 제시하고 프로젝트의 방향을 결정합니다. -- **자가 치유 (Hermes Fallback Fix)**: Reviewer가 지적한 결함이 아주 경미하거나 단순 오탈자/설정 누락인 경우, Worker에게 재할당하지 않고 PM이 직접 소스코드를 수정하여 전체 왕복(Round-trip) 비용을 최소화합니다. +- **Core Responsibility**: Receive user requirements, establish detailed task plans, assign and instruct workers, control the overall workflow, and report final results. +- **Ambiguity Resolution**: If a user's requirements contain ambiguous details, do not guess. Immediately ask the user for clarification (we recommend using the `/grill-me` slash command). +- **Feedback Loop Adjustment**: Analyze verification feedback from Reviewers to decide on improvement paths. For complex technical challenges, direct Workers and Reviewers to research options, add the PM's own assessment, and present a final report to the user to decide the project's direction. +- **Self-Healing (Hermes Fallback Fix)**: If a defect pointed out by a Reviewer is extremely minor or is a simple typo/configuration omission, the PM should directly fix the source code instead of reassigning it to the Worker, thereby minimizing the round-trip cost. ### 🛠️ Worker (Implementation Agent) -- **주요 책무**: PM으로부터 위임받은 구체적인 비즈니스 로직 설계 및 소스코드 구현. -- **협업 및 소통**: 할당받은 업무 범위에서 구현 방향이 모호하거나 인터페이스 설계 변경이 필요한 경우 PM에게 질문하여 합의를 이룬 후 수술적(Surgical) 변경을 적용합니다. -- **계약 준수**: PM이 전달한 단일 작업 지침(Brief) 및 고유 Job ID 규약을 준수하며, 작업 시작 시 `started`, 종료 시 `completed`/`error` 이벤트를 백플레인에 발행해야 합니다. +- **Core Responsibility**: Design business logic and implement source code as delegated by the PM. +- **Collaboration & Communication**: If the implementation path is ambiguous or interface design changes are required within the assigned scope, ask the PM for consensus before applying surgical changes. +- **Contract Adherence**: Comply with the single task instructions (Brief) and the unique Job ID convention provided by the PM. Workers must publish a `started` event when starting work, and a `completed` or `error` event to the backplane upon termination. ### 🔍 Reviewer (Verification Agent) -- **주요 책무**: Worker가 제출한 소스코드 변경 사항(Diff)과 구현 명세를 검증하고, 보안 결함 탐지, 성능 개선안 도출 및 설계 일관성을 심사하는 조력자. -- **구체적 대안 제시**: 단순한 반려(`NOT PASS`) 통보를 금지하며, 문제를 제기할 때는 **안정적이고 검증된 구체적인 코드 대안(Alternative Code)이나 해결 방안을 반드시 함께 제시**해야 합니다. -- **교차 검증의 상호보완성**: 에이전트의 모델 특성(예: Flash 계열은 의미론적 셸 결함 포착에 강하고, Opus/Sonnet 계열은 API 서명 및 논리 회귀 분석에 강함)을 살려 병렬로 상호보완적 심사를 수행합니다. +- **Core Responsibility**: Verify source code changes (Diff) and implementation specifications submitted by Workers. Reviewers act as facilitators by detecting security vulnerabilities, proposing performance improvements, and examining design consistency. +- **Provide Concrete Alternatives**: Simply rejecting changes (`NOT PASS`) is forbidden. When raising an issue, Reviewers must propose a **concrete, stable, and verified alternative code block or solution**. +- **Complementary Cross-Verification**: Leverage the unique characteristics of different agent models (e.g., Flash-class models are skilled at capturing semantic shell bugs, while Opus/Sonnet-class models excel at API signatures and logical regression analysis) to perform parallel and mutually-supportive reviews. --- -## 2. 메시징 백플레인 & 레지스트리 규약 +## 2. Messaging Backplane & Registry Protocol -에이전트 간의 비동기 소통과 상태 관리는 분산 이벤트 채널 및 파일/DB 레지스트리를 통해 제어됩니다. +Asynchronous communication and state management between agents are controlled via distributed event channels and file/DB registries. -### 📡 MQTT 백플레인 (MQTT Backplane) -- **이벤트 라이프사이클**: - - `started` (작업 개시) ➡️ `progress`/`permission_required` (진행 상황 공유) ➡️ `completed` (성공 종료) 또는 `error` (실패 종료) - - `completed` 및 `error`는 단 한 번만 발행되는 단말(Terminal) 이벤트입니다. -- **메시지 발행/구독 규칙**: - - MQTT는 영속 큐를 보장하지 않으므로, 에이전트 구동 전 **반드시 구독자(`job_subscriber.py`)가 먼저 백그라운드에서 대기**해야 합니다 (Subscribe-before-Publish 원칙). - - 단말 이벤트 발행 시 브로커에 `retain=True`로 영속화하여 늦게 합류한 구독자도 최종 상태를 읽을 수 있도록 조치합니다. - - 전송 데이터에는 비밀번호, 개인키 등의 중요 비밀 정보나 절대 경로가 포함되지 않도록 보편화(Generalised)해야 합니다. +### 📡 MQTT Backplane +- **Event Lifecycle**: + - `started` (Job execution starts) ➡️ `progress`/`permission_required` (Share intermediate progress) ➡️ `completed` (Successful termination) or `error` (Failed termination) + - `completed` and `error` are terminal events that are published exactly once. +- **Publish/Subscribe Rules**: + - Since MQTT does not guarantee persistent queues, the subscriber (`job_subscriber.py`) **must be running in the background before the agent starts** (the Subscribe-before-Publish principle). + - When publishing terminal events, publish with `retain=True` on the broker so that subscribers joining late can still read the final state. + - Generalize all transmitted data to ensure that sensitive secrets like passwords, private keys, or absolute system paths are not included. -### 🗃️ 레지스트리 및 상태 관리 -- 본 아키텍처는 목적에 따라 두 가지 레지스트리를 분리하여 운영합니다: - - **잡 레지스트리 (Job Registry)**: 각 비동기 잡의 메타데이터와 생명주기는 개별 JSON 파일(`.hermes/jobs/.json`)로 기록되며, 다중 세션 간의 동시 청구(claiming) 경합은 파일 단위의 `fcntl` advisory lock(`registry_lock` via `registry.py`)을 통해 방어합니다. - - **세션 레지스트리 (Session Registry)**: TMUX 모니터링 상태 및 에이전트 구동 정보는 SQLite WAL 데이터베이스(`.hermes/agent-sessions.db`)를 통해 단일 호스트 내에서 안정적인 동시 트랜잭션으로 일관되게 제어합니다. 단, SQLite WAL 모드는 NFS(네트워크 파일 시스템) 환경에서는 완전한 파일 락이 보장되지 않으므로 로컬 파일 시스템 사용을 권장합니다. +### 🗃️ Registry & State Management +- This architecture maintains two distinct registries based on their purpose: + - **Job Registry**: The metadata and lifecycle of each asynchronous job are recorded in individual JSON files (`.hermes/jobs/.json`). Concurrency conflicts (claiming races) across multiple sessions are prevented via file-based `fcntl` advisory locks (`registry_lock` via `registry.py`). + - **Session Registry**: TMUX monitoring states and running agent metadata are consistently controlled using a SQLite WAL database (`.hermes/agent-sessions.db`) to support reliable concurrent transactions on a single host. However, since SQLite WAL mode does not guarantee complete file locking in Network File System (NFS) environments, we recommend using a local file system. -### 🛡️ 보안 프로토콜 (HMAC-SHA256) -- **무인증 PoC 모드**: 잡 레지스트리 생성 시 `auth_token`이 `null`로 지정된 경우(PoC 기본 모드), 별도의 서명 검증을 생략하고 모든 이벤트를 수용합니다 (`verify_hmac`이 항상 `True`를 반환). -- **인증 Production 모드**: 실배포 환경이나 인증이 필요한 연동 단계에서는 각 잡마다 고유 암호화 토큰(`auth_token`)을 발급합니다. 퍼블리셔는 이 토큰을 키로 삼아 `hmac_sig` 서명을 페이로드에 동반해야 하며, 수신단(`verify_hmac`)에서 서명이 없거나 일치하지 않는 메시지는 즉시 드랍하여 다운그레이드 공격을 원천 차단합니다. -- **롤아웃 전략**: 보안 스킴 갱신 시 송수신 노드 간 불일치로 인한 이벤트 드랍을 피하기 위해, 과도기적 하이브리드 포맷 전송(평문 유출 위험 있음)을 배제하고 **모든 노드를 일제히 업데이트하는 "동시 롤아웃(Simultaneous Rollout)"**을 채택해야 합니다. +### 🛡️ Security Protocol (HMAC-SHA256) +- **Unauthenticated PoC Mode**: If the `auth_token` in the job registry is set to `null` (the default PoC mode), signature verification is skipped and all events are accepted (`verify_hmac` always returns `True`). +- **Authenticated Production Mode**: In production environments or integrations requiring authentication, a unique cryptographic token (`auth_token`) is issued for each job. The publisher must include an `hmac_sig` signature in the payload keyed by this token, and the receiving end (`verify_hmac`) will immediately drop messages that lack a signature or have mismatching signatures to prevent downgrade attacks. +- **Rollout Strategy**: To avoid event drops caused by inconsistencies between publishing and receiving nodes when updating security schemes, hybrid transition formats (which risk leaking plaintext tokens) must not be used. Instead, adopt a **"Simultaneous Rollout"** where all nodes are updated at once. --- -## 3. 협업 워크플로우 실행 절차 (Workflow Loop) +## 3. Collaborative Workflow Execution Loop (Workflow Loop) ```mermaid sequenceDiagram autonumber - actor User as 사용자 + actor User as User participant PM as Project Manager participant W as Worker participant R as Reviewers participant M as MQTT Backplane - User->>PM: 요구사항 전달 - Note over PM: grill-me 및 계획 수립 - PM->>M: Job 등록 및 Subscriber 구동 - PM->>W: 작업 위임 (Job ID & Brief 전달) - W->>M: 'started' 이벤트 발행 - Note over W: 코드 변경 및 구현 - W->>M: 'completed' (혹은 'error') 발행 - PM->>R: 병렬 리뷰 요청 (Diff 전달) - Note over R: 교차 분석 & 검증 - alt 결함 발견 - R->>PM: NOT PASS (대안 포함 피드백) - Note over PM: 경미한 결함은 PM이 직접 수정 - PM->>W: 피드백 반영 및 재할당 - else 검증 통과 + User->>PM: Hand over requirements + Note over PM: Run grill-me & plan tasks + PM->>M: Register Job & start Subscriber + PM->>W: Delegate task (Provide Job ID & Brief) + W->>M: Publish 'started' event + Note over W: Modify code & implement + W->>M: Publish 'completed' (or 'error') + PM->>R: Request parallel review (Provide Diff) + Note over R: Cross-analysis & verification + alt Defect Found + R->>PM: NOT PASS (Feedback with alternatives) + Note over PM: PM directly fixes minor defects + PM->>W: Apply feedback & re-delegate + else Verification Pass R->>PM: PASS end - PM->>User: 최종 검증 통과 보고 & 커밋 + PM->>User: Report final pass & commit changes ``` -1. **계획 수립 및 할당**: PM은 사용자 요청을 구체화하고 의존성이 겹치지 않는 범위에서 잡을 정의합니다. -2. **작업 개시 및 통보**: PM은 구독자를 띄운 뒤 Worker 세션에 잡을 인가하며, Worker는 로직을 수행하고 단말 이벤트를 전송해 세션을 자동 종료합니다. -3. **교차 검수 반복 (Review Loop)**: PM은 작업 완료 후 변경분을 Reviewer 에이전트들에게 병렬 회람시킵니다. 리뷰어 전원이 `PASS` 의견을 낼 때까지 수정-반려 주기를 무한 반복(Loop)하여 코드 완성도를 보증합니다. -4. **릴리즈 및 정리**: 검증이 완료된 코드는 Git에 커밋하고, 임시 세션 리소스를 회수합니다. +1. **Planning and Allocation**: The PM defines requirements and outlines independent jobs to avoid conflicting dependencies. +2. **Execution and Notification**: The PM launches a subscriber, then assigns the job to a Worker session. The Worker performs the logic and sends a terminal event, automatically closing the session. +3. **Cross-Verification Iteration (Review Loop)**: Once the task is complete, the PM circulates the changes to the Reviewer agents in parallel. The modify-reject cycle repeats until all reviewers yield a `PASS`, ensuring high-quality code. +4. **Release and Cleanup**: Code that passes verification is committed to Git, and temporary session resources are reclaimed. --- -## 4. 분석 인프라 패턴 & 실무 가이드 (Infra Patterns) +## 4. Analysis Infrastructure Patterns & Practical Guide (Infra Patterns) -장기 실행 에이전트 분석 중 발생하는 유실 및 인프라적 장애를 예방하기 위한 중요 지침입니다. +These are critical instructions for preventing data loss and infrastructure-level failures during long-running agent analyses. -### 📸 TUI 뷰포트 절단 방지 (Pane Snapshotting 3대 규칙) -TMUX 환경에서 실행되는 에이전트가 화면 스크롤 한계로 인해 이전 출력이나 장문의 디버깅 로그를 잃지 않도록 아래의 **스냅샷 패턴을 의무적으로 수행**합니다. -1. **Pre-brief Capture**: 작업 지침(Brief)을 전송한 직후, 즉시 해당 세션의 pane을 캡처(`capture-pane -S -200`)해두어 입력 기록의 시작점을 백업합니다. -2. **Loop Snapshot**: 장기 실행(5분 이상) 중인 에이전트 세션의 경우, 주기적으로(예: 30초마다) 뷰포트를 스캔하여 증분 데이터를 `/tmp/pane-snap.txt`에 계속 누적(append) 기록합니다. -3. **Post-job Capture**: 잡 완료/에러 반환 즉시 전체 pane 상태를 마지막으로 캡처하여 전체 작업 궤적을 보존합니다. +### 📸 Preventing TUI Viewport Truncation (The 3 Pane Snapshotting Rules) +To ensure that agents running in TMUX environments do not lose debug logs or previous outputs due to screen scrollback limits, the following **snapshotting pattern must be enforced**: +1. **Pre-brief Capture**: Capture the pane (`capture-pane -S -200`) immediately after sending the task instruction (Brief) to back up the starting point of the input history. +2. **Loop Snapshot**: For long-running agent sessions (5 minutes or more), periodically (e.g., every 30 seconds) scan the viewport and append the incremental data to `/tmp/pane-snap.txt`. +3. **Post-job Capture**: Capture the complete pane state one final time immediately after a job completes or returns an error to preserve the entire execution trajectory. -### 📄 장문 브리핑 전달 방식 -- TMUX `send-keys`나 입력 버퍼를 통해 수백 줄의 장문 지시나 프롬프트를 직렬로 입력하면, 에이전트의 TUI가 이를 모두 온전히 소화하지 못하고 일부 문자나 문단이 탈취/누락될 수 있습니다. -- **해결 지침**: 지시 사항이 긴 경우, 반드시 `/tmp/brief-.md` 등의 파일 경로로 지시문을 별도 작성해 전달하고, 에이전트에는 `"Read /tmp/brief-... and execute"` 라는 단순화된 실행 명령만 전달하십시오. +### 📄 Handling Long Briefing Instructions +- Sending long instructions or prompts (hundreds of lines) sequentially via TMUX `send-keys` or input buffers can overwhelm the agent's TUI, leading to lost characters or truncated paragraphs. +- **Resolution**: If instructions are long, write them separately to a file path (e.g., `/tmp/brief-.md`) and send a simplified execution command to the agent: `"Read /tmp/brief-... and execute"`. -### ⏱️ 타임아웃 구성 및 정렬 규칙 -- **잡 실행 제한 (`timeout_sec` & `idle_timeout_sec`)**: 각 잡은 전체 실행 만료 시간(`timeout_sec`, 기본 3600s)과 메세지 미수신 유휴 시간(`idle_timeout_sec`, 기본 120s)을 독립적으로 가집니다. -- **모니터 유휴 대기 (`SUB_IDLE_TIMEOUT`)**: 모니터 스크립트(`reconcile.sh`)의 유휴 대기 시간(`SUB_IDLE_TIMEOUT`) 기본값은 잡 최대 예산에 맞춰 `3600s`(1시간) 이상으로 항상 넉넉히 설정해야 합니다. 모니터가 작업 완료 전에 유휴 감지로 조기 자동 종료되어 백그라운드 태스크 관리를 소실하는 문제를 방지하기 위함입니다. +### ⏱️ Timeout Configuration & Alignment Rules +- **Job Execution Limits (`timeout_sec` & `idle_timeout_sec`)**: Each job independently manages its overall execution timeout (`timeout_sec`, default 3600s) and idle timeout without receiving messages (`idle_timeout_sec`, default 120s). +- **Monitor Idle Waiting (`SUB_IDLE_TIMEOUT`)**: The idle timeout for the monitor script (`reconcile.sh`), `SUB_IDLE_TIMEOUT`, must always be set generously to `3600s` (1 hour) or more to align with the maximum job budget. This prevents the monitor from terminating early due to idle detection, which would lose control over background tasks before they finish. --- -## 5. 새 프로젝트 적용 체크리스트 (Setup Checklist) +## 5. Setup Checklist for New Projects (Setup Checklist) -새 프로젝트에 이 에이전트 오케스트레이션 모델을 구축할 때의 체크리스트입니다. +Use this checklist when deploying this agent orchestration model to a new project: -- [ ] **가상환경 의존성**: `pyyaml`, `paho-mqtt` 등 필요한 Python 패키지가 `.venv` 또는 `requirements.txt`에 포함되었는가? -- [ ] **환경 설정 파일**: MQTT 브로커 주소 및 보안 Credential이 `.env` 파일에 안전하게 로드되고 공유되는가? -- [ ] **디렉토리 규약**: 레지스트리 경로(`.hermes/jobs/`) 및 로깅 경로(`.hermes/delegate_job_logs/`)가 `.gitignore`에 등록되었는가? -- [ ] **스크립트 구비**: `mqtt_common.py`, `publish_event.py`, `job_subscriber.py`, `registry.py` 등의 핵심 모듈이 배치되었는가? -- [ ] **HMAC 활성화**: 새로운 레지스트리 잡 발급 시 난수 기반의 `auth_token`이 정상적으로 주입되고, 서명 기반의 상호 인증이 활성화되는가? -- [ ] **운영 헌장 배치**: 본 규약 파일(`AGENT.md`)이 새 프로젝트의 **최상위 루트(Root) 디렉터리**에 배치되었는가? (협업을 수행하는 에이전트들이 온보딩 시 규칙을 가장 먼저 인지할 수 있도록 루트 경로 배치가 필수적입니다.) +- [ ] **Virtualenv Dependencies**: Are required Python packages like `pyyaml` and `paho-mqtt` included in `.venv` or `requirements.txt`? +- [ ] **Configuration File**: Are the MQTT broker address and security credentials safely loaded and shared via the `.env` file? +- [ ] **Directory Convention**: Are the registry path (`.hermes/jobs/`) and logging path (`.hermes/delegate_job_logs/`) added to `.gitignore`? +- [ ] **Core Scripts**: Are the core scripts (`mqtt_common.py`, `publish_event.py`, `job_subscriber.py`, and `registry.py`) in place? +- [ ] **HMAC Enablement**: When a new registry job is created, is a random `auth_token` correctly injected, and is signature-based mutual authentication active? +- [ ] **Charter Placement**: Is this protocol file (`AGENT.md`) placed in the **top-level root directory** of the new project? (Placing it at the root is essential so that onboarding agents can recognize the rules immediately.) --- -*본 가이드는 협업 효율성과 코드 보안의 엄격한 균형을 유지하기 위한 규범입니다. 변경 사항이 필요한 경우 PM 및 Reviewer의 전원 합의를 거쳐 본 문서를 업데이트해야 합니다.* \ No newline at end of file +*This guide balances collaboration efficiency with strict code security. Any required changes must be discussed and agreed upon by the PM and all Reviewers before updating this document.* \ No newline at end of file diff --git a/BOOTSTRAP.ko.md b/BOOTSTRAP.ko.md new file mode 100644 index 0000000..7ed8b39 --- /dev/null +++ b/BOOTSTRAP.ko.md @@ -0,0 +1,165 @@ +# BOOTSTRAP.md + +본 문서는 `advanced_multi_agent` 오케스트레이션 및 메시징 백플레인 워크플로우를 새로운 프로젝트에 도입하여 이식하고, 새로운 개발자/에이전트가 초기 가동을 시작할 때 수행해야 하는 환경 설정 및 구축 절차를 안내합니다. + +새로운 에이전트는 이 안내서에 기술된 절차를 순차적으로 실행하여 초기 환경을 안정적으로 설정할 수 있습니다. + +--- + +## 1. 프로젝트 구조 이해 (Scaffolding Overview) + +본 프로젝트를 새로운 환경에 복제(Clone)한 후, 핵심 구성 요소들의 위치와 역할을 먼저 파악해야 합니다. + +* `skills/`: 멀티 에이전트 구동 및 비동기 잡 처리를 수행하는 셸 스크립트 모음 + * `lib.sh`: 오케스트레이션의 핵심 셸 함수 및 가상환경(venv) 자동 연동 라이브러리 + * `tmux-agent-orchestrate-create/`: 격리된 tmux 에이전트 세션을 시작하는 스크립트 + * `tmux-agent-orchestrate-stop/`: 세션을 정상적으로 중지하고 상태를 업데이트하는 스크립트 + * `tmux-agent-orchestrate-resume/`: 중지된 에이전트 세션을 이전 대화 상태 그대로 복원하는 스크립트 + * `tmux-agent-orchestrate-status/`: 전체 에이전트 세션의 현재 구동 상태를 조회하는 스크립트 + * `tmux-agent-orchestrate-monitor/`: tmux 상태와 레지스트리 상태를 동기화하는 모니터 스크립트 + * `tmux-agent-orchestrate-delegate-job/`: 비동기 잡 분할 실행 모듈 + * `requirements.txt`: Python 의존성 목록 (paho-mqtt, pyyaml) + * `scripts/`: 핵심 비즈니스 로직을 구동하는 Python 스크립트 디렉터리 + * `registry.py`: 잡의 등록, 클레임 및 원자적 파일 락 제어 (CLI 지원) + * `job_subscriber.py`: 백그라운드 이벤트 구독기 및 오디팅 로그 생성기 + * `publish_event.py`: 실행 상태 및 에러 트랩 시 이벤트 퍼블리셔 + * `mqtt_common.py`: 공통 MQTT 브로커 연결 유틸리티 +* `AGENT.md`: 에이전트 간의 역할 분담(PM, Worker, Reviewer) 및 이벤트 발행 규약 정의 +* `MESSAGING.md`: 에이전트 간 주고받는 MQTT 메시지 와이어 스킴 가이드라인 + +--- + +## 2. 환경 설정 파일 생성 (.env) + +메시징 브로커 설정 및 실행 경로를 설정하기 위해 로컬 환경 설정 파일(`.env`)을 생성하고 수정해야 합니다. + +### 단계 2.1: 자동 생성 스크립트 실행 +프로젝트 루트에서 제공되는 환경 설정 템플릿 복사 스크립트를 실행합니다. + +```bash +# .env.example를 .env로 자동 복제 (이미 존재하면 덮어쓰지 않고 보호됨) +./scripts/generate-env.sh + +# 만약 강제로 덮어쓰고 백업을 생성하고 싶은 경우: +./scripts/generate-env.sh --force +``` + +### 단계 2.2: 환경 변수 수정 및 설정 +생성된 `.env` 파일을 열어 설정을 필요에 따라 구성합니다. + +> [!NOTE] +> `generate-env.sh`로 생성된 기본 `.env` 파일은 모든 환경 변수 항목이 주석 처리되어 있습니다. 주석 처리된 상태로 둘 경우 로컬 프로젝트 루트를 기준으로 한 상대 경로(`.hermes/` 등) 및 기본 공개 브로커 주소가 자동 지정되므로 그대로 사용하셔도 무방합니다. + +1. **MQTT Broker 설정 (`MQTT_BROKER`)**: + * 기본값은 HiveMQ 공개 브로커(`broker.hivemq.com`)로 잡혀 있으나, 보안 및 프라이버시가 중요한 프로덕션 작업 시에는 개인/사설 브로커 주소로 변경할 것을 강력히 권장합니다. +2. **인증 정보 (`MQTT_USERNAME`, `MQTT_PASSWORD`)**: + * 보안 브로커를 사용하는 경우 `replace_me`로 명시된 곳을 실제 브로커 계정 정보로 변경해 주십시오. +3. **경로 관련 변수 (선택 사항)**: + * 특정 빌드 시스템이나 호스트 폴더 구조에 맞추어 `AGENT_SESSIONS_YAML` 및 `DELEGATE_JOB_LOGS_DIR` 등의 경로 값을 절대 경로로 오버라이드해야 하는 경우에만 주석을 풀고 기입하십시오. + +> [!WARNING] +> **보안 모드 기본값 안내**: +> 시스템의 기본 설정은 **무인증 PoC 모드**입니다. 잡 등록 시 `auth_token`이 명시적으로 주입되지 않으면(또는 `null`인 경우) HMAC 서명 검증이 생략됩니다. +> 공개 브로커 사용 환경이나 실제 프로덕션 단계에서는 잡 등록 시 `auth_token`을 고유 난수값으로 생성 및 주입하여 HMAC 보안 서명을 활성화해야 합니다. (자세한 보안 규약은 [MESSAGING.md](./MESSAGING.md) 및 [AGENT.ko.md](./AGENT.ko.md)의 `2.3 보안 프로토콜` 섹션을 참조하십시오. 현재 CLI를 통한 자동 토큰 생성/주입 기능 지원은 향후 로드맵의 `FW-N6` 과제로 처리 예정입니다.) + +--- + +## 3. 의존성 및 가상환경 설정 (Venv Setup) + +오케스트레이션 및 MQTT 메시징을 구동하기 위한 Python 3 의존성을 설정합니다. + +### 단계 3.1: Python 가상환경 구축 +프로젝트 루트에서 `.venv` 가상환경을 생성하고 활성화합니다. + +```bash +# 가상환경 생성 +python3 -m venv .venv + +# 가상환경 활성화 +source .venv/bin/activate +``` + +### 단계 3.2: 의존성 패키지 설치 +`tmux-agent-orchestrate-delegate-job` 디렉터리에 기재된 `requirements.txt` 의존성 목록을 가상환경에 설치합니다. + +```bash +# 의존성 패키지(pyyaml, paho-mqtt 등) 설치 +pip install -r skills/tmux-agent-orchestrate-delegate-job/requirements.txt +``` + +--- + +## 4. 디렉터리 준비 및 보안 감시 가이드 + +에이전트 제어 상태 및 잡 기록을 위해 로컬 레지스트리 디렉터리가 정상적으로 생성되었는지 확인합니다. + +1. **필수 로컬 디렉터리 구조**: + * `.hermes/jobs/`: 등록된 비동기 잡의 세부 메타데이터가 파일 형태로 저장되는 디렉터리 + * `.hermes/delegate_job_logs/`: 에이전트가 발행하는 모든 백플레인 이벤트 흐름이 기록되는 audit log (`events.ndjson`) 보존 디렉터리 +2. **Git 커밋 제어 (.gitignore)**: + * 새 프로젝트 초기화 시 아래 파일들이 절대 리포지토리에 커밋되지 않도록 `.gitignore` 상태를 점검합니다. `!.env.example` 예외 처리가 유지되어야 템플릿이 보존됩니다: + ```text + .env + .env.* + !.env.example + .hermes/ + .venv/ + __pycache__/ + *.pyc + ``` + +--- + +## 5. 실행 환경 검증 및 부트스트랩 테스트 + +환경 구축이 오작동 없이 안전하게 완료되었는지 아래의 체크리스트를 실행해 검증합니다. + +> [!IMPORTANT] +> 아래의 모든 검증 명령은 반드시 **프로젝트 루트 디렉터리**(`.hermes/` 디렉터리가 직접 보이는 위치)에서 실행해야 합니다. 잡 레지스트리 디렉터리 기본 경로가 프로젝트 루트 하위의 `./.hermes/jobs` 상대 경로를 기준으로 탐색되기 때문입니다. + +### 검증 테스트 1: 잡 레지스트리 정상 구동 여부 +Python 스크립트 및 venv 라이브러리가 올바르게 로드되는지 확인하기 위해 잡 목록을 조회합니다. + +```bash +# 가상환경(.venv) 파이썬 인터프리터를 사용하여 실행 +.venv/bin/python3 skills/tmux-agent-orchestrate-delegate-job/scripts/registry.py list +``` +* **출력 기대 결과**: 에러 메시지 없이 빈 JSON 배열 `[]` 또는 현재 등록된 pending/running 잡 목록이 성공적으로 출력되어야 합니다. + +### 검증 테스트 2: MQTT 연결 브로커 핸드셰이크 테스트 +브로커와의 송수신 통신망 상태를 확인하고, 이벤트 생명주기 및 멱등성이 온전히 작동하는지 실측 검증합니다. + +```bash +# 1. 테스트용 임시 잡 등록 및 발급된 8자리 Hex 잡 ID 획득 +JID=$(.venv/bin/python3 skills/tmux-agent-orchestrate-delegate-job/scripts/registry.py register \ + --agent "test-agent" \ + --prompt "Bootstrap check command" \ + --timeout 120) +echo "Generated Job ID: $JID" + +# 2. 획득한 잡 ID에 대해 백그라운드 이벤트 구독기(Subscriber) 구동 +.venv/bin/python3 skills/tmux-agent-orchestrate-delegate-job/scripts/job_subscriber.py --job "$JID" & + +# 3. 구독자의 MQTT Broker 소켓 연결 및 수신부 초기화 완료를 보장하기 위해 2초 대기 +sleep 2 + +# 4. 테스트 시작 이벤트 발행 (Subscribe-before-Publish 원칙 준수) +.venv/bin/python3 skills/tmux-agent-orchestrate-delegate-job/scripts/publish_event.py \ + --job "$JID" \ + --event started \ + --detail "Bootstrap MQTT verification connection check" + +# 5. 이벤트 수신이 터미널(stdout) 및 .hermes/delegate_job_logs/events.ndjson 로그 파일에 정상 기록되는지 확인 + +# 6. 검증 완료 후 백그라운드 프로세스 종료 및 테스트 잡 레코드 수동 정리 +kill %1 +rm -f ".hermes/jobs/$JID.json" ".hermes/jobs/$JID.lock" +``` + +--- + +## 6. 에이전트 온보딩 가이드 (New Agent Onboarding) + +본 환경 구축을 무사히 마쳤다면, 협업하는 에이전트는 즉시 프로젝트 루트에 있는 **[AGENT.ko.md](./AGENT.ko.md)** 문서를 읽어야 합니다. + +해당 문서에는 에이전트가 각 역할(PM, Worker, Reviewer)로 구동될 때 지켜야 할 **수술적 변경 규칙, 교차 검증 통과 규약, Tmux 뷰포트 유실 방지를 위한 스냅샷 패턴** 등이 서술되어 있어 안정적인 멀티 에이전트 워크플로우에 즉시 기여할 수 있도록 돕습니다. diff --git a/BOOTSTRAP.md b/BOOTSTRAP.md index 4600d77..082d932 100644 --- a/BOOTSTRAP.md +++ b/BOOTSTRAP.md @@ -1,103 +1,103 @@ # BOOTSTRAP.md -본 문서는 `advanced_multi_agent` 오케스트레이션 및 메시징 백플레인 워크플로우를 새로운 프로젝트에 도입하여 이식하고, 새로운 개발자/에이전트가 초기 가동을 시작할 때 수행해야 하는 환경 설정 및 구축 절차를 안내합니다. +This document guides you through the setup and initialization procedures required to adopt the `advanced_multi_agent` orchestration and messaging backplane workflow in a new project, enabling a new developer or agent to get up and running quickly. -새로운 에이전트는 이 안내서에 기술된 절차를 순차적으로 실행하여 초기 환경을 안정적으로 설정할 수 있습니다. +A new agent can follow the steps in this guide sequentially to establish a stable and reliable initial environment. --- -## 1. 프로젝트 구조 이해 (Scaffolding Overview) +## 1. Scaffolding Overview (Project Structure) -본 프로젝트를 새로운 환경에 복제(Clone)한 후, 핵심 구성 요소들의 위치와 역할을 먼저 파악해야 합니다. +Before cloning this project into a new environment, you must first understand the locations and roles of its core components: -* `skills/`: 멀티 에이전트 구동 및 비동기 잡 처리를 수행하는 셸 스크립트 모음 - * `lib.sh`: 오케스트레이션의 핵심 셸 함수 및 가상환경(venv) 자동 연동 라이브러리 - * `tmux-agent-orchestrate-create/`: 격리된 tmux 에이전트 세션을 시작하는 스크립트 - * `tmux-agent-orchestrate-stop/`: 세션을 정상적으로 중지하고 상태를 업데이트하는 스크립트 - * `tmux-agent-orchestrate-resume/`: 중지된 에이전트 세션을 이전 대화 상태 그대로 복원하는 스크립트 - * `tmux-agent-orchestrate-status/`: 전체 에이전트 세션의 현재 구동 상태를 조회하는 스크립트 - * `tmux-agent-orchestrate-monitor/`: tmux 상태와 레지스트리 상태를 동기화하는 모니터 스크립트 - * `tmux-agent-orchestrate-delegate-job/`: 비동기 잡 분할 실행 모듈 - * `requirements.txt`: Python 의존성 목록 (paho-mqtt, pyyaml) - * `scripts/`: 핵심 비즈니스 로직을 구동하는 Python 스크립트 디렉터리 - * `registry.py`: 잡의 등록, 클레임 및 원자적 파일 락 제어 (CLI 지원) - * `job_subscriber.py`: 백그라운드 이벤트 구독기 및 오디팅 로그 생성기 - * `publish_event.py`: 실행 상태 및 에러 트랩 시 이벤트 퍼블리셔 - * `mqtt_common.py`: 공통 MQTT 브로커 연결 유틸리티 -* `AGENT.md`: 에이전트 간의 역할 분담(PM, Worker, Reviewer) 및 이벤트 발행 규약 정의 -* `MESSAGING.md`: 에이전트 간 주고받는 MQTT 메시지 와이어 스킴 가이드라인 +* `skills/`: A collection of shell scripts that execute multi-agent coordination and asynchronous job processing. + * `lib.sh`: The core orchestration shell functions and virtual environment (venv) auto-loading library. + * `tmux-agent-orchestrate-create/`: Script to launch isolated tmux agent sessions. + * `tmux-agent-orchestrate-stop/`: Script to gracefully stop agent sessions and update states. + * `tmux-agent-orchestrate-resume/`: Script to restore stopped agent sessions back to their previous conversation state. + * `tmux-agent-orchestrate-status/`: Script to query the current running state of all agent sessions. + * `tmux-agent-orchestrate-monitor/`: Monitor script to sync tmux states with the registry. + * `tmux-agent-orchestrate-delegate-job/`: Asynchronous job splitting and delegation module. + * `requirements.txt`: Python dependency list (`paho-mqtt`, `pyyaml`). + * `scripts/`: Python scripts running the core business logic. + * `registry.py`: Job registration, claiming, and atomic file lock control (CLI supported). + * `job_subscriber.py`: Background event subscriber and audit log generator. + * `publish_event.py`: Event publisher for runtime states and error traps. + * `mqtt_common.py`: Common utility for connecting to the MQTT broker. +* `AGENT.md`: Definition of agent roles (PM, Worker, Reviewer) and event publication rules. +* `MESSAGING.md`: Messaging scheme and wire protocol guidelines for MQTT communication between agents. --- -## 2. 환경 설정 파일 생성 (.env) +## 2. Environment Configuration (.env) -메시징 브로커 설정 및 실행 경로를 설정하기 위해 로컬 환경 설정 파일(`.env`)을 생성하고 수정해야 합니다. +To set up the messaging broker and execution paths, you must create and modify a local environment configuration file (`.env`). -### 단계 2.1: 자동 생성 스크립트 실행 -프로젝트 루트에서 제공되는 환경 설정 템플릿 복사 스크립트를 실행합니다. +### Step 2.1: Run the Generation Script +Run the environment template copy script provided in the project root: ```bash -# .env.example를 .env로 자동 복제 (이미 존재하면 덮어쓰지 않고 보호됨) +# Automatically copy .env.example to .env (does not overwrite if it already exists) ./scripts/generate-env.sh -# 만약 강제로 덮어쓰고 백업을 생성하고 싶은 경우: +# To force overwrite and create a backup of the existing .env: ./scripts/generate-env.sh --force ``` -### 단계 2.2: 환경 변수 수정 및 설정 -생성된 `.env` 파일을 열어 설정을 필요에 따라 구성합니다. +### Step 2.2: Modify Environment Variables +Open the generated `.env` file to configure settings as needed. > [!NOTE] -> `generate-env.sh`로 생성된 기본 `.env` 파일은 모든 환경 변수 항목이 주석 처리되어 있습니다. 주석 처리된 상태로 둘 경우 로컬 프로젝트 루트를 기준으로 한 상대 경로(`.hermes/` 등) 및 기본 공개 브로커 주소가 자동 지정되므로 그대로 사용하셔도 무방합니다. +> The default `.env` file generated by `generate-env.sh` has all environment variables commented out. If left commented out, the system defaults to using relative paths (`.hermes/`, etc.) relative to the local project root, and the public MQTT broker. You can use it as-is without uncommenting anything. -1. **MQTT Broker 설정 (`MQTT_BROKER`)**: - * 기본값은 HiveMQ 공개 브로커(`broker.hivemq.com`)로 잡혀 있으나, 보안 및 프라이버시가 중요한 프로덕션 작업 시에는 개인/사설 브로커 주소로 변경할 것을 강력히 권장합니다. -2. **인증 정보 (`MQTT_USERNAME`, `MQTT_PASSWORD`)**: - * 보안 브로커를 사용하는 경우 `replace_me`로 명시된 곳을 실제 브로커 계정 정보로 변경해 주십시오. -3. **경로 관련 변수 (선택 사항)**: - * 특정 빌드 시스템이나 호스트 폴더 구조에 맞추어 `AGENT_SESSIONS_YAML` 및 `DELEGATE_JOB_LOGS_DIR` 등의 경로 값을 절대 경로로 오버라이드해야 하는 경우에만 주석을 풀고 기입하십시오. +1. **MQTT Broker Setup (`MQTT_BROKER`)**: + * The default broker is HiveMQ's public sandbox broker (`broker.hivemq.com`). However, for production work where security and privacy are critical, we strongly recommend changing this to a private broker address. +2. **Authentication Credentials (`MQTT_USERNAME`, `MQTT_PASSWORD`)**: + * If using a secured broker, change the placeholders marked `replace_me` to your actual broker credentials. +3. **Path Variables (Optional)**: + * Uncomment and specify absolute paths for variables like `AGENT_SESSIONS_YAML` and `DELEGATE_JOB_LOGS_DIR` only if you need to override the default relative paths to align with specific build systems or host directories. > [!WARNING] -> **보안 모드 기본값 안내**: -> 시스템의 기본 설정은 **무인증 PoC 모드**입니다. 잡 등록 시 `auth_token`이 명시적으로 주입되지 않으면(또는 `null`인 경우) HMAC 서명 검증이 생략됩니다. -> 공개 브로커 사용 환경이나 실제 프로덕션 단계에서는 잡 등록 시 `auth_token`을 고유 난수값으로 생성 및 주입하여 HMAC 보안 서명을 활성화해야 합니다. (자세한 보안 규약은 [MESSAGING.md](./MESSAGING.md) 및 [AGENT.md](./AGENT.md)의 `2.3 보안 프로토콜` 섹션을 참조하십시오. 현재 CLI를 통한 자동 토큰 생성/주입 기능 지원은 향후 로드맵의 `FW-N6` 과제로 처리 예정입니다.) +> **Security Mode Default Warning**: +> The system's default setting is the **unauthenticated PoC mode**. If an `auth_token` is not explicitly provided (or is `null`) during job registration, HMAC signature verification is skipped. +> In a public broker environment or production phase, you must generate and inject a unique random `auth_token` during job registration to enable HMAC signature security. (For detailed security protocols, refer to section `2.3 Security Protocol` in [MESSAGING.md](./MESSAGING.md) and [AGENT.md](./AGENT.md). Automated token generation and injection via CLI is on the roadmap under task `FW-N6`.) --- -## 3. 의존성 및 가상환경 설정 (Venv Setup) +## 3. Dependency and Virtualenv Setup -오케스트레이션 및 MQTT 메시징을 구동하기 위한 Python 3 의존성을 설정합니다. +Set up the Python 3 dependencies required to run the orchestration and MQTT messaging backplane. -### 단계 3.1: Python 가상환경 구축 -프로젝트 루트에서 `.venv` 가상환경을 생성하고 활성화합니다. +### Step 3.1: Build Python Virtual Environment +Create and activate a `.venv` virtual environment in the project root: ```bash -# 가상환경 생성 +# Create virtual environment python3 -m venv .venv -# 가상환경 활성화 +# Activate virtual environment source .venv/bin/activate ``` -### 단계 3.2: 의존성 패키지 설치 -`tmux-agent-orchestrate-delegate-job` 디렉터리에 기재된 `requirements.txt` 의존성 목록을 가상환경에 설치합니다. +### Step 3.2: Install Dependency Packages +Install the required packages listed in `requirements.txt` under `tmux-agent-orchestrate-delegate-job`: ```bash -# 의존성 패키지(pyyaml, paho-mqtt 등) 설치 +# Install dependencies (pyyaml, paho-mqtt, etc.) pip install -r skills/tmux-agent-orchestrate-delegate-job/requirements.txt ``` --- -## 4. 디렉터리 준비 및 보안 감시 가이드 +## 4. Directory Structure and Security Audit Guide -에이전트 제어 상태 및 잡 기록을 위해 로컬 레지스트리 디렉터리가 정상적으로 생성되었는지 확인합니다. +Ensure that the local registry directories required to track agent states and jobs are successfully created: -1. **필수 로컬 디렉터리 구조**: - * `.hermes/jobs/`: 등록된 비동기 잡의 세부 메타데이터가 파일 형태로 저장되는 디렉터리 - * `.hermes/delegate_job_logs/`: 에이전트가 발행하는 모든 백플레인 이벤트 흐름이 기록되는 audit log (`events.ndjson`) 보존 디렉터리 -2. **Git 커밋 제어 (.gitignore)**: - * 새 프로젝트 초기화 시 아래 파일들이 절대 리포지토리에 커밋되지 않도록 `.gitignore` 상태를 점검합니다. `!.env.example` 예외 처리가 유지되어야 템플릿이 보존됩니다: +1. **Required Directory Structure**: + * `.hermes/jobs/`: Holds detailed metadata files for registered asynchronous jobs. + * `.hermes/delegate_job_logs/`: Holds the audit logs (`events.ndjson`) for all backplane events published by agents. +2. **Git Ignore Configuration (`.gitignore`)**: + * When initializing a new project, verify that the following entries are configured in `.gitignore` to prevent committing local runtimes to the repository. The exception `!.env.example` must be kept to preserve the template: ```text .env .env.* @@ -110,56 +110,57 @@ pip install -r skills/tmux-agent-orchestrate-delegate-job/requirements.txt --- -## 5. 실행 환경 검증 및 부트스트랩 테스트 +## 5. Execution Verification and Bootstrap Tests -환경 구축이 오작동 없이 안전하게 완료되었는지 아래의 체크리스트를 실행해 검증합니다. +To verify that the environment has been successfully built without runtime errors, run the following verification checklist. > [!IMPORTANT] -> 아래의 모든 검증 명령은 반드시 **프로젝트 루트 디렉터리**(`.hermes/` 디렉터리가 직접 보이는 위치)에서 실행해야 합니다. 잡 레지스트리 디렉터리 기본 경로가 프로젝트 루트 하위의 `./.hermes/jobs` 상대 경로를 기준으로 탐색되기 때문입니다. +> All verification commands below must be executed from the **project root directory** (where the `.hermes/` directory is directly visible). This is because the default job registry path resolved by scripts is relative to the current working directory under `./.hermes/jobs`. -### 검증 테스트 1: 잡 레지스트리 정상 구동 여부 -Python 스크립트 및 venv 라이브러리가 올바르게 로드되는지 확인하기 위해 잡 목록을 조회합니다. +### Verification Test 1: Registry Script Load Check +Verify that the Python scripts and virtual environment libraries load correctly by listing jobs: ```bash -# 가상환경(.venv) 파이썬 인터프리터를 사용하여 실행 +# Run using the python interpreter in the virtual environment .venv/bin/python3 skills/tmux-agent-orchestrate-delegate-job/scripts/registry.py list ``` -* **출력 기대 결과**: 에러 메시지 없이 빈 JSON 배열 `[]` 또는 현재 등록된 pending/running 잡 목록이 성공적으로 출력되어야 합니다. +* **Expected Output**: The command should exit successfully and print an empty JSON array `[]` (or a list of pending/running jobs if any exist) without any python traceback errors. -### 검증 테스트 2: MQTT 연결 브로커 핸드셰이크 테스트 -브로커와의 송수신 통신망 상태를 확인하고, 이벤트 생명주기 및 멱등성이 온전히 작동하는지 실측 검증합니다. +### Verification Test 2: MQTT Broker Connection Handshake Test +Test the end-to-end communication through the broker to verify that events are published and received correctly: ```bash -# 1. 테스트용 임시 잡 등록 및 발급된 8자리 Hex 잡 ID 획득 +# 1. Register a temporary test job and capture its 8-character Hex Job ID JID=$(.venv/bin/python3 skills/tmux-agent-orchestrate-delegate-job/scripts/registry.py register \ --agent "test-agent" \ --prompt "Bootstrap check command" \ --timeout 120) echo "Generated Job ID: $JID" -# 2. 획득한 잡 ID에 대해 백그라운드 이벤트 구독기(Subscriber) 구동 +# 2. Run the background event subscriber (Subscriber) for this Job ID .venv/bin/python3 skills/tmux-agent-orchestrate-delegate-job/scripts/job_subscriber.py --job "$JID" & -# 3. 구독자의 MQTT Broker 소켓 연결 및 수신부 초기화 완료를 보장하기 위해 2초 대기 +# 3. Wait 2 seconds to allow the Subscriber to establish its MQTT socket connection sleep 2 -# 4. 테스트 시작 이벤트 발행 (Subscribe-before-Publish 원칙 준수) +# 4. Publish a start event (adhering to the Subscribe-before-Publish rule) .venv/bin/python3 skills/tmux-agent-orchestrate-delegate-job/scripts/publish_event.py \ --job "$JID" \ --event started \ --detail "Bootstrap MQTT verification connection check" -# 5. 이벤트 수신이 터미널(stdout) 및 .hermes/delegate_job_logs/events.ndjson 로그 파일에 정상 기록되는지 확인 +# 5. Verify that the event is printed to stdout and written to the audit log: +# .hermes/delegate_job_logs/events.ndjson -# 6. 검증 완료 후 백그라운드 프로세스 종료 및 테스트 잡 레코드 수동 정리 +# 6. Stop the background subscriber and clean up the test job records kill %1 rm -f ".hermes/jobs/$JID.json" ".hermes/jobs/$JID.lock" ``` --- -## 6. 에이전트 온보딩 가이드 (New Agent Onboarding) +## 6. Onboarding Collaborating Agents (New Agent Onboarding) -본 환경 구축을 무사히 마쳤다면, 협업하는 에이전트는 즉시 프로젝트 루트에 있는 **[AGENT.md](./AGENT.md)** 문서를 읽어야 합니다. +Once the setup is verified, onboarding agents should immediately read the **[AGENT.md](./AGENT.md)** guidelines in the project root. -해당 문서에는 에이전트가 각 역할(PM, Worker, Reviewer)로 구동될 때 지켜야 할 **수술적 변경 규칙, 교차 검증 통과 규약, Tmux 뷰포트 유실 방지를 위한 스냅샷 패턴** 등이 서술되어 있어 안정적인 멀티 에이전트 워크플로우에 즉시 기여할 수 있도록 돕습니다. +The guidelines describe essential workflows—such as **surgical change constraints, cross-verification review loops, and pane snapshotting to prevent viewport truncation**—allowing new agents to quickly and safely integrate with the multi-agent workflow. diff --git a/DONE.ko.md b/DONE.ko.md new file mode 100644 index 0000000..d6cd5ec --- /dev/null +++ b/DONE.ko.md @@ -0,0 +1,98 @@ +# DONE.md + +> 완료된 작업 추적. 모든 항목은 3개 에이전트(agy-new, agy-existing, claude-existing)의 최종 검증을 거쳤음. +> 검증 일시: 2026-06-21 + +--- + +## 요약 + +- **처리 항목**: FW-01 ~ FW-16, FW-L1 ~ FW-L3, FW-N1 ~ FW-N4, Infra Pattern (총 24개) +- **Working tree**: clean +- **검증 결과**: 모든 장기 과제, 신규 발견 항목 및 분석 인프라 개선 완료 (agy-existing, claude-existing 교차 검증 PASS) + +--- + +## 항목별 완료 현황 + +| 항목 | 내용 | 커밋 | 구현 | 리뷰 | +|---|---|---|---|---| +| FW-01 | MQTT subscriber 자동 재연결 (on_disconnect + reconnect_delay_set + with_retry) | `3677e4a` | agy-new | agy-existing PASS, claude-existing FAIL(on_disconnect 4->5인자) -> Hermes 수정 | +| FW-02 | NFS flock 경고 (_atomic_dump_yaml_check_nfs) | `f1a98be` | agy-new | Hermes 직접 (단기 경고만, SQLite WAL은 장기 과제) | +| FW-03 | delete->stop 명칭 잔재 정리 (REPORT.md + SKILL.md 주석) | `155c6e8`, `5af1387` | Hermes 직접 | 문서 작업 | +| FW-04 | .env 로드 통일 (mqtt_common.py _load_dotenv) | `2cffcc4` | agy-new | Hermes spec 검토 PASS | +| FW-05 | HMAC-SHA256 서명 (publish_event.py + verify_hmac + job_subscriber.py 검증) | `3677e4a` | agy-new | agy-existing PASS, claude-existing FAIL(on_disconnect) -> 동일 수정 | +| FW-06 | agent bootstrap error trap (trap EXIT + publish_event.py --event error) | `2cffcc4` | agy-new | Hermes spec 검토 PASS | +| FW-07 | lib.sh tmux shim 경로 상수화 (_TMUX_SHIM_DIR_PATTERN / _TMUX_SKILLS_BIN_PATTERN) | `4cea114` | agy-new | agy-existing FAIL(슬래시 누락), claude-existing FAIL(:57/:76 잔존) -> Hermes 수정 | +| FW-08 | _delegate_py_bin 캐싱 (AGENT_PYTHON_BIN 셸 변수, export 제거) | `4cea114` | agy-new | 동일 리뷰 (export -> 일반 변수로 수정) | +| FW-09 | monitor status enum 문서화 + reconcile.sh last_visible_note 분리 | `7d925de` | agy-new | Hermes spec 검토 PASS | +| FW-10 | 세션/잡 상태 glossary 추가 (MESSAGING.md) | `155c6e8` | Hermes 직접 | 문서 작업 | +| FW-11 | venv 의존성 통합 (pyyaml 추가, requirements.txt) | `f1a98be` | agy-new | Hermes spec 검토 PASS | +| FW-12 | .bak 잔재 파일 생성 중단 논의 | `478be56` | Hermes 직접 | shutil.copy2 롤백하여 P0-B 복원. 파일 정리는 .gitignore 기반 수동 삭제로 결론. | +| FW-13 | stop SKILL.md frontmatter/heading/산문 stop 재작성 | `5af1387` | Hermes 직접 | claude-existing 최종 검증에서 수정 확인 | +| FW-14 | REPORT.md -> MESSAGING.md git rename 정규화 | `9334352` | Hermes 직접 | git mv로 정규화 | +| FW-15 | monitor --subscribe 보안 경고 문서화 (SKILL.md Security 섹션) | `7d925de` | agy-new | Hermes spec 검토 PASS | +| FW-16 | 세션 상태 vs 잡 상태 도메인 분리 (glossary) | `155c6e8` | Hermes 직접 | FW-10과 동일 커밋 | +| FW-L1 | SQLite WAL 도입 및 YAML 최종 스냅샷 분리 | `440032b`, `478be56` | Hermes 직접 | SQLite DB 런타임 갱신, 세션 종료 시 YAML 덤프, 동시성 락 해결 (최종 6차 리뷰 PASS) | +| FW-L3 | SQLite 테이블 정규화 (sessions 테이블 분리 및 O(1) 쿼리 최적화) | `932f6be` | Hermes 직접 | sessions 테이블과 state 테이블 정규화, resolve_tmux_server/find_workspace_uuid/is_already_stopped O(1) 최적화 및 마이그레이션 호환 fallback 추가 (PASS) | +| FW-L2 | stop 옵션 시맨틱 단순화 (soft/hard 모드 및 graceful/capture 옵션 Deprecate) | `932f6be` | Hermes 직접 | stop_session.sh 단순화, 기본 graceful+capture stopped 상태 전이, --purge-conversation 파괴적 종료 명확화 (PASS) | +| FW-N1 | reconcile.sh 모니터 유휴 타임아웃 조정 (600s -> 3600s) | `5258b50` | Hermes 직접 | reconcile.sh의 SUB_IDLE_TIMEOUT 및 SKILL.md 수정 완료 (PASS) | +| FW-N2 | 와이어 포맷 호환성 (동시 롤아웃 정의 및 HMAC 전용 검증 강제) | `5258b50` | Hermes 직접 | 보안 Regreesion 유발하는 평문 fallback 제거 및 동시 롤아웃 정의 (PASS) | +| FW-N3 | 로그 문구 "auth_token mismatch" -> "HMAC verify failed" 갱신 | `5258b50` | Hermes 직접 | job_subscriber.py drop 로그 문구 수정 완료 (PASS) | +| FW-N4 | MESSAGING.md §2.4 HMAC 기술 갱신 및 롤아웃 정의 | `5258b50` | Hermes 직접 | 보고서 §2.4 최신화 완료 (PASS) | +| Infra | 분석 인프라 개선 (Pane snapshotting / truncate 방지 가이드라인 반영) | `5258b50` | Hermes 직접 | delegate-job SKILL.md에 pane 캡처 3대 규칙 반영 (PASS) | + +--- + +## 커밋 히스토리 + +``` +478be56 fix(lib): hardening and edge-case bugfixes (FW-12, FW-16 round) +440032b feat(lib): migrate to SQLite WAL backend for robust concurrency (FW-L1) +9ee9076 docs(delegate-job): add Subagent Orchestration Pattern section to SKILL.md +f1a98be fix(lib.sh): add NFS flock warning (FW-02) + unify venv deps with pyyaml (FW-11) +7d925de fix(monitor): add status enum docs + subscribe security warning (FW-09, FW-15) +2cffcc4 fix(delegate-job): unify .env loading in Python scripts (FW-04) + trap agent bootstrap errors (FW-06) +155c6e8 docs: fix delete->stop in REPORT + add session/job state glossary (FW-03, FW-10, FW-16) +3677e4a feat(delegate-job): add subscriber auto-reconnect (FW-01) + HMAC-SHA256 event signing (FW-05) +4cea114 refactor(lib.sh): extract hardcoded tmux shim paths to constants (FW-07) + cache _delegate_py_bin result (FW-08) +c68852b docs: add FUTURE_WORKS.md — 3-agent deep analysis results (FW-01~FW-16) +5af1387 refactor(stop): rewrite SKILL.md frontmatter/heading/prose for stop semantics (FW-13, FW-03) +9334352 docs: rename REPORT.md -> MESSAGING.md (FW-14) +a6f7c04 feat(delegate-job): bump default --timeout 600s -> 3600s (1h wall-clock budget) +``` + +--- + +## 검증 결과 (3개 에이전트 교차) + +### agy-new (Gemini 3.1 Pro High) +- 16/16 DONE + FW-L1 DONE (최종 커밋 완료) +- 새 발견: FW-02 근본 해결 지연 (SQLite WAL은 장기 과제) -> FW-L1을 통해 해결됨! + +### agy-existing (Gemini 3.5 Flash High) +- 16/16 DONE +- 새 발견 2건: + 1. AGENT_PYTHON_BIN export 캐시 오염 위험 -> 이미 수정됨 (export 제거, 일반 셸 변수 사용) + 2. reconcile.sh:66 모니터 유휴 타임아웃 600s vs 잡 3600s 불일치 -> 별개 도메인이나 문서화 가치 있음 + +### claude-existing (Claude Opus 4.8) +- working tree clean 확인, 모든 커밋 반영 확인 +- FW-01 on_disconnect 5인자 수정 확인 (이전 FAIL에서 지적한 항목) +- 구문/컴파일/stale 참조/working-tree 전체 검증 통과 + +--- + +## 처리 방식 + +- **Main worker**: agy-new (Gemini 3.1 Pro High) — 6개 배치 구현 +- **Reviewers**: agy-existing (Flash High) + claude-existing (Opus 4.8) — 병렬 리뷰 +- **Orchestrator**: Hermes — dispatch, diff 검토, fallback fix, commit +- **Batch 구성**: 파일 겹침 없이 2-3항씩 6배치로 그룹핑 +- **Hermes fallback**: 리뷰어가 발견한 작은 이슈(슬래시 누락, export 제거, paho 시그니처)를 Hermes가 직접 수정 + +--- + +## 날짜 + +2026-06-21 (Sun) 03:52 ~ 07:00 KST \ No newline at end of file diff --git a/DONE.md b/DONE.md index d6cd5ec..7a60b7c 100644 --- a/DONE.md +++ b/DONE.md @@ -1,52 +1,54 @@ # DONE.md -> 완료된 작업 추적. 모든 항목은 3개 에이전트(agy-new, agy-existing, claude-existing)의 최종 검증을 거쳤음. -> 검증 일시: 2026-06-21 +> **Completed Tasks Tracker**. All items have been verified and passed by three agents (`agy-new`, `agy-existing`, `claude-existing`). +> **Verification Date**: 2026-06-21 --- -## 요약 +## Summary -- **처리 항목**: FW-01 ~ FW-16, FW-L1 ~ FW-L3, FW-N1 ~ FW-N4, Infra Pattern (총 24개) -- **Working tree**: clean -- **검증 결과**: 모든 장기 과제, 신규 발견 항목 및 분석 인프라 개선 완료 (agy-existing, claude-existing 교차 검증 PASS) +- **Completed Items**: FW-01 ~ FW-16, FW-L1 ~ FW-L3, FW-N1 ~ FW-N4, Infra Pattern (total of 24 items) +- **Working Tree**: clean +- **Verification Results**: All long-term tasks, newly discovered items, and analysis infrastructure improvements have been completed (mutual verification PASS from `agy-existing` and `claude-existing`). --- -## 항목별 완료 현황 +## Completion Status by Item -| 항목 | 내용 | 커밋 | 구현 | 리뷰 | +| Item | Description | Commits | Implementation | Review / Verification | |---|---|---|---|---| -| FW-01 | MQTT subscriber 자동 재연결 (on_disconnect + reconnect_delay_set + with_retry) | `3677e4a` | agy-new | agy-existing PASS, claude-existing FAIL(on_disconnect 4->5인자) -> Hermes 수정 | -| FW-02 | NFS flock 경고 (_atomic_dump_yaml_check_nfs) | `f1a98be` | agy-new | Hermes 직접 (단기 경고만, SQLite WAL은 장기 과제) | -| FW-03 | delete->stop 명칭 잔재 정리 (REPORT.md + SKILL.md 주석) | `155c6e8`, `5af1387` | Hermes 직접 | 문서 작업 | -| FW-04 | .env 로드 통일 (mqtt_common.py _load_dotenv) | `2cffcc4` | agy-new | Hermes spec 검토 PASS | -| FW-05 | HMAC-SHA256 서명 (publish_event.py + verify_hmac + job_subscriber.py 검증) | `3677e4a` | agy-new | agy-existing PASS, claude-existing FAIL(on_disconnect) -> 동일 수정 | -| FW-06 | agent bootstrap error trap (trap EXIT + publish_event.py --event error) | `2cffcc4` | agy-new | Hermes spec 검토 PASS | -| FW-07 | lib.sh tmux shim 경로 상수화 (_TMUX_SHIM_DIR_PATTERN / _TMUX_SKILLS_BIN_PATTERN) | `4cea114` | agy-new | agy-existing FAIL(슬래시 누락), claude-existing FAIL(:57/:76 잔존) -> Hermes 수정 | -| FW-08 | _delegate_py_bin 캐싱 (AGENT_PYTHON_BIN 셸 변수, export 제거) | `4cea114` | agy-new | 동일 리뷰 (export -> 일반 변수로 수정) | -| FW-09 | monitor status enum 문서화 + reconcile.sh last_visible_note 분리 | `7d925de` | agy-new | Hermes spec 검토 PASS | -| FW-10 | 세션/잡 상태 glossary 추가 (MESSAGING.md) | `155c6e8` | Hermes 직접 | 문서 작업 | -| FW-11 | venv 의존성 통합 (pyyaml 추가, requirements.txt) | `f1a98be` | agy-new | Hermes spec 검토 PASS | -| FW-12 | .bak 잔재 파일 생성 중단 논의 | `478be56` | Hermes 직접 | shutil.copy2 롤백하여 P0-B 복원. 파일 정리는 .gitignore 기반 수동 삭제로 결론. | -| FW-13 | stop SKILL.md frontmatter/heading/산문 stop 재작성 | `5af1387` | Hermes 직접 | claude-existing 최종 검증에서 수정 확인 | -| FW-14 | REPORT.md -> MESSAGING.md git rename 정규화 | `9334352` | Hermes 직접 | git mv로 정규화 | -| FW-15 | monitor --subscribe 보안 경고 문서화 (SKILL.md Security 섹션) | `7d925de` | agy-new | Hermes spec 검토 PASS | -| FW-16 | 세션 상태 vs 잡 상태 도메인 분리 (glossary) | `155c6e8` | Hermes 직접 | FW-10과 동일 커밋 | -| FW-L1 | SQLite WAL 도입 및 YAML 최종 스냅샷 분리 | `440032b`, `478be56` | Hermes 직접 | SQLite DB 런타임 갱신, 세션 종료 시 YAML 덤프, 동시성 락 해결 (최종 6차 리뷰 PASS) | -| FW-L3 | SQLite 테이블 정규화 (sessions 테이블 분리 및 O(1) 쿼리 최적화) | `932f6be` | Hermes 직접 | sessions 테이블과 state 테이블 정규화, resolve_tmux_server/find_workspace_uuid/is_already_stopped O(1) 최적화 및 마이그레이션 호환 fallback 추가 (PASS) | -| FW-L2 | stop 옵션 시맨틱 단순화 (soft/hard 모드 및 graceful/capture 옵션 Deprecate) | `932f6be` | Hermes 직접 | stop_session.sh 단순화, 기본 graceful+capture stopped 상태 전이, --purge-conversation 파괴적 종료 명확화 (PASS) | -| FW-N1 | reconcile.sh 모니터 유휴 타임아웃 조정 (600s -> 3600s) | `5258b50` | Hermes 직접 | reconcile.sh의 SUB_IDLE_TIMEOUT 및 SKILL.md 수정 완료 (PASS) | -| FW-N2 | 와이어 포맷 호환성 (동시 롤아웃 정의 및 HMAC 전용 검증 강제) | `5258b50` | Hermes 직접 | 보안 Regreesion 유발하는 평문 fallback 제거 및 동시 롤아웃 정의 (PASS) | -| FW-N3 | 로그 문구 "auth_token mismatch" -> "HMAC verify failed" 갱신 | `5258b50` | Hermes 직접 | job_subscriber.py drop 로그 문구 수정 완료 (PASS) | -| FW-N4 | MESSAGING.md §2.4 HMAC 기술 갱신 및 롤아웃 정의 | `5258b50` | Hermes 직접 | 보고서 §2.4 최신화 완료 (PASS) | -| Infra | 분석 인프라 개선 (Pane snapshotting / truncate 방지 가이드라인 반영) | `5258b50` | Hermes 직접 | delegate-job SKILL.md에 pane 캡처 3대 규칙 반영 (PASS) | +| FW-01 | MQTT subscriber auto-reconnect (on_disconnect + reconnect_delay_set + with_retry) | `3677e4a` | agy-new | agy-existing PASS, claude-existing FAIL (on_disconnect 4->5 arguments) -> Fixed by Hermes | +| FW-02 | NFS flock warning (`_atomic_dump_yaml_check_nfs`) | `f1a98be` | agy-new | Hermes Direct (short-term warning; SQLite WAL handled in long-term task) | +| FW-03 | Clean up residual delete->stop naming (comments in `REPORT.md` + `SKILL.md`) | `155c6e8`, `5af1387` | Hermes Direct | Documentation task | +| FW-04 | Unify `.env` loading (`mqtt_common.py` `_load_dotenv`) | `2cffcc4` | agy-new | Hermes spec review PASS | +| FW-05 | HMAC-SHA256 signatures (verification in `publish_event.py` + `verify_hmac` + `job_subscriber.py`) | `3677e4a` | agy-new | agy-existing PASS, claude-existing FAIL (on_disconnect) -> fixed in the same cycle | +| FW-06 | Agent bootstrap error trap (`trap EXIT` + `publish_event.py --event error`) | `2cffcc4` | agy-new | Hermes spec review PASS | +| FW-07 | Constantize tmux shim paths in `lib.sh` (`_TMUX_SHIM_DIR_PATTERN` / `_TMUX_SKILLS_BIN_PATTERN`) | `4cea114` | agy-new | agy-existing FAIL (missing slash), claude-existing FAIL (residual :57/:76) -> Fixed by Hermes | +| FW-08 | Cache `_delegate_py_bin` (`AGENT_PYTHON_BIN` shell variable, removed `export`) | `4cea114` | agy-new | Reviewed (export changed to normal shell variable) | +| FW-09 | Document monitor status enum + isolate `last_visible_note` in `reconcile.sh` | `7d925de` | agy-new | Hermes spec review PASS | +| FW-10 | Add session/job states glossary (`MESSAGING.md`) | `155c6e8` | Hermes Direct | Documentation task | +| FW-11 | Unify venv dependencies (added `pyyaml` to `requirements.txt`) | `f1a98be` | agy-new | Hermes spec review PASS | +| FW-12 | Discussion on stopping the creation of `.bak` residual files | `478be56` | Hermes Direct | Rolled back to `shutil.copy2` to restore P0-B. File cleanup resolved as manual deletion via `.gitignore`. | +| FW-13 | Rewrite frontmatter, headings, and prose of stop `SKILL.md` to align with stop semantics | `5af1387` | Hermes Direct | Verified fixes in `claude-existing` final check | +| FW-14 | Normalize rename of `REPORT.md` -> `MESSAGING.md` | `9334352` | Hermes Direct | Renamed via `git mv` | +| FW-15 | Document `monitor --subscribe` security warning (Security section of `SKILL.md`) | `7d925de` | agy-new | Hermes spec review PASS | +| FW-16 | Domain separation between session states and job states (glossary) | `155c6e8` | Hermes Direct | Same commit as FW-10 | +| FW-L1 | Introduce SQLite WAL backend and isolate YAML final snapshot synchronization | `440032b`, `478be56` | Hermes Direct | Update SQLite DB at runtime, dump to YAML upon session exit, resolved concurrency locking issues (passed 6th review) | +| FW-L3 | Normalize SQLite tables (isolated `sessions` table and O(1) query optimizations) | `932f6be` | Hermes Direct | Normalized `sessions` and `state` tables; O(1) optimizations in `resolve_tmux_server`, `find_workspace_uuid`, and `is_already_stopped` with migration fallback (PASS) | +| FW-L2 | Simplify stop option semantics (deprecated soft/hard modes and graceful/capture options) | `932f6be` | Hermes Direct | Simplified `stop_session.sh`, transition to graceful+capture stopped state by default, clarified destructive `--purge-conversation` (PASS) | +| FW-N1 | Adjust monitor idle timeout in `reconcile.sh` (600s -> 3600s) | `5258b50` | Hermes Direct | Adjusted `SUB_IDLE_TIMEOUT` in `reconcile.sh` and updated `SKILL.md` (PASS) | +| FW-N2 | Wire format compatibility (defined simultaneous rollout and enforced HMAC-only verification) | `5258b50` | Hermes Direct | Removed plaintext fallback to prevent security regressions; defined simultaneous rollout (PASS) | +| FW-N3 | Update log string "auth_token mismatch" -> "HMAC verify failed" | `5258b50` | Hermes Direct | Updated drop log text in `job_subscriber.py` (PASS) | +| FW-N4 | Update HMAC technical description and rollout definition in `MESSAGING.md` §2.4 | `5258b50` | Hermes Direct | Updated report §2.4 (PASS) | +| Infra | Improve analysis infrastructure (implemented pane snapshotting to prevent truncation) | `5258b50` | Hermes Direct | Documented the 3 pane capture rules in delegate-job `SKILL.md` (PASS) | --- -## 커밋 히스토리 +## Commit History ``` +932f6be docs(stop): simplify stop semantics & normalize tables (FW-L2, FW-L3) +5258b50 feat(security): enforce HMAC, bump monitor idle timeout (FW-N1 ~ FW-N4) 478be56 fix(lib): hardening and edge-case bugfixes (FW-12, FW-16 round) 440032b feat(lib): migrate to SQLite WAL backend for robust concurrency (FW-L1) 9ee9076 docs(delegate-job): add Subagent Orchestration Pattern section to SKILL.md @@ -64,35 +66,35 @@ a6f7c04 feat(delegate-job): bump default --timeout 600s -> 3600s (1h wall-clock --- -## 검증 결과 (3개 에이전트 교차) +## Verification Results (Cross-Verification among 3 Agents) ### agy-new (Gemini 3.1 Pro High) -- 16/16 DONE + FW-L1 DONE (최종 커밋 완료) -- 새 발견: FW-02 근본 해결 지연 (SQLite WAL은 장기 과제) -> FW-L1을 통해 해결됨! +- 16/16 DONE + FW-L1 DONE (final commits verified) +- New Discovery: Delay in fundamental resolution of FW-02 (SQLite WAL as long-term task) -> resolved via FW-L1! ### agy-existing (Gemini 3.5 Flash High) - 16/16 DONE -- 새 발견 2건: - 1. AGENT_PYTHON_BIN export 캐시 오염 위험 -> 이미 수정됨 (export 제거, 일반 셸 변수 사용) - 2. reconcile.sh:66 모니터 유휴 타임아웃 600s vs 잡 3600s 불일치 -> 별개 도메인이나 문서화 가치 있음 +- 2 New Discoveries: + 1. Risk of cache pollution in `AGENT_PYTHON_BIN` export -> fixed (removed `export`, using normal shell variable) + 2. Mismatch in idle timeouts: monitor (`reconcile.sh:66`) 600s vs job 3600s -> separate domains, but documented ### claude-existing (Claude Opus 4.8) -- working tree clean 확인, 모든 커밋 반영 확인 -- FW-01 on_disconnect 5인자 수정 확인 (이전 FAIL에서 지적한 항목) -- 구문/컴파일/stale 참조/working-tree 전체 검증 통과 +- Verified clean working tree, verified all commits reflected +- Verified FW-01 5-argument fix on `on_disconnect` (which failed in prior rounds) +- Passed syntax, compilation, stale reference, and repository-wide checks --- -## 처리 방식 +## Methodology -- **Main worker**: agy-new (Gemini 3.1 Pro High) — 6개 배치 구현 -- **Reviewers**: agy-existing (Flash High) + claude-existing (Opus 4.8) — 병렬 리뷰 -- **Orchestrator**: Hermes — dispatch, diff 검토, fallback fix, commit -- **Batch 구성**: 파일 겹침 없이 2-3항씩 6배치로 그룹핑 -- **Hermes fallback**: 리뷰어가 발견한 작은 이슈(슬래시 누락, export 제거, paho 시그니처)를 Hermes가 직접 수정 +- **Main worker**: agy-new (Gemini 3.1 Pro High) — batch implementation across 6 cycles +- **Reviewers**: agy-existing (Flash High) + claude-existing (Opus 4.8) — parallel reviews +- **Orchestrator**: Hermes — dispatch, diff review, fallback fixes, commit +- **Batching**: Grouped tasks into 6 batches (2-3 tasks each) with no file overlapping +- **Hermes Fallback**: Hermes directly committed minor fixes pointed out by reviewers (missing slashes, removing exports, paho signature matching) --- -## 날짜 +## Date 2026-06-21 (Sun) 03:52 ~ 07:00 KST \ No newline at end of file diff --git a/FUTURE_WORKS.ko.md b/FUTURE_WORKS.ko.md new file mode 100644 index 0000000..952f281 --- /dev/null +++ b/FUTURE_WORKS.ko.md @@ -0,0 +1,31 @@ +# FUTURE_WORKS.md + +> **목적**: `advanced_multi_agent` 프로젝트의 향후 작업 후보를 추적한다. +> 완료된 항목은 `DONE.ko.md`를 참조. +> **최종 갱신**: 2026-06-21 + +--- + +## 향후 개선 작업 로드맵 + +현재 대기 중인 향후 작업(Future Works) 항목입니다. 본 항목들은 `Understand_Anything_Analysis.md` 보고서의 보안 및 동시성 분석을 바탕으로 제안되었습니다. + +| ID | 과제명 | 우선순위 | 작업량 | 해결 분야 / 설명 | 의존성 | +|---|---|---|---|---|---| +| **FW-N5** | `job-protocol.md` 보안 프로토콜 규격 갱신 (HMAC 서명 기준) | P1 (High) | 소 (문서) | **문서/설계 정합성**: 정식 프로토콜 문서가 보안상 불안전한 평문 토큰 전송 스킴(`data.auth_token`)으로 잘못 안내되어 있는 문제를 실제 구현된 HMAC 서명 스킴에 맞게 수정 | 없음 (FW-N6와 병행) | +| **FW-N6** | `registry.py` 내 `auth_token` 자동 생성 및 CLI 연동 지원 | P1 (High) | 소~중 | **보안 기능 활성화**: 현재 CLI(`registry.py register`)로 등록되는 모든 잡의 `auth_token`이 항상 `null`(무인증)로 고정되어 HMAC 보안이 무력화되는 결함 해결. CLI에 `--auth-token` 인자를 추가하고, 보안 환경(TLS/Username 등) 감지 시 자동으로 토큰을 생성하도록 개선 | 없음 (최우선 과제) | +| **FW-N7** | `job_subscriber.py` 내 시퀀스 단조 증가 검증을 통한 Replay Attack 방어 | P2 (Medium) | 소~중 | **보안성 강화 (심층 방어)**: 암호화 서명된 비단말(non-terminal) 이벤트(`progress`, `permission_required`)가 네트워크 상에서 탈취되어 재전송(Replay)되는 것을 방지하기 위해, 수신 메시지의 시퀀스(`seq`) 단조 증가 확인 로직 추가 | **FW-N6 선행 필수** (인증/HMAC 활성화 이후 의미 있음) | +| **FW-L4** | Job Registry의 SQLite 마이그레이션 및 NFS flock 한계 극복 | P3 (Low) | 대 | **동시성/인프라 확장성**: 세션 레지스트리와 마찬가지로 개별 JSON 파일 락(`fcntl.flock`) 방식의 잡 레지스트리를 SQLite 데이터베이스 트랜잭션 구조로 통합 마이그레이션하여, NFS 등 분산/네트워크 FS 환경에서의 안정성을 완전 확보 | **조건부** (실제 멀티 호스트/NFS 배포 필요 발생 시 착수) | + +--- + +### 세부 논의 결과 및 방향성 (Reviewer 합의 사항) + +1. **HMAC 보안 활성화를 위한 R2(FW-N6) 우선 해결**: + * 현재 구현된 HMAC 서명 코드(Verify/Sign)는 실재하지만, 정상적인 CLI 경로로 잡을 등록할 때는 암호화 토큰을 생성 또는 주입할 방법이 전무해 강제로 무인증 PoC 모드로 실행됩니다. 따라서 **FW-N6**가 모든 보안 개선의 선행 고리입니다. +2. **문서 동기화(FW-N5)**: + * 문서가 안전하지 않은 설계(평문 전송)를 가이드하고 있으므로 개발 혼선을 막기 위해 즉각 수정합니다. +3. **Replay 공격 방어(FW-N7)의 범위**: + * 시퀀스 단조 증가 검사(`last_seq` 추적)를 수신단에 구현하되, 가입자(`job_subscriber.py`) 재시작 시의 `last_seq` 초기화 예외 처리 및 터미널 이벤트 중복 제어와의 연계를 정밀히 검토해야 합니다. +4. **SQLite 통합(FW-L4)의 조건부 연기**: + * 세션 레지스트리와 달리 개별 잡 데이터는 JSON 파일 구조가 관리 및 디버깅 직관성이 우수하며, 현재 배포 환경은 단일 호스트 로컬 FS로 제한되어 있어 `fcntl.flock` 잠금만으로 안전하게 운용 가능하므로 낮은 우선순위(P3)로 배정하고 필요 시 착수합니다. \ No newline at end of file diff --git a/FUTURE_WORKS.md b/FUTURE_WORKS.md index ca387fb..cd96724 100644 --- a/FUTURE_WORKS.md +++ b/FUTURE_WORKS.md @@ -1,31 +1,31 @@ # FUTURE_WORKS.md -> **목적**: `advanced_multi_agent` 프로젝트의 향후 작업 후보를 추적한다. -> 완료된 항목은 `DONE.md`를 참조. -> **최종 갱신**: 2026-06-21 +> **Purpose**: Track future work candidates for the `advanced_multi_agent` project. +> For completed items, see `DONE.md`. +> **Last Updated**: 2026-06-21 --- -## 향후 개선 작업 로드맵 +## Future Improvements Roadmap -현재 대기 중인 향후 작업(Future Works) 항목입니다. 본 항목들은 `Understand_Anything_Analysis.md` 보고서의 보안 및 동시성 분석을 바탕으로 제안되었습니다. +Below is the list of pending future work items. These items were proposed based on the security and concurrency analysis in the `Understand_Anything_Analysis.md` report. -| ID | 과제명 | 우선순위 | 작업량 | 해결 분야 / 설명 | 의존성 | +| ID | Task | Priority | Effort | Domain / Description | Dependencies | |---|---|---|---|---|---| -| **FW-N5** | `job-protocol.md` 보안 프로토콜 규격 갱신 (HMAC 서명 기준) | P1 (High) | 소 (문서) | **문서/설계 정합성**: 정식 프로토콜 문서가 보안상 불안전한 평문 토큰 전송 스킴(`data.auth_token`)으로 잘못 안내되어 있는 문제를 실제 구현된 HMAC 서명 스킴에 맞게 수정 | 없음 (FW-N6와 병행) | -| **FW-N6** | `registry.py` 내 `auth_token` 자동 생성 및 CLI 연동 지원 | P1 (High) | 소~중 | **보안 기능 활성화**: 현재 CLI(`registry.py register`)로 등록되는 모든 잡의 `auth_token`이 항상 `null`(무인증)로 고정되어 HMAC 보안이 무력화되는 결함 해결. CLI에 `--auth-token` 인자를 추가하고, 보안 환경(TLS/Username 등) 감지 시 자동으로 토큰을 생성하도록 개선 | 없음 (최우선 과제) | -| **FW-N7** | `job_subscriber.py` 내 시퀀스 단조 증가 검증을 통한 Replay Attack 방어 | P2 (Medium) | 소~중 | **보안성 강화 (심층 방어)**: 암호화 서명된 비단말(non-terminal) 이벤트(`progress`, `permission_required`)가 네트워크 상에서 탈취되어 재전송(Replay)되는 것을 방지하기 위해, 수신 메시지의 시퀀스(`seq`) 단조 증가 확인 로직 추가 | **FW-N6 선행 필수** (인증/HMAC 활성화 이후 의미 있음) | -| **FW-L4** | Job Registry의 SQLite 마이그레이션 및 NFS flock 한계 극복 | P3 (Low) | 대 | **동시성/인프라 확장성**: 세션 레지스트리와 마찬가지로 개별 JSON 파일 락(`fcntl.flock`) 방식의 잡 레지스트리를 SQLite 데이터베이스 트랜잭션 구조로 통합 마이그레이션하여, NFS 등 분산/네트워크 FS 환경에서의 안정성을 완전 확보 | **조건부** (실제 멀티 호스트/NFS 배포 필요 발생 시 착수) | +| **FW-N5** | Update `job-protocol.md` security protocol spec (to HMAC signatures) | P1 (High) | Small (Doc) | **Documentation/Design Consistency**: Fix the official protocol document which incorrectly guides users to use an insecure plaintext token transmission scheme (`data.auth_token`), aligning it with the actually implemented HMAC signature scheme. | None (conduct in parallel with FW-N6) | +| **FW-N6** | Support auto-generated `auth_token` and CLI integration in `registry.py` | P1 (High) | Small~Medium | **Activate Security Features**: Resolve the bug where all jobs registered via CLI (`registry.py register`) have `auth_token` set to `null` (unauthenticated mode), which bypasses HMAC security. Add the `--auth-token` argument to the CLI, and automatically generate a token when a secure environment (TLS/Username, etc.) is detected. | None (Highest Priority) | +| **FW-N7** | Prevent Replay Attacks via sequence monotonic increase validation in `job_subscriber.py` | P2 (Medium) | Small~Medium | **Security Hardening (Defense in Depth)**: To prevent cryptographically signed non-terminal events (`progress`, `permission_required`) from being intercepted on the network and retransmitted (Replay Attack), add logic to verify that the sequence number (`seq`) of incoming messages is monotonically increasing. | **FW-N6 is a prerequisite** (only meaningful after authentication/HMAC is active) | +| **FW-L4** | Migrate Job Registry to SQLite to overcome NFS flock limitations | P3 (Low) | Large | **Concurrency/Infrastructure Scalability**: Similar to the Session Registry, migrate the individual JSON file lock (`fcntl.flock`) registry structure into an integrated SQLite database transaction structure, guaranteeing full reliability in distributed/network file systems like NFS. | **Conditional** (commence only when multi-host/NFS deployment is required) | --- -### 세부 논의 결과 및 방향성 (Reviewer 합의 사항) +### Detailed Discussion Results & Directions (Reviewer Consensus) -1. **HMAC 보안 활성화를 위한 R2(FW-N6) 우선 해결**: - * 현재 구현된 HMAC 서명 코드(Verify/Sign)는 실재하지만, 정상적인 CLI 경로로 잡을 등록할 때는 암호화 토큰을 생성 또는 주입할 방법이 전무해 강제로 무인증 PoC 모드로 실행됩니다. 따라서 **FW-N6**가 모든 보안 개선의 선행 고리입니다. -2. **문서 동기화(FW-N5)**: - * 문서가 안전하지 않은 설계(평문 전송)를 가이드하고 있으므로 개발 혼선을 막기 위해 즉각 수정합니다. -3. **Replay 공격 방어(FW-N7)의 범위**: - * 시퀀스 단조 증가 검사(`last_seq` 추적)를 수신단에 구현하되, 가입자(`job_subscriber.py`) 재시작 시의 `last_seq` 초기화 예외 처리 및 터미널 이벤트 중복 제어와의 연계를 정밀히 검토해야 합니다. -4. **SQLite 통합(FW-L4)의 조건부 연기**: - * 세션 레지스트리와 달리 개별 잡 데이터는 JSON 파일 구조가 관리 및 디버깅 직관성이 우수하며, 현재 배포 환경은 단일 호스트 로컬 FS로 제한되어 있어 `fcntl.flock` 잠금만으로 안전하게 운용 가능하므로 낮은 우선순위(P3)로 배정하고 필요 시 착수합니다. \ No newline at end of file +1. **Prioritize R2 (FW-N6) to Enable HMAC Security**: + * Although the HMAC signature code (verify/sign) is implemented, registering a job via the normal CLI lacks a way to generate or inject a cryptographic token, forcing jobs into unauthenticated PoC mode. Thus, **FW-N6** is the prerequisite for all security improvements. +2. **Document Synchronization (FW-N5)**: + * Since the current document details an insecure design (plaintext token transmission), it should be updated immediately to prevent development confusion. +3. **Scope of Replay Attack Prevention (FW-N7)**: + * Implement sequence monotonic check (`last_seq` tracking) on the receiving side. Pay careful attention to handling subscriber restarts (initializing `last_seq`) and coordinate this with terminal event duplicate controls. +4. **Conditional Deferral of SQLite Integration (FW-L4)**: + * Unlike the session registry, maintaining individual job data in JSON files is highly intuitive for management and debugging. Since the current deployment is constrained to a single-host local file system, `fcntl.flock` locks are sufficient. Thus, this is assigned a low priority (P3) and will be tackled conditionally. \ No newline at end of file