diff --git a/README.md b/README.md index b85fd52c..296f956b 100644 --- a/README.md +++ b/README.md @@ -131,6 +131,11 @@ 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, 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 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..dcef7d95 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 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: 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 e6afd85b..3a35da20 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`: 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. 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. 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..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` | — | -¹ 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 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`); Orca only with an explicit isolated 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 | -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 = 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 77fc4d00..9288a298 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,206 @@ def auth_evidence(self) -> tuple[bool, str]: return False, f"no credential at {auth}" +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() + raise ExecutorError(detail) + 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 _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: + 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] + + +def _remove_workspace(path: str) -> str | None: + """Remove a disposable directory; return what is left on disk, or None.""" + try: + 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: + 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: + 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 = 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", + ) + 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 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 clone is not at the reviewed HEAD") + except Exception as exc: + left = _remove_workspace(worktree) if worktree else None + detail = f"could not prepare an isolated review workspace: {exc}" + if left: + detail += f"; cleanup failed, left on disk: {left}" + return adapter._blocked( + target, "review_workspace_isolation", detail, + ) + + 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. 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" + left = 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", + ) + 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 + 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", + ) + workspace_changed = workspace_head != review_head or bool(workspace_status) + except Exception: + workspace_changed = True + finally: + 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"] = "detected" + artifacts["implementer_head_before"] = before_head + 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 + cleanup_error = ( + 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 + if cleanup_error: + detail += "; " + cleanup_error + return replace( + result, outcome=DispatchOutcome.CONTRACT_VIOLATION, + missing_capability=None, detail=detail, artifacts=artifacts, + ) + if cleanup_error: + # 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) + 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) + return replace(result, detail=detail, artifacts=artifacts) + + class ClaudeAdapter(NativeAdapter): name = "claude" binary = "claude" @@ -718,7 +920,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,6 +962,9 @@ def argv(self, target: Target, task: str, cwd: str | None = None, "--effort", target.effort, "--output-format", "json"] if writes: argv += ["--permission-mode", "acceptEdits"] + # 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. @@ -1166,8 +1385,22 @@ 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) + 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 or (not adapter.completes_work diff --git a/scripts/router.py b/scripts/router.py index a6d388b3..025c0688 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 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", - # Compatibility-only registry entry: the read-only - # eligibility filter deliberately never selects Claude. + # 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 969c0d33..aa5566a8 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", "detected"})), "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..a97dab3c 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 @@ -1004,13 +1005,261 @@ def test_claude_non_publishing_stage_gets_no_extra_tools(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 gets no flag here rather than a false guarantee.""" + reading stage keeps its tools; the harness detects writes instead.""" argv = self.claude(writes=False) self.assertNotIn("--permission-mode", argv) self.assertNotIn("--disallowedTools", argv) + 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_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") + + 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.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, "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("{}") + + 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("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) + 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.assertNotIn("--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")) + 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, "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("{}") + + 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) + + @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") + seen = {} + real_rmtree = ex.shutil.rmtree + + def runner(argv, timeout=None, cwd=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: observed_stdin = [] @@ -1089,6 +1338,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..9733b53c 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="detected") + + self.store.record_dispatch("repo", "t-review", "review", decision, result) + + 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)