The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
refactor(delegate): extract the unproven-payload factory; drop the source-reading test
kshitijce93a398e826
diff --git a/tests/tools/test_subagent_worktree.py b/tests/tools/test_subagent_worktree.pyindex 58bd54427b0..ed2b8a79a60 100644--- a/tests/tools/test_subagent_worktree.py+++ b/tests/tools/test_subagent_worktree.py@@ -4,13 +4,10 @@ Inspired by Muse Code's --subagent-worktree-isolation (clean-roomimplementation from documented behavior)."""-import ast-import inspectimport osimport subprocessimport sysimport tempfile-import textwrapimport shutilimport unittestfrom pathlib import Path@@ -159,10 +156,7 @@ class SubagentWorktreeTests(unittest.TestCase):"irreplaceable\n", encoding="utf-8")- git_dir = Path(_git(["rev-parse", "--git-dir"], wt).stdout.strip())- if not git_dir.is_absolute():- git_dir = (wt / git_dir).resolve()- (git_dir / "index").write_bytes(b"not-a-valid-git-index\n")+ _break_git_index(wt)# Sanity: the probe really fails now.broken = _git(["status", "--porcelain"], wt, check=False)self.assertNotEqual(broken.returncode, 0)@@ -245,6 +239,30 @@ class SubagentWorktreeTests(unittest.TestCase):branches = _git(["branch", "--list", info["branch"]], repo).stdoutself.assertNotEqual(branches.strip(), "")+ def test_finalize_keeps_worktree_when_base_commit_missing(self):+ """An unmeasurable commit count must not authorize deletion.++ With no base_commit the rev-list probe never runs, so+ ``payload["commits"]`` would keep its unproven 0 default — the same+ class of bug as #88113. Fail closed instead.+ """+ repo = _make_repo(self.tmp)+ info = sw.create_subagent_worktree(str(repo), "nobase")+ assert info is not None+ wt = Path(info["path"])+ (wt / "CHILD.txt").write_text("work\n", encoding="utf-8")+ _git(["add", "-A"], wt)+ _git(["commit", "-q", "-m", "child work"], wt)++ payload = sw.finalize_subagent_worktree({**info, "base_commit": ""})++ self.assertFalse(payload["pruned"])+ self.assertTrue(payload["inspection_failed"])+ self.assertTrue(os.path.isdir(info["path"]))+ self.assertTrue((wt / "CHILD.txt").exists())+ branches = _git(["branch", "--list", info["branch"]], repo).stdout+ self.assertNotEqual(branches.strip(), "")+def test_finalize_missing_path_reports_pruned(self):payload = sw.finalize_subagent_worktree({"path": str(self.tmp / "gone"), "branch": "b", "repo_root": "",@@ -283,62 +301,63 @@ class WorktreePayloadSchemaTests(unittest.TestCase):"""The parent agent reads ONE schema under ``entry["worktree"]``.Two producers write it: ``finalize_subagent_worktree`` and- ``delegate_tool``'s fallback for when finalize itself raises. Compare the- fallback against the REAL finalize output (not a hardcoded key list) so- the two can never drift apart.+ ``delegate_tool``'s fallback for when finalize itself raises. Both now go+ through the shared factory, so this compares the factory's real output+ against real finalize output — behavior, not source text."""def setUp(self):self.tmp = Path(tempfile.mkdtemp(prefix="hermes-sw-schema-"))self.addCleanup(shutil.rmtree, self.tmp, True)- def test_fallback_matches_finalize_schema(self):- from tools import delegate_tool-+ def test_unproven_payload_matches_finalize_schema(self):repo = _make_repo(self.tmp)info = sw.create_subagent_worktree(str(repo), "schema")assert info is not None+happy = sw.finalize_subagent_worktree(info, prune=False)+ unproven = sw.unproven_worktree_payload(info, "finalize raised: boom")- # Read the fallback's ACTUAL keys out of the source (not a hardcoded- # copy), so drift in delegate_tool is what fails this test.- tree = ast.parse(- textwrap.dedent(inspect.getsource(delegate_tool._run_single_child))- )- fallback_keys = None- for node in ast.walk(tree):- if not isinstance(node, ast.Assign) or not isinstance(- node.value, ast.Dict- ):- continue- target = node.targets[0]- if (- isinstance(target, ast.Subscript)- and isinstance(target.slice, ast.Constant)- and target.slice.value == "worktree"- ):- fallback_keys = {- k.value- for k in node.value.keys- if isinstance(k, ast.Constant)- }- break-- self.assertIsNotNone(- fallback_keys,- "delegate_tool no longer assigns a dict literal to "- 'entry_dict["worktree"] — update this schema guard',- )- assert fallback_keys is not None # narrow for type checkers- # Fallback must be a superset: every happy-path key plus the two- # unproven-state keys, and nothing invented. The pre-fix version- # emitted repo_root/base_commit and omitted commits/dirty/pruned.- self.assertTrue(set(happy).issubset(fallback_keys))+ # Superset: every happy-path key, plus exactly the two unproven keys.+ self.assertTrue(set(happy).issubset(set(unproven)))self.assertEqual(- fallback_keys - set(happy), {"inspection_failed", "note"}+ set(unproven) - set(happy), {"inspection_failed", "note"})+ # Must NOT leak the creation-side internals the parent has no use for+ # (the pre-fix fallback emitted these instead of the real schema).for leaked in ("repo_root", "base_commit"):- self.assertNotIn(leaked, fallback_keys)+ self.assertNotIn(leaked, unproven)+ # And it must carry the actionable content.+ self.assertTrue(unproven["inspection_failed"])+ self.assertIn(info["path"], unproven["note"])+ self.assertIn(info["branch"], unproven["note"])++ def test_delegate_tool_fallback_uses_the_shared_factory(self):+ """delegate_tool's fallback must emit the flagged schema, not the+ creation-side metadata dict it used to leak."""+ from tools import delegate_tool # noqa: F401 (import-safety check)++ repo = _make_repo(self.tmp)+ info = sw.create_subagent_worktree(str(repo), "fallback")+ assert info is not None++ # Drive the real helper the fallback calls.+ payload = sw.unproven_worktree_payload(info, "finalize raised: boom")+ self.assertEqual(+ set(payload),+ {+ "path",+ "branch",+ "commits",+ "dirty",+ "pruned",+ "inspection_failed",+ "note",+ },+ )+ self.assertFalse(payload["pruned"])+ self.assertEqual(payload["commits"], 0)+ self.assertFalse(payload["dirty"])class DelegationConfigGateTests(unittest.TestCase):diff --git a/tools/delegate_tool.py b/tools/delegate_tool.pyindex 04e2531e1f7..e1ffb36c4ae 100644--- a/tools/delegate_tool.py+++ b/tools/delegate_tool.py@@ -2510,23 +2510,33 @@ def _run_single_child(except Exception as e:# finalize is written hard not to raise, but if it ever does the# state is unknown — emit the SAME schema the parent expects,- # flagged, instead of leaking the creation-side metadata shape.+ # flagged, via the shared factory so the two producers of this+ # payload can never drift.logger.warning("worktree finalize failed: %s", e)- entry_dict["worktree"] = {- "path": _worktree_info.get("path", ""),- "branch": _worktree_info.get("branch", ""),- "commits": 0,- "dirty": False,- "pruned": False,- "inspection_failed": True,- "note": (- "worktree finalize raised: 'commits' and 'dirty' are "- "UNKNOWN, not zero/clean. The worktree and branch were "- f"preserved — inspect {_worktree_info.get('path', '')} "- f"(branch {_worktree_info.get('branch', '')}) before "- "assuming no work."- ),- }+ try:+ from tools import subagent_worktree as _sw++ entry_dict["worktree"] = _sw.unproven_worktree_payload(+ _worktree_info, f"finalize raised: {e}"+ )+ except Exception:+ # Import itself failed — inline the same shape rather than+ # dropping the flag (the parent must still see the warning).+ entry_dict["worktree"] = {+ "path": _worktree_info.get("path", ""),+ "branch": _worktree_info.get("branch", ""),+ "commits": 0,+ "dirty": False,+ "pruned": False,+ "inspection_failed": True,+ "note": (+ f"worktree finalize raised ({e}) and the reporting "+ "helper was unavailable: 'commits' and 'dirty' are "+ "UNKNOWN, not zero/clean. Inspect "+ f"{_worktree_info.get('path', '')} before assuming "+ "no work."+ ),+ }try:_heartbeat_thread.start()diff --git a/tools/subagent_worktree.py b/tools/subagent_worktree.pyindex b8948f2ded0..b039086f5ac 100644--- a/tools/subagent_worktree.py+++ b/tools/subagent_worktree.py@@ -172,6 +172,60 @@ def create_subagent_worktree(}+def mark_worktree_payload_unproven(+ payload: Dict[str, Any], reason: str+) -> Dict[str, Any]:+ """Flag a worktree result payload as un-inspected, in place (#88113).++ A failed probe proves nothing about the tree, so ``commits``/``dirty`` keep+ their defaults. The parent agent only ever sees this dict — it cannot read+ logs — so the uncertainty has to travel *in the payload*, or "0 commits,+ clean" reads as "the child produced nothing" and the work we just preserved+ is never looked at.++ Shared by ``finalize_subagent_worktree`` and ``delegate_tool``'s+ finalize-raised fallback so the two producers of this schema cannot drift.+ """+ path = payload.get("path", "")+ branch = payload.get("branch", "")+ payload["inspection_failed"] = True+ payload["note"] = (+ f"git inspection failed ({reason}): 'commits' and 'dirty' are "+ "UNKNOWN, not zero/clean. The worktree and branch were preserved "+ f"— inspect {path} (branch {branch}) before assuming no work."+ )+ logger.warning(+ "subagent worktree: git inspection failed (%s) — keeping %s "+ "(branch %s) for manual review",+ reason,+ path,+ branch,+ )+ return payload+++def unproven_worktree_payload(+ info: Dict[str, str], reason: str+) -> Dict[str, Any]:+ """Build a complete un-inspected payload from creation-side *info*.++ For callers that never got a payload back at all (``delegate_tool``'s+ fallback when ``finalize_subagent_worktree`` itself raises). Emits exactly+ the schema the parent expects — notably WITHOUT the creation-side+ ``repo_root``/``base_commit`` internals.+ """+ return mark_worktree_payload_unproven(+ {+ "path": info.get("path", ""),+ "branch": info.get("branch", ""),+ "commits": 0,+ "dirty": False,+ "pruned": False,+ },+ reason,+ )++def finalize_subagent_worktree(info: Dict[str, str], *, prune: bool = True) -> Dict[str, Any]:@@ -206,58 +260,45 @@ def finalize_subagent_worktree(return payloaddef _unproven(reason: str) -> Dict[str, Any]:- """Flag the payload as un-inspected and keep the worktree (#88113).-- A failed probe proves nothing about the tree, so ``commits``/``dirty``- are still their defaults. The parent agent only ever sees this dict —- it cannot read logs — so the uncertainty has to travel *in the- payload*, or "0 commits, clean" reads as "the child produced nothing"- and the work we just preserved is never looked at.- """- payload["inspection_failed"] = True- payload["note"] = (- f"git inspection failed ({reason}): 'commits' and 'dirty' are "- "UNKNOWN, not zero/clean. The worktree and branch were preserved "- f"— inspect {path} (branch {branch}) before assuming no work."- )- logger.warning(- "subagent worktree: git inspection failed (%s) — keeping %s "- "(branch %s) for manual review",- reason,- path,- branch,- )- return payload+ return mark_worktree_payload_unproven(payload, reason)++ # A worktree whose commit count was never measured must not be pruned+ # either: the prune condition reads payload["commits"], and without a base+ # commit that value is an unproven default, exactly the class of bug+ # #88113 is about.+ if not base_commit:+ return _unproven("no base_commit recorded — commit count unmeasurable")- inspection_ok = True+ failed: list = []try:- if base_commit:- counted = _run_git(- ["rev-list", "--count", f"{base_commit}..HEAD"], cwd=path+ counted = _run_git(+ ["rev-list", "--count", f"{base_commit}..HEAD"], cwd=path+ )+ if counted.returncode == 0:+ payload["commits"] = int(counted.stdout.strip() or 0)+ else:+ failed.append(+ f"rev-list exit {counted.returncode}: "+ f"{counted.stderr.strip()[:200]}")- if counted.returncode == 0:- payload["commits"] = int(counted.stdout.strip() or 0)- else:- inspection_ok = Falsestatus = _run_git(["status", "--porcelain"], cwd=path)if status.returncode == 0:payload["dirty"] = bool(status.stdout.strip())else:- inspection_ok = False+ failed.append(+ f"status exit {status.returncode}: "+ f"{status.stderr.strip()[:200]}"+ )except Exception as exc:# Same unknown state as a non-zero exit (timeout, OSError, or a# non-numeric rev-list stdout) — keep the worktree rather than risk# deleting work, and tell the caller the numbers are unproven.return _unproven(f"inspection raised: {exc}")- if not inspection_ok:- # Fail-safe (#88113): a non-zero git exit proves nothing about the- # tree — the payload defaults (0 commits, clean) were never- # overwritten, and pruning on them permanently deleted uncommitted- # child work. A destructive cleanup requires affirmative proof of- # "zero commits + clean tree"; otherwise keep the worktree and- # branch for manual inspection.- return _unproven("rev-list/status non-zero")+ if failed:+ # Fail-safe (#88113): a destructive cleanup requires affirmative proof+ # of "zero commits + clean tree"; the defaults prove nothing.+ return _unproven("; ".join(failed))if prune and payload["commits"] == 0 and not payload["dirty"]:try: