oficina / equipo Public

refactor: run the bug workflow through direct namespaces

codex agent, operated by paul@keymail.dev pushed by claude agent, operated by paul@keymail.dev 532e867fb597fbaf35bfa24f9f823bc3d6d270bb parent 9118dce
46 files changed, +4,736 −469
  • .rastrillo/budgets.txt +1 −1
  • docs/superpowers/plans/CONTROLLER-REPORT-plan-2b.md +1,923 −0
  • internal/equipo/runner_events.go +17 −2
  • internal/equipo/runner_report_validation.go +56 −17
  • internal/equipotest/direct_containment_test.go +112 −0
  • internal/equipotest/preparation_integration_test.go +2 −2
  • internal/equipotest/runner_flow_test.go +2 −2
  • internal/runner/budget_test.go +7 −1
  • internal/runner/capture.go +9 −0
  • internal/runner/capture_test.go +2 −0
  • internal/runner/checks/budget_test.go +7 −1
  • internal/runner/checks/containment_cleanup_test.go +28 −0
  • internal/runner/checks/containment_test.go +205 −0
  • internal/runner/checks/executor.go +6 −1
  • internal/runner/checks/namespace.go +108 −0
  • internal/runner/checks/sandbox.go +14 −4
  • internal/runner/config.go +24 −7
  • internal/runner/connections.go +6 −2
  • internal/runner/containment/linux.go +27 −3
  • internal/runner/containment/linux_test.go +10 −2
  • internal/runner/containment/mounts.go +12 −1
  • internal/runner/containment/mounts_test.go +1 −1
  • internal/runner/direct_cli_test.go +188 −0
  • internal/runner/direct_graph_test.go +289 −0
  • internal/runner/direct_namespaces.go +156 −0
  • internal/runner/direct_question_workflow_test.go +81 −0
  • internal/runner/direct_recovery.go +13 −1
  • internal/runner/direct_runtime_test.go +147 −0
  • internal/runner/direct_workflow.go +373 −0
  • internal/runner/direct_workflow_test.go +223 −0
  • internal/runner/journal.go +6 −5
  • internal/runner/provider/check_policy.go +86 −0
  • internal/runner/provider/policy.go +3 −0
  • internal/runner/runtime.go +86 −34
  • internal/runner/runtime_direct.go +151 −0
  • internal/runner/runtime_workflow.go +5 −5
  • internal/runner/service.go +5 −3
  • internal/runner/supervisor.go +71 −12
  • internal/runner/witness.go +7 −1
  • internal/runner/workflow.go +23 −98
  • internal/runner/workflow_integration_test.go +2 −2
  • internal/runner/workflow_turn.go +0 −251
  • internal/runner/workspace/direct.go +66 −0
  • internal/runner/workspace/direct_test.go +92 −0
  • internal/runner/workspace/workspace.go +68 −10
  • internal/runnerproto/containment.go +16 −0

CI failed — run details

