367 lines
16 KiB
Python
367 lines
16 KiB
Python
"""A conversation's own commits, and their diffs — on the lab and on workers.
|
|
|
|
The list is the parser's ``commitsAuto`` (``conversations/commits.py``): the
|
|
commits the session itself made, recorded by the Bash hook or read off git's
|
|
commit line — exact, and known for a worker's conversation whether or not the
|
|
Mac is awake. A conversation with none recorded (one from before the hook, on
|
|
the lab) falls back to ``gitdiff``'s time-window guess, flagged ``exact:
|
|
False``; a worker conversation never does — the lab's repos aren't its repos.
|
|
|
|
A commit's diff comes from, in order:
|
|
|
|
1. **The lab's own git** (``gitdiff``) when the commit was made in a lab
|
|
checkout — full, renames included. Its root (``~/projects/<slug>``, a
|
|
worktree of one, the homelab checkout) maps onto a repo token.
|
|
2. **The transcript**: the hook embedded the commit's patch (unless it was
|
|
past the cap).
|
|
3. **The worker** (``POST /git/commit`` on its sidecar) — for a commit whose
|
|
patch the transcript doesn't carry; answered while the machine is online,
|
|
then cached on disk for good (a sha never changes).
|
|
|
|
The net diff ("All changes") is per run of consecutive commits — a commit
|
|
whose first parent is the previous one of the same branch and repo — so
|
|
another agent's commits landing in between never leak in; merges are left out
|
|
(what they bring is the branch's own commits).
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import json
|
|
import os
|
|
import pathlib
|
|
import re
|
|
from pathlib import PurePosixPath
|
|
|
|
from fastapi import HTTPException
|
|
|
|
from conversations import commits as gitcommits
|
|
from diff import gitdiff, worktreediff
|
|
from projects import PROJECTS_DIR
|
|
|
|
COMMIT_CACHE_DIR = pathlib.Path(os.environ.get("COMMIT_CACHE_DIR", "/data/commit-cache"))
|
|
_SHA_RE = re.compile(r"^[0-9a-f]{7,40}$")
|
|
_SAFE_RE = re.compile(r"[^A-Za-z0-9_.-]")
|
|
|
|
|
|
# --------------------------------------------------------------------------- #
|
|
# which runner, which repo
|
|
# --------------------------------------------------------------------------- #
|
|
def session_worker(deps, sid: str, meta: dict) -> str | None:
|
|
"""The worker the conversation ran on (None = the lab)."""
|
|
m = meta or (deps.meta_store.peek(sid) if sid else {}) or {}
|
|
return m.get("worker") or m.get("workerSource")
|
|
|
|
|
|
def lab_token(root: str | None, sha: str, fallback: list[str]) -> str | None:
|
|
"""A lab checkout's host path → the repo token whose git has ``sha``.
|
|
|
|
``/home/u/projects/<slug>`` → ``project:<slug>``; a worktree → its owning
|
|
repo (through its ``.git`` file while it lives, else the
|
|
``<project>-<name>`` directory convention); anything else under the lab
|
|
(the homelab checkout, a ``homelab-<name>`` worktree) → ``super:_``. The
|
|
conversation's own repo tokens are the fallback when that misses."""
|
|
cands: list[str] = []
|
|
p = PurePosixPath(root or "")
|
|
if p.parent.name == "projects" and p.name:
|
|
cands.append(f"project:{p.name}")
|
|
elif p.parent.name == "worktrees" and p.name:
|
|
wt = worktreediff.resolve(p.name)
|
|
if wt:
|
|
cands.append(wt["repo"])
|
|
else:
|
|
slug = next((s for s in sorted((d.name for d in PROJECTS_DIR.iterdir()
|
|
if d.is_dir()), key=len, reverse=True)
|
|
if p.name.startswith(s + "-")), None) if PROJECTS_DIR.is_dir() else None
|
|
cands.append(f"project:{slug}" if slug else "super:_")
|
|
elif root:
|
|
cands.append("super:_")
|
|
for t in [*cands, *fallback, "super:_"]:
|
|
r = gitdiff.resolve_repo(t)
|
|
if r and gitdiff._git(["cat-file", "-e", f"{sha}^{{commit}}"], r[0]) is not None:
|
|
return t
|
|
return None
|
|
|
|
|
|
def _repo_key(c: dict) -> str:
|
|
return c.get("repo") or c.get("root") or c.get("cwd") or "?"
|
|
|
|
|
|
# --------------------------------------------------------------------------- #
|
|
# the list
|
|
# --------------------------------------------------------------------------- #
|
|
def conversation_commits(deps, summary: dict, meta: dict, sid: str) -> dict:
|
|
"""``{commits, repos, exact, worker, …}`` — newest first, like gitdiff's."""
|
|
worker = session_worker(deps, sid, meta)
|
|
recorded = [c for c in summary.get("commitsAuto") or [] if isinstance(c, dict)]
|
|
if not recorded:
|
|
# A worker's repos aren't the lab's; a conversation that never ran a
|
|
# committing command made no commit, whatever landed meanwhile.
|
|
if worker or not summary.get("commitCalls"):
|
|
return _shape([], [], worker=worker, exact=True)
|
|
data = gitdiff.conversation_commits(deps.store, summary, meta, sid)
|
|
commits = [{**c, "source": "window", "pushed": None} for c in data["commits"]]
|
|
_fill_parents(commits)
|
|
return _shape(commits, data["repos"], worker=None, exact=False)
|
|
lab_repos = gitdiff._conversation_repos(summary, meta)
|
|
fallback = [*lab_repos[0], *(["super:_"] if lab_repos[2] else [])]
|
|
out = []
|
|
for c in recorded:
|
|
c = {**c}
|
|
c["worker"] = worker
|
|
if not worker:
|
|
c["repo"] = lab_token(c.get("root") or c.get("cwd"), c["sha"], fallback)
|
|
if c.get("source") == "output" and c["repo"]:
|
|
_complete_from_git(c)
|
|
else:
|
|
c["repo"] = None
|
|
cached = _cache_get(worker, c["sha"])
|
|
if cached and c.get("source") == "output":
|
|
_complete_from_cache(c, cached)
|
|
out.append(c)
|
|
out.reverse() # newest first
|
|
repos = sorted({_repo_key(c) for c in out})
|
|
return _shape(out, repos, worker=worker, exact=True)
|
|
|
|
|
|
def _fill_parents(commits: list[dict]) -> None:
|
|
"""Parents of lab commits (one ``git show`` per repo) — what tells
|
|
consecutive commits apart in the net diff, and a merge from a commit."""
|
|
by_repo: dict[str, list[dict]] = {}
|
|
for c in commits:
|
|
if c.get("repo") and not c.get("parents"):
|
|
by_repo.setdefault(c["repo"], []).append(c)
|
|
for token, cs in by_repo.items():
|
|
r = gitdiff.resolve_repo(token)
|
|
if not r:
|
|
continue
|
|
out = gitdiff._git(["show", "-s", "--format=%H %P", *[c["sha"] for c in cs]], r[0]) or ""
|
|
parents = {ln.split()[0]: ln.split()[1:] for ln in out.splitlines() if ln.strip()}
|
|
for c in cs:
|
|
ps = parents.get(c["sha"])
|
|
if ps is not None:
|
|
c["parents"], c["merge"] = ps, len(ps) > 1
|
|
|
|
|
|
def _shape(commits: list[dict], repos: list[str], *, worker: str | None, exact: bool) -> dict:
|
|
own = [c for c in commits if not c.get("merge")]
|
|
return {"commits": commits, "repos": repos, "exact": exact, "worker": worker,
|
|
"filesChanged": sum(int(c.get("files") or 0) for c in own),
|
|
"additions": sum(int(c.get("additions") or 0) for c in own),
|
|
"deletions": sum(int(c.get("deletions") or 0) for c in own)}
|
|
|
|
|
|
def _complete_from_git(c: dict) -> None:
|
|
"""A commit line gave the sha and subject only: fill parents and stats
|
|
from the lab's git (cheap: one ``git log -1 --numstat``)."""
|
|
found = gitdiff.list_commits(c["repo"], limit=1, revs=[c["sha"]])
|
|
r = gitdiff.resolve_repo(c["repo"])
|
|
if not found or not r:
|
|
return
|
|
f = found[0]
|
|
parents = (gitdiff._git(["rev-parse", f"{c['sha']}^@"], r[0]) or "").split()
|
|
c.update(sha=f["sha"], short=f["short"], date=f["date"], author=f["author"],
|
|
subject=f["subject"], additions=f["additions"], deletions=f["deletions"],
|
|
files=f["files"], parents=parents, merge=len(parents) > 1)
|
|
|
|
|
|
def _complete_from_cache(c: dict, d: dict) -> None:
|
|
parents = d.get("parents") or []
|
|
c.update(sha=d.get("sha") or c["sha"], parents=parents, merge=len(parents) > 1,
|
|
author=d.get("author") or c.get("author"), date=d.get("date") or c.get("date"))
|
|
if d.get("remotes"):
|
|
c["pushed"] = True
|
|
|
|
|
|
# --------------------------------------------------------------------------- #
|
|
# one commit's diff
|
|
# --------------------------------------------------------------------------- #
|
|
def _cache_path(worker: str, key: str) -> pathlib.Path:
|
|
return COMMIT_CACHE_DIR / _SAFE_RE.sub("_", worker) / f"{_SAFE_RE.sub('_', key)}.json"
|
|
|
|
|
|
def _cache_get(worker: str, key: str) -> dict | None:
|
|
try:
|
|
return json.loads(_cache_path(worker, key).read_text())
|
|
except (OSError, ValueError):
|
|
return None
|
|
|
|
|
|
def _cache_put(worker: str, key: str, d: dict) -> None:
|
|
p = _cache_path(worker, key)
|
|
try:
|
|
p.parent.mkdir(parents=True, exist_ok=True)
|
|
tmp = p.with_suffix(".tmp")
|
|
tmp.write_text(json.dumps(d))
|
|
tmp.replace(p)
|
|
except OSError:
|
|
pass
|
|
|
|
|
|
def _transcript_files(ap: pathlib.Path, sha: str) -> list[dict] | None:
|
|
"""The commit's FileDiffs from the hook payload in the transcript."""
|
|
short = sha[:7]
|
|
try:
|
|
fh = ap.open(encoding="utf-8", errors="replace")
|
|
except OSError:
|
|
return None
|
|
with fh:
|
|
for line in fh:
|
|
if short not in line or "gitCommits" not in line:
|
|
continue
|
|
try:
|
|
a = (json.loads(line).get("attachment") or {})
|
|
except ValueError:
|
|
continue
|
|
gc = gitcommits.load_hook(a.get("stdout") or "")
|
|
files = gitcommits.file_diffs(gc, sha) if gc else None
|
|
if files is not None:
|
|
return files
|
|
return None
|
|
|
|
|
|
def _worker_call(deps, worker: str, path: str, payload: dict) -> dict:
|
|
from workers import store as workers_mod
|
|
w = deps.worker_store.get(worker)
|
|
if not w:
|
|
raise HTTPException(404, {"message": "unknown worker", "kind": "worker"})
|
|
if not deps.worker_store.online(worker):
|
|
raise HTTPException(503, {"message": f"{w.get('name') or 'the worker'} is offline",
|
|
"kind": "worker_offline"})
|
|
return workers_mod.sidecar_request(w["url"], w["token"], path, payload, timeout=30,
|
|
label=f"worker {w.get('name') or worker}")
|
|
|
|
|
|
def _dirs(c: dict, summary: dict) -> list[str]:
|
|
return [d for d in (c.get("root"), c.get("cwd"), summary.get("cwd")) if d]
|
|
|
|
|
|
def _result(title: str, subtitle: str, files: list[dict], commits: list[dict], *,
|
|
approx: bool, **extra) -> dict:
|
|
return {"title": title, "subtitle": subtitle, "files": files,
|
|
"additions": sum(f["additions"] for f in files),
|
|
"deletions": sum(f["deletions"] for f in files),
|
|
"commits": [_ref(c) for c in commits], "approx": approx, **extra}
|
|
|
|
|
|
def _ref(c: dict) -> dict:
|
|
return {k: c.get(k) for k in ("sha", "short", "date", "author", "subject",
|
|
"additions", "deletions", "files", "repo")}
|
|
|
|
|
|
def _label(c: dict) -> str:
|
|
return PurePosixPath(c.get("root") or c.get("cwd") or c.get("repo") or "").name or "repo"
|
|
|
|
|
|
def commit_diff(deps, ap: pathlib.Path, summary: dict, data: dict, sha: str) -> dict:
|
|
"""One of the conversation's commits, as a DiffResult."""
|
|
if not _SHA_RE.match(sha or ""):
|
|
raise HTTPException(400, "bad sha")
|
|
c = next((c for c in data["commits"] if gitcommits.same(c["sha"], sha)), None)
|
|
if c is None:
|
|
raise HTTPException(404, "commit not in this conversation")
|
|
sub = f"{c.get('short') or sha[:7]} · {_label(c)}"
|
|
if c.get("repo"):
|
|
out = gitdiff.commit_diff(c["repo"], c["sha"])
|
|
if out:
|
|
return {**out, "subtitle": sub, "source": "git"}
|
|
files = _transcript_files(ap, c["sha"]) if c.get("source") == "hook" else None
|
|
complete = files is not None and not any(f.get("truncated") for f in files)
|
|
if complete or not c.get("worker"):
|
|
if files is None:
|
|
raise HTTPException(404, "this commit's diff is not available")
|
|
return _result(c.get("subject") or "", sub, files, [c], approx=not complete,
|
|
source="transcript")
|
|
worker = c["worker"]
|
|
cached = _cache_get(worker, c["sha"])
|
|
if cached is None:
|
|
try:
|
|
cached = _worker_call(deps, worker, "/git/commit",
|
|
{"dirs": _dirs(c, summary), "sha": c["sha"]})
|
|
except HTTPException as e:
|
|
if files is not None: # what the transcript has, flagged
|
|
return _result(c.get("subject") or "", sub, files, [c], approx=True,
|
|
source="transcript", unavailable=_detail(e))
|
|
raise
|
|
_cache_put(worker, c["sha"], cached)
|
|
if len(cached.get("sha") or "") == 40 and cached["sha"] != c["sha"]:
|
|
_cache_put(worker, cached["sha"], cached)
|
|
files = gitdiff._parse_unified_diff(cached.get("patch") or "")
|
|
return _result(cached.get("subject") or c.get("subject") or "", sub, files, [c],
|
|
approx=bool(cached.get("truncated")), source="worker")
|
|
|
|
|
|
def _detail(e: HTTPException) -> dict:
|
|
d = e.detail if isinstance(e.detail, dict) else {"message": str(e.detail)}
|
|
return {"message": d.get("message") or "unavailable", "kind": d.get("kind") or "unknown"}
|
|
|
|
|
|
# --------------------------------------------------------------------------- #
|
|
# the net diff
|
|
# --------------------------------------------------------------------------- #
|
|
def runs(commits: list[dict]) -> list[list[dict]]:
|
|
"""Non-merge commits (newest-first input) → runs of consecutive commits,
|
|
each oldest first: same repo and branch, each one's first parent the one
|
|
before it."""
|
|
out: list[list[dict]] = []
|
|
for c in reversed(commits):
|
|
if c.get("merge"):
|
|
continue
|
|
prev = next((r for r in out if _repo_key(r[-1]) == _repo_key(c)
|
|
and r[-1].get("branch") == c.get("branch")
|
|
and (c.get("parents") or [None])[0] == r[-1]["sha"]), None)
|
|
if prev is not None:
|
|
prev.append(c)
|
|
else:
|
|
out.append([c])
|
|
return out
|
|
|
|
|
|
def net_diff(deps, ap: pathlib.Path, summary: dict, data: dict, title: str) -> dict:
|
|
"""Every run's net diff, one after the other (a run per repo/branch, in
|
|
practice): the conversation's whole change set."""
|
|
files: list[dict] = []
|
|
approx = not data["exact"]
|
|
unavailable = None
|
|
groups = runs(data["commits"])
|
|
for g in groups:
|
|
oldest, newest = g[0], g[-1]
|
|
got: list[dict] | None = None
|
|
if oldest.get("repo") and newest.get("repo") == oldest["repo"]:
|
|
agg = gitdiff.aggregate_diff(oldest["repo"], [c["sha"] for c in reversed(g)],
|
|
title="", subtitle="")
|
|
got = agg["files"] if agg else None
|
|
elif len(g) == 1:
|
|
try:
|
|
got = commit_diff(deps, ap, summary, data, oldest["sha"])["files"]
|
|
except HTTPException as e:
|
|
unavailable = _detail(e)
|
|
elif oldest.get("worker"):
|
|
key = f"{oldest['sha']}..{newest['sha']}"
|
|
cached = _cache_get(oldest["worker"], key)
|
|
if cached is None:
|
|
try:
|
|
cached = _worker_call(deps, oldest["worker"], "/git/range",
|
|
{"dirs": _dirs(oldest, summary),
|
|
"base": oldest["sha"], "head": newest["sha"]})
|
|
_cache_put(oldest["worker"], key, cached)
|
|
except HTTPException as e:
|
|
unavailable = _detail(e)
|
|
if cached is not None:
|
|
got = gitdiff._parse_unified_diff(cached.get("patch") or "")
|
|
approx |= bool(cached.get("truncated"))
|
|
else: # the Mac sleeps: each commit's own patch, as the transcript has it
|
|
got = []
|
|
for c in g:
|
|
got += [{**f, "commit": c["short"]} for f in
|
|
(_transcript_files(ap, c["sha"]) or [])]
|
|
approx = True
|
|
if got is None:
|
|
continue
|
|
files += [{**f, "repo": oldest.get("repo")} for f in got]
|
|
n = len(data["commits"])
|
|
sub = (f"{n} commit{'s' if n != 1 else ''} · {len(files)} file{'s' if len(files) != 1 else ''}")
|
|
out = _result(title, sub, files, data["commits"], approx=approx)
|
|
if unavailable:
|
|
out["unavailable"] = unavailable
|
|
return out
|