async_delegation_recovery_hints.py 3.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. """Forensic hints attached to an abandoned-delegation recovery event.
  2. When the owner process dies (OOM-kill, crash) before a background child records a
  3. terminal result, the recovery event used to carry only "outcome unknown" plus the
  4. transcript paths — the parent then had to open files to find out where the child
  5. got to. These helpers put the last lines of each live transcript and a one-line git
  6. snapshot of the owner's working directory INTO the event so the parent can decide
  7. whether to continue or re-dispatch without forensics. Everything here is best-effort
  8. and bounded: a missing file, a non-git cwd or a slow git never fails recovery.
  9. """
  10. from __future__ import annotations
  11. import os
  12. import subprocess
  13. from typing import Dict, Optional
  14. from hermes_cli._subprocess_compat import harden_git_argv, noninteractive_repo_git_env
  15. TAIL_LINES = 20
  16. TAIL_CHARS = 2_000
  17. _GIT_TIMEOUT_S = 5
  18. def transcript_tail(path: str, *, lines: int = TAIL_LINES, chars: int = TAIL_CHARS) -> Optional[str]:
  19. """Last ``lines`` lines (at most ``chars`` characters) of a live transcript; None when unreadable."""
  20. try:
  21. with open(path, "rb") as fh:
  22. fh.seek(0, os.SEEK_END)
  23. size = fh.tell()
  24. fh.seek(max(0, size - chars * 4)) # a few bytes per char of headroom; bounded read
  25. raw = fh.read().decode("utf-8", errors="replace")
  26. except OSError:
  27. return None
  28. tail = "\n".join(raw.splitlines()[-lines:]).strip()
  29. if len(tail) > chars:
  30. tail = "…" + tail[-chars:]
  31. return tail or None
  32. def transcript_tails(paths: dict[str, str]) -> dict[str, str]:
  33. return {index: tail for index, path in (paths or {}).items() if (tail := transcript_tail(path))}
  34. def git_state_hint(cwd: Optional[str]) -> Optional[str]:
  35. """``branch @ sha (N uncommitted file(s))`` for the owner's cwd; None when not a git checkout."""
  36. if not cwd or not os.path.isdir(cwd):
  37. return None
  38. # noninteractive_repo_git_env (GHSA-7x36-8jrh-v4pw): runs unattended in the owner's repo and
  39. # ``status`` refreshes the index, which executes a repo-configured ``core.fsmonitor`` and clean filters.
  40. env = noninteractive_repo_git_env(cwd)
  41. if env is None:
  42. return None
  43. def run(*args: str) -> Optional[str]:
  44. try:
  45. out = subprocess.run(["git", "-C", cwd, *harden_git_argv(args)], capture_output=True,
  46. text=True, encoding="utf-8", errors="replace",
  47. stdin=subprocess.DEVNULL, timeout=_GIT_TIMEOUT_S, env=env, check=False)
  48. except (OSError, subprocess.SubprocessError):
  49. return None
  50. return out.stdout if out.returncode == 0 else None
  51. head = run("log", "-1", "--format=%h %s")
  52. if head is None:
  53. return None
  54. branch = (run("rev-parse", "--abbrev-ref", "HEAD") or "?").strip()
  55. status = run("status", "--porcelain")
  56. dirty = len(status.splitlines()) if status is not None else "?"
  57. return f"{branch} @ {head.strip()} ({dirty} uncommitted file(s)) in {cwd}"