`git fetch` leaves `git maintenance run --auto --detach` behind; it daemonizes, launchd (or a subreaper) reaps it, and agent-probe 0.1.0 records that reaper as its ppid while its depth still says where it was forked. components() then took it for a new child of the shell and gave it to the next `git` part: the call card said `git log --oneline -3` ran 23 s with 29 s CPU and 949 MB, when `git fetch`'s background gc did. _parents() puts such a process back under the process one level up that was running when it started, so old records read right too. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
312 lines
13 KiB
Python
312 lines
13 KiB
Python
"""Split a shell command line into the parts it runs, and put each process a
|
|
call started under the part it belongs to.
|
|
|
|
What the command *says* — ``cd x && npm run build 2>&1 | tail -20; vite &`` is
|
|
four parts joined by ``&&``, ``|``, ``;`` and a trailing ``&`` — is read here
|
|
with a small tokenizer (quotes, ``\\`` escapes, ``$( … )`` / backticks and
|
|
heredoc bodies stay inside their word or part). What *ran* is the call
|
|
probe's process tree (``sidecar/callprobe.py``): the shell's direct children
|
|
are the parts that weren't builtins — ``cd``, ``export``, ``echo`` never fork —
|
|
and everything under a child (``npm`` → ``node`` → ``esbuild``) belongs to
|
|
that part. The two are joined in order: each child takes the next part whose
|
|
program it is (``rtk`` and other wrappers seen through), so a part that
|
|
forked nothing shows as *builtin*, and a process no part names (a subshell's
|
|
fork, a ``$( … )``) joins the part that was running when it started.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import os
|
|
import re
|
|
|
|
_OPS = ("&&", "||", ";;", "|&", ";", "|", "&", "\n")
|
|
# Builtins and keywords: a part made of these forks nothing.
|
|
BUILTINS = {"cd", "export", "source", ".", "set", "shopt", "unset", "local", "pushd",
|
|
"popd", "true", "false", "echo", "printf", "test", "[", "[[", "read",
|
|
"return", "exit", "trap", "wait", "eval", "exec", "alias", "unalias",
|
|
"type", "command", "builtin", "declare", "typeset", "let", ":", "shift",
|
|
"umask", "ulimit", "hash", "jobs", "fg", "bg", "kill", "times", "getopts"}
|
|
_KEYWORDS = {"if", "then", "elif", "else", "fi", "for", "while", "until", "do", "done",
|
|
"case", "esac", "in", "function", "select", "!", "{", "}", "(", ")", "time"}
|
|
_ASSIGN_RE = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*(\[[^\]]*\])?\+?=")
|
|
_HEREDOC_RE = re.compile(r"<<-?\s*(['\"]?)([A-Za-z_][A-Za-z0-9_]*)\1")
|
|
_WRAPPERS = {"env", "nohup", "setsid", "timeout", "xvfb-run", "rtk", "time", "nice",
|
|
"flock", "stdbuf", "sudo", "uvx", "npx", "command", "exec", "builtin"}
|
|
MAX_PARTS = 40
|
|
|
|
|
|
def _strip_heredocs(cmd: str) -> str:
|
|
"""Drop heredoc bodies (they are data, not commands)."""
|
|
out, lines, i = [], cmd.split("\n"), 0
|
|
while i < len(lines):
|
|
line = lines[i]
|
|
out.append(line)
|
|
tags = [m.group(2) for m in _HEREDOC_RE.finditer(line)]
|
|
i += 1
|
|
for tag in tags:
|
|
while i < len(lines) and lines[i].strip() != tag:
|
|
i += 1
|
|
i += 1
|
|
return "\n".join(out)
|
|
|
|
|
|
def _tokens(cmd: str) -> list[tuple[str, str]]:
|
|
"""(kind, text): kind ``w`` a word, ``op`` an operator, ``(`` / ``)`` a
|
|
subshell bracket. Quotes, escapes and ``$( … )`` stay inside a word."""
|
|
out: list[tuple[str, str]] = []
|
|
i, n, word = 0, len(cmd), []
|
|
|
|
def flush():
|
|
if word:
|
|
out.append(("w", "".join(word)))
|
|
word.clear()
|
|
|
|
while i < n:
|
|
c = cmd[i]
|
|
if c == "\\" and i + 1 < n:
|
|
word.append(cmd[i:i + 2])
|
|
i += 2
|
|
elif c in "'\"`":
|
|
j = i + 1
|
|
while j < n and cmd[j] != c:
|
|
j += 2 if (c != "'" and cmd[j] == "\\") else 1
|
|
word.append(cmd[i:j + 1])
|
|
i = j + 1
|
|
elif c == "$" and i + 1 < n and cmd[i + 1] == "(":
|
|
depth, j = 0, i + 1
|
|
while j < n:
|
|
if cmd[j] == "(":
|
|
depth += 1
|
|
elif cmd[j] == ")":
|
|
depth -= 1
|
|
if depth == 0:
|
|
break
|
|
elif cmd[j] in "'\"":
|
|
q = cmd[j]
|
|
j += 1
|
|
while j < n and cmd[j] != q:
|
|
j += 1
|
|
j += 1
|
|
word.append(cmd[i:j + 1])
|
|
i = j + 1
|
|
elif c == "#" and not word: # a comment, to the end of the line
|
|
while i < n and cmd[i] != "\n":
|
|
i += 1
|
|
elif c in " \t":
|
|
flush()
|
|
i += 1
|
|
elif c == ")" or (c == "(" and not word):
|
|
flush()
|
|
out.append((c, c))
|
|
i += 1
|
|
else:
|
|
op = next((o for o in _OPS if cmd.startswith(o, i)), None)
|
|
# `2>&1`, `&>`, `>&`: a redirection, not the background operator
|
|
if op in ("&", "|&") and (cmd.startswith("&>", i) or (word and word[-1].endswith(">"))):
|
|
op = None
|
|
if op:
|
|
flush()
|
|
out.append(("op", op))
|
|
i += len(op)
|
|
else:
|
|
word.append(c)
|
|
i += 1
|
|
flush()
|
|
return out
|
|
|
|
|
|
def program(words: list[str]) -> str | None:
|
|
"""The program a simple command runs (assignments, keywords, redirections
|
|
and wrappers skipped) — None for a builtin-only part."""
|
|
ws = [w for w in words if not _ASSIGN_RE.match(w)]
|
|
if ws and ws[0] in ("for", "select", "case"): # `for i in …`: a loop header
|
|
return None
|
|
i = 0
|
|
while i < len(ws):
|
|
w = ws[i]
|
|
if w in _KEYWORDS:
|
|
i += 1
|
|
continue
|
|
if re.match(r"^\d*[<>]", w): # a redirection; its target next
|
|
i += 1 if re.search(r"[<>]&?\S+$", w) and not w.endswith((">", "<")) else 2
|
|
continue
|
|
base = os.path.basename(w.strip("'\""))
|
|
if base in _WRAPPERS:
|
|
i += 1
|
|
while i < len(ws) and (ws[i].startswith("-") or _ASSIGN_RE.match(ws[i])
|
|
or re.fullmatch(r"[\d.]+[smhd]?", ws[i])):
|
|
i += 1
|
|
if base == "rtk" and i < len(ws) and ws[i] == "proxy":
|
|
i += 1
|
|
continue
|
|
return None if base in BUILTINS else base
|
|
return None
|
|
|
|
|
|
def split(command: str) -> list[dict]:
|
|
"""The command's parts, in order: ``{text, program, op, background,
|
|
depth}`` — ``op`` joins it to the next part, ``depth`` counts the
|
|
subshells around it, ``program`` is None for a builtin-only part."""
|
|
toks = _tokens(_strip_heredocs(command or ""))
|
|
parts: list[dict] = []
|
|
words: list[str] = []
|
|
depth = 0
|
|
|
|
def close(op: str | None):
|
|
if words:
|
|
text = " ".join(words)
|
|
parts.append({"text": text[:300], "program": program(words), "op": op,
|
|
"background": op == "&", "depth": depth})
|
|
words.clear()
|
|
elif op and parts and parts[-1]["op"] is None:
|
|
parts[-1]["op"] = op
|
|
parts[-1]["background"] = op == "&"
|
|
|
|
for kind, text in toks:
|
|
if kind == "w":
|
|
words.append(text)
|
|
elif kind == "(":
|
|
close(None)
|
|
depth += 1
|
|
elif kind == ")":
|
|
close(None)
|
|
depth = max(0, depth - 1)
|
|
else:
|
|
close(None if text == "\n" else text)
|
|
if len(parts) >= MAX_PARTS:
|
|
break
|
|
close(None)
|
|
return parts
|
|
|
|
|
|
def _matches(prog: str | None, proc: dict) -> bool:
|
|
"""Is ``proc`` the part's program? Its label or command line names it
|
|
among their first words — ``npx tsc`` runs as ``npm exec tsc``,
|
|
``timeout 30 pytest`` as ``timeout``, ``rtk git status`` as ``rtk``."""
|
|
if not prog:
|
|
return False
|
|
words = f"{proc.get('label') or ''} {proc.get('argv') or ''}".split()[:8]
|
|
names = {os.path.basename(w.strip("'\"")) for w in words}
|
|
if prog in names:
|
|
return True
|
|
return any(n.startswith(prog) for n in names if len(prog) >= 3)
|
|
|
|
|
|
_SHELLS = {"bash", "sh", "zsh", "dash"}
|
|
|
|
|
|
def _is_fork(top: dict, shell: dict) -> bool:
|
|
"""A copy of the shell itself — a ``( … )`` / ``$( … )`` subshell, a
|
|
compound command in a pipeline — rather than a program it ran: it carries
|
|
the shell's own command line."""
|
|
if top.get("argv") and shell.get("argv"):
|
|
return top["argv"] == shell["argv"]
|
|
return os.path.basename((top.get("label") or "").split(" ")[0]) in _SHELLS
|
|
|
|
|
|
_SLACK = 0.05 # s — start / end times are rounded to the millisecond, and read late
|
|
|
|
|
|
def _parents(procs: list[dict], shell: dict) -> dict[int, int | None]:
|
|
"""Each process's fork parent. A process that daemonized (`git fetch` →
|
|
`git maintenance run --auto --detach` → `git gc`) was reparented to init /
|
|
launchd / a subreaper before it ended, and records up to agent-probe
|
|
0.1.0 carry that reaper as its ``ppid`` — while its ``depth`` still says
|
|
where it was forked. Such a process goes back under the one a level up
|
|
that was running when it started (the latest to start, when several were)."""
|
|
by_pid = {p["pid"]: p for p in procs}
|
|
out: dict[int, int | None] = {}
|
|
for p in procs:
|
|
ppid, depth = p.get("ppid"), p.get("depth")
|
|
out[p["pid"]] = ppid
|
|
if p is shell or ppid in by_pid or depth is None or depth <= (shell.get("depth") or 0) + 1:
|
|
continue
|
|
t = p.get("startedAt") or 0
|
|
up = [q for q in procs if q is not p and q.get("depth") == depth - 1
|
|
and (q.get("startedAt") or 0) <= t + _SLACK]
|
|
alive = [q for q in up if q.get("endedAt") is None or q["endedAt"] >= t - _SLACK]
|
|
if alive or up:
|
|
out[p["pid"]] = max(alive or up, key=lambda q: q.get("startedAt") or 0)["pid"]
|
|
return out
|
|
|
|
|
|
def components(command: str, procs: list[dict]) -> list[dict]:
|
|
"""The call's parts, each with the processes it ran (its subtree, in
|
|
start order) and their sums: ``{text, program, op, background, builtin,
|
|
procs: [pid…], cpu, peakRss, exitCode}``. Processes no part takes are a
|
|
last ``other`` part."""
|
|
parts = [{**p, "pids": [], "cpu": 0.0, "peakRss": 0, "exitCode": None,
|
|
"startedAt": None, "endedAt": None} for p in split(command)]
|
|
if not procs:
|
|
return [{**p, "builtin": p["program"] is None} for p in parts]
|
|
by_pid = {p["pid"]: p for p in procs}
|
|
shell = min(procs, key=lambda p: (p.get("depth", 0), p.get("startedAt") or 0))
|
|
parent = _parents(procs, shell)
|
|
kids: dict[int, list[dict]] = {}
|
|
for p in procs:
|
|
if p is not shell:
|
|
kids.setdefault(parent[p["pid"]], []).append(p)
|
|
# the shell's direct children, in start order — a daemonized descendant
|
|
# is back under its fork parent (`_parents`), so it isn't among them
|
|
tops = sorted((p for p in procs if p is not shell and (parent[p["pid"]] == shell["pid"]
|
|
or parent[p["pid"]] not in by_pid)),
|
|
key=lambda p: p.get("startedAt") or 0)
|
|
owner: dict[int, int] = {}
|
|
cursor = 0
|
|
for k, top in enumerate(tops):
|
|
idx = next((i for i in range(cursor, len(parts)) if _matches(parts[i]["program"], top)),
|
|
None)
|
|
if idx is None and not _is_fork(top, shell):
|
|
# a program no part names — an alias, a script that execs into
|
|
# another (`dev-up` → `uv run … dev_env.py`): the next part with a
|
|
# program, unless a process still to come is that one by name
|
|
idx = next((i for i in range(cursor, len(parts)) if parts[i]["program"]), None)
|
|
if idx is not None and any(_matches(parts[idx]["program"], t) for t in tops[k + 1:]):
|
|
idx = None
|
|
if idx is None: # a forked subshell, `$( … )`: the part running then
|
|
idx = max(0, cursor - 1) if cursor else (0 if parts else None)
|
|
# a subshell's fork carries the shell's own argv: its first
|
|
# descendant with a program of its own names it
|
|
if parts and idx is not None and not _matches(parts[idx]["program"], top):
|
|
sub = next((d for d in kids.get(top["pid"], []) if any(
|
|
_matches(p["program"], d) for p in parts[cursor:])), None)
|
|
if sub is not None:
|
|
idx = next(i for i in range(cursor, len(parts)) if _matches(parts[i]["program"], sub))
|
|
else:
|
|
cursor = idx + 1
|
|
parts[idx]["_top"] = top # its status is the part's (a pipeline's last)
|
|
if idx is None:
|
|
continue
|
|
stack = [top]
|
|
while stack:
|
|
p = stack.pop()
|
|
owner[p["pid"]] = idx
|
|
stack += kids.get(p["pid"], [])
|
|
other = {"text": "", "program": None, "op": None, "background": False, "depth": 0,
|
|
"pids": [], "cpu": 0.0, "peakRss": 0, "exitCode": None,
|
|
"startedAt": None, "endedAt": None, "other": True}
|
|
for p in sorted(procs, key=lambda p: p.get("startedAt") or 0):
|
|
if p is shell:
|
|
continue
|
|
part = parts[owner[p["pid"]]] if p["pid"] in owner else other
|
|
part["pids"].append(p["pid"])
|
|
part["cpu"] += p.get("cpuOwn") or 0
|
|
part["peakRss"] = max(part["peakRss"], p.get("peakRss") or 0)
|
|
if part["startedAt"] is None or (p.get("startedAt") or 0) < part["startedAt"]:
|
|
part["startedAt"] = p.get("startedAt")
|
|
if p.get("endedAt") and (part["endedAt"] is None or p["endedAt"] > part["endedAt"]):
|
|
part["endedAt"] = p["endedAt"]
|
|
for part in parts:
|
|
top = part.pop("_top", None)
|
|
if top is not None:
|
|
if top.get("exitCode") is not None:
|
|
part["exitCode"] = top["exitCode"]
|
|
elif top.get("signal") is not None:
|
|
part["exitCode"] = 128 + top["signal"] # the shell's own convention
|
|
out = [{**p, "builtin": p["program"] is None and not p["pids"], "cpu": round(p["cpu"], 4)}
|
|
for p in parts]
|
|
if other["pids"]:
|
|
other["cpu"] = round(other["cpu"], 4)
|
|
out.append({**other, "builtin": False})
|
|
return out
|