diff --git a/.ai/runtime/sandbox/PODMAN-ROOTLESS.md b/.ai/runtime/sandbox/PODMAN-ROOTLESS.md index e81d347..13ec502 100644 --- a/.ai/runtime/sandbox/PODMAN-ROOTLESS.md +++ b/.ai/runtime/sandbox/PODMAN-ROOTLESS.md @@ -1,21 +1,23 @@ -# Linux Rootless Podman Backend (M4.4.1–M4.4.2) +# Linux Rootless Podman Backend (M4.4.1–M4.4.3) -This backend is intentionally narrow: Linux, rootless Podman, cgroup v2, systemd user-service delegation, and delegated cpu/memory/pids controllers. It refuses rootful Podman, cgroup v1, missing subordinate UID/GID mappings, missing resource controllers, mutable image tags, and shared Git worktree pointer files. +This backend is intentionally narrow: Linux, rootless Podman, cgroup v2, systemd user-service delegation, and delegated cpu/memory/pids controllers. It refuses rootful Podman, cgroup v1, missing subordinate UID/GID mappings, missing resource controllers, mutable image tags, and shared Git worktree metadata. ## Runtime image -Every profile must set `runtime.backend=linux-rootless-oci` and an immutable OCI reference of the form `registry/name@sha256:<64 lowercase hex>`. The image must already exist in rootless Podman's local image store; launch uses `--pull=never`. The example uses a syntactically valid placeholder digest only; it is not a published or verified image. +Every profile must set runtime.backend=linux-rootless-oci and an immutable OCI reference of the form registry/name@sha256:<64 lowercase hex>. The image must already exist in rootless Podman's local image store; launch uses --pull=never. The example uses a syntactically valid placeholder digest only; it is not a published or verified image. ## Launch boundary -The launcher applies rootless user namespaces, private PID/network/IPC/cgroup namespaces, `network=none`, read-only container root, dropped capabilities, no-new-privileges, private tmpfs mounts, one task-workspace bind mount, and explicit CPU/memory/PID limits. The Agent receives a minimal container environment. No host credentials, host home, shared Git metadata, or runtime socket are mounted. +The launcher applies rootless user namespaces, private PID/network/IPC/cgroup namespaces, network=none, read-only container root, dropped capabilities, no-new-privileges, private tmpfs mounts, one task-workspace bind mount, and explicit CPU/memory/PID limits. The Agent receives a minimal container environment. No host credentials, host home, shared Git metadata, or runtime socket are mounted. The trusted Podman client receives only the environment required for its rootless runtime. Egress proxy and scoped-secret broker are not implemented; profiles requesting either remain ineligible. -## Git metadata +## Git metadata isolation -A worktree whose `.git` is a pointer file is rejected. Use an independent clone with its own `.git` directory, or make the Agent produce patches without Git metadata. Never mount the host shared Git common directory into the container. +When Orchestrator runs with both --require-sandbox and --worktrees, it creates a full independent clone with git clone --no-hardlinks --no-local, restricted to the current source branch. It removes the clone's origin remote, assigns a non-personal local commit identity, and verifies that .git is a private directory without commondir or object alternates. The container mounts the entire independent task clone read/write, including its private .git directory, so the Agent can create the commit consumed by the existing Integrator flow. This is safe only because the clone has its own object database and refs, no origin remote, and no shared common-dir or object alternates; it is not the stable repository. The container cannot access the stable checkout. Git global/system configuration and terminal prompts are disabled, and hooks are configured off when the clone is created. Any task-local Git writes remain confined to the disposable sandbox. + +Legacy non-sandboxed task runs continue using linked Git Worktrees. Sandbox-required runs persist workspace_mode=independent-clone in the external journal and reject resumes with a mismatched workspace mode. During integration, the trusted Orchestrator fetches the approved commit from the clone into the stable repository before cherry-picking it. The clone is never allowed to write the stable repository's refs or object store. ## Verification status -Unit tests cover launcher argv construction, image pinning, Git pointer rejection and environment shaping. They do not prove kernel enforcement. M4.4.4 still requires a dedicated Linux worker conformance suite against the actual Podman, cgroup and systemd configuration. +CI unit tests cover clone metadata independence, workspace reuse, commit import, launcher argv construction, image pinning, and environment shaping. They do not prove kernel enforcement. M4.4.4 still requires a dedicated Linux worker conformance suite against the actual Podman, cgroup and systemd configuration. diff --git a/scripts/agent-orchestrate.py b/scripts/agent-orchestrate.py index c3cd988..184878c 100644 --- a/scripts/agent-orchestrate.py +++ b/scripts/agent-orchestrate.py @@ -258,44 +258,88 @@ def git_output(repo: Path, *args: str) -> str: def prepare_worktree(repo: Path, runs_dir: Path, task_id: str, - record: dict[str, Any]) -> Path: - """Create or validate a detached worktree dedicated to one task.""" + record: dict[str, Any], independent_clone: bool = False) -> Path: + """Create or validate an isolated task workspace. + + Sandbox-required tasks use a full independent clone so the container never + receives a Git worktree pointer or shared object/ref database. + """ + mode = "independent-clone" if independent_clone else "linked-worktree" if record.get("worktree"): path = Path(record["worktree"]).resolve() if not path.is_dir(): raise ValueError(task_id + ": recorded worktree is missing; inspect journal before recovery.") + if record.get("workspace_mode", "linked-worktree") != mode: + raise ValueError(task_id + ": recorded workspace mode differs from this run; recreate the task workspace deliberately.") top = Path(git_output(path, "rev-parse", "--show-toplevel")).resolve() + git_dir = Path(git_output(path, "rev-parse", "--absolute-git-dir")).resolve() common = Path(git_output(path, "rev-parse", "--git-common-dir")) if not common.is_absolute(): common = (path / common).resolve() else: common = common.resolve() - expected_common = Path(git_output(repo, "rev-parse", "--git-common-dir")) - if not expected_common.is_absolute(): - expected_common = (repo / expected_common).resolve() + if top != path: + raise ValueError(task_id + ": recorded workspace has an unexpected Git top-level.") + if independent_clone: + if git_dir != (path / ".git").resolve() or common != git_dir: + raise ValueError(task_id + ": sandbox workspace does not have independent Git metadata.") + if (git_dir / "commondir").exists() or (git_dir / "objects/info/alternates").exists(): + raise ValueError(task_id + ": sandbox workspace references shared Git metadata.") + if git_output(path, "remote"): + raise ValueError(task_id + ": sandbox workspace must not retain host repository remotes.") else: - expected_common = expected_common.resolve() - if top != path or common != expected_common: - raise ValueError(task_id + ": recorded path is not a worktree of this repository.") + expected_common = Path(git_output(repo, "rev-parse", "--git-common-dir")) + if not expected_common.is_absolute(): + expected_common = (repo / expected_common).resolve() + else: + expected_common = expected_common.resolve() + if common != expected_common: + raise ValueError(task_id + ": recorded path is not a worktree of this repository.") return path run_key = hashlib.sha256(str(runs_dir.resolve()).encode("utf-8")).hexdigest()[:12] - path = (repo.parent / ("." + repo.name + "-agent-worktrees") / run_key / task_id).resolve() + suffix = "-agent-sandboxes" if independent_clone else "-agent-worktrees" + path = (repo.parent / ("." + repo.name + suffix) / run_key / task_id).resolve() if path.exists(): - raise ValueError(task_id + ": worktree path already exists but is not recorded: " + str(path)) + raise ValueError(task_id + ": task workspace path already exists but is not recorded: " + str(path)) path.parent.mkdir(parents=True, exist_ok=True) base_commit = git_output(repo, "rev-parse", "HEAD") - result = subprocess.run( - ["git", "worktree", "add", "--detach", str(path), base_commit], - cwd=repo, text=True, capture_output=True, check=False, - ) - if result.returncode: - raise ValueError(task_id + ": cannot create worktree: " + result.stderr.strip()) + if independent_clone: + branch = git_output(repo, "branch", "--show-current") + if not branch: + raise ValueError(task_id + ": independent sandbox clone requires a checked-out source branch.") + result = subprocess.run( + ["git", "clone", "--no-hardlinks", "--no-local", "--no-tags", + "--single-branch", "--branch", branch, "--no-checkout", str(repo), str(path)], + cwd=repo.parent, text=True, capture_output=True, check=False, + ) + if result.returncode: + shutil.rmtree(path, ignore_errors=True) + raise ValueError(task_id + ": cannot create independent clone: " + result.stderr.strip()) + try: + git_output(path, "checkout", "--detach", base_commit) + git_output(path, "remote", "remove", "origin") + git_output(path, "config", "user.name", "EasyProject Agent") + git_output(path, "config", "user.email", "agent@localhost.invalid") + git_output(path, "config", "core.hooksPath", os.devnull) + git_dir = (path / ".git").resolve() + if (git_dir / "commondir").exists() or (git_dir / "objects/info/alternates").exists(): + raise ValueError("Independent clone unexpectedly contains shared Git metadata.") + except Exception: + shutil.rmtree(path, ignore_errors=True) + raise + else: + result = subprocess.run( + ["git", "worktree", "add", "--detach", str(path), base_commit], + cwd=repo, text=True, capture_output=True, check=False, + ) + if result.returncode: + raise ValueError(task_id + ": cannot create worktree: " + result.stderr.strip()) record["worktree"] = str(path) record["base_commit"] = base_commit + record["workspace_mode"] = mode return path - def collect_change_evidence(repo: Path, base_commit: str, task_id: str, runs_dir: Path, persist: bool = True, automated_checks: dict[str, Any] | None = None) -> dict[str, Any]: @@ -527,7 +571,10 @@ def run_plan(plan: dict[str, Any], runs_dir: Path, state: dict[str, Any], use_wo attempt = record["attempts"] + 1 task_output = runs_dir / task_id / f"attempt-{attempt}.handoff.json" task_output.parent.mkdir(parents=True, exist_ok=True) - workspace = prepare_worktree(ROOT, runs_dir, task_id, record) if use_worktrees else ROOT + workspace = prepare_worktree( + ROOT, runs_dir, task_id, record, + independent_clone=bool(state.get("sandbox_required", False)), + ) if use_worktrees else ROOT cancel_file = runs_dir / task_id / f"cancel-attempt-{attempt}.request" task_envelope = json.loads(task_path.read_text(encoding="utf-8")) harness = item.get("harness", "codex") @@ -798,6 +845,14 @@ def integrate_task(repo: Path, task_id: str, state: dict[str, Any], if git_output(repo, "rev-parse", "HEAD") != target_head: raise ValueError("Target branch moved during integration; inspect the repository and retry.") subject = f"Agent task {task_id}" + if record.get("workspace_mode") == "independent-clone": + fetched = git_result(repo, "fetch", "--no-tags", str(worktree), "HEAD") + if fetched.returncode: + raise ValueError("Cannot import approved commit from independent task clone: " + fetched.stderr.strip()) + present = git_result(repo, "cat-file", "-e", agent_commit + "^{commit}") + if present.returncode: + raise ValueError("Approved commit was not imported from the independent task clone.") + cherry_pick = git_result(repo, "cherry-pick", agent_commit) if cherry_pick.returncode: record.update( diff --git a/scripts/sandbox_backends/podman_rootless.py b/scripts/sandbox_backends/podman_rootless.py index f0279ce..c3acf70 100644 --- a/scripts/sandbox_backends/podman_rootless.py +++ b/scripts/sandbox_backends/podman_rootless.py @@ -140,9 +140,9 @@ def build_command(self, command: Sequence[str], spec: SandboxLaunchSpec) -> list git = workspace / ".git" if git.is_symlink() or git.is_file(): raise SandboxEnforcementError("Git worktree pointer or symlink detected; shared Git metadata is forbidden.") - if git.exists() and not git.is_dir(): - raise SandboxEnforcementError("Unsupported .git metadata type.") - if git.is_dir() and ((git / "commondir").exists() or (git / "objects/info/alternates").exists()): + if not git.is_dir(): + raise SandboxEnforcementError("Sandbox workspace requires a private .git directory.") + if (git / "commondir").exists() or (git / "objects/info/alternates").exists(): raise SandboxEnforcementError("Shared Git common directory or object alternates are forbidden.") fs = spec.profile["filesystem"] if not fs["workspace_read"]: @@ -164,10 +164,16 @@ def build_command(self, command: Sequence[str], spec: SandboxLaunchSpec) -> list "--stop-timeout=5", "--ulimit=core=0", "--tmpfs", "/tmp:rw,noexec,nosuid,nodev,size=256m", "--tmpfs", "/home/sandbox:rw,noexec,nosuid,nodev,size=64m", + # The task clone has private Git metadata (no shared refs/objects/remotes). + # Keep it writable so the Agent can create the commit consumed by Integrator. + # The entire clone remains inside this task sandbox and cannot reach stable refs. "--mount", f"type=bind,src={workspace},dst=/workspace,{mode}", + "--mount", f"type=bind,src={git},dst=/workspace/.git,ro", "--workdir=/workspace", "--env=PATH=/usr/local/bin:/usr/bin:/bin", "--env=HOME=/home/sandbox", "--env=TMPDIR=/tmp", "--env=LANG=C.UTF-8", "--env=LC_ALL=C.UTF-8", "--env=CI=1", + "--env=GIT_OPTIONAL_LOCKS=0", "--env=GIT_CONFIG_NOSYSTEM=1", + "--env=GIT_CONFIG_GLOBAL=/dev/null", "--env=GIT_TERMINAL_PROMPT=0", image, *command, ] diff --git a/tasks/evolution/M4-sandbox-runtime.md b/tasks/evolution/M4-sandbox-runtime.md index dcea11c..f7e49f9 100644 --- a/tasks/evolution/M4-sandbox-runtime.md +++ b/tasks/evolution/M4-sandbox-runtime.md @@ -7,10 +7,10 @@ Introduce OS-enforced, task-scoped isolation so multiple cooperating Agents cann ## Current baseline - Git Worktrees isolate source trees from accidental edits but do not restrict process access to the host. -- `scripts/agent-run.py` is a process dispatcher, not a sandbox. -- Codex has an OS-enforced sandbox mode; Claude Code's Bash sandbox does not cover all built-in tools and helpers. -- Pi's tool allowlist is not a security boundary. The current Evolution path automatically adds `harness_options.pi_unsandboxed_write=true`, which is not genuine human opt-in and must be removed in M4.1. -- The repository has task orchestration, approval artifacts, cancellation and review evidence. The Linux Rootless Podman launcher is now implemented behind a fail-closed capability probe; kernel-level conformance is still pending. +- scripts/agent-run.py is a process dispatcher, not a sandbox. +- Pi's tool allowlist is not a security boundary. Unsafe Pi writes require explicit opt-in or a mandatory OS sandbox. +- The repository has task orchestration, approval artifacts, cancellation and review evidence. The Linux Rootless Podman launcher is implemented behind a fail-closed capability probe; kernel-level conformance is still pending. +- Sandbox-required task workspaces now use independent Git clones instead of linked Git Worktrees, keeping shared Git metadata outside the container boundary. ## Work breakdown @@ -24,18 +24,18 @@ Introduce OS-enforced, task-scoped isolation so multiple cooperating Agents cann | 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.1 | Rootless Podman capability probe | Verify rootless mode, subordinate UID/GID mappings, cgroup v2, systemd delegation and cpu/memory/pids controllers | | M4.4.2 | Rootless OCI launcher | Pinned image, network none, namespaces, read-only rootfs, workspace-only mount, limits, sanitized Agent environment | -| M4.4.3 | Git metadata isolation | Reject shared worktree pointer metadata; move toward independent task clones or patch-only Agent workspaces | +| M4.4.3 | Independent Git metadata | Sandbox-required tasks use independent clones; reject shared Git common-dir and object alternates; Integrator imports reviewed commits explicitly | | M4.4.4 | Linux conformance suite | Prove filesystem, network, process-tree and effective resource enforcement on a dedicated Linux worker | | 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 | ## Backend decision -The platform selection and prerequisites are recorded in [ADR-001: Production Sandbox Backend Selection](../../.ai/runtime/sandbox/ADR-001-backend-selection.md). Linux Rootless Podman is the primary full-profile backend; macOS Seatbelt is a possible weaker local profile, not a full-profile substitute. The first Linux backend must also solve shared Git metadata isolation and use a pinned runtime image. Hosted-model credentials remain blocked until M4.6. +The platform selection and prerequisites are recorded in [ADR-001: Production Sandbox Backend Selection](../../.ai/runtime/sandbox/ADR-001-backend-selection.md). Linux Rootless Podman is the primary full-profile backend; macOS Seatbelt is a possible weaker local profile, not a full-profile substitute. Hosted-model credentials remain blocked until M4.6. ## Execution order -M4.0 is documentation and schema only. M4.1 is merged. M4.2a defines the backend interface and fail-closed launch path, but does not provide OS enforcement. M4.2b records the platform decision. M4.3a/b artifact exchange is complete. M4.4.1/4.4.2 now provide a conservative Rootless Podman probe and launcher, but M4.4 remains incomplete until independent Git metadata handling and dedicated Linux kernel-conformance tests pass. The backend deliberately does not support network egress or credential brokering; those remain M4.6 work. +M4.0–M4.3 are complete. M4.4.1/4.4.2 provide a conservative Rootless Podman probe and launcher. M4.4.3 switches sandbox-required tasks to independent Git clones and explicitly transfers approved commits into the trusted repository during integration. M4.4 remains incomplete until M4.4.4 proves filesystem, network, process-tree and effective cgroup enforcement on a dedicated Linux worker. The backend deliberately does not support network egress or credential brokering; those remain M4.6 work. ## Explicit non-goals diff --git a/tests/test_agent_orchestrator.py b/tests/test_agent_orchestrator.py index 2c71d06..3134c68 100644 --- a/tests/test_agent_orchestrator.py +++ b/tests/test_agent_orchestrator.py @@ -319,6 +319,35 @@ def test_worktree_is_created_and_reused_for_same_task(self): check=True, capture_output=True, text=True).stdout.strip() self.assertEqual(top, str(worktree)) + def test_sandbox_workspace_uses_independent_clone_and_imports_commits(self): + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) / "repo" + root.mkdir() + subprocess.run(["git", "init", "-q", str(root)], check=True) + subprocess.run(["git", "-C", str(root), "config", "user.name", "Test"], check=True) + subprocess.run(["git", "-C", str(root), "config", "user.email", "test@example.com"], check=True) + (root / "README.md").write_text("initial\\n", encoding="utf-8") + subprocess.run(["git", "-C", str(root), "add", "README.md"], check=True) + subprocess.run(["git", "-C", str(root), "commit", "-qm", "initial"], check=True) + record = {"worktree": None, "base_commit": None} + runs = Path(tmp) / "runs" + workspace = orchestrator.prepare_worktree(root, runs, "sandbox-task", record, independent_clone=True) + git_dir = workspace / ".git" + self.assertTrue(git_dir.is_dir()) + self.assertFalse(git_dir.is_symlink()) + self.assertFalse((git_dir / "commondir").exists()) + self.assertFalse((git_dir / "objects/info/alternates").exists()) + self.assertEqual(orchestrator.git_output(workspace, "rev-parse", "--git-common-dir"), ".git") + self.assertEqual(orchestrator.git_output(workspace, "remote"), "") + self.assertEqual(orchestrator.git_output(workspace, "config", "core.hooksPath"), os.devnull) + self.assertEqual(record["workspace_mode"], "independent-clone") + self.assertEqual(orchestrator.prepare_worktree(root, runs, "sandbox-task", record, independent_clone=True), workspace) + (workspace / "README.md").write_text("agent change\\n", encoding="utf-8") + orchestrator.git_output(workspace, "add", "README.md") + orchestrator.git_output(workspace, "commit", "-m", "agent change") + agent_commit = orchestrator.git_output(workspace, "rev-parse", "HEAD") + subprocess.run(["git", "fetch", "--no-tags", str(workspace), "HEAD"], cwd=root, check=True, capture_output=True, text=True) + subprocess.run(["git", "cat-file", "-e", agent_commit + "^{commit}"], cwd=root, check=True) def test_worktree_rejects_missing_recorded_path(self): with tempfile.TemporaryDirectory() as tmp: root = Path(tmp) / "repo" diff --git a/tests/test_sandbox_podman.py b/tests/test_sandbox_podman.py index b13dd48..35d70be 100644 --- a/tests/test_sandbox_podman.py +++ b/tests/test_sandbox_podman.py @@ -13,6 +13,8 @@ SPEC.loader.exec_module(podman) from sandbox_runtime import SandboxLaunchSpec, SandboxEnforcementError def spec_for(ws,writable=True,image=None): + ws.mkdir(parents=True,exist_ok=True) + if not (ws/".git").exists(): (ws/".git").mkdir() profile={"runtime":{"backend":"linux-rootless-oci","image":image or ("registry.example/agent@sha256:"+"a"*64)},"filesystem":{"workspace_read":True,"workspace_write":writable},"process":{"max_memory_mb":2048,"max_cpu":2,"max_processes":128},"network":{"default":"deny"}} return SandboxLaunchSpec("task-1",profile,"b"*64,ws,ws/"runtime",600) class PodmanTests(unittest.TestCase): @@ -20,7 +22,7 @@ def test_rootless_private_networkless_and_limits(self): with tempfile.TemporaryDirectory() as tmp: ws=Path(tmp)/"ws"; ws.mkdir() cmd=podman.RootlessPodmanBackend("/usr/bin/podman").build_command(["python","-m","pytest"],spec_for(ws)); joined=" ".join(cmd) - for flag in ("--userns=keep-id","--network=none","--pid=private","--read-only","--cap-drop=ALL","--security-opt=no-new-privileges","--pids-limit=128","--memory=2048m","--cpus=2","--pull=never","dst=/workspace,rw"): self.assertIn(flag,joined) + for flag in ("--userns=keep-id","--network=none","--pid=private","--read-only","--cap-drop=ALL","--security-opt=no-new-privileges","--pids-limit=128","--memory=2048m","--cpus=2","--pull=never","dst=/workspace,rw","dst=/workspace/.git,ro","GIT_OPTIONAL_LOCKS=0"): self.assertIn(flag,joined) self.assertEqual(cmd[-3:],["python","-m","pytest"]) def test_read_only_workspace(self): with tempfile.TemporaryDirectory() as tmp: @@ -29,6 +31,10 @@ def test_git_worktree_pointer_rejected(self): with tempfile.TemporaryDirectory() as tmp: ws=Path(tmp); (ws/".git").write_text("gitdir: /shared/.git/worktrees/task") with self.assertRaises(SandboxEnforcementError): podman.RootlessPodmanBackend().build_command(["true"],spec_for(ws)) + def test_shared_git_common_directory_is_rejected(self): + with tempfile.TemporaryDirectory() as tmp: + ws=Path(tmp); (ws/".git").mkdir(); (ws/".git"/"commondir").write_text("../shared") + with self.assertRaises(SandboxEnforcementError): podman.RootlessPodmanBackend().build_command(["true"],spec_for(ws)) def test_mutable_image_rejected(self): with tempfile.TemporaryDirectory() as tmp: for image in ("agent:latest","agent:1.0","agent@sha256:abc"):