conversations/parse.py (2,449 lines) becomes conversations/parse/:
records (JSONL records, timestamps, clipped blocks, _item), usertext (inbox /
cancel / relay / author / held / slash / skill / image / compact text), tools
(buckets, sub-labels, project / service / worktree / commit evidence,
lifecycle + deploys), errors (API-error kinds, limit resets), usage (delta /
estimate / cost-state helpers), turns (turn-end records), state
(ParserState + parse_conversation, unchanged) and cut (find_cut_line).
Code moved verbatim. The package re-exports every name the module had, and
its __all__ is exactly what `from .parse import *` exported before, so the
`conversations` namespace is identical (checked name by name).
Verified against 57a4d8ee: parse-ab 500 files x 2 modes 0 differing,
--chunked 0 mismatches, pricing-dump identical, test_parse_fixtures OK.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
659 lines
28 KiB
Python
659 lines
28 KiB
Python
#!/usr/bin/env python3
|
||
"""Claude Code ``PreToolUse``/``PostToolUse`` hook pair for ``Bash``: record
|
||
what a shell command changed on disk, so the viewer can show ``+A −D`` and the
|
||
diff under a Bash card the way it does under an Edit card.
|
||
|
||
Why a hook. An Edit/Write call carries its own diff in the transcript; a
|
||
``sed -i`` or a ``python3 - <<EOF`` rewrite carries nothing — Claude Code's
|
||
file-history checkpoints don't track Bash either. The only moment the change
|
||
is knowable is around the call itself.
|
||
|
||
How. Before the command (``pre``) the working tree of every git repo the
|
||
command can touch — where it starts (its leading ``cd``, else the session
|
||
cwd), any later ``cd`` target, any absolute path it names — is snapshotted to a tree object; after it (``post``) it
|
||
is snapshotted again and the two trees are diffed. A snapshot is
|
||
``git add`` + ``git write-tree`` into a **private index** (a copy of the repo's
|
||
own index, kept per session so its stat cache stays warm) and a **private
|
||
object store** (``GIT_OBJECT_DIRECTORY``, with the repo's own objects as an
|
||
alternate, so what the repo already has is reused, never copied). Nothing is
|
||
written into the repo's ``.git`` — not the index, not HEAD or refs, not a
|
||
loose object — and both private pieces live in this session's state dir,
|
||
swept after ``STATE_TTL_S``. The snapshot's git never reads the repo's own
|
||
``.git/config`` either: it runs against a **private git dir** (``safegit.py``)
|
||
— a guest's repo can name a clean filter, an fsmonitor or a hook there, and
|
||
this hook runs outside their sandbox, as the owner. Nested repos (submodules
|
||
included) are left out for the same reason: git would run ``git status``
|
||
inside them, under *their* config. Only files whose stat changed get hashed;
|
||
untracked files over ``MAX_UNTRACKED_BYTES`` are left out (a model download
|
||
must not be hashed). Warm, a snapshot is ~30 ms of git on the homelab checkout.
|
||
|
||
Where it goes. ``post`` prints ``{"bashDiff": {…}}`` on stdout. Claude Code
|
||
keeps a hook's stdout in the transcript (an ``attachment`` record of type
|
||
``hook_success`` carrying the call's ``toolUseID``) and does **not** add it to
|
||
the model's context — so the diff costs no tokens and travels with the
|
||
transcript everywhere it goes (the lab archive, a Mac worker's feed). Nothing
|
||
is printed when nothing changed. The backend parser attaches it to the tool
|
||
card (``conversations/parse/state.py``).
|
||
|
||
Commits too. The same pair notes each repo's ``HEAD`` (and, for a command
|
||
that pushes, its remote-tracking refs) before the call; when ``HEAD`` moved,
|
||
``post`` adds ``{"gitCommits": {…}}`` next to ``bashDiff``: every commit the
|
||
call *created* — ``old..new`` minus what a pull or a rebase brought in
|
||
(committer time before the call) — with its stats and its patch (capped like
|
||
``bashDiff``, merges stats only), plus the refs a push moved. That is the
|
||
exact record of what a session committed, on the lab as on a worker, readable
|
||
by the hub while the worker sleeps.
|
||
|
||
Never in the way: any failure, a timeout or a background command
|
||
(``run_in_background`` — its post hook fires at launch) prints nothing and
|
||
exits 0. Stdlib only, like ``stop_guard.py``.
|
||
"""
|
||
|
||
from __future__ import annotations
|
||
|
||
import json
|
||
import os
|
||
import re
|
||
import shlex
|
||
import sys
|
||
import time
|
||
|
||
# Started as a bare script (and possibly with ``python -I``, which leaves the
|
||
# script's folder off sys.path): the sidecar's own modules sit next to it.
|
||
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
||
import safegit # noqa: E402
|
||
|
||
# This runs twice around every Bash call, so start-up matters: no pathlib /
|
||
# shutil (~40 ms each), and subprocess / hashlib are imported only once a
|
||
# command turns out not to be read-only.
|
||
STATE_ROOT = (os.environ.get("BASH_DIFF_STATE_DIR")
|
||
or os.path.join(os.path.expanduser("~"), ".cache", "ai-agent", "bash-diff"))
|
||
# Repos snapshotted per call (cwd's first, then cd targets / path arguments).
|
||
MAX_REPOS = 3
|
||
# The embedded patch, all repos together: past it the files keep their stats
|
||
# but lose their hunks (``truncated``).
|
||
MAX_PATCH_BYTES = int(os.environ.get("BASH_DIFF_MAX_PATCH_BYTES", str(48 * 1024)))
|
||
# The commits' patches, all commits of one call together (``gitCommits``).
|
||
MAX_COMMIT_PATCH_BYTES = int(os.environ.get("BASH_DIFF_MAX_COMMIT_PATCH_BYTES", str(96 * 1024)))
|
||
# Commits recorded per call (a rebase of a long branch stops here).
|
||
MAX_COMMITS = 30
|
||
# A command that may move remote-tracking refs: their state is noted before it.
|
||
_PUSH_RE = re.compile(r"\bgit\b[^\n;&|]*\bpush\b|\b(commit-homelab|commit-project|open-pr|tea-cli)\b")
|
||
# git's empty tree — the "before" side of a root commit.
|
||
EMPTY_TREE = "4b825dc642cb6eb9a060e54bf8d69288fbee4904"
|
||
# Untracked files bigger than this are never hashed into a snapshot.
|
||
MAX_UNTRACKED_BYTES = 2 * 1024 * 1024
|
||
# Each git call; a repo whose snapshot is slower than this is skipped.
|
||
GIT_TIMEOUT_S = 6.0
|
||
# Stats only, never hunks: regenerated wholesale, noise in a review.
|
||
NO_PATCH = re.compile(r"(^|/)(package-lock\.json|pnpm-lock\.yaml|yarn\.lock|"
|
||
r"Cargo\.lock|poetry\.lock|uv\.lock|bun\.lockb?)$|\.min\.(js|css)$")
|
||
# A pending pre snapshot older than this no longer counts as a concurrent call
|
||
# (Bash's own timeout tops out at 10 min).
|
||
CONCURRENT_WINDOW_S = 600
|
||
# Session state dirs older than this are swept.
|
||
STATE_TTL_S = 3 * 86400
|
||
|
||
|
||
def _git(args: list[str], cwd: str, repo: dict | None = None, index: str | None = None,
|
||
stdin: bytes | None = None) -> bytes | None:
|
||
"""Run git in ``cwd``, never executing what the repo's config names
|
||
(``safegit``); with ``repo``, against its private object store and — once
|
||
:func:`_snapshot` made one — its private git dir, so the repo's own
|
||
``.git/config`` isn't read at all."""
|
||
import subprocess
|
||
env = safegit.env()
|
||
env["GIT_LITERAL_PATHSPECS"] = "1"
|
||
if repo and repo.get("store"):
|
||
env["GIT_OBJECT_DIRECTORY"] = repo["store"]
|
||
env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = repo["objects"]
|
||
if repo and repo.get("gitdir"):
|
||
env["GIT_DIR"] = repo["gitdir"]
|
||
env["GIT_WORK_TREE"] = repo["root"]
|
||
if index:
|
||
env["GIT_INDEX_FILE"] = index
|
||
try:
|
||
p = subprocess.run(safegit.argv(args, config=("-c", "core.untrackedCache=true",
|
||
"-c", "core.quotePath=false")),
|
||
cwd=cwd, env=env, input=stdin, capture_output=True,
|
||
timeout=GIT_TIMEOUT_S)
|
||
except (OSError, subprocess.TimeoutExpired):
|
||
return None
|
||
return p.stdout if p.returncode == 0 else None
|
||
|
||
|
||
# ── read-only commands skip both snapshots ───────────────────────────────────
|
||
# Most Bash calls only look. A command is skipped when every segment of it
|
||
# (split on `&&`, `||`, `;`, `|`, newlines) starts with one of these programs
|
||
# and nothing is redirected into a file. Deliberately short: a write this
|
||
# misses only costs its diff, a program left out only costs ~50 ms.
|
||
_READERS = frozenset("""
|
||
ls cat head tail wc grep rg egrep fgrep ag find fd tree stat file du df pwd echo printf
|
||
which type command whoami date uptime env printenv id uname hostname realpath readlink
|
||
basename dirname diff cmp sort uniq cut tr column jq yq less more true false test [
|
||
ps pgrep free lsof ss netstat ping dig nslookup host curl wget sleep nl od xxd hexdump
|
||
md5sum sha1sum sha256sum awk sed
|
||
notify notify-done notify-ask ask-form screenshot conv-meta
|
||
""".split())
|
||
# ↑ the ai-agent's own CLIs: a push, an ask / form (`ask-form wait` blocks for
|
||
# minutes — long enough for other agents' edits to land in the snapshot), a
|
||
# screenshot (written to the gitignored .ai/artefacts) touch no tracked file.
|
||
_GIT_READERS = frozenset("""
|
||
status log diff show rev-parse ls-files ls-tree cat-file blame grep describe
|
||
shortlog reflog merge-base for-each-ref name-rev show-ref count-objects
|
||
""".split())
|
||
_WRAPPERS = frozenset({"rtk", "time", "timeout", "nice", "nohup", "command", "builtin"})
|
||
_SEGMENT_RE = re.compile(r"&&|\|\||[;|\n]")
|
||
_REDIRECT_RE = re.compile(r"(?<![0-9&<])>>?(?!\s*&)(?!\s*/dev/null)")
|
||
|
||
|
||
def read_only(command: str) -> bool:
|
||
"""True when ``command`` can't write to the tree (conservatively)."""
|
||
if not command.strip() or "<<" in command or "`" in command or "$(" in command:
|
||
return False
|
||
if _REDIRECT_RE.search(re.sub(r"\d?>\s*&\d|&>\s*/dev/null|\d?>\s*/dev/null", "", command)):
|
||
return False
|
||
for seg in _SEGMENT_RE.split(command):
|
||
try:
|
||
words = shlex.split(seg)
|
||
except ValueError:
|
||
return False
|
||
while words and ("=" in words[0] and not words[0].startswith("=")):
|
||
words.pop(0) # FOO=bar cmd
|
||
while words and words[0] in _WRAPPERS:
|
||
words.pop(0)
|
||
while words and re.fullmatch(r"-\S*|\d+[smh]?", words[0]):
|
||
words.pop(0) # timeout 30 / nice -n 5
|
||
if not words:
|
||
continue
|
||
prog = os.path.basename(words[0])
|
||
if prog == "cd":
|
||
continue
|
||
if prog == "git":
|
||
sub = next((w for w in words[1:] if not w.startswith("-")), "")
|
||
if sub not in _GIT_READERS:
|
||
return False
|
||
continue
|
||
if prog not in _READERS:
|
||
return False
|
||
if prog == "sed" and any(w.startswith("-i") or w == "--in-place" for w in words[1:]):
|
||
return False
|
||
if prog == "find" and any(w in ("-delete", "-exec", "-execdir", "-ok", "-fprint")
|
||
for w in words[1:]):
|
||
return False
|
||
if prog == "awk" and "-i" in words[1:]:
|
||
return False
|
||
if prog in ("curl", "wget") and any(w in ("-o", "-O", "--output", "--remote-name")
|
||
or w.startswith("--output") for w in words[1:]):
|
||
return False
|
||
return True
|
||
|
||
|
||
# ── which repos ──────────────────────────────────────────────────────────────
|
||
_PATH_RE = re.compile(r"""(?:^|(?<=[\s'"(=,:<>]))(~?/[\w.@%+-][^\s'"`;|&<>(),]*)""")
|
||
_CD_RE = re.compile(r"(?:^|[;&|(]\s*)cd\s+([^\s;&|)]+)")
|
||
# Leading `export X=…;` / `X=…;` segments — environment, not a place to run.
|
||
_ENV_PREFIX_RE = re.compile(r"^(?:(?:export\s+)?[A-Za-z_][A-Za-z0-9_]*=[^\s;&|]*\s*(?:;|&&)\s*)+")
|
||
|
||
|
||
def _candidate_dirs(cwd: str, command: str) -> list[str]:
|
||
"""Where the command can write, in order: the directory it starts in (its
|
||
leading ``cd`` target, else the session cwd), every later ``cd`` target,
|
||
then every absolute or ``~`` path it names (a file's directory).
|
||
|
||
The session cwd is *not* a candidate when the command opens with a ``cd``
|
||
elsewhere — the lab's sessions sit in ~/homelab and ``cd`` into a worktree,
|
||
and snapshotting ~/homelab too would credit this call with whatever the
|
||
other agents changed there meanwhile (exactly what Claude Code's built-in
|
||
``bashEditDiff`` does)."""
|
||
cds = [m.group(1) for m in _CD_RE.finditer(command)]
|
||
# `export PATH=…; cd x && …` / `FOO=1; cd x` still start in x.
|
||
lead = _CD_RE.match(_ENV_PREFIX_RE.sub("", command.lstrip()))
|
||
base = os.path.join(cwd, os.path.expanduser(lead.group(1).strip("'\""))) if lead else cwd
|
||
out = [base, *(cds[1:] if lead else cds)]
|
||
# `sed -i … /x/y`, `> ~/z`, `--out=/x`, `open('/x/y', 'w')` in a heredoc
|
||
# — anything path-shaped, quoted or not.
|
||
out += [p for p in _PATH_RE.findall(command) if not p.startswith(("/dev/", "/proc/"))]
|
||
seen: list[str] = []
|
||
for d in out:
|
||
d = os.path.expanduser(d.strip("'\""))
|
||
if not os.path.isabs(d):
|
||
d = os.path.join(base, d)
|
||
d = os.path.normpath(d)
|
||
while d and not os.path.isdir(d):
|
||
parent = os.path.dirname(d)
|
||
if parent == d:
|
||
break
|
||
d = parent
|
||
if d and d != "/" and d not in seen:
|
||
seen.append(d)
|
||
return seen
|
||
|
||
|
||
# A scoped (guest) run's write dirs, from `--within <dir>` args: only repos
|
||
# under one of them are snapshotted. None = unconfined.
|
||
WITHIN: list[str] | None = None
|
||
|
||
|
||
def _allowed(top: str) -> bool:
|
||
return WITHIN is None or any(top == d or top.startswith(d.rstrip("/") + "/")
|
||
for d in WITHIN)
|
||
|
||
|
||
def _repos(cwd: str, command: str) -> list[dict]:
|
||
roots: list[dict] = []
|
||
for d in _candidate_dirs(cwd, command):
|
||
if len(roots) >= MAX_REPOS:
|
||
break
|
||
out = _git(["rev-parse", "--show-toplevel", "--git-path", "index",
|
||
"--git-path", "objects", "--git-path", "info/exclude"], d)
|
||
if not out or len(out.decode().splitlines()) < 4:
|
||
continue
|
||
top, idx, objs, excl = out.decode().splitlines()[:4]
|
||
if top in ("/", os.path.expanduser("~")) or not _allowed(top) or any(r["root"] == top for r in roots):
|
||
continue
|
||
idx, objs, excl = (os.path.normpath(os.path.join(d, p)) for p in (idx, objs, excl))
|
||
r = {"root": top, "realIndex": idx, "objects": objs, "exclude": excl}
|
||
# A linked worktree shares its main checkout's object store
|
||
# (`<main>/.git/objects`): name that checkout, so the hub files the
|
||
# worktree's work under the repo (backend projects/worker_projects.py).
|
||
if objs.endswith("/.git/objects"):
|
||
main = objs[: -len("/.git/objects")]
|
||
if main and main != top:
|
||
r["main"] = main
|
||
roots.append(r)
|
||
return roots
|
||
|
||
|
||
# ── snapshots ────────────────────────────────────────────────────────────────
|
||
def _state_dir(session: str) -> str:
|
||
return os.path.join(STATE_ROOT, re.sub(r"[^A-Za-z0-9_-]", "_", session or "nosession"))
|
||
|
||
|
||
def _copy(src: str, dst: str) -> None:
|
||
with open(src, "rb") as a, open(dst + ".tmp", "wb") as b:
|
||
b.write(a.read())
|
||
os.replace(dst + ".tmp", dst)
|
||
|
||
|
||
def _rmtree(d: str) -> None:
|
||
"""Remove a session's state dir: its indexes, pre files, object stores and
|
||
private git dirs (nested, so bottom-up)."""
|
||
for top, dirs, files in os.walk(d, topdown=False):
|
||
for name in files:
|
||
try:
|
||
os.unlink(os.path.join(top, name))
|
||
except OSError:
|
||
pass
|
||
for name in dirs:
|
||
try:
|
||
os.rmdir(os.path.join(top, name))
|
||
except OSError:
|
||
pass
|
||
try:
|
||
os.rmdir(d)
|
||
except OSError:
|
||
pass
|
||
|
||
|
||
def _private_gitdir(repo: dict, state: str, key: str) -> str | None:
|
||
"""This session's git dir for the repo's snapshots (``safegit``): made
|
||
once, with the few work-tree settings of the real one that decide how a
|
||
file is hashed."""
|
||
gd = os.path.join(state, f"{key}.git")
|
||
if os.path.isfile(os.path.join(gd, "HEAD")):
|
||
return gd
|
||
out = _git(["config", "--local", "-z", "--get-regexp", safegit.SAFE_KEYS_RE], repo["root"])
|
||
try:
|
||
return safegit.private_gitdir(gd, safegit.parse_safe_config(out))
|
||
except OSError:
|
||
return None
|
||
|
||
|
||
def _drop_gitlinks(repo: dict, index: str) -> bool:
|
||
"""Take submodule entries out of the private index: with one in it,
|
||
``git add -u`` runs ``git status`` inside that nested repo — under its
|
||
own config, which is as writable as the rest of the tree."""
|
||
out = _git(["ls-files", "-s", "-z"], repo["root"], repo, index)
|
||
if out is None:
|
||
return False
|
||
links = [rec.split(b"\t", 1)[1] for rec in out.split(b"\0")
|
||
if rec.startswith(b"160000 ") and b"\t" in rec]
|
||
if not links:
|
||
return True
|
||
return _git(["update-index", "--force-remove", "-z", "--stdin"], repo["root"], repo, index,
|
||
stdin=b"\0".join(links) + b"\0") is not None
|
||
|
||
|
||
def _snapshot(repo: dict, state: str) -> str | None:
|
||
"""Tree hash of the repo's working tree, through this session's private
|
||
index (seeded from the real one so its stat cache starts warm)."""
|
||
import hashlib
|
||
root = repo["root"]
|
||
key = hashlib.sha1(root.encode()).hexdigest()[:16]
|
||
index = os.path.join(state, f"{key}.index")
|
||
repo["store"] = os.path.join(state, f"{key}.objects")
|
||
os.makedirs(repo["store"], exist_ok=True)
|
||
repo.pop("gitdir", None)
|
||
gitdir = _private_gitdir(repo, state, key)
|
||
if not gitdir:
|
||
return None
|
||
repo["gitdir"] = gitdir
|
||
if not os.path.exists(index):
|
||
try:
|
||
_copy(repo["realIndex"], index)
|
||
except OSError:
|
||
pass # a fresh repo with no index yet: git builds one
|
||
if os.path.exists(index) and not _drop_gitlinks(repo, index):
|
||
try:
|
||
os.unlink(index)
|
||
except OSError:
|
||
pass
|
||
return None
|
||
# Tracked (in *this* index) files: modified, deleted.
|
||
if _git(["add", "-u", "--ignore-errors", "--", "."], root, repo, index) is None:
|
||
return None
|
||
# New untracked files, the big ones left out.
|
||
# (the private git dir has no info/exclude: the repo's own is named)
|
||
excl = repo.get("exclude")
|
||
out = _git(["ls-files", "-z", "--others", "--exclude-standard",
|
||
*([f"--exclude-from={excl}"] if excl and os.path.isfile(excl) else [])],
|
||
root, repo, index)
|
||
if out is None:
|
||
return None
|
||
small = []
|
||
for rel in out.split(b"\0"):
|
||
if not rel or rel.endswith(b"/"): # `dir/` = a nested repo: never a gitlink
|
||
continue
|
||
try:
|
||
if os.lstat(os.path.join(root.encode(), rel)).st_size <= MAX_UNTRACKED_BYTES:
|
||
small.append(rel)
|
||
except OSError:
|
||
continue
|
||
if small:
|
||
if _git(["add", "--ignore-errors", "--pathspec-from-file=-", "--pathspec-file-nul"],
|
||
root, repo, index, stdin=b"\0".join(small)) is None:
|
||
return None
|
||
tree = _git(["write-tree"], root, repo, index)
|
||
return tree.decode().strip() if tree else None
|
||
|
||
|
||
def _sweep() -> None:
|
||
"""Drop session dirs nobody touched for ``STATE_TTL_S`` (once an hour)."""
|
||
stamp = os.path.join(STATE_ROOT, ".swept")
|
||
now = time.time()
|
||
try:
|
||
if now - os.stat(stamp).st_mtime < 3600:
|
||
return
|
||
except OSError:
|
||
pass
|
||
try:
|
||
os.makedirs(STATE_ROOT, exist_ok=True)
|
||
with open(stamp, "w"):
|
||
pass
|
||
for e in os.scandir(STATE_ROOT):
|
||
if e.is_dir() and now - e.stat().st_mtime > STATE_TTL_S:
|
||
_rmtree(e.path)
|
||
except OSError:
|
||
pass
|
||
|
||
|
||
# ── the diff ─────────────────────────────────────────────────────────────────
|
||
def _files(repo: dict, a: str, b: str) -> list[dict]:
|
||
"""Per-file status + line counts between two trees."""
|
||
root = repo["root"]
|
||
ns = _git(["diff", "--no-renames", "--name-status", "-z", a, b], root, repo)
|
||
nm = _git(["diff", "--no-renames", "--numstat", "-z", a, b], root, repo)
|
||
if ns is None or nm is None:
|
||
return []
|
||
status: dict[str, str] = {}
|
||
parts = ns.decode(errors="replace").split("\0")
|
||
for i in range(0, len(parts) - 1, 2):
|
||
status[parts[i + 1]] = {"A": "added", "D": "deleted"}.get(parts[i][:1], "modified")
|
||
files = []
|
||
for rec in nm.decode(errors="replace").split("\0"):
|
||
if not rec:
|
||
continue
|
||
add, dele, path = rec.split("\t", 2)
|
||
binary = add == "-"
|
||
files.append({"path": path, "status": status.get(path, "modified"),
|
||
"add": 0 if binary else int(add), "del": 0 if binary else int(dele),
|
||
"binary": binary})
|
||
return files
|
||
|
||
|
||
def _patch(repo: dict, a: str, b: str, files: list[dict], budget: int) -> tuple[str, bool]:
|
||
paths = [f["path"] for f in files if not f["binary"] and not NO_PATCH.search(f["path"])]
|
||
if not paths or budget <= 0:
|
||
return "", bool(paths)
|
||
out = _git(["diff", "--no-renames", "--no-color", "--no-ext-diff", "-U3", a, b,
|
||
"--", *paths], repo["root"], repo)
|
||
if out is None:
|
||
return "", True
|
||
if len(out) <= budget:
|
||
return out.decode(errors="replace"), False
|
||
# Cut at a file boundary so every hunk shown is whole.
|
||
cut = out.rfind(b"\ndiff --git ", 0, budget)
|
||
return (out[:cut + 1].decode(errors="replace") if cut > 0 else ""), True
|
||
|
||
|
||
def _concurrent(root: str, tid: str) -> bool:
|
||
"""Another Bash call (any session's) is mid-flight in the same repo — its
|
||
pre snapshot is still pending — so some of this call's changes may be its.
|
||
Stale pre files (a call killed before its post hook) age out of the window."""
|
||
now = time.time()
|
||
try:
|
||
sessions = [e.path for e in os.scandir(STATE_ROOT) if e.is_dir()]
|
||
except OSError:
|
||
return False
|
||
for d in sessions:
|
||
try:
|
||
entries = list(os.scandir(d))
|
||
except OSError:
|
||
continue
|
||
for e in entries:
|
||
if not e.name.endswith(".pre.json") or e.name == f"{tid}.pre.json":
|
||
continue
|
||
try:
|
||
if now - e.stat().st_mtime > CONCURRENT_WINDOW_S:
|
||
continue
|
||
with open(e.path) as f:
|
||
rec = json.load(f)
|
||
except (OSError, ValueError):
|
||
continue
|
||
if any(r.get("root") == root for r in rec.get("repos") or []):
|
||
return True
|
||
return False
|
||
|
||
|
||
# ── commits ──────────────────────────────────────────────────────────────────
|
||
def _head(root: str) -> dict | None:
|
||
"""``HEAD``'s sha and branch (None on a detached HEAD); None in an empty repo."""
|
||
out = _git(["rev-parse", "HEAD"], root)
|
||
if not out:
|
||
return None
|
||
br = _git(["symbolic-ref", "-q", "--short", "HEAD"], root)
|
||
return {"sha": out.decode().strip(), "branch": br.decode().strip() if br else None}
|
||
|
||
|
||
def _remote_refs(root: str) -> dict[str, str]:
|
||
out = _git(["for-each-ref", "--format=%(refname:short)%09%(objectname)", "refs/remotes"], root)
|
||
refs = {}
|
||
for line in (out or b"").decode(errors="replace").splitlines():
|
||
name, _, sha = line.partition("\t")
|
||
if sha and not name.endswith("/HEAD"):
|
||
refs[name] = sha
|
||
return refs
|
||
|
||
|
||
_US = "\x1f"
|
||
|
||
|
||
def _commits(r: dict, since: float, budget: int) -> tuple[list[dict], int]:
|
||
"""The commits ``HEAD`` gained during the call, newest first, with their
|
||
files and (budget allowing) patch. A pull or a rebase also brings commits
|
||
made elsewhere, earlier: only those committed at or after ``since`` count."""
|
||
# A pre snapshot from before this hook noted HEAD (an update landing
|
||
# mid-call) has no baseline: all of history would look new.
|
||
if "head" not in r or since <= 0:
|
||
return [], budget
|
||
root, old = r["root"], (r.get("head") or {}).get("sha")
|
||
new = _head(root)
|
||
if not new or new["sha"] == old:
|
||
return [], budget
|
||
fmt = _US.join(["%H", "%h", "%P", "%ct", "%cI", "%an", "%s"])
|
||
out = _git(["log", f"--format={fmt}", f"--max-count={MAX_COMMITS}",
|
||
f"{old}..{new['sha']}" if old else new["sha"]], root)
|
||
commits = []
|
||
for line in (out or b"").decode(errors="replace").splitlines():
|
||
parts = line.split(_US)
|
||
if len(parts) < 7 or not parts[3].isdigit() or int(parts[3]) < since:
|
||
continue
|
||
sha, short, parents, _ct, date, author = parts[:6]
|
||
parents = parents.split()
|
||
c = {"sha": sha, "short": short, "parents": parents, "date": date, "author": author,
|
||
"subject": _US.join(parts[6:]), "branch": new["branch"]}
|
||
plain = {"root": root}
|
||
base = parents[0] if parents else EMPTY_TREE
|
||
files = _files(plain, base, sha)
|
||
c["files"] = files
|
||
c["add"] = sum(f["add"] for f in files)
|
||
c["del"] = sum(f["del"] for f in files)
|
||
if len(parents) > 1: # a merge: what it brought, no hunks
|
||
c["patch"], c["truncated"] = "", False
|
||
else:
|
||
c["patch"], c["truncated"] = _patch(plain, base, sha, files, budget)
|
||
budget -= len(c["patch"].encode())
|
||
commits.append(c)
|
||
return commits, budget
|
||
|
||
|
||
def _pushed(r: dict) -> list[dict]:
|
||
"""Remote-tracking refs the call moved (a push, a fetch): ``origin/x`` → sha."""
|
||
before = r.get("remotes")
|
||
if before is None:
|
||
return []
|
||
after = _remote_refs(r["root"])
|
||
return [{"ref": k, "sha": v} for k, v in sorted(after.items()) if before.get(k) != v]
|
||
|
||
|
||
# ── entry points ─────────────────────────────────────────────────────────────
|
||
def pre(ev: dict) -> None:
|
||
inp = ev.get("tool_input") or {}
|
||
tid = ev.get("tool_use_id")
|
||
if not tid or inp.get("run_in_background"):
|
||
return
|
||
command = str(inp.get("command") or "")
|
||
if read_only(command):
|
||
return
|
||
state = _state_dir(ev.get("session_id") or "")
|
||
_sweep()
|
||
os.makedirs(state, exist_ok=True)
|
||
t0 = time.monotonic()
|
||
started = time.time()
|
||
pushes = bool(_PUSH_RE.search(command))
|
||
repos = []
|
||
for r in _repos(ev.get("cwd") or os.getcwd(), command):
|
||
tree = _snapshot(r, state)
|
||
if tree:
|
||
extra = {"head": _head(r["root"])}
|
||
if pushes:
|
||
extra["remotes"] = _remote_refs(r["root"])
|
||
repos.append({**r, "from": tree, **extra})
|
||
if repos:
|
||
rec = {"repos": repos, "preMs": round((time.monotonic() - t0) * 1000),
|
||
"started": int(started)}
|
||
with open(os.path.join(state, f"{tid}.pre.json"), "w") as f:
|
||
json.dump(rec, f)
|
||
|
||
|
||
def post(ev: dict) -> dict | None:
|
||
tid = ev.get("tool_use_id")
|
||
if not tid:
|
||
return None
|
||
state = _state_dir(ev.get("session_id") or "")
|
||
pre_file = os.path.join(state, f"{tid}.pre.json")
|
||
try:
|
||
with open(pre_file) as f:
|
||
rec = json.load(f)
|
||
os.unlink(pre_file)
|
||
except (OSError, ValueError):
|
||
return None
|
||
t0 = time.monotonic()
|
||
out_repos, commit_repos = [], []
|
||
budget, commit_budget = MAX_PATCH_BYTES, MAX_COMMIT_PATCH_BYTES
|
||
# A commit stamped a second before the pre snapshot is still this call's
|
||
# (``%ct`` has a one-second grain).
|
||
since = rec["started"] - 1 if rec.get("started") else 0
|
||
for r in rec.get("repos") or []:
|
||
shared = None
|
||
commits, commit_budget = _commits(r, since, commit_budget)
|
||
pushed = _pushed(r)
|
||
if commits or pushed:
|
||
shared = _concurrent(r["root"], tid)
|
||
head = _head(r["root"]) or {}
|
||
cr = {"root": r["root"], "branch": head.get("branch"), "head": head.get("sha"),
|
||
"commits": commits, "pushed": pushed}
|
||
if r.get("main"):
|
||
cr["main"] = r["main"]
|
||
if shared:
|
||
cr["shared"] = True
|
||
commit_repos.append(cr)
|
||
to = _snapshot(r, state)
|
||
if not to or to == r["from"]:
|
||
continue
|
||
files = _files(r, r["from"], to)
|
||
if not files:
|
||
continue
|
||
patch, truncated = _patch(r, r["from"], to, files, budget)
|
||
budget -= len(patch.encode())
|
||
repo = {"root": r["root"], "from": r["from"], "to": to, "files": files,
|
||
"patch": patch, "truncated": truncated}
|
||
if r.get("main"):
|
||
repo["main"] = r["main"]
|
||
if shared if shared is not None else _concurrent(r["root"], tid):
|
||
repo["shared"] = True
|
||
out_repos.append(repo)
|
||
out: dict = {}
|
||
ms = rec.get("preMs", 0) + round((time.monotonic() - t0) * 1000)
|
||
if out_repos:
|
||
files = [f for r in out_repos for f in r["files"]]
|
||
out["bashDiff"] = {
|
||
"v": 1,
|
||
"add": sum(f["add"] for f in files),
|
||
"del": sum(f["del"] for f in files),
|
||
"repos": out_repos,
|
||
"ms": ms,
|
||
}
|
||
if commit_repos:
|
||
out["gitCommits"] = {"v": 1, "repos": commit_repos, "ms": ms}
|
||
return out or None
|
||
|
||
|
||
def main() -> None:
|
||
global WITHIN
|
||
mode = sys.argv[1] if len(sys.argv) > 1 else ""
|
||
args = sys.argv[2:]
|
||
if "--within" in args:
|
||
WITHIN = [os.path.realpath(args[i + 1]) for i, a in enumerate(args[:-1])
|
||
if a == "--within"]
|
||
try:
|
||
ev = json.load(sys.stdin)
|
||
except ValueError:
|
||
return
|
||
if ev.get("tool_name") != "Bash":
|
||
return
|
||
try:
|
||
if mode == "pre":
|
||
pre(ev)
|
||
elif mode == "post":
|
||
out = post(ev)
|
||
if out:
|
||
sys.stdout.write(json.dumps(out, separators=(",", ":")))
|
||
except Exception: # never in the way of the tool call
|
||
return
|
||
|
||
|
||
if __name__ == "__main__":
|
||
main()
|