From 732cf0473673a5d082edc5789a6427f64d399a73 Mon Sep 17 00:00:00 2001 From: datacas <4690232+datacas@users.noreply.github.com> Date: Thu, 24 Sep 2026 14:21:41 +0200 Subject: [PATCH 1/7] Add isolated review worktree harness --- README.md | 4 + docs/instrumentation.md | 20 +--- docs/role-workspace-policy.md | 10 +- docs/routing.md | 6 +- scripts/executors.py | 179 ++++++++++++++++++++++++++++++++-- scripts/router.py | 9 +- scripts/telemetry.py | 2 + tests/test_executors.py | 100 +++++++++++++++++-- tests/test_run_cycle.py | 9 +- tests/test_telemetry.py | 10 +- 10 files changed, 305 insertions(+), 44 deletions(-) diff --git a/README.md b/README.md index b85fd52c..1fc2223a 100644 --- a/README.md +++ b/README.md @@ -131,6 +131,10 @@ Use cc-orchestrator for issue 123. Stop at READY_FOR_MANUAL_MERGE. | [`cc-orca-orchestrator`](docs/workflows.md#cc-orca-orchestrator) | one prompt | supervised workers, paired-review calibration | Orca | | [`run_cycle.py`](docs/workflows.md#runtime-driver-run_cyclepy) | a shell command | recorded, routed cycles across executors | runtime, Codex and/or Claude CLIs | +Read-only roles can use Codex's enforced sandbox or Claude's isolated, +verified review worktree. See [workspace policy](docs/role-workspace-policy.md) +for the branch protection contract. + ## Skills Thirteen skills in two layers. **Cycle skills** own the workflow: the change request, the finding IDs, the published comments, and the merge boundary. **Supporting skills** are focused passes that cycle skills delegate to. Each one also works on its own. diff --git a/docs/instrumentation.md b/docs/instrumentation.md index 7d49a7f6..e09de7fb 100644 --- a/docs/instrumentation.md +++ b/docs/instrumentation.md @@ -735,22 +735,10 @@ nothing had ever asked for anything else. A dispatched Claude, by contrast, edited a file with no flag at all. So the flag on a writing Claude stage declares what is already happening rather than granting something new. -For a **reading** Claude stage there is no honest flag, and this does not -pretend otherwise. `--permission-mode plan` refuses the edit but turns the task -into planning it, which is not a review. Disallowing `Edit`, `Write` and -`NotebookEdit` does not stop a write: a live probe created the file anyway. -Review and rereview therefore route to Codex, whose explicit `-s read-only` -sandbox enforces non-mutation. Orca may be used only when its explicit review -workspace contract is present; it does not claim an OS-level read-only flag and -fails closed for a missing, mismatched or overlapping workspace. A configured -adapter that cannot establish a non-mutating boundary is blocked before it -starts rather than sharing the writable tree. - -The default review profiles intentionally have no fallback. If Codex is -unavailable, a review blocks instead of silently falling back to Claude or Orca -without the required boundary. A direct or future Orca fallback must provide -an immutable or otherwise disposable non-mutating workspace before it starts. -This favors review integrity over availability. +For a **reading** Claude stage, the harness creates a detached worktree at the exact reviewed HEAD, outside the implementer's tree. It records the implementer's HEAD and a fingerprint of `git status --porcelain` before dispatch, then checks both again afterwards. A changed HEAD or working-tree fingerprint makes the stage a `contract_violation`. Writes within Claude's disposable review worktree produce a warning and are discarded with that worktree. The stage prompt prohibits file edits, commits, and pushes; `--disallowedTools Edit Write NotebookEdit` adds defence in depth without serving as the guarantee. Read-only Claude dispatches record `read_only_mode = isolated_verified`. + +Codex retains `-s read-only` and records `read_only_mode = enforced`, meaning its sandbox prevents workspace writes. Orca still requires its explicit review-workspace contract. Reviews may use any configured eligible executor; a profile may still choose no fallback. Publication access remains behavioural: a read-only stage receives only the tools its role permits, such as `gh` for an allowed comment. + ## Running a cycle diff --git a/docs/role-workspace-policy.md b/docs/role-workspace-policy.md index e6afd85b..c7cffbc4 100644 --- a/docs/role-workspace-policy.md +++ b/docs/role-workspace-policy.md @@ -18,11 +18,11 @@ repository. The default auxiliary profile uses Codex because its sandbox can confine writes to the disposable cwd; an adapter without that boundary is not eligible for `disposable`, even when its process cwd is isolated. -An adapter is eligible only when it can enforce the requested policy. Codex -can enforce strict read-only execution directly and can confine writes to a -disposable cwd. Claude cannot enforce either boundary, so it is not a valid -target for `read_only` or `disposable` roles. Orca follows the same fail-closed -rule and requires its own explicit orchestration context where applicable. +An adapter is eligible only when the harness can establish the requested policy. Codex enforces read-only execution directly with its sandbox and records `read_only_mode = enforced`. + +Claude cannot enforce read-only inside its process, so the harness runs it in a detached worktree at the exact reviewed HEAD, outside the implementer's tree. Before and after the stage, the harness compares the implementer's HEAD and `git status --porcelain`; a change is a `contract_violation`. Edits inside the disposable review worktree produce a warning and are discarded. Claude records `read_only_mode = isolated_verified`, and its reviewer cannot write to the branch. The prompt also prohibits edits, commits, and pushes, while CLI tool restrictions provide defence in depth. Publication access remains behavioural and follows the role's existing policy. + +Claude remains ineligible for `disposable` roles because it cannot confine writes to their workspace. Orca follows its explicit review-workspace contract and requires its own orchestration context where applicable. This deliberately separates useful generated output from unauthorized source tree changes: verification reports, caches, build output, and runtime state diff --git a/docs/routing.md b/docs/routing.md index f8924646..dee7aa7c 100644 --- a/docs/routing.md +++ b/docs/routing.md @@ -35,7 +35,7 @@ A profile names a *kind* of work. It never appears in a skill as a model name. | `auxiliary_tool` | verify, run, bootstrap | `codex:openai/gpt-6-luna medium` | — | | `cheap_tool` | compatibility for direct/custom callers; no built-in role selects it | `claude:anthropic/claude-haiku-4-5-20251001 low` | — | -¹ Kept in the registry for compatibility only. The security stage is read-only and Claude can't enforce read-only, so this fallback is never selected. +¹ The security profile retains this configured fallback; Claude runs read-only stages only through the isolated, verified workspace contract described below. The source of truth is `DEFAULT_PROFILES` in [`scripts/router.py`](../scripts/router.py). Override only what you want to change, and the rest keep their defaults: @@ -94,10 +94,10 @@ Each role has a fixed write permission. Only an executor that can **enforce** it | Role | Policy | Eligible executors | |---|---|---| | `implement`, `resolve` | `workspace_write` | Codex (`-s workspace-write`), Claude (`acceptEdits`), Orca | -| `review`, `rereview`, `security`, `bootstrap`, `coordinate` | `read_only` | Codex (`-s read-only`); Orca only with an explicit isolated review workspace | +| `review`, `rereview`, `security`, `bootstrap`, `coordinate` | `read_only` | Codex (`-s read-only`), Claude (isolated and verified worktree), Orca (explicit review workspace) | | `verify`, `run` | `disposable` | Codex, confined to a disposable workspace | -Claude can't enforce read-only, so it is never used for review roles. That is why review profiles have **no fallback**: when Codex is unavailable, a review blocks instead of running without a proven non-mutating boundary. Details are in [Role workspace policy](role-workspace-policy.md). +Codex records `read_only_mode = enforced`: its sandbox prevents workspace writes. Claude records `read_only_mode = isolated_verified`: the harness checks out the reviewed HEAD in a detached disposable worktree, verifies that the implementer's HEAD and working-tree fingerprint did not change, and discards local edits. A Claude reviewer cannot write to the branch. Reviews may still be configured without a fallback; that is a profile choice. Publication access remains role-specific, and a reviewer may publish only the comment its role permits. Details are in [Role workspace policy](role-workspace-policy.md). ## Publication boundary diff --git a/scripts/executors.py b/scripts/executors.py index 77fc4d00..fc17748d 100644 --- a/scripts/executors.py +++ b/scripts/executors.py @@ -29,11 +29,13 @@ from __future__ import annotations +import hashlib import json import os import re import shutil import subprocess +import tempfile import time from dataclasses import dataclass, field, replace from enum import Enum @@ -707,6 +709,137 @@ def auth_evidence(self) -> tuple[bool, str]: return False, f"no credential at {auth}" +def _git_output(cwd: str, *args: str) -> str: + completed = subprocess.run( + ["git", "-C", cwd, *args], capture_output=True, text=True, + ) + if completed.returncode: + detail = (completed.stderr or completed.stdout or "git command failed").strip() + raise ExecutorError(detail) + return completed.stdout.rstrip("\n") + + +def _isolated_review_dispatch(adapter, target, task, *, cwd, dispatch_call): + """Run a reviewer in a detached worktree and verify its source checkout.""" + if not isinstance(cwd, str) or not cwd: + return adapter._blocked( + target, "review_workspace_isolation", + "a Claude read-only stage needs an implementer Git checkout to verify", + ) + worktree = None + root = None + before_head = before_status = before_branch = None + try: + root = _git_output(cwd, "rev-parse", "--show-toplevel") + before_head = _git_output(root, "rev-parse", "HEAD") + before_branch = _git_output(root, "rev-parse", "--symbolic-full-name", "HEAD") + before_status = _git_output( + root, "status", "--porcelain", "--untracked-files=all", "--ignored=matching", + ) + worktree = tempfile.mkdtemp(prefix="code-cycle-review-") + Path(worktree).rmdir() + if _paths_overlap(worktree, root): + raise ExecutorError("the disposable review worktree overlaps the implementer checkout") + _git_output(root, "worktree", "add", "--detach", worktree, before_head) + review_head = _git_output(worktree, "rev-parse", "HEAD") + if review_head != before_head: + raise ExecutorError("the disposable worktree is not at the reviewed HEAD") + except Exception as exc: + if worktree and root: + subprocess.run( + ["git", "-C", root, "worktree", "remove", "--force", worktree], + capture_output=True, text=True, + ) + subprocess.run(["git", "-C", root, "worktree", "prune"], + capture_output=True, text=True) + if worktree: + shutil.rmtree(worktree, ignore_errors=True) + return adapter._blocked( + target, "review_workspace_isolation", + f"could not prepare an isolated review worktree: {exc}", + ) + + prompt = ( + f"{task}\n\nREAD-ONLY HARNESS CONTRACT: Do not modify files, commit, or push. " + "This stage runs in a disposable detached worktree; any local edits will " + "be discarded. Any change to the implementer's branch or working tree " + "fails this stage." + ) + result = None + workspace_changed = False + source_error = "the implementer branch, HEAD, or working-tree fingerprint changed during review" + cleanup_warning = None + after_head = after_status_fingerprint = None + try: + result = dispatch_call(prompt, worktree) + try: + after_head = _git_output(root, "rev-parse", "HEAD") + after_branch = _git_output(root, "rev-parse", "--symbolic-full-name", "HEAD") + after_status = _git_output( + root, "status", "--porcelain", "--untracked-files=all", "--ignored=matching", + ) + after_status_fingerprint = hashlib.sha256(after_status.encode("utf-8")).hexdigest() + source_changed = ( + after_head != before_head or after_branch != before_branch + or after_status != before_status + ) + except Exception as exc: + source_changed = True + source_error = f"could not verify the implementer checkout after review: {exc}" + try: + workspace_head = _git_output(worktree, "rev-parse", "HEAD") + workspace_status = _git_output( + worktree, "status", "--porcelain", "--untracked-files=all", "--ignored=matching", + ) + workspace_changed = workspace_head != review_head or bool(workspace_status) + except Exception: + workspace_changed = True + finally: + try: + removed = subprocess.run( + ["git", "-C", root, "worktree", "remove", "--force", worktree], + capture_output=True, text=True, + ) + if removed.returncode: + shutil.rmtree(worktree, ignore_errors=True) + subprocess.run(["git", "-C", root, "worktree", "prune"], + capture_output=True, text=True) + if Path(worktree).exists(): + cleanup_warning = "the disposable review workspace could not be removed" + except Exception as exc: + shutil.rmtree(worktree, ignore_errors=True) + cleanup_warning = f"could not remove the disposable review workspace: {exc}" + + warnings = [] + if workspace_changed: + warnings.append("the reviewer changed its disposable workspace; those edits were discarded") + if cleanup_warning: + warnings.append(cleanup_warning) + artifacts = dict(result.artifacts) + artifacts["read_only_mode"] = "isolated_verified" + artifacts["implementer_head_before"] = before_head + artifacts["implementer_status_fingerprint_before"] = hashlib.sha256( + before_status.encode("utf-8"), + ).hexdigest() + if after_head is not None: + artifacts["implementer_head_after"] = after_head + if after_status_fingerprint is not None: + artifacts["implementer_status_fingerprint_after"] = after_status_fingerprint + if warnings: + artifacts["warnings"] = warnings + if source_changed: + return replace( + result, outcome=DispatchOutcome.CONTRACT_VIOLATION, + missing_capability=None, + detail="read-only contract violation: " + source_error, + artifacts=artifacts, + ) + detail = result.detail + if warnings: + detail = detail + ("; " if detail else "") + "warning: " + "; ".join(warnings) + return replace(result, detail=detail, artifacts=artifacts) + + class ClaudeAdapter(NativeAdapter): name = "claude" binary = "claude" @@ -718,7 +851,21 @@ class ClaudeAdapter(NativeAdapter): } def publication_access(self, probe: ProbeResult, *, writes: bool) -> tuple[bool, str]: - return True, "Claude receives gh and git; the stage's publication policy is stated in its prompt" + return True, "Claude uses gh for comments and git for writing stages; publication policy stays in its prompt" + + def supports_non_writing(self, **dispatch_kwargs) -> bool: + cwd = dispatch_kwargs.get("cwd") + return isinstance(cwd, str) and bool(cwd) and Path(cwd).is_dir() + + def dispatch(self, target: Target, task: str, *, cwd: str | None = None, + timeout: int = 3600, runner=_run, writes: bool = False, + publishes: bool = False, + publication_permissions: tuple[str, ...] = ()) -> DispatchResult: + return super().dispatch( + target, task, cwd=cwd, timeout=timeout, runner=runner, + writes=writes, publishes=publishes, + publication_permissions=publication_permissions, + ) def argv(self, target: Target, task: str, cwd: str | None = None, writes: bool = False, publishes: bool = False, @@ -746,11 +893,15 @@ def argv(self, target: Target, task: str, cwd: str | None = None, "--effort", target.effort, "--output-format", "json"] if writes: argv += ["--permission-mode", "acceptEdits"] - # A publishing stage keeps its ordinary GitHub tooling. Which of those - # operations the stage may perform is a behavioural rule stated in its - # prompt (`cycle.publication_policy`), not a permission narrowed here. + else: + # Defence in depth. Read-only safety comes from the disposable + # worktree and the source-checkout verification in dispatch(). + argv += ["--disallowedTools", "Edit", "Write", "NotebookEdit"] + # Publication remains behavioural. A read-only publisher may use gh to + # post its comment, but does not need git access to the reviewed branch. if publishes: - argv += ["--allowedTools", "Bash(gh:*)", "Bash(git:*)"] + argv += (["--allowedTools", "Bash(gh:*)", "Bash(git:*)"] if writes + else ["--allowedTools", "Bash(gh:*)"]) return argv def agent_output(self, stdout: str) -> str: @@ -1166,8 +1317,24 @@ def dispatch( kw.pop("workspace", None) started = clock() - result = adapter.dispatch(target, task, **kw) + if (workspace_policy is WorkspacePolicy.READ_ONLY + and target.executor == "claude" and not adapter.enforces_read_only): + result = _isolated_review_dispatch( + adapter, target, task, cwd=kw.get("cwd"), + dispatch_call=lambda prompt, isolated_cwd: adapter.dispatch( + target, prompt, **{**kw, "cwd": isolated_cwd, "writes": False}, + ), + ) + else: + result = adapter.dispatch(target, task, **kw) elapsed = max(0, round((clock() - started) * 1000)) + if workspace_policy is WorkspacePolicy.READ_ONLY: + artifacts = dict(result.artifacts) + artifacts.setdefault( + "read_only_mode", + "enforced" if adapter.enforces_read_only else "isolated_verified", + ) + result = replace(result, artifacts=artifacts) # From what the adapter is, not from what this result remembered to say. asynchronous = (result.asynchronous or (not adapter.completes_work diff --git a/scripts/router.py b/scripts/router.py index a6d388b3..f566e8b9 100644 --- a/scripts/router.py +++ b/scripts/router.py @@ -204,11 +204,12 @@ def explain(self) -> str: "fallback": "claude:anthropic/claude-sonnet-5 high"}, "reviewer": {"primary": "codex:openai/gpt-6-sol high"}, "senior_reviewer": {"primary": "codex:openai/gpt-6-sol max"}, - # Security audits are strict read-only stages. Claude remains available - # for write-capable roles, but its adapter cannot enforce this boundary. + # Claude is an eligible security fallback through the isolated and verified + # read-only worktree harness; profile defaults still express the chosen + # order. "security": {"primary": "codex:openai/gpt-6-sol high", - # Compatibility-only registry entry: the read-only - # eligibility filter deliberately never selects Claude. + # Selected only when the isolated review harness is + # available. "fallback": "claude:anthropic/claude-opus-5-5 high"}, } diff --git a/scripts/telemetry.py b/scripts/telemetry.py index 969c0d33..22581a14 100644 --- a/scripts/telemetry.py +++ b/scripts/telemetry.py @@ -116,6 +116,7 @@ def is_jev_model(value) -> bool: "provider": ("token", frozenset({"openai", "anthropic"})), "effort": ("token", frozenset({"low", "medium", "high", "max"})), "readiness_policy": ("token", frozenset({"proven", "attempt"})), + "read_only_mode": ("token", frozenset({"enforced", "isolated_verified"})), "dispatched_from": ("token", frozenset({ "unknown", "installed", "authenticated", "quota_exhausted", "ready", })), @@ -766,6 +767,7 @@ def record_dispatch(self, repo_id: str, task_id: str, role: str, decision, resul missing_capability=getattr(result, "missing_capability", None), readiness_policy=getattr(getattr(result, "readiness_policy", None), "value", None), dispatched_from=getattr(getattr(result, "dispatched_from", None), "value", None), + read_only_mode=(getattr(result, "artifacts", {}) or {}).get("read_only_mode"), duration_ms=getattr(result, "duration_ms", None), # The reasons themselves are prose and belong in the published # comment, not in a store that promises to hold none. How many there diff --git a/tests/test_executors.py b/tests/test_executors.py index 4285bc0b..4b07c397 100644 --- a/tests/test_executors.py +++ b/tests/test_executors.py @@ -3,6 +3,7 @@ import json import subprocess import sys +import tempfile import unittest from pathlib import Path from unittest.mock import patch @@ -988,28 +989,110 @@ def test_claude_declares_a_writing_stage(self) -> None: self.assertEqual("acceptEdits", argv[argv.index("--permission-mode") + 1]) def test_claude_publishing_stage_keeps_its_github_tooling(self) -> None: - """The publication boundary is behavioural: gh and git stay available, - and the stage's prompt says which operations it may perform.""" + """Read-only publication gets gh only; writing publication also gets git.""" for permissions in (("comment",), ("comment", "push_branch"), ("comment", "create_pr", "push_branch")): argv = self.claude( writes="push_branch" in permissions, publishes=True, publication_permissions=permissions, ) - self.assertEqual(["--allowedTools", "Bash(gh:*)", "Bash(git:*)"], argv[-3:]) + self.assertIn("--allowedTools", argv) + allowed = argv[argv.index("--allowedTools") + 1:] + expected = ["Bash(gh:*)"] + if "push_branch" in permissions: + expected.append("Bash(git:*)") + self.assertEqual(expected, allowed) + if "push_branch" not in permissions: + index = argv.index("--disallowedTools") + self.assertEqual( + ["--disallowedTools", "Edit", "Write", "NotebookEdit"], + argv[index:index + 4], + ) def test_claude_non_publishing_stage_gets_no_extra_tools(self) -> None: self.assertNotIn("--allowedTools", self.claude(writes=True)) - def test_claude_claims_no_confinement_it_does_not_have(self) -> None: - """A live probe wrote the file anyway with the edit tools disallowed, - and plan mode refuses the edit by turning a review into planning. So a - reading stage gets no flag here rather than a false guarantee.""" + def test_claude_read_only_gets_edit_tools_disallowed_as_defence_in_depth(self) -> None: argv = self.claude(writes=False) self.assertNotIn("--permission-mode", argv) - self.assertNotIn("--disallowedTools", argv) + self.assertEqual(["--disallowedTools", "Edit", "Write", "NotebookEdit"], argv[-4:]) + + + def _git(self, cwd, *args): + return subprocess.run( + ["git", "-C", str(cwd), *args], check=True, + capture_output=True, text=True, + ).stdout.strip() + + def _git_repo(self): + temporary = tempfile.TemporaryDirectory() + self.addCleanup(temporary.cleanup) + repo = Path(temporary.name) / "source" + repo.mkdir() + self._git(repo, "init", "-q") + self._git(repo, "config", "user.name", "Cycle Test") + self._git(repo, "config", "user.email", "cycle@example.invalid") + (repo / "tracked.txt").write_text("reviewed\n", encoding="utf-8") + self._git(repo, "add", "tracked.txt") + self._git(repo, "commit", "-qm", "initial") + return repo + + def test_claude_review_uses_a_detached_disposable_worktree(self) -> None: + repo = self._git_repo() + reviewed_head = self._git(repo, "rev-parse", "HEAD") + seen = {} + target = router.parse_target("claude:anthropic/claude-sonnet-5 high") + + def runner(argv, timeout=None, cwd=None): + seen["argv"], seen["cwd"] = argv, cwd + self.assertNotEqual(str(repo), cwd) + self.assertFalse(ex._paths_overlap(cwd, str(repo))) + self.assertEqual(reviewed_head, self._git(cwd, "rev-parse", "HEAD")) + self.assertIn("Do not modify files, commit, or push", argv[argv.index("-p") + 1]) + (Path(cwd) / "reviewer-created.txt").write_text("discard me", encoding="utf-8") + self._git(cwd, "add", "reviewer-created.txt") + self._git(cwd, "commit", "-qm", "agent edit in isolated worktree") + return completed("{}") + result = ex.dispatch( + router.RoutingDecision("reviewer", target, router.RoutingMode.PRODUCTION), + "review the change", ex.Registry([ex.ClaudeAdapter()]), cwd=str(repo), + runner=runner, + probes={"claude": ex.ProbeResult("claude", ex.Availability.READY, "test")}, + ) + + self.assertEqual(ex.DispatchOutcome.SUCCEEDED, result.outcome) + self.assertEqual("isolated_verified", result.artifacts["read_only_mode"]) + self.assertEqual(reviewed_head, result.artifacts["implementer_head_before"]) + self.assertEqual(64, len(result.artifacts["implementer_status_fingerprint_before"])) + self.assertIn("warning", result.detail) + self.assertFalse(Path(seen["cwd"]).exists()) + self.assertFalse((repo / "reviewer-created.txt").exists()) + self.assertIn("--disallowedTools", seen["argv"]) + self.assertNotIn("--permission-mode", seen["argv"]) + + def test_claude_review_fails_if_the_implementer_branch_moves(self) -> None: + repo = self._git_repo() + target = router.parse_target("claude:anthropic/claude-sonnet-5 high") + before = self._git(repo, "rev-parse", "HEAD") + + def runner(argv, timeout=None, cwd=None): + (repo / "branch-change.txt").write_text("changed", encoding="utf-8") + self._git(repo, "add", "branch-change.txt") + self._git(repo, "commit", "-qm", "unexpected branch change") + return completed("{}") + + result = ex.dispatch( + router.RoutingDecision("reviewer", target, router.RoutingMode.PRODUCTION), + "review the change", ex.Registry([ex.ClaudeAdapter()]), cwd=str(repo), + runner=runner, + probes={"claude": ex.ProbeResult("claude", ex.Availability.READY, "test")}, + ) + + self.assertEqual(ex.DispatchOutcome.CONTRACT_VIOLATION, result.outcome) + self.assertIn("implementer branch, HEAD", result.detail) + self.assertNotEqual(before, self._git(repo, "rev-parse", "HEAD")) class PublicationPreflightTests(unittest.TestCase): def test_github_write_permission_uses_repository_permission_write_value(self) -> None: @@ -1089,6 +1172,7 @@ def runner(argv, timeout=None, cwd=None): ) self.assertEqual(ex.DispatchOutcome.SUCCEEDED, result.outcome) + self.assertEqual("enforced", result.artifacts["read_only_mode"]) self.assertEqual("read-only", seen["argv"][seen["argv"].index("-s") + 1]) def test_disposable_dispatch_requires_an_isolated_workspace(self) -> None: diff --git a/tests/test_run_cycle.py b/tests/test_run_cycle.py index 005f33ec..9cac176b 100644 --- a/tests/test_run_cycle.py +++ b/tests/test_run_cycle.py @@ -10,6 +10,7 @@ import contextlib import io import json +import subprocess import sys import tempfile import unittest @@ -224,9 +225,15 @@ def test_local_only_requires_a_git_worktree(self) -> None: cwd=temporary.name, local_only=True) def test_local_only_rejects_the_live_repository(self) -> None: + temporary = tempfile.TemporaryDirectory() + self.addCleanup(temporary.cleanup) + live_repo = Path(temporary.name) / "live-repository" + live_repo.mkdir() + subprocess.run(["git", "-C", str(live_repo), "init", "-q"], check=True) + with self.assertRaises(rc.CycleDriverError): self.run_cycle(Talker("codex"), Talker("claude"), - cwd=str(ROOT), local_only=True) + cwd=str(live_repo), local_only=True) class MainLocalOnlyTests(unittest.TestCase): diff --git a/tests/test_telemetry.py b/tests/test_telemetry.py index e0538c11..b2e5c4e7 100644 --- a/tests/test_telemetry.py +++ b/tests/test_telemetry.py @@ -450,7 +450,7 @@ def test_it_feeds_the_router_cost_model(self) -> None: class DispatchRecordingTests(TelemetryTestCase): - def decision_and_result(self, blocked_capability=None, used_fallback=False): + def decision_and_result(self, blocked_capability=None, used_fallback=False, read_only_mode=None): target = router.parse_target("codex:openai/gpt-6-luna high") decision = router.RoutingDecision( "cheap_coder", target, router.RoutingMode.PRODUCTION, @@ -469,6 +469,7 @@ def decision_and_result(self, blocked_capability=None, used_fallback=False): model_resolved="gpt-6-luna", readiness_policy=ex.ReadinessPolicy.ATTEMPT, dispatched_from=ex.Availability.AUTHENTICATED, + artifacts=({"read_only_mode": read_only_mode} if read_only_mode else {}), ) return decision, result @@ -487,6 +488,13 @@ def test_a_dispatch_is_recorded_from_the_objects_not_by_hand(self) -> None: self.assertEqual("authenticated", row["dispatched_from"]) self.assertEqual(1, row["payload"]["routing_reason_count"]) + def test_read_only_mode_is_recorded_in_dispatch_payload(self) -> None: + decision, result = self.decision_and_result(read_only_mode="isolated_verified") + + self.store.record_dispatch("repo", "t-review", "review", decision, result) + + self.assertEqual("isolated_verified", self.store.rows()[0]["payload"]["read_only_mode"]) + def test_a_fallback_is_visible_in_the_row(self) -> None: decision, result = self.decision_and_result(used_fallback=True) From f0a90f3a1d6a8c608cdd068450ad205f57c67e75 Mon Sep 17 00:00:00 2001 From: datacas <4690232+datacas@users.noreply.github.com> Date: Thu, 24 Sep 2026 15:29:21 +0200 Subject: [PATCH 2/7] Harden isolated review dispatch --- README.md | 2 +- docs/instrumentation.md | 2 +- docs/role-workspace-policy.md | 2 +- docs/routing.md | 4 +- scripts/executors.py | 90 ++++++++++++++++++----------- tests/test_executors.py | 104 +++++++++++++++++++++++++++++++++- 6 files changed, 163 insertions(+), 41 deletions(-) diff --git a/README.md b/README.md index 1fc2223a..1127ddb9 100644 --- a/README.md +++ b/README.md @@ -132,7 +132,7 @@ Use cc-orchestrator for issue 123. Stop at READY_FOR_MANUAL_MERGE. | [`run_cycle.py`](docs/workflows.md#runtime-driver-run_cyclepy) | a shell command | recorded, routed cycles across executors | runtime, Codex and/or Claude CLIs | Read-only roles can use Codex's enforced sandbox or Claude's isolated, -verified review worktree. See [workspace policy](docs/role-workspace-policy.md) +verified review checkout. See [workspace policy](docs/role-workspace-policy.md) for the branch protection contract. ## Skills diff --git a/docs/instrumentation.md b/docs/instrumentation.md index e09de7fb..053c33d6 100644 --- a/docs/instrumentation.md +++ b/docs/instrumentation.md @@ -735,7 +735,7 @@ nothing had ever asked for anything else. A dispatched Claude, by contrast, edited a file with no flag at all. So the flag on a writing Claude stage declares what is already happening rather than granting something new. -For a **reading** Claude stage, the harness creates a detached worktree at the exact reviewed HEAD, outside the implementer's tree. It records the implementer's HEAD and a fingerprint of `git status --porcelain` before dispatch, then checks both again afterwards. A changed HEAD or working-tree fingerprint makes the stage a `contract_violation`. Writes within Claude's disposable review worktree produce a warning and are discarded with that worktree. The stage prompt prohibits file edits, commits, and pushes; `--disallowedTools Edit Write NotebookEdit` adds defence in depth without serving as the guarantee. Read-only Claude dispatches record `read_only_mode = isolated_verified`. +For a **reading** Claude stage, the harness creates an independent detached clone with its own Git object store at the exact reviewed HEAD, outside the implementer's tree, and removes the clone's remotes. A dirty implementer checkout blocks preparation. It records the implementer's HEAD, a fingerprint of `git status --porcelain`, and advertised refs for configured remotes before dispatch, then checks them again afterwards. A detected change makes the stage a `contract_violation`. Writes within Claude's disposable clone produce a warning and are discarded with that clone. The stage prompt prohibits file edits, commits, and pushes; `--disallowedTools Edit Write NotebookEdit` adds defence in depth without serving as the guarantee. Read-only Claude dispatches record `read_only_mode = isolated_verified` only after isolation and verification succeed. Codex retains `-s read-only` and records `read_only_mode = enforced`, meaning its sandbox prevents workspace writes. Orca still requires its explicit review-workspace contract. Reviews may use any configured eligible executor; a profile may still choose no fallback. Publication access remains behavioural: a read-only stage receives only the tools its role permits, such as `gh` for an allowed comment. diff --git a/docs/role-workspace-policy.md b/docs/role-workspace-policy.md index c7cffbc4..04a3759e 100644 --- a/docs/role-workspace-policy.md +++ b/docs/role-workspace-policy.md @@ -20,7 +20,7 @@ eligible for `disposable`, even when its process cwd is isolated. An adapter is eligible only when the harness can establish the requested policy. Codex enforces read-only execution directly with its sandbox and records `read_only_mode = enforced`. -Claude cannot enforce read-only inside its process, so the harness runs it in a detached worktree at the exact reviewed HEAD, outside the implementer's tree. Before and after the stage, the harness compares the implementer's HEAD and `git status --porcelain`; a change is a `contract_violation`. Edits inside the disposable review worktree produce a warning and are discarded. Claude records `read_only_mode = isolated_verified`, and its reviewer cannot write to the branch. The prompt also prohibits edits, commits, and pushes, while CLI tool restrictions provide defence in depth. Publication access remains behavioural and follows the role's existing policy. +Claude cannot enforce read-only inside its process, so the harness runs it in an independent detached clone with its own Git object store at the exact reviewed HEAD, outside the implementer's tree, with the clone's remotes removed. A dirty implementer checkout blocks preparation. Before and after the stage, the harness compares the implementer's HEAD, `git status --porcelain`, and every configured remote's advertised refs; a detected change is a `contract_violation`. Edits inside the disposable clone produce a warning and are discarded. Claude records `read_only_mode = isolated_verified` only after those checks pass. The prompt prohibits edits, commits, and pushes, while CLI tool restrictions provide defence in depth. Publication access remains behavioural and follows the role's existing policy. Claude remains ineligible for `disposable` roles because it cannot confine writes to their workspace. Orca follows its explicit review-workspace contract and requires its own orchestration context where applicable. diff --git a/docs/routing.md b/docs/routing.md index dee7aa7c..c492e9de 100644 --- a/docs/routing.md +++ b/docs/routing.md @@ -94,10 +94,10 @@ Each role has a fixed write permission. Only an executor that can **enforce** it | Role | Policy | Eligible executors | |---|---|---| | `implement`, `resolve` | `workspace_write` | Codex (`-s workspace-write`), Claude (`acceptEdits`), Orca | -| `review`, `rereview`, `security`, `bootstrap`, `coordinate` | `read_only` | Codex (`-s read-only`), Claude (isolated and verified worktree), Orca (explicit review workspace) | +| `review`, `rereview`, `security`, `bootstrap`, `coordinate` | `read_only` | Codex (`-s read-only`), Claude (independent isolated clone, verified), Orca (explicit review workspace) | | `verify`, `run` | `disposable` | Codex, confined to a disposable workspace | -Codex records `read_only_mode = enforced`: its sandbox prevents workspace writes. Claude records `read_only_mode = isolated_verified`: the harness checks out the reviewed HEAD in a detached disposable worktree, verifies that the implementer's HEAD and working-tree fingerprint did not change, and discards local edits. A Claude reviewer cannot write to the branch. Reviews may still be configured without a fallback; that is a profile choice. Publication access remains role-specific, and a reviewer may publish only the comment its role permits. Details are in [Role workspace policy](role-workspace-policy.md). +Codex records `read_only_mode = enforced`: its sandbox prevents workspace writes. Claude records `read_only_mode = isolated_verified`: the harness creates an independent detached clone with its own Git object store at the reviewed HEAD, removes its remotes, and discards local edits. The harness requires a clean implementer checkout and checks its HEAD, working-tree fingerprint, and configured remote refs before and after review; a detected change fails the stage as a contract violation. Publication access remains role-specific, and a reviewer may publish only the comment its role permits. Details are in [Role workspace policy](role-workspace-policy.md). ## Publication boundary diff --git a/scripts/executors.py b/scripts/executors.py index fc17748d..32d9f5ff 100644 --- a/scripts/executors.py +++ b/scripts/executors.py @@ -709,9 +709,10 @@ def auth_evidence(self) -> tuple[bool, str]: return False, f"no credential at {auth}" -def _git_output(cwd: str, *args: str) -> str: +def _git_output(cwd: str, *args: str, timeout: int = 10) -> str: completed = subprocess.run( ["git", "-C", cwd, *args], capture_output=True, text=True, + stdin=subprocess.DEVNULL, timeout=timeout, ) if completed.returncode: detail = (completed.stderr or completed.stdout or "git command failed").strip() @@ -719,8 +720,28 @@ def _git_output(cwd: str, *args: str) -> str: return completed.stdout.rstrip("\n") +def _remote_ref_fingerprint(root: str) -> str: + """Fingerprint every advertised ref at each configured fetch/push URL.""" + snapshot = [] + for remote in _git_output(root, "remote").splitlines(): + urls = set() + for args in (("remote", "get-url", "--all", remote), + ("remote", "get-url", "--push", "--all", remote)): + urls.update(filter(None, _git_output(root, *args).splitlines())) + for url in sorted(urls): + try: + refs = _git_output(root, "ls-remote", "--refs", url) + except Exception as exc: + raise ExecutorError( + f"could not inspect configured remote refs ({type(exc).__name__})" + ) from None + snapshot.extend((remote, url, line) for line in refs.splitlines()) + encoded = json.dumps(sorted(snapshot), separators=(",", ":")) + return hashlib.sha256(encoded.encode("utf-8")).hexdigest() + + def _isolated_review_dispatch(adapter, target, task, *, cwd, dispatch_call): - """Run a reviewer in a detached worktree and verify its source checkout.""" + """Run a reviewer in an independent detached clone and verify its source checkout.""" if not isinstance(cwd, str) or not cwd: return adapter._blocked( target, "review_workspace_isolation", @@ -728,60 +749,66 @@ def _isolated_review_dispatch(adapter, target, task, *, cwd, dispatch_call): ) worktree = None root = None - before_head = before_status = before_branch = None + before_head = before_status = before_branch = before_remote_refs = None try: root = _git_output(cwd, "rev-parse", "--show-toplevel") before_head = _git_output(root, "rev-parse", "HEAD") before_branch = _git_output(root, "rev-parse", "--symbolic-full-name", "HEAD") before_status = _git_output( - root, "status", "--porcelain", "--untracked-files=all", "--ignored=matching", + root, "status", "--porcelain", "--untracked-files=all", ) + if before_status: + raise ExecutorError( + "the implementer checkout must be clean before an isolated review" + ) + before_remote_refs = _remote_ref_fingerprint(root) worktree = tempfile.mkdtemp(prefix="code-cycle-review-") Path(worktree).rmdir() if _paths_overlap(worktree, root): - raise ExecutorError("the disposable review worktree overlaps the implementer checkout") - _git_output(root, "worktree", "add", "--detach", worktree, before_head) + raise ExecutorError("the disposable review workspace overlaps the implementer checkout") + _git_output( + root, "clone", "--no-hardlinks", "--no-checkout", root, worktree, + timeout=300, + ) + for remote in _git_output(worktree, "remote").splitlines(): + _git_output(worktree, "remote", "remove", remote) + _git_output(worktree, "checkout", "--detach", before_head) review_head = _git_output(worktree, "rev-parse", "HEAD") if review_head != before_head: - raise ExecutorError("the disposable worktree is not at the reviewed HEAD") + raise ExecutorError("the disposable clone is not at the reviewed HEAD") except Exception as exc: - if worktree and root: - subprocess.run( - ["git", "-C", root, "worktree", "remove", "--force", worktree], - capture_output=True, text=True, - ) - subprocess.run(["git", "-C", root, "worktree", "prune"], - capture_output=True, text=True) if worktree: shutil.rmtree(worktree, ignore_errors=True) return adapter._blocked( target, "review_workspace_isolation", - f"could not prepare an isolated review worktree: {exc}", + f"could not prepare an isolated review workspace: {exc}", ) prompt = ( f"{task}\n\nREAD-ONLY HARNESS CONTRACT: Do not modify files, commit, or push. " - "This stage runs in a disposable detached worktree; any local edits will " + "This stage runs in an independent disposable clone; any local edits will " "be discarded. Any change to the implementer's branch or working tree " "fails this stage." ) result = None workspace_changed = False - source_error = "the implementer branch, HEAD, or working-tree fingerprint changed during review" + source_error = "the implementer branch, HEAD, working tree, or configured remote refs changed during review" cleanup_warning = None - after_head = after_status_fingerprint = None + after_head = after_status_fingerprint = after_remote_refs = None try: result = dispatch_call(prompt, worktree) try: after_head = _git_output(root, "rev-parse", "HEAD") after_branch = _git_output(root, "rev-parse", "--symbolic-full-name", "HEAD") after_status = _git_output( - root, "status", "--porcelain", "--untracked-files=all", "--ignored=matching", + root, "status", "--porcelain", "--untracked-files=all", ) after_status_fingerprint = hashlib.sha256(after_status.encode("utf-8")).hexdigest() + after_remote_refs = _remote_ref_fingerprint(root) source_changed = ( after_head != before_head or after_branch != before_branch or after_status != before_status + or after_remote_refs != before_remote_refs ) except Exception as exc: source_changed = True @@ -789,23 +816,16 @@ def _isolated_review_dispatch(adapter, target, task, *, cwd, dispatch_call): try: workspace_head = _git_output(worktree, "rev-parse", "HEAD") workspace_status = _git_output( - worktree, "status", "--porcelain", "--untracked-files=all", "--ignored=matching", + worktree, "status", "--porcelain", "--untracked-files=all", ) workspace_changed = workspace_head != review_head or bool(workspace_status) except Exception: workspace_changed = True finally: try: - removed = subprocess.run( - ["git", "-C", root, "worktree", "remove", "--force", worktree], - capture_output=True, text=True, - ) - if removed.returncode: - shutil.rmtree(worktree, ignore_errors=True) - subprocess.run(["git", "-C", root, "worktree", "prune"], - capture_output=True, text=True) - if Path(worktree).exists(): - cleanup_warning = "the disposable review workspace could not be removed" + shutil.rmtree(worktree) + if Path(worktree).exists(): + cleanup_warning = "the disposable review workspace could not be removed" except Exception as exc: shutil.rmtree(worktree, ignore_errors=True) cleanup_warning = f"could not remove the disposable review workspace: {exc}" @@ -821,13 +841,17 @@ def _isolated_review_dispatch(adapter, target, task, *, cwd, dispatch_call): artifacts["implementer_status_fingerprint_before"] = hashlib.sha256( before_status.encode("utf-8"), ).hexdigest() + artifacts["remote_refs_fingerprint_before"] = before_remote_refs if after_head is not None: artifacts["implementer_head_after"] = after_head if after_status_fingerprint is not None: artifacts["implementer_status_fingerprint_after"] = after_status_fingerprint + if after_remote_refs is not None: + artifacts["remote_refs_fingerprint_after"] = after_remote_refs if warnings: artifacts["warnings"] = warnings if source_changed: + artifacts.pop("read_only_mode", None) return replace( result, outcome=DispatchOutcome.CONTRACT_VIOLATION, missing_capability=None, @@ -1330,10 +1354,8 @@ def dispatch( elapsed = max(0, round((clock() - started) * 1000)) if workspace_policy is WorkspacePolicy.READ_ONLY: artifacts = dict(result.artifacts) - artifacts.setdefault( - "read_only_mode", - "enforced" if adapter.enforces_read_only else "isolated_verified", - ) + if adapter.enforces_read_only: + artifacts.setdefault("read_only_mode", "enforced") result = replace(result, artifacts=artifacts) # From what the adapter is, not from what this result remembered to say. asynchronous = (result.asynchronous diff --git a/tests/test_executors.py b/tests/test_executors.py index 4b07c397..d707d78d 100644 --- a/tests/test_executors.py +++ b/tests/test_executors.py @@ -1038,8 +1038,33 @@ def _git_repo(self): self._git(repo, "commit", "-qm", "initial") return repo - def test_claude_review_uses_a_detached_disposable_worktree(self) -> None: + def test_remote_ref_errors_do_not_expose_embedded_credentials(self) -> None: + remote_url = "https://user:secret@example.invalid/repo.git" + with patch.object( + ex, "_git_output", + side_effect=[ + "origin", remote_url, remote_url, + ex.ExecutorError(f"authentication failed for {remote_url}"), + ], + ): + with self.assertRaises(ex.ExecutorError) as raised: + ex._remote_ref_fingerprint("/repo") + + self.assertIn("could not inspect configured remote refs", str(raised.exception)) + self.assertNotIn("secret", str(raised.exception)) + + def test_git_verification_commands_are_bounded_and_noninteractive(self) -> None: + with patch.object(ex.subprocess, "run", return_value=completed("head" + chr(10))) as run: + self.assertEqual("head", ex._git_output("/repo", "rev-parse", "HEAD")) + + self.assertIs(run.call_args.kwargs["stdin"], subprocess.DEVNULL) + self.assertEqual(10, run.call_args.kwargs["timeout"]) + + def test_claude_review_uses_an_independent_disposable_clone(self) -> None: repo = self._git_repo() + (repo / ".git" / "info" / "exclude").write_text(".cache/", encoding="utf-8") + (repo / ".cache").mkdir() + (repo / ".cache" / "artifact").write_text("ignored", encoding="utf-8") reviewed_head = self._git(repo, "rev-parse", "HEAD") seen = {} target = router.parse_target("claude:anthropic/claude-sonnet-5 high") @@ -1049,10 +1074,15 @@ def runner(argv, timeout=None, cwd=None): self.assertNotEqual(str(repo), cwd) self.assertFalse(ex._paths_overlap(cwd, str(repo))) self.assertEqual(reviewed_head, self._git(cwd, "rev-parse", "HEAD")) + self.assertTrue((Path(cwd) / ".git").is_dir()) + self.assertFalse((Path(cwd) / ".git" / "objects" / "info" / "alternates").exists()) + self.assertEqual("", self._git(cwd, "remote")) + self._git(cwd, "branch", "reviewer-local", reviewed_head) + self._git(cwd, "config", "cycle.shared-test", "changed") self.assertIn("Do not modify files, commit, or push", argv[argv.index("-p") + 1]) (Path(cwd) / "reviewer-created.txt").write_text("discard me", encoding="utf-8") self._git(cwd, "add", "reviewer-created.txt") - self._git(cwd, "commit", "-qm", "agent edit in isolated worktree") + self._git(cwd, "commit", "-qm", "agent edit in isolated clone") return completed("{}") result = ex.dispatch( @@ -1069,6 +1099,12 @@ def runner(argv, timeout=None, cwd=None): self.assertIn("warning", result.detail) self.assertFalse(Path(seen["cwd"]).exists()) self.assertFalse((repo / "reviewer-created.txt").exists()) + self.assertEqual("", self._git(repo, "branch", "--list", "reviewer-local")) + shared_config = subprocess.run( + ["git", "-C", str(repo), "config", "--local", "--get", "cycle.shared-test"], + capture_output=True, text=True, + ) + self.assertNotEqual(0, shared_config.returncode) self.assertIn("--disallowedTools", seen["argv"]) self.assertNotIn("--permission-mode", seen["argv"]) @@ -1093,6 +1129,70 @@ def runner(argv, timeout=None, cwd=None): self.assertEqual(ex.DispatchOutcome.CONTRACT_VIOLATION, result.outcome) self.assertIn("implementer branch, HEAD", result.detail) self.assertNotEqual(before, self._git(repo, "rev-parse", "HEAD")) + def test_claude_review_rejects_a_dirty_implementer_checkout(self) -> None: + repo = self._git_repo() + (repo / "tracked.txt").write_text("dirty before review\\n", encoding="utf-8") + target = router.parse_target("claude:anthropic/claude-sonnet-5 high") + + result = ex.dispatch( + router.RoutingDecision("reviewer", target, router.RoutingMode.PRODUCTION), + "review the change", ex.Registry([ex.ClaudeAdapter()]), cwd=str(repo), + runner=lambda *args, **kwargs: self.fail("a dirty checkout must not be reviewed"), + probes={"claude": ex.ProbeResult("claude", ex.Availability.READY, "test")}, + ) + + self.assertEqual(ex.DispatchOutcome.BLOCKED, result.outcome) + self.assertEqual("review_workspace_isolation", result.missing_capability) + self.assertNotIn("read_only_mode", result.artifacts) + + def test_claude_review_detects_a_remote_branch_push(self) -> None: + repo = self._git_repo() + temporary = tempfile.TemporaryDirectory() + self.addCleanup(temporary.cleanup) + remote = Path(temporary.name) / "remote.git" + subprocess.run(["git", "init", "--bare", "-q", str(remote)], check=True) + self._git(repo, "remote", "add", "origin", str(remote)) + self._git(repo, "push", "origin", "HEAD") + target = router.parse_target("claude:anthropic/claude-sonnet-5 high") + + def runner(argv, timeout=None, cwd=None): + (Path(cwd) / "reviewer.txt").write_text("review result\\n", encoding="utf-8") + self._git(cwd, "add", "reviewer.txt") + self._git(cwd, "commit", "-qm", "reviewer change") + self._git(cwd, "push", str(remote), "HEAD:refs/heads/review") + return completed("{}") + + result = ex.dispatch( + router.RoutingDecision("reviewer", target, router.RoutingMode.PRODUCTION), + "review the change", ex.Registry([ex.ClaudeAdapter()]), cwd=str(repo), + runner=runner, + probes={"claude": ex.ProbeResult("claude", ex.Availability.READY, "test")}, + ) + + self.assertEqual(ex.DispatchOutcome.CONTRACT_VIOLATION, result.outcome) + self.assertIn("configured remote refs changed", result.detail) + self.assertNotIn("read_only_mode", result.artifacts) + self.assertNotEqual( + result.artifacts["remote_refs_fingerprint_before"], + result.artifacts["remote_refs_fingerprint_after"], + ) + self.assertIn("reviewer.txt", self._git(remote, "ls-tree", "-r", "--name-only", "refs/heads/review")) + + def test_failed_isolation_does_not_claim_verified_mode(self) -> None: + temporary = tempfile.TemporaryDirectory() + self.addCleanup(temporary.cleanup) + target = router.parse_target("claude:anthropic/claude-sonnet-5 high") + + result = ex.dispatch( + router.RoutingDecision("reviewer", target, router.RoutingMode.PRODUCTION), + "review the change", ex.Registry([ex.ClaudeAdapter()]), cwd=temporary.name, + runner=lambda *args, **kwargs: self.fail("isolation setup must fail first"), + probes={"claude": ex.ProbeResult("claude", ex.Availability.READY, "test")}, + ) + + self.assertEqual(ex.DispatchOutcome.BLOCKED, result.outcome) + self.assertNotIn("read_only_mode", result.artifacts) + class PublicationPreflightTests(unittest.TestCase): def test_github_write_permission_uses_repository_permission_write_value(self) -> None: From 3bc7006ce8375b6b01cb642bd20642b39ca5ba78 Mon Sep 17 00:00:00 2001 From: datacas <4690232+datacas@users.noreply.github.com> Date: Thu, 24 Sep 2026 15:34:23 +0200 Subject: [PATCH 3/7] Set reviewer test identity in isolated clones --- tests/test_executors.py | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/tests/test_executors.py b/tests/test_executors.py index d707d78d..64c616f1 100644 --- a/tests/test_executors.py +++ b/tests/test_executors.py @@ -1082,6 +1082,8 @@ def runner(argv, timeout=None, cwd=None): self.assertIn("Do not modify files, commit, or push", argv[argv.index("-p") + 1]) (Path(cwd) / "reviewer-created.txt").write_text("discard me", encoding="utf-8") self._git(cwd, "add", "reviewer-created.txt") + self._git(cwd, "config", "user.name", "Reviewer Test") + self._git(cwd, "config", "user.email", "reviewer@example.invalid") self._git(cwd, "commit", "-qm", "agent edit in isolated clone") return completed("{}") @@ -1158,6 +1160,8 @@ def test_claude_review_detects_a_remote_branch_push(self) -> None: def runner(argv, timeout=None, cwd=None): (Path(cwd) / "reviewer.txt").write_text("review result\\n", encoding="utf-8") self._git(cwd, "add", "reviewer.txt") + self._git(cwd, "config", "user.name", "Reviewer Test") + self._git(cwd, "config", "user.email", "reviewer@example.invalid") self._git(cwd, "commit", "-qm", "reviewer change") self._git(cwd, "push", str(remote), "HEAD:refs/heads/review") return completed("{}") From dfae17471879a23cd33a44815c57579064e1eadd Mon Sep 17 00:00:00 2001 From: datacas <4690232+datacas@users.noreply.github.com> Date: Thu, 24 Sep 2026 15:39:45 +0200 Subject: [PATCH 4/7] Remove read-only review clone files on Windows --- scripts/executors.py | 22 ++++++++++++++++++---- 1 file changed, 18 insertions(+), 4 deletions(-) diff --git a/scripts/executors.py b/scripts/executors.py index 32d9f5ff..35bad2f1 100644 --- a/scripts/executors.py +++ b/scripts/executors.py @@ -740,6 +740,14 @@ def _remote_ref_fingerprint(root: str) -> str: return hashlib.sha256(encoded.encode("utf-8")).hexdigest() +def _remove_read_only_path(function, path, exc_info) -> None: + try: + os.chmod(path, 0o700) + function(path) + except OSError: + raise exc_info[1] + + def _isolated_review_dispatch(adapter, target, task, *, cwd, dispatch_call): """Run a reviewer in an independent detached clone and verify its source checkout.""" if not isinstance(cwd, str) or not cwd: @@ -777,11 +785,17 @@ def _isolated_review_dispatch(adapter, target, task, *, cwd, dispatch_call): if review_head != before_head: raise ExecutorError("the disposable clone is not at the reviewed HEAD") except Exception as exc: + cleanup_error = None if worktree: - shutil.rmtree(worktree, ignore_errors=True) + try: + shutil.rmtree(worktree, onerror=_remove_read_only_path) + except Exception as cleanup_exc: + cleanup_error = f"; cleanup failed ({type(cleanup_exc).__name__})" + detail = f"could not prepare an isolated review workspace: {exc}" + if cleanup_error: + detail += cleanup_error return adapter._blocked( - target, "review_workspace_isolation", - f"could not prepare an isolated review workspace: {exc}", + target, "review_workspace_isolation", detail, ) prompt = ( @@ -823,7 +837,7 @@ def _isolated_review_dispatch(adapter, target, task, *, cwd, dispatch_call): workspace_changed = True finally: try: - shutil.rmtree(worktree) + shutil.rmtree(worktree, onerror=_remove_read_only_path) if Path(worktree).exists(): cleanup_warning = "the disposable review workspace could not be removed" except Exception as exc: From 8ee2afe80e1f8b68cd1d41d49e9a281af8438044 Mon Sep 17 00:00:00 2001 From: datacas <4690232+datacas@users.noreply.github.com> Date: Thu, 24 Sep 2026 16:15:29 +0200 Subject: [PATCH 5/7] Run Claude reviews without credentials and fail on leftover clones Claude read-only stages now run with a temporary HOME, an empty gh configuration, a neutral global Git configuration, no system Git configuration, no SSH agent, and no token-like variables, so the reviewer cannot push or call GitHub as the user (REV-001). Because it cannot publish, Claude is no longer eligible for read-only stages that publish; a direct dispatch is BLOCKED with harness_publication until harness-side publication lands (#79). A review clone or temporary home that cannot be removed now fails the stage and drops read_only_mode instead of reporting verified isolation (REV-004). --- README.md | 3 +- docs/instrumentation.md | 4 +- docs/role-workspace-policy.md | 2 +- docs/routing.md | 6 +- scripts/executors.py | 205 ++++++++++++++++++++++++++++------ scripts/telemetry.py | 2 +- tests/test_executors.py | 133 +++++++++++++++++++++- tests/test_telemetry.py | 7 ++ 8 files changed, 317 insertions(+), 45 deletions(-) diff --git a/README.md b/README.md index 1127ddb9..676b2635 100644 --- a/README.md +++ b/README.md @@ -132,7 +132,8 @@ Use cc-orchestrator for issue 123. Stop at READY_FOR_MANUAL_MERGE. | [`run_cycle.py`](docs/workflows.md#runtime-driver-run_cyclepy) | a shell command | recorded, routed cycles across executors | runtime, Codex and/or Claude CLIs | Read-only roles can use Codex's enforced sandbox or Claude's isolated, -verified review checkout. See [workspace policy](docs/role-workspace-policy.md) +verified, credential-free review checkout; Claude does not yet serve the +read-only stages that publish a comment. See [workspace policy](docs/role-workspace-policy.md) for the branch protection contract. ## Skills diff --git a/docs/instrumentation.md b/docs/instrumentation.md index 053c33d6..024db0c5 100644 --- a/docs/instrumentation.md +++ b/docs/instrumentation.md @@ -735,9 +735,9 @@ nothing had ever asked for anything else. A dispatched Claude, by contrast, edited a file with no flag at all. So the flag on a writing Claude stage declares what is already happening rather than granting something new. -For a **reading** Claude stage, the harness creates an independent detached clone with its own Git object store at the exact reviewed HEAD, outside the implementer's tree, and removes the clone's remotes. A dirty implementer checkout blocks preparation. It records the implementer's HEAD, a fingerprint of `git status --porcelain`, and advertised refs for configured remotes before dispatch, then checks them again afterwards. A detected change makes the stage a `contract_violation`. Writes within Claude's disposable clone produce a warning and are discarded with that clone. The stage prompt prohibits file edits, commits, and pushes; `--disallowedTools Edit Write NotebookEdit` adds defence in depth without serving as the guarantee. Read-only Claude dispatches record `read_only_mode = isolated_verified` only after isolation and verification succeed. +For a **reading** Claude stage, the harness creates an independent detached clone with its own Git object store at the exact reviewed HEAD, outside the implementer's tree, and removes the clone's remotes. A dirty implementer checkout blocks preparation. It records the implementer's HEAD, a fingerprint of `git status --porcelain`, and advertised refs for configured remotes before dispatch, then checks them again afterwards. A detected change makes the stage a `contract_violation`. Writes within Claude's disposable clone produce a warning and are discarded with that clone. The stage prompt prohibits file edits, commits, and pushes; `--disallowedTools Edit Write NotebookEdit` adds defence in depth without serving as the guarantee. Read-only Claude dispatches record `read_only_mode = isolated_verified` only after isolation and verification succeed. The reviewer runs without GitHub or Git credentials: a temporary `HOME` with only Claude's own login linked in, an empty `GH_CONFIG_DIR`, no `GH_TOKEN`/`GITHUB_TOKEN`, a neutral `GIT_CONFIG_GLOBAL` with `GIT_CONFIG_NOSYSTEM=1`, no SSH agent, and interactive prompts disabled, so it cannot push or call GitHub as the user. This removes the credentials the process is handed; it is not an OS sandbox, and a credential stored in a readable file elsewhere on disk stays outside its reach. Because the reviewer cannot publish, Claude is not eligible for read-only stages that publish (`review`, `rereview`); a direct dispatch of one returns `BLOCKED` with `harness_publication` until harness-side publication lands ([#79](https://github.com/datacas/code-cycle-toolkit/issues/79)). If the clone or the temporary home cannot be removed afterwards, the stage fails and records no `read_only_mode`. -Codex retains `-s read-only` and records `read_only_mode = enforced`, meaning its sandbox prevents workspace writes. Orca still requires its explicit review-workspace contract. Reviews may use any configured eligible executor; a profile may still choose no fallback. Publication access remains behavioural: a read-only stage receives only the tools its role permits, such as `gh` for an allowed comment. +Codex retains `-s read-only` and records `read_only_mode = enforced`, meaning its sandbox prevents workspace writes. Orca still requires its explicit review-workspace contract. Reviews may use any configured eligible executor; a profile may still choose no fallback. Publication access remains behavioural for the executors that hold credentials. ## Running a cycle diff --git a/docs/role-workspace-policy.md b/docs/role-workspace-policy.md index 04a3759e..e08c0740 100644 --- a/docs/role-workspace-policy.md +++ b/docs/role-workspace-policy.md @@ -20,7 +20,7 @@ eligible for `disposable`, even when its process cwd is isolated. An adapter is eligible only when the harness can establish the requested policy. Codex enforces read-only execution directly with its sandbox and records `read_only_mode = enforced`. -Claude cannot enforce read-only inside its process, so the harness runs it in an independent detached clone with its own Git object store at the exact reviewed HEAD, outside the implementer's tree, with the clone's remotes removed. A dirty implementer checkout blocks preparation. Before and after the stage, the harness compares the implementer's HEAD, `git status --porcelain`, and every configured remote's advertised refs; a detected change is a `contract_violation`. Edits inside the disposable clone produce a warning and are discarded. Claude records `read_only_mode = isolated_verified` only after those checks pass. The prompt prohibits edits, commits, and pushes, while CLI tool restrictions provide defence in depth. Publication access remains behavioural and follows the role's existing policy. +Claude cannot enforce read-only inside its process, so the harness runs it in an independent detached clone with its own Git object store at the exact reviewed HEAD, outside the implementer's tree, with the clone's remotes removed. A dirty implementer checkout blocks preparation. Before and after the stage, the harness compares the implementer's HEAD, `git status --porcelain`, and every configured remote's advertised refs; a detected change is a `contract_violation`. Edits inside the disposable clone produce a warning and are discarded. Claude records `read_only_mode = isolated_verified` only after those checks pass. The prompt prohibits edits, commits, and pushes, while CLI tool restrictions provide defence in depth. The reviewer runs without GitHub or Git credentials: a temporary `HOME` with only Claude's own login linked in, an empty `GH_CONFIG_DIR`, no `GH_TOKEN`/`GITHUB_TOKEN`, a neutral `GIT_CONFIG_GLOBAL` with `GIT_CONFIG_NOSYSTEM=1`, no SSH agent, and interactive prompts disabled, so it cannot push or call GitHub as the user. This removes the credentials the process is handed; it is not an OS sandbox, and a credential stored in a readable file elsewhere on disk stays outside its reach. Because the reviewer cannot publish, Claude is not eligible for read-only stages that publish (`review`, `rereview`); a direct dispatch of one returns `BLOCKED` with `harness_publication` until harness-side publication lands ([#79](https://github.com/datacas/code-cycle-toolkit/issues/79)). If the clone or the temporary home cannot be removed afterwards, the stage fails and records no `read_only_mode`. Claude remains ineligible for `disposable` roles because it cannot confine writes to their workspace. Orca follows its explicit review-workspace contract and requires its own orchestration context where applicable. diff --git a/docs/routing.md b/docs/routing.md index c492e9de..1268f98f 100644 --- a/docs/routing.md +++ b/docs/routing.md @@ -35,7 +35,7 @@ A profile names a *kind* of work. It never appears in a skill as a model name. | `auxiliary_tool` | verify, run, bootstrap | `codex:openai/gpt-6-luna medium` | — | | `cheap_tool` | compatibility for direct/custom callers; no built-in role selects it | `claude:anthropic/claude-haiku-4-5-20251001 low` | — | -¹ The security profile retains this configured fallback; Claude runs read-only stages only through the isolated, verified workspace contract described below. +¹ The security profile retains this configured fallback; Claude runs read-only stages only through the isolated, verified, credential-free workspace contract described below. The source of truth is `DEFAULT_PROFILES` in [`scripts/router.py`](../scripts/router.py). Override only what you want to change, and the rest keep their defaults: @@ -94,10 +94,10 @@ Each role has a fixed write permission. Only an executor that can **enforce** it | Role | Policy | Eligible executors | |---|---|---| | `implement`, `resolve` | `workspace_write` | Codex (`-s workspace-write`), Claude (`acceptEdits`), Orca | -| `review`, `rereview`, `security`, `bootstrap`, `coordinate` | `read_only` | Codex (`-s read-only`), Claude (independent isolated clone, verified), Orca (explicit review workspace) | +| `review`, `rereview`, `security`, `bootstrap`, `coordinate` | `read_only` | Codex (`-s read-only`); Claude (independent isolated clone, verified, no credentials) only for `security`, `bootstrap` and `coordinate`, or any of them when run local-only; Orca (explicit review workspace) | | `verify`, `run` | `disposable` | Codex, confined to a disposable workspace | -Codex records `read_only_mode = enforced`: its sandbox prevents workspace writes. Claude records `read_only_mode = isolated_verified`: the harness creates an independent detached clone with its own Git object store at the reviewed HEAD, removes its remotes, and discards local edits. The harness requires a clean implementer checkout and checks its HEAD, working-tree fingerprint, and configured remote refs before and after review; a detected change fails the stage as a contract violation. Publication access remains role-specific, and a reviewer may publish only the comment its role permits. Details are in [Role workspace policy](role-workspace-policy.md). +Codex records `read_only_mode = enforced`: its sandbox prevents workspace writes. Claude records `read_only_mode = isolated_verified`: the harness creates an independent detached clone with its own Git object store at the reviewed HEAD, removes its remotes, and discards local edits. The harness requires a clean implementer checkout and checks its HEAD, working-tree fingerprint, and configured remote refs before and after review; a detected change fails the stage as a contract violation. Claude runs there without GitHub or Git credentials, so it cannot push, and for the same reason cannot publish: `review` and `rereview` stay on Codex until harness-side publication lands ([#79](https://github.com/datacas/code-cycle-toolkit/issues/79)). Publication access for Codex remains role-specific, and a reviewer may publish only the comment its role permits. Details are in [Role workspace policy](role-workspace-policy.md). ## Publication boundary diff --git a/scripts/executors.py b/scripts/executors.py index 35bad2f1..ca6d6e4e 100644 --- a/scripts/executors.py +++ b/scripts/executors.py @@ -270,9 +270,10 @@ def explain(self) -> str: return f"{self.executor}: {self.outcome.value} as {self.model_resolved or '?'}{suffix}" -def _run(argv: list[str], timeout: int = 30, cwd: str | None = None) -> subprocess.CompletedProcess: +def _run(argv: list[str], timeout: int = 30, cwd: str | None = None, + env: dict[str, str] | None = None) -> subprocess.CompletedProcess: return subprocess.run(argv, capture_output=True, text=True, timeout=timeout, cwd=cwd, - stdin=subprocess.DEVNULL) + stdin=subprocess.DEVNULL, env=env) def _publication_preflight(cwd: str | None) -> tuple[bool, str]: @@ -361,6 +362,10 @@ def supports_non_writing(self, **dispatch_kwargs) -> bool: """Whether this adapter can keep this non-writing dispatch isolated.""" return self.enforces_read_only + def read_only_refusal(self, **dispatch_kwargs) -> tuple[str, str] | None: + """A specific (capability, detail) for refusing this non-writing dispatch.""" + return None + def supports_workspace_policy(self, policy: WorkspacePolicy | str, **dispatch_kwargs) -> bool: """Whether this adapter can honour the complete workspace contract.""" @@ -488,7 +493,8 @@ def read_resolved_model(self, stdout: str) -> str | None: def dispatch(self, target: Target, task: str, *, cwd: str | None = None, timeout: int = 3600, runner=_run, writes: bool = False, publishes: bool = False, - publication_permissions: tuple[str, ...] = ()) -> DispatchResult: + publication_permissions: tuple[str, ...] = (), + env: dict[str, str] | None = None) -> DispatchResult: """Run the agent non-interactively and classify what came back. `writes` is what the stage is for, not what it might want: an @@ -509,8 +515,11 @@ def dispatch(self, target: Target, task: str, *, cwd: str | None = None, else: argv = (self.argv(target, task, cwd, writes, True) if publishes else self.argv(target, task, cwd, writes)) + # `env` is passed only when a caller replaced the environment, so a + # runner that never needed one keeps its narrower signature. + extra = {"env": env} if env is not None else {} try: - completed = runner(argv, timeout=timeout, cwd=cwd) + completed = runner(argv, timeout=timeout, cwd=cwd, **extra) except subprocess.TimeoutExpired: return DispatchResult( DispatchOutcome.FAILED, self.name, target, @@ -742,12 +751,104 @@ def _remote_ref_fingerprint(root: str) -> str: def _remove_read_only_path(function, path, exc_info) -> None: try: - os.chmod(path, 0o700) + # chmod follows a link; the linked Claude configuration is not ours. + if not os.path.islink(path): + os.chmod(path, 0o700) function(path) except OSError: raise exc_info[1] +#: Variables that carry a GitHub token, an SSH agent, or Git configuration +#: into a child process. A credential-free reviewer inherits none of them. +_CREDENTIAL_ENVIRONMENT = frozenset({ + "GH_TOKEN", "GITHUB_TOKEN", "GH_ENTERPRISE_TOKEN", "GITHUB_ENTERPRISE_TOKEN", + "SSH_AUTH_SOCK", "SSH_AGENT_PID", "SSH_ASKPASS", "GIT_ASKPASS", "GIT_SSH", + "GIT_CONFIG", "GIT_CONFIG_PARAMETERS", "GIT_CONFIG_COUNT", "GIT_CONFIG_SYSTEM", + "GIT_DIR", "GIT_WORK_TREE", "GIT_COMMON_DIR", "GIT_INDEX_FILE", +}) + +#: Any other variable named like a secret is dropped too, so a Bitbucket or +#: issue-provider token exported for another tool does not reach the reviewer. +#: Claude's own model-provider credentials are the exception: it has to run. +_SECRET_NAME = re.compile(r"TOKEN|PASSWORD|PASSWD|SECRET|CREDENTIAL|APP_KEY|API_KEY") +_REVIEWER_OWN_CREDENTIALS = ( + "ANTHROPIC_", "CLAUDE_", "AWS_", "GOOGLE_", "GCLOUD_", "CLOUD_ML_", + "VERTEX_", "AZURE_", "FOUNDRY_", +) + + +def _reviewer_keeps(name: str) -> bool: + upper = name.upper() + if upper in _CREDENTIAL_ENVIRONMENT or re.fullmatch(r"GIT_CONFIG_(KEY|VALUE)_\d+", upper): + return False + if _SECRET_NAME.search(upper): + return upper.startswith(_REVIEWER_OWN_CREDENTIALS) + return True + + +def _credential_free_environment(base: str) -> dict[str, str]: + """The environment of a reviewer that must not be able to write to a remote. + + `base` is an empty directory the caller owns and removes. It becomes the + reviewer's HOME, with an unauthenticated `gh` configuration, an empty + global Git configuration and no system one, so no credential helper, token + or SSH agent is reachable through the ordinary tools. Claude's own login is + linked in, because the reviewer still has to run. + + This removes the credentials the process is handed. It is not an operating + system sandbox: a credential kept in a readable file elsewhere on disk is + outside what an environment can take away. + """ + root = Path(base) + home = root / "home" + gh_config = root / "gh" + git_config = root / "gitconfig" + home.mkdir() + gh_config.mkdir() + git_config.write_text("", encoding="utf-8") + env = {key: value for key, value in os.environ.items() if _reviewer_keeps(key)} + if not env.get("CLAUDE_CONFIG_DIR"): + real_home = Path.home() + for name in (".claude", ".claude.json"): + if (real_home / name).exists(): + os.symlink(real_home / name, home / name, + target_is_directory=(real_home / name).is_dir()) + null = os.devnull + env.update({ + "HOME": str(home), + "USERPROFILE": str(home), + "XDG_CONFIG_HOME": str(home / ".config"), + "GH_CONFIG_DIR": str(gh_config), + "GH_PROMPT_DISABLED": "1", + "GIT_CONFIG_GLOBAL": str(git_config), + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_TERMINAL_PROMPT": "0", + "GCM_INTERACTIVE": "never", + "GIT_SSH_COMMAND": ( + f"ssh -F {null} -o BatchMode=yes -o IdentitiesOnly=yes " + f"-o IdentityAgent=none -o IdentityFile={null}" + ), + }) + return env + + +def _remove_workspace(path: str) -> str | None: + """Remove a disposable directory; return why it could not be, or None.""" + try: + shutil.rmtree(path, onerror=_remove_read_only_path) + except FileNotFoundError: + return None + except Exception as exc: + shutil.rmtree(path, ignore_errors=True) + if Path(path).exists(): + return f"{path} ({type(exc).__name__})" + return None + if Path(path).exists(): + return path + return None + + def _isolated_review_dispatch(adapter, target, task, *, cwd, dispatch_call): """Run a reviewer in an independent detached clone and verify its source checkout.""" if not isinstance(cwd, str) or not cwd: @@ -756,6 +857,7 @@ def _isolated_review_dispatch(adapter, target, task, *, cwd, dispatch_call): "a Claude read-only stage needs an implementer Git checkout to verify", ) worktree = None + credential_home = None root = None before_head = before_status = before_branch = before_remote_refs = None try: @@ -784,16 +886,17 @@ def _isolated_review_dispatch(adapter, target, task, *, cwd, dispatch_call): review_head = _git_output(worktree, "rev-parse", "HEAD") if review_head != before_head: raise ExecutorError("the disposable clone is not at the reviewed HEAD") + credential_home = tempfile.mkdtemp(prefix="code-cycle-review-env-") + reviewer_env = _credential_free_environment(credential_home) except Exception as exc: - cleanup_error = None - if worktree: - try: - shutil.rmtree(worktree, onerror=_remove_read_only_path) - except Exception as cleanup_exc: - cleanup_error = f"; cleanup failed ({type(cleanup_exc).__name__})" + leftovers = [ + left for left in ( + _remove_workspace(path) for path in (worktree, credential_home) if path + ) if left + ] detail = f"could not prepare an isolated review workspace: {exc}" - if cleanup_error: - detail += cleanup_error + if leftovers: + detail += f"; cleanup failed, left on disk: {', '.join(leftovers)}" return adapter._blocked( target, "review_workspace_isolation", detail, ) @@ -801,16 +904,17 @@ def _isolated_review_dispatch(adapter, target, task, *, cwd, dispatch_call): prompt = ( f"{task}\n\nREAD-ONLY HARNESS CONTRACT: Do not modify files, commit, or push. " "This stage runs in an independent disposable clone; any local edits will " - "be discarded. Any change to the implementer's branch or working tree " + "be discarded. It has no GitHub or Git credentials, so it cannot publish " + "or push. Any change to the implementer's branch or working tree " "fails this stage." ) result = None workspace_changed = False source_error = "the implementer branch, HEAD, working tree, or configured remote refs changed during review" - cleanup_warning = None + leftovers: list[str] = [] after_head = after_status_fingerprint = after_remote_refs = None try: - result = dispatch_call(prompt, worktree) + result = dispatch_call(prompt, worktree, reviewer_env) try: after_head = _git_output(root, "rev-parse", "HEAD") after_branch = _git_output(root, "rev-parse", "--symbolic-full-name", "HEAD") @@ -836,19 +940,15 @@ def _isolated_review_dispatch(adapter, target, task, *, cwd, dispatch_call): except Exception: workspace_changed = True finally: - try: - shutil.rmtree(worktree, onerror=_remove_read_only_path) - if Path(worktree).exists(): - cleanup_warning = "the disposable review workspace could not be removed" - except Exception as exc: - shutil.rmtree(worktree, ignore_errors=True) - cleanup_warning = f"could not remove the disposable review workspace: {exc}" + leftovers = [ + left for left in ( + _remove_workspace(path) for path in (worktree, credential_home) + ) if left + ] warnings = [] if workspace_changed: warnings.append("the reviewer changed its disposable workspace; those edits were discarded") - if cleanup_warning: - warnings.append(cleanup_warning) artifacts = dict(result.artifacts) artifacts["read_only_mode"] = "isolated_verified" artifacts["implementer_head_before"] = before_head @@ -864,14 +964,29 @@ def _isolated_review_dispatch(adapter, target, task, *, cwd, dispatch_call): artifacts["remote_refs_fingerprint_after"] = after_remote_refs if warnings: artifacts["warnings"] = warnings + cleanup_error = ( + "the disposable review workspace could not be removed; left on disk: " + + ", ".join(leftovers) + ) if leftovers else None if source_changed: artifacts.pop("read_only_mode", None) + detail = "read-only contract violation: " + source_error + if cleanup_error: + detail += "; " + cleanup_error return replace( result, outcome=DispatchOutcome.CONTRACT_VIOLATION, - missing_capability=None, - detail="read-only contract violation: " + source_error, - artifacts=artifacts, + missing_capability=None, detail=detail, artifacts=artifacts, ) + if cleanup_error: + # A workspace that outlives its stage is not disposable, whatever the + # reviewer did inside it, so the isolation is not claimed as verified. + # Only a success is downgraded: a failure the run already reported, + # such as model drift, stays the stated outcome. + artifacts.pop("read_only_mode", None) + outcome = (DispatchOutcome.FAILED + if result.outcome is DispatchOutcome.SUCCEEDED else result.outcome) + detail = cleanup_error if not result.detail else f"{result.detail}; {cleanup_error}" + return replace(result, outcome=outcome, detail=detail, artifacts=artifacts) detail = result.detail if warnings: detail = detail + ("; " if detail else "") + "warning: " + "; ".join(warnings) @@ -892,17 +1007,33 @@ def publication_access(self, probe: ProbeResult, *, writes: bool) -> tuple[bool, return True, "Claude uses gh for comments and git for writing stages; publication policy stays in its prompt" def supports_non_writing(self, **dispatch_kwargs) -> bool: + # The isolated harness runs Claude without GitHub or Git credentials, + # so a read-only stage that publishes cannot run here until the + # harness publishes on the stage's behalf. + if dispatch_kwargs.get("publishes"): + return False cwd = dispatch_kwargs.get("cwd") return isinstance(cwd, str) and bool(cwd) and Path(cwd).is_dir() + def read_only_refusal(self, **dispatch_kwargs) -> tuple[str, str] | None: + if dispatch_kwargs.get("publishes"): + return ("harness_publication", ( + "claude runs read-only stages without GitHub or Git credentials, " + "so it cannot publish this stage's comment; harness-side " + "publication is not implemented yet. Route this stage to an " + "executor that enforces read-only access, or run it local-only" + )) + return None + def dispatch(self, target: Target, task: str, *, cwd: str | None = None, timeout: int = 3600, runner=_run, writes: bool = False, publishes: bool = False, - publication_permissions: tuple[str, ...] = ()) -> DispatchResult: + publication_permissions: tuple[str, ...] = (), + env: dict[str, str] | None = None) -> DispatchResult: return super().dispatch( target, task, cwd=cwd, timeout=timeout, runner=runner, writes=writes, publishes=publishes, - publication_permissions=publication_permissions, + publication_permissions=publication_permissions, env=env, ) def argv(self, target: Target, task: str, cwd: str | None = None, @@ -935,8 +1066,9 @@ def argv(self, target: Target, task: str, cwd: str | None = None, # Defence in depth. Read-only safety comes from the disposable # worktree and the source-checkout verification in dispatch(). argv += ["--disallowedTools", "Edit", "Write", "NotebookEdit"] - # Publication remains behavioural. A read-only publisher may use gh to - # post its comment, but does not need git access to the reviewed branch. + # Publication remains behavioural. `dispatch()` refuses a read-only + # publisher, which would run without credentials; the read-only shape + # below is what a direct caller of argv() gets. if publishes: argv += (["--allowedTools", "Bash(gh:*)", "Bash(git:*)"] if writes else ["--allowedTools", "Bash(gh:*)"]) @@ -1343,6 +1475,10 @@ def dispatch( ) ), }.get(workspace_policy, "the adapter cannot satisfy the workspace policy") + refusal = (adapter.read_only_refusal(**kw) + if workspace_policy is WorkspacePolicy.READ_ONLY else None) + if refusal is not None: + capability, detail = refusal return DispatchResult( DispatchOutcome.BLOCKED, target.executor, target, missing_capability=capability, @@ -1359,8 +1495,9 @@ def dispatch( and target.executor == "claude" and not adapter.enforces_read_only): result = _isolated_review_dispatch( adapter, target, task, cwd=kw.get("cwd"), - dispatch_call=lambda prompt, isolated_cwd: adapter.dispatch( - target, prompt, **{**kw, "cwd": isolated_cwd, "writes": False}, + dispatch_call=lambda prompt, isolated_cwd, env: adapter.dispatch( + target, prompt, + **{**kw, "cwd": isolated_cwd, "writes": False, "env": env}, ), ) else: diff --git a/scripts/telemetry.py b/scripts/telemetry.py index 22581a14..aab57c48 100644 --- a/scripts/telemetry.py +++ b/scripts/telemetry.py @@ -134,7 +134,7 @@ def is_jev_model(value) -> bool: "bypass_acknowledgement", "trusted_directory", "orchestration_context", "provider_agent_mapping", "read_only_enforcement", "disposable_workspace", "review_workspace_isolation", "review_workspace_mismatch", - "review_workspace_conflict", "publication_access", + "review_workspace_conflict", "publication_access", "harness_publication", })), "verifiability": ("token", frozenset({"auto", "partial", "human"})), "routing_strategy": ("token", frozenset({"fixed", "measured"})), diff --git a/tests/test_executors.py b/tests/test_executors.py index 64c616f1..389473ae 100644 --- a/tests/test_executors.py +++ b/tests/test_executors.py @@ -1069,7 +1069,7 @@ def test_claude_review_uses_an_independent_disposable_clone(self) -> None: seen = {} target = router.parse_target("claude:anthropic/claude-sonnet-5 high") - def runner(argv, timeout=None, cwd=None): + def runner(argv, timeout=None, cwd=None, env=None): seen["argv"], seen["cwd"] = argv, cwd self.assertNotEqual(str(repo), cwd) self.assertFalse(ex._paths_overlap(cwd, str(repo))) @@ -1115,7 +1115,7 @@ def test_claude_review_fails_if_the_implementer_branch_moves(self) -> None: target = router.parse_target("claude:anthropic/claude-sonnet-5 high") before = self._git(repo, "rev-parse", "HEAD") - def runner(argv, timeout=None, cwd=None): + def runner(argv, timeout=None, cwd=None, env=None): (repo / "branch-change.txt").write_text("changed", encoding="utf-8") self._git(repo, "add", "branch-change.txt") self._git(repo, "commit", "-qm", "unexpected branch change") @@ -1157,7 +1157,7 @@ def test_claude_review_detects_a_remote_branch_push(self) -> None: self._git(repo, "push", "origin", "HEAD") target = router.parse_target("claude:anthropic/claude-sonnet-5 high") - def runner(argv, timeout=None, cwd=None): + def runner(argv, timeout=None, cwd=None, env=None): (Path(cwd) / "reviewer.txt").write_text("review result\\n", encoding="utf-8") self._git(cwd, "add", "reviewer.txt") self._git(cwd, "config", "user.name", "Reviewer Test") @@ -1197,6 +1197,133 @@ def test_failed_isolation_does_not_claim_verified_mode(self) -> None: self.assertEqual(ex.DispatchOutcome.BLOCKED, result.outcome) self.assertNotIn("read_only_mode", result.artifacts) + def test_claude_review_runs_without_github_or_git_credentials(self) -> None: + repo = self._git_repo() + temporary = tempfile.TemporaryDirectory() + self.addCleanup(temporary.cleanup) + real_home = Path(temporary.name) / "real-home" + (real_home / ".claude").mkdir(parents=True) + (real_home / ".claude" / "credentials").write_text("claude login", encoding="utf-8") + (real_home / ".claude.json").write_text("{}", encoding="utf-8") + target = router.parse_target("claude:anthropic/claude-sonnet-5 high") + seen = {} + + def runner(argv, timeout=None, cwd=None, env=None): + seen["env"] = env + home = Path(env["HOME"]) + self.assertFalse(ex._paths_overlap(str(home), str(real_home))) + self.assertEqual( + "claude login", + (home / ".claude" / "credentials").read_text(encoding="utf-8"), + ) + self.assertEqual([], list(Path(env["GH_CONFIG_DIR"]).iterdir())) + self.assertEqual("", Path(env["GIT_CONFIG_GLOBAL"]).read_text(encoding="utf-8")) + configured = subprocess.run( + ["git", "-C", cwd, "config", "--global", "--list"], + capture_output=True, text=True, env=env, + ) + self.assertEqual("", configured.stdout) + self.assertIn("no GitHub or Git credentials", argv[argv.index("-p") + 1]) + return completed("{}") + + environment = { + "GH_TOKEN": "gh-secret", "GITHUB_TOKEN": "github-secret", + "SSH_AUTH_SOCK": "/agent.sock", "GIT_ASKPASS": "/askpass", + "GIT_CONFIG_COUNT": "1", "GIT_CONFIG_KEY_0": "credential.helper", + "GIT_CONFIG_VALUE_0": "store", "BITBUCKET_APP_PASSWORD": "bb-secret", + "PLANE_API_KEY": "plane-secret", "ANTHROPIC_API_KEY": "model-key", + } + with patch.dict(ex.os.environ, environment), \ + patch.object(ex.Path, "home", return_value=real_home): + ex.os.environ.pop("CLAUDE_CONFIG_DIR", None) + result = ex.dispatch( + router.RoutingDecision("reviewer", target, router.RoutingMode.PRODUCTION), + "review the change", ex.Registry([ex.ClaudeAdapter()]), cwd=str(repo), + runner=runner, + probes={"claude": ex.ProbeResult("claude", ex.Availability.READY, "test")}, + ) + + self.assertEqual(ex.DispatchOutcome.SUCCEEDED, result.outcome) + self.assertEqual("isolated_verified", result.artifacts["read_only_mode"]) + env = seen["env"] + for name in ("GH_TOKEN", "GITHUB_TOKEN", "SSH_AUTH_SOCK", "GIT_ASKPASS", + "GIT_CONFIG_COUNT", "GIT_CONFIG_KEY_0", "GIT_CONFIG_VALUE_0", + "BITBUCKET_APP_PASSWORD", "PLANE_API_KEY"): + self.assertNotIn(name, env) + self.assertEqual("model-key", env["ANTHROPIC_API_KEY"]) + self.assertEqual("1", env["GIT_CONFIG_NOSYSTEM"]) + self.assertEqual("0", env["GIT_TERMINAL_PROMPT"]) + self.assertIn("IdentityAgent=none", env["GIT_SSH_COMMAND"]) + # The temporary home and its links are gone; what they linked to is not. + self.assertFalse(Path(env["HOME"]).exists()) + self.assertEqual( + "claude login", + (real_home / ".claude" / "credentials").read_text(encoding="utf-8"), + ) + + def test_claude_is_not_offered_for_a_publishing_read_only_stage(self) -> None: + repo = self._git_repo() + registry = ex.Registry([ex.ClaudeAdapter()]) + + self.assertEqual(frozenset(), registry.compatible_executors( + ex.WorkspacePolicy.READ_ONLY, cwd=str(repo), publishes=True, + publication_permissions=("comment",), + )) + self.assertEqual(frozenset({"claude"}), registry.compatible_executors( + ex.WorkspacePolicy.READ_ONLY, cwd=str(repo), publishes=False, + )) + + def test_a_publishing_claude_review_is_blocked_before_it_runs(self) -> None: + repo = self._git_repo() + target = router.parse_target("claude:anthropic/claude-sonnet-5 high") + + with patch.object(ex, "_publication_preflight", return_value=(True, "passed")): + result = ex.dispatch( + router.RoutingDecision("reviewer", target, router.RoutingMode.PRODUCTION), + "review the change", ex.Registry([ex.ClaudeAdapter()]), cwd=str(repo), + publishes=True, publication_permissions=("comment",), + runner=lambda *args, **kwargs: self.fail("a publishing review must not run"), + probes={"claude": ex.ProbeResult("claude", ex.Availability.READY, "test")}, + ) + + self.assertEqual(ex.DispatchOutcome.BLOCKED, result.outcome) + self.assertEqual("harness_publication", result.missing_capability) + self.assertIn("without GitHub or Git credentials", result.detail) + self.assertNotIn("read_only_mode", result.artifacts) + + def test_a_review_clone_that_cannot_be_removed_fails_without_verified_mode(self) -> None: + repo = self._git_repo() + target = router.parse_target("claude:anthropic/claude-sonnet-5 high") + seen = {} + real_rmtree = ex.shutil.rmtree + + def runner(argv, timeout=None, cwd=None, env=None): + seen["cwd"] = cwd + (Path(cwd) / "reviewer-created.txt").write_text("left", encoding="utf-8") + return completed("{}") + + def locked_rmtree(path, *args, **kwargs): + if str(path) == seen.get("cwd"): + if kwargs.get("ignore_errors"): + return None + raise PermissionError("locked") + return real_rmtree(path, *args, **kwargs) + + with patch.object(ex.shutil, "rmtree", side_effect=locked_rmtree): + result = ex.dispatch( + router.RoutingDecision("reviewer", target, router.RoutingMode.PRODUCTION), + "review the change", ex.Registry([ex.ClaudeAdapter()]), cwd=str(repo), + runner=runner, + probes={"claude": ex.ProbeResult("claude", ex.Availability.READY, "test")}, + ) + self.addCleanup(real_rmtree, seen["cwd"], ignore_errors=True) + + self.assertEqual(ex.DispatchOutcome.FAILED, result.outcome) + self.assertNotIn("read_only_mode", result.artifacts) + self.assertIn("could not be removed", result.detail) + self.assertIn(seen["cwd"], result.detail) + self.assertTrue(Path(seen["cwd"]).exists()) + class PublicationPreflightTests(unittest.TestCase): def test_github_write_permission_uses_repository_permission_write_value(self) -> None: diff --git a/tests/test_telemetry.py b/tests/test_telemetry.py index b2e5c4e7..0191f918 100644 --- a/tests/test_telemetry.py +++ b/tests/test_telemetry.py @@ -512,6 +512,13 @@ def test_blocked_capabilities_are_counted_by_name(self) -> None: self.assertEqual({"operating_quota": 2, "folder_trust": 1}, self.store.dispatch_failures("repo")) + def test_a_refused_credential_free_publisher_is_recordable(self) -> None: + decision, result = self.decision_and_result(blocked_capability="harness_publication") + + self.store.record_dispatch("repo", "t1", "review", decision, result) + + self.assertEqual({"harness_publication": 1}, self.store.dispatch_failures("repo")) + class ModelDriftTests(TelemetryTestCase): def test_a_different_model_is_reported(self) -> None: From 6c35d8b0fa27d595916a716c8d9e39aa18fd203c Mon Sep 17 00:00:00 2001 From: datacas <4690232+datacas@users.noreply.github.com> Date: Thu, 24 Sep 2026 16:41:36 +0200 Subject: [PATCH 6/7] Record Claude read-only as detected and fail on leftover review clones The maintainer accepts the remote-write risk for Claude reviewers, so Claude keeps its full tooling and normal gh/git access. This reverts the credential stripping and the harness_publication refusal from 8ee2afe and drops the read-only --disallowedTools restriction. The stage is told, and shown why, not to write, runs in a disposable clone, and the before/after checks still turn a detected change into a contract_violation. Such stages now record read_only_mode=detected instead of isolated_verified. The docs explain that the Codex sandbox enforces read-only, while with Claude a remote write can be detected but not prevented or undone (REV-001). A review clone that cannot be removed fails the stage without a read_only_mode; a failure the run already reported keeps its outcome (REV-004). --- README.md | 8 +- docs/instrumentation.md | 4 +- docs/role-workspace-policy.md | 4 +- docs/routing.md | 6 +- scripts/executors.py | 188 +++++++--------------------------- scripts/router.py | 10 +- scripts/telemetry.py | 4 +- tests/test_executors.py | 131 +++-------------------- tests/test_telemetry.py | 11 +- 9 files changed, 70 insertions(+), 296 deletions(-) diff --git a/README.md b/README.md index 676b2635..296f956b 100644 --- a/README.md +++ b/README.md @@ -131,10 +131,10 @@ Use cc-orchestrator for issue 123. Stop at READY_FOR_MANUAL_MERGE. | [`cc-orca-orchestrator`](docs/workflows.md#cc-orca-orchestrator) | one prompt | supervised workers, paired-review calibration | Orca | | [`run_cycle.py`](docs/workflows.md#runtime-driver-run_cyclepy) | a shell command | recorded, routed cycles across executors | runtime, Codex and/or Claude CLIs | -Read-only roles can use Codex's enforced sandbox or Claude's isolated, -verified, credential-free review checkout; Claude does not yet serve the -read-only stages that publish a comment. See [workspace policy](docs/role-workspace-policy.md) -for the branch protection contract. +Read-only roles can use Codex, whose sandbox enforces read-only, or Claude, +which reviews in a disposable clone where writes are detected but not +prevented. See [workspace policy](docs/role-workspace-policy.md) for what +that does and does not guarantee. ## Skills diff --git a/docs/instrumentation.md b/docs/instrumentation.md index 024db0c5..dcef7d95 100644 --- a/docs/instrumentation.md +++ b/docs/instrumentation.md @@ -735,9 +735,9 @@ nothing had ever asked for anything else. A dispatched Claude, by contrast, edited a file with no flag at all. So the flag on a writing Claude stage declares what is already happening rather than granting something new. -For a **reading** Claude stage, the harness creates an independent detached clone with its own Git object store at the exact reviewed HEAD, outside the implementer's tree, and removes the clone's remotes. A dirty implementer checkout blocks preparation. It records the implementer's HEAD, a fingerprint of `git status --porcelain`, and advertised refs for configured remotes before dispatch, then checks them again afterwards. A detected change makes the stage a `contract_violation`. Writes within Claude's disposable clone produce a warning and are discarded with that clone. The stage prompt prohibits file edits, commits, and pushes; `--disallowedTools Edit Write NotebookEdit` adds defence in depth without serving as the guarantee. Read-only Claude dispatches record `read_only_mode = isolated_verified` only after isolation and verification succeed. The reviewer runs without GitHub or Git credentials: a temporary `HOME` with only Claude's own login linked in, an empty `GH_CONFIG_DIR`, no `GH_TOKEN`/`GITHUB_TOKEN`, a neutral `GIT_CONFIG_GLOBAL` with `GIT_CONFIG_NOSYSTEM=1`, no SSH agent, and interactive prompts disabled, so it cannot push or call GitHub as the user. This removes the credentials the process is handed; it is not an OS sandbox, and a credential stored in a readable file elsewhere on disk stays outside its reach. Because the reviewer cannot publish, Claude is not eligible for read-only stages that publish (`review`, `rereview`); a direct dispatch of one returns `BLOCKED` with `harness_publication` until harness-side publication lands ([#79](https://github.com/datacas/code-cycle-toolkit/issues/79)). If the clone or the temporary home cannot be removed afterwards, the stage fails and records no `read_only_mode`. +For a **reading** Claude stage, the harness creates an independent detached clone with its own Git object store at the exact reviewed HEAD, outside the implementer's tree, and removes the clone's remotes. A dirty implementer checkout blocks preparation. It records the implementer's HEAD, a fingerprint of `git status --porcelain`, and advertised refs for configured remotes before dispatch, then checks them again afterwards. A detected change makes the stage a `contract_violation`. Writes within Claude's disposable clone produce a warning and are discarded with that clone. The stage prompt prohibits file edits, commits, and pushes and explains why. Claude runs with its full tooling and its ordinary `gh` and `git` access, so it can publish its own comment. With Claude, read-only is watched, not enforced. The harness detects a write it can observe, but it cannot prevent or undo a remote write: a push, a merge, or a change to the change request. A push that is later restored before the stage ends also goes unseen. The maintainer has accepted this risk. Anyone who needs a full guarantee should review with Codex or give the reviewer read-only credentials. Read-only Claude dispatches record `read_only_mode = detected`, and only when the clone was prepared and removed and no change was detected. A clone left on disk fails the stage without a `read_only_mode`. -Codex retains `-s read-only` and records `read_only_mode = enforced`, meaning its sandbox prevents workspace writes. Orca still requires its explicit review-workspace contract. Reviews may use any configured eligible executor; a profile may still choose no fallback. Publication access remains behavioural for the executors that hold credentials. +Codex retains `-s read-only` and records `read_only_mode = enforced`, meaning its sandbox prevents workspace writes. Orca still requires its explicit review-workspace contract. Reviews may use any configured eligible executor; a profile may still choose no fallback. Publication access remains behavioural: the prompt states which operations the role may perform. ## Running a cycle diff --git a/docs/role-workspace-policy.md b/docs/role-workspace-policy.md index e08c0740..3a35da20 100644 --- a/docs/role-workspace-policy.md +++ b/docs/role-workspace-policy.md @@ -18,9 +18,9 @@ repository. The default auxiliary profile uses Codex because its sandbox can confine writes to the disposable cwd; an adapter without that boundary is not eligible for `disposable`, even when its process cwd is isolated. -An adapter is eligible only when the harness can establish the requested policy. Codex enforces read-only execution directly with its sandbox and records `read_only_mode = enforced`. +An adapter is eligible only when the harness can establish the requested policy. Codex enforces read-only execution directly with its sandbox and records `read_only_mode = enforced`: the sandbox imposes read-only. -Claude cannot enforce read-only inside its process, so the harness runs it in an independent detached clone with its own Git object store at the exact reviewed HEAD, outside the implementer's tree, with the clone's remotes removed. A dirty implementer checkout blocks preparation. Before and after the stage, the harness compares the implementer's HEAD, `git status --porcelain`, and every configured remote's advertised refs; a detected change is a `contract_violation`. Edits inside the disposable clone produce a warning and are discarded. Claude records `read_only_mode = isolated_verified` only after those checks pass. The prompt prohibits edits, commits, and pushes, while CLI tool restrictions provide defence in depth. The reviewer runs without GitHub or Git credentials: a temporary `HOME` with only Claude's own login linked in, an empty `GH_CONFIG_DIR`, no `GH_TOKEN`/`GITHUB_TOKEN`, a neutral `GIT_CONFIG_GLOBAL` with `GIT_CONFIG_NOSYSTEM=1`, no SSH agent, and interactive prompts disabled, so it cannot push or call GitHub as the user. This removes the credentials the process is handed; it is not an OS sandbox, and a credential stored in a readable file elsewhere on disk stays outside its reach. Because the reviewer cannot publish, Claude is not eligible for read-only stages that publish (`review`, `rereview`); a direct dispatch of one returns `BLOCKED` with `harness_publication` until harness-side publication lands ([#79](https://github.com/datacas/code-cycle-toolkit/issues/79)). If the clone or the temporary home cannot be removed afterwards, the stage fails and records no `read_only_mode`. +Claude cannot enforce read-only inside its process, so the harness runs it in an independent detached clone with its own Git object store at the exact reviewed HEAD, outside the implementer's tree, with the clone's remotes removed. A dirty implementer checkout blocks preparation. Before and after the stage, the harness compares the implementer's HEAD, `git status --porcelain`, and every configured remote's advertised refs; a detected change is a `contract_violation`. Edits inside the disposable clone produce a warning and are discarded. If the clone cannot be removed afterwards, the stage fails. Claude records `read_only_mode = detected` only when those checks pass. The prompt prohibits edits, commits, and pushes and explains why. Claude runs with its full tooling and its ordinary `gh` and `git` access, so it can publish its own comment. With Claude, read-only is watched, not enforced. The harness detects a write it can observe, but it cannot prevent or undo a remote write: a push, a merge, or a change to the change request. A push that is later restored before the stage ends also goes unseen. The maintainer has accepted this risk. Anyone who needs a full guarantee should review with Codex or give the reviewer read-only credentials. Claude remains ineligible for `disposable` roles because it cannot confine writes to their workspace. Orca follows its explicit review-workspace contract and requires its own orchestration context where applicable. diff --git a/docs/routing.md b/docs/routing.md index 1268f98f..2c46f03f 100644 --- a/docs/routing.md +++ b/docs/routing.md @@ -35,7 +35,7 @@ A profile names a *kind* of work. It never appears in a skill as a model name. | `auxiliary_tool` | verify, run, bootstrap | `codex:openai/gpt-6-luna medium` | — | | `cheap_tool` | compatibility for direct/custom callers; no built-in role selects it | `claude:anthropic/claude-haiku-4-5-20251001 low` | — | -¹ The security profile retains this configured fallback; Claude runs read-only stages only through the isolated, verified, credential-free workspace contract described below. +¹ The security profile retains this configured fallback. Claude runs read-only stages in a disposable clone that the harness watches for changes, as described below. The source of truth is `DEFAULT_PROFILES` in [`scripts/router.py`](../scripts/router.py). Override only what you want to change, and the rest keep their defaults: @@ -94,10 +94,10 @@ Each role has a fixed write permission. Only an executor that can **enforce** it | Role | Policy | Eligible executors | |---|---|---| | `implement`, `resolve` | `workspace_write` | Codex (`-s workspace-write`), Claude (`acceptEdits`), Orca | -| `review`, `rereview`, `security`, `bootstrap`, `coordinate` | `read_only` | Codex (`-s read-only`); Claude (independent isolated clone, verified, no credentials) only for `security`, `bootstrap` and `coordinate`, or any of them when run local-only; Orca (explicit review workspace) | +| `review`, `rereview`, `security`, `bootstrap`, `coordinate` | `read_only` | Codex (`-s read-only`), Claude (disposable clone, writes detected, not prevented), Orca (explicit review workspace) | | `verify`, `run` | `disposable` | Codex, confined to a disposable workspace | -Codex records `read_only_mode = enforced`: its sandbox prevents workspace writes. Claude records `read_only_mode = isolated_verified`: the harness creates an independent detached clone with its own Git object store at the reviewed HEAD, removes its remotes, and discards local edits. The harness requires a clean implementer checkout and checks its HEAD, working-tree fingerprint, and configured remote refs before and after review; a detected change fails the stage as a contract violation. Claude runs there without GitHub or Git credentials, so it cannot push, and for the same reason cannot publish: `review` and `rereview` stay on Codex until harness-side publication lands ([#79](https://github.com/datacas/code-cycle-toolkit/issues/79)). Publication access for Codex remains role-specific, and a reviewer may publish only the comment its role permits. Details are in [Role workspace policy](role-workspace-policy.md). +Codex records `read_only_mode = enforced`: its sandbox prevents workspace writes. Claude records `read_only_mode = detected`: the harness creates an independent detached clone with its own Git object store at the reviewed HEAD, removes its remotes, and discards local edits. The harness requires a clean implementer checkout and checks its HEAD, working-tree fingerprint, and configured remote refs before and after review; a detected change fails the stage as a contract violation. Claude runs with its full tooling and its ordinary `gh` and `git` access, so it can publish its own comment. With Claude, read-only is watched, not enforced. The harness detects a write it can observe, but it cannot prevent or undo a remote write: a push, a merge, or a change to the change request. A push that is later restored before the stage ends also goes unseen. The maintainer has accepted this risk. Anyone who needs a full guarantee should review with Codex or give the reviewer read-only credentials. Publication access remains role-specific, and a reviewer may publish only the comment its role permits. Details are in [Role workspace policy](role-workspace-policy.md). ## Publication boundary diff --git a/scripts/executors.py b/scripts/executors.py index ca6d6e4e..bce72f27 100644 --- a/scripts/executors.py +++ b/scripts/executors.py @@ -270,10 +270,9 @@ def explain(self) -> str: return f"{self.executor}: {self.outcome.value} as {self.model_resolved or '?'}{suffix}" -def _run(argv: list[str], timeout: int = 30, cwd: str | None = None, - env: dict[str, str] | None = None) -> subprocess.CompletedProcess: +def _run(argv: list[str], timeout: int = 30, cwd: str | None = None) -> subprocess.CompletedProcess: return subprocess.run(argv, capture_output=True, text=True, timeout=timeout, cwd=cwd, - stdin=subprocess.DEVNULL, env=env) + stdin=subprocess.DEVNULL) def _publication_preflight(cwd: str | None) -> tuple[bool, str]: @@ -362,10 +361,6 @@ def supports_non_writing(self, **dispatch_kwargs) -> bool: """Whether this adapter can keep this non-writing dispatch isolated.""" return self.enforces_read_only - def read_only_refusal(self, **dispatch_kwargs) -> tuple[str, str] | None: - """A specific (capability, detail) for refusing this non-writing dispatch.""" - return None - def supports_workspace_policy(self, policy: WorkspacePolicy | str, **dispatch_kwargs) -> bool: """Whether this adapter can honour the complete workspace contract.""" @@ -493,8 +488,7 @@ def read_resolved_model(self, stdout: str) -> str | None: def dispatch(self, target: Target, task: str, *, cwd: str | None = None, timeout: int = 3600, runner=_run, writes: bool = False, publishes: bool = False, - publication_permissions: tuple[str, ...] = (), - env: dict[str, str] | None = None) -> DispatchResult: + publication_permissions: tuple[str, ...] = ()) -> DispatchResult: """Run the agent non-interactively and classify what came back. `writes` is what the stage is for, not what it might want: an @@ -515,11 +509,8 @@ def dispatch(self, target: Target, task: str, *, cwd: str | None = None, else: argv = (self.argv(target, task, cwd, writes, True) if publishes else self.argv(target, task, cwd, writes)) - # `env` is passed only when a caller replaced the environment, so a - # runner that never needed one keeps its narrower signature. - extra = {"env": env} if env is not None else {} try: - completed = runner(argv, timeout=timeout, cwd=cwd, **extra) + completed = runner(argv, timeout=timeout, cwd=cwd) except subprocess.TimeoutExpired: return DispatchResult( DispatchOutcome.FAILED, self.name, target, @@ -751,90 +742,14 @@ def _remote_ref_fingerprint(root: str) -> str: def _remove_read_only_path(function, path, exc_info) -> None: try: - # chmod follows a link; the linked Claude configuration is not ours. - if not os.path.islink(path): - os.chmod(path, 0o700) + os.chmod(path, 0o700) function(path) except OSError: raise exc_info[1] -#: Variables that carry a GitHub token, an SSH agent, or Git configuration -#: into a child process. A credential-free reviewer inherits none of them. -_CREDENTIAL_ENVIRONMENT = frozenset({ - "GH_TOKEN", "GITHUB_TOKEN", "GH_ENTERPRISE_TOKEN", "GITHUB_ENTERPRISE_TOKEN", - "SSH_AUTH_SOCK", "SSH_AGENT_PID", "SSH_ASKPASS", "GIT_ASKPASS", "GIT_SSH", - "GIT_CONFIG", "GIT_CONFIG_PARAMETERS", "GIT_CONFIG_COUNT", "GIT_CONFIG_SYSTEM", - "GIT_DIR", "GIT_WORK_TREE", "GIT_COMMON_DIR", "GIT_INDEX_FILE", -}) - -#: Any other variable named like a secret is dropped too, so a Bitbucket or -#: issue-provider token exported for another tool does not reach the reviewer. -#: Claude's own model-provider credentials are the exception: it has to run. -_SECRET_NAME = re.compile(r"TOKEN|PASSWORD|PASSWD|SECRET|CREDENTIAL|APP_KEY|API_KEY") -_REVIEWER_OWN_CREDENTIALS = ( - "ANTHROPIC_", "CLAUDE_", "AWS_", "GOOGLE_", "GCLOUD_", "CLOUD_ML_", - "VERTEX_", "AZURE_", "FOUNDRY_", -) - - -def _reviewer_keeps(name: str) -> bool: - upper = name.upper() - if upper in _CREDENTIAL_ENVIRONMENT or re.fullmatch(r"GIT_CONFIG_(KEY|VALUE)_\d+", upper): - return False - if _SECRET_NAME.search(upper): - return upper.startswith(_REVIEWER_OWN_CREDENTIALS) - return True - - -def _credential_free_environment(base: str) -> dict[str, str]: - """The environment of a reviewer that must not be able to write to a remote. - - `base` is an empty directory the caller owns and removes. It becomes the - reviewer's HOME, with an unauthenticated `gh` configuration, an empty - global Git configuration and no system one, so no credential helper, token - or SSH agent is reachable through the ordinary tools. Claude's own login is - linked in, because the reviewer still has to run. - - This removes the credentials the process is handed. It is not an operating - system sandbox: a credential kept in a readable file elsewhere on disk is - outside what an environment can take away. - """ - root = Path(base) - home = root / "home" - gh_config = root / "gh" - git_config = root / "gitconfig" - home.mkdir() - gh_config.mkdir() - git_config.write_text("", encoding="utf-8") - env = {key: value for key, value in os.environ.items() if _reviewer_keeps(key)} - if not env.get("CLAUDE_CONFIG_DIR"): - real_home = Path.home() - for name in (".claude", ".claude.json"): - if (real_home / name).exists(): - os.symlink(real_home / name, home / name, - target_is_directory=(real_home / name).is_dir()) - null = os.devnull - env.update({ - "HOME": str(home), - "USERPROFILE": str(home), - "XDG_CONFIG_HOME": str(home / ".config"), - "GH_CONFIG_DIR": str(gh_config), - "GH_PROMPT_DISABLED": "1", - "GIT_CONFIG_GLOBAL": str(git_config), - "GIT_CONFIG_NOSYSTEM": "1", - "GIT_TERMINAL_PROMPT": "0", - "GCM_INTERACTIVE": "never", - "GIT_SSH_COMMAND": ( - f"ssh -F {null} -o BatchMode=yes -o IdentitiesOnly=yes " - f"-o IdentityAgent=none -o IdentityFile={null}" - ), - }) - return env - - def _remove_workspace(path: str) -> str | None: - """Remove a disposable directory; return why it could not be, or None.""" + """Remove a disposable directory; return what is left on disk, or None.""" try: shutil.rmtree(path, onerror=_remove_read_only_path) except FileNotFoundError: @@ -857,7 +772,6 @@ def _isolated_review_dispatch(adapter, target, task, *, cwd, dispatch_call): "a Claude read-only stage needs an implementer Git checkout to verify", ) worktree = None - credential_home = None root = None before_head = before_status = before_branch = before_remote_refs = None try: @@ -886,17 +800,11 @@ def _isolated_review_dispatch(adapter, target, task, *, cwd, dispatch_call): review_head = _git_output(worktree, "rev-parse", "HEAD") if review_head != before_head: raise ExecutorError("the disposable clone is not at the reviewed HEAD") - credential_home = tempfile.mkdtemp(prefix="code-cycle-review-env-") - reviewer_env = _credential_free_environment(credential_home) except Exception as exc: - leftovers = [ - left for left in ( - _remove_workspace(path) for path in (worktree, credential_home) if path - ) if left - ] + left = _remove_workspace(worktree) if worktree else None detail = f"could not prepare an isolated review workspace: {exc}" - if leftovers: - detail += f"; cleanup failed, left on disk: {', '.join(leftovers)}" + if left: + detail += f"; cleanup failed, left on disk: {left}" return adapter._blocked( target, "review_workspace_isolation", detail, ) @@ -904,17 +812,19 @@ def _isolated_review_dispatch(adapter, target, task, *, cwd, dispatch_call): prompt = ( f"{task}\n\nREAD-ONLY HARNESS CONTRACT: Do not modify files, commit, or push. " "This stage runs in an independent disposable clone; any local edits will " - "be discarded. It has no GitHub or Git credentials, so it cannot publish " - "or push. Any change to the implementer's branch or working tree " - "fails this stage." + "be discarded. You keep your normal gh and git access; use it only to " + "read and to publish the comment this stage allows. A push, merge, or edit to the " + "change request cannot be undone by the harness and invalidates the " + "review it is judging. Any change to the implementer's branch or " + "working tree fails this stage." ) result = None workspace_changed = False source_error = "the implementer branch, HEAD, working tree, or configured remote refs changed during review" - leftovers: list[str] = [] + left = None after_head = after_status_fingerprint = after_remote_refs = None try: - result = dispatch_call(prompt, worktree, reviewer_env) + result = dispatch_call(prompt, worktree) try: after_head = _git_output(root, "rev-parse", "HEAD") after_branch = _git_output(root, "rev-parse", "--symbolic-full-name", "HEAD") @@ -940,17 +850,13 @@ def _isolated_review_dispatch(adapter, target, task, *, cwd, dispatch_call): except Exception: workspace_changed = True finally: - leftovers = [ - left for left in ( - _remove_workspace(path) for path in (worktree, credential_home) - ) if left - ] + left = _remove_workspace(worktree) warnings = [] if workspace_changed: warnings.append("the reviewer changed its disposable workspace; those edits were discarded") artifacts = dict(result.artifacts) - artifacts["read_only_mode"] = "isolated_verified" + artifacts["read_only_mode"] = "detected" artifacts["implementer_head_before"] = before_head artifacts["implementer_status_fingerprint_before"] = hashlib.sha256( before_status.encode("utf-8"), @@ -965,9 +871,9 @@ def _isolated_review_dispatch(adapter, target, task, *, cwd, dispatch_call): if warnings: artifacts["warnings"] = warnings cleanup_error = ( - "the disposable review workspace could not be removed; left on disk: " - + ", ".join(leftovers) - ) if leftovers else None + f"the disposable review workspace could not be removed; left on disk: {left}" + if left else None + ) if source_changed: artifacts.pop("read_only_mode", None) detail = "read-only contract violation: " + source_error @@ -978,10 +884,9 @@ def _isolated_review_dispatch(adapter, target, task, *, cwd, dispatch_call): missing_capability=None, detail=detail, artifacts=artifacts, ) if cleanup_error: - # A workspace that outlives its stage is not disposable, whatever the - # reviewer did inside it, so the isolation is not claimed as verified. - # Only a success is downgraded: a failure the run already reported, - # such as model drift, stays the stated outcome. + # A workspace that outlives its stage is not disposable, so the stage + # does not report its read-only mode. Only a success is downgraded: a + # failure the run already reported, such as model drift, stays. artifacts.pop("read_only_mode", None) outcome = (DispatchOutcome.FAILED if result.outcome is DispatchOutcome.SUCCEEDED else result.outcome) @@ -1007,33 +912,17 @@ def publication_access(self, probe: ProbeResult, *, writes: bool) -> tuple[bool, return True, "Claude uses gh for comments and git for writing stages; publication policy stays in its prompt" def supports_non_writing(self, **dispatch_kwargs) -> bool: - # The isolated harness runs Claude without GitHub or Git credentials, - # so a read-only stage that publishes cannot run here until the - # harness publishes on the stage's behalf. - if dispatch_kwargs.get("publishes"): - return False cwd = dispatch_kwargs.get("cwd") return isinstance(cwd, str) and bool(cwd) and Path(cwd).is_dir() - def read_only_refusal(self, **dispatch_kwargs) -> tuple[str, str] | None: - if dispatch_kwargs.get("publishes"): - return ("harness_publication", ( - "claude runs read-only stages without GitHub or Git credentials, " - "so it cannot publish this stage's comment; harness-side " - "publication is not implemented yet. Route this stage to an " - "executor that enforces read-only access, or run it local-only" - )) - return None - def dispatch(self, target: Target, task: str, *, cwd: str | None = None, timeout: int = 3600, runner=_run, writes: bool = False, publishes: bool = False, - publication_permissions: tuple[str, ...] = (), - env: dict[str, str] | None = None) -> DispatchResult: + publication_permissions: tuple[str, ...] = ()) -> DispatchResult: return super().dispatch( target, task, cwd=cwd, timeout=timeout, runner=runner, writes=writes, publishes=publishes, - publication_permissions=publication_permissions, env=env, + publication_permissions=publication_permissions, ) def argv(self, target: Target, task: str, cwd: str | None = None, @@ -1062,16 +951,14 @@ def argv(self, target: Target, task: str, cwd: str | None = None, "--effort", target.effort, "--output-format", "json"] if writes: argv += ["--permission-mode", "acceptEdits"] - else: - # Defence in depth. Read-only safety comes from the disposable - # worktree and the source-checkout verification in dispatch(). - argv += ["--disallowedTools", "Edit", "Write", "NotebookEdit"] - # Publication remains behavioural. `dispatch()` refuses a read-only - # publisher, which would run without credentials; the read-only shape - # below is what a direct caller of argv() gets. + # A reading stage keeps its full tooling on purpose. It is told not to + # write, runs in a disposable clone, and dispatch() detects a change to + # the implementer's checkout or remote refs; nothing here narrows it. + # A publishing stage keeps its ordinary GitHub tooling. Which of those + # operations the stage may perform is a behavioural rule stated in its + # prompt (`cycle.publication_policy`), not a permission narrowed here. if publishes: - argv += (["--allowedTools", "Bash(gh:*)", "Bash(git:*)"] if writes - else ["--allowedTools", "Bash(gh:*)"]) + argv += ["--allowedTools", "Bash(gh:*)", "Bash(git:*)"] return argv def agent_output(self, stdout: str) -> str: @@ -1475,10 +1362,6 @@ def dispatch( ) ), }.get(workspace_policy, "the adapter cannot satisfy the workspace policy") - refusal = (adapter.read_only_refusal(**kw) - if workspace_policy is WorkspacePolicy.READ_ONLY else None) - if refusal is not None: - capability, detail = refusal return DispatchResult( DispatchOutcome.BLOCKED, target.executor, target, missing_capability=capability, @@ -1495,9 +1378,8 @@ def dispatch( and target.executor == "claude" and not adapter.enforces_read_only): result = _isolated_review_dispatch( adapter, target, task, cwd=kw.get("cwd"), - dispatch_call=lambda prompt, isolated_cwd, env: adapter.dispatch( - target, prompt, - **{**kw, "cwd": isolated_cwd, "writes": False, "env": env}, + dispatch_call=lambda prompt, isolated_cwd: adapter.dispatch( + target, prompt, **{**kw, "cwd": isolated_cwd, "writes": False}, ), ) else: diff --git a/scripts/router.py b/scripts/router.py index f566e8b9..025c0688 100644 --- a/scripts/router.py +++ b/scripts/router.py @@ -204,12 +204,12 @@ def explain(self) -> str: "fallback": "claude:anthropic/claude-sonnet-5 high"}, "reviewer": {"primary": "codex:openai/gpt-6-sol high"}, "senior_reviewer": {"primary": "codex:openai/gpt-6-sol max"}, - # Claude is an eligible security fallback through the isolated and verified - # read-only worktree harness; profile defaults still express the chosen - # order. + # Claude is an eligible security fallback through the disposable review + # clone, where writes are detected rather than prevented; profile defaults + # still express the chosen order. "security": {"primary": "codex:openai/gpt-6-sol high", - # Selected only when the isolated review harness is - # available. + # Runs in the disposable, change-detecting review + # clone. "fallback": "claude:anthropic/claude-opus-5-5 high"}, } diff --git a/scripts/telemetry.py b/scripts/telemetry.py index aab57c48..aa5566a8 100644 --- a/scripts/telemetry.py +++ b/scripts/telemetry.py @@ -116,7 +116,7 @@ def is_jev_model(value) -> bool: "provider": ("token", frozenset({"openai", "anthropic"})), "effort": ("token", frozenset({"low", "medium", "high", "max"})), "readiness_policy": ("token", frozenset({"proven", "attempt"})), - "read_only_mode": ("token", frozenset({"enforced", "isolated_verified"})), + "read_only_mode": ("token", frozenset({"enforced", "detected"})), "dispatched_from": ("token", frozenset({ "unknown", "installed", "authenticated", "quota_exhausted", "ready", })), @@ -134,7 +134,7 @@ def is_jev_model(value) -> bool: "bypass_acknowledgement", "trusted_directory", "orchestration_context", "provider_agent_mapping", "read_only_enforcement", "disposable_workspace", "review_workspace_isolation", "review_workspace_mismatch", - "review_workspace_conflict", "publication_access", "harness_publication", + "review_workspace_conflict", "publication_access", })), "verifiability": ("token", frozenset({"auto", "partial", "human"})), "routing_strategy": ("token", frozenset({"fixed", "measured"})), diff --git a/tests/test_executors.py b/tests/test_executors.py index 389473ae..4035f987 100644 --- a/tests/test_executors.py +++ b/tests/test_executors.py @@ -989,34 +989,27 @@ def test_claude_declares_a_writing_stage(self) -> None: self.assertEqual("acceptEdits", argv[argv.index("--permission-mode") + 1]) def test_claude_publishing_stage_keeps_its_github_tooling(self) -> None: - """Read-only publication gets gh only; writing publication also gets git.""" + """The publication boundary is behavioural: gh and git stay available, + and the stage's prompt says which operations it may perform.""" for permissions in (("comment",), ("comment", "push_branch"), ("comment", "create_pr", "push_branch")): argv = self.claude( writes="push_branch" in permissions, publishes=True, publication_permissions=permissions, ) - self.assertIn("--allowedTools", argv) - allowed = argv[argv.index("--allowedTools") + 1:] - expected = ["Bash(gh:*)"] - if "push_branch" in permissions: - expected.append("Bash(git:*)") - self.assertEqual(expected, allowed) - if "push_branch" not in permissions: - index = argv.index("--disallowedTools") - self.assertEqual( - ["--disallowedTools", "Edit", "Write", "NotebookEdit"], - argv[index:index + 4], - ) + self.assertEqual(["--allowedTools", "Bash(gh:*)", "Bash(git:*)"], argv[-3:]) def test_claude_non_publishing_stage_gets_no_extra_tools(self) -> None: self.assertNotIn("--allowedTools", self.claude(writes=True)) - def test_claude_read_only_gets_edit_tools_disallowed_as_defence_in_depth(self) -> None: + def test_claude_claims_no_confinement_it_does_not_have(self) -> None: + """A live probe wrote the file anyway with the edit tools disallowed, + and plan mode refuses the edit by turning a review into planning. So a + reading stage keeps its tools; the harness detects writes instead.""" argv = self.claude(writes=False) self.assertNotIn("--permission-mode", argv) - self.assertEqual(["--disallowedTools", "Edit", "Write", "NotebookEdit"], argv[-4:]) + self.assertNotIn("--disallowedTools", argv) def _git(self, cwd, *args): @@ -1069,7 +1062,7 @@ def test_claude_review_uses_an_independent_disposable_clone(self) -> None: seen = {} target = router.parse_target("claude:anthropic/claude-sonnet-5 high") - def runner(argv, timeout=None, cwd=None, env=None): + def runner(argv, timeout=None, cwd=None): seen["argv"], seen["cwd"] = argv, cwd self.assertNotEqual(str(repo), cwd) self.assertFalse(ex._paths_overlap(cwd, str(repo))) @@ -1095,7 +1088,7 @@ def runner(argv, timeout=None, cwd=None, env=None): ) self.assertEqual(ex.DispatchOutcome.SUCCEEDED, result.outcome) - self.assertEqual("isolated_verified", result.artifacts["read_only_mode"]) + self.assertEqual("detected", result.artifacts["read_only_mode"]) self.assertEqual(reviewed_head, result.artifacts["implementer_head_before"]) self.assertEqual(64, len(result.artifacts["implementer_status_fingerprint_before"])) self.assertIn("warning", result.detail) @@ -1107,7 +1100,7 @@ def runner(argv, timeout=None, cwd=None, env=None): capture_output=True, text=True, ) self.assertNotEqual(0, shared_config.returncode) - self.assertIn("--disallowedTools", seen["argv"]) + self.assertNotIn("--disallowedTools", seen["argv"]) self.assertNotIn("--permission-mode", seen["argv"]) def test_claude_review_fails_if_the_implementer_branch_moves(self) -> None: @@ -1115,7 +1108,7 @@ def test_claude_review_fails_if_the_implementer_branch_moves(self) -> None: target = router.parse_target("claude:anthropic/claude-sonnet-5 high") before = self._git(repo, "rev-parse", "HEAD") - def runner(argv, timeout=None, cwd=None, env=None): + def runner(argv, timeout=None, cwd=None): (repo / "branch-change.txt").write_text("changed", encoding="utf-8") self._git(repo, "add", "branch-change.txt") self._git(repo, "commit", "-qm", "unexpected branch change") @@ -1157,7 +1150,7 @@ def test_claude_review_detects_a_remote_branch_push(self) -> None: self._git(repo, "push", "origin", "HEAD") target = router.parse_target("claude:anthropic/claude-sonnet-5 high") - def runner(argv, timeout=None, cwd=None, env=None): + def runner(argv, timeout=None, cwd=None): (Path(cwd) / "reviewer.txt").write_text("review result\\n", encoding="utf-8") self._git(cwd, "add", "reviewer.txt") self._git(cwd, "config", "user.name", "Reviewer Test") @@ -1197,107 +1190,13 @@ def test_failed_isolation_does_not_claim_verified_mode(self) -> None: self.assertEqual(ex.DispatchOutcome.BLOCKED, result.outcome) self.assertNotIn("read_only_mode", result.artifacts) - def test_claude_review_runs_without_github_or_git_credentials(self) -> None: - repo = self._git_repo() - temporary = tempfile.TemporaryDirectory() - self.addCleanup(temporary.cleanup) - real_home = Path(temporary.name) / "real-home" - (real_home / ".claude").mkdir(parents=True) - (real_home / ".claude" / "credentials").write_text("claude login", encoding="utf-8") - (real_home / ".claude.json").write_text("{}", encoding="utf-8") - target = router.parse_target("claude:anthropic/claude-sonnet-5 high") - seen = {} - - def runner(argv, timeout=None, cwd=None, env=None): - seen["env"] = env - home = Path(env["HOME"]) - self.assertFalse(ex._paths_overlap(str(home), str(real_home))) - self.assertEqual( - "claude login", - (home / ".claude" / "credentials").read_text(encoding="utf-8"), - ) - self.assertEqual([], list(Path(env["GH_CONFIG_DIR"]).iterdir())) - self.assertEqual("", Path(env["GIT_CONFIG_GLOBAL"]).read_text(encoding="utf-8")) - configured = subprocess.run( - ["git", "-C", cwd, "config", "--global", "--list"], - capture_output=True, text=True, env=env, - ) - self.assertEqual("", configured.stdout) - self.assertIn("no GitHub or Git credentials", argv[argv.index("-p") + 1]) - return completed("{}") - - environment = { - "GH_TOKEN": "gh-secret", "GITHUB_TOKEN": "github-secret", - "SSH_AUTH_SOCK": "/agent.sock", "GIT_ASKPASS": "/askpass", - "GIT_CONFIG_COUNT": "1", "GIT_CONFIG_KEY_0": "credential.helper", - "GIT_CONFIG_VALUE_0": "store", "BITBUCKET_APP_PASSWORD": "bb-secret", - "PLANE_API_KEY": "plane-secret", "ANTHROPIC_API_KEY": "model-key", - } - with patch.dict(ex.os.environ, environment), \ - patch.object(ex.Path, "home", return_value=real_home): - ex.os.environ.pop("CLAUDE_CONFIG_DIR", None) - result = ex.dispatch( - router.RoutingDecision("reviewer", target, router.RoutingMode.PRODUCTION), - "review the change", ex.Registry([ex.ClaudeAdapter()]), cwd=str(repo), - runner=runner, - probes={"claude": ex.ProbeResult("claude", ex.Availability.READY, "test")}, - ) - - self.assertEqual(ex.DispatchOutcome.SUCCEEDED, result.outcome) - self.assertEqual("isolated_verified", result.artifacts["read_only_mode"]) - env = seen["env"] - for name in ("GH_TOKEN", "GITHUB_TOKEN", "SSH_AUTH_SOCK", "GIT_ASKPASS", - "GIT_CONFIG_COUNT", "GIT_CONFIG_KEY_0", "GIT_CONFIG_VALUE_0", - "BITBUCKET_APP_PASSWORD", "PLANE_API_KEY"): - self.assertNotIn(name, env) - self.assertEqual("model-key", env["ANTHROPIC_API_KEY"]) - self.assertEqual("1", env["GIT_CONFIG_NOSYSTEM"]) - self.assertEqual("0", env["GIT_TERMINAL_PROMPT"]) - self.assertIn("IdentityAgent=none", env["GIT_SSH_COMMAND"]) - # The temporary home and its links are gone; what they linked to is not. - self.assertFalse(Path(env["HOME"]).exists()) - self.assertEqual( - "claude login", - (real_home / ".claude" / "credentials").read_text(encoding="utf-8"), - ) - - def test_claude_is_not_offered_for_a_publishing_read_only_stage(self) -> None: - repo = self._git_repo() - registry = ex.Registry([ex.ClaudeAdapter()]) - - self.assertEqual(frozenset(), registry.compatible_executors( - ex.WorkspacePolicy.READ_ONLY, cwd=str(repo), publishes=True, - publication_permissions=("comment",), - )) - self.assertEqual(frozenset({"claude"}), registry.compatible_executors( - ex.WorkspacePolicy.READ_ONLY, cwd=str(repo), publishes=False, - )) - - def test_a_publishing_claude_review_is_blocked_before_it_runs(self) -> None: - repo = self._git_repo() - target = router.parse_target("claude:anthropic/claude-sonnet-5 high") - - with patch.object(ex, "_publication_preflight", return_value=(True, "passed")): - result = ex.dispatch( - router.RoutingDecision("reviewer", target, router.RoutingMode.PRODUCTION), - "review the change", ex.Registry([ex.ClaudeAdapter()]), cwd=str(repo), - publishes=True, publication_permissions=("comment",), - runner=lambda *args, **kwargs: self.fail("a publishing review must not run"), - probes={"claude": ex.ProbeResult("claude", ex.Availability.READY, "test")}, - ) - - self.assertEqual(ex.DispatchOutcome.BLOCKED, result.outcome) - self.assertEqual("harness_publication", result.missing_capability) - self.assertIn("without GitHub or Git credentials", result.detail) - self.assertNotIn("read_only_mode", result.artifacts) - - def test_a_review_clone_that_cannot_be_removed_fails_without_verified_mode(self) -> None: + def test_a_review_clone_that_cannot_be_removed_fails_without_a_read_only_mode(self) -> None: repo = self._git_repo() target = router.parse_target("claude:anthropic/claude-sonnet-5 high") seen = {} real_rmtree = ex.shutil.rmtree - def runner(argv, timeout=None, cwd=None, env=None): + def runner(argv, timeout=None, cwd=None): seen["cwd"] = cwd (Path(cwd) / "reviewer-created.txt").write_text("left", encoding="utf-8") return completed("{}") diff --git a/tests/test_telemetry.py b/tests/test_telemetry.py index 0191f918..9733b53c 100644 --- a/tests/test_telemetry.py +++ b/tests/test_telemetry.py @@ -489,11 +489,11 @@ def test_a_dispatch_is_recorded_from_the_objects_not_by_hand(self) -> None: self.assertEqual(1, row["payload"]["routing_reason_count"]) def test_read_only_mode_is_recorded_in_dispatch_payload(self) -> None: - decision, result = self.decision_and_result(read_only_mode="isolated_verified") + decision, result = self.decision_and_result(read_only_mode="detected") self.store.record_dispatch("repo", "t-review", "review", decision, result) - self.assertEqual("isolated_verified", self.store.rows()[0]["payload"]["read_only_mode"]) + self.assertEqual("detected", self.store.rows()[0]["payload"]["read_only_mode"]) def test_a_fallback_is_visible_in_the_row(self) -> None: decision, result = self.decision_and_result(used_fallback=True) @@ -512,13 +512,6 @@ def test_blocked_capabilities_are_counted_by_name(self) -> None: self.assertEqual({"operating_quota": 2, "folder_trust": 1}, self.store.dispatch_failures("repo")) - def test_a_refused_credential_free_publisher_is_recordable(self) -> None: - decision, result = self.decision_and_result(blocked_capability="harness_publication") - - self.store.record_dispatch("repo", "t1", "review", decision, result) - - self.assertEqual({"harness_publication": 1}, self.store.dispatch_failures("repo")) - class ModelDriftTests(TelemetryTestCase): def test_a_different_model_is_reported(self) -> None: From 3e53b8825a84abdf17c2ec46b7d0b2e8a3e451e0 Mon Sep 17 00:00:00 2001 From: datacas <4690232+datacas@users.noreply.github.com> Date: Thu, 24 Sep 2026 17:14:39 +0200 Subject: [PATCH 7/7] Never chmod through a reviewer symlink when removing the review clone The cleanup callback chmodded every path it failed to remove, and chmod follows links, so a reviewer-created symlink inside a non-writable directory changed the permissions of a file outside the clone. Links are no longer chmodded. The callback makes the parent directory writable instead, and only a parent inside the workspace being removed. Regression test included (REV-005). --- scripts/executors.py | 17 ++++++++++++++--- tests/test_executors.py | 36 ++++++++++++++++++++++++++++++++++++ 2 files changed, 50 insertions(+), 3 deletions(-) diff --git a/scripts/executors.py b/scripts/executors.py index bce72f27..9288a298 100644 --- a/scripts/executors.py +++ b/scripts/executors.py @@ -740,9 +740,19 @@ def _remote_ref_fingerprint(root: str) -> str: return hashlib.sha256(encoded.encode("utf-8")).hexdigest() -def _remove_read_only_path(function, path, exc_info) -> None: +def _remove_read_only_path(function, path, exc_info, root=None) -> None: + # Removal needs a writable parent, and on Windows a writable entry. chmod + # follows links, and a reviewer can point one anywhere, so a link is never + # chmodded, and a parent is made writable only inside `root`, the + # workspace being removed; rmtree does not descend through links. try: - os.chmod(path, 0o700) + parent = os.path.dirname(path) + if (root is not None and parent and not os.path.islink(parent) + and os.path.commonpath([os.path.abspath(root), os.path.abspath(parent)]) + == os.path.abspath(root)): + os.chmod(parent, 0o700) + if not os.path.islink(path): + os.chmod(path, 0o700) function(path) except OSError: raise exc_info[1] @@ -751,7 +761,8 @@ def _remove_read_only_path(function, path, exc_info) -> None: def _remove_workspace(path: str) -> str | None: """Remove a disposable directory; return what is left on disk, or None.""" try: - shutil.rmtree(path, onerror=_remove_read_only_path) + shutil.rmtree(path, onerror=lambda function, failed, exc_info: + _remove_read_only_path(function, failed, exc_info, root=path)) except FileNotFoundError: return None except Exception as exc: diff --git a/tests/test_executors.py b/tests/test_executors.py index 4035f987..a97dab3c 100644 --- a/tests/test_executors.py +++ b/tests/test_executors.py @@ -1190,6 +1190,42 @@ def test_failed_isolation_does_not_claim_verified_mode(self) -> None: self.assertEqual(ex.DispatchOutcome.BLOCKED, result.outcome) self.assertNotIn("read_only_mode", result.artifacts) + @unittest.skipUnless(hasattr(ex.os, "geteuid") and ex.os.geteuid() != 0, + "needs POSIX permissions enforced for a non-root user") + def test_cleanup_never_follows_a_reviewer_symlink_out_of_the_clone(self) -> None: + repo = self._git_repo() + temporary = tempfile.TemporaryDirectory() + self.addCleanup(temporary.cleanup) + external = Path(temporary.name) / "external-secret" + external.write_text("keep me", encoding="utf-8") + external.chmod(0o600) + target = router.parse_target("claude:anthropic/claude-sonnet-5 high") + seen = {} + + def runner(argv, timeout=None, cwd=None): + seen["cwd"] = cwd + locked = Path(cwd) / "locked" + locked.mkdir() + (locked / "link").symlink_to(external) + locked.chmod(0o500) + return completed("{}") + + result = ex.dispatch( + router.RoutingDecision("reviewer", target, router.RoutingMode.PRODUCTION), + "review the change", ex.Registry([ex.ClaudeAdapter()]), cwd=str(repo), + runner=runner, + probes={"claude": ex.ProbeResult("claude", ex.Availability.READY, "test")}, + ) + locked = Path(seen["cwd"]) / "locked" + if locked.exists(): + self.addCleanup(ex.shutil.rmtree, seen["cwd"], ignore_errors=True) + self.addCleanup(locked.chmod, 0o700) + + self.assertEqual(0o600, external.stat().st_mode & 0o777) + self.assertEqual("keep me", external.read_text(encoding="utf-8")) + self.assertFalse(Path(seen["cwd"]).exists()) + self.assertEqual(ex.DispatchOutcome.SUCCEEDED, result.outcome) + def test_a_review_clone_that_cannot_be_removed_fails_without_a_read_only_mode(self) -> None: repo = self._git_repo() target = router.parse_target("claude:anthropic/claude-sonnet-5 high")