oficina / equipo Public

feat: contain attempts in owned bubblewrap namespaces

codex agent, operated by paul@keymail.dev pushed by claude agent, operated by paul@keymail.dev 5c1de26e4f9e6c2f819f91dab710eace223963f0 parent c87a6f2
14 files changed, +3,604 −3
  • .amadan/ci.d/36-runner-namespaces +2 −0
  • Makefile +7 −2
  • cmd/equipo-runner/main.go +3 −0
  • cmd/equipo-runner/namespace.go +5 −0
  • docs/superpowers/plans/CONTROLLER-REPORT-plan-2b.md +1,739 −0
  • internal/equipotest/foundation_test.go +1 −1
  • internal/runner/containment/budget_test.go +18 −0
  • internal/runner/containment/linux.go +452 −0
  • internal/runner/containment/linux_test.go +636 −0
  • internal/runner/containment/mounts.go +183 −0
  • internal/runner/containment/mounts_test.go +76 −0
  • internal/runner/containment/recovery.go +206 −0
  • internal/runner/containment/recovery_test.go +255 −0
  • internal/runnerproto/containment.go +21 −0

CI passed — run details

diff --git a/.amadan/ci.d/36-runner-namespaces b/.amadan/ci.d/36-runner-namespaces
new file mode 100755
index 00000000..88d7bf45
--- /dev/null
+++ b/.amadan/ci.d/36-runner-namespaces
@@ -0,0 +1,2 @@
+#!/bin/sh
+exec make runner-namespace-test
diff --git a/Makefile b/Makefile
index 3e5e3209..2e43249e 100644
--- a/Makefile
+++ b/Makefile
@@ -24,7 +24,7 @@ RELEASE_BIN := releases/$(APP)-$(RELEASE_GOOS)-$(RELEASE_GOARCH)
# and a suite running beside it would be measured too.
.NOTPARALLEL:
-.PHONY: build release test vet fmt-check staticcheck govulncheck gitleaks budget perf migration-check runner-adapter-test ci
+.PHONY: build release test vet fmt-check staticcheck govulncheck gitleaks budget perf migration-check runner-adapter-test runner-namespace-test ci
RASTRILLO := go run amadan.net/rastrillo/rastrillo/cmd/rastrillo
@@ -135,6 +135,11 @@ migration-check:
runner-prerequisites:
@test "$$(node --version)" = "v24.19.0"
@test "$$(codex --version)" = "codex-cli 0.165.0"
+ @test "$$(/usr/bin/bwrap --version)" = "bubblewrap 0.11.0"
+
+runner-namespace-test:
+ @test "$$(/usr/bin/bwrap --version)" = "bubblewrap 0.11.0"
+ CGO_ENABLED=0 go test ./internal/runner/containment -run '^TestNamespace' -count=1
runner-adapter-test: runner-prerequisites
command -v node
@@ -151,7 +156,7 @@ runner-adapter-test: runner-prerequisites
# fails the build the moment models.go and migrations/ disagree,
# instead of at boot on whatever machine notices next. If the app
# declares manifest resources, also add: rastrillo generate --check
-ci: build vet fmt-check staticcheck govulncheck gitleaks budget test runner-adapter-test migration-check perf
+ci: build vet fmt-check staticcheck govulncheck gitleaks budget test runner-adapter-test runner-namespace-test migration-check perf
.PHONY: copy-release-check release-runner runner-prerequisites
copy-release-check:
diff --git a/cmd/equipo-runner/main.go b/cmd/equipo-runner/main.go
index 5db2643a..ebe329eb 100644
--- a/cmd/equipo-runner/main.go
+++ b/cmd/equipo-runner/main.go
@@ -70,6 +70,9 @@ func run(ctx context.Context, args []string, input io.Reader, output, errorOutpu
return 0
}
func main() {
+ if len(os.Args) > 1 && os.Args[1] == "__namespace" {
+ os.Exit(namespace(os.Args[2:]))
+ }
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
code := run(ctx, os.Args[1:], os.Stdin, os.Stdout, os.Stderr, os.Getenv)
stop()
diff --git a/cmd/equipo-runner/namespace.go b/cmd/equipo-runner/namespace.go
new file mode 100644
index 00000000..19e9b3a2
--- /dev/null
+++ b/cmd/equipo-runner/namespace.go
@@ -0,0 +1,5 @@
+package main
+
+import "amadan.net/oficina/equipo/internal/runner/containment"
+
+func namespace(args []string) int { return containment.NamespaceMain(args) }
diff --git a/docs/superpowers/plans/CONTROLLER-REPORT-plan-2b.md b/docs/superpowers/plans/CONTROLLER-REPORT-plan-2b.md
index 3dfbdc1e..a9964557 100644
--- a/docs/superpowers/plans/CONTROLLER-REPORT-plan-2b.md
+++ b/docs/superpowers/plans/CONTROLLER-REPORT-plan-2b.md
@@ -637,3 +637,1742 @@ No UI strings, README prose or copy.go entries were added. New internal diagnost
No unresolved Task 1 failure. Direct runtime wiring, provider adapters, namespace proof enforcement, policy/account preflight, durable capture implementation and release certification remain later tasks. The old runtime and historical readers remain in place by design. No full suite or make ci was run, as instructed; only the named targeted tests ran. No provider login, enrolment, credential home or live provider run occurred.
All mutation source changes were restored. The task's scratch evidence directory is removed after saving these reports. No server or background process was left running. No push, merge or deployment was performed.
+
+## Task 2: Owned bubblewrap PID namespaces
+
+Status: DONE_WITH_CONCERNS. Implementation and local capability gates pass. The controller must push `plan-2b` and inspect the Amadan worker result; this run did not push, select a remote worker or claim remote CI evidence.
+
+### What changed
+
+`containment.Manager` implements `provider.ProcessHost` and the requested New, Start, Stop and Recover APIs. Each launch gets a random local ID, a durable pre-fork intent, then a durable init identity before the helper receives its release byte. Records and exit proofs are written with file and directory fsync under the private scratch root. The runner holds the exact init pidfd, signals that descriptor and waits for its kernel exit before publishing proof. The bubblewrap launcher is also reaped. Scratch paths are tied to the durable ID; recovery removes only that attempt after proven exit or a changed boot. Wait is acknowledged after live cleanup finishes, without a later duplicate deletion. CLI exit, an empty process group and an empty cgroup are never containment proof.
+
+The lifecycle goroutine locks its OS thread before starting bubblewrap and keeps it alive until reaping. Bubblewrap uses explicit user, PID, IPC, UTS, cgroup and network isolation, `--die-with-parent`, `--new-session`, `--as-pid-1`, and dropped capabilities. The Go helper stays PID 1, reaps orphans and starts the harness as a child. Parent death, caller-thread exit, detached children and a successful cgroup move are covered by real Linux tests. Only test-owned processes are signalled.
+
+The parent uses bubblewrap status FD 3 to learn the helper's host PID. FD 4 is the release barrier; FD 5 carries helper readiness and the final harness outcome. Namespace identity, start ticks and PID-1 topology are checked before release. The helper marks itself nondumpable before starting the harness, preventing the harness from reopening its protocol descriptors through `/proc/1/fd`. It marks all nonstandard descriptors close-on-exec. Stdin, stdout and stderr belong to the Process caller, so buffered output remains readable after Wait. No provider process or credential home was created in this run; all harnesses were local test commands.
+
+Mount sources use `openat2` without symlink or magic-link resolution and bubblewrap FD bind arguments. A live rename/symlink replacement test proves the pinned workspace remains the source. Workspace/state overlap, broad homes, unapproved targets, writable runtime imports, imported sockets and unsafe environment entries are rejected. The namespace receives fresh proc/dev, an empty run/sys, a private on-disk tmp, a private runtime home, and explicit read-only runtime files. Host loopback and inherited host sockets are unavailable. Nested user namespaces remain available for provider sandboxes.
+
+Recovery matches a complete durable record and reacquires only that exact PID/start/namespace identity. It rejects non-init processes, mismatched records, stale start ticks, missing handshakes and missing/corrupt/unverified exit proofs. A new boot proves absence with unknown outcome (`Code=-1`, `Signal=0`). An incomplete same-boot intent or a vanished PID without a saved exit remains blocked; there is no broad same-user process scan.
+
+### Files
+
+- `internal/runner/containment/linux.go`: Manager, lifecycle, startup protocol, owned Process and PID-1 helper.
+- `internal/runner/containment/mounts.go`: pinned sources, mounts, private homes and environment allowlist.
+- `internal/runner/containment/recovery.go`: durable records/proofs, exact identity and recovery.
+- `internal/runner/containment/{linux,mounts,recovery,budget}_test.go`: Linux tests, fixtures and budget TestMain.
+- `cmd/equipo-runner/{main,namespace}.go`: internal command dispatch to the shared helper implementation.
+- `internal/runnerproto/containment.go`: additive NamespaceExit and NamespaceContainmentProof wire types, without a containment import.
+- `Makefile`: exact `bubblewrap 0.11.0` prerequisite, required `runner-namespace-test`, and inclusion in `ci`.
+- `.amadan/ci.d/36-runner-namespaces`: executable delegate to `make runner-namespace-test`.
+- `internal/equipotest/foundation_test.go`: require the new target in both CI routes.
+- This controller section and the requested task report.
+
+### Interpretations and integration notes
+
+1. The controller's explicit no-push instruction supersedes the brief's push/remote-worker wording. Local worker-capability proof is complete; the Amadan result belongs to the controller's subsequent push.
+2. The brief explicitly requests full `make ci` on a capable runner. The first full gate passed. Final review then found a crash-cleanup gap: randomly named scratch could not be recovered from the durable ID. After adding failing tests and fixing that production behavior, the targeted gate and three new mutations passed. The full gate passed again after that fix. A final run explicitly exported `CGO_ENABLED=0` for every Make recipe after noticing that the generic test/tool recipes otherwise inherit the host default of 1. All targeted tests and the Make build target already used 0. These repeats addressed a production change and the build-environment requirement.
+3. `Config.ScratchRoot` must already be an absolute, symlink-free directory with mode 0700. New grants no execution authority. An optional staged `Binding.Home` must be a mode-0700 direct child of `ScratchRoot/homes`; otherwise each attempt gets an empty private home. These fixture directories contained no credentials. Adapters and Task 4 remain responsible for producing the reviewed manifest and staged account content; this task records `Policy.Hash` as ManifestHash.
+4. `/etc` uses a temporary overlay, masks `/etc/claude-code` and `/etc/codex`, then remounts all three read-only. This permits controlled replacement paths even when the host has no `/etc/codex`. The local namespace suite exercises this capability too. `/usr` is the explicit read-only system runtime tree, consistent with the nesting evidence.
+5. The command wrapper lives in `cmd/equipo-runner/namespace.go`; the reusable implementation is `containment.NamespaceMain`, so tests execute the same helper code. Task 3 should extend this helper, retain its nondumpable state, and add only the explicit relay socket capability. General socket imports remain rejected. Task 9 can use the same Manager.
+6. The helper is bubblewrap's child, not the runner's direct child. Production waits on the init pidfd's readable exit state, then reaps bubblewrap. The capability test separately exercises `waitid(P_PIDFD, WEXITED|WNOWAIT)` on a direct test-owned child. The host user can still read the nondumpable helper's namespace identity in this user-namespace layout, so recovery requires the kernel namespace check; no permission-error fallback was retained.
+7. `.amadan/ci` and `.amadan/ci.d/35-runner-adapter-test` already delegate to Make targets and needed no changes. Existing node/npm prerequisite and adapter commands remain unchanged.
+8. A namespace-member fixture must enumerate the tasks of each owned process, since Go may fork on a non-main thread. Tests enumerate only descendants of the exact init they started. The orphan-reaping fixture waits for PID-file content, avoiding an empty-file creation race. Neither test scans unrelated host processes.
+
+### Local capability evidence
+
+Host: DOCS-T1. User: paulca, UID 1001. Go: go1.26.10 linux/amd64. `/usr/bin/bwrap --version` returned exactly `bubblewrap 0.11.0`.
+
+Read-only observations:
+
+```sh
+id
+/usr/bin/bwrap --version
+cat /proc/self/cgroup
+ls -ld /sys/fs/cgroup/user.slice/user-$(id -u).slice/user@$(id -u).service
+cat /sys/fs/cgroup/user.slice/user-$(id -u).slice/user@$(id -u).service/cgroup.subtree_control
+```
+
+```text
+uid=1001(paulca) gid=1001(paulca)
+bubblewrap 0.11.0
+0::/user.slice/user-1001.slice/user@1001.service/app.slice/paseo.service
+drwxr-xr-x ... paulca paulca ... user@1001.service
+cpu memory pids
+```
+
+`TestNamespacePidfdCapability` successfully opened a pidfd, sent SIGKILL through it and called `waitid(P_PIDFD, WEXITED|WNOWAIT)` on a sleep process the test started. All launch tests ran real user/PID/network namespaces. `TestNamespaceNestedUserNamespace` also ran a second bubblewrap inside the first namespace.
+
+`TestNamespaceCgroupMoveKeepsMembership` created its own parent and two leaf cgroups under the delegated user service, moved an owned harness PID into both leaves through `cgroup.procs`, verified `/proc/<pid>/cgroup` after each write, and compared its PID namespace before/after. It then killed namespace init and observed that exact harness pidfd exit. The test removed its cgroups. This is a successful move, separate from `TestNamespaceHidesHostControl` denying an in-namespace cgroup write. Missing delegation or syscall capability causes a clear test failure; no test skips.
+
+Required job/step: `.amadan/ci.d/36-runner-namespaces`, delegating to `make runner-namespace-test`. Local runner: DOCS-T1. Remote Amadan job and runner: not yet observed; controller action required after push. Every Linux launch test needs userns and pidfd support; the move test additionally needs the writable delegated subtree.
+
+### RED evidence
+
+All commands ran from `/home/paulca/amadan.net/oficina/equipo-plan-2b` on `plan-2b`, with default Go caches and on-disk TMPDIR. The initial test-only implementation failed before Manager or the helper existed:
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner/containment -run '^TestNamespace' -count=1
+```
+
+```text
+# amadan.net/oficina/equipo/internal/runner/containment [amadan.net/oficina/equipo/internal/runner/containment.test]
+internal/runner/containment/linux_test.go:23:30: undefined: Manager
+internal/runner/containment/linux_test.go:31:12: undefined: New
+internal/runner/containment/linux_test.go:31:16: undefined: Config
+internal/runner/containment/linux_test.go:35:29: undefined: Manager
+internal/runner/containment/linux_test.go:44:29: undefined: Manager
+internal/runner/containment/linux_test.go:44:57: undefined: Record
+internal/runner/containment/linux_test.go:47:8: undefined: Record
+internal/runner/containment/linux_test.go:138:7: undefined: New
+internal/runner/containment/linux_test.go:138:11: undefined: Config
+internal/runner/containment/budget_test.go:10:63: undefined: NamespaceMain
+internal/runner/containment/linux_test.go:138:11: too many errors
+FAIL amadan.net/oficina/equipo/internal/runner/containment [build failed]
+FAIL
+```
+
+Additional red command (exit 1):
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner/containment -run '^TestNamespace(RecoveryCleansScratch|ScratchIdentity)$' -count=1
+```
+
+```text
+--- FAIL: TestNamespaceRecoveryCleansScratch (0.13s)
+ --- FAIL: TestNamespaceRecoveryCleansScratch/saved-exit (0.06s)
+ recovery_test.go:241: recovery left owned scratch: <nil>
+ --- FAIL: TestNamespaceRecoveryCleansScratch/new-boot (0.07s)
+ recovery_test.go:241: recovery left owned scratch: <nil>
+--- FAIL: TestNamespaceScratchIdentity (0.06s)
+ recovery_test.go:250: scratch not bound to durable ID: stat /home/paulca/t/e2b/TestNamespaceScratchIdentity2348921627/001/state/attempt-f53aceebc32ab1e29f126e8cf49ba187/tmp: no such file or directory
+FAIL
+rastrillo-budget/v1 ran 188ms
+FAIL amadan.net/oficina/equipo/internal/runner/containment 0.190s
+FAIL
+```
+
+Additional red command (exit 1):
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner/containment -run '^TestNamespace(Startup|Intent|Stop|ExitStatus|Socket|Nested|RecoverySaved)' -count=1
+```
+
+```text
+--- FAIL: TestNamespaceStartupFailure (0.02s)
+ linux_test.go:391: missing readiness accepted
+--- FAIL: TestNamespaceExitStatus (0.05s)
+ linux_test.go:447: numeric exit fabricated signal: {Code:-1 Signal:9 ObservedAt:2026-11-03 09:45:40.096810068 +0000 UTC}
+--- FAIL: TestNamespaceRecoverySavedExit (0.05s)
+ recovery_test.go:116: durable exit recovery: {Record:{ID:f88b63fd621d06c2f2bea8900b79c8ff AttemptKey:attempt-fixture BootID:1edb59fc-5665-4f1e-84f5-3b03b0992119 NamespaceID:pid:[4026532762] ManifestHash:fixture-policy HostPID:4033652 StartTicks:855685293} Exit:{Code:-1 Signal:0 ObservedAt:0001-01-01 00:00:00 +0000 UTC} Verified:false} namespace_identity_unproven
+FAIL
+rastrillo-budget/v1 ran 242ms
+FAIL amadan.net/oficina/equipo/internal/runner/containment 0.244s
+FAIL
+```
+
+Additional red command (exit 1):
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner/containment -run '^TestNamespace(RecoveryRejects|PinnedMount|RejectsBroad)' -count=1
+```
+
+```text
+--- FAIL: TestNamespaceRecoveryRejectsNonInit (0.05s)
+ recovery_test.go:130: host process accepted as namespace init
+FAIL
+rastrillo-budget/v1 ran 96ms
+FAIL amadan.net/oficina/equipo/internal/runner/containment 0.098s
+FAIL
+```
+
+Additional red command (exit 1):
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner/containment -run '^TestNamespaceHelperProtocolPrivate$' -count=1
+```
+
+```text
+--- FAIL: TestNamespaceHelperProtocolPrivate (0.06s)
+ linux_test.go:509: helper pipe exposed: {Code:1 Signal:0 ObservedAt:2026-11-03 09:50:23.095916577 +0000 UTC} <nil>
+FAIL
+rastrillo-budget/v1 ran 58ms
+FAIL amadan.net/oficina/equipo/internal/runner/containment 0.060s
+FAIL
+```
+
+Additional red command (exit 1):
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner/containment -run '^TestNamespaceMountEscape/.*environment' -count=1
+```
+
+```text
+--- FAIL: TestNamespaceMountEscape (0.09s)
+ --- FAIL: TestNamespaceMountEscape/home_environment_traversal (0.04s)
+ recovery_test.go:88: unsafe mount/environment accepted
+ --- FAIL: TestNamespaceMountEscape/tmp_environment_traversal (0.04s)
+ recovery_test.go:88: unsafe mount/environment accepted
+FAIL
+rastrillo-budget/v1 ran 86ms
+FAIL amadan.net/oficina/equipo/internal/runner/containment 0.088s
+FAIL
+```
+
+Additional red command (exit 1):
+
+```sh
+CGO_ENABLED=0 go test ./internal/equipotest -run '^TestCIGateSteps$' -count=1
+```
+
+```text
+--- FAIL: TestCIGateSteps (0.01s)
+ foundation_test.go:185: make ci targets = [budget build fmt-check gitleaks govulncheck migration-check perf runner-adapter-test runner-namespace-test staticcheck test vet], want [budget build fmt-check gitleaks govulncheck migration-check perf runner-adapter-test staticcheck test vet]
+ foundation_test.go:221: CI step targets = [budget build fmt-check gitleaks govulncheck migration-check perf runner-adapter-test runner-namespace-test staticcheck test vet], want [budget build fmt-check gitleaks govulncheck migration-check perf runner-adapter-test staticcheck test vet]
+FAIL
+rastrillo-budget/v1 ran 15ms
+FAIL amadan.net/oficina/equipo/internal/equipotest 0.062s
+FAIL
+```
+
+The crash-cleanup regression exposed an attempt directory name that was absent from the durable identity. Binding the directory name to the ID made recovery cleanup possible. A follow-up failure caught a duplicate deferred deletion after Wait; live cleanup now finishes before acknowledgment and does not run twice. The startup regression exposed a typed-nil Process on error; Start now returns a nil interface and waits for failed-start cleanup. Exit tests exposed the incorrect inference that numeric exit 137 means SIGKILL; a private helper outcome frame now preserves the distinction. The protocol test exposed same-UID reopening of `/proc/1/fd/5`; the helper now becomes nondumpable before starting the harness. Environment path checks now reject traversal as well as enforcing their namespace roots.
+
+### GREEN evidence
+
+The final targeted namespace command runs 26 top-level namespace tests, plus their subtests, without skips:
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner/containment -run '^TestNamespace' -count=1 -v
+```
+
+```text
+=== RUN TestNamespaceKillsDetachedChildren
+--- PASS: TestNamespaceKillsDetachedChildren (0.07s)
+=== RUN TestNamespaceCgroupMoveKeepsMembership
+--- PASS: TestNamespaceCgroupMoveKeepsMembership (0.12s)
+=== RUN TestNamespaceHidesHostControl
+--- PASS: TestNamespaceHidesHostControl (0.07s)
+=== RUN TestNamespacePidfdCapability
+--- PASS: TestNamespacePidfdCapability (0.00s)
+=== RUN TestNamespaceParentDeath
+--- PASS: TestNamespaceParentDeath (0.05s)
+=== RUN TestNamespaceStartingThreadExit
+--- PASS: TestNamespaceStartingThreadExit (0.10s)
+=== RUN TestNamespaceStartupFailure
+--- PASS: TestNamespaceStartupFailure (0.02s)
+=== RUN TestNamespaceIntentBeforeFork
+--- PASS: TestNamespaceIntentBeforeFork (0.04s)
+=== RUN TestNamespaceStopWaitsForExit
+--- PASS: TestNamespaceStopWaitsForExit (0.07s)
+=== RUN TestNamespaceExitStatus
+--- PASS: TestNamespaceExitStatus (0.12s)
+=== RUN TestNamespaceSocketImport
+--- PASS: TestNamespaceSocketImport (0.00s)
+=== RUN TestNamespaceNestedUserNamespace
+--- PASS: TestNamespaceNestedUserNamespace (0.07s)
+=== RUN TestNamespaceHelperProtocolPrivate
+--- PASS: TestNamespaceHelperProtocolPrivate (0.07s)
+=== RUN TestNamespaceHelperBarrier
+--- PASS: TestNamespaceHelperBarrier (0.04s)
+=== RUN TestNamespaceReapsOrphans
+--- PASS: TestNamespaceReapsOrphans (0.11s)
+=== RUN TestNamespaceCancellation
+--- PASS: TestNamespaceCancellation (0.06s)
+=== RUN TestNamespacePinnedMountSwap
+--- PASS: TestNamespacePinnedMountSwap (0.04s)
+=== RUN TestNamespaceRejectsBroadWorkspace
+--- PASS: TestNamespaceRejectsBroadWorkspace (0.00s)
+=== RUN TestNamespaceRecoveryIdentity
+=== RUN TestNamespaceRecoveryIdentity/reused_pid
+=== RUN TestNamespaceRecoveryIdentity/changed_manifest
+=== RUN TestNamespaceRecoveryIdentity/changed_namespace
+=== RUN TestNamespaceRecoveryIdentity/missing_handshake
+=== RUN TestNamespaceRecoveryIdentity/unavailable_proof
+--- PASS: TestNamespaceRecoveryIdentity (0.06s)
+ --- PASS: TestNamespaceRecoveryIdentity/reused_pid (0.00s)
+ --- PASS: TestNamespaceRecoveryIdentity/changed_manifest (0.00s)
+ --- PASS: TestNamespaceRecoveryIdentity/changed_namespace (0.00s)
+ --- PASS: TestNamespaceRecoveryIdentity/missing_handshake (0.00s)
+ --- PASS: TestNamespaceRecoveryIdentity/unavailable_proof (0.00s)
+=== RUN TestNamespaceMountEscape
+=== RUN TestNamespaceMountEscape/traversal
+=== RUN TestNamespaceMountEscape/outside_private_home
+=== RUN TestNamespaceMountEscape/broad_home
+=== RUN TestNamespaceMountEscape/protected_state
+=== RUN TestNamespaceMountEscape/parent_of_protected_state
+=== RUN TestNamespaceMountEscape/host_runtime
+=== RUN TestNamespaceMountEscape/host_cgroup
+=== RUN TestNamespaceMountEscape/writable_runtime
+=== RUN TestNamespaceMountEscape/reserved_target
+=== RUN TestNamespaceMountEscape/home_environment_traversal
+=== RUN TestNamespaceMountEscape/tmp_environment_traversal
+=== RUN TestNamespaceMountEscape/environment
+=== RUN TestNamespaceMountEscape/symlink_swap
+--- PASS: TestNamespaceMountEscape (0.00s)
+ --- PASS: TestNamespaceMountEscape/traversal (0.00s)
+ --- PASS: TestNamespaceMountEscape/outside_private_home (0.00s)
+ --- PASS: TestNamespaceMountEscape/broad_home (0.00s)
+ --- PASS: TestNamespaceMountEscape/protected_state (0.00s)
+ --- PASS: TestNamespaceMountEscape/parent_of_protected_state (0.00s)
+ --- PASS: TestNamespaceMountEscape/host_runtime (0.00s)
+ --- PASS: TestNamespaceMountEscape/host_cgroup (0.00s)
+ --- PASS: TestNamespaceMountEscape/writable_runtime (0.00s)
+ --- PASS: TestNamespaceMountEscape/reserved_target (0.00s)
+ --- PASS: TestNamespaceMountEscape/home_environment_traversal (0.00s)
+ --- PASS: TestNamespaceMountEscape/tmp_environment_traversal (0.00s)
+ --- PASS: TestNamespaceMountEscape/environment (0.00s)
+ --- PASS: TestNamespaceMountEscape/symlink_swap (0.00s)
+=== RUN TestNamespaceRecoverySavedExit
+--- PASS: TestNamespaceRecoverySavedExit (0.06s)
+=== RUN TestNamespaceRecoveryRejectsNonInit
+--- PASS: TestNamespaceRecoveryRejectsNonInit (0.09s)
+=== RUN TestNamespaceRecoveryStaleDurableTicks
+--- PASS: TestNamespaceRecoveryStaleDurableTicks (0.10s)
+=== RUN TestNamespaceRecoveryUnavailableProof
+=== RUN TestNamespaceRecoveryUnavailableProof/missing
+=== RUN TestNamespaceRecoveryUnavailableProof/corrupt
+=== RUN TestNamespaceRecoveryUnavailableProof/record
+=== RUN TestNamespaceRecoveryUnavailableProof/unverified
+=== RUN TestNamespaceRecoveryUnavailableProof/timestamp
+--- PASS: TestNamespaceRecoveryUnavailableProof (0.36s)
+ --- PASS: TestNamespaceRecoveryUnavailableProof/missing (0.06s)
+ --- PASS: TestNamespaceRecoveryUnavailableProof/corrupt (0.06s)
+ --- PASS: TestNamespaceRecoveryUnavailableProof/record (0.08s)
+ --- PASS: TestNamespaceRecoveryUnavailableProof/unverified (0.09s)
+ --- PASS: TestNamespaceRecoveryUnavailableProof/timestamp (0.07s)
+=== RUN TestNamespaceRecoveryCleansScratch
+=== RUN TestNamespaceRecoveryCleansScratch/saved-exit
+=== RUN TestNamespaceRecoveryCleansScratch/new-boot
+--- PASS: TestNamespaceRecoveryCleansScratch (0.12s)
+ --- PASS: TestNamespaceRecoveryCleansScratch/saved-exit (0.05s)
+ --- PASS: TestNamespaceRecoveryCleansScratch/new-boot (0.06s)
+=== RUN TestNamespaceScratchIdentity
+--- PASS: TestNamespaceScratchIdentity (0.06s)
+PASS
+rastrillo-budget/v1 ran 1.911s
+ok amadan.net/oficina/equipo/internal/runner/containment 1.913s
+```
+
+Command (exit 0):
+
+```sh
+make runner-namespace-test
+```
+
+```text
+CGO_ENABLED=0 go test ./internal/runner/containment -run '^TestNamespace' -count=1
+ok amadan.net/oficina/equipo/internal/runner/containment 1.877s
+```
+
+Command (exit 0):
+
+```sh
+CGO_ENABLED=0 go test ./internal/equipotest -run '^TestCIGateSteps$' -count=1
+```
+
+```text
+ok amadan.net/oficina/equipo/internal/equipotest 0.054s
+```
+
+Final full required gate (exit 0):
+
+```sh
+CGO_ENABLED=0 make ci
+```
+
+Complete gate output:
+
+```text
+CGO_ENABLED=0 go build ./...
+go vet ./...
+go run honnef.co/go/tools/cmd/staticcheck@v0.7.0 -tags browser,perf ./...
+go run golang.org/x/vuln/cmd/govulncheck@v1.8.0 ./...
+=== Symbol Results ===
+
+No vulnerabilities found.
+
+Your code is affected by 0 vulnerabilities.
+This scan also found 0 vulnerabilities in packages you import and 1
+vulnerability in modules you require, but your code doesn't appear to call these
+vulnerabilities.
+Use '-show verbose' for more details.
+10:19AM INF Unknown SCM platform. Use --platform to include links in findings. host=amadan.net
+10:19AM INF 112 commits scanned.
+10:19AM INF scanned ~4078895 bytes (4.08 MB) in 432ms
+10:19AM INF no leaks found
+go run amadan.net/rastrillo/rastrillo/cmd/rastrillo budget size
+budget size: 17 directories within budget
+go run amadan.net/rastrillo/rastrillo/cmd/rastrillo budget test -count=1 ./...
+
+receipt: test step 3m12.543s against a 60s target (the gate's other steps are not in this figure)
+receipt: 13 packages ran, 0 cached, 4 without tests, 0 failed
+receipt: slow package 3m11.715s amadan.net/oficina/equipo/internal/equipotest
+receipt: slow package 2m52.086s amadan.net/oficina/equipo/internal/runner
+receipt: slow package 27.207s amadan.net/oficina/equipo/internal/equipo/team
+receipt: slow package 11.475s amadan.net/oficina/equipo/internal/runner/checks
+receipt: slow package 5.978s amadan.net/oficina/equipo/internal/runner/forge
+receipt: slow test 22.56s amadan.net/oficina/equipo/internal/equipotest TestRunnerEndToEnd
+receipt: slow test 21.89s amadan.net/oficina/equipo/internal/runner TestRunnerBugWorkflow
+receipt: slow test 17.08s amadan.net/oficina/equipo/internal/runner TestAccountFailoverStops
+receipt: slow test 16.6s amadan.net/oficina/equipo/internal/runner TestDeterministicAttemptErrorsFailWithReason
+receipt: slow test 9.1s amadan.net/oficina/equipo/internal/runner TestRunnerBugWorkflowRejectedTools
+command -v node
+/usr/local/bin/node
+command -v npm
+/usr/local/bin/npm
+npm ci --prefix runner/paseo --ignore-scripts --no-audit --no-fund --registry=https://registry.npmjs.org
+npm warn deprecated uuid@9.0.1: uuid@10 and below is no longer supported. For ESM codebases, update to uuid@latest. For CommonJS codebases, use uuid@11 (but be aware this version will likely be deprecated in 2028).
+
+added 294 packages in 3s
+node --test runner/paseo/bridge.test.mjs
+✔ structured events (8.965317ms)
+✔ permission IDs (1.53576ms)
+✔ MCP at creation (0.844928ms)
+✔ workspace identity (0.499186ms)
+✔ unknown version (0.205111ms)
+✔ read isolation required (0.146903ms)
+✔ provider option schema (0.35596ms)
+✔ cancelAgent export (116.570388ms)
+✔ daemon credentials (0.521848ms)
+✔ subscription ready before prompt (0.406694ms)
+✔ SDK serializes the pinned creation and permission contracts (13.053433ms)
+✔ pinned provider schemas reject unsupported profile passthrough (4.858525ms)
+✔ creation requires durable daemon receipts (0.246738ms)
+✔ timeline gaps and disconnects revoke readiness (0.394763ms)
+✔ recovery cursor and live overlap (0.961494ms)
+✔ agent and MCP credentials cannot be injected (0.197747ms)
+✔ unknown structured events and session changes stop dispatch (0.256416ms)
+✔ pending permission recovery keeps original identity (0.228023ms)
+✔ bounded bridge frames and redacted diagnostics (7.770892ms)
+✔ locked dependency versions (1.817192ms)
+✔ workspace isolation mode (0.141763ms)
+✔ project registration (0.22666ms)
+✔ terminal cleanup uses exact workspace IDs and unknown lists fail closed (0.292152ms)
+✔ runner obtains the pinned creation policy before recording creation (0.149368ms)
+✔ recovery looks up preassigned IDs without creating resources (0.384814ms)
+✔ creation sends preassigned resource IDs (0.194972ms)
+✔ definitive create failures are only tagged before effects (0.43126ms)
+✔ creation absence requires a complete lookup (0.364998ms)
+✔ definitive policy failures retain their specific wire codes (0.18843ms)
+✔ trial routes the chosen credential home using supported agent env (0.12935ms)
+✔ trial starts an empty live timeline and refuses recovered completion (0.183911ms)
+ℹ tests 31
+ℹ suites 0
+ℹ pass 31
+ℹ fail 0
+ℹ cancelled 0
+ℹ skipped 0
+ℹ todo 0
+ℹ duration_ms 303.153669
+CGO_ENABLED=0 go test ./internal/runner/paseo -run 'TestPaseo|TestSubscriptionReady' -count=1
+ok amadan.net/oficina/equipo/internal/runner/paseo 0.376s
+CGO_ENABLED=0 go test ./internal/runner/checks -run '^TestCheckSandbox' -count=1
+ok amadan.net/oficina/equipo/internal/runner/checks 5.771s
+CGO_ENABLED=0 go test ./internal/runner/containment -run '^TestNamespace' -count=1
+ok amadan.net/oficina/equipo/internal/runner/containment 1.472s
+CGO_ENABLED=0 go test ./internal/equipo -run '^TestMigrationModels$' -count=1
+ok amadan.net/oficina/equipo/internal/equipo 0.090s
+go run amadan.net/rastrillo/rastrillo/cmd/rastrillo budget test -no-time -require TestPerfScreens,TestPerfBoot -tags perf -count=1 -p 1 -parallel 1 -run '^TestPerf' ./...
+perf: GET /: median 120µs, worst 139µs, budget 150ms
+perf: GET /auth/callback: median 50µs, worst 53µs, budget 150ms
+perf: GET /auth/verify: median 54µs, worst 60µs, budget 150ms
+perf: GET /connections: median 3.371ms, worst 3.617ms, budget 150ms
+perf: GET /conversation: median 3.75ms, worst 4.602ms, budget 150ms
+perf: GET /journey: median 3.624ms, worst 3.893ms, budget 150ms
+perf: GET /needs-you: median 3.5ms, worst 3.863ms, budget 150ms
+perf: GET /people: median 2.41ms, worst 2.689ms, budget 150ms
+perf: GET /projects: median 2.815ms, worst 3.327ms, budget 150ms
+perf: GET /projects/new: median 2.594ms, worst 2.81ms, budget 150ms
+perf: GET /projects/{id}: median 3.631ms, worst 3.922ms, budget 150ms
+perf: GET /projects/{id}/edit: median 2.68ms, worst 2.826ms, budget 150ms
+perf: GET /runners/enrol: median 8.794ms, worst 9.904ms, budget 150ms
+perf: GET /settings: median 2.611ms, worst 2.785ms, budget 150ms
+perf: GET /settings/recovery: median 8.358ms, worst 9.729ms, budget 150ms
+perf: GET /settings/recovery/release: median 8.197ms, worst 8.643ms, budget 150ms
+perf: GET /signin: median 194µs, worst 239µs, budget 150ms
+perf: GET /specialists/{key}: median 4.219ms, worst 5.692ms, budget 150ms
+perf: GET /tasks/new: median 2.745ms, worst 3.457ms, budget 150ms
+perf: GET /tasks/{id}: median 3.592ms, worst 3.671ms, budget 150ms
+perf: GET /tasks/{id}/merge: median 3.29ms, worst 4.034ms, budget 150ms
+perf: GET /tasks/{id}/questions/{question}: median 3.567ms, worst 3.712ms, budget 150ms
+perf: GET /work: median 2.558ms, worst 2.714ms, budget 150ms
+perf: cold boot: median 59ms of [57.991055ms 58.592532ms 59.697522ms], budget 500ms
+
+receipt: test step 8.484s against a 60s target (the gate's other steps are not in this figure)
+receipt: 1 packages ran, 0 cached, 16 without tests, 0 failed
+receipt: slow package 4.556s amadan.net/oficina/equipo/internal/equipotest
+receipt: slow package 0s amadan.net/oficina/equipo/internal/runner/checks
+receipt: slow package 0s amadan.net/oficina/equipo/internal/equipo/team
+receipt: slow package 0s amadan.net/oficina/equipo/internal/equipo/teamcontract
+receipt: slow package 0s amadan.net/oficina/equipo/internal/equipo
+receipt: slow test 4.35s amadan.net/oficina/equipo/internal/equipotest TestPerfScreens
+receipt: slow test 200ms amadan.net/oficina/equipo/internal/equipotest TestPerfBoot
+```
+
+Additional verification: `make fmt-check`, `git diff --check`, and `CGO_ENABLED=0 go vet ./internal/runner/containment ./cmd/equipo-runner ./internal/runnerproto` passed. The real command binary was built and its private helper entry refused to run outside PID 1:
+
+```text
+CGO_ENABLED=0 go build -o "$TMPDIR/task2-evidence/equipo-runner" ./cmd/equipo-runner
+"$TMPDIR/task2-evidence/equipo-runner" __namespace /usr/bin/true
+exit 125 (expected 125 outside PID 1)
+```
+
+### Guard mutations
+
+40 distinct guard mutations compiled and made the named tests fail. Each mutation was applied alone and restored from the saved original in a `finally` block. No mutation is retained. The complete restored namespace gate and CI-alignment test above passed after the last mutation. The following are the exact mutation diffs, commands and red outputs; each listed command exited 1.
+
+#### 1. pid-isolation
+
+```diff
+--- internal/runner/containment/linux.go
++++ internal/runner/containment/linux.go
+@@ -204,7 +204,7 @@
+ result <- startResult{err: e}
+ return
+ }
+- args := []string{"--unshare-user", "--unshare-pid", "--unshare-ipc", "--unshare-uts", "--unshare-cgroup", "--unshare-net", "--die-with-parent", "--new-session", "--as-pid-1", "--cap-drop", "ALL", "--json-status-fd", "3"}
++ args := []string{"--unshare-user", "--unshare-ipc", "--unshare-uts", "--unshare-cgroup", "--unshare-net", "--die-with-parent", "--new-session", "--as-pid-1", "--cap-drop", "ALL", "--json-status-fd", "3"}
+ args = append(args, mounts.args...)
+ args = append(args, "--", "/equipo-namespace", "__namespace")
+ args = append(args, argv...)
+```
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner/containment -run ^TestNamespaceKillsDetachedChildren$ -count=1 -timeout=20s
+```
+
+```text
+--- FAIL: TestNamespaceKillsDetachedChildren (0.01s)
+ linux_test.go:182: namespace capability/start failed (userns, pidfd required): namespace_startup_failed: bwrap: Specifying --as-pid-1 requires --unshare-pid
+FAIL
+rastrillo-budget/v1 ran 13ms
+FAIL amadan.net/oficina/equipo/internal/runner/containment 0.015s
+FAIL
+```
+
+#### 2. helper-pid-one
+
+```diff
+--- internal/runner/containment/linux.go
++++ internal/runner/containment/linux.go
+@@ -204,7 +204,7 @@
+ result <- startResult{err: e}
+ return
+ }
+- args := []string{"--unshare-user", "--unshare-pid", "--unshare-ipc", "--unshare-uts", "--unshare-cgroup", "--unshare-net", "--die-with-parent", "--new-session", "--as-pid-1", "--cap-drop", "ALL", "--json-status-fd", "3"}
++ args := []string{"--unshare-user", "--unshare-pid", "--unshare-ipc", "--unshare-uts", "--unshare-cgroup", "--unshare-net", "--die-with-parent", "--new-session", "--cap-drop", "ALL", "--json-status-fd", "3"}
+ args = append(args, mounts.args...)
+ args = append(args, "--", "/equipo-namespace", "__namespace")
+ args = append(args, argv...)
+```
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner/containment -run ^TestNamespaceKillsDetachedChildren$ -count=1 -timeout=20s
+```
+
+```text
+--- FAIL: TestNamespaceKillsDetachedChildren (0.02s)
+ linux_test.go:182: namespace capability/start failed (userns, pidfd required): namespace_startup_failed:
+FAIL
+rastrillo-budget/v1 ran 20ms
+FAIL amadan.net/oficina/equipo/internal/runner/containment 0.022s
+FAIL
+```
+
+#### 3. network-isolation
+
+```diff
+--- internal/runner/containment/linux.go
++++ internal/runner/containment/linux.go
+@@ -204,7 +204,7 @@
+ result <- startResult{err: e}
+ return
+ }
+- args := []string{"--unshare-user", "--unshare-pid", "--unshare-ipc", "--unshare-uts", "--unshare-cgroup", "--unshare-net", "--die-with-parent", "--new-session", "--as-pid-1", "--cap-drop", "ALL", "--json-status-fd", "3"}
++ args := []string{"--unshare-user", "--unshare-pid", "--unshare-ipc", "--unshare-uts", "--unshare-cgroup", "--die-with-parent", "--new-session", "--as-pid-1", "--cap-drop", "ALL", "--json-status-fd", "3"}
+ args = append(args, mounts.args...)
+ args = append(args, "--", "/equipo-namespace", "__namespace")
+ args = append(args, argv...)
+```
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner/containment -run ^TestNamespaceHidesHostControl$ -count=1 -timeout=20s
+```
+
+```text
+--- FAIL: TestNamespaceHidesHostControl (0.06s)
+ linux_test.go:320: isolation: {Code:1 Signal:0 ObservedAt:2026-11-03 09:56:16.808517203 +0000 UTC} <nil> Traceback (most recent call last):
+ File "<string>", line 10, in <module>
+ s=socket.socket(); assert s.connect_ex(('127.0.0.1',40593))!=0
+ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+ AssertionError
+FAIL
+rastrillo-budget/v1 ran 59ms
+FAIL amadan.net/oficina/equipo/internal/runner/containment 0.061s
+FAIL
+```
+
+#### 4. host-bus
+
+```diff
+--- internal/runner/containment/mounts.go
++++ internal/runner/containment/mounts.go
+@@ -108,7 +108,7 @@
+ return nil, err
+ }
+ p.args = append(p.args, "--overlay-src", "/etc", "--tmp-overlay", "/etc")
+- p.args = append(p.args, "--symlink", "usr/bin", "/bin", "--symlink", "usr/lib", "/lib", "--symlink", "usr/lib64", "/lib64", "--proc", "/proc", "--dev", "/dev", "--dir", "/run", "--dir", "/sys", "--dir", "/home/runner", "--tmpfs", "/etc/claude-code", "--tmpfs", "/etc/codex")
++ p.args = append(p.args, "--symlink", "usr/bin", "/bin", "--symlink", "usr/lib", "/lib", "--symlink", "usr/lib64", "/lib64", "--proc", "/proc", "--dev", "/dev", "--ro-bind", "/run", "/run", "--dir", "/sys", "--dir", "/home/runner", "--tmpfs", "/etc/claude-code", "--tmpfs", "/etc/codex")
+ if err = p.bind(l.Workspace, "/workspace", false, true); err != nil {
+ return nil, err
+ }
+```
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner/containment -run ^TestNamespaceHidesHostControl$ -count=1 -timeout=20s
+```
+
+```text
+--- FAIL: TestNamespaceHidesHostControl (0.06s)
+ linux_test.go:320: isolation: {Code:1 Signal:0 ObservedAt:2026-11-03 09:56:17.137968151 +0000 UTC} <nil> Traceback (most recent call last):
+ File "<string>", line 3, in <module>
+ assert all(not os.path.exists(p) for p in paths), paths
+ ~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+ AssertionError: ['/sys/fs/cgroup', '/run/user/1001/bus', '/run/user/1001/systemd/private', '/home/paulca', '/proc/1/root/home/paulca', '/etc/claude-code/managed-settings.json', '/etc/codex/config.toml']
+FAIL
+rastrillo-budget/v1 ran 59ms
+FAIL amadan.net/oficina/equipo/internal/runner/containment 0.061s
+FAIL
+```
+
+#### 5. host-cgroup
+
+```diff
+--- internal/runner/containment/mounts.go
++++ internal/runner/containment/mounts.go
+@@ -108,7 +108,7 @@
+ return nil, err
+ }
+ p.args = append(p.args, "--overlay-src", "/etc", "--tmp-overlay", "/etc")
+- p.args = append(p.args, "--symlink", "usr/bin", "/bin", "--symlink", "usr/lib", "/lib", "--symlink", "usr/lib64", "/lib64", "--proc", "/proc", "--dev", "/dev", "--dir", "/run", "--dir", "/sys", "--dir", "/home/runner", "--tmpfs", "/etc/claude-code", "--tmpfs", "/etc/codex")
++ p.args = append(p.args, "--symlink", "usr/bin", "/bin", "--symlink", "usr/lib", "/lib", "--symlink", "usr/lib64", "/lib64", "--proc", "/proc", "--dev", "/dev", "--dir", "/run", "--ro-bind", "/sys", "/sys", "--dir", "/home/runner", "--tmpfs", "/etc/claude-code", "--tmpfs", "/etc/codex")
+ if err = p.bind(l.Workspace, "/workspace", false, true); err != nil {
+ return nil, err
+ }
+```
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner/containment -run ^TestNamespaceHidesHostControl$ -count=1 -timeout=20s
+```
+
+```text
+--- FAIL: TestNamespaceHidesHostControl (0.06s)
+ linux_test.go:320: isolation: {Code:1 Signal:0 ObservedAt:2026-11-03 09:56:17.46310184 +0000 UTC} <nil> Traceback (most recent call last):
+ File "<string>", line 3, in <module>
+ assert all(not os.path.exists(p) for p in paths), paths
+ ~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+ AssertionError: ['/sys/fs/cgroup', '/run/user/1001/bus', '/run/user/1001/systemd/private', '/home/paulca', '/proc/1/root/home/paulca', '/etc/claude-code/managed-settings.json', '/etc/codex/config.toml']
+FAIL
+rastrillo-budget/v1 ran 60ms
+FAIL amadan.net/oficina/equipo/internal/runner/containment 0.062s
+FAIL
+```
+
+#### 6. pid-reuse
+
+```diff
+--- internal/runner/containment/recovery.go
++++ internal/runner/containment/recovery.go
+@@ -57,7 +57,7 @@
+ if e != nil {
+ return -1, e
+ }
+- ticks, ns, e := identity(r.HostPID)
++ ticks, ns, e := identity(r.HostPID); _ = ticks
+ // Once released, the helper is nondumpable, so namespace readlink is
+ // denied even to its host parent. Start ticks and NSpid remain readable.
+ // Recover has already matched the durable handshake record; PID namespace
+@@ -66,7 +66,7 @@
+ ns = r.NamespaceID
+ e = nil
+ }
+- if e != nil || ticks != r.StartTicks || ns != r.NamespaceID {
++ if e != nil || ns != r.NamespaceID {
+ unix.Close(fd)
+ return -1, errIdentity
+ }
+```
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner/containment -run ^TestNamespaceRecoveryStaleDurableTicks$ -count=1 -timeout=20s
+```
+
+```text
+--- FAIL: TestNamespaceRecoveryStaleDurableTicks (0.10s)
+ recovery_test.go:162: reused PID accepted
+FAIL
+rastrillo-budget/v1 ran 97ms
+FAIL amadan.net/oficina/equipo/internal/runner/containment 0.099s
+FAIL
+```
+
+#### 7. durable-identity-match
+
+```diff
+--- internal/runner/containment/recovery.go
++++ internal/runner/containment/recovery.go
+@@ -172,7 +172,7 @@
+ }
+ stored, readErr := os.ReadFile(filepath.Join(m.cfg.ScratchRoot, r.ID+".json"))
+ var durable Record
+- if readErr != nil || json.Unmarshal(stored, &durable) != nil || durable != r {
++ if readErr != nil || json.Unmarshal(stored, &durable) != nil || false {
+ return proof, errIdentity
+ }
+ fd, e := exactPID(r)
+```
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner/containment -run ^TestNamespaceRecoveryIdentity/changed_manifest$ -count=1 -timeout=20s
+```
+
+```text
+--- FAIL: TestNamespaceRecoveryIdentity (0.06s)
+ --- FAIL: TestNamespaceRecoveryIdentity/changed_manifest (0.02s)
+ recovery_test.go:36: uncertain identity accepted: {Record:{ID:a0242603aec81d90ce7907ecfa55bec7 AttemptKey:attempt-fixture BootID:1edb59fc-5665-4f1e-84f5-3b03b0992119 NamespaceID:pid:[4026532756] ManifestHash:fixture-policy-changed HostPID:4137163 StartTicks:855761858} Exit:{Code:-1 Signal:9 ObservedAt:2026-11-03 09:58:25.847797305 +0000 UTC} Verified:true} <nil>
+ recovery_test.go:47: owned unrelated control died: no such process
+FAIL
+rastrillo-budget/v1 ran 59ms
+FAIL amadan.net/oficina/equipo/internal/runner/containment 0.061s
+FAIL
+```
+
+#### 8. host-process-as-init
+
+```diff
+--- internal/runner/containment/recovery.go
++++ internal/runner/containment/recovery.go
+@@ -80,7 +80,8 @@
+ init = len(fields) > 2 && fields[len(fields)-1] == "1"
+ }
+ }
+- if hostErr != nil || statusErr != nil || ns == hostNS || !init {
++ _ = hostNS; _ = init
++ if hostErr != nil || statusErr != nil || false {
+ unix.Close(fd)
+ return -1, errIdentity
+ }
+```
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner/containment -run ^TestNamespaceRecoveryRejectsNonInit$ -count=1 -timeout=20s
+```
+
+```text
+--- FAIL: TestNamespaceRecoveryRejectsNonInit (0.07s)
+ recovery_test.go:138: host process accepted as namespace init
+FAIL
+rastrillo-budget/v1 ran 70ms
+FAIL amadan.net/oficina/equipo/internal/runner/containment 0.072s
+FAIL
+```
+
+#### 9. new-boot
+
+```diff
+--- internal/runner/containment/recovery.go
++++ internal/runner/containment/recovery.go
+@@ -159,7 +159,7 @@
+ if e != nil {
+ return proof, e
+ }
+- if boot != r.BootID {
++ if false && boot != r.BootID {
+ proof.Verified = true
+ proof.Exit.ObservedAt = time.Now().UTC()
+ return proof, nil
+```
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner/containment -run ^TestNamespaceRecoveryIdentity$ -count=1 -timeout=20s
+```
+
+```text
+--- FAIL: TestNamespaceRecoveryIdentity (0.04s)
+ recovery_test.go:40: changed boot fabricated outcome: {Record:{ID:f392789dff42e4f75124bd42a5cf93a7 AttemptKey:attempt-fixture BootID:different-boot NamespaceID:pid:[4026532756] ManifestHash:fixture-policy HostPID:4117397 StartTicks:855749121} Exit:{Code:-1 Signal:0 ObservedAt:0001-01-01 00:00:00 +0000 UTC} Verified:false} namespace_identity_unproven
+FAIL
+rastrillo-budget/v1 ran 41ms
+FAIL amadan.net/oficina/equipo/internal/runner/containment 0.042s
+FAIL
+```
+
+#### 10. early-stop-proof
+
+```diff
+--- internal/runner/containment/linux.go
++++ internal/runner/containment/linux.go
+@@ -363,7 +363,7 @@
+ if p == nil {
+ return Proof{}, errIdentity
+ }
+- if e := p.kill(); e != nil {
++ if true { return Proof{Record:p.record,Verified:true},nil }; if e := p.kill(); e != nil {
+ return Proof{Record: p.record}, e
+ }
+ select {
+```
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner/containment -run ^TestNamespaceStopWaitsForExit$ -count=1 -timeout=20s
+```
+
+```text
+--- FAIL: TestNamespaceStopWaitsForExit (0.04s)
+ linux_test.go:463: stop acknowledged before exact init exit
+FAIL
+rastrillo-budget/v1 ran 40ms
+FAIL amadan.net/oficina/equipo/internal/runner/containment 0.041s
+FAIL
+```
+
+#### 11. missing-intent
+
+```diff
+--- internal/runner/containment/linux.go
++++ internal/runner/containment/linux.go
+@@ -128,7 +128,7 @@
+ return nil, e
+ }
+ r := Record{ID: id, AttemptKey: l.AttemptKey, BootID: boot, ManifestHash: l.Policy.Hash}
+- if e = m.persist(r); e != nil {
++ if e = error(nil); e != nil {
+ mounts.close()
+ return nil, e
+ }
+```
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner/containment -run ^TestNamespaceIntentBeforeFork$ -count=1 -timeout=20s
+```
+
+```text
+--- FAIL: TestNamespaceIntentBeforeFork (0.02s)
+ linux_test.go:448: no durable intent before fork: "" open /home/paulca/t/e2b/TestNamespaceIntentBeforeFork420064207/001/workspace/intent-observed: no such file or directory
+FAIL
+rastrillo-budget/v1 ran 20ms
+FAIL amadan.net/oficina/equipo/internal/runner/containment 0.022s
+FAIL
+```
+
+#### 12. missing-identity-journal
+
+```diff
+--- internal/runner/containment/linux.go
++++ internal/runner/containment/linux.go
+@@ -292,7 +292,7 @@
+ }
+ p := &process{record: s.record, stdin: inputW, stdout: outputR, stderr: errorR, done: make(chan struct{}), fd: s.fd}
+ // Identity is durable before the helper can fork the harness or read input.
+- if e = m.persist(s.record); e == nil {
++ if e = error(nil); e == nil {
+ _, e = releaseW.Write([]byte{1})
+ }
+ releaseW.Close()
+```
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner/containment -run ^TestNamespaceKillsDetachedChildren$ -count=1 -timeout=20s
+```
+
+```text
+--- FAIL: TestNamespaceKillsDetachedChildren (0.04s)
+ linux_test.go:187: incomplete durable identity: {ID:97ebba5bb41c66e6369b494b310d3e8f AttemptKey:attempt-fixture BootID:1edb59fc-5665-4f1e-84f5-3b03b0992119 NamespaceID: ManifestHash:fixture-policy HostPID:0 StartTicks:0}
+FAIL
+rastrillo-budget/v1 ran 45ms
+FAIL amadan.net/oficina/equipo/internal/runner/containment 0.046s
+FAIL
+```
+
+#### 13. helper-barrier
+
+```diff
+--- internal/runner/containment/linux.go
++++ internal/runner/containment/linux.go
+@@ -394,7 +394,8 @@
+ return 125
+ }
+ var token [1]byte
+- if _, e = io.ReadFull(release, token[:]); e != nil || token[0] != 1 {
++ if false {
++ _ = token
+ return 125
+ }
+ release.Close()
+```
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner/containment -run ^TestNamespaceHelperBarrier$ -count=1 -timeout=20s
+```
+
+```text
+--- FAIL: TestNamespaceHelperBarrier (0.04s)
+ linux_test.go:576: harness started before release
+FAIL
+rastrillo-budget/v1 ran 36ms
+FAIL amadan.net/oficina/equipo/internal/runner/containment 0.038s
+FAIL
+```
+
+#### 14. helper-protocol-private
+
+```diff
+--- internal/runner/containment/linux.go
++++ internal/runner/containment/linux.go
+@@ -400,7 +400,7 @@
+ release.Close()
+ // The harness shares our UID. Disallow /proc/1/fd reopening and ptrace so
+ // it cannot forge outcome frames or reach future helper-owned relay FDs.
+- if e = unix.Prctl(unix.PR_SET_DUMPABLE, 0, 0, 0, 0); e != nil {
++ if e = error(nil); e != nil {
+ return 125
+ }
+ // No mount descriptors, journal handles or startup pipes reach the harness.
+```
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner/containment -run ^TestNamespaceHelperProtocolPrivate$ -count=1 -timeout=20s
+```
+
+```text
+--- FAIL: TestNamespaceHelperProtocolPrivate (0.06s)
+ linux_test.go:527: helper pipe exposed: {Code:1 Signal:0 ObservedAt:2026-11-03 09:56:19.995892399 +0000 UTC} <nil>
+FAIL
+rastrillo-budget/v1 ran 61ms
+FAIL amadan.net/oficina/equipo/internal/runner/containment 0.063s
+FAIL
+```
+
+#### 15. pinned-mount-swap
+
+```diff
+--- internal/runner/containment/mounts.go
++++ internal/runner/containment/mounts.go
+@@ -78,7 +78,8 @@
+ flag = "--ro-bind-fd"
+ }
+ // FDs 3, 4 and 5 are status, release and readiness, respectively.
+- p.args = append(p.args, flag, strconv.Itoa(6+len(p.files)), target)
++ _ = flag; _ = strconv.Itoa
++ p.args = append(p.args,"--bind",source,target)
+ p.files = append(p.files, f)
+ return nil
+ }
+```
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner/containment -run ^TestNamespacePinnedMountSwap$ -count=1 -timeout=20s
+```
+
+```text
+--- FAIL: TestNamespacePinnedMountSwap (0.04s)
+ mounts_test.go:63: mutable path replaced pinned source: "protected" {Code:0 Signal:0 ObservedAt:2026-11-03 09:56:20.310200347 +0000 UTC} <nil>
+FAIL
+rastrillo-budget/v1 ran 42ms
+FAIL amadan.net/oficina/equipo/internal/runner/containment 0.044s
+FAIL
+```
+
+#### 16. path-traversal
+
+```diff
+--- internal/runner/containment/mounts.go
++++ internal/runner/containment/mounts.go
+@@ -27,7 +27,7 @@
+ }
+ }
+ func cleanAbsolute(path string) bool {
+- return filepath.IsAbs(path) && filepath.Clean(path) == path && path != "/"
++ return filepath.IsAbs(path) && true && path != "/"
+ }
+ func within(path, root string) bool { return path == root || strings.HasPrefix(path, root+"/") }
+ func overlaps(a, b string) bool { return within(a, b) || within(b, a) }
+```
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner/containment -run ^TestNamespaceMountEscape/traversal$ -count=1 -timeout=20s
+```
+
+```text
+--- FAIL: TestNamespaceMountEscape (0.13s)
+ --- FAIL: TestNamespaceMountEscape/traversal (0.05s)
+ recovery_test.go:88: unsafe mount/environment accepted
+ --- FAIL: TestNamespaceMountEscape/home_environment_traversal (0.04s)
+ recovery_test.go:88: unsafe mount/environment accepted
+ --- FAIL: TestNamespaceMountEscape/tmp_environment_traversal (0.04s)
+ recovery_test.go:88: unsafe mount/environment accepted
+FAIL
+rastrillo-budget/v1 ran 126ms
+FAIL amadan.net/oficina/equipo/internal/runner/containment 0.128s
+FAIL
+```
+
+#### 17. outside-home
+
+```diff
+--- internal/runner/containment/mounts.go
++++ internal/runner/containment/mounts.go
+@@ -115,8 +115,8 @@
+ runtimeHome := filepath.Join(dir, "home")
+ if l.Binding.Home != "" {
+ runtimeHome = l.Binding.Home
+- homes := filepath.Join(m.cfg.ScratchRoot, "homes")
+- if !cleanAbsolute(runtimeHome) || filepath.Dir(runtimeHome) != homes || overlaps(runtimeHome, l.Workspace) {
++ homes := filepath.Join(m.cfg.ScratchRoot, "homes"); _ = homes
++ if !cleanAbsolute(runtimeHome) || false || overlaps(runtimeHome, l.Workspace) {
+ return nil, errMount
+ }
+ info, e := os.Stat(runtimeHome)
+```
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner/containment -run ^TestNamespaceMountEscape/outside_private_home$ -count=1 -timeout=20s
+```
+
+```text
+--- FAIL: TestNamespaceMountEscape (0.06s)
+ --- FAIL: TestNamespaceMountEscape/outside_private_home (0.06s)
+ recovery_test.go:95: unsafe mount/environment accepted
+FAIL
+rastrillo-budget/v1 ran 65ms
+FAIL amadan.net/oficina/equipo/internal/runner/containment 0.067s
+FAIL
+```
+
+#### 18. protected-state-overlap
+
+```diff
+--- internal/runner/containment/mounts.go
++++ internal/runner/containment/mounts.go
+@@ -89,7 +89,7 @@
+ p.close()
+ }
+ }()
+- if !cleanAbsolute(l.Workspace) || overlaps(l.Workspace, m.cfg.ScratchRoot) {
++ if !cleanAbsolute(l.Workspace) || false {
+ return nil, errMount
+ }
+ for _, root := range []string{"/proc", "/sys", "/run", "/dev", "/etc", "/usr"} {
+```
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner/containment -run ^TestNamespaceMountEscape/protected_state$ -count=1 -timeout=20s
+```
+
+```text
+--- FAIL: TestNamespaceMountEscape (0.08s)
+ --- FAIL: TestNamespaceMountEscape/protected_state (0.04s)
+ recovery_test.go:88: unsafe mount/environment accepted
+ --- FAIL: TestNamespaceMountEscape/parent_of_protected_state (0.04s)
+ recovery_test.go:88: unsafe mount/environment accepted
+FAIL
+rastrillo-budget/v1 ran 77ms
+FAIL amadan.net/oficina/equipo/internal/runner/containment 0.079s
+FAIL
+```
+
+#### 19. writable-runtime-request
+
+```diff
+--- internal/runner/containment/mounts.go
++++ internal/runner/containment/mounts.go
+@@ -136,7 +136,7 @@
+ targets := map[string]bool{}
+ for _, mount := range l.Policy.Mounts {
+ target := mount.Target
+- if !mount.ReadOnly || !cleanAbsolute(target) || targets[target] {
++ if !cleanAbsolute(target) || targets[target] {
+ return nil, errMount
+ }
+ if !(strings.HasPrefix(target, "/opt/") || strings.HasPrefix(target, "/config/") || strings.HasPrefix(target, "/etc/claude-code/") || strings.HasPrefix(target, "/etc/codex/")) {
+```
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner/containment -run ^TestNamespaceMountEscape/writable_runtime$ -count=1 -timeout=20s
+```
+
+```text
+--- FAIL: TestNamespaceMountEscape (0.04s)
+ --- FAIL: TestNamespaceMountEscape/writable_runtime (0.04s)
+ recovery_test.go:88: unsafe mount/environment accepted
+FAIL
+rastrillo-budget/v1 ran 41ms
+FAIL amadan.net/oficina/equipo/internal/runner/containment 0.043s
+FAIL
+```
+
+#### 20. reserved-mount-target
+
+```diff
+--- internal/runner/containment/mounts.go
++++ internal/runner/containment/mounts.go
+@@ -139,7 +139,7 @@
+ if !mount.ReadOnly || !cleanAbsolute(target) || targets[target] {
+ return nil, errMount
+ }
+- if !(strings.HasPrefix(target, "/opt/") || strings.HasPrefix(target, "/config/") || strings.HasPrefix(target, "/etc/claude-code/") || strings.HasPrefix(target, "/etc/codex/")) {
++ if false {
+ return nil, errMount
+ }
+ for _, existing := range l.Policy.Mounts {
+```
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner/containment -run ^TestNamespaceMountEscape/reserved_target$ -count=1 -timeout=20s
+```
+
+```text
+--- FAIL: TestNamespaceMountEscape (0.04s)
+ --- FAIL: TestNamespaceMountEscape/reserved_target (0.04s)
+ recovery_test.go:88: unsafe mount/environment accepted
+FAIL
+rastrillo-budget/v1 ran 43ms
+FAIL amadan.net/oficina/equipo/internal/runner/containment 0.045s
+FAIL
+```
+
+#### 21. environment-allowlist
+
+```diff
+--- internal/runner/containment/mounts.go
++++ internal/runner/containment/mounts.go
+@@ -160,14 +160,15 @@
+ }
+ p.args = append(p.args, "--clearenv", "--setenv", "PATH", "/usr/bin:/bin:/opt", "--setenv", "HOME", "/home/runner", "--setenv", "TMPDIR", "/tmp", "--setenv", "LANG", "C.UTF-8")
+ allowed := map[string]bool{"LANG": true, "LC_ALL": true, "TERM": true, "CODEX_HOME": true, "CLAUDE_CONFIG_DIR": true, "CLAUDE_SECURESTORAGE_CONFIG_DIR": true, "CLAUDE_TMPDIR": true, "CLAUDE_CODE_DISABLE_AUTO_UPDATE": true}
+- keys := make([]string, 0, len(l.Policy.Env))
++ _ = allowed
++ keys := make([]string, 0, len(l.Policy.Env))
+ for k := range l.Policy.Env {
+ keys = append(keys, k)
+ }
+ sort.Strings(keys)
+ for _, k := range keys {
+ v := l.Policy.Env[k]
+- if !allowed[k] || strings.ContainsRune(v, 0) {
++ if strings.ContainsRune(v, 0) {
+ return nil, errMount
+ }
+ if (k == "CODEX_HOME" || k == "CLAUDE_CONFIG_DIR" || k == "CLAUDE_SECURESTORAGE_CONFIG_DIR") && (!cleanAbsolute(v) || !within(v, "/home/runner")) {
+```
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner/containment -run ^TestNamespaceMountEscape/environment$ -count=1 -timeout=20s
+```
+
+```text
+--- FAIL: TestNamespaceMountEscape (0.04s)
+ --- FAIL: TestNamespaceMountEscape/environment (0.04s)
+ recovery_test.go:88: unsafe mount/environment accepted
+FAIL
+rastrillo-budget/v1 ran 42ms
+FAIL amadan.net/oficina/equipo/internal/runner/containment 0.044s
+FAIL
+```
+
+#### 22. environment-home-traversal
+
+```diff
+--- internal/runner/containment/mounts.go
++++ internal/runner/containment/mounts.go
+@@ -170,7 +170,7 @@
+ if !allowed[k] || strings.ContainsRune(v, 0) {
+ return nil, errMount
+ }
+- if (k == "CODEX_HOME" || k == "CLAUDE_CONFIG_DIR" || k == "CLAUDE_SECURESTORAGE_CONFIG_DIR") && (!cleanAbsolute(v) || !within(v, "/home/runner")) {
++ if (k == "CODEX_HOME" || k == "CLAUDE_CONFIG_DIR" || k == "CLAUDE_SECURESTORAGE_CONFIG_DIR") && (!within(v,"/home/runner")) {
+ return nil, errMount
+ }
+ if k == "CLAUDE_TMPDIR" && (!cleanAbsolute(v) || !within(v, "/tmp")) {
+```
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner/containment -run ^TestNamespaceMountEscape/home_environment_traversal$ -count=1 -timeout=20s
+```
+
+```text
+--- FAIL: TestNamespaceMountEscape (0.04s)
+ --- FAIL: TestNamespaceMountEscape/home_environment_traversal (0.04s)
+ recovery_test.go:88: unsafe mount/environment accepted
+FAIL
+rastrillo-budget/v1 ran 43ms
+FAIL amadan.net/oficina/equipo/internal/runner/containment 0.045s
+FAIL
+```
+
+#### 23. environment-tmp-traversal
+
+```diff
+--- internal/runner/containment/mounts.go
++++ internal/runner/containment/mounts.go
+@@ -173,7 +173,7 @@
+ if (k == "CODEX_HOME" || k == "CLAUDE_CONFIG_DIR" || k == "CLAUDE_SECURESTORAGE_CONFIG_DIR") && (!cleanAbsolute(v) || !within(v, "/home/runner")) {
+ return nil, errMount
+ }
+- if k == "CLAUDE_TMPDIR" && (!cleanAbsolute(v) || !within(v, "/tmp")) {
++ if k == "CLAUDE_TMPDIR" && (!within(v,"/tmp")) {
+ return nil, errMount
+ }
+ p.args = append(p.args, "--setenv", k, v)
+```
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner/containment -run ^TestNamespaceMountEscape/tmp_environment_traversal$ -count=1 -timeout=20s
+```
+
+```text
+--- FAIL: TestNamespaceMountEscape (0.04s)
+ --- FAIL: TestNamespaceMountEscape/tmp_environment_traversal (0.04s)
+ recovery_test.go:88: unsafe mount/environment accepted
+FAIL
+rastrillo-budget/v1 ran 44ms
+FAIL amadan.net/oficina/equipo/internal/runner/containment 0.046s
+FAIL
+```
+
+#### 24. socket-import
+
+```diff
+--- internal/runner/containment/mounts.go
++++ internal/runner/containment/mounts.go
+@@ -63,7 +63,7 @@
+ if e != nil {
+ return e
+ }
+- if d.Type()&(os.ModeSocket|os.ModeNamedPipe|os.ModeDevice) != 0 {
++ if false {
+ return errMount
+ }
+ return nil
+```
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner/containment -run ^TestNamespaceSocketImport$ -count=1 -timeout=20s
+```
+
+```text
+--- FAIL: TestNamespaceSocketImport (0.04s)
+ linux_test.go:501: host socket imported
+FAIL
+rastrillo-budget/v1 ran 42ms
+FAIL amadan.net/oficina/equipo/internal/runner/containment 0.044s
+FAIL
+```
+
+#### 25. nested-userns
+
+```diff
+--- internal/runner/containment/linux.go
++++ internal/runner/containment/linux.go
+@@ -204,7 +204,7 @@
+ result <- startResult{err: e}
+ return
+ }
+- args := []string{"--unshare-user", "--unshare-pid", "--unshare-ipc", "--unshare-uts", "--unshare-cgroup", "--unshare-net", "--die-with-parent", "--new-session", "--as-pid-1", "--cap-drop", "ALL", "--json-status-fd", "3"}
++ args := []string{"--unshare-user", "--disable-userns", "--unshare-pid", "--unshare-ipc", "--unshare-uts", "--unshare-cgroup", "--unshare-net", "--die-with-parent", "--new-session", "--as-pid-1", "--cap-drop", "ALL", "--json-status-fd", "3"}
+ args = append(args, mounts.args...)
+ args = append(args, "--", "/equipo-namespace", "__namespace")
+ args = append(args, argv...)
+```
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner/containment -run ^TestNamespaceNestedUserNamespace$ -count=1 -timeout=20s
+```
+
+```text
+--- FAIL: TestNamespaceNestedUserNamespace (0.07s)
+ linux_test.go:510: nested sandbox unavailable: {Code:1 Signal:0 ObservedAt:2026-11-03 09:56:23.512872421 +0000 UTC} <nil> bwrap: Creating new namespace failed: nesting depth or /proc/sys/user/max_*_namespaces exceeded (ENOSPC)
+ Traceback (most recent call last):
+ File "<string>", line 1, in <module>
+ import subprocess; subprocess.run(['/usr/bin/bwrap','--unshare-user','--ro-bind','/','/','--','/usr/bin/true'],check=True)
+ ~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+ File "/usr/lib/python3.13/subprocess.py", line 577, in run
+ raise CalledProcessError(retcode, process.args,
+ output=stdout, stderr=stderr)
+ subprocess.CalledProcessError: Command '['/usr/bin/bwrap', '--unshare-user', '--ro-bind', '/', '/', '--', '/usr/bin/true']' returned non-zero exit status 1.
+FAIL
+rastrillo-budget/v1 ran 75ms
+FAIL amadan.net/oficina/equipo/internal/runner/containment 0.077s
+FAIL
+```
+
+#### 26. caller-thread-lifetime
+
+```diff
+--- internal/runner/containment/linux.go
++++ internal/runner/containment/linux.go
+@@ -215,7 +215,7 @@
+ cmd.Stdout = outputW
+ cmd.Stderr = errorW
+ cmd.SysProcAttr = &syscall.SysProcAttr{Pdeathsig: syscall.SIGKILL}
+- if e = cmd.Start(); e != nil {
++ startedOnThread:=make(chan error,1); go func(){runtime.LockOSThread(); startedOnThread<-cmd.Start()}(); if e = <-startedOnThread; e != nil {
+ result <- startResult{err: e}
+ return
+ }
+```
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner/containment -run ^TestNamespaceStartingThreadExit$ -count=1 -timeout=20s
+```
+
+```text
+--- FAIL: TestNamespaceStartingThreadExit (0.02s)
+ linux_test.go:405: start failed
+FAIL
+rastrillo-budget/v1 ran 16ms
+FAIL amadan.net/oficina/equipo/internal/runner/containment 0.018s
+FAIL
+```
+
+#### 27. context-cancellation
+
+```diff
+--- internal/runner/containment/linux.go
++++ internal/runner/containment/linux.go
+@@ -314,7 +314,7 @@
+ go func() {
+ select {
+ case <-ctx.Done():
+- p.kill()
++ // mutation
+ case <-lifecycleDone:
+ }
+ }()
+```
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner/containment -run ^TestNamespaceCancellation$ -count=1 -timeout=20s
+```
+
+```text
+--- FAIL: TestNamespaceCancellation (2.04s)
+ linux_test.go:633: context deadline exceeded
+FAIL
+rastrillo-budget/v1 ran 2.042s
+FAIL amadan.net/oficina/equipo/internal/runner/containment 2.044s
+FAIL
+```
+
+#### 28. ci-required-target
+
+```diff
+--- Makefile
++++ Makefile
+@@ -156,7 +156,7 @@
+ # fails the build the moment models.go and migrations/ disagree,
+ # instead of at boot on whatever machine notices next. If the app
+ # declares manifest resources, also add: rastrillo generate --check
+-ci: build vet fmt-check staticcheck govulncheck gitleaks budget test runner-adapter-test runner-namespace-test migration-check perf
++ci: build vet fmt-check staticcheck govulncheck gitleaks budget test runner-adapter-test migration-check perf
+
+ .PHONY: copy-release-check release-runner runner-prerequisites
+ copy-release-check:
+```
+
+```sh
+CGO_ENABLED=0 go test ./internal/equipotest -run ^TestCIGateSteps$ -count=1 -timeout=20s
+```
+
+```text
+--- FAIL: TestCIGateSteps (0.01s)
+ foundation_test.go:185: make ci targets = [budget build fmt-check gitleaks govulncheck migration-check perf runner-adapter-test staticcheck test vet], want [budget build fmt-check gitleaks govulncheck migration-check perf runner-adapter-test runner-namespace-test staticcheck test vet]
+FAIL
+rastrillo-budget/v1 ran 12ms
+FAIL amadan.net/oficina/equipo/internal/equipotest 0.061s
+FAIL
+```
+
+#### 29. ci-delegation
+
+```diff
+--- .amadan/ci.d/36-runner-namespaces
++++ .amadan/ci.d/36-runner-namespaces
+@@ -1,2 +1,2 @@
+ #!/bin/sh
+-exec make runner-namespace-test
++exec make runner-adapter-test
+```
+
+```sh
+CGO_ENABLED=0 go test ./internal/equipotest -run ^TestCIGateSteps$ -count=1 -timeout=20s
+```
+
+```text
+--- FAIL: TestCIGateSteps (0.01s)
+ foundation_test.go:221: CI step targets = [budget build fmt-check gitleaks govulncheck migration-check perf runner-adapter-test runner-adapter-test staticcheck test vet], want [budget build fmt-check gitleaks govulncheck migration-check perf runner-adapter-test runner-namespace-test staticcheck test vet]
+FAIL
+rastrillo-budget/v1 ran 13ms
+FAIL amadan.net/oficina/equipo/internal/equipotest 0.061s
+FAIL
+```
+
+#### 30. parent-death
+
+```diff
+--- internal/runner/containment/linux.go
++++ internal/runner/containment/linux.go
+@@ -204,7 +204,7 @@
+ result <- startResult{err: e}
+ return
+ }
+- args := []string{"--unshare-user", "--unshare-pid", "--unshare-ipc", "--unshare-uts", "--unshare-cgroup", "--unshare-net", "--die-with-parent", "--new-session", "--as-pid-1", "--cap-drop", "ALL", "--json-status-fd", "3"}
++ args := []string{"--unshare-user", "--unshare-pid", "--unshare-ipc", "--unshare-uts", "--unshare-cgroup", "--unshare-net", "--new-session", "--as-pid-1", "--cap-drop", "ALL", "--json-status-fd", "3"}
+ args = append(args, mounts.args...)
+ args = append(args, "--", "/equipo-namespace", "__namespace")
+ args = append(args, argv...)
+@@ -214,7 +214,7 @@
+ cmd.Stdin = inputR
+ cmd.Stdout = outputW
+ cmd.Stderr = errorW
+- cmd.SysProcAttr = &syscall.SysProcAttr{Pdeathsig: syscall.SIGKILL}
++ cmd.SysProcAttr = &syscall.SysProcAttr{Pdeathsig: 0}
+ if e = cmd.Start(); e != nil {
+ result <- startResult{err: e}
+ return
+```
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner/containment -run ^TestNamespaceParentDeath$ -count=1 -timeout=20s
+```
+
+```text
+--- FAIL: TestNamespaceParentDeath (5.06s)
+ linux_test.go:388: exact process has not exited: poll=0,<nil>
+FAIL
+rastrillo-budget/v1 ran 5.064s
+FAIL amadan.net/oficina/equipo/internal/runner/containment 5.066s
+FAIL
+```
+
+#### 31. capabilities
+
+```diff
+--- internal/runner/containment/linux.go
++++ internal/runner/containment/linux.go
+@@ -204,7 +204,7 @@
+ result <- startResult{err: e}
+ return
+ }
+- args := []string{"--unshare-user", "--unshare-pid", "--unshare-ipc", "--unshare-uts", "--unshare-cgroup", "--unshare-net", "--die-with-parent", "--new-session", "--as-pid-1", "--cap-drop", "ALL", "--json-status-fd", "3"}
++ args := []string{"--unshare-user", "--unshare-pid", "--unshare-ipc", "--unshare-uts", "--unshare-cgroup", "--unshare-net", "--die-with-parent", "--new-session", "--as-pid-1", "--cap-add", "ALL", "--json-status-fd", "3"}
+ args = append(args, mounts.args...)
+ args = append(args, "--", "/equipo-namespace", "__namespace")
+ args = append(args, argv...)
+```
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner/containment -run ^TestNamespaceHidesHostControl$ -count=1 -timeout=20s
+```
+
+```text
+--- FAIL: TestNamespaceHidesHostControl (0.06s)
+ linux_test.go:320: isolation: {Code:1 Signal:0 ObservedAt:2026-11-03 09:57:28.680147135 +0000 UTC} <nil> Traceback (most recent call last):
+ File "<string>", line 7, in <module>
+ assert int([l for l in open('/proc/self/status') if l.startswith('CapEff:')][0].split()[1],16)==0
+ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+ AssertionError
+FAIL
+rastrillo-budget/v1 ran 59ms
+FAIL amadan.net/oficina/equipo/internal/runner/containment 0.061s
+FAIL
+```
+
+#### 32. helper-exec
+
+```diff
+--- internal/runner/containment/linux.go
++++ internal/runner/containment/linux.go
+@@ -408,7 +408,8 @@
+ if e = unix.CloseRange(3, ^uint(0), unix.CLOSE_RANGE_CLOEXEC); e != nil {
+ return 125
+ }
+- cmd := exec.Command(argv[0], argv[1:]...)
++ _ = syscall.Exec(argv[0],argv,os.Environ())
++ cmd := exec.Command(argv[0], argv[1:]...)
+ cmd.Env = os.Environ()
+ cmd.Stdin = os.Stdin
+ cmd.Stdout = os.Stdout
+```
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner/containment -run ^TestNamespaceHidesHostControl$ -count=1 -timeout=20s
+```
+
+```text
+--- FAIL: TestNamespaceHidesHostControl (0.06s)
+ linux_test.go:320: isolation: {Code:-1 Signal:0 ObservedAt:2026-11-03 09:57:28.997468124 +0000 UTC} <nil> Traceback (most recent call last):
+ File "<string>", line 6, in <module>
+ assert os.getppid()==1
+ ^^^^^^^^^^^^^^^
+ AssertionError
+FAIL
+rastrillo-budget/v1 ran 58ms
+FAIL amadan.net/oficina/equipo/internal/runner/containment 0.060s
+FAIL
+```
+
+#### 33. orphan-reaper
+
+```diff
+--- internal/runner/containment/linux.go
++++ internal/runner/containment/linux.go
+@@ -418,7 +418,7 @@
+ }
+ for {
+ var status unix.WaitStatus
+- pid, e := unix.Wait4(-1, &status, 0, nil)
++ pid, e := unix.Wait4(cmd.Process.Pid, &status, 0, nil)
+ if e == unix.EINTR {
+ continue
+ }
+```
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner/containment -run ^TestNamespaceReapsOrphans$ -count=1 -timeout=20s
+```
+
+```text
+--- FAIL: TestNamespaceReapsOrphans (1.12s)
+ linux_test.go:611: orphan not reaped: {Code:1 Signal:0 ObservedAt:2026-11-03 09:57:30.379589918 +0000 UTC} <nil>
+FAIL
+rastrillo-budget/v1 ran 1.123s
+FAIL amadan.net/oficina/equipo/internal/runner/containment 1.124s
+FAIL
+```
+
+#### 34. missing-exit-proof
+
+```diff
+--- internal/runner/containment/recovery.go
++++ internal/runner/containment/recovery.go
+@@ -176,9 +176,7 @@
+ return proof, errIdentity
+ }
+ fd, e := exactPID(r)
+- if e != nil {
+- return proof, errIdentity
+- }
++ if e != nil {proof.Verified=true;return proof,nil}
+ defer unix.Close(fd)
+ if e = unix.PidfdSendSignal(fd, unix.SIGKILL, nil, 0); e != nil && e != unix.ESRCH {
+ return proof, e
+```
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner/containment -run ^TestNamespaceRecoveryUnavailableProof/missing$ -count=1 -timeout=20s
+```
+
+```text
+--- FAIL: TestNamespaceRecoveryUnavailableProof (0.07s)
+ --- FAIL: TestNamespaceRecoveryUnavailableProof/missing (0.07s)
+ recovery_test.go:207: unavailable proof accepted: {Record:{ID:369fcb474959338628b2a032a0239739 AttemptKey:attempt-fixture BootID:1edb59fc-5665-4f1e-84f5-3b03b0992119 NamespaceID:pid:[4026532756] ManifestHash:fixture-policy HostPID:28648 StartTicks:855796599} Exit:{Code:-1 Signal:0 ObservedAt:0001-01-01 00:00:00 +0000 UTC} Verified:true} <nil>
+FAIL
+rastrillo-budget/v1 ran 68ms
+FAIL amadan.net/oficina/equipo/internal/runner/containment 0.070s
+FAIL
+```
+
+#### 35. saved-proof-record
+
+```diff
+--- internal/runner/containment/recovery.go
++++ internal/runner/containment/recovery.go
+@@ -162,7 +162,7 @@
+ saved, readErr := os.ReadFile(filepath.Join(m.cfg.ScratchRoot, r.ID+".exit.json"))
+ if readErr == nil {
+ var prior Proof
+- if json.Unmarshal(saved, &prior) != nil || !prior.Verified || prior.Record != r || prior.Exit.ObservedAt.IsZero() {
++ if json.Unmarshal(saved, &prior) != nil || !prior.Verified || false || prior.Exit.ObservedAt.IsZero() {
+ return proof, errIdentity
+ }
+ return prior, nil
+```
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner/containment -run ^TestNamespaceRecoveryUnavailableProof/record$ -count=1 -timeout=20s
+```
+
+```text
+--- FAIL: TestNamespaceRecoveryUnavailableProof (0.09s)
+ --- FAIL: TestNamespaceRecoveryUnavailableProof/record (0.09s)
+ recovery_test.go:207: unavailable proof accepted: {Record:{ID:544287cb133e57ee8eeba3cf9dde3609 AttemptKey:attempt-fixture BootID:1edb59fc-5665-4f1e-84f5-3b03b0992119 NamespaceID:pid:[4026532756] ManifestHash:fixture-policy-changed HostPID:28794 StartTicks:855796630} Exit:{Code:0 Signal:0 ObservedAt:2026-11-03 10:04:13.581739442 +0000 UTC} Verified:true} <nil>
+FAIL
+rastrillo-budget/v1 ran 91ms
+FAIL amadan.net/oficina/equipo/internal/runner/containment 0.093s
+FAIL
+```
+
+#### 36. saved-proof-verified
+
+```diff
+--- internal/runner/containment/recovery.go
++++ internal/runner/containment/recovery.go
+@@ -162,7 +162,7 @@
+ saved, readErr := os.ReadFile(filepath.Join(m.cfg.ScratchRoot, r.ID+".exit.json"))
+ if readErr == nil {
+ var prior Proof
+- if json.Unmarshal(saved, &prior) != nil || !prior.Verified || prior.Record != r || prior.Exit.ObservedAt.IsZero() {
++ if json.Unmarshal(saved, &prior) != nil || prior.Record != r || prior.Exit.ObservedAt.IsZero() {
+ return proof, errIdentity
+ }
+ return prior, nil
+```
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner/containment -run ^TestNamespaceRecoveryUnavailableProof/unverified$ -count=1 -timeout=20s
+```
+
+```text
+--- FAIL: TestNamespaceRecoveryUnavailableProof (0.08s)
+ --- FAIL: TestNamespaceRecoveryUnavailableProof/unverified (0.08s)
+ recovery_test.go:207: unavailable proof accepted: {Record:{ID:d066fc984cd29c3614bdab6900298251 AttemptKey:attempt-fixture BootID:1edb59fc-5665-4f1e-84f5-3b03b0992119 NamespaceID:pid:[4026532756] ManifestHash:fixture-policy HostPID:28943 StartTicks:855796663} Exit:{Code:0 Signal:0 ObservedAt:2026-11-03 10:04:13.908239355 +0000 UTC} Verified:false} <nil>
+FAIL
+rastrillo-budget/v1 ran 81ms
+FAIL amadan.net/oficina/equipo/internal/runner/containment 0.082s
+FAIL
+```
+
+#### 37. saved-proof-timestamp
+
+```diff
+--- internal/runner/containment/recovery.go
++++ internal/runner/containment/recovery.go
+@@ -162,7 +162,7 @@
+ saved, readErr := os.ReadFile(filepath.Join(m.cfg.ScratchRoot, r.ID+".exit.json"))
+ if readErr == nil {
+ var prior Proof
+- if json.Unmarshal(saved, &prior) != nil || !prior.Verified || prior.Record != r || prior.Exit.ObservedAt.IsZero() {
++ if json.Unmarshal(saved, &prior) != nil || !prior.Verified || prior.Record != r || false {
+ return proof, errIdentity
+ }
+ return prior, nil
+```
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner/containment -run ^TestNamespaceRecoveryUnavailableProof/timestamp$ -count=1 -timeout=20s
+```
+
+```text
+--- FAIL: TestNamespaceRecoveryUnavailableProof (0.09s)
+ --- FAIL: TestNamespaceRecoveryUnavailableProof/timestamp (0.09s)
+ recovery_test.go:207: unavailable proof accepted: {Record:{ID:ca585ad93eb5985eb3b497ff7ad1a2c3 AttemptKey:attempt-fixture BootID:1edb59fc-5665-4f1e-84f5-3b03b0992119 NamespaceID:pid:[4026532756] ManifestHash:fixture-policy HostPID:29083 StartTicks:855796695} Exit:{Code:0 Signal:0 ObservedAt:0001-01-01 00:00:00 +0000 UTC} Verified:true} <nil>
+FAIL
+rastrillo-budget/v1 ran 86ms
+FAIL amadan.net/oficina/equipo/internal/runner/containment 0.087s
+FAIL
+```
+
+#### 38. scratch-identity
+
+```diff
+--- internal/runner/containment/linux.go
++++ internal/runner/containment/linux.go
+@@ -103,7 +103,7 @@
+ return nil, e
+ }
+ id := hex.EncodeToString(random[:])
+- dir := filepath.Join(m.cfg.ScratchRoot, "attempt-"+id)
++ dir := filepath.Join(m.cfg.ScratchRoot, "attempt-unbound-"+id)
+ e := os.Mkdir(dir, 0700)
+ if e != nil {
+ return nil, e
+```
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner/containment -run ^TestNamespaceScratchIdentity$ -count=1 -timeout=20s
+```
+
+```text
+--- FAIL: TestNamespaceScratchIdentity (0.06s)
+ recovery_test.go:253: scratch not bound to durable ID: stat /home/paulca/t/e2b/TestNamespaceScratchIdentity886275472/001/state/attempt-763177bb8fd50b41613e8f03dcd4a072/tmp: no such file or directory
+FAIL
+rastrillo-budget/v1 ran 64ms
+FAIL amadan.net/oficina/equipo/internal/runner/containment 0.065s
+FAIL
+```
+
+#### 39. recover-scratch
+
+```diff
+--- internal/runner/containment/recovery.go
++++ internal/runner/containment/recovery.go
+@@ -198,7 +198,7 @@
+ // Scratch has the durable launch ID, so recovery can remove only this attempt
+ // after proving its namespace gone. Unknown same-boot identities keep it.
+ func (m *Manager) finishRecovery(proof Proof) (Proof, error) {
+- if err := os.RemoveAll(filepath.Join(m.cfg.ScratchRoot, "attempt-"+proof.Record.ID)); err != nil {
++ if err := error(nil); err != nil {
+ proof.Verified = false
+ return proof, err
+ }
+```
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner/containment -run ^TestNamespaceRecoveryCleansScratch$ -count=1 -timeout=20s
+```
+
+```text
+--- FAIL: TestNamespaceRecoveryCleansScratch (0.14s)
+ --- FAIL: TestNamespaceRecoveryCleansScratch/saved-exit (0.07s)
+ recovery_test.go:231: open /home/paulca/t/e2b/TestNamespaceRecoveryCleansScratchsaved-exit2381641995/001/state/attempt-845fcb06c50f2c04ee16205f0b4c04bd/leftover: no such file or directory
+ --- FAIL: TestNamespaceRecoveryCleansScratch/new-boot (0.07s)
+ recovery_test.go:231: open /home/paulca/t/e2b/TestNamespaceRecoveryCleansScratchnew-boot1938237438/001/state/attempt-4f8085b1db96f9efac2208629c939bf0/leftover: no such file or directory
+FAIL
+rastrillo-budget/v1 ran 142ms
+FAIL amadan.net/oficina/equipo/internal/runner/containment 0.143s
+FAIL
+```
+
+#### 40. unproven-scratch
+
+```diff
+--- internal/runner/containment/recovery.go
++++ internal/runner/containment/recovery.go
+@@ -143,7 +143,8 @@
+ // Recover never enumerates host processes. An absent same-boot PID without a
+ // durable exit proof remains uncertain; a new boot proves absence, not outcome.
+ func (m *Manager) Recover(ctx context.Context, r Record) (Proof, error) {
+- proof := Proof{Record: r, Exit: provider.Exit{Code: -1}}
++ defer os.RemoveAll(filepath.Join(m.cfg.ScratchRoot,"attempt-"+r.ID))
++ proof := Proof{Record: r, Exit: provider.Exit{Code: -1}}
+ if len(r.ID) != 32 || strings.ContainsAny(r.ID, "/.\\") || r.AttemptKey == "" || r.BootID == "" || r.ManifestHash == "" {
+ return proof, errIdentity
+ }
+```
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner/containment -run ^TestNamespaceRecoveryIdentity/reused_pid$ -count=1 -timeout=20s
+```
+
+```text
+--- FAIL: TestNamespaceRecoveryIdentity (0.06s)
+ --- FAIL: TestNamespaceRecoveryIdentity/reused_pid (0.00s)
+ recovery_test.go:42: unproven recovery removed scratch: stat /home/paulca/t/e2b/TestNamespaceRecoveryIdentity926612942/001/state/attempt-7f9d15402e810a584d666df62a4b37ff: no such file or directory
+FAIL
+rastrillo-budget/v1 ran 56ms
+FAIL amadan.net/oficina/equipo/internal/runner/containment 0.057s
+FAIL
+```
+
+Four exploratory mutation attempts were not counted: removing the ticks check first failed compilation because `ticks` became unused; the corrected mutation added `_ = ticks`. Removing the durable-record comparison twice survived a namespace-mismatch case because the independent kernel namespace check still rejected it; the final test changes a nonempty manifest hash to isolate the durable-record guard. The outside-home mutation first survived because the fixture also violated the home mode requirement; setting that fixture to 0700 isolated the location guard. All four originals were restored, and the corrected mutations above compiled and failed their named tests.
+
+### User-facing strings
+
+No UI strings, README prose or copy.go entries were added. Internal error codes are `namespace_mount_rejected`, `namespace_identity_unproven`, `namespace_startup_failed` and `namespace_bubblewrap_version`. The internal startup error may include a bounded bubblewrap diagnostic (4096 bytes). If later exposed in the app, map these codes to individually pending copy.go entries for review. Test-only diagnostics include `namespace capability missing`, `namespace capability/start failed (userns, pidfd required)`, and `capability missing` messages for delegated cgroups, pidfd_open, pidfd_send_signal and waitid. No copy-review skill or server was used, as instructed.
+
+### Concerns and remaining work
+
+The remote worker proof is pending the controller's push. Local capability is proven; a remote worker without userns, pidfd, overlay mounts or writable delegated test cgroups will fail the required namespace job. Worker labels alone are not evidence.
+
+Recovery intentionally blocks same-boot reuse if launch identity or durable exit evidence is unavailable. It does not infer a successful provider outcome from containment. Account-content hashing, provider preflight, the in-namespace relay, check execution, capture integration and provider certification remain later tasks. This task does not make a provider run or claim the release is certified.
+
+No push, merge, deployment, sign-in, enrolment, credential import, model prompt or subagent was performed. All test processes and cgroups were cleaned up. After saving these reports, the task-owned evidence directory under TMPDIR is removed. Go caches are unchanged. No server or background process is left running by this task. The requested report remains under `.superpowers` (already ignored); the full controller section is committed.
diff --git a/internal/equipotest/foundation_test.go b/internal/equipotest/foundation_test.go
index 16eae6aa..f3a63bda 100644
--- a/internal/equipotest/foundation_test.go
+++ b/internal/equipotest/foundation_test.go
@@ -168,7 +168,7 @@ func TestFoundationMigratesTwice(t *testing.T) {
// each must fail. Executing with a fake make also checks shell behavior.
func TestCIGateSteps(t *testing.T) {
root := filepath.Join("..", "..")
- want := []string{"build", "vet", "fmt-check", "staticcheck", "govulncheck", "gitleaks", "budget", "test", "runner-adapter-test", "migration-check", "perf"}
+ want := []string{"build", "vet", "fmt-check", "staticcheck", "govulncheck", "gitleaks", "budget", "test", "runner-adapter-test", "runner-namespace-test", "migration-check", "perf"}
sort.Strings(want)
contents, err := os.ReadFile(filepath.Join(root, "Makefile"))
if err != nil {
diff --git a/internal/runner/containment/budget_test.go b/internal/runner/containment/budget_test.go
new file mode 100644
index 00000000..04f87439
--- /dev/null
+++ b/internal/runner/containment/budget_test.go
@@ -0,0 +1,18 @@
+package containment
+
+import (
+ "amadan.net/rastrillo/rastrillo/budget"
+ "os"
+ "testing"
+)
+
+func TestMain(m *testing.M) {
+ if len(os.Args) > 1 && os.Args[1] == "__namespace" {
+ os.Exit(NamespaceMain(os.Args[2:]))
+ }
+ if os.Getenv("EQUIPO_NAMESPACE_PARENT_TEST") == "1" {
+ parentFixture()
+ return
+ }
+ os.Exit(budget.Main(m))
+}
diff --git a/internal/runner/containment/linux.go b/internal/runner/containment/linux.go
new file mode 100644
index 00000000..928de68c
--- /dev/null
+++ b/internal/runner/containment/linux.go
@@ -0,0 +1,452 @@
+// Package containment owns attempt lifetimes through Linux PID namespaces.
+package containment
+
+import (
+ "context"
+ "crypto/rand"
+ "encoding/hex"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "io"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "runtime"
+ "sync"
+ "syscall"
+ "time"
+
+ "amadan.net/oficina/equipo/internal/runner/provider"
+ "golang.org/x/sys/unix"
+)
+
+type Config struct{ Binary, RunnerBinary, ScratchRoot string }
+type Manager struct {
+ cfg Config
+ mu sync.Mutex
+ processes map[string]*process
+}
+
+var _ provider.ProcessHost = (*Manager)(nil)
+var errStartup = errors.New("namespace_startup_failed")
+
+type process struct {
+ killed bool
+ record Record
+ stdin *os.File
+ stdout, stderr *os.File
+ done chan struct{}
+ fd int
+ mu sync.Mutex
+ proof Proof
+ err error
+}
+
+func (p *process) ID() string { return p.record.ID }
+func (p *process) Stdin() io.WriteCloser { return p.stdin }
+func (p *process) Stdout() io.ReadCloser { return p.stdout }
+func (p *process) Stderr() io.ReadCloser { return p.stderr }
+func (p *process) Wait(ctx context.Context) (provider.Exit, error) {
+ select {
+ case <-ctx.Done():
+ return provider.Exit{}, ctx.Err()
+ case <-p.done:
+ return p.proof.Exit, p.err
+ }
+}
+func (p *process) kill() error {
+ p.mu.Lock()
+ defer p.mu.Unlock()
+ if p.fd < 0 {
+ return nil
+ }
+ e := unix.PidfdSendSignal(p.fd, unix.SIGKILL, nil, 0)
+ if e == nil {
+ p.killed = true
+ }
+ if e == unix.ESRCH {
+ return nil
+ }
+ return e
+}
+
+func New(cfg Config) (*Manager, error) {
+ for _, path := range []string{cfg.Binary, cfg.RunnerBinary, cfg.ScratchRoot} {
+ f, e := pin(path)
+ if e != nil {
+ return nil, e
+ }
+ f.Close()
+ }
+ info, e := os.Stat(cfg.ScratchRoot)
+ if e != nil || !info.IsDir() || info.Mode().Perm() != 0700 {
+ return nil, errMount
+ }
+ cmd := exec.Command(cfg.Binary, "--version")
+ cmd.Env = []string{"LANG=C"}
+ version, e := cmd.Output()
+ if e != nil || string(version) != "bubblewrap 0.11.0\n" {
+ return nil, errors.New("namespace_bubblewrap_version")
+ }
+ return &Manager{cfg: cfg, processes: make(map[string]*process)}, nil
+}
+func (m *Manager) Start(ctx context.Context, l provider.Launch, argv []string) (provider.Process, error) {
+ if e := ctx.Err(); e != nil {
+ return nil, e
+ }
+ if l.AttemptKey == "" || l.Policy.Hash == "" || len(argv) == 0 || !cleanAbsolute(argv[0]) {
+ return nil, errStartup
+ }
+ var random [16]byte
+ if _, e := rand.Read(random[:]); e != nil {
+ return nil, e
+ }
+ id := hex.EncodeToString(random[:])
+ dir := filepath.Join(m.cfg.ScratchRoot, "attempt-"+id)
+ e := os.Mkdir(dir, 0700)
+ if e != nil {
+ return nil, e
+ }
+ cleanup := true
+ defer func() {
+ if cleanup {
+ os.RemoveAll(dir)
+ }
+ }()
+ for _, name := range []string{"home", "tmp"} {
+ if e = os.Mkdir(filepath.Join(dir, name), 0700); e != nil {
+ return nil, e
+ }
+ }
+ mounts, e := m.mountPlan(l, dir)
+ if e != nil {
+ return nil, e
+ }
+ boot, e := bootID()
+ if e != nil {
+ mounts.close()
+ return nil, e
+ }
+ r := Record{ID: id, AttemptKey: l.AttemptKey, BootID: boot, ManifestHash: l.Policy.Hash}
+ if e = m.persist(r); e != nil {
+ mounts.close()
+ return nil, e
+ }
+ result := make(chan startResult, 1)
+ // The goroutine that forks also waits. Keeping its OS thread locked prevents
+ // Go's Pdeathsig from firing when an unrelated calling goroutine returns.
+ finished := make(chan struct{})
+ go func() { m.lifecycle(ctx, r, argv, mounts, dir, result); close(finished) }()
+ cleanup = false
+ resultValue := <-result
+ if resultValue.err != nil {
+ <-finished
+ return nil, resultValue.err
+ }
+ return resultValue.p, nil
+}
+
+type startResult struct {
+ p *process
+ err error
+}
+type readiness struct {
+ PID int
+ Namespace string
+}
+
+func pipePair() (*os.File, *os.File, error) { return os.Pipe() }
+func (m *Manager) lifecycle(ctx context.Context, r Record, argv []string, mounts *mounts, dir string, result chan<- startResult) {
+ runtime.LockOSThread()
+ defer runtime.UnlockOSThread()
+ cleanupScratch := true
+ defer func() {
+ if cleanupScratch {
+ os.RemoveAll(dir)
+ }
+ }()
+ defer mounts.close()
+ var files []*os.File
+ pipe := func() (*os.File, *os.File, error) {
+ a, b, e := pipePair()
+ if e == nil {
+ files = append(files, a, b)
+ }
+ return a, b, e
+ }
+ defer func() {
+ for _, f := range files {
+ f.Close()
+ }
+ }()
+ statusR, statusW, e := pipe()
+ if e != nil {
+ result <- startResult{err: e}
+ return
+ }
+ releaseR, releaseW, e := pipe()
+ if e != nil {
+ result <- startResult{err: e}
+ return
+ }
+ readyR, readyW, e := pipe()
+ if e != nil {
+ result <- startResult{err: e}
+ return
+ }
+ inputR, inputW, e := pipe()
+ if e != nil {
+ result <- startResult{err: e}
+ return
+ }
+ outputR, outputW, e := pipe()
+ if e != nil {
+ result <- startResult{err: e}
+ return
+ }
+ errorR, errorW, e := pipe()
+ if e != nil {
+ result <- startResult{err: e}
+ return
+ }
+ args := []string{"--unshare-user", "--unshare-pid", "--unshare-ipc", "--unshare-uts", "--unshare-cgroup", "--unshare-net", "--die-with-parent", "--new-session", "--as-pid-1", "--cap-drop", "ALL", "--json-status-fd", "3"}
+ args = append(args, mounts.args...)
+ args = append(args, "--", "/equipo-namespace", "__namespace")
+ args = append(args, argv...)
+ cmd := exec.Command(m.cfg.Binary, args...)
+ cmd.Env = []string{}
+ cmd.ExtraFiles = append([]*os.File{statusW, releaseR, readyW}, mounts.files...)
+ cmd.Stdin = inputR
+ cmd.Stdout = outputW
+ cmd.Stderr = errorW
+ cmd.SysProcAttr = &syscall.SysProcAttr{Pdeathsig: syscall.SIGKILL}
+ if e = cmd.Start(); e != nil {
+ result <- startResult{err: e}
+ return
+ }
+ statusW.Close()
+ releaseR.Close()
+ readyW.Close()
+ inputR.Close()
+ outputW.Close()
+ errorW.Close()
+ mounts.close()
+ type started struct {
+ record Record
+ fd int
+ err error
+ decoder *json.Decoder
+ }
+ handshake := make(chan started, 1)
+ go func() {
+ fail := func(e error) { handshake <- started{fd: -1, err: e} }
+ var status struct {
+ PID int `json:"child-pid"`
+ }
+ if e := json.NewDecoder(io.LimitReader(statusR, 4096)).Decode(&status); e != nil || status.PID <= 0 {
+ fail(errStartup)
+ return
+ }
+ var ready readiness
+ decoder := json.NewDecoder(io.LimitReader(readyR, 4096))
+ if e := decoder.Decode(&ready); e != nil || ready.PID != 1 {
+ fail(errStartup)
+ return
+ }
+ ticks, ns, e := identity(status.PID)
+ if e != nil {
+ fail(e)
+ return
+ }
+ hostNS, e := os.Readlink("/proc/self/ns/pid")
+ if e != nil || ns == hostNS || ready.Namespace != ns {
+ fail(errIdentity)
+ return
+ }
+ r.HostPID = status.PID
+ r.StartTicks = ticks
+ r.NamespaceID = ns
+ fd, e := exactPID(r)
+ if e != nil {
+ fail(e)
+ return
+ }
+ handshake <- started{record: r, fd: fd, decoder: decoder}
+ }()
+ startupCtx, cancel := context.WithTimeout(ctx, 10*time.Second)
+ var s started
+ select {
+ case s = <-handshake:
+ case <-startupCtx.Done():
+ cmd.Process.Kill()
+ statusR.Close()
+ readyR.Close()
+ s = <-handshake
+ s.err = startupCtx.Err()
+ }
+ cancel()
+ if s.err != nil {
+ cmd.Process.Kill()
+ cmd.Wait()
+ if s.fd >= 0 {
+ unix.Close(s.fd)
+ }
+ diagnostic, _ := io.ReadAll(io.LimitReader(errorR, 4096))
+ result <- startResult{err: fmt.Errorf("%w: %s", s.err, diagnostic)}
+ return
+ }
+ p := &process{record: s.record, stdin: inputW, stdout: outputR, stderr: errorR, done: make(chan struct{}), fd: s.fd}
+ // Identity is durable before the helper can fork the harness or read input.
+ if e = m.persist(s.record); e == nil {
+ _, e = releaseW.Write([]byte{1})
+ }
+ releaseW.Close()
+ if e != nil {
+ p.kill()
+ cmd.Process.Kill()
+ cmd.Wait()
+ unix.Close(s.fd)
+ result <- startResult{err: e}
+ return
+ }
+ m.mu.Lock()
+ m.processes[r.ID] = p
+ m.mu.Unlock()
+ // Returned streams belong to the caller; retain buffered data after Wait.
+ files = []*os.File{statusR, statusW, releaseR, releaseW, readyR, readyW, inputR, outputW, errorW}
+ result <- startResult{p: p}
+ lifecycleDone := make(chan struct{})
+ go func() {
+ select {
+ case <-ctx.Done():
+ p.kill()
+ case <-lifecycleDone:
+ }
+ }()
+ e = waitPID(context.Background(), s.fd)
+ waitErr := cmd.Wait()
+ close(lifecycleDone)
+ exit := provider.Exit{Code: -1}
+ // Only the trusted helper can write this outcome frame. The harness never
+ // inherits the pipe. A numeric exit such as 137 must not invent a signal.
+ var outcome provider.Exit
+ if s.decoder.Decode(&outcome) == nil {
+ exit = outcome
+ }
+ p.mu.Lock()
+ if p.killed {
+ exit = provider.Exit{Code: -1, Signal: int(unix.SIGKILL)}
+ }
+ p.mu.Unlock()
+ exit.ObservedAt = time.Now().UTC()
+ var exitError *exec.ExitError
+ if waitErr != nil && !errors.As(waitErr, &exitError) && e == nil {
+ e = waitErr
+ }
+ p.mu.Lock()
+ unix.Close(p.fd)
+ p.fd = -1
+ p.mu.Unlock()
+ p.proof = Proof{Record: s.record, Exit: exit, Verified: e == nil}
+ p.err = e
+ if e == nil {
+ p.err = durableJSON(m.cfg.ScratchRoot, r.ID+".exit.json", p.proof)
+ if p.err != nil {
+ p.proof.Verified = false
+ }
+ }
+ if cleanupErr := os.RemoveAll(dir); cleanupErr != nil && p.err == nil {
+ p.err = cleanupErr
+ p.proof.Verified = false
+ }
+ cleanupScratch = false
+ close(p.done)
+}
+func (m *Manager) Stop(ctx context.Context, id string) (Proof, error) {
+ m.mu.Lock()
+ p := m.processes[id]
+ m.mu.Unlock()
+ if p == nil {
+ return Proof{}, errIdentity
+ }
+ if e := p.kill(); e != nil {
+ return Proof{Record: p.record}, e
+ }
+ select {
+ case <-ctx.Done():
+ return Proof{Record: p.record}, ctx.Err()
+ case <-p.done:
+ return p.proof, p.err
+ }
+}
+
+// NamespaceMain is the internal runner entry point. FD 4 receives the release
+// byte; FD 5 carries readiness and the final harness outcome.
+// Stdin/stdout/stderr are reserved for the harness. PID 1 always stays Go.
+func NamespaceMain(argv []string) int {
+ if os.Getpid() != 1 || len(argv) == 0 {
+ return 125
+ }
+ release := os.NewFile(4, "release")
+ ready := os.NewFile(5, "ready")
+ if release == nil || ready == nil {
+ return 125
+ }
+ ns, e := os.Readlink("/proc/self/ns/pid")
+ if e != nil {
+ return 125
+ }
+ if e = json.NewEncoder(ready).Encode(readiness{PID: os.Getpid(), Namespace: ns}); e != nil {
+ return 125
+ }
+ var token [1]byte
+ if _, e = io.ReadFull(release, token[:]); e != nil || token[0] != 1 {
+ return 125
+ }
+ release.Close()
+ // The harness shares our UID. Disallow /proc/1/fd reopening and ptrace so
+ // it cannot forge outcome frames or reach future helper-owned relay FDs.
+ if e = unix.Prctl(unix.PR_SET_DUMPABLE, 0, 0, 0, 0); e != nil {
+ return 125
+ }
+ // No mount descriptors, journal handles or startup pipes reach the harness.
+ // CLOEXEC leaves Go's own poller usable until the helper exits.
+ if e = unix.CloseRange(3, ^uint(0), unix.CLOSE_RANGE_CLOEXEC); e != nil {
+ return 125
+ }
+ cmd := exec.Command(argv[0], argv[1:]...)
+ cmd.Env = os.Environ()
+ cmd.Stdin = os.Stdin
+ cmd.Stdout = os.Stdout
+ cmd.Stderr = os.Stderr
+ if e = cmd.Start(); e != nil {
+ return 127
+ }
+ for {
+ var status unix.WaitStatus
+ pid, e := unix.Wait4(-1, &status, 0, nil)
+ if e == unix.EINTR {
+ continue
+ }
+ if e != nil {
+ return 125
+ }
+ if pid == cmd.Process.Pid {
+ _ = cmd.Process.Release()
+ outcome := provider.Exit{Code: status.ExitStatus()}
+ if status.Signaled() {
+ outcome.Code = -1
+ outcome.Signal = int(status.Signal())
+ }
+ if json.NewEncoder(ready).Encode(outcome) != nil {
+ return 125
+ }
+ ready.Close()
+ if status.Signaled() {
+ return 128 + int(status.Signal())
+ }
+ return status.ExitStatus()
+ }
+ }
+}
diff --git a/internal/runner/containment/linux_test.go b/internal/runner/containment/linux_test.go
new file mode 100644
index 00000000..fbf88912
--- /dev/null
+++ b/internal/runner/containment/linux_test.go
@@ -0,0 +1,636 @@
+package containment
+
+import (
+ "bufio"
+ "context"
+ "encoding/json"
+ "fmt"
+ "io"
+ "net"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "runtime"
+ "strconv"
+ "strings"
+ "testing"
+ "time"
+
+ "amadan.net/oficina/equipo/internal/runner/provider"
+ "golang.org/x/sys/unix"
+)
+
+func fixture(t *testing.T) (*Manager, provider.Launch) {
+ t.Helper()
+ root := t.TempDir()
+ scratch := filepath.Join(root, "state")
+ if err := os.Mkdir(scratch, 0700); err != nil {
+ t.Fatal(err)
+ }
+ workspace := filepath.Join(root, "workspace")
+ if err := os.Mkdir(workspace, 0700); err != nil {
+ t.Fatal(err)
+ }
+ binary, err := os.Executable()
+ if err != nil {
+ t.Fatal(err)
+ }
+ m, err := New(Config{Binary: "/usr/bin/bwrap", RunnerBinary: binary, ScratchRoot: scratch})
+ if err != nil {
+ t.Fatalf("namespace capability missing: %v", err)
+ }
+ return m, provider.Launch{AttemptKey: "attempt-fixture", Workspace: workspace, Policy: provider.Policy{Hash: "fixture-policy"}}
+}
+func launch(t *testing.T, m *Manager, l provider.Launch, script string) provider.Process {
+ t.Helper()
+ ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
+ t.Cleanup(cancel)
+ p, err := m.Start(ctx, l, []string{"/usr/bin/python3", "-u", "-c", script})
+ if err != nil {
+ t.Fatalf("namespace capability/start failed (userns, pidfd required): %v", err)
+ }
+ t.Cleanup(func() {
+ ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
+ defer cancel()
+ p.(*process).kill()
+ p.Wait(ctx)
+ if _, err := m.Stop(ctx, p.ID()); err != nil {
+ t.Errorf("cleanup: %v", err)
+ }
+ p.Stdin().Close()
+ p.Stdout().Close()
+ p.Stderr().Close()
+ })
+ return p
+}
+func record(t *testing.T, m *Manager, p provider.Process) Record {
+ t.Helper()
+ b, err := os.ReadFile(filepath.Join(m.cfg.ScratchRoot, p.ID()+".json"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ var r Record
+ if err = json.Unmarshal(b, &r); err != nil {
+ t.Fatal(err)
+ }
+ if r.HostPID == 0 || r.StartTicks == 0 || r.NamespaceID == "" || r.ManifestHash == "" {
+ t.Fatalf("incomplete durable identity: %+v", r)
+ }
+ return r
+}
+func namespace(t *testing.T, pid int) string {
+ t.Helper()
+ n, e := os.Readlink(fmt.Sprintf("/proc/%d/ns/pid", pid))
+ if e != nil {
+ t.Fatal(e)
+ }
+ return n
+}
+func descriptor(t *testing.T, pid int) int {
+ t.Helper()
+ fd, e := unix.PidfdOpen(pid, 0)
+ if e != nil {
+ t.Fatalf("capability missing: pidfd_open: %v", e)
+ }
+ t.Cleanup(func() { unix.Close(fd) })
+ return fd
+}
+func exited(t *testing.T, fd int) {
+ t.Helper()
+ p := []unix.PollFd{{Fd: int32(fd), Events: unix.POLLIN}}
+ n, e := unix.Poll(p, 5000)
+ if e != nil || n != 1 || p[0].Revents&unix.POLLIN == 0 {
+ t.Fatalf("exact process has not exited: poll=%d,%v", n, e)
+ }
+}
+func ownedControl(t *testing.T) (*exec.Cmd, int) {
+ t.Helper()
+ c := exec.Command("/usr/bin/sleep", "60")
+ if e := c.Start(); e != nil {
+ t.Fatal(e)
+ }
+ fd := descriptor(t, c.Process.Pid)
+ t.Cleanup(func() { c.Process.Kill(); c.Wait() })
+ return c, fd
+}
+func alive(t *testing.T, fd int) {
+ t.Helper()
+ if e := unix.PidfdSendSignal(fd, 0, nil, 0); e != nil {
+ t.Fatalf("owned unrelated control died: %v", e)
+ }
+ p := []unix.PollFd{{Fd: int32(fd), Events: unix.POLLIN}}
+ n, e := unix.Poll(p, 0)
+ if e != nil || n != 0 {
+ t.Fatalf("owned unrelated control exited: %d %v", n, e)
+ }
+}
+
+// Resolve only descendants of the exact init we started, never host-wide PIDs.
+func descendants(t *testing.T, root int) []int {
+ t.Helper()
+ out := []int{root}
+ for i := 0; i < len(out); i++ {
+ tasks, e := filepath.Glob(fmt.Sprintf("/proc/%d/task/*/children", out[i]))
+ if e != nil {
+ t.Fatal(e)
+ }
+ for _, task := range tasks {
+ b, e := os.ReadFile(task)
+ if os.IsNotExist(e) {
+ continue
+ }
+ if e != nil {
+ t.Fatal(e)
+ }
+ for _, s := range strings.Fields(string(b)) {
+ pid, e := strconv.Atoi(s)
+ if e != nil {
+ t.Fatal(e)
+ }
+ out = append(out, pid)
+ }
+ }
+ }
+
+ return out
+}
+
+const detachedScript = `import os, subprocess, time
+subprocess.Popen(['/usr/bin/sleep','60'],start_new_session=True)
+pid=os.fork()
+if pid==0:
+ if os.fork()==0:
+ time.sleep(60)
+ os._exit(0)
+ os._exit(0)
+os.waitpid(pid,0)
+pid=os.fork()
+if pid==0:
+ try:
+ open('/sys/fs/cgroup/cgroup.procs','w').write(str(os.getpid()))
+ except OSError:
+ pass
+ time.sleep(60)
+ os._exit(0)
+print('ready',flush=True)
+time.sleep(60)
+`
+
+func TestNamespaceKillsDetachedChildren(t *testing.T) {
+ m, l := fixture(t)
+ _, control := ownedControl(t)
+ p := launch(t, m, l, detachedScript)
+ line, e := bufio.NewReader(p.Stdout()).ReadString('\n')
+ if e != nil || line != "ready\n" {
+ t.Fatalf("fixture readiness %q %v", line, e)
+ }
+ r := record(t, m, p)
+ if namespace(t, os.Getpid()) == r.NamespaceID {
+ t.Fatal("shared host PID namespace")
+ }
+ members := descendants(t, r.HostPID)
+ if len(members) < 5 {
+ t.Fatalf("missing detached children: %v", members)
+ }
+ var fds []int
+ for _, pid := range members {
+ if pid != r.HostPID && namespace(t, pid) != r.NamespaceID {
+ t.Fatal("namespace mismatch")
+ }
+ fds = append(fds, descriptor(t, pid))
+ }
+ proof, e := m.Stop(context.Background(), p.ID())
+ if e != nil || !proof.Verified || proof.Record != r {
+ t.Fatalf("stop proof: %+v %v", proof, e)
+ }
+ for _, fd := range fds {
+ exited(t, fd)
+ }
+ alive(t, control)
+}
+func TestNamespaceCgroupMoveKeepsMembership(t *testing.T) {
+ base := fmt.Sprintf("/sys/fs/cgroup/user.slice/user-%d.slice/user@%d.service", os.Getuid(), os.Getuid())
+ if _, e := os.ReadFile(filepath.Join(base, "cgroup.subtree_control")); e != nil {
+ t.Fatalf("capability missing: delegated cgroup subtree: %v", e)
+ }
+ a, e := os.MkdirTemp(base, "equipo-task2-")
+ if e != nil {
+ t.Fatalf("capability missing: writable delegated cgroup subtree: %v", e)
+ }
+ t.Cleanup(func() {
+ if e := os.Remove(a); e != nil {
+ t.Errorf("remove test cgroup: %v", e)
+ }
+ })
+ b := filepath.Join(a, "destination")
+ if e = os.Mkdir(b, 0700); e != nil {
+ t.Fatal(e)
+ }
+ t.Cleanup(func() {
+ if e := os.Remove(b); e != nil {
+ t.Errorf("remove test cgroup: %v", e)
+ }
+ })
+ // Make two leaf cgroups, keeping the test's parent empty.
+ source := filepath.Join(a, "source")
+ if e = os.Mkdir(source, 0700); e != nil {
+ t.Fatal(e)
+ }
+ t.Cleanup(func() {
+ if e := os.Remove(source); e != nil {
+ t.Errorf("remove test cgroup: %v", e)
+ }
+ })
+ m, l := fixture(t)
+ p := launch(t, m, l, "import time; print('ready',flush=True); time.sleep(60)")
+ if _, e = bufio.NewReader(p.Stdout()).ReadString('\n'); e != nil {
+ t.Fatal(e)
+ }
+ r := record(t, m, p)
+ children := descendants(t, r.HostPID)
+ if len(children) < 2 {
+ t.Fatal("missing harness")
+ }
+ pid := children[1]
+ fd := descriptor(t, pid)
+ before := namespace(t, pid)
+ for _, dir := range []string{source, b} {
+ if e = os.WriteFile(filepath.Join(dir, "cgroup.procs"), []byte(strconv.Itoa(pid)), 0600); e != nil {
+ t.Fatalf("capability missing: authorized cgroup move: %v", e)
+ }
+ actual, e := os.ReadFile(fmt.Sprintf("/proc/%d/cgroup", pid))
+ if e != nil || !strings.Contains(string(actual), filepath.Base(a)+"/"+filepath.Base(dir)) {
+ t.Fatalf("move not observed: %s %v", actual, e)
+ }
+ }
+ if namespace(t, pid) != before {
+ t.Fatal("cgroup move changed PID namespace")
+ }
+ if _, e = m.Stop(context.Background(), p.ID()); e != nil {
+ t.Fatal(e)
+ }
+ exited(t, fd)
+}
+func TestNamespaceHidesHostControl(t *testing.T) {
+ m, l := fixture(t)
+ listener, e := net.Listen("tcp", "127.0.0.1:0")
+ if e != nil {
+ t.Fatal(e)
+ }
+ defer listener.Close()
+ socket, e := net.Listen("unix", filepath.Join(t.TempDir(), "control.sock"))
+ if e != nil {
+ t.Fatal(e)
+ }
+ defer socket.Close()
+ // Deliberately make an owned socket inheritable in the launching process.
+ file, e := socket.(*net.UnixListener).File()
+ if e != nil {
+ t.Fatal(e)
+ }
+ defer file.Close()
+ if _, e = unix.FcntlInt(file.Fd(), unix.F_SETFD, 0); e != nil {
+ t.Fatal(e)
+ }
+ l.Policy.Env = map[string]string{"LANG": "C.UTF-8"}
+ t.Setenv("EQUIPO_TEST_HOST_SECRET", "must-not-inherit")
+ p := launch(t, m, l, fmt.Sprintf(`import os,socket,json
+paths=['/sys/fs/cgroup','/run/user/%d/bus','/run/user/%d/systemd/private','/home/paulca','/proc/1/root/home/paulca','/etc/claude-code/managed-settings.json','/etc/codex/config.toml']
+assert all(not os.path.exists(p) for p in paths), paths
+assert os.listdir('/home')==['runner']
+assert 'EQUIPO_TEST_HOST_SECRET' not in os.environ
+assert os.getppid()==1
+assert int([l for l in open('/proc/self/status') if l.startswith('CapEff:')][0].split()[1],16)==0
+assert open('/proc/1/comm').read().strip()!='python3'
+assert all(not os.readlink('/proc/self/fd/'+f).startswith('socket:') for f in os.listdir('/proc/self/fd') if os.path.exists('/proc/self/fd/'+f))
+s=socket.socket(); assert s.connect_ex(('127.0.0.1',%d))!=0
+try:
+ open('/sys/fs/cgroup/cgroup.procs','w').write(str(os.getpid()))
+ raise AssertionError('cgroup exposed')
+except OSError: pass
+print('isolated')
+`, os.Getuid(), os.Getuid(), listener.Addr().(*net.TCPAddr).Port))
+ output, e := io.ReadAll(p.Stdout())
+ if e != nil {
+ t.Fatal(e)
+ }
+ exit, e := p.Wait(context.Background())
+ if e != nil || exit.Code != 0 || string(output) != "isolated\n" {
+ errout, _ := io.ReadAll(p.Stderr())
+ t.Fatalf("isolation: %s %+v %v %s", output, exit, e, errout)
+ }
+}
+func TestNamespacePidfdCapability(t *testing.T) {
+ c, fd := ownedControl(t)
+ if e := unix.PidfdSendSignal(fd, unix.SIGKILL, nil, 0); e != nil {
+ t.Fatalf("capability missing: pidfd_send_signal: %v", e)
+ }
+ var info unix.Siginfo
+ if e := unix.Waitid(unix.P_PIDFD, fd, &info, unix.WEXITED|unix.WNOWAIT, nil); e != nil {
+ t.Fatalf("capability missing: waitid(P_PIDFD): %v", e)
+ }
+ exited(t, fd)
+ _ = c
+}
+
+func parentFixture() {
+ runtime.LockOSThread()
+ m, e := New(Config{Binary: "/usr/bin/bwrap", RunnerBinary: os.Args[0], ScratchRoot: os.Getenv("EQUIPO_TEST_STATE")})
+ if e != nil {
+ panic(e)
+ }
+ l := provider.Launch{AttemptKey: "parent-death", Workspace: os.Getenv("EQUIPO_TEST_WORKSPACE"), Policy: provider.Policy{Hash: "parent-policy"}}
+ p, e := m.Start(context.Background(), l, []string{"/usr/bin/python3", "-u", "-c", detachedScript})
+ if e != nil {
+ panic(e)
+ }
+ if _, e = bufio.NewReader(p.Stdout()).ReadString('\n'); e != nil {
+ panic(e)
+ }
+ b, e := os.ReadFile(filepath.Join(m.cfg.ScratchRoot, p.ID()+".json"))
+ if e != nil {
+ panic(e)
+ }
+ fmt.Println(string(b))
+ select {}
+}
+func TestNamespaceParentDeath(t *testing.T) {
+ m, l := fixture(t)
+ c := exec.Command(os.Args[0])
+ c.Env = append(os.Environ(), "EQUIPO_NAMESPACE_PARENT_TEST=1", "EQUIPO_TEST_STATE="+m.cfg.ScratchRoot, "EQUIPO_TEST_WORKSPACE="+l.Workspace)
+ stdout, e := c.StdoutPipe()
+ if e != nil {
+ t.Fatal(e)
+ }
+ c.Stderr = os.Stderr
+ if e = c.Start(); e != nil {
+ t.Fatal(e)
+ }
+ t.Cleanup(func() { c.Process.Kill(); c.Wait() })
+ var r Record
+ if e = json.NewDecoder(stdout).Decode(&r); e != nil {
+ t.Fatalf("launcher fixture: %v", e)
+ }
+ members := descendants(t, r.HostPID)
+ var fds []int
+ for _, pid := range members {
+ fds = append(fds, descriptor(t, pid))
+ }
+ t.Cleanup(func() {
+ if len(fds) > 0 {
+ unix.PidfdSendSignal(fds[0], unix.SIGKILL, nil, 0)
+ }
+ })
+ if e = c.Process.Kill(); e != nil {
+ t.Fatal(e)
+ }
+ for _, fd := range fds {
+ exited(t, fd)
+ }
+}
+func TestNamespaceStartingThreadExit(t *testing.T) {
+ m, l := fixture(t)
+ done := make(chan provider.Process, 1)
+ go func() {
+ runtime.LockOSThread()
+ p, e := m.Start(context.Background(), l, []string{"/usr/bin/sleep", "60"})
+ if e != nil {
+ done <- nil
+ return
+ }
+ done <- p
+ }()
+ p := <-done
+ if p == nil {
+ t.Fatal("start failed")
+ }
+ defer m.Stop(context.Background(), p.ID())
+ r := record(t, m, p)
+ fd := descriptor(t, r.HostPID)
+ time.Sleep(50 * time.Millisecond)
+ alive(t, fd)
+}
+
+func TestNamespaceStartupFailure(t *testing.T) {
+ m, l := fixture(t)
+ // The helper cannot acknowledge PID 1, so no process is returned and no
+ // harness side effect is possible. The incomplete intent remains durable.
+ m.cfg.RunnerBinary = "/usr/bin/true"
+ p, e := m.Start(context.Background(), l, []string{"/usr/bin/touch", "/workspace/prompt-sent"})
+ if e == nil || p != nil {
+ t.Fatal("missing readiness accepted")
+ }
+ if _, e = os.Stat(filepath.Join(l.Workspace, "prompt-sent")); !os.IsNotExist(e) {
+ t.Fatal("harness ran before readiness")
+ }
+ entries, e := os.ReadDir(m.cfg.ScratchRoot)
+ if e != nil {
+ t.Fatal(e)
+ }
+ if len(entries) != 1 || !strings.HasSuffix(entries[0].Name(), ".json") {
+ t.Fatalf("startup cleanup or intent missing: %v", entries)
+ }
+}
+func TestNamespaceIntentBeforeFork(t *testing.T) {
+ m, l := fixture(t)
+ marker := filepath.Join(l.Workspace, "intent-observed")
+ shim := filepath.Join(filepath.Dir(l.Workspace), "inspect-intent")
+ script := "#!/usr/bin/python3\nimport glob,json\nrecords=glob.glob(" + strconv.Quote(m.cfg.ScratchRoot+"/*.json") + ")\nassert len(records)==1\nr=json.load(open(records[0]))\nassert r['HostPID']==0 and r['AttemptKey']=='attempt-fixture'\nopen(" + strconv.Quote(marker) + ",'w').write('intent')\n"
+ if e := os.WriteFile(shim, []byte(script), 0700); e != nil {
+ t.Fatal(e)
+ }
+ m.cfg.Binary = shim
+ if p, e := m.Start(context.Background(), l, []string{"/usr/bin/true"}); e == nil {
+ m.Stop(context.Background(), p.ID())
+ t.Fatal("shim acknowledged readiness")
+ }
+ if b, e := os.ReadFile(marker); e != nil || string(b) != "intent" {
+ t.Fatalf("no durable intent before fork: %q %v", b, e)
+ }
+}
+func TestNamespaceStopWaitsForExit(t *testing.T) {
+ m, l := fixture(t)
+ p := launch(t, m, l, "import time; time.sleep(60)")
+ r := record(t, m, p)
+ fd := descriptor(t, r.HostPID)
+ proof, e := m.Stop(context.Background(), p.ID())
+ if e != nil || !proof.Verified {
+ t.Fatalf("stop: %+v %v", proof, e)
+ }
+ polls := []unix.PollFd{{Fd: int32(fd), Events: unix.POLLIN}}
+ n, e := unix.Poll(polls, 0)
+ if e != nil || n != 1 {
+ t.Fatal("stop acknowledged before exact init exit")
+ }
+ b, e := os.ReadFile(filepath.Join(m.cfg.ScratchRoot, p.ID()+".exit.json"))
+ if e != nil {
+ t.Fatal(e)
+ }
+ var saved Proof
+ if e = json.Unmarshal(b, &saved); e != nil || saved.Record != proof.Record || saved.Exit != proof.Exit || !saved.Verified {
+ t.Fatalf("exit proof not durable: %s %v", b, e)
+ }
+}
+func TestNamespaceExitStatus(t *testing.T) {
+ for _, script := range []string{"import sys; sys.exit(137)", "import os,signal; os.kill(os.getpid(),signal.SIGTERM)"} {
+ m, l := fixture(t)
+ p := launch(t, m, l, script)
+ exit, e := p.Wait(context.Background())
+ if e != nil {
+ t.Fatal(e)
+ }
+ if strings.Contains(script, "137") {
+ if exit.Code != 137 || exit.Signal != 0 {
+ t.Fatalf("numeric exit fabricated signal: %+v", exit)
+ }
+ } else if exit.Code != -1 || exit.Signal != int(unix.SIGTERM) {
+ t.Fatalf("signal outcome: %+v", exit)
+ }
+ }
+}
+func TestNamespaceSocketImport(t *testing.T) {
+ m, l := fixture(t)
+ listener, e := net.Listen("unix", filepath.Join(l.Workspace, "service.sock"))
+ if e != nil {
+ t.Fatal(e)
+ }
+ defer listener.Close()
+ p, e := m.Start(context.Background(), l, []string{"/usr/bin/true"})
+ if e == nil {
+ m.Stop(context.Background(), p.ID())
+ t.Fatal("host socket imported")
+ }
+}
+func TestNamespaceNestedUserNamespace(t *testing.T) {
+ m, l := fixture(t)
+ p := launch(t, m, l, "import subprocess; subprocess.run(['/usr/bin/bwrap','--unshare-user','--ro-bind','/','/','--','/usr/bin/true'],check=True)")
+ exit, e := p.Wait(context.Background())
+ if e != nil || exit.Code != 0 {
+ b, _ := io.ReadAll(p.Stderr())
+ t.Fatalf("nested sandbox unavailable: %+v %v %s", exit, e, b)
+ }
+}
+
+func TestNamespaceHelperProtocolPrivate(t *testing.T) {
+ m, l := fixture(t)
+ p := launch(t, m, l, `import os
+try:
+ fd=os.open('/proc/1/fd/5',os.O_WRONLY)
+except OSError:
+ print('private')
+else:
+ os.close(fd)
+ raise AssertionError('harness can forge helper outcome')
+`)
+ exit, e := p.Wait(context.Background())
+ if e != nil || exit.Code != 0 {
+ t.Fatalf("helper pipe exposed: %+v %v", exit, e)
+ }
+}
+
+func TestNamespaceHelperBarrier(t *testing.T) {
+ m, l := fixture(t)
+ runtime.LockOSThread()
+ defer runtime.UnlockOSThread()
+ statusR, statusW, e := os.Pipe()
+ if e != nil {
+ t.Fatal(e)
+ }
+ defer statusR.Close()
+ defer statusW.Close()
+ releaseR, releaseW, e := os.Pipe()
+ if e != nil {
+ t.Fatal(e)
+ }
+ defer releaseR.Close()
+ defer releaseW.Close()
+ readyR, readyW, e := os.Pipe()
+ if e != nil {
+ t.Fatal(e)
+ }
+ defer readyR.Close()
+ defer readyW.Close()
+ c := exec.Command(m.cfg.Binary, "--unshare-user", "--unshare-pid", "--as-pid-1", "--die-with-parent", "--unshare-net", "--ro-bind", "/usr", "/usr", "--symlink", "usr/lib", "/lib", "--symlink", "usr/lib64", "/lib64", "--proc", "/proc", "--dev", "/dev", "--bind", l.Workspace, "/workspace", "--ro-bind", m.cfg.RunnerBinary, "/helper", "--json-status-fd", "3", "--", "/helper", "__namespace", "/usr/bin/touch", "/workspace/released")
+ c.ExtraFiles = []*os.File{statusW, releaseR, readyW}
+ c.Stderr = os.Stderr
+ if e = c.Start(); e != nil {
+ t.Fatal(e)
+ }
+ defer func() { c.Process.Kill(); c.Wait() }()
+ statusW.Close()
+ releaseR.Close()
+ readyW.Close()
+ var status struct {
+ PID int `json:"child-pid"`
+ }
+ if e = json.NewDecoder(statusR).Decode(&status); e != nil {
+ t.Fatal(e)
+ }
+ var ready readiness
+ if e = json.NewDecoder(readyR).Decode(&ready); e != nil || ready.PID != 1 {
+ t.Fatalf("helper topology: %+v %v", ready, e)
+ }
+ time.Sleep(30 * time.Millisecond)
+ marker := filepath.Join(l.Workspace, "released")
+ if _, e = os.Stat(marker); !os.IsNotExist(e) {
+ t.Fatal("harness started before release")
+ }
+ if _, e = releaseW.Write([]byte{1}); e != nil {
+ t.Fatal(e)
+ }
+ if e = c.Wait(); e != nil {
+ t.Fatal(e)
+ }
+ if _, e = os.Stat(marker); e != nil {
+ t.Fatal("released harness never ran")
+ }
+}
+func TestNamespaceReapsOrphans(t *testing.T) {
+ m, l := fixture(t)
+ p := launch(t, m, l, `import os,time
+pid=os.fork()
+if pid==0:
+ if os.fork()==0:
+ open('/workspace/orphan','w').write(str(os.getpid()))
+ time.sleep(.05)
+ os._exit(0)
+ os._exit(0)
+os.waitpid(pid,0)
+while not os.path.exists('/workspace/orphan'): time.sleep(.001)
+orphan=open('/workspace/orphan').read()
+while not orphan:
+ time.sleep(.001)
+ orphan=open('/workspace/orphan').read()
+for i in range(1000):
+ if not os.path.exists('/proc/'+orphan): break
+ time.sleep(.001)
+else: raise AssertionError('orphan remains a zombie')
+`)
+ exit, e := p.Wait(context.Background())
+ if e != nil || exit.Code != 0 {
+ t.Fatalf("orphan not reaped: %+v %v", exit, e)
+ }
+}
+
+func TestNamespaceCancellation(t *testing.T) {
+ m, l := fixture(t)
+ ctx, cancel := context.WithCancel(context.Background())
+ defer cancel()
+ p, e := m.Start(ctx, l, []string{"/usr/bin/sleep", "60"})
+ if e != nil {
+ t.Fatal(e)
+ }
+ defer p.Stdin().Close()
+ defer p.Stdout().Close()
+ defer p.Stderr().Close()
+ t.Cleanup(func() { p.(*process).kill(); p.Wait(context.Background()) })
+ r := record(t, m, p)
+ fd := descriptor(t, r.HostPID)
+ cancel()
+ wait, cancelWait := context.WithTimeout(context.Background(), 2*time.Second)
+ defer cancelWait()
+ if _, e = p.Wait(wait); e != nil {
+ t.Fatal(e)
+ }
+ exited(t, fd)
+}
diff --git a/internal/runner/containment/mounts.go b/internal/runner/containment/mounts.go
new file mode 100644
index 00000000..11197bef
--- /dev/null
+++ b/internal/runner/containment/mounts.go
@@ -0,0 +1,183 @@
+package containment
+
+import (
+ "errors"
+ "fmt"
+ "io/fs"
+ "os"
+ "path/filepath"
+ "sort"
+ "strconv"
+ "strings"
+
+ "amadan.net/oficina/equipo/internal/runner/provider"
+ "golang.org/x/sys/unix"
+)
+
+var errMount = errors.New("namespace_mount_rejected")
+
+type mounts struct {
+ args []string
+ files []*os.File
+}
+
+func (p *mounts) close() {
+ for _, f := range p.files {
+ _ = f.Close()
+ }
+}
+func cleanAbsolute(path string) bool {
+ return filepath.IsAbs(path) && filepath.Clean(path) == path && path != "/"
+}
+func within(path, root string) bool { return path == root || strings.HasPrefix(path, root+"/") }
+func overlaps(a, b string) bool { return within(a, b) || within(b, a) }
+
+// openat2 rejects symlinks in every component. The retained descriptor, rather
+// than the submitted path, is the source bubblewrap mounts after validation.
+func pin(path string) (*os.File, error) {
+ if !cleanAbsolute(path) {
+ return nil, errMount
+ }
+ fd, err := unix.Openat2(unix.AT_FDCWD, path, &unix.OpenHow{Flags: unix.O_PATH | unix.O_CLOEXEC, Resolve: unix.RESOLVE_NO_SYMLINKS | unix.RESOLVE_NO_MAGICLINKS})
+ if err != nil {
+ return nil, fmt.Errorf("%w: %v", errMount, err)
+ }
+ return os.NewFile(uintptr(fd), path), nil
+}
+func (p *mounts) bind(source, target string, ro, tree bool) error {
+ f, err := pin(source)
+ if err != nil {
+ return err
+ }
+ info, err := f.Stat()
+ if err != nil {
+ f.Close()
+ return err
+ }
+ if (tree && !info.IsDir()) || (!tree && source != "/usr" && !info.Mode().IsRegular()) {
+ f.Close()
+ return errMount
+ }
+ if tree {
+ err = filepath.WalkDir(fmt.Sprintf("/proc/self/fd/%d/.", f.Fd()), func(path string, d fs.DirEntry, e error) error {
+ if e != nil {
+ return e
+ }
+ if d.Type()&(os.ModeSocket|os.ModeNamedPipe|os.ModeDevice) != 0 {
+ return errMount
+ }
+ return nil
+ })
+ if err != nil {
+ f.Close()
+ return err
+ }
+ }
+ flag := "--bind-fd"
+ if ro {
+ flag = "--ro-bind-fd"
+ }
+ // FDs 3, 4 and 5 are status, release and readiness, respectively.
+ p.args = append(p.args, flag, strconv.Itoa(6+len(p.files)), target)
+ p.files = append(p.files, f)
+ return nil
+}
+func (m *Manager) mountPlan(l provider.Launch, dir string) (_ *mounts, err error) {
+ p := &mounts{}
+ defer func() {
+ if err != nil {
+ p.close()
+ }
+ }()
+ if !cleanAbsolute(l.Workspace) || overlaps(l.Workspace, m.cfg.ScratchRoot) {
+ return nil, errMount
+ }
+ for _, root := range []string{"/proc", "/sys", "/run", "/dev", "/etc", "/usr"} {
+ if overlaps(l.Workspace, root) {
+ return nil, errMount
+ }
+ }
+ home, err := os.UserHomeDir()
+ if err != nil {
+ return nil, err
+ }
+ if within(home, l.Workspace) || l.Workspace == "/home" || filepath.Dir(l.Workspace) == "/home" || l.Workspace == "/tmp" || l.Workspace == "/root" {
+ return nil, errMount
+ }
+ if err = p.bind("/usr", "/usr", true, false); err != nil {
+ return nil, err
+ }
+ p.args = append(p.args, "--overlay-src", "/etc", "--tmp-overlay", "/etc")
+ p.args = append(p.args, "--symlink", "usr/bin", "/bin", "--symlink", "usr/lib", "/lib", "--symlink", "usr/lib64", "/lib64", "--proc", "/proc", "--dev", "/dev", "--dir", "/run", "--dir", "/sys", "--dir", "/home/runner", "--tmpfs", "/etc/claude-code", "--tmpfs", "/etc/codex")
+ if err = p.bind(l.Workspace, "/workspace", false, true); err != nil {
+ return nil, err
+ }
+ runtimeHome := filepath.Join(dir, "home")
+ if l.Binding.Home != "" {
+ runtimeHome = l.Binding.Home
+ homes := filepath.Join(m.cfg.ScratchRoot, "homes")
+ if !cleanAbsolute(runtimeHome) || filepath.Dir(runtimeHome) != homes || overlaps(runtimeHome, l.Workspace) {
+ return nil, errMount
+ }
+ info, e := os.Stat(runtimeHome)
+ if e != nil || !info.IsDir() || info.Mode().Perm() != 0700 {
+ return nil, errMount
+ }
+ }
+ if err = p.bind(runtimeHome, "/home/runner", false, true); err != nil {
+ return nil, err
+ }
+ if err = p.bind(filepath.Join(dir, "tmp"), "/tmp", false, true); err != nil {
+ return nil, err
+ }
+ if err = p.bind(m.cfg.RunnerBinary, "/equipo-namespace", true, false); err != nil {
+ return nil, err
+ }
+ targets := map[string]bool{}
+ for _, mount := range l.Policy.Mounts {
+ target := mount.Target
+ if !mount.ReadOnly || !cleanAbsolute(target) || targets[target] {
+ return nil, errMount
+ }
+ if !(strings.HasPrefix(target, "/opt/") || strings.HasPrefix(target, "/config/") || strings.HasPrefix(target, "/etc/claude-code/") || strings.HasPrefix(target, "/etc/codex/")) {
+ return nil, errMount
+ }
+ for _, existing := range l.Policy.Mounts {
+ if existing.Target != target && overlaps(existing.Target, target) {
+ return nil, errMount
+ }
+ }
+ for _, protected := range []string{"/proc", "/sys", "/run", "/dev"} {
+ if overlaps(mount.Source, protected) {
+ return nil, errMount
+ }
+ }
+ // bind validates and retains the same descriptor; no second path lookup.
+ if err = p.bind(mount.Source, target, true, false); err != nil {
+ return nil, err
+ }
+ targets[target] = true
+ }
+ p.args = append(p.args, "--clearenv", "--setenv", "PATH", "/usr/bin:/bin:/opt", "--setenv", "HOME", "/home/runner", "--setenv", "TMPDIR", "/tmp", "--setenv", "LANG", "C.UTF-8")
+ allowed := map[string]bool{"LANG": true, "LC_ALL": true, "TERM": true, "CODEX_HOME": true, "CLAUDE_CONFIG_DIR": true, "CLAUDE_SECURESTORAGE_CONFIG_DIR": true, "CLAUDE_TMPDIR": true, "CLAUDE_CODE_DISABLE_AUTO_UPDATE": true}
+ keys := make([]string, 0, len(l.Policy.Env))
+ for k := range l.Policy.Env {
+ keys = append(keys, k)
+ }
+ sort.Strings(keys)
+ for _, k := range keys {
+ v := l.Policy.Env[k]
+ if !allowed[k] || strings.ContainsRune(v, 0) {
+ return nil, errMount
+ }
+ if (k == "CODEX_HOME" || k == "CLAUDE_CONFIG_DIR" || k == "CLAUDE_SECURESTORAGE_CONFIG_DIR") && (!cleanAbsolute(v) || !within(v, "/home/runner")) {
+ return nil, errMount
+ }
+ if k == "CLAUDE_TMPDIR" && (!cleanAbsolute(v) || !within(v, "/tmp")) {
+ return nil, errMount
+ }
+ p.args = append(p.args, "--setenv", k, v)
+ }
+ p.args = append(p.args, "--remount-ro", "/etc/claude-code", "--remount-ro", "/etc/codex", "--remount-ro", "/etc", "--chdir", "/workspace")
+ return p, nil
+}
diff --git a/internal/runner/containment/mounts_test.go b/internal/runner/containment/mounts_test.go
new file mode 100644
index 00000000..d49e4a3e
--- /dev/null
+++ b/internal/runner/containment/mounts_test.go
@@ -0,0 +1,76 @@
+package containment
+
+import (
+ "context"
+ "io"
+ "os"
+ "path/filepath"
+ "testing"
+)
+
+func TestNamespacePinnedMountSwap(t *testing.T) {
+ m, l := fixture(t)
+ if e := os.WriteFile(filepath.Join(l.Workspace, "marker"), []byte("workspace"), 0600); e != nil {
+ t.Fatal(e)
+ }
+ outside := t.TempDir()
+ if e := os.WriteFile(filepath.Join(outside, "marker"), []byte("protected"), 0600); e != nil {
+ t.Fatal(e)
+ }
+ dir, e := os.MkdirTemp(m.cfg.ScratchRoot, "attempt-")
+ if e != nil {
+ t.Fatal(e)
+ }
+ for _, name := range []string{"tmp", "home"} {
+ if e = os.Mkdir(filepath.Join(dir, name), 0700); e != nil {
+ t.Fatal(e)
+ }
+ }
+ plan, e := m.mountPlan(l, dir)
+ if e != nil {
+ t.Fatal(e)
+ }
+ if e = os.Rename(l.Workspace, l.Workspace+"-original"); e != nil {
+ t.Fatal(e)
+ }
+ if e = os.Symlink(outside, l.Workspace); e != nil {
+ t.Fatal(e)
+ }
+ boot, e := bootID()
+ if e != nil {
+ t.Fatal(e)
+ }
+ r := Record{ID: "01234567890123456789012345678901", BootID: boot, AttemptKey: l.AttemptKey, ManifestHash: l.Policy.Hash}
+ if e = m.persist(r); e != nil {
+ t.Fatal(e)
+ }
+ result := make(chan startResult, 1)
+ go m.lifecycle(context.Background(), r, []string{"/usr/bin/cat", "/workspace/marker"}, plan, dir, result)
+ started := <-result
+ if started.err != nil {
+ t.Fatal(started.err)
+ }
+ p := started.p
+ defer p.Stdin().Close()
+ defer p.Stdout().Close()
+ defer p.Stderr().Close()
+ b, e := io.ReadAll(p.Stdout())
+ if e != nil {
+ t.Fatal(e)
+ }
+ exit, e := p.Wait(context.Background())
+ if e != nil || exit.Code != 0 || string(b) != "workspace" {
+ t.Fatalf("mutable path replaced pinned source: %q %+v %v", b, exit, e)
+ }
+}
+func TestNamespaceRejectsBroadWorkspace(t *testing.T) {
+ m, l := fixture(t)
+ for _, path := range []string{"/home/another-user", "/tmp", "/root"} {
+ bad := l
+ bad.Workspace = path
+ // Inspect validation before any open; these paths need not exist.
+ if _, e := m.mountPlan(bad, m.cfg.ScratchRoot); e == nil {
+ t.Fatalf("broad workspace accepted: %s", path)
+ }
+ }
+}
diff --git a/internal/runner/containment/recovery.go b/internal/runner/containment/recovery.go
new file mode 100644
index 00000000..74149455
--- /dev/null
+++ b/internal/runner/containment/recovery.go
@@ -0,0 +1,206 @@
+package containment
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "os"
+ "path/filepath"
+ "strconv"
+ "strings"
+ "time"
+
+ "amadan.net/oficina/equipo/internal/runner/provider"
+ "golang.org/x/sys/unix"
+)
+
+type Record struct {
+ ID, AttemptKey, BootID, NamespaceID, ManifestHash string
+ HostPID int
+ StartTicks uint64
+}
+type Proof struct {
+ Record Record
+ Exit provider.Exit
+ Verified bool
+}
+
+var errIdentity = errors.New("namespace_identity_unproven")
+
+func bootID() (string, error) {
+ b, e := os.ReadFile("/proc/sys/kernel/random/boot_id")
+ return strings.TrimSpace(string(b)), e
+}
+func identity(pid int) (uint64, string, error) {
+ b, e := os.ReadFile(fmt.Sprintf("/proc/%d/stat", pid))
+ if e != nil {
+ return 0, "", e
+ }
+ end := strings.LastIndexByte(string(b), ')')
+ if end < 0 {
+ return 0, "", errIdentity
+ }
+ fields := strings.Fields(string(b)[end+1:])
+ if len(fields) < 20 {
+ return 0, "", errIdentity
+ }
+ ticks, e := strconv.ParseUint(fields[19], 10, 64)
+ if e != nil {
+ return 0, "", e
+ }
+ ns, e := os.Readlink(fmt.Sprintf("/proc/%d/ns/pid", pid))
+ return ticks, ns, e
+}
+func exactPID(r Record) (int, error) {
+ fd, e := unix.PidfdOpen(r.HostPID, 0)
+ if e != nil {
+ return -1, e
+ }
+ ticks, ns, e := identity(r.HostPID)
+ if e != nil || ticks != r.StartTicks || ns != r.NamespaceID {
+ unix.Close(fd)
+ return -1, errIdentity
+ }
+ // Recovery must identify namespace init, not merely a matching process.
+ hostNS, hostErr := os.Readlink("/proc/self/ns/pid")
+ status, statusErr := os.ReadFile(fmt.Sprintf("/proc/%d/status", r.HostPID))
+ init := false
+ for _, line := range strings.Split(string(status), "\n") {
+ if strings.HasPrefix(line, "NSpid:") {
+ fields := strings.Fields(line)
+ init = len(fields) > 2 && fields[len(fields)-1] == "1"
+ }
+ }
+ if hostErr != nil || statusErr != nil || ns == hostNS || !init {
+ unix.Close(fd)
+ return -1, errIdentity
+ }
+ // A readable descriptor refers to an exited process, even if the PID has
+ // already been recycled while /proc was read. Never signal that replacement.
+ polls := []unix.PollFd{{Fd: int32(fd), Events: unix.POLLIN}}
+ n, e := unix.Poll(polls, 0)
+ if e != nil || n != 0 {
+ unix.Close(fd)
+ return -1, errIdentity
+ }
+ return fd, nil
+}
+func waitPID(ctx context.Context, fd int) error {
+ for {
+ if e := ctx.Err(); e != nil {
+ return e
+ }
+ polls := []unix.PollFd{{Fd: int32(fd), Events: unix.POLLIN}}
+ n, e := unix.Poll(polls, 25)
+ if e == unix.EINTR {
+ continue
+ }
+ if e != nil {
+ return e
+ }
+ if n > 0 {
+ if polls[0].Revents&unix.POLLIN == 0 {
+ return errIdentity
+ }
+ return nil
+ }
+ }
+}
+func (m *Manager) persist(r Record) error { return durableJSON(m.cfg.ScratchRoot, r.ID+".json", r) }
+func durableJSON(root, name string, v any) error {
+ data, e := json.Marshal(v)
+ if e != nil {
+ return e
+ }
+ f, e := os.CreateTemp(root, ".journal-")
+ if e != nil {
+ return e
+ }
+ tmp := f.Name()
+ defer os.Remove(tmp)
+ if _, e = f.Write(data); e == nil {
+ e = f.Sync()
+ }
+ closeErr := f.Close()
+ if e != nil {
+ return e
+ }
+ if closeErr != nil {
+ return closeErr
+ }
+ if e = os.Rename(tmp, filepath.Join(root, name)); e != nil {
+ return e
+ }
+ d, e := os.Open(root)
+ if e != nil {
+ return e
+ }
+ defer d.Close()
+ return d.Sync()
+}
+
+// Recover never enumerates host processes. An absent same-boot PID without a
+// durable exit proof remains uncertain; a new boot proves absence, not outcome.
+func (m *Manager) Recover(ctx context.Context, r Record) (Proof, error) {
+ proof := Proof{Record: r, Exit: provider.Exit{Code: -1}}
+ if len(r.ID) != 32 || strings.ContainsAny(r.ID, "/.\\") || r.AttemptKey == "" || r.BootID == "" || r.ManifestHash == "" {
+ return proof, errIdentity
+ }
+ boot, e := bootID()
+ if e != nil {
+ return proof, e
+ }
+ if boot != r.BootID {
+ proof.Verified = true
+ proof.Exit.ObservedAt = time.Now().UTC()
+ return m.finishRecovery(proof)
+ }
+ if r.HostPID <= 0 || r.StartTicks == 0 || r.NamespaceID == "" {
+ return proof, errIdentity
+ }
+ saved, readErr := os.ReadFile(filepath.Join(m.cfg.ScratchRoot, r.ID+".exit.json"))
+ if readErr == nil {
+ var prior Proof
+ if json.Unmarshal(saved, &prior) != nil || !prior.Verified || prior.Record != r || prior.Exit.ObservedAt.IsZero() {
+ return proof, errIdentity
+ }
+ return m.finishRecovery(prior)
+ }
+ if !errors.Is(readErr, os.ErrNotExist) {
+ return proof, readErr
+ }
+ stored, readErr := os.ReadFile(filepath.Join(m.cfg.ScratchRoot, r.ID+".json"))
+ var durable Record
+ if readErr != nil || json.Unmarshal(stored, &durable) != nil || durable != r {
+ return proof, errIdentity
+ }
+ fd, e := exactPID(r)
+ if e != nil {
+ return proof, errIdentity
+ }
+ defer unix.Close(fd)
+ if e = unix.PidfdSendSignal(fd, unix.SIGKILL, nil, 0); e != nil && e != unix.ESRCH {
+ return proof, e
+ }
+ if e = waitPID(ctx, fd); e != nil {
+ return proof, e
+ }
+ proof.Verified = true
+ proof.Exit = provider.Exit{Code: -1, Signal: int(unix.SIGKILL), ObservedAt: time.Now().UTC()}
+ if e = durableJSON(m.cfg.ScratchRoot, r.ID+".exit.json", proof); e != nil {
+ proof.Verified = false
+ return proof, e
+ }
+ return m.finishRecovery(proof)
+}
+
+// Scratch has the durable launch ID, so recovery can remove only this attempt
+// after proving its namespace gone. Unknown same-boot identities keep it.
+func (m *Manager) finishRecovery(proof Proof) (Proof, error) {
+ if err := os.RemoveAll(filepath.Join(m.cfg.ScratchRoot, "attempt-"+proof.Record.ID)); err != nil {
+ proof.Verified = false
+ return proof, err
+ }
+ return proof, nil
+}
diff --git a/internal/runner/containment/recovery_test.go b/internal/runner/containment/recovery_test.go
new file mode 100644
index 00000000..3532f980
--- /dev/null
+++ b/internal/runner/containment/recovery_test.go
@@ -0,0 +1,255 @@
+package containment
+
+import (
+ "bufio"
+ "context"
+ "encoding/json"
+ "os"
+ "path/filepath"
+ "testing"
+ "time"
+
+ "amadan.net/oficina/equipo/internal/runner/provider"
+)
+
+func TestNamespaceRecoveryIdentity(t *testing.T) {
+ m, l := fixture(t)
+ p := launch(t, m, l, "import time; print('ready',flush=True); time.sleep(60)")
+ if _, e := bufio.NewReader(p.Stdout()).ReadString('\n'); e != nil {
+ t.Fatal(e)
+ }
+ r := record(t, m, p)
+ fd := descriptor(t, r.HostPID)
+ for _, tc := range []struct {
+ name string
+ edit func(*Record)
+ }{
+ {"reused pid", func(r *Record) { r.StartTicks++ }},
+ {"changed manifest", func(r *Record) { r.ManifestHash += "-changed" }},
+ {"changed namespace", func(r *Record) { r.NamespaceID = "pid:[0]" }},
+ {"missing handshake", func(r *Record) { r.HostPID = 0; r.StartTicks = 0; r.NamespaceID = "" }},
+ {"unavailable proof", func(r *Record) { r.ManifestHash = "" }},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ bad := r
+ tc.edit(&bad)
+ proof, e := m.Recover(context.Background(), bad)
+ if e == nil || proof.Verified {
+ t.Fatalf("uncertain identity accepted: %+v %v", proof, e)
+ }
+ alive(t, fd)
+ if _, e := os.Stat(filepath.Join(m.cfg.ScratchRoot, "attempt-"+r.ID)); e != nil {
+ t.Fatalf("unproven recovery removed scratch: %v", e)
+ }
+ })
+ }
+ changed := r
+ changed.BootID = "different-boot"
+ proof, e := m.Recover(context.Background(), changed)
+ if e != nil || !proof.Verified || proof.Exit.Code != -1 || proof.Exit.Signal != 0 {
+ t.Fatalf("changed boot fabricated outcome: %+v %v", proof, e)
+ }
+ alive(t, fd)
+ // A fresh manager reacquires only the durable, exact namespace init.
+ fresh, e := New(m.cfg)
+ if e != nil {
+ t.Fatal(e)
+ }
+ proof, e = fresh.Recover(context.Background(), r)
+ if e != nil || !proof.Verified || proof.Record != r {
+ t.Fatalf("recover exact identity: %+v %v", proof, e)
+ }
+ exited(t, fd)
+}
+func TestNamespaceMountEscape(t *testing.T) {
+ m, l := fixture(t)
+ outsideHome := t.TempDir()
+ if e := os.Chmod(outsideHome, 0700); e != nil {
+ t.Fatal(e)
+ }
+ for _, tc := range []struct {
+ name string
+ edit func(*provider.Launch)
+ }{
+ {"traversal", func(l *provider.Launch) { l.Workspace += "/../workspace" }},
+ {"outside private home", func(l *provider.Launch) { l.Binding.Home = outsideHome }},
+ {"broad home", func(l *provider.Launch) { l.Binding.Home = "/home/paulca" }},
+ {"protected state", func(l *provider.Launch) { l.Workspace = m.cfg.ScratchRoot }},
+ {"parent of protected state", func(l *provider.Launch) { l.Workspace = filepath.Dir(m.cfg.ScratchRoot) }},
+ {"host runtime", func(l *provider.Launch) {
+ l.Policy.Mounts = []provider.Mount{{Source: "/run", Target: "/opt/run", ReadOnly: true}}
+ }},
+ {"host cgroup", func(l *provider.Launch) {
+ l.Policy.Mounts = []provider.Mount{{Source: "/sys/fs/cgroup", Target: "/opt/cgroup", ReadOnly: true}}
+ }},
+ {"writable runtime", func(l *provider.Launch) {
+ l.Policy.Mounts = []provider.Mount{{Source: "/etc/hostname", Target: "/opt/name"}}
+ }},
+ {"reserved target", func(l *provider.Launch) {
+ l.Policy.Mounts = []provider.Mount{{Source: "/etc/hostname", Target: "/home/runner/hostname", ReadOnly: true}}
+ }},
+ {"home environment traversal", func(l *provider.Launch) { l.Policy.Env = map[string]string{"CODEX_HOME": "/home/runner/../../etc"} }},
+ {"tmp environment traversal", func(l *provider.Launch) { l.Policy.Env = map[string]string{"CLAUDE_TMPDIR": "/tmp/../workspace"} }},
+ {"environment", func(l *provider.Launch) { l.Policy.Env = map[string]string{"LD_PRELOAD": "/workspace/a.so"} }},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ bad := l
+ tc.edit(&bad)
+ p, e := m.Start(context.Background(), bad, []string{"/usr/bin/true"})
+ if e == nil {
+ m.Stop(context.Background(), p.ID())
+ t.Fatal("unsafe mount/environment accepted")
+ }
+ })
+ }
+ t.Run("symlink swap", func(t *testing.T) {
+ path := filepath.Join(filepath.Dir(l.Workspace), "link")
+ if e := os.Symlink(l.Workspace, path); e != nil {
+ t.Fatal(e)
+ }
+ bad := l
+ bad.Workspace = path
+ if p, e := m.Start(context.Background(), bad, []string{"/usr/bin/true"}); e == nil {
+ m.Stop(context.Background(), p.ID())
+ t.Fatal("symlink accepted")
+ }
+ })
+}
+
+func TestNamespaceRecoverySavedExit(t *testing.T) {
+ m, l := fixture(t)
+ p := launch(t, m, l, "pass")
+ r := record(t, m, p)
+ exit, e := p.Wait(context.Background())
+ if e != nil {
+ t.Fatal(e)
+ }
+ fresh, e := New(m.cfg)
+ if e != nil {
+ t.Fatal(e)
+ }
+ proof, e := fresh.Recover(context.Background(), r)
+ if e != nil || !proof.Verified || proof.Exit != exit {
+ t.Fatalf("durable exit recovery: %+v %v", proof, e)
+ }
+}
+
+func TestNamespaceRecoveryRejectsNonInit(t *testing.T) {
+ m, l := fixture(t)
+ p := launch(t, m, l, "import time; print('ready',flush=True); time.sleep(60)")
+ r := record(t, m, p)
+ // Both candidate PIDs are owned fixtures. Neither is namespace init.
+ control, controlFD := ownedControl(t)
+ bad := r
+ bad.HostPID = control.Process.Pid
+ bad.StartTicks, bad.NamespaceID, _ = identity(bad.HostPID)
+ if e := m.persist(bad); e != nil {
+ t.Fatal(e)
+ }
+ defer m.persist(r)
+ if proof, e := m.Recover(context.Background(), bad); e == nil || proof.Verified {
+ t.Fatal("host process accepted as namespace init")
+ }
+ alive(t, controlFD)
+}
+
+func TestNamespaceRecoveryStaleDurableTicks(t *testing.T) {
+ m, l := fixture(t)
+ p := launch(t, m, l, "import time; time.sleep(60)")
+ r := record(t, m, p)
+ fd := descriptor(t, r.HostPID)
+ bad := r
+ bad.StartTicks++
+ if e := m.persist(bad); e != nil {
+ t.Fatal(e)
+ }
+ defer m.persist(r)
+ if proof, e := m.Recover(context.Background(), bad); e == nil || proof.Verified {
+ t.Fatal("reused PID accepted")
+ }
+ alive(t, fd)
+}
+
+func TestNamespaceRecoveryUnavailableProof(t *testing.T) {
+ for _, kind := range []string{"missing", "corrupt", "record", "unverified", "timestamp"} {
+ t.Run(kind, func(t *testing.T) {
+ m, l := fixture(t)
+ p := launch(t, m, l, "pass")
+ r := record(t, m, p)
+ if _, e := p.Wait(context.Background()); e != nil {
+ t.Fatal(e)
+ }
+ path := filepath.Join(m.cfg.ScratchRoot, p.ID()+".exit.json")
+ b, e := os.ReadFile(path)
+ if e != nil {
+ t.Fatal(e)
+ }
+ var proof Proof
+ if e = json.Unmarshal(b, &proof); e != nil {
+ t.Fatal(e)
+ }
+ switch kind {
+ case "missing":
+ e = os.Remove(path)
+ case "corrupt":
+ e = os.WriteFile(path, []byte("{"), 0600)
+ case "record":
+ proof.Record.ManifestHash += "-changed"
+ e = durableJSON(m.cfg.ScratchRoot, p.ID()+".exit.json", proof)
+ case "unverified":
+ proof.Verified = false
+ e = durableJSON(m.cfg.ScratchRoot, p.ID()+".exit.json", proof)
+ case "timestamp":
+ proof.Exit.ObservedAt = time.Time{}
+ e = durableJSON(m.cfg.ScratchRoot, p.ID()+".exit.json", proof)
+ }
+ if e != nil {
+ t.Fatal(e)
+ }
+ if recovered, e := m.Recover(context.Background(), r); e == nil || recovered.Verified {
+ t.Fatalf("unavailable proof accepted: %+v %v", recovered, e)
+ }
+ })
+ }
+}
+
+func TestNamespaceRecoveryCleansScratch(t *testing.T) {
+ for _, kind := range []string{"saved-exit", "new-boot"} {
+ t.Run(kind, func(t *testing.T) {
+ m, l := fixture(t)
+ p := launch(t, m, l, "pass")
+ r := record(t, m, p)
+ if _, e := p.Wait(context.Background()); e != nil {
+ t.Fatal(e)
+ }
+ // Recreate the crash window after proof fsync but before scratch removal.
+ dir := filepath.Join(m.cfg.ScratchRoot, "attempt-"+r.ID)
+ if e := os.Mkdir(dir, 0700); e != nil {
+ t.Fatal(e)
+ }
+ if e := os.WriteFile(filepath.Join(dir, "leftover"), []byte("owned"), 0600); e != nil {
+ t.Fatal(e)
+ }
+ if kind == "new-boot" {
+ r.BootID = "previous-boot"
+ }
+ fresh, e := New(m.cfg)
+ if e != nil {
+ t.Fatal(e)
+ }
+ if proof, e := fresh.Recover(context.Background(), r); e != nil || !proof.Verified {
+ t.Fatalf("recover: %+v %v", proof, e)
+ }
+ if _, e := os.Stat(dir); !os.IsNotExist(e) {
+ t.Fatalf("recovery left owned scratch: %v", e)
+ }
+ })
+ }
+}
+func TestNamespaceScratchIdentity(t *testing.T) {
+ m, l := fixture(t)
+ p := launch(t, m, l, "import time; time.sleep(60)")
+ if _, e := os.Stat(filepath.Join(m.cfg.ScratchRoot, "attempt-"+p.ID(), "tmp")); e != nil {
+ t.Fatalf("scratch not bound to durable ID: %v", e)
+ }
+}
diff --git a/internal/runnerproto/containment.go b/internal/runnerproto/containment.go
index bdb4753c..ade28f08 100644
--- a/internal/runnerproto/containment.go
+++ b/internal/runnerproto/containment.go
@@ -45,3 +45,24 @@ type FreezeRequest struct {
DefinitionHash string `json:"definition_hash"`
ReproductionHash string `json:"reproduction_hash"`
}
+
+// NamespaceExit binds an observed init exit to the durable launch identity.
+type NamespaceExit struct {
+ ID string `json:"id"`
+ AttemptKey string `json:"attempt_key"`
+ BootID string `json:"boot_id"`
+ NamespaceID string `json:"namespace_id"`
+ ManifestHash string `json:"manifest_hash"`
+ HostPID int `json:"host_pid"`
+ StartTicks uint64 `json:"start_ticks"`
+ ExitCode int `json:"exit_code"`
+ Signal int `json:"signal"`
+ ObservedAt time.Time `json:"observed_at"`
+}
+type NamespaceContainmentProof struct {
+ Version int `json:"version"`
+ Scope team.Scope `json:"scope"`
+ Handle team.Handle `json:"handle"`
+ Namespaces []NamespaceExit `json:"namespaces"`
+ CheckedAt time.Time `json:"checked_at"`
+}