Files
ai-agent/sidecar/test_callprobe.py
gabrielvidalandClaude Opus 5.5 bec07d1dc0 chore(sidecar): agent-probe 0.1.2 at least — Claude Code's Code Mode
0.1.2 groups a Code Mode script's calls (their records carry "script"),
measures the Claude Code that Code Mode's restart re-runs by its versioned
path (it was taken for no agent: calls recorded with no process), and sets
onFailure: continue on its hooks — Code Mode refuses a call from code whose
PreToolUse hook fails. A worker's fetched copy older than this is replaced.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 20:34:04 +01:00

180 lines
6.9 KiB
Python

"""callprobe: the runner's side of agent-probe — finding the binary, its hooks
(the Python probe's old ones taken out), claude-probe's store migrated once,
and /callmeta from the daemon or the store."""
import json
import os
import socket
import stat
import threading
from http.server import BaseHTTPRequestHandler, HTTPServer
import callprobe as cp
def test_old_python_hooks_are_removed_and_the_rest_kept(tmp_path):
p = tmp_path / "settings.json"
old = {"hooks": [{"type": "command", "command": "py call_hook.py # ai-agent call probe"}]}
p.write_text(json.dumps({"model": "opus", "hooks": {
"PreToolUse": [{"matcher": "Bash", "hooks": [{"type": "command", "command": "rtk hook claude"}]},
dict(old, matcher="Bash")],
"Stop": [old]}}))
os.chmod(p, 0o600)
assert cp.remove_old_hooks(p) is True
data = json.loads(p.read_text())
assert data["model"] == "opus"
assert data["hooks"] == {"PreToolUse": [{"matcher": "Bash", "hooks": [
{"type": "command", "command": "rtk hook claude"}]}]}
assert os.stat(p).st_mode & 0o777 == 0o600
assert cp.remove_old_hooks(p) is False
def test_binary_prefers_the_env_then_the_capable_copy(tmp_path, monkeypatch):
b = tmp_path / "agent-probe"
b.write_text("#!/bin/sh\n")
b.chmod(b.stat().st_mode | stat.S_IXUSR)
monkeypatch.delenv("SIDECAR_CLAUDE_PROBE", raising=False)
monkeypatch.setenv("SIDECAR_AGENT_PROBE", str(b))
assert cp.binary() == str(b)
monkeypatch.setenv("SIDECAR_AGENT_PROBE", str(tmp_path / "missing"))
assert cp.binary() is None
# the claude-probe-era name still works when the new one isn't set
monkeypatch.delenv("SIDECAR_AGENT_PROBE")
monkeypatch.setenv("SIDECAR_CLAUDE_PROBE", str(b))
assert cp.binary() == str(b)
def test_release_asset_and_paths_are_agent_probes(monkeypatch):
monkeypatch.setattr(cp.platform, "system", lambda: "Linux")
monkeypatch.setattr(cp.platform, "machine", lambda: "x86_64")
monkeypatch.delenv("AGENT_PROBE_SOCK", raising=False)
monkeypatch.delenv("AGENT_PROBE_STATE_DIR", raising=False)
assert cp._asset() == "agent-probe-linux-amd64"
assert cp.socket_path().endswith("/.cache/agent-probe/probe.sock")
assert str(cp._state_dir()).endswith("/.local/state/agent-probe")
assert cp._legacy()[1].endswith("/.cache/claude-probe/probe.sock")
assert "agent-probe/releases" in cp.RELEASES and cp.MIN_VERSION == (0, 1, 2)
def _fake_bin(tmp_path, records):
b = tmp_path / "agent-probe"
b.write_text("#!/bin/sh\necho '" + json.dumps({"records": records, "last": 7, "head": 7,
"enabled": True}) + "'\n")
b.chmod(0o755)
return b
class UnixServer(HTTPServer):
address_family = socket.AF_UNIX
def server_bind(self):
self.socket.bind(self.server_address)
def get_request(self):
conn, _ = self.socket.accept()
return conn, ("local", 0)
def test_callmeta_falls_back_to_export_without_a_daemon(tmp_path, monkeypatch):
monkeypatch.setenv("AGENT_PROBE_SOCK", str(tmp_path / "none.sock"))
monkeypatch.setenv("SIDECAR_AGENT_PROBE", str(_fake_bin(tmp_path, [{"id": 7, "kind": "call"}])))
monkeypatch.setattr(cp, "_auth", lambda a: None)
out = cp.callmeta(after=0, limit=10, authorization=None)
assert out["last"] == 7 and out["records"][0]["kind"] == "call"
def test_callmeta_asks_the_daemon_first(tmp_path, monkeypatch):
sock = str(tmp_path / "p.sock")
class H(BaseHTTPRequestHandler):
def do_GET(self): # noqa: N802
body = json.dumps({"records": [{"id": 3}], "last": 3, "head": 3, "path": self.path}).encode()
self.send_response(200)
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
def log_message(self, *a):
pass
srv = UnixServer(sock, H)
threading.Thread(target=srv.handle_request, daemon=True).start()
monkeypatch.setenv("AGENT_PROBE_SOCK", sock)
monkeypatch.setattr(cp, "_auth", lambda a: None)
out = cp.callmeta(after=2, limit=5, authorization=None)
srv.server_close()
assert out["last"] == 3 and out["path"] == "/callmeta?after=2&limit=5"
def test_disabled_answers_empty(monkeypatch):
monkeypatch.setattr(cp, "ENABLED", False)
monkeypatch.setattr(cp, "_auth", lambda a: None)
assert cp.callmeta(after=5, limit=1, authorization=None) == {"records": [], "last": 5, "enabled": False}
def _migration_env(tmp_path, monkeypatch, *, new_db=False):
"""claude-probe's store at old/, agent-probe's state at new/, and a fake
agent-probe that logs its argv."""
old, new = tmp_path / "old", tmp_path / "new"
old.mkdir()
(old / "probe.db").write_text("x")
new.mkdir()
if new_db:
(new / "probe.db").write_text("y")
log = tmp_path / "argv.log"
b = tmp_path / "agent-probe"
b.write_text(f"#!/bin/sh\necho \"$@\" >> {log}\necho '12 records copied'\n")
b.chmod(0o755)
monkeypatch.setenv("AGENT_PROBE_STATE_DIR", str(new))
monkeypatch.setattr(cp, "_legacy", lambda: (old, str(tmp_path / "old.sock")))
return str(b), log, old
def test_migrate_once_while_agent_probe_has_no_store(tmp_path, monkeypatch):
b, log, old = _migration_env(tmp_path, monkeypatch)
assert cp.migrate(b) is True
assert log.read_text().split() == ["migrate", "--from", str(old)]
def test_no_migration_once_agent_probe_has_a_store(tmp_path, monkeypatch):
b, log, _ = _migration_env(tmp_path, monkeypatch, new_db=True)
assert cp.migrate(b) is False
assert not log.exists()
def test_migrate_failure_is_logged_not_raised(tmp_path, monkeypatch, capsys):
b, _, _ = _migration_env(tmp_path, monkeypatch)
with open(b, "w") as f:
f.write("#!/bin/sh\necho 'this store already holds 3 records' >&2\nexit 1\n")
assert cp.migrate(b) is False
assert "already holds 3 records" in capsys.readouterr().out
def test_stop_legacy_daemon_terms_the_pid_health_names(tmp_path, monkeypatch):
sock = str(tmp_path / "old.sock")
class H(BaseHTTPRequestHandler):
def do_GET(self): # noqa: N802
body = json.dumps({"version": "v0.3.1", "pid": 4242}).encode()
self.send_response(200)
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
def log_message(self, *a):
pass
srv = UnixServer(sock, H)
threading.Thread(target=srv.handle_request, daemon=True).start()
killed = []
def kill(pid, sig):
killed.append((pid, sig))
srv.server_close()
os.unlink(sock) # the daemon is gone: nothing answers any more
monkeypatch.setattr(cp.os, "kill", kill)
assert cp.stop_legacy_daemon(sock, wait=3) is True
assert killed == [(4242, cp.signal.SIGTERM)]
assert cp.stop_legacy_daemon(sock, wait=1) is False # none running: nothing to stop