Files
multi-agent-mux/tests/test_issue9_server_env.py
T
GodopuandClaude Fable 5.1 497633f64a fix(issue-9,14): sanitize herdr server env and confirm accepted prompt delivery
- Drop per-session agent runtime markers (CLAUDECODE, CLAUDE_CODE_CHILD_SESSION,
  CLAUDE_CODE_SESSION_ID, Claude Code messaging/bridge/pid markers, and the
  agy/hermes/grok/opencode session ids) from the environment lib.sh's shim hands
  to a bootstrapped `herdr --session <name> server`; user configuration such as
  CLAUDE_PROJECT_DIR still inherits
- Add MAM_NO_AUTOSTART=1 so query-only callers never bootstrap a server as a side
  effect; status.sh and reconcile.sh export it, and the shim's `ls` reports a down
  server as "no server running" so reconcile keeps herdr_confirmed instead of
  freezing drift detection for every server
- send_keys_safe: treat `timeout` / `agent_prompt_stalled` from `agent prompt
  --wait` as an accepted submission and confirm delivery for SKS_DELIVERY_GRACE_S
  (default 15 s) via agent_status working, a busy token the pane did not show
  before, or the pane moving on from its pre-submit snapshot; no signal at all
  still fails closed (rc 4). Codex under herdr 0.9.0 never reports `working`, so
  every delivered prompt was closed as agent_blocked and its later
  started/completed events refused
- delegate wrapper: before closing an unconfirmed inject as agent_blocked, honour
  the registry's own acknowledgement for MAM_INJECT_ACK_GRACE_S (default 10 s)
- Switch T1-7's failure trigger to transport_error (timeout now means accepted);
  add test_issue9_server_env.py (5 cases) and test_issue14_delivery_ack.py (7)
- Verified live: a freshly bootstrapped multi-agent-mux server carries no markers
  and the claude panes save transcripts again; codex job d04ebcb5 had its
  started/completed accepted with no agent_blocked

Closes #9
Closes #14

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VCgu9Fa9iT7TbJUSzdq4Ff
2026-09-12 23:11:55 +09:00

182 lines
7.2 KiB
Python

