Generic platform points for the `diff-viewer` and `commits` plugins (ai-agent-plugins): a `conversation.tab` slot (Thread | Changes N) with setTab/openTab/closeTab/reply bridges; stackable + pullOut tool cards and match.hasReport; `pathShims` (a git PATH shim for every harness) with out-of-band reports (lab: /api/plugin-reports, worker: outbox `report`); `conversations.reports` and `diff.read` hub bridges; ui.pages[].opens for Project/Service "Recent commits". The core commit card, Changes view, diff page and review store are gone; bash_diff.py keeps bashDiff only. Legacy gitCommits / commit-line parsing stays for past transcripts. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
554 lines
23 KiB
Python
554 lines
23 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 are not this hook's any more (2026-11-27): until then ``post`` also
|
||
printed ``{"gitCommits": {…}}`` — the commits a call created, their patches,
|
||
the refs a push moved. That capture is the ``commits`` plugin's now, a
|
||
``git`` path shim on every harness (``pathShims``, path_shims.py); the
|
||
backend still reads ``gitCommits`` out of older transcripts
|
||
(``conversations/commits.py``).
|
||
|
||
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)))
|
||
# 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
|
||
|
||
|
||
# ── 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()
|
||
repos = []
|
||
for r in _repos(ev.get("cwd") or os.getcwd(), command):
|
||
tree = _snapshot(r, state)
|
||
if tree:
|
||
repos.append({**r, "from": tree})
|
||
if repos:
|
||
rec = {"repos": repos, "preMs": round((time.monotonic() - t0) * 1000)}
|
||
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 = []
|
||
budget = MAX_PATCH_BYTES
|
||
for r in rec.get("repos") or []:
|
||
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 _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,
|
||
}
|
||
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()
|