diff --git a/.agents/reports/canary-projects-multi-agent-mux-creator-cline/report-9c44c6b2.md b/.agents/reports/canary-projects-multi-agent-mux-creator-cline/report-9c44c6b2.md new file mode 100644 index 0000000..f5cca67 --- /dev/null +++ b/.agents/reports/canary-projects-multi-agent-mux-creator-cline/report-9c44c6b2.md @@ -0,0 +1,114 @@ +# Cross Code Review — Job 9c44c6b2 + +- **Reviewer**: cline (session: `canary-projects-multi-agent-mux-creator-cline`, role: `reviewer`) +- **Job ID**: 9c44c6b2 +- **Task**: Review and verify final `OPTIMIZATION.md` specification for `multi-agent-mux-loop` improvements +- **Scope**: Accumulated `git diff` (working-tree changes vs `HEAD`) + new untracked `OPTIMIZATION.md` +- **Date**: 2026-08-02 + +--- + +## 1. Changeset Summary + +The working tree contains 19 changed files (`52 insertions, 1279 deletions`): + +| Category | Files | Nature | +| :--- | :--- | :--- | +| **New specification** | `OPTIMIZATION.md` (untracked) | New analysis doc defining 9 issues + resolutions for `multi-agent-mux-loop` | +| **Doc fix (spec ↔ doc alignment)** | `.agents/skills/multi-agent-mux-loop/SKILL.md` | Removes the erroneous `--all-reviewer` from the example that combined it with `--reviewer`; adds explicit "상호 배타적" (mutually exclusive) note | +| **Legacy terminology cleanup** | `README.md`, `README.ko.md`, `BOOTSTRAP.md`, `BOOTSTRAP.ko.md`, `MESSAGING.md` | `tmux` → `herdr` wording migration across user-facing docs | +| **Obsolete doc deletion** | `CLAUDE_WORK_LOGS.md`, `DONE.md`, `DONE.ko.md`, `FUTURE_WORKS.md`, `FUTURE_WORKS.ko.md`, `PLAN_HERDR.md`, `PLAN_LOOP.md`, `RECOMMENDED.md`, `REPORT.md`, `SKILL_FEATURES.md`, `TEST_INFRA.md`, `TEST_READY.md`, `mam_delegate_job_role_issue_report.md` | Removal of 13 superseded/archived markdown files | + +No runtime shell/Python source under `.agents/skills/*/scripts/` is modified in this changeset — the loop skill's behavior code (`run_loop.sh`) is unchanged. + +--- + +## 2. Lint & Syntax Verification + +| Check | Target | Result | +| :--- | :--- | :--- | +| `bash -n` syntax | `.agents/skills/multi-agent-mux-loop/scripts/run_loop.sh` | ✅ `syntax OK` (no syntax errors) | +| `shellcheck` | `run_loop.sh` | ⚠️ not installed in environment — cannot run static analysis; flagging as a verification gap, not a defect | +| Markdown structure | `OPTIMIZATION.md` | ✅ Well-formed headings, fenced blocks, tables; consistent Korean/English bilingual style | +| Internal cross-references | `SKILL.md` ↔ `OPTIMIZATION.md` | ✅ ISSUE-1 SKILL.md edit matches the "상호 배타적" wording introduced in `OPTIMIZATION.md` §1.ISSUE-1 | + + +--- + +## 3. Operability & Spec ↔ Implementation Consistency Analysis + +This is a **specification document review**, not a runtime code review. The central question is whether `OPTIMIZATION.md` is a coherent, implementable, and internally consistent spec, and whether the accompanying doc edits correctly align the existing `SKILL.md`/READMEs with it. + +### 3.1 ✅ SKILL.md fix is correct and self-consistent (ISSUE-1 doc half) +The `SKILL.md` edit removes the contradictory `--all-reviewer` line from the example that simultaneously passed `--reviewer "A,B"`, and adds an explicit mutual-exclusivity note to the Phase 3: Consensus row. This directly implements the *documentation* portion of OPTIMIZATION.md ISSUE-1 item 2 ("`SKILL.md` 문서 내의 옵션 예시 ... 정정"). The fix is surgical — only the conflicting lines changed, surrounding text untouched. **Pass.** + +### 3.2 ⚠️ SPEC GAP — ISSUE-1 code enforcement is *not* implemented (fail-fast missing) +`OPTIMIZATION.md` ISSUE-1 item 1 mandates: *"파라미터 파싱 단계에서 상호 배타적인 옵션이 포함된 경우 ... 즉시 에러(`exit 1`)를 반환하도록 검증 로직 강화."* + +However, the actual `run_loop.sh` (lines 99–107) still only **warns** and proceeds: +```bash +# --all-reviewer silently takes precedence over an explicit --reviewer list; warn ... (P2-1). +if [ "$ALL_REVIEWERS" = true ] && [ -n "$REVIEWER_LIST" ]; then + log_warn "--all-reviewer takes precedence; ignoring --reviewer list ('$REVIEWER_LIST')." +fi +if [ "$PLAN_TALK_TURNS" -gt 0 ] && [ "$PLAN_MODE" = false ]; then + log_warn "--plan-talk was specified but --plan mode is not enabled. Discussion turns will be ignored." +fi +``` +This is the *exact* "경고만 출력하고 무시" (warn-only) behavior OPTIMIZATION.md §1.ISSUE-1 identifies as the problem and resolves with `exit 1`. The spec is therefore **defining future work**, not describing an already-shipped fix. This is acceptable for a specification document, but the SKILL.md wording now states the options are "상호 배타적" while the code still silently allows both — a **doc/code divergence** that the spec itself flags as the very class of bug it intends to close. + +**Direction (Reviewer per MULTI_AGENT_RULES §1 — must give concrete, verified alternative):** +The spec is sound; the implementation gap is expected because this changeset ships the *spec + doc alignment*, not the code enforcement. To close the loop in a follow-up Creator iteration, `run_loop.sh` lines 99–107 should become hard failures: +```bash +if [ "$ALL_REVIEWERS" = true ] && [ -n "$REVIEWER_LIST" ]; then + log_error "--all-reviewer and --reviewer are mutually exclusive. Aborting." + exit 1 +fi +if [ "$PLAN_TALK_TURNS" -gt 0 ] && [ "$PLAN_MODE" = false ]; then + log_error "--plan-talk requires --plan. Aborting." + exit 1 +fi +``` +This is a stable, minimal patch that fulfills ISSUE-1 item 1 without altering any other control flow. **Not a blocker for this spec review** — but should be tracked as the first ticket off this spec. + +### 3.3 ✅ ISSUE-2 (legacy tmux terminology) — fully executed in this diff +`BOOTSTRAP.md`, `BOOTSTRAP.ko.md`, `README.md`, `README.ko.md`, `MESSAGING.md` all migrate `tmux` → `herdr` consistently (e.g. `Tmux Workspace` → `Herdr Workspace`, `Tmux Server Isolation` → `Herdr Server Isolation`, `_init_tmux_isolation` → `_init_herdr_isolation`). The renaming is uniform across the English/Korean pairs. **Pass.** + +### 3.4 ✅ ISSUE-3 through ISSUE-9 — defined as spec, not yet implemented (by design) +`OPTIMIZATION.md` §2–§3 define ISSUE-3 (verdict format mechanical validation), ISSUE-4 (`dod_changed_paths` + atomic-commit gate), ISSUE-5 (`[AGREEMENT: REACHED]` early-break), ISSUE-6 (review-rebuttal channel), ISSUE-7 (PID+lstart+workspace triple lock), ISSUE-8 (alive-ping fail-fast), ISSUE-9 (skill-invocation guardrail). + +A `grep` of `run_loop.sh` confirms none of `dod_changed_paths`, `AGREEMENT`, `REACHED`, or `lstart` are present in the current code — i.e. these are **forward-looking spec items**, correctly scoped as a specification. Each issue statement follows a consistent *현상 → 문제점 → 해결 방안* structure with concrete, implementable directions. No issue is left without a remediation path. **Pass as a specification.** + +### 3.5 ✅ No data-loss / orphan risk in the doc deletions +The 13 deleted markdown files are archived dev logs / superseded plans (e.g. `DONE.md`, `PLAN_LOOP.md`, `REPORT.md`, `mam_delegate_job_role_issue_report.md`). They contain no runtime config or referenced anchors. A spot check confirms: +- No `.agents/skills/*/scripts/` source references these deleted files. +- `README.md`/`SKILL.md` do not link to the deleted docs (the only internal links point to live files: `BOOTSTRAP.md`, `MESSAGING.md`, `MULTI_AGENT_RULES.md`). +- Their content (FW-W* future-work items, the role-issue report) is either absorbed into `OPTIMIZATION.md` or is purely historical. + +Removing them is safe and reduces root clutter (aligns with the repo layout note that `.agents/` is the canonical home for protocol docs). **Pass.** + +--- + +## 4. Issues Found (non-blocking, for follow-up tracking) + +| # | Severity | Finding | Recommended Direction | +| :--- | :--- | :--- | :--- | +| R-1 | Low | `run_loop.sh` lines 99–107 still warn-only; contradicts the now-stated "상호 배타적" spec | Convert to `exit 1` per ISSUE-1 item 1 (patch shown in §3.2) | +| R-2 | Low | Untracked stray file `.agents/skills/multi-agent-mux-delegate-job/multi-agent-mux-delegate-job.17678_23708.tmp` present in the working tree and **not covered by `.gitignore`** (no `*.tmp` rule exists) | Add `*.tmp` (or the delegate-job tmp glob) to `.gitignore` and remove the stray file; prevents accidental commit of orchestrator scratch state | +| R-3 | Info | `shellcheck` not available in this environment — static-analysis gap for shell skills | Recommend installing `shellcheck` in CI/dev image; the repo's `deploy/gitea-ci.yml` already intends shellcheck coverage (per `FW-D4` notes) | + +None of R-1..R-3 are blocking defects in the *specification* under review. R-1 is the spec's own next implementation step; R-2 is a hygiene nit outside the `OPTIMIZATION.md` scope; R-3 is an environment limitation, not a code defect. + +--- + +## 5. Verdict + +The `OPTIMIZATION.md` final specification is: +- **Internally consistent** — every issue has a 현상/문제점/해결 방안 triad with a concrete, implementable direction. +- **Lint-clean** — `bash -n` passes on the referenced `run_loop.sh`; markdown is well-formed. +- **Doc-aligned** — the shipped `SKILL.md` edit correctly resolves the documentation half of ISSUE-1, and the legacy tmux→herdr cleanup fully executes ISSUE-2. +- **Loss-free** — deleted obsolete docs are not referenced by any live code/doc; no orphan links introduced. + +The single spec↔code divergence (R-1: warn-only vs. mandated `exit 1`) is *the very gap the spec exists to close* and is correctly scoped as follow-up implementation work, not a defect in the specification itself. No redesign/replanning is required; the spec is ready to drive the next Creator implementation iteration. + +[VERDICT: PASS] \ No newline at end of file diff --git a/.agents/skills/multi-agent-mux-loop/SKILL.md b/.agents/skills/multi-agent-mux-loop/SKILL.md index 8aa27ce..b08b32c 100644 --- a/.agents/skills/multi-agent-mux-loop/SKILL.md +++ b/.agents/skills/multi-agent-mux-loop/SKILL.md @@ -164,7 +164,7 @@ sequenceDiagram | **Phase 1: Debate** | `--plan-talk N` | Planner와 Creator가 상호 대화식 챌린지 루프를 `N`회 돌며 계획을 교차 정제합니다. | | **Phase 2: Execution** | (기본값) | `--target-agent`로 명시한 주 작업 세션에 코딩 태스크를 주입합니다. | | **Phase 3: Review** | `--reviewer "A,B"` | 지정된 리뷰어 세션 리스트(`A`, `B` 등)에 교차 Peer Review를 위임합니다. | -| **Phase 3: Consensus** | `--all-reviewer` | 레지스트리에 등록된 모든 active 리뷰어 세션을 자동으로 수집하여 리뷰를 돌립니다. (지정/수집된 모든 리뷰어의 PASS 만장일치가 항상 필요합니다.) | +| **Phase 3: Consensus** | `--all-reviewer` | 레지스트리에 등록된 모든 active 리뷰어 세션을 자동으로 수집하여 리뷰를 돌립니다. (`--reviewer` 옵션과는 상호 배타적이며, 지정/수집된 모든 리뷰어의 PASS 만장일치가 항상 필요합니다.) | | **Iterative Loop** | `--max-loop M` | NOT PASS 판정 시 최대 `M`회까지 Creator가 자체 수정합니다. `--plan` 모드에서 리뷰어가 리포트에 `[ESCALATE: PLANNER]` 태그를 남기면 설계 변경 수준으로 판단하여 Planner에게 계획 갱신을 위임합니다 (린트는 리뷰어가 검토 관점 중 하나로 확인할 뿐, 별도의 자동 게이트는 아닙니다). | --- @@ -178,12 +178,11 @@ bash .agents/skills/multi-agent-mux-loop/scripts/run_loop.sh \ --task "Fix typo in deploy/README.md" # 2. Collaborative planning + Targeted Reviewers + Safety limits -# (실전 자율 루프 기동의 표준 패턴 — 리뷰어 2인 지정 + 전원 합의 + 최대 3회 반복) +# (실전 자율 루프 기동의 표준 패턴 — 리뷰어 2인 지정 + 최대 3회 반복) bash .agents/skills/multi-agent-mux-loop/scripts/run_loop.sh \ --plan \ --plan-talk 1 \ --reviewer "," \ - --all-reviewer \ --max-loop 3 \ --verbose \ --target-agent "" \ diff --git a/BOOTSTRAP.ko.md b/BOOTSTRAP.ko.md index 99d9880..eae2285 100644 --- a/BOOTSTRAP.ko.md +++ b/BOOTSTRAP.ko.md @@ -1,6 +1,6 @@ # BOOTSTRAP.md -본 문서는 `tmux_agent_orchestration` 오케스트레이션 및 메시징 백플레인 워크플로우를 새로운 프로젝트에 도입하여 이식하고, 새로운 개발자/에이전트가 초기 가동을 시작할 때 수행해야 하는 환경 설정 및 구축 절차를 안내합니다. +본 문서는 `herdr_agent_orchestration` 오케스트레이션 및 메시징 백플레인 워크플로우를 새로운 프로젝트에 도입하여 이식하고, 새로운 개발자/에이전트가 초기 가동을 시작할 때 수행해야 하는 환경 설정 및 구축 절차를 안내합니다. 새로운 에이전트는 이 안내서에 기술된 절차를 순차적으로 실행하여 초기 환경을 안정적으로 설정할 수 있습니다. @@ -15,11 +15,11 @@ * `MULTI_AGENT_RULES.ko.md`: 에이전트 간의 역할 분담(PM, Worker, Reviewer) 및 이벤트 발행 규약 정의 (한국어) * `skills/`: 멀티 에이전트 구동 및 비동기 잡 처리를 수행하는 셸 스크립트 모음 * `lib.sh`: 오케스트레이션의 핵심 셸 함수 및 가상환경(venv) 자동 연동 라이브러리 - * `multi-agent-mux-create/`: 격리된 tmux 에이전트 세션을 시작하는 스크립트 + * `multi-agent-mux-create/`: 격리된 herdr 에이전트 세션을 시작하는 스크립트 * `multi-agent-mux-stop/`: 세션을 정상적으로 중지하고 상태를 업데이트하는 스크립트 * `multi-agent-mux-resume/`: 중지된 에이전트 세션을 이전 대화 상태 그대로 복원하는 스크립트 * `multi-agent-mux-status/`: 전체 에이전트 세션의 현재 구동 상태를 조회하는 스크립트 - * `multi-agent-mux-monitor/`: tmux 상태와 레지스트리 상태를 동기화하는 모니터 스크립트 + * `multi-agent-mux-monitor/`: herdr 상태와 레지스트리 상태를 동기화하는 모니터 스크립트 * `multi-agent-mux-delegate-job/`: 비동기 잡 분할 실행 모듈 * `requirements.txt`: Python 의존성 목록 (paho-mqtt, pyyaml) * `scripts/`: 핵심 비즈니스 로직을 구동하는 Python 스크립트 디렉터리 @@ -182,4 +182,4 @@ rm -f ".mam/jobs/$JID.json" ".mam/jobs/$JID.lock" 본 환경 구축을 무사히 마쳤다면, 협업하는 에이전트는 즉시 .agents/ 디렉터리에 있는 **[MULTI_AGENT_RULES.ko.md](.agents/MULTI_AGENT_RULES.ko.md)** 문서를 읽어야 합니다. -해당 문서에는 에이전트가 각 역할(PM, Worker, Reviewer)로 구동될 때 지켜야 할 **수술적 변경 규칙, 교차 검증 통과 규약, Tmux 뷰포트 유실 방지를 위한 스냅샷 패턴** 등이 서술되어 있어 안정적인 멀티 에이전트 워크플로우에 즉시 기여할 수 있도록 돕습니다. +해당 문서에는 에이전트가 각 역할(PM, Worker, Reviewer)로 구동될 때 지켜야 할 **수술적 변경 규칙, 교차 검증 통과 규약, Herdr 뷰포트 유실 방지를 위한 스냅샷 패턴** 등이 서술되어 있어 안정적인 멀티 에이전트 워크플로우에 즉시 기여할 수 있도록 돕습니다. diff --git a/BOOTSTRAP.md b/BOOTSTRAP.md index 277a725..b367354 100644 --- a/BOOTSTRAP.md +++ b/BOOTSTRAP.md @@ -1,6 +1,6 @@ # BOOTSTRAP.md -This document guides you through the setup and initialization procedures required to adopt the `tmux_agent_orchestration` orchestration and messaging backplane workflow in a new project, enabling a new developer or agent to get up and running quickly. +This document guides you through the setup and initialization procedures required to adopt the `herdr_agent_orchestration` 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. @@ -15,11 +15,11 @@ Before cloning this project into a new environment, you must first understand th * `MULTI_AGENT_RULES.ko.md`: Definition of agent roles (PM, Worker, Reviewer) and event publication rules (Korean). * `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. - * `multi-agent-mux-create/`: Script to launch isolated tmux agent sessions. + * `multi-agent-mux-create/`: Script to launch isolated herdr agent sessions. * `multi-agent-mux-stop/`: Script to gracefully stop agent sessions and update states. * `multi-agent-mux-resume/`: Script to restore stopped agent sessions back to their previous conversation state. * `multi-agent-mux-status/`: Script to query the current running state of all agent sessions. - * `multi-agent-mux-monitor/`: Monitor script to sync tmux states with the registry. + * `multi-agent-mux-monitor/`: Monitor script to sync herdr states with the registry. * `multi-agent-mux-delegate-job/`: Asynchronous job splitting and delegation module. * `requirements.txt`: Python dependency list (`paho-mqtt`, `pyyaml`). * `scripts/`: Python scripts running the core business logic. diff --git a/CLAUDE_WORK_LOGS.md b/CLAUDE_WORK_LOGS.md deleted file mode 100644 index 3e34b5b..0000000 --- a/CLAUDE_WORK_LOGS.md +++ /dev/null @@ -1,102 +0,0 @@ -# CLAUDE_WORK_LOGS.md - -작업 일자: 2026-07-19 -작업자: Claude (herdr 세션 `default:w3:p1`, `claude`) - -## 개요 - -`.agents/skills/` 아래 multi-agent-mux 스킬 세트가 tmux 시절 문법(`capture-pane`, `list-panes`, `kill-session`, `send-keys`, `session attach` 등)을 실제 herdr CLI 문법인 것처럼 잘못 사용하고 있던 문제를 발견하고 전수 조사·수정했다. 추가로 `HERDR_SERVER_NAME` 격리 기능이 진짜 herdr 서버 격리가 아니라 workspace label 흉내에 불과했던 것을 실제 `herdr --session ` 격리로 재설계했고, 프롬프트 주입 검증 로직(`send_keys_safe`)의 멀티바이트/줄바꿈 버그도 잡았다. 모든 수정은 herdr 실제 바이너리(v0.7.4) 대조 + 디스포저블 herdr 세션 실구동 테스트로 검증했으며, 일부는 실제 cline reviewer 에이전트(`canary-projects-multi-agent-mux-reviewer-cline`)에게 `multi-agent-mux-delegate-job`으로 위임하여 독립 교차검증(`[VERDICT: PASS]`)까지 받았다. - -커밋은 아직 하지 않았다 (전부 워킹 트리 변경 상태). - ---- - -## 1. 수정한 내용 - -### 1.1 `.agents/skills/lib.sh` (공유 라이브러리) - -- **`mam_herdr` shim의 `kill-session` 케이스**: `herdr session stop/delete "$sess"` (herdr의 `session`은 서버 전체 단위 개념이라 개별 에이전트 이름으로는 절대 못 찾음, 항상 조용히 실패) → `agent get`으로 `pane_id`를 먼저 해석한 뒤 `pane close `로 교체. -- **`send-keys` 케이스**: 동일하게 `pane send-keys "$sess" ...`(pane_id가 아니라 이름을 넘겨서 항상 실패)를 `agent get`으로 `pane_id` 선해석 후 `pane send-keys ...`로 교체. -- **`list-panes` 케이스**: JSON 경로가 `d.get('pane', d)`로 완전히 틀려있었음 (실제 응답은 `result.agent.{cwd, pane_id, agent}`) → cwd/cmd는 `agent get`에서, pid는 별도로 `pane process-info --pane `에서 조회하도록 재작성. 이 버그로 인해 `create_session.sh`/`update_yaml_resumed.sh`의 `PANE_PID`/`PANE_CWD`/`PANE_CMD` 캡처가 전부 항상 빈 값이었음. -- **`HERDR_SERVER_NAME` 격리를 진짜 herdr session 격리로 통일**: - - `_init_herdr_isolation`에 세션 부트스트랩 로직 추가 — `HERDR_SERVER_NAME != default`일 때 `herdr session list`로 확인 후 없으면 `herdr --session server`를 헤드리스로 백그라운드 기동 (인터랙티브 launch가 걸리는 "nested herdr is disabled" 제한을 회피). - - `_real_herdr()` 헬퍼 도입 — 모든 실제 herdr 호출에 `--session "$HERDR_SERVER_NAME"`를 자동 스코핑. - - `new-session` 케이스에서 기존의 "workspace label 매칭으로 격리 흉내"(진짜 격리가 전혀 아니었음, `agent list`가 서버 전역이라 아무 효과 없었음) 로직을 통째로 제거하고, 활성 세션 안에 fresh workspace를 만들도록 단순화. - - `resolve_herdr_workspace()` 단순화 — workspace_id를 찾던 로직 제거, YAML에 저장된 세션 라벨을 그대로 반환 (호출자 3곳 — resume/stop/update_yaml_resumed — 호환 유지를 위해 함수명은 유지). -- **`send_keys_safe()` paste 검증 로직 버그 2건 수정**: - 1. 마커를 `tail -c 24`(바이트 기준)로 잘라서 한글 등 멀티바이트 UTF-8 문자를 중간에서 자를 위험 → `python3` 문자 기준 슬라이싱(`[-24:]`)으로 교체. - 2. 렌더링된 pane은 터미널 폭에 맞춰 자동 줄바꿈하는데(cline은 이어지는 줄에 공백 들여쓰기까지 추가) 마커가 그 지점에 걸리면 `grep -F`(줄 단위)가 못 찾음 → 매칭 직전에 `tr -d '[:space:]'`로 공백/개행을 전부 제거하고 매칭 (paste 확인 지점 + Enter 제출 확인 지점 둘 다 적용). - -### 1.2 `.agents/skills/multi-agent-mux-create/` -- `SKILL.md`: 문서 예시 명령 정정(`herdr attach`→`agent attach` 등), 존재하지 않는 `list-sessions` 제거, 격리 섹션에 실제 메커니즘(헤드리스 세션 부트스트랩) 설명 추가. -- `scripts/create_session.sh`: YAML에 저장하는 `attach_command`/`kill_command`/`start_command` 템플릿이 `herdr session attach/stop/delete`(서버 전체 단위 명령을 개별 에이전트 이름으로 잘못 호출)로 깨져 있던 것을 `HERDR_SERVER_NAME= herdr ...` 형태로 수정. - -### 1.3 `.agents/skills/multi-agent-mux-resume/` -- `SKILL.md`: Verification 블록의 pseudo-명령 정정, `herdr attach -t`(존재하지 않는 문법) → `herdr agent attach`. -- (스크립트 자체는 버그 없었음 — herdr 관련 이슈 전수조사 완료.) - -### 1.4 `.agents/skills/multi-agent-mux-monitor/` -- `SKILL.md`: `herdr ls`/`list-panes` 문서 예시 정정. -- `scripts/reconcile.sh`: `attach_command` 템플릿의 존재하지 않는 `attach -t` → `agent attach` 수정. (이 파일은 원래 다른 목적 — purging 세션 자동등록 스킵 — 으로 이미 일부 수정되어 있었음.) - -### 1.5 `.agents/skills/multi-agent-mux-status/` -- `SKILL.md`: `herdr has-session`/`list-panes` 설명 정정, 드리프트 안내 메시지의 `herdr kill-session` 제안을 스킬 경유 안내로 변경. - -### 1.6 `.agents/skills/multi-agent-mux-stop/` -- `SKILL.md`: Verification 블록 정정. -- `scripts/stop_session.sh`: (원래 다른 목적으로 이미 수정 중이던) purge 락 파일(`purging-`) 추가, `--agent` 값 검증 추가. - -### 1.7 `.agents/skills/multi-agent-mux-delegate-job/` -- `multi-agent-mux-delegate-job` (메인 스크립트) `run_agent()` 함수의 herdr 버그 3건: - 1. `lib.sh`를 `has-session` 체크보다 늦게 source하고 있어서 체크 시점엔 아직 shim이 아니라 진짜 바이너리 → 존재하지 않는 `has-session` 서브커맨드 호출 → 항상 실패. `source lib.sh`를 파일 최상단으로 이동. - 2. `HERDR_SERVER_NAME`을 레지스트리에서 자동 해석 안 하고 호출자가 export해뒀길 기대함 → 격리 세션에 위임 시 실패 가능 → `resolve_herdr_workspace "$sess"` 자동 호출 추가. - 3. 안내 메시지의 `herdr session attach`(서버 전체 단위) → `herdr agent attach`로 수정. -- `SKILL.md`: "프롬프트는 영어/ASCII/짧게, 한국어 상세 내용은 마크다운 브리핑 파일로" 운영 규칙 추가 (send_keys_safe 버그의 실질적 완화책이자, `submit`의 기본 instructions 템플릿이 이미 따르고 있던 패턴을 명문화). - -### 1.8 기타 -- 루트 `.gitignore`에 Flutter/Dart 빌드 산출물, IDE 파일 패턴 추가 (`multi-agent-mux-ui`), 커밋 완료(`cccc30a`). -- `.mam/agent-sessions.yaml`의 stale 3개 세션(herdr 죽었는데 YAML엔 running으로 남아있던 것) `reconcile.sh`로 정리 → `terminated` 처리. - ---- - -## 2. 검증된 스킬 - -### 2.1 cline reviewer 독립 교차검증 완료 (`[VERDICT: PASS]`) - -**1차 — job `14943484`** (`.mam/jobs/14943484/cline-reports/herdr-cli-fix-review.md`) -- 대상: `lib.sh`(kill-session/send-keys/list-panes 수정 + session 격리 통일), `multi-agent-mux-create/scripts/create_session.sh`, `multi-agent-mux-monitor/scripts/reconcile.sh`, `multi-agent-mux-stop/scripts/stop_session.sh`, 5개 SKILL.md (create/resume/monitor/status/stop) -- 방법: 실제 herdr v0.7.4 바이너리로 10개 명령 문법 + 6개 JSON 스키마 직접 대조, 실구동 테스트, default 경로 회귀 테스트, pipefail 런타임 테스트, 정적분석. -- 잔여 LOW 2건 + INFO 1건 (전부 non-blocking, 비회귀). - -**2차 — job `80040741`** (`.mam/jobs/80040741/cline-agent-reports/report-final.md`, 정식 delegate-job 프로토콜로 완주) -- 대상: `lib.sh`의 `send_keys_safe()` 공백 정규화 수정, `multi-agent-mux-delegate-job/SKILL.md`의 새 규칙. -- 방법: python3 슬라이싱 시뮬레이션(엣지 케이스 15개) + 실제 bash 파이프라인 재현 + 실제 delegate-job 기본 템플릿으로 회귀 테스트. -- 잔여 INFO 1건(빈 marker_norm 위양성 가능성 — 실사용 경로에서 도달 불가로 확인, non-blocking). - -### 2.2 실제 프로덕션 사용으로 검증 (정식 리뷰 없음) - -- **`multi-agent-mux-delegate-job` 메인 스크립트의 `run_agent()` 수정 3건**: 정식 리뷰(job `e84698d7`)가 세션 hang으로 유실됐지만, 그 이후 실제로 여러 차례 `submit`을 성공 실행하면서(격리 세션 안의 살아있는 에이전트를 정확히 찾아내는 것 포함) 실사용 검증됨. -- **`multi-agent-mux-stop/scripts/stop_session.sh`**: 실제로 hung된 `canary-projects-multi-agent-mux-reviewer-cline` 세션을 대상으로 진짜 stop을 실행 — graceful exit-keys → kill-session(수정된 pane close 경로) → conversation id 캡처까지 전 과정 실전 확인. -- **`multi-agent-mux-resume/scripts/resume_session.sh`**: 같은 세션을 동일 conversation id로 실제 resume하여 대화 이력이 정확히 복원되는 것 확인 (2회 반복). - ---- - -## 3. 추후 검증할 스킬 - -| 스킬 | 상태 | -|---|---| -| **`multi-agent-mux-delegate-job` 메인 스크립트** | 정식 cline 리뷰(job `e84698d7`)가 세션 hang으로 미완료. 재위임하면 공식 PASS 서명을 받을 수 있음. | -| **`multi-agent-mux-status/scripts/status.sh`** | `SKILL.md` 문구만 검토됨. 스크립트 자체는 이번 작업에서 한 번도 직접 실행 안 함 (내부적으로 쓰는 `reconcile.sh`는 검증됨). | -| **`multi-agent-mux-loop`** | 완전히 손대지 않음. `run_loop.sh`가 herdr를 직접 다루지 않고 `delegate-job`을 통해서만 위임하는 구조라 영향권 밖일 가능성 높지만 미확인. | -| **`multi-agent-mux-ui`** (Flutter/Dart) | `.gitignore` 정리만 진행. `mam_core`가 `status.sh`를 래핑하는 로직 자체는 이번 herdr 문법 수정과 별개로 전혀 검토 안 함. | - ---- - -## 4. 추후 작업 - -1. **커밋**: 지금까지의 모든 수정(11개 파일, lib.sh + 6개 스킬)이 워킹 트리에 uncommitted 상태. 커밋 여부/단위 결정 필요. -2. **`multi-agent-mux-delegate-job` 메인 스크립트 정식 리뷰 재위임** — job `e84698d7` 재시도 (섹션 3 참조). -3. **`send_keys_safe`의 INFO급 잔여 이슈** — 빈 `marker_norm`일 때 `grep -Fq ''`가 항상 매칭되는 위양성 가능성. 실사용 경로에서 도달 불가로 확인됐지만, 원하면 방어적으로 빈 텍스트 가드를 추가할 수 있음. -4. **`multi-agent-mux-status/scripts/status.sh` 실제 실행 검증** — 아직 한 번도 직접 실행 안 됨. -5. **`multi-agent-mux-loop`/`multi-agent-mux-ui` 전수 조사** — 이번 herdr 문법 감사 범위 밖. -6. **`.mam/agent-sessions.yaml`의 `herdr_workspace`/`herdr_server` 필드명 정리** — 현재 `resolve_herdr_workspace()`가 반환하는 값의 실제 의미(workspace_id가 아니라 session 라벨)와 함수명이 불일치하는 상태(호출자 호환을 위해 이름은 유지함). 장기적으로는 필드명/함수명을 실제 의미(session)에 맞게 리네이밍하는 리팩터링을 고려할 수 있음. diff --git a/DONE.ko.md b/DONE.ko.md deleted file mode 100644 index 510a907..0000000 --- a/DONE.ko.md +++ /dev/null @@ -1,103 +0,0 @@ -# DONE.md - -> 완료된 작업 추적. 모든 항목은 3개 에이전트(agy-new, agy-existing, claude-existing)의 최종 검증을 거쳤음. -> 검증 일시: 2026-06-21 - ---- - -## 요약 - -- **처리 항목**: FW-01 ~ FW-16, FW-L1 ~ FW-L3, FW-N1 ~ FW-N7, FW-W3, Infra Pattern (총 28개) -- **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) | -| FW-N5 | `job-protocol.md` 보안 프로토콜 규격 갱신 (HMAC 서명 기준) | `6a88f10, 450722b` | Hermes 직접 | 문서/설계 정합성 패스 완료 (PASS) | -| FW-N6 | `registry.py` 내 `auth_token` 자동 생성 및 CLI 연동 지원 | `6a88f10` | Hermes 직접 | `--auth-token` 인자 추가 및 보안 브로커 감지 시 자동 생성 처리 완료 (PASS) | -| FW-N7 | `job_subscriber.py` 내 시퀀스 단조 증가 검증을 통한 Replay Attack 방어 | `6a88f10` | Hermes 직접 | Watcher 내 last_seq 추적 및 seq 단조 증가 검사 로직 구현 완료 (PASS) | -| FW-W3 | 개별 잡 와치독을 단일 와일드카드 구독자로 통합 | `358c72b` | Antigravity | watchdog.sh를 제거하고 reconcile.sh --subscribe 단일 구독자로 이벤트 처리 및 와치독 역할 통합 완료 (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 (FW-01 ~ FW-16, FW-L1 ~ FW-L3, FW-N1 ~ FW-N7, Infra) -- 2026-06-22 (Mon) 23:44 ~ KST (FW-W3) \ No newline at end of file diff --git a/DONE.md b/DONE.md deleted file mode 100644 index 4f03ae0..0000000 --- a/DONE.md +++ /dev/null @@ -1,105 +0,0 @@ -# DONE.md - -> **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 - -- **Completed Items**: FW-01 ~ FW-16, FW-L1 ~ FW-L3, FW-N1 ~ FW-N7, FW-W3, Infra Pattern (total of 28 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 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) | -| FW-N5 | Update `job-protocol.md` security protocol spec (to HMAC signatures) | `6a88f10, 450722b` | Hermes Direct | Documentation/Design consistency pass completed (PASS) | -| FW-N6 | Support auto-generated `auth_token` and CLI integration in `registry.py` | `6a88f10` | Hermes Direct | Added `--auth-token` argument, auto-generation on secure broker detection (PASS) | -| FW-N7 | Prevent Replay Attacks via sequence monotonic increase validation in `job_subscriber.py` | `6a88f10` | Hermes Direct | Added seq tracking in watcher to verify monotonic increase (PASS) | -| FW-W3 | Consolidate per-job watchdogs into shared wildcard subscriber | `358c72b` | Antigravity | Consolidate watchdog logic to reconcile.sh --subscribe, remove watchdog.sh (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 -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) -``` - ---- - -## Verification Results (Cross-Verification among 3 Agents) - -### agy-new (Gemini 3.1 Pro High) -- 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 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) -- 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) — 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 (FW-01 ~ FW-16, FW-L1 ~ FW-L3, FW-N1 ~ FW-N7, Infra) -- 2026-06-22 (Mon) 23:44 ~ KST (FW-W3) \ No newline at end of file diff --git a/FUTURE_WORKS.ko.md b/FUTURE_WORKS.ko.md deleted file mode 100644 index 6487ece..0000000 --- a/FUTURE_WORKS.ko.md +++ /dev/null @@ -1,54 +0,0 @@ -# FUTURE_WORKS.md - -> **목적**: `multi-agent-mux` 프로젝트의 향후 작업 후보를 추적한다. -> 완료된 항목은 `DONE.ko.md`를 참조. -> **최종 갱신**: 2026-06-24 - ---- - -## 향후 개선 작업 로드맵 - -현재 대기 중인 향후 작업(Future Works) 항목입니다. 본 항목들은 시스템의 보안, 동시성, 이식성 및 워크플로우 분석을 바탕으로 제안되었습니다. - -| ID | 과제명 | 우선순위 | 작업량 | 해결 분야 / 설명 | 의존성 | -|---|---|---|---|---|---| -| **FW-L4** | Job Registry의 SQLite 마이그레이션 및 NFS flock 한계 극복 | P3 (Low) | 대 | **동시성/인프라 확장성**: 세션 레지스트리와 마찬가지로 개별 JSON 파일 락(`fcntl.flock`) 방식의 잡 레지스트리를 SQLite 데이터베이스 트랜잭션 구조로 통합 마이그레이션하여, NFS 등 분산/네트워크 FS 환경에서의 안정성을 완전 확보 | **조건부** (실제 멀티 호스트/NFS 배포 필요 발생 시 착수) | -| **FW-P1** | lib.sh 내 GNU/Linux 유저랜드 가정 제거 | P2 (Medium) | 소 | **이식성**: `lib.sh`에 포함된 GNU coreutils 전용 명령(`df --output=target` 및 리눅스 mount 포맷 분석)을 이식 가능한 명령어로 대체하여 macOS/BSD에서 NFS 감지가 자동 무력화되는 사각지대 해결 | 없음 | -| **FW-P2** | 윈도우 환경을 위한 명시적인 동시성 제어 전략 제공 | P1 (High) | 중 | **이식성 / 동시성**: `fcntl`이 POSIX 전용이므로 `mqtt_common.py` 임포트 실패 시 예외가 발생하는 문제를 스타트업 시점에 감지하여 사용자 친화적 경고와 함께 조기 종료하게 하거나, 윈도우용 `msvcrt.locking` 등으로 락 메커니즘을 동적 매핑함. 이벤트 감사 로그를 기록하는 `_file_lock`은 설계 사양대로 best-effort(무영향) 속성을 유지함 | 없음 | -| **FW-P3** | 가상환경(virtualenv) 로딩 및 의존성 사전 검증 강화 | P2 (Medium) | 중 | **이식성**: requirements.txt의 paho-mqtt 2.x 의존성 선언 외에, UV/Poetry 등 독립 툴 체인에서 가상환경 인터프리터 불일치를 조기 차단하고, 실행 진입점(entrypoint)에서 필수 라이브러리 탑재 여부를 즉시 검증하는 진단 로직 추가 | 없음 | -| **FW-P4** | 기본 MQTT 브로커 및 네임스페이스 보안 강화 | P1 (High) | 중 | **이식성 / 보안**: 공용 브로커인 `broker.hivemq.com`과 열린 네임스페이스 대신, 사설 TLS 브로커 크레덴셜을 기본 템플릿으로 제공하여 원격 세션 탈취 및 도청 공격 위협 원천 방지 | 없음 | -| **FW-P5** | zsh 환경 하에서의 BASH_SOURCE 경로 오작동 해결 | P2 (Medium) | 소 | **이식성**: zsh 쉘에서 `lib.sh`를 대화형으로 sourcing할 때 `${BASH_SOURCE[0]}`가 공백으로 평가되어 스킬 경로(`SKILL_DIR`)를 잘못 설정하는 오류 해결 | 없음 | -| **FW-P6** | 마커 파일 조회를 통한 프로젝트 루트 동적 감지 | P1 (High) | 중 | **이식성**: `lib.sh`, `status.sh`, `reconcile.sh` 등 여러 스크립트에서 `../..` 등 상대 경로 깊이를 하드코딩하여 발생하는 취약성 해결. `.git`, `.mam`, `.env` 등을 찾는 상위 탐색 마커-파일 워크 방식을 적용하고, 단일한 `WORKSPACE_ROOT` 환경변수로 통일하여 오케스트레이션 안정성 확보 | 없음 | -| **FW-P7** | 모니터 종료 경로에 대한 HMAC 서명 검증 및 활성 상태 체크 강화 | P1 (High) | 중 | **이식성 / 보안**: `reconcile.sh`가 `verify_hmac` 서명 검증 없이 `completed`/`error` 이벤트만으로 세션을 즉시 강제 종료하는 리스크 해결. 모니터링 이벤트 핸들러(`on_message`)에서 보안 토큰 검증을 필수 처리하고, `kill-session` 전 실제 tmux 활성 여부와 예상 아티팩트 보존 상태를 대조하게 설계 | 없음 | -| **FW-W1** | 글로벌 레지스트리 락을 세밀한 락(Fine-grained locks)으로 대체 | P2 (Medium) | 중 | **동시성 / 확장성**: 모든 세션 및 progress/sequence 업데이트가 단일 `.mam/jobs/` 글로벌 fcntl lock을 거치며 생기는 병목 차단. 잡 단위의 개별 락 파일 도입 | 없음 | -| ~~**FW-W2**~~ | ✅ **해결됨 (2026-07-11)** — 키를 시간 지연이 아닌 실측 화면 상태 기반으로 전송하는 안전 헬퍼(send_keys_safe) 및 스타트업 다이얼로그 동적 헬퍼 도입 | — | — | **워크플로우**: 세션 생성, 재개, 중지 시 단순 sleep(예: 6초) 대신 터미널 스크린 스크랩이나 준비도 프로브(Readiness Probe)를 활용하여 다이얼로그나 예외 창을 안전하게 차단 | 완료 | -| **FW-W4** | 구독자 시퀀스 번호(last_seq)의 디스크 영속화 | P1 (High) | 중 | **워크플로우 / 보안**: 와치독 재기동 시 시퀀스 카운터가 리셋되는 구조적 취약을 방지하기 위해 `subscriber.last_seq`를 디스크/DB에 기록하여 잡 라이프타임 전체를 커버하는 Replay 방어선 유지 | 없음 | -| **FW-W5** | 리뷰어 판정을 위한 구조적 메시지 스키마 정의 | P2 (Medium) | 중 | **워크플로우**: PM 에이전트가 터미널 스크롤백 문자열을 무가공 grep 파싱하는 대신, 전용 리뷰 피드백 토픽(예: `reviews//verdicts`) 및 정형화된 JSON 포맷(`PASS`/`NOT_PASS` + 차단 요인) 도입 | 없음 | -| **FW-W6** | 모니터링 복구 루프의 Hermes 에이전트 지원 확장 | P2 (Medium) | 중 | **워크플로우 / 일관성**: `reconcile.sh` 내 자동 등록(drift-B) 및 ID 동기화(drift-C) 로직에 `hermes` 세션을 완전 편입시켜 Claude/Agy 세션과 동일한 모니터링 및 복구 수준 지원 | 없음 | -| **FW-W7** | derive_session_name 내 디렉터리 경로 슬러그 이름 충돌 해결 | P2 (Medium) | 소 | **워크플로우 / 충돌 방지**: 마지막 2개 디렉터리만 슬러그화할 때 발생하는 동일 이름의 중첩 디렉터리 세션 이름 충돌(예: `/projectA/src` 및 `/projectB/src` 가 동일한 세션명으로 슬러그화됨)을 해결하기 위해 워크스페이스 범위 해시 값을 포함하는 세션명 명명 규칙 적용 | 없음 | -| ~~**FW-D1**~~ | ✅ **해결됨 (2026-06-24)** — 설치 스크립트가 더 이상 in-place 추출하지 않음 | — | — | **배포 / 안전성**: `deploy/install.sh`는 이제 다운로드를 `mktemp -d` 임시 디렉터리에 스테이징하고 `.agents/skills/lib.sh` 존재를 검증한 뒤, 런타임 자산(`.agents/`, `.env.example`)만 per-file no-clobber 가드(`[ ! -e ]`)로 타겟에 복사한다. 따라서 기존 타겟 파일이 항상 우선하며 레포 개발 문서가 워크스페이스에 들어가지 않는다. fetch 후 sanity 체크도 디렉터리가 아닌 파일을 검사하도록 변경 | 완료 | -| **FW-D2** | 설치 스크립트가 다운로드하는 소스를 sourcing 전에 고정 및 검증 | P2 (Medium) | 소 | **배포 / 공급망**: 설치 스크립트는 네트워크로 이동형 `main` 브랜치를 clone/추출하고, 워크스페이스는 이후 해당 셸 스크립트(`lib.sh` 등)를 `source`한다. *부분 해결 (2026-06-24): 복사 전에 스테이징된 트리에 `.agents/skills/lib.sh`가 존재하는지 검증함.* **남은 작업:** 릴리스 태그나 커밋 SHA로 고정하고 공개 체크섬을 검증하여 구조적 존재 여부뿐 아니라 콘텐츠 무결성까지 보장 | 없음 | -| **FW-D3** | `install.sh`와 `lib.sh` 간 NFS 감지 로직 중복 제거 | P2 (Medium) | 소 | **배포 / 이식성**: `deploy/install.sh`가 `lib.sh::_check_is_nfs`에 이미 존재하는 GNU 전용 `df --output=target` + `mount` NFS 검사를 재구현한다. FW-P1 이식성 수정이 이 두 번째 사본까지 포함하도록, 단일 공유 헬퍼로 추출하여 macOS/BSD에서 두 호출 지점 모두 올바르게 동작하게 한다 | FW-P1 | -| **FW-D4** | CI shellcheck 커버리지 공백 해소 | P3 (Low) | 소 | **배포 / 품질**: `deploy/gitea-ci.yml`은 9개 스크립트만 shellcheck하며, `status.sh`, `resolve_session_id.sh`, `update_yaml_resumed.sh`는 검사되지 않는다. 추적되는 모든 `*.sh`를 glob 처리하여 신규 스크립트가 자동 포함되도록 한다 | 없음 | - ---- - -### 세부 논의 결과 및 방향성 (Reviewer 합의 사항) - -1. **SQLite 통합(FW-L4)의 조건부 연기**: - * 세션 레지스트리와 달리 개별 잡 데이터는 JSON 파일 구조가 관리 및 디버깅 직관성이 우수하며, 현재 배포 환경은 단일 호스트 로컬 FS로 제한되어 있어 `fcntl.flock` 잠금만으로 안전하게 운용 가능하므로 낮은 우선순위(P3)로 배정하고 필요 시 착수합니다. - -2. **윈도우 환경을 위한 명시적인 동시성 제어 전략 제공 (FW-P1, FW-P2)**: - * 동시성 제어 시스템에서 오류 시 락 없이 그냥 실행되는 침묵형 오작동(Silent failover)은 가장 위험한 구조입니다. 윈도우 환경에서 `fcntl` 모듈 누락 시 묵인하지 않고 진입점에서 명시적인 조기 경고를 내어 POSIX 환경이나 전용 래퍼 실행을 유도하고, 혹은 `msvcrt.locking` 파일 제어 전략을 동적 매핑하여 플랫폼 전반의 안전성을 담보해야 합니다. - -3. **마커 파일을 통한 동적 루트 앵커링 (FW-P6)**: - * 하위 경로 탐색 시 특정 파일의 상대 경로 깊이(`../..` 등)에 의존하는 구조는 디렉터리 리팩토링이나 래퍼 이동 시 치명적 취약점으로 작용합니다. 디렉터리 트리를 따라 `.git`이나 `.mam` 등 알려진 루트 표시 마커를 동적으로 검색하는 방식을 채택하여 스크립트 실행 안정성과 이식 속도를 획기적으로 개선합니다. - -4. **모니터 종료 권한 제어 강화 (FW-P7)**: - * 세션 강제 종료(`tmux kill-session`) 권한은 안전하게 제어되어야 합니다. 모니터(`reconcile.sh`)가 와일드카드 토픽을 무검증 수신하여 즉시 세션을 정리하면 위조 주입 공격에 취약해집니다. 종료 이벤트 수신부에 HMAC 서명 검증을 의무화하고, 세션 강제 중지 전 예상되는 작업 결과물(Artifact) 존속 상태를 교차 검토하도록 설계합니다. - -5. **개별 잡 와치독의 단일 와일드카드 구독자 통합 (FW-W3)**: - * 매 잡마다 개별적으로 실행되어 2분 주기로 끊고 재연결하던 `watchdog.sh` 프로세스 방식 대신, 상시 기동되는 `reconcile.sh --subscribe` 단일 와일드카드 구독자 구조로 이벤트 처리, HMAC 보안 검증 및 시퀀스 추적 로직을 완전히 통일했습니다. 이를 통해 불필요한 MQTT 커넥션 급증을 원천 차단하고 세션 정리 과정을 간소화했으며, 메모리 캐시 기반 시퀀스 추적을 통해 Replay 공격 차단 정합성을 동시 실행 중인 모든 잡에 대해 안정적으로 제공합니다. - -6. **배포 설치 스크립트 강화 (FW-D1 ~ FW-D4)**: - * `deploy/install.sh`와 Gitea 템플릿은 가장 최근에 추가된(DONE.md 검증 라운드 이후) 리뷰가 가장 적은 영역이며, 검증된 오케스트레이션 코드가 실행되기 *이전*에 동작하는 유일한 경로입니다. **FW-D1(릴리스 차단 항목)은 이제 해결되었습니다(2026-06-24):** 처음 제안된 `tar --exclude` 거부목록(denylist) 방식 — 리뷰 결과 이식성이 없고, 더 심각하게는 비앵커드 `--exclude="scripts"` 패턴이 스킬 트리 내부의 `scripts/` 디렉터리까지 제거하여 조용히 깨진 설치를 만든다는 점이 확인됨 — 대신, 임시 디렉터리 스테이징 + 런타임 자산 허용목록(allowlist) 복사 + per-file no-clobber 가드로 재구성했습니다. 이로써 파괴적 덮어쓰기 위험과 개발 문서 오염을 한 번에 해소했습니다. FW-D2는 부분 해결(복사 전 스테이징 트리 구조 검증)되었고, 남은 공급망 강화 작업은 fetch를 태그/SHA + 체크섬으로 고정하는 것입니다. FW-D3(NFS 감지 분기, FW-P1에 통합)와 FW-D4(CI 린트 커버리지)는 일관성/품질 부채로 남아 있습니다. \ No newline at end of file diff --git a/FUTURE_WORKS.md b/FUTURE_WORKS.md deleted file mode 100644 index 077665a..0000000 --- a/FUTURE_WORKS.md +++ /dev/null @@ -1,57 +0,0 @@ -# FUTURE_WORKS.md - -> **Purpose**: Track future work candidates for the `multi-agent-mux` project. -> For completed items, see `DONE.md`. -> **Last Updated**: 2026-06-24 - ---- - -## Future Improvements Roadmap - -Below is the list of pending future work items. These items were proposed based on the security, concurrency, portability, and workflow analysis of the system. - -| ID | Task | Priority | Effort | Domain / Description | Dependencies | -|---|---|---|---|---|---| -| **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) | -| **FW-P1** | Eliminate GNU/Linux userland assumptions in lib.sh | P2 (Medium) | Small | **Portability**: Replace GNU coreutils-specific commands (like `df --output=target` and Linux-specific mount formats) in `lib.sh` with portable equivalents, resolving silent failures of NFS detection on macOS/BSD. | None | -| **FW-P2** | Add explicit Windows concurrency strategy in mqtt_common.py | P1 (High) | Medium | **Portability / Concurrency**: Detect non-POSIX systems at module initialization and either fail fast with a descriptive warning or substitute alternative lock strategies (e.g. `msvcrt.locking`), while preserving the best-effort nature of the `_file_lock` log appender. | None | -| **FW-P3** | Align virtualenv loading and dependency verifications | P2 (Medium) | Medium | **Portability**: Prevent local interpreter mismatches in Poetry/UV environments and ensure the launch scripts fail early with clear diagnostic warnings if required Python dependencies are missing at startup. | None | -| **FW-P4** | Secure default MQTT broker and namespaces | P1 (High) | Medium | **Portability / Security**: Prevent remote session hijack and eavesdropping by providing a private TLS-enabled broker template rather than defaulting to `broker.hivemq.com` in public namespaces. | None | -| **FW-P5** | Resolve BASH_SOURCE path resolution under zsh | P2 (Medium) | Small | **Portability**: Fix `lib.sh` interactive sourcing issues under zsh shell where `${BASH_SOURCE[0]}` resolves to empty. | None | -| **FW-P6** | Anchor project root dynamically via marker-file lookup | P1 (High) | Medium | **Portability**: Resolve structural fragility caused by hardcoded `../..` relative directory traversal in `lib.sh`, `status.sh`, and `reconcile.sh`. Use an upward search for root markers (`.git`, `.mam`, `.env`) to export a single source of truth for `WORKSPACE_ROOT`. | None | -| **FW-P7** | Enforce HMAC verification and liveness checks on monitor termination | P1 (High) | Medium | **Portability / Security**: Prevent remote session killing by unauthorized or spoofed events. Integrate `verify_hmac` inside the monitor (`reconcile.sh`'s `on_message` handler) and confirm expected artifacts exist before executing `tmux kill-session`. | None | -| **FW-P8** | Unify `.env` loading in `lib.sh` to prevent split-brain path resolution | P1 (High) | Small | **Portability / Consistency**: Sourcing the `.env` file inside `lib.sh` is critical to prevent split-brain path resolution where shell scripts query the default session database path while Python scripts query a custom path defined in `.env`. Sourcing `.env` at the top of `lib.sh` ensures all shell utilities automatically inherit user overrides for `TMUX_SERVER_NAME`, `AGENT_SESSIONS_YAML`, etc. | None | -| **FW-W1** | Replace global registry lock with fine-grained locks | P2 (Medium) | Medium | **Concurrency / Scaling**: Eliminate throughput bottlenecks where all progress/sequence updates channel through a single fcntl lock on `.mam/jobs/`. Implement per-job lock files. | None | -| ~~**FW-W2**~~ | ✅ **RESOLVED (2026-07-11)** — implemented evidence-based prompt delivery helper (send_keys_safe) and startup dialog handler to prevent prompt-locks | — | — | **Workflow**: Replace fixed timing sleeps in create, resume, and stop scripts with dynamic terminal readiness probes (e.g. scrapers or CLI checking hooks) to dismiss trust dialogs robustly. | Done | -| **FW-W4** | Persist subscriber sequence numbers alongside job records | P1 (High) | Medium | **Workflow / Security**: Persist `subscriber.last_seq` to disk or SQLite to prevent sequence counter reset on subscriber restart, locking down the replay defense window for the full job lifetime. | None | -| **FW-W5** | Define structured message schema for reviewer verdicts | P2 (Medium) | Medium | **Workflow**: Create a dedicated reviewer topic (e.g., `reviews//verdicts`) emitting structured JSON verdicts (`PASS` / `NOT_PASS` + details) to eliminate raw text grepping by the PM. | None | -| **FW-W6** | Expand monitor reconciliation support to Hermes agent | P2 (Medium) | Medium | **Workflow / Consistency**: Fully integrate `hermes` sessions into auto-registration (drift-B) and ID materialization (drift-C) under `reconcile.sh` to match Claude/Agy monitoring coverage. | None | -| **FW-W7** | Resolve path slug collisions in derive_session_name | P2 (Medium) | Small | **Workflow / Collision Avoidance**: Update `derive_session_name` to handle same-name nested directories (e.g. `/projectA/src` and `/projectB/src` both slugify to identical session names) by incorporating workspace-scoped identifiers or hash digests. | None | -| ~~**FW-D1**~~ | ✅ **RESOLVED (2026-06-24)** — installer no longer extracts in-place | — | — | **Deploy / Safety**: `deploy/install.sh` now stages the download into a `mktemp -d` dir, verifies `.agents/skills/lib.sh` is present, then copies only the runtime assets (`.agents/`, `.env.example`) into the target with per-file no-clobber guards (`[ ! -e ]`), so existing target files always win and repo dev docs never land in the workspace. The post-fetch sanity check now tests a file, not just the directory. | Done | -| **FW-D2** | Pin and verify the source the installer downloads before sourcing it | P2 (Medium) | Small | **Deploy / Supply-chain**: The installer clones/extracts the moving `main` branch over the network, and the workspace later `source`s those shell scripts (`lib.sh` et al.). *Partially addressed (2026-06-24): the staged tree is now verified to contain `.agents/skills/lib.sh` before any file is copied.* **Remaining:** pin to a release tag or commit SHA and/or verify a published checksum so the fetched content is integrity-checked, not merely structurally present. | None | -| **FW-D3** | De-duplicate NFS detection between `install.sh` and `lib.sh` | P2 (Medium) | Small | **Deploy / Portability**: `deploy/install.sh` re-implements the GNU-specific `df --output=target` + `mount` NFS check already present in `lib.sh::_check_is_nfs`. The FW-P1 portability fix must cover this second copy — extract a single shared helper so both call sites stay correct on macOS/BSD. | FW-P1 | -| **FW-D4** | Close CI shellcheck coverage gaps | P3 (Low) | Small | **Deploy / Quality**: `deploy/gitea-ci.yml` shellchecks only 9 scripts; `status.sh`, `resolve_session_id.sh`, and `update_yaml_resumed.sh` are never linted. Glob all tracked `*.sh` so new scripts are covered automatically. | None | - ---- - -### Detailed Discussion Results & Directions (Reviewer Consensus) - -1. **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. - -2. **Explicit Concurrency Strategy on Windows (FW-P1, FW-P2)**: - * Silent failovers are the worst design patterns for concurrency. Instead of letting Windows environments run without a lock (which occurs when fcntl fails silently), we detect POSIX availability at startup. We either fail fast to prompt the user to use a POSIX-compliant shell/wrapper, or dynamically load `msvcrt.locking` to provide a matching file locking mechanism. This guarantees consistent synchronization behaviors across Windows and Unix platforms. - -3. **Dynamic Root Anchor (FW-P6)**: - * Hardcoding relative depth limits (like `../..` relative to a skill's location) creates direct fragility when moving directories or refactoring. By walking up the directory tree to search for known anchors (like `.git` or `.mam`), we establish a single canonical root path and prevent scripts from breaking when their execution wrappers are relocated. - -4. **Monitor Termination Authorization (FW-P7)**: - * Auto-termination must not trust unauthenticated events. Since `reconcile.sh` listens to a wildcard topic, any client on a public broker could spoof a terminal message and trigger `tmux kill-session`. Requiring HMAC signature verification on the terminal event path, combined with artifact validation, mitigates spoofing and accidental session cleanup. - -5. **Consolidation of per-job watchdogs (FW-W3)**: - * Instead of spawning an independent `watchdog.sh` process for each job which reconnects every 2 minutes, we consolidated the event handling, HMAC security verification, and sequence tracking into a single, persistent wildcard subscriber running under `reconcile.sh --subscribe`. This drastically reduces MQTT broker connections, simplifies cleanup logic, and leverages python's memory storage to handle replay attack prevention (monotonic sequence numbers) for concurrent jobs. -6. **Consistent `.env` Sourcing across Shell and Python (FW-P8)**: - * Sourcing the `.env` configuration file inside `lib.sh` ensures that shell utilities and Python scripts are fully aligned. Without this, customized database locations or isolated tmux server names declared in `.env` are only honored by the Python-based MQTT subsystems, while the shell orchestrators silently fall back to default socket files and paths. - -7. **Deployment Installer Hardening (FW-D1 ~ FW-D4)**: - * `deploy/install.sh` and the Gitea templates are the newest, least-reviewed surface (added after the DONE.md verification round) and the one path that runs *before* any of the reviewed orchestration code. **FW-D1 (the release blocker) is now resolved (2026-06-24):** rather than the originally proposed `tar --exclude` denylist — which review showed was non-portable and, worse, stripped the skills' own nested `scripts/` directories via the unanchored `--exclude="scripts"` pattern, yielding a silently broken install — the installer was rebuilt around temp-dir staging + an allowlist copy of runtime assets with per-file no-clobber guards. This closes the destructive-overwrite hole and the dev-doc clutter in one move. FW-D2 is partially addressed (the staged tree is structurally verified before copy); the remaining supply-chain hardening is pinning the fetch to a tag/SHA + checksum. FW-D3 (NFS detection drift, folded into FW-P1) and FW-D4 (CI lint coverage) remain open consistency/quality debt. \ No newline at end of file diff --git a/MESSAGING.md b/MESSAGING.md index 067fffa..347b321 100644 --- a/MESSAGING.md +++ b/MESSAGING.md @@ -35,7 +35,7 @@ graph TD SubClient["job_subscriber.py
(Role: subscriber)"] end - subgraph "Tmux Workspace (Agent Host)" + subgraph "Herdr Workspace (Agent Host)" PubClient["publish_event.py
(Role: publisher)"] end @@ -127,7 +127,7 @@ Every event payload must adhere to the following schema structure: ### 2.3 Event Type Dictionary and Schemas #### 1. `started` -* **Emit Trigger**: Emitted by the worker agent immediately upon boot inside the tmux session, indicating it has parsed the instructions and started execution. +* **Emit Trigger**: Emitted by the worker agent immediately upon boot inside the herdr session, indicating it has parsed the instructions and started execution. * **Payload Constraints**: `seq` must be `1`. Status in registry is transitioned to `running`. * **Example Detail**: `"Job 918b0612 started"` @@ -200,7 +200,7 @@ stateDiagram-v2 * **Timeout Initialization**: Dual timeouts (wall-clock budget and activity idle timer) are calculated and start ticking. #### Phase 4: Execution & Progress Events (`publish`) -* **Trigger**: The agent executes prompts within tmux and runs `publish_event.py` at boot and checkpoint stages. +* **Trigger**: The agent executes prompts within herdr and runs `publish_event.py` at boot and checkpoint stages. * **Network Handshake**: Publisher opens a fresh TCP/TLS socket to the broker, awaits CONNACK, publishes a single QoS 1 message, waits for PUBACK, and gracefully disconnects to avoid socket resource leaks. * **State Updates**: Updates `last_seq` monotonically, updates `status` to `running` (if not already), and mirrors the published payload into the local audit logs (`events.ndjson`). * **Subscriber Capture**: The subscriber captures the payload, performs bearer token checks, prints the formatted line to stdout, and resets its idle timer. @@ -218,7 +218,7 @@ stateDiagram-v2 ### 4.1 `registry.py` & `lib.sh` (Locking & Atomicity) Two concurrency control schemes co-exist in this workspace to coordinate state modification: -1. **`lib.sh::atomic_dump_yaml()`**: Used for workspace-wide tmux session inventory (`agent-sessions.yaml`). +1. **`lib.sh::atomic_dump_yaml()`**: Used for workspace-wide herdr session inventory (`agent-sessions.yaml`). * **Locking**: Uses SQLite database transaction serialization via `BEGIN IMMEDIATE` on `agent-sessions.db`. * **Safe Mutation**: The mutation source code is passed in an environment variable `AGENT_SESSIONS_MUTATION` and executed dynamically using `exec(compile(..., 'exec'), globals())`. This isolates the execution and avoids command-injection vectors. * **Atomicity**: Updates the SQLite tables and then, if a session transitions to a finished state, writes to a temp file in the same directory using `tempfile.mkstemp()` and performs an `os.replace()` rename. POSIX guarantees the replacement is atomic, preventing half-written YAML reads. A `.bak` backup copy is also preserved. @@ -275,9 +275,9 @@ graph LR User["User/Cron Client"] -->|submit| Wrap["multi-agent-mux-delegate-job (Bash)"] Wrap -->|registers| Reg["registry.py (Live Registry)"] Wrap -->|spawns background| Sub["job_subscriber.py"] - Wrap -->|spawns tmux pane| Tmux["tmux Session (Agent Pane)"] + Wrap -->|spawns herdr pane| Herdr["herdr Session (Agent Pane)"] - Tmux -->|executes agent| Agent["Claude / Codex Agent"] + Herdr -->|executes agent| Agent["Claude / Codex Agent"] Agent -->|publish_event.py| Broker["MQTT Broker"] Broker -->|delivers events| Sub Broker -->|delivers events| Mon["reconcile.sh (Monitor Loop)"] @@ -288,18 +288,18 @@ graph LR ### 5.1 Orchestration Wrappers (`multi-agent-mux-*`) 1. **`multi-agent-mux-delegate-job (submit)`**: * Registers a job, spawns `job_subscriber.py` to capture standard output streams to `.mam/jobs/.subscriber.out`, and sleeps for `1` second. - * Boots the agent pane in tmux: + * Boots the agent pane in herdr: ```bash - tmux new-session -d -s "$sess" -c "$WORKDIR" \ + herdr new-session -d -s "$sess" -c "$WORKDIR" \ "printf '%s' \"$instructions\" | $bin --dangerously-skip-permissions; echo; read" ``` * Pre-seeds agent instruction headers via stdin to enforce that the agent runs `publish_event.py` for its transitions. * Blocks on `wait $sub_pid`, and finally prints the audit log directory. 2. **`multi-agent-mux-monitor` (`reconcile.sh`)**: - * **Wildcard Monitor Integration**: Runs a unified background subscriber loop (`reconcile.sh --subscribe`) to capture progress, verify security tokens (HMAC) and sequences, write audit logs, and automatically clean up tmux sessions upon terminal events. - * **Reconciliation loop**: Subscribes to the global job topic. On terminal events, it invokes `lib.sh::atomic_dump_yaml` to sync status drifts (e.g. setting tmux sessions to `terminated` in `agent-sessions.yaml` once the agent exits). + * **Wildcard Monitor Integration**: Runs a unified background subscriber loop (`reconcile.sh --subscribe`) to capture progress, verify security tokens (HMAC) and sequences, write audit logs, and automatically clean up herdr sessions upon terminal events. + * **Reconciliation loop**: Subscribes to the global job topic. On terminal events, it invokes `lib.sh::atomic_dump_yaml` to sync status drifts (e.g. setting herdr sessions to `terminated` in `agent-sessions.yaml` once the agent exits). 3. **`multi-agent-mux-create / stop / resume`**: - * Integrates the job life status into session metadata updates, ensuring standard tmux cleanup triggers state updates in the registry and audit logs. + * Integrates the job life status into session metadata updates, ensuring standard herdr cleanup triggers state updates in the registry and audit logs. --- @@ -312,7 +312,7 @@ graph LR 2. **Bearer Token Leakage over Plaintext (Public Broker)**: The `auth_token` mechanism is a simple plaintext bearer comparison. If the transport layer is unencrypted (e.g., using `broker.hivemq.com` on port `1883`), any eavesdropper on the network can steal the token and spoof legitimate events. 3. **Subscriber Network Drop Orphanage**: - `job_subscriber.py` does not implement automatic reconnection loops. If the subscriber loses connection to the broker, it exits, leaving the running tmux agent orphaned and without a validation/collection hook. + `job_subscriber.py` does not implement automatic reconnection loops. If the subscriber loses connection to the broker, it exits, leaving the running herdr agent orphaned and without a validation/collection hook. 4. **Lack of Ordering Guarantees in QoS 1**: QoS 1 guarantees delivery but not strict ordering. Under heavy backoff retries, a late-delivered progress event could land after a terminal event, causing state inconsistencies. @@ -342,10 +342,10 @@ Valid values (see `lib.sh` valid-status set): | State | Meaning | Set by | |---|---|---| -| `running` | tmux session active, agent running | `create`, `resume` | +| `running` | herdr session active, agent running | `create`, `resume` | | `stopped` | deliberately stopped via `--capture-id`/`--reason`/`--graceful`; conversation preserved for resume | `stop` (STOP mode) | -| `terminated` | hard-killed via `--mode hard`; tmux session destroyed | `stop` (hard mode), `monitor` reconcile | -| `archived` | soft-stopped via `--mode soft`; tmux left alive, YAML-only update | `stop` (soft mode) | +| `terminated` | hard-killed via `--mode hard`; herdr session destroyed | `stop` (hard mode), `monitor` reconcile | +| `archived` | soft-stopped via `--mode soft`; herdr left alive, YAML-only update | `stop` (soft mode) | ### Job States (Registry — `.mam/jobs/.json`) Managed by `.agents/skills/multi-agent-mux-delegate-job/scripts/registry.py`. @@ -359,6 +359,6 @@ Valid values: | `error` | terminal event — agent failed | `publish_event.py --event error` | | `cancelled` | job cancelled by orchestrator | `registry.py cancel` | -**Key distinction**: Session states track the **tmux container lifecycle** (create→stop→resume). +**Key distinction**: Session states track the **herdr container lifecycle** (create→stop→resume). Job states track the **delegated work lifecycle** (submit→run→complete/error). A single session can host multiple sequential jobs; a job runs within exactly one session. diff --git a/OPTIMIZATION.md b/OPTIMIZATION.md new file mode 100644 index 0000000..1ff2849 --- /dev/null +++ b/OPTIMIZATION.md @@ -0,0 +1,68 @@ +# 🛠️ Multi-Agent Mux Loop (`/multi-agent-mux-loop`) 최적화 및 개선 분석서 (`OPTIMIZATION.md`) + +본 문서는 `/multi-agent-mux-loop` 스킬 및 오케스트레이션 스크립트(`run_loop.sh`)의 불필요한 문구, 스킬 명세와 실제 코드 구현 간의 괴리, 필수 절차의 기계적 강제성 부족 항목을 분석하고, 이를 코딩적으로 강제 및 최적화하기 위한 최종 해결 방안을 정의한 분석서입니다. + +--- + +## 1. 🔍 불필요한 문구, 모순 및 중복 항목 (Redundant & Inconsistent Issues) + +### ISSUE-1: CLI 옵션 상호 배타성 및 충돌 경고의 취약함 +- **현상**: `--all-reviewer` 옵션과 `--reviewer "A,B"` 옵션을 함께 전달할 경우, `run_loop.sh`에서 경고 메시지만 출력하고 `--reviewer` 목록을 무시함. 또한 `--plan` 모드가 비활성화된 상태에서 `--plan-talk N`을 전달할 경우 역시 경고 후 턴 설정을 무시하고 진행됨. +- **문제점**: 에이전트나 사용자가 잘못된 파라미터 조합을 주입했을 때 스크립트가 조기에 에러로 실패(Fail-Fast)하지 않고 진행하여 혼선을 야기함. +- **해결 방안**: + 1. 파라미터 파싱 단계에서 상호 배타적인 옵션이 포함된 경우 경고로 넘기지 않고 즉시 에러(`exit 1`)를 반환하도록 검증 로직 강화. + 2. `SKILL.md` 문서 내의 옵션 예시(Workflow 섹션) 중 두 옵션이 동시에 사용된 오류 표기를 상호 배타 규격에 맞게 정정. + +### ISSUE-2: `SKILL.md` 명세 문서 내 레거시 용어 및 문구 +- **현상**: 스킬 명세서 문서 내 일부 설명 및 주석에 TMUX 시절의 표현이나 레거시 파라미터 관련 설명이 혼재되어 있음. +- **해결 방안**: Herdr 엔진 기반으로 완전히 마이그레이션된 현재 구조에 맞춰 스킬 명세서(`SKILL.md`) 내 문구를 정돈하고 불필요한 레거시 언급을 제거함. + +--- + +## 2. ⚠️ 명세(Specification)에는 정의되어 있으나 코드로 강제되지 않은 작업 절차 (Specification vs Implementation Discrepancies) + +### ISSUE-3: `[VERDICT: PASS]` 판정 포맷 템플릿의 기계적 검증 및 가이드 부족 +- **현상**: 스킬 명세 및 규약에서는 리뷰어 보고서의 "마지막 줄 단독 행"에 `[VERDICT: PASS]` 또는 `[VERDICT: NOT PASS]` 토큰이 명시되어야 함을 요구함. 하지만 리뷰어 에이전트 프롬프트에 텍스트 문구로만 지시될 뿐, 작성 전후 양식을 검증하거나 보정하는 장치가 스크립트 레벨에 없음. +- **문제점**: 리뷰어가 보고서 작성 시 줄바꿈 미입력, 마크다운 코드블록 인용, 기타 형식 오류를 범할 경우 내용이 통과이더라도 파서가 `fail-closed`로 동작하여 무조건 `NOT PASS` 처리됨. +- **해결 방안**: 리뷰어 지시 프롬프트에 정확한 템플릿 포맷 예시를 강화하고, 필요시 파싱 실패 시 1회 구조화 재작성 지시(Fix-up prompt) 기계적 트리거 마련. + +### ISSUE-4: Definition of Done (DoD) 및 원자적 커밋(Atomic Commit)의 기계적 검증 부재 +- **현상**: 규약 및 스킬 명세에는 Creator(작업자)가 구현 완료 후 DoD 체크리스트를 실행하고 원자적 커밋을 수행한 뒤 리뷰어에게 전달하도록 명시되어 있음. +- **문제점**: `run_loop.sh`는 Creator 잡이 종료된 후 실제 git status 변경 유무나 커밋 생성 여부를 확인하지 않고 단순히 지시 프롬프트에만 의존함. 커밋이 수행되지 않거나 변경분(diff)이 0건인 경우에도 루프가 그대로 진행되어 무의미한 리뷰가 수행됨. +- **해결 방안**: Phase 2 (구현 단계) 완료 직후 `dod_changed_paths` 헬퍼 및 `git diff` 누적 관제를 수행하여, **변경 경로가 0건인 경우 `exit 1`로 즉시 실패 처리**하고 원자적 커밋 미수행 시 1회 경고 및 재지시를 내리는 코딩 게이트 구축. + +### ISSUE-5: 기획-구현 대화 루프(`--plan-talk`)의 이의제기 수렴 여부 판단 부재 +- **현상**: `--plan-talk N` 설정 시 Planner와 Creator 간의 이의제기(Challenge) 및 계획 갱신(Refine) 대화가 N회 진행됨. +- **문제점**: Creator의 이의제기가 실제로 Planner에 의해 수용 및 합의되었는지 논리적 종결 여부를 확인하지 않고, 무조건 지정된 턴 수(N)를 기계적으로 소모한 후 다음 단계로 진행함. +- **해결 방안**: Planner 갱신 리포트에 `[AGREEMENT: REACHED]` 같은 수렴 판정 토큰을 도입하거나, 이의제기가 없는 경우 N회 턴 전이라도 조기 종료(Early Break)할 수 있는 로직 추가. + +### ISSUE-6: 타당하지 않은 리뷰 피드백 거부/반론 프로토콜의 스크립트 미지원 +- **현상**: `MULTI_AGENT_RULES.md` 1장 규약에는 "개발 팀장이 리뷰어의 타당하지 않은 피드백을 거부하고 명확한 이유를 회신할 수 있다"고 명시되어 있음. +- **문제점**: `run_loop.sh`는 리뷰어의 `NOT PASS` 피드백 전체를 Creator에게 일방적으로 주입할 뿐, Creator가 특정 피드백을 거부하거나 반론을 제기하여 상호 조율하는 이의제기 채널이 코딩적으로 구현되어 있지 않음. +- **해결 방안**: Creator 교정 단계 프롬프트에 반론 작성 템플릿을 허용하고, 반론 발생 시 Planner/Reviewer에게 재검토를 요청하는 이의제기 브랜칭 로직 설계. + +--- + +## 3. 🛡️ 오케스트레이션 위임 및 안전성/동시성 강제안 (Orchestration Enforcement & Reliability) + +### ISSUE-7: 동일 워크스페이스 내 중복 루프 기동 방지 락 (Race-Free Lock) 설계 정교화 +- **현상**: 동일 작업 트리에서 다수의 `run_loop.sh` 스크립트가 병렬 기동될 경우 SQLite DB 갱신 경합 및 YAML 데이터 오염이 일어날 수 있음. +- **문제점**: 단순 PID 파일 존재 여부만 체크할 경우, PID Rollover(프로세스 ID 재사용) 또는 `mkdir`과 PID 기록 사이의 생성 창(Grace Window)에서 살아있는 락을 타 프로세스가 훔쳐가는 "락 도난(Live-lock theft)" 현상 발생. +- **해결 방안**: + 1. 락 소유자 레코드를 단순 `PID`에서 **`PID + 시작시각(lstart) + 워크스페이스`** 3중 구조로 결합하여 PID 재사용을 결정적으로 차단. + 2. `mkdir` 직후 생성 창 유예 대기(Sleep Grace Period)를 부여하여 락 도난 방지. + 3. `ps` CLI 부재 시 Fails-Open(락 무시) 대신 **Fails-Safe(락 존중 + 경고)** 로 전환하여 DB/YAML 오염 원천 방지. + +### ISSUE-8: 비동기 잡 모니터링 타임아웃 및 헬스체크 최적화 +- **현상**: `wait_for_job` 기본 타임아웃이 3900초(65분)로 설정되어 있어, 에이전트 세션 패닉이나 사망 시 오케스트레이터가 과도하게 오랫동안 대기함. +- **해결 방안**: 모니터링 수집 루프 내에서 herdr 세션의 라이브 상태(`alive`)를 매 주기마다 핑(Ping) 확인하여 세션 사망 시 즉시 `fail-fast` 하도록 개선. + +### ISSUE-9: 조건부 오케스트레이션 위임 가드 (Invocation-Aware Scoped Guard) +- **현상**: 오케스트레이터(Antigravity)가 평상시에는 Main Creator로서 코드 및 문서를 직접 집필해야 하지만, `/multi-agent-mux-loop` 슬래시 커맨드/스킬이 인보크된 상황에서도 이를 인지하지 못하고 에이전트들에게 위임하는 대신 직접 수정을 시도하는 지침 이탈 발생. +- **문제점**: 오케스트레이터의 파일 직접 수정 권한을 무조건 뺏으면(1번 방안 부작용) 일반 작업이 불가능해지고, 자연어 지침에만 의존하면 슬래시 커맨드 호출 시 위임을 건너뛰는 모순 발생. +- **해결 방안**: + - **평상시 (일반 요청)**: 오케스트레이터가 **Main Creator**로서 소스 및 마크다운 파일 직접 작성/수정 도구(`write_to_file`, `replace_file_content`)를 자유롭게 사용하여 단독 구현 수행. + - **`/multi-agent-mux-loop` 호출 시 (스킬 활성화 상태)**: 스킬 인터셉터 가드(Guardrail)가 작동하여 직접 수정 도구 호출을 거부(Interception)하고, **"슬래시 커맨드가 인보크되었으므로 직접 수정을 중단하고 `run_loop.sh`를 실행하여 위임하십시오"**라는 에러를 반환해 `run_loop.sh` 자율 위임 실행을 코딩적으로 강제. + +--- +*본 분석서는 Planner(`claude`)와 Creator(`agy`)의 협업 계획(Job `96b6e07b`) 및 리뷰어 만장일치 PASS 합의를 바탕으로 최종 작성된 수합 최적화 명세서입니다.* diff --git a/PLAN_HERDR.md b/PLAN_HERDR.md deleted file mode 100644 index 0c9a5dc..0000000 --- a/PLAN_HERDR.md +++ /dev/null @@ -1,74 +0,0 @@ -# 📋 PLAN_HERDR.md: herdr 기반 멀티플렉서 백엔드 전환 작업 계획서 - -이 문서는 기존 `tmux` 기반의 에이전트 라이프사이클 관리를 Rust 기반의 에이전트 인지형 멀티플렉서인 **herdr**로 전면 전환하기 위한 도입 배경, 아키텍처 전략 및 상세 작업 단계들을 정의합니다. - ---- - -## 1. 🔍 도입 배경 및 필요성 - -현재 운영 중인 `tmux` 기반 백엔드는 훌륭한 호환성을 제공하지만, 다음과 같은 구조적 한계와 간헐적인 프롬프트 유실 오류(Prompt-lock)를 동반합니다. - -### 🔴 기존 tmux 환경의 한계 -* **대략적인 정적 상태 감지 (Coarse Quiescence)**: 입력을 주입하기 전에 터미널이 키를 수락할 수 있는 휴지 상태인지 확인하기 위해, 셸 스크립트 상에서 `capture-pane`을 0.1~0.5초 주기로 돌려 화면 변경 여부를 체크합니다. 이로 인해 CPU 자원이 급증하는 멀티 에이전트 구동 상황에서 입력을 유실하거나 `Enter` 키가 씹히는 현상이 발생합니다. -* **TUI 모달 상태 기계 파싱의 비효율**: 에이전트가 띄운 다이얼로그(예: 인증, 신뢰 확인)를 인식하기 위해 터미널 하단 20줄의 문자열을 정규식으로 직접 파싱하므로, 에이전트 버전업에 따른 TUI 레이아웃 변경에 매우 취약합니다. - -### 🟢 herdr 도입 시 기대 효과 -* **PTY 레벨의 밀리초(ms) 단위 이벤트 제어**: `herdr`은 Rust 네이티브로 작성되어 PTY(가상 터미널) 입출력 스트림의 유휴 상태를 서브-밀리초 레벨로 감지합니다. 이로 인해 프롬프트 주입 실패 및 명령 유실 오류가 **근본적으로 제로(0)에 가깝게 줄어듭니다.** -* **에이전트 상태 인지 API**: 에이전트 프로세스의 상태(Working, Idle, Blocked, Done)를 멀티플렉서 레벨에서 해석해 소켓 API로 제공하므로, 지저분한 화면 파싱 코드 없이 정교한 자율 관제가 가능합니다. - ---- - -## 2. 🔀 형상 관리 및 배포 전략 - -두 백엔드(tmux/herdr)를 단일 코드베이스에서 듀얼 스위칭(`if/else`) 방식으로 지원하면 코드가 과도하게 무거워지고 버그 가능성이 높아집니다. 따라서 **독립된 브랜치 구조**로 깨끗하게 이원화하여 제공합니다. - -* **`main` 브랜치 (tmux 기반)**: - * **목표**: 어디서나 즉시 실행 가능한 고호환성 프로덕션 버전. - * **의존성**: 추가 설치가 필요 없는 표준 `tmux` 환경. -* **`herdr` 브랜치 (herdr 기반)**: - * **목표**: 대화식 락 오류가 완벽히 통제되는 워크스테이션(macOS/Linux) 최적화 고안전성 버전. - * **의존성**: `herdr` CLI 및 Unix 소켓 API 환경. - ---- - -## 3. 🎯 상세 구현 마일스톤 및 작업 계획 - -### 📍 Milestone 1: 개발 환경 구성 및 의존성 진단 -* [ ] **브랜치 격리**: `git checkout -b herdr` 브랜치 생성 및 격리 개발 공간 확보. -* [ ] **인스톨러 개정 (`deploy/install_mam.sh`)**: - * 호스트 의존성 체크 대상에 `herdr` 추가 (`tmux` 진단 제거). - * `herdr`이 미설치된 경우, 공식 설치 가이드라인(`https://herdr.dev/install.sh`) 안내 출력 및 조기 종료 처리. - * `.mam/` 격리 폴더 및 환경설정 배포 규칙을 `herdr` 스펙에 맞게 조정. - -### 📍 Milestone 2: 로우레벨 어댑터 전면 리팩토링 (`lib.sh`) -* [ ] **명령어 매핑**: `lib.sh` 내의 모든 `tmux` API 호출을 `herdr` 명령으로 전면 개정. - * `_tmux new-session` ➡️ `herdr run -d --name "$SESSION_NAME" -- "$CMD_FULL"` - * `_tmux capture-pane` ➡️ `herdr capture --name "$SESSION_NAME"` - * `_tmux send-keys` ➡️ `herdr send-keys --name "$SESSION_NAME" "$KEYS"` - * `_tmux kill-session` ➡️ `herdr kill --name "$SESSION_NAME"` -* [ ] **정적 상태 감지 함수 재작성 (`_pane_quiescent`)**: - * `herdr`이 기본 제공하는 세션 상태 조회 API를 파싱하여 PTY 정적 상태 여부를 판별하도록 대폭 경량화 및 고도화. -* [ ] **인풋 주입 엔진 고도화 (`send_keys_safe`)**: - * 복잡한 버퍼 제어(`set-buffer`/`paste-buffer`) 대신, `herdr` API를 경유한 다이렉트 프롬프트 주입 방식으로 단순화. - -### 📍 Milestone 3: 에이전트 라이프사이클 관리 도구 이관 -* [ ] **`create_session.sh` 수정**: - * `herdr` 기동 방식 및 pane PID 수집 로직 교체. - * `.mam/agent-sessions.yaml` 메타데이터 규격을 `herdr` 사양(예: `tmux_server` ➡️ `herdr_workspace`)에 맞게 정렬. -* [ ] **`resume_session.sh` 수정**: - * 죽은 `herdr` 프로세스를 감지하고 저장된 대화 ID와 함께 `herdr run`으로 복원하는 흐름 이식. -* [ ] **`stop_session.sh` 수정**: - * 에이전트 세션의 깔끔한 graceful 종료 및 최종 TUI 캡처 흐름을 `herdr` 규격으로 전환. - -### 📍 Milestone 4: 검증 및 루프 완주 -* [ ] **정적 분석**: `bash -n` 및 `shellcheck` 신규 경고 0건 검증. -* [ ] **오케스트레이션 루프 검증 (`run_loop.sh`)**: - * `run_loop.sh` 내부의 `delegate_job_safe` 실행을 `herdr` 세션 기반으로 연동하여 100% 자율 루프 구동 확인. - * 피어 리뷰어(`cline`, `claude`)들로부터 최종 `[VERDICT: PASS]` 서명 획득. - ---- - -## 4. 📈 사후 관리 및 형상 병합 정책 - -* `herdr` 브랜치의 개발 및 검증이 완주되어 `PASS` 서명이 누적되면, `deploy/INSTALL.md` 및 `README.md` 문서를 개정하여 각 브랜치별 설치 절차를 문서화합니다. -* `main` 브랜치의 공통 규칙 버그 수정 사항(예: `AGENTS.md` 수정 등)은 주기적으로 `herdr` 브랜치로 `git merge`하여 정책적 일치성을 유지합니다. diff --git a/PLAN_LOOP.md b/PLAN_LOOP.md deleted file mode 100644 index 8896c79..0000000 --- a/PLAN_LOOP.md +++ /dev/null @@ -1,108 +0,0 @@ -# 📑 자율 반복 정제 루프 스킬 (`multi-agent-mux-loop`) 개발 계획서 - -이 문서는 멀티 에이전트 자율 오케스트레이션 루프(`multi-agent-mux-loop`)의 **최종 안전/가드레일 옵션 규격을 포함하여 완벽하게 정제된 마스터 계획서**입니다. -리뷰어 에이전트들의 교차 2차 피드백(Verdict 파싱, 자가 리뷰 방지, 타임아웃 보강)을 완벽하게 수렴하여 정교하게 갱신되었습니다. - ---- - -## 1. ⚙️ 최종 스킬 명령 및 전체 옵션 세트 명세 (CLI Spec) - -```bash -$ bash .agents/skills/multi-agent-mux-loop/scripts/run_loop.sh \ - [--plan] \ - [--plan-talk N] \ - [--reviewer "reviewer-1,reviewer-2"] \ - [--all-reviewer] \ - [--max-loop N] \ - [--verbose] \ - [--cleanup] \ - --target-agent "" \ - --task "수행할 작업 목표" -``` - -### 📥 옵션 상세 리스트 및 가드레일 제약 - -| 옵션명 | 기본값 | 분류 | 역할 및 안전 조치 | -|---|---|---|---| -| `--plan` | 비활성 | 기능 | Planner 에이전트를 기동하여 협력 계획 수립 및 토론 단계 개시. (비활성화 시 기존 계획서를 로드하며, 계획서가 없는 경우 Creator가 직접 계획 및 설계를 수립하여 구동) | -| `--plan-talk N` | `1` | 안전 | 플래너-작업자 간 토론 왕복 횟수 상한선. 토큰 낭비 무한 토론 차단. | -| `--reviewer "A,B"` | 비활성 | 기능 | 지정된 peer 리뷰어 에이전트 세션(들)에 피드백 루프 의뢰 (주 작업자 세션은 강제 제외). | -| `--all-reviewer` | 비활성 | 기능 | 레지스트리 상의 모든 `role: reviewer` 세션들을 전수 자동 수집하여 의뢰 (주 작업자 세션은 강제 제외). | -| `--max-loop N` | `3` | **안전 (필수)** | 반려(`NOT PASS`) 시 최대 수정 횟수 제한. **토큰 비용 폭주 방지 가드레일.** | -| `--verbose` | 비활성 | 편의 | 단계별 타임라인 진행 상태 및 잡 매핑 로그의 실시간 상세 출력. | -| `--cleanup` | 비활성 | 편의 | 루프 완료 후 성공한 임시 잡 파일(`.mam/jobs/`)들의 자동 클린업 청소. | -| `--target-agent` | (필수) | 인프라 | 구현을 처리할 주 개발자(Creator) 세션 이름 명시. | -| `--task` | (필수) | 인프라 | 자율 루프에 전달할 최종 구현 지시사항 텍스트. | - ---- - -## 🔄 2. 자율 오케스트레이션 상세 파이프라인 (Sequence Flow) - -```mermaid -sequenceDiagram - autonumber - actor User as 사용자 / run_loop.sh - participant Plan as Planner Agent - participant Dev as Creator Agent - participant Rev as Reviewer Agents - - User->>User: run_loop.sh 기동 (옵션 세트 검증 및 대상 예외 필터링) - - %% Planning & Challenge discussion - alt --plan 지정 시 - User->>Plan: delegate-job (계획 수립 지시) - Plan-->>User: 계획서 도출 완료 - loop 지정된 --plan-talk 횟수 동안 반복 (기본 1회) - User->>Dev: delegate-job (계획서 비판적 검토 및 이의제기 지시) - Dev->>Plan: 계획서의 맹점 1가지 이상 Challenge 메일 교환 - Plan-->>Dev: 수정 반영 및 최종 계획 합의 - end - else --plan 미지정 - alt 기존 계획 존재 시 - User->>Dev: 기존 계획서 로드 및 구현 지시 - else 계획 미존재 시 - User->>Dev: Self-planning 지시 (스스로 계획/설계 수립하여 구현) - end - end - - %% Execution - User->>Dev: delegate-job (작업 지시) - Dev-->>User: 구현 완료 (git diff 발생) - - %% Peer-Review Loop with Max-Loop constraint - loop 최대 --max-loop 횟수 동안 반복 (기본 3회) - alt 리뷰어 옵션 지정 시 (--reviewer or --all-reviewer) - User->>Rev: delegate-job (정식 peer 코드 리뷰 위임) - Rev-->>User: [VERDICT: PASS] 또는 [VERDICT: NOT PASS] 태그 리포트 제출 - alt 100% PASS 충족 시 - Note over User,Rev: 루프 즉시 탈출 (성공) - else NOT PASS 검출 시 - User->>Dev: 피드백 전달 및 수정 지시 (피드백 난이도에 따라 Planner 우회 계획 갱신 적용) - end - else 리뷰어 미지정 - User->>Dev: Self-Review 지시 (자가 검증 및 자율 종결) - end - end - - %% Cleanup & Final Report - alt --cleanup 지정 시 - User->>User: 임시 잡 폴더 청소 - end - User-->>User: 최종 결과 요약 출력 및 마감 -``` - ---- - -## 🛠️ 3. 개발 로직 및 안전 파싱 체크포인트 - -### 1) Verdict 판정 파서 안전 가이드라인 (Fail-Closed & Precedence) -* **NOT PASS 우선권**: 리뷰 리포트 본문 내에 `[VERDICT: NOT PASS]` 가 단 한 번이라도 등장하면, `[VERDICT: PASS]` 문구 존재 여부와 상관없이 무조건 **NOT PASS**로 처리하여 오독 필터링을 방지합니다. -* **Fail-Closed 기본 실패주의**: 태그 누락이나 malformed 리포트로 인해 두 토큰이 모두 스캔되지 않을 경우, 통과시키지 않고 **NOT PASS(실패)** 로 취급하여 루프 무한 기동 및 맹점 통과를 원천 차단합니다. -* **템플릿 명시**: 리뷰어 위임 잡 발행 시, 최종 결과 요약 행에 정형화된 태그 `[VERDICT: PASS]` 혹은 `[VERDICT: NOT PASS]`를 리포트 본문 하단에 반드시 기재하도록 프롬프트 템플릿에 명시적으로 추가합니다. - -### 2) 자가 리뷰 방지 가드 (Exclusion Rule) -* `--all-reviewer` 혹은 `--reviewer` 목록을 소집할 때, 해당 작업을 수행한 대상 개발자 세션인 `$TARGET_AGENT` 는 **리뷰어 매핑 목록에서 강제로 배제(Exclude)** 하도록 파싱 쉘 스크립트에서 필터링을 적용합니다. - -### 3) 쉘 예외 처리 및 대기 타임아웃 (Error Guard & Timeout) -* `grep -oP` 나 `find | head` 시 매칭이 없을 때 `set -eo pipefail`에 의해 쉘 스크립트 전체가 비명횡사하지 않도록 `|| true` 가드 및 공백 체크문을 엄밀히 적용합니다. -* `wait_for_job` 함수 실행 시 타임아웃 가드레일(`WAIT_TIMEOUT`, 기본값 3600초)을 명시적으로 설계하여 무한 루프 행(Hang) 현상을 차단합니다. diff --git a/README.ko.md b/README.ko.md index 098f73b..0a627d7 100644 --- a/README.ko.md +++ b/README.ko.md @@ -1,6 +1,6 @@ -# tmux-agent-orchestration (다중 에이전트 Tmux 오케스트레이션 및 메시징 백플레인) +# herdr-agent-orchestration (다중 에이전트 Herdr 오케스트레이션 및 메시징 백플레인) -Tmux와 MQTT 브로커를 기반으로 구축된 고신뢰성 **다중 에이전트 오케스트레이션 및 메시징 백플레인** 프레임워크입니다. Claude, Hermes 등 다중 LLM 백엔드 에이전트 전반에 걸쳐 장시간 수행되는 작업(코드 생성, 리팩토링, 보안 검토 등)을 조정, 격리 및 감사할 수 있도록 설계되었습니다. +Herdr와 MQTT 브로커를 기반으로 구축된 고신뢰성 **다중 에이전트 오케스트레이션 및 메시징 백플레인** 프레임워크입니다. Claude, Hermes 등 다중 LLM 백엔드 에이전트 전반에 걸쳐 장시간 수행되는 작업(코드 생성, 리팩토링, 보안 검토 등)을 조정, 격리 및 감사할 수 있도록 설계되었습니다. --- @@ -8,8 +8,8 @@ Tmux와 MQTT 브로커를 기반으로 구축된 고신뢰성 **다중 에이전 최근의 에이전트 워크플로우는 세션 타임아웃, 프로세스 격리 부재, 터미널 뷰포트 잘림(스크롤백 한계로 인한 디버그 로그 유실), 복잡한 동시성 경쟁 등의 문제를 자주 겪습니다. -**tmux-agent-orchestration**은 다음과 같은 솔루션을 통해 이를 해결합니다: -1. **Tmux 기반 프로세스 격리:** 개별적으로 격리된 tmux 환경 내부에 에이전트 CLI 세션을 띄워, 백그라운드에서 끊김 없이 장시간 작업이 영속되도록 보장합니다. +**herdr-agent-orchestration**은 다음과 같은 솔루션을 통해 이를 해결합니다: +1. **Herdr 기반 프로세스 격리:** 개별적으로 격리된 herdr 환경 내부에 에이전트 CLI 세션을 띄워, 백그라운드에서 끊김 없이 장시간 작업이 영속되도록 보장합니다. 2. **비동기 이벤트 기반 아키텍처:** MQTT 브로커를 메시징 백플레인으로 활용하여, 에이전트 간 상태 전이 단계(`started`, `progress`, `completed`, `error`)를 긴밀하게 제어 및 조정합니다. 3. **Multi-Agent Mux (MAM):** 파일 기반의 어드바이저리 락(`fcntl`) 및 SQLite WAL 데이터베이스(`.mam/agent-sessions.db`)를 결합하여, 동시성 작업 선점 경쟁을 방지하고 에이전트 세션의 라이프사이클을 드리프트 없이 관리합니다. 4. **리뷰어 기반 고신뢰 검증 루프:** Worker 에이전트가 구현한 코드 변경 사항에 대해 상이한 강점을 지닌 전문 검증 에이전트(예: 논리 흐름을 정밀 검토하는 Claude, 셸 문법 및 안전성을 빠르게 확인하는 Hermes)들로부터 최종 `PASS` 판정을 획득한 뒤 머지하도록 교차 검증 루프를 자동화합니다. @@ -20,11 +20,11 @@ Tmux와 MQTT 브로커를 기반으로 구축된 고신뢰성 **다중 에이전 모든 오케스트레이션 스킬들은 `.agents/skills/` 디렉터리 하위에 정의되어 있습니다: -* **`multi-agent-mux-create`**: 격리된 tmux 세션을 생성하고 특정 에이전트 CLI를 백그라운드에서 구동합니다. 프로세스 PID 캡처, 메타데이터 레지스트리 업데이트 및 에이전트 인증 검증을 처리합니다. +* **`multi-agent-mux-create`**: 격리된 herdr 세션을 생성하고 특정 에이전트 CLI를 백그라운드에서 구동합니다. 프로세스 PID 캡처, 메타데이터 레지스트리 업데이트 및 에이전트 인증 검증을 처리합니다. * **`multi-agent-mux-stop`**: 에이전트 CLI 세션을 정상 종료 키 입력(`/exit` 또는 `Exit`)을 통해 안전하게 닫고, 격리된 대화 히스토리 및 데이터베이스 로그를 삭제(purge)하는 클린업 작업을 수행합니다. * **`multi-agent-mux-resume`**: 디스크 또는 캐시에서 특정 워크스페이스의 세션 UUID를 조회하여 기존 대화 상태(`claude -r ` 또는 `hermes --resume `) 그대로 세션을 복구하고 재개합니다. -* **`multi-agent-mux-status`**: 활성화된 모든 세션의 실시간 작동 상태를 쿼리하여 PID 정합성, 실행 명령 포맷, tmux 실제 상태와 데이터베이스 간의 동기화 드리프트를 감지합니다. -* **`multi-agent-mux-monitor`**: 백그라운드에서 Kanban Reconcile 프로세스로 실행되어, 실시간 tmux 세션 변화를 모니터링하고 `.mam/agent-sessions.yaml` 메타데이터 파일에 상태를 동기화합니다. +* **`multi-agent-mux-status`**: 활성화된 모든 세션의 실시간 작동 상태를 쿼리하여 PID 정합성, 실행 명령 포맷, herdr 실제 상태와 데이터베이스 간의 동기화 드리프트를 감지합니다. +* **`multi-agent-mux-monitor`**: 백그라운드에서 Kanban Reconcile 프로세스로 실행되어, 실시간 herdr 세션 변화를 모니터링하고 `.mam/agent-sessions.yaml` 메타데이터 파일에 상태를 동기화합니다. * **`multi-agent-mux-delegate-job`**: 태스크를 비동기식 독립 잡으로 위임 및 관리하는 핵심 모듈입니다: * `registry.py`: 파일 락(`fcntl`)을 활용해 경쟁 조건 없이 잡을 원자적으로 등록 및 점유(claim)합니다. * `job_subscriber.py`: MQTT 백플레인 채널을 구독하여 실시간 상태 이벤트를 수집하고 이를 감사 로그(audit trail)에 기록합니다. @@ -37,7 +37,7 @@ Tmux와 MQTT 브로커를 기반으로 구축된 고신뢰성 **다중 에이전 이 시스템은 크게 두 가지 계층(Layer)을 통해 다중 워크스페이스에서 작동하는 LLM 에이전트들을 조율합니다: -1. **Layer A — Tmux 오케스트레이션 (lib.sh + status/resume/stop/create)**: 워크스페이스별 에이전트 세션을 독립된 tmux 인스턴스로 분리 실행하고, `.mam/agent-sessions.yaml` 및 SQLite 데이터베이스(`.mam/agent-sessions.db`)를 통해 에이전트 세션 메타데이터의 단일 참조 지점(Single Source of Truth)을 유지합니다. +1. **Layer A — Herdr 오케스트레이션 (lib.sh + status/resume/stop/create)**: 워크스페이스별 에이전트 세션을 독립된 herdr 인스턴스로 분리 실행하고, `.mam/agent-sessions.yaml` 및 SQLite 데이터베이스(`.mam/agent-sessions.db`)를 통해 에이전트 세션 메타데이터의 단일 참조 지점(Single Source of Truth)을 유지합니다. 2. **Layer B — 비동기 잡 위임 (delegate-job)**: 에이전트에 특정 태스크를 전송하고 비동기 이벤트 채널(MQTT)을 통해 진행 상황과 완료 여부를 모니터링합니다. 두 레이어는 파일 I/O 처리를 위한 하나의 핵심 관문인 `lib.sh::atomic_dump_yaml`을 공유합니다. 모든 YAML/DB 쓰기 작업은 SQLite 데이터베이스 트랜잭션 락과 데이터 스키마 유효성 검증을 거칩니다. @@ -74,12 +74,12 @@ Tmux와 MQTT 브로커를 기반으로 구축된 고신뢰성 **다중 에이전 +--------+ ``` -### 🔒 Tmux 서버 격리 (Tmux Server Isolation) +### 🔒 Herdr 서버 격리 (Herdr Server Isolation) -에이전트 세션 간의 충돌 및 시스템 전역 tmux 프로세스와의 혼선을 막기 위해 독립된 서버 소켓 환경을 보장합니다: -* **워크스페이스별 심(Shim):** `_init_tmux_isolation` 및 `_resolve_real_tmux_path` 함수가 `/tmp/multi-agent-tmux-shim//tmux` 경로에 독립된 심 디렉터리를 구성하고, 일반 tmux 명령 실행 시 자동으로 `tmux -L ` 형태의 독립 소켓 서버를 사용하게 만듭니다. -* **PATH 환경변수 변조:** 자식 프로세스를 생성할 때 `PATH` 변수 맨 앞에 심 디렉터리 경로를 삽입합니다. 이로 인해 에이전트의 내부 셸에서 수행되는 모든 `tmux` 명령어는 해당 격리 서버 소켓으로 강제 제약됩니다. -* **환경 복구:** `TMUX_SERVER_NAME`을 `default`로 설정하는 경우 PATH 오버라이드가 정리되고 기본 전역 tmux 서버를 사용하게 됩니다. +에이전트 세션 간의 충돌 및 시스템 전역 herdr 프로세스와의 혼선을 막기 위해 독립된 서버 소켓 환경을 보장합니다: +* **워크스페이스별 심(Shim):** `_init_herdr_isolation` 및 `_resolve_real_herdr_path` 함수가 `/tmp/multi-agent-herdr-shim//herdr` 경로에 독립된 심 디렉터리를 구성하고, 일반 herdr 명령 실행 시 자동으로 `herdr -L ` 형태의 독립 소켓 서버를 사용하게 만듭니다. +* **PATH 환경변수 변조:** 자식 프로세스를 생성할 때 `PATH` 변수 맨 앞에 심 디렉터리 경로를 삽입합니다. 이로 인해 에이전트의 내부 셸에서 수행되는 모든 `herdr` 명령어는 해당 격리 서버 소켓으로 강제 제약됩니다. +* **환경 복구:** `HERDR_SERVER_NAME`을 `default`로 설정하는 경우 PATH 오버라이드가 정리되고 기본 전역 herdr 서버를 사용하게 됩니다. ### 🛡️ 동시성 설계 및 쓰기 직렬화 diff --git a/README.md b/README.md index b6d41fe..cc07e80 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ -# tmux-agent-orchestration +# herdr-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). +An advanced, high-reliability **Multi-Agent Orchestration & Messaging Backplane** framework built on Herdr 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). --- @@ -8,8 +8,8 @@ An advanced, high-reliability **Multi-Agent Orchestration & Messaging Backplane* 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. +**herdr-agent-orchestration** addresses these problems by providing: +1. **Herdr-based Process Isolation:** Spawning LLM client sessions inside dedicated, isolated herdr 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. @@ -30,7 +30,7 @@ Alternatively, if you have already cloned the repository locally, run the instal bash deploy/install.sh ``` -The idempotent installer automatically validates system dependencies (tmux, python3, and PyYAML), creates the python virtual environment (`.venv`), installs dependencies, copies `.env.example` as `.env`, and initializes the `.agents/` scaffolding. +The idempotent installer automatically validates system dependencies (herdr, python3, and PyYAML), creates the python virtual environment (`.venv`), installs dependencies, copies `.env.example` as `.env`, and initializes the `.agents/` scaffolding. --- @@ -38,11 +38,11 @@ The idempotent installer automatically validates system dependencies (tmux, pyth All orchestration functionalities are structured under the `.agents/skills/` directory: -* **`multi-agent-mux-create`**: Spawns isolated tmux sessions running specified agent CLI wrappers. It captures system processes, updates metadata registries, and enforces authentication checks. +* **`multi-agent-mux-create`**: Spawns isolated herdr sessions running specified agent CLI wrappers. It captures system processes, updates metadata registries, and enforces authentication checks. * **`multi-agent-mux-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). * **`multi-agent-mux-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 ` or `hermes --resume `). -* **`multi-agent-mux-status`**: Queries the running states of all active sessions, detecting PID mismatches, command signatures, and drifts between actual tmux instances and the registry database. -* **`multi-agent-mux-monitor`**: A long-running Kanban reconcile worker that dynamically monitors tmux sessions and synchronizes states to `.mam/agent-sessions.yaml`. +* **`multi-agent-mux-status`**: Queries the running states of all active sessions, detecting PID mismatches, command signatures, and drifts between actual herdr instances and the registry database. +* **`multi-agent-mux-monitor`**: A long-running Kanban reconcile worker that dynamically monitors herdr sessions and synchronizes states to `.mam/agent-sessions.yaml`. * **`multi-agent-mux-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. @@ -55,7 +55,7 @@ All orchestration functionalities are structured under the `.agents/skills/` dir The system coordinates LLM agents across multiple workspaces through two core layers: -1. **Layer A — Tmux Orchestration (lib.sh + status/resume/stop/create)**: Runs the agents (one tmux session per agent-workspace combination) and maintains an authoritative registry in `.mam/agent-sessions.yaml` (+ `.mam/agent-sessions.db`). +1. **Layer A — Herdr Orchestration (lib.sh + status/resume/stop/create)**: Runs the agents (one herdr session per agent-workspace combination) and maintains an authoritative registry in `.mam/agent-sessions.yaml` (+ `.mam/agent-sessions.db`). 2. **Layer B — Async Job Delegation (delegate-job)**: Dispatches a task to an agent and observes progress and completion via an event channel. These two layers share one lock-guarded chokepoint for file I/O: `lib.sh::atomic_dump_yaml`. Every write is protected by an exclusive SQLite database transaction lock and schema validation. @@ -92,12 +92,12 @@ These two layers share one lock-guarded chokepoint for file I/O: `lib.sh::atomic +--------+ ``` -### 🔒 Tmux Server Isolation +### 🔒 Herdr Server Isolation -To prevent workspace tmux processes from interfering with each other or with system tmux servers, the framework enforces isolated tmux environments: -* **Per-Workspace Shim:** `_init_tmux_isolation` and `_resolve_real_tmux_path` instantiate a per-workspace shim directory under `/tmp/multi-agent-tmux-shim//tmux` that intercepts tmux commands and wraps them in `tmux -L `. -* **PATH Rewriting:** The `PATH` environment variable is dynamically prepended with the shim path in all child processes. This ensures any `tmux` invocation within the agent's process tree is restricted to its isolated socket server. -* **Environment Restoration:** If `TMUX_SERVER_NAME` is set to `default`, the PATH override is removed, reverting to the default global tmux server. +To prevent workspace herdr processes from interfering with each other or with system herdr servers, the framework enforces isolated herdr environments: +* **Per-Workspace Shim:** `_init_herdr_isolation` and `_resolve_real_herdr_path` instantiate a per-workspace shim directory under `/tmp/multi-agent-herdr-shim//herdr` that intercepts herdr commands and wraps them in `herdr -L `. +* **PATH Rewriting:** The `PATH` environment variable is dynamically prepended with the shim path in all child processes. This ensures any `herdr` invocation within the agent's process tree is restricted to its isolated socket server. +* **Environment Restoration:** If `HERDR_SERVER_NAME` is set to `default`, the PATH override is removed, reverting to the default global herdr server. ### 🛡️ Concurrency Design & Write Serialization diff --git a/RECOMMENDED.md b/RECOMMENDED.md deleted file mode 100644 index 991fa1d..0000000 --- a/RECOMMENDED.md +++ /dev/null @@ -1,101 +0,0 @@ -# 📋 Recommended Multi-Agent Session Architecture Guide - -본 문서는 `multi-agent-mux` 환경에서 오케스트레이션 루프(`multi-agent-mux-loop`)를 활용해 고품질 소프트웨어를 개발할 때 가장 권장되는 **3-에이전트 역할 분리 아키텍처**와 설정 방법 및 추천 이유에 대해 설명합니다. - ---- - -## 👥 1. 추천 3-에이전트 구성 (Roles & Configuration) - -`multi-agent-mux` 환경에서는 다음 세 가지 전문 세션을 생성하여 상시 기동해 두는 것이 가장 이상적입니다. - -```mermaid -graph TD - User([사용자/Orchestrator]) <--> AGY_Parent[Antigravity Parent] - AGY_Parent -->|1. 계획 수립 위임| Planner[Planner 세션
claude] - AGY_Parent -->|2. 구현 위임| Creator[Creator 세션
agy] - AGY_Parent -->|3. 교차 검증 위임| Reviewer[Reviewer 세션
cline] - - Planner -->|설계/피드백 루프| Creator - Creator -->|구현 완료| Reviewer - Reviewer -->|Verdict PASS/NOT PASS| Planner -``` - -### ① Planner 에이전트 -* **역할 (Role)**: `planner-reviewer` -* **주요 임무**: 전체 아키텍처 아웃라인 설계, 구현 계획서 수립, 이의 제기 수렴 및 계획 개정(Refinement). -* **추천 에이전트 종류**: `claude` (긴 추론 맥락과 설계 완성도가 높음) -* **생성 명령어**: - ```bash - # planner-reviewer 역할로 claude 세션 기동 - bash .agents/skills/multi-agent-mux-create/multi-agent-mux-create \ - --agent claude \ - --role planner-reviewer \ - --name canary-projects-multi-agent-mux-planner-reviewer-claude - ``` - -### ② Creator 에이전트 (주작업자) -* **역할 (Role)**: `creator` -* **주요 임무**: 계획서상의 제약조건 검토 및 이의제기(Challenge), 실제 코드베이스 구현 편집, DoD 자가 검증. -* **추천 에이전트 종류**: `agy` (기민한 도구 실행 속도 및 로컬 파일 편집 최적화) -* **생성 명령어**: - ```bash - # creator 역할로 agy 세션 기동 - bash .agents/skills/multi-agent-mux-create/multi-agent-mux-create \ - --agent agy \ - --role creator \ - --name canary-projects-multi-agent-mux-creator-agy - ``` - -### ③ Reviewer 에이전트 -* **역할 (Role)**: `reviewer` -* **주요 임무**: 구현된 변경분(`git diff`)과 구현 계획서를 기반으로 빌드 가능성, 린트, 로직 유실 교차 피어 리뷰. -* **추천 에이전트 종류**: `cline` (안정적인 컴파일 도구 활용 및 린터 체크 강점) -* **생성 명령어**: - ```bash - # reviewer 역할로 cline 세션 기동 - bash .agents/skills/multi-agent-mux-create/multi-agent-mux-create \ - --agent cline \ - --role reviewer \ - --name canary-projects-multi-agent-mux-reviewer-cline - ``` - ---- - -## 💡 2. 왜 3개의 에이전트 분리를 강력히 추천하는가? - -부모 에이전트(Antigravity)가 오케스트레이션과 코드 개발을 모두 처리하지 않고, 별도의 격리된 3개의 역할 세션을 두는 데에는 다음과 같은 명확한 공학적 이유가 있습니다. - -### ① 대화창 컨텍스트(Context Window) 오염 방지 -* **디테일의 지옥**: 에이전트가 코드를 탐색하고, 컴파일 오류를 잡고, 수많은 파일라인을 편집하는 세부 구현 과정은 수십만 토큰에 달하는 방대한 런타임 로그와 코드를 누적시킵니다. -* **해결책**: 만약 오케스트레이터(부모 에이전트)가 이를 직접 수행하면 사용자님과의 대화창 컨텍스트가 구현 로그로 가득 차, 이전에 의논했던 아키텍처 제약이나 중요 요구사항을 쉽게 잊어버립니다. 역할을 격리함으로써 각 세션은 자신의 세부 구현 컨텍스트만 소비하고 소멸합니다. - -### ② 비동기 개발 자율성 (Asynchronous Autonomy) -* **대기 시간 최소화**: 오케스트레이션 루프가 설계 검토, 피드백, 자가 수정 등을 수차례 반복하며 백그라운드(tmux)에서 스스로 문제를 해결해 나가는 동안, 사용자님은 저(부모 에이전트)와 멈춤 없이 계속해서 고수준 설계 및 다른 기능에 대한 논의를 이어나갈 수 있습니다. -* **생산성 극대화**: 부모 에이전트가 코딩을 하느라 대화를 블로킹하는 현상이 발생하지 않습니다. - -### ③ 교차 검증을 통한 객관성 확보 (Peer Review Objectivity) -* **작성자와 검증자의 분리**: 코드를 직접 짠 에이전트가 자기 자신의 코드를 완벽하게 리뷰하는 것은 불가능에 가깝습니다(인지 편향 발생). -* **해결책**: 구현을 전담한 `Creator`와, 이를 객관적인 삼자 관점에서 검토하는 `Reviewer` 세션을 철저히 독립시킴으로써 코드 품질 결함을 높은 확률로 선제 필터링할 수 있습니다. - -### ④ 이기종 모델/도구의 결합 (Heterogeneous Collaboration) -* **각자 잘하는 분야의 극대화**: - * **Planner (Claude)**: 설계 및 아키텍처 정합성 수립에 특화 - * **Creator (Antigravity/Agy)**: 신속하고 정확한 로컬 파일 편집 및 도구 호출에 특화 - * **Reviewer (Cline)**: 린트 체크, 빌드 테스트 등 철저한 안전망 검증에 특화 -* 이러한 하이브리드 조합을 구성할 때 루프 전체의 최종 도달 성공률이 가장 높게 나타납니다. - ---- - -## 🛠️ 3. 3-에이전트 루프 실행 방법 - -에이전트들이 생성되어 기동(Running) 중인 경우, 다음과 같이 계획 수립(`--plan`) 및 전체 교차 리뷰(`--all-reviewer`) 옵션을 주어 자율 협업 개발을 시작할 수 있습니다. - -```bash -bash .agents/skills/multi-agent-mux-loop/scripts/run_loop.sh \ - --target-agent "canary-projects-multi-agent-mux-creator-agy" \ - --plan \ - --all-reviewer \ - --task "여기에 개발하고자 하는 태스크의 최종 목표를 상세히 기술합니다." -``` - -이 루프는 **기획 ➡️ 작업자 이의제기 ➡️ 계획 개정 ➡️ 코드 개발 ➡️ 교차 피어 리뷰 ➡️ 피드백 수렴 재구현**의 전 과정을 자동으로 진행하여, 빌드 및 린트가 보장되는 코드를 저장소에 자동으로 커밋 및 병합합니다. diff --git a/REPORT.md b/REPORT.md deleted file mode 100644 index 56246a1..0000000 --- a/REPORT.md +++ /dev/null @@ -1,141 +0,0 @@ -# Multi-Agent Mux (MAM) Architecture & Orchestration Report - -본 보고서는 **Multi-Agent Mux (MAM)** 프로젝트의 개발 과정과 아키텍처를 바탕으로, 다중 자율 AI 에이전트(Claude, Agy/Antigravity, Cline, Hermes 등)를 효과적으로 오케스트레이션하기 위해 필요한 핵심 기능과 이를 구현한 방법론, 그리고 각 기능이 부재할 경우 발생하는 장애 문제점을 구체적 예시와 함께 종합 정리한 문서입니다. - ---- - -## 1. 개요 (Executive Summary) - -현대 AI 에이전트 워크플로우는 세션 타임아웃, 프로세스 격리 부재, 터미널 뷰포트 잘림, 단일 에이전트의 자기 과신(Self-Confidence) 오류 등 다양한 문제점을 내포하고 있습니다. - -**Multi-Agent Mux**는 **Tmux/Herdr** 프로세스 관리자와 **MQTT 메시징 백플레인**을 결합하여, 여러 LLM 에이전트가 안전하게 프로세스를 격리받고 비동기로 이벤트를 주고받으며 **Planner ➡️ Creator ➡️ Reviewers** 간의 자율 검증 및 교차 리뷰 루프를 수행할 수 있도록 설계된 고신뢰성 오케스트레이션 프레임워크입니다. - ---- - -## 2. 코어 스킬 구성 명세 (Core Skills Inventory) - -프레임워크의 모든 핵심 제어 로직은 `.agents/skills/` 하위의 독립된 스킬 모듈로 응집되어 있으며, 각 스킬의 기능은 다음과 같습니다. - -* **`multi-agent-mux-create`** - * 지정된 작업 공간에 최적화된 명칭으로 독립된 에이전트 세션을 새로 구동하고, 초기 메타데이터를 원자적으로 등록합니다. - * 에이전트 구동 즉시 워크스페이스 맥락과 자신의 역할(Role)을 스스로 파악하도록 자동 온보딩 지시서 주입을 지원합니다. -* **`multi-agent-mux-resume`** - * 이전에 중지되거나 중단된 에이전트의 대화 식별자(UUID)를 디스크 및 레지스트리에서 추적하여 이전 문맥 그대로 세션을 복원합니다. - * 에이전트 기동 직후 필요한 권한 우회 및 복구 수락 대화상자를 백그라운드 키스트로크 주입으로 자동 처리합니다. -* **`multi-agent-mux-stop`** - * 에이전트 TUI 화면 뷰포트를 최종 스냅샷으로 보존하고 `Safe Exit Key` ➡️ `SIGTERM` ➡️ `SIGKILL` 다단계 수순으로 안전하게 정지시킵니다. - * 에이전트의 대화 파일(JSONL/DB)을 디스크에 영구 보존하여 추후 언제든지 재개(`status=stopped`)할 수 있도록 상태를 기록합니다. -* **`multi-agent-mux-status`** - * 실제 실행 중인 OS 프로세스 현황과 레지스트리 기록 간의 불일치(Drift) 및 동작 상태를 안전하게 즉시 표기합니다. - * 데이터베이스나 프로세스 상태 변경을 유발하지 않는 순수 읽기 전용(Read-only) 모드로 시스템의 정합성을 검증합니다. -* **`multi-agent-mux-monitor`** - * 백그라운드에서 지속 구동되어 죽은 세션 격하, 신규 세션 자동 등록, 디스크 로그와 UUID 동기화를 자동 화해(Reconciliation)합니다. - * 운영체제 Tmux/Herdr 런타임과 YAML 레지스트리 데이터 간의 괴리를 실시간으로 자동 복구합니다. -* **`multi-agent-mux-delegate-job`** - * 타 에이전트에게 비동기 태스크를 위임하고, MQTT 메시징 백플레인을 통해 실행 상태(`started` ➡️ `completed`/`error`)를 관찰합니다. - * 단일 작업 위임(`direct`)부터 에이전트 간 1:1 토론(`discuss`), 검증 루프(`loop`)까지 다양한 비동기 작업 위임 패턴을 처리합니다. -* **`multi-agent-mux-loop`** - * 설계(Planner) ➡️ 구현(Creator) ➡️ 교차 검수(Reviewers)로 이어지는 자율 개발 및 검증 순환 루프를 오케스트레이션합니다. - * 지정되거나 자동 수집된 모든 리뷰어의 만장일치 `[VERDICT: PASS]` 판정을 얻을 때까지 자율 교정 작업을 자동 반복합니다. - ---- - -## 3. Multi-Agent Orchestration을 위한 핵심 기능 및 구현 방법 (부재 시 장애 예시 포함) - -다중 에이전트 협업 환경을 구축하기 위해 필수적이었던 8가지 주요 기능과, 각 기능이 부재할 경우 발생하는 실제 장애 문제점 및 구체적인 구현 기법입니다. - -### 🔑 1) 프로세스 및 실행 환경 격리 (Environment Isolation) -* **기능 부재 시 발생하는 문제 (구체적 장애 예시)**: - * *인증 및 설정 파일 오염*: 서로 다른 에이전트(예: Claude와 Agy)가 동일한 기본 홈 디렉토리(`~/.gemini`, `~/.claude`)를 공유하면, 한 에이전트가 설정을 덮어쓰거나 로그인 세션을 건드려 상대방 에이전트의 인증이 갑자기 해제되는 장애가 발생합니다. - * *초기 대화상자 차단 패닉*: 예컨대 Agy 에이전트가 격리되지 않은 환경에서 구동될 경우 약관 동의(TOS)나 테마 설정 마법사 화면이 매번 출력되어 프롬프트 입력창이 상시 차단(Prompt Lockout)되는 현상이 일어납니다. -* **필요성**: 에이전트 간 설정 파일, 캐시, 세션 이름 및 환경 변수 충돌을 물리적으로 막아야 합니다. -* **구현 방법**: - * `herdr --session ` 명령을 활용해 에이전트 그룹마다 완전히 독립된 소켓과 서버 세션을 부여했습니다. - * 에이전트별로 워크스페이스 내에 임시 홈 디렉토리(`.mam/agent_homes/`)를 프로비저닝하고 `HOME` 또는 `CLAUDE_CONFIG_DIR` 환경변수를 덮어씌워 완벽히 독립된 가상 홈 디렉토리를 제공했습니다. - -### 🗃️ 2) 에이전트 관리를 위한 이중 레지스트리 분리 (`agent-sessions.yaml` vs `agent-sessions.db`) -* **기능 부재 시 발생하는 문제 (구체적 장애 예시)**: - * *YAML 단독 사용 시*: 여러 에이전트와 모니터링 프로세스가 동시 쓰기를 감행하다 텍스트 파일이 도중에 깨져 `YAML parsing syntax error`가 발생하여 전체 시스템 레지스트리가 즉시 마비됩니다. - * *DB 단독 사용 시*: 바이너리 데이터베이스로만 세션을 관리할 경우 개발자나 외부 도구가 `git status`, `cat`, 마크다운 뷰어 등으로 현재 에이전트 세션의 상태나 장애 원인을 직관적으로 디버깅할 수 없어 가시성이 완전 상실됩니다. -* **필요성**: 직관적 디버깅 가시성(Human-Readability)과 고성능 동시 트랜잭션 안전성(Transactional Integrity)이라는 두 가지 목적을 동시에 달성해야 합니다. -* **구현 방법**: - * `.mam/agent-sessions.db` (SQLite)를 내부 동시성 제어 및 원자적 상태 변경의 진실 원천(Single Source of Truth)으로 지정했습니다. - * DB 트랜잭션 커밋 완료 직후 PyYAML 기반 헬퍼 함수(`atomic_dump_yaml`)를 통해 정제된 데이터를 `.mam/agent-sessions.yaml` 파일로 원자적 동기화 덤프(`os.replace`)하여, 사람과 시스템 모두 만족하는 이중화 구조를 구축했습니다. - -### 🔄 3) 역할별 에이전트 페르소나 기반 자율 품질 합의 및 리뷰 루프 (Persona-based Autonomous Consensus Loop) -* **기능 부재 시 발생하는 문제 (구체적 장애 예시)**: - * *단일 에이전트 자기 환각(Hallucination) 머지*: 코드 작성 에이전트 혼자 작업을 진행하고 자가 승인(Self-Approve)하도록 두면, 자신이 유발한 메모리 누수, 잘못된 예외 처리, 안 보이는 타입 오류를 "정상 구현됨"으로 착각하고 버그가 포함된 코드를 저장소에 그대로 커밋/머지하는 치명적 결과가 초래됩니다. -* **필요성**: 객관적인 제3의 에이전트들이 부여된 역할(Planner, Creator, Reviewer) 및 특화된 페르소나(Persona)에 따라 엄격한 품질 기준(DoD)으로 교차 검증하고 승인해야만 코드에 반영되도록 제어해야 합니다. -* **구현 방법**: - * **Planner(설계)**, **Creator(구현)**, **Reviewers(검수)**의 페르소나와 역할을 엄격히 분리했습니다. - * 리뷰어 리포트 맨 마지막 단독 행에 `[VERDICT: PASS]` 또는 `[VERDICT: NOT PASS]` 토큰 입력을 규칙화하고, 파서가 모든 active 리뷰어의 만장일치 PASS를 확인할 때까지 자동으로 교정 수순을 반복(`run_loop.sh`)하도록 오케스트레이션했습니다. - -### 📋 4) 작업 단위 구분 및 관리를 위한 태스크 데이터 구조화 (Job Schema & Task Management) -* **기능 부재 시 발생하는 문제 (구체적 장애 예시)**: - * *작업 유실 및 상태 추적 불가*: 작업 위임 데이터 모델이 정의되어 있지 않으면, Orchestrator가 어떤 에이전트에게 무슨 지시문(`brief.md`)을 전달했는지, 현재 상태가 진행 중(`running`)인지, 성공(`completed`)인지, 에러(`error`)인지 추적할 수 없어 작업이 공중에 뜬 '고아(Orphaned) 상태'로 방치됩니다. - * *중복 태스크 수락 및 Race Condition*: 동일한 작업을 둘 이상의 에이전트가 동시에 중복 수락(Claim)하여 서로의 코드를 덮어쓰거나 엉뚱한 결과물을 교차 전송하는 상충 장애가 일어납니다. -* **필요성**: 에이전트 간 분동(Delegation)되는 작업 단위를 정형화하고, 각 태스크의 생명주기 및 충돌 없는 클레임 관리를 보장해야 합니다. -* **구현 방법**: - * 모든 위임 태스크마다 고유 ID(`job_id`)를 발급하고 `.mam/jobs/.json` 파일에 작업 스키마(주 작업자, 부여된 역할, 실행 타입, 보안 토큰, 생명주기 상태 등)를 명확히 데이터 구조화했습니다. - * `registry.py` 모듈을 통해 작업 등록 및 클레임 시 `fcntl` 파일 자문 잠금(Advisory Lock)을 적용하여 다중 세션 간 작업 중복 수락 경쟁을 원자적으로 제어했습니다. - -### 📡 5) 비동기 메시징 및 이벤트 백플레인 (Async Messaging Backplane) -* **기능 부재 시 발생하는 문제 (구체적 장애 예시)**: - * *동기 블로킹 타임아웃 폭망*: 동기식 HTTP 요청으로 위임할 경우, 코드 구현 및 복잡한 리팩토링으로 10분 이상 소요되는 에이전트 작업을 기다리다가 오케스트레이터의 HTTP 커넥션 타임아웃이 발생하여 전체 작업이 붕괴됩니다. - * *블라인드 진행 장애*: 비동기 이벤트 채널이 없으면 에이전트가 백그라운드에서 무한 루프에 빠졌는지, 정상 동작 중인지 알 수 있는 진행 표기(`progress`)를 수신할 수 없습니다. -* **필요성**: 위임자와 실행자 간에 커넥션을 묶어두지 않고 비동기로 실시간 이벤트 및 중간 진행 상태를 주고받아야 합니다. -* **구현 방법**: - * 경량 메시징 표준인 **MQTT 브로커**를 백플레인으로 채택하고 `publish_event.py`와 `job_subscriber.py`를 연결했습니다. - * 구독을 먼저 개시하는 *Subscribe-before-Publish* 규칙과 terminal 이벤트의 `retain=True` 설정으로 메시지 유실을 방지했습니다. - * Payload 내에 단조 증가 시퀀스 번호(`seq`)와 HMAC-SHA256 서명을 포함시켜 리플레이 공격 및 메시지 변조를 차단했습니다. - -### 📸 6) 컨텍스트 보존 및 화면 유실 방지 (Pane Snapshotting & Markdown Bridge) -* **기능 부재 시 발생하는 문제 (구체적 장애 예시)**: - * *뷰포트 잘림으로 인한 디버그 정보 유실*: 터미널(TUI) 스크롤백 한계(예: 2000줄)로 인해 에이전트가 출력한 핵심 디버그 스택 트레이스나 긴 린트 에러 메시지가 상단으로 밀려 올라가 유실됩니다. - * *입력 깨짐 및 줄바꿈 돌발 실행*: 100줄이 넘는 복잡한 프롬프트나 한글/특수문자를 터미널 입력창에 직접 문자열로 보낼 경우, 멀티바이트 깨짐이나 줄바꿈 문자로 인해 에이전트가 입력을 받다 말고 중간에 명령어를 기습 실행하는 참사가 일어납니다. -* **필요성**: 장시간 터미널 출력 히스토리를 완벽하게 보존하고, 정교한 입력 데이터를 손상 없이 전달해야 합니다. -* **구현 방법**: - * **3단계 Pane Snapshotting** (작업 전, 루프 중 주기적 캡처, 작업 종료 후)을 적용해 터미널 출력을 파일로 상시 백업했습니다. - * 복잡한 지시문이나 리뷰 리포트는 TUI 입력창에 직접 타이핑하지 않고, `.mam/jobs//brief.md` 또는 `report.md` 파일로 작성한 뒤 에이전트에게 마크다운 파일 경로 포인터만 전송하는 **파일 기반 통신 구조**를 구축했습니다. - -### 🔒 7) 이슈 트래킹 및 감사를 위한 원자적 상태 이력 관리 (Issue Tracking & Atomic Concurrency) -* **기능 부재 시 발생하는 문제 (구체적 장애 예시)**: - * *이슈 추적 불능 및 블랙박스 장애*: 에이전트가 작업 도중 에러(exit code non-zero, 프롬프트 잠금, API 실패 등)로 붕괴했을 때, 어떤 세션에서 무슨 이유로 정지되었는지 이력이 남지 않아 문제 발생 지점을 찾지 못하고 원인 분석이 불가능해집니다. - * *갱신 유실(Lost Update)로 인한 감사 이력 파손*: 에이전트 A가 에러 발생 원인과 감사 로그(`status=error`, `stop_reason`)를 덤프하는 순간, 다른 모니터링 프로세스가 1초 전의 예전 정상 스냅샷으로 파일/DB를 덮어씌워 장애 이력이 완전히 증발합니다. -* **필요성**: 에이전트 작업 도중 예외나 문제 발생 시, 이슈 트래커(Issue Tracker)처럼 어느 지점에서 어떤 원인(StackTrace, Pane Snapshot, Job Detail)으로 오류가 났는지 완벽히 추적(Traceability)할 수 있어야 하며, 이 감사 데이터가 동시 쓰기 충돌로 훼손되지 않도록 원자적으로 보호되어야 합니다. -* **구현 방법**: - * 모든 비동기 위임 작업 및 세션 상태 변경 시 고유 작업 ID(`job_id`), 담당 에이전트명, 발생 시각, 상세 원인(`detail`), 뷰포트 스냅샷(`pane.capture`)을 `.mam/jobs//` 디렉토리 및 `.mam/agent-sessions.db`에 감사 이력(Audit Trail)으로 즉시 저장하도록 설계했습니다. - * SQLite의 `BEGIN IMMEDIATE` 배타 트랜잭션과 `atomic_dump_yaml`(`os.replace`)을 조합하여, 장애 원인 추적 이력 데이터가 다중 프로세스 충돌로 덮어씌워지거나 손상되지 않도록 원자적 동시성을 완벽히 제어했습니다. - -### 🚀 8) 자동화된 배포 환경 구성 및 프로비저닝 (Deployment Automation & Provisioning) -* **기능 부재 시 발생하는 문제 (구체적 장애 예시)**: - * *환경설정 파편화 및 접속 불능*: 서버나 에이전트 런타임마다 필수 환경변수(`HERDR_SESSION_NAME`, MQTT 엔드포인트 등)가 누락되거나 수동 설정 오차로 인해, 에이전트 간 통신이 안 되거나 타 격리 세션에 오접속하여 운영 데이터를 덮어쓰는 시스템 파손 발생. - * *배포 재현성 상실 및 임포트 에러*: 파이썬 가상환경(`.venv`)이나 필수 라이브러리(`paho-mqtt`, `pyyaml`) 설치가 누락된 채 에이전트 세션이 기동되어, 작업 위임 직후 `ModuleNotFoundError`로 파이프라인이 즉시 마비되는 장애. -* **필요성**: 개발, 테스트, 운영 환경 전체에서 동일한 구동 환경과 패키지 의존성을 신속히 자동 구축하고 배포 재현성을 보장해야 합니다. -* **구현 방법**: - * `deploy/generate-env.sh` 자동화 스크립트를 제공하여 `.env` 및 `HERDR_SESSION_NAME` 환경 변수를 1초 만에 자동 생성하고 시스템에 유기적으로 주입하도록 구성했습니다. - * `.venv` 가상환경 구성 및 `requirements.txt` 의존성 패키지 자동 프로비저닝 단계를 선행 통합하여 완벽히 재현 가능한 배포 체계를 구현했습니다. - ---- - -## 4. 실전 트러블슈팅 및 튜닝 사례 (Troubleshooting Cases) - -시스템 구축 및 검증 과정에서 직접 발굴하여 해결한 주요 실전 기술 사례입니다. - -### 🛠️ 사례 1: Agy(Antigravity) 에이전트의 TOS/약관 동의 화면 차단 문제 해결 -* **증상**: `agy` 에이전트를 격리 홈(`HOME=$root`)에서 실행했을 때, 구동 시마다 **"Terms of Service & Data Use" 약관 동의 및 테마 선택 마법사**가 출력되며 프롬프트 입력이 블로킹됨. -* **원인**: `agy` 에이전트가 약관 및 초기 설정 상태를 사용자 계정 디렉토리(`~/.gemini/antigravity`, `~/Library/Application Support/Antigravity`, macOS `Preferences` plist 등)에서 가져오는데, 기존 격리 프로비저닝 로직에서 해당 경로들의 심볼릭 링크 시딩이 누락됨. -* **해결**: `lib.sh::provision_isolation` 함수를 수정하여 macOS의 `Preferences`(`com.google.antigravity.plist` 등), `Application Support/Antigravity`, `Group Containers`와 Linux의 XDG 표준 경로(`~/.config/Antigravity`, `~/.local/share/Antigravity`)를 격리 홈 디렉토리로 자동 링킹하도록 확장함으로써 플랫폼에 관계없이 약관 안내 화면을 건너뛰도록 원천 해결함. - -### 🛠️ 사례 2: TUI 입력 버퍼 감지 오탐(False-Positive) 완화 -* **증상**: `cline`이나 `claude` 에이전트에 긴 프롬프트(git diff 포함 지시문 등)를 주입할 때 `send_keys_safe: paste not visible` 타임아웃 오류가 발생하며 작업 위임이 중단됨. -* **원인**: `send_keys_safe` 유틸리티가 입력 텍스트의 끝 24글자 마커(`marker_norm`)가 화면 뷰포트에 출현했는지 검증하는데, `cline` TUI 등 일부 환경은 긴 텍스트 입력 시 입력창 스크롤로 인해 마커가 화면 밖으로 밀려나 오탐(False-Positive)이 발생함. -* **해결**: `cline` 및 `claude` 세션의 경우 실제 페이스트는 성공했으나 스크롤아웃으로 인해 검증이 실패하는 특성을 고려해, 엄격한 마커 노출 검사를 생략하고 C-m(엔터) 제출 대기 루프로 직행하도록 `lib.sh` 검증 조건문을 완화하여 오케스트레이션 루프의 연속성을 확보함. - ---- - -## 5. 결론 및 향후 발전 방향 - -본 프레임워크는 프로세스 격리, 파일 기반 원자적 레지스트리, 비동기 MQTT 메시징, 그리고 마크다운 파일 통신을 결합함으로써 **다종 AI 에이전트를 결합한 안정적이고 강인한 자율 협업 오케스트레이션**을 성공적으로 입증했습니다. - -추후 가상환경 의존성 자동 점검 강화, HMAC 보안 인증 키 자동 교환(FW-N6), 그리고 NFS 환경에서의 파일 락 추상화 레이어 보완을 통해 더욱 확장성 높은 에이전트 플랫폼으로 진화할 수 있습니다. diff --git a/SKILL_FEATURES.md b/SKILL_FEATURES.md deleted file mode 100644 index 99af5d8..0000000 --- a/SKILL_FEATURES.md +++ /dev/null @@ -1,126 +0,0 @@ -# Multi-Agent Mux: Skill Features and Architecture - -이 문서는 `multi-agent-mux` 워크스페이스 내에 구현된 6개의 개별 스킬 및 공통 라이브러리의 핵심 기능, 상태 머신, CLI 사양, 그리고 상호 연동 방식을 종합 정리한 명세입니다. 스킬 최적화 및 팩토링 작업의 기준서로 사용됩니다. - ---- - -## 1. 아키텍처 개요 (Architecture Overview) - -`multi-agent-mux`는 다중 자율 에이전트(Claude, Agy, Cline, Hermes 등)를 격리된 Tmux 세션 환경에서 관리하고 상호 통신할 수 있게 돕는 시스템입니다. -* **중앙 상태 레지스트리**: `.mam/agent-sessions.yaml` 및 동기화된 `.mam/agent-sessions.db` (SQLite3) -* **격리 소켓**: 독립된 tmux 서버 소켓 지정 구동 가능 (예: `multi-agent-mux` 서버) -* **이벤트 버스**: MQTT 프로토콜 기반의 실시간 작업 상태 비동기 관찰 (`multi-agent-mux-delegate-job`) - ---- - -## 2. 공통 라이브러리: `lib.sh` (Common Library) - -모든 스킬 스크립트가 로드하여 사용하는 핵심 공유 헬퍼 라이브러리입니다. - -* **상태 파일 원자적 덤프 (`atomic_dump_yaml`)**: - * NFS(네트워크 파일 시스템) 감지 시 SQLite `PRAGMA journal_mode=DELETE` 폴백, 로컬 환경에서는 `PRAGMA journal_mode=WAL` 설정. - * 독점 잠금(`BEGIN IMMEDIATE`)을 활성화해 멀티프로세스 환경에서 Read-Modify-Write 데이터 유실(lost update race condition) 방지. - * 트랜잭션 커밋 완료 후 `.bak` 백업 파일 생성 및 임시파일 생성 후 `os.replace` 원자적 대체 기법 적용. -* **에이전트 세션 실재성 판단 (`*_exists` 함수군)**: - * `claude`: 프로젝트 디렉터리 하위 `.jsonl` 존재성 - * `agy`: `.gemini/antigravity-cli/conversations/.db` 존재성 - * `hermes`: `~/.hermes/state.db`의 `sessions` 테이블 내 존재성 (SQLite 쿼리 검증) - * `cline`: `.cline/data/sessions//.json` 존재성 -* **세션 ID 해석 엔진 (`find_workspace_uuid` 분기 구조)**: - * **Tier 1 (YAML 직접 조회)**: YAML 내 기록된 에이전트별 전용 필드(`claude_session_id_own` 등) 조회. - * **Tier 2 (디스크 잔해 스캔)**: 워크스페이스 디렉터리(`cwd` / `workspace_root`)와 매칭되는 디스크 상의 세션 로그 중 가장 최근 수정일(`mtime`) 기준 정렬 후 최신 UUID 반환. - * **Tier 3 (아이덴티티 캐시)**: 레지스트리 상단 `agent_identities` 캐시 데이터 연동. - ---- - -## 3. 스킬별 상세 핵심 기능 (Skill Specifications) - -### 3.1. `multi-agent-mux-create` (생성 스킬) -* **용도**: 신규 에이전트 동작용 격리된 Tmux 컨테이너 생성 및 레지스트리 신규 등록. -* **핵심 기능**: - * **사전 기능 검증 (Preflight Check)**: - * `claude`: `claude auth status`를 통한 로그인 상태(`"loggedIn": true`) 검증 - * `agy`: `agy models`를 통한 API 연동 정상 상태 검증 - * `hermes`: `hermes status`를 통한 연동 상태 검증 - * `cline`: `cline history --json` 동작 및 설정 상태 사전 검증 - * **Tmux 세션 생성 및 초기화**: 에이전트별 최적화된 화면 크기(`-x 140 -y 40`) 및 작업 디렉터리(`-c`)를 적용해 세션 백그라운드 생성. - * **초기 상태 YAML 등록**: 사용자 필수 지정 역할(`--role`), `status: running`, `pane` 세부정보(인덱스, PID, CWD, CMD_FULL), 시작 명령 및 `mcp_attachments` 기록. - * **역할 불변성 보장**: 에이전트 생성 시 부여된 역할(`role`)은 사후 수정이 불가하며, 임의 변경 시도 시 데이터 검증(`atomic_dump_yaml`) 단계에서 예외 처리되어 방어됨. - * **TUI 로딩 동적 감지 (Readiness Gating)**: 고정 지연(`sleep 6`)을 탈피하여 각 에이전트별 시작 화면 출력 문자열(예: `Antigravity`, `Hermes`, `Claude`, `Cline`)을 실시간으로 감지(`capture-pane` 폴링)하여 로딩 완료 시점을 동적으로 감지함. - * **자동 온보딩 및 지시사항 주입 (Auto Onboarding & Instruction Injection)**: - * `--onboard` 플래그를 통해 신규 팀장 에이전트 구동 직후 워크스페이스 맥락(README.md, MULTI_AGENT_RULES.md, git status/diff, 타 세션 역할 분석)을 자율적으로 파악하도록 표준 온보딩 지시서 잡을 자동 생성 및 인젝션함. - * `--submit-job` 및 `--onboard` 지시서 입력을 `tmux` 페이스트 버퍼 및 엔터 키스트로크(`inject_instructions`)를 통해 에이전트 TUI 스트림에 자동 전달함. - -### 3.2. `multi-agent-mux-resume` (재개 스킬) -* **용도**: 중지되었거나 유실된 에이전트의 이전 컨텍스트 그대로 Tmux 세션 및 TUI 연결 복원. -* **핵심 기능**: - * **세션 ID 해석 위임**: `lib.sh::find_workspace_uuid`을 구동하여 대상 워크스페이스의 UUID 확인. - * **세션 복원 기동**: - * `claude`: `claude --dangerously-skip-permissions -r ` - * `agy`: `agy --dangerously-skip-permissions --conversation ` - * `hermes`: `hermes --resume ` - * `cline`: `cline -i --id ` - * **TUI 바이패스 자동화 (Claude)**: 기동 직후 백그라운드에서 `Enter` ➔ `Down` ➔ `Enter` 키스트로크를 주입하여 권한 우회 및 복구 확인 대화상자 자동 수락. - * **동기화**: `update_yaml_resumed.sh`를 구동해 상태를 `running`으로 전이하고 기동 시점에 맞춘 하위 자식 PID 갱신 및 기존 종료 메타데이터 제거. - -### 3.3. `multi-agent-mux-stop` (종료 스킬) -* **용도**: 세션을 안전하게 정리하고, 상태 및 UUID를 안전하게 저장 및 동기화. -* **핵심 기능**: - * **종료 전 TUI 스냅숏 저장**: `tmux capture-pane`을 수행해 최종 화면 상태를 `last_visible_status_at_termination` 필드에 보존. - * **다단계 Graceful 종료 프로토콜**: - 1. TUI 안전 종료 키스트로크 주입 (`/exit` 또는 `Exit`) 후 3초 대기. - 2. 생존 시 `tmux kill-session` 전송 및 5초 대기. - 3. 최후 수단으로 감지된 자식 PID에 `kill -9` 전송. - * **디스크 소거 (--purge-conversation)**: - * `resumable`을 `false`로 설정하고 상태를 `terminated`로 기록. - * 에이전트별 데이터 경로에 접근해 해당 세션 파일 파쇄. - * `claude`: `/.jsonl` 삭제 - * `agy`: `conversations/.db` 및 `brain/` 폴더 삭제 - * `hermes`: `sessions/session_.json` 삭제 및 `state.db` 내 이력 삭제 (내부 독자 커넥션 `hconn` 사용으로 상위 YAML DB 충돌 차단) - * `cline`: `~/.cline/data/sessions/` 폴더 소거 - -### 3.4. `multi-agent-mux-delegate-job` (위임 스킬) -* **용도**: 타 에이전트에게 비동기적으로 작업을 위임하고, MQTT 이벤트로 실행 상태 관찰. -* **핵심 기능**: - * **작업 지시 유형 (Delegation Types)**: - * `direct` (기본값): 단일 타겟 세션 기동 후 작업 전달 및 대기. - * `loop` (협업 루프): 구현자(Worker)의 작업 완료 후 검토자(Reviewer)가 코드 검수를 수행하여 `"PASS"` 의견이 나올 때까지 작업 수정을 자동 반복 지시. - * `discuss` (토론/합의): 두 에이전트 간 공동 토론을 추진하여 최종 기획 및 계획 합의 도출. - * **MQTT 이벤트 규격**: `publish_event.py`와 `job_subscriber.py`를 매핑하여 `started` ➔ `permission_required` ➔ `progress` ➔ `completed`/`error` 상태 전이 추적 및 자동 이중 타임아웃 검사 (전체 실행 예산 3600초 + 120초 유휴 타임아웃). - * **감사 로그 기록**: `.mam/delegate_job_logs//`에 `meta.json`, `status.json` 및 원시 NDJSON 형식의 `events.ndjson`을 영속 기록. - -### 3.5. `multi-agent-mux-status` (현황 스킬) -* **용도**: 레지스트리를 읽어와 실행 중인 모든 에이전트의 구동 세션 현황을 즉시 표기. -* **핵심 기능**: - * **읽기 전용 안정성**: DB 수정이나 상태 전이 유발 없이 순수 조회만 수행. - * 실시간 tmux 프로세스 상태 정보와 YAML 간의 이름 매핑 정합성을 검증하여 콘솔에 요약 출력. - -### 3.6. `multi-agent-mux-monitor` (화해 스킬) -* **용도**: 운영체제 Tmux 런타임과 YAML 레지스트리 데이터 불일치를 백그라운드 루프로 감지해 자동 화해(Reconciliation) 처리. -* **핵심 기능**: - * **Drift 감지 및 복구 매뉴얼**: - * **Drift A (Crash/죽은 세션)**: YAML 상 `running`이나 실제 tmux 프로세스가 죽은 경우 감지 ➔ 상태를 `terminated`로 격하 조정. - * **Drift B (새 세션 감지)**: YAML에 없으나 tmux 상에 임의로 떠 있는 `*-creator-*` 세션을 레지스트리에 자동 등록 및 자식 PID 정보 갱신. - * **Drift C (실시간 UUID 갱신)**: 새로 시작된 에이전트가 첫 명령을 받아 세션 ID를 생성했을 때, 디스크 상의 세션 로그 중 가장 수정시간이 일치하는 최신 UUID를 찾아 `*_conversation_id_own` 필드에 주입. - * **Drift D (캐시 정합성 점검)**: 레지스트리 및 캐시 상의 세션 UUID가 실제 디스크에 존재하는지 검사하여 소거된 세션을 리포트. - ---- - -## 4. 에이전트 상태 머신 (Agent State Machine) - -시스템 전반에 걸쳐 에이전트 세션은 아래 흐름을 따라 전이됩니다. - -```mermaid -stateDiagram-v2 - [*] --> running : multi-agent-mux-create / Drift B - running --> stopped : multi-agent-mux-stop (default) - running --> terminated : multi-agent-mux-stop (--purge-conversation) / Drift A - stopped --> running : multi-agent-mux-resume - terminated --> [*] -``` - -## 5. 최적화 및 팩토링 작업 시 주의 사항 - -1. **원자적 쓰기 무력화 금지**: `lib.sh`에 설정된 `atomic_dump_yaml`은 다중 에이전트 병렬 기동 시 데이터 꼬임을 막는 중추 역할을 합니다. DB 잠금 및 트랜잭션 흐름을 훼손하지 않아야 합니다. -2. **Cline 및 Claude의 TUI 입력 바인딩 유지**: 세션 재개나 중지 시, 각 에이전트가 내부적으로 사용하는 프롬프트 제어 명령어(예: `/exit`, `--id `)의 세세한 차이를 유지해야 예외 없이 동작합니다. -3. **데이터베이스 변수 충돌 주의**: 서브셸 또는 인라인 Python 스크립트 실행 시 전역 SQLite 커넥션(`conn`)의 이름 공간을 절대 오염시키지 마십시오. (예: `stop_session.sh` 버그 재발 방지). diff --git a/TEST_INFRA.md b/TEST_INFRA.md deleted file mode 100644 index 68d3a6e..0000000 --- a/TEST_INFRA.md +++ /dev/null @@ -1,49 +0,0 @@ -# Test Infrastructure Specification - -## Test Philosophy -We adopt an **opaque-box, requirement-driven** testing philosophy for the tmux-to-herdr migration scripts. -This approach ensures that the test suite validates external behaviors, input/output contracts, and side-effects rather than asserting internal code structure or layout. The scripts are treated as black boxes that: -- Accept CLI arguments and environment variables. -- Query/interact with the `herdr` daemon through the `_herdr` shim (using mock executable interception). -- Perform state mutations inside `.mam/agent-sessions.yaml` and `.mam/agent-sessions.db`. -- Interact with background agent runners (`claude`, `agy`, `hermes`, `cline`). - -This guarantees that our test assertions remain stable even if the script implementation details are refactored, as long as the functional requirements are met. - -## Feature Inventory -The test suite is structured around five core features, mapping out verification checks across Tiers 1, 2, and 3: - -| Feature | Tier 1 (Unit Checks) | Tier 2 (Component Checks) | Tier 3 (Integration Checks) | -|---|---|---|---| -| **Create Session** | - `derive_session_name` slug generation checks
- Workspace-to-slug character translation
- Invalid workspace path filtering
- Role parameter sanity validations
- Session override string generation | - Verification of state serialization to YAML schema
- Isolation home directory structure validation
- SQLite DB connection verification
- Concurrency check for database registration lock
- Database schema validation on write | - Spawn session execution with mock `herdr` and mock agent
- TUI readiness wait check
- Cleanup trap execution on crash
- Argument validation logic verification
- Isolation directory creation checks | -| **Resume Session** | - Workspace UUID resolution order unit tests
- CLI session ID parser validations
- Check prioritization (yaml file -> disk scan -> cache)
- Workspace path boundary check
- Empty UUID handling logic | - Configuration restore verification
- Environment overrides assertion
- Integrity check on retrieved SQLite metadata
- Validation of session ownership verification
- Config parsing for resume options | - Run `resume_session.sh` with mock agents
- Intercept agent command structure inside mock `herdr`
- Verify agent receives correct conversation UUID flag
- Invalid/missing UUID recovery path test
- Workspace resume CLI args verification | -| **Stop Session** | - Session name verification check
- Purge verification confirmations logic
- Command derivation format validation
- Timeout calculation helper tests
- Reason logging serializer test | - Safe folder path validation (shutil protection)
- Database status field mutation serialization
- Isolation folder cleanup check
- Lock file release checks on stop
- Concurrency handling of stop mutations | - Execute `stop_session.sh` with graceful key delivery (`/exit`)
- Fallback to forcible termination (`herdr kill-session`) check
- Fallback to PID termination (`kill -9`) verify
- Purge files verification on disk (`--purge-conversation`)
- CLI flag verification with yes/no confirmation | -| **Status Query** | - JSON converter unit tests
- Diff formatter text generators
- Output alignment tests
- Table grid column math verify
- CLI status argument parse tests | - Status read locks verification
- Parsing of drift status classifications
- Concurrency read protection test
- Registry YAML-to-JSON structural translation
- Verification of database read access checks | - Running `status.sh` with `--json`
- Verify console output match formatting rules
- Verify exit status codes on different states
- Integration test with `reconcile.sh` read-only diff emission
- Verify status command doesn't trigger side effects | -| **Monitor/Reconcile** | - Drift state classification unit tests
- Signature verification checks
- Subscription topic parsing tests
- MQTT message structure validator
- HMAC validation logic tests | - Concurrency lock checks (`.mam/monitor.lock`)
- Verify YAML and SQLite database reconciliation logic
- DB validation on drift updates
- HMAC signature signature verification
- SQLite journal mode fallback check (WAL vs DELETE) | - Execute `reconcile.sh` in single-pass mode (`--once`)
- MQTT subscription execution with mock messages
- Verify auto-termination of orphaned herdr sessions
- Verify auto-registration of untracked herdr sessions
- Lock contention handling testing | - -## Test Architecture -The E2E testing framework is built using **pytest** and relies on two main pillars to ensure hermetic and reproducible test runs: -1. **Environment Sandboxing**: - All tests run inside a temporary, isolated directory structure provided by the pytest `tmp_path` fixture. The workspace environment is sandboxed by: - - Creating a temporary `.mam/` directory. - - Using the `monkeypatch` fixture to override `AGENT_SESSIONS_YAML` pointing to the sandboxed path. - - Overriding relevant environment variables (like `HOME`, `WORKSPACE_ROOT`, etc.) to prevent tests from modifying the developer's system state. -2. **Mock Binaries Interception**: - To prevent tests from interacting with external systems or relying on running daemons: - - A mock `herdr` script is dynamically generated and placed in a temporary bin folder, which is prepended to the system `PATH`. This mock binary reads/writes to a JSON file (`mock_herdr_state.json`) which acts as the control pane for tests to assert that `herdr` was called with correct arguments and return mocked outputs (session list, capture-pane output, exit codes). - - Mock agent binaries (`claude`, `agy`, `hermes`, `cline`) are also generated and prepended to `PATH`. They emulate successful login verification commands (e.g. `claude auth status`) and mock conversation UUID generation on disk. - -## Real-World Application Scenarios (Tier 4) -We define five key E2E scenarios representing end-to-end user workflows: -1. **Standard Agent Session Lifecycle**: Spawning a new worker agent session via `create_session.sh`, verifying it is registered correctly in the YAML database, checking its status via `status.sh`, and then gracefully stopping it via `stop_session.sh`. -2. **Session Disconnect and Resume**: Creating a session, simulating a network disconnect/agent pane termination (updating herdr state), calling `resume_session.sh` to restore it using the workspace-scoped UUID, and asserting that the session returns to the active state in both herdr and the registry. -3. **Drift Detection and Auto-Reconciliation**: Artificially introducing drift (e.g. terminating a herdr session manually from the backend while keeping it registered in the YAML registry, or starting a herdr session outside the scripts), running `reconcile.sh --once`, and verifying that orphaned sessions are terminated and registry state is updated. -4. **Parallel Session Operations with flock Locking**: Simulating concurrent creation/stop script invocations to verify that SQLite flock transactions block lost update races, and that the registry data remains consistent. -5. **Multi-Agent Orchestrator Review Loop**: Running the orchestrator loop (`run_loop.sh`) where a worker agent and a reviewer agent are spawned, reviewer verdicts (`PASS` and `NOT PASS`) are processed, loops are iterated, and planner escalation is triggered on failure. - -## Coverage Thresholds -To ensure the test suite is comprehensive, we define the following coverage thresholds: -- **Tier 1 (Unit Tests)**: Minimum >=5 unit tests per feature (total >=25 unit tests). -- **Tier 2 (Component Tests)**: Minimum >=5 component tests per feature (total >=25 component tests). -- **Tier 3 (Integration Tests)**: Pairwise combination testing covering CLI options and environment overrides for all features. -- **Tier 4 (E2E Scenarios)**: At least 5 full real-world scenario tests implemented and passing. diff --git a/TEST_READY.md b/TEST_READY.md deleted file mode 100644 index 84c48be..0000000 --- a/TEST_READY.md +++ /dev/null @@ -1,129 +0,0 @@ -# Test Ready Report - -## Test Runner -- **Command**: `.venv/bin/pytest tests/` -- **Expected**: All tests pass with exit code 0 - -## Coverage Summary -- **1. Feature Coverage (Tier 1)**: 29 tests -- **2. Boundary & Corner (Tier 2)**: 26 tests -- **3. Cross-Feature (Tier 3)**: 5 tests -- **4. Real-World Application (Tier 4)**: 5 tests -- **Sanity Checks**: 2 tests -- **Challenger/M2 Unit**: 7 tests -- **Total**: 74 tests - -## Feature Checklist - -### 1. Create Session -- **Tier 1 (Unit Checks)** - - [x] `derive_session_name` slug generation checks - - [x] Workspace-to-slug character translation - - [x] Invalid workspace path filtering - - [x] Role parameter sanity validations - - [x] Session override string generation -- **Tier 2 (Component Checks)** - - [x] Verification of state serialization to YAML schema - - [x] Isolation home directory structure validation - - [x] SQLite DB connection verification - - [x] Concurrency check for database registration lock - - [x] Database schema validation on write -- **Tier 3 (Integration Checks)** - - [x] Spawn session execution with mock `herdr` and mock agent - - [x] TUI readiness wait check - - [x] Cleanup trap execution on crash - - [x] Argument validation logic verification - - [x] Isolation directory creation checks -- **Tier 4 (Real-World Application Scenarios)** - - [x] Standard Agent Session Lifecycle E2E test (Scenario 1) - - [x] Parallel Session Operations with flock Locking E2E test (Scenario 4) - -### 2. Resume Session -- **Tier 1 (Unit Checks)** - - [x] Workspace UUID resolution order unit tests - - [x] CLI session ID parser validations - - [x] Check prioritization (yaml file -> disk scan -> cache) - - [x] Workspace path boundary check - - [x] Empty UUID handling logic -- **Tier 2 (Component Checks)** - - [x] Configuration restore verification - - [x] Environment overrides assertion - - [x] Integrity check on retrieved SQLite metadata - - [x] Validation of session ownership verification - - [x] Config parsing for resume options -- **Tier 3 (Integration Checks)** - - [x] Run `resume_session.sh` with mock agents - - [x] Intercept agent command structure inside mock `herdr` - - [x] Verify agent receives correct conversation UUID flag - - [x] Invalid/missing UUID recovery path test - - [x] Workspace resume CLI args verification -- **Tier 4 (Real-World Application Scenarios)** - - [x] Session Disconnect and Resume E2E test (Scenario 2) - -### 3. Stop Session -- **Tier 1 (Unit Checks)** - - [x] Session name verification check - - [x] Purge verification confirmations logic - - [x] Command derivation format validation - - [x] Timeout calculation helper tests - - [x] Reason logging serializer test -- **Tier 2 (Component Checks)** - - [x] Safe folder path validation (shutil protection) - - [x] Database status field mutation serialization - - [x] Isolation folder cleanup check - - [x] Lock file release checks on stop - - [x] Concurrency handling of stop mutations -- **Tier 3 (Integration Checks)** - - [x] Execute `stop_session.sh` with graceful key delivery (`/exit`) - - [x] Fallback to forcible termination (`herdr kill-session`) check - - [x] Fallback to PID termination (`kill -9`) verify - - [x] Purge files verification on disk (`--purge-conversation`) - - [x] CLI flag verification with yes/no confirmation -- **Tier 4 (Real-World Application Scenarios)** - - [x] Standard Agent Session Lifecycle E2E test (Scenario 1) - - [x] Parallel Session Operations with flock Locking E2E test (Scenario 4) - -### 4. Status Query -- **Tier 1 (Unit Checks)** - - [x] JSON converter unit tests - - [x] Diff formatter text generators - - [x] Output alignment tests - - [x] Table grid column math verify - - [x] CLI status argument parse tests -- **Tier 2 (Component Checks)** - - [x] Status read locks verification - - [x] Parsing of drift status classifications - - [x] Concurrency read protection test - - [x] Registry YAML-to-JSON structural translation - - [x] Verification of database read access checks -- **Tier 3 (Integration Checks)** - - [x] Running `status.sh` with `--json` - - [x] Verify console output match formatting rules - - [x] Verify exit status codes on different states - - [x] Integration test with `reconcile.sh` read-only diff emission - - [x] Verify status command doesn't trigger side effects -- **Tier 4 (Real-World Application Scenarios)** - - [x] Standard Agent Session Lifecycle E2E test (Scenario 1) - - [x] Drift Detection and Auto-Reconciliation E2E test (Scenario 3) - -### 5. Monitor/Reconcile -- **Tier 1 (Unit Checks)** - - [x] Drift state classification unit tests - - [x] Signature verification checks - - [x] Subscription topic parsing tests - - [x] MQTT message structure validator - - [x] HMAC validation logic tests -- **Tier 2 (Component Checks)** - - [x] Concurrency lock checks (`.mam/monitor.lock`) - - [x] Verify YAML and SQLite database reconciliation logic - - [x] DB validation on drift updates - - [x] HMAC signature signature verification - - [x] SQLite journal mode fallback check (WAL vs DELETE) -- **Tier 3 (Integration Checks)** - - [x] Execute `reconcile.sh` in single-pass mode (`--once`) - - [x] MQTT subscription execution with mock messages - - [x] Verify auto-termination of orphaned herdr sessions - - [x] Verify auto-registration of untracked herdr sessions - - [x] Lock contention handling testing -- **Tier 4 (Real-World Application Scenarios)** - - [x] Drift Detection and Auto-Reconciliation E2E test (Scenario 3) diff --git a/mam_delegate_job_role_issue_report.md b/mam_delegate_job_role_issue_report.md deleted file mode 100644 index 95d246d..0000000 --- a/mam_delegate_job_role_issue_report.md +++ /dev/null @@ -1,77 +0,0 @@ -# [보고서] MAM 위임 도구의 역할(Role) 지정 옵션 누락 이슈 분석 - -본 문서는 멀티 에이전트 오케스트레이션 프레임워크(`multi-agent-mux`)의 핵심 CLI 도구인 `multi-agent-mux-delegate-job`에서 세션의 역할(Role)을 지정할 수 있는 옵션이 누락되어 발생하는 정합성 충돌 문제와 이에 대한 원인 분석 및 해결 방안을 정의합니다. - ---- - -## 1. 문제가 발생한 정확한 상황 (Context) - -프로젝트 개발을 오케스트레이션하는 과정에서 아래와 같은 에이전트 간 역할 분담을 적용하고자 했습니다. -* **개발 팀장 (Antigravity)**: 실제 저장소의 문서 수정 및 구현 진행 (**Worker/Implementer**) -* **리뷰 에이전트 (Claude)**: 문서 구조의 설계 및 계획안 수립 (**Planner**) - -이 분담에 따라 Claude 세션(`canary-projects-grpccanary-creator-claude`)에 "문서 모듈화 계획 및 체크리스트 작성" 작업을 위임하기 위해 `multi-agent-mux-delegate-job` 도구로 비동기 작업을 요청했습니다. - -그러나 자동 생성된 잡 지시서인 `.mam/jobs//brief.md` 파일의 메타데이터에 다음과 같이 **구현자의 역할이 `Worker`로 강제 지정**되어 나가는 상황이 발생했습니다: - -```markdown -# 📋 Brief: Job ed31b5fb Delegation - -- **Job ID**: ed31b5fb -- **Target Agent**: claude (session: tmux:canary-projects-grpccanary-creator-claude) -- **Role**: Worker <-- [이슈 발생 지점: Planner가 아닌 Worker로 강제 지정됨] -- **Timeout**: 3600 s (Idle: 120 s) -``` - -이는 프로젝트 협업 규칙(`.agents/MULTI_AGENT_RULES.ko.md`)에 명시된 **"에이전트 역할 범위 준수 원칙(Role Suitability Check)"**에 위배되며, `claude`가 문서 작성이 아닌 파일 직접 수정을 시도할 위험이 있는 정합성 모순을 유발합니다. - ---- - -## 2. 문제 사유 (Root Cause) - -이 문제의 근본적인 기술적 원인은 **CLI 인수 파싱 로직 및 지시서(Brief) 생성 템플릿의 하드코딩**에 있습니다. - -1. **CLI 옵션 설계 누락**: - * `multi-agent-mux-delegate-job submit` 명령어의 헬프 스펙을 확인한 결과, `--agent`, `--agent-session`, `--prompt` 등의 인수는 정의되어 있으나, 작업의 논리적 성격을 조율하는 **`--role ` 파라미터가 구현되어 있지 않습니다**. -2. **템플릿 내부의 상수 고정**: - * API를 통해 비동기 잡이 수임될 때 생성되는 `brief.md` 파일과 잡 레지스트리 JSON의 생성기 로직 내부에 `Role` 값이 **`Worker` 문자열 상수로 하드코딩**되어 동작하고 있습니다. 이로 인해 어떤 에이전트에 어떤 종류의 명령을 위임하더라도 메타데이터상으로는 항상 `Worker`로 바인딩됩니다. - ---- - -## 3. 문제 해결 방법 (Remediation & Workarounds) - -### 3.1 단기적 우회 방법 (Workaround) -프레임워크 CLI 소스코드를 수정하기 어려운 제한적 상황에서는 **프롬프트 페이로드(Prompt Payload) 하드닝** 기법을 사용하여 에이전트의 오작동을 차단합니다. -* **해결 원리**: brief.md의 메타데이터상 `Role: Worker` 지정을 덮어쓸 수 있도록, 프롬프트 문맥 내부에 **"너의 역할은 실제 문서를 수정하지 않고 계획만 수립하는 Planner이다. 절대 문서를 직접 수정하지 말라"**는 강력한 지시 제약(System-level Rule Override)을 포함하여 송신합니다. -* **효과**: AI 에이전트는 메타데이터보다 프롬프트 지시어의 행위 제약을 우선 순위로 받아들이므로, 의도한 대로 설계서 및 계획안만 수립하는 Planner 동작을 정상 수행하게 됩니다. - -### 3.2 근본적인 해결 방법 (Remediation) -프레임워크의 CLI 래퍼인 `multi-agent-mux-delegate-job` 파일의 파싱 로직 및 brief.md 빌더 로직을 다음과 같이 수정합니다. - -#### 1단계: CLI 인수 파서 수정 (`submit` 옵션 추가) -스크립트의 인수 파싱 영역에 `--role` 파라미터를 식별할 수 있는 변수 및 분기 로직을 선언합니다. -```bash -# 옵션 분석 루프 예시 -while [[ $# -gt 0 ]]; do - case $1 in - --role) - DELEGATE_ROLE="$2" - shift 2 - ;; - # ... 기존 옵션 파싱 ... - esac -done - -# 기본값 정의 -DELEGATE_ROLE="${DELEGATE_ROLE:-Worker}" -``` - -#### 2단계: `brief.md` 생성 템플릿 연동 -잡 디렉토리 내에 `brief.md`를 기입하여 내보내는 빌더 영역(Python 혹은 쉘 스크립트 에코 영역)을 다음과 같이 동적 변수와 연결합니다. -```diff -- echo "- **Role**: Worker" >> "$BRIEF_PATH" -+ echo "- **Role**: ${DELEGATE_ROLE}" >> "$BRIEF_PATH" -``` - -#### 3단계: 잡 레지스트리 JSON 메타데이터 갱신 -동일하게 생성되는 `.mam/jobs/.json` 파일 등의 메타데이터 생성 객체 내에 `role: DELEGATE_ROLE` 매핑 키를 추가하여, 타 모니터링 도구(예: `reconcile.sh` 및 `status.sh`)에서도 해당 에이전트의 잡 실행 역할을 정확하게 대시보드에 모니터링할 수 있도록 보완합니다.