diff --git a/.rastrillo/budgets.txt b/.rastrillo/budgets.txt
index 778d1d61..3cf8194b 100644
--- a/.rastrillo/budgets.txt
+++ b/.rastrillo/budgets.txt
@@ -21,5 +21,5 @@ time internal/runner 330s Final corrected package rerun measured 152.897s; revie
perf GET /live skip Authorized notification stream, bounded to 30 seconds; not a GET screen.
perf GET /api/runner/v1/artifacts/{assignment}/{artifact} skip Authenticated runner artifact download, not a browser GET screen. Runner long-poll and blob downloads use POST and are outside the screen inventory.
-size internal/runner 7800 - Task 7 adds durable capture, direct recovery, atomic projection and provider accounting beside the required journal APIs; current source count: 7576.
+size internal/runner 9200 - Task 9 wires direct namespaces, durable events, tool relay and recovery. Current source count is 8980 lines; historical Paseo readers remain until Task 11a.
time internal/runner/provider/claude 45s Task 5 measured 32.430s for fake CLI sessions and fsynced account, policy, capture and refresh checks; 45s gives 38 percent headroom on the shared runner.
diff --git a/docs/superpowers/plans/CONTROLLER-REPORT-plan-2b.md b/docs/superpowers/plans/CONTROLLER-REPORT-plan-2b.md
index f23c1de9..ca530c4f 100644
--- a/docs/superpowers/plans/CONTROLLER-REPORT-plan-2b.md
+++ b/docs/superpowers/plans/CONTROLLER-REPORT-plan-2b.md
@@ -17183,3 +17183,1926 @@ None. No runtime strings or `copy.go` entries were added or changed. Existing pe
### Concerns and completion
No new concerns or unresolved failures for these two findings. Existing Task 8 limits remain: native Codex command/file approvals are deny-only, Task 9 owns runtime composition, and Task 11b owns live provider and deployed-policy certification. No agents, pushes, merges or deployments were started. Test processes were awaited, and test-owned endpoints and temporary directories were closed and removed. Session scratch under `$TMPDIR/t8r2` is removed after saving this evidence and committing. No session process is intended to outlive this task.
+
+
+## Task 9: Local workspaces, checks and namespace recovery
+
+Status: DONE_WITH_CONCERNS.
+Commit subject: `refactor: run the bug workflow through direct namespaces`.
+Author: `codex <codex~paul@keymail.dev>`.
+Branch: `plan-2b`.
+All repository work and commands below used `/home/paulca/amadan.net/oficina/equipo-plan-2b`.
+
+### What changed
+
+The production runtime constructs Claude and Codex launchers with one `NewDirectHost` and `NewCaptureFactory`. Check commands use that same journal-backed host and containment manager. Startup reconciles every namespace record before constructing launch-capable services. Recovery refuses while capture is live. Provider networks are explicitly configured for both providers; dedicated-home authority comes from the account lease. The old Paseo model-turn and workspace-creation path is no longer used by the bug workflow. `BugWorkflowConfig` now requires the launcher registry, namespace manager and launch factory. `workspace.New(Config)` has the requested single-argument signature.
+
+The namespace helper remains behind its release pipe until its full PID/start/boot/namespace identity is durable and the instance has acknowledged a typed `namespace.launch` event. Launch events are bound to the assignment and fenced handle through the authenticated runner transport. They use the existing migration-0015 `runner_events` table. A new launch requires a current assignment; an exact previously committed event can be acknowledged again after fencing. Version-2 containment reports must account for every authenticated launch and match its namespace, attempt, manifest and process identity. Legacy inventory reports and `Empty:true` provide no authority. A successfully queried empty launch set permits cleanup of a claim that never launched anything; a query error never becomes zero.
+
+Workspaces use local Git. A runner-owned worktree is created from the pinned base and review ref, then receives its own credential-free Git directory and copied objects before it can be mounted. The checkout has no metadata dependency on private runner storage. Receipts retain local workspace identity and reject replacement on uncertainty. Changed config, hooks, alternates, external common directories and changed local identity are refused. Candidate capture, staged export and review checkout continue to use immutable Git objects.
+
+Checks retain the pinned Codex command deny sandbox inside an owned bubblewrap namespace. A separate check manifest admits no provider binding, credential home, tool socket or provider network. Go and the configured module cache are mounted read-only. Each namespace gets its own writable build cache and temporary-build directory under its on-disk attempt scratch, exposed only as `/tmp/go-build` and `/tmp/go-tmp` inside that namespace. The host build cache is absent and explicitly denied by the inner profile. Protected descendants are also denied through their mounted aliases. Broad home directories and namespace scratch cannot be configured as runtime/cache mounts. Unknown containment preserves executor checkouts. All namespace proofs are collected before removing check or model workspaces, reporting containment, or releasing an account lease.
+
+The workflow drains provider events into `AppendDirect` independently of uploads and person waits. A terminal notice follows the committed normalized event. A late completion cannot turn a quarantined turn into success, and queued terminal notices take precedence over stream EOF. Uncertain in-flight actions use the existing lost-outcome path, preserving unknown charges and person wait. No provider turn is replayed. Model completion alone does not release capacity.
+
+The tool proxy uses the workflow's `current()` callback on each call. Relay bindings are read after `BindTurn`, including the rewritten agent and provider-session identity. `ask_person` is answered through its bound relay and its tool submission is acknowledged once; the old follow-up path is not called by the direct workflow. Question resolution reads the delivery journal. A nil adapter response is never interpreted as an approval. The existing local-only proxy lifecycle ticker remains unchanged.
+
+Lease renewal keeps connection heartbeats alive using the last verified discovery reports while the selected account lease is held. Dispatch and current-authority checks remain in place. Once model/check/publication work has ended, the workflow stops and drains the lease watcher before reporting completion, avoiding a renewal rejection racing with its own successful completion. Runtime shutdown stops namespaces, waits for captures and then releases the account lease and journal. Failed namespace startup now also records a durable exit proof.
+
+### Coverage
+
+- `TestDirectBugWorkflow` runs reproduce, implement, independent-family review, verify and publish with local fake CLIs, real Git, the real command sandbox, private-cache checks and a local bare publication repository. It sends 200 progress frames through a 64-slot fixture stream, asks one scoped person question, consumes three model admissions and a publication admission, and checks that dependent work cannot claim capacity before containment.
+- `TestDirectWorkspaceIdentity` covers base/ref pinning, identity, fresh attempt paths, retry identity, metadata/config/hooks rejection and immutable export.
+- `TestDirectCancelWaitsForNamespaces` uses two owned namespaces with detached model, code-mode-host, relay, MCP and check stand-ins. Its unproven-namespace and removal-order variants retain capacity and checkouts until all proofs exist.
+- `TestDirectRestartAndLeaseLoss` covers rollback, suspend, revoked membership and changed connection; the live-capture variant refuses recovery during capture. Retained `TestNamespaceParentDeath` and `TestDirectInterrupted*` regressions cover runner death and durable recovery without replay.
+- `TestDirectContainmentReportBinding` and its launch-replay test exercise production instance validators on the pre-0018 schema, including missing and mismatched records, forged empty/inventory proofs, fenced replay and never-started claims.
+- `TestCheckNamespace*` and `TestCheckCache*` cover detached children, cache writes, host-cache exclusion, separate caches, mounted aliases, retained scratch and unsafe cache roots. Existing command-sandbox deny and evidence tests were retained and run.
+
+### Interpretations
+
+1. This implementation dispatch supersedes the old revision-only sentence in `global-context.md` and the original spec's Paseo engine description. The Task 9 brief and the supplied carry requirements control the runtime.
+2. `ContainmentProof` carries the new namespace fields under version 2 so the existing supervisor `Run`, `Cancel` and `Recover` entry points remain usable. Its old fields remain readable for history. Provider `Session` is authoritative for active launches; the existing typed tool/witness contracts still receive a projection using their historical agent data type.
+3. A claim with no authenticated launch records is a known empty launch set when the database query succeeds. This is needed for recovery before any process was dispatched. A report claiming a namespace without its launch record, or omitting an authenticated namespace, is rejected.
+4. Checks need a credential-free manifest of their own. The check-only attestation branch requires an empty provider selection and binding and cannot authorize a model launch. Read-only directory mounts are limited to the configured Go and module-cache roles; host development commands keep their default caches.
+5. Account/namespace cleanup is ordered after containment even when completion, an upload or credential rotation fails. The lease watcher stops only after untrusted workflow work has ended, immediately before its final instance report.
+6. The new optional configuration variables are `EQUIPO_BWRAP_PATH` (default `/usr/bin/bwrap`) and `EQUIPO_GO_MODULE_CACHE` (default the user's `go/pkg/mod`). They do not set host `GOCACHE`, `GOMODCACHE` or `GOTMPDIR`.
+7. The old Paseo package and historical cleanup/readers remain for Task 11a. They do not grant permission to start the new workflow. Older fixture call sites were updated to compile with the new workspace/workflow interfaces.
+
+### Files
+
+- `.rastrillo/budgets.txt`
+- `internal/equipo/runner_events.go`
+- `internal/equipo/runner_report_validation.go`
+- `internal/equipotest/direct_containment_test.go`
+- `internal/equipotest/preparation_integration_test.go`
+- `internal/equipotest/runner_flow_test.go`
+- `internal/runner/budget_test.go`
+- `internal/runner/capture.go`
+- `internal/runner/capture_test.go`
+- `internal/runner/checks/budget_test.go`
+- `internal/runner/checks/containment_cleanup_test.go`
+- `internal/runner/checks/containment_test.go`
+- `internal/runner/checks/executor.go`
+- `internal/runner/checks/namespace.go`
+- `internal/runner/checks/sandbox.go`
+- `internal/runner/config.go`
+- `internal/runner/connections.go`
+- `internal/runner/containment/linux.go`
+- `internal/runner/containment/linux_test.go`
+- `internal/runner/containment/mounts.go`
+- `internal/runner/containment/mounts_test.go`
+- `internal/runner/direct_cli_test.go`
+- `internal/runner/direct_graph_test.go`
+- `internal/runner/direct_namespaces.go`
+- `internal/runner/direct_question_workflow_test.go`
+- `internal/runner/direct_recovery.go`
+- `internal/runner/direct_runtime_test.go`
+- `internal/runner/direct_workflow.go`
+- `internal/runner/direct_workflow_test.go`
+- `internal/runner/journal.go`
+- `internal/runner/provider/check_policy.go`
+- `internal/runner/provider/policy.go`
+- `internal/runner/runtime.go`
+- `internal/runner/runtime_direct.go`
+- `internal/runner/runtime_workflow.go`
+- `internal/runner/service.go`
+- `internal/runner/supervisor.go`
+- `internal/runner/witness.go`
+- `internal/runner/workflow.go`
+- `internal/runner/workflow_integration_test.go`
+- `internal/runner/workflow_turn.go`
+- `internal/runner/workspace/direct.go`
+- `internal/runner/workspace/direct_test.go`
+- `internal/runner/workspace/workspace.go`
+- `internal/runnerproto/containment.go`
+- `docs/superpowers/plans/CONTROLLER-REPORT-plan-2b.md`: this appended controller evidence.
+- `.superpowers/sdd/2026-11-03-equipo-plan-2b-direct/task-9-report.md`: this full local report, at the existing ignored dispatch-report location.
+
+The runner source budget is 9,200 lines, with 8,980 physical source lines after removing the old model-turn branch. Time budgets are unchanged.
+
+### RED evidence
+
+The first required command ran after the new workspace contract test and before implementation:
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner/... ./internal/equipotest -run 'TestDirectBug|TestDirectWorkspace|TestDirectCancel|TestDirectRestart|TestDirectContainment|TestCheckNamespace|TestCheckCache' -count=1
+```
+
+Exit 1, API/compile RED:
+
+```text
+internal/runner/workspace/direct_test.go:12:17: not enough arguments in call to New
+ have (Config)
+ want (Config, *paseo.Client)
+internal/runner/workspace/direct_test.go:15:7: w.ID undefined (type Workspace has no field or method ID)
+internal/runner/workspace/direct_test.go:15:35: w.Path undefined (type Workspace has no field or method Path)
+FAIL amadan.net/oficina/equipo/internal/runner/workspace [build failed]
+```
+
+Other initial contract REDs reported the missing namespace-launch wire fields, direct supervisor fields and check-host configuration fields. These compile failures are not counted as guard mutations. After adding the wire types, the instance tests supplied behavioral RED before validator implementation:
+
+```sh
+CGO_ENABLED=0 go test ./internal/equipotest -run TestDirectContainment -count=1
+```
+
+```text
+--- FAIL: TestDirectContainmentReportBinding
+ --- FAIL: TestDirectContainmentReportBinding/valid
+ bound proof refused: One or more values are invalid. Check the form and try again.
+ --- FAIL: TestDirectContainmentReportBinding/inventory-only
+ unbound proof released capacity
+```
+
+Additional behavioral REDs before their fixes:
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner/checks -run TestCheckNamespaceRetainsScratch -count=1
+```
+
+```text
+--- FAIL: TestCheckNamespaceRetainsScratchWithoutProof
+ removed checkout without containment proof
+```
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner/checks -run TestCheckNamespaceDeniedMountAliases -count=1
+```
+
+```text
+--- FAIL: TestCheckNamespaceDeniedMountAliases
+ module mount alias bypassed denied path
+```
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner/workspace -run TestDirectWorkspace -count=1
+```
+
+```text
+--- FAIL: TestDirectWorkspaceIdentity
+ accepted changed local workspace id
+```
+
+```sh
+CGO_ENABLED=0 go test ./internal/equipotest -run TestDirectContainmentLaunchReplay -count=1
+```
+
+```text
+--- FAIL: TestDirectContainmentLaunchReplayAfterStop
+ team: fence: attempt 1 fence 1, step at 2
+```
+
+The logged RED runs below include the remaining runtime, cache, terminal and never-started cases.
+
+#### red-broad-cache
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner/checks -run TestCheckCacheRejectsBroadHome -count=1
+```
+
+Exit 1:
+
+```text
+--- FAIL: TestCheckCacheRejectsBroadHome (0.00s)
+ containment_test.go:187: broad home accepted as module cache: /home/paulca
+FAIL
+rastrillo-budget/v1 ran 1ms
+FAIL amadan.net/oficina/equipo/internal/runner/checks 0.003s
+FAIL
+```
+
+#### red-check-removal-order
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner -run TestDirectCancelRetainsCheckUntilEveryProof -count=1
+```
+
+Exit 1:
+
+```text
+--- FAIL: TestDirectCancelRetainsCheckUntilEveryProof (0.84s)
+ direct_runtime_test.go:106: removed check checkout before every namespace was contained
+FAIL
+rastrillo-budget/v1 ran 843ms
+FAIL amadan.net/oficina/equipo/internal/runner 0.846s
+FAIL
+```
+
+#### red-renew-heartbeat
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner -run TestDirectBugRuntimeRenewHeartbeat -count=1
+```
+
+Exit 1:
+
+```text
+--- FAIL: TestDirectBugRuntimeRenewHeartbeat (0.26s)
+ direct_runtime_test.go:144: active connection liveness was not renewed: [/api/runner/v1/renew]
+FAIL
+rastrillo-budget/v1 ran 261ms
+FAIL amadan.net/oficina/equipo/internal/runner 0.264s
+FAIL
+```
+
+#### red-runtime-release
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner -run TestDirectBugRuntimeClosesNamespaces -count=1
+```
+
+Exit 1:
+
+```text
+--- FAIL: TestDirectBugRuntimeClosesNamespaces (1.03s)
+ direct_runtime_test.go:79: runtime shutdown retained account lease after containment
+FAIL
+rastrillo-budget/v1 ran 1.033s
+FAIL amadan.net/oficina/equipo/internal/runner 1.043s
+FAIL
+```
+
+#### red-scratch-cache
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner/checks -run TestCheckCacheRejectsNamespaceScratch -count=1
+```
+
+Exit 1:
+
+```text
+--- FAIL: TestCheckCacheRejectsNamespaceScratch (1.65s)
+ containment_test.go:195: namespace scratch accepted as module cache
+FAIL
+rastrillo-budget/v1 ran 1.652s
+FAIL amadan.net/oficina/equipo/internal/runner/checks 1.721s
+FAIL
+```
+
+#### red-terminal-authority
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner -run TestDirectBugTerminalRequiresCommit -count=1
+```
+
+Exit 1:
+
+```text
+# amadan.net/oficina/equipo/internal/runner [amadan.net/oficina/equipo/internal/runner.test]
+internal/runner/direct_question_workflow_test.go:64:10: j.requireDirectCompletion undefined (type *Journal has no field or method requireDirectCompletion)
+FAIL amadan.net/oficina/equipo/internal/runner [build failed]
+FAIL
+```
+
+#### red-unstarted-containment
+
+```sh
+CGO_ENABLED=0 go test ./internal/equipotest -run TestDirectContainmentReportBinding/unstarted -count=1
+```
+
+Exit 1:
+
+```text
+--- FAIL: TestDirectContainmentReportBinding (0.91s)
+ --- FAIL: TestDirectContainmentReportBinding/unstarted (0.91s)
+ direct_containment_test.go:81: bound proof refused: You do not have access to this page. Ask an owner for access.
+FAIL
+rastrillo-budget/v1 ran 913ms
+FAIL amadan.net/oficina/equipo/internal/equipotest 0.969s
+FAIL
+```
+
+### Intermediate corrections
+
+The initial graph integration exposed protocol encoding, source-time and full agent-binding mismatches; these were fixed before the graph passed. Two combined runs found a stale private `lifecycle` test call after adding the admission callback. The first attempted test-call edit did not match that call; the corrected call and subsequent package compilation pass are recorded in the logs. A later graph run caught renewal racing with successful completion, leading to the explicit lease-watch shutdown and its compiling mutation.
+
+A retained capture test inserted an unscoped answer even though Task 8 now invalidates only answers scoped to the interrupted attempt. It failed with the unchanged HEAD capture implementation too. The fixture now inserts the matching `direct_answer_scopes` row. The production scoped invalidation rule was not weakened. The startup-failure test now requires both the launch record and the new exit proof, and verifies recovery of that proof.
+
+#### green
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner/... ./internal/equipotest -run 'TestDirectBug|TestDirectWorkspace|TestDirectCancel|TestDirectRestart|TestDirectContainment|TestCheckNamespace|TestCheckCache' -count=1
+```
+
+Exit 1:
+
+```text
+# amadan.net/oficina/equipo/internal/runner/containment [amadan.net/oficina/equipo/internal/runner/containment.test]
+internal/runner/containment/mounts_test.go:48:100: not enough arguments in call to m.lifecycle
+ have (context.Context, Record, []string, *mounts, string, chan startResult)
+ want (context.Context, Record, []string, *mounts, string, chan<- startResult, func(context.Context, Record) error)
+ok amadan.net/oficina/equipo/internal/runner 194.433s
+ok amadan.net/oficina/equipo/internal/runner/checks 5.064s
+FAIL amadan.net/oficina/equipo/internal/runner/containment [build failed]
+ok amadan.net/oficina/equipo/internal/runner/egress 0.004s [no tests to run]
+ok amadan.net/oficina/equipo/internal/runner/forge 0.005s [no tests to run]
+ok amadan.net/oficina/equipo/internal/runner/paseo 0.005s [no tests to run]
+ok amadan.net/oficina/equipo/internal/runner/provider 0.004s [no tests to run]
+ok amadan.net/oficina/equipo/internal/runner/provider/claude 0.006s [no tests to run]
+ok amadan.net/oficina/equipo/internal/runner/provider/codex 0.004s [no tests to run]
+ok amadan.net/oficina/equipo/internal/runner/workspace 0.535s
+ok amadan.net/oficina/equipo/internal/equipotest 6.168s
+FAIL
+```
+
+#### green2
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner/... ./internal/equipotest -run 'TestDirectBug|TestDirectWorkspace|TestDirectCancel|TestDirectRestart|TestDirectContainment|TestCheckNamespace|TestCheckCache' -count=1
+```
+
+Exit 1:
+
+```text
+# amadan.net/oficina/equipo/internal/runner/containment [amadan.net/oficina/equipo/internal/runner/containment.test]
+internal/runner/containment/mounts_test.go:48:100: not enough arguments in call to m.lifecycle
+ have (context.Context, Record, []string, *mounts, string, chan startResult)
+ want (context.Context, Record, []string, *mounts, string, chan<- startResult, func(context.Context, Record) error)
+ok amadan.net/oficina/equipo/internal/runner 191.873s
+ok amadan.net/oficina/equipo/internal/runner/checks 5.742s
+FAIL amadan.net/oficina/equipo/internal/runner/containment [build failed]
+ok amadan.net/oficina/equipo/internal/runner/egress 0.004s [no tests to run]
+ok amadan.net/oficina/equipo/internal/runner/forge 0.005s [no tests to run]
+ok amadan.net/oficina/equipo/internal/runner/paseo 0.004s [no tests to run]
+ok amadan.net/oficina/equipo/internal/runner/provider 0.005s [no tests to run]
+ok amadan.net/oficina/equipo/internal/runner/provider/claude 0.005s [no tests to run]
+ok amadan.net/oficina/equipo/internal/runner/provider/codex 0.005s [no tests to run]
+ok amadan.net/oficina/equipo/internal/runner/workspace 0.592s
+ok amadan.net/oficina/equipo/internal/equipotest 6.197s
+FAIL
+```
+
+#### green3
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner/... ./internal/equipotest -run 'TestDirectBug|TestDirectWorkspace|TestDirectCancel|TestDirectRestart|TestDirectContainment|TestCheckNamespace|TestCheckCache' -count=1
+```
+
+Exit 1:
+
+```text
+--- FAIL: TestDirectBugWorkflow (145.03s)
+ direct_graph_test.go:206: review (completed): context canceled
+ {"cause":"renew: team: fence: attempt 3 fence 1, step at 1","operation":"watchLease.renew"}
+ {"cause":"renew: team: fence: attempt 3 fence 1, step at 1","operation":"watchLease.renew"}
+ complete: team: fence: attempt 3 fence 1, step at 1
+FAIL
+rastrillo-budget/v1 ran 2m35.186s
+FAIL amadan.net/oficina/equipo/internal/runner 155.199s
+ok amadan.net/oficina/equipo/internal/runner/checks 5.903s
+ok amadan.net/oficina/equipo/internal/runner/containment 0.010s [no tests to run]
+ok amadan.net/oficina/equipo/internal/runner/egress 0.004s [no tests to run]
+ok amadan.net/oficina/equipo/internal/runner/forge 0.005s [no tests to run]
+ok amadan.net/oficina/equipo/internal/runner/paseo 0.011s [no tests to run]
+ok amadan.net/oficina/equipo/internal/runner/provider 0.007s [no tests to run]
+ok amadan.net/oficina/equipo/internal/runner/provider/claude 0.006s [no tests to run]
+ok amadan.net/oficina/equipo/internal/runner/provider/codex 0.024s [no tests to run]
+ok amadan.net/oficina/equipo/internal/runner/workspace 0.564s
+ok amadan.net/oficina/equipo/internal/equipotest 6.192s
+FAIL
+```
+
+#### regressions-direct
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner ./internal/runner/containment ./internal/runner/provider/claude ./internal/runner/provider/codex -run 'TestDirectFaultIsolation|TestDirectTerminalTransition|TestDirectInterrupted|TestDirectCompletion|TestToolProxyIdle|TestToolProxyAuthority|TestToolProxyCapabilityConcurrentBind|TestDirectToolStaleTurn|TestClaudePermissionResponse|TestCodexApprovalResponse|TestNamespaceParentDeath|TestNamespaceStopWaitsForExit|TestNamespaceKillsDetachedChildren|TestNamespaceReadOnly|TestNamespaceMount' -count=1
+```
+
+Exit 1:
+
+```text
+--- FAIL: TestDirectInterruptedLiveCapture (0.63s)
+ capture_test.go:456: live cancellation retained pending answers
+FAIL
+rastrillo-budget/v1 ran 32.556s
+FAIL amadan.net/oficina/equipo/internal/runner 32.560s
+ok amadan.net/oficina/equipo/internal/runner/containment 1.509s
+ok amadan.net/oficina/equipo/internal/runner/provider/claude 1.742s
+ok amadan.net/oficina/equipo/internal/runner/provider/codex 7.901s
+FAIL
+```
+
+#### inherited-capture-regression
+
+Unchanged HEAD capture.go temporarily restored; task implementation restored afterwards.
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner -run TestDirectInterruptedLiveCapture -count=1
+```
+
+Exit 1:
+
+```text
+--- FAIL: TestDirectInterruptedLiveCapture (0.53s)
+ capture_test.go:456: live cancellation retained pending answers
+FAIL
+rastrillo-budget/v1 ran 528ms
+FAIL amadan.net/oficina/equipo/internal/runner 0.536s
+FAIL
+```
+
+#### regressions-final
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner ./internal/runner/containment ./internal/runner/checks -run 'TestRunnerLeaseWatchdogCauseSites|TestRunnerLeaseRenewMeasuredAtSend|TestDirectInterruptedLiveCapture|TestNamespaceStartupFailure|TestNamespaceIntentBeforeFork|TestNamespaceHelperBarrier|TestNamespaceDirectPolicyAdmission|TestCheckSandboxDeniedPaths|TestFrozenReproduction|TestTrustedBaseCheckDefinitions|TestExecutorCandidateBinding' -count=1
+```
+
+Exit 1:
+
+```text
+ok amadan.net/oficina/equipo/internal/runner 2.491s
+--- FAIL: TestNamespaceStartupFailure (0.10s)
+ linux_test.go:439: startup cleanup or intent missing: [- 08480a572bdc405d1a57cbd09d8acad4.exit.json - 08480a572bdc405d1a57cbd09d8acad4.json]
+FAIL
+rastrillo-budget/v1 ran 2.287s
+FAIL amadan.net/oficina/equipo/internal/runner/containment 2.292s
+ok amadan.net/oficina/equipo/internal/runner/checks 18.252s
+FAIL
+```
+
+### GREEN and regression evidence
+
+The final required command passed after restoration. All test commands used `CGO_ENABLED=0`, the supplied on-disk TMPDIR and default host Go caches. No whole-suite run or `make ci` was performed.
+
+#### Final required gate
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner/... ./internal/equipotest -run 'TestDirectBug|TestDirectWorkspace|TestDirectCancel|TestDirectRestart|TestDirectContainment|TestCheckNamespace|TestCheckCache' -count=1
+```
+
+Exit 0:
+
+```text
+ok amadan.net/oficina/equipo/internal/runner 201.871s
+ok amadan.net/oficina/equipo/internal/runner/checks 7.623s
+ok amadan.net/oficina/equipo/internal/runner/containment 0.009s [no tests to run]
+ok amadan.net/oficina/equipo/internal/runner/egress 0.005s [no tests to run]
+ok amadan.net/oficina/equipo/internal/runner/forge 0.008s [no tests to run]
+ok amadan.net/oficina/equipo/internal/runner/paseo 0.008s [no tests to run]
+ok amadan.net/oficina/equipo/internal/runner/provider 0.008s [no tests to run]
+ok amadan.net/oficina/equipo/internal/runner/provider/claude 0.009s [no tests to run]
+ok amadan.net/oficina/equipo/internal/runner/provider/codex 0.013s [no tests to run]
+ok amadan.net/oficina/equipo/internal/runner/workspace 0.520s
+ok amadan.net/oficina/equipo/internal/equipotest 11.276s
+```
+
+#### regressions-core
+
+```sh
+CGO_ENABLED=0 go test ./internal/equipo/team ./internal/equipotest -run 'TestReservationLimitsAndOverflow|TestSettlementRules|TestLateUsageAfterCancelAndAuditedSettlement|TestPredicateRejectsInvalidEvidence|TestArtifactsOfUnfinishedAttemptsAreNotEvidence|TestLostReplyNeverReplaysBlind|TestReconcileWithoutReceiptNeverRedispatches|TestCancelSerialisesWithAdmission|TestRevokedGrantAtAdmission|TestRunnerEventReplayDirect|TestRevokedCleanupContainmentPreservesIntentCharge|TestUnconfinedContainmentProofRequired' -count=1
+```
+
+Exit 0:
+
+```text
+ok amadan.net/oficina/equipo/internal/equipo/team 1.661s
+ok amadan.net/oficina/equipo/internal/equipotest 1.971s
+```
+
+#### scoped-answer-regression-green
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner -run TestDirectInterruptedLiveCapture -count=1
+```
+
+Exit 0:
+
+```text
+ok amadan.net/oficina/equipo/internal/runner 0.710s
+```
+
+#### startup-proof-restored
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner/containment -run 'TestNamespaceStartupFailure|TestNamespaceParentDeath|TestNamespaceStopWaitsForExit|TestNamespaceDirectPolicyAdmission' -count=1
+```
+
+Exit 0:
+
+```text
+ok amadan.net/oficina/equipo/internal/runner/containment 1.990s
+```
+
+#### cache-boundary-green
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner/checks ./internal/runner/containment -run 'TestCheckCache|TestCheckNamespace|TestNamespaceStartupFailure' -count=1
+```
+
+Exit 0:
+
+```text
+ok amadan.net/oficina/equipo/internal/runner/checks 6.018s
+ok amadan.net/oficina/equipo/internal/runner/containment 0.084s
+```
+
+#### unstarted-containment-green
+
+```sh
+CGO_ENABLED=0 go test ./internal/equipotest -run TestDirectContainment -count=1
+```
+
+Exit 0:
+
+```text
+ok amadan.net/oficina/equipo/internal/equipotest 10.108s
+```
+
+#### final-contract-compile
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner/... ./internal/equipotest -run 'TestDirectBugRuntime|TestDirectWorkspace|TestDirectContainment|TestDirectCancel|TestDirectBugTerminal' -count=1
+```
+
+Exit 0:
+
+```text
+ok amadan.net/oficina/equipo/internal/runner 6.390s
+ok amadan.net/oficina/equipo/internal/runner/checks 0.008s [no tests to run]
+ok amadan.net/oficina/equipo/internal/runner/containment 0.006s [no tests to run]
+ok amadan.net/oficina/equipo/internal/runner/egress 0.005s [no tests to run]
+ok amadan.net/oficina/equipo/internal/runner/forge 0.007s [no tests to run]
+ok amadan.net/oficina/equipo/internal/runner/paseo 0.007s [no tests to run]
+ok amadan.net/oficina/equipo/internal/runner/provider 0.006s [no tests to run]
+ok amadan.net/oficina/equipo/internal/runner/provider/claude 0.007s [no tests to run]
+ok amadan.net/oficina/equipo/internal/runner/provider/codex 0.009s [no tests to run]
+ok amadan.net/oficina/equipo/internal/runner/workspace 0.418s
+ok amadan.net/oficina/equipo/internal/equipotest 10.170s
+```
+
+The runner executable also built successfully:
+
+```sh
+CGO_ENABLED=0 go build -o /home/paulca/t/e2b/task9-evidence/equipo-runner ./cmd/equipo-runner
+```
+
+Exit 0. `git diff --check` passed. The owned binary and evidence scratch were removed after copying the evidence into these reports.
+
+### Compiling mutations
+
+All 42 mutations below compiled, failed their named tests and were restored individually. No build failure is counted as mutation evidence. Module-cache mutation failures also demonstrate the remaining attestation/inner-sandbox defenses; the restored command must both start successfully and preserve the required read-only policy.
+
+#### answer-delivery
+
+File: `internal/runner/direct_workflow.go`.
+
+Original:
+
+```go
+if state != "delivered" {
+```
+
+Mutation:
+
+```go
+if false && state != "delivered" {
+```
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner -run TestDirectBugQuestionResolution -count=1
+```
+
+Exit 1, compiled, caught:
+
+```text
+--- FAIL: TestDirectBugQuestionResolution (1.16s)
+ --- FAIL: TestDirectBugQuestionResolution/pending (0.43s)
+ direct_question_workflow_test.go:31: question resolution trusted transport result instead of journal: [question_resolved]
+ --- FAIL: TestDirectBugQuestionResolution/invalid (0.38s)
+ direct_question_workflow_test.go:31: question resolution trusted transport result instead of journal: [question_resolved]
+FAIL
+rastrillo-budget/v1 ran 1.159s
+FAIL amadan.net/oficina/equipo/internal/runner 1.163s
+FAIL
+```
+
+#### attempt-context
+
+File: `internal/runner/direct_recovery.go`.
+
+Original:
+
+```go
+return h.manager.StartRecorded(ctx, l, args,
+```
+
+Mutation:
+
+```go
+return h.manager.StartRecorded(context.WithoutCancel(ctx), l, args,
+```
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner -run 'TestDirectRestartAndLeaseLoss$/suspend' -count=1
+```
+
+Exit 1, compiled, caught:
+
+```text
+--- FAIL: TestDirectRestartAndLeaseLoss (4.00s)
+ --- FAIL: TestDirectRestartAndLeaseLoss/suspend (4.00s)
+ direct_workflow_test.go:215: namespace survived authority loss: context deadline exceeded
+FAIL
+rastrillo-budget/v1 ran 3.996s
+FAIL amadan.net/oficina/equipo/internal/runner 4.008s
+FAIL
+```
+
+#### broad-cache-root
+
+File: `internal/runner/provider/check_policy.go`.
+
+Original:
+
+```go
+if path == "/" || withinPath(home, path) {
+```
+
+Mutation:
+
+```go
+if false && (path == "/" || withinPath(home, path)) {
+```
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner/checks -run TestCheckCacheRejectsBroadHome -count=1
+```
+
+Exit 1, compiled, caught:
+
+```text
+--- FAIL: TestCheckCacheRejectsBroadHome (0.00s)
+ containment_test.go:194: broad home accepted as module cache: /home/paulca
+FAIL
+rastrillo-budget/v1 ran 1ms
+FAIL amadan.net/oficina/equipo/internal/runner/checks 0.003s
+FAIL
+```
+
+#### check-cache-separation
+
+File: `internal/runner/checks/namespace.go`.
+
+Original:
+
+```go
+"check-" + rand.Text()
+```
+
+Mutation:
+
+```go
+"check-fixed" + rand.Text()[:0]
+```
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner/checks -run TestCheckCacheIsolation -count=1
+```
+
+Exit 1, compiled, caught:
+
+```text
+--- FAIL: TestCheckCacheIsolation (2.11s)
+ containment_test.go:132: cache check 1: -1 provider_identity_mismatch
+FAIL
+rastrillo-budget/v1 ran 2.114s
+FAIL amadan.net/oficina/equipo/internal/runner/checks 2.166s
+FAIL
+```
+
+#### check-removal-order
+
+File: `internal/runner/direct_namespaces.go`.
+
+Original:
+
+```go
+if failures != nil {
+```
+
+Mutation:
+
+```go
+if false && failures != nil {
+```
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner -run TestDirectCancelRetainsCheckUntilEveryProof -count=1
+```
+
+Exit 1, compiled, caught:
+
+```text
+--- FAIL: TestDirectCancelRetainsCheckUntilEveryProof (1.02s)
+ direct_runtime_test.go:127: missing namespace proof accepted
+FAIL
+rastrillo-budget/v1 ran 1.016s
+FAIL amadan.net/oficina/equipo/internal/runner 1.019s
+FAIL
+```
+
+#### check-scratch-proof
+
+File: `internal/runner/checks/executor.go`.
+
+Original:
+
+```go
+ok && !sandbox.Contained(work)
+```
+
+Mutation:
+
+```go
+ok && false && !sandbox.Contained(work)
+```
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner/checks -run TestCheckNamespaceRetainsScratchWithoutProof -count=1
+```
+
+Exit 1, compiled, caught:
+
+```text
+--- FAIL: TestCheckNamespaceRetainsScratchWithoutProof (0.17s)
+ containment_cleanup_test.go:26: removed checkout without containment proof
+FAIL
+rastrillo-budget/v1 ran 170ms
+FAIL amadan.net/oficina/equipo/internal/runner/checks 0.172s
+FAIL
+```
+
+#### early-capacity
+
+File: `internal/runner/direct_namespaces.go`.
+
+Original:
+
+```go
+if failures != nil {
+```
+
+Mutation:
+
+```go
+if false && failures != nil {
+```
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner -run TestDirectCancelWaitsForNamespacesUnproven -count=1
+```
+
+Exit 1, compiled, caught:
+
+```text
+--- FAIL: TestDirectCancelWaitsForNamespacesUnproven (0.55s)
+ direct_workflow_test.go:150: unproven check namespace released capacity
+FAIL
+rastrillo-budget/v1 ran 546ms
+FAIL amadan.net/oficina/equipo/internal/runner 0.552s
+FAIL
+```
+
+#### failed-start-proof
+
+File: `internal/runner/containment/linux.go`.
+
+Original:
+
+```go
+if !startedProcess {
+```
+
+Mutation:
+
+```go
+if false && !startedProcess {
+```
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner/containment -run TestNamespaceStartupFailure -count=1
+```
+
+Exit 1, compiled, caught:
+
+```text
+--- FAIL: TestNamespaceStartupFailure (0.04s)
+ linux_test.go:439: startup intent or exit proof missing: [- 23142add44701ce5f4ea833ca18062d5.json]
+FAIL
+rastrillo-budget/v1 ran 43ms
+FAIL amadan.net/oficina/equipo/internal/runner/containment 0.046s
+FAIL
+```
+
+#### git-config
+
+File: `internal/runner/workspace/direct.go`.
+
+Original:
+
+```go
+digest(config) != at.ConfigHash
+```
+
+Mutation:
+
+```go
+len(config) < 0
+```
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner/workspace -run TestDirectWorkspaceIdentity/config -count=1
+```
+
+Exit 1, compiled, caught:
+
+```text
+--- FAIL: TestDirectWorkspaceIdentity (0.33s)
+ --- FAIL: TestDirectWorkspaceIdentity/config (0.00s)
+ direct_test.go:53: accepted untrusted Git metadata
+FAIL
+rastrillo-budget/v1 ran 331ms
+FAIL amadan.net/oficina/equipo/internal/runner/workspace 0.335s
+FAIL
+```
+
+#### git-hooks
+
+File: `internal/runner/workspace/direct.go`.
+
+Original:
+
+```go
+ || strings.HasPrefix(rel, "hooks/")
+```
+
+Mutation:
+
+```go
+
+```
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner/workspace -run TestDirectWorkspaceIdentity/hooks -count=1
+```
+
+Exit 1, compiled, caught:
+
+```text
+--- FAIL: TestDirectWorkspaceIdentity (0.33s)
+ --- FAIL: TestDirectWorkspaceIdentity/hooks/pre-commit (0.00s)
+ direct_test.go:53: accepted untrusted Git metadata
+FAIL
+rastrillo-budget/v1 ran 329ms
+FAIL amadan.net/oficina/equipo/internal/runner/workspace 0.331s
+FAIL
+```
+
+#### git-metadata
+
+File: `internal/runner/workspace/direct.go`.
+
+Original:
+
+```go
+rel == "commondir" ||
+```
+
+Mutation:
+
+```go
+
+```
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner/workspace -run TestDirectWorkspaceIdentity/commondir -count=1
+```
+
+Exit 1, compiled, caught:
+
+```text
+--- FAIL: TestDirectWorkspaceIdentity (0.10s)
+ --- FAIL: TestDirectWorkspaceIdentity/commondir (0.00s)
+ direct_test.go:53: accepted untrusted Git metadata
+ direct_test.go:63: git [commit -am candidate]: exit status 128 fatal: not a git repository (or any of the parent directories): .git
+FAIL
+rastrillo-budget/v1 ran 103ms
+FAIL amadan.net/oficina/equipo/internal/runner/workspace 0.105s
+FAIL
+```
+
+#### host-cache-exclusion
+
+File: `internal/runner/checks/namespace.go`.
+
+Original:
+
+```go
+filepath.Join(s.home, ".cache/go-build"): "deny"
+```
+
+Mutation:
+
+```go
+filepath.Join(s.home, ".cache/go-build"): "read"
+```
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner/checks -run TestCheckCacheIsolation -count=1
+```
+
+Exit 1, compiled, caught:
+
+```text
+--- FAIL: TestCheckCacheIsolation (2.44s)
+ containment_test.go:144: host build cache exclusion missing
+FAIL
+rastrillo-budget/v1 ran 2.439s
+FAIL amadan.net/oficina/equipo/internal/runner/checks 2.507s
+FAIL
+```
+
+#### launch-admission
+
+File: `internal/runner/direct_recovery.go`.
+
+Original:
+
+```go
+return observe(ctx, r)
+```
+
+Mutation:
+
+```go
+_ = observe; return nil
+```
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner -run TestDirectBugLaunchAdmission -count=1
+```
+
+Exit 1, compiled, caught:
+
+```text
+--- FAIL: TestDirectBugLaunchAdmission (0.53s)
+ direct_workflow_test.go:114: namespace ran without launch ACK
+FAIL
+rastrillo-budget/v1 ran 531ms
+FAIL amadan.net/oficina/equipo/internal/runner 0.537s
+FAIL
+```
+
+#### launch-current-handle
+
+File: `internal/equipo/runner_events.go`.
+
+Original:
+
+```go
+if event.Kind == "namespace.launch" || event.Kind == "namespace.owner" {
+```
+
+Mutation:
+
+```go
+if false && (event.Kind == "namespace.launch" || event.Kind == "namespace.owner") {
+```
+
+```sh
+CGO_ENABLED=0 go test ./internal/equipotest -run TestDirectContainmentLaunchReplayAfterStop -count=1
+```
+
+Exit 1, compiled, caught:
+
+```text
+--- FAIL: TestDirectContainmentLaunchReplayAfterStop (1.11s)
+ direct_containment_test.go:108: new launch admitted after stop
+FAIL
+rastrillo-budget/v1 ran 1.107s
+FAIL amadan.net/oficina/equipo/internal/equipotest 1.169s
+FAIL
+```
+
+#### launch-manifest
+
+File: `internal/runnerproto/containment.go`.
+
+Original:
+
+```go
+len(n.ManifestHash) == 64 &&
+```
+
+Mutation:
+
+```go
+
+```
+
+```sh
+CGO_ENABLED=0 go test ./internal/equipotest -run TestDirectContainmentReportBinding/launch-no-manifest -count=1
+```
+
+Exit 1, compiled, caught:
+
+```text
+--- FAIL: TestDirectContainmentReportBinding (0.99s)
+ --- FAIL: TestDirectContainmentReportBinding/launch-no-manifest (0.99s)
+ direct_containment_test.go:37: invalid authenticated launch accepted
+FAIL
+rastrillo-budget/v1 ran 994ms
+FAIL amadan.net/oficina/equipo/internal/equipotest 1.069s
+FAIL
+```
+
+#### launch-namespace
+
+File: `internal/runnerproto/containment.go`.
+
+Original:
+
+```go
+n.NamespaceID != "" &&
+```
+
+Mutation:
+
+```go
+
+```
+
+```sh
+CGO_ENABLED=0 go test ./internal/equipotest -run TestDirectContainmentReportBinding/launch-no-namespace -count=1
+```
+
+Exit 1, compiled, caught:
+
+```text
+--- FAIL: TestDirectContainmentReportBinding (0.97s)
+ --- FAIL: TestDirectContainmentReportBinding/launch-no-namespace (0.97s)
+ direct_containment_test.go:37: invalid authenticated launch accepted
+FAIL
+rastrillo-budget/v1 ran 975ms
+FAIL amadan.net/oficina/equipo/internal/equipotest 1.039s
+FAIL
+```
+
+#### launch-owner
+
+File: `internal/runnerproto/containment.go`.
+
+Original:
+
+```go
+n.OwnerKey == owner &&
+```
+
+Mutation:
+
+```go
+
+```
+
+```sh
+CGO_ENABLED=0 go test ./internal/equipotest -run TestDirectContainmentReportBinding/launch-wrong-owner -count=1
+```
+
+Exit 1, compiled, caught:
+
+```text
+--- FAIL: TestDirectContainmentReportBinding (1.12s)
+ --- FAIL: TestDirectContainmentReportBinding/launch-wrong-owner (1.12s)
+ direct_containment_test.go:37: invalid authenticated launch accepted
+FAIL
+rastrillo-budget/v1 ran 1.124s
+FAIL amadan.net/oficina/equipo/internal/equipotest 1.190s
+FAIL
+```
+
+#### launch-policy
+
+File: `internal/runnerproto/containment.go`.
+
+Original:
+
+```go
+len(n.PolicyHash) == 64 &&
+```
+
+Mutation:
+
+```go
+
+```
+
+```sh
+CGO_ENABLED=0 go test ./internal/equipotest -run TestDirectContainmentReportBinding/launch-no-policy -count=1
+```
+
+Exit 1, compiled, caught:
+
+```text
+--- FAIL: TestDirectContainmentReportBinding (1.02s)
+ --- FAIL: TestDirectContainmentReportBinding/launch-no-policy (1.02s)
+ direct_containment_test.go:37: invalid authenticated launch accepted
+FAIL
+rastrillo-budget/v1 ran 1.023s
+FAIL amadan.net/oficina/equipo/internal/equipotest 1.089s
+FAIL
+```
+
+#### lease-completion-order
+
+File: `internal/runner/workflow.go`.
+
+Original:
+
+```go
+s.stopLeaseWatch()
+```
+
+Mutation:
+
+```go
+// mutation: watchdog still running
+```
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner -run 'TestDirectBugWorkflow$' -count=1
+```
+
+Exit 1, compiled, caught:
+
+```text
+--- FAIL: TestDirectBugWorkflow (60.58s)
+ direct_graph_test.go:214: reproduce (completing): completion while lease watchdog was still live
+FAIL
+rastrillo-budget/v1 ran 1m0.578s
+FAIL amadan.net/oficina/equipo/internal/runner 60.663s
+FAIL
+```
+
+#### legacy-launch-refused
+
+File: `internal/runner/workflow.go`.
+
+Original:
+
+```go
+(len(c.Launchers) != 2 || c.Launchers["claude"] == nil || c.Launchers["codex"] == nil || c.Namespaces == nil || c.Launch == nil)
+```
+
+Mutation:
+
+```go
+false
+```
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner -run 'TestDirectBugRuntime$' -count=1
+```
+
+Exit 1, compiled, caught:
+
+```text
+--- FAIL: TestDirectBugRuntime (0.28s)
+ direct_runtime_test.go:51: legacy client authorized new workflow
+FAIL
+rastrillo-budget/v1 ran 280ms
+FAIL amadan.net/oficina/equipo/internal/runner 0.283s
+FAIL
+```
+
+#### live-capture-recovery
+
+File: `internal/runner/direct_recovery.go`.
+
+Original:
+
+```go
+if !j.captureMu.TryLock() {
+ return nil, errDirectUncertain
+ }
+ defer j.captureMu.Unlock()
+```
+
+Mutation:
+
+```go
+_ = &j.captureMu
+```
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner -run TestDirectRestartAndLeaseLossLiveCapture -count=1
+```
+
+Exit 1, compiled, caught:
+
+```text
+--- FAIL: TestDirectRestartAndLeaseLossLiveCapture (0.43s)
+ direct_workflow_test.go:136: recovery admitted while capture was live
+FAIL
+rastrillo-budget/v1 ran 434ms
+FAIL amadan.net/oficina/equipo/internal/runner 0.437s
+FAIL
+```
+
+#### local-workspace-identity
+
+File: `internal/runner/workspace/workspace.go`.
+
+Original:
+
+```go
+ || (at.Local && (w.ID != at.Workspace.WorkspaceID || w.Path != at.Workspace.Path))
+```
+
+Mutation:
+
+```go
+
+```
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner/workspace -run TestDirectWorkspaceIdentity -count=1
+```
+
+Exit 1, compiled, caught:
+
+```text
+--- FAIL: TestDirectWorkspaceIdentity (0.10s)
+ direct_test.go:41: accepted changed local workspace id
+FAIL
+rastrillo-budget/v1 ran 102ms
+FAIL amadan.net/oficina/equipo/internal/runner/workspace 0.104s
+FAIL
+```
+
+#### missed-check
+
+File: `internal/runner/direct_namespaces.go`.
+
+Original:
+
+```go
+if n.Owner != attemptKey(r.Claim.Scope, r.Claim.Handle) {
+```
+
+Mutation:
+
+```go
+if n.Owner != attemptKey(r.Claim.Scope, r.Claim.Handle) || n.Record.AttemptKey == "check-fixture" {
+```
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner -run 'TestDirectCancelWaitsForNamespaces$' -count=1
+```
+
+Exit 1, compiled, caught:
+
+```text
+--- FAIL: TestDirectCancelWaitsForNamespaces (1.75s)
+ direct_workflow_test.go:97: missing namespace proof: {Namespaces:[{ID:a6fc516cb4785e76a8ebc235b9a49328 AttemptKey:model-fixture BootID:1edb59fc-5665-4f1e-84f5-3b03b0992119 NamespaceID:pid:[4026532942] ManifestHash:52bbe0c95bc9a9e52a21769df95aab1624cab4dfa3fc696b3161e0ac9133f8f7 HostPID:3736228 StartTicks:858635478 ExitCode:-1 Signal:9 ObservedAt:2026-11-03 17:57:22.9065385 +0000 UTC}] CheckedAt:2026-11-03 17:57:23.07603421 +0000 UTC Version:2 Scope:{Account:team Job:1} Handle:{Revision:0 Attempt:1 Fence:1 Runner:runner} Owner:{LocalOnly:false Attempt:0 Fence:0 Marker: AgentID: Workspace:{ServerID: ProjectID: WorkspaceID: Path:} ExecutorGroups:[]} Inventory:{Observed:[] ExecutorGroups:[] Processes:[] TerminalIDs:[] CoverageKnown:false BootID: CheckedAt:0001-01-01 00:00:00 +0000 UTC} Observed:[] Empty:false}
+FAIL
+rastrillo-budget/v1 ran 1.753s
+FAIL amadan.net/oficina/equipo/internal/runner 1.759s
+FAIL
+```
+
+#### module-alias-denial
+
+File: `internal/runner/checks/namespace.go`.
+
+Original:
+
+```go
+roots[filepath.Join(mount.Target, rel)] = "deny"
+```
+
+Mutation:
+
+```go
+_ = rel
+```
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner/checks -run TestCheckNamespaceDeniedMountAliases -count=1
+```
+
+Exit 1, compiled, caught:
+
+```text
+--- FAIL: TestCheckNamespaceDeniedMountAliases (1.25s)
+ containment_test.go:179: module mount alias bypassed denied path
+FAIL
+rastrillo-budget/v1 ran 1.251s
+FAIL amadan.net/oficina/equipo/internal/runner/checks 1.293s
+FAIL
+```
+
+#### module-cache-inner
+
+File: `internal/runner/checks/namespace.go`.
+
+Original:
+
+```go
+"/opt/go-mod": "read"
+```
+
+Mutation:
+
+```go
+"/opt/go-mod": "write"
+```
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner/checks -run TestCheckCacheIsolation -count=1
+```
+
+Exit 1, compiled, caught:
+
+```text
+--- FAIL: TestCheckCacheIsolation (1.30s)
+ containment_test.go:132: cache check 0: 1 <nil> bwrap: Can't mkdir /opt/go-mod/.git: Read-only file system
+FAIL
+rastrillo-budget/v1 ran 1.304s
+FAIL amadan.net/oficina/equipo/internal/runner/checks 1.339s
+FAIL
+```
+
+#### module-cache-outer
+
+File: `internal/runner/provider/check_policy.go`.
+
+Original:
+
+```go
+{Source: in.ModuleCache, Target: "/opt/go-mod", ReadOnly: true}
+```
+
+Mutation:
+
+```go
+{Source: in.ModuleCache, Target: "/opt/go-mod", ReadOnly: false}
+```
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner/checks -run TestCheckCacheIsolation -count=1
+```
+
+Exit 1, compiled, caught:
+
+```text
+--- FAIL: TestCheckCacheIsolation (0.82s)
+ containment_test.go:132: cache check 0: -1 provider_policy_rejected
+FAIL
+rastrillo-budget/v1 ran 817ms
+FAIL amadan.net/oficina/equipo/internal/runner/checks 0.875s
+FAIL
+```
+
+#### proof-attempt
+
+File: `internal/runnerproto/containment.go`.
+
+Original:
+
+```go
+n.AttemptKey == x.AttemptKey &&
+```
+
+Mutation:
+
+```go
+
+```
+
+```sh
+CGO_ENABLED=0 go test ./internal/equipotest -run TestDirectContainmentReportBinding/wrong-attempt -count=1
+```
+
+Exit 1, compiled, caught:
+
+```text
+--- FAIL: TestDirectContainmentReportBinding (0.83s)
+ --- FAIL: TestDirectContainmentReportBinding/wrong-attempt (0.83s)
+ direct_containment_test.go:83: unbound proof released capacity
+FAIL
+rastrillo-budget/v1 ran 827ms
+FAIL amadan.net/oficina/equipo/internal/equipotest 0.883s
+FAIL
+```
+
+#### proof-boot
+
+File: `internal/runnerproto/containment.go`.
+
+Original:
+
+```go
+n.BootID == x.BootID &&
+```
+
+Mutation:
+
+```go
+
+```
+
+```sh
+CGO_ENABLED=0 go test ./internal/equipotest -run TestDirectContainmentReportBinding/wrong-boot -count=1
+```
+
+Exit 1, compiled, caught:
+
+```text
+--- FAIL: TestDirectContainmentReportBinding (1.26s)
+ --- FAIL: TestDirectContainmentReportBinding/wrong-boot (1.26s)
+ direct_containment_test.go:83: unbound proof released capacity
+FAIL
+rastrillo-budget/v1 ran 1.259s
+FAIL amadan.net/oficina/equipo/internal/equipotest 1.364s
+FAIL
+```
+
+#### proof-fence
+
+File: `internal/equipo/runner_report_validation.go`.
+
+Original:
+
+```go
+p.Handle != q.Handle ||
+```
+
+Mutation:
+
+```go
+
+```
+
+```sh
+CGO_ENABLED=0 go test ./internal/equipotest -run TestDirectContainmentReportBinding/wrong-fence -count=1
+```
+
+Exit 1, compiled, caught:
+
+```text
+--- FAIL: TestDirectContainmentReportBinding (1.13s)
+ --- FAIL: TestDirectContainmentReportBinding/wrong-fence (1.13s)
+ direct_containment_test.go:83: unbound proof released capacity
+FAIL
+rastrillo-budget/v1 ran 1.131s
+FAIL amadan.net/oficina/equipo/internal/equipotest 1.197s
+FAIL
+```
+
+#### proof-init
+
+File: `internal/runnerproto/containment.go`.
+
+Original:
+
+```go
+n.StartTicks == x.StartTicks &&
+```
+
+Mutation:
+
+```go
+
+```
+
+```sh
+CGO_ENABLED=0 go test ./internal/equipotest -run TestDirectContainmentReportBinding/wrong-init -count=1
+```
+
+Exit 1, compiled, caught:
+
+```text
+--- FAIL: TestDirectContainmentReportBinding (1.15s)
+ --- FAIL: TestDirectContainmentReportBinding/wrong-init (1.15s)
+ direct_containment_test.go:83: unbound proof released capacity
+FAIL
+rastrillo-budget/v1 ran 1.154s
+FAIL amadan.net/oficina/equipo/internal/equipotest 1.277s
+FAIL
+```
+
+#### proof-manifest
+
+File: `internal/runnerproto/containment.go`.
+
+Original:
+
+```go
+n.ManifestHash == x.ManifestHash &&
+```
+
+Mutation:
+
+```go
+
+```
+
+```sh
+CGO_ENABLED=0 go test ./internal/equipotest -run TestDirectContainmentReportBinding/wrong-manifest -count=1
+```
+
+Exit 1, compiled, caught:
+
+```text
+--- FAIL: TestDirectContainmentReportBinding (1.11s)
+ --- FAIL: TestDirectContainmentReportBinding/wrong-manifest (1.11s)
+ direct_containment_test.go:83: unbound proof released capacity
+FAIL
+rastrillo-budget/v1 ran 1.111s
+FAIL amadan.net/oficina/equipo/internal/equipotest 1.168s
+FAIL
+```
+
+#### proof-namespace-count
+
+File: `internal/equipo/runner_report_validation.go`.
+
+Original:
+
+```go
+if len(launches) != len(p.Namespaces) {
+```
+
+Mutation:
+
+```go
+if false && len(launches) != len(p.Namespaces) {
+```
+
+```sh
+CGO_ENABLED=0 go test ./internal/equipotest -run TestDirectContainmentReportBinding/missing-namespace -count=1
+```
+
+Exit 1, compiled, caught:
+
+```text
+--- FAIL: TestDirectContainmentReportBinding (1.01s)
+ --- FAIL: TestDirectContainmentReportBinding/missing-namespace (1.01s)
+ direct_containment_test.go:85: unbound proof released capacity
+FAIL
+rastrillo-budget/v1 ran 1.009s
+FAIL amadan.net/oficina/equipo/internal/equipotest 1.079s
+FAIL
+```
+
+#### proof-namespace
+
+File: `internal/runnerproto/containment.go`.
+
+Original:
+
+```go
+n.NamespaceID == x.NamespaceID &&
+```
+
+Mutation:
+
+```go
+
+```
+
+```sh
+CGO_ENABLED=0 go test ./internal/equipotest -run TestDirectContainmentReportBinding/wrong-namespace -count=1
+```
+
+Exit 1, compiled, caught:
+
+```text
+--- FAIL: TestDirectContainmentReportBinding (1.18s)
+ --- FAIL: TestDirectContainmentReportBinding/wrong-namespace (1.18s)
+ direct_containment_test.go:83: unbound proof released capacity
+FAIL
+rastrillo-budget/v1 ran 1.176s
+FAIL amadan.net/oficina/equipo/internal/equipotest 1.311s
+FAIL
+```
+
+#### proof-version
+
+File: `internal/equipo/runner_report_validation.go`.
+
+Original:
+
+```go
+p.Version != 2 ||
+```
+
+Mutation:
+
+```go
+
+```
+
+```sh
+CGO_ENABLED=0 go test ./internal/equipotest -run TestDirectContainmentReportBinding/inventory-only -count=1
+```
+
+Exit 1, compiled, caught:
+
+```text
+--- FAIL: TestDirectContainmentReportBinding (1.17s)
+ --- FAIL: TestDirectContainmentReportBinding/inventory-only (1.17s)
+ direct_containment_test.go:83: unbound proof released capacity
+FAIL
+rastrillo-budget/v1 ran 1.171s
+FAIL amadan.net/oficina/equipo/internal/equipotest 1.228s
+FAIL
+```
+
+#### renew-heartbeat
+
+File: `internal/runner/runtime.go`.
+
+Original:
+
+```go
+if op == "renew" {
+```
+
+Mutation:
+
+```go
+if false && op == "renew" {
+```
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner -run TestDirectBugRuntimeRenewHeartbeat -count=1
+```
+
+Exit 1, compiled, caught:
+
+```text
+--- FAIL: TestDirectBugRuntimeRenewHeartbeat (0.24s)
+ direct_runtime_test.go:147: active connection liveness was not renewed: [/api/runner/v1/renew]
+FAIL
+rastrillo-budget/v1 ran 244ms
+FAIL amadan.net/oficina/equipo/internal/runner 0.247s
+FAIL
+```
+
+#### runtime-lease-release
+
+File: `internal/runner/runtime.go`.
+
+Original:
+
+```go
+if r.service != nil && r.service.Supervisor.activeRelease != nil {
+```
+
+Mutation:
+
+```go
+if false && r.service != nil && r.service.Supervisor.activeRelease != nil {
+```
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner -run TestDirectBugRuntimeClosesNamespaces -count=1
+```
+
+Exit 1, compiled, caught:
+
+```text
+--- FAIL: TestDirectBugRuntimeClosesNamespaces (0.93s)
+ direct_runtime_test.go:94: runtime shutdown retained account lease after containment
+FAIL
+rastrillo-budget/v1 ran 935ms
+FAIL amadan.net/oficina/equipo/internal/runner 0.944s
+FAIL
+```
+
+#### runtime-namespace-stop
+
+File: `internal/runner/runtime.go`.
+
+Original:
+
+```go
+var err error
+ if r.namespaces != nil {
+```
+
+Mutation:
+
+```go
+var err error
+ if false && r.namespaces != nil {
+```
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner -run TestDirectBugRuntimeClosesNamespaces -count=1
+```
+
+Exit 1, compiled, caught:
+
+```text
+--- FAIL: TestDirectBugRuntimeClosesNamespaces (0.94s)
+ direct_runtime_test.go:92: context deadline exceeded
+FAIL
+rastrillo-budget/v1 ran 937ms
+FAIL amadan.net/oficina/equipo/internal/runner 0.943s
+FAIL
+```
+
+#### scratch-cache-root
+
+File: `internal/runner/containment/mounts.go`.
+
+Original:
+
+```go
+if l.Policy.IsCheck() && (overlaps(mount.Source, m.cfg.ScratchRoot) || mount.Source == "/" || within(home, mount.Source)) {
+```
+
+Mutation:
+
+```go
+if false && l.Policy.IsCheck() && (overlaps(mount.Source, m.cfg.ScratchRoot) || mount.Source == "/" || within(home, mount.Source)) {
+```
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner/checks -run TestCheckCacheRejectsNamespaceScratch -count=1
+```
+
+Exit 1, compiled, caught:
+
+```text
+--- FAIL: TestCheckCacheRejectsNamespaceScratch (1.39s)
+ containment_test.go:203: namespace scratch accepted as module cache
+FAIL
+rastrillo-budget/v1 ran 1.386s
+FAIL amadan.net/oficina/equipo/internal/runner/checks 1.446s
+FAIL
+```
+
+#### startup-reconciliation
+
+File: `internal/runner/runtime.go`.
+
+Original:
+
+```go
+if _, err = r.journal.ReconcileDirect(ctx, r.namespaces); err != nil {
+ return r, err
+ }
+```
+
+Mutation:
+
+```go
+
+```
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner -run TestDirectBugRuntimeRecoveryBeforeStart -count=1
+```
+
+Exit 1, compiled, caught:
+
+```text
+--- FAIL: TestDirectBugRuntimeRecoveryBeforeStart (0.14s)
+ direct_runtime_test.go:62: admitted launchers before reconciling unknown namespace
+FAIL
+rastrillo-budget/v1 ran 138ms
+FAIL amadan.net/oficina/equipo/internal/runner 0.141s
+FAIL
+```
+
+#### terminal-authority
+
+File: `internal/runner/direct_workflow.go`.
+
+Original:
+
+```go
+if state != "completed" {
+```
+
+Mutation:
+
+```go
+if false && state != "completed" {
+```
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner -run TestDirectBugTerminalRequiresCommit -count=1
+```
+
+Exit 1, compiled, caught:
+
+```text
+--- FAIL: TestDirectBugTerminalRequiresCommit (1.21s)
+ --- FAIL: TestDirectBugTerminalRequiresCommit/cancelled-before-commit (0.61s)
+ direct_question_workflow_test.go:77: wrong terminal authority after cancellation: <nil>
+FAIL
+rastrillo-budget/v1 ran 1.207s
+FAIL amadan.net/oficina/equipo/internal/runner 1.210s
+FAIL
+```
+
+#### terminal-before-eof
+
+File: `internal/runner/direct_workflow.go`.
+
+Original:
+
+```go
+func nextDirectNotice(ctx context.Context, notices <-chan provider.Event, done chan error) (provider.Event, error) {
+ select {
+ case event := <-notices:
+ return event, nil
+ default:
+ }
+ select {
+ case event := <-notices:
+ return event, nil
+ case <-ctx.Done():
+ return provider.Event{}, ctx.Err()
+ case err := <-done:
+ done <- err
+ select {
+ case event := <-notices:
+ return event, nil
+ default:
+ return provider.Event{}, err
+ }
+ }
+}
+
+```
+
+Mutation:
+
+```go
+func nextDirectNotice(ctx context.Context, notices <-chan provider.Event, done chan error) (provider.Event, error) {err:=<-done;done<-err;return provider.Event{},err}
+
+```
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner -run TestDirectBugTerminalEOF -count=1
+```
+
+Exit 1, compiled, caught:
+
+```text
+--- FAIL: TestDirectBugTerminalEOF (0.00s)
+ direct_question_workflow_test.go:45: EOF replaced committed terminal event
+FAIL
+rastrillo-budget/v1 ran 0s
+FAIL amadan.net/oficina/equipo/internal/runner 0.016s
+FAIL
+```
+
+#### unstarted-known-zero
+
+File: `internal/equipo/runner_report_validation.go`.
+
+Original:
+
+```go
+if len(launches) != len(p.Namespaces) {
+```
+
+Mutation:
+
+```go
+if len(launches) != len(p.Namespaces) || len(launches)==0 {
+```
+
+```sh
+CGO_ENABLED=0 go test ./internal/equipotest -run TestDirectContainmentReportBinding/unstarted -count=1
+```
+
+Exit 1, compiled, caught:
+
+```text
+--- FAIL: TestDirectContainmentReportBinding (1.05s)
+ --- FAIL: TestDirectContainmentReportBinding/unstarted (1.05s)
+ direct_containment_test.go:82: bound proof refused: You do not have access to this page. Ask an owner for access.
+FAIL
+rastrillo-budget/v1 ran 1.054s
+FAIL amadan.net/oficina/equipo/internal/equipotest 1.116s
+FAIL
+```
+
+### User-facing strings
+
+No new `copy.go` entries or app-owned UI prose were added, so there are no new pending copy entries. Existing accepted/rejected tool copy and existing error codes are reused. New operational identifiers include `namespace.owner`, `namespace.launch`, `opening-provider`, `checks-v1`, `direct-cli`, `EQUIPO_BWRAP_PATH` and `EQUIPO_GO_MODULE_CACHE`. Test prompts, sentinels and fixture replies are test-only. README prose and UI assets are unchanged. No copy-review skill or server was invoked.
+
+### Concerns and remaining release work
+
+- No live provider gate was authorized or run. Provider-home fixtures contain only synthetic data and are removed with test scratch. There was no sign-in, enrolment, model-provider prompt, external forge write, push, merge or deployment.
+- The release manifest has no certified direct policies. Production construction keeps uncertified routes unavailable and rejects their launches. Task 11a still needs the direct connection-eligibility/schema cutover; the existing instance connection report rules still expect legacy Paseo fields for an available route. This task does not fabricate those fields. Task 11b remains responsible for live provider/native-tool/refresh certification.
+- The old Paseo end-to-end, preparation and service fixtures still compile, but they target the retired constructor/inspector path and are outside this task's required selector. They need conversion or retirement in Task 11a before the whole `make ci` gate can be claimed. No full-suite success is claimed here. Core authority, budget, evidence, recovery, direct adapter/relay and command-denial regressions are recorded above.
+- The new workflow-level lease-loss tests and retained namespace parent-death/direct-journal tests divide the crash coverage across boundaries. The fake CLI graph is not a live provider certification.
+
+The task remains on `plan-2b`. No agent or subagent was spawned, no other worktree was changed, and no `.claude/HANDOFF.md` was created. The controller performs the review and push.
diff --git a/internal/equipo/runner_events.go b/internal/equipo/runner_events.go
index 5becf1e3..13fd783e 100644
--- a/internal/equipo/runner_events.go
+++ b/internal/equipo/runner_events.go
@@ -80,10 +80,10 @@ func (e *Execution) IngestRunnerEvent(ctx context.Context, p RunnerPrincipal, ev
}
// Historical observations need current roster and runner authority, but a
// cancelled task must still accept corroborated completion accounting.
- return e.ingestEventAt(ctx, tx, a, value, event)
+ return e.ingestEventAt(ctx, tx, p, a, value, event)
})
}
-func (e *Execution) ingestEventAt(ctx context.Context, tx *gorm.DB, a runnerAssignment, value Assignment, event runnerproto.Event) error {
+func (e *Execution) ingestEventAt(ctx context.Context, tx *gorm.DB, p RunnerPrincipal, a runnerAssignment, value Assignment, event runnerproto.Event) error {
key, hash := event.DedupKey(), event.ContentHash()
var alias runnerEventID
err := tx.First(&alias, "runner_id=? AND event_id=?", a.RunnerID, event.ID).Error
@@ -107,6 +107,21 @@ func (e *Execution) ingestEventAt(ctx context.Context, tx *gorm.DB, a runnerAssi
if !errors.Is(err, gorm.ErrRecordNotFound) {
return storeError(err)
}
+ if event.Kind == "namespace.launch" || event.Kind == "namespace.owner" {
+ if _, err = e.assignmentCurrent(ctx, tx, p, a); err != nil {
+ return err
+ }
+ if a.State != "claimed" {
+ return ErrForbidden
+ }
+ if a.Kind == "step" {
+ if err = e.Core.ValidateHandle(ctx, event.Scope, event.Handle); err != nil {
+ return err
+ }
+ } else if !e.store.runnerClock.Now().Before(a.LeaseDeadline) {
+ return ErrForbidden
+ }
+ }
if e.validators.Events == nil {
return ErrUnavailable
}
diff --git a/internal/equipo/runner_report_validation.go b/internal/equipo/runner_report_validation.go
index 346e3e85..d55ada38 100644
--- a/internal/equipo/runner_report_validation.go
+++ b/internal/equipo/runner_report_validation.go
@@ -31,6 +31,13 @@ func instanceValidators() RunnerValidators {
if runnerproto.DecodeLimit(bytes.NewReader(q.Event), &event, runnerproto.MaxEventBytes+4096) != nil || event.Validate() != nil || event.AssignmentID != a.ID || event.Scope != q.Scope || event.Handle != q.Handle || event.ActionID != q.ActionID {
return ErrInvalid
}
+ if event.Kind == "namespace.launch" {
+ var n runnerproto.NamespaceLaunch
+ owner := runnerproto.EventHash([]any{q.Scope, q.Handle.Attempt, q.Handle.Fence, q.Handle.Runner})
+ if json.Unmarshal(event.Payload, &n) != nil || !n.Valid(owner) || event.AgentID != n.AttemptKey || event.SessionID != n.ID {
+ return ErrInvalid
+ }
+ }
return nil
},
Question: func(ctx context.Context, a Assignment, q RunnerRequest) error {
@@ -90,23 +97,7 @@ func instanceValidators() RunnerValidators {
}
return team.Receipt{ID: event.TurnID, Outcome: outcome, Provider: a.Selection.Provider, Model: a.Selection.Model, Usage: usage}, nil
},
- Containment: func(_ context.Context, a Assignment, q RunnerRequest) error {
- var p runnerproto.ContainmentProof
- if a.ID != q.AssignmentID || json.Unmarshal(q.Proof, &p) != nil || !p.Empty || p.Scope != q.Scope || p.Handle != q.Handle || p.Owner.Attempt != q.Handle.Attempt || p.Owner.Fence != q.Handle.Fence || p.Inventory.BootID == "" || p.Inventory.CheckedAt.IsZero() || !p.Inventory.CoverageKnown || len(p.Inventory.Processes) != 0 || len(p.Inventory.TerminalIDs) != 0 {
- return ErrInvalid
- }
- marker := runnerproto.EventHash([]any{q.Scope, q.Handle.Attempt, q.Handle.Fence, q.Handle.Runner})
- if a.Kind == "prepare" {
- marker = a.ID
- }
- if p.Owner.Marker != marker || (a.Kind == "prepare" && !p.Owner.LocalOnly) {
- return ErrForbidden
- }
- if !p.Owner.LocalOnly && (p.Owner.Workspace.ServerID == "" || p.Owner.Workspace.WorkspaceID == "") {
- return ErrInvalid
- }
- return nil
- },
+ Containment: validateNamespaceContainment,
}
}
@@ -189,3 +180,51 @@ func (s *Store) supervisedExecutorEvidence(ctx context.Context, raw *sql.Tx, sco
func executorReportIsolation(have, need team.IsolationSnapshot) bool {
return team.IsolationContains(have, need)
}
+
+func validateNamespaceContainment(ctx context.Context, a Assignment, q RunnerRequest) error {
+ var p runnerproto.ContainmentProof
+ if a.ID != q.AssignmentID || json.Unmarshal(q.Proof, &p) != nil || p.Version != 2 || p.Scope != q.Scope || p.Handle != q.Handle || p.CheckedAt.IsZero() {
+ return ErrInvalid
+ }
+ tx, ok := ctx.Value(runnerTxKey{}).(*gorm.DB)
+ if !ok {
+ return ErrUnavailable
+ }
+ var rows []runnerEvent
+ if err := tx.Where("assignment_id=? AND kind IN ?", a.ID, []string{"namespace.launch", "namespace.owner"}).Find(&rows).Error; err != nil {
+ return storeError(err)
+ }
+ owner := runnerproto.EventHash([]any{q.Scope, q.Handle.Attempt, q.Handle.Fence, q.Handle.Runner})
+ launches := map[string]runnerproto.NamespaceLaunch{}
+ for _, row := range rows {
+ var e runnerproto.Event
+ if json.Unmarshal([]byte(row.Body), &e) != nil || e.Scope != q.Scope || e.Handle != q.Handle {
+ return ErrForbidden
+ }
+ if e.Kind == "namespace.owner" {
+ if e.AgentID != owner || e.SessionID != owner {
+ return ErrForbidden
+ }
+ continue
+ }
+ var n runnerproto.NamespaceLaunch
+ if json.Unmarshal(e.Payload, &n) != nil || !n.Valid(owner) || e.AgentID != n.AttemptKey || e.SessionID != n.ID {
+ return ErrForbidden
+ }
+ if _, duplicate := launches[n.ID]; duplicate {
+ return ErrConflict
+ }
+ launches[n.ID] = n
+ }
+ if len(launches) != len(p.Namespaces) {
+ return ErrForbidden
+ }
+ for _, exit := range p.Namespaces {
+ n, ok := launches[exit.ID]
+ if !ok || !n.Matches(exit) {
+ return ErrForbidden
+ }
+ delete(launches, exit.ID)
+ }
+ return nil
+}
diff --git a/internal/equipotest/direct_containment_test.go b/internal/equipotest/direct_containment_test.go
new file mode 100644
index 00000000..06c77a4d
--- /dev/null
+++ b/internal/equipotest/direct_containment_test.go
@@ -0,0 +1,112 @@
+package equipotest
+
+import (
+ "encoding/json"
+ "strings"
+ "testing"
+ "time"
+
+ "amadan.net/oficina/equipo/internal/runnerproto"
+)
+
+func TestDirectContainmentReportBinding(t *testing.T) {
+ for _, change := range []string{"valid", "unstarted", "no-launch", "missing-namespace", "wrong-attempt", "wrong-fence", "wrong-manifest", "wrong-init", "wrong-boot", "wrong-namespace", "empty-flag", "inventory-only", "launch-no-manifest", "launch-no-namespace", "launch-no-policy", "launch-wrong-owner"} {
+ t.Run(change, func(t *testing.T) {
+ f := runnerFixtureNew(t, true, true)
+ // Launch evidence uses migration 0015's tables, without a direct-launch table.
+ if scalar(t, f.d, "SELECT count(*) FROM sqlite_master WHERE name='runner_namespace_launches'") != 0 {
+ t.Fatal("unexpected launch table")
+ }
+ key := runnerproto.EventHash([]any{f.claim.Scope, f.claim.Handle.Attempt, f.claim.Handle.Fence, f.claim.Handle.Runner})
+ n := runnerproto.NamespaceLaunch{ID: strings.Repeat("a", 32), AttemptKey: key + "/model", OwnerKey: key, ManifestHash: strings.Repeat("b", 64), PolicyHash: strings.Repeat("c", 64), BootID: "boot", NamespaceID: "pid:[42]", HostPID: 42, StartTicks: 7}
+ switch change {
+ case "launch-no-manifest":
+ n.ManifestHash = ""
+ case "launch-no-namespace":
+ n.NamespaceID = ""
+ case "launch-no-policy":
+ n.PolicyHash = ""
+ case "launch-wrong-owner":
+ n.OwnerKey = "other"
+ }
+ e := fixtureEvent(f, "launch", 0)
+ e.Kind, e.Sequence, e.AgentID, e.SessionID = "namespace.launch", nil, n.AttemptKey, n.ID
+ e.Payload, _ = json.Marshal(n)
+ if strings.HasPrefix(change, "launch-") {
+ if f.s.IngestRunnerEvent(connectionContext, f.principal, e) == nil {
+ t.Fatal("invalid authenticated launch accepted")
+ }
+ return
+ }
+ if change == "inventory-only" {
+ e.Kind = "namespace.owner"
+ e.AgentID = key
+ e.SessionID = key
+ e.Payload = []byte(`{}`)
+ }
+ if change != "no-launch" && change != "unstarted" {
+ executionMust(t, f.s.IngestRunnerEvent(connectionContext, f.principal, e))
+ }
+ p := runnerproto.ContainmentProof{Version: 2, Scope: f.claim.Scope, Handle: f.claim.Handle, CheckedAt: time.Now().UTC(), Namespaces: []runnerproto.NamespaceExit{{ID: n.ID, AttemptKey: n.AttemptKey, ManifestHash: n.ManifestHash, BootID: n.BootID, NamespaceID: n.NamespaceID, HostPID: n.HostPID, StartTicks: n.StartTicks, ObservedAt: time.Now().UTC()}}}
+ switch change {
+ case "unstarted":
+ p.Namespaces = nil
+ case "missing-namespace":
+ p.Namespaces = nil
+ case "wrong-attempt":
+ p.Namespaces[0].AttemptKey += "other"
+ case "wrong-fence":
+ p.Handle.Fence++
+ case "wrong-manifest":
+ p.Namespaces[0].ManifestHash = strings.Repeat("d", 64)
+ case "wrong-init":
+ p.Namespaces[0].StartTicks++
+ case "wrong-boot":
+ p.Namespaces[0].BootID = "other"
+ case "wrong-namespace":
+ p.Namespaces[0].NamespaceID = "pid:[43]"
+ case "empty-flag":
+ p.Empty = true
+ p.Namespaces = nil
+ case "inventory-only":
+ p.Version = 0
+ p.Empty = true
+ p.Namespaces = nil
+ p.Owner = runnerproto.ProcessOwner{LocalOnly: true, Attempt: f.claim.Handle.Attempt, Fence: f.claim.Handle.Fence, Marker: key}
+ p.Inventory = runnerproto.ProcessInventory{CoverageKnown: true, BootID: "boot", CheckedAt: time.Now().UTC()}
+ }
+ q := f.request()
+ q.Proof, _ = json.Marshal(p)
+ _, err := f.x.Cleanup(connectionContext, f.claim.CleanupToken, "contained", q)
+ if (change == "valid" || change == "unstarted") && err != nil {
+ t.Fatalf("bound proof refused: %v", err)
+ }
+ if change != "valid" && change != "unstarted" && err == nil {
+ t.Fatal("unbound proof released capacity")
+ }
+ })
+ }
+}
+
+func TestDirectContainmentLaunchReplayAfterStop(t *testing.T) {
+ f := runnerFixtureNew(t, true, true)
+ key := runnerproto.EventHash([]any{f.claim.Scope, f.claim.Handle.Attempt, f.claim.Handle.Fence, f.claim.Handle.Runner})
+ n := runnerproto.NamespaceLaunch{ID: strings.Repeat("a", 32), AttemptKey: key + "/model", OwnerKey: key, ManifestHash: strings.Repeat("b", 64), PolicyHash: strings.Repeat("c", 64), BootID: "boot", NamespaceID: "pid:[42]", HostPID: 42, StartTicks: 7}
+ e := fixtureEvent(f, "launch", 0)
+ e.Kind = "namespace.launch"
+ e.Sequence = nil
+ e.AgentID = n.AttemptKey
+ e.SessionID = n.ID
+ e.Payload, _ = json.Marshal(n)
+ executionMust(t, f.s.IngestRunnerEvent(connectionContext, f.principal, e))
+ _, err := f.x.Mutate(connectionContext, f.principal, "stop", f.request())
+ executionMust(t, err)
+ executionMust(t, f.s.IngestRunnerEvent(connectionContext, f.principal, e))
+ n.ID = strings.Repeat("d", 32)
+ e.ID = "new-launch"
+ e.SessionID = n.ID
+ e.Payload, _ = json.Marshal(n)
+ if err = f.s.IngestRunnerEvent(connectionContext, f.principal, e); err == nil {
+ t.Fatal("new launch admitted after stop")
+ }
+}
diff --git a/internal/equipotest/preparation_integration_test.go b/internal/equipotest/preparation_integration_test.go
index 52947e84..130ce018 100644
--- a/internal/equipotest/preparation_integration_test.go
+++ b/internal/equipotest/preparation_integration_test.go
@@ -127,7 +127,7 @@ func runPreparationSupervisor(t *testing.T, crash bool) {
}
b, _ := json.Marshal(d)
return runnerproto.PreparedBug{CheckDefinition: b, CheckDefinitionHash: checks.Digest(b), BaselineTestSetHash: d.Baseline.Hash}, nil
- }}, client)
+ }})
executionMust(t, err)
token := strings.Repeat("A", 43)
@@ -144,7 +144,7 @@ func runPreparationSupervisor(t *testing.T, crash bool) {
// Fixture clocks are fixed; the runner's Linux clock needs live deadlines.
claim.LeaseDeadline = time.Now().Add(time.Minute)
claim.AttemptDeadline = time.Now().Add(10 * time.Minute)
- wf, err := runner.NewBugWorkflow(runner.BugWorkflowConfig{Workspaces: m, Client: client, Witness: w, Policy: func(context.Context, paseo.Selection) (paseo.ReadPolicy, error) { return policy, nil }, Executor: func(context.Context, runner.RunClaim, checks.Definition, checks.Reproduction, time.Time) (*checks.Executor, error) {
+ wf, err := runner.NewBugWorkflow(runner.BugWorkflowConfig{Workspaces: m, Witness: w, Policy: func(context.Context, paseo.Selection) (paseo.ReadPolicy, error) { return policy, nil }, Executor: func(context.Context, runner.RunClaim, checks.Definition, checks.Reproduction, time.Time) (*checks.Executor, error) {
return nil, paseo.ErrContract
}, Publisher: &forge.Publisher{}, StateDir: state, Executable: "/bin/false", InstanceID: "fixture"})
executionMust(t, err)
diff --git a/internal/equipotest/runner_flow_test.go b/internal/equipotest/runner_flow_test.go
index 3a2cd24c..f224ca09 100644
--- a/internal/equipotest/runner_flow_test.go
+++ b/internal/equipotest/runner_flow_test.go
@@ -159,7 +159,7 @@ func TestRunnerEndToEnd(t *testing.T) {
raw := flowJSON(d)
return runnerproto.PreparedBug{CheckDefinition: raw, CheckDefinitionHash: checks.Digest(raw), BaselineTestSetHash: d.Baseline.Hash}, nil
- }}, client)
+ }})
executionMust(t, err)
description := &flowDescription{}
pubroot := filepath.Join(root, "publish")
@@ -172,7 +172,7 @@ func TestRunnerEndToEnd(t *testing.T) {
return forge.Credential{Remote: "https://" + f.project.Repository, Agent: "test~person@example.test", Bearer: "fixture-only"}, nil
}, Description: description})
}
- workflow, err := runner.NewBugWorkflow(runner.BugWorkflowConfig{PublisherFor: publisherFor, Workspaces: manager, Client: client, Witness: w, Policy: func(context.Context, paseo.Selection) (paseo.ReadPolicy, error) { return policy, nil }, Executor: executor, StateDir: state, Executable: "/bin/false", InstanceID: "fixture", Copy: runner.ToolCopy{Accepted: "accepted", Rejected: "rejected"}})
+ workflow, err := runner.NewBugWorkflow(runner.BugWorkflowConfig{PublisherFor: publisherFor, Workspaces: manager, Witness: w, Policy: func(context.Context, paseo.Selection) (paseo.ReadPolicy, error) { return policy, nil }, Executor: executor, StateDir: state, Executable: "/bin/false", InstanceID: "fixture", Copy: runner.ToolCopy{Accepted: "accepted", Rejected: "rejected"}})
executionMust(t, err)
inspector, err := runner.NewLinuxProcessInspector("/proc", client, j)
executionMust(t, err)
diff --git a/internal/runner/budget_test.go b/internal/runner/budget_test.go
index faeba8b9..e2d4f589 100644
--- a/internal/runner/budget_test.go
+++ b/internal/runner/budget_test.go
@@ -1,9 +1,15 @@
package runner
import (
+ "amadan.net/oficina/equipo/internal/runner/containment"
"amadan.net/rastrillo/rastrillo/budget"
"os"
"testing"
)
-func TestMain(m *testing.M) { os.Exit(budget.Main(m)) }
+func TestMain(m *testing.M) {
+ if len(os.Args) > 1 && os.Args[1] == "__namespace" {
+ os.Exit(containment.NamespaceMain(os.Args[2:]))
+ }
+ os.Exit(budget.Main(m))
+}
diff --git a/internal/runner/capture.go b/internal/runner/capture.go
index 52211528..467cb7b4 100644
--- a/internal/runner/capture.go
+++ b/internal/runner/capture.go
@@ -142,6 +142,13 @@ func (f *captureFactory) Open(ctx context.Context, p provider.Process, l provide
if !ok || f.journal == nil {
return nil, runnerproto.ErrInvalid
}
+ f.journal.captureMu.RLock()
+ transferred := false
+ defer func() {
+ if !transferred {
+ f.journal.captureMu.RUnlock()
+ }
+ }()
contain := func() error {
cleanup, cancel := context.WithTimeout(context.WithoutCancel(ctx), 5*time.Second)
defer cancel()
@@ -164,6 +171,7 @@ func (f *captureFactory) Open(ctx context.Context, p provider.Process, l provide
if input == nil || stdout == nil || stderr == nil {
return nil, errors.Join(runnerproto.ErrInvalid, contain())
}
+ transferred = true
runCtx, cancel := context.WithCancel(ctx)
frames := make(chan provider.Frame)
done := make(chan error, 1)
@@ -266,6 +274,7 @@ func (f *captureFactory) Open(ctx context.Context, p provider.Process, l provide
stderr.Close()
close(frames)
failureMu.Lock()
+ f.journal.captureMu.RUnlock()
done <- failure
failureMu.Unlock()
close(done)
diff --git a/internal/runner/capture_test.go b/internal/runner/capture_test.go
index 9c497330..e47c8f0f 100644
--- a/internal/runner/capture_test.go
+++ b/internal/runner/capture_test.go
@@ -444,6 +444,8 @@ func TestDirectInterruptedLiveCapture(t *testing.T) {
mustJournal(t, err)
_, err = j.db.Exec("INSERT INTO journal_answers VALUES('answer','hash','pending')")
mustJournal(t, err)
+ _, err = j.db.Exec("INSERT INTO direct_answer_scopes VALUES('answer',?,?)", s.AttemptKey, "turn")
+ mustJournal(t, err)
cancel()
<-cap.Done
var state string
diff --git a/internal/runner/checks/budget_test.go b/internal/runner/checks/budget_test.go
index 3c5553b9..1b730e45 100644
--- a/internal/runner/checks/budget_test.go
+++ b/internal/runner/checks/budget_test.go
@@ -1,9 +1,15 @@
package checks
import (
+ "amadan.net/oficina/equipo/internal/runner/containment"
"amadan.net/rastrillo/rastrillo/budget"
"os"
"testing"
)
-func TestMain(m *testing.M) { os.Exit(budget.Main(m)) }
+func TestMain(m *testing.M) {
+ if len(os.Args) > 1 && os.Args[1] == "__namespace" {
+ os.Exit(containment.NamespaceMain(os.Args[2:]))
+ }
+ os.Exit(budget.Main(m))
+}
diff --git a/internal/runner/checks/containment_cleanup_test.go b/internal/runner/checks/containment_cleanup_test.go
new file mode 100644
index 00000000..09616ff8
--- /dev/null
+++ b/internal/runner/checks/containment_cleanup_test.go
@@ -0,0 +1,28 @@
+package checks
+
+import (
+ "context"
+ "io"
+ "os"
+ "testing"
+
+ "amadan.net/oficina/equipo/internal/runner/paseo"
+)
+
+type unprovenSandbox struct{}
+
+func (unprovenSandbox) Run(context.Context, Command, string, paseo.ReadPolicy, io.Writer, io.Writer) (int, error) {
+ return -1, paseo.ErrUncertain
+}
+func (unprovenSandbox) Contained(string) bool { return false }
+
+func TestCheckNamespaceRetainsScratchWithoutProof(t *testing.T) {
+ f := newFixture(t)
+ f.e.sandbox = unprovenSandbox{}
+ work, cleanup, err := f.e.scratch(context.Background(), baseID)
+ must(t, err)
+ cleanup()
+ if _, err = os.Stat(work); err != nil {
+ t.Fatal("removed checkout without containment proof")
+ }
+}
diff --git a/internal/runner/checks/containment_test.go b/internal/runner/checks/containment_test.go
new file mode 100644
index 00000000..d9ce08d1
--- /dev/null
+++ b/internal/runner/checks/containment_test.go
@@ -0,0 +1,205 @@
+package checks_test
+
+import (
+ "bytes"
+ "context"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "strings"
+ "testing"
+
+ "amadan.net/oficina/equipo/internal/runner"
+ "amadan.net/oficina/equipo/internal/runner/checks"
+ "amadan.net/oficina/equipo/internal/runner/containment"
+ "amadan.net/oficina/equipo/internal/runner/paseo"
+ "amadan.net/oficina/equipo/internal/runner/provider"
+ "amadan.net/oficina/equipo/internal/runner/workspace"
+)
+
+type checkHost struct {
+ provider.ProcessHost
+ launches []provider.Launch
+ args [][]string
+}
+
+func (h *checkHost) Start(ctx context.Context, l provider.Launch, argv []string) (provider.Process, error) {
+ h.launches = append(h.launches, l)
+ h.args = append(h.args, argv)
+ return h.ProcessHost.Start(ctx, l, argv)
+}
+
+func namespaceCheck(t *testing.T, cacheInScratch ...bool) (*checks.CodexSandbox, string, string, paseo.ReadPolicy, *checkHost) {
+ t.Helper()
+ root := t.TempDir()
+ if err := os.Chmod(root, 0700); err != nil {
+ t.Fatal(err)
+ }
+ scratch, work, mods := filepath.Join(root, "ns"), filepath.Join(root, "work"), filepath.Join(root, "modules")
+ for _, p := range []string{scratch, work, mods} {
+ if err := os.Mkdir(p, 0700); err != nil {
+ t.Fatal(err)
+ }
+ }
+ if len(cacheInScratch) > 0 && cacheInScratch[0] {
+ mods = scratch
+ }
+ binary, err := exec.LookPath("codex")
+ if err != nil {
+ t.Fatal(err)
+ }
+ goBin, err := exec.LookPath("go")
+ if err != nil {
+ t.Fatal(err)
+ }
+ goBin, err = filepath.EvalSymlinks(goBin)
+ if err != nil {
+ t.Fatal(err)
+ }
+ helper, err := os.Executable()
+ if err != nil {
+ t.Fatal(err)
+ }
+ m, err := containment.New(containment.Config{Binary: "/usr/bin/bwrap", RunnerBinary: helper, ScratchRoot: scratch})
+ if err != nil {
+ t.Fatal(err)
+ }
+ j, err := runner.OpenJournal(context.Background(), filepath.Join(root, "journal.db"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { j.Close() })
+ if _, err = j.ReconcileDirect(context.Background(), m); err != nil {
+ t.Fatal(err)
+ }
+ p := filepath.Join(root, "private")
+ protected := workspace.SecurityPaths{RunnerState: p, RunnerConfig: p, Journal: p, Bearer: p, Cleanup: p, ForgeCredential: p, PaseoHome: p, SSH: p, ProviderHomes: []string{p}}
+ host := &checkHost{ProcessHost: runner.NewDirectHost(j, m)}
+ s, err := checks.NewCodexSandbox(context.Background(), checks.SandboxConfig{Binary: binary, ScratchRoot: scratch, GoBinary: goBin, GoRoot: filepath.Dir(filepath.Dir(goBin)), Protected: protected, Host: host, RunnerBinary: helper, Bwrap: "/usr/bin/bwrap", ModuleCache: mods})
+ if err != nil {
+ t.Fatal(err)
+ }
+ return s, work, scratch, paseo.ReadPolicy{ConfigHash: "checks", DeniedPaths: []string{p}}, host
+}
+
+func TestCheckNamespaceContainment(t *testing.T) {
+ s, work, scratch, policy, _ := namespaceCheck(t)
+ var out, stderr bytes.Buffer
+ code, err := s.Run(context.Background(), checks.Command{Argv: []string{"/usr/bin/python3", "-c", `import os,time
+if os.fork()==0:
+ os.setsid()
+ time.sleep(1)
+ open('/workspace/escaped','w').write('bad')
+ os._exit(0)
+print('parent done',flush=True)`}, Dir: ".", TimeoutSeconds: 10}, work, policy, &out, &stderr)
+ if err != nil || code != 0 {
+ t.Fatalf("check: %d %v %s", code, err, &stderr)
+ }
+ if !strings.Contains(out.String(), "parent done") {
+ t.Fatal("command did not run")
+ }
+ if _, err := os.Stat(filepath.Join(work, "escaped")); !os.IsNotExist(err) {
+ t.Fatal("detached child escaped")
+ }
+ files, err := os.ReadDir(scratch)
+ if err != nil {
+ t.Fatal(err)
+ }
+ for _, f := range files {
+ if f.IsDir() && strings.HasPrefix(f.Name(), "attempt-") {
+ t.Fatal("attempt scratch survived containment")
+ }
+ }
+}
+
+func TestCheckCacheIsolation(t *testing.T) {
+ s, work, scratch, policy, tracker := namespaceCheck(t)
+ home, err := os.UserHomeDir()
+ if err != nil {
+ t.Fatal(err)
+ }
+ for i := 0; i < 2; i++ {
+ var out, stderr bytes.Buffer
+ code, err := s.Run(context.Background(), checks.Command{Argv: []string{"/usr/bin/python3", "-c", `import os
+assert not os.path.exists(os.environ['GOCACHE']+'/prior')
+open(os.environ['GOCACHE']+'/prior','w').write('owned')
+try:
+ open(os.environ['GOMODCACHE']+'/poison','w').write('bad')
+except OSError: pass
+else: raise Exception('module cache writable')
+assert not os.path.exists('` + filepath.Join(home, ".cache/go-build") + `')
+assert os.environ['GOCACHE'].startswith('/tmp/')
+assert os.environ['GOTMPDIR'].startswith('/tmp/')
+print('isolated')`}, Dir: ".", TimeoutSeconds: 10}, work, policy, &out, &stderr)
+ if err != nil || code != 0 || !strings.Contains(out.String(), "isolated") {
+ t.Fatalf("cache check %d: %d %v %s %s", i, code, err, &out, &stderr)
+ }
+ }
+ if len(tracker.launches) != 2 || tracker.launches[0].AttemptKey == tracker.launches[1].AttemptKey {
+ t.Fatal("checks shared a namespace identity")
+ }
+ for i, launch := range tracker.launches {
+ args := strings.Join(tracker.args[i], " ")
+ if !strings.Contains(args, `"/opt/go-mod"="read"`) {
+ t.Fatal("module-cache inner write protection missing")
+ }
+ if !strings.Contains(args, `"`+filepath.Join(home, ".cache/go-build")+`"="deny"`) {
+ t.Fatal("host build cache exclusion missing")
+ }
+ for _, mount := range launch.Policy.Mounts {
+ if mount.Source == filepath.Join(home, ".cache/go-build") {
+ t.Fatal("host build cache mounted")
+ }
+ if mount.Target == "/opt/go-mod" && (!mount.ReadOnly || mount.Source != filepath.Join(filepath.Dir(work), "modules")) {
+ t.Fatal("module cache mount changed")
+ }
+ }
+ }
+ files, err := os.ReadDir(scratch)
+ if err != nil {
+ t.Fatal(err)
+ }
+ for _, f := range files {
+ if f.IsDir() && strings.HasPrefix(f.Name(), "attempt-") {
+ t.Fatal("check cache left behind")
+ }
+ }
+}
+
+func TestCheckNamespaceDeniedMountAliases(t *testing.T) {
+ s, work, _, policy, _ := namespaceCheck(t)
+ secret := filepath.Join(filepath.Dir(work), "modules", "private")
+ if err := os.WriteFile(secret, []byte("denied-sentinel"), 0600); err != nil {
+ t.Fatal(err)
+ }
+ policy.DeniedPaths = append(policy.DeniedPaths, secret)
+ var out, stderr bytes.Buffer
+ code, err := s.Run(context.Background(), checks.Command{Argv: []string{"/usr/bin/cat", "/opt/go-mod/private"}, Dir: ".", TimeoutSeconds: 10}, work, policy, &out, &stderr)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if code == 0 || strings.Contains(out.String(), "denied-sentinel") {
+ t.Fatal("module mount alias bypassed denied path")
+ }
+}
+
+func TestCheckCacheRejectsBroadHome(t *testing.T) {
+ home, err := os.UserHomeDir()
+ if err != nil {
+ t.Fatal(err)
+ }
+ for _, root := range []string{home, "/home", "/"} {
+ _, err = provider.BuildCheckPolicy(provider.CheckPolicyInputs{Workspace: t.TempDir(), Binary: "/usr/bin/true", RunnerBinary: "/usr/bin/true", Bwrap: "/usr/bin/bwrap", GoRoot: t.TempDir(), ModuleCache: root, Argv: []string{"/opt/codex"}})
+ if err == nil {
+ t.Fatalf("broad home accepted as module cache: %s", root)
+ }
+ }
+}
+
+func TestCheckCacheRejectsNamespaceScratch(t *testing.T) {
+ s, work, _, policy, _ := namespaceCheck(t, true)
+ var out, stderr bytes.Buffer
+ if _, err := s.Run(context.Background(), checks.Command{Argv: []string{"/usr/bin/true"}, Dir: ".", TimeoutSeconds: 10}, work, policy, &out, &stderr); err == nil {
+ t.Fatal("namespace scratch accepted as module cache")
+ }
+}
diff --git a/internal/runner/checks/executor.go b/internal/runner/checks/executor.go
index 7f8129c2..31c15e97 100644
--- a/internal/runner/checks/executor.go
+++ b/internal/runner/checks/executor.go
@@ -77,8 +77,13 @@ func (e *Executor) scratch(ctx context.Context, commit string) (string, func(),
if err != nil {
return "", nil, err
}
- cleanup := func() { _ = os.RemoveAll(root) }
work := filepath.Join(root, "work")
+ cleanup := func() {
+ if sandbox, ok := e.sandbox.(interface{ Contained(string) bool }); ok && !sandbox.Contained(work) {
+ return
+ }
+ _ = os.RemoveAll(root)
+ }
if err = e.cfg.Export(ctx, commit, work); err != nil {
cleanup()
return "", nil, err
diff --git a/internal/runner/checks/namespace.go b/internal/runner/checks/namespace.go
new file mode 100644
index 00000000..b20ec24c
--- /dev/null
+++ b/internal/runner/checks/namespace.go
@@ -0,0 +1,108 @@
+package checks
+
+import (
+ "context"
+ "crypto/rand"
+ "encoding/json"
+ "errors"
+ "io"
+ "path/filepath"
+ "sort"
+ "strings"
+ "time"
+
+ "amadan.net/oficina/equipo/internal/runner/paseo"
+ "amadan.net/oficina/equipo/internal/runner/provider"
+)
+
+func (s *CodexSandbox) runNamespace(ctx context.Context, c Command, work string, policy paseo.ReadPolicy, stdout, stderr io.Writer) (int, error) {
+ roots := map[string]string{":minimal": "read", "/workspace": "write", "/tmp": "write", "/opt/go": "read", "/opt/go-mod": "read", "/opt/codex": "read", "/home/runner": "deny", filepath.Join(s.home, ".cache/go-build"): "deny"}
+ for _, path := range append(append([]string(nil), s.protected...), policy.DeniedPaths...) {
+ roots[path] = "deny"
+ for _, mount := range []provider.Mount{{Source: work, Target: "/workspace"}, {Source: s.goRoot, Target: "/opt/go"}, {Source: s.direct.ModuleCache, Target: "/opt/go-mod"}} {
+ if within(mount.Source, path) {
+ rel, _ := filepath.Rel(mount.Source, path)
+ roots[filepath.Join(mount.Target, rel)] = "deny"
+ }
+ }
+ }
+ keys := make([]string, 0, len(roots))
+ for k := range roots {
+ keys = append(keys, k)
+ }
+ sort.Strings(keys)
+ entries := make([]string, 0, len(keys))
+ for _, k := range keys {
+ key, _ := json.Marshal(k)
+ v, _ := json.Marshal(roots[k])
+ entries = append(entries, string(key)+"="+string(v))
+ }
+ argv := []string{"/opt/codex", "sandbox", "-P", "equipo-checks", "-C", filepath.Join("/workspace", c.Dir), "-c", "permissions.equipo-checks.filesystem={" + strings.Join(entries, ",") + "}", "-c", "permissions.equipo-checks.network.enabled=false", "--"}
+ command := append([]string(nil), c.Argv...)
+ if command[0] == "go" {
+ command[0] = "/opt/go/bin/go"
+ }
+ argv = append(argv, command...)
+ env := map[string]string{"CODEX_HOME": "/home/runner", "GOCACHE": "/tmp/go-build", "GOTMPDIR": "/tmp/go-tmp", "GOMODCACHE": "/opt/go-mod", "GOROOT": "/opt/go", "GOTOOLCHAIN": "local", "GOWORK": "off", "GOENV": "off", "GOTELEMETRY": "off", "GOPROXY": "off", "GOSUMDB": "off", "CGO_ENABLED": "0", "XDG_CONFIG_HOME": "/tmp/xdg", "PATH": "/opt/go/bin:/usr/bin:/bin"}
+ p, err := provider.BuildCheckPolicy(provider.CheckPolicyInputs{Workspace: work, Binary: s.binary, RunnerBinary: s.direct.RunnerBinary, Bwrap: s.direct.Bwrap, GoRoot: s.goRoot, ModuleCache: s.direct.ModuleCache, Argv: argv, Env: env})
+ if err != nil {
+ return -1, err
+ }
+ ctx, cancel := context.WithTimeout(ctx, time.Duration(c.TimeoutSeconds)*time.Second)
+ defer cancel()
+ s.setContained(work, false)
+ proc, err := s.direct.Host.Start(ctx, provider.Launch{AttemptKey: "check-" + rand.Text(), Workspace: work, Policy: p}, argv)
+ if err != nil {
+ return -1, err
+ }
+ defer proc.Stdin().Close()
+ defer proc.Stdout().Close()
+ defer proc.Stderr().Close()
+ if err = proc.Stdin().Close(); err != nil {
+ return -1, err
+ }
+ done := make(chan error, 2)
+ go func() { _, err := io.Copy(stdout, proc.Stdout()); done <- err }()
+ go func() { _, err := io.Copy(stderr, proc.Stderr()); done <- err }()
+ exit, err := proc.Wait(ctx)
+ if err == nil {
+ s.setContained(work, true)
+ }
+ if err != nil {
+ cancel()
+ cleanup, stop := context.WithTimeout(context.WithoutCancel(ctx), 10*time.Second)
+ defer stop()
+ _, waitErr := proc.Wait(cleanup)
+ if waitErr == nil {
+ s.setContained(work, true)
+ }
+ if waitErr != nil {
+ proc.Stdout().Close()
+ proc.Stderr().Close()
+ }
+ err = errors.Join(err, waitErr)
+ }
+ err = errors.Join(err, <-done, <-done)
+ if err != nil {
+ return -1, err
+ }
+ return exit.Code, nil
+}
+
+func (s *CodexSandbox) Contained(work string) bool {
+ s.containMu.Lock()
+ defer s.containMu.Unlock()
+ return !s.uncontained[work]
+}
+func (s *CodexSandbox) setContained(work string, contained bool) {
+ s.containMu.Lock()
+ defer s.containMu.Unlock()
+ if s.uncontained == nil {
+ s.uncontained = map[string]bool{}
+ }
+ if contained {
+ delete(s.uncontained, work)
+ } else {
+ s.uncontained[work] = true
+ }
+}
diff --git a/internal/runner/checks/sandbox.go b/internal/runner/checks/sandbox.go
index 76a82580..1a2b12bf 100644
--- a/internal/runner/checks/sandbox.go
+++ b/internal/runner/checks/sandbox.go
@@ -12,10 +12,12 @@ import (
"runtime"
"sort"
"strings"
+ "sync"
"syscall"
"time"
"amadan.net/oficina/equipo/internal/runner/paseo"
+ "amadan.net/oficina/equipo/internal/runner/provider"
"amadan.net/oficina/equipo/internal/runner/workspace"
"amadan.net/oficina/equipo/internal/runnerproto"
)
@@ -24,11 +26,16 @@ const CodexVersion = "codex-cli 0.165.0"
const GoVersion = "go1.26.10"
type SandboxConfig struct {
- Binary, ScratchRoot string
- GoRoot, GoBinary string
- Protected workspace.SecurityPaths
+ Host provider.ProcessHost
+ RunnerBinary, Bwrap, ModuleCache string
+ Binary, ScratchRoot string
+ GoRoot, GoBinary string
+ Protected workspace.SecurityPaths
}
type CodexSandbox struct {
+ containMu sync.Mutex
+ uncontained map[string]bool
+ direct SandboxConfig
binary, version, scratch, home string
protected []string
goRoot, goBinary, goVersion string
@@ -91,7 +98,7 @@ func NewCodexSandbox(ctx context.Context, cfg SandboxConfig) (*CodexSandbox, err
if err != nil || strings.TrimSpace(string(b)) != "go version "+GoVersion+" "+runtime.GOOS+"/"+runtime.GOARCH {
return nil, paseo.ErrContract
}
- return &CodexSandbox{binary: binary, version: CodexVersion, scratch: cfg.ScratchRoot, home: home, protected: paths, goRoot: goRoot, goBinary: goBinary, goVersion: GoVersion}, nil
+ return &CodexSandbox{direct: cfg, binary: binary, version: CodexVersion, scratch: cfg.ScratchRoot, home: home, protected: paths, goRoot: goRoot, goBinary: goBinary, goVersion: GoVersion}, nil
}
func canonicalPath(path string) (string, error) {
if !filepath.IsAbs(path) || filepath.Clean(path) != path || strings.ContainsAny(path, "*?[\x00") {
@@ -137,6 +144,9 @@ func (s *CodexSandbox) Run(ctx context.Context, c Command, work string, policy p
denies[p] = true
denies[r] = true
}
+ if s.direct.Host != nil {
+ return s.runNamespace(ctx, c, work, policy, stdout, stderr)
+ }
control, err := os.MkdirTemp(s.scratch, "sandbox-")
if err != nil {
return -1, err
diff --git a/internal/runner/config.go b/internal/runner/config.go
index e5c85bc8..370cef20 100644
--- a/internal/runner/config.go
+++ b/internal/runner/config.go
@@ -17,6 +17,7 @@ import (
)
type Config struct {
+ BwrapPath, ModuleCache string
ClaudePath string
Report func(string)
Origin, StateDir, PaseoHome, NodePath, BridgePath, AmadanCredentialPath, AccountBindingsPath, CodexPath string
@@ -26,7 +27,7 @@ type Config struct {
}
func LoadConfig(getenv func(string) string) (Config, error) {
- c := Config{ClaudePath: getenv("EQUIPO_CLAUDE_PATH"), Origin: getenv("EQUIPO_ORIGIN"), StateDir: getenv("EQUIPO_RUNNER_STATE_DIR"), PaseoHome: getenv("EQUIPO_PASEO_HOME"), NodePath: getenv("EQUIPO_NODE_PATH"), BridgePath: getenv("EQUIPO_BRIDGE_PATH"), AmadanCredentialPath: getenv("EQUIPO_AMADAN_CREDENTIAL_PATH"), AccountBindingsPath: getenv("EQUIPO_ACCOUNT_BINDINGS_PATH"), CodexPath: getenv("EQUIPO_CODEX_PATH"), GoRoot: getenv("EQUIPO_GO_ROOT"), GoBinary: getenv("EQUIPO_GO_BINARY"), WorkspaceRoot: getenv("EQUIPO_WORKSPACE_ROOT"), ScratchRoot: getenv("EQUIPO_SCRATCH_ROOT"), GitPath: getenv("EQUIPO_GIT_PATH"), Executable: getenv("EQUIPO_RUNNER_EXECUTABLE"), PaseoEndpoint: getenv("EQUIPO_PASEO_ENDPOINT"), PaseoServerID: getenv("EQUIPO_PASEO_SERVER_ID"), InstanceID: getenv("EQUIPO_INSTANCE_ID")}
+ c := Config{BwrapPath: getenv("EQUIPO_BWRAP_PATH"), ModuleCache: getenv("EQUIPO_GO_MODULE_CACHE"), ClaudePath: getenv("EQUIPO_CLAUDE_PATH"), Origin: getenv("EQUIPO_ORIGIN"), StateDir: getenv("EQUIPO_RUNNER_STATE_DIR"), PaseoHome: getenv("EQUIPO_PASEO_HOME"), NodePath: getenv("EQUIPO_NODE_PATH"), BridgePath: getenv("EQUIPO_BRIDGE_PATH"), AmadanCredentialPath: getenv("EQUIPO_AMADAN_CREDENTIAL_PATH"), AccountBindingsPath: getenv("EQUIPO_ACCOUNT_BINDINGS_PATH"), CodexPath: getenv("EQUIPO_CODEX_PATH"), GoRoot: getenv("EQUIPO_GO_ROOT"), GoBinary: getenv("EQUIPO_GO_BINARY"), WorkspaceRoot: getenv("EQUIPO_WORKSPACE_ROOT"), ScratchRoot: getenv("EQUIPO_SCRATCH_ROOT"), GitPath: getenv("EQUIPO_GIT_PATH"), Executable: getenv("EQUIPO_RUNNER_EXECUTABLE"), PaseoEndpoint: getenv("EQUIPO_PASEO_ENDPOINT"), PaseoServerID: getenv("EQUIPO_PASEO_SERVER_ID"), InstanceID: getenv("EQUIPO_INSTANCE_ID")}
return c, c.validate()
}
func validOrigin(origin string) bool {
@@ -37,23 +38,25 @@ func (c Config) validate() error {
if !validOrigin(c.Origin) {
return configIssue("runner.config.origin", "EQUIPO_ORIGIN", paseo.ErrContract)
}
- for _, v := range []struct{ name, value string }{{"EQUIPO_INSTANCE_ID", c.InstanceID}, {"EQUIPO_PASEO_SERVER_ID", c.PaseoServerID}} {
+ for _, v := range []struct{ name, value string }{{"EQUIPO_INSTANCE_ID", c.InstanceID}} {
if v.value == "" {
return configIssue("runner.config.missing", v.name, paseo.ErrContract)
}
}
- host, port, err := net.SplitHostPort(c.PaseoEndpoint)
- if err != nil || host != "127.0.0.1" || port == "" {
- return configIssue("runner.config.endpoint", "EQUIPO_PASEO_ENDPOINT", paseo.ErrContract)
+ if c.PaseoEndpoint != "" {
+ host, port, err := net.SplitHostPort(c.PaseoEndpoint)
+ if err != nil || host != "127.0.0.1" || port == "" {
+ return configIssue("runner.config.endpoint", "EQUIPO_PASEO_ENDPOINT", paseo.ErrContract)
+ }
}
for _, v := range []struct{ name, path string }{
- {"EQUIPO_RUNNER_STATE_DIR", c.StateDir}, {"EQUIPO_PASEO_HOME", c.PaseoHome}, {"EQUIPO_NODE_PATH", c.NodePath}, {"EQUIPO_BRIDGE_PATH", c.BridgePath}, {"EQUIPO_AMADAN_CREDENTIAL_PATH", c.AmadanCredentialPath}, {"EQUIPO_ACCOUNT_BINDINGS_PATH", c.AccountBindingsPath}, {"EQUIPO_CODEX_PATH", c.CodexPath}, {"EQUIPO_GO_ROOT", c.GoRoot}, {"EQUIPO_GO_BINARY", c.GoBinary}, {"EQUIPO_WORKSPACE_ROOT", c.WorkspaceRoot}, {"EQUIPO_SCRATCH_ROOT", c.ScratchRoot}, {"EQUIPO_GIT_PATH", c.GitPath}, {"EQUIPO_RUNNER_EXECUTABLE", c.Executable},
+ {"EQUIPO_RUNNER_STATE_DIR", c.StateDir}, {"EQUIPO_AMADAN_CREDENTIAL_PATH", c.AmadanCredentialPath}, {"EQUIPO_ACCOUNT_BINDINGS_PATH", c.AccountBindingsPath}, {"EQUIPO_CODEX_PATH", c.CodexPath}, {"EQUIPO_GO_ROOT", c.GoRoot}, {"EQUIPO_GO_BINARY", c.GoBinary}, {"EQUIPO_WORKSPACE_ROOT", c.WorkspaceRoot}, {"EQUIPO_SCRATCH_ROOT", c.ScratchRoot}, {"EQUIPO_GIT_PATH", c.GitPath}, {"EQUIPO_RUNNER_EXECUTABLE", c.Executable},
} {
if !filepath.IsAbs(v.path) || filepath.Clean(v.path) != v.path || v.path == "/" {
return configIssue("runner.config.path", v.name, paseo.ErrContract)
}
}
- for _, v := range []struct{ name, path string }{{"EQUIPO_WORKSPACE_ROOT", c.WorkspaceRoot}, {"EQUIPO_SCRATCH_ROOT", c.ScratchRoot}, {"EQUIPO_PASEO_HOME", c.PaseoHome}} {
+ for _, v := range []struct{ name, path string }{{"EQUIPO_WORKSPACE_ROOT", c.WorkspaceRoot}, {"EQUIPO_SCRATCH_ROOT", c.ScratchRoot}} {
if containsPath(c.StateDir, v.path) || containsPath(v.path, c.StateDir) {
return configIssue("runner.config.overlap", v.name, paseo.ErrPolicy)
}
@@ -132,3 +135,17 @@ func (c Config) DirectBinding(b AccountBinding) (provider.Binding, error) {
}
return provider.Binding{ID: b.ID, Home: b.ProviderHome, AccountID: b.AccountID, Provider: b.Provider, Expected: b.ExpectedIdentity, RuntimeRoot: filepath.Join(c.ScratchRoot, "homes")}, nil
}
+
+func (c Config) bwrap() string {
+ if c.BwrapPath != "" {
+ return c.BwrapPath
+ }
+ return "/usr/bin/bwrap"
+}
+func (c Config) moduleCache() string {
+ if c.ModuleCache != "" {
+ return c.ModuleCache
+ }
+ home, _ := os.UserHomeDir()
+ return filepath.Join(home, "go/pkg/mod")
+}
diff --git a/internal/runner/connections.go b/internal/runner/connections.go
index f47e7f4e..2c409115 100644
--- a/internal/runner/connections.go
+++ b/internal/runner/connections.go
@@ -57,9 +57,13 @@ func (c Config) securityPaths(bs []AccountBinding) workspace.SecurityPaths {
home, _ := os.UserHomeDir()
homes := []string{filepath.Join(home, ".claude"), filepath.Join(home, ".codex")}
for _, b := range bs {
- homes = append(homes, b.CredentialHome)
+ if b.ProviderHome != "" {
+ homes = append(homes, b.ProviderHome)
+ } else {
+ homes = append(homes, b.CredentialHome)
+ }
}
- return workspace.SecurityPaths{RunnerState: c.StateDir, RunnerConfig: c.AccountBindingsPath, Journal: filepath.Join(c.StateDir, "journal.db"), Bearer: filepath.Join(c.StateDir, "credentials.json"), Cleanup: filepath.Join(c.StateDir, "credentials.json"), ForgeCredential: c.AmadanCredentialPath, PaseoHome: c.PaseoHome, SSH: filepath.Join(home, ".ssh"), ProviderHomes: homes}
+ return workspace.SecurityPaths{RunnerState: c.StateDir, RunnerConfig: c.AccountBindingsPath, Journal: filepath.Join(c.StateDir, "journal.db"), Bearer: filepath.Join(c.StateDir, "credentials.json"), Cleanup: filepath.Join(c.StateDir, "credentials.json"), ForgeCredential: c.AmadanCredentialPath, PaseoHome: filepath.Join(home, ".paseo"), SSH: filepath.Join(home, ".ssh"), ProviderHomes: homes}
}
func canonicalSecurityPath(path string) (string, error) {
tail := ""
diff --git a/internal/runner/containment/linux.go b/internal/runner/containment/linux.go
index 57f52aa1..5ce11142 100644
--- a/internal/runner/containment/linux.go
+++ b/internal/runner/containment/linux.go
@@ -161,6 +161,16 @@ func (m *Manager) StartRecorded(ctx context.Context, l provider.Launch, argv []s
return nil, e
}
}
+ if l.Policy.IsCheck() {
+ for _, name := range []string{"go-build", "go-tmp", "xdg/go/telemetry"} {
+ if e = os.MkdirAll(filepath.Join(dir, "tmp", name), 0700); e != nil {
+ return nil, e
+ }
+ }
+ if e = os.WriteFile(filepath.Join(dir, "tmp/xdg/go/telemetry/mode"), []byte("off\n"), 0600); e != nil {
+ return nil, e
+ }
+ }
mounts, e := m.mountPlan(l, dir)
if e != nil {
return nil, e
@@ -207,7 +217,7 @@ func (m *Manager) StartRecorded(ctx context.Context, l provider.Launch, argv []s
// 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) }()
+ go func() { m.lifecycle(ctx, r, argv, mounts, dir, result, record); close(finished) }()
cleanup = false
transferred = true
resultValue := <-result
@@ -228,10 +238,19 @@ type readiness struct {
}
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) {
+func (m *Manager) lifecycle(ctx context.Context, r Record, argv []string, mounts *mounts, dir string, result chan<- startResult, admit func(context.Context, Record) error) {
runtime.LockOSThread()
defer runtime.UnlockOSThread()
cleanupScratch := true
+ startedProcess := false
+ defer func() {
+ if !startedProcess {
+ proof := Proof{Record: r, Exit: provider.Exit{Code: -1, ObservedAt: time.Now().UTC()}, Verified: true}
+ if durableJSON(m.cfg.ScratchRoot, r.ID+".exit.json", proof) == nil {
+ m.finishRecovery(proof)
+ }
+ }
+ }()
defer func() {
if cleanupScratch {
os.RemoveAll(dir)
@@ -367,9 +386,13 @@ func (m *Manager) lifecycle(ctx context.Context, r Record, argv []string, mounts
result <- startResult{err: fmt.Errorf("%w: %s", s.err, diagnostic)}
return
}
+ r = s.record
p := &process{record: s.record, stdin: inputW, stdout: outputR, stderr: errorR, done: make(chan struct{}), fd: s.fd, egress: mounts.proxy}
// Identity is durable before the helper can fork the harness or read input.
- if e = m.persist(s.record); e == nil {
+ if e = m.persist(s.record); e == nil && admit != nil {
+ e = admit(ctx, s.record)
+ }
+ if e == nil {
_, e = releaseW.Write([]byte{1})
}
releaseW.Close()
@@ -386,6 +409,7 @@ func (m *Manager) lifecycle(ctx context.Context, r Record, argv []string, mounts
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}
+ startedProcess = true
result <- startResult{p: p}
lifecycleDone := make(chan struct{})
var proxyDone <-chan struct{}
diff --git a/internal/runner/containment/linux_test.go b/internal/runner/containment/linux_test.go
index 736c229f..9f2281b0 100644
--- a/internal/runner/containment/linux_test.go
+++ b/internal/runner/containment/linux_test.go
@@ -435,8 +435,16 @@ func TestNamespaceStartupFailure(t *testing.T) {
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)
+ if len(entries) != 2 {
+ t.Fatalf("startup intent or exit proof missing: %v", entries)
+ }
+ records, e := m.Records(context.Background())
+ if e != nil || len(records) != 1 {
+ t.Fatalf("startup records: %v %v", records, e)
+ }
+ proof, e := m.Recover(context.Background(), records[0])
+ if e != nil || !proof.Verified || proof.Exit.ObservedAt.IsZero() {
+ t.Fatalf("failed startup was not proven contained: %+v %v", proof, e)
}
}
func TestNamespaceIntentBeforeFork(t *testing.T) {
diff --git a/internal/runner/containment/mounts.go b/internal/runner/containment/mounts.go
index fed46660..6f8169bc 100644
--- a/internal/runner/containment/mounts.go
+++ b/internal/runner/containment/mounts.go
@@ -137,6 +137,9 @@ func (m *Manager) mountPlan(l provider.Launch, dir string) (_ *mounts, err error
}
targets := map[string]bool{}
for _, mount := range l.Policy.Mounts {
+ if l.Policy.IsCheck() && (overlaps(mount.Source, m.cfg.ScratchRoot) || mount.Source == "/" || within(home, mount.Source)) {
+ return nil, errMount
+ }
target := mount.Target
if !mount.ReadOnly || !cleanAbsolute(target) || targets[target] {
return nil, errMount
@@ -155,7 +158,7 @@ func (m *Manager) mountPlan(l provider.Launch, dir string) (_ *mounts, err error
}
}
// bind validates and retains the same descriptor; no second path lookup.
- if err = p.bind(mount.Source, target, true, false); err != nil {
+ if err = p.bind(mount.Source, target, true, l.Policy.IsCheck() && (target == "/opt/go" || target == "/opt/go-mod")); err != nil {
return nil, err
}
targets[target] = true
@@ -167,6 +170,14 @@ func (m *Manager) mountPlan(l provider.Launch, dir string) (_ *mounts, err error
}
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_NONESSENTIAL_TRAFFIC": true, "DISABLE_AUTOUPDATER": true}
+ if l.Policy.IsCheck() {
+ for k, v := range map[string]string{"GOCACHE": "/tmp/go-build", "GOTMPDIR": "/tmp/go-tmp", "GOMODCACHE": "/opt/go-mod", "GOROOT": "/opt/go", "GOTOOLCHAIN": "local", "GOWORK": "off", "GOENV": "off", "GOTELEMETRY": "off", "GOPROXY": "off", "GOSUMDB": "off", "CGO_ENABLED": "0", "XDG_CONFIG_HOME": "/tmp/xdg", "PATH": "/opt/go/bin:/usr/bin:/bin"} {
+ if l.Policy.Env[k] != v {
+ return nil, errMount
+ }
+ allowed[k] = true
+ }
+ }
keys := make([]string, 0, len(l.Policy.Env))
for k := range l.Policy.Env {
keys = append(keys, k)
diff --git a/internal/runner/containment/mounts_test.go b/internal/runner/containment/mounts_test.go
index dff253ae..30d490e8 100644
--- a/internal/runner/containment/mounts_test.go
+++ b/internal/runner/containment/mounts_test.go
@@ -45,7 +45,7 @@ func TestNamespacePinnedMountSwap(t *testing.T) {
t.Fatal(e)
}
result := make(chan startResult, 1)
- go m.lifecycle(context.Background(), r, []string{"/usr/bin/cat", "/workspace/marker"}, plan, dir, result)
+ go m.lifecycle(context.Background(), r, []string{"/usr/bin/cat", "/workspace/marker"}, plan, dir, result, nil)
started := <-result
if started.err != nil {
t.Fatal(started.err)
diff --git a/internal/runner/direct_cli_test.go b/internal/runner/direct_cli_test.go
new file mode 100644
index 00000000..f57918e1
--- /dev/null
+++ b/internal/runner/direct_cli_test.go
@@ -0,0 +1,188 @@
+package runner
+
+import (
+ "context"
+ "encoding/json"
+ "fmt"
+ "os"
+ "path/filepath"
+ "sync"
+ "testing"
+
+ "amadan.net/oficina/equipo/internal/runner/egress"
+ "amadan.net/oficina/equipo/internal/runner/provider"
+ "amadan.net/oficina/equipo/internal/runner/workspace"
+)
+
+type graphCLI struct {
+ j *Journal
+ host provider.ProcessHost
+ mu sync.Mutex
+ sessions map[string]*graphCLISession
+ proxies map[string]*ToolProxy
+}
+type graphCLISession struct {
+ session provider.Session
+ capture *provider.Capture
+ events chan provider.Event
+ turn string
+ mu sync.Mutex
+}
+
+func fakeDirectGraph(t *testing.T, j *Journal, host provider.ProcessHost, root, scratch, helper string) (map[string]provider.Launcher, func(context.Context, RunClaim, workspace.Workspace, *ToolProxy) (provider.Launch, func() error, error)) {
+ f := &graphCLI{j: j, host: host, sessions: map[string]*graphCLISession{}, proxies: map[string]*ToolProxy{}}
+ binary := filepath.Join(root, "fake-cli")
+ wfMust(t, os.WriteFile(binary, []byte(graphScript), 0700))
+ launch := func(ctx context.Context, c RunClaim, ws workspace.Workspace, proxy *ToolProxy) (provider.Launch, func() error, error) {
+ name := c.Assignment.Selection.Provider
+ home := filepath.Join(root, "fixture-account-"+c.Assignment.StepKey)
+ wfMust(t, os.Mkdir(home, 0700))
+ id := provider.Identity{AccountID: "account", HomeID: "fake-" + c.Assignment.StepKey, ProviderVersion: map[string]string{"claude": "2.1.312", "codex": "0.165.0"}[name]}
+ wfMust(t, os.WriteFile(filepath.Join(home, provider.IdentityFile), marshal(id), 0600))
+ credential := map[string]string{"claude": ".credentials.json", "codex": "auth.json"}[name]
+ wfMust(t, os.WriteFile(filepath.Join(home, credential), []byte(`{"fixture":true}`), 0600))
+ lease, err := provider.OpenAccount(ctx, provider.Binding{ID: "fake-binding", Home: home, Provider: name, AccountID: "account", Expected: id, RuntimeRoot: filepath.Join(scratch, "homes")})
+ if err != nil {
+ return provider.Launch{}, nil, err
+ }
+ err = lease.Preflight(ctx, func(context.Context, provider.Binding) (provider.Identity, error) { return id, nil })
+ if err != nil {
+ return provider.Launch{}, lease.Close, err
+ }
+ binding := lease.Binding()
+ network, err := egress.ProviderPolicy(provider.NetworkContract{Provider: name}, true)
+ if err != nil {
+ return provider.Launch{}, lease.Close, err
+ }
+ policyScratch, err := os.MkdirTemp(scratch, "policy-")
+ if err != nil {
+ return provider.Launch{}, lease.Close, err
+ }
+ policy, err := provider.BuildPolicy(binding, provider.PolicyInputs{Workspace: ws.Path, Scratch: policyScratch, ProviderVersion: id.ProviderVersion, LauncherVersion: "fixture", BwrapVersion: "0.11.0", Argv: []string{"/opt/fake-cli", name}, RuntimeFiles: []provider.Mount{{Source: binary, Target: "/opt/fake-cli", ReadOnly: true}, {Source: helper, Target: "/opt/helper", ReadOnly: true}, {Source: "/usr/bin/bwrap", Target: "/opt/bwrap", ReadOnly: true}}, EgressHosts: network.Hosts})
+ if err != nil {
+ return provider.Launch{}, lease.Close, err
+ }
+ l := provider.Launch{AttemptKey: attemptKey(c.Scope, c.Handle) + "/model", Workspace: ws.Path, Selection: provider.Selection{Provider: name, AccountID: "account", Family: c.Assignment.Selection.Family, Model: "model", ConnectionID: c.Assignment.Selection.ConnectionID}, Binding: binding, Policy: policy}
+ f.proxies[l.AttemptKey] = proxy
+ return l, lease.Close, nil
+ }
+ return map[string]provider.Launcher{"claude": f, "codex": f}, launch
+}
+func (f *graphCLI) Preflight(context.Context, provider.Binding, provider.Policy) (provider.Identity, error) {
+ return provider.Identity{}, nil
+}
+func (f *graphCLI) Open(ctx context.Context, l provider.Launch) (provider.Session, error) {
+ p, err := f.host.Start(ctx, l, []string{"/opt/fake-cli", l.Selection.Provider})
+ if err != nil {
+ return provider.Session{}, err
+ }
+ c, err := NewCaptureFactory(f.j).Open(ctx, p, l)
+ if err != nil {
+ return provider.Session{}, err
+ }
+ session := provider.Session{ID: l.AttemptKey + "-session", AttemptKey: l.AttemptKey, Provider: l.Selection.Provider, AccountID: l.Selection.AccountID, Model: l.Selection.Model, Family: l.Selection.Family}
+ if err = f.j.BindSession(ctx, session); err != nil {
+ return session, err
+ }
+ s := &graphCLISession{session: session, capture: c, events: make(chan provider.Event, 64)}
+ f.mu.Lock()
+ f.sessions[l.AttemptKey] = s
+ f.mu.Unlock()
+ go func() {
+ defer close(s.events)
+ for frame := range c.Frames {
+ s.mu.Lock()
+ turn := s.turn
+ s.mu.Unlock()
+ var payload struct {
+ Tool string
+ Arguments json.RawMessage
+ Final bool
+ }
+ if json.Unmarshal(frame.Bytes, &payload) != nil {
+ return
+ }
+ kind := "timeline"
+ if payload.Tool != "" {
+ if err := f.proxies[l.AttemptKey].submit(ctx, payload.Tool, payload.Tool, payload.Arguments); err != nil {
+ s.events <- provider.Event{SessionID: session.ID, TurnID: turn, Kind: "turn.failed"}
+ return
+ }
+ }
+ if payload.Tool == "ask_person" {
+ proxy := f.proxies[l.AttemptKey]
+ proxy.broker.mu.Lock()
+ bound := proxy.broker.binding
+ proxy.broker.mu.Unlock()
+ if _, err := bound.Ask(ctx, bound, payload.Tool, payload.Arguments); err != nil {
+ s.events <- provider.Event{SessionID: session.ID, TurnID: turn, Kind: "turn.failed"}
+ return
+ }
+ }
+ if payload.Final {
+ kind = "turn.completed"
+ }
+ e := provider.Event{Sequence: frame.Sequence, SessionID: session.ID, TurnID: turn, Kind: kind, Payload: frame.Bytes}
+ select {
+ case s.events <- e:
+ case <-ctx.Done():
+ return
+ }
+ }
+ }()
+ return session, nil
+}
+func (f *graphCLI) Events(_ context.Context, s provider.Session) (<-chan provider.Event, error) {
+ return f.sessions[s.AttemptKey].events, nil
+}
+func (f *graphCLI) StartTurn(ctx context.Context, session provider.Session, t provider.Turn) error {
+ s := f.sessions[session.AttemptKey]
+ s.mu.Lock()
+ s.turn = t.ID
+ s.mu.Unlock()
+ if err := f.j.BeginTurn(ctx, session, t); err != nil {
+ return err
+ }
+ var raw []byte
+ if session.Provider == "claude" {
+ raw = marshal(map[string]any{"type": "user", "session_id": session.ID, "message": map[string]string{"role": "user", "content": t.Prompt}})
+ } else {
+ raw = marshal(map[string]any{"method": "turn/start", "params": map[string]any{"threadId": session.ID, "input": []any{map[string]string{"type": "text", "text": t.Prompt}}}})
+ }
+ _, err := s.capture.Input.Write(append(raw, '\n'))
+ return err
+}
+func (f *graphCLI) Respond(context.Context, provider.Session, provider.Answer) error {
+ return fmt.Errorf("unexpected answer")
+}
+func (f *graphCLI) Interrupt(context.Context, provider.Session) error { return nil }
+func (f *graphCLI) Close(_ context.Context, s provider.Session) error {
+ c := f.sessions[s.AttemptKey].capture
+ c.Input.Close()
+ return <-c.Done
+}
+
+const graphScript = `#!/usr/bin/python3
+import sys,json,subprocess,os,base64
+def git(*args):
+ env={'PATH':'/usr/bin:/bin','GIT_CONFIG_NOSYSTEM':'1','GIT_CONFIG_GLOBAL':'/dev/null','GIT_AUTHOR_NAME':'fixture','GIT_AUTHOR_EMAIL':'fixture@example.test','GIT_COMMITTER_NAME':'fixture','GIT_COMMITTER_EMAIL':'fixture@example.test'}
+ return subprocess.check_output(['git',*args],env=env,stderr=subprocess.DEVNULL).decode().strip()
+for line in sys.stdin:
+ v=json.loads(line)
+ message=json.loads(v['message']['content'] if sys.argv[1]=='claude' else v['params']['input'][0]['text'])
+ step=message['Step']
+ if step=='reproduce':
+ print(json.dumps({'tool':'ask_person','arguments':{'question':'Which case?'}}),flush=True)
+ tool='submit_reproduction'
+ args={'expected_symptom':'wrong value','files':[{'path':'bug_test.go','bytes':base64.b64encode(b'package fixture\nimport "testing"\nfunc TestBug(t *testing.T){if Value()!=2 {t.Fatal("wrong value")}}\n').decode()}],'test_names':[{'package':'fixture','name':'TestBug'}]}
+ elif step=='implement':
+ open('value.go','w').write('package fixture\nfunc Value() int {return 2}\n')
+ git('add','.')
+ git('commit','-m','fix')
+ tool='submit_candidate';args={'commit':git('rev-parse','HEAD')}
+ else:
+ tool='submit_review';args={'candidate':message['candidate_commit'],'decision':'approve','findings':[]}
+ for i in range(200): print(json.dumps({'progress':i}),flush=True)
+ print(json.dumps({'tool':tool,'arguments':args}),flush=True)
+ print(json.dumps({'final':True,'usage':{'input_tokens':2,'output_tokens':3}}),flush=True)
+`
diff --git a/internal/runner/direct_graph_test.go b/internal/runner/direct_graph_test.go
new file mode 100644
index 00000000..de1c18fa
--- /dev/null
+++ b/internal/runner/direct_graph_test.go
@@ -0,0 +1,289 @@
+package runner
+
+import (
+ "amadan.net/oficina/equipo/internal/equipo/team"
+ "amadan.net/oficina/equipo/internal/runner/checks"
+ "amadan.net/oficina/equipo/internal/runner/containment"
+ "amadan.net/oficina/equipo/internal/runner/forge"
+ "amadan.net/oficina/equipo/internal/runner/paseo"
+ "amadan.net/oficina/equipo/internal/runner/provider"
+ "amadan.net/oficina/equipo/internal/runner/workspace"
+ "amadan.net/oficina/equipo/internal/runnerproto"
+ "context"
+ "database/sql"
+ "encoding/json"
+ "fmt"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "strings"
+ "testing"
+ "time"
+)
+
+func runDirectBugGraph(t *testing.T) {
+ ctx := context.Background()
+ root, err := os.MkdirTemp(os.Getenv("TMPDIR"), "e15-")
+ wfMust(t, err)
+ t.Cleanup(func() { os.RemoveAll(root) })
+ state := filepath.Join(root, "s")
+ private := filepath.Join(root, "p")
+ works := filepath.Join(root, "w")
+ scratch := filepath.Join(root, "c")
+ seed := filepath.Join(root, "seed")
+ for _, p := range []string{state, private, works, scratch, seed} {
+ wfMust(t, os.Mkdir(p, 0700))
+ }
+ j, err := OpenJournal(ctx, filepath.Join(state, "j.db"))
+ wfMust(t, err)
+ defer j.Close()
+ w, err := NewWitness(j)
+ wfMust(t, err)
+ policy := paseo.ReadPolicy{ConfigHash: strings.Repeat("a", 64), DeniedPaths: []string{state, private}}
+ helper, err := os.Executable()
+ wfMust(t, err)
+ namespaces, err := containment.New(containment.Config{Binary: "/usr/bin/bwrap", RunnerBinary: helper, ScratchRoot: scratch, ProviderNetworks: []provider.NetworkContract{{Provider: "claude"}, {Provider: "codex"}}})
+ wfMust(t, err)
+ _, err = j.ReconcileDirect(ctx, namespaces)
+ wfMust(t, err)
+ host := NewDirectHost(j, namespaces)
+ registry, launch := fakeDirectGraph(t, j, host, root, scratch, helper)
+ wfMust(t, os.WriteFile(filepath.Join(seed, "go.mod"), []byte("module fixture\n\ngo 1.26.0\n"), 0600))
+ wfMust(t, os.WriteFile(filepath.Join(seed, "value.go"), []byte("package fixture\nfunc Value() int {return 1}\n"), 0600))
+ wfMust(t, os.WriteFile(filepath.Join(seed, "old_test.go"), []byte("package fixture\nimport \"testing\"\nfunc TestOld(t *testing.T) {}\n"), 0600))
+ cmd := runnerproto.CheckCommand{Argv: []string{"go", "test", "-json", "-count=1", "./..."}, Dir: ".", Parser: "go-test-json", TimeoutSeconds: 120}
+ wfMust(t, os.Mkdir(filepath.Join(seed, ".equipo"), 0700))
+ wfMust(t, os.WriteFile(filepath.Join(seed, ".equipo/checks.json"), marshal(checks.Definition{Version: 1, Commands: []checks.Command{cmd}, Reproduction: cmd}), 0600))
+ wfGit(t, seed, "init", "-b", "main")
+ wfGit(t, seed, "add", ".")
+ wfGit(t, seed, "commit", "-m", "base")
+ base := wfGit(t, seed, "rev-parse", "HEAD")
+ remote := filepath.Join(root, "remote.git")
+ wfGit(t, root, "clone", "--bare", seed, remote)
+ protected := workspace.SecurityPaths{RunnerState: state, RunnerConfig: filepath.Join(state, "config"), Journal: filepath.Join(state, "j.db"), Bearer: filepath.Join(state, "bearer"), Cleanup: filepath.Join(state, "cleanup"), ForgeCredential: filepath.Join(state, "forge"), PaseoHome: filepath.Join(state, "paseo"), ProviderHomes: []string{filepath.Join(state, "provider")}, SSH: filepath.Join(state, "ssh")}
+ codex, err := exec.LookPath("codex")
+ wfMust(t, err)
+ goBinary, err := exec.LookPath("go")
+ wfMust(t, err)
+ goBinary, err = filepath.EvalSymlinks(goBinary)
+ wfMust(t, err)
+ goRoot := filepath.Dir(filepath.Dir(goBinary))
+ wfMust(t, os.Mkdir(filepath.Join(root, "modules"), 0700))
+ sandbox, err := checks.NewCodexSandbox(ctx, checks.SandboxConfig{Binary: codex, ScratchRoot: scratch, GoRoot: goRoot, GoBinary: filepath.Join(goRoot, "bin/go"), Protected: protected, Host: host, Bwrap: "/usr/bin/bwrap", RunnerBinary: helper, ModuleCache: filepath.Join(root, "modules")})
+ wfMust(t, err)
+ iso := team.IsolationSnapshot{Status: "confined", ObservedTuples: []team.IsolationTuple{{Provider: "claude", ProviderVersion: "2.1.312", PaseoVersion: "0.14.0", IsolationConfigHash: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"}}}
+ target := team.TargetBinding{Kind: team.TargetRepository, Repository: "amadan.net/test/fixture", DefaultRef: "main", Ref: "equipo/test", BaseRevision: base}
+ var manager *workspace.Manager
+ var pinned checks.Definition
+ var repo string
+ executor := func(ctx context.Context, c RunClaim, d checks.Definition, r checks.Reproduction, deadline time.Time) (*checks.Executor, error) {
+ if c.Handle.Attempt > 0 && !deadline.Equal(c.AttemptDeadline) {
+ return nil, fmt.Errorf("executor got lease snapshot instead of attempt deadline")
+ }
+ return checks.New(checks.Config{ScratchRoot: works, Scope: c.Scope, Handle: c.Handle, Deadline: deadline, Policy: policy, DefinitionHash: checks.Digest(marshal(d)), ReproductionHash: checks.Digest(marshal(r)), Reproduction: func(context.Context, string) (checks.Reproduction, error) { return r, nil }, Isolation: func(context.Context) (team.IsolationSnapshot, error) { return c.Brief.Selection.Isolation, nil }, ResolveCandidate: func(ctx context.Context, hash string) (team.GitCandidate, error) {
+ arts, err := apiArtifacts(ctx, w, c)
+ if err != nil {
+ return team.GitCandidate{}, err
+ }
+ for _, a := range arts {
+ var v team.GitCandidate
+ if a.Role == team.RoleCandidate && checks.CandidateHash(decodeCandidate(a.Payload)) == hash {
+ json.Unmarshal(a.Payload, &v)
+ return v, nil
+ }
+ }
+ return team.GitCandidate{}, paseo.ErrIdentity
+ }, Export: func(ctx context.Context, commit, dest string) error {
+ if commit == base {
+ return checks.ExportBase(ctx, repo, base, dest)
+ }
+ arts, err := apiArtifacts(ctx, w, c)
+ if err != nil {
+ return err
+ }
+ for _, a := range arts {
+ v := decodeCandidate(a.Payload)
+ if a.Role == team.RoleCandidate && v.Commit == commit {
+ return manager.ExportCandidate(ctx, v, dest)
+ }
+ }
+ return paseo.ErrIdentity
+ }}, sandbox)
+ }
+ manager, err = workspace.New(workspace.Config{Protected: protected, PrivateRoot: private, WorkspaceRoot: works, GitPath: "/usr/bin/git", Forge: localRead{remote}, Policy: func(context.Context, paseo.Selection) (paseo.ReadPolicy, error) { return policy, nil }, Definitions: func(ctx context.Context, tgt team.TargetBinding, repository string) (runnerproto.PreparedBug, error) {
+ repo = repository
+ d, err := checks.LoadBaseDefinition(ctx, repository, tgt.Repository, tgt.BaseRevision, scratch)
+ if err != nil {
+ t.Log("preparation callback", err)
+ return runnerproto.PreparedBug{}, err
+ }
+ e, err := executor(ctx, RunClaim{ClaimResponse: runnerproto.ClaimResponse{Brief: runnerproto.RunnerBrief{Selection: runnerproto.Selection{Isolation: iso}}}}, d, checks.Reproduction{}, time.Now().Add(2*time.Minute))
+ if err != nil {
+ t.Log("preparation callback", err)
+ return runnerproto.PreparedBug{}, err
+ }
+ d.Baseline, err = e.CaptureBaseline(ctx, d)
+ if err != nil {
+ t.Log("preparation callback", err)
+ return runnerproto.PreparedBug{}, err
+ }
+ pinned = d
+ raw := marshal(d)
+ return runnerproto.PreparedBug{CheckDefinition: raw, CheckDefinitionHash: checks.Digest(raw), BaselineTestSetHash: d.Baseline.Hash}, nil
+ }})
+ wfMust(t, err)
+ prepared, err := manager.Prepare(ctx, target)
+ wfMust(t, err)
+ clock := team.RealClock{}
+ auth := team.NewFakeAuthority(clock, 5*time.Second)
+ auth.Issue("grant", team.Grant{Account: "team", Operations: map[team.Operation]bool{team.OpProviderCall: true, team.OpForgePublish: true, team.OpJobContinue: true, team.OpAttemptContinue: true}})
+ api := &directCoreAPI{coreWorkflowAPI: &coreWorkflowAPI{t: t, w: w, assignments: map[string]runnerproto.Assignment{}}}
+ core, err := team.Open(ctx, filepath.Join(state, "core.db"), team.Options{Clock: clock, Authority: auth, ExecutorEvidence: w.ExecutorEvidence, Provenance: func(ctx context.Context, tx *sql.Tx, scope team.Scope, h team.Handle) (team.Provenance, error) {
+ p, err := w.Provenance(ctx, tx, scope, h)
+ if err == nil {
+ for _, a := range api.assignments {
+ if a.WorkspaceKey == fmt.Sprint(h.Attempt) {
+ p.Isolation = a.Selection.Isolation
+ p.ConnectionID = a.Selection.ConnectionID
+ }
+ }
+ }
+ return p, err
+ }, Adapters: map[team.Operation]team.Adapter{team.OpProviderCall: team.NewFakeProvider("claude", "model", nil), team.OpForgePublish: team.NewFakeForge()}})
+ wfMust(t, err)
+ defer core.Close()
+ api.core = core
+ _, err = core.Resume(ctx)
+ wfMust(t, err)
+ limits := team.Limits{Calls: 24, InputTokens: 200000, OutputTokens: 40000}
+ pol, err := team.RunnerPolicy("subscription", limits, team.Limits{Calls: 1, InputTokens: 32000, OutputTokens: 4000}, team.Rates{})
+ wfMust(t, err)
+ job, err := core.CreateJob(ctx, team.JobSpec{Account: "team", Requester: "person", GrantRef: "grant", Target: target, Evidence: team.EvidenceRequirement{Predicate: team.PredicateSoftwareFix, ExpectedSymptom: "wrong value", CheckDefinitionHash: prepared.CheckDefinitionHash, BaselineTestSetHash: prepared.BaselineTestSetHash, RequireBugFreeze: true}, Policy: pol, Steps: []team.StepSpec{{Key: "reproduce", Version: 1, Capability: team.CapReproduce}, {Key: "implement", Version: 1, Capability: team.CapImplement, DependsOn: []string{"reproduce"}}, {Key: "review", Version: 1, Capability: team.CapReview, DependsOn: []string{"implement"}}, {Key: "verify", Version: 1, Capability: team.CapVerify, DependsOn: []string{"review"}}, {Key: "publish", Version: 1, Capability: team.CapPublish, DependsOn: []string{"verify"}}}})
+ wfMust(t, err)
+ scope := team.Scope{Account: job.Account, Job: job.ID}
+
+ pubroot := filepath.Join(root, "pub")
+ policy.DeniedPaths = append(policy.DeniedPaths, pubroot)
+ gitSpy := filepath.Join(root, "publish-git")
+ wfMust(t, os.WriteFile(gitSpy, []byte("#!/bin/bash\nargs=()\nfor arg in \"$@\"; do\n if [[ \"$arg\" == https://amadan.net/test/fixture ]]; then args+=("+fmt.Sprintf("%q", remote)+"); else args+=(\"$arg\"); fi\ndone\nexec /usr/bin/git -c protocol.file.allow=always \"${args[@]}\"\n"), 0700))
+ status, err := core.Status(ctx)
+ wfMust(t, err)
+ publisher, err := forge.New(forge.Config{Root: pubroot, GitPath: gitSpy, Runner: "runner", Incarnation: status.Incarnation, Clock: time.Now, Authorize: w.PublicationAuthorization, Revalidate: func(ctx context.Context, a forge.Authorization) error {
+ return core.ValidateHandle(ctx, a.Ticket.Scope, a.Ticket.Handle)
+ }, Export: manager.ExportCandidate, Credential: func(context.Context, string) (forge.Credential, error) {
+ return forge.Credential{Remote: "https://amadan.net/test/fixture", Agent: "test~person@example.test", Bearer: "fixture-only"}, nil
+ }, Description: &workflowDescription{}})
+ wfMust(t, err)
+ workflow, err := NewBugWorkflow(BugWorkflowConfig{Publisher: publisher, Workspaces: manager, Launchers: registry, Namespaces: namespaces, Launch: launch, Witness: w, Policy: func(context.Context, paseo.Selection) (paseo.ReadPolicy, error) { return policy, nil }, Executor: executor, StateDir: state, Executable: "/bin/false", InstanceID: "instance", Copy: ToolCopy{Accepted: "accepted", Rejected: "rejected"}})
+ wfMust(t, err)
+ s, err := NewSupervisor(SupervisorConfig{Journal: j, Namespaces: namespaces, API: api, Workflow: workflow, CredentialsPath: filepath.Join(state, "credentials"), InstallCredentials: func(context.Context, runnerproto.CredentialRotation, string) error { return nil }})
+ wfMust(t, err)
+ wfMust(t, s.Recover(ctx))
+ api.beforeComplete = func() error {
+ select {
+ case <-s.leaseDone:
+ return nil
+ default:
+ return fmt.Errorf("completion while lease watchdog was still live")
+ }
+ }
+ for i, step := range []string{"reproduce", "implement", "review", "verify", "publish"} {
+ h, err := core.Claim(ctx, scope, step, "runner", fmt.Sprint(i+1))
+ wfMust(t, err)
+ sel := runnerproto.Selection{ConnectionID: step, Provider: "claude", Family: "claude", Model: "model", AccountID: "account", Isolation: iso}
+ if step == "review" || step == "verify" {
+ sel.Provider = "codex"
+ sel.Family = "gpt"
+
+ }
+ a := runnerproto.Assignment{ID: step, TaskID: "task", StepKey: step, WorkspaceKey: fmt.Sprint(h.Attempt), Scope: scope, Kind: "step", Selection: sel}
+ api.assignments[step] = a
+ arts, err := core.Artifacts(ctx, scope)
+ wfMust(t, err)
+ for i, art := range arts {
+ arts[i], err = core.Artifact(ctx, scope, art.ID)
+ wfMust(t, err)
+ }
+ wfMust(t, w.record(ctx, "artifacts", attemptKey(scope, h), arts))
+ hashes := []string{prepared.CheckDefinitionHash}
+ for _, art := range arts {
+ hashes = append(hashes, art.Hash)
+ }
+ claim := RunClaim{Assignment: a, ClaimResponse: runnerproto.ClaimResponse{Scope: scope, Handle: h, Brief: runnerproto.RunnerBrief{Target: target, Selection: sel, Policy: pol, CheckDefinition: marshal(pinned), ArtifactHashes: hashes}, AttemptDeadline: time.Now().Add(20 * time.Minute), LeaseDeadline: time.Now().Add(60 * time.Second)}}
+ if err = s.Run(ctx, claim); err != nil {
+ t.Fatalf("%s (%s): %v", step, s.states[attemptKey(scope, h)].FailurePhase, err)
+ }
+ }
+
+ entries, err := os.ReadDir(filepath.Join(state, "admissions"))
+ wfMust(t, err)
+ consumed := 0
+ for _, entry := range entries {
+ if strings.HasSuffix(entry.Name(), ".consumed") {
+ consumed++
+ }
+ }
+ if consumed != 4 {
+ t.Fatal("dispatch bypassed durable ticket consumption", consumed)
+ }
+ if api.admissions != 3 {
+ t.Fatal("model admission count", api.admissions)
+ }
+ if api.questions != 1 {
+ t.Fatal("ask_person produced duplicate questions", api.questions)
+ }
+ finished, err := core.GetJob(ctx, scope)
+ wfMust(t, err)
+ if finished.State != team.JobSucceeded {
+ t.Fatal("publication not concluded", finished.State)
+ }
+ attempts, err := core.Attempts(ctx, scope)
+ wfMust(t, err)
+ if len(attempts) != 5 {
+ t.Fatal("attempt count", len(attempts))
+ }
+ for _, a := range attempts {
+ if a.State != team.AttemptSucceeded || a.Containment != team.ContainmentContained {
+ t.Fatalf("unfinished %+v", a)
+ }
+ }
+}
+
+type directCoreAPI struct {
+ beforeComplete func() error
+ *coreWorkflowAPI
+ questions int
+}
+
+func (a *directCoreAPI) Call(ctx context.Context, op string, q runnerproto.RunnerRequest, out any) error {
+ if op == "complete" && a.beforeComplete != nil {
+ if err := a.beforeComplete(); err != nil {
+ return err
+ }
+ }
+ if op == "questions" {
+ a.questions++
+ }
+ if op == "answers" && a.question == nil {
+ return json.Unmarshal([]byte(`[]`), out)
+ }
+ if op == "events" {
+ var e Event
+ if runnerproto.DecodeLimit(strings.NewReader(string(q.Event)), &e, runnerproto.MaxEventBytes+4096) != nil {
+ return runnerproto.ErrInvalid
+ }
+ if e.Kind == "turn.completed" || e.Kind == "turn.failed" {
+ if err := a.w.Events(ctx, a.assignments[q.AssignmentID], q); err != nil {
+ return err
+ }
+ var payload struct {
+ Usage *team.Usage `json:"usage"`
+ }
+ if json.Unmarshal(e.Payload, &payload) != nil {
+ return runnerproto.ErrInvalid
+ }
+ return a.core.Record(ctx, q.Scope, q.ActionID, team.Receipt{ID: e.TurnID, Outcome: team.OutcomeSuccess, Usage: payload.Usage})
+ }
+ }
+ return a.coreWorkflowAPI.Call(ctx, op, q, out)
+}
diff --git a/internal/runner/direct_namespaces.go b/internal/runner/direct_namespaces.go
new file mode 100644
index 00000000..15558d45
--- /dev/null
+++ b/internal/runner/direct_namespaces.go
@@ -0,0 +1,156 @@
+package runner
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "time"
+
+ "amadan.net/oficina/equipo/internal/runner/containment"
+ "amadan.net/oficina/equipo/internal/runner/provider"
+ "amadan.net/oficina/equipo/internal/runnerproto"
+)
+
+type namespaceAdmissionKey struct{}
+type namespaceState struct {
+ Owner string
+ Record containment.Record
+ Proof *containment.Proof
+}
+
+func (s *Supervisor) namespaceContext(ctx context.Context, r *attemptState) context.Context {
+ owner := attemptKey(r.Claim.Scope, r.Claim.Handle)
+ return context.WithValue(ctx, namespaceAdmissionKey{}, func(ctx context.Context, record containment.Record) error {
+ if err := s.journal.saveState(ctx, "namespace", record.ID, namespaceState{Owner: owner, Record: record}); err != nil {
+ return err
+ }
+ if record.HostPID == 0 {
+ return nil
+ }
+ n := runnerproto.NamespaceLaunch{ID: record.ID, AttemptKey: record.AttemptKey, OwnerKey: owner, BootID: record.BootID, NamespaceID: record.NamespaceID, ManifestHash: record.ManifestHash, PolicyHash: record.PolicyHash, HostPID: record.HostPID, StartTicks: record.StartTicks}
+ return s.namespaceEvent(ctx, r, "namespace.launch", record.AttemptKey, record.ID, n)
+ })
+}
+
+func (s *Supervisor) namespaceEvent(ctx context.Context, r *attemptState, kind, agent, session string, payload any) error {
+ e := Event{Version: 1, ID: runnerproto.EventHash([]string{kind, agent, session}), TaskID: r.Claim.Assignment.TaskID, AssignmentID: r.Claim.Assignment.ID, Scope: r.Claim.Scope, Handle: r.Claim.Handle, ServerID: "direct", AgentID: agent, SessionID: session, Kind: kind, Payload: marshal(payload), SourceTime: time.Now().UTC(), Isolation: r.Claim.Assignment.Selection.Isolation}
+ var old []byte
+ if err := s.journal.db.QueryRowContext(ctx, "SELECT body FROM journal_events WHERE event_key=?", e.DedupKey()).Scan(&old); err == nil {
+ var saved Event
+ if json.Unmarshal(old, &saved) != nil {
+ return ErrJournal
+ }
+ e.SourceTime = saved.SourceTime
+ }
+ pump := EventPump{Journal: s.journal, Contain: func(context.Context) error { return provider.ErrContainment }}
+ if err := pump.Append(ctx, e, nil); err != nil {
+ return err
+ }
+ q := r.request(e.ID)
+ q.RequestID = e.ID
+ q.Event, _ = runnerproto.Marshal(e)
+ if err := s.api.Call(ctx, "events", q, nil); err != nil {
+ return err
+ }
+ return s.journal.Ack(ctx, e.ID)
+}
+
+func (s *Supervisor) cleanupDirect(ctx context.Context, r *attemptState) (ContainmentProof, error) {
+ proof := ContainmentProof{Version: 2, Scope: r.Claim.Scope, Handle: r.Claim.Handle, CheckedAt: time.Now().UTC()}
+ if r.Phase == "contained" && r.Proof != nil {
+ return *r.Proof, nil
+ }
+ if r.Rotation != nil {
+ return s.finishRotation(ctx, r)
+ }
+ if r.Phase == "verified" && r.Proof != nil {
+ return s.reportContainment(ctx, r)
+ }
+ if s.namespaces == nil {
+ return proof, provider.ErrContainment
+ }
+ s.mu.Lock()
+ proxy := s.activeProxy
+ s.mu.Unlock()
+ if proxy != nil {
+ if err := proxy.Close(); err != nil {
+ return proof, err
+ }
+ }
+ var states []namespaceState
+ if err := s.journal.readStates(ctx, "namespace", &states); err != nil {
+ return proof, err
+ }
+ var failures error
+ checkWorkspaces := map[string]bool{}
+ for _, n := range states {
+ if n.Owner != attemptKey(r.Claim.Scope, r.Claim.Handle) {
+ continue
+ }
+ p, err := s.namespaces.Stop(ctx, n.Record.ID)
+ if err != nil {
+ p, err = s.namespaces.Recover(ctx, n.Record)
+ }
+ if err != nil || !p.Verified {
+ failures = errors.Join(failures, provider.ErrContainment, err)
+ continue
+ }
+ if err = s.journal.validateDirectRecord(ctx, p.Record); err != nil {
+ failures = errors.Join(failures, err)
+ continue
+ }
+ n.Proof = &p
+ if err = s.journal.saveState(ctx, "namespace", n.Record.ID, n); err != nil {
+ failures = errors.Join(failures, err)
+ continue
+ }
+ if _, err = s.journal.db.ExecContext(ctx, "UPDATE direct_attempts SET contained=1 WHERE attempt=?", n.Record.AttemptKey); err != nil {
+ failures = errors.Join(failures, err)
+ continue
+ }
+ if s.workflow != nil {
+ var raw []byte
+ var launch provider.Launch
+ if err = s.journal.db.QueryRowContext(ctx, "SELECT launch FROM direct_attempts WHERE attempt=?", n.Record.AttemptKey).Scan(&raw); err != nil {
+ failures = errors.Join(failures, err)
+ continue
+ }
+ if json.Unmarshal(raw, &launch) != nil {
+ failures = errors.Join(failures, ErrJournal)
+ continue
+ }
+ if launch.Policy.IsCheck() {
+ checkWorkspaces[launch.Workspace] = true
+ }
+ }
+ if n.Record.HostPID != 0 {
+ proof.Namespaces = append(proof.Namespaces, runnerproto.NamespaceExit{ID: p.Record.ID, AttemptKey: p.Record.AttemptKey, BootID: p.Record.BootID, NamespaceID: p.Record.NamespaceID, ManifestHash: p.Record.ManifestHash, HostPID: p.Record.HostPID, StartTicks: p.Record.StartTicks, ExitCode: p.Exit.Code, Signal: p.Exit.Signal, ObservedAt: p.Exit.ObservedAt})
+ }
+ }
+ if failures != nil {
+ return proof, failures
+ }
+ for work := range checkWorkspaces {
+ if err := s.workflow.cfg.Workspaces.RemoveCheck(work); err != nil {
+ return proof, err
+ }
+ }
+ if s.activeRelease != nil {
+ if err := s.activeRelease(); err != nil {
+ return proof, err
+ }
+ s.activeRelease = nil
+ }
+ if s.workflow != nil && r.WorkspacePath != "" {
+ if err := s.workflow.cfg.Workspaces.Remove(ctx, r.Claim.Assignment, r.WorkspacePath); err != nil {
+ return proof, err
+ }
+ }
+ proof.CheckedAt = time.Now().UTC()
+ r.Proof = &proof
+ r.Phase = "verified"
+ if err := s.save(ctx, r); err != nil {
+ return proof, err
+ }
+ return s.reportContainment(ctx, r)
+}
diff --git a/internal/runner/direct_question_workflow_test.go b/internal/runner/direct_question_workflow_test.go
new file mode 100644
index 00000000..90cb3ae5
--- /dev/null
+++ b/internal/runner/direct_question_workflow_test.go
@@ -0,0 +1,81 @@
+package runner
+
+import (
+ "context"
+ "io"
+ "testing"
+
+ "amadan.net/oficina/equipo/internal/runner/provider"
+ "amadan.net/oficina/equipo/internal/runnerproto"
+)
+
+func TestDirectBugQuestionResolution(t *testing.T) {
+ for _, state := range []string{"pending", "invalid", "delivered"} {
+ t.Run(state, func(t *testing.T) {
+ s, r, _, order := cleanupFixture(t)
+ r.Claim.Assignment.TaskID = "task"
+ r.Session = provider.Session{AttemptKey: "attempt", ID: "session"}
+ q := runnerproto.Question{ID: "question", TaskID: "task", AssignmentID: r.Claim.Assignment.ID, Attempt: int64(r.Claim.Handle.Attempt), Fence: r.Claim.Handle.Fence, ServerID: "direct", AgentID: "attempt", SessionID: "session", PermissionID: "request"}
+ w, err := NewWitness(s.journal)
+ mustJournal(t, err)
+ mustJournal(t, w.record(context.Background(), "question", q.ID, q))
+ key := runnerproto.EventHash([]any{q.TaskID, q.Attempt, q.Fence, q.ServerID, q.AgentID, q.SessionID, q.PermissionID})
+ _, err = s.journal.db.Exec("INSERT INTO journal_answers VALUES(?,'hash',?)", key, state)
+ mustJournal(t, err)
+ mustJournal(t, s.resolveDeliveredQuestions(context.Background(), r))
+ want := 0
+ if state == "delivered" {
+ want = 1
+ }
+ if len(*order) != want {
+ t.Fatalf("question resolution trusted transport result instead of journal: %v", *order)
+ }
+ })
+ }
+}
+
+func TestDirectBugTerminalEOF(t *testing.T) {
+ for i := 0; i < 100; i++ {
+ notices := make(chan provider.Event, 1)
+ done := make(chan error, 1)
+ notices <- provider.Event{Kind: "turn.completed"}
+ done <- errDirectUncertain
+ e, err := nextDirectNotice(context.Background(), notices, done)
+ if err != nil || e.Kind != "turn.completed" {
+ t.Fatal("EOF replaced committed terminal event")
+ }
+ }
+}
+
+func TestDirectBugTerminalRequiresCommit(t *testing.T) {
+ for _, early := range []bool{false, true} {
+ t.Run(map[bool]string{false: "committed", true: "cancelled-before-commit"}[early], func(t *testing.T) {
+ j, l, session, p := directFixture(t, "codex")
+ reader, writer := io.Pipe()
+ p.out = reader
+ defer writer.Close()
+ ctx, cancel := context.WithCancel(context.Background())
+ defer cancel()
+ capture, err := NewCaptureFactory(j).Open(ctx, p, l)
+ mustJournal(t, err)
+ mustJournal(t, j.BeginTurn(ctx, session, directTurn()))
+ mustJournal(t, j.consumeTurn(ctx, session.AttemptKey, session.ID, "hello"))
+ if early {
+ cancel()
+ <-capture.Done
+ }
+ pump := EventPump{Journal: j, Contain: func(context.Context) error { return nil }}
+ template := journalEvent("completion", 1)
+ template.ActionID = 1
+ mustJournal(t, pump.AppendDirect(context.Background(), session, directComplete("turn"), template))
+ if !early {
+ cancel()
+ <-capture.Done
+ }
+ err = j.requireDirectCompletion(context.Background(), session, "turn")
+ if (err != nil) != early {
+ t.Fatalf("wrong terminal authority after cancellation: %v", err)
+ }
+ })
+ }
+}
diff --git a/internal/runner/direct_recovery.go b/internal/runner/direct_recovery.go
index 21049e62..886e6642 100644
--- a/internal/runner/direct_recovery.go
+++ b/internal/runner/direct_recovery.go
@@ -43,7 +43,15 @@ func (h *directHost) Start(ctx context.Context, l provider.Launch, args []string
if err := h.journal.AdmissionAllowed(ctx); err != nil {
return nil, err
}
- return h.manager.StartRecorded(ctx, l, args, func(ctx context.Context, r containment.Record) error { return h.journal.recordDirectLaunch(ctx, l, r) })
+ return h.manager.StartRecorded(ctx, l, args, func(ctx context.Context, r containment.Record) error {
+ if err := h.journal.recordDirectLaunch(ctx, l, r); err != nil {
+ return err
+ }
+ if observe, ok := ctx.Value(namespaceAdmissionKey{}).(func(context.Context, containment.Record) error); ok {
+ return observe(ctx, r)
+ }
+ return nil
+ })
}
func (j *Journal) recordDirectLaunch(ctx context.Context, l provider.Launch, r containment.Record) error {
if l.AttemptKey == "" || r.AttemptKey != l.AttemptKey || r.ID == "" || r.ManifestHash == "" || r.PolicyHash == "" || r.PolicyHash != l.Policy.Hash || l.Policy.ManifestHash == "" || !json.Valid(l.Policy.Manifest) {
@@ -182,6 +190,10 @@ func (j *Journal) BeginTurn(ctx context.Context, s provider.Session, t provider.
return err
}
func (j *Journal) RecoverDirect(ctx context.Context) ([]Recovery, error) {
+ if !j.captureMu.TryLock() {
+ return nil, errDirectUncertain
+ }
+ defer j.captureMu.Unlock()
tx, err := j.db.BeginTx(ctx, nil)
if err != nil {
return nil, j.storageFailure(ctx, err)
diff --git a/internal/runner/direct_runtime_test.go b/internal/runner/direct_runtime_test.go
new file mode 100644
index 00000000..37a77d63
--- /dev/null
+++ b/internal/runner/direct_runtime_test.go
@@ -0,0 +1,147 @@
+package runner
+
+import (
+ "context"
+ "crypto/sha256"
+ "encoding/hex"
+ "encoding/json"
+ "io"
+ "net/http"
+ "os"
+ "path/filepath"
+ "strings"
+ "testing"
+ "time"
+
+ "amadan.net/oficina/equipo/internal/runner/containment"
+ "amadan.net/oficina/equipo/internal/runner/provider"
+ "amadan.net/oficina/equipo/internal/runnerproto"
+)
+
+func directRuntimeFixture(t *testing.T) Config {
+ c := runtimeFixture(t)
+ c.NodePath, c.BridgePath, c.PaseoHome, c.PaseoEndpoint, c.PaseoServerID = "", "", "", "", ""
+ c.Executable, _ = os.Executable()
+ c.ClaudePath = c.CodexPath
+ c.ModuleCache = t.TempDir()
+ // No credential file or account lease is needed to open and wire the runtime.
+ b := AccountBinding{ID: "binding", LocalID: "local", Provider: "codex", Family: "gpt", Model: "model", AccountID: "account", ProviderHome: filepath.Join(t.TempDir(), "unopened"), Kind: "subscription", ExpectedIdentity: provider.Identity{AccountID: "account", HomeID: "home", ProviderVersion: "0.165.0"}}
+ mustJournal(t, os.WriteFile(c.AccountBindingsPath, marshal([]AccountBinding{b}), 0600))
+ return c
+}
+
+func TestDirectBugRuntime(t *testing.T) {
+ c := directRuntimeFixture(t)
+ r, err := openRuntime(context.Background(), c)
+ mustJournal(t, err)
+ defer r.Close()
+ mustJournal(t, r.wire(context.Background()))
+ if r.client != nil || r.inspector != nil || r.namespaces == nil || len(r.launchers) != 2 || r.service.Supervisor.namespaces != r.namespaces {
+ t.Fatal("runtime retained Paseo or inventory authority")
+ }
+ host, ok := r.host.(*directHost)
+ if !ok || host.journal != r.journal || host.manager != r.namespaces {
+ t.Fatal("namespace launches bypass durable host")
+ }
+ legacy := r.service.Supervisor.workflow.cfg
+ legacy.Launchers = nil
+ if _, err := NewBugWorkflow(legacy); err == nil {
+ t.Fatal("missing launcher registry authorized new workflow")
+ }
+}
+
+func TestDirectBugRuntimeRecoveryBeforeStart(t *testing.T) {
+ c := directRuntimeFixture(t)
+ mustJournal(t, os.Mkdir(c.ScratchRoot, 0700))
+ record := containment.Record{ID: strings.Repeat("a", 32), AttemptKey: "orphan"}
+ mustJournal(t, os.WriteFile(filepath.Join(c.ScratchRoot, record.ID+".json"), marshal(record), 0600))
+ if r, err := openRuntime(context.Background(), c); err == nil {
+ r.Close()
+ t.Fatal("admitted launchers before reconciling unknown namespace")
+ }
+}
+
+func TestDirectBugRuntimeClosesNamespaces(t *testing.T) {
+ s, r, m, host, l := directNamespaceFixture(t)
+ var manifest struct{ Argv []string }
+ mustJournal(t, json.Unmarshal(l.Policy.Manifest, &manifest))
+ p, err := host.Start(s.namespaceContext(context.Background(), r), l, manifest.Argv)
+ mustJournal(t, err)
+ t.Cleanup(func() {
+ m.Stop(context.Background(), p.ID())
+ p.Stdout().Close()
+ p.Stderr().Close()
+ p.Stdin().Close()
+ })
+ b := make([]byte, 6)
+ _, err = io.ReadFull(p.Stdout(), b)
+ mustJournal(t, err)
+ runtime := &Runtime{namespaces: m}
+ released := false
+ runtime.service = &Service{Supervisor: &Supervisor{activeRelease: func() error {
+ ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond)
+ defer cancel()
+ if _, err := p.Wait(ctx); err != nil {
+ return err
+ }
+ released = true
+ return nil
+ }}}
+ mustJournal(t, runtime.Close())
+ if !released {
+ t.Fatal("runtime shutdown retained account lease after containment")
+ }
+ ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond)
+ defer cancel()
+ if _, err = p.Wait(ctx); err != nil {
+ t.Fatal("runtime shutdown left namespace alive")
+ }
+}
+
+func TestDirectCancelRetainsCheckUntilEveryProof(t *testing.T) {
+ c := directRuntimeFixture(t)
+ runtime, err := openRuntime(context.Background(), c)
+ mustJournal(t, err)
+ defer runtime.Close()
+ mustJournal(t, runtime.wire(context.Background()))
+ s := runtime.service.Supervisor
+ _, r, _, _ := cleanupFixture(t)
+ r.Direct = true
+ r.Proof = nil
+ s.api = &supervisorAPI{order: new([]string)}
+ root, err := os.MkdirTemp(c.WorkspaceRoot, "checks-")
+ mustJournal(t, err)
+ work := filepath.Join(root, "work")
+ mustJournal(t, os.Mkdir(work, 0700))
+ raw := []byte(`{"Version":"checks-v1"}`)
+ hash := sha256.Sum256(raw)
+ l := provider.Launch{AttemptKey: "check-recorded", Workspace: work, Policy: provider.Policy{Manifest: raw, ManifestHash: hex.EncodeToString(hash[:]), Hash: strings.Repeat("c", 64)}}
+ record := containment.Record{ID: strings.Repeat("a", 32), AttemptKey: l.AttemptKey, BootID: "old-boot", ManifestHash: strings.Repeat("b", 64), PolicyHash: l.Policy.Hash}
+ mustJournal(t, s.journal.recordDirectLaunch(context.Background(), l, record))
+ owner := attemptKey(r.Claim.Scope, r.Claim.Handle)
+ mustJournal(t, s.journal.saveState(context.Background(), "namespace", record.ID, namespaceState{Owner: owner, Record: record}))
+ mustJournal(t, s.journal.saveState(context.Background(), "namespace", "zz-missing", namespaceState{Owner: owner, Record: containment.Record{ID: "missing", AttemptKey: "missing"}}))
+ if _, err = s.cleanup(context.Background(), r); err == nil {
+ t.Fatal("missing namespace proof accepted")
+ }
+ if _, err = os.Stat(work); err != nil {
+ t.Fatal("removed check checkout before every namespace was contained")
+ }
+}
+
+func TestDirectBugRuntimeRenewHeartbeat(t *testing.T) {
+ c := directRuntimeFixture(t)
+ r, err := openRuntime(context.Background(), c)
+ mustJournal(t, err)
+ defer r.Close()
+ r.lastReports = []runnerproto.ConnectionReport{{LocalID: "cached"}}
+ var paths []string
+ r.api.client.Transport = transportFunc(func(q *http.Request) (*http.Response, error) {
+ paths = append(paths, q.URL.Path)
+ return &http.Response{StatusCode: 200, Header: http.Header{}, Body: io.NopCloser(strings.NewReader(`{"version":1,"result":null}`))}, nil
+ })
+ mustJournal(t, r.Call(context.Background(), "renew", runnerproto.RunnerRequest{Version: 1, AssignmentID: "assignment", RequestID: "renew"}, nil))
+ if len(paths) != 2 || !strings.HasSuffix(paths[0], "/heartbeat") || !strings.HasSuffix(paths[1], "/renew") {
+ t.Fatalf("active connection liveness was not renewed: %v", paths)
+ }
+}
diff --git a/internal/runner/direct_workflow.go b/internal/runner/direct_workflow.go
new file mode 100644
index 00000000..22ee63a6
--- /dev/null
+++ b/internal/runner/direct_workflow.go
@@ -0,0 +1,373 @@
+package runner
+
+import (
+ "context"
+ "database/sql"
+ "encoding/json"
+ "errors"
+ "path/filepath"
+ "sync/atomic"
+ "time"
+
+ "amadan.net/oficina/equipo/internal/equipo/team"
+ "amadan.net/oficina/equipo/internal/runner/paseo"
+ "amadan.net/oficina/equipo/internal/runner/provider"
+ "amadan.net/oficina/equipo/internal/runner/workspace"
+ "amadan.net/oficina/equipo/internal/runnerproto"
+)
+
+func (w *BugWorkflow) directModel(ctx context.Context, s *Supervisor, r *attemptState, l *leaseGuard, current func(context.Context) error, ws workspace.Workspace, policy paseo.ReadPolicy, artifacts []team.Artifact) error {
+ launcher := w.cfg.Launchers[r.Claim.Assignment.Selection.Provider]
+ if launcher == nil {
+ return provider.ErrProvider
+ }
+ tool := map[string]string{"reproduce": "submit_reproduction", "implement": "submit_candidate", "review": "submit_review"}[r.Claim.Assignment.StepKey]
+ var proxy *ToolProxy
+ ask := w.directAsk(s, r, l, current)
+ questionCurrent := func(ctx context.Context, q runnerproto.Question) (time.Time, error) {
+ if err := current(ctx); err != nil {
+ return time.Time{}, err
+ }
+ var answers []runnerproto.Question
+ if err := s.api.Call(ctx, "answers", r.request("answers-current"), &answers); err != nil {
+ return time.Time{}, err
+ }
+ for _, saved := range answers {
+ if saved.ID == q.ID && (saved.Revision != q.Revision || saved.PermissionID != q.PermissionID || saved.SessionID != q.SessionID || saved.AgentID != q.AgentID) {
+ return time.Time{}, provider.ErrIdentity
+ }
+ }
+ return l.bound(), nil
+ }
+ b := ToolBinding{ReadPolicy: policy, Copy: w.cfg.Copy, InstanceID: w.cfg.InstanceID, TaskID: r.Claim.Assignment.TaskID, Attempt: int64(r.Claim.Handle.Attempt), Fence: r.Claim.Handle.Fence, Tools: []string{tool, "ask_person"}, LeaseDeadline: l.bound(), Agent: paseo.Agent{ServerID: "direct", Provider: r.Claim.Assignment.Selection.Provider, AccountID: r.Claim.Assignment.Selection.AccountID, Family: r.Claim.Assignment.Selection.Family, Model: r.Claim.Assignment.Selection.Model}, Isolation: r.Claim.Assignment.Selection.Isolation, Journal: s.journal, Current: current}
+ b.Ask = func(ctx context.Context, bound ToolBinding, id string, args json.RawMessage) (json.RawMessage, error) {
+ relay := DirectQuestionRelay{Binding: bound, Proxy: proxy, Launcher: launcher, Current: questionCurrent}
+ answer, err := relay.Ask(ctx, id, args, ask)
+ if err != nil {
+ return nil, err
+ }
+ pending, err := s.journal.ToolSubmissions(ctx, 128)
+ if err != nil {
+ return nil, err
+ }
+ for _, submission := range pending {
+ if submission.RequestID == id && submission.Name == "ask_person" && submission.Agent == bound.Agent && submission.Attempt == bound.Attempt && submission.Fence == bound.Fence && submission.TaskID == bound.TaskID {
+ if err = s.journal.AckTool(ctx, submission); err != nil {
+ return nil, err
+ }
+ }
+ }
+ if err = s.resolveDeliveredQuestions(ctx, r); err != nil {
+ return nil, err
+ }
+ return answer, nil
+ }
+ if permission, ok := launcher.(interface {
+ Permission(context.Context, provider.Session, json.RawMessage) (json.RawMessage, error)
+ }); ok {
+ b.Permission = func(ctx context.Context, raw json.RawMessage) (json.RawMessage, error) {
+ proxy.broker.mu.Lock()
+ session := proxy.broker.binding.Session
+ proxy.broker.mu.Unlock()
+ return permission.Permission(ctx, session, raw)
+ }
+ }
+ var err error
+ proxy, err = OpenToolProxy(ctx, b)
+ if err != nil {
+ return err
+ }
+ s.mu.Lock()
+ s.activeProxy = proxy
+ s.mu.Unlock()
+ launch, release, err := w.cfg.Launch(ctx, r.Claim, ws, proxy)
+ if release != nil {
+ s.activeRelease = release
+ }
+ if err != nil {
+ return err
+ }
+ if err = current(ctx); err != nil {
+ return err
+ }
+ r.Phase = "opening-provider"
+ if err = s.save(ctx, r); err != nil {
+ return err
+ }
+ session, err := launcher.Open(ctx, launch)
+ if err != nil {
+ return err
+ }
+ r.Session = session
+ r.Agent = paseo.Agent{ServerID: "direct", AgentID: session.AttemptKey, ProviderSessionID: session.ID, Provider: session.Provider, AccountID: session.AccountID, Family: session.Family, Model: session.Model}
+ if err = s.save(ctx, r); err != nil {
+ return err
+ }
+ if err = w.cfg.Witness.record(ctx, "session", attemptKey(r.Claim.Scope, r.Claim.Handle), r.Agent); err != nil {
+ return err
+ }
+ events, err := launcher.Events(ctx, session)
+ if err != nil {
+ return err
+ }
+ var action atomic.Int64
+ pump := EventPump{Journal: s.journal, Contain: func(ctx context.Context) error { return launcher.Interrupt(ctx, session) }, Upload: func(ctx context.Context, e Event) error {
+ q := r.request(e.ID)
+ q.RequestID = e.ID
+ q.ActionID = e.ActionID
+ q.Event, _ = runnerproto.Marshal(e)
+ return s.api.Call(ctx, "events", q, nil)
+ }}
+ streamCtx, stopStream := context.WithCancel(ctx)
+ notices := make(chan provider.Event, 64)
+ drainDone := make(chan error, 1)
+ go func() {
+ for {
+ select {
+ case <-streamCtx.Done():
+ drainDone <- streamCtx.Err()
+ return
+ case e, ok := <-events:
+ if !ok {
+ drainDone <- errDirectUncertain
+ return
+ }
+ template := Event{Version: 1, TaskID: r.Claim.Assignment.TaskID, AssignmentID: r.Claim.Assignment.ID, Scope: r.Claim.Scope, Handle: r.Claim.Handle, ServerID: "direct", ActionID: team.ActionID(action.Load()), SourceTime: time.Now().UTC(), Isolation: r.Claim.Assignment.Selection.Isolation}
+ if err := pump.AppendDirect(streamCtx, session, e, template); err != nil {
+ drainDone <- err
+ return
+ }
+ if e.Kind == "request" || e.Kind == "turn.completed" || e.Kind == "turn.failed" {
+ select {
+ case notices <- e:
+ case <-streamCtx.Done():
+ drainDone <- streamCtx.Err()
+ return
+ default:
+ drainDone <- errDirectUncertain
+ return
+ }
+ }
+ }
+ }
+ }()
+ defer func() { stopStream(); <-drainDone }()
+ // Upload independently: a slow instance or person must not stall capture.
+ uploadCtx, stopUpload := context.WithCancel(ctx)
+ uploadDone := make(chan struct{})
+ go func() {
+ defer close(uploadDone)
+ ticker := time.NewTicker(100 * time.Millisecond)
+ defer ticker.Stop()
+ for {
+ select {
+ case <-uploadCtx.Done():
+ return
+ case <-ticker.C:
+ _ = pump.Flush(uploadCtx, 128)
+ }
+ }
+ }()
+ defer func() { stopUpload(); <-uploadDone }()
+ ready := Event{Version: 1, ID: r.request("ready").RequestID, TaskID: r.Claim.Assignment.TaskID, AssignmentID: r.Claim.Assignment.ID, Scope: r.Claim.Scope, Handle: r.Claim.Handle, ServerID: "direct", AgentID: session.AttemptKey, SessionID: session.ID, Epoch: session.AttemptKey, Kind: "timeline_ready", Payload: json.RawMessage(`{}`), SourceTime: time.Now().UTC(), Isolation: r.Claim.Assignment.Selection.Isolation}
+ if err = pump.Append(ctx, ready, nil); err != nil {
+ return err
+ }
+ if err = pump.Flush(ctx, 128); err != nil {
+ return err
+ }
+ message, err := buildTurnPrompt(r.Claim, artifacts)
+ if err != nil {
+ return err
+ }
+ if err = current(ctx); err != nil {
+ return err
+ }
+ payload, err := turnIntentPayload(session.Provider, session.Model, message)
+ if err != nil {
+ return err
+ }
+ q := r.request("turn-intent-0")
+ q.Intent = &team.IntentSpec{Key: q.RequestID, Operation: team.OpProviderCall, Payload: payload, Reserve: team.Usage{Calls: 1, InputTokens: 32000, OutputTokens: 4000, CostUnavailable: true}}
+ var admitted team.ActionID
+ if err = retryAuthority(ctx, func() error { return s.api.Call(ctx, "intend", q, &admitted) }); err != nil {
+ return err
+ }
+ action.Store(int64(admitted))
+ q = r.request("turn-admit-0")
+ q.ActionID = admitted
+ dir := filepath.Join(w.cfg.StateDir, "admissions")
+ if err = runnerproto.JournalAdmission(dir, q); err != nil {
+ return err
+ }
+ var ticket team.AdmissionTicket
+ if err = retryAuthority(ctx, func() error { return s.api.Call(ctx, "admit", q, &ticket) }); err != nil {
+ return err
+ }
+ r.InFlightAction = admitted
+ r.Phase = "turn"
+ if err = s.save(ctx, r); err != nil {
+ return err
+ }
+ turn := provider.Turn{ID: r.request("turn-0").RequestID, AdmissionID: q.RequestID, Prompt: message}
+ if err = proxy.BindTurn(session, turn.ID); err != nil {
+ return err
+ }
+ proxy.broker.mu.Lock()
+ bound := proxy.broker.binding
+ proxy.broker.mu.Unlock()
+ relay := DirectQuestionRelay{Binding: bound, Proxy: proxy, Launcher: launcher, Current: questionCurrent}
+ if err = current(ctx); err != nil {
+ return err
+ }
+ if err = runnerproto.ConsumeTicket(dir, q.RequestID, ticket, time.Now().UTC(), ticket.Incarnation); err != nil {
+ return err
+ }
+ if err = launcher.StartTurn(ctx, session, turn); err != nil {
+ return err
+ }
+ for {
+ e, err := nextDirectNotice(ctx, notices, drainDone)
+ if err != nil {
+ return err
+ }
+ if e.Kind == "request" {
+ if err = pump.Flush(ctx, 128); err != nil {
+ return err
+ }
+ // Respond returning nil is transport success, never approval evidence.
+ if err = relay.Handle(ctx, e, ask); err != nil {
+ return err
+ }
+ if err = s.resolveDeliveredQuestions(ctx, r); err != nil {
+ return err
+ }
+ continue
+ }
+ // Cancellation may have quarantined the turn before its terminal frame was normalized.
+ if e.Kind == "turn.completed" {
+ if err = s.journal.requireDirectCompletion(ctx, session, e.TurnID); err != nil {
+ return err
+ }
+ } else if len(e.Payload) == 0 {
+ return errDirectUncertain
+ }
+ // AppendDirect committed the terminal event before publishing this notice.
+ if err = pump.Flush(ctx, 128); err != nil {
+ return err
+ }
+ r.InFlightAction = 0
+ if err = s.save(ctx, r); err != nil {
+ return err
+ }
+ if e.Kind == "turn.failed" {
+ return team.ErrEvidence
+ }
+ return launcher.Close(ctx, session)
+ }
+}
+
+func nextDirectNotice(ctx context.Context, notices <-chan provider.Event, done chan error) (provider.Event, error) {
+ select {
+ case event := <-notices:
+ return event, nil
+ default:
+ }
+ select {
+ case event := <-notices:
+ return event, nil
+ case <-ctx.Done():
+ return provider.Event{}, ctx.Err()
+ case err := <-done:
+ done <- err
+ select {
+ case event := <-notices:
+ return event, nil
+ default:
+ return provider.Event{}, err
+ }
+ }
+}
+
+func (w *BugWorkflow) directAsk(s *Supervisor, r *attemptState, l *leaseGuard, current func(context.Context) error) func(context.Context, runnerproto.Question) (runnerproto.QuestionAnswer, error) {
+ return func(ctx context.Context, q runnerproto.Question) (runnerproto.QuestionAnswer, error) {
+ q.AssignmentID = r.Claim.Assignment.ID
+ q.ExpiresAt = l.bound()
+ if err := w.cfg.Witness.record(ctx, "question", q.ID, q); err != nil {
+ return runnerproto.QuestionAnswer{}, err
+ }
+ request := r.request("question-" + q.ID)
+ request.Question = &q
+ var saved runnerproto.Question
+ if err := s.api.Call(ctx, "questions", request, &saved); err != nil {
+ return runnerproto.QuestionAnswer{}, err
+ }
+ ticker := time.NewTicker(100 * time.Millisecond)
+ defer ticker.Stop()
+ for {
+ if err := current(ctx); err != nil {
+ return runnerproto.QuestionAnswer{}, err
+ }
+ var answers []runnerproto.Question
+ if err := s.api.Call(ctx, "answers", r.request("answers"), &answers); err != nil {
+ return runnerproto.QuestionAnswer{}, err
+ }
+ for _, answer := range answers {
+ if answer.ID != saved.ID || answer.Answer == nil {
+ continue
+ }
+ if answer.Revision != saved.Revision || answer.AgentID != saved.AgentID || answer.SessionID != saved.SessionID || saved.ValidateAnswer(*answer.Answer) != nil {
+ return runnerproto.QuestionAnswer{}, provider.ErrIdentity
+ }
+ return *answer.Answer, nil
+ }
+ select {
+ case <-ctx.Done():
+ return runnerproto.QuestionAnswer{}, ctx.Err()
+ case <-ticker.C:
+ }
+ }
+ }
+}
+
+// Resolution acknowledges delivery, never an approval inferred from Respond's return.
+func (s *Supervisor) resolveDeliveredQuestions(ctx context.Context, r *attemptState) error {
+ var questions []runnerproto.Question
+ if err := s.journal.readStates(ctx, "witness-question", &questions); err != nil {
+ return err
+ }
+ for _, q := range questions {
+ if q.AssignmentID != r.Claim.Assignment.ID || q.TaskID != r.Claim.Assignment.TaskID || q.Attempt != int64(r.Claim.Handle.Attempt) || q.Fence != r.Claim.Handle.Fence || q.AgentID != r.Session.AttemptKey || q.SessionID != r.Session.ID {
+ continue
+ }
+ key := runnerproto.EventHash([]any{q.TaskID, q.Attempt, q.Fence, q.ServerID, q.AgentID, q.SessionID, q.PermissionID})
+ var state string
+ err := s.journal.db.QueryRowContext(ctx, "SELECT state FROM journal_answers WHERE answer_key=?", key).Scan(&state)
+ if errors.Is(err, sql.ErrNoRows) {
+ continue
+ }
+ if err != nil {
+ return err
+ }
+ if state != "delivered" {
+ continue
+ }
+ request := r.request("question-resolved-" + q.ID)
+ request.Question = &q
+ if err = s.api.Call(ctx, "question_resolved", request, nil); err != nil {
+ return err
+ }
+ }
+ return nil
+}
+
+func (j *Journal) requireDirectCompletion(ctx context.Context, s provider.Session, turn string) error {
+ var state string
+ if err := j.db.QueryRowContext(ctx, "SELECT state FROM direct_turns WHERE attempt=? AND session=? AND turn=?", s.AttemptKey, s.ID, turn).Scan(&state); err != nil {
+ return err
+ }
+ if state != "completed" {
+ return errDirectUncertain
+ }
+ return nil
+}
diff --git a/internal/runner/direct_workflow_test.go b/internal/runner/direct_workflow_test.go
new file mode 100644
index 00000000..7d6281aa
--- /dev/null
+++ b/internal/runner/direct_workflow_test.go
@@ -0,0 +1,223 @@
+package runner
+
+import (
+ "context"
+ "encoding/json"
+ "io"
+ "os"
+ "path/filepath"
+ "sync/atomic"
+ "testing"
+ "time"
+
+ "amadan.net/oficina/equipo/internal/runner/containment"
+ "amadan.net/oficina/equipo/internal/runner/provider"
+ "amadan.net/oficina/equipo/internal/runnerproto"
+)
+
+func TestDirectBugWorkflow(t *testing.T) { runDirectBugGraph(t) }
+
+func directNamespaceFixture(t *testing.T) (*Supervisor, *attemptState, *containment.Manager, provider.ProcessHost, provider.Launch) {
+ t.Helper()
+ s, r, _, _ := cleanupFixture(t)
+ r.Direct = true
+ r.Claim.Assignment.TaskID = "task"
+ r.Owner = ProcessOwner{}
+ r.Proof = nil
+ scratch := filepath.Join(t.TempDir(), "scratch")
+ mustJournal(t, os.Mkdir(scratch, 0700))
+ work := t.TempDir()
+ mods := t.TempDir()
+ binary, err := filepath.EvalSymlinks("/usr/bin/python3")
+ mustJournal(t, err)
+ helper, err := os.Executable()
+ mustJournal(t, err)
+ m, err := containment.New(containment.Config{Binary: "/usr/bin/bwrap", RunnerBinary: helper, ScratchRoot: scratch})
+ mustJournal(t, err)
+ s.namespaces = m
+ _, err = s.journal.ReconcileDirect(context.Background(), m)
+ mustJournal(t, err)
+ env := map[string]string{"GOCACHE": "/tmp/go-build", "GOTMPDIR": "/tmp/go-tmp", "GOMODCACHE": "/opt/go-mod", "GOROOT": "/opt/go", "GOTOOLCHAIN": "local", "GOWORK": "off", "GOENV": "off", "GOTELEMETRY": "off", "GOPROXY": "off", "GOSUMDB": "off", "CGO_ENABLED": "0", "XDG_CONFIG_HOME": "/tmp/xdg", "PATH": "/opt/go/bin:/usr/bin:/bin"}
+ argv := []string{"/opt/codex", "-u", "-c", `import os,time
+for name in ['model','code-mode-host','relay','mcp','check']:
+ if os.fork()==0:
+ os.setsid()
+ time.sleep(60)
+ os._exit(0)
+print('ready',flush=True)
+time.sleep(60)`}
+ p, err := provider.BuildCheckPolicy(provider.CheckPolicyInputs{Workspace: work, Binary: binary, RunnerBinary: helper, Bwrap: "/usr/bin/bwrap", GoRoot: mods, ModuleCache: mods, Argv: argv, Env: env})
+ mustJournal(t, err)
+ return s, r, m, NewDirectHost(s.journal, m), provider.Launch{AttemptKey: "model-fixture", Workspace: work, Policy: p}
+}
+
+func TestDirectCancelWaitsForNamespaces(t *testing.T) {
+ s, r, m, host, l := directNamespaceFixture(t)
+ ctx, cancel := context.WithCancel(context.Background())
+ defer cancel()
+ ctx = s.namespaceContext(ctx, r)
+ p, err := host.Start(ctx, l, []string{"/opt/codex", "-u", "-c", `import os,time
+for name in ['model','code-mode-host','relay','mcp','check']:
+ if os.fork()==0:
+ os.setsid()
+ time.sleep(60)
+ os._exit(0)
+print('ready',flush=True)
+time.sleep(60)`})
+ mustJournal(t, err)
+ t.Cleanup(func() {
+ m.Stop(context.Background(), p.ID())
+ p.Stdout().Close()
+ p.Stderr().Close()
+ p.Stdin().Close()
+ })
+ var manifest struct{ Argv []string }
+ mustJournal(t, json.Unmarshal(l.Policy.Manifest, &manifest))
+ l.AttemptKey = "check-fixture"
+ check, err := host.Start(ctx, l, manifest.Argv)
+ mustJournal(t, err)
+ t.Cleanup(func() {
+ m.Stop(context.Background(), check.ID())
+ check.Stdout().Close()
+ check.Stderr().Close()
+ check.Stdin().Close()
+ })
+ b := make([]byte, 6)
+ _, err = io.ReadFull(p.Stdout(), b)
+ mustJournal(t, err)
+ if string(b) != "ready\n" {
+ t.Fatal("fixture did not launch")
+ }
+ if r.Phase == "contained" {
+ t.Fatal("capacity released on launch")
+ }
+ proof, err := s.cleanup(context.Background(), r)
+ mustJournal(t, err)
+ if proof.Version != 2 || len(proof.Namespaces) != 2 || r.Phase != "contained" {
+ t.Fatalf("missing namespace proof: %+v", proof)
+ }
+ if _, err = p.Wait(context.Background()); err != nil {
+ t.Fatal(err)
+ }
+}
+
+func TestDirectBugLaunchAdmission(t *testing.T) {
+ s, r, m, host, l := directNamespaceFixture(t)
+ s.api = &supervisorAPI{order: new([]string), fail: true}
+ ctx, cancel := context.WithTimeout(s.namespaceContext(context.Background(), r), time.Second)
+ defer cancel()
+ var manifest struct{ Argv []string }
+ if err := json.Unmarshal(l.Policy.Manifest, &manifest); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := host.Start(ctx, l, manifest.Argv); err == nil {
+ t.Fatal("namespace ran without launch ACK")
+ }
+ records, err := m.Records(context.Background())
+ mustJournal(t, err)
+ for _, record := range records {
+ proof, err := m.Recover(context.Background(), record)
+ if err != nil || !proof.Verified {
+ t.Fatalf("refused launch not contained: %v", err)
+ }
+ }
+}
+
+func TestDirectRestartAndLeaseLossLiveCapture(t *testing.T) {
+ j, l, _, p := directFixture(t, "codex")
+ reader, writer := io.Pipe()
+ p.out = reader
+ defer writer.Close()
+ ctx, cancel := context.WithCancel(context.Background())
+ defer cancel()
+ c, err := NewCaptureFactory(j).Open(ctx, p, l)
+ mustJournal(t, err)
+ if _, err = j.RecoverDirect(context.Background()); err == nil {
+ t.Fatal("recovery admitted while capture was live")
+ }
+ cancel()
+ <-c.Done
+ if _, err = j.RecoverDirect(context.Background()); err != nil {
+ t.Fatal(err)
+ }
+}
+
+func TestDirectCancelWaitsForNamespacesUnproven(t *testing.T) {
+ s, r, _, _, _ := directNamespaceFixture(t)
+ n := namespaceState{Owner: attemptKey(r.Claim.Scope, r.Claim.Handle), Record: containment.Record{ID: "missing", AttemptKey: "check-missing"}}
+ mustJournal(t, s.journal.saveState(context.Background(), "namespace", "missing", n))
+ if _, err := s.cleanup(context.Background(), r); err == nil || r.Phase == "contained" {
+ t.Fatal("unproven check namespace released capacity")
+ }
+}
+
+func TestDirectRestartAndLeaseLoss(t *testing.T) {
+ for _, kind := range []string{"rollback", "suspend", "membership", "connection"} {
+ t.Run(kind, func(t *testing.T) {
+ s, r, m, host, l := directNamespaceFixture(t)
+ ctx, cancel := context.WithCancelCause(s.namespaceContext(context.Background(), r))
+ defer cancel(nil)
+ var manifest struct{ Argv []string }
+ mustJournal(t, json.Unmarshal(l.Policy.Manifest, &manifest))
+ p, err := host.Start(ctx, l, manifest.Argv)
+ mustJournal(t, err)
+ t.Cleanup(func() {
+ m.Stop(context.Background(), p.ID())
+ p.Stdout().Close()
+ p.Stderr().Close()
+ p.Stdin().Close()
+ })
+ b := make([]byte, 6)
+ _, err = io.ReadFull(p.Stdout(), b)
+ mustJournal(t, err)
+ now := ClockReading{Wall: time.Now(), Elapsed: time.Hour, BootID: "boot"}
+ lease, err := newLease(now, now.Wall.Add(time.Minute), now.Wall.Add(5*time.Minute))
+ mustJournal(t, err)
+ var reads atomic.Int32
+ s.clock = clockFuncR3(func() (ClockReading, error) {
+ v := now
+ if reads.Add(1) > 1 {
+ switch kind {
+ case "rollback":
+ v.Wall = v.Wall.Add(-time.Second)
+ case "suspend":
+ v.Elapsed += time.Minute
+ default:
+ v.Elapsed += 16 * time.Second
+ v.Wall = v.Wall.Add(16 * time.Second)
+ }
+ }
+ return v, nil
+ })
+ s.api = apiFuncR3(func(_ context.Context, _ string, _ runnerproto.RunnerRequest, out any) error {
+ if kind == "membership" {
+ return provider.ErrIdentity
+ }
+ *out.(*time.Time) = now.Wall.Add(time.Minute)
+ return nil
+ })
+ s.activeCurrent = func(context.Context) error {
+ if kind == "connection" {
+ return provider.ErrIdentity
+ }
+ return nil
+ }
+ done := make(chan struct{})
+ go s.watchLease(ctx, cancel, r, lease, done)
+ select {
+ case <-done:
+ case <-time.After(3 * time.Second):
+ t.Fatal("watchdog did not stop")
+ }
+ cleanup, stop := context.WithTimeout(context.Background(), 3*time.Second)
+ defer stop()
+ if _, err = p.Wait(cleanup); err != nil {
+ t.Fatalf("namespace survived authority loss: %v", err)
+ }
+ proof, err := m.Stop(cleanup, p.ID())
+ if err != nil || !proof.Verified {
+ t.Fatalf("no namespace proof: %v", err)
+ }
+ })
+ }
+}
diff --git a/internal/runner/journal.go b/internal/runner/journal.go
index 5bd445ee..9fe02077 100644
--- a/internal/runner/journal.go
+++ b/internal/runner/journal.go
@@ -22,11 +22,12 @@ const MaxJournalBytes int64 = 128 << 20
var ErrJournal = errors.Join(paseo.ErrUncertain, errors.New("runner.journal"))
type Journal struct {
- db *sql.DB
- path string
- maxBytes int64
- mu sync.Mutex
- blocked bool
+ captureMu sync.RWMutex
+ db *sql.DB
+ path string
+ maxBytes int64
+ mu sync.Mutex
+ blocked bool
}
func OpenJournal(ctx context.Context, path string) (*Journal, error) {
diff --git a/internal/runner/provider/check_policy.go b/internal/runner/provider/check_policy.go
new file mode 100644
index 00000000..2b5a7450
--- /dev/null
+++ b/internal/runner/provider/check_policy.go
@@ -0,0 +1,86 @@
+package provider
+
+import (
+ "encoding/json"
+ "os"
+ "path/filepath"
+ "reflect"
+
+ "golang.org/x/sys/unix"
+)
+
+const checkPolicyVersion = "checks-v1"
+
+type CheckPolicyInputs struct {
+ Workspace, Binary, RunnerBinary, Bwrap, GoRoot, ModuleCache string
+ Argv []string
+ Env map[string]string
+}
+
+// BuildCheckPolicy admits no provider home, network, or writable host cache.
+func BuildCheckPolicy(in CheckPolicyInputs) (Policy, error) {
+ home, err := os.UserHomeDir()
+ if err != nil {
+ return Policy{}, ErrPolicy
+ }
+ m := effectiveManifest{Version: checkPolicyVersion, Workspace: in.Workspace, Argv: in.Argv, Env: in.Env, NamespaceArgs: NamespaceArguments()}
+ for _, path := range []string{in.Workspace, in.GoRoot, in.ModuleCache} {
+ if path == "/" || withinPath(home, path) {
+ return Policy{}, ErrPolicy
+ }
+ f, err := pinDirectory(path)
+ if err != nil {
+ return Policy{}, err
+ }
+ f.Close()
+ }
+ m.OuterMounts = []Mount{{Source: in.Binary, Target: "/opt/codex", ReadOnly: true}, {Source: in.RunnerBinary, Target: "/opt/equipo-runner", ReadOnly: true}, {Source: in.Bwrap, Target: "/opt/bwrap", ReadOnly: true}, {Source: in.GoRoot, Target: "/opt/go", ReadOnly: true}, {Source: in.ModuleCache, Target: "/opt/go-mod", ReadOnly: true}}
+ for _, mount := range m.OuterMounts[:3] {
+ fd, err := unix.Openat2(unix.AT_FDCWD, mount.Source, &unix.OpenHow{Flags: unix.O_RDONLY | unix.O_CLOEXEC | unix.O_NONBLOCK, Resolve: unix.RESOLVE_NO_SYMLINKS | unix.RESOLVE_NO_MAGICLINKS})
+ if err != nil {
+ return Policy{}, ErrPolicy
+ }
+ f := os.NewFile(uintptr(fd), mount.Source)
+ info, err := f.Stat()
+ f.Close()
+ if err != nil || !info.Mode().IsRegular() {
+ return Policy{}, ErrPolicy
+ }
+ raw, err := os.ReadFile(mount.Source)
+ if err != nil {
+ return Policy{}, err
+ }
+ m.Files = append(m.Files, fileDigest{Mount: mount, SHA256: digest(raw)})
+ }
+ raw, hash, err := hashJSON(m)
+ if err != nil {
+ return Policy{}, err
+ }
+ return Policy{Hash: hash, ManifestHash: hash, Manifest: raw, Mounts: m.OuterMounts, Env: in.Env}, nil
+}
+
+func (p Policy) IsCheck() bool {
+ var m effectiveManifest
+ return json.Unmarshal(p.Manifest, &m) == nil && m.Version == checkPolicyVersion
+}
+
+func attestCheck(l Launch, argv []string) (string, error) {
+ p := l.Policy
+ var m effectiveManifest
+ if l.Selection != (Selection{}) || l.Binding != (Binding{}) || l.ToolSocket != "" || l.ResumeSessionID != "" || l.AttemptKey == "" || json.Unmarshal(p.Manifest, &m) != nil || digest(p.Manifest) != p.ManifestHash || p.Hash != p.ManifestHash || m.Workspace != l.Workspace || !reflect.DeepEqual(argv, m.Argv) || !reflect.DeepEqual(p.Env, m.Env) || !reflect.DeepEqual(p.Mounts, m.OuterMounts) || !reflect.DeepEqual(m.NamespaceArgs, NamespaceArguments()) {
+ return "", ErrPolicy
+ }
+ for _, f := range m.Files {
+ raw, err := os.ReadFile(f.Mount.Source)
+ if err != nil || digest(raw) != f.SHA256 {
+ return "", ErrPolicy
+ }
+ }
+ for _, mount := range p.Mounts {
+ if !mount.ReadOnly || !filepath.IsAbs(mount.Source) {
+ return "", ErrPolicy
+ }
+ }
+ _, hash, err := hashJSON(struct{ Manifest, Attempt string }{p.ManifestHash, l.AttemptKey})
+ return hash, err
+}
diff --git a/internal/runner/provider/policy.go b/internal/runner/provider/policy.go
index 07143813..32623052 100644
--- a/internal/runner/provider/policy.go
+++ b/internal/runner/provider/policy.go
@@ -433,6 +433,9 @@ func (p Policy) ValidateReadback(r ConfigReadback) error {
// AttestLaunch binds a concrete attempt to the already built policy. Containment
// persists this hash separately from the reusable policy certificate hash.
func AttestLaunch(l Launch, argv []string) (string, error) {
+ if l.Policy.IsCheck() {
+ return attestCheck(l, argv)
+ }
p := l.Policy
if p.ManifestHash == "" {
// Legacy check jobs have no direct-provider manifest during the cutover.
diff --git a/internal/runner/runtime.go b/internal/runner/runtime.go
index 0e537765..f0adb4e8 100644
--- a/internal/runner/runtime.go
+++ b/internal/runner/runtime.go
@@ -6,24 +6,32 @@ import (
"os"
"path/filepath"
"sync"
+ "time"
- "amadan.net/oficina/equipo/internal/release"
"amadan.net/oficina/equipo/internal/runner/checks"
+ "amadan.net/oficina/equipo/internal/runner/containment"
"amadan.net/oficina/equipo/internal/runner/paseo"
+ "amadan.net/oficina/equipo/internal/runner/provider"
+ "amadan.net/oficina/equipo/internal/runner/provider/claude"
+ "amadan.net/oficina/equipo/internal/runner/provider/codex"
"amadan.net/oficina/equipo/internal/runnerproto"
)
type Runtime struct {
- cfg Config
- lock *os.File
- journal *Journal
- client *paseo.Client
- inspector *LinuxProcessInspector
- api *HTTPInstance
- service *Service
- sandbox *checks.CodexSandbox
- mu sync.Mutex
- current *RunClaim
+ lastReports []runnerproto.ConnectionReport
+ namespaces *containment.Manager
+ launchers map[string]provider.Launcher
+ host provider.ProcessHost
+ cfg Config
+ lock *os.File
+ journal *Journal
+ client *paseo.Client
+ inspector *LinuxProcessInspector
+ api *HTTPInstance
+ service *Service
+ sandbox *checks.CodexSandbox
+ mu sync.Mutex
+ current *RunClaim
}
func openRuntime(ctx context.Context, c Config) (r *Runtime, err error) {
@@ -47,25 +55,16 @@ func openRuntime(ctx context.Context, c Config) (r *Runtime, err error) {
return r, err
}
variable = "EQUIPO_ACCOUNT_BINDINGS_PATH"
- bs, err := loadBindings(c.AccountBindingsPath)
+ bs, err := loadDirectBindings(c.AccountBindingsPath)
if err != nil {
return r, err
}
- variable = "EQUIPO_NODE_PATH"
- if err = checkNode(ctx, c.NodePath); err != nil {
- return r, err
- }
for _, dir := range []struct{ name, path string }{{"EQUIPO_SCRATCH_ROOT", c.ScratchRoot}, {"EQUIPO_WORKSPACE_ROOT", c.WorkspaceRoot}} {
variable = dir.name
if err = os.MkdirAll(dir.path, 0700); err != nil {
return r, err
}
}
- variable = "EQUIPO_CODEX_PATH"
- r.sandbox, err = checks.NewCodexSandbox(ctx, checks.SandboxConfig{Binary: c.CodexPath, ScratchRoot: c.ScratchRoot, GoRoot: c.GoRoot, GoBinary: c.GoBinary, Protected: c.securityPaths(bs)})
- if err != nil {
- return r, err
- }
variable = "EQUIPO_RUNNER_STATE_DIR"
r.journal, err = OpenJournal(ctx, filepath.Join(c.StateDir, "journal.db"))
if err != nil {
@@ -79,19 +78,31 @@ func openRuntime(ctx context.Context, c Config) (r *Runtime, err error) {
for id, token := range credentials.CleanupTokens {
r.api.cleanup[id] = token
}
- tuples := []paseo.VerifiedTuple{}
- for _, v := range release.BuildManifest().VerifiedIsolationTuples {
- tuples = append(tuples, paseo.VerifiedTuple{Provider: v.Provider, ProviderVersion: v.ProviderVersion, PaseoVersion: v.PaseoVersion, ConfigHash: v.IsolationConfigHash})
+ variable = "EQUIPO_SCRATCH_ROOT"
+ r.namespaces, err = containment.New(containment.Config{Binary: c.bwrap(), RunnerBinary: c.Executable, ScratchRoot: c.ScratchRoot, ProviderNetworks: []provider.NetworkContract{{Provider: "claude"}, {Provider: "codex"}}})
+ if err != nil {
+ return r, err
}
- variable = "EQUIPO_BRIDGE_PATH"
- r.client, err = paseo.Start(ctx, paseo.Config{CredentialHome: func(s paseo.Selection) (string, error) { b, _, err := r.binding(s); return b.CredentialHome, err }, ObserveProviderVersion: r.providerVersion, TrialConsent: r.trialConsent, InspectDedicatedUser: r.dedicatedUser, AuthorizeTrial: r.authorizeTrial, VerifyRouting: r.verifyRouting, VerifiedTuples: tuples, NodePath: c.NodePath, BridgePath: c.BridgePath, DaemonHome: c.PaseoHome, Endpoint: c.PaseoEndpoint, ServerID: c.PaseoServerID, RecordIntent: r.journal.RecordIntent, RecordCreationRefusal: r.journal.RecordCreationRefusal, InspectProcesses: r.coverage, AuthorizeUnconfined: r.authorizeUnconfined})
+ if _, err = r.journal.ReconcileDirect(ctx, r.namespaces); err != nil {
+ return r, err
+ }
+ r.host = NewDirectHost(r.journal, r.namespaces)
+ captures := NewCaptureFactory(r.journal)
+ claudeLauncher, err := claude.New(r.host, captures)
if err != nil {
return r, err
}
- r.inspector, err = serviceInspector(r.client, r.journal)
+ codexLauncher, err := codex.New(r.host, captures)
if err != nil {
return r, err
}
+ r.launchers = map[string]provider.Launcher{"claude": claudeLauncher, "codex": codexLauncher}
+ variable = "EQUIPO_CODEX_PATH"
+ r.sandbox, err = checks.NewCodexSandbox(ctx, checks.SandboxConfig{Binary: c.CodexPath, ScratchRoot: c.ScratchRoot, GoRoot: c.GoRoot, GoBinary: c.GoBinary, Protected: c.securityPaths(bs), Host: r.host, RunnerBinary: c.Executable, Bwrap: c.bwrap(), ModuleCache: c.moduleCache()})
+ if err != nil {
+ return r, err
+ }
+
return r, nil
}
func (r *Runtime) Close() error {
@@ -99,12 +110,40 @@ func (r *Runtime) Close() error {
return nil
}
var err error
+ if r.namespaces != nil {
+ ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
+ records, e := r.namespaces.Records(ctx)
+ err = errors.Join(err, e)
+ for _, record := range records {
+ if _, e = r.namespaces.Stop(ctx, record.ID); e != nil {
+ // Failed construction may contain an unrelated record. Never claim it.
+ if r.journal == nil || r.journal.validateDirectRecord(ctx, record) != nil {
+ continue
+ }
+ _, e = r.namespaces.Recover(ctx, record)
+ }
+ err = errors.Join(err, e)
+ }
+ cancel()
+ if err != nil {
+ return err
+ }
+ r.namespaces = nil
+ }
+ if r.service != nil && r.service.Supervisor.activeRelease != nil {
+ if e := r.service.Supervisor.activeRelease(); e != nil {
+ return e
+ }
+ r.service.Supervisor.activeRelease = nil
+ }
if r.client != nil {
err = errors.Join(err, r.client.Close())
r.client = nil
}
if r.journal != nil {
+ r.journal.captureMu.Lock()
err = errors.Join(err, r.journal.Close())
+ r.journal.captureMu.Unlock()
r.journal = nil
}
if r.lock != nil {
@@ -142,7 +181,13 @@ func (r *Runtime) authorizeUnconfined(ctx context.Context, s paseo.Selection, ca
return r.api.Call(ctx, "validate", runnerproto.RunnerRequest{Version: 1, AssignmentID: claim.Assignment.ID, Scope: claim.Scope, Handle: claim.Handle, RequestID: "preflight"}, nil)
}
func (r *Runtime) binding(s paseo.Selection) (AccountBinding, []AccountBinding, error) {
- bs, err := loadBindings(r.cfg.AccountBindingsPath)
+ var bs []AccountBinding
+ var err error
+ if r.namespaces != nil {
+ bs, err = loadDirectBindings(r.cfg.AccountBindingsPath)
+ } else {
+ bs, err = loadBindings(r.cfg.AccountBindingsPath)
+ }
if err != nil {
return AccountBinding{}, nil, err
}
@@ -190,7 +235,7 @@ func Preflight(ctx context.Context, c Config) ([]runnerproto.ConnectionReport, e
return nil, err
}
defer r.Close()
- return discover(ctx, c, r.client)
+ return r.discoverNamespaces(ctx)
}
func Run(ctx context.Context, c Config) error {
r, err := openRuntime(ctx, c)
@@ -207,13 +252,16 @@ func (r *Runtime) Poll(ctx context.Context) ([]runnerproto.Assignment, error) {
r.mu.Lock()
r.current = nil
r.mu.Unlock()
- reports, err := discover(ctx, r.cfg, r.client)
+ reports, err := r.discoverNamespaces(ctx)
if err != nil {
return nil, err
}
if err = r.api.Heartbeat(ctx, reports); err != nil {
return nil, err
}
+ r.mu.Lock()
+ r.lastReports = append([]runnerproto.ConnectionReport(nil), reports...)
+ r.mu.Unlock()
return r.api.Poll(ctx)
}
func (r *Runtime) Claim(ctx context.Context, q runnerproto.ClaimRequest) (runnerproto.ClaimResponse, error) {
@@ -225,11 +273,15 @@ func (r *Runtime) RecoverClaim(ctx context.Context, q runnerproto.ClaimRequest)
func (r *Runtime) Call(ctx context.Context, op string, q runnerproto.RunnerRequest, out any) error {
if op == "renew" {
- reports, err := discover(ctx, r.cfg, r.client)
- if err != nil {
- return err
+ r.mu.Lock()
+ reports := append([]runnerproto.ConnectionReport(nil), r.lastReports...)
+ r.mu.Unlock()
+ if len(reports) == 0 {
+ return provider.ErrPreflightRequired
}
- if err = r.api.Heartbeat(ctx, reports); err != nil {
+ // A held account lease cannot be reopened for a heartbeat. Dispatch and
+ // the workflow's current callback still revalidate the selected account.
+ if err := r.api.Heartbeat(ctx, reports); err != nil {
return err
}
}
diff --git a/internal/runner/runtime_direct.go b/internal/runner/runtime_direct.go
new file mode 100644
index 00000000..602ce973
--- /dev/null
+++ b/internal/runner/runtime_direct.go
@@ -0,0 +1,151 @@
+package runner
+
+import (
+ "context"
+ "crypto/sha256"
+ "encoding/hex"
+ "errors"
+ "os"
+ "path/filepath"
+ "slices"
+
+ "amadan.net/oficina/equipo/internal/release"
+ "amadan.net/oficina/equipo/internal/runner/egress"
+ "amadan.net/oficina/equipo/internal/runner/paseo"
+ "amadan.net/oficina/equipo/internal/runner/provider"
+ "amadan.net/oficina/equipo/internal/runner/provider/claude"
+ "amadan.net/oficina/equipo/internal/runner/provider/codex"
+ "amadan.net/oficina/equipo/internal/runner/workspace"
+ "amadan.net/oficina/equipo/internal/runnerproto"
+)
+
+func directLauncherVersion() string {
+ if v := release.BuildManifest().LauncherVersion; v != "" {
+ return v
+ }
+ return provider.PolicyVersion
+}
+func certifiedDirect(name, version, hash string) bool {
+ return slices.Contains(release.BuildManifest().DirectPolicies, release.PolicyCertificate{Provider: name, ProviderVersion: version, LauncherVersion: directLauncherVersion(), BwrapVersion: "0.11.0", PolicyHash: hash})
+}
+
+func (r *Runtime) constructDirect(ctx context.Context, s paseo.Selection, work, step string) (provider.Launch, func() error, error) {
+ b, _, err := r.binding(s)
+ if err != nil {
+ return provider.Launch{}, nil, err
+ }
+ binding, err := r.cfg.DirectBinding(b)
+ if err != nil {
+ return provider.Launch{}, nil, err
+ }
+ lease, err := provider.OpenAccount(ctx, binding)
+ if err != nil {
+ return provider.Launch{}, nil, err
+ }
+ policyScratch, err := os.MkdirTemp(r.cfg.ScratchRoot, "policy-")
+ if err != nil {
+ return provider.Launch{}, lease.Close, err
+ }
+ cleanup := func() error { return errors.Join(lease.Close(), os.RemoveAll(policyScratch)) }
+ binding = lease.Binding()
+ denies, err := r.policy(ctx, s)
+ if err != nil {
+ return provider.Launch{}, cleanup, err
+ }
+ network, err := egress.ProviderPolicy(provider.NetworkContract{Provider: s.Provider}, binding.VerifiedDedicatedHome())
+ if err != nil {
+ return provider.Launch{}, cleanup, err
+ }
+ runtimeFiles := []provider.Mount{{Source: r.cfg.Executable, Target: "/opt/equipo-tool-proxy", ReadOnly: true}, {Source: r.cfg.bwrap(), Target: "/opt/bwrap", ReadOnly: true}}
+ binary := r.cfg.ClaudePath
+ if s.Provider == "codex" {
+ binary = r.cfg.CodexPath
+ }
+ binary, err = filepath.EvalSymlinks(binary)
+ if err != nil {
+ return provider.Launch{}, cleanup, err
+ }
+ runtimeFiles = append(runtimeFiles, provider.Mount{Source: binary, Target: "/opt/" + s.Provider, ReadOnly: true})
+ if s.Provider == "codex" {
+ runtimeFiles = append(runtimeFiles, provider.Mount{Source: filepath.Join(filepath.Dir(binary), "codex-code-mode-host"), Target: "/opt/codex-code-mode-host", ReadOnly: true})
+ }
+ tool := map[string]string{"reproduce": "submit_reproduction", "implement": "submit_candidate", "review": "submit_review"}[step]
+ if tool == "" {
+ return provider.Launch{}, cleanup, provider.ErrPolicy
+ }
+ in := provider.PolicyInputs{Workspace: work, Scratch: policyScratch, RuntimeFiles: runtimeFiles, DeniedPaths: denies.DeniedPaths, EgressHosts: network.Hosts, LauncherVersion: directLauncherVersion(), BwrapVersion: "0.11.0", Tools: []string{"mcp__equipo__" + tool, "mcp__equipo__ask_person"}}
+ if s.Provider == "claude" {
+ specialist := "Engineering"
+ if step == "review" {
+ specialist = "Review"
+ }
+ in, err = claude.PolicyInputs(binding, in, specialist, s.Model)
+ } else {
+ in, err = codex.PolicyInputs(binding, in, s.Model)
+ }
+ if err != nil {
+ return provider.Launch{}, cleanup, err
+ }
+ policy, err := provider.BuildPolicy(binding, in)
+ if err != nil {
+ return provider.Launch{}, cleanup, err
+ }
+ return provider.Launch{Workspace: work, Selection: provider.Selection{ConnectionID: s.ConnectionID, Provider: s.Provider, Family: s.Family, AccountID: s.AccountID, Model: s.Model}, Binding: binding, Policy: policy}, cleanup, nil
+}
+
+func (r *Runtime) directLaunch(ctx context.Context, c RunClaim, ws workspace.Workspace, proxy *ToolProxy) (provider.Launch, func() error, error) {
+ l, cleanup, err := r.constructDirect(ctx, selection(c.Assignment), ws.Path, c.Assignment.StepKey)
+ if err != nil {
+ return l, cleanup, err
+ }
+ if c.Assignment.Selection.Isolation.Status != "confined" || !certifiedDirect(l.Selection.Provider, l.Binding.Expected.ProviderVersion, l.Policy.Hash) {
+ return l, cleanup, provider.ErrPolicy
+ }
+ l.AttemptKey = attemptKey(c.Scope, c.Handle) + "/model"
+ l.ToolSocket = proxy.SocketPath
+ return l, cleanup, nil
+}
+
+func (r *Runtime) discoverNamespaces(ctx context.Context) ([]runnerproto.ConnectionReport, error) {
+ bs, err := loadDirectBindings(r.cfg.AccountBindingsPath)
+ if err != nil {
+ return nil, err
+ }
+ reports := make([]runnerproto.ConnectionReport, 0, len(bs))
+ for _, b := range bs {
+ hash := sha256.Sum256([]byte(b.ProviderHome))
+ report := runnerproto.ConnectionReport{LocalID: b.LocalID, Provider: b.Provider, Family: b.Family, Model: b.Model, Kind: b.Kind, ProviderVersion: b.ExpectedIdentity.ProviderVersion, LauncherVersion: directLauncherVersion(), BwrapVersion: "0.11.0", PolicyVersion: provider.PolicyVersion, ProviderVersionSource: "direct-cli", UnavailableReason: "capability_unverified", IsolationConfigHash: runnerproto.EventHash(b), Routing: runnerproto.ConnectionRouting{BindingID: b.ID, AccountID: b.AccountID, CredentialHomeHash: hex.EncodeToString(hash[:])}}
+ work, err := os.MkdirTemp(r.cfg.WorkspaceRoot, "preflight-")
+ if err != nil {
+ return nil, err
+ }
+ l, cleanup, err := r.constructDirect(ctx, paseo.Selection{ConnectionID: b.LocalID, Provider: b.Provider, Family: b.Family, Model: b.Model, AccountID: b.AccountID}, work, "implement")
+ if err == nil {
+ report.IsolationConfigHash = l.Policy.Hash
+ // Certification is a release gate. Do not advertise an uncertified route.
+ if certifiedDirect(b.Provider, b.ExpectedIdentity.ProviderVersion, l.Policy.Hash) {
+ _, err = r.launchers[b.Provider].Preflight(ctx, l.Binding, l.Policy)
+ if err == nil {
+ report.Available = true
+ report.ReadIsolation = true
+ report.UnavailableReason = ""
+ report.Routing.ObservedAccountID = b.AccountID
+ report.Routing.AccountPinned = true
+ report.Routing.NoFailover = true
+ report.Routing.TimelineRecovery = true
+ report.Routing.ProcessOwnership = true
+ }
+ }
+ }
+ if cleanup != nil {
+ if e := cleanup(); e != nil {
+ return nil, e
+ }
+ }
+ if e := os.RemoveAll(work); e != nil {
+ return nil, e
+ }
+ reports = append(reports, report)
+ }
+ return reports, nil
+}
diff --git a/internal/runner/runtime_workflow.go b/internal/runner/runtime_workflow.go
index b552acc9..32667124 100644
--- a/internal/runner/runtime_workflow.go
+++ b/internal/runner/runtime_workflow.go
@@ -84,7 +84,7 @@ func (r *Runtime) wire(ctx context.Context) error {
if err != nil {
return err
}
- bs, err := loadBindings(r.cfg.AccountBindingsPath)
+ bs, err := loadDirectBindings(r.cfg.AccountBindingsPath)
if err != nil {
return err
}
@@ -110,7 +110,7 @@ func (r *Runtime) wire(ctx context.Context) error {
}
return team.GitCandidate{}, paseo.ErrIdentity
}
- return checks.New(checks.Config{ScratchRoot: r.cfg.ScratchRoot, Scope: c.Scope, Handle: c.Handle, Deadline: deadline, Policy: policy, DefinitionHash: checks.Digest(marshal(d)), ReproductionHash: checks.Digest(marshal(repro)), Reproduction: func(_ context.Context, hash string) (checks.Reproduction, error) {
+ return checks.New(checks.Config{ScratchRoot: r.cfg.WorkspaceRoot, Scope: c.Scope, Handle: c.Handle, Deadline: deadline, Policy: policy, DefinitionHash: checks.Digest(marshal(d)), ReproductionHash: checks.Digest(marshal(repro)), Reproduction: func(_ context.Context, hash string) (checks.Reproduction, error) {
if hash != checks.Digest(marshal(repro)) {
return checks.Reproduction{}, paseo.ErrIdentity
}
@@ -161,7 +161,7 @@ func (r *Runtime) wire(ctx context.Context) error {
}
raw := marshal(d)
return runnerproto.PreparedBug{CheckDefinition: raw, CheckDefinitionHash: checks.Digest(raw), BaselineTestSetHash: d.Baseline.Hash}, nil
- }}, r.client)
+ }})
if err != nil {
return err
}
@@ -177,11 +177,11 @@ func (r *Runtime) wire(ctx context.Context) error {
return r.api.Call(ctx, "validate", claimRequest(c, "publish-validate"), nil)
}, Export: manager.ExportCandidate, Credential: credentials.credential, Description: unavailableDescription{}})
}
- workflow, err := NewBugWorkflow(BugWorkflowConfig{Workspaces: manager, Client: r.client, Witness: w, Policy: r.policy, Executor: executor, PublisherFor: publisherFor, StateDir: r.cfg.StateDir, Executable: r.cfg.Executable, InstanceID: r.cfg.InstanceID, Copy: r.cfg.Copy})
+ workflow, err := NewBugWorkflow(BugWorkflowConfig{Workspaces: manager, Launchers: r.launchers, Namespaces: r.namespaces, Launch: r.directLaunch, Witness: w, Policy: r.policy, Executor: executor, PublisherFor: publisherFor, StateDir: r.cfg.StateDir, Executable: r.cfg.Executable, InstanceID: r.cfg.InstanceID, Copy: r.cfg.Copy})
if err != nil {
return err
}
- supervisor, err := NewSupervisor(SupervisorConfig{Journal: r.journal, Client: r.client, Inspector: r.inspector, API: r, Workflow: workflow, CredentialsPath: filepath.Join(r.cfg.StateDir, "credentials.json"), InstallCredentials: r.api.InstallCredentials})
+ supervisor, err := NewSupervisor(SupervisorConfig{Journal: r.journal, Namespaces: r.namespaces, API: r, Workflow: workflow, CredentialsPath: filepath.Join(r.cfg.StateDir, "credentials.json"), InstallCredentials: r.api.InstallCredentials})
if err != nil {
return err
}
diff --git a/internal/runner/service.go b/internal/runner/service.go
index af2f2e95..2c273aab 100644
--- a/internal/runner/service.go
+++ b/internal/runner/service.go
@@ -154,15 +154,17 @@ func (s *Service) recoverClaims(ctx context.Context) error {
if json.Unmarshal(raw, &assignment) != nil {
return paseo.ErrIdentity
}
- record := &attemptState{Claim: RunClaim{Assignment: assignment, ClaimResponse: reply}, Phase: "recovering", Owner: ProcessOwner{LocalOnly: true, Attempt: reply.Handle.Attempt, Fence: reply.Handle.Fence, Marker: assignment.ID, Workspace: paseo.Workspace{Path: s.Supervisor.workflow.cfg.Workspaces.PreparationDirectory()}}}
+ record := &attemptState{Direct: s.Supervisor.namespaces != nil, Claim: RunClaim{Assignment: assignment, ClaimResponse: reply}, Phase: "recovering", Owner: ProcessOwner{LocalOnly: true, Attempt: reply.Handle.Attempt, Fence: reply.Handle.Fence, Marker: assignment.ID, Workspace: paseo.Workspace{Path: s.Supervisor.workflow.cfg.Workspaces.PreparationDirectory()}}}
if assignment.Kind != "prepare" {
record.Owner.Marker = attemptKey(reply.Scope, reply.Handle)
}
if err = s.Supervisor.save(ctx, record); err != nil {
return err
}
- if err = s.Supervisor.inspector.Track(ctx, record.Owner); err != nil {
- return err
+ if !record.Direct {
+ if err = s.Supervisor.inspector.Track(ctx, record.Owner); err != nil {
+ return err
+ }
}
}
return nil
diff --git a/internal/runner/supervisor.go b/internal/runner/supervisor.go
index fc3bb753..021296b8 100644
--- a/internal/runner/supervisor.go
+++ b/internal/runner/supervisor.go
@@ -11,7 +11,9 @@ import (
"time"
"amadan.net/oficina/equipo/internal/equipo/team"
+ "amadan.net/oficina/equipo/internal/runner/containment"
"amadan.net/oficina/equipo/internal/runner/paseo"
+ "amadan.net/oficina/equipo/internal/runner/provider"
"amadan.net/oficina/equipo/internal/runnerproto"
)
@@ -29,6 +31,9 @@ type RunClaim struct {
runnerproto.ClaimResponse
}
type attemptState struct {
+ Direct bool
+ Session provider.Session
+ WorkspacePath string
InFlightAction team.ActionID
Claim RunClaim
Owner ProcessOwner
@@ -45,6 +50,7 @@ type attemptState struct {
// Authority is deliberately not restored from this record.
}
type SupervisorConfig struct {
+ Namespaces *containment.Manager
Journal *Journal
Client *paseo.Client
Inspector *LinuxProcessInspector
@@ -54,6 +60,11 @@ type SupervisorConfig struct {
InstallCredentials func(context.Context, runnerproto.CredentialRotation, string) error
}
type Supervisor struct {
+ leaseDone <-chan struct{}
+ leaseStop context.CancelFunc
+ activeRelease func() error
+ namespaces *containment.Manager
+ activeProxy *ToolProxy
journal *Journal
client CleanupClient
inspector ProcessInspector
@@ -75,13 +86,13 @@ type Supervisor struct {
}
func NewSupervisor(c SupervisorConfig) (*Supervisor, error) {
- if c.Journal == nil || c.Client == nil || c.Inspector == nil || c.API == nil || c.Workflow == nil || !filepath.IsAbs(c.CredentialsPath) || filepath.Clean(c.CredentialsPath) != c.CredentialsPath || c.InstallCredentials == nil {
+ if c.Journal == nil || c.Namespaces == nil || c.API == nil || c.Workflow == nil || !filepath.IsAbs(c.CredentialsPath) || filepath.Clean(c.CredentialsPath) != c.CredentialsPath || c.InstallCredentials == nil {
return nil, paseo.ErrContract
}
- if c.Workflow.cfg.Witness == nil || c.Workflow.cfg.Workspaces == nil || c.Workflow.cfg.Client != c.Client || c.Inspector.client != c.Client || c.Inspector.journal != c.Journal || c.Workflow.cfg.Witness.journal != c.Journal {
+ if c.Workflow.cfg.Witness == nil || c.Workflow.cfg.Workspaces == nil || (c.Workflow.cfg.Namespaces != c.Namespaces || len(c.Workflow.cfg.Launchers) != 2 || c.Workflow.cfg.Launch == nil) || c.Workflow.cfg.Witness.journal != c.Journal {
return nil, paseo.ErrContract
}
- return &Supervisor{journal: c.Journal, client: c.Client, inspector: c.Inspector, api: c.API, workflow: c.Workflow, clock: linuxClock{}, credentialsPath: c.CredentialsPath, installCredentials: c.InstallCredentials, states: map[string]*attemptState{}}, nil
+ return &Supervisor{namespaces: c.Namespaces, journal: c.Journal, client: c.Client, inspector: c.Inspector, api: c.API, workflow: c.Workflow, clock: linuxClock{}, credentialsPath: c.CredentialsPath, installCredentials: c.InstallCredentials, states: map[string]*attemptState{}}, nil
}
func attemptKey(scope team.Scope, h team.Handle) string {
return runnerproto.EventHash([]any{scope, h.Attempt, h.Fence, h.Runner})
@@ -96,7 +107,7 @@ func (s *Supervisor) Run(ctx context.Context, claim RunClaim) error {
// One active attempt also serializes runner-wide credential rotation.
s.runMu.Lock()
defer s.runMu.Unlock()
- if !s.ready {
+ if !s.ready || s.namespaces == nil {
return paseo.ErrUncertain
}
key := attemptKey(claim.Scope, claim.Handle)
@@ -119,7 +130,7 @@ func (s *Supervisor) Run(ctx context.Context, claim RunClaim) error {
if err != nil {
return err
}
- r := &attemptState{Claim: claim, Phase: "claimed"}
+ r := &attemptState{Direct: s.namespaces != nil, Claim: claim, Phase: "claimed"}
raw, err := json.Marshal(r)
if err != nil {
return err
@@ -146,11 +157,16 @@ func (s *Supervisor) Run(ctx context.Context, claim RunClaim) error {
s.activeKey = ""
s.activeCancel = nil
s.activeSocket = nil
+ s.activeProxy = nil
s.activeCurrent = nil
s.mu.Unlock()
}()
done := make(chan struct{})
- go s.watchLease(active, cancel, r, lease, done)
+ watchCtx, stopWatch := context.WithCancel(active)
+ s.leaseStop = stopWatch
+ s.leaseDone = done
+ defer stopWatch()
+ go s.watchLease(watchCtx, cancel, r, lease, done)
err = s.workflow.run(active, s, r, lease)
if err != nil {
err = errors.Join(err, context.Cause(active))
@@ -176,7 +192,11 @@ func (s *Supervisor) finishAttempt(cleanupCtx context.Context, r *attemptState,
}
bookkeepingErr := s.journal.finishTools(cleanupCtx, r.Claim, outcome)
if err != nil {
- if errors.Is(err, errTrialReconnect) {
+ if r.Direct && r.InFlightAction != 0 {
+ q := r.request("lost")
+ q.ActionID = r.InFlightAction
+ err = errors.Join(err, s.api.Call(cleanupCtx, "lost", q, nil))
+ } else if errors.Is(err, errTrialReconnect) {
// trialLost has already put the job into a charged human wait.
} else if infrastructureOnly(err, r) {
q := r.request("release")
@@ -247,12 +267,22 @@ func (s *Supervisor) watchLease(ctx context.Context, cancel context.CancelCauseF
return
case err := <-reply:
if err != nil {
+ if ctx.Err() != nil {
+ return
+ }
cancel(attemptCancellation{"watchLease.renew", err})
return
}
s.mu.Lock()
+ proxy := s.activeProxy
socket := s.activeSocket
s.mu.Unlock()
+ if proxy != nil {
+ if err = proxy.RenewLease(ctx, l.bound()); err != nil {
+ cancel(err)
+ return
+ }
+ }
if socket != nil {
if err = socket.RenewLease(ctx, l.bound()); err != nil {
cancel(attemptCancellation{"watchLease.RenewLease", err})
@@ -299,6 +329,9 @@ func (s *Supervisor) Cancel(ctx context.Context, scope team.Scope, h team.Handle
return proof, errors.Join(stopErr, err)
}
func (s *Supervisor) cleanup(ctx context.Context, r *attemptState) (ContainmentProof, error) {
+ if r.Direct {
+ return s.cleanupDirect(ctx, r)
+ }
proof := ContainmentProof{Scope: r.Claim.Scope, Handle: r.Claim.Handle, Owner: r.Owner}
if r.Phase == "contained" && r.Proof != nil {
return *r.Proof, nil
@@ -362,7 +395,7 @@ func (s *Supervisor) cleanup(ctx context.Context, r *attemptState) (ContainmentP
return s.reportContainment(ctx, r)
}
func (s *Supervisor) reportContainment(ctx context.Context, r *attemptState) (ContainmentProof, error) {
- if r.Proof == nil || !r.Proof.Empty {
+ if r.Proof == nil || (r.Proof.Version != 2 && !r.Proof.Empty) {
return ContainmentProof{}, paseo.ErrUncertain
}
if err := s.cleanupSocket(ctx, r); err != nil {
@@ -393,8 +426,10 @@ func (s *Supervisor) finishRotation(ctx context.Context, r *attemptState) (Conta
if r.Proof == nil || r.Rotation == nil {
return ContainmentProof{}, paseo.ErrUncertain
}
- if err := s.inspector.Retire(ctx, r.Owner); err != nil {
- return *r.Proof, err
+ if !r.Direct {
+ if err := s.inspector.Retire(ctx, r.Owner); err != nil {
+ return *r.Proof, err
+ }
}
if r.Rotation.Bearer.Token != "" {
if s.credentialsPath == "" || s.installCredentials == nil {
@@ -414,6 +449,11 @@ func (s *Supervisor) Recover(ctx context.Context) error {
s.runMu.Lock()
defer s.runMu.Unlock()
s.ready = false
+ if s.namespaces != nil {
+ if _, err := s.journal.ReconcileDirect(ctx, s.namespaces); err != nil {
+ return err
+ }
+ }
var states []attemptState
if err := s.journal.readStates(ctx, "attempt", &states); err != nil {
return err
@@ -421,7 +461,7 @@ func (s *Supervisor) Recover(ctx context.Context) error {
var failures error
// Close historical records before scanning any unfinished attempt.
for _, r := range states {
- if r.Phase == "contained" || r.Rotation != nil {
+ if !r.Direct && s.inspector != nil && (r.Phase == "contained" || r.Rotation != nil) {
failures = errors.Join(failures, s.inspector.Retire(ctx, r.Owner))
}
}
@@ -430,13 +470,25 @@ func (s *Supervisor) Recover(ctx context.Context) error {
}
for i := range states {
r := &states[i]
+ if !r.Direct && r.Phase != "contained" && s.inspector == nil {
+ failures = errors.Join(failures, provider.ErrContainment)
+ continue
+ }
failures = errors.Join(failures, s.journal.finishTools(ctx, r.Claim, "interrupted"))
s.states[attemptKey(r.Claim.Scope, r.Claim.Handle)] = r
if restore, ok := s.api.(interface{ RestoreClaim(RunClaim) error }); ok {
failures = errors.Join(failures, restore.RestoreClaim(r.Claim))
}
if r.Phase != "contained" {
- failures = errors.Join(failures, s.trialLost(ctx, r))
+ if r.Direct {
+ if r.InFlightAction != 0 {
+ q := r.request("lost")
+ q.ActionID = r.InFlightAction
+ failures = errors.Join(failures, s.api.Call(ctx, "lost", q, nil))
+ }
+ } else {
+ failures = errors.Join(failures, s.trialLost(ctx, r))
+ }
if r.Phase != "completed" && r.Phase != "prepared" && r.Phase != "verified" {
stopErr := s.api.Call(ctx, "stop", r.request("stop"), nil)
if stopErr != nil {
@@ -526,3 +578,10 @@ func (s *Supervisor) cleanupInventory(ctx context.Context, o ProcessOwner) (Proc
}
return s.inspector.Remaining(ctx, o)
}
+
+func (s *Supervisor) stopLeaseWatch() {
+ if s.leaseStop != nil {
+ s.leaseStop()
+ <-s.leaseDone
+ }
+}
diff --git a/internal/runner/witness.go b/internal/runner/witness.go
index 8c12d80f..125ff316 100644
--- a/internal/runner/witness.go
+++ b/internal/runner/witness.go
@@ -140,7 +140,13 @@ func (w *Witness) Question(ctx context.Context, a runnerproto.Assignment, q runn
}
func (w *Witness) Containment(ctx context.Context, a runnerproto.Assignment, q runnerproto.RunnerRequest) error {
var proof ContainmentProof
- if json.Unmarshal(q.Proof, &proof) != nil || !proof.Empty || proof.Scope != q.Scope || proof.Handle != q.Handle || proof.Owner.Attempt != q.Handle.Attempt || proof.Owner.Fence != q.Handle.Fence || !proof.Inventory.CoverageKnown || len(proof.Inventory.Processes) != 0 || len(proof.Inventory.TerminalIDs) != 0 || proof.Inventory.BootID == "" || proof.Inventory.CheckedAt.IsZero() {
+ if json.Unmarshal(q.Proof, &proof) != nil {
+ return paseo.ErrIdentity
+ }
+ if proof.Scope != q.Scope || proof.Handle != q.Handle {
+ return paseo.ErrIdentity
+ }
+ if proof.Version != 2 && (!proof.Empty || proof.Scope != q.Scope || proof.Handle != q.Handle || proof.Owner.Attempt != q.Handle.Attempt || proof.Owner.Fence != q.Handle.Fence || !proof.Inventory.CoverageKnown || len(proof.Inventory.Processes) != 0 || len(proof.Inventory.TerminalIDs) != 0 || proof.Inventory.BootID == "" || proof.Inventory.CheckedAt.IsZero()) {
return paseo.ErrIdentity
}
var states []attemptState
diff --git a/internal/runner/workflow.go b/internal/runner/workflow.go
index 50d815e4..8bf8bf5e 100644
--- a/internal/runner/workflow.go
+++ b/internal/runner/workflow.go
@@ -10,16 +10,20 @@ import (
"amadan.net/oficina/equipo/internal/equipo/team"
"amadan.net/oficina/equipo/internal/runner/checks"
+ "amadan.net/oficina/equipo/internal/runner/containment"
"amadan.net/oficina/equipo/internal/runner/forge"
"amadan.net/oficina/equipo/internal/runner/paseo"
+ "amadan.net/oficina/equipo/internal/runner/provider"
"amadan.net/oficina/equipo/internal/runner/workspace"
"amadan.net/oficina/equipo/internal/runnerproto"
)
type BugWorkflowConfig struct {
- UsageProfile func(paseo.Selection) (UsageProfile, error)
+ Launchers map[string]provider.Launcher
+ Namespaces *containment.Manager
+ Launch func(context.Context, RunClaim, workspace.Workspace, *ToolProxy) (provider.Launch, func() error, error)
+
Workspaces *workspace.Manager
- Client *paseo.Client
Witness *Witness
Policy func(context.Context, paseo.Selection) (paseo.ReadPolicy, error)
Executor func(context.Context, RunClaim, checks.Definition, checks.Reproduction, time.Time) (*checks.Executor, error)
@@ -31,7 +35,7 @@ type BugWorkflowConfig struct {
type BugWorkflow struct{ cfg BugWorkflowConfig }
func NewBugWorkflow(c BugWorkflowConfig) (*BugWorkflow, error) {
- if c.Workspaces == nil || c.Client == nil || c.Witness == nil || c.Policy == nil || c.Executor == nil || (c.Publisher == nil && c.PublisherFor == nil) || !filepath.IsAbs(c.StateDir) || filepath.Clean(c.StateDir) != c.StateDir || !filepath.IsAbs(c.Executable) || filepath.Clean(c.Executable) != c.Executable || c.InstanceID == "" {
+ if c.Workspaces == nil || (len(c.Launchers) != 2 || c.Launchers["claude"] == nil || c.Launchers["codex"] == nil || c.Namespaces == nil || c.Launch == nil) || c.Witness == nil || c.Policy == nil || c.Executor == nil || (c.Publisher == nil && c.PublisherFor == nil) || !filepath.IsAbs(c.StateDir) || filepath.Clean(c.StateDir) != c.StateDir || !filepath.IsAbs(c.Executable) || filepath.Clean(c.Executable) != c.Executable || c.InstanceID == "" {
return nil, paseo.ErrContract
}
return &BugWorkflow{cfg: c}, nil
@@ -45,26 +49,19 @@ func (w *BugWorkflow) run(ctx context.Context, s *Supervisor, r *attemptState, l
runErr = errors.Join(runErr, context.Cause(ctx))
}
}()
+ if r.Direct {
+ ctx = s.namespaceContext(ctx, r)
+ key := attemptKey(r.Claim.Scope, r.Claim.Handle)
+ if err := s.namespaceEvent(ctx, r, "namespace.owner", key, key, map[string]string{"owner": key}); err != nil {
+ return err
+ }
+ }
if r.Claim.Assignment.Kind == "prepare" {
r.Owner = ProcessOwner{LocalOnly: true, Attempt: r.Claim.Handle.Attempt, Fence: r.Claim.Handle.Fence, Marker: r.Claim.Assignment.ID, Workspace: paseo.Workspace{Path: w.cfg.Workspaces.PreparationDirectory()}}
if err := s.save(ctx, r); err != nil {
return err
}
- if err := s.inspector.Track(ctx, r.Owner); err != nil {
- return err
- }
- var stopMonitoring func()
- ctx, stopMonitoring = monitorOwnership(ctx, s.inspector, r.Owner)
- s.monitorStop = stopMonitoring
- inspector, ok := s.inspector.(*LinuxProcessInspector)
- if !ok {
- return paseo.ErrContract
- }
- ctx = checks.WithProcessOwnership(ctx, r.Owner.Marker, func(ctx context.Context, pid int) error { return inspector.TrackPID(ctx, r.Owner, pid) })
- ctx = runnerproto.WithCommandOwnership(ctx, func(ctx context.Context, pid int, command string) error {
- return inspector.BeginCommand(ctx, r.Owner, pid, command)
- }, func(ctx context.Context, command string) error { return inspector.EndCommand(ctx, r.Owner, command) })
prepared, err := w.cfg.Witness.PrepareBug(ctx, w.cfg.Workspaces, r.Claim.Assignment, r.Claim.Brief.Target)
if err != nil {
return err
@@ -74,6 +71,7 @@ func (w *BugWorkflow) run(ctx context.Context, s *Supervisor, r *attemptState, l
if err != nil {
return err
}
+ s.stopLeaseWatch()
if err = s.api.Call(ctx, "prepare", q, nil); err != nil {
return err
}
@@ -85,9 +83,7 @@ func (w *BugWorkflow) run(ctx context.Context, s *Supervisor, r *attemptState, l
if err := s.save(ctx, r); err != nil {
return err
}
- if err := s.inspector.Track(ctx, r.Owner); err != nil {
- return err
- }
+
ws, err := w.cfg.Workspaces.Create(ctx, r.Claim.Assignment, r.Claim.Brief)
if err != nil {
return err
@@ -97,17 +93,16 @@ func (w *BugWorkflow) run(ctx context.Context, s *Supervisor, r *attemptState, l
if err = s.save(ctx, r); err != nil {
return err
}
- if err = s.inspector.Track(ctx, r.Owner); err != nil {
+
+ r.WorkspacePath = ws.Path
+ if err = s.save(ctx, r); err != nil {
return err
}
- ctx, stopMonitoring := monitorOwnership(ctx, s.inspector, r.Owner)
- s.monitorStop = stopMonitoring
- owner := r.Owner
+
policy, err := w.cfg.Policy(ctx, selection(r.Claim.Assignment))
if err != nil {
return err
}
- var socket *AttemptSocket
current := func(ctx context.Context) error {
_, err := l.checkClock(s.clock)
if err != nil {
@@ -119,18 +114,6 @@ func (w *BugWorkflow) run(ctx context.Context, s *Supervisor, r *attemptState, l
if err = retryAuthority(ctx, func() error { return s.api.Call(ctx, "validate", r.request("validate"), nil) }); err != nil {
return err
}
- if r.Agent.AgentID != "" {
- if err = s.journal.Ready(ctx, r.Agent); err != nil {
- return err
- }
- }
- inv, err := s.inspector.Remaining(ctx, owner)
- if err != nil {
- return err
- }
- if !inv.CoverageKnown {
- return paseo.ErrUncertain
- }
return nil
}
s.mu.Lock()
@@ -183,59 +166,7 @@ func (w *BugWorkflow) run(ctx context.Context, s *Supervisor, r *attemptState, l
}
if step == "reproduce" || step == "implement" || step == "review" {
- tool := map[string]string{"reproduce": "submit_reproduction", "implement": "submit_candidate", "review": "submit_review"}[step]
- r.Phase = "creating-socket"
- socket, err = NewPendingAttemptSocket(ctx, w.cfg.StateDir, ToolBinding{ReadPolicy: policy, Copy: w.cfg.Copy, InstanceID: w.cfg.InstanceID, TaskID: r.Claim.Assignment.TaskID, Attempt: int64(r.Claim.Handle.Attempt), Fence: r.Claim.Handle.Fence, Tools: []string{tool, "ask_person"}, LeaseDeadline: l.bound(), Agent: paseo.Agent{Provider: r.Claim.Assignment.Selection.Provider}, Isolation: r.Claim.Assignment.Selection.Isolation, Journal: s.journal, Current: current})
- if err != nil {
- return err
- }
- defer socket.Invalidate()
- s.mu.Lock()
- s.activeSocket = socket
- s.mu.Unlock()
- r.SocketPath = socket.SocketPath
- r.CapabilityPath = socket.CapabilityPath
- mcp, err := socket.MCPConfig(w.cfg.Executable)
- if err != nil {
- return err
- }
- mcp.Env["EQUIPO_ATTEMPT_MARKER"] = r.Owner.Marker
- r.Phase = "creating-agent"
- if err = s.save(ctx, r); err != nil {
- return err
- }
- env := ws.Environment()
- env["EQUIPO_ATTEMPT_MARKER"] = r.Owner.Marker
- options, err := w.cfg.Client.ProviderPolicy(ctx, selection(r.Claim.Assignment), policy)
- if err != nil {
- return err
- }
- agent, err := w.cfg.Client.CreateAgent(ctx, paseo.AgentRequest{ResourceID: paseo.CreationID("agent", r.request("agent").RequestID), ProviderOptions: options, Workspace: ws.Paseo, Selection: selection(r.Claim.Assignment), IdempotencyKey: r.request("agent").RequestID, ModeID: "default", ReadPolicy: policy, Env: env, MCPServers: map[string]paseo.MCPServer{"equipo": mcp}})
- if err != nil {
- return err
- }
- r.Agent = agent
- r.Owner.AgentID = agent.AgentID
- r.Phase = "tracking-agent"
- if err = s.save(ctx, r); err != nil {
- return err
- }
- if err = s.inspector.Track(ctx, r.Owner); err != nil {
- return err
- }
- // Keep the ownership key stable across creation; the agent identity is saved separately.
- r.Phase = "agent"
- if err = s.save(ctx, r); err != nil {
- return err
- }
- if err = socket.BindAgent(agent); err != nil {
- return err
- }
- if err = w.cfg.Witness.record(ctx, "session", attemptKey(r.Claim.Scope, r.Claim.Handle), agent); err != nil {
- return err
- }
- r.Phase = "turn"
- if err = w.modelTurn(ctx, s, r, l, current, socket, artifacts); err != nil {
+ if err = w.directModel(ctx, s, r, l, current, ws, policy, artifacts); err != nil {
return err
}
}
@@ -336,14 +267,7 @@ func (w *BugWorkflow) run(ctx context.Context, s *Supervisor, r *attemptState, l
}
}
if step == "reproduce" || step == "verify" {
- inspector, ok := s.inspector.(*LinuxProcessInspector)
- if !ok {
- return paseo.ErrContract
- }
- ctx = checks.WithProcessOwnership(ctx, r.Owner.Marker, func(ctx context.Context, pid int) error { return inspector.TrackPID(ctx, r.Owner, pid) })
- ctx = runnerproto.WithCommandOwnership(ctx, func(ctx context.Context, pid int, command string) error {
- return inspector.BeginCommand(ctx, r.Owner, pid, command)
- }, func(ctx context.Context, command string) error { return inspector.EndCommand(ctx, r.Owner, command) })
+
executor, err := w.cfg.Executor(ctx, r.Claim, definition, reproduction, r.Claim.AttemptDeadline)
if err != nil {
return err
@@ -385,6 +309,7 @@ func (w *BugWorkflow) run(ctx context.Context, s *Supervisor, r *attemptState, l
}
q := r.request("complete")
q.Result = &team.AttemptResult{Outcome: team.OutcomeSuccess}
+ s.stopLeaseWatch()
if err = s.api.Call(ctx, "complete", q, nil); err != nil {
return err
}
diff --git a/internal/runner/workflow_integration_test.go b/internal/runner/workflow_integration_test.go
index 74b7bbe8..786363b8 100644
--- a/internal/runner/workflow_integration_test.go
+++ b/internal/runner/workflow_integration_test.go
@@ -280,7 +280,7 @@ func runBugWorkflowMode(t *testing.T, reject bool, failover string) {
pinned = d
raw := marshal(d)
return runnerproto.PreparedBug{CheckDefinition: raw, CheckDefinitionHash: checks.Digest(raw), BaselineTestSetHash: d.Baseline.Hash}, nil
- }}, client)
+ }})
wfMust(t, err)
prepared, err := manager.Prepare(ctx, target)
wfMust(t, err)
@@ -334,7 +334,7 @@ func runBugWorkflowMode(t *testing.T, reject bool, failover string) {
return forge.Credential{Remote: "https://amadan.net/test/fixture", Agent: "test~person@example.test", Bearer: "fixture-only"}, nil
}, Description: &workflowDescription{}})
wfMust(t, err)
- workflow, err := NewBugWorkflow(BugWorkflowConfig{Publisher: publisher, Workspaces: manager, Client: client, Witness: w, Policy: func(context.Context, paseo.Selection) (paseo.ReadPolicy, error) { return policy, nil }, Executor: executor, StateDir: state, Executable: "/bin/false", InstanceID: "instance", Copy: ToolCopy{Accepted: "accepted", Rejected: "rejected"}})
+ workflow, err := NewBugWorkflow(BugWorkflowConfig{Publisher: publisher, Workspaces: manager, Witness: w, Policy: func(context.Context, paseo.Selection) (paseo.ReadPolicy, error) { return policy, nil }, Executor: executor, StateDir: state, Executable: "/bin/false", InstanceID: "instance", Copy: ToolCopy{Accepted: "accepted", Rejected: "rejected"}})
wfMust(t, err)
s, err := NewSupervisor(SupervisorConfig{Journal: j, Client: client, Inspector: inspector, API: api, Workflow: workflow, CredentialsPath: filepath.Join(state, "credentials"), InstallCredentials: func(context.Context, runnerproto.CredentialRotation, string) error { return nil }})
wfMust(t, err)
diff --git a/internal/runner/workflow_turn.go b/internal/runner/workflow_turn.go
index 4effcf93..9db93af6 100644
--- a/internal/runner/workflow_turn.go
+++ b/internal/runner/workflow_turn.go
@@ -4,7 +4,6 @@ import (
"context"
"encoding/json"
"path/filepath"
- "strconv"
"time"
"amadan.net/oficina/equipo/internal/equipo/team"
@@ -12,256 +11,6 @@ import (
"amadan.net/oficina/equipo/internal/runnerproto"
)
-func (w *BugWorkflow) modelTurn(ctx context.Context, s *Supervisor, r *attemptState, l *leaseGuard, current func(context.Context) error, socket *AttemptSocket, artifacts []team.Artifact) (turnErr error) {
- defer func() { turnErr = s.trialTurnError(ctx, r, turnErr) }()
- if err := s.journal.BeginReplay(ctx, r.Agent); err != nil {
- return err
- }
- sub, err := w.cfg.Client.Subscribe(ctx, r.Agent, paseo.Cursor{})
- if err != nil {
- return err
- }
- defer sub.Close(context.WithoutCancel(ctx))
- var usage *UsageAccumulator
- if w.cfg.UsageProfile != nil {
- profile, err := w.cfg.UsageProfile(selection(r.Claim.Assignment))
- if err != nil {
- return err
- }
- usage = NewUsageAccumulator(profile)
- }
- var action team.ActionID
- pump := EventPump{Journal: s.journal, Upload: func(ctx context.Context, e Event) error {
- q := r.request(e.ID)
- q.RequestID = e.ID
- var err error
- q.Event, err = runnerproto.Marshal(e)
- if err != nil {
- return err
- }
- q.ActionID = e.ActionID
- return s.api.Call(ctx, "events", q, nil)
- }, Contain: func(context.Context) error { return paseo.ErrUncertain }}
- observed := func(e paseo.Event) error {
- if e.ServerID != r.Agent.ServerID || e.AgentID != r.Agent.AgentID || e.ProviderSessionID != r.Agent.ProviderSessionID {
- return paseo.ErrIdentity
- }
- event := Event{Version: 1, ID: runnerproto.EventHash(e), TaskID: r.Claim.Assignment.TaskID, AssignmentID: r.Claim.Assignment.ID, ServerID: e.ServerID, AgentID: e.AgentID, SessionID: e.ProviderSessionID, Epoch: e.Epoch, Kind: e.Kind, TurnID: e.TurnID, RequestID: e.PermissionID, Sequence: e.Sequence, Scope: r.Claim.Scope, Handle: r.Claim.Handle, ActionID: action, Payload: e.Payload, SourceTime: time.Now().UTC(), Isolation: r.Claim.Assignment.Selection.Isolation}
- var prior []byte
- if err := s.journal.db.QueryRowContext(ctx, "SELECT body FROM journal_events WHERE event_key=?", event.DedupKey()).Scan(&prior); err == nil {
- var saved Event
- if json.Unmarshal(prior, &saved) != nil {
- return ErrJournal
- }
- event.SourceTime = saved.SourceTime
- }
- if event.Kind == "turn_completed" || event.Kind == "turn_failed" {
- if action == 0 {
- return paseo.ErrUncertain
- }
- outcome := team.OutcomeSuccess
- if event.Kind == "turn_failed" {
- outcome = team.OutcomeFailure
- }
- // Unknown token counts retain their reservation. No inferred usage receipt.
- receipt := team.Receipt{ID: e.TurnID, Outcome: outcome, Provider: r.Agent.Provider, Model: r.Agent.Model}
- if usage != nil {
- receipt.Usage = usage.ObservePaseo(e)
- }
- key := runnerproto.EventHash([]any{r.Claim.Scope, r.Claim.Handle.Attempt, r.Claim.Handle.Fence, action})
- if err := w.cfg.Witness.record(ctx, "receipt", key, receipt); err != nil {
- return err
- }
- }
- if err := pump.Append(ctx, event, nil); err != nil {
- return err
- }
- return pump.Flush(ctx, 128)
- }
- ready := false
- for !ready {
- select {
- case <-ctx.Done():
- return ctx.Err()
- case err, ok := <-sub.Ready:
- if !ok || err != nil {
- return paseo.ErrNotReady
- }
- ready = true
- case e, ok := <-sub.Events:
- if !ok {
- return paseo.ErrUncertain
- }
- if err := observed(e); err != nil {
- return err
- }
- }
- }
- // Drain the refetch before marking the subscription ready.
- for {
- select {
- case e, ok := <-sub.Events:
- if !ok {
- return paseo.ErrUncertain
- }
- if err := observed(e); err != nil {
- return err
- }
- default:
- goto drained
- }
- }
-drained:
- cursor, err := s.journal.Cursor(ctx, r.Agent)
- if err != nil || cursor.Epoch == "" {
- return paseo.ErrNotReady
- }
- if err = s.journal.BeginReplay(ctx, r.Agent); err != nil {
- return err
- }
- if err = s.journal.Recovered(ctx, r.Agent, cursor); err != nil {
- return err
- }
- event := Event{Version: 1, ID: r.request("ready").RequestID, TaskID: r.Claim.Assignment.TaskID, AssignmentID: r.Claim.Assignment.ID, ServerID: r.Agent.ServerID, AgentID: r.Agent.AgentID, SessionID: r.Agent.ProviderSessionID, Epoch: cursor.Epoch, Kind: "timeline_ready", Scope: r.Claim.Scope, Handle: r.Claim.Handle, Payload: json.RawMessage(`{}`), SourceTime: time.Now().UTC(), Isolation: r.Claim.Assignment.Selection.Isolation}
- if err = pump.Append(ctx, event, nil); err != nil {
- return err
- }
- if err = pump.Flush(ctx, 128); err != nil {
- return err
- }
- message, err := buildTurnPrompt(r.Claim, artifacts)
- if err != nil {
- return err
- }
- turn := 0
- dispatch := func() error {
- if turn >= 24 {
- return team.ErrQuota
- }
- if err := current(ctx); err != nil {
- return err
- }
- suffix := strconv.Itoa(turn)
- payload, err := turnIntentPayload(r.Agent.Provider, r.Agent.Model, message)
- if err != nil {
- return err
- }
- q := r.request("turn-intent-" + suffix)
- q.Intent = &team.IntentSpec{Key: q.RequestID, Operation: team.OpProviderCall, Payload: payload, Reserve: team.Usage{Calls: 1, InputTokens: 32000, OutputTokens: 4000, CostUnavailable: true}}
- var intent team.ActionID
- if err := retryAuthority(ctx, func() error { return s.api.Call(ctx, "intend", q, &intent) }); err != nil {
- return err
- }
- action = intent
- q = r.request("turn-admit-" + suffix)
- q.ActionID = action
- dir := filepath.Join(w.cfg.StateDir, "admissions")
- if err := runnerproto.JournalAdmission(dir, q); err != nil {
- return err
- }
- var ticket team.AdmissionTicket
- if err := retryAuthority(ctx, func() error { return s.api.Call(ctx, "admit", q, &ticket) }); err != nil {
- return err
- }
- r.InFlightAction = action
- if err := s.save(ctx, r); err != nil {
- return err
- }
- if err := current(ctx); err != nil {
- return err
- }
- if err := runnerproto.ConsumeTicket(dir, q.RequestID, ticket, time.Now().UTC(), ticket.Incarnation); err != nil {
- return err
- }
- return sendAdmittedTurn(ctx, func() error { return w.cfg.Client.Send(ctx, r.Agent, message, q.RequestID) }, func(reportCtx context.Context) error {
- lost := r.request("turn-lost-" + suffix)
- lost.ActionID = action
- return s.api.Call(reportCtx, "lost", lost, nil)
- })
- }
- if err = dispatch(); err != nil {
- return err
- }
- for {
- select {
- case <-ctx.Done():
- return ctx.Err()
- case e, ok := <-sub.Events:
- if !ok {
- return paseo.ErrUncertain
- }
- if err = observed(e); err != nil {
- return err
- }
- if e.Kind == "permission_requested" {
- question, err := QuestionFromEvent(e, runnerproto.EventHash(e), r.Claim.Assignment.TaskID, nil)
- if err != nil {
- return err
- }
- question.AssignmentID = r.Claim.Assignment.ID
- question.Attempt = int64(r.Claim.Handle.Attempt)
- question.Fence = r.Claim.Handle.Fence
- question.ExpiresAt = l.bound()
- if err = w.cfg.Witness.record(ctx, "question", question.ID, question); err != nil {
- return err
- }
- q := r.request("question-" + question.ID)
- q.Question = &question
- var saved runnerproto.Question
- if err = s.api.Call(ctx, "questions", q, &saved); err != nil {
- return err
- }
- relay := QuestionRelay{Journal: s.journal, Client: w.cfg.Client, Agent: r.Agent, Current: func(ctx context.Context, _ runnerproto.Question) (time.Time, error) {
- err := current(ctx)
- return l.bound(), err
- }}
- if err = relay.Wait(ctx, saved, func(ctx context.Context) (*runnerproto.QuestionAnswer, error) {
- var answers []runnerproto.Question
- err := retryAuthority(ctx, func() error { return s.api.Call(ctx, "answers", r.request("answers"), &answers) })
- if err != nil {
- return nil, err
- }
- for _, a := range answers {
- if a.ID == saved.ID {
- return a.Answer, nil
- }
- }
- return nil, nil
- }, func(context.Context) error { return paseo.ErrUncertain }); err != nil {
- return err
- }
- }
- if e.Kind == "turn_completed" || e.Kind == "turn_failed" {
- r.InFlightAction = 0
- if err := s.save(ctx, r); err != nil {
- return err
- }
- }
- if e.Kind == "turn_failed" {
- return team.ErrEvidence
- }
- if e.Kind == "turn_completed" {
- answer, asked, err := w.personFollowup(ctx, s, r, l, current)
- if err != nil {
- return err
- }
- if !asked {
- return nil
- }
- var prompt map[string]any
- if json.Unmarshal([]byte(message), &prompt) != nil {
- return paseo.ErrContract
- }
- prompt["person_answer"] = answer
- message = string(marshal(prompt))
- turn++
- if err = dispatch(); err != nil {
- return err
- }
- }
- }
- }
-}
func (w *BugWorkflow) publish(ctx context.Context, s *Supervisor, r *attemptState, current func(context.Context) error) error {
var publication team.Publication
if err := s.api.Call(ctx, "publication_ready", r.request("publication-ready"), &publication); err != nil {
diff --git a/internal/runner/workspace/direct.go b/internal/runner/workspace/direct.go
new file mode 100644
index 00000000..ddf8780a
--- /dev/null
+++ b/internal/runner/workspace/direct.go
@@ -0,0 +1,66 @@
+package workspace
+
+import (
+ "context"
+ "os"
+ "path/filepath"
+ "strings"
+
+ "amadan.net/oficina/equipo/internal/runner/paseo"
+ "amadan.net/oficina/equipo/internal/runnerproto"
+)
+
+func (m *Manager) Remove(_ context.Context, a runnerproto.Assignment, path string) error {
+ m.mu.Lock()
+ defer m.mu.Unlock()
+ var at attempt
+ if load(filepath.Join(m.cfg.PrivateRoot, "attempt-"+digest(a.WorkspaceKey), "attempt.json"), &at) != nil || !at.Local || at.AssignmentHash != digest(a) || at.Workspace.Path != path || filepath.Dir(path) != m.cfg.WorkspaceRoot {
+ return paseo.ErrIdentity
+ }
+ resolved, err := canonical(path)
+ if err != nil || resolved != path {
+ return paseo.ErrIdentity
+ }
+ return os.RemoveAll(path)
+}
+
+func (m *Manager) localGitdir(at attempt) (string, error) {
+ dir := filepath.Join(at.Workspace.Path, ".git")
+ if at.Request.Path != at.Workspace.Path || at.Workspace.WorkspaceID == "" {
+ return "", paseo.ErrIdentity
+ }
+ info, err := os.Lstat(dir)
+ if err != nil || !info.IsDir() {
+ return "", paseo.ErrIdentity
+ }
+ config, err := regular(filepath.Join(dir, "config"))
+ if err != nil || at.ConfigHash == "" || digest(config) != at.ConfigHash {
+ return "", paseo.ErrIdentity
+ }
+ err = filepath.WalkDir(dir, func(path string, entry os.DirEntry, err error) error {
+ if err != nil {
+ return err
+ }
+ rel, err := filepath.Rel(dir, path)
+ if err != nil || entry.Type()&os.ModeSymlink != 0 || (!entry.IsDir() && !entry.Type().IsRegular()) {
+ return paseo.ErrIdentity
+ }
+ if rel == "commondir" || rel == "gitdir" || rel == "config.worktree" || rel == "worktrees" || rel == "objects/info/alternates" || rel == "objects/info/http-alternates" || strings.HasPrefix(rel, "hooks/") {
+ return paseo.ErrIdentity
+ }
+ return nil
+ })
+ return dir, err
+}
+
+func (m *Manager) RemoveCheck(work string) error {
+ root := filepath.Dir(work)
+ if filepath.Base(work) != "work" || filepath.Dir(root) != m.cfg.WorkspaceRoot || !strings.HasPrefix(filepath.Base(root), "checks-") {
+ return paseo.ErrIdentity
+ }
+ resolved, err := canonical(root)
+ if err != nil || resolved != root {
+ return paseo.ErrIdentity
+ }
+ return os.RemoveAll(root)
+}
diff --git a/internal/runner/workspace/direct_test.go b/internal/runner/workspace/direct_test.go
new file mode 100644
index 00000000..53d80d00
--- /dev/null
+++ b/internal/runner/workspace/direct_test.go
@@ -0,0 +1,92 @@
+package workspace
+
+import (
+ "os"
+ "path/filepath"
+ "testing"
+)
+
+func TestDirectWorkspaceIdentity(t *testing.T) {
+ f := setup(t)
+ var err error
+ f.m, err = New(f.cfg)
+ if err != nil {
+ t.Fatal(err)
+ }
+ w := f.create(t)
+ if w.ID != f.a.WorkspaceKey || w.Path == "" {
+ t.Fatal("missing local identity")
+ }
+ if git(t, w.Path, "rev-parse", "HEAD") != f.target.BaseRevision || git(t, w.Path, "branch", "--show-current") != f.target.Ref {
+ t.Fatal("base or ref changed")
+ }
+ dir := filepath.Join(w.Path, ".git")
+ if info, e := os.Lstat(dir); e != nil || !info.IsDir() {
+ t.Fatal("metadata escapes checkout")
+ }
+ if git(t, w.Path, "rev-parse", "--git-common-dir") != ".git" {
+ t.Fatal("external common directory")
+ }
+ if e := f.m.ValidateTurn(ctx, f.a, w); e != nil {
+ t.Fatal(e)
+ }
+ for _, field := range []string{"id", "path"} {
+ changed := w
+ if field == "id" {
+ changed.ID = "other"
+ } else {
+ changed.Path = f.root
+ }
+ if err := f.m.ValidateTurn(ctx, f.a, changed); err == nil {
+ t.Fatalf("accepted changed local workspace %s", field)
+ }
+ }
+ for _, name := range []string{"config", "hooks/pre-commit", "objects/info/alternates", "commondir"} {
+ t.Run(name, func(t *testing.T) {
+ path := filepath.Join(dir, name)
+ old, readErr := os.ReadFile(path)
+ if e := os.MkdirAll(filepath.Dir(path), 0700); e != nil {
+ t.Fatal(e)
+ }
+ put(t, path, "untrusted\n")
+ if e := f.m.ValidateTurn(ctx, f.a, w); e == nil {
+ t.Fatal("accepted untrusted Git metadata")
+ }
+ if readErr == nil {
+ put(t, path, string(old))
+ } else if e := os.Remove(path); e != nil {
+ t.Fatal(e)
+ }
+ })
+ }
+ put(t, filepath.Join(w.Path, "file"), "candidate\n")
+ git(t, w.Path, "commit", "-am", "candidate")
+ c, err := f.m.CaptureCandidate(ctx, w, f.target)
+ if err != nil {
+ t.Fatal(err)
+ }
+ put(t, filepath.Join(w.Path, "file"), "later\n")
+ git(t, w.Path, "commit", "-am", "later")
+ export := filepath.Join(f.root, "export")
+ if err = f.m.ExportCandidate(ctx, c, export); err != nil {
+ t.Fatal(err)
+ }
+ if got := git(t, export, "rev-parse", "HEAD"); got != c.Commit {
+ t.Fatal("export followed builder changes")
+ }
+ again, err := f.m.Create(ctx, f.a, f.brief)
+ if err != nil || again.ID != w.ID || again.Path != w.Path {
+ t.Fatalf("retry replaced workspace: %+v %v", again, err)
+ }
+ f.a.WorkspaceKey = "attempt-2"
+ next := f.create(t)
+ if next.Path == w.Path || git(t, next.Path, "rev-parse", "HEAD") != f.target.BaseRevision {
+ t.Fatal("attempt reused mutable checkout")
+ }
+ if err := os.RemoveAll(filepath.Join(next.Path, ".git")); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := f.m.Create(ctx, f.a, f.brief); err == nil {
+ t.Fatal("uncertain workspace replaced")
+ }
+}
diff --git a/internal/runner/workspace/workspace.go b/internal/runner/workspace/workspace.go
index 3c42151d..2e20fec6 100644
--- a/internal/runner/workspace/workspace.go
+++ b/internal/runner/workspace/workspace.go
@@ -56,12 +56,15 @@ type Manager struct {
mu sync.Mutex
}
type Workspace struct {
+ ID, Path string
Paseo paseo.Workspace
ArtifactHashes []string
Isolation team.IsolationSnapshot
key string
}
type attempt struct {
+ Local bool
+ ConfigHash string
AssignmentHash string
Hash string
Request paseo.WorkspaceRequest
@@ -74,14 +77,11 @@ type attempt struct {
var objectID = regexp.MustCompile(`^(?:[a-f0-9]{40}|[a-f0-9]{64})$`)
var packFile = regexp.MustCompile(`^pack-[a-f0-9]{40}(?:[a-f0-9]{24})?\.(pack|idx|rev)$`)
-func New(cfg Config, client *paseo.Client) (*Manager, error) {
- if client == nil {
- return nil, paseo.ErrContract
- }
- return newManager(cfg, client)
+func New(cfg Config) (*Manager, error) {
+ return newManager(cfg, nil)
}
func newManager(cfg Config, client workspaceClient) (*Manager, error) {
- if client == nil || cfg.Forge == nil || cfg.Policy == nil || cfg.Definitions == nil || !filepath.IsAbs(cfg.GitPath) {
+ if cfg.Forge == nil || cfg.Policy == nil || cfg.Definitions == nil || !filepath.IsAbs(cfg.GitPath) {
return nil, paseo.ErrContract
}
for _, p := range []string{cfg.PrivateRoot, cfg.WorkspaceRoot} {
@@ -330,6 +330,9 @@ func (m *Manager) preflight(ctx context.Context, a runnerproto.Assignment) (pase
if !allowed(m.cfg.WorkspaceRoot, p) {
return p, paseo.ErrPolicy
}
+ if m.client == nil {
+ return p, nil
+ }
c, e := m.client.Preflight(ctx, s, p)
if e != nil {
return p, e
@@ -450,6 +453,55 @@ func (m *Manager) Create(ctx context.Context, a runnerproto.Assignment, brief ru
if _, e = m.run(ctx, source, "checkout", "--detach", brief.Target.BaseRevision); e != nil {
return zero, e
}
+ if m.client == nil {
+ path := filepath.Join(m.cfg.WorkspaceRoot, "attempt-"+digest(a.WorkspaceKey))
+ if _, e = m.run(ctx, source, "worktree", "add", "-b", brief.Target.Ref, path, brief.Target.BaseRevision); e != nil {
+ return zero, e
+ }
+ // Detach the worktree metadata from the source before exposing the checkout.
+ gitfile, e := regular(filepath.Join(path, ".git"))
+ if e != nil {
+ return zero, e
+ }
+ metadata := strings.TrimSpace(strings.TrimPrefix(string(gitfile), "gitdir: "))
+ index, e := regular(filepath.Join(metadata, "index"))
+ if e != nil {
+ return zero, e
+ }
+ if e = os.Remove(filepath.Join(path, ".git")); e != nil {
+ return zero, e
+ }
+ if e = m.init(ctx, path, objectFormat(brief.Target.BaseRevision), false); e != nil {
+ return zero, e
+ }
+ if e = copyObjects(filepath.Join(source, ".git", "objects"), filepath.Join(path, ".git", "objects")); e != nil {
+ return zero, e
+ }
+ if _, e = m.run(ctx, path, "symbolic-ref", "HEAD", "refs/heads/"+brief.Target.Ref); e != nil {
+ return zero, e
+ }
+ if _, e = m.run(ctx, path, "update-ref", "refs/heads/"+brief.Target.Ref, brief.Target.BaseRevision); e != nil {
+ return zero, e
+ }
+ if e = os.WriteFile(filepath.Join(path, ".git", "index"), index, 0600); e != nil {
+ return zero, e
+ }
+ config, e := regular(filepath.Join(path, ".git", "config"))
+ if e != nil {
+ return zero, e
+ }
+ at = attempt{Local: true, ConfigHash: digest(config), AssignmentHash: digest(a), Hash: hash, Request: paseo.WorkspaceRequest{Path: path, ReadPolicy: policy}, Workspace: paseo.Workspace{WorkspaceID: a.WorkspaceKey, Path: path}, Target: brief.Target, ArtifactHashes: append([]string(nil), brief.ArtifactHashes...), Isolation: a.Selection.Isolation}
+ if e = m.validateWorkspace(at); e != nil {
+ return zero, e
+ }
+ if e = save(record, at); e != nil {
+ return zero, e
+ }
+ if e = os.RemoveAll(source); e != nil {
+ return zero, e
+ }
+ return localWorkspace(at, a.WorkspaceKey), nil
+ }
project, e := m.client.RegisterProject(ctx, paseo.ProjectRequest{Path: source, IdempotencyKey: "project-" + a.WorkspaceKey, Selection: selection(a), ReadPolicy: policy})
if e != nil {
return zero, e
@@ -489,7 +541,7 @@ func (m *Manager) Create(ctx context.Context, a runnerproto.Assignment, brief ru
} else if err = m.validateWorkspace(at); err != nil {
return zero, err
}
- return Workspace{Paseo: at.Workspace, ArtifactHashes: append([]string(nil), at.ArtifactHashes...), Isolation: at.Isolation, key: a.WorkspaceKey}, nil
+ return localWorkspace(at, a.WorkspaceKey), nil
}
func regular(path string) ([]byte, error) {
s, e := os.Lstat(path)
@@ -502,7 +554,13 @@ func regular(path string) ([]byte, error) {
}
return b, nil
}
+func localWorkspace(at attempt, key string) Workspace {
+ return Workspace{ID: at.Workspace.WorkspaceID, Path: at.Workspace.Path, Paseo: at.Workspace, ArtifactHashes: append([]string(nil), at.ArtifactHashes...), Isolation: at.Isolation, key: key}
+}
func (m *Manager) gitdir(at attempt) (string, error) {
+ if at.Local {
+ return m.localGitdir(at)
+ }
b, e := regular(filepath.Join(at.Workspace.Path, ".git"))
if e != nil || !strings.HasPrefix(string(b), "gitdir: ") {
return "", paseo.ErrIdentity
@@ -720,7 +778,7 @@ func (m *Manager) CaptureCandidate(ctx context.Context, w Workspace, target team
defer m.mu.Unlock()
var zero GitCandidate
var at attempt
- if w.key == "" || load(filepath.Join(m.cfg.PrivateRoot, "attempt-"+digest(w.key), "attempt.json"), &at) != nil || at.Workspace != w.Paseo || at.Target != target {
+ if w.key == "" || load(filepath.Join(m.cfg.PrivateRoot, "attempt-"+digest(w.key), "attempt.json"), &at) != nil || at.Workspace != w.Paseo || (at.Local && (w.ID != at.Workspace.WorkspaceID || w.Path != at.Workspace.Path)) || at.Target != target {
return zero, paseo.ErrIdentity
}
if e := m.validateWorkspace(at); e != nil {
@@ -862,7 +920,7 @@ func (m *Manager) ValidateTurn(ctx context.Context, a runnerproto.Assignment, w
m.mu.Lock()
defer m.mu.Unlock()
var at attempt
- if w.key == "" || w.key != a.WorkspaceKey || load(filepath.Join(m.cfg.PrivateRoot, "attempt-"+digest(w.key), "attempt.json"), &at) != nil || at.Workspace != w.Paseo || at.AssignmentHash != digest(a) {
+ if w.key == "" || w.key != a.WorkspaceKey || load(filepath.Join(m.cfg.PrivateRoot, "attempt-"+digest(w.key), "attempt.json"), &at) != nil || at.Workspace != w.Paseo || (at.Local && (w.ID != at.Workspace.WorkspaceID || w.Path != at.Workspace.Path)) || at.AssignmentHash != digest(a) {
return paseo.ErrIdentity
}
policy, err := m.preflight(ctx, a)
@@ -881,7 +939,7 @@ func (m *Manager) CheckoutCandidate(ctx context.Context, w Workspace, c GitCandi
m.mu.Lock()
defer m.mu.Unlock()
var at attempt
- if w.key == "" || load(filepath.Join(m.cfg.PrivateRoot, "attempt-"+digest(w.key), "attempt.json"), &at) != nil || at.Workspace != w.Paseo || at.Target.Repository != c.Repository || at.Target.BaseRevision != c.BaseCommit {
+ if w.key == "" || load(filepath.Join(m.cfg.PrivateRoot, "attempt-"+digest(w.key), "attempt.json"), &at) != nil || at.Workspace != w.Paseo || (at.Local && (w.ID != at.Workspace.WorkspaceID || w.Path != at.Workspace.Path)) || at.Target.Repository != c.Repository || at.Target.BaseRevision != c.BaseCommit {
return paseo.ErrIdentity
}
if err := m.validateWorkspace(at); err != nil {
diff --git a/internal/runnerproto/containment.go b/internal/runnerproto/containment.go
index ade28f08..4a3cf76c 100644
--- a/internal/runnerproto/containment.go
+++ b/internal/runnerproto/containment.go
@@ -30,6 +30,8 @@ type ProcessInventory struct {
CheckedAt time.Time `json:"checked_at"`
}
type ContainmentProof struct {
+ Namespaces []NamespaceExit `json:"namespaces,omitempty"`
+ CheckedAt time.Time `json:"checked_at,omitempty"`
// Zero identifies a historical proof without a version field.
Version int `json:"version,omitempty"`
Scope team.Scope `json:"scope"`
@@ -66,3 +68,17 @@ type NamespaceContainmentProof struct {
Namespaces []NamespaceExit `json:"namespaces"`
CheckedAt time.Time `json:"checked_at"`
}
+
+// NamespaceLaunch is authenticated runner evidence recorded before releasing init.
+type NamespaceLaunch struct {
+ ID, AttemptKey, OwnerKey, BootID, NamespaceID, ManifestHash, PolicyHash string
+ HostPID int
+ StartTicks uint64
+}
+
+func (n NamespaceLaunch) Valid(owner string) bool {
+ return n.OwnerKey == owner && n.ID != "" && n.AttemptKey != "" && n.BootID != "" && n.NamespaceID != "" && len(n.ManifestHash) == 64 && len(n.PolicyHash) == 64 && n.HostPID > 0 && n.StartTicks > 0
+}
+func (n NamespaceLaunch) Matches(x NamespaceExit) bool {
+ return n.ID == x.ID && n.AttemptKey == x.AttemptKey && n.BootID == x.BootID && n.NamespaceID == x.NamespaceID && n.ManifestHash == x.ManifestHash && n.HostPID == x.HostPID && n.StartTicks == x.StartTicks && !x.ObservedAt.IsZero()
+}