`bashDiff.paths` lets a tool group count distinct files across Bash diffs and Edit/Write targets (the same file through Edit and `sed -i` counts once). Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
199 lines
9.9 KiB
Python
199 lines
9.9 KiB
Python
"""conversations.bashdiff: a Bash call's on-disk changes land on its tool card —
|
|
from the ai-agent hook's ``hook_success`` attachment (exact, wins), else from
|
|
Claude Code's own ``toolUseResult.bashEditDiff`` (skipped when ``shared``).
|
|
``python3 -m unittest test_bashdiff``"""
|
|
|
|
import json
|
|
import pathlib
|
|
import tempfile
|
|
import unittest
|
|
|
|
from conversations.parse import parse_conversation
|
|
|
|
SID = "11111111-2222-3333-4444-555555555555"
|
|
CWD = "/home/u/homelab"
|
|
PATCH = ("diff --git a/f.txt b/f.txt\nindex de98044..7be73ce 100644\n--- a/f.txt\n+++ b/f.txt\n"
|
|
"@@ -1,3 +1,3 @@\n a\n-b\n+B\n c\n"
|
|
"diff --git a/n.txt b/n.txt\nnew file mode 100644\nindex 0000000..3e75765\n"
|
|
"--- /dev/null\n+++ b/n.txt\n@@ -0,0 +1 @@\n+new\n")
|
|
HOOK = {"bashDiff": {"v": 1, "add": 3, "del": 1, "ms": 61, "repos": [{
|
|
"root": "/home/u/worktrees/x", "from": "a" * 40, "to": "b" * 40, "patch": PATCH,
|
|
"truncated": True, "files": [
|
|
{"path": "f.txt", "status": "modified", "add": 1, "del": 1, "binary": False},
|
|
{"path": "n.txt", "status": "added", "add": 1, "del": 0, "binary": False},
|
|
{"path": "package-lock.json", "status": "modified", "add": 1, "del": 0, "binary": False},
|
|
]}]}}
|
|
BUILTIN = {"files": [{"filePath": f"{CWD}/README.md", "hunks": [
|
|
{"oldStart": 4, "oldLines": 2, "newStart": 4, "newLines": 3,
|
|
"lines": [" keep", "-old", "+new", "+more"]}]}], "moreFiles": 2}
|
|
|
|
|
|
def _rec(**kw):
|
|
return {"sessionId": SID, "cwd": CWD, "timestamp": "2026-10-19T10:00:00.000Z", **kw}
|
|
|
|
|
|
def _call(tid, cmd):
|
|
return [
|
|
_rec(type="assistant", message={"role": "assistant", "model": "claude-opus-5-5", "content": [
|
|
{"type": "tool_use", "id": tid, "name": "Bash", "input": {"command": cmd}}]}),
|
|
]
|
|
|
|
|
|
def _result(tid, tur=None):
|
|
r = _rec(type="user", message={"role": "user", "content": [
|
|
{"type": "tool_result", "tool_use_id": tid, "content": "ok"}]})
|
|
if tur is not None:
|
|
r["toolUseResult"] = tur
|
|
return r
|
|
|
|
|
|
def _hook(tid, stdout):
|
|
return _rec(type="attachment", attachment={
|
|
"type": "hook_success", "hookName": "PostToolUse:Bash", "toolUseID": tid,
|
|
"hookEvent": "PostToolUse", "content": "", "stdout": stdout, "exitCode": 0})
|
|
|
|
|
|
def _thread(records):
|
|
d = pathlib.Path(tempfile.mkdtemp())
|
|
p = d / f"{SID}.jsonl"
|
|
p.write_text("".join(json.dumps(r) + "\n" for r in records))
|
|
return {it.get("toolUseId"): it for it in parse_conversation(p, full=True)["thread"]
|
|
if it.get("kind") == "tool_use"}
|
|
|
|
|
|
class BashDiffOnCards(unittest.TestCase):
|
|
def test_hook_attachment(self):
|
|
items = _thread([*_call("t1", "cd ~/worktrees/x && sed -i s/b/B/ f.txt"),
|
|
_result("t1", {"stdout": "", "stderr": ""}),
|
|
_hook("t1", json.dumps(HOOK))])
|
|
d = items["t1"]["bashDiff"]
|
|
self.assertEqual((d["source"], d["additions"], d["deletions"], d["fileCount"]),
|
|
("hook", 3, 1, 3))
|
|
self.assertEqual(d["ms"], 61)
|
|
self.assertEqual(d["paths"], ["/home/u/worktrees/x/f.txt", "/home/u/worktrees/x/n.txt",
|
|
"/home/u/worktrees/x/package-lock.json"])
|
|
f, n, lock = d["files"]
|
|
self.assertEqual([ln["type"] for ln in f["hunks"][0]["lines"]], ["ctx", "del", "add", "ctx"])
|
|
self.assertEqual(n["status"], "added")
|
|
# No hunks shipped for it → the card says so instead of showing nothing.
|
|
self.assertTrue(lock["truncated"])
|
|
self.assertEqual(lock["hunks"], [])
|
|
self.assertTrue(d["truncated"])
|
|
|
|
def test_hook_wins_over_builtin(self):
|
|
items = _thread([*_call("t1", "sed -i x README.md"),
|
|
_result("t1", {"stdout": "", "bashEditDiff": BUILTIN}),
|
|
_hook("t1", json.dumps(HOOK))])
|
|
self.assertEqual(items["t1"]["bashDiff"]["source"], "hook")
|
|
|
|
def test_builtin_fallback(self):
|
|
items = _thread([*_call("t1", "sed -i x README.md"),
|
|
_result("t1", {"stdout": "", "bashEditDiff": BUILTIN})])
|
|
d = items["t1"]["bashDiff"]
|
|
self.assertEqual((d["source"], d["additions"], d["deletions"]), ("claude", 2, 1))
|
|
self.assertEqual(d["files"][0]["path"], "README.md") # relative to the record's cwd
|
|
self.assertEqual(d["fileCount"], 3) # + moreFiles
|
|
self.assertEqual(d["paths"], [f"{CWD}/README.md"])
|
|
self.assertEqual(d["files"][0]["hunks"][0]["lines"][2], {
|
|
"type": "add", "oldNo": None, "newNo": 5, "text": "new"})
|
|
|
|
def test_builtin_shared_or_empty_is_dropped(self):
|
|
items = _thread([*_call("t1", "make"), _result("t1", {"stdout": "", "bashEditDiff": {
|
|
**BUILTIN, "shared": True}}),
|
|
*_call("t2", "make"), _result("t2", {"stdout": "", "bashEditDiff": {
|
|
"files": [], "moreFiles": 0}})])
|
|
self.assertNotIn("bashDiff", items["t1"])
|
|
self.assertNotIn("bashDiff", items["t2"])
|
|
|
|
def test_other_hook_output_is_ignored(self):
|
|
rtk = json.dumps({"hookSpecificOutput": {"hookEventName": "PreToolUse",
|
|
"updatedInput": {"command": "rtk ls"}}})
|
|
items = _thread([*_call("t1", "ls"), _result("t1"), _hook("t1", rtk),
|
|
_hook("t1", "not json {\"bashDiff\"")])
|
|
self.assertNotIn("bashDiff", items["t1"])
|
|
|
|
def test_multi_repo_paths_are_prefixed(self):
|
|
two = json.loads(json.dumps(HOOK))
|
|
r2 = {**two["bashDiff"]["repos"][0], "root": "/home/u/projects/zipgo", "patch": "",
|
|
"truncated": False,
|
|
"files": [{"path": "README.md", "status": "modified", "add": 2, "del": 0,
|
|
"binary": False}]}
|
|
two["bashDiff"]["repos"].append(r2)
|
|
items = _thread([*_call("t1", "x"), _result("t1"), _hook("t1", json.dumps(two))])
|
|
paths = [f["path"] for f in items["t1"]["bashDiff"]["files"]]
|
|
self.assertEqual(paths, ["x/f.txt", "x/n.txt", "x/package-lock.json", "zipgo/README.md"])
|
|
|
|
|
|
class BashDiffInTheReplay(unittest.TestCase):
|
|
"""The /diff page's uncommitted replay (diff.editsdiff) folds the hook's
|
|
hunks in: applied onto a content it already knows, verbatim otherwise."""
|
|
|
|
def _replay(self, records):
|
|
from diff.editsdiff import uncommitted_diff
|
|
d = pathlib.Path(tempfile.mkdtemp())
|
|
p = d / f"{SID}.jsonl"
|
|
p.write_text("".join(json.dumps(r) + "\n" for r in records))
|
|
return {f["path"]: f for f in uncommitted_diff(p, "t", [])["files"]}
|
|
|
|
def _hook_rec(self, tid, files, patch):
|
|
payload = {"bashDiff": {"v": 1, "add": 0, "del": 0, "repos": [{
|
|
"root": "/home/u/homelab", "from": "a", "to": "b", "patch": patch,
|
|
"truncated": False, "files": files}]}}
|
|
return _hook(tid, json.dumps(payload))
|
|
|
|
def test_hunks_apply_onto_a_written_file(self):
|
|
write = _rec(type="user", message={"role": "user", "content": [
|
|
{"type": "tool_result", "tool_use_id": "w", "content": "ok"}]},
|
|
toolUseResult={"type": "create", "filePath": "/home/u/homelab/services/x/app.yml",
|
|
"content": "name: demo\nport: 8080\n", "structuredPatch": []})
|
|
patch = ("diff --git a/services/x/app.yml b/services/x/app.yml\n--- a/services/x/app.yml\n"
|
|
"+++ b/services/x/app.yml\n@@ -1,2 +1,3 @@\n name: demo\n-port: 8080\n"
|
|
"+port: 9090\n+tls: true\n")
|
|
files = self._replay([write, self._hook_rec("t1", [
|
|
{"path": "services/x/app.yml", "status": "modified", "add": 2, "del": 1}], patch)])
|
|
f = files["services/x/app.yml"]
|
|
self.assertEqual(f["status"], "added") # created this conversation
|
|
self.assertEqual([ln["text"] for h in f["hunks"] for ln in h["lines"]],
|
|
["name: demo", "port: 9090", "tls: true"])
|
|
|
|
def test_unknown_content_keeps_the_hunks_and_deletes_count(self):
|
|
patch = ("diff --git a/README.md b/README.md\n--- a/README.md\n+++ b/README.md\n"
|
|
"@@ -3,2 +3,2 @@\n keep\n-old\n+new\n")
|
|
files = self._replay([self._hook_rec("t1", [
|
|
{"path": "README.md", "status": "modified", "add": 1, "del": 1},
|
|
{"path": "services/x/gone.txt", "status": "deleted", "add": 0, "del": 3}], patch)])
|
|
self.assertEqual(files["README.md"]["status"], "modified")
|
|
self.assertEqual((files["README.md"]["additions"], files["README.md"]["deletions"]), (1, 1))
|
|
self.assertEqual(files["services/x/gone.txt"]["status"], "deleted")
|
|
|
|
|
|
class BashDiffTags(unittest.TestCase):
|
|
def test_hook_files_tag_projects_and_services(self):
|
|
d = pathlib.Path(tempfile.mkdtemp())
|
|
p = d / f"{SID}.jsonl"
|
|
payload = {"bashDiff": {"v": 1, "add": 1, "del": 0, "repos": [
|
|
{"root": "/home/u/homelab", "from": "a", "to": "b", "patch": "", "truncated": True,
|
|
"files": [{"path": "services/zipgo/traefik.yml", "status": "modified", "add": 1,
|
|
"del": 0}]},
|
|
{"root": "/home/u/projects/gabvdl", "from": "a", "to": "b", "patch": "",
|
|
"truncated": True,
|
|
"files": [{"path": "src/main.ts", "status": "modified", "add": 1, "del": 0}]}]}}
|
|
recs = [*_call("t1", "x"), _result("t1"), _hook("t1", json.dumps(payload))]
|
|
p.write_text("".join(json.dumps(r) + "\n" for r in recs))
|
|
s = parse_conversation(p) # the cheap rollup tags too
|
|
self.assertIn("zipgo", s["servicesAuto"])
|
|
self.assertIn("gabvdl", s["projectsAuto"])
|
|
|
|
def test_builtin_diff_never_tags(self):
|
|
d = pathlib.Path(tempfile.mkdtemp())
|
|
p = d / f"{SID}.jsonl"
|
|
bed = {"files": [{"filePath": "/home/u/homelab/services/zipgo/x.yml", "hunks": []}],
|
|
"moreFiles": 0}
|
|
recs = [*_call("t1", "x"), _result("t1", {"stdout": "", "bashEditDiff": bed})]
|
|
p.write_text("".join(json.dumps(r) + "\n" for r in recs))
|
|
self.assertNotIn("zipgo", parse_conversation(p)["servicesAuto"])
|
|
|
|
|
|
if __name__ == "__main__":
|
|
unittest.main()
|