oficina / equipo Public

test: verify the runner workflow and live compatibility gate

codex agent, operated by paul@keymail.dev pushed by claude agent, operated by paul@keymail.dev 1215b58774372b1d9b8e004701848da1e30e5d84 parent c117de7
21 files changed, +829 −13
  • .rastrillo/budgets.txt +5 −5
  • cmd/equipo-runner/budget_test.go +9 −0
  • docs/live-gate.md +157 −0
  • internal/equipo/runner_receipt_test.go +35 −0
  • internal/equipo/runner_report_validation.go +5 −1
  • internal/equipo/team/harness_test.go +1 −1
  • internal/equipo/team/store_test.go +1 −1
  • internal/equipotest/live_gate_test.go +41 −0
  • internal/equipotest/pages_test.go +2 −2
  • internal/equipotest/release_test.go +1 −0
  • internal/equipotest/runner_api_test.go +9 −1
  • internal/equipotest/runner_flow_test.go +379 −0
  • internal/equipotest/specialists_test.go +2 −2
  • internal/equipotest/testdata/runner-flow.mjs +23 −0
  • internal/runner/budget_test.go +9 −0
  • internal/runner/checks/budget_test.go +9 −0
  • internal/runner/forge/budget_test.go +9 −0
  • internal/runner/paseo/budget_test.go +9 −0
  • internal/runner/paseo/live_test.go +99 −0
  • internal/runner/workspace/budget_test.go +9 −0
  • scripts/live-gate.sh +15 −0

CI passed — run details

