tangled_pr: verify against the pulls list, not a response header; and a tools test suite

THE BUG THAT PROMPTED THIS. tangled_pr.py judged success ONLY by an HX-Redirect header on the POST.
A create that SUCCEEDED but answered without that header read as a failure, so the caller retried
and Tangled grew duplicates — that is exactly how #397, #398 and #399 were filed for one branch. A
response header describes what the server meant to say; it is not the artifact.

Now it checks the artifact, in both directions:
  * BEFORE posting, refuse if an open pull already exists for this source branch, naming it. A
    retry cannot duplicate, whatever the response said. (--allow-duplicate to override.)
  * AFTER posting, confirm against the pulls list: a new pull number that did not exist before,
    whose page names this source branch, IS the success — with or without a redirect header.
  * Failure is reported only when no such pull appeared. A false failure is worse than a loud
    error here, because the caller's remedy is to retry.
Verified live: a dry-run against a branch that already has a pull refuses with rc=3, naming #417.

TWO REAL DEFECTS FOUND BY WRITING THE TESTS.

agents.py shelled out to `pgrep -P` and `ps -o comm=`. Neither is on the agent PATH on this host,
and a missing binary under shell=True returns rc=127 with EMPTY stdout — indistinguishable from
"this process has no children" and "no build is running". So _build_running was ALWAYS False and
the stall detector could reboot an agent mid-build. Both now read /proc directly: no PATH
dependency, and it cannot fail silently in that direction.

That shipped because the unit tests MOCKED pgrep and ps. The fakes stood in for the broken
dependency, so the suite passed on a host where neither tool was reachable and never exercised the
real path. The tests now patch _proc_descendants and _comms — the seams this repo owns. A test that
mocks a dependency proves the mock works.

Also fixed a monkeypatch leak those tests had: restoration used a name derivation that silently
matched nothing, so the patch escaped into another test class and failed an unrelated test — only
in a full run, never when that test ran alone. Now addCleanup, which cannot be ordered wrong.

NEW: tests/test_tools.py, 24 tests over tangled_pr, tangled_pr_close and gateway-domain, with every
HTTP boundary injected so they run offline. Mutation-checked: breaking classify(), the pull-number
regex, the branch match, or the scan bound each turns the suite red. Suite is 93 tests, green, and
order-stable across repeated runs.

README: a "PATH on a NixOS host" section. Every one of ps, pgrep, free, cmp, awk, curl, diff,
strings, nm, getent and ping is INSTALLED here and simply not on the agent PATH, so each reports
"command not found" and reads as a missing package. Documents how to check before concluding a tool
is absent, how to add the system profile, `nix shell` for what is genuinely missing, and the rule
that harness code should not shell out for what the kernel already exposes.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01V3LdmEL7CvCYTNpoBq1kce
This commit is contained in:
2026-08-21 03:50:11 +00:00
co-authored by Claude Fable 5
parent e1ba9b39be
commit e185cec88c
5 changed files with 427 additions and 29 deletions
+34 -14
View File
@@ -568,9 +568,17 @@ class TestProcDescendants(unittest.TestCase):
kids = agents._proc_descendants([str(p.pid)])
self.assertNotIn(str(p.pid), kids) # root excluded
self.assertGreaterEqual(len(kids), 2) # the two sleeps
comms = subprocess.run("ps -o comm= -p " + ",".join(sorted(kids)),
shell=True, capture_output=True, text=True).stdout
self.assertIn("sleep", comms)
# Read /proc/<pid>/comm rather than shelling to `ps -o comm=`: this host's ps
# returns nothing for that form, and an empty result from a tool that is absent or
# unsupported is indistinguishable from "the children are not sleeps". Same class of
# bug as the pgrep dependency this test just caught in _proc_descendants.
comms = []
for k in sorted(kids):
try:
comms.append(open(f"/proc/{k}/comm").read().strip())
except OSError:
pass
self.assertIn("sleep", comms, f"expected a sleep among {comms}")
finally:
os.killpg(os.getpgid(p.pid), signal.SIGKILL); p.wait()
@@ -594,26 +602,38 @@ class TestBuildRunning(unittest.TestCase):
self.ps_targets = ""
def tearDown(self):
# Restore EXPLICITLY. A cleverer derivation of these names silently matched nothing, so the
# monkeypatch leaked into the next test class and made an unrelated test fail — visible only
# in a full run, never when that test was run alone.
agents.subprocess.run = self._orig_run
shutil.rmtree(self.tmp, ignore_errors=True)
def _patch(self, descendant_comms):
"""Fake tmux/pgrep/ps: pane_pid=1000; its children are 1001,1002 with the given comms."""
"""pane_pid=1000; its children are 1001,1002 with the given comms.
Patches the two internal seams (_proc_descendants, _comms) rather than faking
`pgrep`/`ps` subprocess calls. WHY (2026-08-21): the previous version mocked those two
commands, so the suite passed on hosts where NEITHER IS INSTALLED — the fake stood in for
the broken dependency and the real bug (empty output read as "no build running", which
lets the watchdog reboot an agent mid-build) was invisible to every test. Mock the seam
you own, not the tool you depend on, or the test proves the mock works.
"""
outer = self
class R:
def __init__(self, out): self.stdout = out; self.returncode = 0
def fake_run(cmd, *a, **k):
if "list-panes" in cmd:
return R("1000\n")
if "pgrep -P 1000" in cmd:
return R("1001\n1002\n")
if "pgrep -P" in cmd:
return R("") # 1001/1002 are leaves
if cmd.startswith("ps -o comm="):
outer.ps_targets = cmd.split("-p", 1)[1].strip()
return R("\n".join(descendant_comms) + "\n")
return R("")
return R("1000\n") if "list-panes" in cmd else R("")
agents.subprocess.run = fake_run
orig_desc, orig_comms = agents._proc_descendants, agents._comms
def _restore():
agents._proc_descendants, agents._comms = orig_desc, orig_comms
self.addCleanup(_restore) # runs even if the test errors; no tearDown ordering to get wrong
agents._proc_descendants = lambda roots: (
{"1001", "1002"} if "1000" in list(roots) else set())
def fake_comms(pids):
outer.ps_targets = ",".join(sorted(pids))
return list(descendant_comms)
agents._comms = fake_comms
def test_detects_running_build(self):
self._patch(["bash", "cargo"])