Files
gabrielvidalandClaude Opus 5.5 0fa0de88ef fix(commits): no commit list from a hook updated mid-call; pushes match short shas
The merge that shipped the hook ran its pre with the old one: no HEAD noted,
and post took all history as new. The hook now skips such a call and the
parser drops a recorded commit dated before its Bash call (parser v36). A push
marks a commit known by its abbreviated sha too.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 20:53:23 +02:00

186 lines
8.1 KiB
Python

"""The commits a conversation made, as the transcript records them.
Two sources, both already in the transcript — the runner's repo is never
needed to *list* them, so a worker's commits show while the Mac sleeps:
- **The ai-agent's Bash hook** (``sidecar/bash_diff.py``): when a call moved a
repo's ``HEAD`` it adds ``{"gitCommits": {…}}`` to the ``hook_success``
attachment — every commit the call created (what a pull or a rebase brought
in from elsewhere is left out), its files, its patch (capped) and the
remote-tracking refs a push moved. Exact; ``source: "hook"``.
- **git's own commit line** in a Bash result, ``[branch abc1234] subject``
(terminal sessions, transcripts from before the hook, a runner whose
sidecar predates it). The sha and the subject only; ``source: "output"``.
rtk rewrites ``git commit``'s output on the lab, so there it rarely
fires — the hook is what counts there.
The same commit recorded twice (a hook and a line, a commit seen again by a
later merge) is kept once, the hook's record winning.
"""
from __future__ import annotations
import json
import re
from diff.gitdiff import _parse_unified_diff
# `[main abc1234] subject`, `[feat/x (root-commit) abc1234] subject`; a
# detached HEAD reads `[detached HEAD abc1234]`.
_OUTPUT_RE = re.compile(
r"^\[(?P<branch>detached HEAD|[^\]\s]+)(?: \(root-commit\))? (?P<sha>[0-9a-f]{7,40})\] "
r"(?P<subject>.+)$", re.M)
_STAT_RE = re.compile(r"(\d+) files? changed(?:, (\d+) insertions?\(\+\))?"
r"(?:, (\d+) deletions?\(-\))?")
# Per commit in the stored summary: enough for the list, never the patch.
_MAX_FILES = 200
def load_hook(stdout: str) -> dict | None:
"""The hook's ``gitCommits`` payload out of its stdout, or None."""
if not stdout or '"gitCommits"' not in stdout:
return None
try:
d = json.loads(stdout).get("gitCommits")
except (ValueError, AttributeError):
return None
return d if isinstance(d, dict) and d.get("v") == 1 else None
def _file_stat(f: dict) -> dict:
return {"path": str(f.get("path") or ""),
"status": f.get("status") if f.get("status") in ("added", "deleted") else "modified",
"additions": int(f.get("add") or 0), "deletions": int(f.get("del") or 0),
"binary": bool(f.get("binary"))}
def from_hook(d: dict, *, tool_use_id: str | None = None, ts: str | None = None) -> list[dict]:
"""The hook's payload → one record per commit (no patch: see ``file_diffs``)."""
out: list[dict] = []
for r in d.get("repos") or []:
if not isinstance(r, dict):
continue
pushed = {p.get("sha") for p in r.get("pushed") or [] if isinstance(p, dict)}
for c in r.get("commits") or []:
if not isinstance(c, dict) or not c.get("sha"):
continue
files = [_file_stat(f) for f in c.get("files") or [] if isinstance(f, dict)]
parents = [p for p in c.get("parents") or [] if isinstance(p, str)]
out.append({
"sha": c["sha"], "short": c.get("short") or c["sha"][:7],
"subject": c.get("subject") or "", "author": c.get("author"),
"date": c.get("date") or ts, "branch": c.get("branch") or r.get("branch"),
"parents": parents, "merge": len(parents) > 1,
"root": r.get("root"),
"additions": int(c.get("add") or 0), "deletions": int(c.get("del") or 0),
"files": len(files), "fileStats": files[:_MAX_FILES],
"truncated": bool(c.get("truncated")),
"shared": bool(r.get("shared")),
"pushed": c["sha"] in pushed,
"source": "hook", "toolUseId": tool_use_id,
})
return out
def pushed_refs(d: dict) -> list[dict]:
"""``[{root, ref, sha}]`` — the remote-tracking refs a call moved."""
return [{"root": r.get("root"), "ref": p.get("ref"), "sha": p.get("sha")}
for r in d.get("repos") or [] if isinstance(r, dict)
for p in r.get("pushed") or [] if isinstance(p, dict) and p.get("sha")]
_LOG_LINE_RE = re.compile(r"^(?P<sha>[0-9a-f]{7,40}) (?P<subject>\S.*)$", re.M)
def from_output(text: str, *, cwd: str | None = None, tool_use_id: str | None = None,
ts: str | None = None, log_one: bool = False) -> list[dict]:
"""git's ``[branch sha] subject`` lines in a Bash result → records. With
``log_one`` (the command committed, then ran ``git log -1``) a lone
``sha subject`` line counts too."""
if not text:
return []
if log_one and not _OUTPUT_RE.search(text):
lines = _LOG_LINE_RE.findall(text)
if len(lines) == 1:
text = f"[detached HEAD {lines[0][0]}] {lines[0][1]}"
if "] " not in text:
return []
out = []
for m in _OUTPUT_RE.finditer(text):
branch = m.group("branch")
add = dele = files = 0
st = _STAT_RE.search(text, m.end(), m.end() + 400)
if st:
files, add, dele = (int(g or 0) for g in st.groups())
out.append({
"sha": m.group("sha"), "short": m.group("sha")[:10],
"subject": m.group("subject").strip(), "author": None, "date": ts,
"branch": None if branch == "detached HEAD" else branch,
"parents": [], "merge": m.group("subject").startswith("Merge "),
"root": None, "cwd": cwd,
"additions": add, "deletions": dele, "files": files, "fileStats": [],
"truncated": True, "shared": False, "pushed": False,
"source": "output", "toolUseId": tool_use_id,
})
return out
def same(a: str, b: str) -> bool:
"""Two (possibly abbreviated) shas name the same commit."""
n = min(len(a), len(b))
return n >= 7 and a[:n] == b[:n]
def add(into: list[dict], found: list[dict]) -> None:
"""Fold ``found`` into ``into`` (oldest first), once per commit — the
hook's record replaces a commit line's, never the reverse."""
for c in found:
hit = next((i for i, o in enumerate(into) if same(o["sha"], c["sha"])), None)
if hit is None:
into.append(c)
elif into[hit]["source"] == "output" and c["source"] == "hook":
into[hit] = {**c, "toolUseId": into[hit].get("toolUseId") or c.get("toolUseId")}
elif c.get("pushed"):
into[hit]["pushed"] = True
def mark_pushed(commits: list[dict], refs: list[dict]) -> None:
"""A push moved ``origin/<branch>`` to a sha this conversation made → that
commit and the ones before it on the same branch are pushed. A merge's
second parent carries its branch's commits along. Shas may be abbreviated
(git's commit line), so they match by prefix."""
def find(sha: str) -> dict | None:
return next((c for c in commits if sha and same(c["sha"], sha)), None)
for ref in refs:
todo = [find(ref.get("sha") or "")]
while todo:
c = todo.pop()
if c is None or c.get("pushed") is True and c.get("_seen"):
continue
c["pushed"], c["_seen"] = True, True
todo += [find(p) for p in c.get("parents") or []]
for c in commits:
c.pop("_seen", None)
def file_diffs(d: dict, sha: str) -> list[dict] | None:
"""One commit's ``FileDiff``s out of a hook payload (the /diff hunk model),
or None when that payload doesn't carry it."""
for r in d.get("repos") or []:
for c in (r or {}).get("commits") or []:
if not isinstance(c, dict) or not same(str(c.get("sha") or ""), sha):
continue
hunks = {f["path"]: f for f in _parse_unified_diff(c.get("patch") or "")}
files = []
for f in c.get("files") or []:
st = _file_stat(f)
parsed = hunks.get(st["path"])
files.append({**st, "oldPath": None,
"truncated": parsed is None and not st["binary"]
and (st["additions"] + st["deletions"]) > 0
and len(c.get("parents") or []) < 2,
"hunks": parsed["hunks"] if parsed else []})
return files
return None