diff --git a/.rastrillo/budgets.txt b/.rastrillo/budgets.txt
index 43c44f14..bfb7eac4 100644
--- a/.rastrillo/budgets.txt
+++ b/.rastrillo/budgets.txt
@@ -11,13 +11,13 @@
# boot <duration> <reason>
size internal/equipo/team 8200 - Preserve the plan-mandated core layout; Task 14 raises 7900 after adding publication description provenance, receipt guards and scoped admission authorization (7931 lines).
perf GET /* skip Unknown private paths render 404; this fallback contains no screens.
-time internal/equipo/team 15s Copied core crash, recovery and concurrency tests take about 7.7s idle and 13.6s on the loaded shared machine.
-time internal/equipotest 90s Task 16 keeps real-session task, live-stream, authority and unconfined-surface tests beside the existing runner fixtures; its focused gate alone took 37.268s, in addition to the prior tasks covered by the 25s allowance.
+time internal/equipo/team 35s Task 18 whole-slice CI measured 26.546s for the copied core migration, recovery and concurrency suite on the shared machine.
+time internal/equipotest 180s Task 18 whole-slice CI measured 155.288s including the real HTTP runner workflow, browser-session authority, preparation sandbox, restore and label coverage.
size internal/equipo 9600 - Task 16 adds the mandated task projections, live authorization and transaction notifier, connection and recovery pages, ordinary answer forms and flagged copy inventory beside the existing runner services.
-size internal/equipotest - 11200 Task 16 keeps the mandated task_pages and browser tests beside the shared activation and runner fixtures, including live authorization, rollback, replay, isolation surfaces, merge authority and scriptless forms.
-time internal/runner/checks 15s Task 11 runs real Go fixtures and Codex sandbox sentinels, including timeout and child-process cleanup; the targeted suite took 10.710s on the shared machine.
-time internal/runner 75s Task 15 keeps local Git workflow, real sandbox checks, publication, Linux containment and 130 fsynced report drains in this package. The supervisor group took 49.269s on the loaded shared machine, plus 12.542s for separate journal/tool regressions.
+size internal/equipotest - 11600 Task 18 keeps the mandated runner_flow integration beside shared fixtures: real HTTP, Linux containment, local Git, exact evidence and publication assertions, plus confirmation-script checks (11230 total test lines before final review).
+time internal/runner/checks 25s Task 18 whole-slice CI measured 17.451s for real Go fixtures, Codex sandbox sentinels, timeout and child-process cleanup on the shared machine.
+time internal/runner 240s Task 18 restores missing budget timing for the complete runner suite; one lease test takes 65s, plus local Git workflows, real sandbox checks, Linux containment and fsynced recovery. The first whole-slice test lane took 182s with this package running throughout.
perf GET /live skip Authorized notification stream, bounded to 30 seconds; not a GET screen.
perf GET /api/runner/v1/artifacts/{assignment}/{artifact} skip Authenticated runner artifact download, not a browser GET screen. Runner long-poll and blob downloads use POST and are outside the screen inventory.
diff --git a/cmd/equipo-runner/budget_test.go b/cmd/equipo-runner/budget_test.go
new file mode 100644
index 00000000..433b0eb1
--- /dev/null
+++ b/cmd/equipo-runner/budget_test.go
@@ -0,0 +1,9 @@
+package main
+
+import (
+ "amadan.net/rastrillo/rastrillo/budget"
+ "os"
+ "testing"
+)
+
+func TestMain(m *testing.M) { os.Exit(budget.Main(m)) }
diff --git a/docs/live-gate.md b/docs/live-gate.md
new file mode 100644
index 00000000..cfe85339
--- /dev/null
+++ b/docs/live-gate.md
@@ -0,0 +1,157 @@
+DRAFT: copy review required
+
+# Paul's runner live gate
+
+The current build cannot pass this gate. Paseo 0.14.0 lacks per-agent account
+binding and no-failover guarantees, provider version reporting, effective
+isolation configuration, and recoverable completion. These are discussion 3,
+items 1 through 4. Amadan lacks branch description readback, item 5.
+Containment on docs-t1 needs a dedicated runner OS user or Paseo cgroup
+ownership, item 6. The runner service's own cgroup does not cover agents
+started by a separate shared Paseo daemon.
+
+The three tagged tests currently probe the shipped adapter and fail on those
+missing capabilities. They also fail if preflight becomes green without the
+remaining live observations being implemented. They do not yet dispatch the
+sentinel or calibration turns. Resolve the owning-product contracts, implement
+the probes below against those supported contracts, and review them before
+attempting acceptance. A failed or skipped test supplies no verified tuple.
+
+## Prepare the machine and instance
+
+1. Use docs-t1 and a disposable repository that you own. Record the exact
+ instance origin, machine fingerprint, repository, base commit, review ref,
+ connection IDs, provider accounts and chosen models. Leave other projects,
+ agents and the shared daemon unchanged. Do not enrol tito-studio.
+2. Resolve process ownership first. Arrange a dedicated runner OS user or
+ supported Paseo cgroup ownership. The runner must account for every owned
+ agent, terminal and background process across reconnect and restart.
+ Unknown coverage blocks work and cannot be called stopped.
+3. Review pending copy and the clean commit. From that commit run `make release`
+ and `make release-runner` (the runner release target in this repository).
+ Confirm the instance is linux/arm64 and the runner linux/amd64, both stamped
+ with that commit. Compare the runner's `COMMIT` and `manifest.json` with the
+ reviewed source. Deploy the versioned instance through the oficina CARLOS
+ account yourself. Never deploy a dirty build.
+4. Choose always-on live mode on CARLOS. Set `EQUIPO_ALWAYS_ON=1` and explicitly
+ enable execution with `EQUIPO_EXECUTION_ENABLED=1`. Configure the required
+ origin, instance key and mail settings. Preserve the execution witness
+ outside any database rollback or hibernation snapshot. Missing or newer
+ witness state requires quarantine and owner reconciliation.
+5. Copy the versioned runner bundle to `~/.local/lib/equipo-runner/`. Put the
+ bundled service at `~/.config/systemd/user/equipo-runner.service`. Create
+ `~/.config/equipo-runner/runner.env` with mode 0600. Use absolute canonical
+ paths for every path in `internal/runner/config.go`: runner state, Paseo
+ home, Node, bridge, Amadan credential, account bindings, Codex, Go root and
+ binary, workspace, scratch, Git and runner executable. Set the instance
+ identity and observed Paseo server identity. The endpoint is loopback only.
+ State is mode 0700; credentials and bindings are mode 0600. Use disk-backed
+ scratch. Keep provider credentials out of workspaces.
+6. Run the installed `equipo-runner enrol` yourself with that environment.
+ Open the displayed device approval page. Confirm the exact origin and
+ machine fingerprint before approving. Never paste a bearer, credential or
+ sign-in link into gate evidence. Enrol the second member separately.
+7. Run `systemctl --user daemon-reload`, then
+ `systemctl --user enable --now equipo-runner.service`. Inspect its status.
+ Only this human-installed service may remain running after acceptance.
+8. In Connections, enable each person's own accounts for the disposable
+ project and choose the pins. A current team owner must acknowledge the
+ exact Codex connection after checking its observed provider version,
+ daemon server version and configuration hash. This checklist is not an
+ acknowledgement. Do not set acknowledgement fields through a fixture or
+ environment flag. A changed version, configuration, owner role or roster
+ invalidates the acknowledgement.
+
+## Run and record the gate
+
+Create a private `EQUIPO_LIVE_INPUT` JSON file with an absolute disposable
+`repository` path, two `selections` in Claude then Codex order, and a
+`read_policy` containing `denied_paths` and `config_hash`. Each selection uses
+`connection_id`, `provider`, `family`, `model` and `account_id` from the
+operator-selected enrolled connections. Use the runner environment from the
+previous steps. These values select the probe; they do not attest capabilities.
+The tests use the shipped bridge at `runner/paseo/bridge.mjs`.
+
+Provide disposable sentinel locations for actual runner state, config,
+journal, bearer and cleanup storage, the Amadan credential location, Paseo
+home, every routed provider credential home, and `~/.ssh`. Use unique nonsecret
+sentinel content. For the credential-file rule, provision a disposable test
+credential under the identical policy. Never overwrite or read real secrets.
+Include a readable workspace control and resolved symlink aliases. Record
+only paths, nonsecret sentinel identities and observations.
+
+The completed probes must establish all of the following before a tuple passes:
+
+- Claude denies shell `cat`, native Read and search, symlink aliases, and
+ sandbox or policy escape requests for every protected path. The workspace
+ control is readable and the trusted tool still authenticates. Repeat after
+ restart and in every enabled confined mode. Unknown, skipped or readable
+ protected sentinels fail confinement. The executor has its own mandatory
+ sentinel gate, independent of the agent result.
+- Both providers produce structured events, recover after lost events and
+ reconnect without invented completion, answer permissions by exact request
+ ID, use per-agent MCP, and prove the selected credential home and account
+ without failover. Cancel during a permission wait and with background and
+ terminal processes. Stop, archive and process inspection must leave no
+ owned processes. Remove only the sentinels and resources this gate created.
+- Codex reports `ReadIsolation=false`, has a current exact owner
+ acknowledgement, and carries `unconfined` provenance. This is not a passed
+ deny-read test. Both families, executor evidence, concurrent confined work
+ and the published branch on the tainted runner retain that label. Prove
+ bearer and cleanup rotation after containment without losing concurrent
+ cleanup authority. A future supported Codex profile must use Task 9's
+ restoration path and pass the full sentinel gate before confinement returns.
+- Measure a representative turn for each eligible family with provider,
+ provider version, model, configuration hash, uncached input, cached input,
+ output and completeness flags. The historical Claude measurement of 18
+ input, 29,591 cached and 404 output is not calibration. Use explicit bounded
+ calibration reservations recorded separately from production dispatch.
+ For each input and output reservation, take twice the largest measured
+ corresponding total, round up to 1,000, and reject arithmetic overflow.
+ Count cached input according to the observed provider usage semantics.
+ Fund the job for at least 23 reservations and set explicit project and team
+ period headroom. Report required funding if existing lower limits block it;
+ never silently raise them. Exercise an unknown-usage reservation followed by
+ a known completed turn with headroom, then exhaustion. Keep later overruns
+ charged before stopping further work. Record limits and overruns.
+
+Run `scripts/live-gate.sh`. It asks for two explicit confirmations and then
+runs exactly:
+
+```sh
+EQUIPO_LIVE_PASEO=1 go test -tags paseo_live ./internal/runner/paseo -run 'TestPaseoLiveContract|TestPaseoLiveReadIsolation|TestPaseoLiveTurnCalibration' -count=1
+```
+
+Keep the exit status and full nonsecret output. Today this command fails on
+the blockers above. Do not turn that result into a pass or use an offline
+fixture as live proof.
+
+After every required assertion passes, record each exact provider, provider
+version, observed daemon server version and configuration hash in
+`internal/release/manifest.json`, under `verified_isolation_tuples`, with the
+nonsecret gate evidence references in `gate_evidence`. This manifest is also
+the instance build's immutable verified list. Runtime reports cannot extend
+it. Never add Codex as confined after the acknowledged unconfined subcase.
+Update the empty-list release test to validate the reviewed evidence-backed
+list, commit, review, rebuild both releases and deploy that version yourself.
+Recheck stamps and manifest equality. Changed tuples need a new live gate.
+
+## Human acceptance
+
+Submit a bounded bug in the disposable repository. Follow Engineering, Review
+and Journey in always-on mode, then check the same views with scripts off and
+manual reload. The second member must be able to read the task but cannot use
+your connection. With only one family eligible, work waits without dispatch.
+
+Read the Amadan review branch and its `unconfined` label. Verify the pushed
+commit is exactly the reviewed and checked candidate, the frozen reproduction
+failed on the base and passed on the candidate, and repository test counts
+and independent-family provenance are present. A missing branch description
+readback leaves delivery incomplete. Equipo waits for the named merge owner.
+Merge personally and record your acknowledgement in Equipo.
+
+Repeat with an active cancellation, including a permission wait and a
+background process. Inspect agent, workspace, terminal and process cleanup.
+A missing receipt or uncertain containment must remain unknown and charged,
+never stopped or succeeded. Preserve the gate evidence, remove only owned
+scratch and sentinels, and leave only the service you installed running.
diff --git a/internal/equipo/runner_receipt_test.go b/internal/equipo/runner_receipt_test.go
new file mode 100644
index 00000000..ea133dad
--- /dev/null
+++ b/internal/equipo/runner_receipt_test.go
@@ -0,0 +1,35 @@
+package equipo
+
+import (
+ "context"
+ "testing"
+
+ "amadan.net/oficina/equipo/internal/equipo/team"
+)
+
+func TestSupervisedReceiptProvider(t *testing.T) {
+ for _, tc := range []struct {
+ step, provider, model string
+ accept bool
+ }{
+ {"publish", "amadan", "", true},
+ {"publish", "claude", "sonnet", false},
+ {"publish", "amadan", "sonnet", false},
+ {"implement", "amadan", "", false},
+ {"implement", "claude", "sonnet", true},
+ {"implement", "claude", "other", false},
+ } {
+ t.Run(tc.step+"/"+tc.provider+"/"+tc.model, func(t *testing.T) {
+ a := Assignment{ID: "assignment", StepKey: tc.step, Selection: Selection{Provider: "claude", Model: "sonnet"}}
+ q := RunnerRequest{AssignmentID: a.ID, Receipt: &team.Receipt{Provider: tc.provider, Model: tc.model}}
+ _, err := instanceValidators().Receipt(context.Background(), a, q)
+ if (err == nil) != tc.accept {
+ t.Fatalf("receipt acceptance=%t want %t: %v", err == nil, tc.accept, err)
+ }
+ q.AssignmentID = "foreign"
+ if _, err = instanceValidators().Receipt(context.Background(), a, q); err == nil {
+ t.Fatal("foreign assignment receipt accepted")
+ }
+ })
+ }
+}
diff --git a/internal/equipo/runner_report_validation.go b/internal/equipo/runner_report_validation.go
index 10532dbc..21b3fb1e 100644
--- a/internal/equipo/runner_report_validation.go
+++ b/internal/equipo/runner_report_validation.go
@@ -62,7 +62,11 @@ func instanceValidators() RunnerValidators {
return team.Receipt{}, ErrForbidden
}
if q.Receipt != nil {
- if q.Receipt.Provider != a.Selection.Provider || q.Receipt.Model != a.Selection.Model {
+ provider, model := a.Selection.Provider, a.Selection.Model
+ if a.StepKey == "publish" {
+ provider, model = "amadan", ""
+ }
+ if q.Receipt.Provider != provider || q.Receipt.Model != model {
return team.Receipt{}, ErrForbidden
}
return *q.Receipt, nil
diff --git a/internal/equipo/team/harness_test.go b/internal/equipo/team/harness_test.go
index bf5208a4..6fc86861 100644
--- a/internal/equipo/team/harness_test.go
+++ b/internal/equipo/team/harness_test.go
@@ -175,7 +175,7 @@ func dropRecoverySchema(t *testing.T, db *sql.DB) {
func dropRunnerPolicySchema(t *testing.T, db *sql.DB) {
t.Helper()
- for _, q := range []string{"DROP INDEX jobs_request", "ALTER TABLE jobs DROP COLUMN request_key", "ALTER TABLE jobs DROP COLUMN request_hash"} {
+ for _, q := range []string{"DROP TABLE admission_tickets", "DROP INDEX jobs_request", "ALTER TABLE jobs DROP COLUMN request_key", "ALTER TABLE jobs DROP COLUMN request_hash"} {
_, err := db.Exec(q)
must(t, err)
}
diff --git a/internal/equipo/team/store_test.go b/internal/equipo/team/store_test.go
index c8024c19..b3963a53 100644
--- a/internal/equipo/team/store_test.go
+++ b/internal/equipo/team/store_test.go
@@ -60,7 +60,7 @@ func TestUnknownKindsFailClosed(t *testing.T) {
_, err = e.store.CreateJob(e.ctx, bad)
wantCode(t, err, CodeUnknownKind)
bad = spec
- bad.Policy.Version = 2
+ bad.Policy.Version = PolicyVersion + 1
_, err = e.store.CreateJob(e.ctx, bad)
wantCode(t, err, CodeUnknownKind)
bad = spec
diff --git a/internal/equipotest/live_gate_test.go b/internal/equipotest/live_gate_test.go
new file mode 100644
index 00000000..dc795366
--- /dev/null
+++ b/internal/equipotest/live_gate_test.go
@@ -0,0 +1,41 @@
+package equipotest
+
+import (
+ "os"
+ "os/exec"
+ "path/filepath"
+ "strings"
+ "testing"
+)
+
+func TestLiveGateConfirmation(t *testing.T) {
+ for _, input := range []string{"", "no\n", "no\nRUN LIVE GATE\n", "LIVE DISPOSABLE ONLY\nno\n", "LIVE DISPOSABLE ONLY\nRUN LIVE GATE\n"} {
+ t.Run(strings.ReplaceAll(input, "\n", "_"), func(t *testing.T) {
+ root := t.TempDir()
+ capture := filepath.Join(root, "capture")
+ executionMust(t, os.WriteFile(filepath.Join(root, "go"), []byte("#!/bin/sh\nprintf '%s\\n' \"$EQUIPO_LIVE_PASEO\" \"$@\" > \"$CAPTURE\"\nexit 23\n"), 0700))
+ cmd := exec.Command("/bin/sh", "../../scripts/live-gate.sh")
+ cmd.Env = []string{"PATH=" + root + ":/usr/bin:/bin", "CAPTURE=" + capture}
+ cmd.Stdin = strings.NewReader(input)
+ _, err := cmd.CombinedOutput()
+ if err == nil {
+ t.Fatal("script hid gate failure or accepted missing confirmation")
+ }
+ raw, readErr := os.ReadFile(capture)
+ if input != "LIVE DISPOSABLE ONLY\nRUN LIVE GATE\n" {
+ if !os.IsNotExist(readErr) {
+ t.Fatal("ran before both confirmations")
+ }
+ return
+ }
+ executionMust(t, readErr)
+ want := "1\ntest\n-tags\npaseo_live\n./internal/runner/paseo\n-run\nTestPaseoLiveContract|TestPaseoLiveReadIsolation|TestPaseoLiveTurnCalibration\n-count=1\n"
+ if string(raw) != want {
+ t.Fatalf("authorized command changed: %q", raw)
+ }
+ if cmd.ProcessState.ExitCode() != 23 {
+ t.Fatal("gate exit status lost")
+ }
+ })
+ }
+}
diff --git a/internal/equipotest/pages_test.go b/internal/equipotest/pages_test.go
index 43807568..64355111 100644
--- a/internal/equipotest/pages_test.go
+++ b/internal/equipotest/pages_test.go
@@ -266,8 +266,8 @@ func TestEmptyScreensDoNotStartWork(t *testing.T) {
pagePost(t, c, f.server.URL, path, testOrigin, url.Values{}, 404)
}
var n int
- if err := f.db.Writer().QueryRow("SELECT count(*) FROM sqlite_master WHERE type='table' AND name IN ('jobs','attempts','actions')").Scan(&n); err != nil || n != 0 {
- t.Fatal("execution store opened")
+ if err := f.db.Writer().QueryRow("SELECT (SELECT count(*) FROM jobs)+(SELECT count(*) FROM attempts)+(SELECT count(*) FROM actions)").Scan(&n); err != nil || n != 0 {
+ t.Fatal("empty screens created execution records")
}
}
diff --git a/internal/equipotest/release_test.go b/internal/equipotest/release_test.go
index d5742544..b895c211 100644
--- a/internal/equipotest/release_test.go
+++ b/internal/equipotest/release_test.go
@@ -43,6 +43,7 @@ func TestReleaseStampContract(t *testing.T) {
write("tracked", "original\n", 0600)
write("bin/go", `#!/bin/sh
set -eu
+if [ "$1" = test ]; then exit 0; fi
printf '%s\n' "CGO_ENABLED=$CGO_ENABLED" "GOOS=$GOOS" "GOARCH=$GOARCH" "$@" > "$RELEASE_CAPTURE"
`, 0700)
// Catch an accidental deployment without invoking the real CLI.
diff --git a/internal/equipotest/runner_api_test.go b/internal/equipotest/runner_api_test.go
index 2d6a129e..dfe988f9 100644
--- a/internal/equipotest/runner_api_test.go
+++ b/internal/equipotest/runner_api_test.go
@@ -690,13 +690,21 @@ func TestRunnerPrepareOutbox(t *testing.T) {
executionMust(t, err)
rf := runnerFixture{connectionFixture: f, x: x, a: aa[0], claim: claim}
token := runnerBearerFor(t, rf)
- x.SetRunnerValidators(equipo.RunnerValidators{Prepare: func(context.Context, equipo.Assignment, equipo.RunnerRequest) (equipo.PreparedBug, error) {
+ x.SetRunnerValidators(equipo.RunnerValidators{Containment: func(context.Context, equipo.Assignment, equipo.RunnerRequest) error { return nil }, Prepare: func(context.Context, equipo.Assignment, equipo.RunnerRequest) (equipo.PreparedBug, error) {
return bugPrepared(f), nil
}})
if status := runnerHTTP(t, rf, "prepare", token, rf.request()); status != 200 {
t.Fatal("prepare HTTP failed", status)
}
executionMust(t, x.Sync(connectionContext))
+ if scalar(t, f.d, "SELECT count(*) FROM jobs") != 0 {
+ t.Fatal("prepared outbox linked before containment")
+ }
+ q := rf.request()
+ q.RequestID = "contained"
+ _, err = x.Cleanup(connectionContext, claim.CleanupToken, "contained", q)
+ executionMust(t, err)
+ executionMust(t, x.Sync(connectionContext))
task, err = f.s.Task(connectionContext, ownerActor, task.ID)
executionMust(t, err)
if task.JobID == 0 || task.State != "queued" {
diff --git a/internal/equipotest/runner_flow_test.go b/internal/equipotest/runner_flow_test.go
new file mode 100644
index 00000000..c8c54161
--- /dev/null
+++ b/internal/equipotest/runner_flow_test.go
@@ -0,0 +1,379 @@
+package equipotest
+
+import (
+ "amadan.net/oficina/equipo/internal/equipo"
+ "amadan.net/oficina/equipo/internal/equipo/team"
+ "amadan.net/oficina/equipo/internal/runner"
+ "amadan.net/oficina/equipo/internal/runner/checks"
+ "amadan.net/oficina/equipo/internal/runner/forge"
+ "amadan.net/oficina/equipo/internal/runner/paseo"
+ "amadan.net/oficina/equipo/internal/runner/workspace"
+ "amadan.net/oficina/equipo/internal/runnerproto"
+ "context"
+ "crypto/sha256"
+ "database/sql"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "net/http/httptest"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "strings"
+ "testing"
+ "time"
+)
+
+func TestRunnerEndToEnd(t *testing.T) {
+ if privateProcTest(t) {
+ return
+ }
+
+ ctx := context.Background()
+ root, err := os.MkdirTemp(os.Getenv("TMPDIR"), "e15-")
+ executionMust(t, err)
+ t.Cleanup(func() { os.RemoveAll(root) })
+ state := filepath.Join(root, "s")
+ private := filepath.Join(root, "p")
+ works := filepath.Join(root, "w")
+ scratch := filepath.Join(root, "c")
+ seed := filepath.Join(root, "seed")
+ for _, p := range []string{state, private, works, scratch, seed} {
+ executionMust(t, os.Mkdir(p, 0700))
+ }
+ j, err := runner.OpenJournal(ctx, filepath.Join(state, "j.db"))
+ executionMust(t, err)
+ defer j.Close()
+ w, err := runner.NewWitness(j)
+ executionMust(t, err)
+ bridge, err := filepath.Abs("testdata/runner-flow.mjs")
+ executionMust(t, err)
+ // The fake bridge uses this owned directory for diagnostics only.
+ node, err := exec.LookPath("node")
+ executionMust(t, err)
+ wrapper := filepath.Join(root, "node")
+ executionMust(t, os.WriteFile(wrapper, []byte("#!/bin/sh\nexec "+node+" \"$@\" "+root+"\n"), 0700))
+ f := bugFixture(t)
+ f.s = equipo.NewStore(f.d, equipo.WithRunnerClock(team.RealClock{}), equipo.WithVerifiedIsolationTuples([]team.IsolationTuple{connectionTuple(f.reports[0])}))
+ task := bugTask(t, f)
+ if again := bugTask(t, f); again.ID != task.ID {
+ t.Fatal("duplicate submission")
+ }
+ var dbPath string
+ executionMust(t, f.d.Writer().QueryRow("SELECT file FROM pragma_database_list WHERE name='main'").Scan(&dbPath))
+ x, err := f.s.AttachSupervisedExecution(ctx, dbPath, team.Options{Clock: team.RealClock{}, Authority: equipo.NewAuthority(f.s, team.RealClock{})})
+ executionMust(t, err)
+ defer x.Core.Close()
+ _, err = x.Core.Resume(ctx)
+ executionMust(t, err)
+ token := strings.Repeat("A", 43)
+ sum := sha256.Sum256([]byte(runnerproto.RunnerAudience + "\x00" + token))
+ mustSQL(t, f.d, "UPDATE runner_credentials SET token_hash=? WHERE id=?", fmt.Sprintf("%x", sum), f.principal.CredentialID)
+ server := httptest.NewServer(f.s.RunnerHandler())
+ defer server.Close()
+ api, err := runner.NewHTTPInstance(server.URL, j, runnerproto.RunnerCredential{Token: token, ExpiresAt: time.Now().Add(time.Hour)})
+ executionMust(t, err)
+ var active runner.RunClaim
+
+ policy := paseo.ReadPolicy{ConfigHash: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", DeniedPaths: []string{state, private}}
+ client, err := paseo.Start(ctx, paseo.Config{NodePath: wrapper, BridgePath: bridge, DaemonHome: state, Endpoint: "127.0.0.1:1", ServerID: "server", RecordIntent: j.RecordIntent, RecordCreationRefusal: j.RecordCreationRefusal, InspectProcesses: func(context.Context, paseo.Selection) (bool, error) { return true, nil }, AuthorizeUnconfined: func(context.Context, paseo.Selection, paseo.Capabilities) error { return nil }, VerifiedTuples: []paseo.VerifiedTuple{{Provider: "claude", ProviderVersion: "2.1.312", PaseoVersion: "0.14.0", ConfigHash: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"}}})
+ executionMust(t, err)
+ defer client.Close()
+ executionMust(t, os.WriteFile(filepath.Join(seed, "go.mod"), []byte("module fixture\n\ngo 1.26.0\n"), 0600))
+ executionMust(t, os.WriteFile(filepath.Join(seed, "value.go"), []byte("package fixture\nfunc Value() int {return 1}\n"), 0600))
+ executionMust(t, os.WriteFile(filepath.Join(seed, "old_test.go"), []byte("package fixture\nimport \"testing\"\nfunc TestOld(t *testing.T) {}\n"), 0600))
+ cmd := runnerproto.CheckCommand{Argv: []string{"go", "test", "-json", "-count=1", "./..."}, Dir: ".", Parser: "go-test-json", TimeoutSeconds: 120}
+ executionMust(t, os.Mkdir(filepath.Join(seed, ".equipo"), 0700))
+ executionMust(t, os.WriteFile(filepath.Join(seed, ".equipo/checks.json"), flowJSON(checks.Definition{Version: 1, Commands: []checks.Command{cmd}, Reproduction: cmd}), 0600))
+ flowGit(t, seed, "init", "-b", f.project.DefaultBranch)
+ flowGit(t, seed, "add", ".")
+ flowGit(t, seed, "commit", "-m", "base")
+ base := flowGit(t, seed, "rev-parse", "HEAD")
+ remote := filepath.Join(root, "remote.git")
+ flowGit(t, root, "clone", "--bare", seed, remote)
+ protected := workspace.SecurityPaths{RunnerState: state, RunnerConfig: filepath.Join(state, "config"), Journal: filepath.Join(state, "j.db"), Bearer: filepath.Join(state, "bearer"), Cleanup: filepath.Join(state, "cleanup"), ForgeCredential: filepath.Join(state, "forge"), PaseoHome: filepath.Join(state, "paseo"), ProviderHomes: []string{filepath.Join(state, "provider")}, SSH: filepath.Join(state, "ssh")}
+ codex, err := exec.LookPath("codex")
+ executionMust(t, err)
+ goBinary, err := exec.LookPath("go")
+ executionMust(t, err)
+ goBinary, err = filepath.EvalSymlinks(goBinary)
+ executionMust(t, err)
+ goRoot := filepath.Dir(filepath.Dir(goBinary))
+ sandbox, err := checks.NewCodexSandbox(ctx, checks.SandboxConfig{Binary: codex, ScratchRoot: scratch, GoRoot: goRoot, GoBinary: filepath.Join(goRoot, "bin/go"), Protected: protected})
+ executionMust(t, err)
+
+ var manager *workspace.Manager
+
+ var repo string
+ executor := func(ctx context.Context, c runner.RunClaim, d checks.Definition, r checks.Reproduction, deadline time.Time) (*checks.Executor, error) {
+ if c.Handle.Attempt > 0 && !deadline.Equal(c.AttemptDeadline) {
+ return nil, fmt.Errorf("executor got lease snapshot instead of attempt deadline")
+ }
+ return checks.New(checks.Config{ScratchRoot: scratch, Scope: c.Scope, Handle: c.Handle, Deadline: deadline, Policy: policy, DefinitionHash: checks.Digest(flowJSON(d)), ReproductionHash: checks.Digest(flowJSON(r)), Reproduction: func(context.Context, string) (checks.Reproduction, error) { return r, nil }, Isolation: func(context.Context) (team.IsolationSnapshot, error) { return c.Brief.Selection.Isolation, nil }, ResolveCandidate: func(ctx context.Context, hash string) (team.GitCandidate, error) {
+ arts, err := flowArtifacts(ctx, api, c)
+ if err != nil {
+ return team.GitCandidate{}, err
+ }
+ for _, a := range arts {
+ var v team.GitCandidate
+ if a.Role == team.RoleCandidate && checks.CandidateHash(flowCandidate(a.Payload)) == hash {
+ json.Unmarshal(a.Payload, &v)
+ return v, nil
+ }
+ }
+ return team.GitCandidate{}, paseo.ErrIdentity
+ }, Export: func(ctx context.Context, commit, dest string) error {
+ if commit == base {
+ return checks.ExportBase(ctx, repo, base, dest)
+ }
+ arts, err := flowArtifacts(ctx, api, c)
+ if err != nil {
+ return err
+ }
+ for _, a := range arts {
+ v := flowCandidate(a.Payload)
+ if a.Role == team.RoleCandidate && v.Commit == commit {
+ return manager.ExportCandidate(ctx, v, dest)
+ }
+ }
+ return paseo.ErrIdentity
+ }}, sandbox)
+ }
+ manager, err = workspace.New(workspace.Config{Protected: protected, PrivateRoot: private, WorkspaceRoot: works, GitPath: "/usr/bin/git", Forge: preparationRemote{remote}, Policy: func(context.Context, paseo.Selection) (paseo.ReadPolicy, error) { return policy, nil }, Definitions: func(ctx context.Context, tgt team.TargetBinding, repository string) (runnerproto.PreparedBug, error) {
+ repo = repository
+ d, err := checks.LoadBaseDefinition(ctx, repository, tgt.Repository, tgt.BaseRevision, scratch)
+ if err != nil {
+ t.Log("preparation callback", err)
+ return runnerproto.PreparedBug{}, err
+ }
+ e, err := executor(ctx, active, d, checks.Reproduction{}, active.AttemptDeadline)
+ if err != nil {
+ t.Log("preparation callback", err)
+ return runnerproto.PreparedBug{}, err
+ }
+ d.Baseline, err = e.CaptureBaseline(ctx, d)
+ if err != nil {
+ t.Log("preparation callback", err)
+ return runnerproto.PreparedBug{}, err
+ }
+
+ raw := flowJSON(d)
+ return runnerproto.PreparedBug{CheckDefinition: raw, CheckDefinitionHash: checks.Digest(raw), BaselineTestSetHash: d.Baseline.Hash}, nil
+ }}, client)
+ executionMust(t, err)
+ description := &flowDescription{}
+ pubroot := filepath.Join(root, "publish")
+ gitSpy := filepath.Join(root, "publish-git")
+ executionMust(t, os.WriteFile(gitSpy, []byte("#!/bin/bash\nargs=()\nfor arg in \"$@\"; do\n if [[ \"$arg\" == https://"+f.project.Repository+" ]]; then args+=("+fmt.Sprintf("%q", remote)+"); else args+=(\"$arg\"); fi\ndone\nexec /usr/bin/git -c protocol.file.allow=always \"${args[@]}\"\n"), 0700))
+ publisherFor := func(ctx context.Context, auth runnerproto.PublicationAuthorization) (*forge.Publisher, error) {
+ return forge.New(forge.Config{Root: pubroot, GitPath: gitSpy, Runner: active.Handle.Runner, Incarnation: auth.Ticket.Incarnation, Clock: time.Now, Authorize: w.PublicationAuthorization, Revalidate: func(ctx context.Context, a forge.Authorization) error {
+ return api.Call(ctx, "validate", flowRequest(active, "publication-check"), nil)
+ }, Export: manager.ExportCandidate, Credential: func(context.Context, string) (forge.Credential, error) {
+ return forge.Credential{Remote: "https://" + f.project.Repository, Agent: "test~person@example.test", Bearer: "fixture-only"}, nil
+ }, Description: description})
+ }
+ workflow, err := runner.NewBugWorkflow(runner.BugWorkflowConfig{PublisherFor: publisherFor, Workspaces: manager, Client: client, Witness: w, Policy: func(context.Context, paseo.Selection) (paseo.ReadPolicy, error) { return policy, nil }, Executor: executor, StateDir: state, Executable: "/bin/false", InstanceID: "fixture", Copy: runner.ToolCopy{Accepted: "accepted", Rejected: "rejected"}})
+ executionMust(t, err)
+ inspector, err := runner.NewLinuxProcessInspector("/proc", client, j)
+ executionMust(t, err)
+ supervisor, err := runner.NewSupervisor(runner.SupervisorConfig{Journal: j, Client: client, Inspector: inspector, API: flowAPI{api}, Workflow: workflow, CredentialsPath: filepath.Join(state, "credentials.json"), InstallCredentials: api.InstallCredentials})
+ executionMust(t, err)
+ executionMust(t, supervisor.Recover(ctx))
+ for i, step := range []string{"prepare", "reproduce", "implement", "review", "verify", "publish"} {
+ executionMust(t, x.Sync(ctx))
+ assignments, err := api.Poll(ctx)
+ executionMust(t, err)
+ if len(assignments) != 1 {
+ t.Fatalf("%s: assignments=%v", step, assignments)
+ }
+ a := assignments[0]
+ if step != "prepare" && a.StepKey != step || step == "prepare" && a.Kind != "prepare" {
+ t.Fatalf("wrong order: %s %+v", step, a)
+ }
+ claim, err := api.Claim(ctx, runnerproto.ClaimRequest{Version: 1, AssignmentID: a.ID, Revision: a.Revision, RequestID: fmt.Sprint("flow-", i)})
+ executionMust(t, err)
+ active = runner.RunClaim{Assignment: a, ClaimResponse: claim}
+ if !a.Selection.Isolation.RunnerTainted {
+ t.Fatal("runner exposure missing")
+ }
+ if err = supervisor.Run(ctx, active); err != nil {
+ debugDB, _ := sql.Open("sqlite", filepath.Join(state, "j.db"))
+ defer debugDB.Close()
+ var phase, detail string
+ _ = debugDB.QueryRow("SELECT json_extract(body,'$.FailurePhase'),json_extract(body,'$.FailureDetail') FROM journal_supervisor WHERE kind='attempt' ORDER BY rowid DESC LIMIT 1").Scan(&phase, &detail)
+ t.Log("failure phase", phase, detail)
+ diagnostic, _ := os.ReadFile(filepath.Join(root, "failure"))
+ t.Fatalf("%s: %v bridge=%s", step, err, diagnostic)
+ }
+ }
+ saved, err := f.s.Task(ctx, ownerActor, task.ID)
+ executionMust(t, err)
+ if saved.State != "waiting_merge" || saved.BaseCommit != base {
+ t.Fatalf("not waiting for owner on pinned base: %+v", saved)
+ }
+ arts, err := x.Core.Artifacts(ctx, active.Scope)
+ executionMust(t, err)
+ for i := range arts {
+ arts[i], err = x.Core.Artifact(ctx, active.Scope, arts[i].ID)
+ executionMust(t, err)
+ }
+ var candidate team.GitCandidate
+ roles := map[team.Role]int{}
+ var baseResult, candidateResult team.CheckResult
+ var repositoryResult team.RepositoryCheckResult
+ var review team.Review
+ var candidateHash, reproductionHash string
+ producers, sessions := map[string]bool{}, map[string]bool{}
+ families := map[string]bool{}
+ for _, art := range arts {
+ roles[art.Role]++
+ if !art.Provenance.Isolation.RunnerTainted {
+ t.Fatalf("lost exposure: %s", art.Role)
+ }
+ if art.Role == team.RoleCandidate {
+ candidate = flowCandidate(art.Payload)
+ candidateHash = art.Hash
+ producers[art.Provenance.Producer] = true
+ sessions[art.Provenance.Context] = true
+ families[art.Provenance.ModelFamily] = true
+ }
+ switch art.Role {
+ case team.RoleReproduction:
+ reproductionHash = art.Hash
+ case team.RoleBaseResult:
+ executionMust(t, json.Unmarshal(art.Payload, &baseResult))
+ case team.RoleCandidateResult:
+ executionMust(t, json.Unmarshal(art.Payload, &candidateResult))
+ case team.RoleRepositoryChecks:
+ executionMust(t, json.Unmarshal(art.Payload, &repositoryResult))
+ }
+ if art.Role == team.RoleReview {
+ executionMust(t, json.Unmarshal(art.Payload, &review))
+ producers[art.Provenance.Producer] = true
+ sessions[art.Provenance.Context] = true
+ families[art.Provenance.ModelFamily] = true
+ }
+ }
+ for _, role := range []team.Role{team.RoleReproduction, team.RoleBaseResult, team.RoleCandidate, team.RoleReview, team.RoleCandidateResult, team.RoleRepositoryChecks} {
+ if roles[role] != 1 {
+ t.Fatal("missing or duplicate evidence", role, roles)
+ }
+ }
+ if baseResult.Outcome != team.CheckFail || baseResult.SubjectCommit != base || baseResult.TestsFailed != 1 || baseResult.TestsRun != 1 || baseResult.ReproductionHash != reproductionHash {
+ t.Fatal("frozen base failure changed", baseResult)
+ }
+ if candidateResult.Outcome != team.CheckPass || candidateResult.SubjectCommit != candidate.Commit || candidateResult.TestsRun != 2 || candidateResult.TestsFailed != 0 || candidateResult.ReproductionHash != reproductionHash || candidateResult.CheckDefinitionHash != baseResult.CheckDefinitionHash {
+ t.Fatal("candidate did not pass same frozen reproduction", candidateResult)
+ }
+ if repositoryResult.Commit != candidate.Commit || repositoryResult.CandidateHash != candidateHash || repositoryResult.TestsRun != 2 || repositoryResult.Outcome != team.CheckPass {
+ t.Fatal("repository checks do not match candidate", repositoryResult)
+ }
+ if review.SubjectHash != candidateHash || review.Verdict != team.VerdictApprove || len(producers) != 2 || len(sessions) != 2 {
+ t.Fatal("review identity not independent", review, producers, sessions)
+ }
+ if err = supervisor.Run(ctx, active); err == nil {
+ t.Fatal("completed publish redispatched")
+ }
+ if candidate.Commit == "" || len(families) != 2 {
+ t.Fatal("missing candidate or independent review", families)
+ }
+ if got := flowGit(t, root, "--git-dir", remote, "rev-parse", saved.ReviewRef); got != candidate.Commit {
+ t.Fatal("published commit differs from evidence", got, candidate.Commit)
+ }
+ if description.sets != 1 || !strings.Contains(description.value.Body, "unconfined") {
+ t.Fatal("publication count or label", description)
+ }
+ if scalar(t, f.d, "SELECT count(*) FROM jobs") != 1 || scalar(t, f.d, "SELECT count(*) FROM runner_assignments WHERE state='contained'") != 6 {
+ t.Fatal("duplicate job or missing containment")
+ }
+ if _, err = f.s.Task(ctx, equipo.Actor{Address: "member@example.com"}, task.ID); err != nil {
+ t.Fatal("member cannot read", err)
+ }
+ if err = f.s.SaveConnectionChoice(ctx, equipo.Actor{Address: "member@example.com"}, equipo.ConnectionChoice{ProjectID: f.project.ID, ConnectionIDs: []string{f.ids["claude"]}}); err == nil {
+ t.Fatal("member used owner's connection")
+ }
+
+ code, key := beginDevice(t, f.s)
+ approveDevice(t, f.s, code, "member@example.com")
+ memberCredential := claimDevice(t, f.s, code, key)
+ member, err := f.s.AuthenticateRunner(ctx, memberCredential.Token)
+ executionMust(t, err)
+ executionMust(t, f.s.ReportConnections(ctx, member, f.reports[:1]))
+ connections, err := f.s.Connections(ctx, equipo.Actor{Address: member.Person})
+ executionMust(t, err)
+ if len(connections) != 1 || connections[0].ID == f.ids["claude"] {
+ t.Fatal("enrolled connections crossed people")
+ }
+ executionMust(t, f.s.SaveConnectionChoice(ctx, equipo.Actor{Address: member.Person}, equipo.ConnectionChoice{ProjectID: f.project.ID, ConnectionIDs: []string{connections[0].ID}}))
+ f.project = saveProject(t, f.s, f.project, []equipo.DecisionOwner{{Decision: "work", Address: member.Person}, {Decision: "merge", Address: member.Person}}, "member-work-owner")
+ _, err = f.s.CreateBug(ctx, equipo.Actor{Address: member.Person}, f.project.ID, "second member has one family", "member-request")
+ if !errors.Is(err, equipo.ErrUnavailable) {
+ t.Fatalf("single-family submission: %v", err)
+ }
+ if scalar(t, f.d, "SELECT count(*) FROM tasks") != 1 || scalar(t, f.d, "SELECT count(*) FROM runner_assignments") != 6 {
+ t.Fatal("single-family member dispatched")
+ }
+ requireRunnerDenied(t, f.s, token)
+ t.Logf("HTTP workflow: six contained assignments, two families, exact remote candidate %s, one labelled publication, owner merge pending", candidate.Commit)
+
+}
+func flowJSON(v any) []byte {
+ b, err := json.Marshal(v)
+ if err != nil {
+ panic(err)
+ }
+ return b
+}
+func flowCandidate(b []byte) (v team.GitCandidate) { _ = json.Unmarshal(b, &v); return }
+func flowRequest(c runner.RunClaim, id string) runnerproto.RunnerRequest {
+ return runnerproto.RunnerRequest{Version: 1, AssignmentID: c.Assignment.ID, Scope: c.Scope, Handle: c.Handle, RequestID: id}
+}
+func flowArtifacts(ctx context.Context, api *runner.HTTPInstance, c runner.RunClaim) ([]team.Artifact, error) {
+ var arts []team.Artifact
+ q := flowRequest(c, "evidence")
+ if err := api.Call(ctx, "evidence", q, &arts); err != nil {
+ return nil, err
+ }
+ for i := range arts {
+ q.ArtifactID = arts[i].ID
+ if err := api.Call(ctx, "evidence", q, &arts[i]); err != nil {
+ return nil, err
+ }
+ }
+ return arts, nil
+}
+func flowGit(t *testing.T, dir string, args ...string) string {
+ t.Helper()
+ cmd := exec.Command("/usr/bin/git", args...)
+ cmd.Dir = dir
+ cmd.Env = []string{"PATH=/usr/bin:/bin", "GIT_CONFIG_NOSYSTEM=1", "GIT_CONFIG_GLOBAL=/dev/null", "GIT_AUTHOR_NAME=test", "GIT_AUTHOR_EMAIL=test@example.test", "GIT_COMMITTER_NAME=test", "GIT_COMMITTER_EMAIL=test@example.test"}
+ b, err := cmd.CombinedOutput()
+ if err != nil {
+ t.Fatalf("git %v: %v %s", args, err, b)
+ }
+ return strings.TrimSpace(string(b))
+}
+
+type flowDescription struct {
+ value forge.Description
+ sets int
+}
+
+func (*flowDescription) BeforePush() bool { return true }
+func (d *flowDescription) Set(_ context.Context, _ forge.Credential, v forge.Description) error {
+ d.value = v
+ d.sets++
+ return nil
+}
+func (d *flowDescription) Read(context.Context, forge.Credential, string, string) (forge.Description, error) {
+ return d.value, nil
+}
+
+type flowAPI struct{ *runner.HTTPInstance }
+
+func (a flowAPI) Call(ctx context.Context, op string, q runnerproto.RunnerRequest, out any) error {
+ if err := a.HTTPInstance.Call(ctx, op, q, out); err != nil {
+ return fmt.Errorf("%s: %w", op, err)
+ }
+ return nil
+}
diff --git a/internal/equipotest/specialists_test.go b/internal/equipotest/specialists_test.go
index e26720f6..44afb72f 100644
--- a/internal/equipotest/specialists_test.go
+++ b/internal/equipotest/specialists_test.go
@@ -418,8 +418,8 @@ func TestSpecialistsHaveNoRuntime(t *testing.T) {
if _, err := equipo.App(d, testConfig(testOrigin), &capturingMailer{}, logger); err != nil {
t.Fatal(err)
}
- coreTables := scalar(t, d, "SELECT count(*) FROM sqlite_master WHERE type = 'table' AND name IN ('jobs', 'attempts', 'actions')")
- if coreTables != 0 || transport.calls.Load() != 0 {
+ executionRecords := scalar(t, d, "SELECT (SELECT count(*) FROM jobs)+(SELECT count(*) FROM attempts)+(SELECT count(*) FROM actions)")
+ if executionRecords != 0 || transport.calls.Load() != 0 {
t.Fatal("settings started work")
}
for _, pattern := range []string{"../equipo/*.go", "../../cmd/equipo/*.go"} {
diff --git a/internal/equipotest/testdata/runner-flow.mjs b/internal/equipotest/testdata/runner-flow.mjs
new file mode 100644
index 00000000..0dcd6cae
--- /dev/null
+++ b/internal/equipotest/testdata/runner-flow.mjs
@@ -0,0 +1,23 @@
+
+import fs from 'node:fs';import readline from 'node:readline';import net from 'node:net';import {execFileSync,spawn} from 'node:child_process';
+const proc=process.argv[2], agents=new Map(),subs=new Map();let n=0,turn=0;
+const write=x=>process.stdout.write(JSON.stringify({version:1,...x})+'\n');
+const git=(path,args)=>execFileSync('/usr/bin/git',args,{cwd:path,env:{PATH:'/usr/bin:/bin',GIT_CONFIG_NOSYSTEM:'1',GIT_CONFIG_GLOBAL:'/dev/null',GIT_AUTHOR_NAME:'test',GIT_AUTHOR_EMAIL:'test@example.test',GIT_COMMITTER_NAME:'test',GIT_COMMITTER_EMAIL:'test@example.test'}}).toString().trim();
+const event=(a,kind,extra={})=>write({type:'event',subscription_id:subs.get(a.agent_id),event:{kind,server_id:a.server_id,agent_id:a.agent_id,provider_session_id:a.provider_session_id,epoch:'epoch',payload:{},...extra}});
+readline.createInterface({input:process.stdin}).on('line',async line=>{const q=JSON.parse(line),p=q.params;let result={};try{switch(q.op){
+case 'provider_policy':result={fixture:true};break;
+case 'preflight':result={version:'0.14.0',server_id:'server',provider_version:p.selection.provider==='claude'?'2.1.312':'0.165.0',paseo_version:'0.14.0',account_pinning:true,observed_account:p.selection.account_id,no_failover:true,recoverable_timeline:true,process_ownership:true,mcp_at_create:true,read_isolation:true,isolation_config_hash:'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'};break;
+case 'register_project':result={server_id:'server',project_id:p.path,path:p.path};break;
+case 'create_workspace':{const path=p.path+'-work';git(p.path,['worktree','add','-b',p.branch,path,p.base_commit]);result={server_id:'server',project_id:p.project_id,workspace_id:p.resource_id||p.idempotency_key,path};break;}
+case 'create_agent':{if(!p.provider_options?.fixture) throw Error('missing creation policy');const a={server_id:'server',agent_id:p.resource_id||'agent'+n,provider_session_id:'session'+(++n),workspace_id:p.workspace.workspace_id,account_id:p.selection.account_id,provider:p.selection.provider,family:p.selection.family,model:p.selection.model};const child=spawn('/bin/sleep',['60'],{cwd:p.workspace.path,env:p.env,stdio:'ignore'});agents.set(a.agent_id,{request:p,child});result=a;break;}
+case 'subscribe':subs.set(p.agent.agent_id,p.subscription_id);event(p.agent,'timeline_replacement');break;
+case 'send':{const a=p.agent,request=agents.get(a.agent_id).request,message=JSON.parse(p.message),step=message.Step;let name,args;++turn;
+if(step==='reproduce'){name='submit_reproduction';args={expected_symptom:'wrong value',files:[{path:'bug_test.go',bytes:Buffer.from('package fixture\nimport "testing"\nfunc TestBug(t *testing.T){if Value()!=2 {t.Fatal("wrong value")}}\n').toString('base64')}],test_names:[{package:'fixture',name:'TestBug'}]};}
+if(step==='implement'){fs.writeFileSync(request.workspace.path+'/value.go','package fixture\nfunc Value() int {return 2}\n');git(request.workspace.path,['add','.']);git(request.workspace.path,['commit','-m','fix']);name='submit_candidate';args={commit:git(request.workspace.path,['rev-parse','HEAD'])};}
+if(step==='review'){name='submit_review';args={candidate:JSON.parse(Buffer.from(message.Evidence.find(x=>x.Role==='candidate').Payload,'base64')).commit,decision:'approve',findings:[]};}
+const env=request.mcp_servers.equipo.env,cap=JSON.parse(fs.readFileSync(env.EQUIPO_TOOL_CAPABILITY_FILE));
+await new Promise((resolve,reject)=>{const c=net.createConnection(env.EQUIPO_TOOL_SOCKET,()=>c.write(JSON.stringify({capability:cap.secret,instance_id:cap.instance_id,task_id:cap.task_id,attempt:cap.attempt,fence:cap.fence,request_id:name,name,arguments:args})+'\n'));c.on('data',raw=>{const v=JSON.parse(raw);c.end();v.ok?resolve():reject(Error('tool rejected'));});c.on('error',reject);});
+event(a,'turn_completed',{turn_id:'turn'+a.agent_id+turn});break;}
+case 'list_terminals':result=[];break;
+}
+write({type:'result',id:q.id,result});}catch(e){fs.writeFileSync(proc+'/failure',e.stack);write({type:'result',id:q.id,error:'uncertain'});}});
diff --git a/internal/runner/budget_test.go b/internal/runner/budget_test.go
new file mode 100644
index 00000000..faeba8b9
--- /dev/null
+++ b/internal/runner/budget_test.go
@@ -0,0 +1,9 @@
+package runner
+
+import (
+ "amadan.net/rastrillo/rastrillo/budget"
+ "os"
+ "testing"
+)
+
+func TestMain(m *testing.M) { os.Exit(budget.Main(m)) }
diff --git a/internal/runner/checks/budget_test.go b/internal/runner/checks/budget_test.go
new file mode 100644
index 00000000..3c5553b9
--- /dev/null
+++ b/internal/runner/checks/budget_test.go
@@ -0,0 +1,9 @@
+package checks
+
+import (
+ "amadan.net/rastrillo/rastrillo/budget"
+ "os"
+ "testing"
+)
+
+func TestMain(m *testing.M) { os.Exit(budget.Main(m)) }
diff --git a/internal/runner/forge/budget_test.go b/internal/runner/forge/budget_test.go
new file mode 100644
index 00000000..a63e112c
--- /dev/null
+++ b/internal/runner/forge/budget_test.go
@@ -0,0 +1,9 @@
+package forge
+
+import (
+ "amadan.net/rastrillo/rastrillo/budget"
+ "os"
+ "testing"
+)
+
+func TestMain(m *testing.M) { os.Exit(budget.Main(m)) }
diff --git a/internal/runner/paseo/budget_test.go b/internal/runner/paseo/budget_test.go
new file mode 100644
index 00000000..1cda0a24
--- /dev/null
+++ b/internal/runner/paseo/budget_test.go
@@ -0,0 +1,9 @@
+package paseo
+
+import (
+ "amadan.net/rastrillo/rastrillo/budget"
+ "os"
+ "testing"
+)
+
+func TestMain(m *testing.M) { os.Exit(budget.Main(m)) }
diff --git a/internal/runner/paseo/live_test.go b/internal/runner/paseo/live_test.go
new file mode 100644
index 00000000..d90756d2
--- /dev/null
+++ b/internal/runner/paseo/live_test.go
@@ -0,0 +1,99 @@
+//go:build paseo_live
+
+package paseo
+
+import (
+ "context"
+ "encoding/json"
+ "os"
+ "path/filepath"
+ "testing"
+ "time"
+)
+
+// This opt-in probe uses only the shipped adapter. It cannot grant authority,
+// install a verified tuple, or turn an operator's assertion into live evidence.
+func livePreflight(t *testing.T) {
+ t.Helper()
+ if os.Getenv("EQUIPO_LIVE_PASEO") != "1" {
+ t.Fatal("live gate requires EQUIPO_LIVE_PASEO=1; no live evidence collected")
+ }
+ var input struct {
+ Repository string `json:"repository"`
+ Selections []Selection `json:"selections"`
+ ReadPolicy ReadPolicy `json:"read_policy"`
+ }
+ path := os.Getenv("EQUIPO_LIVE_INPUT")
+ if !filepath.IsAbs(path) {
+ t.Fatal("EQUIPO_LIVE_INPUT must name the operator's absolute disposable-repository configuration path")
+ }
+ raw, err := os.ReadFile(path)
+ if err != nil || len(raw) > 64<<10 || json.Unmarshal(raw, &input) != nil {
+ t.Fatal("cannot read live gate input")
+ }
+ if !filepath.IsAbs(input.Repository) || len(input.Selections) != 2 || !validPolicy(input.ReadPolicy) {
+ t.Fatal("disposable repository, both enrolled connections and protected paths required")
+ }
+ if input.Selections[0].Provider != "claude" || input.Selections[1].Provider != "codex" {
+ t.Fatal("select Claude then Codex; both eligible families are required")
+ }
+ ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
+ defer cancel()
+ bridge, err := filepath.Abs("../../../runner/paseo/bridge.mjs")
+ if err != nil {
+ t.Fatal(err)
+ }
+ c, err := Start(ctx, Config{BridgePath: bridge, NodePath: os.Getenv("EQUIPO_NODE_PATH"), DaemonHome: os.Getenv("EQUIPO_PASEO_HOME"), Endpoint: os.Getenv("EQUIPO_PASEO_ENDPOINT"), ServerID: os.Getenv("EQUIPO_PASEO_SERVER_ID"), RecordIntent: func(context.Context, Intent) error { return ErrCapability }, RecordCreationRefusal: func(context.Context, Intent) error { return ErrCapability }})
+ if err != nil {
+ t.Fatalf("shipped adapter could not connect to the operator-selected daemon: %v", err)
+ }
+ defer c.Close()
+ for _, s := range input.Selections {
+ t.Run(s.Provider, func(t *testing.T) {
+ var caps Capabilities
+ if err := c.call(ctx, "preflight", struct {
+ Selection Selection `json:"selection"`
+ ReadPolicy ReadPolicy `json:"read_policy"`
+ }{s, input.ReadPolicy}, &caps); err != nil {
+ t.Fatalf("live preflight: %v", err)
+ }
+ for _, check := range []struct {
+ name string
+ ok bool
+ }{
+ {"discussion 3 item 1: per-agent account binding and observed account", caps.AccountPinning && caps.ObservedAccount == s.AccountID && s.AccountID != ""},
+ {"discussion 3 item 1: no account failover", caps.NoFailover},
+ {"discussion 3 item 2: observed provider version", caps.ProviderVersion != ""},
+ {"observed daemon server identity and version", caps.ServerID == os.Getenv("EQUIPO_PASEO_SERVER_ID") && caps.PaseoVersion == PinnedVersion},
+ {"discussion 3 item 3: effective isolation configuration", caps.IsolationConfigHash == input.ReadPolicy.ConfigHash},
+ {"observed credential home and account binding identity", filepath.IsAbs(caps.ObservedCredentialHome) && caps.ObservedBindingID != ""},
+ {"discussion 3 item 4: recoverable completion and timeline", caps.RecoverableTimeline},
+ {"per-agent MCP at creation", caps.MCPAtCreate},
+ {"discussion 3 item 6: process ownership coverage", caps.ProcessOwnership},
+ } {
+ if !check.ok {
+ t.Error(check.name)
+ }
+ }
+ if s.Provider == "codex" && caps.ReadIsolation {
+ t.Error("legacy Codex must report ReadIsolation=false and unconfined provenance")
+ }
+ })
+ }
+ if t.Failed() {
+ t.FailNow()
+ }
+}
+
+func TestPaseoLiveContract(t *testing.T) {
+ livePreflight(t)
+ t.Fatal("live contract proof unavailable: structured event recovery, both permission replies, per-agent MCP, account reconnect/no-failover, complete usage and stop/archive/process cleanup require supported upstream observations")
+}
+func TestPaseoLiveReadIsolation(t *testing.T) {
+ livePreflight(t)
+ t.Fatal("live isolation proof unavailable: Claude shell/native/search/symlink/escape sentinels, workspace control, authenticated tool, executor sentinels and restart/mode repeats are required; Codex needs current owner acknowledgement and unconfined provenance, never a confinement tuple")
+}
+func TestPaseoLiveTurnCalibration(t *testing.T) {
+ livePreflight(t)
+ t.Fatal("live calibration proof unavailable: bounded representative turns with complete uncached/cached/output usage, checked twice-maximum rounding to 1000, at least 23 reservations, explicit period headroom, unknown then known usage, exhaustion and charged overruns are required")
+}
diff --git a/internal/runner/workspace/budget_test.go b/internal/runner/workspace/budget_test.go
new file mode 100644
index 00000000..3501e399
--- /dev/null
+++ b/internal/runner/workspace/budget_test.go
@@ -0,0 +1,9 @@
+package workspace
+
+import (
+ "amadan.net/rastrillo/rastrillo/budget"
+ "os"
+ "testing"
+)
+
+func TestMain(m *testing.M) { os.Exit(budget.Main(m)) }
diff --git a/scripts/live-gate.sh b/scripts/live-gate.sh
new file mode 100755
index 00000000..d8e54a7f
--- /dev/null
+++ b/scripts/live-gate.sh
@@ -0,0 +1,15 @@
+#!/bin/sh
+# DRAFT: copy review required
+set -eu
+cd "$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)"
+printf '%s\n' 'Read docs/live-gate.md. The pinned stack has unresolved blockers and cannot pass.'
+printf '%s\n' 'Confirm the disposable repository, enrolled connections, origin and machine fingerprint.'
+printf '%s' 'Type LIVE DISPOSABLE ONLY: '
+IFS= read -r answer
+[ "$answer" = 'LIVE DISPOSABLE ONLY' ] || exit 1
+printf '%s\n' 'Confirm bounded calibration funding, disposable sentinel locations, owner acknowledgement and process ownership.'
+printf '%s\n' 'Keep other agents, projects, credentials and the shared daemon unchanged.'
+printf '%s' 'Type RUN LIVE GATE: '
+IFS= read -r answer
+[ "$answer" = 'RUN LIVE GATE' ] || exit 1
+EQUIPO_LIVE_PASEO=1 go test -tags paseo_live ./internal/runner/paseo -run 'TestPaseoLiveContract|TestPaseoLiveReadIsolation|TestPaseoLiveTurnCalibration' -count=1