Files
ai-agent/sidecar/test_bash_diff.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

343 lines
14 KiB
Python

"""bash_diff: the Bash pre/post hook pair records exactly what a command
changed in the repo it ran in — and never touches that repo's .git."""
import json
import os
import subprocess
import sys
import pytest
import bash_diff as bd
HOOK = os.path.join(os.path.dirname(os.path.abspath(__file__)), "bash_diff.py")
def _git(repo, *args):
subprocess.run(["git", "-C", str(repo), *args], check=True, capture_output=True)
@pytest.fixture
def repo(tmp_path, monkeypatch):
r = tmp_path / "repo"
r.mkdir()
_git(r, "init", "-q")
_git(r, "config", "user.email", "t@t")
_git(r, "config", "user.name", "t")
(r / "f.txt").write_text("a\nb\nc\n")
(r / "keep.md").write_text("x\n")
(r / ".gitignore").write_text("ignored/\n")
_git(r, "add", ".")
_git(r, "commit", "-qm", "init")
(r / "keep.md").write_text("x\ndirty\n") # dirty before the call
monkeypatch.setenv("BASH_DIFF_STATE_DIR", str(tmp_path / "state"))
return r
def _run(mode, cwd, command, tid="toolu_1", session="s1", **inp):
ev = {"session_id": session, "tool_name": "Bash", "tool_use_id": tid, "cwd": str(cwd),
"hook_event_name": "PreToolUse" if mode == "pre" else "PostToolUse",
"tool_input": {"command": command, **inp}}
p = subprocess.run([sys.executable, HOOK, mode], input=json.dumps(ev), text=True,
capture_output=True, env=os.environ, timeout=30)
assert p.returncode == 0 and p.stderr == ""
return json.loads(p.stdout)["bashDiff"] if p.stdout else None
def _around(cwd, command, effect, **kw):
assert _run("pre", cwd, command, **kw) is None # pre never prints
effect()
return _run("post", cwd, command, **kw)
def _objects(repo):
return sorted(str(p) for p in (repo / ".git" / "objects").rglob("*") if p.is_file())
def test_records_edits_creations_and_deletions(repo, tmp_path):
before = _objects(repo)
index = (repo / ".git" / "index").read_bytes()
def effect():
(repo / "f.txt").write_text("a\nB\nc\n")
(repo / "n.txt").write_text("new\n")
(repo / "keep.md").unlink()
(repo / "ignored").mkdir()
(repo / "ignored" / "x").write_text("no\n")
d = _around(tmp_path, f"cd {repo} && sed -i s/b/B/ f.txt && echo new > n.txt && rm keep.md",
effect)
files = {f["path"]: f for f in d["repos"][0]["files"]}
assert set(files) == {"f.txt", "n.txt", "keep.md"}
assert files["keep.md"] == {"path": "keep.md", "status": "deleted", "add": 0, "del": 2,
"binary": False} # the dirty content, not HEAD's
assert files["n.txt"]["status"] == "added"
assert (d["add"], d["del"]) == (2, 3)
assert "-b\n+B" in d["repos"][0]["patch"]
# Nothing was written into the repo's own .git.
assert _objects(repo) == before
assert (repo / ".git" / "index").read_bytes() == index
def test_nothing_changed_prints_nothing(repo):
assert _around(repo, "make -n", lambda: None) is None
def test_read_only_and_background_calls_are_skipped(repo, tmp_path):
state = tmp_path / "state" / "s1"
_run("pre", repo, "git status && ls | head")
_run("pre", repo, "npm run dev", run_in_background=True)
assert not state.exists() or not list(state.glob("*.pre.json"))
def test_session_cwd_is_left_out_when_the_command_cds_elsewhere(repo, tmp_path):
other = tmp_path / "other"
other.mkdir()
_git(other, "init", "-q")
(other / "o.txt").write_text("1\n")
def effect():
(other / "o.txt").write_text("2\n") # another agent, in the session's checkout
(repo / "f.txt").write_text("z\n")
d = _around(other, f"cd {repo} && python3 fix.py", effect)
assert [r["root"] for r in d["repos"]] == [str(repo)]
def test_within_confines_a_scoped_run(repo, tmp_path):
def run(mode, *within):
ev = {"session_id": "s1", "tool_name": "Bash", "tool_use_id": "w1", "cwd": str(repo),
"tool_input": {"command": "python3 x.py"}}
args = [a for d in within for a in ("--within", str(d))]
p = subprocess.run([sys.executable, HOOK, mode, *args], input=json.dumps(ev),
text=True, capture_output=True, env=os.environ, timeout=30)
return p.stdout
run("pre", tmp_path / "guest") # the repo is outside it
(repo / "f.txt").write_text("leak\n")
assert run("post", tmp_path / "guest") == ""
run("pre", tmp_path) # …and inside this one
(repo / "f.txt").write_text("ok\n")
assert json.loads(run("post", tmp_path))["bashDiff"]["repos"][0]["root"] == str(repo)
def test_absolute_paths_in_a_heredoc_are_snapshotted(repo, tmp_path):
cmd = f"python3 - <<'EOF'\nopen('{repo}/f.txt','w').write('q\\n')\nEOF"
d = _around(tmp_path, cmd, lambda: (repo / "f.txt").write_text("q\n"))
assert d["repos"][0]["root"] == str(repo)
def test_patch_cap_keeps_stats(repo, monkeypatch):
monkeypatch.setenv("BASH_DIFF_MAX_PATCH_BYTES", "64")
d = _around(repo, "python3 gen.py", lambda: (repo / "f.txt").write_text("x\n" * 500))
r = d["repos"][0]
assert r["truncated"] and r["patch"] == ""
assert r["files"][0]["add"] == 500
def test_big_untracked_files_are_not_hashed(repo, tmp_path, monkeypatch):
monkeypatch.setattr(bd, "MAX_UNTRACKED_BYTES", 10)
monkeypatch.setattr(bd, "STATE_ROOT", str(tmp_path / "state-inproc"))
big = repo / "model.bin"
big.write_bytes(b"0" * 100)
state = bd._state_dir("s9")
os.makedirs(state)
r = bd._repos(str(repo), "x")[0]
tree = bd._snapshot(r, state)
out = subprocess.run(["git", "ls-tree", "--name-only", tree], cwd=repo, capture_output=True,
text=True, env={**os.environ, "GIT_OBJECT_DIRECTORY": r["store"],
"GIT_ALTERNATE_OBJECT_DIRECTORIES": r["objects"]})
assert "model.bin" not in out.stdout.split()
def test_concurrent_call_in_the_same_repo_is_flagged(repo):
_run("pre", repo, "make a", tid="toolu_a", session="s1")
_run("pre", repo, "make b", tid="toolu_b", session="s2") # still running
(repo / "f.txt").write_text("changed\n")
d = _run("post", repo, "make a", tid="toolu_a", session="s1")
assert d["repos"][0]["shared"] is True
@pytest.mark.parametrize("cmd,ro", [
("ls -la", True), ("git status && git log --oneline -5", True),
("cd ~/x && grep -rn foo . | head", True), ("sed -n 1,20p f", True),
("rtk git diff", True), ("timeout 30 curl -s http://x | jq .", True),
("ls > /dev/null 2>&1", True), ("cat f 2>&1 | head", True),
("sed -i s/a/b/ f", False), ("echo hi > f.txt", False), ("cmd 2>&1 | tail", False),
("python3 - <<EOF\nx\nEOF", False), ("find . -name x -delete", False),
("npm run build", False), ("curl -o x http://y", False), ("git commit -m x", False),
("echo $(date)", False), ("awk -i inplace 1 f", False), ("make all", False),
("ask-form wait frm_abc --timeout 270", True), ("notify-done 'x' 'y' --final", True),
])
def test_read_only(cmd, ro):
assert bd.read_only(cmd) is ro
# ── commits: none any more (the commits plugin's git shim) ──────────────────
def _run_all(mode, cwd, command, tid="toolu_c", session="s1"):
ev = {"session_id": session, "tool_name": "Bash", "tool_use_id": tid, "cwd": str(cwd),
"tool_input": {"command": command}}
p = subprocess.run([sys.executable, HOOK, mode], input=json.dumps(ev), text=True,
capture_output=True, env=os.environ, timeout=30)
assert p.returncode == 0 and p.stderr == ""
return json.loads(p.stdout) if p.stdout else None
def _around_all(cwd, command, effect, **kw):
assert _run_all("pre", cwd, command, **kw) is None
effect()
return _run_all("post", cwd, command, **kw)
def test_a_commit_prints_no_git_commits_any_more(repo):
"""Commits are the commits plugin's git path shim's since 2026-11-27: the
hook records file changes only (a commit changes none)."""
(repo / "f.txt").write_text("a\nB\nc\n") # edited by an earlier call
def effect():
_git(repo, "commit", "-qm", "feat: capital B", "f.txt")
out = _around_all(repo, "git commit -m 'feat: capital B' f.txt", effect)
assert out is None
def test_a_merge_bringing_files_still_shows_them(repo, tmp_path):
_git(repo, "branch", "side")
_git(repo, "checkout", "-q", "side")
(repo / "s.txt").write_text("old side work\n")
_git(repo, "add", "s.txt")
_git(repo, "commit", "-qm", "old")
_git(repo, "checkout", "-q", "-")
def effect():
_git(repo, "merge", "-q", "--ff-only", "side")
out = _around_all(repo, "git merge --ff-only side", effect)
assert "gitCommits" not in out
assert out["bashDiff"]["repos"][0]["files"][0]["path"] == "s.txt"
def test_a_cd_after_an_export_is_where_the_command_starts(repo, tmp_path):
other = tmp_path / "other"
other.mkdir()
_git(other, "init", "-q")
dirs = bd._candidate_dirs(str(other), f"export PATH=/x:$PATH; cd {repo} && make")
assert dirs[0] == str(repo) and str(other) not in dirs
def test_linked_worktree_names_its_main_checkout(repo, tmp_path):
"""A linked worktree's record carries ``main`` — the hub files the
worktree's work under the repo (backend projects/worker_projects.py)."""
wt = tmp_path / "repo-feature"
_git(repo, "worktree", "add", "-q", str(wt), "-b", "feature")
def effect():
(wt / "f.txt").write_text("a\nchanged\nc\n")
d = _around(wt, "sed -i s/b/changed/ f.txt", effect)
r = d["repos"][0]
assert r["root"] == str(wt)
assert r["main"] == str(repo)
# …and the main checkout itself carries none.
d = _around(repo, "echo y >> f.txt", lambda: (repo / "f.txt").write_text("y\n"),
tid="toolu_2")
assert "main" not in d["repos"][0]
# ── a repo's own config must never run anything (safegit.py) ─────────────────
def _trap(tmp_path, name):
"""A script that leaves a marker when git runs it."""
marker = tmp_path / f"{name}.ran"
script = tmp_path / f"{name}.sh"
script.write_text(f"#!/bin/sh\necho x >> {marker}\ncat\n")
script.chmod(0o755)
return script, marker
def test_a_repos_fsmonitor_filter_hook_and_textconv_never_run(repo, tmp_path):
fsm, fsm_ran = _trap(tmp_path, "fsmonitor")
flt, flt_ran = _trap(tmp_path, "filter")
hook, hook_ran = _trap(tmp_path, "hook")
txt, txt_ran = _trap(tmp_path, "textconv")
ext, ext_ran = _trap(tmp_path, "extdiff")
_git(repo, "config", "core.fsmonitor", str(fsm))
_git(repo, "config", "filter.x.clean", str(flt))
_git(repo, "config", "filter.x.process", str(flt))
_git(repo, "config", "diff.x.textconv", str(txt))
_git(repo, "config", "diff.external", str(ext))
(repo / ".gitattributes").write_text("* filter=x diff=x\n")
hooks = repo / ".git" / "hooks"
hooks.mkdir(exist_ok=True)
for name in ("post-index-change", "pre-commit", "reference-transaction"):
(hooks / name).write_text(hook.read_text())
(hooks / name).chmod(0o755)
def effect():
(repo / "f.txt").write_text("a\nB\nc\n")
(repo / "n.txt").write_text("new\n")
for within in ([], ["--within", str(repo)]):
ev = {"session_id": "s-hostile" + str(len(within)), "tool_name": "Bash",
"tool_use_id": "toolu_h", "cwd": str(repo),
"tool_input": {"command": "sed -i s/b/B/ f.txt && echo new > n.txt"}}
(repo / "f.txt").write_text("a\nb\nc\n")
(repo / "n.txt").unlink(missing_ok=True)
for mode in ("pre", "post"):
p = subprocess.run([sys.executable, HOOK, mode, *within], input=json.dumps(ev),
text=True, capture_output=True, env=os.environ, timeout=30)
assert p.returncode == 0 and p.stderr == ""
if mode == "pre":
effect()
d = json.loads(p.stdout)["bashDiff"]
# the diff is still recorded…
assert {f["path"] for f in d["repos"][0]["files"]} >= {"f.txt", "n.txt"}
assert "+B" in d["repos"][0]["patch"]
# …and nothing the repo's config or hooks name ever ran
for marker in (fsm_ran, flt_ran, hook_ran, txt_ran, ext_ran):
assert not marker.exists(), marker.name
def test_a_nested_repos_config_never_runs_either(repo, tmp_path):
"""`git init sub && git -C sub config …` in the same command: the nested
repo is neither snapshotted as a gitlink nor entered by a `git status`."""
flt, flt_ran = _trap(tmp_path, "subfilter")
fsm, fsm_ran = _trap(tmp_path, "subfsmonitor")
sub = repo / "sub"
sub.mkdir()
_git(sub, "init", "-q")
_git(sub, "config", "user.email", "t@t")
_git(sub, "config", "user.name", "t")
(sub / "a.txt").write_text("a\n")
_git(sub, "add", ".")
_git(sub, "commit", "-qm", "sub")
_git(sub, "config", "filter.x.clean", str(flt))
_git(sub, "config", "core.fsmonitor", str(fsm))
(sub / ".gitattributes").write_text("* filter=x\n")
# registered as a submodule entry in the real index, the worst case
_git(repo, "add", "sub")
def effect():
(sub / "a.txt").write_text("changed\n")
(repo / "f.txt").write_text("a\nB\nc\n")
d = _around(repo, "sed -i s/b/B/ f.txt && echo changed > sub/a.txt", effect,
session="s-nested")
assert [f["path"] for f in d["repos"][0]["files"]] == ["f.txt"]
assert not flt_ran.exists() and not fsm_ran.exists()
def test_git_env_drops_the_callers_git_variables(monkeypatch):
import safegit
monkeypatch.setenv("GIT_EXTERNAL_DIFF", "/tmp/x")
monkeypatch.setenv("GIT_DIR", "/elsewhere")
monkeypatch.setenv("GIT_CONFIG_COUNT", "1")
env = safegit.env()
assert not {"GIT_EXTERNAL_DIFF", "GIT_DIR", "GIT_CONFIG_COUNT"} & set(env)
assert env["GIT_OPTIONAL_LOCKS"] == "0"
assert safegit.argv(["show", "abc"])[-4:] == ["--no-ext-diff", "--no-textconv",
"--submodule=short", "abc"]
assert "core.fsmonitor=false" in safegit.argv(["add", "-u"])
# only allowed values of the few work-tree keys survive into a private git dir
keep = safegit.parse_safe_config(b"core.autocrlf\ninput\0core.fsmonitor\n/x.sh\0"
b"core.eol\n$(id)\0core.filemode\nfalse\0")
assert keep == {"core.autocrlf": "input", "core.filemode": "false"}