#!/usr/bin/env python3
"""Issue #9 — herdr server bootstrap must not inherit the caller's agent-runtime
markers, and query-only skills must never bootstrap a server at all.
The bootstrap lives in the `.mam/shim/herdr` wrapper that lib.sh writes, so every
test drives that shim against a fake `herdr` binary placed first on PATH: it logs
each call, answers `session list --json` with "not running", and dumps its own
environment when asked to run as the `server`.
"""
from __future__ import annotations
import json
import os
import subprocess
import sys
from pathlib import Path
REPO_ROOT = Path(__file__).resolve().parent.parent
RECONCILE_SH = REPO_ROOT / ".agents" / "skills" / "multi-agent-mux-monitor" / "scripts" / "reconcile.sh"
STATUS_SH = REPO_ROOT / ".agents" / "skills" / "multi-agent-mux-status" / "scripts" / "status.sh"
FAKE_HERDR = r'''#!/usr/bin/env python3
import json, os, sys
args = sys.argv[1:]
with open(os.environ["FAKE_HERDR_LOG"], "a") as f:
f.write(json.dumps(args) + "\n")
if args[-1:] == ["server"]:
with open(os.environ["FAKE_HERDR_ENV_DUMP"], "w") as f:
json.dump(dict(os.environ), f)
sys.exit(0)
if args[-3:] == ["session", "list", "--json"]:
print(json.dumps({"sessions": []}))
sys.exit(0)
print(json.dumps({"result": {"agents": []}}))
'''
# Per-session runtime markers of the calling agent CLI: none of these may reach
# the daemon (and through it, every pane it later spawns).
RUNTIME_MARKERS = {
"CLAUDECODE": "1",
"CLAUDE_CODE_CHILD_SESSION": "1",
"CLAUDE_CODE_SESSION_ID": "orchestrator-uuid",
"CLAUDE_CODE_MESSAGING_SOCKET": "/tmp/cc-socks/1.sock",
"CLAUDE_PID": "12345",
"ANTIGRAVITY_CONVERSATION_ID": "agy-uuid",
"HERMES_SESSION_ID": "hermes-uuid",
"GROK_SESSION_ID": "grok-uuid",
"OPENCODE_SESSION_ID": "opencode-uuid",
}
# Ordinary configuration must keep flowing through unchanged.
KEPT_CONFIG = {
"CLAUDE_CONFIG_DIR": "/keep/claude-config",
"MAM_CUSTOM_SETTING": "kept",
}
def _install_fake_herdr(sandbox: Path) -> dict:
fakebin = sandbox / "fakebin"
fakebin.mkdir(exist_ok=True)
binary = fakebin / "herdr"
binary.write_text(FAKE_HERDR)
binary.chmod(0o755)
env = dict(os.environ)
env.update({
"PATH": f"{fakebin}:{env['PATH']}",
"FAKE_HERDR_LOG": str(sandbox / "fake_herdr_calls.log"),
"FAKE_HERDR_ENV_DUMP": str(sandbox / "server_env.json"),
"AGENT_PYTHON_BIN": sys.executable,
"DELEGATE_JOB_PYTHON": sys.executable,
})
return env
def _calls(env: dict) -> list:
log = Path(env["FAKE_HERDR_LOG"])
if not log.exists():
return []
return [json.loads(line) for line in log.read_text().splitlines() if line.strip()]
def _run_through_shim(sandbox: Path, env: dict, session: str) -> subprocess.CompletedProcess:
"""`herdr agent list` through lib.sh's shim, scoped to an isolated session
whose server the fake reports as not running."""
lib = sandbox / ".agents" / "skills" / "lib.sh"
env = dict(env, HERDR_SESSION_NAME=session)
return subprocess.run(
["bash", "-c", f'source "{lib}" >/dev/null 2>&1; herdr agent list'],
capture_output=True, text=True, cwd=str(sandbox), env=env, timeout=60,
)
def test_bootstrap_strips_agent_runtime_markers(mam_sandbox):
env = _install_fake_herdr(mam_sandbox)
env.update(RUNTIME_MARKERS)
env.update(KEPT_CONFIG)
res = _run_through_shim(mam_sandbox, env, "issue9-probe")
assert res.returncode == 0, res.stderr
server_calls = [c for c in _calls(env) if c[-1:] == ["server"]]
assert server_calls == [["--session", "issue9-probe", "server"]], _calls(env)
dump = Path(env["FAKE_HERDR_ENV_DUMP"])
assert dump.exists(), "server was bootstrapped but never received an environment"
server_env = json.loads(dump.read_text())
leaked = sorted(k for k in RUNTIME_MARKERS if k in server_env)
assert not leaked, f"runtime markers leaked into the herdr server: {leaked}"
for key, value in KEPT_CONFIG.items():
assert server_env.get(key) == value, f"{key} must be inherited unchanged"
# MAM's own configuration is configuration, not a marker.
assert server_env.get("CLAUDE_PROJECT_DIR") == os.environ["CLAUDE_PROJECT_DIR"]
for key in ("HOME", "PATH", "WORKSPACE_ROOT"):
assert key in server_env
def test_no_autostart_skips_bootstrap_but_still_routes_the_call(mam_sandbox):
env = _install_fake_herdr(mam_sandbox)
env["MAM_NO_AUTOSTART"] = "1"
res = _run_through_shim(mam_sandbox, env, "issue9-quiet")
assert res.returncode == 0, res.stderr
calls = _calls(env)
assert not any(c[-1:] == ["server"] for c in calls), f"server must not be started: {calls}"
assert not Path(env["FAKE_HERDR_ENV_DUMP"]).exists()
# The command itself still goes to the named session, whose server answers.
assert ["--session", "issue9-quiet", "agent", "list"] in calls, calls
def test_status_query_never_starts_a_server(mam_sandbox):
"""status.sh sweeps every herdr_session named in the YAML; a stopped
isolated server must be reported dead, not bootstrapped to answer."""
env = _install_fake_herdr(mam_sandbox)
(mam_sandbox / ".mam" / "agent-sessions.yaml").write_text(
"herdr_sessions:\n"
" - name: ghost-creator-claude\n"
" status: stopped\n"
" herdr_session: ghost-srv\n"
" pane:\n"
" cwd: /tmp/nonexistent-workspace\n"
)
status_sh = mam_sandbox / "skills" / "multi-agent-mux-status" / "scripts" / "status.sh"
res = subprocess.run(["bash", str(status_sh), "--json"], capture_output=True, text=True,
cwd=str(mam_sandbox), env=env, timeout=120)
assert res.returncode == 0, res.stderr
calls = _calls(env)
assert any("--session" in c and "ghost-srv" in c for c in calls), \
f"the ghost-srv session was never queried: {calls}"
assert not any(c[-1:] == ["server"] for c in calls), f"status.sh started a server: {calls}"
assert not Path(env["FAKE_HERDR_ENV_DUMP"]).exists()
def test_reconcile_and_status_opt_out_of_autostart_statically():
for script in (RECONCILE_SH, STATUS_SH):
assert "export MAM_NO_AUTOSTART=1" in script.read_text(), \
f"{script.name} must opt out of the shim's server bootstrap"
def test_ls_reports_down_server_as_no_server_running(mam_sandbox):
"""reconcile.sh treats a nonzero `ls` as 'empty' only when stderr says
'no server running'; anything else flips herdr_confirmed=False for every
server. The shim must therefore translate server_not_running explicitly."""
env = _install_fake_herdr(mam_sandbox)
env["MAM_NO_AUTOSTART"] = "1"
fake = mam_sandbox / "fakebin" / "herdr"
fake.write_text(FAKE_HERDR.replace(
'print(json.dumps({"result": {"agents": []}}))',
'sys.stderr.write(json.dumps({"error": {"code": "server_not_running"}}) + "\\n"); sys.exit(1)',
))
lib = mam_sandbox / ".agents" / "skills" / "lib.sh"
res = subprocess.run(
["bash", "-c", f'source "{lib}" >/dev/null 2>&1; herdr -L down-srv ls -F "#{{session_name}}|#{{session_created}}"'],
capture_output=True, text=True, cwd=str(mam_sandbox), env=env, timeout=60,
)
assert res.returncode != 0
assert "no server running" in res.stderr, res.stderr
assert res.stdout.strip() == ""