Files
gabrielvidalandClaude Opus 5.5 31d25f7ea3 feat(conversations): a Bash diff carries every changed file's absolute path
`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>
2026-10-19 16:37:48 +02:00

163 lines
6.9 KiB
Python

"""What a Bash call changed on disk, as the tool card's ``bashDiff``.
Two sources, both already in the transcript — nothing is re-read from disk:
- **The ai-agent's hook** (``sidecar/bash_diff.py``): a ``PostToolUse:Bash``
hook whose stdout, ``{"bashDiff": {…}}``, Claude Code keeps as a
``hook_success`` attachment carrying the call's ``toolUseID`` (and never
shows the model). Exact: a git snapshot of the repo the command ran in,
before and after, with the unified patch embedded (capped).
- **Claude Code's own** ``toolUseResult.bashEditDiff`` (v2.1.278+): computed
on a few percent of calls, for the session cwd's checkout only, hunks for at
most five files. Used only when the hook left nothing for that call and the
CLI didn't flag it ``shared`` (another call ran in the repo meanwhile — its
files are then someone else's as often as not). It is the only record older
conversations have.
Both come out as the same view: totals, and one ``FileDiff`` per file (the
/diff page's hunk model, so the card reuses its renderer).
"""
from __future__ import annotations
import json
import os
from diff.gitdiff import _parse_unified_diff
# A single tool card shouldn't carry the /diff page's per-file budget.
_MAX_FILES = 60
def _view(files: list[dict], *, source: str, shared: bool, truncated: bool,
ms: int | None, paths: list[str], more: int = 0) -> dict | None:
if not files:
return None
return {
"paths": paths,
"source": source,
"additions": sum(f["additions"] for f in files),
"deletions": sum(f["deletions"] for f in files),
"fileCount": len(files) + more,
"files": files[:_MAX_FILES],
"truncated": truncated or more > 0 or len(files) > _MAX_FILES,
"shared": shared,
"ms": ms,
}
def load_hook(stdout: str) -> dict | None:
"""The hook's ``bashDiff`` payload out of its stdout, or None."""
if not stdout or '"bashDiff"' not in stdout:
return None
try:
d = json.loads(stdout).get("bashDiff")
except (ValueError, AttributeError):
return None
return d if isinstance(d, dict) and d.get("v") == 1 else None
def changed_paths(d: dict) -> list[str]:
"""Absolute paths of every file a hook payload says changed — what the
project/service auto-tags and the /diff replay key on. (Only the hook's:
the CLI's own diff can carry another agent's files.)"""
return [os.path.join(str(r.get("root") or ""), str(f.get("path") or ""))
for r in d.get("repos") or [] if isinstance(r, dict)
for f in r.get("files") or [] if isinstance(f, dict) and f.get("path")]
def from_hook(stdout: str | dict) -> dict | None:
"""The hook's stdout (or its loaded payload) → the card view."""
d = load_hook(stdout) if isinstance(stdout, str) else stdout
if not d:
return None
repos = [r for r in d.get("repos") or [] if isinstance(r, dict)]
multi = len(repos) > 1
files: list[dict] = []
truncated = shared = False
for r in repos:
root = str(r.get("root") or "")
prefix = f"{os.path.basename(root)}/" if multi else ""
hunks = {f["path"]: f for f in _parse_unified_diff(r.get("patch") or "")}
truncated |= bool(r.get("truncated"))
shared |= bool(r.get("shared"))
for f in r.get("files") or []:
path = str(f.get("path") or "")
parsed = hunks.get(path)
add, dele = int(f.get("add") or 0), int(f.get("del") or 0)
files.append({
"path": prefix + path,
"oldPath": None,
"status": f.get("status") if f.get("status") in ("added", "deleted") else "modified",
"additions": add,
"deletions": dele,
"binary": bool(f.get("binary")),
# Lines changed but no hunks shipped (the cap, a lockfile).
"truncated": parsed is None and not f.get("binary") and (add + dele) > 0,
"hunks": parsed["hunks"] if parsed else [],
"repo": None,
})
ms = d.get("ms")
return _view(files, source="hook", shared=shared, truncated=truncated,
ms=ms if isinstance(ms, int) else None, paths=changed_paths(d))
def _rel(path: str, cwd: str | None) -> str:
if cwd and path.startswith(cwd.rstrip("/") + "/"):
return path[len(cwd.rstrip("/")) + 1:]
home = os.path.expanduser("~")
return "~" + path[len(home):] if path.startswith(home + "/") else path
def from_builtin(bed: object, cwd: str | None = None) -> dict | None:
"""Claude Code's ``toolUseResult.bashEditDiff`` → the card view."""
if not isinstance(bed, dict) or bed.get("shared") or bed.get("unavailable"):
return None
files: list[dict] = []
for f in bed.get("files") or []:
if not isinstance(f, dict) or not f.get("filePath"):
continue
hunks, add, dele = [], 0, 0
for h in f.get("hunks") or []:
old_no, new_no = int(h.get("oldStart") or 0), int(h.get("newStart") or 0)
lines = []
for ln in h.get("lines") or []:
tag, text = (ln[:1], ln[1:]) if isinstance(ln, str) else (" ", "")
if tag == "+":
lines.append({"type": "add", "oldNo": None, "newNo": new_no, "text": text})
new_no += 1
add += 1
elif tag == "-":
lines.append({"type": "del", "oldNo": old_no, "newNo": None, "text": text})
old_no += 1
dele += 1
elif tag != "\\":
lines.append({"type": "ctx", "oldNo": old_no, "newNo": new_no, "text": text})
old_no += 1
new_no += 1
hunks.append({
"header": f"@@ -{h.get('oldStart')},{h.get('oldLines')} "
f"+{h.get('newStart')},{h.get('newLines')} @@",
"oldStart": int(h.get("oldStart") or 0), "oldLines": int(h.get("oldLines") or 0),
"newStart": int(h.get("newStart") or 0), "newLines": int(h.get("newLines") or 0),
"lines": lines,
})
files.append({
"path": _rel(str(f["filePath"]), cwd),
"oldPath": None,
"status": "added" if f.get("created") else "deleted" if f.get("deleted") else "modified",
"additions": add,
"deletions": dele,
"binary": False,
"truncated": not hunks,
"hunks": hunks,
"repo": None,
})
more = int(bed.get("moreFiles") or 0)
# `changedFiles` (newer CLIs) lists them all, past the five with hunks.
paths = [p for p in bed.get("changedFiles") or [] if isinstance(p, str)] \
or [str(f["filePath"]) for f in bed.get("files") or []
if isinstance(f, dict) and f.get("filePath")]
return _view(files, source="claude", shared=False, truncated=False, ms=None,
more=more, paths=paths)