From 2b4964813380cf3e93514dcb04e5625f7514ab2c Mon Sep 17 00:00:00 2001 From: wangzhizhou <824219521@qq.com> Date: Sun, 22 Nov 2026 12:43:51 +0800 Subject: [PATCH 01/23] security: require sandbox backend to terminate all task descendants on exit --- scripts/sandbox_runtime.py | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/scripts/sandbox_runtime.py b/scripts/sandbox_runtime.py index 234435e..c811dd5 100644 --- a/scripts/sandbox_runtime.py +++ b/scripts/sandbox_runtime.py @@ -44,6 +44,7 @@ class SandboxCapabilities: enforces_filesystem: bool enforces_network: bool isolates_process_tree: bool + terminates_process_tree_on_exit: bool enforces_resource_limits: bool supports_egress_proxy: bool supports_secrets_broker: bool @@ -123,6 +124,7 @@ def capabilities(self) -> list[SandboxCapabilities]: enforces_filesystem=False, enforces_network=False, isolates_process_tree=False, + terminates_process_tree_on_exit=False, enforces_resource_limits=False, supports_egress_proxy=False, supports_secrets_broker=False, @@ -137,7 +139,7 @@ def doctor(self) -> dict: ready = any( item.platform == current and item.available and item.enforces_filesystem and item.enforces_network and item.isolates_process_tree - and item.enforces_resource_limits + and item.terminates_process_tree_on_exit and item.enforces_resource_limits for item in capabilities ) return { @@ -224,7 +226,8 @@ def build_command( needs_secrets_broker = bool(profile["secrets"].get("brokered_credentials")) if (caps.platform == current and caps.available and caps.enforces_filesystem and caps.enforces_network - and caps.isolates_process_tree and caps.enforces_resource_limits + and caps.isolates_process_tree and caps.terminates_process_tree_on_exit + and caps.enforces_resource_limits and (not needs_egress_proxy or caps.supports_egress_proxy) and (not needs_secrets_broker or caps.supports_secrets_broker)): candidates.append(backend) From bca847f8fa4bfc088c34465601d11144bd6584b9 Mon Sep 17 00:00:00 2001 From: wangzhizhou <824219521@qq.com> Date: Sun, 22 Nov 2026 12:43:54 +0800 Subject: [PATCH 02/23] test: include task descendant cleanup in backend capability contract --- tests/test_sandbox_runtime.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/test_sandbox_runtime.py b/tests/test_sandbox_runtime.py index 794c162..5e048c0 100644 --- a/tests/test_sandbox_runtime.py +++ b/tests/test_sandbox_runtime.py @@ -56,7 +56,7 @@ class FakeBackend: def probe(self): return sandbox.SandboxCapabilities( self.backend_id, sandbox.host_platform(), True, True, True, True, - True, True, False, "ready", "test double only" + True, True, True, False, "ready", "test double only" ) def build_command(self, command, spec): From 92fdcda9093e13c3ceb5221a42a48c1f79c2f017 Mon Sep 17 00:00:00 2001 From: wangzhizhou <824219521@qq.com> Date: Sun, 22 Nov 2026 12:43:56 +0800 Subject: [PATCH 03/23] docs: require descendant cleanup before task workspace freeze --- .ai/runtime/sandbox/LAUNCHER-CONTRACT.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.ai/runtime/sandbox/LAUNCHER-CONTRACT.md b/.ai/runtime/sandbox/LAUNCHER-CONTRACT.md index 2002122..9c39d31 100644 --- a/.ai/runtime/sandbox/LAUNCHER-CONTRACT.md +++ b/.ai/runtime/sandbox/LAUNCHER-CONTRACT.md @@ -12,7 +12,7 @@ A backend is eligible only if it can enforce all of the following for the reques - workspace-only filesystem access, including denial of stable checkout, other task workspaces, shared Git common metadata/object/ref stores, user home, credentials and control-plane runtime; - default-deny network, no host/LAN access, and explicit egress proxy policy; -- process-tree inheritance and reliable termination; +- process-tree inheritance and reliable termination, including killing every descendant before the launcher reports task completion; - CPU, memory, process-count and wall-clock limits; - no privilege escalation and no host container-runtime socket; - effective-policy evidence (backend/version, profile digest and platform); From ffc799cf21b3f5e62547d9dedcc1a4e5fcff4a71 Mon Sep 17 00:00:00 2001 From: wangzhizhou <824219521@qq.com> Date: Sun, 22 Nov 2026 12:44:16 +0800 Subject: [PATCH 04/23] feat: sandbox acceptance checks and publish immutable review artifacts --- scripts/agent-orchestrate.py | 97 ++++++++++++++++++++++++++++++++++-- 1 file changed, 93 insertions(+), 4 deletions(-) diff --git a/scripts/agent-orchestrate.py b/scripts/agent-orchestrate.py index f8c9a6d..3afadac 100644 --- a/scripts/agent-orchestrate.py +++ b/scripts/agent-orchestrate.py @@ -74,7 +74,8 @@ def stop_command_tree(process: subprocess.Popen[str]) -> tuple[str, str]: def run_command_controlled(argv: list[str], workspace: Path, timeout_seconds: int, - cancel_file: Path | None = None) -> tuple[int, str, str, str | None]: + cancel_file: Path | None = None, + environment: dict[str, str] | None = None) -> tuple[int, str, str, str | None]: options: dict[str, object] = {} if os.name == "nt": options["creationflags"] = subprocess.CREATE_NEW_PROCESS_GROUP @@ -82,7 +83,8 @@ def run_command_controlled(argv: list[str], workspace: Path, timeout_seconds: in options["start_new_session"] = True process = subprocess.Popen( argv, cwd=workspace, text=True, stdout=subprocess.PIPE, - stderr=subprocess.PIPE, **options, + stderr=subprocess.PIPE, + env=environment if environment is not None else os.environ.copy(), **options, ) started = time.monotonic() while True: @@ -99,7 +101,11 @@ def run_command_controlled(argv: list[str], workspace: Path, timeout_seconds: in def run_acceptance_checks(check_ids: list[str], workspace: Path, - runs_dir: Path, task_id: str, attempt: int, cancel_file: Path | None = None) -> dict[str, Any]: + runs_dir: Path, task_id: str, attempt: int, + cancel_file: Path | None = None, + require_sandbox: bool = False, + sandbox_profile: Path | None = None, + task_permissions: dict[str, Any] | None = None) -> dict[str, Any]: """Run only fixed, allowlisted test commands and persist their outputs.""" if not check_ids: return {"status": "not_configured", "results": []} @@ -110,11 +116,24 @@ def run_acceptance_checks(check_ids: list[str], workspace: Path, argv = acceptance_command(check_id) stdout_path = output_dir / f"{check_id}.stdout.txt" stderr_path = output_dir / f"{check_id}.stderr.txt" + environment = None + check_timeout = ACCEPTANCE_CHECK_TIMEOUT_SECONDS + sandbox_evidence = None if shutil.which(argv[0]) is None: stdout, stderr, exit_code, result = "", f"Executable not found: {argv[0]}", None, "not_found" else: + if require_sandbox: + if sandbox_profile is None or task_permissions is None: + raise ValueError("Sandboxed acceptance checks require the trusted profile and task permissions.") + from sandbox_runtime import SandboxManager + argv, environment, sandbox_evidence = SandboxManager().build_command( + argv, sandbox_profile, f"{task_id}-check-{attempt}-{check_id}", + workspace, runs_dir / "sandbox-runtime" / task_id / check_id, + task_permissions, + ) + check_timeout = min(check_timeout, sandbox_evidence["timeout_seconds"]) exit_code, stdout, stderr, termination = run_command_controlled( - argv, workspace, ACCEPTANCE_CHECK_TIMEOUT_SECONDS, cancel_file, + argv, workspace, check_timeout, cancel_file, environment, ) if termination == "cancelled": result = "cancelled" @@ -132,6 +151,8 @@ def run_acceptance_checks(check_ids: list[str], workspace: Path, "exit_code": exit_code, "stdout_path": str(stdout_path), "stderr_path": str(stderr_path), + "sandbox_status": sandbox_evidence["status"] if sandbox_evidence else "not-requested", + "sandbox_backend": sandbox_evidence.get("backend") if sandbox_evidence else None, }) if result == "cancelled": return {"status": "cancelled", "results": results} @@ -359,6 +380,74 @@ def verify_change_evidence(repo: Path, record: dict[str, Any]) -> None: +def publish_review_artifact(evidence: dict[str, Any], runs_dir: Path, + task_id: str, attempt: int) -> dict[str, Any]: + """Publish a portable immutable review snapshot after a sandboxed task has stopped.""" + from artifact_broker import export_artifact + + source_dir = runs_dir / task_id / f".artifact-source-attempt-{attempt}" + if source_dir.exists(): + raise ValueError(f"Artifact staging directory already exists: {source_dir}") + source_dir.mkdir(parents=True) + try: + diff_source = Path(evidence["diff_path"]) + if diff_source.is_symlink() or not diff_source.is_file(): + raise ValueError("Review diff is missing or unsafe; cannot publish review artifact.") + shutil.copyfile(diff_source, source_dir / "review.diff") + portable = dict(evidence) + portable["diff_path"] = "review.diff" + portable.pop("evidence_path", None) + acceptance = portable.get("acceptance", {}) + checks = acceptance.get("automated_checks", {}) + for item in checks.get("results", []): + for key in ("stdout_path", "stderr_path"): + if item.get(key): + item[key] = Path(item[key]).name + (source_dir / "review-evidence.json").write_text( + json.dumps(portable, ensure_ascii=False, indent=2) + "\\n", + encoding="utf-8", + ) + result = export_artifact( + source_dir, runs_dir / "artifacts", task_id, "review-evidence", + ["review.diff", "review-evidence.json"], evidence.get("base_commit"), + ) + manifest = result["manifest"] + return { + "artifact_id": manifest["artifact_id"], + "artifact_dir": result["artifact_dir"], + "kind": manifest["kind"], + "source_revision": manifest["source_revision"], + } + finally: + shutil.rmtree(source_dir, ignore_errors=True) + + +def verify_review_artifact(record: dict[str, Any]) -> dict[str, Any]: + """Verify immutable artifact integrity and bind it to the reviewed workspace evidence.""" + from artifact_broker import verify_artifact + + artifact = record.get("review_artifact") + if not isinstance(artifact, dict) or not artifact.get("artifact_dir"): + raise ValueError("Sandbox-required task is missing its immutable review artifact.") + artifact_dir = Path(artifact["artifact_dir"]) + manifest = verify_artifact(artifact_dir) + if (manifest.get("task_id") != record.get("task_id") + or manifest.get("kind") != "review-evidence" + or manifest.get("artifact_id") != artifact.get("artifact_id")): + raise ValueError("Review artifact manifest does not match the task journal.") + artifact_evidence = json.loads((artifact_dir / "review-evidence.json").read_text(encoding="utf-8")) + evidence_path = record.get("review_evidence") + if not evidence_path or not Path(evidence_path).is_file(): + raise ValueError("Original review evidence is missing.") + original = json.loads(Path(evidence_path).read_text(encoding="utf-8")) + if (artifact_evidence.get("task_id") != record.get("task_id") + or artifact_evidence.get("fingerprint") != original.get("fingerprint") + or artifact_evidence.get("base_commit") != original.get("base_commit") + or manifest.get("source_revision") != original.get("base_commit")): + raise ValueError("Immutable review artifact is not bound to the current task evidence.") + return manifest + + def resolve_task_path(task_file: str, runs_dir: Path) -> Path: """Resolve a task file from the repository or this run's external data directory.""" candidate = Path(task_file) From 72d1bef4da933ec253f75905a1a383a39e9a859b Mon Sep 17 00:00:00 2001 From: wangzhizhou <824219521@qq.com> Date: Sun, 22 Nov 2026 12:44:29 +0800 Subject: [PATCH 05/23] feat: export review artifacts only after enforced task and check execution --- scripts/agent-orchestrate.py | 43 +++++++++++++++++++++++++++++++----- 1 file changed, 37 insertions(+), 6 deletions(-) diff --git a/scripts/agent-orchestrate.py b/scripts/agent-orchestrate.py index 3afadac..07cdd31 100644 --- a/scripts/agent-orchestrate.py +++ b/scripts/agent-orchestrate.py @@ -537,20 +537,51 @@ def run_plan(plan: dict[str, Any], runs_dir: Path, state: dict[str, Any], use_wo result = subprocess.run(command, cwd=ROOT, check=False) record["last_exit_code"] = result.returncode record["handoff"] = str(task_output) + sandbox_enforced = not require_sandbox + sandbox_error = None + if result.returncode == 0 and require_sandbox: + try: + handoff = json.loads(task_output.read_text(encoding="utf-8")) + sandbox_enforced = handoff.get("artifacts", {}).get("sandbox_status") == "enforced" + except (OSError, json.JSONDecodeError) as exc: + sandbox_error = f"Required sandbox handoff evidence is missing or invalid: {exc}" + if not sandbox_enforced and sandbox_error is None: + sandbox_error = "Runner completed without an enforced sandbox status." automated_checks = {"status": "not_configured", "results": []} - if result.returncode == 0: - automated_checks = run_acceptance_checks( - task_envelope.get("acceptance_checks", []), workspace, - runs_dir, task_id, attempt, cancel_file, - ) + if result.returncode == 0 and sandbox_error is None: + try: + automated_checks = run_acceptance_checks( + task_envelope.get("acceptance_checks", []), workspace, + runs_dir, task_id, attempt, cancel_file, + require_sandbox=require_sandbox, + sandbox_profile=sandbox_profile, + task_permissions=task_envelope.get("permissions", {}), + ) + except RuntimeError as exc: + automated_checks = {"status": "failed", "results": [], "error": str(exc)} record["automated_checks"] = automated_checks + artifact_error = None if use_worktrees and record.get("base_commit"): evidence = collect_change_evidence( workspace, record["base_commit"], task_id, runs_dir, automated_checks=automated_checks, ) record["review_evidence"] = evidence["evidence_path"] - if result.returncode == 130 or automated_checks["status"] == "cancelled": + if (require_sandbox and sandbox_enforced + and automated_checks["status"] in {"passed", "not_configured"}): + try: + record["review_artifact"] = publish_review_artifact( + evidence, runs_dir, task_id, attempt, + ) + except (OSError, ValueError, RuntimeError) as exc: + artifact_error = str(exc) + if artifact_error: + record.update(status="failed", termination_reason="artifact_export_failed", + artifact_error=artifact_error, finished_at=now()) + elif sandbox_error: + record.update(status="failed", termination_reason="sandbox_evidence_invalid", + sandbox_error=sandbox_error, finished_at=now()) + elif result.returncode == 130 or automated_checks["status"] == "cancelled": record.update(status="cancelled", termination_reason="cancelled", finished_at=now()) elif result.returncode == 0 and automated_checks["status"] in {"passed", "not_configured"}: # The adapter intentionally emits partial; only explicit human From 7aabc60c2e7663c246c2bad5dd2f33538e2f46a3 Mon Sep 17 00:00:00 2001 From: wangzhizhou <824219521@qq.com> Date: Sun, 22 Nov 2026 12:44:52 +0800 Subject: [PATCH 06/23] security: bind approvals and integration to verified immutable review artifact --- scripts/agent-orchestrate.py | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/scripts/agent-orchestrate.py b/scripts/agent-orchestrate.py index 07cdd31..67be372 100644 --- a/scripts/agent-orchestrate.py +++ b/scripts/agent-orchestrate.py @@ -237,6 +237,7 @@ def initial_state(plan: dict[str, Any], use_worktrees: bool = False, "updated_at": now(), "tasks": { item["task_id"]: { + "task_id": item["task_id"], "status": "pending", "attempts": 0, "handoff": None, "last_exit_code": None, "worktree": None, "base_commit": None, "updated_at": now() } @@ -404,7 +405,7 @@ def publish_review_artifact(evidence: dict[str, Any], runs_dir: Path, if item.get(key): item[key] = Path(item[key]).name (source_dir / "review-evidence.json").write_text( - json.dumps(portable, ensure_ascii=False, indent=2) + "\\n", + json.dumps(portable, ensure_ascii=False, indent=2) + "\n", encoding="utf-8", ) result = export_artifact( @@ -648,6 +649,8 @@ def approve(task_id: str, state: dict[str, Any], state_path: Path) -> None: raise ValueError("A failed handoff cannot be approved.") if record.get("automated_checks", {}).get("status") == "failed": raise ValueError("Configured acceptance checks failed; task cannot be approved.") + if state.get("sandbox_required", False): + verify_review_artifact(record) if record.get("worktree"): verify_change_evidence(Path(record["worktree"]), record) record.update(status="approved", approved_at=now(), updated_at=now()) @@ -716,6 +719,8 @@ def integrate_task(repo: Path, task_id: str, state: dict[str, Any], raise ValueError("Target branch no longer contains the task base commit; rebase/recreate the task deliberately.") verify_change_evidence(worktree, record) + if state.get("sandbox_required", False): + verify_review_artifact(record) worktree_head = git_output(worktree, "rev-parse", "HEAD") if not is_ancestor(worktree, base_commit, worktree_head): raise ValueError("Task worktree HEAD is not based on its recorded base commit.") From 52502271149d8d968c2d181c34025edc23a59b7d Mon Sep 17 00:00:00 2001 From: wangzhizhou <824219521@qq.com> Date: Sun, 22 Nov 2026 12:45:11 +0800 Subject: [PATCH 07/23] test: verify sandboxed artifact publication and approval gating --- tests/test_agent_orchestrator.py | 67 ++++++++++++++++++++++++++++++++ 1 file changed, 67 insertions(+) diff --git a/tests/test_agent_orchestrator.py b/tests/test_agent_orchestrator.py index 866c11d..08495f6 100644 --- a/tests/test_agent_orchestrator.py +++ b/tests/test_agent_orchestrator.py @@ -134,6 +134,73 @@ def test_sandbox_requirement_is_passed_from_control_plane_not_task_envelope(self self.assertTrue(state["sandbox_required"]) self.assertEqual(state["sandbox_profile_sha256"], "a" * 64) + def test_sandboxed_acceptance_checks_fail_closed_without_backend(self): + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + workspace = root / "workspace" + workspace.mkdir() + with self.assertRaisesRegex(RuntimeError, "No registered backend"): + orchestrator.run_acceptance_checks( + ["python-unittest"], workspace, root / "runs", + "task-a", 1, require_sandbox=True, + sandbox_profile=ROOT / ".ai/runtime/examples/sandbox-profile.json", + task_permissions={ + "repository_read": True, "repository_write": True, + "network_access": False, "secret_access": False, + }, + ) + + def test_review_artifact_is_portable_and_bound_to_review_evidence(self): + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + runs = root / "runs" + task_dir = runs / "task-a" + task_dir.mkdir(parents=True) + diff_path = task_dir / "review.diff" + diff_path.write_text("diff --git a/a.txt b/a.txt\\n", encoding="utf-8") + evidence = { + "protocol_version": "1.0", + "task_id": "task-a", + "base_commit": "abcdef0123456789", + "captured_at": "2026-11-22T00:00:00+00:00", + "changed_files": ["a.txt"], + "diff_stat": "1 file changed", + "diff_check": {"result": "passed", "output": ""}, + "fingerprint": "a" * 64, + "diff_path": str(diff_path), + "acceptance": {"automated_checks": {"status": "passed", "results": [{ + "stdout_path": str(task_dir / "checks" / "stdout.txt"), + "stderr_path": str(task_dir / "checks" / "stderr.txt"), + }]}}, + } + evidence_path = task_dir / "review-evidence.json" + evidence_path.write_text(json.dumps(evidence), encoding="utf-8") + artifact = orchestrator.publish_review_artifact(evidence, runs, "task-a", 1) + record = { + "task_id": "task-a", + "review_evidence": str(evidence_path), + "review_artifact": artifact, + } + manifest = orchestrator.verify_review_artifact(record) + self.assertEqual(manifest["kind"], "review-evidence") + portable = json.loads( + (Path(artifact["artifact_dir"]) / "review-evidence.json").read_text(encoding="utf-8") + ) + self.assertEqual(portable["diff_path"], "review.diff") + self.assertEqual(portable["acceptance"]["automated_checks"]["results"][0]["stdout_path"], "stdout.txt") + + def test_sandbox_required_approval_rejects_missing_immutable_artifact(self): + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + handoff = root / "handoff.json" + handoff.write_text(json.dumps({"task_id": "task-a", "status": "partial"}), encoding="utf-8") + state = orchestrator.initial_state(plan([item("task-a")]), sandbox_required=True) + record = state["tasks"]["task-a"] + record.update(status="awaiting_review", handoff=str(handoff), + automated_checks={"status": "passed", "results": []}) + with self.assertRaisesRegex(ValueError, "immutable review artifact"): + orchestrator.approve("task-a", state, root / "state.json") + def test_valid_dag(self): with tempfile.TemporaryDirectory() as tmp: path = Path(tmp) / "plan.json" From 48d49dea432aa614685ae1505bb1bc4f97025926 Mon Sep 17 00:00:00 2001 From: wangzhizhou <824219521@qq.com> Date: Sun, 22 Nov 2026 12:45:27 +0800 Subject: [PATCH 08/23] docs: document sandbox-gated artifact publication and review flow --- .ai/runtime/artifacts/README.md | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/.ai/runtime/artifacts/README.md b/.ai/runtime/artifacts/README.md index 58fabb2..45b1509 100644 --- a/.ai/runtime/artifacts/README.md +++ b/.ai/runtime/artifacts/README.md @@ -2,9 +2,9 @@ ## Purpose and trust boundary -The Artifact Broker is the target trusted control-plane utility for file exchange between Agent tasks, reviewers and the integrator. This milestone delivers its standalone CLI and immutable storage contract; Orchestrator automation and Integrator wiring are a follow-up M4.3b task. Agents must not share writable directories. +The Artifact Broker is the target trusted control-plane utility for file exchange between Agent tasks, reviewers and the integrator. The standalone CLI and immutable storage contract are implemented. Orchestrator integration now exports a review artifact only for sandbox-required tasks after the Runner and sandboxed acceptance checks complete; approval and integration re-verify the artifact and bind it to the current review fingerprint. Agents must not share writable directories. -The broker must run after the producing Agent and its descendants have stopped. Exporting a workspace while an Agent is still writing creates a time-of-check/time-of-use race and does not produce a reliable snapshot. The broker validates source paths and file metadata, but a frozen source workspace is an operational precondition. +The broker must run after the producing Agent and its descendants have stopped. The sandbox backend contract now requires termination of every task descendant before the launcher reports completion. Exporting a workspace while any Agent or check process is still writing creates a time-of-check/time-of-use race and does not produce a reliable snapshot. The broker validates source paths and file metadata, but a frozen source workspace is an operational precondition. ## Artifact format @@ -31,6 +31,8 @@ Files are copied, never hard-linked. The store and source workspace must be disj - Verification revalidates the manifest, canonical artifact ID, each file size/hash, and the exact file set. - Materialization creates a new, non-existing, read-only reviewer snapshot. It never applies files to the stable checkout. +Legacy unsandboxed Orchestrator runs do not auto-export artifacts. Sandbox-required runs require `--require-sandbox --worktrees`; if the Runner handoff does not say `sandbox_status: enforced`, or a check cannot be sandboxed, the task cannot be approved or integrated. + Sensitive-name filtering is a conservative guard, not a complete secret scanner. Do not put credentials in task workspaces. A future credential broker must keep raw secrets outside the Agent and artifact planes. ## CLI From ebffa2a4e1a47dafe17e89d3421b782d91e8d5de Mon Sep 17 00:00:00 2001 From: wangzhizhou <824219521@qq.com> Date: Sun, 22 Nov 2026 12:45:30 +0800 Subject: [PATCH 09/23] docs: retain process-tree lifecycle requirement in launcher contract From 0ebbd33dcf6cccc75d3947c771b11815339729d6 Mon Sep 17 00:00:00 2001 From: wangzhizhou <824219521@qq.com> Date: Sun, 22 Nov 2026 12:45:33 +0800 Subject: [PATCH 10/23] docs: record sandbox-gated artifact broker integration acceptance --- tasks/evolution/M4-sandbox-runtime.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tasks/evolution/M4-sandbox-runtime.md b/tasks/evolution/M4-sandbox-runtime.md index 933f7c6..bc6ff2a 100644 --- a/tasks/evolution/M4-sandbox-runtime.md +++ b/tasks/evolution/M4-sandbox-runtime.md @@ -21,7 +21,7 @@ Introduce OS-enforced, task-scoped isolation so multiple cooperating Agents cann | M4.2a | Launcher contract | Backend interface, profile validation, capability doctor, handoff enforcement evidence, fail-closed Runner integration | | M4.2b | First OS backend | macOS Seatbelt full-process launcher, sanitized environment, effective-policy doctor and macOS conformance tests | | M4.3a | Artifact Broker core | Content-addressed export, manifest/hash verification, read-only reviewer materialization, path/symlink/type/size validation | -| M4.3b | Artifact Broker integration | Orchestrator freezes task output, exports approved artifacts, reviewers consume verified snapshots, Integrator remains the only apply path | +| M4.3b | Artifact Broker integration | Sandbox-required Orchestrator exports immutable review artifacts after Agent and checks exit; approval and Integrator verify task/base/fingerprint binding | | M4.4 | Linux OCI backend | Rootless runtime, namespaces, seccomp, LSM, resource limits, network deny, conformance suite | | M4.5 | Strong isolation backends | gVisor/Kata/Firecracker plugin interface and documented deployment profiles | | M4.6 | Brokers and audit | Scoped credential/network broker, policy hash, denial evidence, operational guide | From 009af98101f65f2c735c9702c213be62b0569f78 Mon Sep 17 00:00:00 2001 From: wangzhizhou <824219521@qq.com> Date: Sun, 22 Nov 2026 12:45:37 +0800 Subject: [PATCH 11/23] docs: document sandbox-gated artifact broker orchestration --- .ai/runtime/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.ai/runtime/README.md b/.ai/runtime/README.md index ff1f816..7c034ba 100644 --- a/.ai/runtime/README.md +++ b/.ai/runtime/README.md @@ -45,4 +45,4 @@ Do not use `completed` when checks were skipped or when the result relies on unv ## Artifact exchange -See [Immutable Artifact Broker](artifacts/README.md) for the standalone content-addressed export, verification and read-only reviewer snapshot CLI. Orchestrator and Integrator automation is not wired yet; Agents must not exchange files through shared writable directories. +See [Immutable Artifact Broker](artifacts/README.md) for the standalone content-addressed export, verification and read-only reviewer snapshot CLI. Sandbox-required Orchestrator runs export immutable review evidence after the Agent and sandboxed checks exit; approval and integration re-verify the artifact. Legacy unsandboxed runs do not auto-export. Agents must not exchange files through shared writable directories. From 02903fd80c2a1fe590d967ad772dcbfd2802f675 Mon Sep 17 00:00:00 2001 From: wangzhizhou <824219521@qq.com> Date: Sun, 22 Nov 2026 12:45:56 +0800 Subject: [PATCH 12/23] fix: keep artifact store outside run workspace and write valid JSON --- scripts/agent-orchestrate.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/scripts/agent-orchestrate.py b/scripts/agent-orchestrate.py index 67be372..ae049e2 100644 --- a/scripts/agent-orchestrate.py +++ b/scripts/agent-orchestrate.py @@ -409,7 +409,7 @@ def publish_review_artifact(evidence: dict[str, Any], runs_dir: Path, encoding="utf-8", ) result = export_artifact( - source_dir, runs_dir / "artifacts", task_id, "review-evidence", + source_dir, runs_dir.parent / f"{runs_dir.name}.artifacts", task_id, "review-evidence", ["review.diff", "review-evidence.json"], evidence.get("base_commit"), ) manifest = result["manifest"] From 37f38c352a5862ce2edbea4646334d8f68bc8163 Mon Sep 17 00:00:00 2001 From: wangzhizhou <824219521@qq.com> Date: Sun, 22 Nov 2026 12:46:08 +0800 Subject: [PATCH 13/23] fix: require complete sandbox evidence and report artifact failures --- scripts/agent-orchestrate.py | 15 ++++++++++++--- 1 file changed, 12 insertions(+), 3 deletions(-) diff --git a/scripts/agent-orchestrate.py b/scripts/agent-orchestrate.py index ae049e2..79504a0 100644 --- a/scripts/agent-orchestrate.py +++ b/scripts/agent-orchestrate.py @@ -138,7 +138,7 @@ def run_acceptance_checks(check_ids: list[str], workspace: Path, if termination == "cancelled": result = "cancelled" elif termination == "timeout": - stderr += f"\\nTimed out after {ACCEPTANCE_CHECK_TIMEOUT_SECONDS} seconds." + stderr += f"\\nTimed out after {check_timeout} seconds." result = "timeout" else: result = "passed" if exit_code == 0 else "failed" @@ -153,6 +153,7 @@ def run_acceptance_checks(check_ids: list[str], workspace: Path, "stderr_path": str(stderr_path), "sandbox_status": sandbox_evidence["status"] if sandbox_evidence else "not-requested", "sandbox_backend": sandbox_evidence.get("backend") if sandbox_evidence else None, + "sandbox_profile_sha256": sandbox_evidence.get("profile_sha256") if sandbox_evidence else None, }) if result == "cancelled": return {"status": "cancelled", "results": results} @@ -543,7 +544,14 @@ def run_plan(plan: dict[str, Any], runs_dir: Path, state: dict[str, Any], use_wo if result.returncode == 0 and require_sandbox: try: handoff = json.loads(task_output.read_text(encoding="utf-8")) - sandbox_enforced = handoff.get("artifacts", {}).get("sandbox_status") == "enforced" + sandbox_artifacts = handoff.get("artifacts", {}) + sandbox_enforced = ( + sandbox_artifacts.get("sandbox_status") == "enforced" + and isinstance(sandbox_artifacts.get("sandbox_backend"), str) + and bool(sandbox_artifacts.get("sandbox_backend")) + and isinstance(sandbox_artifacts.get("sandbox_profile_sha256"), str) + and len(sandbox_artifacts["sandbox_profile_sha256"]) == 64 + ) except (OSError, json.JSONDecodeError) as exc: sandbox_error = f"Required sandbox handoff evidence is missing or invalid: {exc}" if not sandbox_enforced and sandbox_error is None: @@ -609,7 +617,8 @@ def run_plan(plan: dict[str, Any], runs_dir: Path, state: dict[str, Any], use_wo progress = True # Stop after one actual agent invocation: review/approval is a gate. print(f"{task_id}: {record['status']} (exit={result.returncode}, checks={automated_checks['status']}, attempt={attempt})") - return 1 if result.returncode or automated_checks["status"] not in {"passed", "not_configured"} else 0 + return 1 if (result.returncode or sandbox_error or artifact_error + or automated_checks["status"] not in {"passed", "not_configured"}) else 0 save_state(state_path, state) return 0 From d39fe0cbd81eb6c623d8ae90e2656d9eb38e79ae Mon Sep 17 00:00:00 2001 From: wangzhizhou <824219521@qq.com> Date: Sun, 22 Nov 2026 12:46:25 +0800 Subject: [PATCH 14/23] security: bind review artifacts to enforced backend and profile evidence --- scripts/agent-orchestrate.py | 20 ++++++++++++++++++-- 1 file changed, 18 insertions(+), 2 deletions(-) diff --git a/scripts/agent-orchestrate.py b/scripts/agent-orchestrate.py index 79504a0..d88c180 100644 --- a/scripts/agent-orchestrate.py +++ b/scripts/agent-orchestrate.py @@ -383,9 +383,15 @@ def verify_change_evidence(repo: Path, record: dict[str, Any]) -> None: def publish_review_artifact(evidence: dict[str, Any], runs_dir: Path, - task_id: str, attempt: int) -> dict[str, Any]: + task_id: str, attempt: int, + sandbox_evidence: dict[str, Any] | None = None) -> dict[str, Any]: """Publish a portable immutable review snapshot after a sandboxed task has stopped.""" from artifact_broker import export_artifact + if (not isinstance(sandbox_evidence, dict) + or sandbox_evidence.get("sandbox_status") != "enforced" + or not sandbox_evidence.get("sandbox_backend") + or not re.fullmatch(r"[0-9a-f]{64}", str(sandbox_evidence.get("sandbox_profile_sha256", "")))): + raise ValueError("Review artifact publication requires verified sandbox backend and profile evidence.") source_dir = runs_dir / task_id / f".artifact-source-attempt-{attempt}" if source_dir.exists(): @@ -398,6 +404,11 @@ def publish_review_artifact(evidence: dict[str, Any], runs_dir: Path, shutil.copyfile(diff_source, source_dir / "review.diff") portable = dict(evidence) portable["diff_path"] = "review.diff" + portable["sandbox"] = { + "status": sandbox_evidence["sandbox_status"], + "backend": sandbox_evidence["sandbox_backend"], + "profile_sha256": sandbox_evidence["sandbox_profile_sha256"], + } portable.pop("evidence_path", None) acceptance = portable.get("acceptance", {}) checks = acceptance.get("automated_checks", {}) @@ -442,6 +453,10 @@ def verify_review_artifact(record: dict[str, Any]) -> dict[str, Any]: if not evidence_path or not Path(evidence_path).is_file(): raise ValueError("Original review evidence is missing.") original = json.loads(Path(evidence_path).read_text(encoding="utf-8")) + sandbox = artifact_evidence.get("sandbox", {}) + if (sandbox.get("status") != "enforced" or not sandbox.get("backend") + or not re.fullmatch(r"[0-9a-f]{64}", str(sandbox.get("profile_sha256", "")))): + raise ValueError("Review artifact is missing verified sandbox provenance.") if (artifact_evidence.get("task_id") != record.get("task_id") or artifact_evidence.get("fingerprint") != original.get("fingerprint") or artifact_evidence.get("base_commit") != original.get("base_commit") @@ -541,6 +556,7 @@ def run_plan(plan: dict[str, Any], runs_dir: Path, state: dict[str, Any], use_wo record["handoff"] = str(task_output) sandbox_enforced = not require_sandbox sandbox_error = None + sandbox_evidence = None if result.returncode == 0 and require_sandbox: try: handoff = json.loads(task_output.read_text(encoding="utf-8")) @@ -580,7 +596,7 @@ def run_plan(plan: dict[str, Any], runs_dir: Path, state: dict[str, Any], use_wo and automated_checks["status"] in {"passed", "not_configured"}): try: record["review_artifact"] = publish_review_artifact( - evidence, runs_dir, task_id, attempt, + evidence, runs_dir, task_id, attempt, sandbox_evidence, ) except (OSError, ValueError, RuntimeError) as exc: artifact_error = str(exc) From 89434ae11f0a92ea1e43bd7caa6da83bd7770476 Mon Sep 17 00:00:00 2001 From: wangzhizhou <824219521@qq.com> Date: Sun, 22 Nov 2026 12:46:43 +0800 Subject: [PATCH 15/23] fix: carry verified sandbox provenance into review artifact publisher --- scripts/agent-orchestrate.py | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/scripts/agent-orchestrate.py b/scripts/agent-orchestrate.py index d88c180..953e38e 100644 --- a/scripts/agent-orchestrate.py +++ b/scripts/agent-orchestrate.py @@ -570,6 +570,12 @@ def run_plan(plan: dict[str, Any], runs_dir: Path, state: dict[str, Any], use_wo ) except (OSError, json.JSONDecodeError) as exc: sandbox_error = f"Required sandbox handoff evidence is missing or invalid: {exc}" + if sandbox_enforced: + sandbox_evidence = { + "sandbox_status": sandbox_artifacts["sandbox_status"], + "sandbox_backend": sandbox_artifacts["sandbox_backend"], + "sandbox_profile_sha256": sandbox_artifacts["sandbox_profile_sha256"], + } if not sandbox_enforced and sandbox_error is None: sandbox_error = "Runner completed without an enforced sandbox status." automated_checks = {"status": "not_configured", "results": []} From d33c639c1ccdb6bd49d134dc28e66e4571fd4e33 Mon Sep 17 00:00:00 2001 From: wangzhizhou <824219521@qq.com> Date: Sun, 22 Nov 2026 12:46:47 +0800 Subject: [PATCH 16/23] test: provide verified sandbox provenance to artifact publisher --- tests/test_agent_orchestrator.py | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/tests/test_agent_orchestrator.py b/tests/test_agent_orchestrator.py index 08495f6..288e1d6 100644 --- a/tests/test_agent_orchestrator.py +++ b/tests/test_agent_orchestrator.py @@ -175,7 +175,14 @@ def test_review_artifact_is_portable_and_bound_to_review_evidence(self): } evidence_path = task_dir / "review-evidence.json" evidence_path.write_text(json.dumps(evidence), encoding="utf-8") - artifact = orchestrator.publish_review_artifact(evidence, runs, "task-a", 1) + artifact = orchestrator.publish_review_artifact( + evidence, runs, "task-a", 1, + { + "sandbox_status": "enforced", + "sandbox_backend": "test-backend", + "sandbox_profile_sha256": "b" * 64, + }, + ) record = { "task_id": "task-a", "review_evidence": str(evidence_path), From 378594e5cd636d421feb65cedf2e9c906c31a093 Mon Sep 17 00:00:00 2001 From: wangzhizhou <824219521@qq.com> Date: Sun, 22 Nov 2026 12:47:06 +0800 Subject: [PATCH 17/23] test: reject backends that cannot terminate task descendants --- tests/test_sandbox_runtime.py | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/tests/test_sandbox_runtime.py b/tests/test_sandbox_runtime.py index 5e048c0..c0aa3f9 100644 --- a/tests/test_sandbox_runtime.py +++ b/tests/test_sandbox_runtime.py @@ -5,6 +5,7 @@ import importlib.util import json import tempfile +from dataclasses import replace import unittest from pathlib import Path @@ -66,6 +67,11 @@ def build_environment(self, spec): return {"PATH": "/sandbox/bin", "HOME": "/sandbox/home"} +class LeakyBackend(FakeBackend): + def probe(self): + return replace(super().probe(), terminates_process_tree_on_exit=False) + + class SandboxRuntimeTests(unittest.TestCase): def test_doctor_fails_closed_when_no_backend_is_registered(self): doctor = sandbox.SandboxManager().doctor() @@ -73,6 +79,18 @@ def test_doctor_fails_closed_when_no_backend_is_registered(self): self.assertEqual(doctor["fallback"], "forbidden") self.assertEqual(doctor["backends"][0]["status"], "not-implemented") + def test_backend_without_descendant_cleanup_is_not_eligible(self): + with tempfile.TemporaryDirectory() as tmp: + profile_path = Path(tmp) / "profile.json" + profile_path.write_text(json.dumps(profile()), encoding="utf-8") + manager = sandbox.SandboxManager([LeakyBackend()]) + with self.assertRaises(sandbox.SandboxBackendUnavailable): + manager.build_command( + ["agent"], profile_path, "task-1", Path(tmp), Path(tmp) / "runtime", + {"repository_read": True, "repository_write": True, + "network_access": False, "secret_access": False} + ) + def test_valid_profile_has_stable_digest(self): with tempfile.TemporaryDirectory() as tmp: path = Path(tmp) / "profile.json" From 9fa432543506c52e09844b053c85c7c5dbf55564 Mon Sep 17 00:00:00 2001 From: wangzhizhou <824219521@qq.com> Date: Sun, 22 Nov 2026 12:47:08 +0800 Subject: [PATCH 18/23] docs: name process-tree cleanup capability in backend contract --- .ai/runtime/sandbox/LAUNCHER-CONTRACT.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.ai/runtime/sandbox/LAUNCHER-CONTRACT.md b/.ai/runtime/sandbox/LAUNCHER-CONTRACT.md index 9c39d31..f61c5ee 100644 --- a/.ai/runtime/sandbox/LAUNCHER-CONTRACT.md +++ b/.ai/runtime/sandbox/LAUNCHER-CONTRACT.md @@ -26,7 +26,7 @@ The manager rejects partial backends. A backend must not claim support based on Implemented in `scripts/sandbox_runtime.py`: -- `SandboxBackend.probe() -> SandboxCapabilities` +- `SandboxBackend.probe() -> SandboxCapabilities` (must prove both process-tree inheritance and descendant cleanup on task exit) - `SandboxBackend.build_command(command, spec) -> argv` - `SandboxBackend.build_environment(spec) -> minimal env` - `SandboxManager.doctor()` From 9056921b628a8c12f1607fed9461928eaa041303 Mon Sep 17 00:00:00 2001 From: wangzhizhou <824219521@qq.com> Date: Sun, 22 Nov 2026 12:47:12 +0800 Subject: [PATCH 19/23] docs: clarify backend descendant cleanup is a mandatory capability --- .ai/runtime/artifacts/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.ai/runtime/artifacts/README.md b/.ai/runtime/artifacts/README.md index 45b1509..3a9711d 100644 --- a/.ai/runtime/artifacts/README.md +++ b/.ai/runtime/artifacts/README.md @@ -4,7 +4,7 @@ The Artifact Broker is the target trusted control-plane utility for file exchange between Agent tasks, reviewers and the integrator. The standalone CLI and immutable storage contract are implemented. Orchestrator integration now exports a review artifact only for sandbox-required tasks after the Runner and sandboxed acceptance checks complete; approval and integration re-verify the artifact and bind it to the current review fingerprint. Agents must not share writable directories. -The broker must run after the producing Agent and its descendants have stopped. The sandbox backend contract now requires termination of every task descendant before the launcher reports completion. Exporting a workspace while any Agent or check process is still writing creates a time-of-check/time-of-use race and does not produce a reliable snapshot. The broker validates source paths and file metadata, but a frozen source workspace is an operational precondition. +The broker must run after the producing Agent and its descendants have stopped. The sandbox backend contract now requires both process-tree isolation and termination of every task descendant before the launcher reports completion; the Manager rejects backends that cannot prove both. Exporting a workspace while any Agent or check process is still writing creates a time-of-check/time-of-use race and does not produce a reliable snapshot. The broker validates source paths and file metadata, but a frozen source workspace is an operational precondition. ## Artifact format From 14a9c22404b98fdc640c39bfdbab5883798fc263 Mon Sep 17 00:00:00 2001 From: wangzhizhou <824219521@qq.com> Date: Sun, 22 Nov 2026 12:47:26 +0800 Subject: [PATCH 20/23] security: validate sandbox profile digest as hexadecimal SHA-256 --- scripts/agent-orchestrate.py | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/scripts/agent-orchestrate.py b/scripts/agent-orchestrate.py index 953e38e..2640898 100644 --- a/scripts/agent-orchestrate.py +++ b/scripts/agent-orchestrate.py @@ -565,8 +565,7 @@ def run_plan(plan: dict[str, Any], runs_dir: Path, state: dict[str, Any], use_wo sandbox_artifacts.get("sandbox_status") == "enforced" and isinstance(sandbox_artifacts.get("sandbox_backend"), str) and bool(sandbox_artifacts.get("sandbox_backend")) - and isinstance(sandbox_artifacts.get("sandbox_profile_sha256"), str) - and len(sandbox_artifacts["sandbox_profile_sha256"]) == 64 + and re.fullmatch(r"[0-9a-f]{64}", str(sandbox_artifacts.get("sandbox_profile_sha256", ""))) ) except (OSError, json.JSONDecodeError) as exc: sandbox_error = f"Required sandbox handoff evidence is missing or invalid: {exc}" From eff9448d22631c249ddb4d825ced4e176f065db6 Mon Sep 17 00:00:00 2001 From: wangzhizhou <824219521@qq.com> Date: Sun, 22 Nov 2026 12:47:59 +0800 Subject: [PATCH 21/23] test: clean up read-only artifacts from orchestrator integration tests --- tests/test_agent_orchestrator.py | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/tests/test_agent_orchestrator.py b/tests/test_agent_orchestrator.py index 288e1d6..57463be 100644 --- a/tests/test_agent_orchestrator.py +++ b/tests/test_agent_orchestrator.py @@ -6,6 +6,7 @@ import importlib.util import io import json +import os import subprocess import sys import tempfile @@ -30,6 +31,19 @@ def item(task_id, deps=None): class OrchestratorTests(unittest.TestCase): + def make_writable(self, root: Path) -> None: + for current, directories, files in os.walk(root, topdown=False): + current_path = Path(current) + for name in files: + path = current_path / name + if not path.is_symlink(): + os.chmod(path, 0o600) + for name in directories: + path = current_path / name + if not path.is_symlink(): + os.chmod(path, 0o700) + os.chmod(current_path, 0o700) + def test_allowlisted_acceptance_check_runs_and_persists_logs(self): with tempfile.TemporaryDirectory() as tmp: workspace = Path(tmp) / "workspace" @@ -153,6 +167,7 @@ def test_sandboxed_acceptance_checks_fail_closed_without_backend(self): def test_review_artifact_is_portable_and_bound_to_review_evidence(self): with tempfile.TemporaryDirectory() as tmp: root = Path(tmp) + self.addCleanup(self.make_writable, root) runs = root / "runs" task_dir = runs / "task-a" task_dir.mkdir(parents=True) From a1bf5d118cc7621028858b5fb6430665090a3f1a Mon Sep 17 00:00:00 2001 From: wangzhizhou <824219521@qq.com> Date: Sun, 22 Nov 2026 12:48:13 +0800 Subject: [PATCH 22/23] security: bind artifact to complete review checks and reject evidence symlinks --- scripts/agent-orchestrate.py | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/scripts/agent-orchestrate.py b/scripts/agent-orchestrate.py index 2640898..cf24b05 100644 --- a/scripts/agent-orchestrate.py +++ b/scripts/agent-orchestrate.py @@ -450,16 +450,17 @@ def verify_review_artifact(record: dict[str, Any]) -> dict[str, Any]: raise ValueError("Review artifact manifest does not match the task journal.") artifact_evidence = json.loads((artifact_dir / "review-evidence.json").read_text(encoding="utf-8")) evidence_path = record.get("review_evidence") - if not evidence_path or not Path(evidence_path).is_file(): - raise ValueError("Original review evidence is missing.") + if not evidence_path or Path(evidence_path).is_symlink() or not Path(evidence_path).is_file(): + raise ValueError("Original review evidence is missing or unsafe.") original = json.loads(Path(evidence_path).read_text(encoding="utf-8")) sandbox = artifact_evidence.get("sandbox", {}) if (sandbox.get("status") != "enforced" or not sandbox.get("backend") or not re.fullmatch(r"[0-9a-f]{64}", str(sandbox.get("profile_sha256", "")))): raise ValueError("Review artifact is missing verified sandbox provenance.") - if (artifact_evidence.get("task_id") != record.get("task_id") - or artifact_evidence.get("fingerprint") != original.get("fingerprint") - or artifact_evidence.get("base_commit") != original.get("base_commit") + comparable_fields = ("task_id", "fingerprint", "base_commit", "changed_files", "diff_stat", "diff_check") + if (any(artifact_evidence.get(field) != original.get(field) for field in comparable_fields) + or artifact_evidence.get("acceptance", {}).get("automated_checks", {}).get("status") + != original.get("acceptance", {}).get("automated_checks", {}).get("status") or manifest.get("source_revision") != original.get("base_commit")): raise ValueError("Immutable review artifact is not bound to the current task evidence.") return manifest From ad6d0950ebd478e29eca84548a8cca9149fcb520 Mon Sep 17 00:00:00 2001 From: wangzhizhou <824219521@qq.com> Date: Sun, 22 Nov 2026 12:48:48 +0800 Subject: [PATCH 23/23] security: skip host evidence capture when sandbox enforcement is unverified --- scripts/agent-orchestrate.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/scripts/agent-orchestrate.py b/scripts/agent-orchestrate.py index cf24b05..c3cd988 100644 --- a/scripts/agent-orchestrate.py +++ b/scripts/agent-orchestrate.py @@ -592,7 +592,8 @@ def run_plan(plan: dict[str, Any], runs_dir: Path, state: dict[str, Any], use_wo automated_checks = {"status": "failed", "results": [], "error": str(exc)} record["automated_checks"] = automated_checks artifact_error = None - if use_worktrees and record.get("base_commit"): + if (use_worktrees and record.get("base_commit") + and sandbox_error is None and (not require_sandbox or sandbox_enforced)): evidence = collect_change_evidence( workspace, record["base_commit"], task_id, runs_dir, automated_checks=automated_checks,