oficina / equipo Public

Fix certified connection discovery after binary relocation

Co-Authored-By: Astra <noreply@openai.com>
claude b59a42aef6bb92d83b431c25768c8a79aa1ec072 parent afd77f8
14 files changed, +1,139 −171
  • docs/superpowers/plans/CONTROLLER-REPORT-connection-available.md +277 −0
  • internal/plan3test/connection_available_fixture.go +130 −0
  • internal/plan3test/coordinator_acceptance_http_test.go +0 −123
  • internal/plan3test/coordinator_cli_fixture.go +137 −0
  • internal/release/manifest.go +4 −3
  • internal/release/manifest.json +4 −2
  • internal/release/policy_relocation.go +24 −0
  • internal/runner/certified/discovery.go +76 −0
  • internal/runner/certified/discoverytest/budget_test.go +9 −0
  • internal/runner/certified/discoverytest/connection_available_test.go +212 −0
  • internal/runner/provider/policy_relocation.go +43 −0
  • internal/runner/provider/policy_relocation_test.go +75 −0
  • internal/runner/runtime_direct.go +29 −43
  • scripts/runner-reference-allowlist.json +119 −0

CI passed — run details

diff --git a/docs/superpowers/plans/CONTROLLER-REPORT-connection-available.md b/docs/superpowers/plans/CONTROLLER-REPORT-connection-available.md
new file mode 100644
index 00000000..709d7165
--- /dev/null
+++ b/docs/superpowers/plans/CONTROLLER-REPORT-connection-available.md
@@ -0,0 +1,277 @@
+# Connection availability
+
+The relocation fix passes the local fake CLI flow and the production no-turn
+preflight. Deployment and instance receipt of the new heartbeat are pending the
+controller. No deployment, push, merge or message as Paul was performed.
+
+## Root cause
+
+The read-only instance query returned both unavailable reports from transaction
+5152, written 2026-11-06 12:32:22 UTC. The unit was active on release 8989033.
+`claude-a` reported `f415d19a3841596750d28113f2217f380e0955b4fb8fd4dc9a9ef1052f66fac4`.
+`claude-b` reported `9b5b1e544a1fd642682a8911ec3d1fe696b6356c438c012e5d3706874340199f`.
+These were constructed implement-policy hashes, not the fallback binding hashes.
+All five installed binary digests passed `VerifyInstalled`.
+
+`discoverNamespaces` constructed only the implement policy. It required both
+installed binary verification and an exact implement certificate before running
+the CLI preflight. A failed certificate comparison left the default
+`capability_unverified` reason. The account/version probe and dependency probe
+therefore never ran. There is no missing startup registration or additional
+model capability trial to perform.
+
+`policyTemplate` retains runtime binary source paths as well as their digests.
+The live gate used these two source paths:
+
+- `/home/paulca/.local/share/equipo/try/bin/claude`
+- `/home/paulca/.local/share/equipo/try/bin/equipo-tool-proxy`
+
+The enrolled service used the same bytes at these paths:
+
+- `/home/paulca/.local/share/claude/versions/2.1.312`
+- `/home/paulca/.local/share/equipo-runner/releases/8989033/equipo-tool-proxy`
+
+A temporary diagnostic called the production policy constructor on only the
+`paul@tito.io` binding. With the service paths it reproduced the reported hash.
+Changing just those two executable paths to the gate paths reproduced all three
+existing certificates exactly:
+
+| Action | Certified hash |
+|---|---|
+| implement | `07f4d97e1629d285c30411766ba75135ad7adb599fd8e50321d781e5b88c7e54` |
+| review | `19832014cb5aa65fb42d2cd29661d336752b7ad58efef7a8fc4a4e42ee6ed269` |
+| coordinate | `3ba26b99cbfb29041600d32d0eb4c2fa53174ff8bb8d79ad4d65180c654b53cf` |
+
+The second binding belongs to `paul@keymail.dev`. These certificates bind the
+first account and home. Relocation does not make the second account certified.
+
+## Change
+
+The release manifest records the two live-gate paths as `policy_source` metadata
+on the existing binary entries. Certificate comparison can substitute those
+source paths for read-only executable mounts. Digests, mount targets, access
+modes, account identity, home, model, settings, denied paths, tools and versions
+remain in the comparison. The original concrete manifest and policy hash remain
+unchanged and continue to protect launch attestation and source validation.
+Neither evidence artifacts nor certified hashes were rewritten.
+
+Discovery now tries certified actions, preferring coordinate, instead of
+requiring implement. Only a matching certificate followed by a successful
+preflight makes a connection available. It reports the matching certified tuple
+so the instance can verify isolation. Specialist and coordinator launch guards
+use the same relocation-aware comparison and still require installed pins and
+confined selection. Every launch still checks its own action; availability does
+not certify an uncertified action.
+
+The CLI preflight checks the account/version and dependency startup without a
+model turn. Its successful result is cached by binding, credential-generation
+fingerprint and actual policy hash. Construction and certificate checks still
+run on each discovery. Changed credentials require another preflight.
+
+The report-selection code lives in the existing certified package. New discovery
+tests have their own package to stay inside source and test budgets. The existing
+fake coordinator launcher was moved unchanged into a reusable fixture file. No
+budget was raised. No application copy or README changed. The controller report
+is an agent handoff; no copy-review server was started.
+
+Future certificates must record the binary source paths used by their own live
+gate if their binaries will move. These optional paths describe the original
+certificate; they are not installation paths or a mechanism to certify new
+accounts. Other changes to the exact policy still require certification.
+
+## Verification
+
+Go commands use `CGO_ENABLED=0`; the full gate pins Go 1.26.10. Go caches stayed
+at their defaults. Scratch was under the existing on-disk `$TMPDIR`.
+
+1. Before the relocation implementation, `go test ./internal/runner/provider
+ -run '^TestPolicyBinaryRelocation$' -count=1` failed with
+ `identical relocated binary lost certification`.
+2. The final targeted run covers `TestPolicyBinaryRelocation`,
+ `TestConnectionAvailableGuards`, `TestConnectionAvailableCoordinatorFakeCLI`,
+ `TestDirectClaimRevalidates`, `TestRuntimeMountsStandaloneToolProxy` and
+ `TestCoordinatorSessionProductionWiring`. All passed.
+3. `TestConnectionAvailableCoordinatorFakeCLI` uses a synthetic certificate and
+ actual local CLI subprocesses. It exercises account preflight, relocated
+ policy comparison, HTTP heartbeat, instance isolation verification, automatic
+ binding, admitted coordinator claim, runner journal, tool proxy, reply and
+ delivered turn. The adapter and namespace containment are simulated; this is
+ not live isolation evidence.
+4. The discovery guards cover coordinator-only and review-only certificates,
+ absent certificates, wrong actions, another binding, changed binary bytes,
+ failed installed verification, failed account preflight, sign-in maintenance
+ and failed cleanup. Provider tests also cover settings, denied paths, targets,
+ writable mounts, manifest integrity, policy-hash integrity and invalid paths.
+5. Mutation checks removed relocation, concrete manifest validation, policy hash
+ validation, installed verification, preflight, exact action/hash matching and
+ support for coordinator-only discovery. Each targeted test failed at its
+ assertion. All mutations were restored. The first cleanup mutation contained
+ a substitution typo and failed compilation; a corrected cleanup mutation is
+ recorded in the final results below.
+
+The mutation commands were `go test ./internal/runner/provider -run
+'^TestPolicyBinaryRelocation$' -count=1`, its `manifest` and `hash` subtests,
+and the `uninstalled`, `preflight`, `cleanup`, `wrong-action` discovery subtests
+plus `TestConnectionAvailableCoordinatorFakeCLI`. Discovery tests initially lived
+in `internal/plan3test`; their final location is
+`internal/runner/certified/discoverytest`.
+
+### Production preflight
+
+The unit was stopped briefly and restarted in a `finally` block. An initial
+test-binary diagnostic was refused because containment requires its runner path
+to identify the current executable. No provider was launched by that attempt.
+A scratch build of the real command then ran `preflight` with the service's
+configuration and exited 0. It reported:
+
+```json
+{
+ "LocalID": "claude-a",
+ "Available": true,
+ "ReadIsolation": true,
+ "UnavailableReason": "",
+ "IsolationConfigHash": "3ba26b99cbfb29041600d32d0eb4c2fa53174ff8bb8d79ad4d65180c654b53cf",
+ "ObservedAccountID": "paul@tito.io"
+}
+```
+
+`claude-b` remained unavailable with `capability_unverified`; its CLI was not
+launched. No model turns were used, against the authorized ceiling of 15. No
+credential file contents were inspected or printed by the diagnostic harness;
+the production account code performed its normal staging and validation.
+
+This foreground preflight does not send a heartbeat. It proves that the updated
+runner can produce the report, not that the deployed instance has received it.
+The original unit was active again on release 8989033 after the check.
+
+## Controller deployment and receipt check
+
+Run these steps only after the controller has reviewed, pushed and integrated
+the commit. This agent has not run them. Keep the existing enrollment and account
+bindings. Re-enrollment is unnecessary.
+
+1. In the clean integrated checkout, load the existing service configuration and
+ build the versioned release:
+
+ ```sh
+ set -a
+ . "$HOME/.local/share/equipo-runner/service.env"
+ set +a
+ make release
+ connection_version=$(git rev-parse --short HEAD)
+ carlos deploy --app equipo --account oficina --channel edge --timeout 5m \
+ "releases/equipo-linux-arm64-$connection_version"
+ ```
+
+2. Update the local runner to the same version. The following script preserves
+ the existing environment and unit except for their executable paths:
+
+ ```sh
+ export connection_version
+ python3 - <<'PY'
+ import os, pathlib, shutil, subprocess
+ version = os.environ['connection_version']
+ home = pathlib.Path.home()
+ root = home / '.local/share/equipo-runner'
+ source = pathlib.Path('releases') / ('equipo-runner-linux-amd64-' + version)
+ destination = root / 'releases' / version
+ unit = home / '.config/systemd/user/equipo-runner.service'
+ env = root / 'service.env'
+ old_unit, old_env = unit.read_text(), env.read_text()
+ assert sum(x.startswith('ExecStart=') for x in old_unit.splitlines()) == 1
+ assert sum(x.startswith('EQUIPO_TOOL_PROXY_PATH=') for x in old_env.splitlines()) == 1
+ subprocess.run(['systemctl', '--user', 'stop', 'equipo-runner.service'], check=True)
+ try:
+ destination.mkdir(mode=0o700, exist_ok=False)
+ for name in ('equipo-runner', 'equipo-tool-proxy', 'install-manifest.json'):
+ shutil.copy2(source / name, destination / name)
+ unit.write_text('\n'.join(
+ 'ExecStart=' + str(destination / 'equipo-runner') + ' run'
+ if x.startswith('ExecStart=') else x for x in old_unit.splitlines()) + '\n')
+ env.write_text('\n'.join(
+ 'EQUIPO_TOOL_PROXY_PATH="' + str(destination / 'equipo-tool-proxy') + '"'
+ if x.startswith('EQUIPO_TOOL_PROXY_PATH=') else x for x in old_env.splitlines()) + '\n')
+ subprocess.run(['systemctl', '--user', 'daemon-reload'], check=True)
+ except BaseException:
+ unit.write_text(old_unit)
+ env.write_text(old_env)
+ subprocess.run(['systemctl', '--user', 'daemon-reload'], check=True)
+ raise
+ finally:
+ subprocess.run(['systemctl', '--user', 'start', 'equipo-runner.service'], check=True)
+ PY
+ systemctl --user is-active equipo-runner.service
+ ```
+
+3. After the next heartbeat, query the read-only replica. Confirm its snapshot
+ and `last_seen` are newer than the runner update. Repeat if the replica lags.
+
+ ```sh
+ carlos db query --app equipo --account oficina --sql "
+ SELECT local_id, last_seen,
+ json_extract(reports_json, '\$[0].Available') AS available,
+ json_extract(reports_json, '\$[0].ReadIsolation') AS read_isolation,
+ json_extract(reports_json, '\$[0].UnavailableReason') AS reason,
+ json_extract(reports_json, '\$[0].IsolationConfigHash') AS policy_hash
+ FROM connections ORDER BY local_id"
+ ```
+
+ For `claude-a`, require `available=1`, `read_isolation=1`, an empty reason and
+ the coordinator hash printed above. `claude-b` must remain unavailable.
+ Save this output as the missing deployed receipt evidence.
+
+4. Paul sends a new message himself. Do not send or retry one as Paul. Verify
+ the coordinator binds to `claude-a` and its new turn reaches `delivered`:
+
+ ```sh
+ carlos db query --app equipo --account oficina --sql "
+ SELECT b.id, b.person, c.local_id, b.generation
+ FROM coordinator_bindings b JOIN connections c ON c.id=b.connection_id"
+ carlos db query --app equipo --account oficina --sql "
+ SELECT id, message_id, state FROM coordinator_turns ORDER BY rowid DESC LIMIT 5"
+ ```
+
+ An existing finished setup note is not a queued request. The fresh message
+ supplies the request for this check. Record the turn ID and final state.
+
+## Final gate and handoff
+
+The first `make -k ci` exited 2. It found six unclassified references: five
+already in the controller brief and one in the new regression test. The same
+inventory failure caused `TestDirectDeadReferencesRepository` to fail. Staticcheck
+also required `http.StatusConflict` instead of literal 409 in the new fixture.
+Both issues were corrected. All other test assertions passed: 34 packages ran,
+one failed on that inventory check. Adapter, namespace and migration checks
+passed. Performance passed, including a cold boot median of 116ms against 500ms.
+
+Local timing warnings were runner 352.369s/330s, provider 21.388s/15s, Claude
+adapter 46.973s/45s and Codex adapter 39.399s/35s. These would fail their budgets
+in CI mode. No timing allowance was changed.
+
+The corrected cleanup mutation failed at `cleanup failure hidden <nil>`.
+Restoring the guard made the final targeted tests pass: provider 0.309s,
+discovery 6.027s and the existing coordinator HTTP acceptance test 4.225s.
+`make copy-release-check direct-release-check` also passed with the installed
+binary paths. The existing evidence remains byte-identical.
+
+The first permitted full `make -k ci` rerun exited 0. All 35 test packages
+passed, with no cached packages and eight packages without tests. The test phase
+took 362.191s. Build, vet, formatting, staticcheck, vulnerability scanning,
+secret scanning, reference inventory, size budgets, adapter, namespace,
+migration and performance checks passed. Cold boot median was 121ms against
+500ms. Total full gate runs: two; no second rerun was needed.
+
+The rerun retained local timing warnings: runner 360.185s/330s, provider
+21.488s/15s, Claude adapter 47.208s/45s and Codex adapter 39.783s/35s. Exit 0
+establishes the local gate result, not CI-mode timing compliance.
+
+A second read-only instance query, transaction 5291 written at
+2026-11-06 12:52:12 UTC, returned no coordinator bindings. The controller can
+therefore test initial automatic binding with Paul's next message after the
+update. Receipt of an available heartbeat and a delivered production turn
+remain pending deployment; neither is claimed here.
+
+Task scratch and diagnostic sources were removed. No task server or background
+process remains. The existing unit is active on release 8989033, as requested.
+The changes and this report are committed on `connection-available`; the
+controller owns push, integration and deployment. The workspace is safe to close.
diff --git a/internal/plan3test/connection_available_fixture.go b/internal/plan3test/connection_available_fixture.go
new file mode 100644
index 00000000..016c839d
--- /dev/null
+++ b/internal/plan3test/connection_available_fixture.go
@@ -0,0 +1,130 @@
+package plan3test
+
+import (
+ "amadan.net/oficina/equipo/internal/equipo"
+ "amadan.net/oficina/equipo/internal/equipo/team"
+ "amadan.net/oficina/equipo/internal/release"
+ "amadan.net/oficina/equipo/internal/runner"
+ "amadan.net/oficina/equipo/internal/runner/containment"
+ "amadan.net/oficina/equipo/internal/runner/provider"
+ "amadan.net/oficina/equipo/internal/runner/provider/claude"
+ "amadan.net/oficina/equipo/internal/runnerproto"
+ "context"
+ "encoding/json"
+ "net/http"
+ "net/http/httptest"
+ "os/exec"
+ "path/filepath"
+ "strings"
+ "testing"
+ "time"
+)
+
+func RunConnectionAvailableCoordinator(t *testing.T, report runnerproto.ConnectionReport, manifest release.Manifest, build func(string) (provider.Launch, func() error, error), binary string) {
+ t.Helper()
+ f := newFixture(t)
+ task := f.createTask(t)
+ f.planConnections(t, task.ProjectID)
+ f.exec(t, "INSERT INTO runner_credentials(id,runner_id,instance_id,audience,person,machine_key_hash,token_hash,expires_at) VALUES('fixture-credential','fixture-runner',?,?,?,'','fixture-token',?)", f.TeamID, runnerproto.RunnerAudience, owner.Address, time.Now().Add(time.Hour).UTC())
+ p := equipo.RunnerPrincipal{RunnerID: "fixture-runner", Person: owner.Address, CredentialID: "fixture-credential"}
+ tuple := team.IsolationTuple{Provider: report.Provider, ProviderVersion: report.ProviderVersion, LauncherVersion: report.LauncherVersion, BwrapVersion: report.BwrapVersion, PolicyVersion: report.PolicyVersion, IsolationConfigHash: report.IsolationConfigHash}
+ f.Store = equipo.NewStore(f.DB, equipo.WithVerifiedIsolationTuples([]team.IsolationTuple{tuple}), equipo.WithCoordinatorRelease(manifest))
+ var dbPath string
+ must(t, f.DB.Writer().QueryRow("SELECT file FROM pragma_database_list WHERE name='main'").Scan(&dbPath))
+ x, err := f.Store.AttachExecution(ctx, dbPath, team.Options{Clock: team.RealClock{}, Authority: equipo.NewAuthority(f.Store, nil), Adapters: map[team.Operation]team.Adapter{team.OpProviderCall: f.Store.RunnerAdapter(team.OpProviderCall)}})
+ must(t, err)
+ t.Cleanup(func() { _ = x.Core.Close() })
+ _, err = x.Core.Resume(ctx)
+ must(t, err)
+ must(t, f.Store.SetCoordinatorLimits(ctx, owner, owner.Address, team.Limits{Calls: 24, InputTokens: 200000, OutputTokens: 40000, Seconds: 10000}, equipo.Mutation{RequestID: "limits"}))
+ validators := runnerproto.ReportValidators(runnerproto.ReportErrors{Invalid: equipo.ErrInvalid, Forbidden: equipo.ErrForbidden, Conflict: equipo.ErrConflict}, nil)
+ validators.Containment = func(context.Context, equipo.Assignment, equipo.RunnerRequest) error { return nil }
+ x.SetRunnerValidators(validators)
+ h := runnerproto.Handler{Execution: func() runnerproto.ExecutionAPI { return x }, AuthenticateRunner: func(context.Context, string) (runnerproto.RunnerPrincipal, error) { return p, nil }, ReportConnections: f.Store.ReportConnections, JSON: func(w http.ResponseWriter, status int, v any) {
+ w.WriteHeader(status)
+ raw, e := runnerproto.Marshal(v)
+ if e != nil {
+ t.Error(e)
+ }
+ w.Write(raw)
+ }, Failure: func(w http.ResponseWriter, e error) { t.Log(e); http.Error(w, e.Error(), http.StatusConflict) }, Invalid: equipo.ErrInvalid, Forbidden: equipo.ErrForbidden, Unavailable: equipo.ErrUnavailable}
+ server := httptest.NewServer(h.Router())
+ defer server.Close()
+ j, err := runner.OpenJournal(ctx, filepath.Join(t.TempDir(), "runner", "journal.db"))
+ must(t, err)
+ defer j.Close()
+ api, err := runner.NewHTTPInstance(server.URL, j, runnerproto.RunnerCredential{Token: "fixture", ExpiresAt: time.Now().Add(time.Hour)})
+ must(t, err)
+ must(t, api.Heartbeat(ctx, []runnerproto.ConnectionReport{report}))
+ msg, err := f.Store.SendMessage(ctx, owner, "", "hello", equipo.Mutation{RequestID: "available-message"})
+ must(t, err)
+ if f.count(t, "SELECT count(*) FROM coordinator_bindings WHERE connection_id='claude'") != 1 {
+ t.Fatal("heartbeat did not permit automatic binding")
+ }
+ launcher := &connectionReplyCLI{acceptanceLauncher: acceptanceLauncher{journal: j}, binary: binary}
+ service := runner.CoordinatorService{Journal: j, API: api, Launchers: map[string]provider.Launcher{"claude": launcher}}
+ service.OpenLaunch = func(ctx context.Context, c runnerproto.CoordinatorClaim, proxy *runner.ToolProxy) (provider.Launch, func() error, error) {
+ l, close, err := build("coordinate")
+ if err != nil {
+ return l, close, err
+ }
+ if _, ok := manifest.CertifiedPolicyHash("claude", "coordinate", claude.Version, l.Policy); !ok {
+ return l, close, provider.ErrUncertified
+ }
+ launcher.proxy = proxy
+ l.AttemptKey = c.Turn.ID
+ err = j.RecordDirectLaunch(ctx, l, containment.Record{ID: c.Turn.ID, AttemptKey: c.Turn.ID, ManifestHash: l.Policy.ManifestHash, PolicyHash: l.Policy.Hash})
+ return l, close, err
+ }
+ service.Contain = func(_ context.Context, c runnerproto.CoordinatorClaim) (runnerproto.ContainmentProof, error) {
+ return runnerproto.ContainmentProof{Scope: c.Scope, Handle: c.Handle, Version: 2, CheckedAt: time.Now()}, nil
+ }
+ must(t, service.Poll(ctx))
+ if launcher.starts != 1 || f.count(t, "SELECT count(*) FROM coordinator_turns WHERE message_id=? AND state='delivered'", msg.ID) != 1 {
+ t.Fatalf("coordinator did not deliver fake CLI turn: starts=%d", launcher.starts)
+ }
+ page, err := f.Store.Conversation(ctx, owner, "", 20)
+ must(t, err)
+ found := false
+ for _, m := range page.Messages {
+ if m.Body == "fixture coordinator reply" {
+ found = true
+ }
+ }
+ if !found {
+ t.Fatal("CLI answer missing from conversation")
+ }
+}
+
+type connectionReplyCLI struct {
+ acceptanceLauncher
+ binary string
+}
+
+func (l *connectionReplyCLI) StartTurn(ctx context.Context, s provider.Session, turn provider.Turn) error {
+ if err := l.journal.BeginTurn(ctx, s, turn); err != nil {
+ return err
+ }
+ rawInput, _ := json.Marshal(map[string]any{"type": "user", "session_id": s.ID, "message": map[string]string{"role": "user", "content": turn.Prompt}})
+ if _, err := l.capture.Input.Write(append(rawInput, '\n')); err != nil {
+ return err
+ }
+ cmd := exec.CommandContext(ctx, l.binary)
+ cmd.Stdin = strings.NewReader(turn.Prompt)
+ raw, err := cmd.Output()
+ if err != nil {
+ return err
+ }
+ l.starts++
+ args, _ := json.Marshal(map[string]any{"body": strings.TrimSpace(string(raw)), "source_refs": []string{}})
+ if _, err = l.proxy.CallCoordinatorTool(ctx, runnerproto.CoordinatorToolCall{RequestID: "reply", Name: "post_message", Arguments: args}); err != nil {
+ return err
+ }
+ event := provider.Event{SessionID: s.ID, TurnID: turn.ID, Kind: "turn.completed", Payload: json.RawMessage(`{"usage":{"input_tokens":2,"cache_read_input_tokens":0,"cache_creation_input_tokens":0,"output_tokens":3}}`)}
+ raw, err = json.Marshal(event)
+ if err != nil {
+ return err
+ }
+ _, err = l.process.writer.Write(append(raw, '\n'))
+ return err
+}
diff --git a/internal/plan3test/coordinator_acceptance_http_test.go b/internal/plan3test/coordinator_acceptance_http_test.go
index 03d6ff51..fa1096e8 100644
--- a/internal/plan3test/coordinator_acceptance_http_test.go
+++ b/internal/plan3test/coordinator_acceptance_http_test.go
@@ -1,8 +1,6 @@
package plan3test
import (
- "amadan.net/oficina/equipo/internal/coordinator"
- "bytes"
"context"
"encoding/json"
"errors"
@@ -12,7 +10,6 @@ import (
"net/http/httptest"
"path/filepath"
"strings"
- "sync"
"testing"
"time"
@@ -191,123 +188,3 @@ func acceptanceHTTP(t *testing.T) {
request(owner, "POST", "/api/v1/tasks/"+id+"/cancel", `{}`, "cancel-"+id, fmt.Sprintf(`"%d"`, task.Revision))
}
}
-
-type acceptanceLauncher struct {
- capture *provider.Capture
- process *acceptanceProcess
- journal *runner.Journal
- proxy *runner.ToolProxy
- claim runnerproto.CoordinatorClaim
- plan taskplan.Plan
- message string
- result runnerproto.CoordinatorToolResult
- events chan provider.Event
- starts int
- interrupt bool
-}
-
-func (l *acceptanceLauncher) Preflight(_ context.Context, b provider.Binding, _ provider.Policy) (provider.Identity, error) {
- return b.Expected, nil
-}
-func (l *acceptanceLauncher) Open(ctx context.Context, v provider.Launch) (provider.Session, error) {
- s := provider.Session{ID: v.AttemptKey + "-session", AttemptKey: v.AttemptKey, Provider: v.Selection.Provider, AccountID: v.Selection.AccountID, Family: v.Selection.Family, Model: v.Selection.Model}
- stdout, writer := io.Pipe()
- l.process = &acceptanceProcess{record: containment.Record{ID: v.AttemptKey, AttemptKey: v.AttemptKey, ManifestHash: v.Policy.ManifestHash, PolicyHash: v.Policy.Hash}, stdout: stdout, writer: writer}
- var err error
- l.capture, err = runner.NewCaptureFactory(l.journal).Open(ctx, l.process, v)
- if err != nil {
- return s, err
- }
- l.events = make(chan provider.Event, 1)
- go func() {
- defer close(l.events)
- for frame := range l.capture.Frames {
- var event provider.Event
- if json.Unmarshal(frame.Bytes, &event) == nil {
- event.Sequence = frame.Sequence
- l.events <- event
- }
- }
- }()
- return s, l.journal.BindSession(ctx, s)
-}
-func (l *acceptanceLauncher) Events(context.Context, provider.Session) (<-chan provider.Event, error) {
- return l.events, nil
-}
-func (l *acceptanceLauncher) StartTurn(ctx context.Context, s provider.Session, turn provider.Turn) error {
- if strings.Contains(turn.Prompt, "peer private") {
- return fmt.Errorf("foreign private context")
- }
- if err := l.journal.BeginTurn(ctx, s, turn); err != nil {
- return fmt.Errorf("begin: %w", err)
- }
- l.starts++
- rawInput, _ := json.Marshal(map[string]any{"type": "user", "session_id": s.ID, "message": map[string]string{"role": "user", "content": turn.Prompt}})
- if _, err := l.capture.Input.Write(append(rawInput, '\n')); err != nil {
- return err
- }
- if l.interrupt {
- return provider.ErrUncertain
- }
- draft := coordinator.Plan{Kind: l.plan.Kind, ProjectID: l.plan.ProjectID}
- for _, step := range l.plan.Steps {
- draft.Steps = append(draft.Steps, coordinator.PlanStep{Key: step.Key, Specialist: step.Specialist, Action: step.Action, Instructions: step.Instructions, DependsOn: step.DependsOn})
- }
- input := coordinator.ProposePlan{MessageID: l.message, Plan: draft}
- raw, err := json.Marshal(input)
- if err != nil {
- return err
- }
- call := runnerproto.CoordinatorToolCall{RequestID: "proposal", Name: "propose_plan", Arguments: raw}
- l.result, err = l.proxy.CallCoordinatorTool(ctx, call)
- if err != nil {
- return err
- }
- again, err := l.proxy.CallCoordinatorTool(ctx, call)
- if err != nil {
- return err
- }
- if again.ResourceID != l.result.ResourceID {
- return fmt.Errorf("duplicate proposal")
- }
- event := provider.Event{SessionID: s.ID, TurnID: turn.ID, Kind: "turn.completed", Payload: json.RawMessage(`{"usage":{"input_tokens":2,"cache_read_input_tokens":0,"cache_creation_input_tokens":0,"output_tokens":3}}`)}
- raw, err = json.Marshal(event)
- if err != nil {
- return err
- }
- _, err = l.process.writer.Write(append(raw, '\n'))
- return err
-}
-func (l *acceptanceLauncher) Respond(context.Context, provider.Session, provider.Answer) error {
- return nil
-}
-func (l *acceptanceLauncher) Interrupt(context.Context, provider.Session) error {
- return l.process.Contain(ctx)
-}
-func (l *acceptanceLauncher) Close(context.Context, provider.Session) error {
- _ = l.process.Contain(ctx)
- return <-l.capture.Done
-}
-
-type acceptanceProcess struct {
- record containment.Record
- stdout *io.PipeReader
- writer *io.PipeWriter
- once sync.Once
-}
-
-func (p *acceptanceProcess) ID() string { return p.record.ID }
-func (p *acceptanceProcess) Record() containment.Record { return p.record }
-func (p *acceptanceProcess) Stdin() io.WriteCloser { return acceptanceInput{} }
-func (p *acceptanceProcess) Stdout() io.ReadCloser { return p.stdout }
-func (p *acceptanceProcess) Stderr() io.ReadCloser { return io.NopCloser(bytes.NewReader(nil)) }
-func (p *acceptanceProcess) Wait(context.Context) (provider.Exit, error) { return provider.Exit{}, nil }
-func (p *acceptanceProcess) Contain(context.Context) error {
- p.once.Do(func() { _ = p.writer.Close() })
- return nil
-}
-
-type acceptanceInput struct{}
-
-func (acceptanceInput) Write(raw []byte) (int, error) { return len(raw), nil }
-func (acceptanceInput) Close() error { return nil }
diff --git a/internal/plan3test/coordinator_cli_fixture.go b/internal/plan3test/coordinator_cli_fixture.go
new file mode 100644
index 00000000..59bcc176
--- /dev/null
+++ b/internal/plan3test/coordinator_cli_fixture.go
@@ -0,0 +1,137 @@
+package plan3test
+
+import (
+ "amadan.net/oficina/equipo/internal/coordinator"
+ "amadan.net/oficina/equipo/internal/runner"
+ "amadan.net/oficina/equipo/internal/runner/containment"
+ "amadan.net/oficina/equipo/internal/runner/provider"
+ "amadan.net/oficina/equipo/internal/runnerproto"
+ "amadan.net/oficina/equipo/internal/taskplan"
+ "bytes"
+ "context"
+ "encoding/json"
+ "fmt"
+ "io"
+ "strings"
+ "sync"
+)
+
+type acceptanceLauncher struct {
+ capture *provider.Capture
+ process *acceptanceProcess
+ journal *runner.Journal
+ proxy *runner.ToolProxy
+ claim runnerproto.CoordinatorClaim
+ plan taskplan.Plan
+ message string
+ result runnerproto.CoordinatorToolResult
+ events chan provider.Event
+ starts int
+ interrupt bool
+}
+
+func (l *acceptanceLauncher) Preflight(_ context.Context, b provider.Binding, _ provider.Policy) (provider.Identity, error) {
+ return b.Expected, nil
+}
+func (l *acceptanceLauncher) Open(ctx context.Context, v provider.Launch) (provider.Session, error) {
+ s := provider.Session{ID: v.AttemptKey + "-session", AttemptKey: v.AttemptKey, Provider: v.Selection.Provider, AccountID: v.Selection.AccountID, Family: v.Selection.Family, Model: v.Selection.Model}
+ stdout, writer := io.Pipe()
+ l.process = &acceptanceProcess{record: containment.Record{ID: v.AttemptKey, AttemptKey: v.AttemptKey, ManifestHash: v.Policy.ManifestHash, PolicyHash: v.Policy.Hash}, stdout: stdout, writer: writer}
+ var err error
+ l.capture, err = runner.NewCaptureFactory(l.journal).Open(ctx, l.process, v)
+ if err != nil {
+ return s, err
+ }
+ l.events = make(chan provider.Event, 1)
+ go func() {
+ defer close(l.events)
+ for frame := range l.capture.Frames {
+ var event provider.Event
+ if json.Unmarshal(frame.Bytes, &event) == nil {
+ event.Sequence = frame.Sequence
+ l.events <- event
+ }
+ }
+ }()
+ return s, l.journal.BindSession(ctx, s)
+}
+func (l *acceptanceLauncher) Events(context.Context, provider.Session) (<-chan provider.Event, error) {
+ return l.events, nil
+}
+func (l *acceptanceLauncher) StartTurn(ctx context.Context, s provider.Session, turn provider.Turn) error {
+ if strings.Contains(turn.Prompt, "peer private") {
+ return fmt.Errorf("foreign private context")
+ }
+ if err := l.journal.BeginTurn(ctx, s, turn); err != nil {
+ return fmt.Errorf("begin: %w", err)
+ }
+ l.starts++
+ rawInput, _ := json.Marshal(map[string]any{"type": "user", "session_id": s.ID, "message": map[string]string{"role": "user", "content": turn.Prompt}})
+ if _, err := l.capture.Input.Write(append(rawInput, '\n')); err != nil {
+ return err
+ }
+ if l.interrupt {
+ return provider.ErrUncertain
+ }
+ draft := coordinator.Plan{Kind: l.plan.Kind, ProjectID: l.plan.ProjectID}
+ for _, step := range l.plan.Steps {
+ draft.Steps = append(draft.Steps, coordinator.PlanStep{Key: step.Key, Specialist: step.Specialist, Action: step.Action, Instructions: step.Instructions, DependsOn: step.DependsOn})
+ }
+ input := coordinator.ProposePlan{MessageID: l.message, Plan: draft}
+ raw, err := json.Marshal(input)
+ if err != nil {
+ return err
+ }
+ call := runnerproto.CoordinatorToolCall{RequestID: "proposal", Name: "propose_plan", Arguments: raw}
+ l.result, err = l.proxy.CallCoordinatorTool(ctx, call)
+ if err != nil {
+ return err
+ }
+ again, err := l.proxy.CallCoordinatorTool(ctx, call)
+ if err != nil {
+ return err
+ }
+ if again.ResourceID != l.result.ResourceID {
+ return fmt.Errorf("duplicate proposal")
+ }
+ event := provider.Event{SessionID: s.ID, TurnID: turn.ID, Kind: "turn.completed", Payload: json.RawMessage(`{"usage":{"input_tokens":2,"cache_read_input_tokens":0,"cache_creation_input_tokens":0,"output_tokens":3}}`)}
+ raw, err = json.Marshal(event)
+ if err != nil {
+ return err
+ }
+ _, err = l.process.writer.Write(append(raw, '\n'))
+ return err
+}
+func (l *acceptanceLauncher) Respond(context.Context, provider.Session, provider.Answer) error {
+ return nil
+}
+func (l *acceptanceLauncher) Interrupt(context.Context, provider.Session) error {
+ return l.process.Contain(ctx)
+}
+func (l *acceptanceLauncher) Close(context.Context, provider.Session) error {
+ _ = l.process.Contain(ctx)
+ return <-l.capture.Done
+}
+
+type acceptanceProcess struct {
+ record containment.Record
+ stdout *io.PipeReader
+ writer *io.PipeWriter
+ once sync.Once
+}
+
+func (p *acceptanceProcess) ID() string { return p.record.ID }
+func (p *acceptanceProcess) Record() containment.Record { return p.record }
+func (p *acceptanceProcess) Stdin() io.WriteCloser { return acceptanceInput{} }
+func (p *acceptanceProcess) Stdout() io.ReadCloser { return p.stdout }
+func (p *acceptanceProcess) Stderr() io.ReadCloser { return io.NopCloser(bytes.NewReader(nil)) }
+func (p *acceptanceProcess) Wait(context.Context) (provider.Exit, error) { return provider.Exit{}, nil }
+func (p *acceptanceProcess) Contain(context.Context) error {
+ p.once.Do(func() { _ = p.writer.Close() })
+ return nil
+}
+
+type acceptanceInput struct{}
+
+func (acceptanceInput) Write(raw []byte) (int, error) { return len(raw), nil }
+func (acceptanceInput) Close() error { return nil }
diff --git a/internal/release/manifest.go b/internal/release/manifest.go
index f6a70448..c848cfc9 100644
--- a/internal/release/manifest.go
+++ b/internal/release/manifest.go
@@ -35,9 +35,10 @@ type PolicyCertificate struct {
}
type BinaryDigest struct {
- Name string `json:"name"`
- Version string `json:"version"`
- SHA256 string `json:"sha256"`
+ PolicySource string `json:"policy_source,omitempty"`
+ Name string `json:"name"`
+ Version string `json:"version"`
+ SHA256 string `json:"sha256"`
}
type Certification struct {
diff --git a/internal/release/manifest.json b/internal/release/manifest.json
index 7a144878..27983348 100644
--- a/internal/release/manifest.json
+++ b/internal/release/manifest.json
@@ -118,7 +118,8 @@
{
"name": "claude",
"version": "2.1.312",
- "sha256": "4f4178ce41d83e23341ebfbaecdbcf8ea6bf7baea0690025abe49eeec3a5d01d"
+ "sha256": "4f4178ce41d83e23341ebfbaecdbcf8ea6bf7baea0690025abe49eeec3a5d01d",
+ "policy_source": "/home/paulca/.local/share/equipo/try/bin/claude"
},
{
"name": "codex",
@@ -138,7 +139,8 @@
{
"name": "equipo-tool-proxy",
"version": "direct-v3",
- "sha256": "bd995d55020b5bea574b5f4a49eac167cce599958ac2c5645f98a9de9f8a7502"
+ "sha256": "bd995d55020b5bea574b5f4a49eac167cce599958ac2c5645f98a9de9f8a7502",
+ "policy_source": "/home/paulca/.local/share/equipo/try/bin/equipo-tool-proxy"
}
],
"direct_policies": [
diff --git a/internal/release/policy_relocation.go b/internal/release/policy_relocation.go
new file mode 100644
index 00000000..84c45f77
--- /dev/null
+++ b/internal/release/policy_relocation.go
@@ -0,0 +1,24 @@
+package release
+
+import "amadan.net/oficina/equipo/internal/runner/provider"
+
+// CertifiedPolicyHash returns the existing certificate identity for an exact
+// policy or a relocation of its pinned executables. PolicySource records where
+// the live gate mounted each binary; it never changes the installed mount.
+func (m Manifest) CertifiedPolicyHash(name, action, version string, p provider.Policy) (string, bool) {
+ sources := map[string]string{}
+ for _, binary := range m.Binaries {
+ if binary.PolicySource != "" {
+ sources["/opt/"+binary.Name] = binary.PolicySource
+ }
+ }
+ hash, err := p.HashAtBinarySources(nil)
+ if err != nil {
+ return "", false
+ }
+ if m.ActionCertified(name, action, version, hash) {
+ return hash, true
+ }
+ hash, err = p.HashAtBinarySources(sources)
+ return hash, err == nil && m.ActionCertified(name, action, version, hash)
+}
diff --git a/internal/runner/certified/discovery.go b/internal/runner/certified/discovery.go
new file mode 100644
index 00000000..65e180e6
--- /dev/null
+++ b/internal/runner/certified/discovery.go
@@ -0,0 +1,76 @@
+package certified
+
+import (
+ "context"
+ "crypto/sha256"
+ "encoding/hex"
+ "errors"
+ "slices"
+
+ "amadan.net/oficina/equipo/internal/release"
+ "amadan.net/oficina/equipo/internal/runner/provider"
+ runnersetup "amadan.net/oficina/equipo/internal/runner/setup"
+ "amadan.net/oficina/equipo/internal/runnerproto"
+)
+
+func ConnectionReport(ctx context.Context, b runnersetup.AccountBinding, m release.Manifest, installed bool, construct func(string) (provider.Launch, func() error, error), preflight func(provider.Launch) error) (runnerproto.ConnectionReport, error) {
+ homeHash := sha256.Sum256([]byte(b.ProviderHome))
+ report := runnerproto.ConnectionReport{AccountLabel: b.Label, LocalID: b.LocalID, Provider: b.Provider, Family: b.Family, Model: b.Model, Kind: b.Kind, ProviderVersion: b.ExpectedIdentity.ProviderVersion, LauncherVersion: m.LauncherVersion, BwrapVersion: m.BwrapVersion, PolicyVersion: m.PolicyVersion, ProviderVersionSource: "direct-cli", UnavailableReason: "capability_unverified", IsolationConfigHash: runnerproto.EventHash(b), Routing: runnerproto.ConnectionRouting{BindingID: b.ID, AccountID: b.AccountID, CredentialHomeHash: hex.EncodeToString(homeHash[:])}}
+ if !installed {
+ return report, nil
+ }
+ policies := slices.Clone(m.DirectPolicies)
+ // Prefer the coordinator certificate when the account supports it.
+ slices.SortStableFunc(policies, func(a, b release.PolicyCertificate) int {
+ if a.Action == b.Action {
+ return 0
+ }
+ if a.Action == "coordinate" {
+ return -1
+ }
+ if b.Action == "coordinate" {
+ return 1
+ }
+ return 0
+ })
+ seen := map[string]bool{}
+ for _, c := range policies {
+ if c.Provider != b.Provider || seen[c.Action] || !m.HasCertifiedAction(b.Provider, c.Action) {
+ continue
+ }
+ seen[c.Action] = true
+ if err := ctx.Err(); err != nil {
+ return report, err
+ }
+ launch, cleanup, err := construct(c.Action)
+ if err == nil {
+ report.IsolationConfigHash = launch.Policy.Hash
+ if hash, ok := m.CertifiedPolicyHash(b.Provider, c.Action, b.ExpectedIdentity.ProviderVersion, launch.Policy); ok {
+ err = preflight(launch)
+ if err == nil {
+ report.IsolationConfigHash = hash
+ report.Available = true
+ report.ReadIsolation = true
+ report.UnavailableReason = ""
+ report.Routing.ObservedAccountID = b.AccountID
+ report.Routing.AccountPinned = true
+ report.Routing.NoFailover = true
+ report.Routing.TimelineRecovery = true
+ report.Routing.ProcessOwnership = true
+ }
+ }
+ }
+ if cleanup != nil {
+ if e := cleanup(); e != nil {
+ return report, e
+ }
+ }
+ if errors.Is(err, provider.ErrAccountMaintenance) {
+ report.UnavailableReason = "account.sign_in_again"
+ }
+ if report.Available || err != nil {
+ return report, nil
+ }
+ }
+ return report, nil
+}
diff --git a/internal/runner/certified/discoverytest/budget_test.go b/internal/runner/certified/discoverytest/budget_test.go
new file mode 100644
index 00000000..a48aebed
--- /dev/null
+++ b/internal/runner/certified/discoverytest/budget_test.go
@@ -0,0 +1,9 @@
+package discoverytest
+
+import (
+ "amadan.net/rastrillo/rastrillo/budget"
+ "os"
+ "testing"
+)
+
+func TestMain(m *testing.M) { os.Exit(budget.Main(m)) }
diff --git a/internal/runner/certified/discoverytest/connection_available_test.go b/internal/runner/certified/discoverytest/connection_available_test.go
new file mode 100644
index 00000000..8826e859
--- /dev/null
+++ b/internal/runner/certified/discoverytest/connection_available_test.go
@@ -0,0 +1,212 @@
+package discoverytest
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "strings"
+ "testing"
+
+ "amadan.net/oficina/equipo/internal/equipo/team"
+ "amadan.net/oficina/equipo/internal/plan3test"
+ "amadan.net/oficina/equipo/internal/release"
+ "amadan.net/oficina/equipo/internal/runner/certified"
+ "amadan.net/oficina/equipo/internal/runner/provider"
+ "amadan.net/oficina/equipo/internal/runner/provider/claude"
+ runnersetup "amadan.net/oficina/equipo/internal/runner/setup"
+)
+
+type connectionFixture struct {
+ m release.Manifest
+ b runnersetup.AccountBinding
+ binary, source string
+ build func(string) (provider.Launch, func() error, error)
+ paths map[string]string
+}
+
+func availableFixture(t *testing.T) *connectionFixture {
+ t.Helper()
+ root := t.TempDir()
+ home, work, scratch := filepath.Join(root, "account"), filepath.Join(root, "work"), filepath.Join(root, "scratch")
+ for _, p := range []string{home, work, scratch} {
+ must(t, os.Mkdir(p, 0700))
+ }
+ id := provider.Identity{AccountID: "claude", HomeID: "fixture-home", ProviderVersion: claude.Version}
+ raw, _ := json.Marshal(id)
+ must(t, os.WriteFile(filepath.Join(home, provider.IdentityFile), raw, 0600))
+ must(t, os.WriteFile(filepath.Join(home, ".credentials.json"), []byte(`{"fixture":true}`), 0600))
+ f := &connectionFixture{m: release.BuildManifest(), b: runnersetup.AccountBinding{ID: "claude", LocalID: "claude", Provider: "claude", Family: "claude", Model: "fixture-model", AccountID: id.AccountID, ExpectedIdentity: id, ProviderHome: home, Kind: "subscription"}, paths: map[string]string{}}
+ f.m.DirectPolicies = nil
+ f.m.Certifications = nil
+ f.m.UncertifiedPolicies = nil
+ script := []byte("#!/bin/sh\nif [ \"$1\" = auth ]; then\n printf '%s\\n' '{\"account_id\":\"claude\",\"home_id\":\"fixture-home\",\"provider_version\":\"2.1.312\"}'\nelse\n cat >/dev/null\n printf '%s\\n' 'fixture coordinator reply'\nfi\n")
+ for i := range f.m.Binaries {
+ b := &f.m.Binaries[i]
+ path := filepath.Join(root, b.Name)
+ must(t, os.WriteFile(path, script, 0700))
+ b.SHA256 = team.ContentDigest(script)
+ b.PolicySource = ""
+ f.paths[b.Name] = path
+ if b.Name == "claude" {
+ f.source = path
+ b.PolicySource = path
+ }
+ }
+ f.binary = filepath.Join(root, "installed-claude")
+ must(t, os.WriteFile(f.binary, script, 0700))
+ selected := f.source
+ f.build = func(action string) (provider.Launch, func() error, error) {
+ lease, err := provider.OpenAccount(ctx, provider.Binding{ID: f.b.ID, Provider: f.b.Provider, AccountID: f.b.AccountID, Expected: f.b.ExpectedIdentity, Home: home, RuntimeRoot: filepath.Join(root, "homes")})
+ if err != nil {
+ return provider.Launch{}, nil, err
+ }
+ profile, err := provider.Profile(action)
+ if err != nil {
+ return provider.Launch{}, lease.Close, err
+ }
+ in, err := claude.PolicyInputs(lease.Binding(), provider.PolicyInputs{Action: action, Tools: profile.MCPTools(), Workspace: work, Scratch: scratch, RuntimeFiles: []provider.Mount{{Source: selected, Target: "/opt/claude", ReadOnly: true}, {Source: f.paths["equipo-tool-proxy"], Target: "/opt/equipo-tool-proxy", ReadOnly: true}}, EgressHosts: []string{"api.anthropic.com"}, LauncherVersion: f.m.LauncherVersion, BwrapVersion: f.m.BwrapVersion}, profile.Specialist, f.b.Model)
+ if err != nil {
+ return provider.Launch{}, lease.Close, err
+ }
+ policy, err := provider.BuildPolicy(lease.Binding(), in)
+ return provider.Launch{Workspace: work, Binding: lease.Binding(), Policy: policy, Selection: provider.Selection{ConnectionID: f.b.LocalID, Provider: f.b.Provider, Family: f.b.Family, Model: f.b.Model, AccountID: f.b.AccountID}}, lease.Close, err
+ }
+ for _, action := range []string{"implement", "review", "coordinate"} {
+ l, close, err := f.build(action)
+ must(t, err)
+ must(t, close())
+ f.m.DirectPolicies = append(f.m.DirectPolicies, release.PolicyCertificate{Provider: "claude", Action: action, ProviderVersion: claude.Version, LauncherVersion: f.m.LauncherVersion, BwrapVersion: f.m.BwrapVersion, PolicyHash: l.Policy.Hash, NoRefreshReason: "fixture"})
+ f.m.Certifications = append(f.m.Certifications, release.Certification{Provider: "claude", PolicyHash: l.Policy.Hash, SHA256: strings.Repeat("a", 64)})
+ }
+ selected = f.binary
+ f.paths["claude"] = f.binary
+ return f
+}
+func (f *connectionFixture) probe(l provider.Launch) error {
+ lease, err := l.Binding.AccountLease()
+ if err != nil {
+ return err
+ }
+ return lease.Preflight(ctx, func(context.Context, provider.Binding) (provider.Identity, error) {
+ raw, err := exec.CommandContext(ctx, f.binary, "auth").Output()
+ if err != nil {
+ return provider.Identity{}, err
+ }
+ var id provider.Identity
+ err = json.Unmarshal(raw, &id)
+ return id, err
+ })
+}
+func TestConnectionAvailableGuards(t *testing.T) {
+ for _, kind := range []string{"relocated", "coordinate-only", "review-only", "uncertified", "wrong-action", "other-account", "changed-binary", "uninstalled", "preflight", "maintenance", "cleanup"} {
+ t.Run(kind, func(t *testing.T) {
+ f := availableFixture(t)
+ installed := true
+ want := kind == "relocated" || kind == "coordinate-only" || kind == "review-only"
+ calls := 0
+ closed := 0
+ probe := func(l provider.Launch) error {
+ calls++
+ if kind == "preflight" {
+ return provider.ErrIdentity
+ }
+ if kind == "maintenance" {
+ return provider.ErrAccountMaintenance
+ }
+ return f.probe(l)
+ }
+ switch kind {
+ case "coordinate-only":
+ f.m.DirectPolicies = f.m.DirectPolicies[2:]
+ case "review-only":
+ f.m.DirectPolicies = f.m.DirectPolicies[1:2]
+ case "uncertified":
+ f.m.Certifications = nil
+ case "wrong-action":
+ for i := range f.m.DirectPolicies {
+ f.m.DirectPolicies[i].Action = "copy"
+ }
+ case "other-account":
+ f.b.ID = "other-binding"
+ case "changed-binary":
+ must(t, os.WriteFile(f.binary, []byte("#!/bin/sh\nexit 0\n"), 0700))
+ case "uninstalled":
+ installed = false
+ }
+ build := func(action string) (provider.Launch, func() error, error) {
+ l, close, e := f.build(action)
+ return l, func() error {
+ closed++
+ e := close()
+ if kind == "cleanup" {
+ return provider.ErrContainment
+ }
+ return e
+ }, e
+ }
+ report, err := certified.ConnectionReport(ctx, f.b, f.m, installed, build, probe)
+ if kind == "cleanup" {
+ if !errors.Is(err, provider.ErrContainment) {
+ t.Fatal("cleanup failure hidden", err)
+ }
+ return
+ }
+ must(t, err)
+ if report.Available != want || report.ReadIsolation != want || report.TrialReady {
+ t.Fatalf("availability: %+v", report)
+ }
+ if want && (calls != 1 || closed != 1 || report.Routing.ObservedAccountID != f.b.AccountID || report.UnavailableReason != "") {
+ t.Fatal("missing probe, cleanup or routing", report, calls, closed)
+ }
+ if !want && kind != "preflight" && kind != "maintenance" && calls != 0 {
+ t.Fatal("uncertified route probed")
+ }
+ if kind == "maintenance" && report.UnavailableReason != "account.sign_in_again" {
+ t.Fatal("maintenance reason lost")
+ }
+ if want {
+ action := "coordinate"
+ if kind == "review-only" {
+ action = "review"
+ }
+ if !f.m.ActionCertified("claude", action, claude.Version, report.IsolationConfigHash) {
+ t.Fatal("report lacks certified tuple")
+ }
+ }
+ })
+ }
+ f := availableFixture(t)
+ must(t, f.m.VerifyInstalled(f.paths))
+ for _, action := range []string{"implement", "review", "coordinate", "copy", "recommend"} {
+ l, close, err := f.build(action)
+ must(t, err)
+ _, ok := f.m.CertifiedPolicyHash("claude", action, claude.Version, l.Policy)
+ if ok != (action == "implement" || action == "review" || action == "coordinate") {
+ t.Fatal("action certification", action, ok)
+ }
+ must(t, close())
+ }
+}
+
+func TestConnectionAvailableCoordinatorFakeCLI(t *testing.T) {
+ cf := availableFixture(t)
+ cf.m.DirectPolicies = cf.m.DirectPolicies[2:]
+ report, err := certified.ConnectionReport(ctx, cf.b, cf.m, cf.m.VerifyInstalled(cf.paths) == nil, cf.build, cf.probe)
+ must(t, err)
+ if !report.Available {
+ t.Fatal("certified relocated coordinator unavailable")
+ }
+ plan3test.RunConnectionAvailableCoordinator(t, report, cf.m, cf.build, cf.binary)
+}
+
+var ctx = context.Background()
+
+func must(t *testing.T, err error) {
+ t.Helper()
+ if err != nil {
+ t.Fatal(err)
+ }
+}
diff --git a/internal/runner/provider/policy_relocation.go b/internal/runner/provider/policy_relocation.go
new file mode 100644
index 00000000..463a1c1d
--- /dev/null
+++ b/internal/runner/provider/policy_relocation.go
@@ -0,0 +1,43 @@
+package provider
+
+import "encoding/json"
+
+// HashAtBinarySources compares a policy at the binary locations used by its
+// certificate. Only read-only executable sources move; their digests, targets,
+// account identity and every other policy input remain bound. The concrete
+// manifest and launch attestation continue to use the installed paths.
+func (p Policy) HashAtBinarySources(sources map[string]string) (string, error) {
+ if digest(p.Manifest) != p.ManifestHash {
+ return "", ErrPolicy
+ }
+ var m effectiveManifest
+ if json.Unmarshal(p.Manifest, &m) != nil {
+ return "", ErrPolicy
+ }
+ m = policyTemplate(m)
+ _, hash, err := hashJSON(m)
+ if err != nil || hash != p.Hash {
+ return "", ErrPolicy
+ }
+ for target, source := range sources {
+ switch target {
+ case "/opt/claude", "/opt/codex", "/opt/codex-code-mode-host", "/opt/bwrap", "/opt/equipo-tool-proxy":
+ default:
+ return "", ErrPolicy
+ }
+ if !cleanPath(source) {
+ return "", ErrPolicy
+ }
+ for i := range m.Files {
+ if m.Files[i].Mount.Target != target {
+ continue
+ }
+ if !m.Files[i].Mount.ReadOnly {
+ return "", ErrPolicy
+ }
+ m.Files[i].Mount.Source = source
+ }
+ }
+ _, hash, err = hashJSON(m)
+ return hash, err
+}
diff --git a/internal/runner/provider/policy_relocation_test.go b/internal/runner/provider/policy_relocation_test.go
new file mode 100644
index 00000000..e2aa2eaf
--- /dev/null
+++ b/internal/runner/provider/policy_relocation_test.go
@@ -0,0 +1,75 @@
+package provider
+
+import (
+ "os"
+ "path/filepath"
+ "testing"
+)
+
+func TestPolicyBinaryRelocation(t *testing.T) {
+ b, in := policyFixture(t)
+ original := mustPolicy(t, b, in)
+ source := in.RuntimeFiles[0].Source
+ raw, err := os.ReadFile(source)
+ if err != nil {
+ t.Fatal(err)
+ }
+ moved := filepath.Join(t.TempDir(), "codex")
+ if err = os.WriteFile(moved, raw, 0700); err != nil {
+ t.Fatal(err)
+ }
+ in.RuntimeFiles[0].Source = moved
+ relocated := mustPolicy(t, b, in)
+ hash, err := relocated.HashAtBinarySources(map[string]string{"/opt/codex": source})
+ if err != nil || hash != original.Hash {
+ t.Fatalf("identical relocated binary lost certification: %s %v", hash, err)
+ }
+ if relocated.Hash == original.Hash || relocated.ManifestHash == original.ManifestHash {
+ t.Fatal("concrete source no longer bound")
+ }
+ for _, kind := range []string{"bytes", "target", "writable", "account", "settings", "denied", "manifest", "hash", "invalid-source"} {
+ t.Run(kind, func(t *testing.T) {
+ changed := in
+ changed.RuntimeFiles = append([]Mount(nil), in.RuntimeFiles...)
+ account := b
+ sources := map[string]string{"/opt/codex": source}
+ switch kind {
+ case "bytes":
+ if err := os.WriteFile(moved, []byte("changed binary"), 0700); err != nil {
+ t.Fatal(err)
+ }
+ defer os.WriteFile(moved, raw, 0700)
+ case "target":
+ changed.RuntimeFiles[0].Target = "/opt/other"
+ changed.Argv = []string{"/opt/other"}
+ case "writable":
+ changed.RuntimeFiles[0].ReadOnly = false
+ case "account":
+ account, _ = policyFixture(t)
+ case "settings":
+ changed.Settings = []byte(`{"sandbox":"workspace-write"}`)
+ case "denied":
+ changed.DeniedPaths = append(append([]string(nil), in.DeniedPaths...), "/private/extra")
+ case "invalid-source":
+ sources["/opt/codex"] = "relative"
+ }
+ p, e := BuildPolicy(account, changed)
+ if e != nil {
+ if kind != "writable" {
+ t.Fatal(e)
+ }
+ return
+ }
+ if kind == "manifest" {
+ p.Manifest = append(p.Manifest, ' ')
+ }
+ if kind == "hash" {
+ p.Hash = original.Hash
+ }
+ h, e := p.HashAtBinarySources(sources)
+ if e == nil && h == original.Hash {
+ t.Fatal("changed security input reused certificate")
+ }
+ })
+ }
+}
diff --git a/internal/runner/runtime_direct.go b/internal/runner/runtime_direct.go
index d57efaa1..c1f797f0 100644
--- a/internal/runner/runtime_direct.go
+++ b/internal/runner/runtime_direct.go
@@ -2,8 +2,6 @@ package runner
import (
"context"
- "crypto/sha256"
- "encoding/hex"
"errors"
"os"
@@ -70,7 +68,8 @@ func (r *Runtime) directLaunch(ctx context.Context, c RunClaim, ws workspace.Wor
if err != nil {
return l, cleanup, err
}
- if r.verifyRelease() != nil || c.Assignment.Selection.Isolation.Status != "confined" || !release.BuildManifest().ActionCertified(l.Selection.Provider, action, l.Binding.Expected.ProviderVersion, l.Policy.Hash) {
+ _, policyCertified := release.BuildManifest().CertifiedPolicyHash(l.Selection.Provider, action, l.Binding.Expected.ProviderVersion, l.Policy)
+ if r.verifyRelease() != nil || c.Assignment.Selection.Isolation.Status != "confined" || !policyCertified {
return l, cleanup, provider.ErrPolicy
}
l.AttemptKey = attemptKey(c.Scope, c.Handle) + "/model"
@@ -107,7 +106,8 @@ func (r *Runtime) coordinatorLaunch(ctx context.Context, c runnerproto.Coordinat
return l, cleanup, nil
}
func releaseCertifiedCoordinator(l provider.Launch) bool {
- return release.BuildManifest().ActionCertified(l.Selection.Provider, "coordinate", l.Binding.Expected.ProviderVersion, l.Policy.Hash)
+ _, ok := release.BuildManifest().CertifiedPolicyHash(l.Selection.Provider, "coordinate", l.Binding.Expected.ProviderVersion, l.Policy)
+ return ok
}
func (r *Runtime) discoverNamespaces(ctx context.Context) ([]runnerproto.ConnectionReport, error) {
@@ -116,49 +116,35 @@ func (r *Runtime) discoverNamespaces(ctx context.Context) ([]runnerproto.Connect
return nil, err
}
reports := make([]runnerproto.ConnectionReport, 0, len(bs))
+ manifest := release.BuildManifest()
+ installed := r.verifyRelease() == nil
for _, b := range bs {
- hash := sha256.Sum256([]byte(b.ProviderHome))
- report := runnerproto.ConnectionReport{AccountLabel: b.Label, LocalID: b.LocalID, Provider: b.Provider, Family: b.Family, Model: b.Model, Kind: b.Kind, ProviderVersion: b.ExpectedIdentity.ProviderVersion, LauncherVersion: directLauncherVersion(), BwrapVersion: "0.11.0", PolicyVersion: provider.PolicyVersion, ProviderVersionSource: "direct-cli", UnavailableReason: "capability_unverified", IsolationConfigHash: runnerproto.EventHash(b), Routing: runnerproto.ConnectionRouting{BindingID: b.ID, AccountID: b.AccountID, CredentialHomeHash: hex.EncodeToString(hash[:])}}
- work, err := os.MkdirTemp(r.cfg.WorkspaceRoot, "preflight-")
- if err != nil {
- return nil, err
- }
- l, cleanup, err := r.constructDirect(ctx, provider.Selection{ConnectionID: b.LocalID, Provider: b.Provider, Family: b.Family, Model: b.Model, AccountID: b.AccountID}, work, "implement")
- if err == nil {
- report.IsolationConfigHash = l.Policy.Hash
- // Certification is a release gate. Do not advertise an uncertified route.
- if r.verifyRelease() == nil && release.BuildManifest().ActionCertified(b.Provider, "implement", b.ExpectedIdentity.ProviderVersion, l.Policy.Hash) {
- lease, leaseErr := l.Binding.AccountLease()
- err = leaseErr
- if err == nil {
- var fingerprint string
- fingerprint, err = lease.PreflightFingerprint(ctx)
- if err == nil {
- err = r.cachedPreflight(ctx, b.ID, runnerproto.EventHash([]string{fingerprint, l.Policy.Hash}), func() error { _, e := r.launchers[b.Provider].Preflight(ctx, l.Binding, l.Policy); return e })
- }
- }
- if err == nil {
- report.Available = true
- report.ReadIsolation = true
- report.UnavailableReason = ""
- report.Routing.ObservedAccountID = b.AccountID
- report.Routing.AccountPinned = true
- report.Routing.NoFailover = true
- report.Routing.TimelineRecovery = true
- report.Routing.ProcessOwnership = true
+ report, err := certified.ConnectionReport(ctx, b, manifest, installed, func(action string) (provider.Launch, func() error, error) {
+ work, err := os.MkdirTemp(r.cfg.WorkspaceRoot, "preflight-")
+ if err != nil {
+ return provider.Launch{}, nil, err
+ }
+ l, cleanup, err := r.constructDirect(ctx, provider.Selection{ConnectionID: b.LocalID, Provider: b.Provider, Family: b.Family, Model: b.Model, AccountID: b.AccountID}, work, action)
+ return l, func() error {
+ var e error
+ if cleanup != nil {
+ e = cleanup()
}
+ return errors.Join(e, os.RemoveAll(work))
+ }, err
+ }, func(l provider.Launch) error {
+ lease, err := l.Binding.AccountLease()
+ if err != nil {
+ return err
}
- }
- if errors.Is(err, provider.ErrAccountMaintenance) {
- report.UnavailableReason = "account.sign_in_again"
- }
- if cleanup != nil {
- if e := cleanup(); e != nil {
- return nil, e
+ fingerprint, err := lease.PreflightFingerprint(ctx)
+ if err != nil {
+ return err
}
- }
- if e := os.RemoveAll(work); e != nil {
- return nil, e
+ return r.cachedPreflight(ctx, b.ID, runnerproto.EventHash([]string{fingerprint, l.Policy.Hash}), func() error { _, e := r.launchers[b.Provider].Preflight(ctx, l.Binding, l.Policy); return e })
+ })
+ if err != nil {
+ return nil, err
}
if err = r.journal.prunePreflights(ctx, r.namespaces.Forget); err != nil {
return nil, err
diff --git a/scripts/runner-reference-allowlist.json b/scripts/runner-reference-allowlist.json
index dd081abe..56363b33 100644
--- a/scripts/runner-reference-allowlist.json
+++ b/scripts/runner-reference-allowlist.json
@@ -9770,5 +9770,124 @@
"match": "equipo-runner",
"count": 2,
"reason": "Byte-identical hashed live-gate evidence; records provider observations and isolation restrictions, not an execution dependency."
+ },
+ {
+ "path": "docs/superpowers/plans/CODEX-BRIEF-connection-available.md",
+ "line_sha256": "09bb421a58d2e054f0fc7f8c37e3bc28e5a5b46cf27ab14273dd99c3790ba491",
+ "match": "equipo-runner",
+ "count": 1,
+ "reason": "Controller instructions identify the direct runner service, deployed paths and unavailable report; no legacy execution is enabled."
+ },
+ {
+ "path": "docs/superpowers/plans/CODEX-BRIEF-connection-available.md",
+ "line_sha256": "e94ccecf6cd13e5a83ec3c1ac53f0358f15ce0bb2fc1d3e8330377d80c601eca",
+ "match": "equipo-runner",
+ "count": 1,
+ "reason": "Controller instructions identify the direct runner service, deployed paths and unavailable report; no legacy execution is enabled."
+ },
+ {
+ "path": "docs/superpowers/plans/CODEX-BRIEF-connection-available.md",
+ "line_sha256": "802ddc6d6b3b08b82edeb0ac8b23437f7c3fe9e580443c47ab149f6b71878d37",
+ "match": "equipo-runner",
+ "count": 1,
+ "reason": "Controller instructions identify the direct runner service, deployed paths and unavailable report; no legacy execution is enabled."
+ },
+ {
+ "path": "docs/superpowers/plans/CODEX-BRIEF-connection-available.md",
+ "line_sha256": "b1ae8de8514d741b1b861be620e98e34a022a13e516b5879aecf6ff320a7e60b",
+ "match": "Trial",
+ "count": 1,
+ "reason": "Controller instructions identify the direct runner service, deployed paths and unavailable report; no legacy execution is enabled."
+ },
+ {
+ "path": "docs/superpowers/plans/CODEX-BRIEF-connection-available.md",
+ "line_sha256": "4dc1c12d570a8056414375f4abf64fababf8e86f99a92f4e0f6a10bf2d4ac64f",
+ "match": "equipo-runner",
+ "count": 1,
+ "reason": "Controller instructions identify the direct runner service, deployed paths and unavailable report; no legacy execution is enabled."
+ },
+ {
+ "path": "docs/superpowers/plans/CONTROLLER-REPORT-connection-available.md",
+ "line_sha256": "e489fd779d0186a8683e1f6a7abc78efdca7c7df10c02df8d55851dfdac93810",
+ "match": "trial",
+ "count": 1,
+ "reason": "Controller handoff records direct runner diagnosis, verification and versioned operator deployment commands; no legacy execution is enabled."
+ },
+ {
+ "path": "docs/superpowers/plans/CONTROLLER-REPORT-connection-available.md",
+ "line_sha256": "59a16140ce07e3d77bb7cfcf2b1323894987e6523862e968cff64a5f4fdc147b",
+ "match": "equipo-runner",
+ "count": 1,
+ "reason": "Controller handoff records direct runner diagnosis, verification and versioned operator deployment commands; no legacy execution is enabled."
+ },
+ {
+ "path": "docs/superpowers/plans/CONTROLLER-REPORT-connection-available.md",
+ "line_sha256": "896e1d7dd7a7c695c04e98aaf1546ce78ab36ad2006eef452fece7591a449bd9",
+ "match": "equipo-runner",
+ "count": 1,
+ "reason": "Controller handoff records direct runner diagnosis, verification and versioned operator deployment commands; no legacy execution is enabled."
+ },
+ {
+ "path": "docs/superpowers/plans/CONTROLLER-REPORT-connection-available.md",
+ "line_sha256": "e71cea44e3bbd467c33e36a5d05bffa8dd0b6042fe2dee9ed93ef8257e1fa69e",
+ "match": "equipo-runner",
+ "count": 1,
+ "reason": "Controller handoff records direct runner diagnosis, verification and versioned operator deployment commands; no legacy execution is enabled."
+ },
+ {
+ "path": "docs/superpowers/plans/CONTROLLER-REPORT-connection-available.md",
+ "line_sha256": "ca07555883b394232e5dff77b563f0246865e732ab0ecd73f49f50dbaa933477",
+ "match": "equipo-runner",
+ "count": 1,
+ "reason": "Controller handoff records direct runner diagnosis, verification and versioned operator deployment commands; no legacy execution is enabled."
+ },
+ {
+ "path": "docs/superpowers/plans/CONTROLLER-REPORT-connection-available.md",
+ "line_sha256": "c9480ae08b108a9f559701a45f74f71f54ed95e03321b2c3f8ccf327836d56e9",
+ "match": "equipo-runner",
+ "count": 1,
+ "reason": "Controller handoff records direct runner diagnosis, verification and versioned operator deployment commands; no legacy execution is enabled."
+ },
+ {
+ "path": "docs/superpowers/plans/CONTROLLER-REPORT-connection-available.md",
+ "line_sha256": "1cc09e1cff7b0acf6e2db4db56d0dfdae560ba4d40c2d8d464a0c577599fda89",
+ "match": "equipo-runner",
+ "count": 1,
+ "reason": "Controller handoff records direct runner diagnosis, verification and versioned operator deployment commands; no legacy execution is enabled."
+ },
+ {
+ "path": "docs/superpowers/plans/CONTROLLER-REPORT-connection-available.md",
+ "line_sha256": "c56229b48dbac0cc6caf88c6c596ad5c60faa9f73bf2f4bb042e586f9b219441",
+ "match": "equipo-runner",
+ "count": 1,
+ "reason": "Controller handoff records direct runner diagnosis, verification and versioned operator deployment commands; no legacy execution is enabled."
+ },
+ {
+ "path": "docs/superpowers/plans/CONTROLLER-REPORT-connection-available.md",
+ "line_sha256": "c2e589e173b5dddfdd4d669705d1dfa58a0b05400a13816dd86b83bd73a65d03",
+ "match": "equipo-runner",
+ "count": 1,
+ "reason": "Controller handoff records direct runner diagnosis, verification and versioned operator deployment commands; no legacy execution is enabled."
+ },
+ {
+ "path": "docs/superpowers/plans/CONTROLLER-REPORT-connection-available.md",
+ "line_sha256": "10275c442396a159f3e3799ff276418ed773c9c5775d15d05c351c659c167e32",
+ "match": "equipo-runner",
+ "count": 1,
+ "reason": "Controller handoff records direct runner diagnosis, verification and versioned operator deployment commands; no legacy execution is enabled."
+ },
+ {
+ "path": "docs/superpowers/plans/CONTROLLER-REPORT-connection-available.md",
+ "line_sha256": "1e81d72f86aed89a783a179a412a1756dc80dfd451e1488ba59c70f570b19ae7",
+ "match": "equipo-runner",
+ "count": 1,
+ "reason": "Controller handoff records direct runner diagnosis, verification and versioned operator deployment commands; no legacy execution is enabled."
+ },
+ {
+ "path": "internal/runner/certified/discoverytest/connection_available_test.go",
+ "line_sha256": "60cebc2920163c76d404af4595adc0494a6516e6c783b347b73df4e38ee52532",
+ "match": "Trial",
+ "count": 1,
+ "reason": "Discovery regression requires the obsolete trial flag to remain false for certified direct connections."
}
]