Files
ai-agent/backend/test_conv_commits.py
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

129 lines
5.9 KiB
Python

"""A conversation's own commits: the Bash hook's ``gitCommits`` record (exact,
patch included), git's ``[branch sha]`` line as the fallback, pushes marking
them pushed, and the net diff split into runs of consecutive commits.
``python3 -m unittest test_conv_commits``"""
import json
import pathlib
import tempfile
import unittest
from conversations import commits as gitcommits
from conversations.parse import parse_conversation
from diff import convcommits
SID = "11111111-2222-3333-4444-555555555555"
CWD = "/Users/g/WORK/orus"
A, B, M = "a" * 40, "b" * 40, "c" * 40
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")
def _commit(sha, parents, subject, patch="", files=None, truncated=False):
return {"sha": sha, "short": sha[:10], "parents": parents, "date": "2026-10-22T10:00:00+02:00",
"author": "g", "subject": subject, "branch": "feat", "add": 1, "del": 1,
"files": files if files is not None else
[{"path": "f.txt", "status": "modified", "add": 1, "del": 1, "binary": False}],
"patch": patch, "truncated": truncated}
def _gc(*commits, pushed=None, root=f"{CWD}/.claude/worktrees/feat"):
return {"gitCommits": {"v": 1, "ms": 12, "repos": [{
"root": root, "branch": "feat", "head": commits[-1]["sha"] if commits else None,
"commits": list(commits), "pushed": pushed or []}]}}
def _rec(**kw):
return {"sessionId": SID, "cwd": CWD, "timestamp": "2026-10-22T08:00:00.000Z", **kw}
def _call(tid, cmd, out="ok", hook=None):
recs = [
_rec(type="assistant", message={"role": "assistant", "model": "claude-opus-5-5", "content": [
{"type": "tool_use", "id": tid, "name": "Bash", "input": {"command": cmd}}]}),
_rec(type="user", message={"role": "user", "content": [
{"type": "tool_result", "tool_use_id": tid, "content": out}]}),
]
if hook is not None:
recs.append(_rec(type="attachment", attachment={
"type": "hook_success", "hookName": "PostToolUse:Bash", "toolUseID": tid,
"hookEvent": "PostToolUse", "content": "", "stdout": json.dumps(hook), "exitCode": 0}))
return recs
def _parse(records, full=False):
d = pathlib.Path(tempfile.mkdtemp())
p = d / f"{SID}.jsonl"
p.write_text("".join(json.dumps(r) + "\n" for r in records))
return parse_conversation(p, full=full), p
class HookRecord(unittest.TestCase):
def test_hook_commits_are_listed_and_carded(self):
recs = _call("t1", "git commit -m one", hook=_gc(_commit(A, ["0" * 40], "one", PATCH)))
recs += _call("t2", "git commit -m two && git push origin feat",
hook=_gc(_commit(B, [A], "two", PATCH),
pushed=[{"ref": "origin/feat", "sha": B}]))
s, _ = _parse(recs)
cs = s["commitsAuto"]
self.assertEqual([c["subject"] for c in cs], ["one", "two"])
self.assertTrue(all(c["source"] == "hook" for c in cs))
# the push of B carries A (its parent) along
self.assertEqual([c["pushed"] for c in cs], [True, True])
self.assertEqual(s["commitCalls"], 2)
full, _ = _parse(recs, full=True)
card = next(it for it in full["thread"] if it.get("toolUseId") == "t1")
[c] = card["commits"]
self.assertEqual(c["diffFiles"][0]["hunks"][0]["lines"][1]["text"], "b")
def test_commits_dated_before_the_call_are_dropped(self):
old = {**_commit(A, ["0" * 40], "someone else's, hours ago"), "date": "2026-10-22T07:00:00+02:00"}
new = {**_commit(B, [A], "this call's"), "date": "2026-10-22T10:00:01+02:00"}
s, _ = _parse(_call("t1", "git merge feat", hook=_gc(old, new)))
self.assertEqual([c["subject"] for c in s["commitsAuto"]], ["this call's"])
def test_git_commit_line_is_the_fallback_and_the_hook_wins(self):
out = "[feat 1234567abc] fix: thing\n 2 files changed, 5 insertions(+), 1 deletion(-)"
s, _ = _parse(_call("t1", "git commit -m 'fix: thing'", out=out))
[c] = s["commitsAuto"]
self.assertEqual((c["source"], c["branch"], c["additions"], c["files"]),
("output", "feat", 5, 2))
hooked = _commit("1234567abc" + "d" * 30, [A], "fix: thing", PATCH)
s, _ = _parse(_call("t1", "git commit -m 'fix: thing'", out=out, hook=_gc(hooked)))
[c] = s["commitsAuto"]
self.assertEqual(c["source"], "hook")
def test_quiet_commit_then_log_one(self):
s, _ = _parse(_call("t1", "git commit -qm x && git log --oneline -1",
out="9eeb7b4a81 chore: track it"))
self.assertEqual([c["sha"] for c in s["commitsAuto"]], ["9eeb7b4a81"])
# a longer log is not this call's commit list
s, _ = _parse(_call("t1", "git commit -qm x && git log --oneline -3",
out="9eeb7b4a81 a\n371de371f1 b\n1bbd85c6e5 c"))
self.assertEqual(s["commitsAuto"], [])
def test_a_log_read_is_not_a_commit(self):
s, _ = _parse(_call("t1", "cat build.log", out="[main 1234567] looks like a commit"))
self.assertEqual((s["commitsAuto"], s["commitCalls"]), ([], 0))
class Runs(unittest.TestCase):
def test_consecutive_commits_form_one_run_merges_are_dropped(self):
def c(sha, parents, branch="feat", merge=False):
return {"sha": sha, "parents": parents, "branch": branch, "merge": merge,
"root": "/r", "repo": None}
newest_first = [c(M, [B, "x"], branch="main", merge=True), c(B, [A]), c(A, ["0"]),
c("e" * 40, ["z"])]
runs = convcommits.runs(newest_first)
self.assertEqual([[x["sha"] for x in r] for r in runs], [["e" * 40], [A, B]])
class Same(unittest.TestCase):
def test_abbreviated_shas(self):
self.assertTrue(gitcommits.same("1234567abc", "1234567abcdef"))
self.assertFalse(gitcommits.same("123456", "1234567"))
if __name__ == "__main__":
unittest.main()