feat(issue-5): DelegationService, cli router, ensure_subscriber_daemon; lib.sh helpers delegate to python
Adds the python side of the delegation helpers and switches lib.sh over to it.
daemon.py port of start_watchdog. Same monitor path, same pgrep pattern, so
a daemon started by either implementation is found by the other;
same stderr wording and exit 1 when reconcile.sh is missing; same
"print the PID" contract, multiple pgrep matches included, since
the shell echoed them all and trimming would be a silent change.
start_new_session detaches it, and SIGHUP is ignored across the
exec so it outlives its parent exactly as nohup did.
cli.py thin router. submit/publish forward to the existing main() of the
module that already owned the behaviour, so exit codes, stdout
shape and side effects cannot drift between the shell path and
the script path. Only ensure-daemon carries logic of its own.
service.py DelegationService facade, with an optional persistent connection
for the phase 2a engine. CLI and shell always use one-shot.
lib.sh keeps the three legacy bodies verbatim as _*_legacy behind
MAM_DELEGATION_PY=0, which is the instant rollback switch. PYTHONPATH is passed
explicitly so `-m` resolves lib_py from the tree this lib.sh belongs to, which
is what makes a frozen loop run frozen delegation code. start_watchdog survives
as an alias for ensure_subscriber_daemon.
The wrapper and run_loop.sh are untouched; reconcile.sh gains only the
ensure_env_loaded line from the previous commit.
Verified: C-01..C-09 pass against both the legacy and the python bodies, the
daemon dedups and survives its parent, the cli reproduces the legacy failure
line exactly, and publish failure semantics (status synced, seq consumed,
audit records published=false) are identical through the shim and the cli.
tier1+tier2 109 passed; bash -n clean on all six shell files.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UrDNJkHmm18uu7n7JwV5Qd
This commit is contained in:
1 parent
fb3498e23b
commit
78cb9ecfa9
7 files changed
+423
-3
No files matched your search
@@ -607,3 +607,116 @@ def test_k6_subprocess_executes_the_copy_it_was_given(shim_trees):
|
||||
assert probe.returncode == 0, probe.stderr
|
||||
assert str(shim_trees / "sandbox") in probe.stdout, probe.stdout
|
||||
|
||||
|
||||
# ==============================================================================
|
||||
# 5. P1-02 — daemon module, cli router, shell-to-python equivalence
|
||||
# ==============================================================================
|
||||
|
||||
def _delegation_env(mam_sandbox):
|
||||
"""Env for running the package out of the sandbox copy."""
|
||||
env = dict(os.environ)
|
||||
env["PYTHONPATH"] = str(_sandbox_skills(mam_sandbox))
|
||||
env["MAM_ENV_FILE"] = str(Path(mam_sandbox) / ".mam.env.absent")
|
||||
return env
|
||||
|
||||
|
||||
def test_daemon_missing_monitor_raises_with_the_legacy_path(mam_sandbox):
|
||||
from lib_py.delegation import daemon
|
||||
|
||||
workdir = Path(mam_sandbox) / "no_monitor"
|
||||
workdir.mkdir()
|
||||
with pytest.raises(FileNotFoundError) as exc:
|
||||
daemon.ensure_subscriber_daemon("job1", str(workdir))
|
||||
assert exc.value.args[0] == str(daemon.monitor_script_path(str(workdir)))
|
||||
|
||||
|
||||
def test_daemon_spawn_dedup_and_survives_parent_exit(mam_sandbox):
|
||||
"""The daemon must outlive the shell that started it and never double-spawn."""
|
||||
from lib_py.delegation import daemon
|
||||
|
||||
monitor = _install_fake_monitor(mam_sandbox)
|
||||
workdir = str(mam_sandbox)
|
||||
spawned = []
|
||||
try:
|
||||
first = daemon.ensure_subscriber_daemon("job1", workdir)
|
||||
spawned += first
|
||||
assert len(first) == 1 and _alive(first[0])
|
||||
assert (Path(workdir) / ".mam" / "multi-agent-mux-monitor.log").exists()
|
||||
second = daemon.ensure_subscriber_daemon("job1", workdir)
|
||||
assert second == first, "a running daemon must be reused, not replaced"
|
||||
# detached into its own session, so a parent's process-group signal misses it
|
||||
pgid = os.getpgid(int(first[0]))
|
||||
assert pgid != os.getpgid(os.getpid())
|
||||
assert daemon.find_running(str(monitor)) == first
|
||||
finally:
|
||||
_kill(spawned)
|
||||
|
||||
|
||||
def test_cli_ensure_daemon_reproduces_the_legacy_failure_line(mam_sandbox):
|
||||
workdir = Path(mam_sandbox) / "no_monitor_cli"
|
||||
workdir.mkdir()
|
||||
res = subprocess.run(
|
||||
[sys.executable, "-m", "lib_py.delegation.cli",
|
||||
"ensure-daemon", "--job", "j1", "--workdir", str(workdir)],
|
||||
capture_output=True, text=True, env=_delegation_env(mam_sandbox), timeout=60,
|
||||
)
|
||||
assert res.returncode == 1
|
||||
expected = str(workdir / ".agents" / "skills" / "multi-agent-mux-monitor"
|
||||
/ "scripts" / "reconcile.sh")
|
||||
assert res.stderr.strip() == "ERROR: monitor script not found: {}".format(expected)
|
||||
assert res.stdout == ""
|
||||
|
||||
|
||||
def test_cli_submit_prints_only_the_job_id(mam_sandbox):
|
||||
reg_dir = Path(mam_sandbox) / ".mam" / "jobs"
|
||||
reg_dir.mkdir(parents=True, exist_ok=True)
|
||||
res = subprocess.run(
|
||||
[sys.executable, "-m", "lib_py.delegation.cli", "submit",
|
||||
"--prompt", "hello", "--agent", "claude-code",
|
||||
"--agent-session", "herdr:claude", "--registry-dir", str(reg_dir)],
|
||||
capture_output=True, text=True, env=_delegation_env(mam_sandbox), timeout=60,
|
||||
)
|
||||
assert res.returncode == 0, res.stderr
|
||||
job_id = res.stdout.strip()
|
||||
assert re.fullmatch(r"[0-9a-f]+", job_id), repr(res.stdout)
|
||||
assert res.stdout == job_id + "\n", "stdout must carry the id and nothing else"
|
||||
assert (reg_dir / (job_id + ".json")).exists()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("entry", ["script", "cli"])
|
||||
def test_publish_failure_semantics_match_across_entry_points(mam_sandbox, entry):
|
||||
"""G-1/G-2/G-4 semantics must be identical through the shim and through the cli.
|
||||
|
||||
Broker points at a non-routable port, so nothing touches the network."""
|
||||
reg_dir = Path(mam_sandbox) / ".mam" / "jobs"
|
||||
reg_dir.mkdir(parents=True, exist_ok=True)
|
||||
env = _delegation_env(mam_sandbox)
|
||||
job_id = subprocess.run(
|
||||
[sys.executable, "-m", "lib_py.delegation.cli", "submit", "--prompt", "p",
|
||||
"--registry-dir", str(reg_dir)],
|
||||
capture_output=True, text=True, env=env, timeout=60,
|
||||
).stdout.strip()
|
||||
|
||||
record = json.loads((reg_dir / (job_id + ".json")).read_text(encoding="utf-8"))
|
||||
record["broker"] = {"host": "127.0.0.1", "port": 65432, "tls": False}
|
||||
(reg_dir / (job_id + ".json")).write_text(json.dumps(record), encoding="utf-8")
|
||||
|
||||
if entry == "cli":
|
||||
cmd = [sys.executable, "-m", "lib_py.delegation.cli", "publish"]
|
||||
else:
|
||||
cmd = [sys.executable, str(SHIM_DIR / "publish_event.py")]
|
||||
res = subprocess.run(
|
||||
cmd + ["--job", job_id, "--event", "completed", "--detail", "done",
|
||||
"--attempts", "1", "--registry-dir", str(reg_dir)],
|
||||
capture_output=True, text=True, env=env, cwd=str(mam_sandbox), timeout=120,
|
||||
)
|
||||
assert res.returncode == 2, (res.stdout, res.stderr)
|
||||
assert res.stdout == "", "publish must stay silent on stdout"
|
||||
after = json.loads((reg_dir / (job_id + ".json")).read_text(encoding="utf-8"))
|
||||
assert after["status"] == "completed", "status syncs even when the publish fails"
|
||||
assert after.get("last_seq") == 1, "seq is consumed on failure by design"
|
||||
audit = (Path(mam_sandbox) / ".mam" / "delegate_job_logs" / job_id / "events.ndjson")
|
||||
events = [json.loads(l) for l in audit.read_text(encoding="utf-8").splitlines() if l.strip()]
|
||||
published = [e for e in events if e.get("event") == "published"]
|
||||
assert published and published[-1]["published"] is False
|
||||
assert published[-1]["publish_error"]
|
||||
Reference in new issue
Block a user