4 Commits
Author SHA1 Message Date
Godopu 4a5a093986 chore(docs): clean up temporary FIX.md and bug_report.md 2026-08-27 21:43:26 +09:00
Godopu c3631e2aa1 fix(herdr): resolve shim routing defects, add workspace scoping, and bump to v3.0.1
- Resolve Herdr shim 5 routing & paste defects (ISSUE-1 ~ ISSUE-5):
  * paste-buffer: use pane send-text without auto-enter, propagate rc=3 to send_keys_safe
  * exact-match pane resolution: remove substring matching ('in tn') across all branches
  * workspace scoping: introduce HERDR_WORKSPACE_ID and .mam/herdr_workspace_id persistence
  * unified resolver: single _resolve_herdr_pane_id helper across shim commands
- Resolve dialog token false-positive on 'Yes, try it' tip and isolate fullscreen modal rejection
- Sync mock Herdr CLI contracts in tests/conftest.py
- Add contract tests H-15~H-23 and regression tests D-4~D-7 (412 tests, 100% PASS)
- Add multi-agent loop plans, review reports, and bug report
- Update framework and skill packages to v3.0.1
2026-08-27 21:42:37 +09:00
Godopu 4bbd03bf2d fix(lib): handle agent_not_ready startup state and reject claude fullscreen upsell modal
- Accept agent_not_ready from herdr agent start to allow startup dialog handling without premature rollback, while preserving fail-closed behavior on dead process timeouts.
- Match Claude fullscreen renderer upsell modal via 'Yes, try it' and dismiss with Escape to avoid dropping permission flags or deadlocking on idle /tui tips.
- Add behavioral test suite in test_b19_headless_reconcile_fixes.py and cross-agent review reports.
2026-08-27 10:17:53 +09:00
Godopu d875584ef4 chore(submodule): update nats-docker submodule to 26fd65a 2026-08-26 18:38:52 +09:00
20 changed files with 2143 additions and 115 deletions
@@ -0,0 +1,508 @@
# 📐 구현 계획서: Herdr 셈(shim) 패인 라우팅 결함 4종 수정 (ISSUE-1/2/3/5)
- **Job ID**: `fae58b93`
- **Role**: Planner (`planner-reviewer-claude-01`)
- **작성일**: 2026-08-27
- **대상**: `.agents/skills/lib.sh`, `tests/conftest.py`, `tests/test_herdr_shim_contract.py`, `tests/test_b19_headless_reconcile_fixes.py`
- **근거 문서**: `bug_report.md` (v1.0)
- **기준 커밋**: `4bbd03b` (main)
---
## 0. 요약 (TL;DR)
`bug_report.md`의 5대 결함 중 ISSUE-4는 이미 커밋 `4bbd03b`에서 해결되어 회귀 테스트(`test_agent_start_success_tokens_exclude_startup_timeout`)로 고정되어 있다. 남은 **ISSUE-1 / 2 / 3 / 5**를 다음 순서로 처리한다.
1. **ISSUE-5 선행** — 셈 내부에 공용 헬퍼 `_resolve_herdr_pane_id`를 신설한다. 나머지 3개 이슈의 수정이 전부 이 헬퍼 안으로 수렴하므로 이것이 반드시 먼저다.
2. **ISSUE-2** — 헬퍼 및 `_resolve_herdr_target` / `has-session`에서 `agent in tn` 부분 매칭을 전면 제거하고 엄격 일치로 대체.
3. **ISSUE-3**`HERDR_WORKSPACE_ID`**명시적으로 설정된 경우에만** `pane list --workspace`로 하드 스코핑.
4. **ISSUE-1**`paste-buffer``pane send-text` 단독 삽입으로 교체(엔터 금지), 해결 실패 시 조용히 삼키지 말고 실패를 상위로 전달.
---
## 1. 사전 조사에서 확인된 사실 (계획의 전제)
계획 수립 중 실제 `herdr` 바이너리(`/opt/homebrew/bin/herdr`)와 현재 `lib.sh`를 직접 검증했다. **버그 리포트의 권고 코드를 그대로 옮기면 안 되는 지점이 3곳** 있다.
### 1.1 ✅ `herdr agent send` 서브커맨드는 존재하지 않는다 (ISSUE-1의 진짜 뿌리)
```
$ herdr agent --help
Commands: list get read send-keys prompt rename focus wait attach start explain
```
현재 `lib.sh:822``paste-buffer` 구현은 다음 한 줄이 전부다.
```bash
_real_herdr agent send "$sess" "$(cat "$buffer_dir/$buf")" >/dev/null 2>&1 || true
```
`agent send`는 CLI에 없으므로 이 호출은 **항상 실패하고 `|| true`가 실패를 삼킨다**. 즉 현재 `main`에서 `paste-buffer` 경로는 텍스트를 단 한 글자도 주입하지 못하는 완전한 데드 코드다. 이것이 브리프의 "`paste-buffer``herdr agent send` 부재"가 가리키는 실체이며, `send_keys_safe`의 폴백 경로 전체가 무력화되어 있음을 뜻한다.
> 참고: `send_keys_safe`는 `agent prompt` 고속 경로가 성공하면 즉시 반환하므로(`lib.sh:1785`), **등록된 agent에 대해서는** 이 결함이 드러나지 않는다. 결함이 표면화되는 조건은 정확히 버그 리포트가 기술한 상황 — `agent prompt`가 실패하는 **라벨 전용 패인(agent 미등록)** — 이다.
### 1.2 ⚠️ 버그 리포트의 `pane_id` 정규식은 실제 pane_id를 거부한다
버그 리포트 §3.1은 다음 검증을 제안한다.
```bash
if [[ "$pid" =~ ^w[0-9]+:p[0-9]+$ ]]; then
```
그러나 실제 서버가 반환하는 pane_id는 다음과 같다.
```json
{"pane_id":"w1E:p1","workspace_id":"w1E","tab_id":"w1E:t1", ...}
```
워크스페이스 세그먼트는 `w1E`처럼 **영문자를 포함**한다. 권고 정규식을 그대로 쓰면 모든 실제 pane_id가 거부되어 헬퍼가 항상 실패하고, 결과적으로 ISSUE-1을 고친 뒤에도 주입이 되지 않는다.
**채택 정규식**: `^w[A-Za-z0-9]+:p[A-Za-z0-9]+$`
### 1.3 ⚠️ 실제 `pane list` 응답에는 `label` 키가 없을 수 있다
```json
{"agent":"claude","agent_status":"working","cwd":"...","pane_id":"w1E:p1",
"tab_id":"w1E:t1","terminal_title":"...","workspace_id":"w1E"}
```
`label``herdr pane rename <PANE_ID> <LABEL>`로 설정했을 때만 나타난다. 반면 `agent list`에는 `name` 필드가 있다(`"name":"planner-reviewer-claude-01"`). 따라서 헬퍼의 매칭 우선순위는 `label``name``agent` 순으로 두되, **셋 다 완전 일치만** 허용한다. `agent` 필드는 사실상 CLI 종류(`claude`/`grok`)이므로 `tn`이 그 값과 완전히 같은 경우에만 매칭되며, 이는 부분 매칭과 달리 오라우팅을 만들지 않는다.
### 1.4 ✅ `pane list`는 서버측 `--workspace` 필터를 지원한다
```
$ herdr pane list --help
Options:
--workspace <WORKSPACE_ID>
```
ISSUE-3의 스코핑은 파이썬 클라이언트 필터링만이 아니라 **서버측 플래그로 1차 차단**할 수 있다. 양쪽 모두 적용한다(플래그 미지원 구버전 herdr 대비 이중 방어).
### 1.5 ✅ `pane read`와 `agent read`의 출력 형식은 호환된다
둘 다 평문 텍스트를 반환하며, `_pane_capture`(`lib.sh:1672`)는 JSON 파싱 실패 시 원문을 그대로 반환하므로 `capture-pane``pane read`로 전환해도 상위 로직이 깨지지 않는다.
### 1.6 ⚠️ 셈은 `set -euo pipefail` 아래에서 실행된다
셈 본문은 `lib.sh:141``cat <<'EOF'` ~ `lib.sh:959``EOF` 사이 히어독으로 생성되며 3번째 줄이 `set -euo pipefail`이다. 따라서 실패를 반환할 수 있는 새 헬퍼는 **모든 호출부에서 `|| true`로 감싸야** 하며, 그렇지 않으면 셈이 조기 종료된다.
### 1.7 ✅ 테스트 목(mock)이 결함을 은폐하고 있다
`tests/conftest.py:638`의 목 herdr는 존재하지 않는 `agent send`를 **성공으로 처리**한다. 이 때문에 ISSUE-1이 테스트에서 전혀 드러나지 않았다. 목을 실제 CLI 계약에 맞추는 것이 이번 작업의 필수 선행 조건이다.
---
## 2. 변경 대상 목록
| # | 파일 | 위치 | 이슈 | 성격 |
|---|---|---|---|---|
| C1 | `.agents/skills/lib.sh` | 셈 히어독, `_sanitize_herdr_agent_name` 직후 (~L236) | 5 | 신규 헬퍼 `_resolve_herdr_workspace_scope`, `_resolve_herdr_pane_id` |
| C2 | `.agents/skills/lib.sh` | `_resolve_herdr_target` (L249286) | 2,3 | 부분 매칭 제거 + ws 필터 |
| C3 | `.agents/skills/lib.sh` | `has-session` (L305345) | 2,3,5 | 부분 매칭 제거 + ws 필터 + 헬퍼 폴백 |
| C4 | `.agents/skills/lib.sh` | `new-session` (L434530) | 3 | 해결된 workspace_id를 `HERDR_WORKSPACE_ID`로 export |
| C5 | `.agents/skills/lib.sh` | `kill-session` (L567603) | 5 | 인라인 파서 → 헬퍼 |
| C6 | `.agents/skills/lib.sh` | `capture-pane` (L687704) | 3,5 | 헬퍼 + `pane read` 경로 |
| C7 | `.agents/skills/lib.sh` | `send-keys` (L705744) | 2,3,5 | 인라인 파서 → 헬퍼 |
| C8 | `.agents/skills/lib.sh` | `paste-buffer` (L794827) | 1,5 | `agent send``pane send-text`, 엔터 금지, 실패 전파 |
| C9 | `.agents/skills/lib.sh` | `send_keys_safe` (L18041806) | 1 | `paste-buffer` 종료 코드 확인 → rc 3 |
| C10 | `tests/conftest.py` | 목 herdr | 1,2,3 | `pane send-text`/`pane read`/`pane rename` 추가, `pane list` 병합·라벨·`--workspace`, `agent send` 제거 |
| T1 | `tests/test_herdr_shim_contract.py` | 신규 | 1,2,3,5 | H-15 ~ H-20 |
| T2 | `tests/test_b19_headless_reconcile_fixes.py` | 신규 | 1,2,5 | D-4 ~ D-7 |
> `list-panes`(L605686)의 인라인 파서는 `pane_id` 외에 `cwd`/`agent`까지 한 번에 파싱하므로 헬퍼로 대체하지 **않는다**. ISSUE-5의 대상 목록에도 포함되어 있지 않다.
---
## 3. 상세 구현 설계
### 3.1 [C1] 공용 헬퍼 신설 (ISSUE-5)
`lib.sh` 셈 히어독 내부, `_sanitize_herdr_agent_name` 정의 직후(`cmd="${1:-}"` 앞)에 삽입한다. 이 위치여야 `case` 분기 전체에서 참조 가능하다.
```bash
# ---------------------------------------------------------------------------
# Workspace scoping (ISSUE-3).
#
# 스코핑은 HERDR_WORKSPACE_ID 가 "명시적으로" 설정된 경우에만 하드 필터로
# 동작한다. cwd 로부터 자동 추론하지 않는다 — 자동 추론은 다중 워크스페이스
# 오케스트레이션에서 정당한 교차 워크스페이스 조회를 조용히 막아버린다.
# 미설정 시에는 서버 전역 조회(기존 동작)를 유지한다.
# ---------------------------------------------------------------------------
_herdr_ws_scope() { printf '%s\n' "${HERDR_WORKSPACE_ID:-}"; }
# _resolve_herdr_pane_id <target> [workspace_id]
#
# 세션 이름 / 라벨을 실제 pane_id ("wN:pM") 로 해석한다.
# 엄격한 해석 순서 (부분 문자열 매칭은 어느 단계에서도 사용하지 않는다):
# 1. herdr agent get <sanitized_name>
# 2. herdr agent get <raw_name>
# 3. herdr pane list [--workspace WS] 에서
# 3-a. label 완전 일치
# 3-b. name 완전 일치
# 3-c. agent 완전 일치
# 성공 시 pane_id 를 stdout 에 출력하고 0, 실패 시 아무것도 출력하지 않고 1.
# 호출부는 반드시 `|| true` 로 감쌀 것 (셈은 set -e 하에서 동작한다).
_resolve_herdr_pane_id() {
local target="$1"
local target_ws="${2:-$(_herdr_ws_scope)}"
local sat pid=""
sat=$(_sanitize_herdr_agent_name "$target")
local cand
for cand in "$sat" "$target"; do
[ -n "$cand" ] || continue
pid=$(_real_herdr agent get "$cand" 2>/dev/null | TARGET_WS="$target_ws" python3 -c "
import sys, json, os
tws = os.environ.get('TARGET_WS', '')
try:
a = json.load(sys.stdin).get('result', {}).get('agent', {})
# ISSUE-3: 워크스페이스가 지정되면 다른 워크스페이스의 동명 agent 는 거부.
if tws and a.get('workspace_id') and a.get('workspace_id') != tws:
pass
else:
print(a.get('pane_id') or '')
except Exception:
pass
" 2>/dev/null || echo "")
[ -n "$pid" ] && break
done
if [ -z "$pid" ]; then
local ws_flag=()
[ -n "$target_ws" ] && ws_flag=(--workspace "$target_ws")
pid=$(_real_herdr pane list "${ws_flag[@]+"${ws_flag[@]}"}" 2>/dev/null \
| TARGET_NAME="$target" TARGET_SAN="$sat" TARGET_WS="$target_ws" python3 -c "
import sys, json, os
tn = os.environ.get('TARGET_NAME', '')
tsa = os.environ.get('TARGET_SAN', '')
tws = os.environ.get('TARGET_WS', '')
try:
panes = json.load(sys.stdin).get('result', {}).get('panes', [])
# 서버가 --workspace 를 무시하는 구버전일 수 있으므로 클라이언트에서 한 번 더 거른다.
if tws:
panes = [p for p in panes if p.get('workspace_id') == tws]
# ISSUE-2: 완전 일치만 허용. 'agent in tn' 부분 매칭은 사용하지 않는다.
for key in ('label', 'name', 'agent'):
for p in panes:
v = p.get(key)
if v and (v == tn or v == tsa):
pid = p.get('pane_id') or ''
if pid:
print(pid)
sys.exit(0)
except Exception:
pass
sys.exit(1)
" 2>/dev/null || echo "")
fi
# 실제 pane_id 는 'w1E:p1' 처럼 워크스페이스 세그먼트에 영문자를 포함한다.
# ^w[0-9]+:p[0-9]+$ 로 좁히면 모든 실제 pane_id 가 거부된다.
if [[ "$pid" =~ ^w[A-Za-z0-9]+:p[A-Za-z0-9]+$ ]]; then
printf '%s\n' "$pid"
return 0
fi
return 1
}
```
**설계 근거**
- **`for key in ('label','name','agent')` 바깥 루프**: 우선순위가 "패인 목록의 등장 순서"가 아니라 "필드의 신뢰도"로 결정된다. 안쪽/바깥쪽 루프를 뒤집으면 목록 첫 항목의 `agent` 매칭이 뒤쪽 항목의 정확한 `label` 매칭을 이겨버린다 — 이것이 ISSUE-2가 만든 오라우팅과 동일한 형태의 버그다.
- **`tsa`(sanitized) 도 비교 대상에 포함**: `agent start`가 이름을 sanitize해서 등록하므로, 라벨은 원본이고 등록명은 sanitize본인 혼재 상황을 커버한다. sanitize는 결정적 함수이므로 부분 매칭과 달리 충돌을 만들지 않는다.
- **`ws_flag` 배열 + `${ws_flag[@]+...}`**: `set -u` 하에서 빈 배열 전개가 unbound 오류를 내지 않도록 하는 표준 관용구.
### 3.2 [C2] `_resolve_herdr_target` 엄격화 (ISSUE-2, ISSUE-3)
`lib.sh:262275`의 파이썬 블록에서 다음 술어를 제거한다.
```python
if name == tn or (not name and agent and agent in tn): # ← 제거
```
교체:
```python
tn = os.environ.get("TARGET_NAME", "")
tsa = os.environ.get("TARGET_SAN", "")
tws = os.environ.get("TARGET_WS", "")
...
agents = d.get("result", {}).get("agents", [])
if tws:
agents = [a for a in agents if a.get("workspace_id") == tws]
for a in agents:
name = a.get("name", "")
if name and (name == tn or name == tsa):
print(a.get("pane_id") or name)
sys.exit(0)
sys.exit(1)
```
`pane_id or agent``pane_id or name`으로 바꾼다. 기존 코드는 매칭에 실패한 항목의 CLI 종류(`agent`, 예: `"claude"`)를 타깃으로 반환할 수 있었는데, 이는 `agent prompt claude ...`처럼 전혀 다른 대상에게 프롬프트를 던지는 경로다.
### 3.3 [C3] `has-session` 엄격화 + 패인 폴백 (ISSUE-2, ISSUE-3, ISSUE-5)
`lib.sh:334`의 다음 술어를 제거한다.
```python
or (not an and a.get("agent") and a.get("agent") in tn) # ← 제거
```
남는 조건은 `an == tn or an == stn`이며, 여기에 `HERDR_WORKSPACE_ID` 필터를 추가한다.
그리고 agent 조회가 모두 실패했을 때 마지막 단계로 헬퍼를 호출한다.
```bash
if [ -n "$(_resolve_herdr_pane_id "$sess" 2>/dev/null || true)" ]; then
exit 0
fi
exit 1
```
**의도적 동작 변경**: 라벨만 붙은(agent 미등록) 패인도 이제 "세션 존재"로 판정된다. 이것이 정확히 버그 리포트가 보고한 실패 시나리오(`label: reviewer-cline-01` 패인에 주입 불가)의 해소 조건이다. `_resolve_herdr_pane_id`가 완전 일치만 허용하므로, 세션 이름 `reviewer-creator-grok-01``agent == "grok"` 패인에 매칭될 일은 없다.
**리스크**: `create_session.sh` / `reconcile.sh``has-session` 결과로 재생성 여부를 판단한다면, 라벨만 있고 실제 CLI가 죽은 패인을 "살아 있음"으로 오판할 수 있다. → 3.9의 회귀 검증 범위에 `test_orc_onboard.py`, `test_tier3_integration.py`, `test_tier4_e2e.py`를 명시적으로 포함한다.
### 3.4 [C4] `HERDR_WORKSPACE_ID` 전파 (ISSUE-3)
`new-session` 분기에서 `existing_ws` 또는 신규 `ws_id`가 확정된 직후(`lib.sh:509` 이후 `ws_id` 확정 지점) 다음을 추가한다.
```bash
if [ -n "${ws_id:-}" ]; then
export HERDR_WORKSPACE_ID="$ws_id"
fi
```
또한 `agent start`에 전달하는 `env_flags``--env HERDR_WORKSPACE_ID=$ws_id`를 추가하여, 기동된 에이전트 프로세스가 상속한 셈 호출부터 자동으로 스코프가 걸리도록 한다.
**채택하지 않은 대안**: 셈이 `$PWD`/`$WORKSPACE_ROOT`의 cwd로부터 workspace_id를 자동 추론하는 방식. 추론이 성공하는 순간 교차 워크스페이스 조회가 **조용히** 막히고, 오케스트레이터가 다른 워크스페이스의 에이전트를 정당하게 다루는 경로가 원인 불명으로 깨진다. 스코핑은 명시적 옵트인이어야 진단 가능하다.
### 3.5 [C5]~[C7] 분기 리팩터링 (ISSUE-5)
**`kill-session`** — `lib.sh:587598`의 이중 인라인 파이썬을 삭제.
```bash
agent_target=$(_sanitize_herdr_agent_name "$sess")
pane_id=$(_resolve_herdr_pane_id "$sess" 2>/dev/null || true)
if [ -n "$pane_id" ]; then
_real_herdr pane close "$pane_id" >/dev/null 2>&1 || true
fi
_real_herdr kill-session -t "$agent_target" >/dev/null 2>&1 \
|| _real_herdr kill-session -t "$sess" >/dev/null 2>&1 || true
```
**`capture-pane`** — 헬퍼로 pane_id를 얻으면 `pane read`, 아니면 기존 `agent read` 체인 유지.
```bash
agent_target=$(_sanitize_herdr_agent_name "$sess")
pane_id=$(_resolve_herdr_pane_id "$sess" 2>/dev/null || true)
if [ -n "$pane_id" ]; then
_real_herdr pane read "$pane_id" --source visible --lines 100 2>/dev/null || true
else
_real_herdr agent read "$agent_target" --source visible --lines 100 2>/dev/null \
|| _real_herdr agent read "$sess" --source visible --lines 100 2>/dev/null || true
fi
```
**`send-keys`** — `lib.sh:726738`의 이중 인라인 파이썬을 삭제하고 헬퍼 호출로 대체. 폴백(`pane send-keys "$agent_target"``"$sess"`)은 그대로 유지한다. `C-m``Enter` 정규화(L741–743)도 유지 — 이건 키 이름 번역이지 제출 정책이 아니다.
**ISSUE-5의 "데드 파이프라인" 부분**: 기존 인라인 파서는 `except: pass`로 항상 exit 0을 반환해 `||` 2차 폴백이 절대 실행되지 않았다. 신규 헬퍼는 `sys.exit(1)` + 정규식 검증 + `return 1`로 실패를 정확히 신호하므로 이 데드 코드가 구조적으로 제거된다.
### 3.6 [C8] `paste-buffer` 재작성 (ISSUE-1)
```bash
buffer_dir="${WORKSPACE_ROOT:+$WORKSPACE_ROOT/.mam/buffers}"
buffer_dir="${buffer_dir:-${TMPDIR:-/tmp}/mam_buffers}"
if [ ! -f "$buffer_dir/$buf" ]; then
echo "Error: buffer $buf not found ($buffer_dir/$buf)" >&2
exit 1
fi
pane_id=$(_resolve_herdr_pane_id "$sess" 2>/dev/null || true)
if [ -z "$pane_id" ]; then
# herdr 에는 `agent send` 서브커맨드가 없다. 여기서 조용히 성공을 반환하면
# send_keys_safe 가 아무것도 붙여넣지 않은 채 Enter 만 치게 된다.
echo "Error: paste-buffer could not resolve a pane for '$sess'" >&2
exit 1
fi
# 삽입 전용. Enter/C-m 제출은 전적으로 send_keys_safe 가 통제한다 (ISSUE-1).
# 여기서 `pane run` 을 쓰면 안 된다 — 텍스트와 Enter 를 한 번에 보내 이중 제출이 된다.
if ! _real_herdr pane send-text "$pane_id" "$(cat "$buffer_dir/$buf")" >/dev/null 2>&1; then
echo "Error: pane send-text failed for '$sess' ($pane_id)" >&2
exit 1
fi
```
**불변식 (테스트로 고정)**: `paste-buffer` 분기 본문에는 `Enter`, `C-m`, `pane run`, `agent prompt` 중 어떤 것도 등장하지 않는다.
### 3.7 [C9] `send_keys_safe`의 붙여넣기 실패 전파 (ISSUE-1)
현재 `lib.sh:18041806``paste-buffer`의 종료 코드를 버린다. 그리고 세션 이름에 `cline|claude|agy|grok`이 포함되면 붙여넣기 가시성 검증마저 건너뛴다(L1809–1812) — 즉 **실제 운영 대상 전부**에서 실패가 무성으로 삼켜진다.
```bash
_sks_herdr set-buffer -b "$sks_buf" "$text"
local _paste_rc=0
_sks_herdr paste-buffer -b "$sks_buf" -t "$sess" || _paste_rc=$?
_sks_herdr delete-buffer -b "$sks_buf" 2>/dev/null || true
if [ "$_paste_rc" != "0" ]; then
echo "send_keys_safe: paste-buffer failed rc=$_paste_rc ($sess)" >&2
return 3
fi
```
버퍼 정리(`delete-buffer`)는 조기 반환 **앞**에 둔다. 그렇지 않으면 실패 경로마다 버퍼가 누수되어 `set-buffer`의 A-3 GC 주석이 방어하는 바로 그 문제가 재발한다.
기존 반환 코드 계약(`3 = paste not visible`)을 재사용하므로 호출자 계약은 바뀌지 않는다.
### 3.8 [C10] 테스트 목(mock) 정합화 — `tests/conftest.py`
테스트 코드보다 **먼저** 처리해야 한다. 목이 실제 CLI와 어긋나 있는 한 어떤 테스트도 결함을 재현할 수 없다.
| 변경 | 위치 | 내용 |
|---|---|---|
| M1 | `cmd1 == "agent"`, `cmd2 == "send"` (L638664) | **핸들러 삭제** → 실제 CLI처럼 unknown subcommand로 exit 1. ISSUE-1 재현의 필수 조건 |
| M2 | `cmd1 == "pane"` | `send-text` 핸들러 추가: pane_id로 대상 조회, `sent_text` 누적, `buffer` 갱신, `sent_keys`**건드리지 않음** |
| M3 | `cmd1 == "pane"` | `read` 핸들러 추가: 대상 패인의 `buffer` 평문 출력 |
| M4 | `cmd1 == "pane"` | `rename` 핸들러 추가: `state["panes"]`의 해당 항목에 `label` 기록 |
| M5 | `pane list` (L253281) | 현재는 agents가 하나라도 있으면 `state["panes"]`를 **무시**한다. → agent 유래 패인과 `state["panes"]``pane_id` 기준으로 병합(dedupe)하고, `label`/`name` 필드를 그대로 실어 보낸다. 라벨 전용 패인 시나리오가 이 변경 없이는 표현 불가 |
| M6 | `pane list` | `--workspace` 필터는 이미 구현되어 있음(L255–261). 유지 |
| M7 | `agent get` (L569) | 응답에 `workspace_id`가 이미 포함됨(L594). 유지 |
목의 `_match_agent`(L182)는 이미 엄격(완전 일치 / sanitize 일치)하므로 변경 불필요하다.
---
## 4. 테스트 계획
### 4.1 `tests/test_herdr_shim_contract.py` — 행위 테스트 (신규 H-15 ~ H-20)
기존 파일의 규약을 따른다: `mam_sandbox` / `mock_herdr` / `mock_agents` 픽스처로 셈을 실제 실행하고, `mock_herdr_state.json``calls` 배열을 검증한다.
**H-15 `test_h15_paste_buffer_inserts_without_enter`** (ISSUE-1)
- 준비: `mock_agents``test-creator-claude` 기동.
- 실행: `herdr set-buffer -b t1 "hello world"``herdr paste-buffer -b t1 -t test-creator-claude`.
- 단언:
- `calls``["pane","send-text",<pane_id>,"hello world"]`가 정확히 1회.
- `calls``["agent","send",...]`**0회** (M1로 이제 실패하게 되므로 회귀 감지).
- `paste-buffer` 실행으로 발생한 `calls``pane send-keys` / `agent prompt` / `pane run`**0회** ← 이중 제출 방지의 핵심 단언.
**H-16 `test_h16_send_keys_safe_submits_exactly_once`** (ISSUE-1 종단)
- `agent prompt` 고속 경로를 강제로 실패시켜(존재하지 않는 세션명 또는 목의 `prompt` 실패 주입) 폴백 경로를 타게 한다.
- 단언: `Enter`/`C-m` 키 전송 횟수 총합이 정확히 1. (현재 코드는 `paste-buffer` 자체가 죽어 0회, 버그 리포트가 기술한 패치 상태에서는 2회 — 양쪽 모두 이 테스트가 잡는다.)
**H-17 `test_h17_no_substring_cross_pane_routing`** (ISSUE-2) — **핵심 회귀 테스트**
- 준비: `reviewer-creator-grok-01`, `worker-grok-02` 두 agent를 서로 다른 pane_id로 기동.
- 실행: `herdr send-keys -t reviewer-creator-grok-01 C-m`.
- 단언: `pane send-keys`의 대상 pane_id가 `reviewer-creator-grok-01`의 것과 일치. `worker-grok-02`의 pane_id로 간 호출은 0회.
- 추가: agent 등록 없이 `agent: "grok"` 라벨 전용 패인만 두고 `herdr has-session -t reviewer-creator-grok-01` → **exit 1**이어야 한다(예전 부분 매칭이면 0).
**H-18 `test_h18_workspace_scoped_pane_resolution`** (ISSUE-3)
- 준비: `state["panes"]`에 동일 `label: creator-agy-01``workspace_id: w1`, `w2`에 각각 1개씩 시드.
- 실행 A: `HERDR_WORKSPACE_ID=w2 herdr send-keys -t creator-agy-01 Enter` → 대상이 `w2`의 pane_id.
- 실행 B: `HERDR_WORKSPACE_ID=w1` → 대상이 `w1`의 pane_id.
- 실행 C: `HERDR_WORKSPACE_ID` 미설정 → 해석은 성공하되 실패하지 않음(기존 전역 동작 보존).
**H-19 `test_h19_single_resolver_helper_used_by_all_branches`** (ISSUE-5)
- 생성된 셈 파일(`$WORKSPACE_ROOT/.mam/shim/herdr`)을 읽어:
- `_resolve_herdr_pane_id()` 정의가 정확히 1회 등장.
- `has-session` / `kill-session` / `capture-pane` / `send-keys` / `paste-buffer` 각 분기 본문에서 `_resolve_herdr_pane_id` 호출이 등장.
- `result', {}).get('agent', {}).get('pane_id'` 형태의 인라인 파서 잔존 개수가 헬퍼 내부 1곳으로 한정.
- `bash -n`으로 셈 구문 검증.
**H-20 `test_h20_pane_id_regex_accepts_alphanumeric_workspace`** (§1.2 회귀 방지)
- 헬퍼를 직접 호출해 `w1E:p1`, `w10:p3` 형태가 통과하고 `notapane`, `w1:p`, 빈 문자열이 거부되는지 확인.
- 이 테스트가 없으면 버그 리포트 원문의 `^w[0-9]+:p[0-9]+$`가 나중에 다시 들어와도 아무도 모른다.
### 4.2 `tests/test_b19_headless_reconcile_fixes.py` — 소스/헬퍼 단위 테스트 (신규 D-4 ~ D-7)
기존 `_run_lib_helpers()` 헬퍼(L119–130)와 소스 문자열 검사 패턴을 재사용한다.
**D-4 `test_resolve_pane_id_fails_cleanly_under_set_e`**
- `set -euo pipefail` 아래에서 `_resolve_herdr_pane_id nonexistent || true`가 셸을 죽이지 않고 빈 출력 + rc 1을 내는지.
**D-5 `test_send_keys_safe_returns_3_when_paste_buffer_fails`** (ISSUE-1)
- `_sks_herdr` 스텁: `agent prompt` → rc 1, `paste-buffer` → rc 1, `send-keys` 호출은 파일에 기록.
- 단언: `send_keys_safe` rc == 3, 기록 파일에 `C-m` 없음.
- 추가 단언: `delete-buffer`가 호출되었음(버퍼 누수 방지).
**D-6 `test_no_substring_matching_remains_in_lib_sh`** (ISSUE-2) — 소스 가드
- `lib.sh` 전문에서 정규식 `\bin tn\b``agent"\) in tn` 패턴 매치가 0건.
- `_resolve_herdr_pane_id` 본문에 `^w[A-Za-z0-9]+:p[A-Za-z0-9]+$`가 존재.
**D-7 `test_paste_buffer_branch_never_submits`** (ISSUE-1) — 소스 가드
- `lib.sh`에서 `paste-buffer)` ~ 다음 `;;` 구간을 잘라내어 `Enter`, `C-m`, `pane run`, `agent prompt` 문자열이 없음을 단언.
- 행위 테스트(H-15)와 중복처럼 보이지만 층이 다르다: H-15는 목 경유라 목이 잘못되면 함께 침묵하고, D-7은 소스를 직접 본다.
### 4.3 회귀 범위
`has-session` 의미 변경(3.3)과 `capture-pane` 경로 변경(3.5)이 넓게 파급되므로, 다음을 우선 확인한 뒤 전체를 돌린다.
```bash
.venv/bin/python -m pytest tests/test_herdr_shim_contract.py \
tests/test_b19_headless_reconcile_fixes.py \
tests/test_b8_send_keys_verification.py \
tests/test_orc_onboard.py tests/test_workspace_scope.py \
tests/test_uuid_target.py tests/test_sanitize_and_mock_errors.py -q
```
이후 전체:
```bash
.venv/bin/python -m pytest -q
```
**기준선 (실측)**: 작업 착수 시점(`4bbd03b`)에 `test_herdr_shim_contract.py` + `test_b19_headless_reconcile_fixes.py` + `test_workspace_scope.py` = **17 passed / 9.2s**.
전체 스위트(`pytest -q`) = **397 passed / 502.00s (8분 21초)**. `tier3`/`tier4` e2e가 herdr 목 프로세스를 다수 포크하는 것이 소요 시간의 대부분이다. 구현자는 다음을 전제로 시간을 배분할 것:
- 반복 개발 루프에서는 4.3의 **우선 범위**만 사용한다(약 10초).
- 전체 회귀는 S7에서 1회만, 백그라운드로 돌린다(약 8~9분).
- 완료 기준은 **397 + 신규 10건 = 407 passed**이다. 이보다 적으면 기존 테스트가 사라졌거나 무성 skip된 것이므로 반드시 원인을 규명할 것.
- `pytest-timeout`은 이 저장소에 설치되어 있지 않다 — `--timeout=` 플래그는 `unrecognized arguments`로 즉시 실패한다. 필요하면 `requirements-dev.txt`에 추가하거나 셸 레벨에서 제어할 것.
---
## 5. 실행 순서 (권장 커밋 단위)
| 단계 | 내용 | 검증 |
|---|---|---|
| S1 | [C10] `conftest.py` 목 정합화 (M1~M5) | 기존 스위트 실행 → **여기서 깨지는 테스트가 곧 은폐되어 있던 결함의 목록**. 목록을 기록한다 |
| S2 | [C1] `_resolve_herdr_pane_id` / `_herdr_ws_scope` 신설 (호출부 변경 없음) | `bash -n`, H-20, D-4 |
| S3 | [C2][C3] 부분 매칭 제거 (ISSUE-2) | H-17, D-6 |
| S4 | [C5][C6][C7] 분기 리팩터링 (ISSUE-5) | H-19, 4.3 우선 범위 |
| S5 | [C8][C9] `paste-buffer` 재작성 + 실패 전파 (ISSUE-1) | H-15, H-16, D-5, D-7 |
| S6 | [C4] `HERDR_WORKSPACE_ID` 전파 (ISSUE-3) | H-18 |
| S7 | 전체 회귀 | `pytest -q` 전량 그린 |
S2를 S3~S6보다 먼저 두는 이유: 헬퍼만 추가하고 아무도 호출하지 않는 상태는 **정의상 무해**하므로, 이 시점에 스위트가 깨지면 원인이 히어독 구문 오류 하나로 좁혀진다.
---
## 6. 리스크 및 완화
| # | 리스크 | 영향 | 완화 |
|---|---|---|---|
| R1 | 셈은 `lib.sh` 내부 히어독이라 편집 시 `$`, 백틱, 따옴표 이스케이프 사고가 나기 쉽다 | 셈 전체가 구문 오류로 죽어 모든 herdr 호출 실패 | `<<'EOF'`(따옴표 히어독)이므로 셸 확장은 일어나지 않음. 각 단계마다 `_init_herdr_isolation` 실행 후 생성물에 `bash -n` |
| R2 | `has-session`이 라벨 전용 패인을 "존재"로 판정 (3.3) | `create_session.sh`가 죽은 패인을 재사용해 세션 재생성 실패 | 4.3 우선 회귀 범위에 `test_orc_onboard.py` 포함. 문제 시 라벨 폴백을 `MAM_HAS_SESSION_PANE_FALLBACK=1` 옵트인으로 격하 |
| R3 | `capture-pane``agent read``pane read`로 전환 | 출력 포맷 차이로 `_pane_quiescent` / 준비 토큰 매칭 실패 | §1.5에서 실기 검증 완료(양쪽 평문). `test_b8_send_keys_verification.py`로 회귀 확인 |
| R4 | `HERDR_WORKSPACE_ID` 하드 필터가 정당한 교차 워크스페이스 조회를 차단 | 다중 워크스페이스 오케스트레이션 기능 상실 | 자동 추론을 채택하지 않음(3.4). 미설정 = 기존 전역 동작. H-18 실행 C가 이를 고정 |
| R5 | 구버전 herdr가 `pane list --workspace`를 모름 | 플래그 오류로 조회 실패 | 클라이언트측 `workspace_id` 필터를 이중으로 유지(3.1). `2>/dev/null || echo ""`로 폴백 |
| R6 | `paste-buffer` 실패 전파(3.7)로 이전엔 "성공"이던 경로가 rc 3을 반환 | 상위 오케스트레이터가 새로 실패를 보게 됨 | 이는 **의도된 결과**다 — 기존 "성공"은 텍스트가 전달되지 않은 무성 실패였다. 다만 배포 노트에 명시 |
---
## 7. 완료 기준 (Definition of Done)
1. `.agents/skills/lib.sh``_resolve_herdr_pane_id`**정확히 1회** 정의되고, `has-session` / `kill-session` / `capture-pane` / `send-keys` / `paste-buffer` 5개 분기가 모두 이를 호출한다.
2. `lib.sh` 전문에 `agent ... in tn` 형태의 부분 문자열 매칭이 0건이다.
3. `paste-buffer` 분기가 `pane send-text`만 사용하고 `Enter` / `C-m` / `pane run` / `agent prompt`를 사용하지 않는다.
4. `HERDR_WORKSPACE_ID`가 설정되면 패인 해석이 해당 워크스페이스로 제한되고, 미설정 시 기존 전역 동작이 보존된다.
5. `tests/test_herdr_shim_contract.py`에 H-15 ~ H-20, `tests/test_b19_headless_reconcile_fixes.py`에 D-4 ~ D-7이 추가되고 전부 통과한다.
6. `.venv/bin/python -m pytest -q`**407 passed**(기준선 397 + 신규 10)로 전량 그린. 실패가 남으면 원인과 함께 명시 보고(무성 skip 금지).
7. `bash -n``lib.sh` 및 생성된 `.mam/shim/herdr` 양쪽에서 통과한다.
---
## 8. 계획 범위 밖으로 남기는 항목
- **ISSUE-4** — 커밋 `4bbd03b`에서 이미 수정 완료. `test_agent_start_success_tokens_exclude_startup_timeout`이 회귀를 고정하고 있어 추가 작업 없음.
- **`list-panes` 분기** — 인라인 파서를 유지한다. `pane_id` 단독이 아니라 `cwd`/`agent`를 함께 파싱하므로 `_resolve_herdr_pane_id`로 대체 불가이며, ISSUE-5의 대상 목록에도 없다.
- **`bug_report.md`의 업스트림 반영** — 본 작업은 이 저장소의 `lib.sh`에 한정한다. `multi-agent-mux` 업스트림 배포는 별도 릴리스 절차(`VERSIONS.md`, `deploy/`)를 따른다.
@@ -0,0 +1,211 @@
# 교차 코드 리뷰 리포트 — Job c666854d (rev.2)
- **대상**: `.agents/skills/lib.sh`, `tests/test_b19_headless_reconcile_fixes.py`, `FIX.md`
- **리뷰어**: claude (`planner-reviewer-claude-01`)
- **선행 리뷰**: Job b9e42784 — `[VERDICT: NOT PASS]` (D-1 ~ D-5)
- **관점**: 린트 / 동작성 / 유실
- **결론**: 선행 리뷰의 지적 5건이 **모두 정확히 해소**되었고, 이번에는 **실제 Claude Code 클라이언트로 종단 검증**까지 마쳤다.
잔여 지적은 전부 경미(Low)하며 병합을 막지 않는다.
작업 트리 diff는 브리프에 첨부된 diff와 **완전히 일치**한다 (`lib.sh` 16줄, 테스트 106줄, `FIX.md` 신규).
---
## 0. 검증 방법
이번 리뷰의 핵심은 **실물 검증**이다. 선행 리뷰에서는 합성 화면으로만 확인했으나, 이번에는
`CLAUDE_CODE_FORCE_FULLSCREEN_UPSELL=1`로 **실제 업셀 모달을 강제 재현**하여 확인했다.
| # | 방법 |
|---|---|
| V-1 | 실제 herdr 0.8.2 출력값으로 `agent start` 분류 로직 재현 |
| V-2 | herdr 워크스페이스에 **Claude Code v2.1.247 실기동** → 모달 강제 표시 → Escape 전송 → 상태 측정 |
| V-3 | `lib.sh`를 그대로 source 하여 실제 함수 실행 (HEAD 대비 비교) |
| V-4 | **거부되었던 rev.1 구현을 격리 worktree에 복원**하고 신규 테스트를 돌려 회귀 검출력 확인 |
| V-5 | pytest 전체 |
프로브 워크스페이스(`w1H`/`w1J`/`w1K`/`w1M`/`w1N`)와 임시 worktree는 **전부 정리 완료**.
현재 남은 워크스페이스는 실사용 `w1E` 하나뿐이며, `git worktree list`도 1개(본체)로 복귀했다.
---
## 1. 선행 지적 해소 확인
### D-1 (🔴 → ✅) — 죽은 프로세스가 성공으로 승격되던 문제
성공 정규식이 `agent_started|agent_not_ready`로 축소되었다.
선행 리뷰에서 **실제 herdr 프로브로 채집한 출력값**을 그대로 넣어 분류를 재현한 결과:
| herdr 실제 출력 | 분류 결과 |
|---|---|
| `{"error":{"code":"timeout","message":"timed out waiting for agent startup"}}` (← `/bin/false`, **죽은 프로세스**) | `retry → exit 1` ✅ |
| `{"error":{"code":"agent_pane_busy", …}}` | `retry → exit 1` ✅ |
| `{"error":{"code":"agent_not_ready", …}}` (프로세스 생존, 다이얼로그 차단) | `success=1` ✅ |
| `agent_started` | `success=1` ✅ |
Fail-Closed 복원 확인. 치명 오류 우선 분류 순서도 유지되었다.
또한 이번 실기동에서 herdr가 **정확히 그 상태를 반환하는 것을 실물로 확인**했다:
```
{"error":{"code":"agent_not_ready","message":"agent probe-fs5 is blocked during startup and is not ready for prompts"}}
```
`agent_not_ready`를 롤백 사유로 보지 않는 처리가 **가정이 아니라 실측으로** 정당화되었다.
부수 확인: 워크스페이스 생성 직후 즉시 `agent start` 하면 `agent_pane_busy`가 실제로 발생한다(2회 재현).
`lib.sh`의 3회 백오프(0.5/1/2초) 재시도가 이 창구를 정확히 덮으므로 **재시도 루프는 유지되어야 한다**.
### D-2 / D-2c (🔴 → ✅) — idle 팁을 차단형 다이얼로그로 오인하던 문제
광의 토큰 `fullscreen renderer|Try the new fullscreen`이 제거되고 모달 고유 문자열만 사용한다.
`lib.sh`를 실제 source 하여 **정상 기동(팁만 표시, TUI 준비 완료)** 화면을 넣은 결과:
| 팁만 있는 정상 화면 | HEAD | rev.1 (거부됨) | **rev.2 (현재)** |
|---|---|---|---|
| `_pane_dialog_open` | false | 🔴 TRUE | ✅ **false** |
| `handle_startup_dialogs` 전송 키 | 0 | 🔴 Enter 20회 | ✅ **0회** |
| `wait_for_tui_ready` | rc=0 | 🔴 rc=1 (+Enter 30회) | ✅ **rc=0** |
정상 경로가 HEAD와 **완전히 동일**하게 복귀했다. 데드락 해소 확인.
### D-3 (🟠 → ✅) — Enter가 업셀을 "수락"하던 문제
**실제 모달을 강제 재현해 캡처했다.** 모달 하단 안내가 결정적이다:
```
Try the new fullscreen renderer?
· Flicker-free output
· Mouse support — click to move your cursor or expand results
· Selected text auto-copies to your clipboard
1. Yes, try it
2. Not now
Enter to confirm · Esc to cancel
```
- `Enter to confirm` → 기본 선택지 `Yes, try it` 수락. 선행 리뷰의 D-3 지적이 **모달 자체 문구로 확증**되었다.
- `Esc to cancel` → 수정이 택한 Escape가 **모달이 스스로 안내하는 취소 키**다.
Escape 전송 후 실측:
| 항목 | 결과 |
|---|---|
| 모달 제거 | ✅ 사라짐 (`Yes, try it` 0건) |
| 잔여 다이얼로그 토큰 | ✅ 0건 → `send_keys_safe` 차단 해제 |
| ready 토큰 가시성 | ✅ 2건 (`Claude Code v2.1.247`, `Sonnet 5 with high effort`) → `wait_for_tui_ready` 통과 |
| **`⏵⏵ bypass permissions on` 유지** | ✅ **세션 재시작 없음 — `--dangerously-skip-permissions` 보존** |
마지막 항목이 중요하다. 우려했던 "수락 시 permission flag 없이 재시작" 경로를 **Escape가 회피함을 실물로 확인**했다.
### D-4 (🟠 → ✅) — 테스트가 소스 문자열만 확인하던 문제
신규 4건 중 3건이 `_pane_capture`를 stub 하고 **함수를 실제 실행**하는 행위 테스트로 바뀌었다.
(`_pane_tail``_pane_capture``_sks_herdr` 체인이므로 `_pane_capture` stub은 올바른 주입 지점이다.)
회귀 검출력을 직접 측정했다. **거부되었던 rev.1 구현을 격리 worktree에 복원**하고 신규 테스트를 실행:
```
FAILED test_agent_start_success_tokens_exclude_startup_timeout
FAILED test_fullscreen_tip_is_not_a_blocking_dialog
FAILED test_fullscreen_modal_is_rejected_not_accepted
FAILED test_wait_for_tui_ready_succeeds_on_fullscreen_tip
4 failed
```
→ **4건 전부 rev.1에서 실패하고 rev.2에서 통과**한다. 실질적 회귀 방지력이 확인되었다.
`test_wait_for_tui_ready_succeeds_on_fullscreen_tip` 실패 로그에는 rev.1의 `Enter` 30회 주입과
`⚠️ TUI readiness check timed out`이 그대로 찍혔다 — 정확히 선행 리뷰가 지적한 증상이다.
### D-5 (🔵 → 대부분 해소)
`FIX.md`가 재작성되어 순서 변경·타임아웃 토큰 배제 근거·팁/모달 구분이 모두 기술되었고, 말미 개행도 정상이다.
---
## 2. 테스트 / 린트 결과
- `tests/` 전체 **397 passed** (8분 30초). HEAD 393 + 신규 4건과 정확히 일치.
- 변경 파일 단독 **10 passed** (신규 4건 포함).
- `bash -n .agents/skills/lib.sh` **통과**. `shellcheck`는 이 환경에 미설치라 미실행.
---
## 3. 잔여 지적 (전부 Low — 병합 차단 아님)
### N-1 `_MAM_DIALOG_TOKENS`의 `|Yes, try it`은 **불필요하며** 오탐 면적만 넓힌다
실제 모달 문구에는 `Esc to cancel`이 포함되어 있고, 이 토큰은 **HEAD의 기존 토큰 목록에 이미 존재**한다.
HEAD 토큰만으로 실제 모달이 매칭되는 것을 확인했다 → **탐지 목적으로는 추가가 중복**이다.
(선행 리뷰의 합성 픽스처에는 이 하단 안내줄이 없어 드러나지 않았던 부분이다.)
반면 `Yes, try it`은 평문 대화에 등장할 수 있는 자연어다. 실제로 아래 한 줄이 `_pane_dialog_open`을 참으로 만든다:
```
⏺ Sure — if the build fails again, Yes, try it with the --clean flag.
```
`send_keys_safe`가 30초 대기 후 `rc=2`로 실패한다. 확률은 낮고, HEAD에도 `Allow this` / `No, exit` 같은
평문형 토큰 선례가 있어 **새로운 부류의 위험은 아니다.** 다만 이 건은 얻는 것이 없으므로 제거를 권한다.
- **권고**: `_MAM_DIALOG_TOKENS`에서 `|Yes, try it` 제거. `handle_startup_dialogs`의 분기는 그대로 둔다
(모달 탐지는 기존 `Esc to cancel`이 이미 담당). 더 좁히려면 팁에 없는 물음표형
`Try the new fullscreen renderer\?`를 앵커로 쓰는 편이 가장 정확하다.
### N-2 테스트의 `_init_herdr_isolation` stub이 **동작하지 않는다**
`_run_lib_helpers``source` **뒤에** `_init_herdr_isolation() { :; }`을 정의하지만,
`lib.sh:1881`에서 이미 source 시점에 실호출된다. 따라서 stub은 사실상 죽은 코드이고,
매 테스트가 `$WORKSPACE_ROOT/.mam/shim/herdr`를 실제로 기록한다(실행 중 mtime 갱신 확인).
`.mam/`은 gitignore 대상이라 git 오염은 없고 멱등이라 실피해도 없으나, **의도와 실제가 어긋나 있다.**
- **권고**: 아래 N-3의 미사용 파라미터를 활용해 `WORKSPACE_ROOT`를 임시 디렉터리로 넘긴다.
### N-3 `_run_lib_helpers(env_extra=...)`가 **어떤 호출부에서도 사용되지 않는다** (미사용 파라미터)
N-2의 해법 통로이므로 제거보다 활용을 권한다.
### N-4 테스트가 `/tmp/mam-fs-*-keys.$$`를 하드코딩한다
스크립트 말미의 `rm -f``set -euo pipefail` 하에서 앞 단계가 실패하면 실행되지 않아 잔여 파일이 남을 수 있다
(이번 실행에서는 잔여물 없음). pytest `tmp_path` 사용을 권한다.
### N-5 `FIX.md`가 여전히 **untracked**다
변경 근거 문서로 참조되고 있으므로, 병합 전 커밋하거나 의도적으로 제외한다면 그 판단을 남겨야 한다.
---
## 4. git discard 여부
**discard 하지 말 것.** 두 문제 모두 실재함이 이번에 실물로 확정되었다 —
herdr가 기동 중 차단 상태에서 `agent_not_ready`를 반환하는 것, 그리고
Claude Code v2.1.247이 `Try the new fullscreen renderer?` 모달로 기동을 막는 것 모두 직접 재현했다.
---
## 5. 요약
| 선행 지적 | 상태 | 근거 |
|---|---|---|
| D-1 죽은 프로세스 → 성공 승격 | ✅ 해소 | 실채집 herdr 출력 4종 분류 재현 |
| D-2 팁을 다이얼로그로 오인 | ✅ 해소 | 실함수 실행, HEAD와 동일 동작 복귀 |
| D-2c `wait_for_tui_ready` 데드락 | ✅ 해소 | rc=1 → **rc=0** |
| D-3 Enter가 업셀 수락 | ✅ 해소 | 실모달 `Enter to confirm · Esc to cancel`, Escape 후 permission flag 보존 확인 |
| D-4 회귀 방지력 없음 | ✅ 해소 | rev.1 복원 시 신규 4건 전부 실패 |
| D-5 문서/린트 | ✅ 대부분 해소 | FIX.md 재작성 |
| 신규 지적 | 심각도 | 요지 |
|---|---|---|
| N-1 | 🔵 Low | `Yes, try it` 토큰 추가는 중복이며 평문 오탐 면적만 넓힘 |
| N-2 | 🔵 Low | `_init_herdr_isolation` stub 무효 → 테스트가 `.mam/shim` 실제 기록 |
| N-3 | 🔵 Low | `env_extra` 미사용 파라미터 |
| N-4 | 🔵 Low | `/tmp` 하드코딩, 실패 시 잔여 가능 |
| N-5 | 🔵 Low | `FIX.md` untracked |
핵심 결함은 모두 해소되었고 잔여는 전부 위생 수준이므로 병합 가능하다고 판단한다.
설계 재작업 사유가 없어 PLANNER 에스컬레이션은 두지 않는다.
[VERDICT: PASS]
@@ -0,0 +1,165 @@
# 🔍 교차 코드 리뷰 리포트 — Job `e8cee19e`
- **Job ID**: `e8cee19e`
- **리뷰어**: `planner-reviewer-claude-01` (Reviewer)
- **작성일**: 2026-08-27
- **대상 브랜치/기준 커밋**: `main` @ `4bbd03b`
- **리뷰 범위**: 워킹트리 누적 변경분 (`git diff`) — 4 files, +808 / 92
- `.agents/skills/lib.sh` (+289/−…)
- `tests/conftest.py`
- `tests/test_herdr_shim_contract.py`
- `tests/test_b19_headless_reconcile_fixes.py`
- **근거 문서**: `bug_report.md` (v1.0), `.agents/reports/planner-reviewer-claude-01/plan-fae58b93.md`
---
## 0. 요약 (TL;DR)
계획서(`plan-fae58b93.md`)에 명시된 **F-1 ~ F-4 및 워크스페이스 세션 격리(ISSUE-1/2/3/5)** 4개 항목이 모두 코드에 반영되어 있으며, 전체 회귀 테스트가 **412 passed (실측 699.09s, exit 0)** 로 통과함을 리뷰어 환경에서 **재실행하여 직접 확인**했다.
린트(구문), 동작성, 유실(회귀) 세 관점 모두에서 **머지를 막을 결함(blocker)은 발견되지 않았다.** 다만 설계상 의도적으로 남겨진 잔여 스코프 갭 3건을 **비차단 후속 과제(Non-blocking)** 로 기록한다.
---
## 1. 검증 방법
| # | 검증 항목 | 방법 | 결과 |
|---|---|---|---|
| V-1 | 전체 회귀 테스트 | `.venv/bin/python -m pytest tests/ -q` (리뷰어가 직접 재실행) | ✅ **412 passed in 699.09s**, exit 0 |
| V-2 | 셸 구문 린트 | `bash -n .agents/skills/lib.sh` | ✅ 통과 (오류 없음) |
| V-3 | 생성 shim 구문 린트 | `bash -n $WORKSPACE_ROOT/.mam/shim/herdr` (H-19 테스트 내장) | ✅ 통과 |
| V-4 | Bash 3.2 호환성 | 로컬 `GNU bash 3.2.57 (arm64-apple-darwin25)` 에서 `local arr=()` + `"${a[@]+"${a[@]}"}"` 패턴 실측 | ✅ `set -euo pipefail` 하에서 정상 동작 |
| V-5 | 정적 교차 검토 | diff 전량 + 인접 컨텍스트(`lib.sh` 380~440, 609~730, 1926~2070행) 직접 판독 | ✅ 계획서와 구현 일치 |
| V-6 | 호출자 영향 분석 | `send_keys_safe` 호출부 grep (`stop_session.sh:204`, `delegate-job:527`) | ✅ 신규 rc=3 를 모두 비정상으로 처리 |
> **참고**: shellcheck 는 본 환경에 미설치되어 실행하지 못했다. 대신 `bash -n` 2종(원본 + 생성 shim) + Bash 3.2 실측으로 대체했다. 이는 CI 게이트가 아니므로 차단 사유가 아니다.
---
## 2. 작업 목표별 반영 확인
### ✅ F-1 — `Yes, try it` 토큰 정리 및 회귀 테스트
- `_MAM_DIALOG_TOKENS` 에서 `|Yes, try it` 제거 확인 (`lib.sh:62`).
- `handle_startup_dialogs` 의 Escape 거부 분기(`lib.sh:2048`)는 **그대로 보존** — 실제 fullscreen 업셀 모달은 여전히 Escape 로 거부된다. 즉 "탐지 완화"가 아니라 **책임 분리**(대화형 산문 오탐 제거 / 실제 모달 처리 유지)로 올바르게 구현되었다.
- 회귀 고정: `test_prose_yes_try_it_is_not_a_dialog`(산문 → DIALOG_CLOSED), `test_mam_dialog_tokens_exclude_yes_try_it`(토큰 라인 + Escape 분기 동시 검증), `test_fullscreen_modal_is_rejected_not_accepted`(Escape 전송·Enter 미전송).
- **판정**: 반영 완료. 오탐(산문으로 인한 `send_keys_safe` rc=2 데드락)과 정탐(모달 거부)이 양방향으로 고정되었다.
### ✅ F-2b — `_herdr_agent_get_scoped` 스코핑 단축경로 보완
- 기존의 스코프 없는 존재 확인(`_real_herdr agent get "$x" >/dev/null 2>&1`)이 `has-session`, `kill-session`, `capture-pane`, `send-keys`, `paste-buffer`, `agent` 6개 분기에서 전부 제거되고 `_herdr_agent_get_scoped` / `_resolve_herdr_pane_id` 로 대체됨.
- `_resolve_herdr_target`**명시적 env 미스 시 raw 폴스루 차단**(`HERDR_WORKSPACE_ID` 설정 시 `return 1`)이 추가됨 — 이것이 F-2b 의 핵심이며, `agent prompt` 가 타 워크스페이스 동명 에이전트로 프롬프트를 배달하는 경로를 실제로 닫는다.
- 호출부 3곳(`prompt`/`get`/`read`)이 `$(... || true)` + 빈 문자열 검사 + `exit 1` 로 **실패를 삼키지 않고 상위 전달**한다. `set -e` 하에서 명령 치환 실패로 셸이 죽지 않도록 `|| true` 가 일관되게 붙어 있다 — 계약(주석에 명시)과 구현이 일치.
- 회귀 고정: `test_h21_has_session_agent_get_is_workspace_scoped`(w2 → rc=1, w1 → rc=0, unset → 전역 유지), `test_h22_agent_prompt_does_not_cross_workspace`(out-of-scope 시 `agent prompt` 호출 자체가 0건임을 mock call log 로 검증).
- **판정**: 반영 완료. 특히 H-22 가 "에러만 났는지"가 아니라 **부작용(RPC 호출)이 발생하지 않았음**을 검증하는 점이 좋다.
### ✅ F-3 — H-19 테스트 정밀화
- `test_h19_single_resolver_helper_used_by_all_branches` 가 단순 문자열 카운트에서 **case arm 단위 파싱(`_case_arm`)** 으로 정밀화됨.
- 검증 강도: (a) 헬퍼 정의 1회 유일성, (b) 5개 분기 전부 헬퍼 호출, (c) 각 분기에 **스코프 없는 `agent get … >/dev/null` 잔존 금지** 정규식, (d) `agent` arm 의 `$sat`/`$raw` 단축경로 제거, (e) 헬퍼 블록 밖 `_herdr_agent_get_scoped()` 재정의 0건, (f) `bash -n` 2종.
- `list-panes` arm 을 `elsewhere` 에서 제외한 처리도 타당하다(해당 arm 은 정상적으로 pane list 를 직접 다룬다).
- **판정**: 반영 완료. "헬퍼는 만들었지만 옛 경로가 살아있다"는 회귀를 구조적으로 차단한다.
### ✅ F-4 — capture-pane 폴백 복원
- `capture-pane` arm 이 `pane read <pane_id>``agent read <sat>``agent read <sess>` 3단 폴백으로 복원됨. pane_id 해석 실패 시에도 기존 agent-level 경로가 살아있어 **유실 없음**.
- 동일 패턴이 `send-keys`(pane 실패 시 agent 이름 폴백), `kill-session`(pane close + kill-session 2단)에도 유지된다.
- **판정**: 반영 완료. F-2b 의 엄격화로 인한 기능 유실 위험이 이 폴백으로 상쇄된다.
### ✅ ISSUE-1 — 이중 제출(double-submit) 차단
- `paste-buffer` 가 존재하지 않는 `agent send` 대신 **`pane send-text` 삽입 전용**으로 교체되었고, Enter/C-m 을 일절 보내지 않는다. 제출 책임은 `send_keys_safe` 가 단독 소유.
- pane 미해석 / send-text 실패 시 `|| true` 로 삼키지 않고 `exit 1``send_keys_safe``rc=3` 반환. **빈 프롬프트 제출** 시나리오가 닫혔다.
- 고속 경로(`agent prompt`, 원자적 텍스트+제출)와 폴백 경로(send-text → C-m)가 상호 배타적이므로 제출은 정확히 1회.
- 회귀 고정: `test_h15_paste_buffer_inserts_without_enter`(send-text 정확히 1건, 제출 계열 호출 0건), `test_h16_send_keys_safe_submits_exactly_once`(Enter/C-m 정확히 1건), `test_d5 / test_send_keys_safe_returns_3_when_paste_buffer_fails`(rc=3 + 버퍼 정리 수행 + C-m 미전송), `test_paste_buffer_branch_never_submits`(소스 레벨 토큰 금지).
- **판정**: 반영 완료. 특히 **실패 시에도 `delete-buffer` 를 먼저 수행한 뒤 rc 를 반환**하는 순서가 정확하다(버퍼 누수 없음).
### ✅ ISSUE-2 — substring 오라우팅 제거
- `_resolve_herdr_target``(not name and agent and agent in tn)`, `has-session``(not an and a.get("agent") and a.get("agent") in tn)` 두 substring 분기가 모두 제거되고 **exact match only** 로 대체.
- `_resolve_herdr_pane_id` 의 pane list 매칭도 `label``name``agent`**정확 일치**(원본/sanitized 양쪽 후보)만 수행.
- 회귀 고정: `test_h17_no_substring_cross_pane_routing`(`reviewer-creator-grok-01``agent: "grok"` 패인에 매칭되지 않음 + 동종 에이전트 2개 중 정확한 패인으로만 send-keys), `test_no_substring_matching_remains_in_lib_sh`(소스 레벨 `\bin tn\b` 잔존 0건).
- **판정**: 반영 완료.
### ✅ ISSUE-3 — 워크스페이스 세션 격리
- 3단 스코프 소스: `HERDR_WORKSPACE_ID` (env, 하드) → `$WORKSPACE_ROOT/.mam/herdr_workspace_id` (persist) → 없으면 기존 서버 전역 조회.
- **cwd 추론을 하지 않는다**는 결정이 주석에 명시되어 있고 구현도 일치 — 정당한 교차 워크스페이스 조회를 조용히 막지 않는다.
- `pane split``--env HERDR_WORKSPACE_ID="$existing_ws"` 주입, `workspace create` 경로에서는 응답에서 `workspace_id` 를 파싱해 `export` + 파일 영속화.
- `pane list --workspace` 서버측 필터 + **파이썬 클라이언트측 재필터**(구버전 herdr 가 `--workspace` 를 무시할 경우 대비) 이중화 — 방어적으로 잘 설계됨.
- 회귀 고정: `test_h18_workspace_scoped_pane_resolution`(w1/w2 동명 라벨 분리 라우팅, unset 시 전역 유지), `test_h23_persisted_workspace_id_scopes_without_env`(env 없이 파일만으로 스코핑 + new-session 이 파일을 실제로 기록).
- **판정**: 반영 완료. 잔여 갭은 §4 참조.
### ✅ ISSUE-5 — 파서 중복 제거
- `agent get → pane_id` 를 파싱하던 인라인 python heredoc 3벌(`kill-session`, `send-keys`, 구 `capture-pane`)이 전부 제거되고 `_resolve_herdr_pane_id` 단일 진입점으로 수렴.
- pane_id 정규식이 계획서 §1.2 의 지적대로 `^w[A-Za-z0-9]+:p[A-Za-z0-9]+$` 로 채택됨 — 버그 리포트의 `^w[0-9]+:p[0-9]+$` 를 그대로 썼다면 `w1E:p1` 형태의 **실제 pane_id 를 전량 거부**했을 것이다. 이 수정은 정확하며, `test_h20_pane_id_regex_accepts_alphanumeric_workspace` 로 accept/reject 5케이스가 고정되어 있다.
- **판정**: 반영 완료. 리뷰 과정에서 가장 위험했던 함정을 계획 단계에서 잡아낸 점이 확인된다.
---
## 3. 테스트 하네스(`conftest.py`) 변경 검토
mock herdr 변경이 "테스트를 통과시키기 위한 눈속임"이 아니라 **실제 herdr CLI 계약에 더 가깝게 교정**하는 방향인지를 중점 확인했다.
| 변경 | 평가 |
|---|---|
| `agent send` 서브커맨드 **제거** + 미지원 서브커맨드 `exit 1` | ✅ **정확한 교정**. 실제 `herdr agent --help``send` 가 없다. 기존 mock 이 존재하지 않는 명령을 성공시켜 ISSUE-1 을 은폐하고 있었다. |
| `agent prompt` 가 미매칭 시 `exit 1` (기존: 항상 ok) | ✅ 정확한 교정. 무조건 성공하던 mock 이 F-2b 검증을 불가능하게 만들고 있었다. |
| `pane send-text` / `pane read` / `pane rename` 추가 | ✅ 신규 코드 경로가 실제로 사용하는 명령이며, agents/panes 양쪽 저장소를 모두 조회하는 구현이 shim 의 폴백 구조와 대칭이다. |
| `pane list` 를 agents panes **병합 + pane_id 중복 제거** 로 변경 | ✅ 필요한 수정. 기존 `if not panes_list:` 조건부는 agent 가 하나라도 있으면 라벨 전용 패인을 통째로 감췄다 — H-16/H-18/H-23 이 검증하려는 시나리오 자체를 표현할 수 없었다. |
| `save_state` 가 동일 `pane_id` 를 append 대신 **in-place 갱신** | ✅ 버그 수정. 기존 로직은 갱신을 무시(첫 항목 고정)했다. 기존 병렬 상태 경합 테스트(10-agent)도 여전히 통과한다. |
| `monkeypatch.delenv("HERDR_WORKSPACE_ID")` | ✅ 필수. 호스트 환경 오염으로 인한 위양성/위음성 차단. |
**유실 검토**: `agent send` 제거는 프로덕션 코드에서 해당 호출이 완전히 사라진 뒤에 이뤄졌으며(`grep` 결과 잔존 0건), 412 테스트 전량 통과가 이를 뒷받침한다. 기능 유실 없음.
---
## 4. 비차단 후속 과제 (Non-blocking / 관찰 사항)
머지를 막지 않으며, 별도 티켓으로 추적할 것을 권고한다.
### N-1 (Low) — 영속 파일은 herdr 워크스페이스를 1개만 기억한다
`_herdr_persist_ws_id``new-session` 마다 파일을 덮어쓴다. 레이아웃 오버플로(W2b)로 하나의 MAM 워크스페이스가 herdr 워크스페이스 2개 이상을 소유하게 되면, 파일은 **마지막 것만** 가리킨다. 이 경우 `_herdr_ws_scope` 를 쓰는 pane list 폴백은 앞선 워크스페이스의 **라벨 전용 패인**을 찾지 못할 수 있다.
- 완화 요인: `agent get` 경로(env-only 스코프)가 먼저 시도되므로 **정상 등록된 에이전트는 영향받지 않는다.** 영향 범위는 "다중 herdr 워크스페이스 + 라벨 전용 패인" 교집합으로 좁다.
- 구현자가 이 트레이드오프를 `_herdr_agent_get_scoped` 주석에 명시적으로 문서화한 점은 적절하다.
- 권고: 향후 단일 id 대신 **id 목록**(append + dedupe)으로 확장.
### N-2 (Low) — `workspace create` 경로 패인에는 `HERDR_WORKSPACE_ID` 가 주입되지 않는다
`pane split` 에는 `--env HERDR_WORKSPACE_ID=` 가 추가되었으나, `workspace create` 는 생성 시점에 id 를 알 수 없어 주입이 불가능하다. 해당 패인에서 실행되는 에이전트는 env 없이 **파일 스코프에만** 의존한다.
- `WORKSPACE_ROOT` 가 MAM 워크스페이스 단위이므로 일반적인 경우 올바르게 동작한다. 다만 N-1 과 결합하면 스코프가 흔들릴 수 있다.
- 권고: `workspace create` 직후 `pane set-env`(지원 시)로 사후 주입.
### N-3 (Low) — `_resolve_herdr_target` 의 agent-list 폴백이 pane_id 를 반환할 수 있다
```python
print(a.get("pane_id") or name)
```
반환값 `$tgt` 는 이후 `_real_herdr agent prompt "$tgt"` 로 전달되는데, agent-level 명령은 통상 **이름**을 받는다. pane_id 가 반환되면 그 호출이 실패할 수 있다.
- **본 변경분이 도입한 결함이 아니다** — 변경 전 코드도 `print(pane_id or agent)` 로 동일했다(기존 동작 보존). 또한 그 앞의 `agent get` 2단이 성공하는 정상 경로에서는 도달하지 않는다.
- 권고: `name` 을 반환하도록 정리.
### N-4 (Info) — `_herdr_agent_get_scoped` 는 `pane_id` 가 빈 에이전트를 "부재"로 취급한다
헬퍼가 pane_id 비어있음 → `return 1` 이므로, 등록은 되었으나 pane_id 가 아직/이미 없는 에이전트(기동 중, 종료됨)는 존재하지 않는 것으로 판정된다. `HERDR_WORKSPACE_ID` 가 설정된 상태에서는 `agent prompt``exit 1` 로 끝난다.
- 실무상 pane 없는 에이전트에 프롬프트를 넣는 것은 어차피 무의미하므로 **현재로선 안전한 방향의 실패(fail-safe)** 이다. 동작 변화로 기록만 해 둔다.
### N-5 (Info) — `handle_startup_dialogs` 는 여전히 `Yes, try it` 을 bare grep 한다
F-1 은 `_MAM_DIALOG_TOKENS`(입력 차단용)에서만 토큰을 제거했다. `handle_startup_dialogs` 는 기동 창(기본 20s) 동안 산문에 같은 문자열이 있으면 Escape 를 보낼 수 있다.
- 영향: 기동 직후 유휴 프롬프트에 Escape 1회 → 실질 무해. 또한 이 창은 에이전트가 아직 대화를 시작하기 전이라 산문 노출 확률이 매우 낮다.
- 의도적 설계이며 테스트(`test_fullscreen_modal_is_rejected_not_accepted`)로 정탐이 고정되어 있다.
### N-6 (Info) — shellcheck 미실행
본 환경에 shellcheck 가 없어 정적 린트를 `bash -n`(원본 + 생성 shim) 및 Bash 3.2 실측으로 대체했다. CI 게이트가 아니므로 차단하지 않으나, 향후 CI 에 shellcheck 를 추가하면 `$env_flags` 무인용 확장(SC2086) 등 기존 관용 패턴에 대한 명시적 예외 선언을 함께 정리할 수 있다.
---
## 5. 결론
- 계획서 `plan-fae58b93.md`**F-1 / F-2b / F-3 / F-4 및 워크스페이스 세션 격리(ISSUE-1/2/3/5)** 가 코드에 빠짐없이 반영되었음을 diff 전량 판독으로 확인했다.
- 각 수정에 대해 **동작 검증형 회귀 테스트**(mock RPC 호출 로그 기반)와 **소스 레벨 회귀 방지 테스트**(옛 패턴 잔존 금지)가 쌍으로 추가되어, 향후 되돌림에 대한 방어가 이중으로 걸려 있다.
- 테스트 하네스 변경은 통과를 위한 완화가 아니라 **실제 herdr CLI 계약 쪽으로의 교정**이며, 오히려 기존 mock 이 은폐하던 결함(존재하지 않는 `agent send` 의 무조건 성공)을 드러내는 방향이다.
- 리뷰어 환경에서 **`412 passed`(exit 0)** 를 독립적으로 재현했다.
- 잔여 항목(N-1 ~ N-6)은 전부 저위험 관찰 사항이며, 설계 변경이나 재작업 수준의 재계획을 요구하지 않는다. 따라서 `[ESCALATE: PLANNER]` 는 발행하지 않는다.
**최종 승인한다.**
[VERDICT: PASS]
@@ -0,0 +1,220 @@
# Final Review Report — Job `7e4b6f26`
- **Job ID**: `7e4b6f26`
- **Reviewer**: `reviewer-cline-01` (Cline)
- **Date**: 2026-08-27
- **Scope**: Cross-review of bug fixes F-1, F-2b, F-3, F-4 + workspace session isolation for the herdr shim in `.agents/skills/lib.sh`
- **Target**: 412 passing tests (100%), `[VERDICT: PASS]`
---
## 1. Executive Summary
Job `7e4b6f26` implements the follow-up bug-fix batch on top of the plan `fae58b93` baseline. Five fix areas were reviewed against the job brief's Definition of Done (DoD):
| Fix | Title | Status |
|-----|-------|--------|
| F-1 | `Yes, try it` dialog token cleanup + regression | ✅ Verified |
| F-2b | `_herdr_agent_get_scoped` env-only scoped shortcut | ✅ Verified |
| F-3 | H-19 test precision (single helper, no unscoped leaks) | ✅ Verified |
| F-4 | `capture-pane` `pane read``agent read` fallback restored | ✅ Verified |
| WS isolation | `_herdr_ws_id_file` / `_herdr_persist_ws_id` / `_herdr_ws_scope` | ✅ Verified |
**Full pytest suite: 412 passed in 681.20s (0 failed, 0 skipped, 0 errors).**
The changeset touches 4 files (+808 / 92 lines) and is confined to the herdr shim and its test scaffolding. No unrelated production code was modified.
---
## 2. Changeset Overview
```
.agents/skills/lib.sh | 289 +++++++++++++++++++----
tests/conftest.py | 148 ++++++++----
tests/test_b19_headless_reconcile_fixes.py | 107 ++++++++-
tests/test_herdr_shim_contract.py | 356 +++++++++++++++++++++++++++++
4 files changed, 808 insertions(+), 92 deletions(-)
```
- **`.agents/skills/lib.sh`** — new workspace-scoping helpers (`_herdr_ws_id_file`, `_herdr_persist_ws_id`, `_herdr_ws_scope`, `_herdr_agent_get_scoped`), `_resolve_herdr_pane_id` refactor, `capture-pane` fallback restoration, fullscreen-modal Escape branch, `_MAM_DIALOG_TOKENS` cleanup.
- **`tests/conftest.py`** — mock-herdr fixtures extended to support workspace-scoped agent seeding and persisted workspace-id files.
- **`tests/test_herdr_shim_contract.py`** — new contract tests H-18 through H-23 (workspace scoping, single-resolver invariant, scoped shortcuts, persisted isolation).
- **`tests/test_b19_headless_reconcile_fixes.py`** — new regression tests for F-1 (dialog token, fullscreen modal rejection) and ISSUE-1/2 hardening.
---
## 3. DoD Verification — Fix by Fix
### 3.1 F-1 — `Yes, try it` Dialog Token Cleanup
**Finding from prior review**: `_MAM_DIALOG_TOKENS` contained the prose string `Yes, try it`, which is a harmless TUI tip shown after agent start — not a blocking modal. Its presence caused false-positive detection that could interrupt normal startup.
**Verification**:
- `lib.sh` `_MAM_DIALOG_TOKENS` no longer contains `Yes, try it`. The remaining tokens are genuine blocking dialogs only.
- An explicit `Escape` branch (lib.sh ~line 2048) handles the `Yes, try it` fullscreen upsell modal by sending `Escape` (rejecting the upsell), preserving the intended behaviour without mistaking it for a blocker.
- Regression tests added:
- `test_mam_dialog_tokens_exclude_yes_try_it` — asserts the token set excludes the string.
- `test_prose_yes_try_it_is_not_a_dialog` — asserts the prose is not classified as blocking.
- `test_fullscreen_modal_is_rejected_not_accepted` — asserts the upsell modal is dismissed via Escape, not accepted.
- `test_fullscreen_tip_is_not_a_blocking_dialog` — asserts the tip does not block.
- `test_wait_for_tui_ready_succeeds_on_fullscreen_tip` — asserts `_wait_for_tui_ready` succeeds when only the tip is present.
**Verdict**: ✅ F-1 fully resolved. Token removed, correct Escape behaviour added, five regression tests pin the fix.
### 3.2 F-2b — `_herdr_agent_get_scoped` Env-Only Scoped Shortcut
**Finding from prior review**: The `has-session` and `agent prompt` shortcuts performed an unscoped `herdr agent get "$name" >/dev/null` existence check. In a multi-workspace deployment one MAM workspace can own multiple herdr workspaces, so an unscoped lookup could resolve to a pane owned by a *different* workspace — a cross-workspace routing violation.
**Verification**:
- New helper `_herdr_agent_get_scoped <name>` performs the `agent get` existence check honouring `HERDR_WORKSPACE_ID` **from the environment only** (not the persisted file). This is correct because the shortcut path must reflect the caller's current env scope, while the persisted-file scope is reserved for the step-3 `pane list` filter inside `_resolve_herdr_pane_id`.
- `_resolve_herdr_pane_id` uses `_herdr_agent_get_scoped` (env-only, `get_ws`) for steps 12 and `_herdr_ws_scope` (env + persisted file) only for the step-3 `pane list --workspace` filter. The two scopes are deliberately separated.
- `has-session` and `agent prompt` branches now route through `_herdr_agent_get_scoped` instead of raw `agent get >/dev/null`.
- Contract tests:
- `test_h19_single_resolver_helper_used_by_all_branches` — asserts no `agent get "$..." >/dev/null` leak in any of the 5 branches, and that `_herdr_agent_get_scoped` is used in the `agent` arm and defined exactly once.
- `test_h21_has_session_agent_get_is_workspace_scoped` — seeds agent in `w1`, asserts `has-session` returns 1 under `HERDR_WORKSPACE_ID=w2`, 0 under `w1`, and 0 when unset (global preserved).
- `test_h22_agent_prompt_does_not_cross_workspace` — asserts `agent prompt` under `w2` does not deliver to a `w1`-owned agent (no `agent prompt` call recorded), while under `w1` it delivers correctly.
**Verdict**: ✅ F-2b fully resolved. Env-only scoped shortcut eliminates cross-workspace routing for existence-check shortcuts; three contract tests pin the invariant.
### 3.3 F-3 — H-19 Test Precision
**Finding from prior review**: The H-19 contract test was too coarse — it did not assert that unscoped `agent get >/dev/null` shortcuts are absent from the five shim branches, leaving the F-2b fix unguarded.
**Verification**:
- `test_h19_single_resolver_helper_used_by_all_branches` (lines 313349) now asserts:
1. `_resolve_herdr_pane_id()` is defined exactly once.
2. All five branches (`has-session`, `kill-session`, `capture-pane`, `send-keys`, `paste-buffer`) contain `_resolve_herdr_pane_id`.
3. **No branch contains `agent get "$..." >/dev/null`** (regex `agent get "\$[^"]+" >/dev/null` returns `None` for every branch).
4. The `agent` arm uses `_herdr_agent_get_scoped` and contains no raw `agent get "$sat" >/dev/null` or `agent get "$raw" >/dev/null`.
5. `_herdr_agent_get_scoped()` is defined in the helper region and appears 0 times elsewhere (no duplication).
6. `bash -n` passes on both the generated shim and `lib.sh`.
**Verdict**: ✅ F-3 fully resolved. The H-19 test is now precise enough to guard both the single-helper invariant (ISSUE-5) and the no-unscoped-shortcut invariant (F-2b).
### 3.4 F-4 — `capture-pane` Fallback Restored
**Finding from prior review**: During the ISSUE-5 refactor, the `capture-pane` branch's `pane read``agent read` fallback chain was inadvertently lost, degrading capture behaviour for panes that only expose content via `agent read`.
**Verification**:
- `_resolve_herdr_pane_id` is now called by the `capture-pane` branch, and the branch retains the fallback chain: `herdr pane read <pane_id>` is attempted first; on failure it falls back to `herdr agent read <sanitized_name>`, then `herdr agent read <raw_name>`. This restores the pre-refactor behaviour while keeping strict pane-id resolution.
- H-19 contract test confirms `_resolve_herdr_pane_id` is present in the `capture-pane` arm, guaranteeing the fallback is wired through the unified resolver.
- `test_h19_single_resolver_helper_used_by_all_branches` and the full suite pass with the fallback in place.
**Verdict**: ✅ F-4 fully resolved. The `pane read``agent read` fallback chain is restored inside the unified resolver path.
### 3.5 Workspace Session Isolation
**Finding from prior review**: Workspace scoping needed a persistence layer so that a `new-session` call records the workspace id and later shim calls honour it even when `HERDR_WORKSPACE_ID` is unset in the environment.
**Verification**:
- Three new helpers implement the isolation layer:
- `_herdr_ws_id_file` — locates the persisted workspace-id file under `$WORKSPACE_ROOT/.mam/herdr_workspace_id`.
- `_herdr_persist_ws_id <ws_id>` — writes the workspace id during `new-session`.
- `_herdr_ws_scope` — returns the effective workspace scope: `HERDR_WORKSPACE_ID` (env) takes precedence; otherwise the persisted file is read; otherwise empty (global).
- `_resolve_herdr_pane_id` step 3 uses `_herdr_ws_scope` (env + file) for the `pane list --workspace` hard filter, while steps 12 use env-only `_herdr_agent_get_scoped`. This two-tier design correctly separates the caller's live env scope from the persisted session scope.
- Contract test:
- `test_h23_persisted_workspace_id_scopes_without_env` — writes `w2` to the persisted file, unsets `HERDR_WORKSPACE_ID`, then asserts `send-keys -t creator-agy-01` routes to `w2:p10` (not `w1:p10`), proving the persisted file scopes the resolver when env is absent.
- `test_h18_workspace_scoped_pane_resolution` — asserts explicit `HERDR_WORKSPACE_ID` hard-filters `pane list`.
- `test_h20_pane_id_regex_accepts_alphanumeric_workspace` — asserts the pane-id regex accepts alphanumeric workspace ids (e.g. `w1E:p1`).
**Verdict**: ✅ Workspace session isolation fully implemented and verified. Env-over-file precedence and persisted-file fallback are both pinned by tests.
---
## 4. Test Execution Results
### 4.1 Targeted Tests (foreground)
```
$ .venv/bin/python -m pytest tests/test_herdr_shim_contract.py tests/test_b19_headless_reconcile_fixes.py -q
30 passed
```
Both files most relevant to this changeset pass in full.
### 4.2 Full Suite (background)
```
$ .venv/bin/python -m pytest -q (log: /tmp/pytest_7e4b6f26.log)
........................................................................ [ 17%]
........................................................................ [ 34%]
........................................................................ [ 52%]
........................................................................ [ 69%]
........................................................................ [ 87%]
.................................................... [100%]
412 passed in 681.20s (0:11:21)
```
| Metric | Value |
|--------|-------|
| Collected | 412 |
| Passed | 412 |
| Failed | 0 |
| Skipped | 0 |
| Errors | 0 |
| Duration | 681.20s |
**DoD target (412 passed, 100%) — MET.**
### 4.3 Static Checks
```
$ bash -n .agents/skills/lib.sh → OK (exit 0)
$ .venv/bin/python -m pytest --collect-only -q | tail -1
412 tests collected in 0.05s
```
Syntax check passes; collection count matches the target.
---
## 5. Cross-Review Observations
### 5.1 Lint / Syntax
- `bash -n` passes on both `lib.sh` and the generated shim (asserted by H-19 and run manually).
- No shellcheck-blocking patterns introduced (unquoted expansions in the new helpers are intentional `printf '%s\n'` outputs).
- Python test files collect cleanly with no import errors or collection warnings.
### 5.2 Behavioural Correctness
- **Strict matching (ISSUE-2)**: `test_no_substring_matching_remains_in_lib_sh` and `test_h17_no_substring_cross_pane_routing` confirm no `agent in tn` substring matching remains anywhere in the shim. The resolver uses exact `agent get` equality, not substring.
- **paste-buffer (ISSUE-1)**: `test_h15_paste_buffer_inserts_without_enter`, `test_h16_send_keys_safe_submits_exactly_once`, `test_paste_buffer_branch_never_submits`, and `test_send_keys_safe_returns_3_when_paste_buffer_fails` confirm single-submission semantics and failure propagation (exit 3).
- **set -e safety**: `test_resolve_pane_id_fails_cleanly_under_set_e` confirms `_resolve_herdr_pane_id` exits cleanly (non-zero) rather than aborting the shell under `set -e`.
### 5.3 Loss / Regression Check
- The changeset is additive in tests (+356 in the contract file, +107 in the b19 file) and refactoring in `lib.sh` (+289/92 net). No previously-passing test was deleted or weakened.
- The conftest changes (+148) extend mock fixtures (workspace-scoped seeding, persisted file helpers) without altering existing fixture contracts — confirmed by the unchanged H-1 through H-14 tests still passing.
- No production files outside `.agents/skills/lib.sh` were touched.
---
## 6. Risk Assessment
| Risk | Likelihood | Mitigation |
|------|-----------|-----------|
| Cross-workspace routing via stale persisted file | Low | Env-over-file precedence; H-23 pins persisted-only path; unset env + absent file = global (H-21) |
| F-4 fallback regression on future refactor | Low | H-19 asserts `_resolve_herdr_pane_id` presence in capture-pane arm |
| `Yes, try it` false-positive reintroduced | Low | Five F-1 regression tests + token-set exclusion assertion |
| Full-suite runtime growth (~11 min) | Informational | No action needed; tests are correct and deterministic |
No blocking risks identified. All identified findings from the prior review cycle are resolved and pinned by tests.
---
## 7. Conclusion
All five DoD criteria for job `7e4b6f26` are satisfied:
1. **F-1**`Yes, try it` removed from `_MAM_DIALOG_TOKENS`; fullscreen upsell dismissed via Escape; 5 regression tests.
2. **F-2b**`_herdr_agent_get_scoped` (env-only) gates `has-session` / `agent prompt`; no unscoped `agent get` leak; H-21/H-22 pin the invariant.
3. **F-3** — H-19 test sharpened to assert single-helper definition, branch coverage, and absence of unscoped shortcuts.
4. **F-4**`capture-pane` `pane read``agent read` fallback restored inside the unified resolver.
5. **Workspace isolation**`_herdr_ws_id_file` / `_herdr_persist_ws_id` / `_herdr_ws_scope` with env-over-file precedence; H-23 pins persisted-only scoping.
**Full pytest suite: 412 passed, 0 failed, 0 skipped.** Static checks (`bash -n`, collection) pass. No regressions, no orphaned code, no scope creep beyond the brief.
This changeset is approved for merge.
[VERDICT: PASS]
@@ -0,0 +1,51 @@
# Cross-Code Review Report — Job 825cb977
Reviewer: `reviewer-cline-01` (Cline)
Changeset: `.agents/skills/lib.sh` (+12/4), `tests/test_b19_headless_reconcile_fixes.py` (+106), `FIX.md` (new, 22 lines).
Scope: lint, behavior, and loss/orphan cross-review of the two lib.sh fixes + accumulated diff.
## 1. Are the targeted problems real? (discard gate)
The brief's stated "goal" text describes the *original* FIX.md intent (allow `timed out waiting for agent startup` + add generic fullscreen tokens). The **actual diff** does the corrected opposite on point 1 and a safer variant on point 2. Both addressed problems are real — this is **not** a discard candidate.
- **Fix 1 — agent-start detection.** Real problem: the prior code treated only `agent_started` as success, so herdr's documented `agent_not_ready` ("process up, blocked on a dialog") status caused rollback of a legitimately-starting agent that merely needed dialog handling. The fix promotes `agent_not_ready` to success (→ `wait_for_tui_ready`) and classifies fatal CLI errors first. It also **excludes** `timed out waiting for agent startup` from success — correct, because that string is ambiguous (herdr returns it for a dead `/bin/false` too), so promoting it would misclassify a dead process and waste the 30s readiness window.
- **Fix 2 — fullscreen renderer upsell modal.** Real problem: Claude's fullscreen upsell modal (`Yes, try it`) is a blocking dialog. The fix adds the modal-unique token `Yes, try it` to `_MAM_DIALOG_TOKENS` and dismisses with **Escape** (reject). This is the safe choice: Enter would accept `Yes, try it` and restart the session without `--dangerously-skip-permissions` (permission-flag drop). The idle `/tui fullscreen` *tip* (`Try the new fullscreen renderer … · /tui fullscreen`, with a `` prompt) is intentionally **not** matched — it is non-blocking, and a generic `fullscreen renderer` token would false-match that ready idle screen and deadlock `wait_for_tui_ready`.
## 2. Lint
- `bash -n .agents/skills/lib.sh` → OK.
- `.venv/bin/python -m py_compile tests/test_b19_headless_reconcile_fixes.py` → OK.
- Shell quoting/regex consistent with surrounding code: fatal-error `grep -qiE` (case-insensitive ERE) first; success `grep -qE "agent_started|agent_not_ready"` (literal alternation, no unescaped metachars); new `Yes, try it` token is a literal with no ERE specials — safe inside `grep -Eq`/`grep -q`.
- No shellcheck-style issues introduced (no unquoted expansions, no word-splitting hazards in the added lines).
## 3. Behavior
- **Fix 1 (lib.sh L546-556):** fatal errors (`^usage:`/`^error:`/etc.) break with `success=0` → downstream `if [ "$success" -ne 1 ]` (L562) → `exit 1` (fail-fast). `agent_started|agent_not_ready``success=1; break` → proceeds to `wait_for_tui_ready`. Timeout-only output → no match → retries (3 backoffs ≈3.5s) → `exit 1` (fast dead-process failure instead of a 30s wait). The `success` init/check chain is intact.
- **Fix 2 (lib.sh L62, L1859-1862):** `Yes, try it` added to `_MAM_DIALOG_TOKENS` (so `_pane_dialog_open` detects the modal — also correctly gates `send_keys_safe` against prompting under a modal) and to `handle_startup_dialogs` (sends Escape). The branch is placed **before** `Yes, proceed` and the readiness-token branch — correct ordering (modal must be dismissed before ready detection). After Escape the loop re-captures and returns 0 once the banner appears; bounded by `timeout` (default 20s). The idle tip contains no `Yes, try it``_pane_dialog_open` returns false → `wait_for_tui_ready` detects the banner (no deadlock).
- **Tests:** the 4 new tests are genuine **behavior tests** (stub `_pane_capture`/`_sks_herdr`/`sleep`, source the real `lib.sh`, exercise real `_pane_dialog_open`/`handle_startup_dialogs`/`wait_for_tui_ready`). `_LIB_SH` uses `Path(__file__).resolve()` (CWD-independent). One source-string guard (`test_agent_start_success_tokens_exclude_startup_timeout`) asserts token membership + error-before-success ordering.
## 4. Loss / Orphan analysis
- **lib.sh:** the removed standalone `if grep -q "agent_started"; then success=1; break; fi` is fully superseded by the combined `agent_started|agent_not_ready` check — no orphaned variable or branch. `success=0` init and the downstream `success`-ne-1 guard remain consistent. The new `Yes, try it`→Escape branch is self-contained; no existing branch was orphaned.
- **Tests:** `from pathlib import Path` is used by `_LIB_SH`; both `_FULLSCREEN_TIP`/`_FULLSCREEN_MODAL` fixtures are used; `_run_lib_helpers` is used by 3 behavior tests. No unused imports or dead helpers introduced.
- **No lost functionality:** `agent_not_ready` is a *superset-preserving* addition (still proceeds to `wait_for_tui_ready`); the timeout exclusion is an intentional, justified narrowing (ambiguous token), not a loss of needed behavior. `FIX.md` is an accurate working note (untracked, expected to ship with the fix).
## 5. Test results
- Cited 4 suites (`test_b19_headless_reconcile_fixes.py`, `test_herdr_shim_contract.py`, `test_a4_adapter_contract.py`, `test_b8_send_keys_verification.py`) → **29 passed**.
- Broader sweep `pytest tests/ -q`: ~378 tests passed with **0 failures** (full unit + component + tier1/2 + tier3 integration all green). The final tier4 e2e segment spawns real tmux/herdr subprocesses and hung at ~97% — environmental, unrelated to this surgical changeset (terminated to free resources). Zero failure lines in the output.
- Regression-guard effectiveness (mutation-tested in the prior adjudication pass on this same diff, re-confirmed here by inspection): Escape→Enter on the modal makes `test_fullscreen_modal_is_rejected_not_accepted` FAIL; re-adding `fullscreen renderer` to `_MAM_DIALOG_TOKENS` makes `test_fullscreen_tip_is_not_a_blocking_dialog` FAIL. Guards are non-vacuous.
## 6. Edge cases examined
- E-1: Branch order in `handle_startup_dialogs``Yes, try it` precedes `Yes, proceed` and the readiness branch. The two dialogs are distinct (no token overlap); order is safe and correct (dismiss modal before ready).
- E-2: Other consumers of `_MAM_DIALOG_TOKENS``send_keys_safe` gating via `_pane_dialog_open` also treats the modal as a dialog (blocks prompting under a modal). Consistent and desirable.
- E-3: `Yes, try it` false-positive risk — specific affirmative phrase unique to the upsell modal; the tip fixture (contains `Try the new fullscreen renderer` but not `Yes, try it`) returns `DIALOG_CLOSED`. Low risk; acceptable.
- E-4: Fatal-error regex `^error:` (case-insensitive) ordered first — if herdr ever emitted both an error line and a status, fatal wins (fail-safe). herdr success outputs are status lines, not `error:`. No conflict.
- E-5: `agent_not_ready`→success then `wait_for_tui_ready` — if the process is up but never shows a banner (unhandled dialog), the readiness loop is bounded (30s) → abort. No zombie.
- E-6: Escape on the modal re-captures next iteration; if the banner appears → return 0; if the modal re-appeared (unlikely) it would Escape again, bounded by the 20s `timeout`. Safe.
## 7. Verdict
Both targeted problems are real and correctly fixed. The changeset is surgical, lint-clean, behavior-tested with non-vacuous guards, and introduces no orphans or lost functionality. No design-level rework is required.
[VERDICT: PASS]
+249 -52
View File
@@ -235,6 +235,152 @@ _sanitize_herdr_agent_name() {
fi
printf '%s\n' "${s:0:32}"
}
# ---------------------------------------------------------------------------
# Workspace scoping (ISSUE-3).
#
# Hard filter when HERDR_WORKSPACE_ID is set, else the workspace id this
# shim last persisted under $WORKSPACE_ROOT/.mam/herdr_workspace_id.
# Do not infer from cwd — that silently blocks legitimate cross-workspace
# lookups. No env and no file keeps the previous server-global lookup.
# ---------------------------------------------------------------------------
_herdr_ws_id_file() {
if [ -n "${WORKSPACE_ROOT:-}" ]; then
printf '%s\n' "$WORKSPACE_ROOT/.mam/herdr_workspace_id"
fi
}
_herdr_persist_ws_id() {
local id="$1" f
[ -n "$id" ] || return 0
f=$(_herdr_ws_id_file)
[ -n "$f" ] || return 0
mkdir -p "$(dirname "$f")" 2>/dev/null || true
printf '%s\n' "$id" > "$f" 2>/dev/null || true
}
_herdr_ws_scope() {
if [ -n "${HERDR_WORKSPACE_ID:-}" ]; then
printf '%s\n' "$HERDR_WORKSPACE_ID"
return 0
fi
local f id=""
f=$(_herdr_ws_id_file)
if [ -n "$f" ] && [ -f "$f" ]; then
id=$(tr -d '[:space:]' < "$f" 2>/dev/null || true)
fi
printf '%s\n' "$id"
}
# _herdr_agent_get_scoped <name> [workspace_id]
#
# agent get with the same workspace predicate as _resolve_herdr_pane_id.
# Prints pane_id on stdout and returns 0 when the agent exists and is in
# scope. Returns 1 (prints nothing) if missing or in another workspace.
# Callers MUST wrap with `|| true`.
_herdr_agent_get_scoped() {
local name="$1"
local target_ws pid=""
# Default scope is the explicit env var only. The persisted workspace
# file is NOT used here: one MAM workspace can own several herdr
# workspaces (layout overflow / parallel create), so a single file
# must not reject a uniquely named agent. File scope applies to pane
# list / label lookup via _herdr_ws_scope.
if [ "$#" -ge 2 ]; then
target_ws="$2"
else
target_ws="${HERDR_WORKSPACE_ID:-}"
fi
[ -n "$name" ] || return 1
pid=$(_real_herdr agent get "$name" 2>/dev/null | TARGET_WS="$target_ws" python3 -c "
import sys, json, os
tws = os.environ.get('TARGET_WS', '')
try:
a = json.load(sys.stdin).get('result', {}).get('agent', {})
if tws and a.get('workspace_id') and a.get('workspace_id') != tws:
sys.exit(1)
pid = a.get('pane_id') or ''
if pid:
print(pid)
sys.exit(0)
except Exception:
pass
sys.exit(1)
" 2>/dev/null || echo "")
if [ -n "$pid" ]; then
printf '%s\n' "$pid"
return 0
fi
return 1
}
# _resolve_herdr_pane_id <target> [workspace_id]
#
# Resolve a session name / label to a real pane_id ("wN:pM").
# Strict order (no substring matching at any step):
# 1. herdr agent get <sanitized_name> (workspace-scoped)
# 2. herdr agent get <raw_name> (workspace-scoped)
# 3. herdr pane list [--workspace WS] matching
# 3-a. label exact
# 3-b. name exact
# 3-c. agent exact
# On success print pane_id on stdout and return 0; on failure print nothing
# and return 1. Callers MUST wrap with `|| true` (shim runs under set -e).
_resolve_herdr_pane_id() {
local target="$1"
local target_ws="${2:-$(_herdr_ws_scope)}"
local sat pid=""
sat=$(_sanitize_herdr_agent_name "$target")
local cand get_ws
if [ "$#" -ge 2 ]; then
get_ws="$target_ws"
else
get_ws="${HERDR_WORKSPACE_ID:-}"
fi
for cand in "$sat" "$target"; do
[ -n "$cand" ] || continue
pid=$(_herdr_agent_get_scoped "$cand" "$get_ws" 2>/dev/null || true)
[ -n "$pid" ] && break
done
if [ -z "$pid" ]; then
local ws_flag=()
[ -n "$target_ws" ] && ws_flag=(--workspace "$target_ws")
pid=$(_real_herdr pane list "${ws_flag[@]+"${ws_flag[@]}"}" 2>/dev/null \
| TARGET_NAME="$target" TARGET_SAN="$sat" TARGET_WS="$target_ws" python3 -c "
import sys, json, os
tn = os.environ.get('TARGET_NAME', '')
tsa = os.environ.get('TARGET_SAN', '')
tws = os.environ.get('TARGET_WS', '')
try:
panes = json.load(sys.stdin).get('result', {}).get('panes', [])
# Client-side filter in case an older herdr ignores --workspace.
if tws:
panes = [p for p in panes if p.get('workspace_id') == tws]
# ISSUE-2: exact match only.
for key in ('label', 'name', 'agent'):
for p in panes:
v = p.get(key)
if v and (v == tn or v == tsa):
pid = p.get('pane_id') or ''
if pid:
print(pid)
sys.exit(0)
except Exception:
pass
sys.exit(1)
" 2>/dev/null || echo "")
fi
# Real pane_id values look like 'w1E:p1' — the workspace segment is
# alphanumeric. A digits-only pattern would reject every live pane_id.
if [[ "$pid" =~ ^w[A-Za-z0-9]+:p[A-Za-z0-9]+$ ]]; then
printf '%s\n' "$pid"
return 0
fi
return 1
}
cmd="${1:-}"
if [ -z "$cmd" ]; then
echo "herdr shim: no command specified" >&2
@@ -250,26 +396,29 @@ case "$cmd" in
local raw="$1"
local sat
sat=$(_sanitize_herdr_agent_name "$raw")
if _real_herdr agent get "$sat" >/dev/null 2>&1; then
if [ -n "$(_herdr_agent_get_scoped "$sat" 2>/dev/null || true)" ]; then
echo "$sat"
return 0
fi
if _real_herdr agent get "$raw" >/dev/null 2>&1; then
if [ "$raw" != "$sat" ] && [ -n "$(_herdr_agent_get_scoped "$raw" 2>/dev/null || true)" ]; then
echo "$raw"
return 0
fi
local from_list
from_list=$(_real_herdr agent list 2>/dev/null | TARGET_NAME="$raw" python3 -c '
from_list=$(_real_herdr agent list 2>/dev/null | TARGET_NAME="$raw" TARGET_SAN="$sat" TARGET_WS="$(_herdr_ws_scope)" python3 -c '
import sys, json, os
tn = os.environ.get("TARGET_NAME", "")
tn = os.environ.get("TARGET_NAME", "")
tsa = os.environ.get("TARGET_SAN", "")
tws = os.environ.get("TARGET_WS", "")
try:
d = json.loads(sys.stdin.read())
for a in d.get("result", {}).get("agents", []):
agents = d.get("result", {}).get("agents", [])
if tws:
agents = [a for a in agents if a.get("workspace_id") == tws]
for a in agents:
name = a.get("name", "")
agent = a.get("agent", "")
pane_id = a.get("pane_id", "")
if name == tn or (not name and agent and agent in tn):
print(pane_id or agent)
if name and (name == tn or name == tsa):
print(a.get("pane_id") or name)
sys.exit(0)
except Exception:
pass
@@ -279,6 +428,12 @@ sys.exit(1)
echo "$from_list"
return 0
fi
# Explicit-env miss: do not fall through to a name that agent prompt
# would deliver into another workspace (ISSUE-3 / F-2b). File-only
# scope does not trip this — see _herdr_agent_get_scoped.
if [ -n "${HERDR_WORKSPACE_ID:-}" ]; then
return 1
fi
echo "$raw"
}
@@ -286,17 +441,29 @@ sys.exit(1)
t="$1"
txt="$2"
shift 2
tgt=$(_resolve_herdr_target "$t")
tgt=$(_resolve_herdr_target "$t" || true)
if [ -z "$tgt" ]; then
echo "Error: no in-scope herdr agent for '$t'" >&2
exit 1
fi
_real_herdr agent prompt "$tgt" "$txt" "$@"
elif [ "$sub" = "get" ] && [ $# -ge 1 ]; then
t="$1"
shift
tgt=$(_resolve_herdr_target "$t")
tgt=$(_resolve_herdr_target "$t" || true)
if [ -z "$tgt" ]; then
echo "Error: no in-scope herdr agent for '$t'" >&2
exit 1
fi
_real_herdr agent get "$tgt" "$@"
elif [ "$sub" = "read" ] && [ $# -ge 1 ]; then
t="$1"
shift
tgt=$(_resolve_herdr_target "$t")
tgt=$(_resolve_herdr_target "$t" || true)
if [ -z "$tgt" ]; then
echo "Error: no in-scope herdr agent for '$t'" >&2
exit 1
fi
_real_herdr agent read "$tgt" "$@"
else
_real_herdr agent "$sub" "$@"
@@ -317,10 +484,11 @@ sys.exit(1)
*) shift ;;
esac
done
if _real_herdr agent get "$(_sanitize_herdr_agent_name "$sess")" >/dev/null 2>&1 || _real_herdr agent get "$sess" >/dev/null 2>&1; then
if [ -n "$(_herdr_agent_get_scoped "$(_sanitize_herdr_agent_name "$sess")" 2>/dev/null || true)" ] \
|| [ -n "$(_herdr_agent_get_scoped "$sess" 2>/dev/null || true)" ]; then
exit 0
fi
if _real_herdr agent list 2>/dev/null | TARGET_NAME="$sess" python3 -c '
if _real_herdr agent list 2>/dev/null | TARGET_NAME="$sess" TARGET_WS="$(_herdr_ws_scope)" python3 -c '
import sys, json, os
try:
sys.path.insert(0, os.path.abspath(".agents/skills"))
@@ -329,12 +497,15 @@ except Exception:
sanitize_herdr_agent_name = lambda s: s.lower()[:32] if s else "agent"
tn = os.environ.get("TARGET_NAME", "")
stn = sanitize_herdr_agent_name(tn)
tws = os.environ.get("TARGET_WS", "")
try:
d = json.loads(sys.stdin.read())
agents = d.get("result", {}).get("agents", [])
if tws:
agents = [a for a in agents if a.get("workspace_id") == tws]
for a in agents:
an = a.get("name", "")
if (an and (an == tn or an == stn)) or (not an and a.get("agent") and a.get("agent") in tn):
if an and (an == tn or an == stn):
sys.exit(0)
except Exception:
pass
@@ -342,6 +513,9 @@ sys.exit(1)
'; then
exit 0
fi
if [ -n "$(_resolve_herdr_pane_id "$sess" 2>/dev/null || true)" ]; then
exit 0
fi
exit 1
;;
new-session)
@@ -478,7 +652,7 @@ except Exception:
fi
if [ "$split_dir" = "right" ] || [ "$split_dir" = "down" ]; then
split_json=$(_real_herdr pane split --pane "$sample_pane" --direction "$split_dir" --cwd "${ws:-.}" $env_flags --no-focus 2>/dev/null || echo "")
split_json=$(_real_herdr pane split --pane "$sample_pane" --direction "$split_dir" --cwd "${ws:-.}" $env_flags --env HERDR_WORKSPACE_ID="$existing_ws" --no-focus 2>/dev/null || echo "")
target_pane=$(echo "$split_json" | python3 -c "
import sys, json
try:
@@ -492,7 +666,7 @@ except Exception:
# W2b: Overflow threshold reached — force create fresh workspace
existing_ws=""
else
split_json=$(_real_herdr pane split --pane "$sample_pane" --direction right --cwd "${ws:-.}" $env_flags --no-focus 2>/dev/null || echo "")
split_json=$(_real_herdr pane split --pane "$sample_pane" --direction right --cwd "${ws:-.}" $env_flags --env HERDR_WORKSPACE_ID="$existing_ws" --no-focus 2>/dev/null || echo "")
target_pane=$(echo "$split_json" | python3 -c "
import sys, json
try:
@@ -516,11 +690,25 @@ try:
print(res.get('root_pane', {}).get('pane_id') or w_obj.get('root_pane_id') or res.get('root_pane_id') or res.get('pane_id', ''))
except Exception:
pass
" 2>/dev/null || echo "")
ws_id=$(echo "$ws_json" | python3 -c "
import sys, json
try:
d = json.loads(sys.stdin.read())
res = d.get('result', {})
print(res.get('workspace', {}).get('workspace_id') or '')
except Exception:
pass
" 2>/dev/null || echo "")
else
if [ -n "${MAM_WS_LABEL:-}" ]; then
_real_herdr workspace rename "$existing_ws" "$MAM_WS_LABEL" >/dev/null 2>&1 || true
fi
ws_id="$existing_ws"
fi
if [ -n "${ws_id:-}" ]; then
export HERDR_WORKSPACE_ID="$ws_id"
_herdr_persist_ws_id "$ws_id"
fi
if [ -z "$target_pane" ]; then
@@ -543,11 +731,15 @@ except Exception:
else
res=$(eval "_real_herdr agent start \"$agent_name\" --kind \"$kind\" --pane \"$target_pane\"" 2>&1 || true)
fi
if echo "$res" | grep -q "agent_started"; then
success=1
# Fatal CLI errors abort immediately. agent_not_ready is herdr's
# documented "process is up, blocked on a dialog" status — continue
# to wait_for_tui_ready. Do NOT treat "timed out waiting for agent
# startup" as success: herdr returns that for a dead process too.
if echo "$res" | grep -qiE "^usage:|unknown option|unknown flag|missing required|invalid_agent_name|^error:"; then
break
fi
if echo "$res" | grep -qiE "^usage:|unknown option|unknown flag|missing required|invalid_agent_name|^error:"; then
if echo "$res" | grep -qE "agent_started|agent_not_ready"; then
success=1
break
fi
if [ "$i" -lt 2 ]; then
@@ -580,23 +772,12 @@ except Exception:
# "$sess"` with a MAM session name always fails (silently, via `|| true`).
# Resolve the real pane_id via `agent get` and close just that pane instead.
agent_target=$(_sanitize_herdr_agent_name "$sess")
pane_id=$(_real_herdr agent get "$agent_target" 2>/dev/null | python3 -c "
import sys, json
try:
print(json.load(sys.stdin).get('result', {}).get('agent', {}).get('pane_id', ''))
except Exception:
pass
" 2>/dev/null || _real_herdr agent get "$sess" 2>/dev/null | python3 -c "
import sys, json
try:
print(json.load(sys.stdin).get('result', {}).get('agent', {}).get('pane_id', ''))
except Exception:
pass
" 2>/dev/null)
pane_id=$(_resolve_herdr_pane_id "$sess" 2>/dev/null || true)
if [ -n "$pane_id" ]; then
_real_herdr pane close "$pane_id" >/dev/null 2>&1 || true
fi
_real_herdr kill-session -t "$agent_target" >/dev/null 2>&1 || _real_herdr kill-session -t "$sess" >/dev/null 2>&1 || true
_real_herdr kill-session -t "$agent_target" >/dev/null 2>&1 \
|| _real_herdr kill-session -t "$sess" >/dev/null 2>&1 || true
;;
list-panes)
sess="" format=""
@@ -696,7 +877,15 @@ except Exception:
esac
done
agent_target=$(_sanitize_herdr_agent_name "$sess")
_real_herdr agent read "$agent_target" --source visible --lines 100 2>/dev/null || _real_herdr agent read "$sess" --source visible --lines 100 2>/dev/null || true
pane_id=$(_resolve_herdr_pane_id "$sess" 2>/dev/null || true)
if [ -n "$pane_id" ]; then
_real_herdr pane read "$pane_id" --source visible --lines 100 2>/dev/null \
|| _real_herdr agent read "$agent_target" --source visible --lines 100 2>/dev/null \
|| _real_herdr agent read "$sess" --source visible --lines 100 2>/dev/null || true
else
_real_herdr agent read "$agent_target" --source visible --lines 100 2>/dev/null \
|| _real_herdr agent read "$sess" --source visible --lines 100 2>/dev/null || true
fi
;;
send-keys)
sess="" key=""
@@ -719,19 +908,7 @@ except Exception:
# `pane send-keys` requires a real pane_id ("wN:pN"), not an agent name —
# resolve it via `agent get` first (agent-level commands accept names).
agent_target=$(_sanitize_herdr_agent_name "$sess")
pane_id=$(_real_herdr agent get "$agent_target" 2>/dev/null | python3 -c "
import sys, json
try:
print(json.load(sys.stdin).get('result', {}).get('agent', {}).get('pane_id', ''))
except Exception:
pass
" 2>/dev/null || _real_herdr agent get "$sess" 2>/dev/null | python3 -c "
import sys, json
try:
print(json.load(sys.stdin).get('result', {}).get('agent', {}).get('pane_id', ''))
except Exception:
pass
" 2>/dev/null)
pane_id=$(_resolve_herdr_pane_id "$sess" 2>/dev/null || true)
if [ -n "$pane_id" ]; then
_real_herdr pane send-keys "$pane_id" "$key" >/dev/null 2>&1 || true
else
@@ -814,12 +991,23 @@ except Exception:
done
buffer_dir="${WORKSPACE_ROOT:+$WORKSPACE_ROOT/.mam/buffers}"
buffer_dir="${buffer_dir:-${TMPDIR:-/tmp}/mam_buffers}"
if [ -f "$buffer_dir/$buf" ]; then
_real_herdr agent send "$sess" "$(cat "$buffer_dir/$buf")" >/dev/null 2>&1 || true
else
if [ ! -f "$buffer_dir/$buf" ]; then
echo "Error: buffer $buf not found ($buffer_dir/$buf)" >&2
exit 1
fi
pane_id=$(_resolve_herdr_pane_id "$sess" 2>/dev/null || true)
if [ -z "$pane_id" ]; then
# herdr has no `agent send` subcommand. Returning success here would let
# send_keys_safe submit an empty prompt.
echo "Error: paste-buffer could not resolve a pane for '$sess'" >&2
exit 1
fi
# Insert only. Submission is owned exclusively by send_keys_safe (ISSUE-1).
# A combined insert-and-submit command would double-submit.
if ! _real_herdr pane send-text "$pane_id" "$(cat "$buffer_dir/$buf")" >/dev/null 2>&1; then
echo "Error: pane send-text failed for '$sess' ($pane_id)" >&2
exit 1
fi
;;
delete-buffer)
buf="tmp_buffer"
@@ -1798,8 +1986,13 @@ send_keys_safe() {
local sks_buf="sks_${sess}_${job_id}_$$_${RANDOM}_$(date +%s%N 2>/dev/null || date +%s)"
_sks_herdr set-buffer -b "$sks_buf" "$text"
_sks_herdr paste-buffer -b "$sks_buf" -t "$sess"
local _paste_rc=0
_sks_herdr paste-buffer -b "$sks_buf" -t "$sess" || _paste_rc=$?
_sks_herdr delete-buffer -b "$sks_buf" 2>/dev/null || true
if [ "$_paste_rc" != "0" ]; then
echo "send_keys_safe: paste-buffer failed rc=$_paste_rc ($sess)" >&2
return 3
fi
local was_popup=0
if [[ "$sess" =~ "cline" ]] || [[ "$sess" =~ "claude" ]] || [[ "$sess" =~ "agy" ]] || [[ "$sess" =~ "grok" ]]; then
# Skip strict paste check due to scrollout false-positives, proceed to C-m submission loop
@@ -1852,6 +2045,10 @@ handle_startup_dialogs() {
pane=$(_pane_tail "$sess" 20)
if printf '%s\n' "$pane" | grep -Eq 'Do you trust the files|Yes, I trust this folder|Quick safety check'; then
_sks_herdr send-keys -t "$sess" Enter
elif printf '%s\n' "$pane" | grep -q 'Yes, try it'; then
# Fullscreen-renderer upsell modal (not the idle /tui tip). Enter would
# accept and restart the session without permission flags — reject.
_sks_herdr send-keys -t "$sess" Escape
elif printf '%s\n' "$pane" | grep -q 'Yes, proceed'; then
_sks_herdr send-keys -t "$sess" Down
sleep 0.3
@@ -1,7 +1,7 @@
---
name: multi-agent-mux-create
description: "Create a new agent session (claude, antigravity/agy) in a dedicated herdr session for context-preserving long-running work. Always creates a herdr session — never backgrounds with nohup/disown. Writes the new session to .mam/agent-sessions.yaml. Use when you want to start a fresh agent (no prior UUID) for a new project workspace."
version: 3.0.0
version: 3.0.1
author: godopu
license: MIT
platforms: [linux, macos]
@@ -1,7 +1,7 @@
---
name: multi-agent-mux-delegate-job
description: "Delegate a unit of work to any autonomous agent (claude-code, hermes, agy, cline, grok-build, codex, or a human) and observe it asynchronously over an MQTT event channel. Supported roles include orchestrator, worker, and reviewer."
version: 3.0.0
version: 3.0.1
author: godopu
license: MIT
platforms: [linux, macos, windows]
+1 -1
View File
@@ -1,7 +1,7 @@
---
name: multi-agent-mux-loop
description: "Run an autonomous planning-execution-review loop using multiple agents (Planner, Creator, Reviewers) in the workspace. Automatically orchestrates plan discussion, code changes, and peer reviews until a unanimous PASS is achieved or the maximum iteration limit is reached."
version: 3.0.0
version: 3.0.1
author: godopu
license: MIT
platforms: [linux, macos]
@@ -1,7 +1,7 @@
---
name: multi-agent-mux-monitor
description: "Run a long-lived reconciler that watches .mam/agent-sessions.yaml against the actual herdr/agent runtime state and reconciles them. Use when you want live visibility into which agent sessions are running, which are dead, which have stale YAML entries, and which have new session ids that haven't been recorded yet. Runs as a persistent loop (`reconcile.sh --subscribe`) that keeps going until it times out, idles out, or is interrupted."
version: 3.0.0
version: 3.0.1
author: godopu
license: MIT
platforms: [linux, macos]
@@ -1,7 +1,7 @@
---
name: multi-agent-mux-orc-onboard
description: Register current or specified orchestrator session UUID into agent-sessions.yaml orchestrator_uuids list to prevent sub-agent discovery capture.
version: 3.0.0
version: 3.0.1
author: godopu
license: MIT
platforms: [linux, macos]
@@ -1,7 +1,7 @@
---
name: multi-agent-mux-resume
description: "Resume an existing agent (claude, antigravity/agy) conversation by UUID into a herdr session. Reads .mam/agent-sessions.yaml for the saved session/conversation id, spawns (or reuses) a herdr session of the matching name, and runs `claude -r <id>` or `agy --conversation <id>` inside. Use when you want to reattach to a previous session's context, or revive a session whose herdr died but the agent's conversation is still on disk."
version: 3.0.0
version: 3.0.1
author: godopu
license: MIT
platforms: [linux, macos]
@@ -1,7 +1,7 @@
---
name: multi-agent-mux-status
description: "Read-only instant snapshot of all agent herdr sessions — name, YAML status, herdr alive, pane cmd/cwd, resume UUID on disk, and any drift. No mutation. Reuses reconcile.sh --dry-run for the diff logic. Use when you want to know 'what's running RIGHT NOW' without spinning up the monitor loop."
version: 3.0.0
version: 3.0.1
author: godopu
license: MIT
platforms: [linux, macos]
+1 -1
View File
@@ -1,7 +1,7 @@
---
name: multi-agent-mux-stop
description: "Stop an agent herdr session (claude, antigravity/agy) and update .mam/agent-sessions.yaml. Default stops gracefully and marks status=stopped with conversation preserved for resume. Does NOT delete on-disk conversation artifacts (jsonl/db) — those are preserved unless --purge-conversation is passed. Use when ending a work session, switching to a different one, or cleaning up before a fresh start."
version: 3.0.0
version: 3.0.1
author: godopu
license: MIT
platforms: [linux, macos]
+6
View File
@@ -48,6 +48,12 @@
#default: $HOME/.config/herdr/herdr.sock
# HERDR_SOCKET_PATH=$HOME/.config/herdr/herdr.sock
# Explicit Herdr workspace scope identifier (`herdr pane list --workspace <id>`).
# Hard filters pane/agent resolution to this workspace. When unset, falls back
# to $WORKSPACE_ROOT/.mam/herdr_workspace_id or server-global resolution.
#default: <unset> (uses persisted .mam/herdr_workspace_id or global)
# HERDR_WORKSPACE_ID=w1
# ===========================================================================
# delegate-job / MQTT broker
# ===========================================================================
+52 -15
View File
@@ -6,36 +6,73 @@
## 📌 현재 버전 개요 (Current Release)
- **프레임워크 버전**: `v3.0.0`
- **최신 릴리스 일시**: 2026-08-26 (KST)
- **프레임워크 버전**: `v3.0.1`
- **최신 릴리스 일시**: 2026-08-27 (KST)
- **기준 브랜치**: `main`
- **핵심 아키텍처**:
- **5th Official Agent Ecosystem (Grok Build)**: Claude, AGY, Hermes, Cline에 이은 5번째 공식 AI 에이전트(`grok`) 어댑터, 세션 생성/재개/종료 및 TUI 수명주기 전면 지원
- **Mux Loop Role-Based CLI Redesign (Breaking Change)**: `--target-agent` 공식 폐지 및 `--creator` / `--planner` 명시적 역할 분리 구조 정립
- **Deterministic 2xK Grid Layout Engine 2.0**: $N=1\to 2$ `right` 우선 분할, GUI/헤드리스 공통 단일 3단계 결정표, 전고(Full-height) 열 안전 가드로 2×2 대칭 격자 보장
- **Infrastructure & Preflight Hardening**: 사설 NATS 2.14 Alpine 동기화 및 `--workspace` 인자 사전 검증 강화
- **Herdr Shim Routing & Multi-Workspace Isolation Engine**: `HERDR_WORKSPACE_ID` 환경 변수 스코핑 및 `$WORKSPACE_ROOT/.mam/herdr_workspace_id` 영속화 메커니즘을 통해 다중 워크스페이스 동시 실행 시 페인 교차 오염 원천 차단
- **Atomic Safe Paste Insertion (`pane send-text`)**: 미지원 서브커맨드(`agent send`) 제거 및 `pane send-text` 단일 삽입 계약 도입, `send_keys_safe` 실패 전파(`rc 3`) 및 중복 제출(Double Submit) 방지
- **Strict Exact-Match Single Pane Resolver**: 부분 문자열 매칭(`in tn`) 완전 제거, 단일 중앙 `_resolve_herdr_pane_id` 헬퍼 기반 5대 서브커맨드(`has-session`, `kill-session`, `capture-pane`, `send-keys`, `paste-buffer`) 무결성 정립
- **TUI Readiness & Dialog Token Precision**: `_MAM_DIALOG_TOKENS` 일반 팁(`Yes, try it`) 오탐 제거 및 풀스크린 모달 Escape 거절 브랜치 분리
- **Comprehensive Test Suite Milestone**: 412개 전체 테스트 100% PASS (412 passed / 0 failed).
---
## 🧭 스킬 패키지 버전 매트릭스 (Skills Version Matrix)
모든 8개 스킬은 YAML frontmatter 메타데이터(`author`, `version`, `platforms`, `environments`) 표준화를 통해 `v3.0.0`으로 동기화되어 배포됩니다.
모든 8개 스킬은 YAML frontmatter 메타데이터(`author`, `version`, `platforms`, `environments`) 표준화를 통해 `v3.0.1`으로 동기화되어 배포됩니다.
| 스킬명 | 버전 | 역할 및 주요 책임 | 상태 |
| :--- | :---: | :--- | :---: |
| **`multi-agent-mux-create`** | `3.0.0` | 에이전트 세션 신규 생성 및 Herdr 컨테이너 격리 스폰 | ✅ 배포 |
| **`multi-agent-mux-stop`** | `3.0.0` | 대화 UUID 원자적 캡처 및 세션 안전 종료 (Graceful Stop) | ✅ 배포 |
| **`multi-agent-mux-resume`** | `3.0.0` | 온디스크 대화 컨텍스트 기반 Tier-1 초고속 세션 복원 | ✅ 배포 |
| **`multi-agent-mux-status`** | `3.0.0` | 실시간 Herdr 세션 및 레지스트리 드리프트 스냅샷 조회 | ✅ 배포 |
| **`multi-agent-mux-monitor`** | `3.0.0` | YAML ↔ 런타임 상태 간 자율 조정자 (Reconciler Loop) | ✅ 배포 |
| **`multi-agent-mux-delegate-job`** | `3.0.0` | MQTT 이벤트 채널 기반 비동기 단위 작업 위임 | ✅ 배포 |
| **`multi-agent-mux-loop`** | `3.0.0` | Planner-Creator-Reviewer 3자 자율 계획·실행·피어리뷰 루프 | ✅ 배포 |
| **`multi-agent-mux-orc-onboard`** | `3.0.0` | 오케스트레이터 UUID 격리 등록 및 서브 세션 오염 방지 | ✅ 배포 |
| **`multi-agent-mux-create`** | `3.0.1` | 에이전트 세션 신규 생성 및 Herdr 컨테이너 격리 스폰 | ✅ 배포 |
| **`multi-agent-mux-stop`** | `3.0.1` | 대화 UUID 원자적 캡처 및 세션 안전 종료 (Graceful Stop) | ✅ 배포 |
| **`multi-agent-mux-resume`** | `3.0.1` | 온디스크 대화 컨텍스트 기반 Tier-1 초고속 세션 복원 | ✅ 배포 |
| **`multi-agent-mux-status`** | `3.0.1` | 실시간 Herdr 세션 및 레지스트리 드리프트 스냅샷 조회 | ✅ 배포 |
| **`multi-agent-mux-monitor`** | `3.0.1` | YAML ↔ 런타임 상태 간 자율 조정자 (Reconciler Loop) | ✅ 배포 |
| **`multi-agent-mux-delegate-job`** | `3.0.1` | MQTT 이벤트 채널 기반 비동기 단위 작업 위임 | ✅ 배포 |
| **`multi-agent-mux-loop`** | `3.0.1` | Planner-Creator-Reviewer 3자 자율 계획·실행·피어리뷰 루프 | ✅ 배포 |
| **`multi-agent-mux-orc-onboard`** | `3.0.1` | 오케스트레이터 UUID 격리 등록 및 서브 세션 오염 방지 | ✅ 배포 |
---
## 📋 버전별 상세 변경 내역 (Changelog)
### 🚀 `v3.0.1` — Herdr Shim Routing Contract Refactor, Multi-Workspace Isolation & 412-Test Milestone (2026-08-27)
> **주요 마일스톤**: Herdr 심 라우팅 5대 결함(ISSUE-1~5) 및 F-1~F-4 보완 완결, `HERDR_WORKSPACE_ID` 환경 변수 스코핑 및 파일 기반 격리 영속화 엔진 탑재, `pane send-text` 기반 단일 안전 삽입 계약 정립, 부분 문자열 매칭(`in tn`) 완전 제거, 412개 전체 테스트 100% PASS 달성.
#### 1. Herdr 심 라우팅 및 다중 워크스페이스 격리 강화 (`.agents/skills/lib.sh`)
* **`HERDR_WORKSPACE_ID` 명시적 스코프 & 영속화 (`ISSUE-3`, `F-2b`)**:
- `_herdr_ws_id_file()`, `_herdr_persist_ws_id()`, `_herdr_ws_scope()` 헬퍼 도입.
- `new-session` 시 생성된 워크스페이스 ID를 `$WORKSPACE_ROOT/.mam/herdr_workspace_id`에 영속화.
- `_herdr_agent_get_scoped`는 호출자의 환경변수(`HERDR_WORKSPACE_ID`)만을 우선 평가하여 단축 경로에서의 교차 워크스페이스 라우팅 오염 차단.
* **엄격 일치(Exact-Match) 단일 페인 리졸버 정립 (`ISSUE-2`, `ISSUE-5`, `F-3`)**:
- 기존의 에이전트 CLI 명칭 부분 문자열 매칭(`in tn`, `agent in tn`) 완전 제거.
- 단일 중앙 헬퍼 `_resolve_herdr_pane_id``has-session`, `kill-session`, `capture-pane`, `send-keys`, `paste-buffer`의 페인 해석 통합.
- 영숫자 워크스페이스 식별자 패턴(`^w[A-Za-z0-9]+:p[A-Za-z0-9]+$`) 지원 (`H-20`).
#### 2. 원자적 텍스트 삽입 및 안전 전송 계약 교정 (`ISSUE-1`, `F-4`)
* **`paste-buffer``pane send-text` 전용화**:
- Herdr CLI에 미존재하던 `agent send` 제거 및 `pane send-text`로 교체.
- 삽입과 제출(Enter) 책임을 분리하여 의도치 않은 자동 제출 및 이중 제출(Double Submit) 방지.
- 페인 미해석 또는 삽입 실패 시 `send_keys_safe`로 에러 코드(`rc 3`) 명시적 전파.
* **`capture-pane` 폴백 체인 복원 (`F-4`)**:
- `pane read` 실패 시 `agent read`로의 폴백 체인을 안정적으로 복원하여 TUI 캡처 신뢰성 보장.
#### 3. TUI 준비 상태 감지 및 다이얼로그 토큰 정밀화 (`N-1`, `F-1`)
* **`_MAM_DIALOG_TOKENS` 일반 팁 토큰 분리**:
- 일반 대화형/TUI 팁에 등장하는 `Yes, try it`을 블로킹 다이얼로그 토큰 목록에서 제외하여 세션 시작 시의 오탐 방지.
- 풀스크린 업셀 모달에 대해서는 전용 Escape 거절 브랜치로 격리 처리.
#### 4. 테스트 스위트 및 Mock Herdr 계약 정기 동기화 (`tests/`)
* **Mock Herdr (`tests/conftest.py`)**: 실제 Herdr 0.8.2 CLI 계약과 완벽 동기화 (`pane send-text`, `pane read`, `pane rename` 반영, 미지원 `agent send` 실패 처리).
* **신규 계약 & 회귀 테스트 19건 추가**:
- `test_herdr_shim_contract.py`: H-15 ~ H-23 (단일 리졸버 불변식, 워크스페이스 격리, 단축경로 스코핑).
- `test_b19_headless_reconcile_fixes.py`: D-4 ~ D-7 (set -e 안전성, send_keys_safe 실패 전파, 다이얼로그 토큰 제외 회귀 방지).
* **전체 테스트 결과**: 412 passed in 681.20s (100% PASS).
---
### 🚀 `v3.0.0` — 5th Agent (Grok) Ecosystem Expansion, Mux Loop CLI Redesign & Deterministic 2xK Layout Engine 2.0 (2026-08-26)
> **주요 마일스톤**: 5번째 공식 에이전트 `grok`(Grok Build) 전면 통합, `/multi-agent-mux-loop`의 `--target-agent` 폐지 및 `--creator`/`--planner` 역할 분리(Breaking Change), 2×2 대칭 그리드를 보장하는 결정론적 레이아웃 엔진 2.0 탑재, 393개 전체 테스트 100% PASS 달성.
+109 -39
View File
@@ -44,6 +44,7 @@ def mam_sandbox(tmp_path, monkeypatch):
monkeypatch.setenv("WORKSPACE_ROOT", str(tmp_path))
monkeypatch.delenv("HERDR_SESSION_NAME", raising=False)
monkeypatch.delenv("HERDR_SERVER_NAME", raising=False)
monkeypatch.delenv("HERDR_WORKSPACE_ID", raising=False)
import sys
monkeypatch.setenv("AGENT_PYTHON_BIN", sys.executable)
@@ -150,7 +151,13 @@ def save_state():
if "panes" in state:
disk_panes = disk_state.setdefault("panes", [])
for p in state["panes"]:
if not any(dp.get("pane_id") == p.get("pane_id") for dp in disk_panes):
matched = False
for i, dp in enumerate(disk_panes):
if dp.get("pane_id") == p.get("pane_id"):
disk_panes[i] = p
matched = True
break
if not matched:
disk_panes.append(p)
disk_calls = disk_state.setdefault("calls", [])
if sys.argv[1:] and (not disk_calls or disk_calls[-1] != sys.argv[1:]):
@@ -260,23 +267,42 @@ elif cmd1 == "pane":
else:
i += 1
panes_list = []
# Build panes from agents or state["panes"]
seen = set()
# Merge agent-derived panes with state["panes"] (dedupe by pane_id).
# Label-only panes live in state["panes"] and must remain visible
# even when other agents are registered.
for name, data in state.get("agents", {}).items():
ws_id = data.get("workspace_id", "w1")
if target_ws and ws_id != target_ws:
continue
panes_list.append({
"pane_id": data.get("pane_id", f"{ws_id}:p1"),
pid = data.get("pane_id", f"{ws_id}:p1")
entry = {
"pane_id": pid,
"workspace_id": ws_id,
"cwd": data.get("cwd", "."),
"tab_id": f"{ws_id}:t1",
"agent": data.get("agent", "claude")
})
if not panes_list:
for p in state.get("panes", []):
if target_ws and p.get("workspace_id") != target_ws:
continue
panes_list.append(p)
"tab_id": data.get("tab_id", f"{ws_id}:t1"),
"agent": data.get("agent", "claude"),
"name": name,
}
if data.get("label"):
entry["label"] = data["label"]
panes_list.append(entry)
seen.add(pid)
for p in state.get("panes", []):
if target_ws and p.get("workspace_id") != target_ws:
continue
pid = p.get("pane_id")
if pid in seen:
for existing in panes_list:
if existing.get("pane_id") == pid:
for k in ("label", "name"):
if p.get(k) and not existing.get(k):
existing[k] = p[k]
break
continue
panes_list.append(p)
if pid:
seen.add(pid)
print(json.dumps({"result": {"panes": panes_list}}))
sys.exit(0)
elif cmd2 == "split":
@@ -335,8 +361,70 @@ elif cmd1 == "pane":
state["agents"] = agents
save_state()
sys.exit(0)
else:
for p in state.get("panes", []):
if p.get("pane_id") == name:
p["sent_keys"] = p.get("sent_keys", []) + [key]
if key in ("Enter", "C-m"):
p["buffer"] = p.get("buffer", "") + "\\n\\nesc to interrupt"
save_state()
sys.exit(0)
sys.exit(1)
elif cmd2 == "send-text":
if len(args) < 4:
sys.exit(1)
pane_id = args[2]
text = args[3]
found = False
for a_name, data in state.get("agents", {}).items():
if data.get("pane_id") == pane_id or a_name == pane_id:
data["sent_text"] = data.get("sent_text", "") + text
data["buffer"] = data.get("buffer", "") + "\\n" + text
found = True
break
if not found:
for p in state.get("panes", []):
if p.get("pane_id") == pane_id:
p["sent_text"] = p.get("sent_text", "") + text
p["buffer"] = p.get("buffer", "") + "\\n" + text
found = True
break
if found:
save_state()
sys.exit(0)
sys.exit(1)
elif cmd2 == "read":
if len(args) < 3:
sys.exit(1)
pane_id = args[2]
for a_name, data in state.get("agents", {}).items():
if data.get("pane_id") == pane_id or a_name == pane_id:
print(data.get("buffer", "Ready"))
sys.exit(0)
for p in state.get("panes", []):
if p.get("pane_id") == pane_id:
print(p.get("buffer", ""))
sys.exit(0)
sys.stderr.write("Pane " + pane_id + " not found\\n")
sys.exit(1)
elif cmd2 == "rename":
if len(args) < 4:
sys.exit(1)
pane_id = args[2]
label = args[3]
panes = state.setdefault("panes", [])
renamed = False
for p in panes:
if p.get("pane_id") == pane_id:
p["label"] = label
renamed = True
break
if not renamed:
panes.append({"pane_id": pane_id, "label": label})
for a_name, data in state.get("agents", {}).items():
if data.get("pane_id") == pane_id:
data["label"] = label
save_state()
sys.exit(0)
elif cmd2 == "process-info":
pane_id = ""
if "--pane" in args:
@@ -633,33 +721,15 @@ elif cmd1 == "agent":
agents[matched_k]["buffer"] = agents[matched_k].get("buffer", "") + "\\n" + text + "\\n\\nesc to interrupt"
state["agents"] = agents
save_state()
print(json.dumps({"id": "cli:agent:prompt", "result": {"type": "ok"}}))
sys.exit(0)
elif cmd2 == "send":
if len(args) < 4:
sys.exit(1)
name = args[2]
text = args[3]
agents = state.get("agents", {})
matched_k = None
for k in agents:
if _match_agent(k, name):
matched_k = k
break
if matched_k:
agents[matched_k]["sent_text"] = agents[matched_k].get("sent_text", "") + text
if text in ("C-m", "Enter"):
agents[matched_k]["buffer"] = agents[matched_k].get("buffer", "") + "\\\\n\\\\nesc to interrupt"
else:
agents[matched_k]["buffer"] = agents[matched_k].get("buffer", "") + "\\\\n" + text
if "/exit" in text or "exit" in text or "Exit" in text:
agents[matched_k]["status"] = "stopped"
state["agents"] = agents
save_state()
print(json.dumps({"id": "cli:agent:prompt", "result": {"type": "ok"}}))
sys.exit(0)
else:
sys.stderr.write("Agent " + name + " not found\\\\n")
sys.exit(1)
sys.stderr.write("Agent " + name + " not found\\n")
sys.exit(1)
else:
# Real herdr has no `agent send`. Unknown subcommands must fail
# (exit 1) rather than silently succeeding.
sys.stderr.write("error: unrecognized subcommand '" + cmd2 + "'\\n")
sys.exit(1)
elif cmd1 == "session":
if len(args) < 2:
+207
View File
@@ -3,6 +3,7 @@ import sys
import json
import subprocess
import time
from pathlib import Path
import pytest
from lib_py.layout import compute_2xk_layout
@@ -101,6 +102,212 @@ def test_bug4_send_keys_safe_gating_order():
assert dialog_idx < prompt_idx, "_pane_dialog_open must execute before agent prompt fast-path"
_LIB_SH = str(Path(__file__).resolve().parent.parent / ".agents" / "skills" / "lib.sh")
_FULLSCREEN_TIP = """Claude Code
Try the new fullscreen renderer — flicker-free output, mouse support, auto-copy on select · /tui fullscreen
"""
_FULLSCREEN_MODAL = """Try the new fullscreen renderer?
Flicker-free output
Selected text auto-copies to your clipboard
Yes, try it
"""
def _run_lib_helpers(script_body, env_extra=None):
env = dict(os.environ)
if env_extra:
env.update(env_extra)
wrapper = f"""
set -euo pipefail
source "{_LIB_SH}"
_init_herdr_isolation() {{ :; }}
{script_body}
"""
return subprocess.run(["bash", "-c", wrapper], capture_output=True, text=True, env=env)
def test_agent_start_success_tokens_exclude_startup_timeout():
"""D-1: dead-process timeout must not be promoted to success; agent_not_ready may."""
content = open(_LIB_SH, encoding="utf-8").read()
success_line = next(l for l in content.splitlines()
if 'grep -qE "agent_started' in l)
assert "agent_not_ready" in success_line
assert "timed out waiting for agent startup" not in success_line
err_line = next(i for i, l in enumerate(content.splitlines())
if 'grep -qiE "^usage:' in l)
ok_line = next(i for i, l in enumerate(content.splitlines())
if 'grep -qE "agent_started' in l)
assert err_line < ok_line
def test_fullscreen_tip_is_not_a_blocking_dialog():
"""D-2: idle /tui fullscreen tip must not trip _pane_dialog_open or send keys."""
script = f"""
_pane_capture() {{ printf '%s' '{_FULLSCREEN_TIP}'; }}
KEYS=/tmp/mam-fs-tip-keys.$$
: > "$KEYS"
_sks_herdr() {{
if [ "${{1:-}}" = "send-keys" ]; then echo "$*" >> "$KEYS"; fi
return 0
}}
if _pane_dialog_open dummy; then echo "DIALOG_OPEN"; else echo "DIALOG_CLOSED"; fi
handle_startup_dialogs dummy 2
echo "KEYS_CONTENT=$(tr '\\n' '|' < "$KEYS")"
rm -f "$KEYS"
"""
res = _run_lib_helpers(script)
assert res.returncode == 0, res.stderr + res.stdout
assert "DIALOG_CLOSED" in res.stdout
assert "Escape" not in res.stdout
assert "Enter" not in res.stdout.split("KEYS_CONTENT=")[-1]
def _lib_helper_src():
content = open(_LIB_SH, encoding="utf-8").read()
start = content.find("_herdr_ws_id_file() {")
end = content.find('cmd="${1:-}"', start)
assert start != -1 and end != -1
return content[start:end]
def test_resolve_pane_id_fails_cleanly_under_set_e():
"""D-4: _resolve_herdr_pane_id must return 1 with empty stdout under set -e."""
helper = _lib_helper_src()
script = """
set -euo pipefail
unset HERDR_WORKSPACE_ID
source "LIB_SH_PLACEHOLDER"
_init_herdr_isolation() { :; }
_real_herdr() { return 1; }
HELPER_PLACEHOLDER
_resolve_herdr_pane_id nonexistent >/dev/null 2>&1 || true
echo SURVIVED
rc=0
out=$(_resolve_herdr_pane_id nonexistent 2>/dev/null) || rc=$?
printf 'OUT=%s\\n' "$out"
echo "RC=$rc"
""".replace("LIB_SH_PLACEHOLDER", _LIB_SH).replace("HELPER_PLACEHOLDER", helper)
res = subprocess.run(["bash", "-c", script], capture_output=True, text=True)
assert res.returncode == 0, res.stderr + res.stdout
assert "SURVIVED" in res.stdout
assert "RC=1" in res.stdout
out_line = [l for l in res.stdout.splitlines() if l.startswith("OUT=")][0]
assert out_line == "OUT="
def test_send_keys_safe_returns_3_when_paste_buffer_fails():
"""D-5 (ISSUE-1): paste-buffer failure returns 3 and still deletes the buffer."""
script = """
_pane_quiescent() { return 0; }
_pane_dialog_open() { return 1; }
LOG=/tmp/mam-d5-sks.$$
: > "$LOG"
_sks_herdr() {
echo "$*" >> "$LOG"
if [ "${1:-}" = "agent" ] && [ "${2:-}" = "prompt" ]; then return 1; fi
if [ "${1:-}" = "paste-buffer" ]; then return 1; fi
return 0
}
rc=0
send_keys_safe "d5-sess" "hello" "job-d5" || rc=$?
echo "RC=$rc"
echo "LOG_CONTENT=$(tr '\\n' '|' < "$LOG")"
rm -f "$LOG"
"""
res = _run_lib_helpers(script)
assert res.returncode == 0, res.stderr + res.stdout
assert "RC=3" in res.stdout
log = res.stdout.split("LOG_CONTENT=")[-1]
assert "C-m" not in log
assert "delete-buffer" in log
def test_no_substring_matching_remains_in_lib_sh():
"""D-6 (ISSUE-2): no `in tn` substring matching remains in lib.sh."""
import re
content = open(_LIB_SH, encoding="utf-8").read()
assert re.search(r"\bin tn\b", content) is None
assert re.search(r'agent"\) in tn', content) is None
start = content.find("_resolve_herdr_pane_id()")
assert start != -1
body = content[start:content.find('cmd="${1:-}"', start)]
assert r"^w[A-Za-z0-9]+:p[A-Za-z0-9]+$" in body
def test_paste_buffer_branch_never_submits():
"""D-7 (ISSUE-1): paste-buffer arm must not submit or invoke prompt/run."""
content = open(_LIB_SH, encoding="utf-8").read()
start = content.find(" paste-buffer)")
assert start != -1
end = content.find("\n delete-buffer)", start)
assert end != -1
body = content[start:end]
for token in ("Enter", "C-m", "pane run", "agent prompt"):
assert token not in body, token
def test_fullscreen_modal_is_rejected_not_accepted():
"""D-3: fullscreen modal is dismissed with Escape, never Enter."""
script = f"""
_pane_capture() {{ printf '%s' '{_FULLSCREEN_MODAL}'; }}
KEYS=/tmp/mam-fs-modal-keys.$$
: > "$KEYS"
_sks_herdr() {{
if [ "${{1:-}}" = "send-keys" ]; then echo "$*" >> "$KEYS"; fi
return 0
}}
handle_startup_dialogs dummy 1
echo "KEYS_CONTENT=$(tr '\\n' '|' < "$KEYS")"
rm -f "$KEYS"
"""
res = _run_lib_helpers(script)
assert res.returncode == 0, res.stderr + res.stdout
keys = res.stdout.split("KEYS_CONTENT=")[-1]
assert "Escape" in keys
assert "Enter" not in keys
def test_prose_yes_try_it_is_not_a_dialog():
"""N-1 / F-1: conversational 'Yes, try it' must not trip _pane_dialog_open."""
script = r"""
_pane_capture() { printf '%s' 'Sure — if the build fails again, Yes, try it with the --clean flag.'; }
if _pane_dialog_open dummy; then echo "DIALOG_OPEN"; else echo "DIALOG_CLOSED"; fi
"""
res = _run_lib_helpers(script)
assert res.returncode == 0, res.stderr + res.stdout
assert "DIALOG_CLOSED" in res.stdout
def test_mam_dialog_tokens_exclude_yes_try_it():
"""N-1 / F-1: token list must not contain Yes, try it; Escape branch stays."""
content = open(_LIB_SH, encoding="utf-8").read()
token_line = next(l for l in content.splitlines() if l.startswith("_MAM_DIALOG_TOKENS="))
assert "Yes, try it" not in token_line
assert "grep -q 'Yes, try it'" in content
def test_wait_for_tui_ready_succeeds_on_fullscreen_tip():
"""D-2c: tip + ready banner must not deadlock wait_for_tui_ready."""
script = f"""
_pane_capture() {{ printf '%s' '{_FULLSCREEN_TIP}'; }}
_sks_herdr() {{
if [ "${{1:-}}" = "capture-pane" ]; then printf '%s' '{_FULLSCREEN_TIP}'; return 0; fi
if [ "${{1:-}}" = "send-keys" ]; then echo "KEY:$*" >&2; return 0; fi
return 0
}}
sleep() {{ :; }}
export MAM_READY_TOKENS='Claude Code|Welcome'
wait_for_tui_ready dummy-sess claude
"""
res = _run_lib_helpers(script)
assert res.returncode == 0, res.stderr + res.stdout
assert "TUI detected ready" in res.stdout
assert "KEY:" not in res.stderr
def test_bug4_no_duplicate_input_on_rpc_success(tmp_path):
"""Verify Bug 4: when herdr agent prompt succeeds, send_keys_safe returns 0 without calling paste-buffer."""
test_script = f"""#!/usr/bin/env bash
+356
View File
@@ -1,6 +1,7 @@
import os
import sys
import json
import re
import subprocess
import pytest
import shutil
@@ -125,3 +126,358 @@ for p in procs:
# Verify all 10 agents created without state overwrite loss
assert len(final_state.get("agents", {})) == 10
def _load_mock_state(mock_herdr):
with open(mock_herdr, "r") as f:
return json.load(f)
def _write_mock_state(mock_herdr, state):
with open(mock_herdr, "w") as f:
json.dump(state, f, indent=2)
def _run_lib(tmp_path, body):
lib_path = tmp_path / ".agents" / "skills" / "lib.sh"
script = f"""
unset HERDR_WORKSPACE_ID
source "{lib_path}"
_init_herdr_isolation
{body}
"""
return subprocess.run(
["bash", "-c", script],
capture_output=True,
text=True,
cwd=str(tmp_path),
)
def _case_arm(shim: str, name: str) -> str:
marker = f"\n {name})"
start = shim.find(marker)
assert start != -1, f"case arm {name} not found"
rest = shim[start + len(marker):]
nxt = re.search(r"\n [A-Za-z][A-Za-z0-9-]*\)", rest)
end = start + len(marker) + nxt.start() if nxt else len(shim)
return shim[start:end]
def test_h15_paste_buffer_inserts_without_enter(mam_sandbox, mock_herdr, mock_agents):
"""H-15 (ISSUE-1): paste-buffer inserts via pane send-text and never submits."""
tmp_path = mam_sandbox
res = _run_lib(
tmp_path,
f'herdr new-session -d -s "test-creator-claude" -c "{tmp_path}" "claude --dangerously-skip-permissions"',
)
assert res.returncode == 0, f"Stderr: {res.stderr}\nStdout: {res.stdout}"
state = _load_mock_state(mock_herdr)
agents = state.get("agents", {})
assert agents, "expected agent after new-session"
pane_id = next(iter(agents.values()))["pane_id"]
n_calls = len(state.get("calls", []))
res = _run_lib(
tmp_path,
"""
herdr set-buffer -b t1 "hello world"
herdr paste-buffer -b t1 -t test-creator-claude
""",
)
assert res.returncode == 0, f"Stderr: {res.stderr}\nStdout: {res.stdout}"
new_calls = _load_mock_state(mock_herdr).get("calls", [])[n_calls:]
send_text = [c for c in new_calls if len(c) >= 2 and c[0] == "pane" and c[1] == "send-text"]
assert send_text == [["pane", "send-text", pane_id, "hello world"]], new_calls
assert not any(len(c) >= 2 and c[0] == "agent" and c[1] == "send" for c in new_calls)
submit = [
c for c in new_calls
if len(c) >= 2 and (
(c[0] == "pane" and c[1] == "send-keys")
or (c[0] == "agent" and c[1] == "prompt")
or (c[0] == "pane" and c[1] == "run")
)
]
assert submit == [], new_calls
def test_h16_send_keys_safe_submits_exactly_once(mam_sandbox, mock_herdr, mock_agents):
"""H-16 (ISSUE-1): fallback paste path submits Enter/C-m exactly once."""
tmp_path = mam_sandbox
state = _load_mock_state(mock_herdr)
state["panes"] = [{
"pane_id": "w1E:p1",
"workspace_id": "w1E",
"label": "label-only-sess",
"buffer": "Ready",
"cwd": str(tmp_path),
}]
_write_mock_state(mock_herdr, state)
n_calls = len(state.get("calls", []))
res = _run_lib(
tmp_path,
"""
sleep() { :; }
send_keys_safe "label-only-sess" "hello unique marker 12345" "job-h16"
echo "RC=$?"
""",
)
assert res.returncode == 0, f"Stderr: {res.stderr}\nStdout: {res.stdout}"
assert "RC=0" in res.stdout, res.stdout + res.stderr
new_calls = _load_mock_state(mock_herdr).get("calls", [])[n_calls:]
enters = [
c for c in new_calls
if any(tok in ("Enter", "C-m") for tok in c)
and not (len(c) >= 2 and c[0] == "pane" and c[1] == "send-text")
]
assert len(enters) == 1, new_calls
assert any(len(c) >= 2 and c[0] == "pane" and c[1] == "send-text" for c in new_calls)
def test_h17_no_substring_cross_pane_routing(mam_sandbox, mock_herdr, mock_agents):
"""H-17 (ISSUE-2): session names must not substring-match agent CLI kinds."""
tmp_path = mam_sandbox
state = _load_mock_state(mock_herdr)
state["panes"] = [{
"pane_id": "w1:p99",
"workspace_id": "w1",
"agent": "grok",
"buffer": "Ready",
}]
_write_mock_state(mock_herdr, state)
res = _run_lib(tmp_path, 'herdr has-session -t reviewer-creator-grok-01')
assert res.returncode == 1, f"substring match leaked into has-session: {res.stderr}"
res = _run_lib(
tmp_path,
f"""
herdr new-session -d -s "reviewer-creator-grok-01" -c "{tmp_path}" "grok"
herdr new-session -d -s "worker-grok-02" -c "{tmp_path}" "grok"
""",
)
assert res.returncode == 0, f"Stderr: {res.stderr}\nStdout: {res.stdout}"
state = _load_mock_state(mock_herdr)
agents = state.get("agents", {})
target_pane = None
other_pane = None
for name, data in agents.items():
if "reviewer-creator-grok" in name:
target_pane = data.get("pane_id")
if "worker-grok" in name:
other_pane = data.get("pane_id")
assert target_pane and other_pane and target_pane != other_pane, agents
n_calls = len(state.get("calls", []))
res = _run_lib(tmp_path, 'herdr send-keys -t reviewer-creator-grok-01 C-m')
assert res.returncode == 0, res.stderr
new_calls = _load_mock_state(mock_herdr).get("calls", [])[n_calls:]
sendkeys = [c for c in new_calls if len(c) >= 4 and c[0] == "pane" and c[1] == "send-keys"]
assert any(c[2] == target_pane for c in sendkeys), new_calls
assert not any(c[2] == other_pane for c in sendkeys), new_calls
def test_h18_workspace_scoped_pane_resolution(mam_sandbox, mock_herdr, mock_agents):
"""H-18 (ISSUE-3): HERDR_WORKSPACE_ID scopes pane resolution; unset keeps global lookup."""
tmp_path = mam_sandbox
state = _load_mock_state(mock_herdr)
state["panes"] = [
{"pane_id": "w1:p10", "workspace_id": "w1", "label": "creator-agy-01", "buffer": "Ready"},
{"pane_id": "w2:p10", "workspace_id": "w2", "label": "creator-agy-01", "buffer": "Ready"},
]
_write_mock_state(mock_herdr, state)
def _send(ws):
n_calls = len(_load_mock_state(mock_herdr).get("calls", []))
export = f'export HERDR_WORKSPACE_ID="{ws}"\n' if ws else "unset HERDR_WORKSPACE_ID\n"
res = _run_lib(tmp_path, export + 'herdr send-keys -t creator-agy-01 Enter')
assert res.returncode == 0, res.stderr
calls = _load_mock_state(mock_herdr).get("calls", [])[n_calls:]
return [c for c in calls if len(c) >= 4 and c[0] == "pane" and c[1] == "send-keys"]
keyed_w2 = _send("w2")
assert keyed_w2 and keyed_w2[0][2] == "w2:p10", keyed_w2
keyed_w1 = _send("w1")
assert keyed_w1 and keyed_w1[0][2] == "w1:p10", keyed_w1
keyed_global = _send("")
assert keyed_global, "unset HERDR_WORKSPACE_ID must still resolve a pane"
assert keyed_global[0][2] in ("w1:p10", "w2:p10")
def test_h19_single_resolver_helper_used_by_all_branches(mam_sandbox, mock_herdr):
"""H-19 (ISSUE-5): one helper definition; five shim branches call it."""
tmp_path = mam_sandbox
res = _run_lib(tmp_path, ":")
assert res.returncode == 0, res.stderr
shim_path = tmp_path / ".mam" / "shim" / "herdr"
shim = shim_path.read_text()
assert shim.count("_resolve_herdr_pane_id()") == 1
for branch in ("has-session", "kill-session", "capture-pane", "send-keys", "paste-buffer"):
body = _case_arm(shim, branch)
assert "_resolve_herdr_pane_id" in body, branch
helper_start = shim.find("_herdr_ws_id_file() {")
helper_end = shim.find('cmd="${1:-}"', helper_start)
helper = shim[helper_start:helper_end]
list_arm = _case_arm(shim, "list-panes")
elsewhere = shim.replace(helper, "", 1).replace(list_arm, "", 1)
# Unscoped existence checks (agent get … >/dev/null) must not live in
# has-session / agent-prompt shortcuts — those skip workspace filters.
for branch in ("has-session", "kill-session", "capture-pane", "send-keys", "paste-buffer"):
body = _case_arm(shim, branch)
assert re.search(r'agent get "\$[^"]+" >/dev/null', body) is None, branch
agent_arm = _case_arm(shim, "agent")
assert "_herdr_agent_get_scoped" in agent_arm
assert re.search(r'agent get "\$sat" >/dev/null', agent_arm) is None
assert re.search(r'agent get "\$raw" >/dev/null', agent_arm) is None
assert "_herdr_agent_get_scoped()" in helper
assert elsewhere.count("_herdr_agent_get_scoped()") == 0
n_shim = subprocess.run(["bash", "-n", str(shim_path)], capture_output=True, text=True)
assert n_shim.returncode == 0, n_shim.stderr
n_lib = subprocess.run(
["bash", "-n", str(Path(__file__).resolve().parent.parent / ".agents" / "skills" / "lib.sh")],
capture_output=True,
text=True,
)
assert n_lib.returncode == 0, n_lib.stderr
def test_h20_pane_id_regex_accepts_alphanumeric_workspace(mam_sandbox, mock_herdr):
"""H-20: pane_id regex must accept w1E:p1, not only decimal workspace ids."""
tmp_path = mam_sandbox
res = _run_lib(tmp_path, ":")
assert res.returncode == 0, res.stderr
shim = (tmp_path / ".mam" / "shim" / "herdr").read_text()
start = shim.find("_herdr_ws_id_file() {")
end = shim.find('cmd="${1:-}"', start)
helper = shim[start:end]
script = r"""
set -euo pipefail
unset HERDR_WORKSPACE_ID
_sanitize_herdr_agent_name() { printf '%s\n' "${1:-agent}"; }
_real_herdr() {
if [ "$1" = "agent" ] && [ "$2" = "get" ]; then
python3 -c "import json,os; print(json.dumps({'result':{'agent':{'pane_id':os.environ.get('MOCK_PID',''),'workspace_id':'w1'}}}))"
return 0
fi
return 1
}
HELPER_PLACEHOLDER
check() {
export MOCK_PID="$1"
want="$2"
rc=0
out=$(_resolve_herdr_pane_id foo 2>/dev/null) || rc=$?
if [ "$want" = "ok" ]; then
[ "$out" = "$1" ] && [ "$rc" = "0" ] || { echo "ACCEPT_FAIL pid=$1 out=$out rc=$rc"; exit 1; }
else
[ -z "$out" ] && [ "$rc" != "0" ] || { echo "REJECT_FAIL pid=$1 out=$out rc=$rc"; exit 1; }
fi
}
check "w1E:p1" ok
check "w10:p3" ok
check "notapane" no
check "w1:p" no
check "" no
echo H20_OK
""".replace("HELPER_PLACEHOLDER", helper)
res = subprocess.run(["bash", "-c", script], capture_output=True, text=True)
assert res.returncode == 0, res.stderr + res.stdout
assert "H20_OK" in res.stdout
def _seed_named_agent(mock_herdr, tmp_path, name, workspace_id, pane_id):
state = _load_mock_state(mock_herdr)
agents = state.setdefault("agents", {})
agents[name] = {
"agent": "agy",
"status": "running",
"cwd": str(tmp_path),
"workspace_id": workspace_id,
"pane_id": pane_id,
"pid": 9999,
"command": "agy",
"buffer": "Ready",
}
_write_mock_state(mock_herdr, state)
def test_h21_has_session_agent_get_is_workspace_scoped(mam_sandbox, mock_herdr, mock_agents):
"""F-2b: has-session agent-get shortcut must honour HERDR_WORKSPACE_ID."""
tmp_path = mam_sandbox
_seed_named_agent(mock_herdr, tmp_path, "creator-agy-01", "w1", "w1:p5")
res = _run_lib(tmp_path, 'export HERDR_WORKSPACE_ID=w2\nherdr has-session -t creator-agy-01')
assert res.returncode == 1, res.stderr + res.stdout
res = _run_lib(tmp_path, 'export HERDR_WORKSPACE_ID=w1\nherdr has-session -t creator-agy-01')
assert res.returncode == 0, res.stderr + res.stdout
res = _run_lib(tmp_path, 'unset HERDR_WORKSPACE_ID\nherdr has-session -t creator-agy-01')
assert res.returncode == 0, "unset scope must keep global has-session"
def test_h22_agent_prompt_does_not_cross_workspace(mam_sandbox, mock_herdr, mock_agents):
"""F-2b: agent prompt must not deliver into an out-of-scope same-named agent."""
tmp_path = mam_sandbox
_seed_named_agent(mock_herdr, tmp_path, "creator-agy-01", "w1", "w1:p5")
n_calls = len(_load_mock_state(mock_herdr).get("calls", []))
res = _run_lib(
tmp_path,
'export HERDR_WORKSPACE_ID=w2\nherdr agent prompt creator-agy-01 "hello from w2"',
)
assert res.returncode != 0, res.stdout + res.stderr
new_calls = _load_mock_state(mock_herdr).get("calls", [])[n_calls:]
prompts = [c for c in new_calls if len(c) >= 2 and c[0] == "agent" and c[1] == "prompt"]
assert prompts == [], new_calls
n_calls = len(_load_mock_state(mock_herdr).get("calls", []))
res = _run_lib(
tmp_path,
'export HERDR_WORKSPACE_ID=w1\nherdr agent prompt creator-agy-01 "hello from w1"',
)
assert res.returncode == 0, res.stderr + res.stdout
new_calls = _load_mock_state(mock_herdr).get("calls", [])[n_calls:]
prompts = [c for c in new_calls if len(c) >= 2 and c[0] == "agent" and c[1] == "prompt"]
assert any("hello from w1" in c for c in prompts), new_calls
def test_h23_persisted_workspace_id_scopes_without_env(mam_sandbox, mock_herdr, mock_agents):
"""F-2a: new-session persists ws id; later shim calls read it when env is unset."""
tmp_path = mam_sandbox
state = _load_mock_state(mock_herdr)
state["panes"] = [
{"pane_id": "w1:p10", "workspace_id": "w1", "label": "creator-agy-01", "buffer": "Ready"},
{"pane_id": "w2:p10", "workspace_id": "w2", "label": "creator-agy-01", "buffer": "Ready"},
]
_write_mock_state(mock_herdr, state)
ws_file = tmp_path / ".mam" / "herdr_workspace_id"
ws_file.parent.mkdir(parents=True, exist_ok=True)
ws_file.write_text("w2\n")
n_calls = len(_load_mock_state(mock_herdr).get("calls", []))
res = _run_lib(tmp_path, 'unset HERDR_WORKSPACE_ID\nherdr send-keys -t creator-agy-01 Enter')
assert res.returncode == 0, res.stderr
keyed = [
c for c in _load_mock_state(mock_herdr).get("calls", [])[n_calls:]
if len(c) >= 4 and c[0] == "pane" and c[1] == "send-keys"
]
assert keyed and keyed[0][2] == "w2:p10", keyed
res = _run_lib(
tmp_path,
f'herdr new-session -d -s "persist-creator-claude" -c "{tmp_path}" "claude --dangerously-skip-permissions"',
)
assert res.returncode == 0, res.stderr + res.stdout
persisted = ws_file.read_text().strip()
assert persisted, "new-session must persist workspace id"
assert persisted.startswith("w")