From 1b747ef6c0065755f946a83a6d7a194dbfa5379f Mon Sep 17 00:00:00 2001 From: datacas <4690232+datacas@users.noreply.github.com> Date: Mon, 30 Nov 2026 11:10:36 +0100 Subject: [PATCH 1/5] fix: attribute Claude stage refusals to the layer that refused and keep completed work (#550) A hook deny also appears in Claude's permission_denials, so every toolkit-hook refusal was recorded a second time as claude_permission, without the hook's rule, operation or intent; that record kept a published implementation BLOCKED. Entries answered by the hook are no longer recorded again. An inherited MCP tool the host refused is judged with the stage's refusals as a host limit and never becomes a question. Before the cycle records its change request, an implement stage may name its own branch's open pull request by number. Refs #550 --- scripts/command_permissions.py | 7 +- scripts/executors.py | 54 ++-- scripts/stage_permissions.py | 41 ++- tests/test_claude_stage_refusals.py | 377 ++++++++++++++++++++++++++++ 4 files changed, 456 insertions(+), 23 deletions(-) create mode 100644 tests/test_claude_stage_refusals.py diff --git a/scripts/command_permissions.py b/scripts/command_permissions.py index 4db6e5c..af4f192 100644 --- a/scripts/command_permissions.py +++ b/scripts/command_permissions.py @@ -13,7 +13,7 @@ ALLOW_CYCLE, ALLOW_PERSISTENT, ALLOW_GLOBAL, DENY, denial_context, granted_context) from stage_permissions import (operation, matching_answer, protected_reason, credential_reason, parse_command, consent_role, split_environment, same_operation, configured_check_id, - TOOL_RESULT_OUTPUT, is_session_tool_results) + TOOL_RESULT_OUTPUT, is_session_tool_results, MCP_TOOL_PREFIX) #: Top-level keys only the runtime writes into a stage's result, after the agent @@ -621,6 +621,11 @@ def classify_denial(record: dict[str, Any], payload: dict[str, Any] | None, *, return ESSENTIAL_PERMISSION, "the refused command is a mandatory check" if record.get("inspection") is True: return AUXILIARY_DENIAL, "the command only inspects JSON/argv data" + if str(record["tool"]).startswith(MCP_TOOL_PREFIX): + # The host refused a tool the stage inherited (#486, #550): a host + # limit, recorded as such. The call never ran, and the published state + # the runtime verifies, not the tool, decides whether the work is done. + return AUXILIARY_DENIAL, "the host refused an inherited MCP tool; recorded as a host limit" if record["tool"] != "Bash": target = record.get("target") tmpdir = record.get("tmpdir") diff --git a/scripts/executors.py b/scripts/executors.py index f0fe36a..9ade018 100644 --- a/scripts/executors.py +++ b/scripts/executors.py @@ -3380,28 +3380,17 @@ def add(command) -> None: bash_calls: dict[str, str] = {} operation_calls: dict[str, dict[str, Any]] = {} + # The calls the stage hook refused. Claude also lists a hook's `deny` + # among its `permission_denials`; that entry is the same refusal, not a + # second one by the permission layer, so it is never recorded again as + # `claude_permission` (#550). + hook_refused: set[str] = set() + results: list[dict[str, Any]] = [] for event in _events(stdout): kind = event.get("type") if kind == "result": - for denial in event.get("permission_denials") or []: - if not isinstance(denial, dict): - continue - tool = denial.get("tool_name") - tool_input = denial.get("tool_input") - tool_input = tool_input if isinstance(tool_input, dict) else {} - if tool == "Bash": - add(tool_input.get("command")) - if tool == "Bash" or tool in sp.FILE_EDIT_TOOLS: - command_refusals.append({"tool": tool, "input": tool_input, - "layer": "claude_permission"}) - target = (tool_input.get("command") or tool_input.get("file_path") - or tool_input.get("notebook_path") or tool_input.get("url")) - entry: dict[str, object] = {"tool": str(tool or "unknown")[:80], - "command": failure_excerpt(target, 300) if isinstance(target, str) else None, - "tool_use_id": denial.get("tool_use_id") - if isinstance(denial.get("tool_use_id"), str) else None} - if entry not in layer: - layer.append(entry) + # Read after every tool result, whatever the stream's order. + results.append(event) continue message = event.get("message") content = message.get("content") if isinstance(message, dict) else None @@ -3423,6 +3412,7 @@ def add(command) -> None: tool_output = _tool_result_text(block.get("content")) command = bash_calls.get(tool_use_id) if sp.HOOK_DENIAL_MARKER in tool_output: + hook_refused.add(tool_use_id) add(command) refusal = operation_calls.get(tool_use_id) if refusal is not None: @@ -3463,6 +3453,32 @@ def add(command) -> None: } if failure not in sandbox_startup_failures: sandbox_startup_failures.append(failure) + for event in results: + for denial in event.get("permission_denials") or []: + if not isinstance(denial, dict): + continue + tool_use_id = denial.get("tool_use_id") + if isinstance(tool_use_id, str) and tool_use_id in hook_refused: + continue + tool = denial.get("tool_name") + tool_input = denial.get("tool_input") + tool_input = tool_input if isinstance(tool_input, dict) else {} + if tool == "Bash": + add(tool_input.get("command")) + if (tool == "Bash" or tool in sp.FILE_EDIT_TOOLS + or (isinstance(tool, str) and tool.startswith(sp.MCP_TOOL_PREFIX))): + # An inherited MCP tool is judged with the stage's other + # refusals (#550) but never becomes a question: the + # toolkit neither hides nor pre-approves it (#486). + command_refusals.append({"tool": tool, "input": tool_input, + "layer": "claude_permission"}) + target = (tool_input.get("command") or tool_input.get("file_path") + or tool_input.get("notebook_path") or tool_input.get("url")) + entry: dict[str, object] = {"tool": str(tool or "unknown")[:80], + "command": failure_excerpt(target, 300) if isinstance(target, str) else None, + "tool_use_id": tool_use_id if isinstance(tool_use_id, str) else None} + if entry not in layer: + layer.append(entry) artifacts: dict[str, object] = {"permission_denials": denied} if denied else {} # A command is evidence only when its observed tool result completed. for event in _events(stdout): diff --git a/scripts/stage_permissions.py b/scripts/stage_permissions.py index 970e197..8ac4924 100644 --- a/scripts/stage_permissions.py +++ b/scripts/stage_permissions.py @@ -145,6 +145,9 @@ def credential_read_denials(*, publishes: bool = False, #: In every denial reason, so the runtime can tell this hook's denials apart. HOOK_DENIAL_MARKER = "stage policy denied this command" +#: How Claude Code names a tool an MCP server provides. The stage inherits +#: these from the host; the toolkit neither hides nor pre-approves them (#486). +MCP_TOOL_PREFIX = "mcp__" #: The fixed Bash timeout of a dispatched Claude `-p` stage, in milliseconds #: (10 minutes). Claude Code reads it from the `env` of the dispatch settings. CLAUDE_VERIFICATION_TIMEOUT_MS = 600_000 @@ -3144,9 +3147,11 @@ def _check_gh(args: list[str], policy: StagePolicy, *, cwd: str | None, run, if spec.scope == "pr": expected = policy.pr_number if expected is None: - # Before the change request exists (an implementation opens it), - # only the current branch's own one may be named, by naming none. - if positional: + # Before the cycle records a change request (an implementation + # opens it), only the current branch's own one may be targeted: + # by naming none, or by naming the number GitHub reports as this + # branch's open pull request in this repository (#550). + if positional and not _branch_pull_request(positional[0], policy, cwd=cwd, run=run): raise PolicyError(f"gh {' '.join(key)} may target only the current branch's " "change request until this cycle has one") elif not positional or _number(positional[0], ("/pull/", "#")) != expected: @@ -3176,6 +3181,36 @@ def lookup_github_field(path: str, jq: str, *, cwd: str | None = None, GITHUB_FIELD = lookup_github_field +def _branch_pull_request(reference: str, policy: StagePolicy, *, cwd: str | None, + run=subprocess.run) -> bool: + """Whether `reference` is the open pull request of the checkout's branch (#550). + + `gh pr edit` and `gh pr comment` with no argument already target that pull + request; naming its number reaches the same one and nothing else. Both + facts are read at the moment of the call, from the configured repository + and the checkout, and any doubt keeps the refusal (fail closed). + """ + number = _number(reference, ("/pull/", "#")) + if (number is None or not number.isdigit() or not policy.repo + or not _SAFE_REPOSITORY.fullmatch(policy.repo)): + return False + try: + branch = run(["git", "branch", "--show-current"], cwd=cwd, capture_output=True, + text=True, timeout=10, stdin=subprocess.DEVNULL) + except (OSError, subprocess.SubprocessError): + return False + current = (branch.stdout or "").strip() if branch.returncode == 0 else "" + if not current: + return False + found = GITHUB_FIELD(f"repos/{policy.repo}/pulls/{number}", + '[.state, .head.repo.full_name, .head.ref] | join(" ")', cwd=cwd, run=run) + if found is None: + return False + state, _, rest = found.partition(" ") + repository, _, ref = rest.partition(" ") + return state == "open" and repository.lower() == policy.repo.lower() and ref == current + + def _checked_repository(policy: StagePolicy) -> str: if not policy.repo or not _SAFE_REPOSITORY.fullmatch(policy.repo): raise PolicyError("this stage has no configured repository to read failed checks in") diff --git a/tests/test_claude_stage_refusals.py b/tests/test_claude_stage_refusals.py new file mode 100644 index 0000000..b2b31c0 --- /dev/null +++ b/tests/test_claude_stage_refusals.py @@ -0,0 +1,377 @@ +"""Which layer refused a Claude stage's command, and completed work survives it (#550). + +The reported refusals came from the toolkit's stage hook. Claude also lists a +hook's `deny` in its `permission_denials`, so each was recorded a second time as +`claude_permission`, without the hook's rule, operation or intent. That second +record kept a finished implementation `BLOCKED`. +""" +from __future__ import annotations + +import io +import json +import os +import shlex +import subprocess +import sys +import tempfile +import unittest +from dataclasses import replace +from fnmatch import fnmatchcase +from pathlib import Path +from unittest import mock + +ROOT = Path(__file__).resolve().parent.parent +sys.path.insert(0, str(ROOT / "scripts")) +sys.path.insert(0, str(Path(__file__).resolve().parent)) + +import command_permissions as cp +import executors as ex +import grants +import router +import run_cycle as rc +import stage_permissions as sp +from test_command_permissions import SHA, published +from test_run_cycle import RunCycleTestCase, Talker, block + +#: The refusals reported from the #486 cycle (PR #549) and the #503 cycle +#: (PR #554), with the repository and the change request made generic. +REPORTED_486 = ( + 'git grep -n "def require_security" -- scripts', + 'git grep -n -F "prefix=\\"diff-" -- scripts', + 'git grep -n -e tool-results -e "tasks/" -e "def test" -- tests/test_read_parity.py', + "git diff --output=$TMPDIR/wip.diff", + "gh pr view 549 --repo owner/repo --json headRefOid,statusCheckRollup,body --jq '.headRefOid'", + 'grep -n "def \\(stage\\|require_security\\|complete\\|mark\\)" scripts/plan_service.py', + 'grep -rn "exactly one attributable" scripts/stage_evidence.py', + 'git grep -n "def receipt_problem" -- scripts', + 'gh pr view 549 --repo owner/repo --json comments --jq ".comments[-1].url"', +) +REPORTED_503 = ( + "git grep -n -A3 receipt -- scripts", + "git grep -n -B2 receipt -- scripts", + "git grep -n -o receipt -- scripts", + 'git grep -n -i -E "receipt|attempt" -- scripts', + 'grep -n "import yaml" tests/test_cycle.py', + "git ls-files scripts | head -200; wc -l scripts/cycle.py", + "git --version", + "printenv CODE_CYCLE_STAGE_ROLE", + "gh pr view 549 --json headRefOid,body --jq .headRefOid", +) +#: The stage's own publication, before the cycle records its change request. +OWN_PUBLICATION = ( + "gh pr edit 549 --repo owner/repo --body-file $TMPDIR/report.md", + "gh pr comment 549 --body-file $TMPDIR/pr-comment.md", +) +#: #524: these stay free of consent; everything else above keeps asking. +CONSENT_FREE = frozenset({ + "git grep -n -A3 receipt -- scripts", "git grep -n -B2 receipt -- scripts", + "git grep -n -o receipt -- scripts", + "gh pr view 549 --json headRefOid,body --jq .headRefOid", +}) + + +def claude_admits(command: str, patterns: list[str]) -> bool: + """Whether an `--allowedTools` entry admits every segment of `command`. + + A model of Claude Code's rule matching: `Bash(prefix:*)` by word prefix and + `Bash(glob)` by pattern, each pipeline or list segment on its own. The + native run in docs/native-parity-runs.md checks Claude Code itself. + """ + lexer = shlex.shlex(command, posix=True, punctuation_chars="|;&") + lexer.whitespace_split = True + segments, current = [], [] + for token in lexer: + if token in {"|", ";", "&&", "||"}: + segments.append(current) + current = [] + else: + current.append(token) + segments.append(current) + texts = [part.strip() for part in command.replace("&&", ";").replace("||", ";") + .replace("|", ";").split(";")] + for words, text in zip(segments, texts): + admitted = False + for pattern in patterns: + if not (pattern.startswith("Bash(") and pattern.endswith(")")): + continue + body = pattern[len("Bash("):-1] + if body.endswith(":*"): + prefix = body[:-2].split() + admitted = words[:len(prefix)] == prefix + else: + admitted = fnmatchcase(text, body) + if admitted: + break + if not admitted: + return False + return True + + +class StageFixture(unittest.TestCase): + def setUp(self): + scratch = tempfile.TemporaryDirectory(prefix="code-cycle-tmp-") + self.addCleanup(scratch.cleanup) + self.root = Path(scratch.name) + self.cwd = self.root / "checkout" + self.cwd.mkdir() + subprocess.run(["git", "init", "-q", "-b", "fix/550-claude"], cwd=self.cwd, check=True) + self.tmpdir = self.root / "dispatch" + self.tmpdir.mkdir() + + def policy(self, role="implement", **changes): + return replace(sp.StagePolicy(role, repo="owner/repo", work_item_id="486", + base_branch="main", tmpdir=str(self.tmpdir)), **changes) + + def broker(self): + return grants.ConsentBroker("owner/repo", platform="linux", + store=grants.ConsentStore(self.root / "consents.json")) + + def hook_reason(self, policy, command): + """What the stage hook says to Claude about `command`, or None when allowed.""" + path = self.root / "policy.json" + path.write_text(policy.to_json()) + output = io.StringIO() + sp.hook_main([str(path)], io.StringIO(json.dumps({ + "tool_name": "Bash", "tool_input": {"command": command}, "cwd": str(self.cwd)})), output) + if not output.getvalue(): + return None + return json.loads(output.getvalue())["hookSpecificOutput"]["permissionDecisionReason"] + + +def stream(*events) -> str: + return "\n".join(json.dumps(event) for event in events) + + +def tool_call(identifier, name, tool_input): + return {"type": "assistant", "message": {"content": [ + {"type": "tool_use", "id": identifier, "name": name, "input": tool_input}]}} + + +def tool_error(identifier, text): + return {"type": "user", "message": {"content": [ + {"type": "tool_result", "tool_use_id": identifier, "is_error": True, "content": text}]}} + + +def denied(identifier, name, tool_input): + return {"tool_name": name, "tool_use_id": identifier, "tool_input": tool_input} + + +@unittest.skipIf(os.name == "nt", "POSIX command forms") +class ReportedCommandTests(StageFixture): + """AC-1/AC-4: each reported command runs or asks; none is refused silently.""" + + def test_each_reported_command_runs_or_asks_and_claude_admits_it_once_decided(self): + for role in ("implement", "review"): + commands = REPORTED_486 + REPORTED_503 + (OWN_PUBLICATION if role == "implement" else ()) + policy = self.policy(role, change_request_id="549") + for command in commands: + with self.subTest(role=role, command=command): + decision = sp.check(command, policy, cwd=str(self.cwd)) + current = policy + if not decision.allowed: + broker = self.broker() + request = cp.refused_operation([command], policy, broker, "claude", str(self.cwd)) + self.assertIsNotNone(request, decision.reason) # asked, never silent + assert request is not None + grant = broker.operations[request["resource"]] + broker.apply_answer(grant, grant.scopes[0], "cycle") + current = replace(policy, command_permissions=tuple( + broker.command_entries("claude", role))) + self.assertTrue(sp.check(command, current, cwd=str(self.cwd)).allowed) + # What the hook lets through, Claude's own layer must not refuse. + self.assertTrue(claude_admits(command, sp.allowed_tool_patterns(current)), + sp.allowed_tool_patterns(current)) + + def test_524_consent_boundaries_are_kept(self): + policy = self.policy(change_request_id="549") + for command in REPORTED_486 + REPORTED_503: + with self.subTest(command=command): + self.assertEqual(command in CONSENT_FREE, + sp.check(command, policy, cwd=str(self.cwd)).allowed) + + def test_the_refusals_come_from_the_toolkit_hook(self): + policy = self.policy(change_request_id="549") + for command in sorted(set(REPORTED_486 + REPORTED_503) - CONSENT_FREE): + with self.subTest(command=command): + reason = self.hook_reason(policy, command) + assert reason is not None + self.assertIn("[layer=toolkit_hook]", reason) + self.assertIn("COMMAND_PERMISSION_ID=", reason) + + +@unittest.skipIf(os.name == "nt", "POSIX command forms") +class OwnChangeRequestTests(StageFixture): + """The stage may name its own branch's pull request before the cycle records it.""" + + def lookup(self, value): + return mock.patch.object(sp, "GITHUB_FIELD", lambda path, jq, **_: ( + value if path == "repos/owner/repo/pulls/549" else None)) + + def test_the_branch_pull_request_can_be_named(self): + policy = self.policy() + with self.lookup("open owner/repo fix/550-claude"): + for command in OWN_PUBLICATION: + with self.subTest(command=command): + self.assertTrue(sp.check(command, policy, cwd=str(self.cwd)).allowed) + + def test_any_doubt_keeps_the_refusal(self): + policy = self.policy() + for value in ("closed owner/repo fix/550-claude", "open fork/repo fix/550-claude", + "open owner/repo main", "open owner/repo", None): + with self.subTest(value=value), self.lookup(value): + for command in OWN_PUBLICATION + ("gh pr edit 550 --body-file $TMPDIR/report.md",): + decision = sp.check(command, policy, cwd=str(self.cwd)) + self.assertFalse(decision.allowed) + self.assertIn("current branch's change request", decision.reason) + + def test_a_checkout_without_a_branch_keeps_the_refusal(self): + detached = self.root / "plain" + detached.mkdir() + with self.lookup("open owner/repo fix/550-claude"): + self.assertFalse(sp.check(OWN_PUBLICATION[0], self.policy(), cwd=str(detached)).allowed) + + def test_a_recorded_change_request_is_still_exact(self): + policy = self.policy(change_request_id="548") + with self.lookup("open owner/repo fix/550-claude"): + self.assertFalse(sp.check(OWN_PUBLICATION[0], policy, cwd=str(self.cwd)).allowed) + self.assertTrue(sp.check("gh pr edit --body-file $TMPDIR/report.md", self.policy(), + cwd=str(self.cwd)).allowed) + + +@unittest.skipIf(os.name == "nt", "POSIX command forms") +class AttributionTests(StageFixture): + """AC-3: the layer that refused is the layer recorded, once.""" + + def test_a_hook_denial_is_not_recorded_again_as_claude_permission(self): + command = 'git grep -n "def require_security" -- scripts' + reason = self.hook_reason(self.policy(), command) + artifacts = ex.ClaudeAdapter().extra_artifacts(stream( + tool_call("t1", "Bash", {"command": command}), tool_error("t1", reason), + {"type": "result", "permission_denials": [denied("t1", "Bash", {"command": command})]})) + self.assertEqual([command], artifacts["permission_denials"]) + self.assertNotIn("claude_permission_denials", artifacts) + records = cp.denial_records(artifacts["command_refusals"], self.policy(), "claude", str(self.cwd)) + self.assertEqual(["toolkit_hook"], [record["layer"] for record in records]) + self.assertEqual("command_table", records[0]["rule"]) + + def test_a_refusal_without_a_hook_answer_stays_claude_permission(self): + command = "git status" + artifacts = ex.ClaudeAdapter().extra_artifacts(stream( + tool_call("t1", "Bash", {"command": command}), + tool_error("t1", "Claude requested permissions to use Bash, but you haven't granted it yet."), + {"type": "result", "permission_denials": [denied("t1", "Bash", {"command": command})]})) + self.assertEqual(["t1"], [item["tool_use_id"] for item in artifacts["claude_permission_denials"]]) + records = cp.denial_records(artifacts["command_refusals"], self.policy(), "claude", str(self.cwd)) + self.assertEqual(["claude_permission"], [record["layer"] for record in records]) + + def test_an_inherited_mcp_refusal_is_a_host_limit_and_never_a_question(self): + tool, data = "mcp__serena__find_symbol", {"name_path_pattern": "require_security"} + artifacts = ex.ClaudeAdapter().extra_artifacts(stream( + tool_call("t1", tool, data), + {"type": "result", "permission_denials": [denied("t1", tool, data)]})) + self.assertEqual([tool], [item["tool"] for item in artifacts["claude_permission_denials"]]) + refusals = artifacts["command_refusals"] + self.assertIsNone(cp.refused_operation(refusals, self.policy(), self.broker(), "claude", + str(self.cwd))) + records = cp.classify_denials( + cp.denial_records(refusals, self.policy(), "claude", str(self.cwd)), {}) + self.assertEqual([("claude_permission", cp.AUXILIARY_DENIAL)], + [(record["layer"], record["class"]) for record in records]) + + +class StreamingClaude(Talker): + """A Claude implementer whose refusals pass through the real hook and parser.""" + + def __init__(self, fixture, calls, status="BLOCKED"): + super().__init__("claude") + self.fixture, self.calls, self.status = fixture, calls, status + + def dispatch(self, target, task, **kwargs): + self.dispatched.append(task) + policy = kwargs.get("command_policy") + if policy is None or policy.role != "implement": + return ex.DispatchResult(ex.DispatchOutcome.SUCCEEDED, "claude", target, + start_state="started", process_exited=True, agent_output=block("APPROVED")) + # The fixture cycle has no GitHub command table, so the hook answers + # with the implement stage's table for this repository. + policy = self.fixture.policy(repo="owner/api", work_item_id="435") + events, denials = [], [] + for index, (tool, data) in enumerate(self.calls): + identifier = f"t{index}" + events.append(tool_call(identifier, tool, data)) + if tool == "Bash": + reason = self.fixture.hook_reason(policy, data["command"]) + self.fixture.assertIsNotNone(reason, data["command"]) + events.append(tool_error(identifier, reason)) + denials.append(denied(identifier, tool, data)) + events.append({"type": "result", "permission_denials": denials}) + spoken = block(self.status, head_sha=SHA, change_request_id="442", + work_units=[{"id": "WU-1", "commit_sha": SHA, "rollback": "independent"}], + tests={"ran": True, "passed": True, "checks": []}) + return ex.DispatchResult(ex.DispatchOutcome.SUCCEEDED, "claude", target, + start_state="started", process_exited=True, agent_output=spoken, + artifacts=ex.ClaudeAdapter().extra_artifacts(stream(*events))) + + +@unittest.skipIf(os.name == "nt", "POSIX command forms") +class CompletedStageTests(RunCycleTestCase): + """AC-2: an optional refusal never turns a published implementation into BLOCKED.""" + + def setUp(self): + super().setUp() + self.fixture = StageFixture() + self.fixture.setUp() + self.addCleanup(self.fixture.doCleanups) + + def cycle(self, calls, status="BLOCKED"): + claude = StreamingClaude(self.fixture, calls, status) + broker = grants.ConsentBroker("owner/api", platform="linux", + store=grants.ConsentStore(self.home / "consents.json")) + profiles = router.load_profiles({"code_cycle": {"profiles": { + "deep_coder": {"primary": "claude:anthropic/claude-opus-5-5 high"}, + "reviewer": {"primary": "claude:anthropic/claude-sonnet-5 high"}}}}) + report = rc.run_cycle("owner/api", "435", router.TaskSignals(), self.store, + registry=ex.Registry([claude]), availability={"claude": ex.Availability.READY}, + profiles=profiles, issue_review="off", consent=broker, + publication_observer=lambda *_: published(), trusted_authors=("reviewer",)) + return report, claude + + def journal(self, component): + from cycle_journal import events + return [row for row in events(self.store.path, "owner/api") if row["component"] == component] + + def assert_completed(self, report, claude): + self.assertEqual(rc.APPROVED_END, report.status, report.stopped_because) + self.assertEqual("IMPLEMENTED", report.stage_details[0].status) + self.assertEqual(2, len(claude.dispatched)) # implement, then review: no retry + self.assertFalse(report.permission_requests) + + def test_a_published_stage_after_a_refused_optional_command_is_implemented(self): + body = self.fixture.tmpdir / "report.md" + body.write_text("Closes #435\n") + report, claude = self.cycle([ + ("Bash", {"command": 'git grep -n "def require_security" -- scripts'}), + ("Bash", {"command": "gh pr edit 442 --repo owner/api --body-file $TMPDIR/report.md"})]) + self.assert_completed(report, claude) + self.assertEqual(["reconciled"], [row["status"] for row in self.journal("reconciliation")]) + self.assertFalse(self.journal("claude_permission")) # the hook refused, not Claude + classified = self.journal("denial_classification") + self.assertEqual({"toolkit_hook"}, {row["correlation"]["layer"] for row in classified}) + self.assertEqual(2, len(classified)) + + def test_a_published_stage_after_a_refused_inherited_mcp_tool_is_implemented(self): + report, claude = self.cycle([("mcp__serena__find_symbol", {"name_path_pattern": "x"})]) + self.assert_completed(report, claude) + self.assertEqual(["reconciled"], [row["status"] for row in self.journal("reconciliation")]) + refused = self.journal("claude_permission") + self.assertEqual(["mcp__serena__find_symbol"], [row["command"] for row in refused]) + + def test_a_stage_that_reports_implemented_stays_implemented(self): + report, claude = self.cycle([ + ("Bash", {"command": "printenv CODE_CYCLE_STAGE_ROLE"}), + ("mcp__serena__find_symbol", {"name_path_pattern": "x"})], status="IMPLEMENTED") + self.assert_completed(report, claude) + + +if __name__ == "__main__": + unittest.main() From 13541d286296c8229f339beda71102b75d15617c Mon Sep 17 00:00:00 2001 From: datacas <4690232+datacas@users.noreply.github.com> Date: Mon, 30 Nov 2026 11:12:06 +0100 Subject: [PATCH 2/5] docs: record refusal attribution, the own pull request rule and the #550 native procedure host-permissions: a hook deny is attributed to toolkit_hook and not recorded again as claude_permission; implement may name its branch's open pull request by number; an inherited MCP denial is judged as an auxiliary host limit. capability-parity-audit: PA-53 (converted by #550) and PA-36/PA-52 updates. native-parity-runs and run.py: a dispatch mode that runs claude -p with the stage hook and --allowedTools and reports the refusing layer. Refs #550 --- docs/capability-parity-audit.md | 6 ++- docs/host-permissions.md | 14 ++++++- docs/native-parity-runs.md | 29 +++++++++++++++ docs/native-parity/run.py | 66 +++++++++++++++++++++++++++++++++ 4 files changed, 112 insertions(+), 3 deletions(-) diff --git a/docs/capability-parity-audit.md b/docs/capability-parity-audit.md index 7db0ae5..77cee73 100644 --- a/docs/capability-parity-audit.md +++ b/docs/capability-parity-audit.md @@ -179,7 +179,7 @@ given instead of line numbers so the references stay valid. | PA-33 | A configured verification command needs a Bash timeout of at least 600 s, and the toolkit sets `BASH_MAX_TIMEOUT_MS` to the same 600 s, so a longer check cannot finish | `stage_permissions.CLAUDE_VERIFICATION_TIMEOUT_MS`; `executors.py` dispatch environment | Avoids a check timing out early | #416: `basedpyright` needs 12 min 25 s | toolkit veto | #377 | | PA-34 | A stage report that differs only in representation is normalized before strict validation: receipt aliases `plan_revision` / `plan_digest` become `revision` / `digest`; a single `evidence` object becomes a one-item list; unknown top-level keys in a closed result move to `normalization.original`; lexical `check.level` variants are lower-cased and trimmed. Original values remain beside normalized values. Outcome, execution and integrity fields are never coerced or inferred | `scripts/review_contract.py` (`PLAN_RECEIPT_ALIASES`), `scripts/issue_review.py` (`normalize_result`), `scripts/verification_plan.py` (`normalize_tests`, `CHECK_LEVELS`) | Machine-readable results | #433, #412, #435 | toolkit veto | #433 (converted by #453 for `attempts`), #459; a `tests` block the runtime cannot read no longer stops the cycle `BLOCKED` and a reported frozen check without `command` takes it from the frozen check (#450) | | PA-35 | A grant for a configured verification command does not cover its variants (an environment prefix, `rtk`, a redirection into `$TMPDIR`), so the stage asks again | `grants.py` exact matching; `stage_permissions.operation` | Exact consent | #439 | toolkit veto | #439 | -| PA-36 | A publishing stage that reported `BLOCKED` after a verified publication stopped the cycle as `stage_not_completed`. Since #464 a stage that reports `BLOCKED` without `completed_status` is judged on its structured result (`inferred_completion`), and a stop that remains names the real cause apart from the incidental refusals | `scripts/command_permissions.py` `reconcile_result`, `inferred_completion`; `scripts/cycle_dispatch.py` `blocked_cause` | Completion evidence | #364, #446, #397 | toolkit veto | #364 (converted by #449 and #464) | +| PA-36 | A publishing stage that reported `BLOCKED` after a verified publication stopped the cycle as `stage_not_completed`. Since #464 a stage that reports `BLOCKED` without `completed_status` is judged on its structured result (`inferred_completion`), and a stop that remains names the real cause apart from the incidental refusals | `scripts/command_permissions.py` `reconcile_result`, `inferred_completion`; `scripts/cycle_dispatch.py` `blocked_cause` | Completion evidence | #364, #446, #397 | toolkit veto | #364 (converted by #449 and #464); #550: a hook refusal is no longer recorded a second time as `claude_permission`, whose duplicate record lacked the hook's intent and kept a published stage `BLOCKED` | | PA-37 | A review or rereview publication the runtime did not observe was treated as missing and retried without confirming the remote state. Since #446 it is re-read three times with backoff before it is called absent, and a persistent read failure stops the cycle as `BLOCKED` with `publication_unverified`, which is a real limit of the provider and never triggers another publication | `scripts/cycle_publication.py` (`settle_publication`), `scripts/cycle_history.py` (`REREAD_BACKOFF`) | Completion evidence | #446 | toolkit veto | #446 (converted by #446) | | PA-38 | Docker access needs the `docker_host` grant | `stage_permissions._check_docker` (`_DockerDenied`); `--grant docker_host=…` | Docker access is root on the host | #345, #398 | toolkit veto | #289 (converted to a cycle or persistent grant) | | PA-39 | An issue review is not dispatched when the runtime's snapshot of its GitHub work item is not complete, and a `READY` that leaves an unreadable referenced item of the snapshot unnamed is not confirmed | `cycle_dispatch.review_issue`; `issue_review.assess` (`unreadable_links`); `scripts/issue_snapshot.py` | A readiness judgement on complete, disclosed input | #397 | role contract | — | @@ -192,7 +192,8 @@ given instead of line numbers so the references stay valid. | PA-49 | Writing path/domain grants never reach review roles | `grants.ConsentBroker.granted`; `executors.dispatch` | Owner-defined stage scope | #509 | role contract | — | | PA-50 | The local-socket spike cannot be repeated inside a nested Codex boundary | `grants.LOCAL_SOCKETS`; `docs/research/local-sockets-509.md` | The executor masks its daemon socket directory; the host-reported measurement is retained separately from local verification | #509 | real limit | — | | PA-51 | Command-output targets require an explicit confirmed definition before permission; reviews request a separate cycle-only grant | `grants.ConsentBroker.request_definition`, `request` | User-defined source and role boundaries; output is an untrusted suggestion and a definition never authorizes access | #509 | role contract | #509 (converted to canonical consent and separate review scopes) | -| PA-52 | MCP tools a stage inherits from the user's configuration are neither hidden nor pre-approved by the toolkit; a `claude -p` denial of one is recorded as a `claude_permission` refusal (host limit), never invalidates evidence already obtained, and never becomes the stop cause of a review recovered from its receipt | `scripts/cycle_dispatch.py` (receipt recovery), `scripts/cycle_review_gate.py` (`recover_review`), `docs/host-permissions.md#inherited-mcp-tools-486` | The user's configuration decides which inherited tools run; a code-executing MCP tool runs outside the command hook and is not presented as supervised | #486: an MCP tool denial was mixed into a receipt-recovery stop | real limit | #486 | +| PA-52 | MCP tools a stage inherits from the user's configuration are neither hidden nor pre-approved by the toolkit; a `claude -p` denial of one is recorded as a `claude_permission` refusal (host limit), never invalidates evidence already obtained, and never becomes the stop cause of a review recovered from its receipt | `scripts/cycle_dispatch.py` (receipt recovery), `scripts/cycle_review_gate.py` (`recover_review`), `docs/host-permissions.md#inherited-mcp-tools-486` | The user's configuration decides which inherited tools run; a code-executing MCP tool runs outside the command hook and is not presented as supervised | #486: an MCP tool denial was mixed into a receipt-recovery stop | real limit | #486; since #550 a published implement or resolve stage that reported `BLOCKED` is reconciled with the denial counted as an auxiliary host limit, still never a question | +| PA-53 | Before the cycle records its change request, `gh pr edit` and `gh pr comment` in implement may target only the current branch's pull request. Naming that pull request by number was refused, which refused the stage's own receipt publication after it opened the PR. Since #550 the number is allowed when GitHub reports it, at the moment of the call, as the open pull request of this repository whose head is the checkout's branch; any other number, or any doubt, keeps the refusal | `stage_permissions._check_gh`, `_branch_pull_request` | Publication only on the cycle's own change request (PA-11) | #486: `gh pr edit 549 --body-file $TMPDIR/report.md`; #503: `gh pr comment 554 --body-file $TMPDIR/pr-comment.md` | toolkit veto | #550 | ## Kept restrictions @@ -274,6 +275,7 @@ the real repository. | PA-36 | #449 and #464 reconcile a `BLOCKED` publishing stage from structured completion and observed publication. #523 also reconciles `FAILED` implement/resolve results when the verified publication, valid completion, checks and denial classes permit it; verified dispatch-`TMPDIR` writes are auxiliary, and reconciled refusals are excluded from pending decisions. Changed heads, failed checks, essential/unknown denials and unverified publication still stop | `claude -p` publishes the PR, then reports `BLOCKED` or `FAILED` after only a TMPDIR write/refused read-only command | `codex exec -s workspace-write` exercises the same end conditions | | PA-37 | #446 re-reads the change request a bounded number of times before retrying | `claude -p` posts the review comment, which then exists on the change request | `codex exec` posts the same comment | | PA-38 | Done in #289: `--grant docker_host=cycle\|persistent` or `docker.host_socket_access: true` | `claude -p` with the user's Docker access runs `docker compose ps` | `codex exec -s workspace-write` with socket access runs `docker compose ps` | +| PA-53 | Done in #550: the branch's own pull request may be named by number once GitHub confirms it; `test_the_branch_pull_request_can_be_named` and `test_any_doubt_keeps_the_refusal` pin the boundary. The native procedure is the #550 section of `docs/native-parity-runs.md` | `claude -p` runs `gh pr comment --body-file $TMPDIR/pr-comment.md` on the pull request it opened | `codex exec -s workspace-write` runs the same; a Codex stage has no command table | | PA-40 | Done in #464: `sed -n`, `sed -E` and `sed -e` read-only scripts, `date` without a clock change and `ps` with fields that show no command line are in the table of every stage; the other forms stay the PA-18 consent question | `claude -p` runs `sed -n 1,5p fixture.txt`, `date +%s` and `ps -eo pid,comm`, then `sed -i s/a/b/ fixture.txt` and `ps -eo pid,args` | `codex exec -s workspace-write` runs the same commands; a Codex stage has no command table, so the test pins that it stays equal | ## Sensitive operations diff --git a/docs/host-permissions.md b/docs/host-permissions.md index c4bf61d..16a0019 100644 --- a/docs/host-permissions.md +++ b/docs/host-permissions.md @@ -227,6 +227,14 @@ filesystem and credential isolation; no command table is added to Codex. An executor refusal is attributed to `claude_permission`, with `--allowedTools` and `permissions.allow/deny` (including managed settings) in the reason and journal. A toolkit grant cannot override those settings. +A refusal by the stage hook is attributed to `toolkit_hook` and journaled by +the hook as `hook_bash` or `hook_edit`. Claude also lists a hook's `deny` in +its final `permission_denials`; an entry whose call the hook answered is the +same refusal, so it is not recorded again as `claude_permission` (#550). Only +the hook's record carries the rule, the operation and, for `gh pr edit`, the +intent that the runtime needs to judge a stage that published and then +reported `BLOCKED`. [Native parity runs](native-parity-runs.md#550-which-layer-refuses-a-dispatched-claude-stage) +shows which layer refuses each reported form. Auxiliary refusals after completed stages and observed successful retries stay in the refusal log but do not create unanswered decisions. Required checks and unresolved essential operations keep their existing decision path. @@ -244,7 +252,7 @@ fall back to `git grep` or `grep`. See [project choices and preparation](depende | every stage | `git status`, `diff`, `log`, `rev-parse`, `show`, `branch --show-current`; `gh issue view`, `pr view`, `pr checks`, `auth status`, `repo view`; `gh api user --jq .login`; `ls`, `cat`, `head`, `tail`, `wc`, `grep`, `find`, `jq` | — | | `issue_review` | `gh issue list`, `gh pr list`, `gh search issues\|prs`; `git merge-base`, `ls-files`, `grep`, `blame` | none | | `review`, `rereview` | `gh pr diff`, `git merge-base`, `ls-files`, `grep`, `blame`; `git fetch origin` only when the workspace has an `origin` remote (Claude's review clones have none) | `gh pr comment` and `gh pr review --comment` on the cycle's change request | -| `implement` | as review, plus `git worktree list`, `gh pr list`, `gh run view\|list` | `git add`, `commit`, `push`, `fetch`, `checkout`, `switch`, `pull`, `rm`, `mv`; `gh pr create`, `gh pr edit` and `gh pr comment` on the branch's change request; `gh issue comment` on the work item | +| `implement` | as review, plus `git worktree list`, `gh pr list`, `gh run view\|list` | `git add`, `commit`, `push`, `fetch`, `checkout`, `switch`, `pull`, `rm`, `mv`; `gh pr create`, `gh pr edit` and `gh pr comment` on the branch's change request, named by no argument or, before the cycle records it, by the number GitHub reports as this repository's open pull request for the checkout's branch (#550); `gh issue comment` on the work item | | `resolve` | as implement; literal `gh api repos///check-runs//annotations` with only `--jq` and `--paginate` | as implement without `gh pr create`/`edit`; and exactly three `gh api graphql` calls for review threads | In resolve, `gh run view` requires a numeric run ID. Every `--job`/`-j` @@ -809,6 +817,10 @@ prevents an indispensable operation with no valid alternative, and then it is reported as that host limit. A review that already published a valid receipt for the current head is recovered from it and continues to the CI gate ([Review verdicts recovered from a receipt](review-cycle.md#review-verdicts-recovered-from-a-receipt-486)). +An implement or resolve stage that published and then reported `BLOCKED` is +judged with the denial among its other refusals, as an auxiliary host limit: +the published state the runtime verifies decides whether it completes (#550). +The denial is never a consent question. ### Own stage artefacts and dispatch-unique paths (#486) diff --git a/docs/native-parity-runs.md b/docs/native-parity-runs.md index 19677ab..36ed7aa 100644 --- a/docs/native-parity-runs.md +++ b/docs/native-parity-runs.md @@ -69,6 +69,34 @@ and any actual permission or infrastructure limit. Keep #455 open until both native comparisons are recorded; `not_verified` does not demonstrate parity. PA-19 needs no Docker cleanup. +### #550: which layer refuses a dispatched Claude stage + +`dispatch` starts `claude -p` the way the runtime dispatches an implement stage: +the stage's `PreToolUse` hook in `--settings` and the `--allowedTools` patterns +of its table. It asks for each command refused in the #486 and #503 cycles, +made independent of their repository, and records: + +```text +python3 docs/native-parity/run.py setup +python3 docs/native-parity/run.py dispatch +``` + +| Field | Meaning | +|---|---| +| `layer` | `ran`, `toolkit_hook` (the hook refused it with a consent question), `claude_permission` (Claude's own layer refused it with no hook answer) or `not_run` | +| `consent_offered` | the hook's refusal carries the exact operation the runtime asks about | +| `claude_listed_denials` | how many entries Claude's final `permission_denials` holds | +| `recorded_claude_permission` | how many of them the toolkit records as `claude_permission` | + +A row passes when its `layer` is `ran`, or `toolkit_hook` with +`consent_offered`, and `recorded_claude_permission` is 0 for a `toolkit_hook` +row. `claude_listed_denials` greater than 0 on a `toolkit_hook` row is the +native evidence that Claude lists a hook's `deny` among its own denials, which +the toolkit recorded twice before #550. A `claude_permission` row on a command +the hook allowed is a gap in the dispatch's `--allowedTools`: file it with the +output. The quoted, `-e`, `$TMPDIR` and compound forms stay `toolkit_hook` +under #524; `git grep -n -A3` runs. + ## What each side does | Side | What it runs | @@ -76,6 +104,7 @@ does not demonstrate parity. PA-19 needs no Docker cleanup. | `toolkit` | For each command and each executor, with the real consent machinery and no mocks: the table refuses it, a consent question is offered, an exact grant allows it, the same command plus an extra flag is still refused, and the subprocess hook allows it. | | `native claude` | `claude -p --allowedTools Bash` is asked to run the audit's baseline command in the fixture and to report its exit code and output. | | `native codex` | `codex exec -s workspace-write` does the same, with `sandbox_workspace_write.network_access=true` for PA-21 and PA-22. | +| `dispatch` | `claude -p` with the implement stage's hook and `--allowedTools` runs the #550 commands; the result names the refusing layer. | The commands per row are the ones in the audit: a pipe to `head` and a heredoc into `$TMPDIR` (PA-19), `git ls-tree HEAD` and diff --git a/docs/native-parity/run.py b/docs/native-parity/run.py index cf28762..73942e9 100644 --- a/docs/native-parity/run.py +++ b/docs/native-parity/run.py @@ -7,6 +7,7 @@ run.py setup create the fixture repository and Compose file run.py toolkit toolkit side: table, consent, exact grant, hook run.py native claude|codex native side: the agent runs each baseline directly + run.py dispatch #550: claude -p with the stage's hook and --allowedTools run.py cleanup docker compose down for the fixture PA-22 writes real issues to --fixture-repo. Use a private, disposable repository. @@ -144,6 +145,70 @@ def native(args): Path(args.workdir, f"native_{executor}.json").write_text(json.dumps(out, indent=1)) +#: #550: the forms refused in the #486 and #503 cycles, made independent of +#: their repository. `{repo}` is the repository the dispatch policy names. +DISPATCH_COMMANDS = ( + 'git grep -n "def require_security" -- .', + 'git grep -n -e init -e "fixture" -- .', + "git diff --output=$TMPDIR/wip.diff", + 'grep -n "fixture" README.md', + "git grep -n -A3 fixture -- .", + "git ls-files | head -200; wc -l README.md", + "git --version", + "printenv CODE_CYCLE_STAGE_ROLE", + "gh pr view 1 --repo {repo} --json number --jq '.number'", +) + + +def dispatch(args): + """`claude -p` as the runtime dispatches an implement stage: which layer refuses?""" + sys.path.insert(0, str(REPO_ROOT / "scripts")) + import executors as ex + import stage_permissions as sp + + cwd = Path(args.workdir) / "fx" + tmp = Path(tempfile.mkdtemp()) + policy = sp.StagePolicy("implement", repo=args.read_repo, work_item_id="1", + base_branch="main", tmpdir=str(tmp)) + policy_file = tmp / "policy.json" + policy_file.write_text(policy.to_json()) + settings = sp.hook_settings(f"{sys.executable} {sp.__file__} hook {policy_file}") + env = {k: v for k, v in os.environ.items() if k not in ("CLAUDECODE", "CLAUDE_CODE_ENTRYPOINT")} + env["TMPDIR"] = str(tmp) + out = [] + for command in DISPATCH_COMMANDS: + command = command.format(repo=args.read_repo) + argv = ["claude", "-p", PROMPT + command, "--model", args.claude_model, + "--output-format", "stream-json", "--verbose", "--permission-mode", "acceptEdits", + "--settings", json.dumps(settings), + "--allowedTools", *sp.allowed_tool_patterns(policy)] + try: + run = subprocess.run(argv, cwd=cwd, env=env, capture_output=True, text=True, + timeout=300, stdin=subprocess.DEVNULL) + stdout, code = run.stdout, run.returncode + except subprocess.TimeoutExpired: + stdout, code = "", -1 + artifacts = ex.ClaudeAdapter().extra_artifacts(stdout) + listed = [] + for line in stdout.splitlines(): + try: + event = json.loads(line) + except ValueError: + continue + if isinstance(event, dict) and event.get("type") == "result": + listed += [item.get("tool_use_id") for item in event.get("permission_denials") or []] + hook = [item for item in artifacts.get("command_refusals", []) if item.get("rule")] + layer = ("ran" if command in artifacts.get("command_executions", []) else + "toolkit_hook" if hook else + "claude_permission" if artifacts.get("claude_permission_denials") else "not_run") + out.append({"command": command, "cli_rc": code, "layer": layer, + "consent_offered": bool(hook and hook[0].get("operation")), + "claude_listed_denials": len(listed), + "recorded_claude_permission": len(artifacts.get("claude_permission_denials", []))}) + print(command[:60], out[-1], flush=True) + Path(args.workdir, "dispatch_claude.json").write_text(json.dumps(out, indent=1)) + + def cleanup(args): subprocess.run(["docker", "compose", "down"], cwd=Path(args.workdir) / "dk") @@ -162,6 +227,7 @@ def main(): nat = sub.add_parser("native") nat.add_argument("executor", choices=("claude", "codex")) nat.set_defaults(func=native) + sub.add_parser("dispatch").set_defaults(func=dispatch) sub.add_parser("cleanup").set_defaults(func=cleanup) args = parser.parse_args() if args.command in ("toolkit", "native") and not args.fixture_repo and not (args.rows and "PA-22" not in args.rows): From 5fa7f6c2ba8980ac5d76ac1e9e441d726e459e5d Mon Sep 17 00:00:00 2001 From: datacas <4690232+datacas@users.noreply.github.com> Date: Mon, 30 Nov 2026 11:23:47 +0100 Subject: [PATCH 3/5] fix: match the own pull request against the runtime's cycle branch first (#550) When the runtime fixed the stage's branch (head_ref or checkout_branch), the own-pull-request check compares GitHub's head ref with it rather than with whatever directory the call runs in. Refs #550 --- scripts/stage_permissions.py | 16 ++++++++++------ tests/test_claude_stage_refusals.py | 9 +++++++++ 2 files changed, 19 insertions(+), 6 deletions(-) diff --git a/scripts/stage_permissions.py b/scripts/stage_permissions.py index 8ac4924..da56d99 100644 --- a/scripts/stage_permissions.py +++ b/scripts/stage_permissions.py @@ -3194,12 +3194,16 @@ def _branch_pull_request(reference: str, policy: StagePolicy, *, cwd: str | None if (number is None or not number.isdigit() or not policy.repo or not _SAFE_REPOSITORY.fullmatch(policy.repo)): return False - try: - branch = run(["git", "branch", "--show-current"], cwd=cwd, capture_output=True, - text=True, timeout=10, stdin=subprocess.DEVNULL) - except (OSError, subprocess.SubprocessError): - return False - current = (branch.stdout or "").strip() if branch.returncode == 0 else "" + # The branch the runtime fixed for this stage wins over whatever directory + # the call runs in; only without one is the checkout asked. + current = policy.head_ref or policy.checkout_branch + if not current: + try: + branch = run(["git", "branch", "--show-current"], cwd=cwd, capture_output=True, + text=True, timeout=10, stdin=subprocess.DEVNULL) + except (OSError, subprocess.SubprocessError): + return False + current = (branch.stdout or "").strip() if branch.returncode == 0 else "" if not current: return False found = GITHUB_FIELD(f"repos/{policy.repo}/pulls/{number}", diff --git a/tests/test_claude_stage_refusals.py b/tests/test_claude_stage_refusals.py index b2b31c0..bb08892 100644 --- a/tests/test_claude_stage_refusals.py +++ b/tests/test_claude_stage_refusals.py @@ -224,6 +224,15 @@ def test_any_doubt_keeps_the_refusal(self): self.assertFalse(decision.allowed) self.assertIn("current branch's change request", decision.reason) + def test_the_runtime_branch_wins_over_the_call_directory(self): + with self.lookup("open owner/repo fix/550-claude"): + for field in ("head_ref", "checkout_branch"): + with self.subTest(field=field): + other = self.policy(**{field: "task-other"}) + self.assertFalse(sp.check(OWN_PUBLICATION[0], other, cwd=str(self.cwd)).allowed) + same = self.policy(**{field: "fix/550-claude"}) + self.assertTrue(sp.check(OWN_PUBLICATION[0], same, cwd=str(self.root)).allowed) + def test_a_checkout_without_a_branch_keeps_the_refusal(self): detached = self.root / "plain" detached.mkdir() From 386237650557502628158c5d55b4da3392da794c Mon Sep 17 00:00:00 2001 From: datacas <4690232+datacas@users.noreply.github.com> Date: Mon, 30 Nov 2026 11:24:49 +0100 Subject: [PATCH 4/5] test: assign test_claude_stage_refusals to a Windows shard (#550) Refs #550 --- scripts/windows-test-shards.json | 2 ++ 1 file changed, 2 insertions(+) diff --git a/scripts/windows-test-shards.json b/scripts/windows-test-shards.json index 9b5bca4..5798056 100644 --- a/scripts/windows-test-shards.json +++ b/scripts/windows-test-shards.json @@ -47,6 +47,7 @@ "unmeasured_modules": [ "test_basedpyright_configuration", "test_command_permissions", + "test_claude_stage_refusals", "test_consent_variants", "test_compose_consent", "test_compound_parity", @@ -108,6 +109,7 @@ "windows-3": [ "test_compound_parity", "test_command_permissions", + "test_claude_stage_refusals", "test_consent_variants", "test_compose_consent", "test_table_consent", From e3c3e8a7176fad9603271f10360c847d7f777bf4 Mon Sep 17 00:00:00 2001 From: datacas <4690232+datacas@users.noreply.github.com> Date: Mon, 30 Nov 2026 12:18:06 +0100 Subject: [PATCH 5/5] fix: never turn an inherited MCP denial into an unattended consent question (#550) REV-001: a review awaiting CI or an unreconciled BLOCKED stage journaled an unattended_denial decision for an mcp__ host denial. The toolkit can neither grant nor deny an inherited tool, so it is now classified and journaled as claude_permission but never pending. REV-002: the native dispatch procedure does not cover PA-53; say that it is pinned by unit tests, record the 2026-11-30 native run, and keep the PA rows in order. --- docs/capability-parity-audit.md | 4 +- docs/host-permissions.md | 8 +++- docs/native-parity-runs.md | 13 +++++++ scripts/cycle.py | 6 ++- tests/test_claude_stage_refusals.py | 60 +++++++++++++++++++++++++---- 5 files changed, 79 insertions(+), 12 deletions(-) diff --git a/docs/capability-parity-audit.md b/docs/capability-parity-audit.md index 77cee73..7a28b2f 100644 --- a/docs/capability-parity-audit.md +++ b/docs/capability-parity-audit.md @@ -192,7 +192,7 @@ given instead of line numbers so the references stay valid. | PA-49 | Writing path/domain grants never reach review roles | `grants.ConsentBroker.granted`; `executors.dispatch` | Owner-defined stage scope | #509 | role contract | — | | PA-50 | The local-socket spike cannot be repeated inside a nested Codex boundary | `grants.LOCAL_SOCKETS`; `docs/research/local-sockets-509.md` | The executor masks its daemon socket directory; the host-reported measurement is retained separately from local verification | #509 | real limit | — | | PA-51 | Command-output targets require an explicit confirmed definition before permission; reviews request a separate cycle-only grant | `grants.ConsentBroker.request_definition`, `request` | User-defined source and role boundaries; output is an untrusted suggestion and a definition never authorizes access | #509 | role contract | #509 (converted to canonical consent and separate review scopes) | -| PA-52 | MCP tools a stage inherits from the user's configuration are neither hidden nor pre-approved by the toolkit; a `claude -p` denial of one is recorded as a `claude_permission` refusal (host limit), never invalidates evidence already obtained, and never becomes the stop cause of a review recovered from its receipt | `scripts/cycle_dispatch.py` (receipt recovery), `scripts/cycle_review_gate.py` (`recover_review`), `docs/host-permissions.md#inherited-mcp-tools-486` | The user's configuration decides which inherited tools run; a code-executing MCP tool runs outside the command hook and is not presented as supervised | #486: an MCP tool denial was mixed into a receipt-recovery stop | real limit | #486; since #550 a published implement or resolve stage that reported `BLOCKED` is reconciled with the denial counted as an auxiliary host limit, still never a question | +| PA-52 | MCP tools a stage inherits from the user's configuration are neither hidden nor pre-approved by the toolkit; a `claude -p` denial of one is recorded as a `claude_permission` refusal (host limit), never invalidates evidence already obtained, and never becomes the stop cause of a review recovered from its receipt | `scripts/cycle_dispatch.py` (receipt recovery), `scripts/cycle_review_gate.py` (`recover_review`), `docs/host-permissions.md#inherited-mcp-tools-486` | The user's configuration decides which inherited tools run; a code-executing MCP tool runs outside the command hook and is not presented as supervised | #486: an MCP tool denial was mixed into a receipt-recovery stop | real limit | #486; since #550 a published implement or resolve stage that reported `BLOCKED` is reconciled with the denial counted as an auxiliary host limit, still never a question, including no `unattended_denial` decision in a run without a human channel | | PA-53 | Before the cycle records its change request, `gh pr edit` and `gh pr comment` in implement may target only the current branch's pull request. Naming that pull request by number was refused, which refused the stage's own receipt publication after it opened the PR. Since #550 the number is allowed when GitHub reports it, at the moment of the call, as the open pull request of this repository whose head is the checkout's branch; any other number, or any doubt, keeps the refusal | `stage_permissions._check_gh`, `_branch_pull_request` | Publication only on the cycle's own change request (PA-11) | #486: `gh pr edit 549 --body-file $TMPDIR/report.md`; #503: `gh pr comment 554 --body-file $TMPDIR/pr-comment.md` | toolkit veto | #550 | ## Kept restrictions @@ -275,8 +275,8 @@ the real repository. | PA-36 | #449 and #464 reconcile a `BLOCKED` publishing stage from structured completion and observed publication. #523 also reconciles `FAILED` implement/resolve results when the verified publication, valid completion, checks and denial classes permit it; verified dispatch-`TMPDIR` writes are auxiliary, and reconciled refusals are excluded from pending decisions. Changed heads, failed checks, essential/unknown denials and unverified publication still stop | `claude -p` publishes the PR, then reports `BLOCKED` or `FAILED` after only a TMPDIR write/refused read-only command | `codex exec -s workspace-write` exercises the same end conditions | | PA-37 | #446 re-reads the change request a bounded number of times before retrying | `claude -p` posts the review comment, which then exists on the change request | `codex exec` posts the same comment | | PA-38 | Done in #289: `--grant docker_host=cycle\|persistent` or `docker.host_socket_access: true` | `claude -p` with the user's Docker access runs `docker compose ps` | `codex exec -s workspace-write` with socket access runs `docker compose ps` | -| PA-53 | Done in #550: the branch's own pull request may be named by number once GitHub confirms it; `test_the_branch_pull_request_can_be_named` and `test_any_doubt_keeps_the_refusal` pin the boundary. The native procedure is the #550 section of `docs/native-parity-runs.md` | `claude -p` runs `gh pr comment --body-file $TMPDIR/pr-comment.md` on the pull request it opened | `codex exec -s workspace-write` runs the same; a Codex stage has no command table | | PA-40 | Done in #464: `sed -n`, `sed -E` and `sed -e` read-only scripts, `date` without a clock change and `ps` with fields that show no command line are in the table of every stage; the other forms stay the PA-18 consent question | `claude -p` runs `sed -n 1,5p fixture.txt`, `date +%s` and `ps -eo pid,comm`, then `sed -i s/a/b/ fixture.txt` and `ps -eo pid,args` | `codex exec -s workspace-write` runs the same commands; a Codex stage has no command table, so the test pins that it stays equal | +| PA-53 | Done in #550: the branch's own pull request may be named by number once GitHub confirms it. The boundary is pinned by unit tests only (`test_the_branch_pull_request_can_be_named`, `test_any_doubt_keeps_the_refusal`, with the GitHub lookup mocked). The #550 native procedure in `docs/native-parity-runs.md` does not run `gh pr edit ` or `gh pr comment `: it would need an open pull request whose head is the fixture's branch, and it would publish on it | `claude -p` runs `gh pr comment --body-file $TMPDIR/pr-comment.md` on the pull request it opened | `codex exec -s workspace-write` runs the same; a Codex stage has no command table | ## Sensitive operations diff --git a/docs/host-permissions.md b/docs/host-permissions.md index 16a0019..d67576a 100644 --- a/docs/host-permissions.md +++ b/docs/host-permissions.md @@ -820,7 +820,9 @@ for the current head is recovered from it and continues to the CI gate An implement or resolve stage that published and then reported `BLOCKED` is judged with the denial among its other refusals, as an auxiliary host limit: the published state the runtime verifies decides whether it completes (#550). -The denial is never a consent question. +The denial is never a consent question, in any stage or status: an unattended +run journals no `unattended_denial` decision for it, because the toolkit can +neither grant nor deny an inherited tool. ### Own stage artefacts and dispatch-unique paths (#486) @@ -1054,7 +1056,9 @@ refusal in such a run, not only `--detach` (#464): reason and runtime class (`denial_classification`), and as a pending decision (`decision_asked`, component `unattended_denial`, status `unanswered`). The decisions record of the cycle lists it afterwards, and - `--grant command_=…` answers it on the next run. + `--grant command_=…` answers it on the next run. A denial of an + inherited MCP tool is classified but never pending: it is a host limit + ([Inherited MCP tools](#inherited-mcp-tools-486)). 3. **An incidental denial continues.** A stage whose work is done, whose publication is verified and whose refusals were only inspection or redundant keeps its status. The checks it could not run stay `not_verified`. diff --git a/docs/native-parity-runs.md b/docs/native-parity-runs.md index 36ed7aa..1fa00bc 100644 --- a/docs/native-parity-runs.md +++ b/docs/native-parity-runs.md @@ -97,6 +97,12 @@ the hook allowed is a gap in the dispatch's `--allowedTools`: file it with the output. The quoted, `-e`, `$TMPDIR` and compound forms stay `toolkit_hook` under #524; `git grep -n -A3` runs. +`dispatch` does not cover PA-53, the stage's own pull request named by number +(`gh pr edit `, `gh pr comment `). Allowing it needs an open pull request +whose head is the fixture's branch, and running it would publish on that pull +request. PA-53 is pinned by `OwnChangeRequestTests` in +`tests/test_claude_stage_refusals.py`, with the GitHub lookup mocked. + ## What each side does | Side | What it runs | @@ -151,3 +157,10 @@ Limits of this comparison: execution with execution after the real shared hook accepts each executor's grant metadata; they do not launch either native executor, so this run is the native evidence. +- 2026-11-30, #550 (PR #555, commit `3862376`): `dispatch` with this + branch's `scripts/`, outside any cycle. All nine `DISPATCH_COMMANDS` rows + pass. `git grep -n -A3 fixture -- .` ran; the other eight were refused by + `toolkit_hook` with a consent question. Claude listed each hook `deny` among + its own `permission_denials` (one entry, two for `git --version` and + `printenv CODE_CYCLE_STAGE_ROLE`), and none was recorded as + `claude_permission`. PA-53 was not part of the run (see the #550 section). diff --git a/scripts/cycle.py b/scripts/cycle.py index 0a1063b..7736d96 100644 --- a/scripts/cycle.py +++ b/scripts/cycle.py @@ -1665,6 +1665,7 @@ def observation(name, status, observed=None, detail=None): "--allowedTools and permissions.allow/deny (including managed settings)"), correlation={"tool_use_id": denial.get("tool_use_id"), "layer": "claude_permission"}) from command_permissions import _result_block + from stage_permissions import MCP_TOOL_PREFIX result_block = _result_block(result.agent_output) runtime_record = result_block[2].get("reconciliation") if result_block else None reconciled = isinstance(runtime_record, dict) and runtime_record.get("reconciled") is True @@ -1680,7 +1681,10 @@ def observation(name, status, observed=None, detail=None): "stage": record.get("stage")}) if (self.consent is not None and self.consent.prompt is None and not reconciled and not record.get("worked_around") - and record.get("class") != "unverifiable_check"): + and record.get("class") != "unverifiable_check" + # An inherited MCP tool is a host limit the toolkit can + # neither grant nor deny (#486, #550): no question. + and not str(record.get("tool") or "").startswith(MCP_TOOL_PREFIX)): # No human channel (`--detach`, no terminal): the refusal is a # denial that grants nothing, and the question it would have # raised is asked afterwards from the decisions record (#464). diff --git a/tests/test_claude_stage_refusals.py b/tests/test_claude_stage_refusals.py index bb08892..95258b6 100644 --- a/tests/test_claude_stage_refusals.py +++ b/tests/test_claude_stage_refusals.py @@ -291,13 +291,24 @@ def test_an_inherited_mcp_refusal_is_a_host_limit_and_never_a_question(self): class StreamingClaude(Talker): """A Claude implementer whose refusals pass through the real hook and parser.""" - def __init__(self, fixture, calls, status="BLOCKED"): + def __init__(self, fixture, calls, status="BLOCKED", review=None): super().__init__("claude") self.fixture, self.calls, self.status = fixture, calls, status + #: `(calls, status)` for the review stage; only inherited tools here. + self.review = review def dispatch(self, target, task, **kwargs): self.dispatched.append(task) policy = kwargs.get("command_policy") + if policy is not None and policy.role == "review" and self.review is not None: + calls, status = self.review + events = [tool_call(f"r{index}", tool, data) for index, (tool, data) in enumerate(calls)] + events.append({"type": "result", "permission_denials": [ + denied(f"r{index}", tool, data) for index, (tool, data) in enumerate(calls)]}) + return ex.DispatchResult(ex.DispatchOutcome.SUCCEEDED, "claude", target, + start_state="started", process_exited=True, + agent_output=block(status, head_sha=SHA, security_audit_ran=True), + artifacts=ex.ClaudeAdapter().extra_artifacts(stream(*events))) if policy is None or policy.role != "implement": return ex.DispatchResult(ex.DispatchOutcome.SUCCEEDED, "claude", target, start_state="started", process_exited=True, agent_output=block("APPROVED")) @@ -322,9 +333,8 @@ def dispatch(self, target, task, **kwargs): artifacts=ex.ClaudeAdapter().extra_artifacts(stream(*events))) -@unittest.skipIf(os.name == "nt", "POSIX command forms") -class CompletedStageTests(RunCycleTestCase): - """AC-2: an optional refusal never turns a published implementation into BLOCKED.""" +class ClaudeCycle(RunCycleTestCase): + """A whole cycle whose Claude stages stream refusals through the real parser.""" def setUp(self): super().setUp() @@ -332,8 +342,8 @@ def setUp(self): self.fixture.setUp() self.addCleanup(self.fixture.doCleanups) - def cycle(self, calls, status="BLOCKED"): - claude = StreamingClaude(self.fixture, calls, status) + def cycle(self, calls, status="BLOCKED", review=None, observer=published): + claude = StreamingClaude(self.fixture, calls, status, review) broker = grants.ConsentBroker("owner/api", platform="linux", store=grants.ConsentStore(self.home / "consents.json")) profiles = router.load_profiles({"code_cycle": {"profiles": { @@ -342,13 +352,18 @@ def cycle(self, calls, status="BLOCKED"): report = rc.run_cycle("owner/api", "435", router.TaskSignals(), self.store, registry=ex.Registry([claude]), availability={"claude": ex.Availability.READY}, profiles=profiles, issue_review="off", consent=broker, - publication_observer=lambda *_: published(), trusted_authors=("reviewer",)) + publication_observer=lambda *_: observer(), trusted_authors=("reviewer",)) return report, claude def journal(self, component): from cycle_journal import events return [row for row in events(self.store.path, "owner/api") if row["component"] == component] + +@unittest.skipIf(os.name == "nt", "POSIX command forms") +class CompletedStageTests(ClaudeCycle): + """AC-2: an optional refusal never turns a published implementation into BLOCKED.""" + def assert_completed(self, report, claude): self.assertEqual(rc.APPROVED_END, report.status, report.stopped_because) self.assertEqual("IMPLEMENTED", report.stage_details[0].status) @@ -382,5 +397,36 @@ def test_a_stage_that_reports_implemented_stays_implemented(self): self.assert_completed(report, claude) +@unittest.skipIf(os.name == "nt", "POSIX command forms") +class UnattendedHostLimitTests(ClaudeCycle): + """REV-001: with no one to ask, an inherited MCP denial raises no consent question. + + The toolkit cannot grant an inherited MCP tool (#486), so an allow/deny + question about one could never be answered usefully. The refusal is still + journaled as `claude_permission` and classified as a host limit. + """ + + MCP = ("mcp__serena__find_symbol", {"name_path_pattern": "x"}) + + def unattended(self): + return [row["command"] for row in self.journal("unattended_denial")] + + def test_an_unreconciled_blocked_stage_asks_only_about_its_grantable_refusal(self): + command = 'git grep -n "def require_security" -- scripts' + self.cycle([("Bash", {"command": command}), self.MCP], observer=lambda: None) + self.assertEqual([command], self.unattended()) + refused = self.journal("claude_permission") + self.assertEqual(["mcp__serena__find_symbol"], [row["command"] for row in refused]) + classified = {row["command"]: row["status"] for row in self.journal("denial_classification")} + self.assertEqual(cp.AUXILIARY_DENIAL, classified["mcp__serena__find_symbol"]) + + def test_a_review_awaiting_ci_asks_nothing_about_an_mcp_refusal(self): + self.cycle([], status="IMPLEMENTED", review=([self.MCP], "REVIEW_PASSED_AWAITING_CI")) + self.assertEqual([], self.unattended()) + refused = self.journal("claude_permission") + self.assertEqual(["mcp__serena__find_symbol"], [row["command"] for row in refused]) + self.assertEqual(["review"], [row["role"] for row in self.journal("denial_classification")]) + + if __name__ == "__main__": unittest.main()