oficina / equipo Public

fix: close final review gaps in approvals and certification evidence

codex agent, operated by paul@keymail.dev pushed by claude agent, operated by paul@keymail.dev 8ff9cc202c76a4c07d0a02e87afe42a7ffb8e61c parent 488b79d
70 files changed, +2,577 −287
  • cmd/equipo-runner/direct_live.go +19 −0
  • cmd/equipo-runner/direct_live_disabled.go +9 −0
  • cmd/equipo-runner/main.go +2 −13
  • docs/live-gate.md +7 −5
  • docs/superpowers/plans/CONTROLLER-REPORT-plan-2b.md +1,195 −0
  • internal/directlive/certificate.go +3 −0
  • internal/directlive/certification_guards.go +30 −0
  • internal/directlive/certification_guards_test.go +126 −0
  • internal/directlive/driver.go +19 −11
  • internal/directlive/driver_test.go +21 −0
  • internal/directlive/generation.go +35 −68
  • internal/directlive/observations.go +1 −1
  • internal/directlive/probes.go +19 −5
  • internal/directlive/readback.go +67 −0
  • internal/directlive/recovery.go +8 −1
  • internal/directlive/staged_source.go +62 −0
  • internal/directlive/testdata/fake-cli.py +2 −2
  • internal/directlive/turn.go +7 −8
  • internal/equipo/approval_revoke.go +64 −0
  • internal/equipo/copy.go +3 −1
  • internal/equipo/questions.go +3 −0
  • internal/equipo/runner_events.go +3 −3
  • internal/equipo/templates/runners.html +1 −1
  • internal/equipotest/approval_once_test.go +33 −0
  • internal/equipotest/direct_boundaries_test.go +27 −0
  • internal/equipotest/direct_containment_test.go +9 −3
  • internal/release/refresh_test.go +1 −1
  • internal/runner/certified/policy.go +2 −1
  • internal/runner/certified_network_test.go +18 −0
  • internal/runner/checks/namespace.go +0 −1
  • internal/runner/containment/helper_version_test.go +77 −0
  • internal/runner/containment/linux.go +25 −7
  • internal/runner/containment/mounts.go +4 −3
  • internal/runner/containment/mounts_test.go +3 −0
  • internal/runner/diagnostics.go +3 −0
  • internal/runner/direct_admission.go +20 −0
  • internal/runner/direct_admission_test.go +61 −0
  • internal/runner/direct_answer_capture.go +10 −1
  • internal/runner/direct_events.go +4 −1
  • internal/runner/direct_runtime_test.go +19 −0
  • internal/runner/direct_tools_test.go +13 −1
  • internal/runner/direct_workflow.go +1 −6
  • internal/runner/egress/policy.go +6 −0
  • internal/runner/forge/approval_profile_test.go +37 −2
  • internal/runner/forge/description.go +3 −1
  • internal/runner/forge/description_test.go +16 −0
  • internal/runner/forge/description_transport.go +16 −0
  • internal/runner/forge/publisher.go +4 −2
  • internal/runner/journal.go +4 −1
  • internal/runner/preflight_cache_test.go +26 −0
  • internal/runner/provider/accounts.go +6 −0
  • internal/runner/provider/accounts_test.go +59 −0
  • internal/runner/provider/check_policy.go +2 −2
  • internal/runner/provider/claude/launcher_test.go +2 −2
  • internal/runner/provider/codex/answers.go +17 −0
  • internal/runner/provider/codex/answers_test.go +29 −0
  • internal/runner/provider/codex/launcher.go +6 −0
  • internal/runner/provider/codex/launcher_test.go +1 −1
  • internal/runner/provider/codex/native_approval.go +3 −121
  • internal/runner/provider/direct_certification.go +1 −1
  • internal/runner/provider/direct_certification_test.go +1 −1
  • internal/runner/provider/native_approval.go +141 −0
  • internal/runner/provider/native_json.go +90 −0
  • internal/runner/provider/native_overlay_test.go +23 −0
  • internal/runner/provider/runtime_home.go +32 −0
  • internal/runner/provider/types.go +3 −0
  • internal/runner/runtime.go +4 −0
  • internal/runner/service.go +1 −0
  • internal/runner/tool_journal.go +2 −2
  • internal/runnerproto/questions.go +6 −7
