Files
ai-agent/sidecar/test_path_shims.py
gabrielvidalandClaude Opus 5.5 16aabb9922 feat(plugins): move commits + diff viewer out of core into plugins
Generic platform points for the `diff-viewer` and `commits` plugins
(ai-agent-plugins): a `conversation.tab` slot (Thread | Changes N) with
setTab/openTab/closeTab/reply bridges; stackable + pullOut tool cards and
match.hasReport; `pathShims` (a git PATH shim for every harness) with
out-of-band reports (lab: /api/plugin-reports, worker: outbox `report`);
`conversations.reports` and `diff.read` hub bridges; ui.pages[].opens for
Project/Service "Recent commits". The core commit card, Changes view, diff
page and review store are gone; bash_diff.py keeps bashDiff only. Legacy
gitCommits / commit-line parsing stays for past transcripts.

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

301 lines
13 KiB
Python

"""path_shims + aia_report: live plugins' ``pathShims`` on this machine — the
wrappers every run gets first on its PATH, the env a shim script runs with,
the out-of-band report and its spool — and the worker's /sync writer keeping
them (labsync.write_hooks)."""
import base64
import http.server
import json
import os
import pathlib
import shutil
import subprocess
import sys
import threading
import pytest
import aia_report
import labsync
import outbox
import path_shims as ps
REAL_GIT = shutil.which("git")
SID = "11111111-2222-3333-4444-555555555555"
# A shim script: notes how it was started, files a report, then runs the real
# git — exit code and stdio its.
SHIM = r'''
import importlib.util, json, os, sys
with open(os.environ["SHIM_LOG"], "a") as f:
f.write(json.dumps({"argv": sys.argv[1:], "env": {k: os.environ.get(k) for k in (
"AIA_SHIM_REAL", "AIA_SHIM_PLUGIN", "AIA_SESSION_ID", "AIA_REPORT_PY",
"AIA_SHIM_ACTIVE")}}) + "\n")
spec = importlib.util.spec_from_file_location("aia_report", os.environ["AIA_REPORT_PY"])
m = importlib.util.module_from_spec(spec); spec.loader.exec_module(m)
r = __import__("subprocess").run([os.environ["AIA_SHIM_REAL"], *sys.argv[1:]])
m.report("commit", {"v": 1, "argv": sys.argv[1:12]}, {"v": 1, "patches": {"x": "y"}})
sys.exit(r.returncode)
'''
def _index(base: pathlib.Path, shims, files=None):
base.mkdir(parents=True, exist_ok=True)
(base / "index.json").write_text(json.dumps({"hash": "h", "hooks": [], "shims": shims}))
for rel, text in (files or {}).items():
p = base / rel
p.parent.mkdir(parents=True, exist_ok=True)
p.write_text(text)
GIT_SHIM = {"plugin": "commits", "id": "git", "command": "git", "script": "commits/shim/git_shim.py",
"triggers": ["commit", "merge", "push"], "guestAllowed": True}
OWNER_ONLY = {"plugin": "other", "id": "tea", "command": "tea", "script": "other/t.py",
"triggers": ["pr"], "guestAllowed": False}
@pytest.fixture
def lab(tmp_path, monkeypatch):
base = tmp_path / "live-hooks"
_index(base, [GIT_SHIM, OWNER_ONLY],
{"commits/shim/git_shim.py": SHIM, "other/t.py": "print(1)\n"})
root = tmp_path / "shims"
monkeypatch.setenv("SHIM_LOG", str(tmp_path / "shim.log"))
for k in ("AIA_SHIM_ACTIVE", "AI_AGENT_OUTBOX_URL", "AIA_REPORT_URL"):
monkeypatch.delenv(k, raising=False)
return base, root, tmp_path
def _env(lab, scoped=False, **kw):
base, root, _ = lab
env = {"PATH": os.environ["PATH"], "HOME": os.environ.get("HOME", "/tmp"),
"SHIM_LOG": os.environ["SHIM_LOG"]}
return ps.apply(env, SID, scoped=scoped, is_worker=True, base=base, root=root, **kw)
def _log(tmp):
p = tmp / "shim.log"
return [json.loads(x) for x in p.read_text().splitlines()] if p.exists() else []
# ── the wrappers ─────────────────────────────────────────────────────────────
def test_wrappers_go_first_on_path(lab):
base, root, _ = lab
env = _env(lab)
first = env["PATH"].split(os.pathsep)[0]
assert first == str(root / "bin")
assert sorted(os.listdir(first)) == ["git", "tea"]
assert os.access(root / "bin" / "git", os.X_OK)
assert env["AIA_SESSION_ID"] == SID and env["AIA_REPORT_SPOOL"] == str(root / "spool.jsonl")
assert (root / "aia_report.py").read_text() == ps.REPORT_PY.read_text()
# applied twice: the shim dir is there once
again = ps.apply(env, SID, scoped=False, is_worker=True, base=base, root=root)
assert again["PATH"].split(os.pathsep).count(str(root / "bin")) == 1
def test_a_scoped_run_gets_guest_allowed_shims_only(lab):
_, root, _ = lab
env = _env(lab, scoped=True)
assert env["PATH"].split(os.pathsep)[0] == str(root / "bin-guest")
assert os.listdir(root / "bin-guest") == ["git"]
def test_off_or_nothing_delivered_leaves_path_alone(lab, tmp_path):
env = _env(lab, enabled=False)
assert env["PATH"] == os.environ["PATH"] and env["AIA_SESSION_ID"] == SID
empty = tmp_path / "empty"
_index(empty, [])
env = ps.apply({"PATH": "/usr/bin"}, SID, scoped=False, is_worker=True, base=empty,
root=tmp_path / "s2")
assert env["PATH"] == "/usr/bin"
def test_a_script_outside_the_index_dir_is_refused(tmp_path):
base = tmp_path / "idx"
_index(base, [{**GIT_SHIM, "script": "../evil.py"}])
(tmp_path / "evil.py").write_text("print(1)")
assert ps.load(base) == []
def test_the_lab_gets_a_report_token(lab, monkeypatch):
import config
monkeypatch.setattr(config, "TOKEN", "sidecar-bearer")
base, root, _ = lab
env = ps.apply({"PATH": "/usr/bin"}, SID, scoped=False, is_worker=False, base=base, root=root)
assert env["AIA_REPORT_URL"].startswith("http")
assert env["AIA_REPORT_TOKEN"] == ps.report_token(SID, "sidecar-bearer")
assert len(env["AIA_REPORT_TOKEN"]) == 40
# ── a real run of the generated wrapper ──────────────────────────────────────
@pytest.fixture
def repo(tmp_path):
r = tmp_path / "repo"
r.mkdir()
for args in (["init", "-q"], ["config", "user.email", "t@t"], ["config", "user.name", "t"]):
subprocess.run([REAL_GIT, "-C", str(r), *args], check=True)
(r / "a.txt").write_text("a\n")
return r
def _git(env, repo, *args):
return subprocess.run(["git", *args], cwd=repo, env=env, capture_output=True, text=True,
timeout=30)
def test_read_only_git_never_starts_the_script(lab, repo):
env = _env(lab)
assert shutil.which("git", path=env["PATH"]) == str(lab[1] / "bin" / "git")
p = _git(env, repo, "status", "--porcelain")
assert p.returncode == 0 and "a.txt" in p.stdout
assert _log(lab[2]) == []
# git's own exit code comes through untouched
p = _git(env, repo, "rev-parse", "--verify", "-q", "nope")
assert p.returncode == subprocess.run([REAL_GIT, "rev-parse", "--verify", "-q", "nope"],
cwd=repo).returncode != 0
assert _log(lab[2]) == []
def test_a_trigger_word_runs_the_script_with_its_env(lab, repo):
env = _env(lab)
_git(env, repo, "add", "a.txt")
p = _git(env, repo, "commit", "-qm", "first")
assert p.returncode == 0
[rec] = _log(lab[2])
assert rec["argv"] == ["commit", "-qm", "first"]
e = rec["env"]
assert os.path.realpath(e["AIA_SHIM_REAL"]) == os.path.realpath(REAL_GIT)
assert e["AIA_SHIM_PLUGIN"] == "commits" and e["AIA_SESSION_ID"] == SID
assert e["AIA_REPORT_PY"] == str(lab[1] / "aia_report.py") and e["AIA_SHIM_ACTIVE"] == "1"
log = subprocess.run([REAL_GIT, "log", "--format=%s"], cwd=repo, capture_output=True,
text=True).stdout
assert log.strip() == "first"
# the script's exit code is the command's: nothing to commit → git's 1
p = _git(env, repo, "commit", "-qm", "again")
assert p.returncode == 1 and len(_log(lab[2])) == 2
def test_a_nested_call_takes_the_fast_path(lab, repo):
env = {**_env(lab), "AIA_SHIM_ACTIVE": "1"}
_git(env, repo, "add", "a.txt")
assert _git(env, repo, "commit", "-qm", "x").returncode == 0
assert _log(lab[2]) == []
def test_a_stale_real_path_is_searched_again(lab, repo):
_env(lab)
w = lab[1] / "bin" / "git"
w.write_text(w.read_text().replace(f"AIA_SHIM_REAL='{REAL_GIT}'",
"AIA_SHIM_REAL=/nonexistent/git"))
env = {**os.environ, "PATH": f"{lab[1] / 'bin'}{os.pathsep}{os.environ['PATH']}"}
assert _git(env, repo, "status").returncode == 0
def test_the_report_spools_when_the_hub_is_unreachable_and_drains(lab, repo, monkeypatch):
env = {**_env(lab), "AI_AGENT_OUTBOX_URL": "http://127.0.0.1:9", "AI_AGENT_OUTBOX_TOKEN": "t"}
_git(env, repo, "add", "a.txt")
assert _git(env, repo, "commit", "-qm", "spooled").returncode == 0
spool = lab[1] / "spool.jsonl"
[line] = spool.read_text().splitlines()
p = json.loads(line)
assert p["sessionId"] == SID and p["plugin"] == "commits" and p["id"].startswith("rpt_")
assert p["report"]["event"] == "commit" and p["report"]["blob"] == {"v": 1, "patches": {"x": "y"}}
assert "token" not in p
got = []
assert ps.drain_spool(lambda x: got.append(x) or False, root=lab[1]) == 0
assert spool.read_text().strip() # refused: kept
assert ps.drain_spool(lambda x: True, root=lab[1]) == 1
assert spool.read_text() == ""
# ── aia_report ───────────────────────────────────────────────────────────────
def test_report_caps(monkeypatch):
monkeypatch.setenv("AIA_SESSION_ID", SID)
monkeypatch.setenv("AIA_SHIM_PLUGIN", "commits")
assert aia_report.build("commit", {"x": "y" * 9000}) is None # summary > 8 KB
p = aia_report.build("commit", {"v": 1}, {"big": "z" * 200_000})
assert "blob" not in p["report"] and p["report"]["summary"]["blobDropped"] is True
assert aia_report.build("Bad Event", {}) is None
monkeypatch.delenv("AIA_SHIM_PLUGIN")
assert aia_report.report("commit", {"v": 1}) is False # no plugin: nothing
def test_report_goes_to_the_outbox_on_a_worker(monkeypatch):
got = []
class H(http.server.BaseHTTPRequestHandler):
def do_POST(self):
got.append((self.path, self.headers.get("Authorization"),
json.loads(self.rfile.read(int(self.headers["Content-Length"])))))
self.send_response(202)
self.end_headers()
self.wfile.write(b"{}")
def log_message(self, *a):
pass
srv = http.server.HTTPServer(("127.0.0.1", 0), H)
threading.Thread(target=srv.handle_request, daemon=True).start()
monkeypatch.setenv("AIA_SESSION_ID", SID)
monkeypatch.setenv("AIA_SHIM_PLUGIN", "commits")
monkeypatch.setenv("AI_AGENT_OUTBOX_URL", f"http://127.0.0.1:{srv.server_port}")
monkeypatch.setenv("AI_AGENT_OUTBOX_TOKEN", "run-tok")
assert aia_report.report("commit", {"v": 1}) is True
srv.server_close()
[(path, auth, body)] = got
assert path == "/outbox" and auth == "Bearer run-tok" and body["kind"] == "report"
assert body["payload"]["sessionId"] == SID and body["payload"]["report"]["summary"] == {"v": 1}
# the sidecar's outbox takes it as a one-shot; the ack drops the blob
box = outbox.Outbox(pathlib.Path(os.environ.get("TMPDIR", "/tmp")) / f"ob-{os.getpid()}.json")
payload = {**body["payload"], "report": {**body["payload"]["report"], "blob": {"a": 1}}}
box.put("report", payload)
it = box.ack(payload["id"], {"ok": True})
assert it["status"] == "applied"
assert "blob" not in it["payload"]["report"] and it["payload"]["report"]["blobCollected"]
with pytest.raises(ValueError):
box.put("report", {**payload, "id": "met_000000000000"})
# ── the worker's /sync writer ────────────────────────────────────────────────
def test_write_hooks_keeps_the_shims(tmp_path, monkeypatch):
monkeypatch.setattr(labsync, "_guest_computer", lambda: False)
root = tmp_path / "hooks"
files = {GIT_SHIM["script"]: base64.b64encode(b"print(1)\n").decode(),
OWNER_ONLY["script"]: base64.b64encode(b"print(2)\n").decode()}
out = labsync.write_hooks({"hash": "h1", "rules": [], "shims": [GIT_SHIM, OWNER_ONLY],
"files": files}, root)
assert out == {"hash": "h1", "rules": 0, "shims": 2}
assert [s["command"] for s in ps.load(root)] == ["git", "tea"]
assert (root / GIT_SHIM["script"]).read_text() == "print(1)\n"
# a guest's computer keeps the guestAllowed ones only
monkeypatch.setattr(labsync, "_guest_computer", lambda: True)
labsync.write_hooks({"hash": "h2", "rules": [], "shims": [GIT_SHIM, OWNER_ONLY],
"files": files}, root)
assert [s["command"] for s in ps.load(root)] == ["git"]
assert not (root / OWNER_ONLY["script"]).exists()
# a shim whose file didn't come is dropped
labsync.write_hooks({"hash": "h3", "rules": [], "shims": [GIT_SHIM], "files": {}}, root)
assert ps.load(root) == []
# ── launch._launch: every harness goes through it ────────────────────────────
@pytest.mark.parametrize("harness", ["claude", "pi", "opencode", "agy"])
def test_every_harness_launch_gets_the_wrappers(lab, monkeypatch, harness):
import guest_git
import launch
import pids
base, root, tmp = lab
monkeypatch.setenv("SIDECAR_LIVE_HOOKS_DIR", str(base))
monkeypatch.setenv("SIDECAR_SHIMS_DIR", str(root))
monkeypatch.setattr(launch, "LOG_DIR", tmp)
monkeypatch.setattr(pids, "LOG_DIR", tmp)
monkeypatch.setattr(guest_git, "STATE_DIR", tmp / "state")
monkeypatch.setattr(guest_git, "GLOBAL_CONFIG", tmp / "state" / "gitconfig")
prog = [sys.executable, "-c", "import json, os, shutil; print(json.dumps("
"{'git': shutil.which('git'), 'sid': os.environ.get('AIA_SESSION_ID')}))"]
launch._launch(prog, SID, str(tmp), harness=harness,
env={"PATH": os.environ["PATH"], "HOME": os.environ.get("HOME", "/tmp")})
pids._procs.pop(SID).wait(timeout=10)
got = json.loads((tmp / f"{SID}.log").read_text().strip().splitlines()[-1])
assert got == {"git": str(root / "bin" / "git"), "sid": SID}