docs: add README.md and README.ko.md introducing the orchestration skills and backplane architecture

This commit is contained in:
2026-06-22 14:19:15 +09:00
parent 9735258bc5
commit ee48d77d0a
2 changed files with 270 additions and 1 deletions
+136
View File
@@ -0,0 +1,136 @@
# tmux-agent-orchestration (다중 에이전트 Tmux 오케스트레이션 및 메시징 백플레인)
Tmux와 MQTT 브로커를 기반으로 구축된 고신뢰성 **다중 에이전트 오케스트레이션 및 메시징 백플레인** 프레임워크입니다. Claude, Hermes 등 다중 LLM 백엔드 에이전트 전반에 걸쳐 장시간 수행되는 작업(코드 생성, 리팩토링, 보안 검토 등)을 조정, 격리 및 감사할 수 있도록 설계되었습니다.
---
## 🚀 개요
최근의 에이전트 워크플로우는 세션 타임아웃, 프로세스 격리 부재, 터미널 뷰포트 잘림(스크롤백 한계로 인한 디버그 로그 유실), 복잡한 동시성 경쟁 등의 문제를 자주 겪습니다.
**tmux-agent-orchestration**은 다음과 같은 솔루션을 통해 이를 해결합니다:
1. **Tmux 기반 프로세스 격리:** 개별적으로 격리된 tmux 환경 내부에 에이전트 CLI 세션을 띄워, 백그라운드에서 끊김 없이 장시간 작업이 영속되도록 보장합니다.
2. **비동기 이벤트 기반 아키텍처:** MQTT 브로커를 메시징 백플레인으로 활용하여, 에이전트 간 상태 전이 단계(`started`, `progress`, `completed`, `error`)를 긴밀하게 제어 및 조정합니다.
3. **Multi-Agent Mux (MAM):** 파일 기반의 어드바이저리 락(`fcntl`) 및 SQLite WAL 데이터베이스(`.mam/agent-sessions.db`)를 결합하여, 동시성 작업 선점 경쟁을 방지하고 에이전트 세션의 라이프사이클을 드리프트 없이 관리합니다.
4. **리뷰어 기반 고신뢰 검증 루프:** Worker 에이전트가 구현한 코드 변경 사항에 대해 상이한 강점을 지닌 전문 검증 에이전트(예: 논리 흐름을 정밀 검토하는 Claude, 셸 문법 및 안전성을 빠르게 확인하는 Hermes)들로부터 최종 `PASS` 판정을 획득한 뒤 머지하도록 교차 검증 루프를 자동화합니다.
---
## 🛠️ 핵심 스킬 및 구조
모든 오케스트레이션 스킬들은 `.agents/skills/` 디렉터리 하위에 정의되어 있습니다:
* **`tmux-agent-orchestrate-create`**: 격리된 tmux 세션을 생성하고 특정 에이전트 CLI를 백그라운드에서 구동합니다. 프로세스 PID 캡처, 메타데이터 레지스트리 업데이트 및 에이전트 인증 검증을 처리합니다.
* **`tmux-agent-orchestrate-stop`**: 에이전트 CLI 세션을 정상 종료 키 입력(`/exit` 또는 `Exit`)을 통해 안전하게 닫고, 격리된 대화 히스토리 및 데이터베이스 로그를 삭제(purge)하는 클린업 작업을 수행합니다.
* **`tmux-agent-orchestrate-resume`**: 디스크 또는 캐시에서 특정 워크스페이스의 세션 UUID를 조회하여 기존 대화 상태(`claude -r <uuid>` 또는 `hermes --resume <uuid>`) 그대로 세션을 복구하고 재개합니다.
* **`tmux-agent-orchestrate-status`**: 활성화된 모든 세션의 실시간 작동 상태를 쿼리하여 PID 정합성, 실행 명령 포맷, tmux 실제 상태와 데이터베이스 간의 동기화 드리프트를 감지합니다.
* **`tmux-agent-orchestrate-monitor`**: 백그라운드에서 Kanban Reconcile 프로세스로 실행되어, 실시간 tmux 세션 변화를 모니터링하고 `.mam/agent-sessions.yaml` 메타데이터 파일에 상태를 동기화합니다.
* **`tmux-agent-orchestrate-delegate-job`**: 태스크를 비동기식 독립 잡으로 위임 및 관리하는 핵심 모듈입니다:
* `registry.py`: 파일 락(`fcntl`)을 활용해 경쟁 조건 없이 잡을 원자적으로 등록 및 점유(claim)합니다.
* `job_subscriber.py`: MQTT 백플레인 채널을 구독하여 실시간 상태 이벤트를 수집하고 이를 감사 로그(audit trail)에 기록합니다.
* `publish_event.py`: 실행 상태 전환 및 세부 에러 내용을 워크스페이스 스크립트에서 백플레인으로 발행합니다.
* `mqtt_common.py`: 브로커 접속 규칙, 크레덴셜 인증 및 HMAC 서명 기능을 공통 관리합니다.
---
## 📐 아키텍처 및 조정 루프 (Review Loop)
Project Manager(PM), Worker, Reviewer 역할 간의 협업 구조는 엄격한 교차 검증 루프를 따릅니다:
```mermaid
sequenceDiagram
autonumber
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: 태스크 수립 및 Job 등록
PM->>M: Job 등록 및 Subscriber 시작
PM->>W: 작업 위임 (Job ID 및 가이드 제공)
W->>M: 'started' 이벤트 발행
Note over W: 코드 변경 및 자체 검증 수행
W->>M: 'completed' (또는 'error') 발행
PM->>R: 병렬 리뷰 요청 (Diff 제공)
Note over R: 에이전트 교차 검증 (Claude, Hermes)
alt 리뷰 피드백 (NOT PASS)
R->>PM: NOT PASS (대안 코드 블록과 함께 피드백 전달)
Note over PM: PM 직접 수정 또는 다시 위임 결정
PM->>W: 리뷰 피드백 반영 재요청
else 검증 통과 (PASS)
R->>PM: PASS
end
PM->>User: 최종 머지 완료 보고 및 변경사항 커밋
```
---
## 🔒 보안 프로토콜 및 Replay 공격 방어
공용 MQTT 브로커 환경에서도 통신의 무결성을 보장하기 위해 **HMAC-SHA256 암호화 서명** 체계를 갖추고 있습니다:
* **PoC 모드 (무인증):** 기본 설정 모드로 `auth_token``null`로 세팅되어 간단한 로컬 환경 검증 시 암호화 시그니처 체크를 건너뜁니다.
* **프로덕션 모드 (인증 필수):** 각 잡마다 무작위 암호화 토큰이 발급되며, 백플레인을 오가는 모든 페이로드에 토큰 기반으로 생성된 `hmac_sig` 서명을 탑재해야 수신측에서 수용합니다.
* **Replay 공격 방어:** 각 이벤트는 단조 증가하는 정수형 시퀀스 번호(`seq`)를 포함합니다. 구독자(`job_subscriber.py`)는 특정 잡에 대해 이미 수용한 최대 시퀀스 번호보다 크지 않은 시퀀스 번호를 가진 페이로드를 즉시 폐기합니다. 페이로드 바디에 대한 HMAC 서명과 결합하여, 이 메커니즘은 클록 동기화에 의존하지 않고 재전송(re-injected) 및 순서가 바뀐 패킷을 차단합니다. 메시지 내 타임스탬프 필드는 참고용 메타데이터이며, 백플레인은 시간 오차(clock-skew) 윈도우를 별도로 검증하지 않습니다.
---
## 📁 리포지토리 구성
```text
.
├── .agents/
│ └── skills/ # 코어 오케스트레이션 셸 스크립트 및 라이브러리
│ ├── lib.sh # 공통 오케스트레이션 셸 함수 라이브러리
│ ├── tmux-agent-orchestrate-create/
│ ├── tmux-agent-orchestrate-stop/
│ ├── tmux-agent-orchestrate-resume/
│ ├── tmux-agent-orchestrate-status/
│ ├── tmux-agent-orchestrate-monitor/
│ └── tmux-agent-orchestrate-delegate-job/
│ ├── requirements.txt # 파이썬 의존성 패키지 선언
│ └── scripts/ # 파이썬 기반 백플레인 구현체
├── .mam/ # Multi-Agent Mux 메타데이터 (git-ignored)
│ ├── agent-sessions.db # SQLite WAL 세션 데이터베이스
│ ├── agent-sessions.yaml # 텍스트 형식의 세션 레지스트리 스냅샷
│ └── jobs/ # 비동기 잡 메타데이터 JSON 파일들
├── scripts/
│ └── generate-env.sh # 환경 파일(.env) 템플릿 복사 스크립트
├── AGENT.ko.md # 에이전트 역할 행동 강령 (한국어 백업)
├── AGENT.md # 에이전트 역할 행동 강령 및 뷰포트 스냅샷 규칙
├── BOOTSTRAP.ko.md # 프로젝트 초기 설치 가이드 (한국어 백업)
├── BOOTSTRAP.md # 프로젝트 초기 설치 및 검증 상세 가이드
├── MESSAGING.md # MQTT 메시징 프로토콜 와이어 규격서
└── README.md # 프로젝트 대표 소개 파일
```
---
## 🚦 빠른 시작
자세한 빌드 절차는 **[BOOTSTRAP.md](./BOOTSTRAP.md)** 문서를 참조하십시오. 아래는 간략한 요약입니다:
1. **환경 설정 파일(.env) 생성:**
```bash
./scripts/generate-env.sh
```
2. **가상환경 생성 및 의존성 패키지 설치:**
```bash
python3 -m venv .venv
source .venv/bin/activate
pip install -r .agents/skills/tmux-agent-orchestrate-delegate-job/requirements.txt
```
3. **레지스트리 및 환경 작동 자가 검증:**
```bash
.venv/bin/python3 .agents/skills/tmux-agent-orchestrate-delegate-job/scripts/registry.py list
```
---
## 📝 협업 에이전트 준수 사항
이 프로젝트에 새로 합류한 에이전트는 다음 규칙을 준수해야 합니다:
1. **[AGENT.md](./AGENT.md)** 문서를 정독하여 프로젝트 매니저(PM), 작업자(Worker), 리뷰어(Reviewer) 간의 역할 및 개발 제약조건을 인지하십시오.
2. 장시간 명령을 실행하는 경우 터미널 스크롤백 로그 유실을 방지하기 위해 `AGENT.md` (제4장)에 기재된 **뷰포트 스냅샷 규칙(Pane Snapshotting Rules)**을 반드시 적용하십시오.
3. 리뷰어 세션에 diff 검증을 요청하기 전에는 어떠한 코어 파일의 임의 수정도 프로덕션 브랜치에 승인 없이 머지할 수 없습니다.
+134 -1
View File
@@ -1 +1,134 @@
# README.md # tmux-agent-orchestration
An advanced, high-reliability **Multi-Agent Orchestration & Messaging Backplane** framework built on Tmux and MQTT. It is designed to coordinate, isolate, and audit long-running agent tasks (such as code generation, refactoring, and security reviews) across multiple LLM backend clients (e.g., Claude, Hermes).
---
## 🚀 Overview
Modern agentic workflows often suffer from session timeout, lack of process isolation, terminal viewport truncation (scrollback limits), and complex concurrency issues.
**tmux-agent-orchestration** addresses these problems by providing:
1. **Tmux-based Process Isolation:** Spawning LLM client sessions inside dedicated, isolated tmux environments to support persistent background runs.
2. **Asynchronous Event-Driven Architecture:** Leveraging an MQTT broker as a message backplane to coordinate state transitions (`started`, `progress`, `completed`, `error`) between collaborating agents.
3. **Multi-Agent Mux (MAM):** Combining local file-based locks (fcntl) and an ACID-compliant SQLite WAL database (`.mam/agent-sessions.db`) to manage concurrent job claims and track running agent sessions without drift.
4. **Automated Review & Quality Loop:** Implementing parallel reviewer loops where worker agents must receive a `PASS` rating from various specialized verification agents (e.g., Claude for high-level logic, Hermes for shell syntax/safety) before merging code.
---
## 🛠️ Core Skills & Scaffolding
All orchestration functionalities are structured under the `.agents/skills/` directory:
* **`tmux-agent-orchestrate-create`**: Spawns isolated tmux sessions running specified agent CLI wrappers. It captures system processes, updates metadata registries, and enforces authentication checks.
* **`tmux-agent-orchestrate-stop`**: Gracefully terminates agent CLI sessions (using key macros like `/exit` or `Exit`) and handles disk purge operations (removing conversation JSON files and SQLite logs for deleted workspaces).
* **`tmux-agent-orchestrate-resume`**: Restores stopped sessions by resolving workspace UUIDs from disk or cache, and invokes the underlying agent using session-resume parameters (e.g., `claude -r <uuid>` or `hermes --resume <uuid>`).
* **`tmux-agent-orchestrate-status`**: Queries the running states of all active sessions, detecting PID mismatches, command signatures, and drifts between actual tmux instances and the registry database.
* **`tmux-agent-orchestrate-monitor`**: A long-running Kanban reconcile worker that dynamically monitors tmux sessions and synchronizes states to `.mam/agent-sessions.yaml`.
* **`tmux-agent-orchestrate-delegate-job`**: The core asynchronous task distribution module containing:
* `registry.py`: Atomically registers and claims jobs using file advisory locks (`fcntl`).
* `job_subscriber.py`: Connects to the MQTT backplane, captures live events, and appends them to audit trails.
* `publish_event.py`: Emits execution status transitions and error details from workspace scripts.
* `mqtt_common.py`: Manages connection policies, authentication, and HMAC signing.
---
## 📐 Architecture & Coordination Loop
The interaction between roles (Project Manager, Worker, and Reviewer) is structured as a strict iterative loop:
```mermaid
sequenceDiagram
autonumber
actor User as User
participant PM as Project Manager
participant W as Worker
participant R as Reviewers
participant M as MQTT Backplane
User->>PM: Hand over requirements
Note over PM: Plan tasks & register jobs
PM->>M: Register Job & start Subscriber
PM->>W: Delegate task (Provide Job ID & Brief)
W->>M: Publish 'started' event
Note over W: Implement & verify code
W->>M: Publish 'completed' (or 'error')
PM->>R: Request parallel reviews (Provide Diff)
Note over R: Parallel analysis (Claude, Hermes)
alt Review Feedback (NOT PASS)
R->>PM: NOT PASS (Feedback with code blocks)
Note over PM: Apply fixes or re-delegate
PM->>W: Re-delegate with comments
else Verification PASS
R->>PM: PASS
end
PM->>User: Commit changes & Report completion
```
---
## 🔒 Security & Replay Attack Defense
To ensure communication integrity across public MQTT brokers, the backplane integrates an **HMAC-SHA256 signature protocol**:
* **PoC Mode (Unauthenticated):** Default mode where `auth_token` is `null`, skipping cryptographic validations for quick setups.
* **Production Mode (Authenticated):** A unique cryptographic token is issued per job. Event payloads must include an `hmac_sig` computed with the token.
* **Replay Attack Mitigation:** Each event carries a monotonically increasing integer sequence counter (`seq`). The subscriber (`job_subscriber.py`) drops any payload whose sequence number is not strictly greater than the highest sequence number it has already accepted for that job. Combined with the HMAC signature on the payload body, this rejects both re-injected and out-of-order packets without relying on clock synchronization. The wire-format timestamp field is advisory metadata only; the backplane does not enforce a clock-skew window.
---
## 📁 Repository Layout
```text
.
├── .agents/
│ └── skills/ # Core orchestration shell wrappers & libraries
│ ├── lib.sh # Shared orchestration library
│ ├── tmux-agent-orchestrate-create/
│ ├── tmux-agent-orchestrate-stop/
│ ├── tmux-agent-orchestrate-resume/
│ ├── tmux-agent-orchestrate-status/
│ ├── tmux-agent-orchestrate-monitor/
│ └── tmux-agent-orchestrate-delegate-job/
│ ├── requirements.txt # Python dependency declaration
│ └── scripts/ # Core backplane implementation (Python)
├── .mam/ # Multi-Agent Mux metadata (git-ignored)
│ ├── agent-sessions.db # SQLite WAL session database
│ ├── agent-sessions.yaml # Human-readable session registry
│ └── jobs/ # Asynchronous job metadata files
├── scripts/
│ └── generate-env.sh # Environment bootstrap helper
├── AGENT.md # Agent roles, snapshottings, and execution charter
├── BOOTSTRAP.md # Detailed installation and verification guide
├── MESSAGING.md # MQTT wire protocol specification
└── README.md # Project introduction and overview (this file)
```
---
## 🚦 Quick Start
For detailed setup instructions, please consult the **[BOOTSTRAP.md](./BOOTSTRAP.md)** file. Below is a quick summary:
1. **Initialize Environment Config:**
```bash
./scripts/generate-env.sh
```
2. **Create Virtual Environment and Install Dependencies:**
```bash
python3 -m venv .venv
source .venv/bin/activate
pip install -r .agents/skills/tmux-agent-orchestrate-delegate-job/requirements.txt
```
3. **Run Registry Diagnostics:**
```bash
.venv/bin/python3 .agents/skills/tmux-agent-orchestrate-delegate-job/scripts/registry.py list
```
---
## 📝 Guidelines for Collaborating Agents
If you are an AI agent newly onboarded to this project:
1. Read **[AGENT.md](./AGENT.md)** to align on development constraints and roles (PM, Worker, Reviewer).
2. Adhere to the **Pane Snapshotting Rules** in `AGENT.md` (Section 4) to prevent scrollback data loss during long execution steps.
3. Never modify core logic without submitting a diff to the reviewer sessions for evaluation.