diff --git a/cmd/equipo-runner/direct_live.go b/cmd/equipo-runner/direct_live.go
new file mode 100644
index 00000000..9d5c8e60
--- /dev/null
+++ b/cmd/equipo-runner/direct_live.go
@@ -0,0 +1,19 @@
+//go:build direct_live
+
+package main
+
+import (
+ "amadan.net/oficina/equipo/internal/directlive"
+ "amadan.net/oficina/equipo/internal/runner/provider"
+ "context"
+)
+
+func directLiveWorker(ctx context.Context, args []string, getenv func(string) string) (bool, error) {
+ if len(args) != 2 || args[0] != "__direct-live-worker" {
+ return false, nil
+ }
+ if getenv("EQUIPO_LIVE_DIRECT") != "1" {
+ return true, provider.ErrPolicy
+ }
+ return true, directlive.RecoveryWorker(ctx, args[1])
+}
diff --git a/cmd/equipo-runner/direct_live_disabled.go b/cmd/equipo-runner/direct_live_disabled.go
new file mode 100644
index 00000000..31e3c25b
--- /dev/null
+++ b/cmd/equipo-runner/direct_live_disabled.go
@@ -0,0 +1,9 @@
+//go:build !direct_live
+
+package main
+
+import "context"
+
+func directLiveWorker(context.Context, []string, func(string) string) (bool, error) {
+ return false, nil
+}
diff --git a/cmd/equipo-runner/main.go b/cmd/equipo-runner/main.go
index e3bfc707..cc752412 100644
--- a/cmd/equipo-runner/main.go
+++ b/cmd/equipo-runner/main.go
@@ -10,7 +10,6 @@ import (
"os/signal"
"syscall"
- "amadan.net/oficina/equipo/internal/directlive"
"amadan.net/oficina/equipo/internal/equipo"
"amadan.net/oficina/equipo/internal/release"
"amadan.net/oficina/equipo/internal/runner"
@@ -23,22 +22,12 @@ func run(ctx context.Context, args []string, input io.Reader, output, errorOutpu
_, _ = fmt.Fprintf(errorOutput, equipo.CopyRunnerDiagnostic, code, variable)
return 1
}
- if len(args) == 2 && args[0] == "__direct-live-worker" {
- if getenv("EQUIPO_LIVE_DIRECT") != "1" {
- return fail(nil)
- }
- if err := directlive.RecoveryWorker(ctx, args[1]); err != nil {
+ if handled, err := directLiveWorker(ctx, args, getenv); handled {
+ if err != nil {
return fail(err)
}
return 0
}
- if len(args) == 2 && args[0] == "--socket" {
- if runner.ServeToolProxy(ctx, input, output, args[1]) != nil {
- _, _ = io.WriteString(errorOutput, equipo.CopyToolRejected+"\n")
- return 1
- }
- return 0
- }
if len(args) != 1 {
return fail(nil)
}
diff --git a/docs/live-gate.md b/docs/live-gate.md
index 5a51c3db..e5b939e1 100644
--- a/docs/live-gate.md
+++ b/docs/live-gate.md
@@ -26,11 +26,13 @@ collector uses a separate temporary journal and never opens production state.
The configured scratch root must have no existing namespace records. Only this
run's records and temporary homes are removed, after verified exit.
-When an auth host is named, the generation exercise appends whitespace to the
-selected login JSON without changing token values, then requires fresh preflight
-before another turn. A separate negative check temporarily changes Equipo's
-identity marker and restores it. This tests marker tampering; it does not claim
-to have changed the provider account.
+When an auth host is named, the generation exercise stages a copy of the
+selected login JSON with added whitespace. To test the configured source path,
+it swaps that copy in with an atomic rename, then restores the original bytes
+on success, failure or cancellation. The identity-marker check uses the same
+replacement and restoration path. Neither test changes token values or writes
+in place. These bounded source changes test the production binding; they do not
+claim to have changed the provider account.
The stdio helper is now a separate `equipo-tool-proxy` executable. Its digest is
part of provider policy. The namespace runner still embeds the manifest; the
diff --git a/docs/superpowers/plans/CONTROLLER-REPORT-plan-2b.md b/docs/superpowers/plans/CONTROLLER-REPORT-plan-2b.md
index d87c61da..63a71d8a 100644
--- a/docs/superpowers/plans/CONTROLLER-REPORT-plan-2b.md
+++ b/docs/superpowers/plans/CONTROLLER-REPORT-plan-2b.md
@@ -25697,3 +25697,1198 @@ Exit 0:
ok amadan.net/oficina/equipo/internal/runner/provider/claude 11.983s
```
+
+## A-m3
+
+containment/linux.go and mounts.go retain the verified bubblewrap descriptor through exec. The command executes /proc/self/fd/N. Replacing its pathname after manifest pinning cannot change the launched executable. The existing mount-swap fixture now also runs the manifest-pinning stage.
+
+Interpretations: The RED command is the same named test and package as the GREEN command. Mutations are compile-valid and restored. No new UI strings unless listed.
+
+### A-m3-red
+
+```text
+--- FAIL: TestBwrapRunsPinnedDescriptor (0.04s)
+ helper_version_test.go:58: executed replaced bwrap path namespace_startup_failed:
+FAIL
+rastrillo-budget/v1 ran 43ms
+FAIL amadan.net/oficina/equipo/internal/runner/containment 0.045s
+FAIL
+```
+
+### A-m3-green
+
+`CGO_ENABLED=0 go test ./internal/runner/containment -run ^TestBwrapRunsPinnedDescriptor$ -count=1`
+
+Exit 0:
+
+```text
+ok amadan.net/oficina/equipo/internal/runner/containment 0.064s
+```
+
+### A-m3-mutation
+
+`CGO_ENABLED=0 go test ./internal/runner/containment -run ^TestBwrapRunsPinnedDescriptor$ -count=1`
+
+Exit 1:
+
+```text
+--- FAIL: TestBwrapRunsPinnedDescriptor (0.04s)
+ helper_version_test.go:82: executed replaced bwrap path namespace_startup_failed:
+FAIL
+rastrillo-budget/v1 ran 44ms
+FAIL amadan.net/oficina/equipo/internal/runner/containment 0.047s
+FAIL
+```
+
+
+## A-m4
+
+provider/runtime_home.go checks an allowlist of runtime-home entries before BeginTurn and ValidatePolicy (resume). It rejects unexpected configuration, instruction, hook, plugin and skill entries, including nested entries and symlinks. Adapter fakes write a permitted history artifact instead of creating config files. Source fingerprint tests also verify stable identity and credential-generation invalidation.
+
+Interpretations: The runtime allowlist fails closed if a future CLI adds a new artifact. No live provider compatibility is claimed. Red: CGO_ENABLED=0 go test ./internal/runner/provider -run ^Test(RuntimeHomeRejectsPolicyInjection|RefreshDoesNotOverwriteNewerSource)$ -count=1.
+
+### A-m4-ledger-red
+
+```text
+--- FAIL: TestRuntimeHomeRejectsPolicyInjection (0.49s)
+ --- FAIL: TestRuntimeHomeRejectsPolicyInjection/config.tomlfalse (0.04s)
+ accounts_test.go:725: runtime policy injection accepted
+ --- FAIL: TestRuntimeHomeRejectsPolicyInjection/config.tomltrue (0.04s)
+ accounts_test.go:725: runtime policy injection accepted
+ --- FAIL: TestRuntimeHomeRejectsPolicyInjection/AGENTS.mdfalse (0.04s)
+ accounts_test.go:725: runtime policy injection accepted
+ --- FAIL: TestRuntimeHomeRejectsPolicyInjection/AGENTS.mdtrue (0.04s)
+ accounts_test.go:725: runtime policy injection accepted
+ --- FAIL: TestRuntimeHomeRejectsPolicyInjection/CLAUDE.mdfalse (0.04s)
+ accounts_test.go:725: runtime policy injection accepted
+ --- FAIL: TestRuntimeHomeRejectsPolicyInjection/CLAUDE.mdtrue (0.04s)
+ accounts_test.go:725: runtime policy injection accepted
+ --- FAIL: TestRuntimeHomeRejectsPolicyInjection/settings.jsonfalse (0.04s)
+ accounts_test.go:725: runtime policy injection accepted
+ --- FAIL: TestRuntimeHomeRejectsPolicyInjection/settings.jsontrue (0.04s)
+ accounts_test.go:725: runtime policy injection accepted
+ --- FAIL: TestRuntimeHomeRejectsPolicyInjection/hooksfalse (0.04s)
+ accounts_test.go:725: runtime policy injection accepted
+ --- FAIL: TestRuntimeHomeRejectsPolicyInjection/hookstrue (0.04s)
+ accounts_test.go:725: runtime policy injection accepted
+ --- FAIL: TestRuntimeHomeRejectsPolicyInjection/sessions/AGENTS.mdfalse (0.04s)
+ accounts_test.go:725: runtime policy injection accepted
+ --- FAIL: TestRuntimeHomeRejectsPolicyInjection/sessions/AGENTS.mdtrue (0.04s)
+ accounts_test.go:725: runtime policy injection accepted
+--- FAIL: TestRefreshDoesNotOverwriteNewerSource (0.05s)
+ accounts_test.go:732: new source overwritten by older refresh
+FAIL
+rastrillo-budget/v1 ran 540ms
+FAIL amadan.net/oficina/equipo/internal/runner/provider 0.542s
+FAIL
+```
+
+### A-m4-green
+
+`CGO_ENABLED=0 go test ./internal/runner/provider -run ^TestRuntimeHomeRejectsPolicyInjection$ -count=1`
+
+Exit 0:
+
+```text
+ok amadan.net/oficina/equipo/internal/runner/provider 0.494s
+```
+
+### A-m4-mutation
+
+`CGO_ENABLED=0 go test ./internal/runner/provider -run ^TestRuntimeHomeRejectsPolicyInjection$ -count=1`
+
+Exit 1:
+
+```text
+--- FAIL: TestRuntimeHomeRejectsPolicyInjection (0.49s)
+ --- FAIL: TestRuntimeHomeRejectsPolicyInjection/config.tomlfalse (0.04s)
+ accounts_test.go:739: runtime policy injection accepted
+ --- FAIL: TestRuntimeHomeRejectsPolicyInjection/config.tomltrue (0.04s)
+ accounts_test.go:739: runtime policy injection accepted
+ --- FAIL: TestRuntimeHomeRejectsPolicyInjection/AGENTS.mdfalse (0.04s)
+ accounts_test.go:739: runtime policy injection accepted
+ --- FAIL: TestRuntimeHomeRejectsPolicyInjection/AGENTS.mdtrue (0.04s)
+ accounts_test.go:739: runtime policy injection accepted
+ --- FAIL: TestRuntimeHomeRejectsPolicyInjection/CLAUDE.mdfalse (0.05s)
+ accounts_test.go:739: runtime policy injection accepted
+ --- FAIL: TestRuntimeHomeRejectsPolicyInjection/CLAUDE.mdtrue (0.04s)
+ accounts_test.go:739: runtime policy injection accepted
+ --- FAIL: TestRuntimeHomeRejectsPolicyInjection/settings.jsonfalse (0.04s)
+ accounts_test.go:739: runtime policy injection accepted
+ --- FAIL: TestRuntimeHomeRejectsPolicyInjection/settings.jsontrue (0.04s)
+ accounts_test.go:739: runtime policy injection accepted
+ --- FAIL: TestRuntimeHomeRejectsPolicyInjection/hooksfalse (0.04s)
+ accounts_test.go:739: runtime policy injection accepted
+ --- FAIL: TestRuntimeHomeRejectsPolicyInjection/hookstrue (0.04s)
+ accounts_test.go:739: runtime policy injection accepted
+ --- FAIL: TestRuntimeHomeRejectsPolicyInjection/sessions/AGENTS.mdfalse (0.04s)
+ accounts_test.go:739: runtime policy injection accepted
+ --- FAIL: TestRuntimeHomeRejectsPolicyInjection/sessions/AGENTS.mdtrue (0.04s)
+ accounts_test.go:739: runtime policy injection accepted
+FAIL
+rastrillo-budget/v1 ran 494ms
+FAIL amadan.net/oficina/equipo/internal/runner/provider 0.496s
+FAIL
+```
+
+
+## A-m5
+
+Startup failure waits for the known PID-1 descriptor before recording verified exit. Failed exit observation leaves an unverified proof. Both admission failure and a startup-error path with a known descriptor use the wait. The test injects an observation failure after a real pidfd wait and requires the persisted proof to remain unverified.
+
+Interpretations: The RED command is the same named test and package as the GREEN command. Mutations are compile-valid and restored. No new UI strings unless listed.
+
+### A-m5-red
+
+```text
+--- FAIL: TestNamespaceStartupFailureWaitsForInit (0.05s)
+ helper_version_test.go:70: PID 1 exit never observed on failed admission
+FAIL
+rastrillo-budget/v1 ran 53ms
+FAIL amadan.net/oficina/equipo/internal/runner/containment 0.054s
+FAIL
+```
+
+### A-m5-green
+
+`CGO_ENABLED=0 go test ./internal/runner/containment -run ^TestNamespaceStartupFailureWaitsForInit$ -count=1`
+
+Exit 0:
+
+```text
+ok amadan.net/oficina/equipo/internal/runner/containment 0.055s
+```
+
+### A-m5-mutation
+
+`CGO_ENABLED=0 go test ./internal/runner/containment -run ^TestNamespaceStartupFailureWaitsForInit$ -count=1`
+
+Exit 1:
+
+```text
+--- FAIL: TestNamespaceStartupFailureWaitsForInit (0.05s)
+ helper_version_test.go:114: PID 1 exit never observed on failed admission
+FAIL
+rastrillo-budget/v1 ran 54ms
+FAIL amadan.net/oficina/equipo/internal/runner/containment 0.056s
+FAIL
+```
+
+
+## A-m6
+
+NativeRequest, native approval validation and strict envelope decoding now live in neutral provider files. runnerproto no longer imports provider/codex. A go-list dependency test catches reintroducing that adapter dependency.
+
+Interpretations: This is a dependency refactor with unchanged native approval semantics. The compile-valid mutation imports the adapter back into runnerproto.
+
+### A-m678-red
+
+```text
+--- FAIL: TestDirectBinaryBoundaries (0.06s)
+ direct_boundaries_test.go:11: production binary links adapter/certification worker ../../cmd/equipo-runner
+--- FAIL: TestCheckPolicyNoRedundantRunner (0.00s)
+ direct_boundaries_test.go:16: unused runner mount retained
+FAIL
+rastrillo-budget/v1 ran 63ms
+FAIL amadan.net/oficina/equipo/internal/equipotest 0.110s
+FAIL
+```
+
+### A-m678-C-m-history-green
+
+`CGO_ENABLED=0 go test ./internal/equipotest -run '^Test(DirectBinaryBoundaries|CheckPolicyNoRedundantRunner|RunnerTrialHistoryLabel)$' -count=1`
+
+Exit 0:
+
+```text
+ok amadan.net/oficina/equipo/internal/equipotest 3.522s
+```
+
+### A-m6-mutation
+
+`CGO_ENABLED=0 go test ./internal/equipotest -run '^Test(DirectBinaryBoundaries|CheckPolicyNoRedundantRunner|RunnerTrialHistoryLabel)$' -count=1`
+
+Exit 1:
+
+```text
+2026/11/04 01:12:39 INFO Apply migrations. applied=[] skipped=24 adopted=false
+--- FAIL: TestDirectBinaryBoundaries (0.02s)
+ direct_boundaries_test.go:15: production binary links adapter/certification worker ../runnerproto
+FAIL
+rastrillo-budget/v1 ran 3.44s
+FAIL amadan.net/oficina/equipo/internal/equipotest 3.486s
+FAIL
+```
+
+
+## A-m7/m8
+
+Removed the runner --socket entry point; its integration test builds the standalone equipo-tool-proxy. Removed the redundant /opt/equipo-runner check-policy mount and mapping. The certification recovery worker is compiled only with direct_live. Default binary dependency tests reject linking internal/directlive.
+
+Interpretations: The RED command is the same named test and package as the GREEN command. Mutations are compile-valid and restored. No new UI strings unless listed.
+
+### A-m678-red
+
+```text
+--- FAIL: TestDirectBinaryBoundaries (0.06s)
+ direct_boundaries_test.go:11: production binary links adapter/certification worker ../../cmd/equipo-runner
+--- FAIL: TestCheckPolicyNoRedundantRunner (0.00s)
+ direct_boundaries_test.go:16: unused runner mount retained
+FAIL
+rastrillo-budget/v1 ran 63ms
+FAIL amadan.net/oficina/equipo/internal/equipotest 0.110s
+FAIL
+```
+
+### A-m678-C-m-history-green
+
+`CGO_ENABLED=0 go test ./internal/equipotest -run '^Test(DirectBinaryBoundaries|CheckPolicyNoRedundantRunner|RunnerTrialHistoryLabel)$' -count=1`
+
+Exit 0:
+
+```text
+ok amadan.net/oficina/equipo/internal/equipotest 3.522s
+```
+
+### A-m7-mutation
+
+`CGO_ENABLED=0 go test ./internal/equipotest -run '^Test(DirectBinaryBoundaries|CheckPolicyNoRedundantRunner|RunnerTrialHistoryLabel)$' -count=1`
+
+Exit 1:
+
+```text
+2026/11/04 01:12:43 INFO Apply migrations. applied=[] skipped=24 adopted=false
+--- FAIL: TestDirectBinaryBoundaries (0.06s)
+ direct_boundaries_test.go:15: production binary links adapter/certification worker ../../cmd/equipo-runner
+FAIL
+rastrillo-budget/v1 ran 3.48s
+FAIL amadan.net/oficina/equipo/internal/equipotest 3.528s
+FAIL
+```
+
+### A-m8-mutation
+
+`CGO_ENABLED=0 go test ./internal/equipotest -run '^Test(DirectBinaryBoundaries|CheckPolicyNoRedundantRunner|RunnerTrialHistoryLabel)$' -count=1`
+
+Exit 1:
+
+```text
+2026/11/04 01:12:48 INFO Apply migrations. applied=[] skipped=24 adopted=false
+--- FAIL: TestCheckPolicyNoRedundantRunner (0.00s)
+ direct_boundaries_test.go:24: unused runner mount retained
+FAIL
+rastrillo-budget/v1 ran 3.474s
+FAIL amadan.net/oficina/equipo/internal/equipotest 3.524s
+FAIL
+```
+
+
+## A-m9
+
+Disagreeing certified auth hosts produce an explicit conflict with provider and host names. Egress refuses that contract, and the runner exposes the fixed runner.certified_auth_conflict diagnostic code instead of an unexplained startup failure. The auth-host allowlist remains deferred.
+
+Interpretations: The RED command is the same named test and package as the GREEN command. Mutations are compile-valid and restored. No new UI strings unless listed.
+
+### A-m9-red
+
+```text
+--- FAIL: TestCertifiedNetworkConflictDiagnostic (0.00s)
+ certified_network_test.go:157: missing conflict diagnostic <nil>
+FAIL
+rastrillo-budget/v1 ran 0s
+FAIL amadan.net/oficina/equipo/internal/runner 0.003s
+FAIL
+```
+
+### A-m9-green
+
+`CGO_ENABLED=0 go test ./internal/runner -run ^TestCertifiedNetworkConflictDiagnostic$ -count=1`
+
+Exit 0:
+
+```text
+ok amadan.net/oficina/equipo/internal/runner 0.003s
+```
+
+### A-m9-mutation
+
+`CGO_ENABLED=0 go test ./internal/runner -run ^TestCertifiedNetworkConflictDiagnostic$ -count=1`
+
+Exit 1:
+
+```text
+--- FAIL: TestCertifiedNetworkConflictDiagnostic (0.00s)
+ certified_network_test.go:166: missing conflict diagnostic <nil>
+FAIL
+rastrillo-budget/v1 ran 0s
+FAIL amadan.net/oficina/equipo/internal/runner 0.003s
+FAIL
+```
+
+
+## Ledger: CommitRefresh
+
+Refuse refresh publication when the source generation observed before the probe differs from the lease generation. This prevents an old runtime refresh from overwriting a newer source login. The test verifies the newer fake source bytes survive.
+
+Interpretations: The RED command is the same named test and package as the GREEN command. Mutations are compile-valid and restored. No new UI strings unless listed.
+
+### A-m4-ledger-red
+
+```text
+--- FAIL: TestRuntimeHomeRejectsPolicyInjection (0.49s)
+ --- FAIL: TestRuntimeHomeRejectsPolicyInjection/config.tomlfalse (0.04s)
+ accounts_test.go:725: runtime policy injection accepted
+ --- FAIL: TestRuntimeHomeRejectsPolicyInjection/config.tomltrue (0.04s)
+ accounts_test.go:725: runtime policy injection accepted
+ --- FAIL: TestRuntimeHomeRejectsPolicyInjection/AGENTS.mdfalse (0.04s)
+ accounts_test.go:725: runtime policy injection accepted
+ --- FAIL: TestRuntimeHomeRejectsPolicyInjection/AGENTS.mdtrue (0.04s)
+ accounts_test.go:725: runtime policy injection accepted
+ --- FAIL: TestRuntimeHomeRejectsPolicyInjection/CLAUDE.mdfalse (0.04s)
+ accounts_test.go:725: runtime policy injection accepted
+ --- FAIL: TestRuntimeHomeRejectsPolicyInjection/CLAUDE.mdtrue (0.04s)
+ accounts_test.go:725: runtime policy injection accepted
+ --- FAIL: TestRuntimeHomeRejectsPolicyInjection/settings.jsonfalse (0.04s)
+ accounts_test.go:725: runtime policy injection accepted
+ --- FAIL: TestRuntimeHomeRejectsPolicyInjection/settings.jsontrue (0.04s)
+ accounts_test.go:725: runtime policy injection accepted
+ --- FAIL: TestRuntimeHomeRejectsPolicyInjection/hooksfalse (0.04s)
+ accounts_test.go:725: runtime policy injection accepted
+ --- FAIL: TestRuntimeHomeRejectsPolicyInjection/hookstrue (0.04s)
+ accounts_test.go:725: runtime policy injection accepted
+ --- FAIL: TestRuntimeHomeRejectsPolicyInjection/sessions/AGENTS.mdfalse (0.04s)
+ accounts_test.go:725: runtime policy injection accepted
+ --- FAIL: TestRuntimeHomeRejectsPolicyInjection/sessions/AGENTS.mdtrue (0.04s)
+ accounts_test.go:725: runtime policy injection accepted
+--- FAIL: TestRefreshDoesNotOverwriteNewerSource (0.05s)
+ accounts_test.go:732: new source overwritten by older refresh
+FAIL
+rastrillo-budget/v1 ran 540ms
+FAIL amadan.net/oficina/equipo/internal/runner/provider 0.542s
+FAIL
+```
+
+### Ledger-refresh-green
+
+`CGO_ENABLED=0 go test ./internal/runner/provider -run ^TestRefreshDoesNotOverwriteNewerSource$ -count=1`
+
+Exit 0:
+
+```text
+ok amadan.net/oficina/equipo/internal/runner/provider 0.044s
+```
+
+### Ledger-refresh-mutation
+
+`CGO_ENABLED=0 go test ./internal/runner/provider -run ^TestRefreshDoesNotOverwriteNewerSource$ -count=1`
+
+Exit 1:
+
+```text
+--- FAIL: TestRefreshDoesNotOverwriteNewerSource (0.05s)
+ accounts_test.go:752: new source overwritten by older refresh
+FAIL
+rastrillo-budget/v1 ran 52ms
+FAIL amadan.net/oficina/equipo/internal/runner/provider 0.053s
+FAIL
+```
+
+
+## B1-m
+
+Native approvals retain approvalId, additionalPermissions and networkApprovalContext. The full original request already travels through the person page and journal; network contexts and network overlays cannot be allowed. Unsupported Codex server requests receive protocol errors immediately; denying structured user input also writes a durable protocol error. Capture accepts only the fixed refusal shape.
+
+The driver stages changed bytes in a private temporary file, uses rename plus fsync to replace the selected source, and restores the original bytes on success, failure and cancellation. It never edits credentials or the identity marker in place. The full fake-driver test verifies both dedicated source homes remain byte-identical. Recovery and attempted identity-control turns consume call and token reservations; ordinary turns reserve before dispatch and settle known usage. Interrupted usage remains unknown in the artifacts.
+
+Probe paths name files, and the denial classifier rejects directory, missing-file and generic sandbox text as proof. Policy artifacts contain captured config/read and thread replies or Claude init frames. Codex policy values are derived from readback. Calibration uses charged counters and computed reservations, not literal pass values. ManifestCandidate compares provider and code-mode-host digests against the adapter pins.
+
+Interpretations: The permitted source-change fallback is necessary to test the exact configured production binding without changing its policy hash. Only staged file replacements are published, and deferred restoration runs on every returned path. This run uses fake homes only. Abrupt machine/process termination cannot execute a Go defer; the live-gate operator must retain the pre-run backup and inspect source homes after an interrupted gate. Missing FD alias targets are not certified: only explicit correlated permission refusals count. Claude init does not expose effective hooks, and currency-cap absence is not observed, so those checks remain not-certified. These are conservative release-gate limits, not fabricated passes. Recovery token reservations use ceil(JobInput/23) and ceil(JobOutput/23); unknown usage is not reported as measured zero.
+
+### B1-m-approval-red
+
+```text
+--- FAIL: TestNativeApprovalOverlay (0.00s)
+ native_overlay_test.go:6: approval overlay hidden
+FAIL
+rastrillo-budget/v1 ran 0s
+FAIL amadan.net/oficina/equipo/internal/runner/provider 0.003s
+--- FAIL: TestCodexRefusesUnsupportedRequests (0.63s)
+ --- FAIL: TestCodexRefusesUnsupportedRequests/item/permissions/requestApproval (0.15s)
+ answers_test.go:308: cannot refuse server request provider_policy_rejected
+ --- FAIL: TestCodexRefusesUnsupportedRequests/async/requestUserInput (0.15s)
+ answers_test.go:308: cannot refuse server request provider_policy_rejected
+ --- FAIL: TestCodexRefusesUnsupportedRequests/unlisted/request (0.14s)
+ answers_test.go:308: cannot refuse server request provider_policy_rejected
+ --- FAIL: TestCodexRefusesUnsupportedRequests/item/tool/requestUserInput (0.18s)
+ answers_test.go:308: cannot refuse server request provider_policy_rejected
+FAIL
+rastrillo-budget/v1 ran 628ms
+FAIL amadan.net/oficina/equipo/internal/runner/provider/codex 0.641s
+--- FAIL: TestDirectAnswerProtocolError (0.08s)
+ direct_tools_test.go:534: protocol refusal cannot pass durable capture runner.invalid
+FAIL
+rastrillo-budget/v1 ran 78ms
+FAIL amadan.net/oficina/equipo/internal/runner 0.081s
+FAIL
+```
+
+### B1-m-driver-red
+
+```text
+--- FAIL: TestGenerationUsesStagedSource (0.00s)
+ fixwave_test.go:9: generation would mutate source home
+--- FAIL: TestRecoveryChargesFunding (0.00s)
+ fixwave_test.go:16: recovery not charged 0 0 0
+--- FAIL: TestCandidateBinariesPinned (0.00s)
+ fixwave_test.go:22: foreign binary certified claude
+--- FAIL: TestProbeFileTargetsAndDenials (0.00s)
+ fixwave_test.go:25: directory probe /egress /egress
+FAIL
+rastrillo-budget/v1 ran 2ms
+FAIL amadan.net/oficina/equipo/internal/directlive 0.042s
+FAIL
+```
+
+### B1-m-readback-red
+
+```text
+--- FAIL: TestPolicyEvidenceRequiresObservedFrames (0.00s)
+ fixwave_test.go:88: requested policy became observed evidence
+--- FAIL: TestCalibrationRequiresChargedCalls (0.08s)
+ fixwave_test.go:94: uncounted calls certified
+FAIL
+rastrillo-budget/v1 ran 85ms
+FAIL amadan.net/oficina/equipo/internal/directlive 0.126s
+FAIL
+```
+
+### B1-m-overlay-green
+
+`CGO_ENABLED=0 go test ./internal/runner/provider -run ^TestNativeApprovalOverlay$ -count=1`
+
+Exit 0:
+
+```text
+ok amadan.net/oficina/equipo/internal/runner/provider 0.002s
+```
+
+### B1-m-overlay-mutation
+
+`CGO_ENABLED=0 go test ./internal/runner/provider -run ^TestNativeApprovalOverlay$ -count=1`
+
+Exit 1:
+
+```text
+--- FAIL: TestNativeApprovalOverlay (0.00s)
+ native_overlay_test.go:17: approval overlay hidden
+FAIL
+rastrillo-budget/v1 ran 0s
+FAIL amadan.net/oficina/equipo/internal/runner/provider 0.002s
+FAIL
+```
+
+### B1-m-network-green
+
+`CGO_ENABLED=0 go test ./internal/runner/provider -run ^TestNativeApprovalOverlay$ -count=1`
+
+Exit 0:
+
+```text
+ok amadan.net/oficina/equipo/internal/runner/provider 0.002s
+```
+
+### B1-m-network-mutation
+
+`CGO_ENABLED=0 go test ./internal/runner/provider -run ^TestNativeApprovalOverlay$ -count=1`
+
+Exit 1:
+
+```text
+--- FAIL: TestNativeApprovalOverlay (0.00s)
+ native_overlay_test.go:21: network approval accepted
+FAIL
+rastrillo-budget/v1 ran 0s
+FAIL amadan.net/oficina/equipo/internal/runner/provider 0.002s
+FAIL
+```
+
+### B1-m-decline-green
+
+`CGO_ENABLED=0 go test ./internal/runner/provider/codex -run ^TestCodexRefusesUnsupportedRequests$ -count=1`
+
+Exit 0:
+
+```text
+ok amadan.net/oficina/equipo/internal/runner/provider/codex 0.566s
+```
+
+### B1-m-decline-mutation
+
+`CGO_ENABLED=0 go test ./internal/runner/provider/codex -run ^TestCodexRefusesUnsupportedRequests$ -count=1`
+
+Exit 1:
+
+```text
+--- FAIL: TestCodexRefusesUnsupportedRequests (0.56s)
+ --- FAIL: TestCodexRefusesUnsupportedRequests/item/tool/requestUserInput (0.14s)
+ answers_test.go:314: cannot refuse server request provider_policy_rejected
+FAIL
+rastrillo-budget/v1 ran 558ms
+FAIL amadan.net/oficina/equipo/internal/runner/provider/codex 0.560s
+FAIL
+```
+
+### B1-m-unlisted-green
+
+`CGO_ENABLED=0 go test ./internal/runner/provider/codex -run ^TestCodexRefusesUnsupportedRequests$ -count=1`
+
+Exit 0:
+
+```text
+ok amadan.net/oficina/equipo/internal/runner/provider/codex 0.549s
+```
+
+### B1-m-unlisted-mutation
+
+`CGO_ENABLED=0 go test ./internal/runner/provider/codex -run ^TestCodexRefusesUnsupportedRequests$ -count=1`
+
+Exit 1:
+
+```text
+--- FAIL: TestCodexRefusesUnsupportedRequests (3.55s)
+ --- FAIL: TestCodexRefusesUnsupportedRequests/item/permissions/requestApproval (1.14s)
+ answers_test.go:327: request left hanging
+ --- FAIL: TestCodexRefusesUnsupportedRequests/async/requestUserInput (1.14s)
+ answers_test.go:327: request left hanging
+ --- FAIL: TestCodexRefusesUnsupportedRequests/unlisted/request (1.13s)
+ answers_test.go:327: request left hanging
+FAIL
+rastrillo-budget/v1 ran 3.549s
+FAIL amadan.net/oficina/equipo/internal/runner/provider/codex 3.551s
+FAIL
+```
+
+### B1-m-error-wire-green
+
+`CGO_ENABLED=0 go test ./internal/runner -run ^TestDirectAnswerProtocolError$ -count=1`
+
+Exit 0:
+
+```text
+ok amadan.net/oficina/equipo/internal/runner 0.102s
+```
+
+### B1-m-error-wire-mutation
+
+`CGO_ENABLED=0 go test ./internal/runner -run ^TestDirectAnswerProtocolError$ -count=1`
+
+Exit 1:
+
+```text
+--- FAIL: TestDirectAnswerProtocolError (0.07s)
+ direct_tools_test.go:538: protocol refusal cannot pass durable capture runner.invalid
+FAIL
+rastrillo-budget/v1 ran 70ms
+FAIL amadan.net/oficina/equipo/internal/runner 0.073s
+FAIL
+```
+
+### B1-m-stage-green
+
+`CGO_ENABLED=0 go test ./internal/directlive -run ^TestGenerationUsesStagedSource$ -count=1`
+
+Exit 0:
+
+```text
+ok amadan.net/oficina/equipo/internal/directlive 0.098s
+```
+
+### B1-m-stage-mutation
+
+`CGO_ENABLED=0 go test ./internal/directlive -run ^TestGenerationUsesStagedSource$ -count=1`
+
+Exit 1:
+
+```text
+--- FAIL: TestGenerationUsesStagedSource (0.02s)
+ certification_guards_test.go:35: staged binding {binding /home/paulca/t/e2b/TestGenerationUsesStagedSource1041771645/001/source fake codex false {fake fake 0.165.0} /home/paulca/t/e2b/TestGenerationUsesStagedSource1041771645/001/runtime <nil>}: provider_account_busy
+FAIL
+rastrillo-budget/v1 ran 24ms
+FAIL amadan.net/oficina/equipo/internal/directlive 0.071s
+FAIL
+```
+
+### B1-m-recovery-calls-green
+
+`CGO_ENABLED=0 go test ./internal/directlive -run ^TestRecoveryChargesFunding$ -count=1`
+
+Exit 0:
+
+```text
+ok amadan.net/oficina/equipo/internal/directlive 0.047s
+```
+
+### B1-m-recovery-calls-mutation
+
+`CGO_ENABLED=0 go test ./internal/directlive -run ^TestRecoveryChargesFunding$ -count=1`
+
+Exit 1:
+
+```text
+--- FAIL: TestRecoveryChargesFunding (0.00s)
+ certification_guards_test.go:55: recovery not charged 0 1000 2000
+FAIL
+rastrillo-budget/v1 ran 0s
+FAIL amadan.net/oficina/equipo/internal/directlive 0.047s
+FAIL
+```
+
+### B1-m-recovery-tokens-green
+
+`CGO_ENABLED=0 go test ./internal/directlive -run ^TestRecoveryChargesFunding$ -count=1`
+
+Exit 0:
+
+```text
+ok amadan.net/oficina/equipo/internal/directlive 0.046s
+```
+
+### B1-m-recovery-tokens-mutation
+
+`CGO_ENABLED=0 go test ./internal/directlive -run ^TestRecoveryChargesFunding$ -count=1`
+
+Exit 1:
+
+```text
+--- FAIL: TestRecoveryChargesFunding (0.00s)
+ certification_guards_test.go:55: recovery not charged 1 0 2000
+FAIL
+rastrillo-budget/v1 ran 0s
+FAIL amadan.net/oficina/equipo/internal/directlive 0.049s
+FAIL
+```
+
+### B1-m-pins-green
+
+`CGO_ENABLED=0 go test ./internal/directlive -run ^TestCandidateBinariesPinned$ -count=1`
+
+Exit 0:
+
+```text
+ok amadan.net/oficina/equipo/internal/directlive 0.047s
+```
+
+### B1-m-pins-mutation
+
+`CGO_ENABLED=0 go test ./internal/directlive -run ^TestCandidateBinariesPinned$ -count=1`
+
+Exit 1:
+
+```text
+--- FAIL: TestCandidateBinariesPinned (0.00s)
+ certification_guards_test.go:69: foreign binary certified codex-code-mode-host
+FAIL
+rastrillo-budget/v1 ran 0s
+FAIL amadan.net/oficina/equipo/internal/directlive 0.049s
+FAIL
+```
+
+### B1-m-probe-green
+
+`CGO_ENABLED=0 go test ./internal/directlive -run ^TestProbeFileTargetsAndDenials$ -count=1`
+
+Exit 0:
+
+```text
+ok amadan.net/oficina/equipo/internal/directlive 0.048s
+```
+
+### B1-m-probe-mutation
+
+`CGO_ENABLED=0 go test ./internal/directlive -run ^TestProbeFileTargetsAndDenials$ -count=1`
+
+Exit 1:
+
+```text
+--- FAIL: TestProbeFileTargetsAndDenials (0.00s)
+ certification_guards_test.go:77: directory probe /egress /egress
+FAIL
+rastrillo-budget/v1 ran 0s
+FAIL amadan.net/oficina/equipo/internal/directlive 0.045s
+FAIL
+```
+
+### B1-m-classifier-green
+
+`CGO_ENABLED=0 go test ./internal/directlive -run ^TestProbeFileTargetsAndDenials$ -count=1`
+
+Exit 0:
+
+```text
+ok amadan.net/oficina/equipo/internal/directlive 0.047s
+```
+
+### B1-m-classifier-mutation
+
+`CGO_ENABLED=0 go test ./internal/directlive -run ^TestProbeFileTargetsAndDenials$ -count=1`
+
+Exit 1:
+
+```text
+--- FAIL: TestProbeFileTargetsAndDenials (0.00s)
+ certification_guards_test.go:82: non-denial classified as proof sandbox configuration loaded
+FAIL
+rastrillo-budget/v1 ran 0s
+FAIL amadan.net/oficina/equipo/internal/directlive 0.048s
+FAIL
+```
+
+### B1-m-readback-green
+
+`CGO_ENABLED=0 go test ./internal/directlive -run ^TestPolicyEvidenceRequiresObservedFrames$ -count=1`
+
+Exit 0:
+
+```text
+ok amadan.net/oficina/equipo/internal/directlive 0.046s
+```
+
+### B1-m-readback-mutation
+
+`CGO_ENABLED=0 go test ./internal/directlive -run ^TestPolicyEvidenceRequiresObservedFrames$ -count=1`
+
+Exit 1:
+
+```text
+--- FAIL: TestPolicyEvidenceRequiresObservedFrames (0.00s)
+ certification_guards_test.go:95: requested policy became observed evidence
+FAIL
+rastrillo-budget/v1 ran 0s
+FAIL amadan.net/oficina/equipo/internal/directlive 0.047s
+FAIL
+```
+
+### B1-m-calibration-green
+
+`CGO_ENABLED=0 go test ./internal/directlive -run ^TestCalibrationRequiresChargedCalls$ -count=1`
+
+Exit 0:
+
+```text
+ok amadan.net/oficina/equipo/internal/directlive 0.097s
+```
+
+### B1-m-calibration-mutation
+
+`CGO_ENABLED=0 go test ./internal/directlive -run ^TestCalibrationRequiresChargedCalls$ -count=1`
+
+Exit 1:
+
+```text
+--- FAIL: TestCalibrationRequiresChargedCalls (0.05s)
+ certification_guards_test.go:105: uncounted calls certified
+FAIL
+rastrillo-budget/v1 ran 48ms
+FAIL amadan.net/oficina/equipo/internal/directlive 0.094s
+FAIL
+```
+
+### B1-m-staged-final-green
+
+`CGO_ENABLED=0 go test ./internal/directlive -run ^TestGenerationUsesStagedSource$ -count=1`
+
+Exit 0:
+
+```text
+ok amadan.net/oficina/equipo/internal/directlive 0.086s
+```
+
+### B1-m-staged-restore-mutation
+
+`CGO_ENABLED=0 go test ./internal/directlive -run ^TestGenerationUsesStagedSource$ -count=1`
+
+Exit 1:
+
+```text
+--- FAIL: TestGenerationUsesStagedSource (0.01s)
+ certification_guards_test.go:39: source not restored after probe false
+FAIL
+rastrillo-budget/v1 ran 13ms
+FAIL amadan.net/oficina/equipo/internal/directlive 0.053s
+FAIL
+```
+
+### B1-m-staged-atomic-mutation
+
+`CGO_ENABLED=0 go test ./internal/directlive -run ^TestGenerationUsesStagedSource$ -count=1`
+
+Exit 1:
+
+```text
+--- FAIL: TestGenerationUsesStagedSource (0.00s)
+ certification_guards_test.go:27: source edited in place
+FAIL
+rastrillo-budget/v1 ran 2ms
+FAIL amadan.net/oficina/equipo/internal/directlive 0.044s
+FAIL
+```
+
+### minor-fake-driver-final
+
+`CGO_ENABLED=0 go test ./internal/directlive -run ^TestDirectDriverFakeCLI$ -count=1`
+
+Exit 0:
+
+```text
+ok amadan.net/oficina/equipo/internal/directlive 85.866s
+```
+
+
+## C-m
+
+Reopening an answer after revocation removes its profile approval and label from assignment, event, timeline and artifact provenance in the same transaction. Publisher validation decodes PublicationDescription and compares its approval structure, accepting JSON-escaped labels while rejecting labels planted in unrelated text. Historical trial rows are labelled Historical supervised trial. Description readback uses a dedicated transport with Proxy nil and disables cookies and redirects. Startup sweeps stale describe-* directories under the owned ScratchRoot while the runner state lock is held.
+
+New pending copy: trial.history = Historical supervised trial.
+
+Interpretations: The historical label is a copy-only change. Its rendered HTTP assertion and compile-valid template mutation cover it. The initial HTTP fixture used the nonexistent /runners path; the valid page is /runners/enrol.
+
+### C-m-revocation-red
+
+```text
+--- FAIL: TestReopenedQuestionDropsProfileApproval (0.65s)
+ approval_once_test.go:150: revoked approval label retained {"profile_approvals":[{"question_id":"native","request_id":"7","item_id":"item","turn_id":"provider-turn","session_id":"session","person":"second-owner@example.com","label":"approved beyond profile","request":{"id":7,"method":"item/commandExecution/requestApproval","params":{"command":"printf hello","cwd":"/workspace","itemId":"item","threadId":"session","turnId":"provider-turn"}}}],"status":"confined","runner_tainted":false,"acknowledgement_ids":null,"observed_tuples":[{"provider":"claude","provider_version":"2.1.312","launcher_version":"direct-v2","bwrap_version":"0.11.0","policy_version":"policy-v2","isolation_config_hash":"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"}]}
+FAIL
+rastrillo-budget/v1 ran 647ms
+FAIL amadan.net/oficina/equipo/internal/equipotest 0.749s
+FAIL
+```
+
+### C-m-approval-red
+
+```text
+--- FAIL: TestReopenedQuestionDropsProfileApproval (0.54s)
+ approval_once_test.go:146: team: grant_stale: job grant needs reconciliation
+FAIL
+rastrillo-budget/v1 ran 540ms
+FAIL amadan.net/oficina/equipo/internal/equipotest 0.641s
+--- FAIL: TestPublisherChecksDecodedProfileApproval (0.05s)
+ approval_profile_test.go:44: decoded approval valid=false: <nil>
+FAIL
+rastrillo-budget/v1 ran 54ms
+FAIL amadan.net/oficina/equipo/internal/runner/forge 0.058s
+FAIL
+```
+
+### C-m-transport-red
+
+```text
+--- FAIL: TestDescriptionIgnoresDefaultProxyClient (0.00s)
+ description_test.go:341: description used ambient proxy client
+FAIL
+rastrillo-budget/v1 ran 0s
+FAIL amadan.net/oficina/equipo/internal/runner/forge 0.003s
+--- FAIL: TestRunnerSweepsStaleDescriptionTokens (0.05s)
+ direct_runtime_test.go:206: stale token directory survived startup
+FAIL
+rastrillo-budget/v1 ran 49ms
+FAIL amadan.net/oficina/equipo/internal/runner 0.052s
+FAIL
+```
+
+### C-m-revocation-green
+
+`CGO_ENABLED=0 go test ./internal/equipotest -run ^TestReopenedQuestionDropsProfileApproval$ -count=1`
+
+Exit 0:
+
+```text
+ok amadan.net/oficina/equipo/internal/equipotest 0.424s
+```
+
+### C-m-revocation-mutation
+
+`CGO_ENABLED=0 go test ./internal/equipotest -run ^TestReopenedQuestionDropsProfileApproval$ -count=1`
+
+Exit 1:
+
+```text
+--- FAIL: TestReopenedQuestionDropsProfileApproval (0.37s)
+ approval_once_test.go:156: revoked approval label retained {"profile_approvals":[{"question_id":"native","request_id":"7","item_id":"item","turn_id":"provider-turn","session_id":"session","person":"second-owner@example.com","label":"approved beyond profile","request":{"id":7,"method":"item/commandExecution/requestApproval","params":{"command":"printf hello","cwd":"/workspace","itemId":"item","threadId":"session","turnId":"provider-turn"}}}],"status":"confined","runner_tainted":false,"acknowledgement_ids":null,"observed_tuples":[{"provider":"claude","provider_version":"2.1.312","launcher_version":"direct-v2","bwrap_version":"0.11.0","policy_version":"policy-v2","isolation_config_hash":"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"}]}
+FAIL
+rastrillo-budget/v1 ran 373ms
+FAIL amadan.net/oficina/equipo/internal/equipotest 0.420s
+FAIL
+```
+
+### C-m-label-green
+
+`CGO_ENABLED=0 go test ./internal/runner/forge -run ^TestPublisherChecksDecodedProfileApproval$ -count=1`
+
+Exit 0:
+
+```text
+ok amadan.net/oficina/equipo/internal/runner/forge 0.020s
+```
+
+### C-m-label-mutation
+
+`CGO_ENABLED=0 go test ./internal/runner/forge -run ^TestPublisherChecksDecodedProfileApproval$ -count=1`
+
+Exit 1:
+
+```text
+--- FAIL: TestPublisherChecksDecodedProfileApproval (0.02s)
+ approval_profile_test.go:64: decoded approval valid=false: <nil>
+FAIL
+rastrillo-budget/v1 ran 18ms
+FAIL amadan.net/oficina/equipo/internal/runner/forge 0.020s
+FAIL
+```
+
+### C-m-proxy-green
+
+`CGO_ENABLED=0 go test ./internal/runner/forge -run ^TestDescriptionIgnoresDefaultProxyClient$ -count=1`
+
+Exit 0:
+
+```text
+ok amadan.net/oficina/equipo/internal/runner/forge 0.002s
+```
+
+### C-m-proxy-mutation
+
+`CGO_ENABLED=0 go test ./internal/runner/forge -run ^TestDescriptionIgnoresDefaultProxyClient$ -count=1`
+
+Exit 1:
+
+```text
+--- FAIL: TestDescriptionIgnoresDefaultProxyClient (0.00s)
+ description_test.go:348: description used ambient proxy client
+FAIL
+rastrillo-budget/v1 ran 0s
+FAIL amadan.net/oficina/equipo/internal/runner/forge 0.002s
+FAIL
+```
+
+### C-m-sweep-green
+
+`CGO_ENABLED=0 go test ./internal/runner -run ^TestRunnerSweepsStaleDescriptionTokens$ -count=1`
+
+Exit 0:
+
+```text
+ok amadan.net/oficina/equipo/internal/runner 0.051s
+```
+
+### C-m-sweep-mutation
+
+`CGO_ENABLED=0 go test ./internal/runner -run ^TestRunnerSweepsStaleDescriptionTokens$ -count=1`
+
+Exit 1:
+
+```text
+--- FAIL: TestRunnerSweepsStaleDescriptionTokens (0.05s)
+ direct_runtime_test.go:213: stale token directory survived startup
+FAIL
+rastrillo-budget/v1 ran 47ms
+FAIL amadan.net/oficina/equipo/internal/runner 0.049s
+FAIL
+```
+
+### C-m-history-mutation
+
+`CGO_ENABLED=0 go test ./internal/equipotest -run '^Test(DirectBinaryBoundaries|CheckPolicyNoRedundantRunner|RunnerTrialHistoryLabel)$' -count=1`
+
+Exit 1:
+
+```text
+2026/11/04 01:12:53 INFO Apply migrations. applied=[] skipped=24 adopted=false
+--- FAIL: TestRunnerTrialHistoryLabel (3.42s)
+ approval_once_test.go:172: old trial displayed without historical label
+FAIL
+rastrillo-budget/v1 ran 3.476s
+FAIL amadan.net/oficina/equipo/internal/equipotest 3.522s
+FAIL
+```
+
+### A-m678-C-m-history-green
+
+`CGO_ENABLED=0 go test ./internal/equipotest -run '^Test(DirectBinaryBoundaries|CheckPolicyNoRedundantRunner|RunnerTrialHistoryLabel)$' -count=1`
+
+Exit 0:
+
+```text
+ok amadan.net/oficina/equipo/internal/equipotest 3.522s
+```
+
+
+## B2-m
+
+M1: persist the action and admitting phase before the admit RPC, so recovery can report a lost admission. M2: a failed admission check requests recovery before polling again. M6 is covered by the B2-I2 preflight cache. Follow-up coverage also applies non-latching budget errors to event and tool queues, and verifies that an instance accepts a matching unstarted exit after a lost launch acknowledgment while rejecting a mismatched exit.
+
+Interpretations: The RED command is the same named test and package as the GREEN command. Mutations are compile-valid and restored. No new UI strings unless listed.
+
+### B2-m-red
+
+```text
+--- FAIL: TestDirectAdmissionIntentBeforeRPC (0.04s)
+ direct_admission_test.go:7: admission reached instance before durable action intent
+--- FAIL: TestServiceRecoversAdmissionFailure (0.55s)
+ direct_admission_test.go:20: admission failure skipped recovery 1
+FAIL
+rastrillo-budget/v1 ran 593ms
+FAIL amadan.net/oficina/equipo/internal/runner 0.595s
+FAIL
+```
+
+### B2-M1-green
+
+`CGO_ENABLED=0 go test ./internal/runner -run ^TestDirectAdmissionIntentBeforeRPC$ -count=1`
+
+Exit 0:
+
+```text
+ok amadan.net/oficina/equipo/internal/runner 0.081s
+```
+
+### B2-M1-mutation
+
+`CGO_ENABLED=0 go test ./internal/runner -run ^TestDirectAdmissionIntentBeforeRPC$ -count=1`
+
+Exit 1:
+
+```text
+--- FAIL: TestDirectAdmissionIntentBeforeRPC (0.06s)
+ direct_admission_test.go:18: admission reached instance before durable action intent
+FAIL
+rastrillo-budget/v1 ran 56ms
+FAIL amadan.net/oficina/equipo/internal/runner 0.059s
+FAIL
+```
+
+### B2-M2-green
+
+`CGO_ENABLED=0 go test ./internal/runner -run ^TestServiceRecoversAdmissionFailure$ -count=1`
+
+Exit 0:
+
+```text
+ok amadan.net/oficina/equipo/internal/runner 0.561s
+```
+
+### B2-M2-mutation
+
+`CGO_ENABLED=0 go test ./internal/runner -run ^TestServiceRecoversAdmissionFailure$ -count=1`
+
+Exit 1:
+
+```text
+--- FAIL: TestServiceRecoversAdmissionFailure (0.56s)
+ direct_admission_test.go:59: admission failure skipped recovery 1
+FAIL
+rastrillo-budget/v1 ran 557ms
+FAIL amadan.net/oficina/equipo/internal/runner 0.559s
+FAIL
+```
+
+### B2-I2-budget-green
+
+`CGO_ENABLED=0 go test ./internal/runner -run ^TestPendingBudgetsDoNotLatch$ -count=1`
+
+Exit 0:
+
+```text
+ok amadan.net/oficina/equipo/internal/runner 0.120s
+```
+
+### B2-I2-budget-mutation
+
+`CGO_ENABLED=0 go test ./internal/runner -run ^TestPendingBudgetsDoNotLatch$ -count=1`
+
+Exit 1:
+
+```text
+--- FAIL: TestPendingBudgetsDoNotLatch (0.13s)
+ --- FAIL: TestPendingBudgetsDoNotLatch/event (0.06s)
+ preflight_cache_test.go:94: budget refusal latched storage provider_uncertain
+ runner.journal
+FAIL
+rastrillo-budget/v1 ran 133ms
+FAIL amadan.net/oficina/equipo/internal/runner 0.136s
+FAIL
+```
+
+### B2-I1-lost-ack-green
+
+`CGO_ENABLED=0 go test ./internal/equipotest -run '^TestDirectContainmentReportBinding/(lost-launch-ack|unstarted-mismatch)$' -count=1`
+
+Exit 0:
+
+```text
+ok amadan.net/oficina/equipo/internal/equipotest 0.849s
+```
+
+### B2-I1-lost-ack-mutation
+
+`CGO_ENABLED=0 go test ./internal/equipotest -run '^TestDirectContainmentReportBinding/(lost-launch-ack|unstarted-mismatch)$' -count=1`
+
+Exit 1:
+
+```text
+--- FAIL: TestDirectContainmentReportBinding (0.78s)
+ --- FAIL: TestDirectContainmentReportBinding/lost-launch-ack (0.54s)
+ direct_containment_test.go:88: bound proof refused: You do not have access to this page. Ask an owner for access.
+FAIL
+rastrillo-budget/v1 ran 782ms
+FAIL amadan.net/oficina/equipo/internal/equipotest 0.832s
+FAIL
+```
+
+### B2-I1-unstarted-binding-mutation
+
+`CGO_ENABLED=0 go test ./internal/equipotest -run '^TestDirectContainmentReportBinding/(lost-launch-ack|unstarted-mismatch)$' -count=1`
+
+Exit 1:
+
+```text
+--- FAIL: TestDirectContainmentReportBinding (0.92s)
+ --- FAIL: TestDirectContainmentReportBinding/unstarted-mismatch (0.32s)
+ direct_containment_test.go:91: unbound proof released capacity
+FAIL
+rastrillo-budget/v1 ran 917ms
+FAIL amadan.net/oficina/equipo/internal/equipotest 0.965s
+FAIL
+```
+
+
+## Minor group verification
+
+All restored targeted guards passed across adapters, namespace containment, runner, instance integration, publisher and driver. The complete fake CLI exercise passed with real namespaces and fake providers only.
+
+### minor-green-restored
+
+`CGO_ENABLED=0 go test ./internal/runner/containment ./internal/runner/provider ./internal/runner/provider/codex ./internal/runner/provider/claude ./internal/equipotest ./internal/runner ./internal/runner/forge ./internal/directlive -run '^Test(Namespace.*|BwrapRunsPinnedDescriptor|Codex.*|Claude.*|DirectBinaryBoundaries|CheckPolicyNoRedundantRunner|RunnerTrialHistoryLabel|ReopenedQuestionDropsProfileApproval|PublisherChecksDecodedProfileApproval|ApprovedBeyondProfilePublisher|PendingBudgetsDoNotLatch|DirectAdmissionIntentBeforeRPC|ServiceRecoversAdmissionFailure|RuntimeHomeRejectsPolicyInjection|RefreshDoesNotOverwriteNewerSource|GenerationUsesStagedSource|RecoveryChargesFunding|CandidateBinariesPinned|ProbeFileTargetsAndDenials|PolicyEvidenceRequiresObservedFrames|CalibrationRequiresChargedCalls|CodexPolicyEvidenceUsesReadback)$' -count=1`
+
+Exit 0:
+
+```text
+ok amadan.net/oficina/equipo/internal/runner/containment 5.543s
+ok amadan.net/oficina/equipo/internal/runner/provider 1.021s
+ok amadan.net/oficina/equipo/internal/runner/provider/codex 11.525s
+ok amadan.net/oficina/equipo/internal/runner/provider/claude 16.797s
+ok amadan.net/oficina/equipo/internal/equipotest 8.341s
+ok amadan.net/oficina/equipo/internal/runner 7.723s
+ok amadan.net/oficina/equipo/internal/runner/forge 0.184s
+ok amadan.net/oficina/equipo/internal/directlive 0.214s
+```
+
+### minor-fake-driver-final
+
+`CGO_ENABLED=0 go test ./internal/directlive -run ^TestDirectDriverFakeCLI$ -count=1`
+
+Exit 0:
+
+```text
+ok amadan.net/oficina/equipo/internal/directlive 85.866s
+```
+
diff --git a/internal/directlive/certificate.go b/internal/directlive/certificate.go
index 7fdac519..882f94e7 100644
--- a/internal/directlive/certificate.go
+++ b/internal/directlive/certificate.go
@@ -59,6 +59,9 @@ func ManifestCandidate(root string) error {
if binaries != nil && string(marshal(binaries)) != string(marshal(e.Binaries)) {
return errEvidence
}
+ if err = evidenceBinaries(e.Binaries); err != nil {
+ return err
+ }
binaries = e.Binaries
}
for _, name := range []string{"claude", "codex", "codex-code-mode-host", "bwrap", "equipo-tool-proxy"} {
diff --git a/internal/directlive/certification_guards.go b/internal/directlive/certification_guards.go
new file mode 100644
index 00000000..6a340a34
--- /dev/null
+++ b/internal/directlive/certification_guards.go
@@ -0,0 +1,30 @@
+package directlive
+
+import (
+ "amadan.net/oficina/equipo/internal/runner/provider"
+ "amadan.net/oficina/equipo/internal/runner/provider/claude"
+ "amadan.net/oficina/equipo/internal/runner/provider/codex"
+)
+
+func (d *driver) reserveRecovery() error {
+ f := d.cfg.Funding
+ input, output := (f.JobInput+22)/23, (f.JobOutput+22)/23
+ if input <= 0 || output <= 0 || d.calls >= f.Calls || input > f.InputTokens-d.input || output > f.OutputTokens-d.output {
+ return provider.ErrPolicy
+ }
+ d.calls++
+ d.input += input
+ d.output += output
+ return nil
+}
+func evidenceBinaries(b map[string]string) error {
+ for name, pin := range map[string]string{"claude": claude.ExecutableSHA256, "codex": codex.ExecutableSHA256, "codex-code-mode-host": codex.CodeModeHostSHA256} {
+ if b[name] != pin {
+ return provider.ErrVersion
+ }
+ }
+ return nil
+}
+func probeTargets() map[string]string {
+ return map[string]string{"/egress": "/egress/equipo-read-sentinel", "/proc/*/root": "/proc/1/root/home/runner/equipo-read-sentinel", "/proc/*/fd": "/proc/1/fd/equipo-read-sentinel", "/dev/fd": "/dev/fd/equipo-read-sentinel"}
+}
diff --git a/internal/directlive/certification_guards_test.go b/internal/directlive/certification_guards_test.go
new file mode 100644
index 00000000..947d7de6
--- /dev/null
+++ b/internal/directlive/certification_guards_test.go
@@ -0,0 +1,126 @@
+package directlive
+
+import (
+ "amadan.net/oficina/equipo/internal/runner/provider"
+ "amadan.net/oficina/equipo/internal/runner/provider/claude"
+ "amadan.net/oficina/equipo/internal/runner/provider/codex"
+ "encoding/json"
+ "errors"
+ "os"
+ "path/filepath"
+ "strings"
+ "testing"
+)
+
+func TestGenerationUsesStagedSource(t *testing.T) {
+ path := filepath.Join(t.TempDir(), "auth.json")
+ original := []byte(`{"fake":"login"}`)
+ if err := os.WriteFile(path, original, 0600); err != nil {
+ t.Fatal(err)
+ }
+ before, _ := os.Stat(path)
+ failure := errors.New("probe failed")
+ for _, failed := range []bool{false, true} {
+ err := withStagedSource(path, func(raw []byte) ([]byte, error) { return append(raw, '\n'), nil }, func() error {
+ current, _ := os.Stat(path)
+ if os.SameFile(before, current) {
+ t.Fatal("source edited in place")
+ }
+ if failed {
+ return failure
+ }
+ return nil
+ })
+ if failed && !errors.Is(err, failure) || !failed && err != nil {
+ t.Fatal(err)
+ }
+ after, _ := os.ReadFile(path)
+ if string(after) != string(original) {
+ t.Fatal("source not restored after probe", failed)
+ }
+ }
+}
+func TestRecoveryChargesFunding(t *testing.T) {
+ d := &driver{cfg: provider.DirectLiveConfig{Funding: provider.LiveFunding{Calls: 1, InputTokens: 1000, OutputTokens: 2000, JobInput: 23000, JobOutput: 46000}}}
+ if err := d.reserveRecovery(); err != nil {
+ t.Fatal(err)
+ }
+ if d.calls != 1 || d.input != 1000 || d.output != 2000 {
+ t.Fatal("recovery not charged", d.calls, d.input, d.output)
+ }
+ if err := d.reserveRecovery(); err == nil {
+ t.Fatal("exhausted recovery budget admitted")
+ }
+}
+func TestCandidateBinariesPinned(t *testing.T) {
+ pins := map[string]string{"claude": claude.ExecutableSHA256, "codex": codex.ExecutableSHA256, "codex-code-mode-host": codex.CodeModeHostSHA256}
+ if err := evidenceBinaries(pins); err != nil {
+ t.Fatal(err)
+ }
+ for name, old := range pins {
+ pins[name] = strings.Repeat("a", 64)
+ if evidenceBinaries(pins) == nil {
+ t.Fatal("foreign binary certified", name)
+ }
+ pins[name] = old
+ }
+}
+func TestProbeFileTargetsAndDenials(t *testing.T) {
+ for key, path := range probeTargets() {
+ if path == key || path == "/proc/1/root/home/runner" || path == "/proc/1/fd" {
+ t.Fatal("directory probe", key, path)
+ }
+ }
+ for _, s := range []string{"Is a directory", "No such file or directory", "sandbox configuration loaded"} {
+ if denial(s) {
+ t.Fatal("non-denial classified as proof", s)
+ }
+ }
+ for _, s := range []string{"Permission denied", "access denied by sandbox"} {
+ if !denial(s) {
+ t.Fatal("denial missed", s)
+ }
+ }
+}
+
+func TestPolicyEvidenceRequiresObservedFrames(t *testing.T) {
+ checks, policy := observedPolicy(nil, provider.Launch{Selection: provider.Selection{Provider: "codex"}})
+ if checks["effective-policy-readback"] || policy != nil && (policy.StrictConfig || policy.DenyProfile || policy.ApprovalPolicy != "") {
+ t.Fatal("requested policy became observed evidence")
+ }
+}
+func TestCalibrationRequiresChargedCalls(t *testing.T) {
+ f := provider.LiveFunding{Calls: 10, InputTokens: 100000, OutputTokens: 100000, JobInput: 23000, JobOutput: 23000, ProjectInputHeadroom: 23000, ProjectOutputHeadroom: 23000, TeamInputHeadroom: 23000, TeamOutputHeadroom: 23000}
+ x := &exercise{root: t.TempDir(), d: &driver{cfg: provider.DirectLiveConfig{Funding: f}}, evidence: provider.DirectEvidence{Funding: f, Usage: []provider.LiveUsage{{Input: 1, Output: 1, Complete: true}}, Checks: map[string]provider.LiveObservation{}}}
+ if err := x.calibration(); err != nil {
+ t.Fatal(err)
+ }
+ if x.evidence.Checks["separate-bounded-admission"].Status == "pass" {
+ t.Fatal("uncounted calls certified")
+ }
+}
+
+func TestCodexPolicyEvidenceUsesReadback(t *testing.T) {
+ raw, err := os.ReadFile("../runner/provider/codex/testdata/unauthenticated-0.165.0.json")
+ if err != nil {
+ t.Fatal(err)
+ }
+ var fixture struct {
+ Settings json.RawMessage
+ Frames []json.RawMessage
+ }
+ if err = json.Unmarshal(raw, &fixture); err != nil {
+ t.Fatal(err)
+ }
+ frames := append(fixture.Frames, json.RawMessage(`{"result":{"approvalPolicy":"on-request","approvalsReviewer":"user","activePermissionProfile":{"id":"equipo"}}}`))
+ launch := provider.Launch{Selection: provider.Selection{Provider: "codex"}, Policy: provider.Policy{Settings: fixture.Settings}}
+ checks, p := observedPolicy(frames, launch)
+ if !checks["effective-policy-readback"] || !p.DenyProfile || p.ApprovalPolicy != "on-request" {
+ t.Fatal("actual policy readback lost", checks, p)
+ }
+ launch.Policy.Settings = json.RawMessage(`{"model":"wrong"}`)
+ checks, p = observedPolicy(frames, launch)
+ if checks["effective-policy-readback"] || p.DenyProfile {
+ t.Fatal("mismatched effective settings certified")
+ }
+}
diff --git a/internal/directlive/driver.go b/internal/directlive/driver.go
index 80438443..212d3ec2 100644
--- a/internal/directlive/driver.go
+++ b/internal/directlive/driver.go
@@ -174,7 +174,7 @@ type exercise struct {
}
func (d *driver) exercise(ctx context.Context, b provider.DirectLiveBinding, role, root string) (e provider.DirectEvidence, err error) {
- e = provider.DirectEvidence{Schema: 1, Source: d.source, RunID: d.cfg.RunID, Provider: b.Binding.Provider, ProviderVersion: b.Binding.Expected.ProviderVersion, LauncherVersion: "direct-v2", BwrapVersion: "0.11.0", PolicyVersion: provider.PolicyVersion, AccountID: b.Binding.AccountID, HomeID: b.Binding.Expected.HomeID, Model: b.Model, Specialist: strings.TrimSuffix(role, "-reproduction"), AuthHost: b.AuthHost, ConfigSHA256: d.configHash, Binaries: d.hashes, Funding: d.cfg.Funding, Checks: map[string]provider.LiveObservation{}}
+ e = provider.DirectEvidence{Schema: 1, Source: d.source, RunID: d.cfg.RunID, Provider: b.Binding.Provider, ProviderVersion: b.Binding.Expected.ProviderVersion, LauncherVersion: provider.LauncherVersion, BwrapVersion: "0.11.0", PolicyVersion: provider.PolicyVersion, AccountID: b.Binding.AccountID, HomeID: b.Binding.Expected.HomeID, Model: b.Model, Specialist: strings.TrimSuffix(role, "-reproduction"), AuthHost: b.AuthHost, ConfigSHA256: d.configHash, Binaries: d.hashes, Funding: d.cfg.Funding, Checks: map[string]provider.LiveObservation{}}
phase := "journal"
defer func() {
if err != nil {
@@ -280,20 +280,28 @@ func (d *driver) exercise(ctx context.Context, b provider.DirectLiveBinding, rol
if err = x.check("account-version-readback", true, x.session); err != nil {
return e, err
}
- // Open validates the complete effective config and provider identity through
- // the adapter, before a turn can be dispatched.
- for _, check := range []string{"effective-policy-readback", "inner-sandbox-enabled", "strict-mcp", "no-hooks-plugins"} {
- if err = x.check(check, true, json.RawMessage(policy.Manifest)); err != nil {
- return e, err
- }
- }
- if binding.Provider == "codex" {
- x.evidence.CodexPolicy = &provider.LiveCodexPolicy{ApprovalPolicy: "on-request", ApprovalsReviewer: "user", StrictConfig: true, DenyProfile: true}
- }
phase = "probes"
if err = x.probes(ctx, in.Tools); err != nil {
return e, err
}
+ captured, captureErr := x.journal.CaptureEvidence(ctx)
+ if captureErr != nil {
+ return e, captureErr
+ }
+ observed, readback := observedPolicy(captured, x.launch)
+ x.evidence.CodexPolicy = readback
+ sandboxDenied := false
+ for _, tool := range x.evidence.Tools {
+ if tool.Surface == "shell" && tool.Probes["selected-home"].Status == "denied" {
+ sandboxDenied = true
+ }
+ }
+ observed["inner-sandbox-enabled"] = sandboxDenied && x.evidence.Checks["workspace-positive-control"].Status == "pass"
+ for check, ok := range observed {
+ if err = x.check(check, ok, map[string]any{"frames": captured, "checks": observed, "codex_policy": readback}); err != nil {
+ return e, err
+ }
+ }
phase = "controls"
if err = x.controls(ctx); err != nil {
return e, err
diff --git a/internal/directlive/driver_test.go b/internal/directlive/driver_test.go
index 0ee37cd6..6c768d60 100644
--- a/internal/directlive/driver_test.go
+++ b/internal/directlive/driver_test.go
@@ -131,6 +131,21 @@ func TestDirectDriverFakeWorker(t *testing.T) {
if err := os.WriteFile(paths.AccountBindingsPath, marshal(bindings), 0600); err != nil {
t.Fatal(err)
}
+ original := map[string]string{}
+ for _, b := range c.Bindings {
+ entries, err := os.ReadDir(b.Binding.Home)
+ if err != nil {
+ t.Fatal(err)
+ }
+ for _, entry := range entries {
+ path := filepath.Join(b.Binding.Home, entry.Name())
+ raw, err := os.ReadFile(path)
+ if err != nil {
+ t.Fatal(err)
+ }
+ original[path] = string(raw)
+ }
+ }
if err := run(context.Background(), c, marshal(c), p, "fake-cli", answer, paths); err != nil {
files, _ := filepath.Glob(filepath.Join(c.EvidenceDir, "*", "diagnostics.json"))
for _, p := range files {
@@ -139,6 +154,12 @@ func TestDirectDriverFakeWorker(t *testing.T) {
}
t.Fatal(err)
}
+ for path, before := range original {
+ raw, err := os.ReadFile(path)
+ if err != nil || string(raw) != before {
+ t.Fatal("dedicated source changed", path, err)
+ }
+ }
entries, err := os.ReadDir(paths.ScratchRoot)
if err != nil || len(entries) != 0 {
t.Fatalf("driver left runtime scratch: %v %v", entries, err)
diff --git a/internal/directlive/generation.go b/internal/directlive/generation.go
index f4a9e396..66db775c 100644
--- a/internal/directlive/generation.go
+++ b/internal/directlive/generation.go
@@ -6,90 +6,57 @@ import (
"context"
"encoding/json"
"errors"
- "golang.org/x/sys/unix"
- "os"
"path/filepath"
)
-// Generation exercises change JSON whitespace, never token values. They only
-// run when the operator explicitly selects an auth host for this account.
func (x *exercise) generation(ctx context.Context) error {
if x.evidence.AuthHost == "" {
return nil
}
name := map[string]string{"claude": ".credentials.json", "codex": "auth.json"}[x.evidence.Provider]
- fd, err := unix.Openat2(unix.AT_FDCWD, filepath.Join(x.launch.Binding.CredentialHome, name), &unix.OpenHow{Flags: unix.O_WRONLY | unix.O_APPEND | unix.O_CLOEXEC, Resolve: unix.RESOLVE_NO_SYMLINKS | unix.RESOLVE_NO_MAGICLINKS})
- if err != nil {
- return err
- }
- f := os.NewFile(uintptr(fd), name)
- var stat unix.Stat_t
- if unix.Fstat(fd, &stat) != nil || stat.Mode&unix.S_IFMT != unix.S_IFREG || stat.Mode&0777 != 0600 || stat.Nlink != 1 || stat.Uid != uint32(os.Getuid()) {
- f.Close()
- return provider.ErrPolicy
- }
- _, err = f.Write([]byte("\n"))
- err = errors.Join(err, f.Sync(), f.Close())
- if err != nil {
- return err
- }
- pending := x.lease.Validate(ctx)
- if !errors.Is(pending, provider.ErrPreflightRequired) {
- return provider.ErrPolicy
- }
- if _, err = x.turn(ctx, "Credential-generation certification. Reply with the word unchanged without using tools."); err != nil {
- return err
- }
- valid := x.lease.ValidatePolicy(ctx) == nil
- for _, name := range []string{"same-identity-generation-fresh-preflight-bind", "same-identity-continued-availability"} {
- if err = x.check(name, valid, map[string]any{"preflight_required_before": true, "policy_valid_after": valid, "session": x.session}); err != nil {
+ return withStagedSource(filepath.Join(x.launch.Binding.CredentialHome, name), func(raw []byte) ([]byte, error) {
+ if !json.Valid(raw) {
+ return nil, provider.ErrPolicy
+ }
+ return append(raw, '\n'), nil
+ }, func() error {
+ pending := x.lease.Validate(ctx)
+ if !errors.Is(pending, provider.ErrPreflightRequired) {
+ return provider.ErrPolicy
+ }
+ if _, err := x.turn(ctx, "Credential-generation certification. Reply with the word unchanged without using tools."); err != nil {
return err
}
- }
- return nil
+ valid := x.lease.ValidatePolicy(ctx) == nil
+ for _, name := range []string{"same-identity-generation-fresh-preflight-bind", "same-identity-continued-availability"} {
+ if err := x.check(name, valid, map[string]any{"preflight_required_before": errors.Is(pending, provider.ErrPreflightRequired), "policy_valid_after": valid, "session": x.session}); err != nil {
+ return err
+ }
+ }
+ return nil
+ })
}
-func (x *exercise) changedIdentity(ctx context.Context) (err error) {
+func (x *exercise) changedIdentity(ctx context.Context) error {
if x.evidence.AuthHost == "" {
return nil
}
- if x.d.calls >= x.d.cfg.Funding.Calls {
- return provider.ErrPolicy
- }
- x.d.calls++
- path := filepath.Join(x.launch.Binding.CredentialHome, provider.IdentityFile)
- fd, err := unix.Openat2(unix.AT_FDCWD, path, &unix.OpenHow{Flags: unix.O_RDWR | unix.O_CLOEXEC, Resolve: unix.RESOLVE_NO_SYMLINKS | unix.RESOLVE_NO_MAGICLINKS})
- if err != nil {
+ if err := x.d.reserveRecovery(); err != nil {
return err
}
- f := os.NewFile(uintptr(fd), path)
- defer f.Close()
- var before provider.Identity
- decoder := json.NewDecoder(f)
- decoder.DisallowUnknownFields()
- if decoder.Decode(&before) != nil || before != x.launch.Binding.Expected {
- return provider.ErrIdentity
- }
- restore := func(id provider.Identity) error {
- raw := marshal(id)
- if _, e := f.WriteAt(raw, 0); e != nil {
- return e
+ return withStagedSource(filepath.Join(x.launch.Binding.CredentialHome, provider.IdentityFile), func(raw []byte) ([]byte, error) {
+ var before provider.Identity
+ if json.Unmarshal(raw, &before) != nil || before != x.launch.Binding.Expected {
+ return nil, provider.ErrIdentity
}
- if e := f.Truncate(int64(len(raw))); e != nil {
- return e
+ before.AccountID += "-certification-mismatch"
+ return marshal(before), nil
+ }, func() error {
+ turn := provider.Turn{ID: "identity-mismatch", AdmissionID: "identity-mismatch", Prompt: "Identity guard certification. This request must be refused before dispatch."}
+ rejected := runner.DispatchDirectTurn(ctx, x.proxy, x.launcher, x.session, turn)
+ stopped := errors.Is(rejected, provider.ErrIdentity) || errors.Is(rejected, provider.ErrContainment)
+ if rejected == nil {
+ _ = x.launcher.Interrupt(ctx, x.session)
}
- return f.Sync()
- }
- defer func() { err = errors.Join(err, restore(before)) }()
- changed := before
- changed.AccountID += "-certification-mismatch"
- if err = restore(changed); err != nil {
- return err
- }
- turn := provider.Turn{ID: "identity-mismatch", AdmissionID: "identity-mismatch", Prompt: "Identity guard certification. This request must be refused before dispatch."}
- rejected := runner.DispatchDirectTurn(ctx, x.proxy, x.launcher, x.session, turn)
- stopped := errors.Is(rejected, provider.ErrIdentity) || errors.Is(rejected, provider.ErrContainment)
- if rejected == nil {
- _ = x.launcher.Interrupt(ctx, x.session)
- }
- return x.check("identity-marker-tamper-denied", stopped, map[string]any{"expected": before, "rejected_before_dispatch": stopped})
+ return x.check("identity-marker-tamper-denied", stopped, map[string]any{"expected": x.launch.Binding.Expected, "rejected_before_dispatch": stopped})
+ })
}
diff --git a/internal/directlive/observations.go b/internal/directlive/observations.go
index 486bc14b..bd6caa1a 100644
--- a/internal/directlive/observations.go
+++ b/internal/directlive/observations.go
@@ -74,7 +74,7 @@ func observedRead(name string, frames [][]byte, tool, path string, denied bool)
}
func denial(s string) bool {
s = strings.ToLower(s)
- return strings.Contains(s, "permission denied") || strings.Contains(s, "access denied") || strings.Contains(s, "not allowed") || strings.Contains(s, "denied by") || strings.Contains(s, "sandbox")
+ return strings.Contains(s, "permission denied") || strings.Contains(s, "access denied") || strings.Contains(s, "not allowed") || strings.Contains(s, "denied by") || strings.Contains(s, "sandbox denied")
}
func shellRead(path string) string {
diff --git a/internal/directlive/probes.go b/internal/directlive/probes.go
index 7f3701f6..662832ed 100644
--- a/internal/directlive/probes.go
+++ b/internal/directlive/probes.go
@@ -12,7 +12,12 @@ import (
)
func (x *exercise) probes(ctx context.Context, inventory []string) error {
- targets := map[string]string{"selected-home": "/home/runner/" + filepath.Base(x.d.cfg.Sentinels[x.evidence.Provider]), "other-home": "", "runner-state": x.d.cfg.Sentinels["state"], "/egress": "/egress", "/tool/equipo.sock": "/tool/equipo.sock", "/proc/*/root": "/proc/1/root/home/runner", "/proc/*/fd": "/proc/1/fd", "/dev/fd": "/dev/fd"}
+ targets := probeTargets()
+ targets["selected-home"] = "/home/runner/equipo-read-sentinel"
+ targets["other-home"] = ""
+ targets["runner-state"] = x.d.cfg.Sentinels["state"]
+ targets["/tool/equipo.sock"] = "/tool/equipo.sock"
+
for _, b := range x.d.cfg.Bindings {
if b.Binding.Provider != x.evidence.Provider {
targets["other-home"] = x.d.cfg.Sentinels[b.Binding.Provider]
@@ -27,12 +32,12 @@ func (x *exercise) probes(ctx context.Context, inventory []string) error {
return err
}
defer os.Remove(alias)
- targets["symlink"] = "/workspace/equipo-sentinel-alias/" + filepath.Base(x.d.cfg.Sentinels[x.evidence.Provider])
+ targets["symlink"] = "/workspace/equipo-sentinel-alias/equipo-read-sentinel"
sentinel, err := os.ReadFile(x.d.cfg.Sentinels[x.evidence.Provider])
if err != nil {
return err
}
- if err = os.WriteFile(filepath.Join(x.launch.Binding.Home, filepath.Base(x.d.cfg.Sentinels[x.evidence.Provider])), sentinel, 0600); err != nil {
+ if err = os.WriteFile(filepath.Join(x.launch.Binding.Home, "equipo-read-sentinel"), sentinel, 0600); err != nil {
return err
}
keys := make([]string, 0, len(targets))
@@ -106,9 +111,18 @@ func (x *exercise) calibration() error {
return err
}
f := x.d.cfg.Funding
- checks := map[string]bool{"separate-bounded-admission": true, "complete-input-output": true, "usage-unknowns-recorded": true, "twice-max-rounded-1000": true, "23-reservations-per-job": f.JobInput >= 23*in && f.JobOutput >= 23*out, "project-period-headroom": f.ProjectInputHeadroom >= f.JobInput && f.ProjectOutputHeadroom >= f.JobOutput, "team-period-headroom": f.TeamInputHeadroom >= f.JobInput && f.TeamOutputHeadroom >= f.JobOutput, "configured-limits-unchanged": true, "no-subscription-currency-cap": true}
+ complete := len(x.evidence.Usage) > 0
+ var maxInput, maxOutput int64
+ for _, sample := range x.evidence.Usage {
+ complete = complete && sample.Complete && sample.Input >= 0 && sample.Output >= 0
+ maxInput = max(maxInput, sample.Input)
+ maxOutput = max(maxOutput, sample.Output)
+ }
+ bounded := x.d.calls > 0 && x.d.calls <= f.Calls && x.d.input <= f.InputTokens && x.d.output <= f.OutputTokens
+ checks := map[string]bool{"separate-bounded-admission": bounded, "complete-input-output": complete, "usage-unknowns-recorded": complete && x.evidence.Checks["unknown-usage-retained"].Status == "pass", "twice-max-rounded-1000": in == ((2*maxInput+999)/1000)*1000 && out == ((2*maxOutput+999)/1000)*1000, "23-reservations-per-job": f.JobInput >= 23*in && f.JobOutput >= 23*out, "project-period-headroom": f.ProjectInputHeadroom >= f.JobInput && f.ProjectOutputHeadroom >= f.JobOutput, "team-period-headroom": f.TeamInputHeadroom >= f.JobInput && f.TeamOutputHeadroom >= f.JobOutput, "configured-limits-unchanged": x.evidence.Funding == x.d.cfg.Funding, "no-subscription-currency-cap": false}
+
for name, ok := range checks {
- if err = x.check(name, ok, map[string]any{"input_reservation": in, "output_reservation": out, "funding": f, "usage": x.evidence.Usage}); err != nil {
+ if err = x.check(name, ok, map[string]any{"input_reservation": in, "output_reservation": out, "funding": f, "usage": x.evidence.Usage, "charged_calls": x.d.calls, "charged_input": x.d.input, "charged_output": x.d.output, "currency_cap_observed": false}); err != nil {
return err
}
}
diff --git a/internal/directlive/readback.go b/internal/directlive/readback.go
new file mode 100644
index 00000000..58b55ed3
--- /dev/null
+++ b/internal/directlive/readback.go
@@ -0,0 +1,67 @@
+package directlive
+
+import (
+ "amadan.net/oficina/equipo/internal/runner/provider"
+ "amadan.net/oficina/equipo/internal/runner/provider/codex"
+ "encoding/json"
+)
+
+func observedPolicy(frames []json.RawMessage, l provider.Launch) (map[string]bool, *provider.LiveCodexPolicy) {
+ checks := map[string]bool{"effective-policy-readback": false, "strict-mcp": false, "no-hooks-plugins": false}
+ var policy *provider.LiveCodexPolicy
+ if l.Selection.Provider == "codex" {
+ policy = &provider.LiveCodexPolicy{}
+ }
+ configOK, profileOK := false, false
+ for _, raw := range frames {
+ var frame struct {
+ Type, Subtype string
+ Session string `json:"session_id"`
+ Version string `json:"claude_code_version"`
+ Model, PermissionMode string
+ Plugins, Skills []json.RawMessage
+ MCP []struct{ Name, Status string } `json:"mcp_servers"`
+ Result json.RawMessage
+ }
+ if json.Unmarshal(raw, &frame) != nil {
+ continue
+ }
+ if l.Selection.Provider == "claude" && frame.Type == "system" && frame.Subtype == "init" {
+ checks["effective-policy-readback"] = frame.Version == l.Binding.Expected.ProviderVersion && frame.Model == l.Selection.Model && frame.PermissionMode == "manual"
+ checks["strict-mcp"] = len(frame.MCP) == 1 && frame.MCP[0].Name == "equipo" && frame.MCP[0].Status == "connected"
+ // Init exposes plugins and skills but no effective hook settings.
+ checks["no-hooks-plugins"] = false
+ }
+ if policy != nil && len(frame.Result) > 0 {
+ var reply struct {
+ Config json.RawMessage
+ ApprovalPolicy, ApprovalsReviewer string
+ Profile struct{ ID string } `json:"activePermissionProfile"`
+ }
+ if json.Unmarshal(frame.Result, &reply) != nil {
+ continue
+ }
+ if len(reply.Config) > 0 {
+ configOK = codex.ConfigMatchesReadback(frame.Result, l.Policy)
+ checks["effective-policy-readback"] = configOK
+ checks["strict-mcp"] = configOK
+ policy.StrictConfig = configOK
+ var cfg struct {
+ Hooks json.RawMessage
+ Plugins map[string]json.RawMessage
+ }
+ _ = json.Unmarshal(reply.Config, &cfg)
+ checks["no-hooks-plugins"] = configOK && (len(cfg.Hooks) == 0 || string(cfg.Hooks) == "null") && len(cfg.Plugins) == 0
+ }
+ if reply.ApprovalPolicy != "" {
+ policy.ApprovalPolicy = reply.ApprovalPolicy
+ policy.ApprovalsReviewer = reply.ApprovalsReviewer
+ profileOK = reply.Profile.ID == "equipo"
+ }
+ }
+ }
+ if policy != nil {
+ policy.DenyProfile = configOK && profileOK
+ }
+ return checks, policy
+}
diff --git a/internal/directlive/recovery.go b/internal/directlive/recovery.go
index 58f42b61..cbbfbf0a 100644
--- a/internal/directlive/recovery.go
+++ b/internal/directlive/recovery.go
@@ -54,6 +54,10 @@ func RecoveryWorker(ctx context.Context, path string) error {
return err
}
func (x *exercise) waitForKill(ctx context.Context) error {
+ if x.d.calls >= x.d.cfg.Funding.Calls {
+ return provider.ErrPolicy
+ }
+ x.d.calls++
turn := provider.Turn{ID: "interrupted", AdmissionID: "interrupted", Prompt: "Recovery certification. Start a shell sleep lasting 300 seconds in the disposable workspace. Keep the sandbox and do not detach."}
if err := runner.DispatchDirectTurn(ctx, x.proxy, x.launcher, x.session, turn); err != nil {
return err
@@ -78,6 +82,9 @@ func (x *exercise) waitForKill(ctx context.Context) error {
return provider.ErrUncertain
}
func (d *driver) recover(ctx context.Context, b provider.DirectLiveBinding, role, root string, e *provider.DirectEvidence) (err error) {
+ if err = d.reserveRecovery(); err != nil {
+ return err
+ }
scratch, err := os.MkdirTemp(os.Getenv("TMPDIR"), "kill-")
if err != nil {
return err
@@ -204,7 +211,7 @@ func (d *driver) recover(ctx context.Context, b provider.DirectLiveBinding, role
}
}
redispatchDenied := j.BeginTurn(ctx, ready.Session, ready.Turn) != nil
- value := map[string]any{"dispatched": ready, "recovery": recovered, "replayed": again, "frames_before": before, "frames_after": after, "pid1_status": string(status), "pidfd_events": polls[0].Revents, "redispatch_denied": redispatchDenied}
+ value := map[string]any{"dispatched": ready, "reserved_input": (d.cfg.Funding.JobInput + 22) / 23, "reserved_output": (d.cfg.Funding.JobOutput + 22) / 23, "usage_known": false, "recovery": recovered, "replayed": again, "frames_before": before, "frames_after": after, "pid1_status": string(status), "pidfd_events": polls[0].Revents, "redispatch_denied": redispatchDenied}
checks := map[string]bool{"mid-turn-runner-kill": unknown, "durable-replay": reflect.DeepEqual(recovered, again), "no-redispatch": redispatchDenied && reflect.DeepEqual(stable, after), "unknown-usage-retained": unknown, "pidfd-exit": polls[0].Revents&unix.POLLIN != 0}
for name, ok := range checks {
state := "not-certified"
diff --git a/internal/directlive/staged_source.go b/internal/directlive/staged_source.go
new file mode 100644
index 00000000..b0071569
--- /dev/null
+++ b/internal/directlive/staged_source.go
@@ -0,0 +1,62 @@
+package directlive
+
+import (
+ "amadan.net/oficina/equipo/internal/runner/provider"
+ "errors"
+ "golang.org/x/sys/unix"
+ "io"
+ "os"
+ "path/filepath"
+)
+
+func withStagedSource(path string, change func([]byte) ([]byte, error), probe func() error) (err error) {
+ fd, err := unix.Openat2(unix.AT_FDCWD, path, &unix.OpenHow{Flags: unix.O_RDONLY | unix.O_CLOEXEC, Resolve: unix.RESOLVE_NO_SYMLINKS | unix.RESOLVE_NO_MAGICLINKS})
+ if err != nil {
+ return err
+ }
+ f := os.NewFile(uintptr(fd), path)
+ var stat unix.Stat_t
+ if unix.Fstat(fd, &stat) != nil || stat.Mode&unix.S_IFMT != unix.S_IFREG || stat.Mode&0777 != 0600 || stat.Nlink != 1 || stat.Uid != uint32(os.Getuid()) {
+ f.Close()
+ return provider.ErrPolicy
+ }
+ before, err := io.ReadAll(io.LimitReader(f, 1<<20+1))
+ closeErr := f.Close()
+ if err != nil || closeErr != nil || len(before) > 1<<20 {
+ return errors.Join(provider.ErrPolicy, err, closeErr)
+ }
+ after, err := change(append([]byte(nil), before...))
+ if err != nil {
+ return err
+ }
+ defer func() { err = errors.Join(err, replaceStaged(path, before)) }()
+ if err = replaceStaged(path, after); err != nil {
+ return err
+ }
+ return probe()
+}
+func replaceStaged(path string, raw []byte) error {
+ f, err := os.CreateTemp(filepath.Dir(path), ".equipo-probe-")
+ if err != nil {
+ return err
+ }
+ name := f.Name()
+ defer os.Remove(name)
+ _, err = f.Write(raw)
+ if err == nil {
+ err = f.Sync()
+ }
+ closeErr := f.Close()
+ if err != nil || closeErr != nil {
+ return errors.Join(err, closeErr)
+ }
+ if err = os.Rename(name, path); err != nil {
+ return err
+ }
+ dir, err := os.Open(filepath.Dir(path))
+ if err != nil {
+ return err
+ }
+ defer dir.Close()
+ return dir.Sync()
+}
diff --git a/internal/directlive/testdata/fake-cli.py b/internal/directlive/testdata/fake-cli.py
index 844eddb2..6d0a4171 100644
--- a/internal/directlive/testdata/fake-cli.py
+++ b/internal/directlive/testdata/fake-cli.py
@@ -36,7 +36,7 @@ def helper(method,params):
return reply['result']
def mcp():
return ['mcp__equipo__'+t['name'] for t in helper('tools/list',{})['tools']]
-turn=int(open('/home/runner/fixture-turn').read()) if os.path.exists('/home/runner/fixture-turn') else 0
+turn=int(open('/home/runner/history.jsonl').read()) if os.path.exists('/home/runner/history.jsonl') else 0
for line in sys.stdin:
req=json.loads(line)
if family=='codex':
@@ -53,7 +53,7 @@ for line in sys.stdin:
result={'thread':{'id':'thread-fixture'},'model':'fixture-model','modelProvider':'openai','cwd':'/workspace','approvalPolicy':'on-request','approvalsReviewer':'user','activePermissionProfile':{'id':'equipo','extends':None},'runtimeWorkspaceRoots':['/workspace']}
elif method=='turn/start':
turn+=1
- open('/home/runner/fixture-turn','w').write(str(turn))
+ open('/home/runner/history.jsonl','w').write(str(turn))
result={'turn':{'id':str(turn)}}
else:result={}
emit({'id':req['id'],'result':result})
diff --git a/internal/directlive/turn.go b/internal/directlive/turn.go
index f4dd6320..356f60ec 100644
--- a/internal/directlive/turn.go
+++ b/internal/directlive/turn.go
@@ -66,12 +66,11 @@ func (x *exercise) open(ctx context.Context, tool string) error {
}
func (x *exercise) turn(ctx context.Context, prompt string) ([][]byte, error) {
d := x.d
- if d.calls >= d.cfg.Funding.Calls || d.input >= d.cfg.Funding.InputTokens || d.output >= d.cfg.Funding.OutputTokens {
- return nil, provider.ErrPolicy
+ beforeInput, beforeOutput := d.input, d.output
+ if err := d.reserveRecovery(); err != nil {
+ return nil, err
}
- // Calibration admission is separate from job reservations. A started call is
- // charged before writing stdin; unknown usage stops further admission.
- d.calls++
+ reservedInput, reservedOutput := d.input-beforeInput, d.output-beforeOutput
x.sequence++
turn := provider.Turn{ID: fmt.Sprintf("certification-%d", x.sequence), AdmissionID: fmt.Sprintf("%s/%d", x.launch.AttemptKey, x.sequence), Prompt: prompt}
if err := x.proxy.BindTurn(x.session, turn.ID); err != nil {
@@ -123,11 +122,11 @@ func (x *exercise) turn(ctx context.Context, prompt string) ([][]byte, error) {
if usage == nil {
return frames, fmt.Errorf("turn-%d-usage: %w", x.sequence, provider.ErrUncertain)
}
- if usage.InputTokens > d.cfg.Funding.InputTokens-d.input || usage.OutputTokens > d.cfg.Funding.OutputTokens-d.output {
+ d.input += usage.InputTokens - reservedInput
+ d.output += usage.OutputTokens - reservedOutput
+ if d.input > d.cfg.Funding.InputTokens || d.output > d.cfg.Funding.OutputTokens {
return frames, provider.ErrPolicy
}
- d.input += usage.InputTokens
- d.output += usage.OutputTokens
raw := make([]json.RawMessage, len(frames))
for i, f := range frames {
raw[i] = runner.RedactJSON(f, nil)
diff --git a/internal/equipo/approval_revoke.go b/internal/equipo/approval_revoke.go
new file mode 100644
index 00000000..ac01ae94
--- /dev/null
+++ b/internal/equipo/approval_revoke.go
@@ -0,0 +1,64 @@
+package equipo
+
+import (
+ "amadan.net/oficina/equipo/internal/equipo/team"
+ "encoding/json"
+ "gorm.io/gorm"
+)
+
+func withoutApproval(iso team.IsolationSnapshot, ids ...string) team.IsolationSnapshot {
+ kept := iso.ProfileApprovals[:0]
+ for _, a := range iso.ProfileApprovals {
+ remove := false
+ for _, id := range ids {
+ if a.QuestionID == id {
+ remove = true
+ }
+ }
+ if !remove {
+ kept = append(kept, a)
+ }
+ }
+ iso.ProfileApprovals = kept
+ return iso
+}
+func dropProfileApproval(tx *gorm.DB, assignment, id string) error {
+ var a runnerAssignment
+ if err := tx.First(&a, "id=?", assignment).Error; err != nil {
+ return storeError(err)
+ }
+ value, err := assignmentValue(a)
+ if err != nil {
+ return err
+ }
+ iso := withoutApproval(value.Selection.Isolation, id)
+ raw, err := json.Marshal(iso)
+ if err != nil {
+ return err
+ }
+ if err = tx.Model(&runnerAssignment{}).Where("id=?", assignment).Select("Isolation").Updates(&runnerAssignment{Isolation: string(raw)}).Error; err != nil {
+ return storeError(err)
+ }
+ if err = syncRunnerEventExposure(tx, assignment, iso, id); err != nil {
+ return err
+ }
+ var artifacts []executionArtifacts
+ if err = tx.Where("attempt_id=? AND job_id=?", a.AttemptID, a.JobID).Find(&artifacts).Error; err != nil {
+ return storeError(err)
+ }
+ for _, art := range artifacts {
+ var p team.Provenance
+ if err = json.Unmarshal([]byte(art.Provenance), &p); err != nil {
+ return err
+ }
+ p.Isolation = withoutApproval(p.Isolation, id)
+ raw, err = json.Marshal(p)
+ if err != nil {
+ return err
+ }
+ if err = tx.Model(&executionArtifacts{}).Where("id=?", art.ID).Select("Provenance").Updates(&executionArtifacts{Provenance: string(raw)}).Error; err != nil {
+ return storeError(err)
+ }
+ }
+ return nil
+}
diff --git a/internal/equipo/copy.go b/internal/equipo/copy.go
index 8db84ab4..affb5cf0 100644
--- a/internal/equipo/copy.go
+++ b/internal/equipo/copy.go
@@ -210,7 +210,9 @@ var runnerDraftCopy = map[string]string{
// COPY REVIEW REQUIRED: isolation.approved_beyond_profile
"isolation.approved_beyond_profile": "approved beyond profile",
// COPY REVIEW REQUIRED: trial.label
- "trial.label": "supervised trial",
+ // Pending copy review: trial.history.
+ "trial.history": "Historical supervised trial",
+ "trial.label": "supervised trial",
// COPY REVIEW REQUIRED: trial.reconnect
"trial.reconnect": "trial outcome uncertain",
// COPY REVIEW REQUIRED: trial.observed_locally
diff --git a/internal/equipo/questions.go b/internal/equipo/questions.go
index 39825334..661e366b 100644
--- a/internal/equipo/questions.go
+++ b/internal/equipo/questions.go
@@ -229,6 +229,9 @@ func (e *Execution) questionAnswers(ctx context.Context, tx *gorm.DB, a runnerAs
return nil, storeError(err)
}
if errors.Is(err, ErrNotFound) || !questionAnswerAllowed(member, task) {
+ if err := dropProfileApproval(tx, q.AssignmentID, q.ID); err != nil {
+ return nil, err
+ }
q.State, q.Answer, q.AnsweredBy = "pending", "", ""
if err := tx.Model(&questionRecord{}).Where("id=?", q.ID).Select("State", "Answer", "AnsweredBy").Updates(&q).Error; err != nil {
return nil, storeError(err)
diff --git a/internal/equipo/runner_events.go b/internal/equipo/runner_events.go
index 972de1d8..06372c63 100644
--- a/internal/equipo/runner_events.go
+++ b/internal/equipo/runner_events.go
@@ -265,7 +265,7 @@ func (e *Execution) registerArtifactOnce(ctx context.Context, tx *gorm.DB, a run
return artifact, storeError(err)
}
-func syncRunnerEventExposure(tx *gorm.DB, assignment string, iso team.IsolationSnapshot) error {
+func syncRunnerEventExposure(tx *gorm.DB, assignment string, iso team.IsolationSnapshot, revoked ...string) error {
expected, _ := json.Marshal(iso)
var events []runnerEvent
if err := tx.Where("assignment_id=? AND isolation!=?", assignment, string(expected)).Find(&events).Error; err != nil {
@@ -276,7 +276,7 @@ func syncRunnerEventExposure(tx *gorm.DB, assignment string, iso team.IsolationS
if err := json.Unmarshal([]byte(row.Body), &event); err != nil {
return err
}
- event.Isolation = mergeIsolation(event.Isolation, iso)
+ event.Isolation = mergeIsolation(withoutApproval(event.Isolation, revoked...), iso)
raw, _ := json.Marshal(event.Isolation)
body, _ := json.Marshal(event)
if row.Isolation == string(raw) && row.Body == string(body) {
@@ -295,7 +295,7 @@ func syncRunnerEventExposure(tx *gorm.DB, assignment string, iso team.IsolationS
if err := json.Unmarshal([]byte(row.Isolation), &old); err != nil {
return err
}
- raw, _ := json.Marshal(mergeIsolation(old, iso))
+ raw, _ := json.Marshal(mergeIsolation(withoutApproval(old, revoked...), iso))
if row.Isolation == string(raw) {
continue
}
diff --git a/internal/equipo/templates/runners.html b/internal/equipo/templates/runners.html
index 1c3e8953..e321f20c 100644
--- a/internal/equipo/templates/runners.html
+++ b/internal/equipo/templates/runners.html
@@ -29,7 +29,7 @@
<dt>{{copy "runner.person"}}</dt><dd>{{.Person}}</dd>
<dt>{{copy "runner.fingerprint"}}</dt><dd>{{.MachineKeyHash}}</dd>
</dl>
-{{if .TrialOwner}}<p>{{copy "trial.label"}}: {{.TrialOwner}} / {{.TrialAt}}</p><pre>{{.TrialVersions}}</pre>{{end}}
+{{if .TrialOwner}}<p>{{copy "trial.history"}}: {{.TrialOwner}} / {{.TrialAt}}</p><pre>{{.TrialVersions}}</pre>{{end}}
{{if not .RevokedAt}}<form method="post" action="/runners/{{.ID}}/revoke" equipo-form>
<input type="hidden" name="revision" value="{{.Revision}}">
<button rst-btn type="submit">{{copy "runner.revoke"}}</button>
diff --git a/internal/equipotest/approval_once_test.go b/internal/equipotest/approval_once_test.go
index 1dc4b0b5..f23714b2 100644
--- a/internal/equipotest/approval_once_test.go
+++ b/internal/equipotest/approval_once_test.go
@@ -139,3 +139,36 @@ func TestApprovedBeyondProfileLegacyArgv(t *testing.T) {
}
}
}
+
+func TestReopenedQuestionDropsProfileApproval(t *testing.T) {
+ f, q := nativeQuestionFixture(t)
+ person := "second-owner@example.com"
+ executionMust(t, f.d.G.Create(&equipo.Member{Address: person, Role: equipo.RoleOwner, Active: true, Revision: 1}).Error)
+ executionMust(t, f.s.AnswerQuestion(connectionContext, equipo.Actor{Address: person}, q.ID, 1, runnerproto.QuestionAnswer{Behavior: "allow"}))
+ mustSQL(t, f.d, "UPDATE members SET active=0 WHERE address=?", person)
+ r := f.request()
+ r.RequestID = "reopen"
+ _, err := f.x.Mutate(connectionContext, f.principal, "answers", r)
+ executionMust(t, err)
+ var iso string
+ executionMust(t, f.d.Writer().QueryRow("SELECT isolation FROM runner_assignments WHERE id=?", f.a.ID).Scan(&iso))
+ if strings.Contains(iso, "approved beyond profile") || strings.Contains(iso, person) {
+ t.Fatal("revoked approval label retained", iso)
+ }
+}
+
+func TestRunnerTrialHistoryLabel(t *testing.T) {
+ f := runnerFixtureNew(t, false)
+ cutoverRow(t, f.d, "supervised_trials", map[string]any{"id": "history", "runner_id": f.principal.RunnerID, "owner": ownerAddress, "acknowledged_at": "2026-11-01T00:00:00Z", "revoked_at": "2026-11-02T00:00:00Z", "versions": "historical versions"})
+ mail := &capturingMailer{}
+ router, err := equipo.RouterWithStore(f.d, testConfig(testOrigin), mail, nil, f.s)
+ executionMust(t, err)
+ server := httptest.NewServer(router)
+ defer server.Close()
+ client := signinClient(t, server.URL)
+ signinEmail(t, client, server.URL, testOrigin, mail, ownerAddress)
+ body := taskGet(t, client, server.URL, "/runners/enrol", 200)
+ if !strings.Contains(body, "Historical supervised trial") || !strings.Contains(body, "historical versions") {
+ t.Fatal("old trial displayed without historical label")
+ }
+}
diff --git a/internal/equipotest/direct_boundaries_test.go b/internal/equipotest/direct_boundaries_test.go
new file mode 100644
index 00000000..eed5fb26
--- /dev/null
+++ b/internal/equipotest/direct_boundaries_test.go
@@ -0,0 +1,27 @@
+package equipotest
+
+import (
+ "amadan.net/oficina/equipo/internal/runner/provider"
+ "os/exec"
+ "strings"
+ "testing"
+)
+
+func TestDirectBinaryBoundaries(t *testing.T) {
+ for _, pkg := range []string{"../runnerproto", "../../cmd/equipo-runner"} {
+ raw, err := exec.Command("go", "list", "-deps", pkg).CombinedOutput()
+ executionMust(t, err)
+ if strings.Contains(string(raw), "/internal/directlive") || pkg == "../runnerproto" && strings.Contains(string(raw), "/provider/codex") {
+ t.Fatal("production binary links adapter/certification worker", pkg)
+ }
+ }
+}
+func TestCheckPolicyNoRedundantRunner(t *testing.T) {
+ p, err := provider.BuildCheckPolicy(provider.CheckPolicyInputs{Workspace: t.TempDir(), GoRoot: t.TempDir(), ModuleCache: t.TempDir(), Binary: "/usr/bin/true", RunnerBinary: "/usr/bin/true", Bwrap: "/usr/bin/bwrap", Argv: []string{"/opt/codex"}})
+ executionMust(t, err)
+ for _, m := range p.Mounts {
+ if m.Target == "/opt/equipo-runner" {
+ t.Fatal("unused runner mount retained")
+ }
+ }
+}
diff --git a/internal/equipotest/direct_containment_test.go b/internal/equipotest/direct_containment_test.go
index 06c77a4d..7e5b9b5b 100644
--- a/internal/equipotest/direct_containment_test.go
+++ b/internal/equipotest/direct_containment_test.go
@@ -10,7 +10,7 @@ import (
)
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"} {
+ for _, change := range []string{"valid", "lost-launch-ack", "unstarted-mismatch", "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.
@@ -49,6 +49,12 @@ func TestDirectContainmentReportBinding(t *testing.T) {
}
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 "lost-launch-ack", "unstarted-mismatch":
+ p.Unstarted = p.Namespaces
+ p.Namespaces = nil
+ if change == "unstarted-mismatch" {
+ p.Unstarted[0].ManifestHash = strings.Repeat("e", 64)
+ }
case "unstarted":
p.Namespaces = nil
case "missing-namespace":
@@ -78,10 +84,10 @@ func TestDirectContainmentReportBinding(t *testing.T) {
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 {
+ if (change == "valid" || change == "unstarted" || change == "lost-launch-ack") && err != nil {
t.Fatalf("bound proof refused: %v", err)
}
- if change != "valid" && change != "unstarted" && err == nil {
+ if change != "valid" && change != "unstarted" && change != "lost-launch-ack" && err == nil {
t.Fatal("unbound proof released capacity")
}
})
diff --git a/internal/release/refresh_test.go b/internal/release/refresh_test.go
index 754ffc3a..1b5b5cb3 100644
--- a/internal/release/refresh_test.go
+++ b/internal/release/refresh_test.go
@@ -9,7 +9,7 @@ import (
func TestCertifiedRefreshExactTuple(t *testing.T) {
m := BuildManifest()
hash := strings.Repeat("a", 64)
- raw := `{"provider":"codex","provider_version":"0.165.0","launcher_version":"direct-v2","bwrap_version":"0.11.0","policy_hash":"` + hash + `","certified_refresh":{"auth_host":"auth.openai.com","evidence_sha256":"` + strings.Repeat("b", 64) + `"}}`
+ raw := `{"provider":"codex","provider_version":"0.165.0","launcher_version":"direct-v3","bwrap_version":"0.11.0","policy_hash":"` + hash + `","certified_refresh":{"auth_host":"auth.openai.com","evidence_sha256":"` + strings.Repeat("b", 64) + `"}}`
var c PolicyCertificate
if err := json.Unmarshal([]byte(raw), &c); err != nil {
t.Fatal(err)
diff --git a/internal/runner/certified/policy.go b/internal/runner/certified/policy.go
index e160d6e8..29a6da98 100644
--- a/internal/runner/certified/policy.go
+++ b/internal/runner/certified/policy.go
@@ -4,6 +4,7 @@ import (
"amadan.net/oficina/equipo/internal/release"
"amadan.net/oficina/equipo/internal/runner/egress"
"amadan.net/oficina/equipo/internal/runner/provider"
+ "fmt"
)
func Networks(m release.Manifest) []provider.NetworkContract {
@@ -19,7 +20,7 @@ func Networks(m release.Manifest) []provider.NetworkContract {
continue
}
if c.AuthHost != "" && c.AuthHost != host {
- c.AuthHost = ""
+ c.Conflict = fmt.Sprintf("certified auth host conflict for %s: %s and %s", name, c.AuthHost, host)
break
}
c.AuthHost = host
diff --git a/internal/runner/certified_network_test.go b/internal/runner/certified_network_test.go
index c16b309d..05bec8c1 100644
--- a/internal/runner/certified_network_test.go
+++ b/internal/runner/certified_network_test.go
@@ -150,3 +150,21 @@ func TestRuntimeMountsStandaloneToolProxy(t *testing.T) {
t.Fatal("helper digest not bound to policy")
}
}
+
+func TestCertifiedNetworkConflictDiagnostic(t *testing.T) {
+ m := release.BuildManifest()
+ for i, host := range []string{"auth.first.invalid", "auth.second.invalid"} {
+ hash := strings.Repeat(string(rune('a'+i)), 64)
+ evidence := strings.Repeat("d", 64)
+ m.DirectPolicies = append(m.DirectPolicies, release.PolicyCertificate{Provider: "codex", ProviderVersion: m.Codex, LauncherVersion: m.LauncherVersion, BwrapVersion: m.BwrapVersion, PolicyHash: hash, CertifiedRefresh: release.CertifiedRefresh{AuthHost: host, EvidenceSHA256: evidence}})
+ m.Certifications = append(m.Certifications, release.Certification{Provider: "codex", PolicyHash: hash, SHA256: evidence})
+ }
+ for _, n := range certified.Networks(m) {
+ if n.Provider == "codex" {
+ _, err := egress.ProviderPolicy(n, true)
+ if err == nil || !strings.Contains(err.Error(), "conflict") || !strings.Contains(err.Error(), "auth.first.invalid") || !strings.Contains(err.Error(), "auth.second.invalid") {
+ t.Fatal("missing conflict diagnostic", err)
+ }
+ }
+ }
+}
diff --git a/internal/runner/checks/namespace.go b/internal/runner/checks/namespace.go
index e73e0c38..25d0e6a3 100644
--- a/internal/runner/checks/namespace.go
+++ b/internal/runner/checks/namespace.go
@@ -24,7 +24,6 @@ func (s *CodexSandbox) runNamespace(ctx context.Context, c Command, work string,
{Source: s.goRoot, Target: "/opt/go"},
{Source: s.direct.ModuleCache, Target: "/opt/go-mod"},
{Source: s.binary, Target: "/opt/codex"},
- {Source: s.direct.RunnerBinary, Target: "/opt/equipo-runner"},
{Source: s.direct.RunnerBinary, Target: "/equipo-namespace"},
{Source: s.direct.Bwrap, Target: "/opt/bwrap"},
{Source: "/usr", Target: "/usr"},
diff --git a/internal/runner/containment/helper_version_test.go b/internal/runner/containment/helper_version_test.go
index 37d4ad79..703685a5 100644
--- a/internal/runner/containment/helper_version_test.go
+++ b/internal/runner/containment/helper_version_test.go
@@ -2,9 +2,12 @@ package containment
import (
"amadan.net/oficina/equipo/internal/release"
+ "context"
"crypto/sha256"
+ "encoding/json"
"fmt"
"os"
+ "path/filepath"
"strings"
"testing"
)
@@ -48,3 +51,77 @@ func TestNamespaceVersionTracksImplementation(t *testing.T) {
t.Fatalf("NamespaceMain or helper protocol changed; bump LauncherVersion and record its implementation: %s", digest)
}
}
+
+func TestBwrapRunsPinnedDescriptor(t *testing.T) {
+ m, l := fixture(t)
+ path := filepath.Join(t.TempDir(), "bwrap")
+ raw, err := os.ReadFile(m.cfg.Binary)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err = os.WriteFile(path, raw, 0700); err != nil {
+ t.Fatal(err)
+ }
+ cfg := m.cfg
+ cfg.Binary = path
+ m, err = New(cfg)
+ if err != nil {
+ t.Fatal(err)
+ }
+ p, err := m.StartRecorded(context.Background(), l, []string{"/usr/bin/true"}, func(_ context.Context, r Record) error {
+ if r.HostPID == 0 {
+ replacement := path + ".new"
+ if e := os.WriteFile(replacement, []byte("#!/bin/sh\nexit 99\n"), 0700); e != nil {
+ return e
+ }
+ return os.Rename(replacement, path)
+ }
+ return nil
+ })
+ if err != nil {
+ t.Fatal("executed replaced bwrap path", err)
+ }
+ defer p.Stdin().Close()
+ defer p.Stdout().Close()
+ defer p.Stderr().Close()
+ if _, err = p.Wait(context.Background()); err != nil {
+ t.Fatal(err)
+ }
+}
+
+func TestNamespaceStartupFailureWaitsForInit(t *testing.T) {
+ m, l := fixture(t)
+ called := false
+ m.waitExit = func(ctx context.Context, fd int) error {
+ called = true
+ if err := waitPID(ctx, fd); err != nil {
+ return err
+ }
+ return errIdentity
+ }
+ var record Record
+ _, err := m.StartRecorded(context.Background(), l, []string{"/usr/bin/true"}, func(_ context.Context, r Record) error {
+ record = r
+ if r.HostPID != 0 {
+ return errStartup
+ }
+ return nil
+ })
+ if err == nil {
+ t.Fatal("failed admission accepted")
+ }
+ if !called {
+ t.Fatal("PID 1 exit never observed on failed admission")
+ }
+ raw, err := os.ReadFile(filepath.Join(m.cfg.ScratchRoot, record.ID+".exit.json"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ var proof Proof
+ if err = json.Unmarshal(raw, &proof); err != nil {
+ t.Fatal(err)
+ }
+ if proof.Verified {
+ t.Fatal("failed exit observation fabricated proof")
+ }
+}
diff --git a/internal/runner/containment/linux.go b/internal/runner/containment/linux.go
index 9dbdbfa7..e79b3811 100644
--- a/internal/runner/containment/linux.go
+++ b/internal/runner/containment/linux.go
@@ -28,6 +28,7 @@ type Config struct {
ProviderNetworks []provider.NetworkContract
}
type Manager struct {
+ waitExit func(context.Context, int) error
namespaceDigest string
cfg Config
// beforePin is a test seam for replacement after attestation.
@@ -134,7 +135,7 @@ func New(cfg Config) (*Manager, error) {
if e != nil || closeErr != nil {
return nil, errors.Join(e, closeErr)
}
- return &Manager{cfg: cfg, namespaceDigest: hex.EncodeToString(h.Sum(nil)), processes: make(map[string]*process)}, nil
+ return &Manager{waitExit: waitPID, cfg: cfg, namespaceDigest: hex.EncodeToString(h.Sum(nil)), processes: make(map[string]*process)}, nil
}
func (m *Manager) Start(ctx context.Context, l provider.Launch, argv []string) (provider.Process, error) {
return m.StartRecorded(ctx, l, argv, nil)
@@ -251,7 +252,7 @@ type startResult struct {
}
const HelperProtocol = 3
-const LauncherVersion = "direct-v3"
+const LauncherVersion = provider.LauncherVersion
type readiness struct {
Protocol int
@@ -265,9 +266,10 @@ func (m *Manager) lifecycle(ctx context.Context, r Record, argv []string, mounts
defer runtime.UnlockOSThread()
cleanupScratch := true
startedProcess := false
+ startupVerified := true
defer func() {
if !startedProcess {
- proof := Proof{Record: r, Exit: provider.Exit{Code: -1, ObservedAt: time.Now().UTC()}, Verified: true}
+ proof := Proof{Record: r, Exit: provider.Exit{Code: -1, ObservedAt: time.Now().UTC()}, Verified: startupVerified}
if durableJSON(m.cfg.ScratchRoot, r.ID+".exit.json", proof) == nil {
m.finishRecovery(proof)
}
@@ -326,7 +328,7 @@ func (m *Manager) lifecycle(ctx context.Context, r Record, argv []string, mounts
return
}
args := namespaceArgs(mounts, argv)
- cmd := exec.Command(m.cfg.Binary, args...)
+ cmd := exec.Command(fmt.Sprintf("/proc/self/fd/%d", mounts.binaryFD), args...)
cmd.Env = []string{}
cmd.ExtraFiles = append([]*os.File{statusW, releaseR, readyW}, mounts.files...)
cmd.Stdin = inputR
@@ -402,6 +404,11 @@ func (m *Manager) lifecycle(ctx context.Context, r Record, argv []string, mounts
cmd.Process.Kill()
cmd.Wait()
if s.fd >= 0 {
+ waitCtx, stopWait := context.WithTimeout(context.Background(), 5*time.Second)
+ waitErr := m.waitExit(waitCtx, s.fd)
+ stopWait()
+ startupVerified = waitErr == nil
+ s.err = errors.Join(s.err, waitErr)
unix.Close(s.fd)
}
diagnostic, _ := io.ReadAll(io.LimitReader(errorR, 4096))
@@ -422,6 +429,11 @@ func (m *Manager) lifecycle(ctx context.Context, r Record, argv []string, mounts
p.kill()
cmd.Process.Kill()
cmd.Wait()
+ waitCtx, stopWait := context.WithTimeout(context.Background(), 5*time.Second)
+ waitErr := m.waitExit(waitCtx, s.fd)
+ stopWait()
+ startupVerified = waitErr == nil
+ e = errors.Join(e, waitErr)
unix.Close(s.fd)
result <- startResult{err: e}
return
@@ -663,12 +675,18 @@ func (m *Manager) namespaceManifest(l provider.Launch, argv []string, launchHash
return "", e
}
hash, e := pinnedDigest(f)
- f.Close()
+ if e == nil {
+ e = m.validatePinnedFile(l.Policy, path, hash)
+ }
if e != nil {
+ f.Close()
return "", e
}
- if e = m.validatePinnedFile(l.Policy, path, hash); e != nil {
- return "", e
+ if path == m.cfg.Binary {
+ p.binaryFD = 6 + len(p.files)
+ p.files = append(p.files, f)
+ } else {
+ f.Close()
}
files = append(files, file{Path: path, Hash: hash})
}
diff --git a/internal/runner/containment/mounts.go b/internal/runner/containment/mounts.go
index 6f8169bc..adbd16df 100644
--- a/internal/runner/containment/mounts.go
+++ b/internal/runner/containment/mounts.go
@@ -18,9 +18,10 @@ import (
var errMount = errors.New("namespace_mount_rejected")
type mounts struct {
- proxy *egress.Proxy
- args []string
- files []*os.File
+ binaryFD int
+ proxy *egress.Proxy
+ args []string
+ files []*os.File
}
func (p *mounts) close() {
diff --git a/internal/runner/containment/mounts_test.go b/internal/runner/containment/mounts_test.go
index 30d490e8..6b12ae3c 100644
--- a/internal/runner/containment/mounts_test.go
+++ b/internal/runner/containment/mounts_test.go
@@ -30,6 +30,9 @@ func TestNamespacePinnedMountSwap(t *testing.T) {
if e != nil {
t.Fatal(e)
}
+ if _, e = m.namespaceManifest(l, []string{"/usr/bin/cat", "/workspace/marker"}, l.Policy.Hash, dir, plan); e != nil {
+ t.Fatal(e)
+ }
if e = os.Rename(l.Workspace, l.Workspace+"-original"); e != nil {
t.Fatal(e)
}
diff --git a/internal/runner/diagnostics.go b/internal/runner/diagnostics.go
index fe30a97d..8868bdec 100644
--- a/internal/runner/diagnostics.go
+++ b/internal/runner/diagnostics.go
@@ -6,6 +6,7 @@ import (
"net"
"os"
+ "amadan.net/oficina/equipo/internal/runner/egress"
"amadan.net/oficina/equipo/internal/runner/provider"
)
@@ -40,6 +41,8 @@ func Diagnostic(err error) (string, string) {
var network net.Error
code := "runner.unavailable"
switch {
+ case errors.Is(err, egress.ErrConflict):
+ code = "runner.certified_auth_conflict"
case err == nil:
code = "runner.command"
case errors.Is(err, os.ErrNotExist):
diff --git a/internal/runner/direct_admission.go b/internal/runner/direct_admission.go
new file mode 100644
index 00000000..fa901ebd
--- /dev/null
+++ b/internal/runner/direct_admission.go
@@ -0,0 +1,20 @@
+package runner
+
+import (
+ "amadan.net/oficina/equipo/internal/equipo/team"
+ "amadan.net/oficina/equipo/internal/runnerproto"
+ "context"
+)
+
+func (s *Supervisor) admitDirect(ctx context.Context, r *attemptState, q runnerproto.RunnerRequest, ticket *team.AdmissionTicket) error {
+ r.InFlightAction = q.ActionID
+ r.Phase = "admitting"
+ if err := s.save(ctx, r); err != nil {
+ return err
+ }
+ if err := retryAuthority(ctx, func() error { return s.api.Call(ctx, "admit", q, ticket) }); err != nil {
+ return err
+ }
+ r.Phase = "turn"
+ return s.save(ctx, r)
+}
diff --git a/internal/runner/direct_admission_test.go b/internal/runner/direct_admission_test.go
new file mode 100644
index 00000000..61b48ee5
--- /dev/null
+++ b/internal/runner/direct_admission_test.go
@@ -0,0 +1,61 @@
+package runner
+
+import (
+ "amadan.net/oficina/equipo/internal/equipo/team"
+ "amadan.net/oficina/equipo/internal/runnerproto"
+ "context"
+ "testing"
+)
+
+func TestDirectAdmissionIntentBeforeRPC(t *testing.T) {
+ s, r, _, _ := cleanupFixture(t)
+ q := r.request("admit")
+ q.ActionID = 42
+ s.api = apiFuncR3(func(ctx context.Context, op string, _ runnerproto.RunnerRequest, _ any) error {
+ var states []attemptState
+ mustJournal(t, s.journal.readStates(ctx, "attempt", &states))
+ if len(states) != 1 || states[0].InFlightAction != 42 {
+ t.Fatal("admission reached instance before durable action intent")
+ }
+ return nil
+ })
+ var ticket team.AdmissionTicket
+ mustJournal(t, s.admitDirect(context.Background(), r, q, &ticket))
+}
+
+type recoveryCounter struct{ calls int }
+
+func (a *recoveryCounter) Call(context.Context, string, runnerproto.RunnerRequest, any) error {
+ return nil
+}
+func (a *recoveryCounter) RestoreClaim(RunClaim) error { a.calls++; return nil }
+
+type admissionFailureSource struct {
+ journal *Journal
+ polls int
+}
+
+func (a *admissionFailureSource) Poll(context.Context) ([]runnerproto.Assignment, error) {
+ a.polls++
+ if a.polls > 1 {
+ return nil, context.Canceled
+ }
+ a.journal.maxBytes = 0
+ return []runnerproto.Assignment{{ID: "work"}}, nil
+}
+func (a *admissionFailureSource) Claim(context.Context, runnerproto.ClaimRequest) (runnerproto.ClaimResponse, error) {
+ return runnerproto.ClaimResponse{}, nil
+}
+func TestServiceRecoversAdmissionFailure(t *testing.T) {
+ s, r, _, _ := cleanupFixture(t)
+ r.Direct = true
+ r.Phase = "contained"
+ mustJournal(t, s.save(context.Background(), r))
+ api := &recoveryCounter{}
+ s.api = api
+ service := Service{Supervisor: s, Source: &admissionFailureSource{journal: s.journal}}
+ _ = service.Run(context.Background())
+ if api.calls < 2 {
+ t.Fatal("admission failure skipped recovery", api.calls)
+ }
+}
diff --git a/internal/runner/direct_answer_capture.go b/internal/runner/direct_answer_capture.go
index 446b3e4a..b3adb4f3 100644
--- a/internal/runner/direct_answer_capture.go
+++ b/internal/runner/direct_answer_capture.go
@@ -22,6 +22,7 @@ func (c *captureInput) WriteAnswer(ctx context.Context, s provider.Session, turn
Method string `json:"method,omitempty"`
Params json.RawMessage `json:"params,omitempty"`
Result json.RawMessage `json:"result,omitempty"`
+ Error json.RawMessage `json:"error,omitempty"`
}
if runnerproto.DecodeLimit(bytes.NewReader(raw), &v, MaxFrameBytes) != nil || len(v.ID) == 0 || string(v.ID) == "null" {
return 0, runnerproto.ErrInvalid
@@ -31,7 +32,15 @@ func (c *captureInput) WriteAnswer(ctx context.Context, s provider.Session, turn
if json.Unmarshal(v.ID, &idString) != nil && json.Unmarshal(v.ID, &idNumber) != nil {
return 0, runnerproto.ErrInvalid
}
- if v.Method == "turn/steer" {
+ if len(v.Error) > 0 {
+ var denial struct {
+ Code int `json:"code"`
+ Message string `json:"message"`
+ }
+ if v.Method != "" || len(v.Result) > 0 || len(v.Params) > 0 || runnerproto.DecodeLimit(bytes.NewReader(v.Error), &denial, MaxFrameBytes) != nil || denial.Code != -32000 || denial.Message != provider.ErrPolicy.Error() {
+ return 0, runnerproto.ErrInvalid
+ }
+ } else if v.Method == "turn/steer" {
var p struct {
Thread string `json:"threadId"`
Expected string `json:"expectedTurnId"`
diff --git a/internal/runner/direct_events.go b/internal/runner/direct_events.go
index dc00c633..a52a329a 100644
--- a/internal/runner/direct_events.go
+++ b/internal/runner/direct_events.go
@@ -136,7 +136,10 @@ func (j *Journal) appendDirect(ctx context.Context, s provider.Session, e provid
if err = tx.QueryRowContext(ctx, "SELECT blocked,"+directPendingSize+" FROM journal_state WHERE id=1").Scan(&blocked, &size); err != nil {
return err
}
- if blocked != 0 || int64(len(body)) > j.maxBytes-size {
+ if size >= 0 && int64(len(body)) > j.maxBytes-size {
+ return ErrJournalBudget
+ }
+ if blocked != 0 || size < 0 {
return ErrJournal
}
if _, err = tx.ExecContext(ctx, "INSERT INTO direct_events(event_key,attempt,body,usage) VALUES(?,?,?,?)", key, s.AttemptKey, body, receipt); err != nil {
diff --git a/internal/runner/direct_runtime_test.go b/internal/runner/direct_runtime_test.go
index 3c1bf4e5..82e6b7d1 100644
--- a/internal/runner/direct_runtime_test.go
+++ b/internal/runner/direct_runtime_test.go
@@ -197,3 +197,22 @@ func TestDirectClaimRevalidates(t *testing.T) {
t.Fatal("configuration granted home provenance")
}
}
+
+func TestRunnerSweepsStaleDescriptionTokens(t *testing.T) {
+ c := directRuntimeFixture(t)
+ mustJournal(t, os.MkdirAll(c.ScratchRoot, 0700))
+ stale := filepath.Join(c.ScratchRoot, "describe-stale")
+ mustJournal(t, os.Mkdir(stale, 0700))
+ mustJournal(t, os.WriteFile(filepath.Join(stale, "credentials"), []byte("fake-old-token"), 0600))
+ keep := filepath.Join(c.ScratchRoot, "keep")
+ mustJournal(t, os.WriteFile(keep, []byte("keep"), 0600))
+ r, err := openRuntime(context.Background(), c)
+ mustJournal(t, err)
+ defer r.Close()
+ if _, err = os.Stat(stale); !os.IsNotExist(err) {
+ t.Fatal("stale token directory survived startup")
+ }
+ if _, err = os.Stat(keep); err != nil {
+ t.Fatal("unrelated scratch removed")
+ }
+}
diff --git a/internal/runner/direct_tools_test.go b/internal/runner/direct_tools_test.go
index 3c3a19f1..9672da7f 100644
--- a/internal/runner/direct_tools_test.go
+++ b/internal/runner/direct_tools_test.go
@@ -32,7 +32,7 @@ func TestDirectToolScope(t *testing.T) {
mustJournal(t, e)
defer p.Close()
binary := filepath.Join(t.TempDir(), "equipo-tool-proxy")
- build := exec.Command("go", "build", "-o", binary, "../../cmd/equipo-runner")
+ build := exec.Command("go", "build", "-o", binary, "../../cmd/equipo-tool-proxy")
build.Env = append(os.Environ(), "CGO_ENABLED=0")
if out, e := build.CombinedOutput(); e != nil {
t.Fatalf("build: %v %s", e, out)
@@ -526,3 +526,15 @@ func TestToolProxyRenewedLease(t *testing.T) {
t.Fatal("closed lease revived")
}
}
+
+func TestDirectAnswerProtocolError(t *testing.T) {
+ j, l, s, p := directFixture(t, "codex")
+ ctx := context.Background()
+ mustJournal(t, j.BeginTurn(ctx, s, directTurn()))
+ mustJournal(t, j.consumeTurn(ctx, s.AttemptKey, s.ID, "hello"))
+ c := &captureInput{journal: j, launch: l, process: p, input: p.Stdin(), ctx: ctx}
+ raw := []byte("{\"id\":7,\"error\":{\"code\":-32000,\"message\":\"provider_policy_rejected\"}}\n")
+ if _, err := c.WriteAnswer(ctx, s, "turn", raw); err != nil {
+ t.Fatal("protocol refusal cannot pass durable capture", err)
+ }
+}
diff --git a/internal/runner/direct_workflow.go b/internal/runner/direct_workflow.go
index 92565112..1fa5a1a0 100644
--- a/internal/runner/direct_workflow.go
+++ b/internal/runner/direct_workflow.go
@@ -190,12 +190,7 @@ func (w *BugWorkflow) directModel(ctx context.Context, s *Supervisor, r *attempt
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 {
+ if err = s.admitDirect(ctx, r, q, &ticket); err != nil {
return err
}
turn := provider.Turn{ID: r.request("turn-0").RequestID, AdmissionID: q.RequestID, Prompt: message}
diff --git a/internal/runner/egress/policy.go b/internal/runner/egress/policy.go
index 16f179ba..06679b61 100644
--- a/internal/runner/egress/policy.go
+++ b/internal/runner/egress/policy.go
@@ -6,6 +6,7 @@ import (
"encoding/hex"
"encoding/json"
"errors"
+ "fmt"
"net/netip"
"sort"
"strings"
@@ -18,11 +19,16 @@ type Policy struct {
Hosts []string
}
+var ErrConflict = errors.New("egress_certified_auth_conflict")
+
var errPolicy = errors.New("egress_policy_rejected")
// ProviderPolicy consumes an installed contract, never model or permission input.
// AuthHost remains empty until refresh certification pins an exact hostname.
func ProviderPolicy(c provider.NetworkContract, dedicated bool) (Policy, error) {
+ if c.Conflict != "" {
+ return Policy{}, fmt.Errorf("%w: %s", ErrConflict, c.Conflict)
+ }
p := Policy{Provider: c.Provider}
switch c.Provider {
case "claude":
diff --git a/internal/runner/forge/approval_profile_test.go b/internal/runner/forge/approval_profile_test.go
index 179b9c4d..4545718b 100644
--- a/internal/runner/forge/approval_profile_test.go
+++ b/internal/runner/forge/approval_profile_test.go
@@ -14,8 +14,13 @@ func TestApprovedBeyondProfilePublisher(t *testing.T) {
approval := team.ProfileApproval{QuestionID: "q", RequestID: "7", ItemID: "item", TurnID: "turn", SessionID: "session", Person: "owner@example.com", Label: "approved beyond profile", Request: json.RawMessage(`{"command":"printf hello","cwd":"/workspace"}`)}
f.auth.Publication.Isolation.ProfileApprovals = []team.ProfileApproval{approval}
for _, label := range []string{"unconfined", "unconfined; approved beyond profile"} {
- f.auth.Publication.Description = label
- f.auth.Publication.DescriptionHash = Digest([]byte(label))
+ desc := team.PublicationDescription{Version: 1, Label: label, Isolation: f.auth.Publication.Isolation}
+ if !strings.Contains(label, approval.Label) {
+ desc.Isolation.ProfileApprovals = nil
+ }
+ description, _ := json.Marshal(desc)
+ f.auth.Publication.Description = string(description)
+ f.auth.Publication.DescriptionHash = Digest([]byte(f.auth.Publication.Description))
raw, _ := json.Marshal(f.auth.Publication)
raw, hash, _ := Canonical(raw)
f.auth.Ticket.Dispatch.Payload, f.auth.Ticket.Dispatch.Hash = raw, hash
@@ -30,3 +35,33 @@ func TestApprovedBeyondProfilePublisher(t *testing.T) {
t.Fatal("published branch description lost label")
}
}
+
+func TestPublisherChecksDecodedProfileApproval(t *testing.T) {
+ f := newFixture(t)
+ approval := team.ProfileApproval{QuestionID: "q", RequestID: "7", ItemID: "item", TurnID: "turn", SessionID: "session", Person: "owner@example.com", Label: "approved beyond profile", Request: json.RawMessage(`{"command":"printf hello"}`)}
+ f.auth.Publication.Isolation.ProfileApprovals = []team.ProfileApproval{approval}
+ desc := team.PublicationDescription{Version: 1, Label: "unconfined", Isolation: f.auth.Publication.Isolation}
+ for _, valid := range []bool{false, true} {
+ if !valid {
+ desc.Isolation.ProfileApprovals = nil
+ } else {
+ desc.Isolation = f.auth.Publication.Isolation
+ }
+ raw, _ := json.Marshal(desc)
+ body := string(raw)
+ if !valid {
+ body = strings.Replace(body, `"label":"unconfined"`, `"label":"unconfined; approved beyond profile"`, 1)
+ } else {
+ body = strings.ReplaceAll(body, "approved beyond profile", `approved beyond pro\u0066ile`)
+ }
+ f.auth.Publication.Description = body
+ f.auth.Publication.DescriptionHash = Digest([]byte(body))
+ payload, _ := json.Marshal(f.auth.Publication)
+ payload, hash, _ := Canonical(payload)
+ f.auth.Ticket.Dispatch.Payload, f.auth.Ticket.Dispatch.Hash = payload, hash
+ err := f.p.validate(f.auth, f.auth.Ticket.Dispatch)
+ if (err == nil) != valid {
+ t.Fatalf("decoded approval valid=%v: %v", valid, err)
+ }
+ }
+}
diff --git a/internal/runner/forge/description.go b/internal/runner/forge/description.go
index 6ee605d2..febfd9dd 100644
--- a/internal/runner/forge/description.go
+++ b/internal/runner/forge/description.go
@@ -41,7 +41,9 @@ func ReadBranchDescription(ctx context.Context, client *http.Client, cred Creden
req.Header.Set("Authorization", "Bearer "+cred.Bearer)
req.Header.Set("Accept", "application/json")
if client == nil {
- client = http.DefaultClient
+ transport := &http.Transport{Proxy: nil}
+ defer transport.CloseIdleConnections()
+ client = &http.Client{Transport: transport}
}
local := *client
local.Jar = nil
diff --git a/internal/runner/forge/description_test.go b/internal/runner/forge/description_test.go
index 7acd912a..a1bbfa09 100644
--- a/internal/runner/forge/description_test.go
+++ b/internal/runner/forge/description_test.go
@@ -332,3 +332,19 @@ func TestAmadanDescriptionNotDispatched(t *testing.T) {
})
}
}
+
+func TestDescriptionIgnoresDefaultProxyClient(t *testing.T) {
+ old := http.DefaultClient
+ defer func() { http.DefaultClient = old }()
+ called := false
+ http.DefaultClient = &http.Client{Transport: descriptionRoundTrip(func(*http.Request) (*http.Response, error) {
+ called = true
+ return nil, errors.New("default proxy reached")
+ })}
+ ctx, cancel := context.WithCancel(context.Background())
+ cancel()
+ _, _ = ReadBranchDescription(ctx, nil, Credential{Remote: "https://amadan.net/oficina/equipo", Agent: "equipo~owner@example.com", Bearer: "fake-only"}, "amadan.net/oficina/equipo", "heads/fix")
+ if called {
+ t.Fatal("description used ambient proxy client")
+ }
+}
diff --git a/internal/runner/forge/description_transport.go b/internal/runner/forge/description_transport.go
index 1c7c7f28..2e384565 100644
--- a/internal/runner/forge/description_transport.go
+++ b/internal/runner/forge/description_transport.go
@@ -93,3 +93,19 @@ func (w commandDescriptionWriter) Set(ctx context.Context, c Credential, d Descr
}
return nil
}
+
+// SweepDescriptions runs under the runner state lock before new commands start.
+func SweepDescriptions(root string) error {
+ entries, err := os.ReadDir(root)
+ if err != nil {
+ return err
+ }
+ for _, entry := range entries {
+ if strings.HasPrefix(entry.Name(), "describe-") && entry.IsDir() {
+ if err = os.RemoveAll(filepath.Join(root, entry.Name())); err != nil {
+ return err
+ }
+ }
+ }
+ return nil
+}
diff --git a/internal/runner/forge/publisher.go b/internal/runner/forge/publisher.go
index 2a50348b..347de1f1 100644
--- a/internal/runner/forge/publisher.go
+++ b/internal/runner/forge/publisher.go
@@ -129,11 +129,13 @@ func (p *Publisher) validate(a Authorization, d team.Dispatch) error {
return team.ErrEvidence
}
iso := v.Isolation
- for _, approval := range iso.ProfileApprovals {
- if !strings.Contains(v.Description, approval.Label) {
+ if len(iso.ProfileApprovals) > 0 {
+ var description team.PublicationDescription
+ if json.Unmarshal([]byte(v.Description), &description) != nil || description.Version != 1 || !reflect.DeepEqual(description.Isolation.ProfileApprovals, iso.ProfileApprovals) {
return team.ErrEvidence
}
}
+
if !iso.Valid() || (iso.Trial != nil && !strings.Contains(v.Description, "supervised trial")) || ((iso.RunnerTainted || iso.Status == "unconfined") && !strings.Contains(v.Description, "unconfined")) {
return team.ErrEvidence
}
diff --git a/internal/runner/journal.go b/internal/runner/journal.go
index 9e3c1637..29b673d2 100644
--- a/internal/runner/journal.go
+++ b/internal/runner/journal.go
@@ -229,7 +229,10 @@ func (j *Journal) appendTx(ctx context.Context, tx *sql.Tx, e Event, hash string
if err = tx.QueryRowContext(ctx, "SELECT blocked,"+directPendingSize+" FROM journal_state WHERE id=1").Scan(&blocked, &size); err != nil {
return err
}
- if blocked != 0 || size < 0 || int64(len(body)) > j.maxBytes-size {
+ if size >= 0 && int64(len(body)) > j.maxBytes-size {
+ return ErrJournalBudget
+ }
+ if blocked != 0 || size < 0 {
return ErrJournal
}
if _, err = tx.ExecContext(ctx, "INSERT INTO journal_events(id,event_key,content_hash,body,size) VALUES(?,?,?,?,?)", e.ID, key, hash, body, len(body)); err != nil {
diff --git a/internal/runner/preflight_cache_test.go b/internal/runner/preflight_cache_test.go
index 1b5b7a22..988917f7 100644
--- a/internal/runner/preflight_cache_test.go
+++ b/internal/runner/preflight_cache_test.go
@@ -70,3 +70,29 @@ func TestDirectPreflightCache(t *testing.T) {
t.Fatal("failure retained")
}
}
+
+func TestPendingBudgetsDoNotLatch(t *testing.T) {
+ for _, kind := range []string{"event", "direct-event", "tool"} {
+ t.Run(kind, func(t *testing.T) {
+ j, _, s, _ := directFixture(t, "codex")
+ ctx := context.Background()
+ j.maxBytes = 1
+ var err error
+ switch kind {
+ case "event":
+ err = j.Append(ctx, journalEvent("budget", 1))
+ case "direct-event":
+ _, err = j.ObserveDirect(ctx, s, provider.Event{Kind: "timeline", SessionID: s.ID, Payload: []byte(`{"message":"hello"}`)})
+ case "tool":
+ err = j.appendTool(ctx, ToolSubmission{RequestID: "budget"}, "hash")
+ }
+ if err == nil {
+ t.Fatal("overrun accepted")
+ }
+ j.maxBytes = MaxJournalBytes
+ if err = j.AdmissionAllowed(ctx); err != nil {
+ t.Fatal("budget refusal latched storage", err)
+ }
+ })
+ }
+}
diff --git a/internal/runner/provider/accounts.go b/internal/runner/provider/accounts.go
index 282ec023..f7a02871 100644
--- a/internal/runner/provider/accounts.go
+++ b/internal/runner/provider/accounts.go
@@ -587,6 +587,9 @@ func (l *AccountLease) check(ctx context.Context, probe func(context.Context, Bi
return ErrPreflightRequired
}
if refresh {
+ if before != l.generation {
+ return ErrPreflightRequired
+ }
if e = atomicPrivate(l.dir, credentialName(l.source.Provider), runtimeAfter); e != nil {
return e
}
@@ -624,6 +627,9 @@ func (l *AccountLease) ValidatePolicy(ctx context.Context) error {
return l.validatePolicy()
}
func (l *AccountLease) validatePolicy() error {
+ if err := l.validateRuntimeEntries(); err != nil {
+ return err
+ }
if l.policy == nil {
return nil
}
diff --git a/internal/runner/provider/accounts_test.go b/internal/runner/provider/accounts_test.go
index 26ec61b6..44fd36dd 100644
--- a/internal/runner/provider/accounts_test.go
+++ b/internal/runner/provider/accounts_test.go
@@ -9,6 +9,7 @@ import (
"os/user"
"path/filepath"
"strconv"
+ "strings"
"testing"
)
@@ -715,3 +716,61 @@ func TestAccountRefreshFailure(t *testing.T) {
})
}
}
+
+func TestRuntimeHomeRejectsPolicyInjection(t *testing.T) {
+ for _, name := range []string{"config.toml", "AGENTS.md", "CLAUDE.md", "settings.json", "hooks", "sessions/AGENTS.md"} {
+ for _, resume := range []bool{false, true} {
+ t.Run(fmt.Sprint(name, resume), func(t *testing.T) {
+ b, r := accountFixture(t)
+ l := openFixture(t, b, r)
+ preflightFixture(t, l)
+ path := filepath.Join(l.Binding().Home, name)
+ if err := os.MkdirAll(filepath.Dir(path), 0700); err != nil {
+ t.Fatal(err)
+ }
+ writeFake(t, path, "injected policy")
+ var err error
+ if resume {
+ err = l.ValidatePolicy(context.Background())
+ } else {
+ err = l.BeginTurn(context.Background())
+ }
+ if err == nil {
+ t.Fatal("runtime policy injection accepted")
+ }
+ })
+ }
+ }
+}
+func TestRefreshDoesNotOverwriteNewerSource(t *testing.T) {
+ b, r := accountFixture(t)
+ l := openFixture(t, b, r)
+ preflightFixture(t, l)
+ writeFake(t, filepath.Join(l.Binding().Home, "auth.json"), `{"token":"refreshed"}`)
+ writeFake(t, filepath.Join(b.Home, "auth.json"), `{"token":"newer-source"}`)
+ if err := l.CommitRefresh(context.Background(), func(context.Context, Binding) (Identity, error) { return b.Expected, nil }); err == nil {
+ t.Fatal("new source overwritten by older refresh")
+ }
+ raw, _ := os.ReadFile(filepath.Join(b.Home, "auth.json"))
+ if !strings.Contains(string(raw), "newer-source") {
+ t.Fatal("newer login lost")
+ }
+}
+
+func TestPreflightFingerprintTracksSource(t *testing.T) {
+ b, r := accountFixture(t)
+ l := openFixture(t, b, r)
+ first, err := l.PreflightFingerprint(context.Background())
+ if err != nil {
+ t.Fatal(err)
+ }
+ again, err := l.PreflightFingerprint(context.Background())
+ if err != nil || again != first {
+ t.Fatal("unchanged source invalidated cache", err)
+ }
+ writeFake(t, filepath.Join(b.Home, "auth.json"), `{"token":"different"}`)
+ changed, err := l.PreflightFingerprint(context.Background())
+ if err != nil || changed == first {
+ t.Fatal("source generation omitted from cache key", err)
+ }
+}
diff --git a/internal/runner/provider/check_policy.go b/internal/runner/provider/check_policy.go
index 557cad2f..2075d2f8 100644
--- a/internal/runner/provider/check_policy.go
+++ b/internal/runner/provider/check_policy.go
@@ -35,8 +35,8 @@ func BuildCheckPolicy(in CheckPolicyInputs) (Policy, error) {
}
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] {
+ m.OuterMounts = []Mount{{Source: in.Binary, Target: "/opt/codex", 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[:2] {
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
diff --git a/internal/runner/provider/claude/launcher_test.go b/internal/runner/provider/claude/launcher_test.go
index 074539fc..5d1a4343 100644
--- a/internal/runner/provider/claude/launcher_test.go
+++ b/internal/runner/provider/claude/launcher_test.go
@@ -24,7 +24,7 @@ import (
const fakeCLI = `import sys,json,os
args=sys.argv[1:]
-with open(os.path.join(os.environ['CLAUDE_CONFIG_DIR'],'settings.json'),'w') as config: config.write('{"trust":"fake-cli-write"}')
+with open(os.path.join(os.environ['CLAUDE_CONFIG_DIR'],'history.jsonl'),'w') as config: config.write('{"trust":"fake-cli-write"}')
if 'auth' in args:
try:
with open(os.path.join(os.environ['CLAUDE_CONFIG_DIR'],'.claude.json')) as f: email=json.load(f).get('oauthAccount',{}).get('emailAddress')
@@ -420,7 +420,7 @@ func TestClaudeNoPromptBeforeAdmission(t *testing.T) {
if e := f.l.Close(context.Background(), s); e != nil {
t.Fatal(e)
}
- runtimeConfig, _ := os.ReadFile(filepath.Join(f.lease.Binding().Home, "settings.json"))
+ runtimeConfig, _ := os.ReadFile(filepath.Join(f.lease.Binding().Home, "history.jsonl"))
if string(runtimeConfig) != `{"trust":"fake-cli-write"}` {
t.Fatal("fake did not exercise config writes")
}
diff --git a/internal/runner/provider/codex/answers.go b/internal/runner/provider/codex/answers.go
index 963bc06f..5f4eb255 100644
--- a/internal/runner/provider/codex/answers.go
+++ b/internal/runner/provider/codex/answers.go
@@ -130,6 +130,12 @@ func (l *Launcher) respond(ctx context.Context, session provider.Session, a prov
if e != nil {
return e
}
+ if a.Behavior == "deny" && len(a.Input) == 0 && (v.Method == "item/tool/requestUserInput" || !supportedRequest(v.Method)) {
+ s.mu.Lock()
+ delete(s.requests, a.RequestID)
+ s.mu.Unlock()
+ return s.rpc.answer(ctx, session, a.TurnID, requestRefusal(a.RequestID))
+ }
var result any
steer := false
keys, keyErr := QuestionKeys(ev)
@@ -247,3 +253,14 @@ func (l *Launcher) respond(ctx context.Context, session provider.Session, a prov
}
return s.rpc.answer(ctx, session, a.TurnID, map[string]any{"id": json.RawMessage(a.RequestID), "result": result})
}
+
+func supportedRequest(method string) bool {
+ switch method {
+ case "item/commandExecution/requestApproval", "item/fileChange/requestApproval", "mcpServer/elicitation/request", "execCommandApproval", "applyPatchApproval", "item/tool/requestUserInput", "item/completed":
+ return true
+ }
+ return false
+}
+func requestRefusal(id string) any {
+ return map[string]any{"id": json.RawMessage(id), "error": map[string]any{"code": -32000, "message": provider.ErrPolicy.Error()}}
+}
diff --git a/internal/runner/provider/codex/answers_test.go b/internal/runner/provider/codex/answers_test.go
index 9961f1e3..440db5d5 100644
--- a/internal/runner/provider/codex/answers_test.go
+++ b/internal/runner/provider/codex/answers_test.go
@@ -300,3 +300,32 @@ func TestCodexApprovalResponseInvalidAuthorizationWire(t *testing.T) {
})
}
}
+
+func TestCodexRefusesUnsupportedRequests(t *testing.T) {
+ for _, method := range []string{"item/permissions/requestApproval", "async/requestUserInput", "unlisted/request", "item/tool/requestUserInput"} {
+ t.Run(method, func(t *testing.T) {
+ l, s, w, _ := answerFixture(t)
+ raw := fmt.Sprintf(`{"id":7,"method":%q,"params":{"threadId":%q,"turnId":"provider-turn","questions":[{"id":"q"}]}}`, method, s.session.ID)
+ if err := s.handle(provider.Frame{Sequence: 99, Bytes: []byte(raw)}); err != nil {
+ t.Fatal(err)
+ }
+ if supportedRequest(method) {
+ if err := l.Respond(context.Background(), s.session, provider.Answer{RequestID: "7", TurnID: "local-turn", Behavior: "deny"}); err != nil {
+ t.Fatal("cannot refuse server request", err)
+ }
+ }
+ select {
+ case raw := <-w.sent:
+ var reply struct {
+ ID json.RawMessage
+ Error json.RawMessage
+ }
+ if json.Unmarshal(raw, &reply) != nil || len(reply.Error) == 0 {
+ t.Fatal("missing protocol refusal", string(raw))
+ }
+ case <-time.After(time.Second):
+ t.Fatal("request left hanging")
+ }
+ })
+ }
+}
diff --git a/internal/runner/provider/codex/launcher.go b/internal/runner/provider/codex/launcher.go
index f82d06b8..739767ac 100644
--- a/internal/runner/provider/codex/launcher.go
+++ b/internal/runner/provider/codex/launcher.go
@@ -800,6 +800,9 @@ func (s *sessionState) handle(frame provider.Frame) error {
}
}
if ev.Kind == "request" {
+ if !supportedRequest(envelope.Method) {
+ return s.rpc.answer(s.ctx, s.session, s.turn.ID, requestRefusal(ev.RequestID))
+ }
s.correlateMCP(&ev)
s.correlateNative(&ev)
if s.requests == nil {
@@ -908,3 +911,6 @@ func configSubset(want, got []byte) bool {
}
return true
}
+
+// ConfigMatchesReadback validates a captured effective config with the adapter's rules.
+func ConfigMatchesReadback(raw []byte, p provider.Policy) bool { return validateConfig(raw, p) == nil }
diff --git a/internal/runner/provider/codex/launcher_test.go b/internal/runner/provider/codex/launcher_test.go
index 34c5f311..40b9b28e 100644
--- a/internal/runner/provider/codex/launcher_test.go
+++ b/internal/runner/provider/codex/launcher_test.go
@@ -79,7 +79,7 @@ func (h *fakeHost) Start(ctx context.Context, l provider.Launch, args []string)
defer in.Close()
defer out.Close()
// Simulate an app-server writing only its constructed home.
- os.WriteFile(filepath.Join(l.Binding.Home, "config.toml"), []byte("# private fake config\n"), 0600)
+ os.WriteFile(filepath.Join(l.Binding.Home, "history.jsonl"), []byte("# private fake config\n"), 0600)
scan := bufio.NewScanner(in)
scan.Buffer(make([]byte, 4096), MaxFrameBytes)
send := func(v any) { raw, _ := json.Marshal(v); out.Write(append(raw, '\n')) }
diff --git a/internal/runner/provider/codex/native_approval.go b/internal/runner/provider/codex/native_approval.go
index ca30c7ac..a16d3e97 100644
--- a/internal/runner/provider/codex/native_approval.go
+++ b/internal/runner/provider/codex/native_approval.go
@@ -1,83 +1,14 @@
package codex
import (
+ "amadan.net/oficina/equipo/internal/runner/provider"
"bytes"
"encoding/json"
-
- "amadan.net/oficina/equipo/internal/runner/provider"
)
-// NativeRequest retains the exact request and correlated file item. It carries
-// evidence, never a policy update or a replacement command.
-type NativeRequest struct {
- RequestID string `json:"request_id"`
- ItemID string `json:"item_id"`
- TurnID string `json:"turn_id"`
- SessionID string `json:"session_id"`
- Request json.RawMessage `json:"request"`
- ToolCall json.RawMessage `json:"tool_call,omitempty"`
-}
-
-func NativeApproval(ev provider.Event) (NativeRequest, error) {
- n := NativeRequest{RequestID: ev.RequestID, Request: bytes.Clone(ev.Payload)}
- v, err := parse(ev.Payload)
- if err != nil || string(v.ID) != ev.RequestID {
- return n, provider.ErrPolicy
- }
- if v.Method == "execCommandApproval" || v.Method == "applyPatchApproval" {
- return legacyNativeApproval(ev, v)
- }
- var p struct {
- ThreadID, TurnID, ItemID, Command, Cwd, Kind, GrantRoot string
- }
- if json.Unmarshal(v.Params, &p) != nil || p.ThreadID == "" || p.ThreadID != ev.SessionID || p.GrantRoot != "" || p.TurnID == "" || (ev.ProviderTurnID != "" && ev.ProviderTurnID != p.TurnID) || p.ItemID == "" {
- return n, provider.ErrPolicy
- }
- n.ItemID, n.TurnID, n.SessionID = p.ItemID, p.TurnID, p.ThreadID
- switch v.Method {
- case "item/commandExecution/requestApproval":
- if p.Command == "" || p.Cwd == "" || (p.Kind != "" && p.Kind != "command") {
- return n, provider.ErrPolicy
- }
- case "item/fileChange/requestApproval":
- call, err := parse(ev.ToolCall)
- if err != nil || call.Method != "item/started" {
- return n, provider.ErrPolicy
- }
- var c struct {
- ThreadID, TurnID string
- Item struct {
- ID, Type, Status string
- Changes []struct {
- Path string
- Diff *string
- Kind struct {
- Type string
- MovePath *string `json:"move_path"`
- }
- }
- }
- }
- if json.Unmarshal(call.Params, &c) != nil || c.ThreadID != p.ThreadID || c.TurnID != p.TurnID || c.Item.ID != p.ItemID || c.Item.Type != "fileChange" || c.Item.Status != "inProgress" || len(c.Item.Changes) == 0 {
- return n, provider.ErrPolicy
- }
- for _, change := range c.Item.Changes {
- if change.Path == "" || change.Diff == nil {
- return n, provider.ErrPolicy
- }
- switch change.Kind.Type {
- case "add", "delete", "update":
- default:
- return n, provider.ErrPolicy
- }
- }
- n.ToolCall = bytes.Clone(ev.ToolCall)
- default:
- return n, provider.ErrPolicy
- }
- return n, nil
-}
+type NativeRequest = provider.NativeRequest
+func NativeApproval(ev provider.Event) (NativeRequest, error) { return provider.NativeApproval(ev) }
func (s *sessionState) correlateNative(ev *provider.Event) {
v, err := parse(ev.Payload)
if err != nil || v.Method != "item/fileChange/requestApproval" {
@@ -88,52 +19,3 @@ func (s *sessionState) correlateNative(ev *provider.Event) {
ev.ToolCall = bytes.Clone(s.nativeCalls[p.ItemID])
}
}
-
-func legacyNativeApproval(ev provider.Event, v envelope) (NativeRequest, error) {
- n := NativeRequest{RequestID: ev.RequestID, Request: bytes.Clone(ev.Payload), TurnID: ev.ProviderTurnID}
- var p struct {
- ConversationID, CallID, Cwd, GrantRoot string
- Command []string
- FileChanges map[string]struct {
- Type string
- Content, UnifiedDiff *string
- MovePath *string `json:"move_path"`
- }
- }
- // Legacy update diffs use snake case.
- var changes struct{ FileChanges map[string]json.RawMessage }
- if json.Unmarshal(v.Params, &p) != nil || p.ConversationID != ev.SessionID || p.ConversationID == "" || p.CallID == "" || p.GrantRoot != "" || ev.ProviderTurnID == "" {
- return n, provider.ErrPolicy
- }
- n.SessionID, n.ItemID = p.ConversationID, p.CallID
- if v.Method == "execCommandApproval" {
- if len(p.Command) == 0 || p.Command[0] == "" || p.Cwd == "" {
- return n, provider.ErrPolicy
- }
- } else {
- if len(p.FileChanges) == 0 || json.Unmarshal(v.Params, &changes) != nil {
- return n, provider.ErrPolicy
- }
- for path, change := range p.FileChanges {
- if path == "" {
- return n, provider.ErrPolicy
- }
- switch change.Type {
- case "add", "delete":
- if change.Content == nil {
- return n, provider.ErrPolicy
- }
- case "update":
- var c struct {
- Diff *string `json:"unified_diff"`
- }
- if json.Unmarshal(changes.FileChanges[path], &c) != nil || c.Diff == nil {
- return n, provider.ErrPolicy
- }
- default:
- return n, provider.ErrPolicy
- }
- }
- }
- return n, nil
-}
diff --git a/internal/runner/provider/direct_certification.go b/internal/runner/provider/direct_certification.go
index 50cfd5c4..6da96010 100644
--- a/internal/runner/provider/direct_certification.go
+++ b/internal/runner/provider/direct_certification.go
@@ -140,7 +140,7 @@ func (e DirectEvidence) ValidateGroup(root, group string) error {
}
}
required := DirectRequirements(group)
- if len(required) == 0 || e.Schema != 1 || e.Source != "direct-live" || e.RunID == "" || e.LauncherVersion != "direct-v2" || e.BwrapVersion != "0.11.0" || e.PolicyVersion != PolicyVersion || !liveDigest(e.PolicyHash) || !liveDigest(e.ConfigSHA256) || e.AccountID == "" || e.HomeID == "" || e.Model == "" || !liveAuthHost(e.AuthHost) {
+ if len(required) == 0 || e.Schema != 1 || e.Source != "direct-live" || e.RunID == "" || e.LauncherVersion != LauncherVersion || e.BwrapVersion != "0.11.0" || e.PolicyVersion != PolicyVersion || !liveDigest(e.PolicyHash) || !liveDigest(e.ConfigSHA256) || e.AccountID == "" || e.HomeID == "" || e.Model == "" || !liveAuthHost(e.AuthHost) {
return ErrPolicy
}
version := map[string]string{"claude": "2.1.312", "codex": "0.165.0"}[e.Provider]
diff --git a/internal/runner/provider/direct_certification_test.go b/internal/runner/provider/direct_certification_test.go
index 7a9a4dd5..58d99d77 100644
--- a/internal/runner/provider/direct_certification_test.go
+++ b/internal/runner/provider/direct_certification_test.go
@@ -30,7 +30,7 @@ func directEvidenceFixture(t *testing.T) (DirectEvidence, string) {
t.Fatal(err)
}
observation := LiveObservation{Status: "pass", Artifact: "capture.json", SHA256: DigestDirectEvidence(raw), Detail: "synthetic unit-test fixture"}
- e := DirectEvidence{Artifacts: map[string]string{"capture.json": DigestDirectEvidence(raw)}, Schema: 1, Source: "direct-live", RunID: "fixture", Provider: "codex", ProviderVersion: "0.165.0", LauncherVersion: "direct-v2", BwrapVersion: "0.11.0", PolicyVersion: PolicyVersion, PolicyHash: strings.Repeat("a", 64), AccountID: "fixture", HomeID: "fixture", Model: "fixture", AuthHost: "auth.example.com", ConfigSHA256: strings.Repeat("b", 64), Binaries: map[string]string{}, Checks: map[string]LiveObservation{}, Usage: []LiveUsage{{Input: 1, Output: 1, Complete: true}}, Funding: LiveFunding{Calls: 1, InputTokens: 1000, OutputTokens: 1000, Seconds: 60, JobInput: 23000, JobOutput: 23000, ProjectInputHeadroom: 23000, ProjectOutputHeadroom: 23000, TeamInputHeadroom: 23000, TeamOutputHeadroom: 23000}, CodexPolicy: &LiveCodexPolicy{ApprovalPolicy: "on-request", ApprovalsReviewer: "user", StrictConfig: true, DenyProfile: true}}
+ e := DirectEvidence{Artifacts: map[string]string{"capture.json": DigestDirectEvidence(raw)}, Schema: 1, Source: "direct-live", RunID: "fixture", Provider: "codex", ProviderVersion: "0.165.0", LauncherVersion: LauncherVersion, BwrapVersion: "0.11.0", PolicyVersion: PolicyVersion, PolicyHash: strings.Repeat("a", 64), AccountID: "fixture", HomeID: "fixture", Model: "fixture", AuthHost: "auth.example.com", ConfigSHA256: strings.Repeat("b", 64), Binaries: map[string]string{}, Checks: map[string]LiveObservation{}, Usage: []LiveUsage{{Input: 1, Output: 1, Complete: true}}, Funding: LiveFunding{Calls: 1, InputTokens: 1000, OutputTokens: 1000, Seconds: 60, JobInput: 23000, JobOutput: 23000, ProjectInputHeadroom: 23000, ProjectOutputHeadroom: 23000, TeamInputHeadroom: 23000, TeamOutputHeadroom: 23000}, CodexPolicy: &LiveCodexPolicy{ApprovalPolicy: "on-request", ApprovalsReviewer: "user", StrictConfig: true, DenyProfile: true}}
for _, name := range []string{"claude", "codex", "codex-code-mode-host", "bwrap", "runner", "equipo-tool-proxy"} {
e.Binaries[name] = strings.Repeat("c", 64)
}
diff --git a/internal/runner/provider/native_approval.go b/internal/runner/provider/native_approval.go
new file mode 100644
index 00000000..aa60054d
--- /dev/null
+++ b/internal/runner/provider/native_approval.go
@@ -0,0 +1,141 @@
+package provider
+
+import (
+ "bytes"
+ "encoding/json"
+)
+
+// NativeRequest retains the exact request and correlated file item. It carries
+// evidence, never a policy update or a replacement command.
+type NativeRequest struct {
+ AdditionalPermissions json.RawMessage `json:"additional_permissions,omitempty"`
+ NetworkApprovalContext json.RawMessage `json:"network_approval_context,omitempty"`
+ ApprovalID string `json:"approval_id,omitempty"`
+ RequestID string `json:"request_id"`
+ ItemID string `json:"item_id"`
+ TurnID string `json:"turn_id"`
+ SessionID string `json:"session_id"`
+ Request json.RawMessage `json:"request"`
+ ToolCall json.RawMessage `json:"tool_call,omitempty"`
+}
+
+func NativeApproval(ev Event) (NativeRequest, error) {
+ n := NativeRequest{RequestID: ev.RequestID, Request: bytes.Clone(ev.Payload)}
+ v, err := parseNative(ev.Payload)
+ if err != nil || string(v.ID) != ev.RequestID {
+ return n, ErrPolicy
+ }
+ if v.Method == "execCommandApproval" || v.Method == "applyPatchApproval" {
+ return legacyNativeApproval(ev, v)
+ }
+ var p struct {
+ ThreadID, TurnID, ItemID, Command, Cwd, Kind, GrantRoot, ApprovalID string
+ AdditionalPermissions, NetworkApprovalContext json.RawMessage
+ }
+ if json.Unmarshal(v.Params, &p) != nil || p.ThreadID == "" || p.ThreadID != ev.SessionID || p.GrantRoot != "" || p.TurnID == "" || (ev.ProviderTurnID != "" && ev.ProviderTurnID != p.TurnID) || p.ItemID == "" {
+ return n, ErrPolicy
+ }
+ n.ItemID, n.TurnID, n.SessionID = p.ItemID, p.TurnID, p.ThreadID
+ n.AdditionalPermissions, n.NetworkApprovalContext, n.ApprovalID = bytes.Clone(p.AdditionalPermissions), bytes.Clone(p.NetworkApprovalContext), p.ApprovalID
+ if len(p.NetworkApprovalContext) > 0 && string(p.NetworkApprovalContext) != "null" {
+ return n, ErrPolicy
+ }
+ var extra struct{ Network json.RawMessage }
+ if len(p.AdditionalPermissions) > 0 && json.Unmarshal(p.AdditionalPermissions, &extra) != nil {
+ return n, ErrPolicy
+ }
+ if len(extra.Network) > 0 && string(extra.Network) != "null" {
+ return n, ErrPolicy
+ }
+ switch v.Method {
+ case "item/commandExecution/requestApproval":
+ if p.Command == "" || p.Cwd == "" || (p.Kind != "" && p.Kind != "command") {
+ return n, ErrPolicy
+ }
+ case "item/fileChange/requestApproval":
+ call, err := parseNative(ev.ToolCall)
+ if err != nil || call.Method != "item/started" {
+ return n, ErrPolicy
+ }
+ var c struct {
+ ThreadID, TurnID string
+ Item struct {
+ ID, Type, Status string
+ Changes []struct {
+ Path string
+ Diff *string
+ Kind struct {
+ Type string
+ MovePath *string `json:"move_path"`
+ }
+ }
+ }
+ }
+ if json.Unmarshal(call.Params, &c) != nil || c.ThreadID != p.ThreadID || c.TurnID != p.TurnID || c.Item.ID != p.ItemID || c.Item.Type != "fileChange" || c.Item.Status != "inProgress" || len(c.Item.Changes) == 0 {
+ return n, ErrPolicy
+ }
+ for _, change := range c.Item.Changes {
+ if change.Path == "" || change.Diff == nil {
+ return n, ErrPolicy
+ }
+ switch change.Kind.Type {
+ case "add", "delete", "update":
+ default:
+ return n, ErrPolicy
+ }
+ }
+ n.ToolCall = bytes.Clone(ev.ToolCall)
+ default:
+ return n, ErrPolicy
+ }
+ return n, nil
+}
+
+func legacyNativeApproval(ev Event, v nativeEnvelope) (NativeRequest, error) {
+ n := NativeRequest{RequestID: ev.RequestID, Request: bytes.Clone(ev.Payload), TurnID: ev.ProviderTurnID}
+ var p struct {
+ ConversationID, CallID, Cwd, GrantRoot string
+ Command []string
+ FileChanges map[string]struct {
+ Type string
+ Content, UnifiedDiff *string
+ MovePath *string `json:"move_path"`
+ }
+ }
+ // Legacy update diffs use snake case.
+ var changes struct{ FileChanges map[string]json.RawMessage }
+ if json.Unmarshal(v.Params, &p) != nil || p.ConversationID != ev.SessionID || p.ConversationID == "" || p.CallID == "" || p.GrantRoot != "" || ev.ProviderTurnID == "" {
+ return n, ErrPolicy
+ }
+ n.SessionID, n.ItemID = p.ConversationID, p.CallID
+ if v.Method == "execCommandApproval" {
+ if len(p.Command) == 0 || p.Command[0] == "" || p.Cwd == "" {
+ return n, ErrPolicy
+ }
+ } else {
+ if len(p.FileChanges) == 0 || json.Unmarshal(v.Params, &changes) != nil {
+ return n, ErrPolicy
+ }
+ for path, change := range p.FileChanges {
+ if path == "" {
+ return n, ErrPolicy
+ }
+ switch change.Type {
+ case "add", "delete":
+ if change.Content == nil {
+ return n, ErrPolicy
+ }
+ case "update":
+ var c struct {
+ Diff *string `json:"unified_diff"`
+ }
+ if json.Unmarshal(changes.FileChanges[path], &c) != nil || c.Diff == nil {
+ return n, ErrPolicy
+ }
+ default:
+ return n, ErrPolicy
+ }
+ }
+ }
+ return n, nil
+}
diff --git a/internal/runner/provider/native_json.go b/internal/runner/provider/native_json.go
new file mode 100644
index 00000000..e8bf2c16
--- /dev/null
+++ b/internal/runner/provider/native_json.go
@@ -0,0 +1,90 @@
+package provider
+
+import (
+ "bytes"
+ "encoding/json"
+ "io"
+)
+
+type nativeEnvelope struct {
+ ID json.RawMessage `json:"id"`
+ Method string `json:"method"`
+ Params json.RawMessage `json:"params"`
+ Result json.RawMessage `json:"result"`
+ Error json.RawMessage `json:"error"`
+}
+
+func parseNative(raw []byte) (nativeEnvelope, error) {
+ var v nativeEnvelope
+ if len(raw) == 0 || len(raw) > (1<<20) || !uniqueNativeJSON(raw) || json.Unmarshal(raw, &v) != nil {
+ return v, ErrPolicy
+ }
+ if len(v.ID) > 0 {
+ var s string
+ var n int64
+ if json.Unmarshal(v.ID, &s) != nil && json.Unmarshal(v.ID, &n) != nil {
+ return v, ErrPolicy
+ }
+ if bytes.Equal(v.ID, []byte("null")) {
+ return v, ErrPolicy
+ }
+ }
+ if v.Method != "" {
+ if len(v.Result) > 0 || len(v.Error) > 0 || len(v.Params) == 0 {
+ return v, ErrPolicy
+ }
+ } else if len(v.ID) == 0 || (len(v.Result) == 0) == (len(v.Error) == 0) {
+ return v, ErrPolicy
+ }
+ return v, nil
+}
+
+func uniqueNativeJSON(raw []byte) bool {
+ d := json.NewDecoder(bytes.NewReader(raw))
+ d.UseNumber()
+ var value func() bool
+ value = func() bool {
+ token, e := d.Token()
+ if e != nil {
+ return false
+ }
+ delim, ok := token.(json.Delim)
+ if !ok {
+ return true
+ }
+ switch delim {
+ case '{':
+ seen := map[string]bool{}
+ for d.More() {
+ k, e := d.Token()
+ if e != nil {
+ return false
+ }
+ s, ok := k.(string)
+ if !ok || seen[s] {
+ return false
+ }
+ seen[s] = true
+ if !value() {
+ return false
+ }
+ }
+ end, e := d.Token()
+ return e == nil && end == json.Delim('}')
+ case '[':
+ for d.More() {
+ if !value() {
+ return false
+ }
+ }
+ end, e := d.Token()
+ return e == nil && end == json.Delim(']')
+ }
+ return false
+ }
+ if !value() {
+ return false
+ }
+ _, e := d.Token()
+ return e == io.EOF
+}
diff --git a/internal/runner/provider/native_overlay_test.go b/internal/runner/provider/native_overlay_test.go
new file mode 100644
index 00000000..245ab614
--- /dev/null
+++ b/internal/runner/provider/native_overlay_test.go
@@ -0,0 +1,23 @@
+package provider
+
+import (
+ "encoding/json"
+ "strings"
+ "testing"
+)
+
+func TestNativeApprovalOverlay(t *testing.T) {
+ raw := `{"id":7,"method":"item/commandExecution/requestApproval","params":{"threadId":"s","turnId":"t","itemId":"i","command":"cat /outside/a","cwd":"/workspace","approvalId":"overlay","additionalPermissions":{"fileSystem":{"read":["/outside/a"]}}}}`
+ ev := Event{RequestID: "7", SessionID: "s", ProviderTurnID: "t", Payload: json.RawMessage(raw)}
+ n, err := NativeApproval(ev)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if n.ApprovalID != "overlay" || !strings.Contains(string(n.AdditionalPermissions), "/outside/a") {
+ t.Fatal("approval overlay hidden")
+ }
+ ev.Payload = json.RawMessage(strings.Replace(raw, `"approvalId":"overlay"`, `"approvalId":"overlay","networkApprovalContext":{"host":"example.com"}`, 1))
+ if _, err = NativeApproval(ev); err == nil {
+ t.Fatal("network approval accepted")
+ }
+}
diff --git a/internal/runner/provider/runtime_home.go b/internal/runner/provider/runtime_home.go
new file mode 100644
index 00000000..be50b86a
--- /dev/null
+++ b/internal/runner/provider/runtime_home.go
@@ -0,0 +1,32 @@
+package provider
+
+import (
+ "io/fs"
+ "os"
+ "path/filepath"
+ "strings"
+)
+
+func (l *AccountLease) validateRuntimeEntries() error {
+ allowed := map[string]bool{IdentityFile: true, credentialName(l.source.Provider): true, ".claude.json": true, "history.jsonl": true, "sessions": true, "archived_sessions": true, "session_index.jsonl": true, "shell_snapshots": true, "log": true, "logs": true, "debug": true, "projects": true, "todos": true, "tasks": true, "plans": true, "backups": true, "file-history": true, "telemetry": true, "statsig": true, "paste-cache": true, "downloads": true, "stats-cache.json": true, "models_cache.json": true, "version.json": true, ".last_migration": true, ".codex-global-state.json": true, "equipo-read-sentinel": true}
+ return filepath.WalkDir(l.runtime, func(path string, d fs.DirEntry, err error) error {
+ if err != nil {
+ return ErrContainment
+ }
+ if path == l.runtime {
+ return nil
+ }
+ name := d.Name()
+ if d.Type()&os.ModeSymlink != 0 || d.Type()&(os.ModeSocket|os.ModeDevice|os.ModeNamedPipe) != 0 {
+ return ErrContainment
+ }
+ switch strings.ToLower(name) {
+ case "config.toml", "agents.md", "claude.md", "settings.json", "settings.local.json", "hooks", "plugins", "skills", ".mcp.json":
+ return ErrContainment
+ }
+ if filepath.Dir(path) == l.runtime && !allowed[name] && !strings.HasPrefix(name, "state_") && !strings.HasPrefix(name, "logs_") {
+ return ErrContainment
+ }
+ return nil
+ })
+}
diff --git a/internal/runner/provider/types.go b/internal/runner/provider/types.go
index 85e0a436..cfc0323f 100644
--- a/internal/runner/provider/types.go
+++ b/internal/runner/provider/types.go
@@ -25,6 +25,7 @@ type Binding struct {
// NetworkContract is installed by the runner, never supplied by a permission answer.
// AuthHost is empty until Task 11b certifies refresh for this provider.
type NetworkContract struct {
+ Conflict string
Provider string
AuthHost string
}
@@ -195,3 +196,5 @@ type SessionBinding interface {
type AnswerWriter interface {
WriteAnswer(context.Context, Session, string, []byte) (int, error)
}
+
+const LauncherVersion = "direct-v3"
diff --git a/internal/runner/runtime.go b/internal/runner/runtime.go
index 5ad526c2..b3de4618 100644
--- a/internal/runner/runtime.go
+++ b/internal/runner/runtime.go
@@ -12,6 +12,7 @@ import (
"amadan.net/oficina/equipo/internal/runner/certified"
"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/provider"
"amadan.net/oficina/equipo/internal/runner/provider/claude"
@@ -66,6 +67,9 @@ func openRuntime(ctx context.Context, c Config) (r *Runtime, err error) {
return r, err
}
}
+ if err = forge.SweepDescriptions(c.ScratchRoot); err != nil {
+ return r, err
+ }
variable = "EQUIPO_RUNNER_STATE_DIR"
r.journal, err = OpenJournal(ctx, filepath.Join(c.StateDir, "journal.db"))
if err != nil {
diff --git a/internal/runner/service.go b/internal/runner/service.go
index 0f9303bb..70113f8e 100644
--- a/internal/runner/service.go
+++ b/internal/runner/service.go
@@ -61,6 +61,7 @@ func (s *Service) Run(ctx context.Context) error {
}
for _, a := range assignments {
if err := s.Supervisor.journal.AdmissionAllowed(ctx); err != nil {
+ needsRecovery = true
if ctx.Err() != nil {
return ctx.Err()
}
diff --git a/internal/runner/tool_journal.go b/internal/runner/tool_journal.go
index ffcca7ec..da24a836 100644
--- a/internal/runner/tool_journal.go
+++ b/internal/runner/tool_journal.go
@@ -53,7 +53,7 @@ func (j *Journal) appendTool(ctx context.Context, v ToolSubmission, inputHash st
return j.storageFailure(ctx, err)
}
if size+int64(len(raw)) > j.maxBytes {
- return ErrJournal
+ return ErrJournalBudget
}
var pending, attemptBytes int64
if err = tx.QueryRowContext(ctx, `SELECT count(*), COALESCE(SUM(length(body)),0) FROM journal_tools WHERE acked=0
@@ -63,7 +63,7 @@ func (j *Journal) appendTool(ctx context.Context, v ToolSubmission, inputHash st
return j.storageFailure(ctx, err)
}
if pending >= 128 || attemptBytes+int64(len(raw)) > j.maxBytes/4 {
- return ErrJournal
+ return ErrJournalBudget
}
if _, err = tx.ExecContext(ctx, "INSERT INTO journal_tools(request_key,content_hash,body,acked) VALUES(?,?,?,0)", key, hash, raw); err != nil {
tx.Rollback()
diff --git a/internal/runnerproto/questions.go b/internal/runnerproto/questions.go
index 657ed7c3..b94636e9 100644
--- a/internal/runnerproto/questions.go
+++ b/internal/runnerproto/questions.go
@@ -8,7 +8,6 @@ import (
"time"
"amadan.net/oficina/equipo/internal/runner/provider"
- "amadan.net/oficina/equipo/internal/runner/provider/codex"
)
type Question struct {
@@ -170,7 +169,7 @@ func (q Question) ValidateAnswer(a QuestionAnswer) error {
// NativeApproval validates the saved envelope as well as its original Codex
// frame. The local turn and provider turn are deliberately separate identities.
-func (q Question) NativeApproval() (codex.NativeRequest, error) {
+func (q Question) NativeApproval() (provider.NativeRequest, error) {
var raw struct {
Direct bool
Provider, Name string
@@ -181,7 +180,7 @@ func (q Question) NativeApproval() (codex.NativeRequest, error) {
Input json.RawMessage
}
if q.Validate() != nil || q.Kind != "tool" || json.Unmarshal(q.RawRequest, &raw) != nil || !raw.Direct || (raw.Provider != "codex" && raw.Provider != "claude") || raw.TurnID == "" {
- return codex.NativeRequest{}, ErrInvalid
+ return provider.NativeRequest{}, ErrInvalid
}
if raw.Provider == "claude" {
var original struct {
@@ -190,22 +189,22 @@ func (q Question) NativeApproval() (codex.NativeRequest, error) {
Input json.RawMessage
}
if json.Unmarshal(raw.Request, &original) != nil || original.Tool == "" || original.Tool != raw.Name || !SameRequestJSON(raw.Input, original.Input) {
- return codex.NativeRequest{}, ErrInvalid
+ return provider.NativeRequest{}, ErrInvalid
}
item := original.ToolUseID
if item == "" {
item = q.PermissionID
}
- return codex.NativeRequest{RequestID: q.PermissionID, ItemID: item, TurnID: raw.TurnID, SessionID: q.SessionID, Request: raw.Request}, nil
+ return provider.NativeRequest{RequestID: q.PermissionID, ItemID: item, TurnID: raw.TurnID, SessionID: q.SessionID, Request: raw.Request}, nil
}
var frame struct {
Method string
Params json.RawMessage
}
if json.Unmarshal(raw.Request, &frame) != nil || raw.Name != frame.Method || !SameRequestJSON(raw.Input, frame.Params) {
- return codex.NativeRequest{}, ErrInvalid
+ return provider.NativeRequest{}, ErrInvalid
}
- return codex.NativeApproval(provider.Event{Kind: "request", SessionID: q.SessionID, TurnID: raw.TurnID, ProviderTurnID: raw.ProviderTurnID, RequestID: q.PermissionID, Payload: raw.Request, ToolCall: raw.ToolCall})
+ return provider.NativeApproval(provider.Event{Kind: "request", SessionID: q.SessionID, TurnID: raw.TurnID, ProviderTurnID: raw.ProviderTurnID, RequestID: q.PermissionID, Payload: raw.Request, ToolCall: raw.ToolCall})
}
// SameRequestJSON preserves string bytes and JSON number spelling while allowing