The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
refactor(web): dedupe web_git subprocess/ref-list plumbing, drop dead _MAX_BUFFER
Tekniumbdf1d8b0cf0d
diff --git a/hermes_cli/web_git.py b/hermes_cli/web_git.pyindex f06f736d492..7082357c4b2 100644--- a/hermes_cli/web_git.py+++ b/hermes_cli/web_git.py@@ -23,7 +23,6 @@ from hermes_cli._subprocess_compat import harden_git_argv, noninteractive_git_en_GIT_TIMEOUT = 30_GH_TIMEOUT = 30-_MAX_BUFFER = 32 * 1024 * 1024_UNTRACKED_LINE_MAX_BYTES = 1024 * 1024_UNTRACKED_SCAN_CAP = 500_COMMIT_CONTEXT_DIFF_MAX_CHARS = 120_000@@ -31,26 +30,26 @@ _COMMIT_CONTEXT_UNTRACKED_MAX = 80_TRUNK_BRANCHES = ("main", "master")-def _git(cwd: str, args: list[str], *, timeout: int = _GIT_TIMEOUT) -> tuple[int, str, str]:- """Run ``git`` in ``cwd``. Returns (returncode, stdout, stderr); never raises- on a non-zero exit (callers decide what an error means).-- Runs non-interactively (stdin nulled, ``GIT_TERMINAL_PROMPT=0``): these- calls serve authenticated REST requests from the dashboard/desktop, so a- credential prompt from ``fetch``/``push``/``pull`` could never be answered- — it would just hang the request until the timeout. Failing fast surfaces- the real auth error in the toast instead."""+def _run(argv: list[str], cwd: str, timeout: int, env: dict) -> subprocess.CompletedProcess | None:+ """Non-interactive subprocess (stdin nulled, prompts disabled): these calls+ serve authenticated REST requests, so a credential prompt from+ ``fetch``/``push``/``pull`` could never be answered — it would hang the+ request until the timeout. Failing fast surfaces the real auth error in+ the toast instead. None when the process could not run at all."""try:- proc = subprocess.run(- ["git", *harden_git_argv(args)],- cwd=cwd,- capture_output=True,- text=True, encoding='utf-8', errors='replace',- timeout=timeout,- stdin=subprocess.DEVNULL,- env=noninteractive_git_env(),+ return subprocess.run(+ argv, cwd=cwd, capture_output=True, text=True, encoding='utf-8',+ errors='replace', timeout=timeout, stdin=subprocess.DEVNULL, env=env,)except (OSError, subprocess.SubprocessError):+ return None+++def _git(cwd: str, args: list[str], *, timeout: int = _GIT_TIMEOUT) -> tuple[int, str, str]:+ """Run ``git`` in ``cwd``. Returns (returncode, stdout, stderr); never raises+ on a non-zero exit (callers decide what an error means)."""+ proc = _run(["git", *harden_git_argv(args)], cwd, timeout, noninteractive_git_env())+ if proc is None:return 1, "", "git invocation failed"return proc.returncode, proc.stdout, proc.stderr@@ -131,11 +130,8 @@ def _fill_untracked_counts(cwd: str, files: list[dict]) -> None:def _branch_base(cwd: str) -> str | None:"""Merge-base with the remote default branch for "all branch changes"."""- candidates: list[str] = []head = _git_out(cwd, ["rev-parse", "--abbrev-ref", "origin/HEAD"]).strip()- if head:- candidates.append(head)- candidates += ["origin/main", "origin/master", "main", "master"]+ candidates = ([head] if head else []) + ["origin/main", "origin/master", "main", "master"]for ref in candidates:base = _git_out(cwd, ["merge-base", "HEAD", ref]).strip()if base:@@ -203,7 +199,7 @@ def _classify(tag: str, xy: str, path: str) -> dict:def _status_letter(tag: str, xy: str) -> str:if tag in ("?", "u"):- return tag.upper() if tag == "u" else "?"+ return tag.upper()code = xy[0] if xy[0] != "." else (xy[1] if len(xy) > 1 else ".")return (code if code != "." else "M").upper()@@ -239,10 +235,9 @@ def repo_status(cwd: str) -> dict | None:# +/- vs HEAD (tracked), then fold in untracked insertions — `git diff HEAD`# ignores them, so a new-file-only turn would otherwise read +0 (bounded scan).- added = removed = 0- for a, r in _numstat(cwd, ["HEAD"]).values():- added += a- removed += r+ counts = _numstat(cwd, ["HEAD"]).values()+ added = sum(a for a, _ in counts)+ removed = sum(r for _, r in counts)added += sum(_untracked_insertions(cwd, f["path"]) for f in files[:_UNTRACKED_SCAN_CAP] if f["untracked"])return {@@ -301,15 +296,8 @@ def review_list(cwd: str, scope: str, base_ref: str | None) -> dict:for tag, xy, path in _walk_entries(raw):sa, sr = staged.get(path, (0, 0))ua, ur = unstaged.get(path, (0, 0))- files.append(- {- "path": path,- "added": sa + ua,- "removed": sr + ur,- "status": _status_letter(tag, xy),- "staged": _entry_staged(tag, xy),- }- )+ files.append({"path": path, "added": sa + ua, "removed": sr + ur,+ "status": _status_letter(tag, xy), "staged": _entry_staged(tag, xy)})files.sort(key=lambda f: f["path"])_fill_untracked_counts(cwd, files)return {"files": files, "base": None}@@ -418,7 +406,7 @@ def review_commit_context(cwd: str) -> dict:note = "\n# New (untracked) files:\n" + "".join(f"# {p}\n" for p in visible)if len(untracked) > len(visible):note += f"# ... {len(untracked) - len(visible)} more omitted\n"- diff = f"{diff}{note}" if diff else note+ diff += notereturn {"diff": diff or "", "recent": _git_out(cwd, ["log", "-n", "10", "--pretty=format:%s"]).strip()}@@ -429,17 +417,12 @@ def review_commit_context(cwd: str) -> dict:def _gh(cwd: str, args: list[str]) -> tuple[bool, str]:if not shutil.which("gh"):return False, ""- # Same non-interactive contract as _git: these serve REST requests, so gh- # must fail fast instead of prompting (GH_PROMPT_DISABLED is gh's own- # documented kill-switch for interactive prompts).+ # GH_PROMPT_DISABLED is gh's own documented kill-switch for interactive+ # prompts (same non-interactive contract as _git).env = noninteractive_git_env()env["GH_PROMPT_DISABLED"] = "1"- try:- proc = subprocess.run(- ["gh", *args], cwd=cwd, capture_output=True, text=True, encoding='utf-8', errors='replace', timeout=_GH_TIMEOUT,- stdin=subprocess.DEVNULL, env=env,- )- except (OSError, subprocess.SubprocessError):+ proc = _run(["gh", *args], cwd, _GH_TIMEOUT, env)+ if proc is None:return False, ""return proc.returncode == 0, proc.stdout or ""@@ -457,7 +440,7 @@ def review_ship_info(cwd: str) -> dict:try:pr = json.loads(out)except json.JSONDecodeError:- return {"ghReady": True, "pr": None}+ pr = Noneif pr and pr.get("url"):return {"ghReady": True, "pr": {"url": pr["url"], "state": pr.get("state"), "number": pr.get("number")}}return {"ghReady": True, "pr": None}@@ -468,8 +451,6 @@ def review_ship_info(cwd: str) -> dict:# the document well inside GitHub's node budget._PR_QUERY_BRANCH_CHUNK = 50_PR_QUERY_BRANCH_CAP = 300--_PR_NODE_FIELDS = "number state isDraft isCrossRepository title url headRefName"@@ -519,13 +500,9 @@ def review_pr_list(cwd: str, branches: list[str], numbers: list[int] = None) ->return {"ghReady": False, "prs": []}prs: list[dict] = []- chunks = [- (wanted[i : i + _PR_QUERY_BRANCH_CHUNK], [])- for i in range(0, len(wanted), _PR_QUERY_BRANCH_CHUNK)- ] + [- ([], by_number[i : i + _PR_QUERY_BRANCH_CHUNK])- for i in range(0, len(by_number), _PR_QUERY_BRANCH_CHUNK)- ]+ step = _PR_QUERY_BRANCH_CHUNK+ chunks = ([(wanted[i:i + step], []) for i in range(0, len(wanted), step)]+ + [([], by_number[i:i + step]) for i in range(0, len(by_number), step)])for branch_chunk, number_chunk in chunks:ok, out = _gh(cwd, ["api", "graphql", "-f", f"query={_pr_query(owner, name, branch_chunk, number_chunk)}"])if not ok:@@ -570,49 +547,34 @@ def review_create_pr(cwd: str) -> dict:def _parse_worktrees(out: str) -> list[dict]:+ """``git worktree list --porcelain`` -> one dict per tree (main tree first)."""trees: list[dict] = []- cur: dict | None = Nonefor line in out.split("\n"):if line.startswith("worktree "):- if cur:- trees.append(cur)- cur = {"path": line[9:].strip(), "branch": None, "detached": False, "bare": False, "locked": False}- elif cur is None:+ trees.append({"path": line[9:].strip(), "branch": None, "detached": False, "locked": False})+ elif not trees:continueelif line.startswith("branch "):- cur["branch"] = line[7:].strip().replace("refs/heads/", "", 1)+ trees[-1]["branch"] = line[7:].strip().replace("refs/heads/", "", 1)elif line == "detached":- cur["detached"] = True- elif line == "bare":- cur["bare"] = True+ trees[-1]["detached"] = Trueelif line.startswith("locked"):- cur["locked"] = True- if cur:- trees.append(cur)+ trees[-1]["locked"] = Truereturn treesdef worktree_list(cwd: str) -> list[dict]:out = _git_out(cwd, ["worktree", "list", "--porcelain"])- if not out:- return []return [- {- "path": tree["path"],- "branch": tree["branch"],- "isMain": index == 0,- "detached": tree["detached"],- "locked": tree["locked"],- }- for index, tree in enumerate(_parse_worktrees(out))- ]+ {"path": t["path"], "branch": t["branch"], "isMain": i == 0,+ "detached": t["detached"], "locked": t["locked"]}+ for i, t in enumerate(_parse_worktrees(out))+ ] if out else []def _main_root(cwd: str) -> str:- for tree in worktree_list(cwd):- if tree["isMain"]:- return tree["path"]- return cwd+ trees = worktree_list(cwd)+ return trees[0]["path"] if trees else cwddef _sanitize_branch(name: str) -> str:@@ -649,28 +611,14 @@ def _default_branch(cwd: str) -> str:def _ensure_repo(cwd: str) -> None:"""A new project folder may not be a repo (or has no commit to branch from);init it with a root commit so worktrees just work. No-op for a committed repo."""- inside = _git_out(cwd, ["rev-parse", "--is-inside-work-tree"]).strip()- needs_root = False- if inside != "true":+ if _git_out(cwd, ["rev-parse", "--is-inside-work-tree"]).strip() != "true":_git_ok(cwd, ["init"])needs_root = Trueelse:- code, _, _ = _git(cwd, ["rev-parse", "--verify", "HEAD"])- needs_root = code != 0+ needs_root = _git(cwd, ["rev-parse", "--verify", "HEAD"])[0] != 0if needs_root:- _git_ok(- cwd,- [- "-c",- "user.email=hermes@localhost",- "-c",- "user.name=Hermes",- "commit",- "--allow-empty",- "-m",- "Initial commit",- ],- )+ _git_ok(cwd, ["-c", "user.email=hermes@localhost", "-c", "user.name=Hermes",+ "commit", "--allow-empty", "-m", "Initial commit"])def _unique_dir(base: str) -> str:@@ -688,8 +636,7 @@ def _remote_of_ref(cwd: str, name: str) -> str:assuming the remote is called "origin" (mirrors the Electron op)."""if "/" not in name:return ""- code, _, _ = _git(cwd, ["show-ref", "--verify", "--quiet", f"refs/remotes/{name}"])- if code != 0:+ if _git(cwd, ["show-ref", "--verify", "--quiet", f"refs/remotes/{name}"])[0] != 0:return ""return name.split("/", 1)[0]@@ -706,9 +653,9 @@ def worktree_add(cwd: str, options: dict) -> dict:# "origin/feature" is a remote-tracking ref, not a branch git can check# out — `git worktree add <dir> origin/feature` detaches HEAD. Create a# local branch with the same short name that tracks the remote ref,- # like `git switch feature` does for a branch on exactly one remote.- # (Parity with the Electron op; a remote gateway serves this mirror, so- # the desktop's convert-a-branch flow must behave identically. #81724)+ # like `git switch feature` does for a branch on exactly one remote+ # (parity with the Electron op: the desktop's convert-a-branch flow+ # must behave identically through a remote gateway).remote = _remote_of_ref(root, requested)existing = requested.split("/", 1)[1] if remote else requestedif not remote and existing == _default_branch(root):@@ -754,40 +701,33 @@ def worktree_add(cwd: str, options: dict) -> dict:def worktree_remove(cwd: str, worktree_path: str, force: bool) -> dict:- root = _main_root(cwd)- args = ["worktree", "remove"]- if force:- args.append("--force")- args.append(worktree_path)- _git_ok(root, args)+ _git_ok(_main_root(cwd), ["worktree", "remove", *(["--force"] if force else []), worktree_path])return {"removed": worktree_path}+def _ref_names(cwd: str, *patterns: str, fmt: str = "%(refname:short)") -> list[str]:+ """Non-empty ``for-each-ref`` lines, newest commit first."""+ out = _git_out(cwd, ["for-each-ref", f"--format={fmt}", "--sort=-committerdate", *patterns])+ return [line.strip() for line in out.split("\n") if line.strip()]++def branch_list(cwd: str) -> list[dict]:"""Branches for the convert-a-branch picker: local heads first, then theremote-tracking refs that have no local head yet (a teammate's branch isreachable without a manual checkout). Parity with the Electron op — a- remote gateway serves this mirror for the same desktop UI (#81724)."""- out = _git_out(- cwd, ["for-each-ref", "--format=%(refname:short)", "--sort=-committerdate", "refs/heads"]- )- if not out:+ remote gateway serves this mirror for the same desktop UI."""+ locals_ = _ref_names(cwd, "refs/heads")+ if not locals_:return []- trees = worktree_list(cwd)- path_by_branch = {t["branch"]: t["path"] for t in trees if t["branch"]}+ path_by_branch = {t["branch"]: t["path"] for t in worktree_list(cwd) if t["branch"]}trunk = _default_branch(cwd)- locals_ = [name for name in (line.strip() for line in out.split("\n")) if name]local_set = set(locals_)- remote_out = _git_out(- cwd, ["for-each-ref", "--format=%(refname:short)", "--sort=-committerdate", "refs/remotes"]- )remotes = [name- for name in (line.strip() for line in remote_out.split("\n"))- if name+ for name in _ref_names(cwd, "refs/remotes")# "origin/HEAD" is a symbolic alias for the remote's default branch —# not a branch, and a duplicate row in the list.- and not name.endswith("/HEAD")+ if not name.endswith("/HEAD")# A remote branch tracked locally is reachable via its local head; a# second row is noise, and checking out the remote ref detaches HEAD.and name.split("/", 1)[-1] not in local_set@@ -830,39 +770,17 @@ def base_branch_list(cwd: str) -> list[dict]:The remote default (origin/HEAD) is flagged so the UI can preselect it."""- out = _git_out(- cwd,- [- "for-each-ref",- "--format=%(refname:short)\t%(committerdate:iso)",- "--sort=-committerdate",- "refs/heads",- "refs/remotes",- ],- )- if not out:+ lines = _ref_names(cwd, "refs/heads", "refs/remotes",+ fmt="%(refname:short)\t%(committerdate:iso)")+ if not lines:return []- remote_default = _git_out(+ # origin/HEAD when a remote exists; otherwise the local default+ # (main/master/init.defaultBranch) so a no-remote repo still flags its trunk.+ default = _git_out(cwd, ["symbolic-ref", "--quiet", "--short", "refs/remotes/origin/HEAD"]- ).strip()- local_default = _default_branch(cwd) if not remote_default else ""- result: list[dict] = []- for line in out.split("\n"):- line = line.strip()- if not line:- continue- name = line.split("\t")[0]- result.append(- {- "name": name,- "isRemote": name.startswith("origin/"),- # origin/HEAD when a remote exists; otherwise the local- # default (main/master/init.defaultBranch) so a no-remote- # repo still flags its trunk.- "isDefault": bool(- (remote_default and name == remote_default)- or (not remote_default and local_default and name == local_default)- ),- }- )- return result+ ).strip() or _default_branch(cwd)+ return [+ {"name": name, "isRemote": name.startswith("origin/"),+ "isDefault": bool(default and name == default)}+ for name in (line.split("\t")[0] for line in lines)+ ]