oficina / equipo Public

Test live coordinator dispatch and add optimistic chat sends

Exercise the instance and runner with the pinned Claude launcher. Reject
unavailable coordinator bindings and reconcile pending chat messages.
Co-Authored-By: Astra <noreply@openai.com>
claude b59f1418a399454dccbf2c40e4065653ec13f638 parent 116010f
32 files changed, +2,409 −13
  • Makefile +4 −0
  • docs/superpowers/plans/CONTROLLER-REPORT-e2e-coordinator.md +163 −0
  • docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md +4 −0
  • internal/chatsend/requests.go +23 −0
  • internal/chatsend/requests_test.go +43 −0
  • internal/coordinatorcontract/fixtures.go +34 −0
  • internal/coordinatorcontract/testdata/claim.json +209 −0
  • internal/coordinatorcontract/testdata/delivery.json +253 −0
  • internal/coordinatorcontract/testdata/heartbeat.json +48 −0
  • internal/coordinatorcontract/testdata/poll.json +24 −0
  • internal/coordinatorcontract/testdata/reply.json +240 −0
  • internal/e2elivetest/e2e_live_certificate_test.go +72 −0
  • internal/e2elivetest/e2e_live_helpers_test.go +119 −0
  • internal/e2elivetest/e2e_live_record_test.go +123 −0
  • internal/e2elivetest/e2e_live_test.go +195 −0
  • internal/e2elivetest/http_helpers_test.go +231 −0
  • internal/equipo/conversation/coordinator_application.go +6 −0
  • internal/equipo/conversation/settings.go +15 −2
  • internal/equipo/conversation/views.go +7 −1
  • internal/equipo/copy.go +10 −4
  • internal/equipo/static/chat-send.js +95 −0
  • internal/equipo/static/equipo.css +2 −0
  • internal/equipo/templates/chrome.html +1 −1
  • internal/equipo/templates/conversation_card.html +3 −2
  • internal/equipo/templates/coordinator.html +2 −2
  • internal/equipo/templates/settings.html +1 −1
  • internal/equipotest/optimistic_browser_test.go +83 −0
  • internal/plan3test/coordinator_claim_gap_test.go +22 −0
  • internal/runner/containment/linux_test.go +3 −0
  • internal/runner/transporttest/coordinator_contract_test.go +124 −0
  • internal/runnerproto/coordinator_contract_test.go +124 −0
  • scripts/runner-reference-allowlist.json +126 −0
diff --git a/Makefile b/Makefile
index 27d79751..43625127 100644
--- a/Makefile
+++ b/Makefile
@@ -182,3 +182,7 @@ release-runner: copy-release-check direct-release-check
cp packaging/install/install-v1.sh $(RUNNER_RELEASE_DIR)/install-v1.sh
python3 scripts/runner-install-manifest.py $(RUNNER_RELEASE_DIR) "$$(git rev-parse --short HEAD)"
@git rev-parse HEAD > $(RUNNER_RELEASE_DIR)/COMMIT
+
+.PHONY: e2e-live
+e2e-live:
+ EQUIPO_E2E_LIVE=1 go test -tags e2elive ./internal/e2elivetest -run '^TestCoordinatorE2ELive$$' -count=1 -timeout=10m -v
diff --git a/docs/superpowers/plans/CONTROLLER-REPORT-e2e-coordinator.md b/docs/superpowers/plans/CONTROLLER-REPORT-e2e-coordinator.md
new file mode 100644
index 00000000..903b46bc
--- /dev/null
+++ b/docs/superpowers/plans/CONTROLLER-REPORT-e2e-coordinator.md
@@ -0,0 +1,163 @@
+# Coordinator end-to-end report
+
+Branch: `e2e-coordinator`, based on `0fa1a48`. No production writes, service
+changes, push or deployment. New interface strings are individually marked
+`// COPY REVIEW PENDING`; no copy-review server was started.
+
+## Diagnosis
+
+There is an HTTP bridge. The service calls task poll, then coordinator poll;
+task poll can hold the loop for 25 seconds. The coordinator endpoints are
+`POST /api/runner/v2/coordinator/{poll,claim,renew,tool,event,containment}`.
+Heartbeat is `POST /api/runner/v2/heartbeat`. Coordinator requests carry
+version 2 and capability `coordinator.v1`. The instance returns a fenced claim
+with the selected account, context, admission ticket and deadlines. The runner
+launches the provider, posts structured tool results and delivery events, then
+reports containment.
+
+Read-only evidence came from `carlos db query --app equipo --account oficina`.
+The replica had advanced beyond the brief's four queued rows:
+
+| Snapshot, UTC on 2026-11-06 | Evidence |
+| --- | --- |
+| 14:33:55, transaction 6000 | Binding generation 2 selects `claude-b`. Binding and runner both belong to `paul@tito.io`. Member is active at revision 1; binding member revision is 1. Connection and binding connection revisions are both 4. Neither connection nor runner is revoked. |
+| 14:34:25, transaction 6004 | Generation 1 turns are superseded. The first generation 2 turn is `waiting_connection`; later turns remain queued. Every job ID is zero and every claim is empty. This proves coordinator polling reaches the instance. |
+| 14:37:25, transaction 6025 | `claude-a` is available and confined, account `paul@tito.io`, policy `3ba26b99cbfb29041600d32d0eb4c2fa53174ff8bb8d79ad4d65180c654b53cf`. `claude-b` is unavailable and unconfined, account `paul@keymail.dev`, policy `8d121c4a565bf378c0eedaa256072a9f9e674c82b0506c5c8a88649f6cca9475`. Its report says `capability_unverified`. |
+| 14:53:48, transaction 6139 | `SELECT person,revision,limits FROM coordinator_limits` returns no rows. |
+| 14:54:58, transaction 6147 | `SELECT team_id,revision,config FROM budget_records` returns no rows. |
+| 15:17:38, transaction 6306 | Final recheck still selects unavailable `claude-b`; team-budget and coordinator-limit row counts are both zero. |
+
+The current binding cannot be claimed because its selected account is not
+certified. Switching to `claude-a` alone is insufficient: the team and personal
+coordinator budgets are both unset. Budget admission must continue to deny that
+state. The provider account's email is distinct from the authenticated runner's
+person; server ownership checks use the latter. No account substitution is
+appropriate without the person's choice.
+
+The instance also requires current roster and connection revisions, a fresh
+heartbeat, pinned identity and routing, a verified isolation tuple, a current
+binding generation, no earlier blocked turn or uncontained attempt, no task
+holding the account, and budget capacity. Claim repeats authority checks inside
+the write transaction. The production launcher separately verifies executable
+digests and the exact coordinator policy. None of these checks was removed.
+
+## Changes
+
+- Binding changes now verify selection eligibility inside the transaction before
+ cancelling or superseding existing work. An unavailable choice leaves the old
+ binding and generation intact. Settings disable unavailable choices.
+- Blocked conversation cards link to coordinator settings. Missing coordinator
+ limits link the owner to team limits, which must be set first.
+- Chat appends a pending bubble synchronously on submit, waits 500 ms before
+ showing Sending, and keeps Retry on failure. Retries reuse the original
+ idempotency key. Server HTML echoes only the viewing person's send keys;
+ reconciliation handles live feed replacement and identical message bodies.
+ Native form submission still works without JavaScript. Vendored scripts are
+ unchanged.
+- `make e2e-live` builds the actual instance and runner binaries, uses loopback
+ HTTP and a new database, signs in through the real email flow, and enrols a
+ scratch runner using the existing test-side approval helper. No test endpoint
+ or authentication bypass was added to either production binary.
+- The harness selects only dedicated `claude-a`, `paul@tito.io`, Claude 2.1.312.
+ It verifies installed binaries against the release manifest. Scratch paths
+ require an exact harness-only policy certificate; a Go build overlay embeds
+ it only in scratch binaries. The checked-in manifest and evidence are intact.
+- The final harness starts with both budgets absent, proves `budget_needed`,
+ then uses the owner team-budget and coordinator-limit forms to authorize six
+ calls. It sends two small messages through `/conversation`, waits for delivered
+ turns and checks the rendered reply and project-setup card. The unconfigured
+ repository is advertised with an empty fixture credential; no forge access
+ occurs. Each failure names its stage.
+- Five recorded request/response fixtures cover heartbeat, coordinator poll,
+ claim, post_message reply and delivery. Both the instance handler and runner
+ transport tests consume them. Recording excludes all headers and enrollment
+ traffic; the provider email, admission identifier and credential-home hash
+ are replaced with fixed fixture values.
+
+The harness reads installed tool paths and the dedicated account binding from
+`~/.local/share/equipo-runner/service.env`; `EQUIPO_E2E_ENV` can name another
+configuration. It copies only the selected binding metadata into scratch, not
+credentials. The existing dedicated home is leased through the production
+account lock. All test processes and scratch files are removed after each run.
+
+## Verification
+
+Initial failing tests and observed failures:
+
+- `CGO_ENABLED=0 go test ./internal/chatsend -count=1`
+- `EQUIPO_BROWSER_NO_JS=1 CGO_ENABLED=0 go test -tags browser ./internal/equipotest -run '^TestChatBrowser$' -count=1`
+- `CGO_ENABLED=0 go test ./internal/plan3test -run '^TestCoordinatorRejectsUnavailableBinding$' -count=1`:
+ failed because an unavailable binding was accepted with no error. Passed after
+ transactional selection validation; the original binding remains intact.
+- `CGO_ENABLED=0 go test -tags browser ./internal/equipotest -run '^TestOptimisticChat$' -count=1`:
+ failed because there was no pending bubble before the POST completed.
+- Renaming the wire `turn_id` field to `turn_key` made both recorded-contract
+ tests fail. Restored it.
+- Removing the coordinator capability check made the instance contract test
+ fail. Restored it.
+- Changing the Sending timer from 500 ms to zero made the strengthened browser
+ test fail at its 250 ms assertion. Restored it. The first timing assertion was
+ too weak; it was strengthened after a mutation unexpectedly passed.
+- Replacing the server send key with a wrong key made reconciliation fail.
+ Restored it.
+- Removing viewer scoping made `TestRequestsStayWithViewer` expose the other
+ person's key and fail. Restored it; a database lookup error also fails closed.
+- Replacing the feed with a response captured before the POST made the browser
+ test lose the confirmed message. It now retains the last 50 confirmed sends
+ across stale live responses and passes.
+
+Passing targeted commands:
+
+- `CGO_ENABLED=0 go test ./internal/plan3test -run '^TestCoordinator' -count=1`
+- `CGO_ENABLED=0 go test ./internal/runner/transporttest ./internal/runnerproto -run '^TestCoordinatorRecorded' -count=1`
+- `CGO_ENABLED=0 go test -tags browser ./internal/equipotest -run '^(TestOptimisticChat|TestChatBrowser)$' -count=1`
+
+The browser tests cover Enter, Shift+Enter, immediate display, delayed Sending,
+network failure, retry, a response lost after the write commits, identical text
+sent twice, live feed replacement, escaping, focus and scrolling.
+
+The final `make e2e-live` passed twice consecutively in **115.35 s and 115.18 s**.
+Both runs started without budgets, recovered through the owner forms, and
+checked the coordinator message element and the proposal's setup form in the
+rendered feed. Earlier runs caught scratch setup errors: missing budgets, an
+uncertified scratch policy and an unadvertised repository. The final HTML checks
+also prevent the person's own prompt from satisfying a reply assertion.
+
+Across eleven invocations, two failed before model dispatch, one dispatched one
+turn, and eight dispatched two each: **17 admitted coordinator turns**, below
+the authorized total of 30. Each run admitted at most two, below its six-call
+cap. No live model use occurred outside the harness.
+
+CI: the first full `make -k ci` found the brief's missing reference allowance,
+a numeric HTTP status in a contract test, and the three missing pending-copy
+inventory entries. It also hit `TestNamespaceStartingThreadExit`: `unix.Poll`
+returned `EINTR`, which the test mistook for process exit. The test helper now
+retries interrupted polling without accepting a dead process. Production
+containment code is unchanged. Build, vet, vulnerability scanning, secret
+scanning, size budgets, adapter tests, migration checks and performance passed.
+Timing notices under concurrent load included runner 358.194 s (330 s budget),
+provider 22.522 s (15 s), Claude adapter 49.642 s (45 s) and Codex adapter 41.092 s
+(35 s). No budget was raised.
+
+The one full rerun of `make -k ci` exited **0**: 36 tested packages, none failed;
+all remaining gates passed. It still reported timing overruns for runner
+355.421 s, provider 21.600 s, Claude adapter 47.512 s and Codex adapter 39.940 s.
+These are warnings locally and failures when CI enforces timing budgets. The
+controller should retain this timing caveat when assessing the branch; this
+session did not relax those limits or claim a hosted-CI pass.
+
+The post-commit secret scan identified four high-entropy fixture identifiers.
+They were replaced with fixed values, the shared contract tests were rerun,
+and the unpushed commit was amended. The final browser checks passed, including the stale-feed race and scriptless
+submission. Scratch instances, runners and browsers stopped through test
+cleanup. Task logs were removed after recording these results. The production
+service remained running; no merge, push or deployment was performed.
+
+## Controller action
+
+After reviewing and releasing this commit, Paul must explicitly choose
+`claude-a`, set the team budget in `/settings#budgets`, then set coordinator
+limits in `/settings/coordinator`. Choose real operating limits, not the
+harness's test values. Existing queued messages can then resume through normal
+polling. This session did not change those production settings or Paul's
+conversation. Copy approval remains a release step for the three marked strings.
diff --git a/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md b/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md
index 8a5abb7c..4918f50b 100644
--- a/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md
+++ b/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md
@@ -5192,6 +5192,10 @@ records remain unchanged.
+| `conversation.sending` | Sending | Optimistic conversation send state | COPY REVIEW REQUIRED |
+| `conversation.retry` | Retry | Failed optimistic conversation send | COPY REVIEW REQUIRED |
+| `coordinator.connection_unavailable` | Unavailable | Coordinator connection choices | COPY REVIEW REQUIRED |
+
## Task 21
Status: DONE_WITH_CONCERNS. Offline 3b acceptance, the complete person API contract
diff --git a/internal/chatsend/requests.go b/internal/chatsend/requests.go
new file mode 100644
index 00000000..2f77f345
--- /dev/null
+++ b/internal/chatsend/requests.go
@@ -0,0 +1,23 @@
+// Package sends resolves a viewer's idempotent sends for optimistic chat.
+package sends
+
+import "gorm.io/gorm"
+
+func Requests[T any](tx *gorm.DB, person string, messages []T, id func(T) string) (map[string]string, error) {
+ ids := make([]string, 0, len(messages))
+ for _, m := range messages {
+ ids = append(ids, id(m))
+ }
+ out := map[string]string{}
+ if len(ids) == 0 {
+ return out, nil
+ }
+ var rows []struct{ ID, RequestID string }
+ if err := tx.Table("conversation_requests").Select("json_extract(result,'$.ID') AS id,request_id").Where("principal=? AND operation='send' AND json_extract(result,'$.ID') IN ?", person, ids).Find(&rows).Error; err != nil {
+ return nil, err
+ }
+ for _, r := range rows {
+ out[r.ID] = r.RequestID
+ }
+ return out, nil
+}
diff --git a/internal/chatsend/requests_test.go b/internal/chatsend/requests_test.go
new file mode 100644
index 00000000..89d8f271
--- /dev/null
+++ b/internal/chatsend/requests_test.go
@@ -0,0 +1,43 @@
+package sends
+
+import (
+ "io"
+ "log/slog"
+ "os"
+ "path/filepath"
+ "testing"
+
+ "amadan.net/rastrillo/rastrillo/budget"
+ "amadan.net/rastrillo/rastrillo/db"
+)
+
+func TestMain(m *testing.M) { os.Exit(budget.Main(m)) }
+func TestRequestsStayWithViewer(t *testing.T) {
+ d, err := db.Open(filepath.Join(t.TempDir(), "requests.db"), slog.New(slog.NewTextHandler(io.Discard, nil)))
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer d.Close()
+ for _, q := range []string{
+ `CREATE TABLE conversation_requests(principal text,operation text,request_id text,result text)`,
+ `INSERT INTO conversation_requests VALUES('alice','send','alice-request','{"ID":"alice-message"}'),('bob','send','bob-request','{"ID":"bob-message"}')`,
+ } {
+ if _, err := d.Writer().Exec(q); err != nil {
+ t.Fatal(err)
+ }
+ }
+ ids := []string{"alice-message", "bob-message"}
+ result, err := Requests(d.G, "alice", ids, func(id string) string { return id })
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(result) != 1 || result["alice-message"] != "alice-request" {
+ t.Fatalf("another viewer's request exposed: %v", result)
+ }
+ if err = d.Close(); err != nil {
+ t.Fatal(err)
+ }
+ if _, err = Requests(d.G, "alice", ids, func(id string) string { return id }); err == nil {
+ t.Fatal("lookup failure became an empty success")
+ }
+}
diff --git a/internal/coordinatorcontract/fixtures.go b/internal/coordinatorcontract/fixtures.go
new file mode 100644
index 00000000..7aab3a98
--- /dev/null
+++ b/internal/coordinatorcontract/fixtures.go
@@ -0,0 +1,34 @@
+// Package coordinatorcontract shares recorded, credential-free wire exchanges
+// between the instance handler and runner transport tests.
+package coordinatorcontract
+
+import (
+ "embed"
+ "encoding/json"
+)
+
+//go:embed testdata/*.json
+var files embed.FS
+
+type Packet struct {
+ Path string `json:"path"`
+ Request json.RawMessage `json:"request"`
+ Response json.RawMessage `json:"response"`
+}
+
+func Load(name string) (Packet, error) {
+ var p Packet
+ raw, err := files.ReadFile("testdata/" + name + ".json")
+ if err == nil {
+ err = json.Unmarshal(raw, &p)
+ }
+ return p, err
+}
+func Canonical(raw []byte) string {
+ var v any
+ if json.Unmarshal(raw, &v) != nil {
+ return "invalid JSON"
+ }
+ out, _ := json.Marshal(v)
+ return string(out)
+}
diff --git a/internal/coordinatorcontract/testdata/claim.json b/internal/coordinatorcontract/testdata/claim.json
new file mode 100644
index 00000000..0a289986
--- /dev/null
+++ b/internal/coordinatorcontract/testdata/claim.json
@@ -0,0 +1,209 @@
+{
+ "path": "/api/runner/v2/coordinator/claim",
+ "request": {
+ "capabilities": [
+ "coordinator.v1"
+ ],
+ "revision": 1,
+ "turn_id": "fixture-admission-key",
+ "version": 2
+ },
+ "response": {
+ "result": {
+ "admission": {
+ "dispatch": {
+ "action": 1,
+ "hash": "de251da296706d0ba43bf6197ca86e669c8b91525ee14f17f7dd9fe55726b726",
+ "key": "fixture-admission-key",
+ "operation": "provider.call",
+ "payload": "eyJCaW5kaW5nSUQiOiJBWlpXSVFVN0JDRDM0N1ZGMkZRVFNLNjdPWiIsIkNvbnRleHRIYXNoIjoiMDFmOGJhNGVmMDM4ODhlNTI5MDU3MGJiOGUyYWVjZmJmMmZlM2VkYTUzZWI5MDkyNzEyNzVlNDllYWU4OThjYyIsIkdlbmVyYXRpb24iOjEsIk1lc3NhZ2VJRCI6IkxEQ0tFV1NCTDZPUUVKSkJRVk1LT1I0WUtTIiwiVHVybklEIjoiVk9RUUFETVBRUERNUFJTSUE0U1VRSUUzUUkifQ=="
+ },
+ "expires_at": "2026-11-06T14:47:57.625208278Z",
+ "handle": {
+ "attempt": 1,
+ "fence": 1,
+ "revision": 2,
+ "runner": "PH7VDUINM6WWERJKF5TFXMH527"
+ },
+ "incarnation": 2,
+ "scope": {
+ "account": "HSCPNNCT5L2STZQFKTQISL7L6M",
+ "job": 1
+ }
+ },
+ "attempt_deadline": "2026-11-06T15:07:52.620394945Z",
+ "binding": {
+ "connection_id": "F5NZDYKGJFVKXU7BT46NYHPUFU",
+ "generation": 1,
+ "id": "AZZWIQU7BCD347VF2FQTSK67OZ",
+ "person": "owner@example.test",
+ "revision": 1,
+ "runner_id": "PH7VDUINM6WWERJKF5TFXMH527"
+ },
+ "brief": {
+ "artifact_hashes": null,
+ "attempt_deadline": "2026-11-06T15:07:52.620394945Z",
+ "budget_revision": 0,
+ "check_definition": null,
+ "confirmed_preferences": null,
+ "instructions": "",
+ "policy": {
+ "account": {
+ "calls": 6,
+ "cost_micros": 0,
+ "input_tokens": 192000,
+ "output_tokens": 24000,
+ "seconds": 7200
+ },
+ "admission_seconds": 5,
+ "attempt_seconds": 1200,
+ "job": {
+ "calls": 6,
+ "cost_micros": 0,
+ "input_tokens": 192000,
+ "output_tokens": 24000,
+ "seconds": 7200
+ },
+ "job_seconds": 1200,
+ "lease_seconds": 60,
+ "max_attempts_per_step": 1,
+ "max_concurrent_attempts": 2,
+ "max_depth": 0,
+ "per_call": {
+ "calls": 1,
+ "cost_micros": 0,
+ "input_tokens": 32000,
+ "output_tokens": 4000
+ },
+ "rates": {
+ "call_micros": 0,
+ "forge_call_micros": 0,
+ "input_micros_per_token": 0,
+ "output_micros_per_token": 0,
+ "tracker_call_micros": 0,
+ "version": 0
+ },
+ "require_distinct_review_family": true,
+ "require_distinct_review_provider": true,
+ "usage_mode": "subscription",
+ "version": 2
+ },
+ "project_revision": 0,
+ "selection": {
+ "account_id": "owner@example.test",
+ "account_label": "claude-a",
+ "allowance_known": false,
+ "allowance_remaining": 0,
+ "choice_revision": 0,
+ "connection_id": "F5NZDYKGJFVKXU7BT46NYHPUFU",
+ "family": "claude",
+ "isolation": {
+ "acknowledgement_ids": null,
+ "observed_tuples": [
+ {
+ "bwrap_version": "0.11.0",
+ "isolation_config_hash": "1cdc42ee82f63b57a06bd57162f95f87fd0eca70aade6fdbb678ddbca05a6592",
+ "launcher_version": "direct-v3",
+ "policy_version": "direct-v1",
+ "provider": "claude",
+ "provider_version": "2.1.312"
+ }
+ ],
+ "runner_tainted": false,
+ "status": "confined"
+ },
+ "max_concurrent": 0,
+ "model": "claude-opus-5-5",
+ "person": "owner@example.test",
+ "provider": "claude",
+ "reason": "",
+ "revision": 1,
+ "runner_id": "PH7VDUINM6WWERJKF5TFXMH527",
+ "specialist_revision": 0
+ },
+ "standing_instructions": "",
+ "step": {
+ "action": "coordinate",
+ "artifact_hashes": null,
+ "plan_revision": 0,
+ "specialist_icon": "",
+ "specialist_key": "coordinator",
+ "specialist_name": "",
+ "specialist_revision": 0,
+ "step_key": "coordinate"
+ },
+ "target": {
+ "kind": "conversation",
+ "subject": "owner@example.test"
+ }
+ },
+ "context": {
+ "confirmed_preferences": null,
+ "conversation_id": "JV6EBC4DI2AO4OPHDXMMFFQMJL",
+ "hash": "01f8ba4ef03888e5290570bb8e2aecfbf2fe3eda53eb909271275e49eae898cc",
+ "messages": null,
+ "projects": null,
+ "recent": [
+ {
+ "author_kind": "person",
+ "body": "Reply using post_message with exactly: e2e coordinator ready. Do not use any other tool.",
+ "id": "LDCKEWSBL6OQEJJBQVMKOR4YKS",
+ "revision": 1,
+ "sequence": 1
+ }
+ ],
+ "retrieved": [
+ {
+ "source": {
+ "hash": "0db740b7994b77b41e581204d618918d7eeed89e666f2677fc7a905eb972cf41",
+ "id": "owner@example.test",
+ "kind": "project_setup",
+ "revision": 1
+ },
+ "text": "{\"ReportedRepositories\":[\"amadan.net/oficina/e2e-unknown-repo\"],\"ExistingProjects\":[],\"HasProjects\":false}"
+ }
+ ],
+ "revision": 3,
+ "sources": null
+ },
+ "handle": {
+ "attempt": 1,
+ "fence": 1,
+ "revision": 2,
+ "runner": "PH7VDUINM6WWERJKF5TFXMH527"
+ },
+ "lease_deadline": "2026-11-06T14:48:52.621259617Z",
+ "scope": {
+ "account": "HSCPNNCT5L2STZQFKTQISL7L6M",
+ "job": 1
+ },
+ "tool_copy": {
+ "accepted": "Saved for validation.",
+ "descriptions": {
+ "ask_person": "Ask your person a question for a later turn.",
+ "post_message": "Post a message with references to its sources.",
+ "propose_plan": "Propose a plan for the current message. Ask which project if it is unclear.",
+ "propose_project": "Suggest a project from this person’s reported repositories. Explain why. The person must tap Set up before it is created.",
+ "read_project": "Read the project material this connection may use.",
+ "read_task": "Read a task in an allowed project.",
+ "route_to_task": "Link the current message to a task requested by your person.",
+ "suggest_playbook": "Suggest a playbook for your person to review.",
+ "suggest_preference": "Suggest a preference for your person to review.",
+ "suggest_specialist": "Suggest a specialist for your person to review."
+ },
+ "rejected": "This tool request could not be accepted."
+ },
+ "turn": {
+ "context_hash": "01f8ba4ef03888e5290570bb8e2aecfbf2fe3eda53eb909271275e49eae898cc",
+ "generation": 1,
+ "id": "fixture-admission-key",
+ "message_id": "LDCKEWSBL6OQEJJBQVMKOR4YKS",
+ "provider_session_id": "",
+ "request_id": "message:LDCKEWSBL6OQEJJBQVMKOR4YKS",
+ "revision": 1,
+ "state": "running"
+ }
+ },
+ "version": 2
+ }
+}
diff --git a/internal/coordinatorcontract/testdata/delivery.json b/internal/coordinatorcontract/testdata/delivery.json
new file mode 100644
index 00000000..5efb65e0
--- /dev/null
+++ b/internal/coordinatorcontract/testdata/delivery.json
@@ -0,0 +1,253 @@
+{
+ "path": "/api/runner/v2/coordinator/event",
+ "request": {
+ "capabilities": [
+ "coordinator.v1"
+ ],
+ "claim": {
+ "admission": {
+ "dispatch": {
+ "action": 1,
+ "hash": "de251da296706d0ba43bf6197ca86e669c8b91525ee14f17f7dd9fe55726b726",
+ "key": "fixture-admission-key",
+ "operation": "provider.call",
+ "payload": "eyJCaW5kaW5nSUQiOiJBWlpXSVFVN0JDRDM0N1ZGMkZRVFNLNjdPWiIsIkNvbnRleHRIYXNoIjoiMDFmOGJhNGVmMDM4ODhlNTI5MDU3MGJiOGUyYWVjZmJmMmZlM2VkYTUzZWI5MDkyNzEyNzVlNDllYWU4OThjYyIsIkdlbmVyYXRpb24iOjEsIk1lc3NhZ2VJRCI6IkxEQ0tFV1NCTDZPUUVKSkJRVk1LT1I0WUtTIiwiVHVybklEIjoiVk9RUUFETVBRUERNUFJTSUE0U1VRSUUzUUkifQ=="
+ },
+ "expires_at": "2026-11-06T14:47:57.625208278Z",
+ "handle": {
+ "attempt": 1,
+ "fence": 1,
+ "revision": 2,
+ "runner": "PH7VDUINM6WWERJKF5TFXMH527"
+ },
+ "incarnation": 2,
+ "scope": {
+ "account": "HSCPNNCT5L2STZQFKTQISL7L6M",
+ "job": 1
+ }
+ },
+ "attempt_deadline": "2026-11-06T15:07:52.620394945Z",
+ "binding": {
+ "connection_id": "F5NZDYKGJFVKXU7BT46NYHPUFU",
+ "generation": 1,
+ "id": "AZZWIQU7BCD347VF2FQTSK67OZ",
+ "person": "owner@example.test",
+ "revision": 1,
+ "runner_id": "PH7VDUINM6WWERJKF5TFXMH527"
+ },
+ "brief": {
+ "artifact_hashes": null,
+ "attempt_deadline": "2026-11-06T15:07:52.620394945Z",
+ "budget_revision": 0,
+ "check_definition": null,
+ "confirmed_preferences": null,
+ "instructions": "",
+ "policy": {
+ "account": {
+ "calls": 6,
+ "cost_micros": 0,
+ "input_tokens": 192000,
+ "output_tokens": 24000,
+ "seconds": 7200
+ },
+ "admission_seconds": 5,
+ "attempt_seconds": 1200,
+ "job": {
+ "calls": 6,
+ "cost_micros": 0,
+ "input_tokens": 192000,
+ "output_tokens": 24000,
+ "seconds": 7200
+ },
+ "job_seconds": 1200,
+ "lease_seconds": 60,
+ "max_attempts_per_step": 1,
+ "max_concurrent_attempts": 2,
+ "max_depth": 0,
+ "per_call": {
+ "calls": 1,
+ "cost_micros": 0,
+ "input_tokens": 32000,
+ "output_tokens": 4000
+ },
+ "rates": {
+ "call_micros": 0,
+ "forge_call_micros": 0,
+ "input_micros_per_token": 0,
+ "output_micros_per_token": 0,
+ "tracker_call_micros": 0,
+ "version": 0
+ },
+ "require_distinct_review_family": true,
+ "require_distinct_review_provider": true,
+ "usage_mode": "subscription",
+ "version": 2
+ },
+ "project_revision": 0,
+ "selection": {
+ "account_id": "owner@example.test",
+ "account_label": "claude-a",
+ "allowance_known": false,
+ "allowance_remaining": 0,
+ "choice_revision": 0,
+ "connection_id": "F5NZDYKGJFVKXU7BT46NYHPUFU",
+ "family": "claude",
+ "isolation": {
+ "acknowledgement_ids": null,
+ "observed_tuples": [
+ {
+ "bwrap_version": "0.11.0",
+ "isolation_config_hash": "1cdc42ee82f63b57a06bd57162f95f87fd0eca70aade6fdbb678ddbca05a6592",
+ "launcher_version": "direct-v3",
+ "policy_version": "direct-v1",
+ "provider": "claude",
+ "provider_version": "2.1.312"
+ }
+ ],
+ "runner_tainted": false,
+ "status": "confined"
+ },
+ "max_concurrent": 0,
+ "model": "claude-opus-5-5",
+ "person": "owner@example.test",
+ "provider": "claude",
+ "reason": "",
+ "revision": 1,
+ "runner_id": "PH7VDUINM6WWERJKF5TFXMH527",
+ "specialist_revision": 0
+ },
+ "standing_instructions": "",
+ "step": {
+ "action": "coordinate",
+ "artifact_hashes": null,
+ "plan_revision": 0,
+ "specialist_icon": "",
+ "specialist_key": "coordinator",
+ "specialist_name": "",
+ "specialist_revision": 0,
+ "step_key": "coordinate"
+ },
+ "target": {
+ "kind": "conversation",
+ "subject": "owner@example.test"
+ }
+ },
+ "context": {
+ "confirmed_preferences": null,
+ "conversation_id": "JV6EBC4DI2AO4OPHDXMMFFQMJL",
+ "hash": "01f8ba4ef03888e5290570bb8e2aecfbf2fe3eda53eb909271275e49eae898cc",
+ "messages": null,
+ "projects": null,
+ "recent": [
+ {
+ "author_kind": "person",
+ "body": "Reply using post_message with exactly: e2e coordinator ready. Do not use any other tool.",
+ "id": "LDCKEWSBL6OQEJJBQVMKOR4YKS",
+ "revision": 1,
+ "sequence": 1
+ }
+ ],
+ "retrieved": [
+ {
+ "source": {
+ "hash": "0db740b7994b77b41e581204d618918d7eeed89e666f2677fc7a905eb972cf41",
+ "id": "owner@example.test",
+ "kind": "project_setup",
+ "revision": 1
+ },
+ "text": "{\"ReportedRepositories\":[\"amadan.net/oficina/e2e-unknown-repo\"],\"ExistingProjects\":[],\"HasProjects\":false}"
+ }
+ ],
+ "revision": 3,
+ "sources": null
+ },
+ "handle": {
+ "attempt": 1,
+ "fence": 1,
+ "revision": 2,
+ "runner": "PH7VDUINM6WWERJKF5TFXMH527"
+ },
+ "lease_deadline": "2026-11-06T14:48:52.621259617Z",
+ "scope": {
+ "account": "HSCPNNCT5L2STZQFKTQISL7L6M",
+ "job": 1
+ },
+ "tool_copy": {
+ "accepted": "Saved for validation.",
+ "descriptions": {
+ "ask_person": "Ask your person a question for a later turn.",
+ "post_message": "Post a message with references to its sources.",
+ "propose_plan": "Propose a plan for the current message. Ask which project if it is unclear.",
+ "propose_project": "Suggest a project from this person’s reported repositories. Explain why. The person must tap Set up before it is created.",
+ "read_project": "Read the project material this connection may use.",
+ "read_task": "Read a task in an allowed project.",
+ "route_to_task": "Link the current message to a task requested by your person.",
+ "suggest_playbook": "Suggest a playbook for your person to review.",
+ "suggest_preference": "Suggest a preference for your person to review.",
+ "suggest_specialist": "Suggest a specialist for your person to review."
+ },
+ "rejected": "This tool request could not be accepted."
+ },
+ "turn": {
+ "context_hash": "01f8ba4ef03888e5290570bb8e2aecfbf2fe3eda53eb909271275e49eae898cc",
+ "generation": 1,
+ "id": "fixture-admission-key",
+ "message_id": "LDCKEWSBL6OQEJJBQVMKOR4YKS",
+ "provider_session_id": "",
+ "request_id": "message:LDCKEWSBL6OQEJJBQVMKOR4YKS",
+ "revision": 1,
+ "state": "running"
+ }
+ },
+ "event": {
+ "action_id": 1,
+ "agent_id": "3058d635e8239e42b9224a3e39039bf9af079ae57265f8aa95012f99fe8f1ad3/coordinator",
+ "assignment_id": "fixture-admission-key",
+ "epoch": "",
+ "handle": {
+ "attempt": 1,
+ "fence": 1,
+ "revision": 2,
+ "runner": "PH7VDUINM6WWERJKF5TFXMH527"
+ },
+ "id": "9d27a679fc48c03e46ff8510587dd85c97ceff2c5d95fb857815224e2a602dc0",
+ "isolation": {
+ "acknowledgement_ids": null,
+ "observed_tuples": [
+ {
+ "bwrap_version": "0.11.0",
+ "isolation_config_hash": "1cdc42ee82f63b57a06bd57162f95f87fd0eca70aade6fdbb678ddbca05a6592",
+ "launcher_version": "direct-v3",
+ "policy_version": "direct-v1",
+ "provider": "claude",
+ "provider_version": "2.1.312"
+ }
+ ],
+ "runner_tainted": false,
+ "status": "confined"
+ },
+ "kind": "coordinator.delivery",
+ "payload": {
+ "request_id": "LDCKEWSBL6OQEJJBQVMKOR4YKS-reply",
+ "resource_id": "L6NUX33UJPDMHQS36FOGGEZ2DR"
+ },
+ "request_id": "",
+ "scope": {
+ "account": "HSCPNNCT5L2STZQFKTQISL7L6M",
+ "job": 1
+ },
+ "sequence": null,
+ "server_id": "direct",
+ "session_id": "3f716df0-9f89-420b-80a9-edc59d9ee13a",
+ "source_time": "2026-11-06T14:48:07.133874631Z",
+ "task_id": "fixture-admission-key",
+ "turn_id": "fixture-admission-key",
+ "version": 2
+ },
+ "version": 2
+ },
+ "response": {
+ "result": null,
+ "version": 2
+ }
+}
diff --git a/internal/coordinatorcontract/testdata/heartbeat.json b/internal/coordinatorcontract/testdata/heartbeat.json
new file mode 100644
index 00000000..6c3df914
--- /dev/null
+++ b/internal/coordinatorcontract/testdata/heartbeat.json
@@ -0,0 +1,48 @@
+{
+ "path": "/api/runner/v2/heartbeat",
+ "request": {
+ "reports": [
+ {
+ "account_label": "claude-a",
+ "allowance_known": false,
+ "allowance_remaining": 0,
+ "available": true,
+ "bwrap_version": "0.11.0",
+ "family": "claude",
+ "isolation_config_hash": "1cdc42ee82f63b57a06bd57162f95f87fd0eca70aade6fdbb678ddbca05a6592",
+ "kind": "subscription",
+ "launcher_version": "direct-v3",
+ "local_id": "claude-a",
+ "model": "claude-opus-5-5",
+ "paseo_version": "",
+ "policy_version": "direct-v1",
+ "provider": "claude",
+ "provider_version": "2.1.312",
+ "provider_version_source": "direct-cli",
+ "read_isolation": true,
+ "routing": {
+ "account_id": "owner@example.test",
+ "account_pinned": true,
+ "binding_id": "claude-a",
+ "credential_home_hash": "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb",
+ "dedicated_user": false,
+ "no_failover": true,
+ "observed_account_id": "owner@example.test",
+ "process_ownership": true,
+ "timeline_recovery": true
+ },
+ "trial_ready": false,
+ "unavailable_reason": ""
+ }
+ ],
+ "repositories": [
+ "amadan.net/oficina/e2e-unknown-repo"
+ ],
+ "request_id": "XOCIOCLXIEY6GAABFJMUOEIPMJ",
+ "version": 2
+ },
+ "response": {
+ "result": {},
+ "version": 2
+ }
+}
diff --git a/internal/coordinatorcontract/testdata/poll.json b/internal/coordinatorcontract/testdata/poll.json
new file mode 100644
index 00000000..008004a2
--- /dev/null
+++ b/internal/coordinatorcontract/testdata/poll.json
@@ -0,0 +1,24 @@
+{
+ "path": "/api/runner/v2/coordinator/poll",
+ "request": {
+ "capabilities": [
+ "coordinator.v1"
+ ],
+ "version": 2
+ },
+ "response": {
+ "result": [
+ {
+ "context_hash": "",
+ "generation": 1,
+ "id": "fixture-admission-key",
+ "message_id": "LDCKEWSBL6OQEJJBQVMKOR4YKS",
+ "provider_session_id": "",
+ "request_id": "message:LDCKEWSBL6OQEJJBQVMKOR4YKS",
+ "revision": 1,
+ "state": "queued"
+ }
+ ],
+ "version": 2
+ }
+}
diff --git a/internal/coordinatorcontract/testdata/reply.json b/internal/coordinatorcontract/testdata/reply.json
new file mode 100644
index 00000000..b3bc12b5
--- /dev/null
+++ b/internal/coordinatorcontract/testdata/reply.json
@@ -0,0 +1,240 @@
+{
+ "path": "/api/runner/v2/coordinator/tool",
+ "request": {
+ "capabilities": [
+ "coordinator.v1"
+ ],
+ "claim": {
+ "admission": {
+ "dispatch": {
+ "action": 1,
+ "hash": "de251da296706d0ba43bf6197ca86e669c8b91525ee14f17f7dd9fe55726b726",
+ "key": "fixture-admission-key",
+ "operation": "provider.call",
+ "payload": "eyJCaW5kaW5nSUQiOiJBWlpXSVFVN0JDRDM0N1ZGMkZRVFNLNjdPWiIsIkNvbnRleHRIYXNoIjoiMDFmOGJhNGVmMDM4ODhlNTI5MDU3MGJiOGUyYWVjZmJmMmZlM2VkYTUzZWI5MDkyNzEyNzVlNDllYWU4OThjYyIsIkdlbmVyYXRpb24iOjEsIk1lc3NhZ2VJRCI6IkxEQ0tFV1NCTDZPUUVKSkJRVk1LT1I0WUtTIiwiVHVybklEIjoiVk9RUUFETVBRUERNUFJTSUE0U1VRSUUzUUkifQ=="
+ },
+ "expires_at": "2026-11-06T14:47:57.625208278Z",
+ "handle": {
+ "attempt": 1,
+ "fence": 1,
+ "revision": 2,
+ "runner": "PH7VDUINM6WWERJKF5TFXMH527"
+ },
+ "incarnation": 2,
+ "scope": {
+ "account": "HSCPNNCT5L2STZQFKTQISL7L6M",
+ "job": 1
+ }
+ },
+ "attempt_deadline": "2026-11-06T15:07:52.620394945Z",
+ "binding": {
+ "connection_id": "F5NZDYKGJFVKXU7BT46NYHPUFU",
+ "generation": 1,
+ "id": "AZZWIQU7BCD347VF2FQTSK67OZ",
+ "person": "owner@example.test",
+ "revision": 1,
+ "runner_id": "PH7VDUINM6WWERJKF5TFXMH527"
+ },
+ "brief": {
+ "artifact_hashes": null,
+ "attempt_deadline": "2026-11-06T15:07:52.620394945Z",
+ "budget_revision": 0,
+ "check_definition": null,
+ "confirmed_preferences": null,
+ "instructions": "",
+ "policy": {
+ "account": {
+ "calls": 6,
+ "cost_micros": 0,
+ "input_tokens": 192000,
+ "output_tokens": 24000,
+ "seconds": 7200
+ },
+ "admission_seconds": 5,
+ "attempt_seconds": 1200,
+ "job": {
+ "calls": 6,
+ "cost_micros": 0,
+ "input_tokens": 192000,
+ "output_tokens": 24000,
+ "seconds": 7200
+ },
+ "job_seconds": 1200,
+ "lease_seconds": 60,
+ "max_attempts_per_step": 1,
+ "max_concurrent_attempts": 2,
+ "max_depth": 0,
+ "per_call": {
+ "calls": 1,
+ "cost_micros": 0,
+ "input_tokens": 32000,
+ "output_tokens": 4000
+ },
+ "rates": {
+ "call_micros": 0,
+ "forge_call_micros": 0,
+ "input_micros_per_token": 0,
+ "output_micros_per_token": 0,
+ "tracker_call_micros": 0,
+ "version": 0
+ },
+ "require_distinct_review_family": true,
+ "require_distinct_review_provider": true,
+ "usage_mode": "subscription",
+ "version": 2
+ },
+ "project_revision": 0,
+ "selection": {
+ "account_id": "owner@example.test",
+ "account_label": "claude-a",
+ "allowance_known": false,
+ "allowance_remaining": 0,
+ "choice_revision": 0,
+ "connection_id": "F5NZDYKGJFVKXU7BT46NYHPUFU",
+ "family": "claude",
+ "isolation": {
+ "acknowledgement_ids": null,
+ "observed_tuples": [
+ {
+ "bwrap_version": "0.11.0",
+ "isolation_config_hash": "1cdc42ee82f63b57a06bd57162f95f87fd0eca70aade6fdbb678ddbca05a6592",
+ "launcher_version": "direct-v3",
+ "policy_version": "direct-v1",
+ "provider": "claude",
+ "provider_version": "2.1.312"
+ }
+ ],
+ "runner_tainted": false,
+ "status": "confined"
+ },
+ "max_concurrent": 0,
+ "model": "claude-opus-5-5",
+ "person": "owner@example.test",
+ "provider": "claude",
+ "reason": "",
+ "revision": 1,
+ "runner_id": "PH7VDUINM6WWERJKF5TFXMH527",
+ "specialist_revision": 0
+ },
+ "standing_instructions": "",
+ "step": {
+ "action": "coordinate",
+ "artifact_hashes": null,
+ "plan_revision": 0,
+ "specialist_icon": "",
+ "specialist_key": "coordinator",
+ "specialist_name": "",
+ "specialist_revision": 0,
+ "step_key": "coordinate"
+ },
+ "target": {
+ "kind": "conversation",
+ "subject": "owner@example.test"
+ }
+ },
+ "context": {
+ "confirmed_preferences": null,
+ "conversation_id": "JV6EBC4DI2AO4OPHDXMMFFQMJL",
+ "hash": "01f8ba4ef03888e5290570bb8e2aecfbf2fe3eda53eb909271275e49eae898cc",
+ "messages": null,
+ "projects": null,
+ "recent": [
+ {
+ "author_kind": "person",
+ "body": "Reply using post_message with exactly: e2e coordinator ready. Do not use any other tool.",
+ "id": "LDCKEWSBL6OQEJJBQVMKOR4YKS",
+ "revision": 1,
+ "sequence": 1
+ }
+ ],
+ "retrieved": [
+ {
+ "source": {
+ "hash": "0db740b7994b77b41e581204d618918d7eeed89e666f2677fc7a905eb972cf41",
+ "id": "owner@example.test",
+ "kind": "project_setup",
+ "revision": 1
+ },
+ "text": "{\"ReportedRepositories\":[\"amadan.net/oficina/e2e-unknown-repo\"],\"ExistingProjects\":[],\"HasProjects\":false}"
+ }
+ ],
+ "revision": 3,
+ "sources": null
+ },
+ "handle": {
+ "attempt": 1,
+ "fence": 1,
+ "revision": 2,
+ "runner": "PH7VDUINM6WWERJKF5TFXMH527"
+ },
+ "lease_deadline": "2026-11-06T14:48:52.621259617Z",
+ "scope": {
+ "account": "HSCPNNCT5L2STZQFKTQISL7L6M",
+ "job": 1
+ },
+ "tool_copy": {
+ "accepted": "Saved for validation.",
+ "descriptions": {
+ "ask_person": "Ask your person a question for a later turn.",
+ "post_message": "Post a message with references to its sources.",
+ "propose_plan": "Propose a plan for the current message. Ask which project if it is unclear.",
+ "propose_project": "Suggest a project from this person’s reported repositories. Explain why. The person must tap Set up before it is created.",
+ "read_project": "Read the project material this connection may use.",
+ "read_task": "Read a task in an allowed project.",
+ "route_to_task": "Link the current message to a task requested by your person.",
+ "suggest_playbook": "Suggest a playbook for your person to review.",
+ "suggest_preference": "Suggest a preference for your person to review.",
+ "suggest_specialist": "Suggest a specialist for your person to review."
+ },
+ "rejected": "This tool request could not be accepted."
+ },
+ "turn": {
+ "context_hash": "01f8ba4ef03888e5290570bb8e2aecfbf2fe3eda53eb909271275e49eae898cc",
+ "generation": 1,
+ "id": "fixture-admission-key",
+ "message_id": "LDCKEWSBL6OQEJJBQVMKOR4YKS",
+ "provider_session_id": "",
+ "request_id": "message:LDCKEWSBL6OQEJJBQVMKOR4YKS",
+ "revision": 1,
+ "state": "running"
+ }
+ },
+ "tool_call": {
+ "arguments": {
+ "body": "e2e coordinator ready.",
+ "source_refs": []
+ },
+ "name": "post_message",
+ "request_id": "LDCKEWSBL6OQEJJBQVMKOR4YKS-reply"
+ },
+ "version": 2
+ },
+ "response": {
+ "result": {
+ "resource_id": "L6NUX33UJPDMHQS36FOGGEZ2DR",
+ "revision": 1,
+ "value": {
+ "audit_ids": [
+ 46
+ ],
+ "result": {
+ "message": {
+ "SourceRefs": [],
+ "ID": "L6NUX33UJPDMHQS36FOGGEZ2DR",
+ "ConversationID": "JV6EBC4DI2AO4OPHDXMMFFQMJL",
+ "ThreadID": "",
+ "AuthorKind": "coordinator",
+ "AuthorID": "coordinator:AZZWIQU7BCD347VF2FQTSK67OZ",
+ "Body": "e2e coordinator ready.",
+ "Sequence": 3,
+ "Revision": 1,
+ "CreatedAt": "2026-11-06T14:48:04.27152435Z"
+ },
+ "source_refs": []
+ },
+ "tool": "post_message"
+ }
+ },
+ "version": 2
+ }
+}
diff --git a/internal/e2elivetest/e2e_live_certificate_test.go b/internal/e2elivetest/e2e_live_certificate_test.go
new file mode 100644
index 00000000..4d744009
--- /dev/null
+++ b/internal/e2elivetest/e2e_live_certificate_test.go
@@ -0,0 +1,72 @@
+//go:build e2elive
+
+package e2elivetest
+
+import (
+ "context"
+ "crypto/sha256"
+ "encoding/json"
+ "fmt"
+ "os"
+ "path/filepath"
+ "testing"
+
+ "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/certified"
+ "amadan.net/oficina/equipo/internal/runner/provider"
+)
+
+// Scratch paths change the exact deny policy. Only the harness's binaries embed
+// this certificate; the checked-in release manifest and evidence stay untouched.
+func liveCertificate(t *testing.T, root string, env map[string]string) string {
+ t.Helper()
+ ctx := context.Background()
+ cfg, err := runner.LoadConfig(func(k string) string { return env[k] })
+ executionMust(t, err)
+ raw, err := os.ReadFile(cfg.AccountBindingsPath)
+ executionMust(t, err)
+ var bs []runner.AccountBinding
+ executionMust(t, json.Unmarshal(raw, &bs))
+ b, err := cfg.DirectBinding(bs[0])
+ executionMust(t, err)
+ lease, err := provider.OpenAccount(ctx, b)
+ executionMust(t, err)
+ defer lease.Close()
+ b = lease.Binding()
+ work := filepath.Join(cfg.WorkspaceRoot, "certificate")
+ scratch := filepath.Join(cfg.ScratchRoot, "certificate")
+ executionMust(t, os.Mkdir(work, 0700))
+ executionMust(t, os.Mkdir(scratch, 0700))
+ defer os.RemoveAll(work)
+ defer os.RemoveAll(scratch)
+ in, err := runner.CertificationInputs(ctx, cfg, provider.Selection{ConnectionID: bs[0].LocalID, Provider: bs[0].Provider, Family: bs[0].Family, AccountID: bs[0].AccountID, Model: bs[0].Model}, b, work, "coordinate", scratch)
+ executionMust(t, err)
+ m := release.BuildManifest()
+ executionMust(t, m.VerifyInstalled(map[string]string{"claude": cfg.ClaudePath, "codex": cfg.CodexPath, "codex-code-mode-host": cfg.CodexCodeModeHostPath, "bwrap": cfg.BwrapPath, "equipo-tool-proxy": cfg.ToolProxyPath}))
+ if !m.HasCertifiedAction("claude", "coordinate") {
+ t.Fatal("stage certification: release has no coordinator certification")
+ }
+ policy, err := certified.BuildPolicy(b, in, m)
+ executionMust(t, err)
+ raw, err = json.Marshal(policy)
+ executionMust(t, err)
+ evidence := filepath.Join(root, "harness-policy.json")
+ executionMust(t, os.WriteFile(evidence, raw, 0600))
+ m.DirectPolicies = []release.PolicyCertificate{{Action: "coordinate", Provider: "claude", ProviderVersion: "2.1.312", LauncherVersion: m.LauncherVersion, BwrapVersion: m.BwrapVersion, PolicyHash: policy.Hash, NoRefreshReason: "Harness-only certificate; credential refresh remains denied."}}
+ m.Certifications = []release.Certification{{Provider: "claude", PolicyHash: policy.Hash, Path: evidence, SHA256: fmt.Sprintf("%x", sha256.Sum256(raw))}}
+ m.VerifiedIsolationTuples = []team.IsolationTuple{{Provider: "claude", ProviderVersion: "2.1.312", LauncherVersion: m.LauncherVersion, BwrapVersion: m.BwrapVersion, PolicyVersion: m.PolicyVersion, IsolationConfigHash: policy.Hash}}
+ raw, err = json.Marshal(m)
+ executionMust(t, err)
+ manifest := filepath.Join(root, "manifest.json")
+ executionMust(t, os.WriteFile(manifest, raw, 0600))
+ source, err := filepath.Abs("../release/manifest.json")
+ executionMust(t, err)
+ raw, err = json.Marshal(map[string]any{"Replace": map[string]string{source: manifest}})
+ executionMust(t, err)
+ overlay := filepath.Join(root, "overlay.json")
+ executionMust(t, os.WriteFile(overlay, raw, 0600))
+ t.Logf("harness-only certified policy: %s", policy.Hash)
+ return overlay
+}
diff --git a/internal/e2elivetest/e2e_live_helpers_test.go b/internal/e2elivetest/e2e_live_helpers_test.go
new file mode 100644
index 00000000..2d5a5c72
--- /dev/null
+++ b/internal/e2elivetest/e2e_live_helpers_test.go
@@ -0,0 +1,119 @@
+//go:build e2elive
+
+package e2elivetest
+
+import (
+ "encoding/json"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "strconv"
+ "strings"
+ "syscall"
+ "testing"
+ "time"
+
+ "amadan.net/oficina/equipo/internal/runner"
+)
+
+func liveEnvironment(t *testing.T, root string) map[string]string {
+ t.Helper()
+ home, err := os.UserHomeDir()
+ executionMust(t, err)
+ source := os.Getenv("EQUIPO_E2E_ENV")
+ if source == "" {
+ source = filepath.Join(home, ".local/share/equipo-runner/service.env")
+ }
+ raw, err := os.ReadFile(source)
+ executionMust(t, err)
+ env := map[string]string{}
+ for _, line := range strings.Split(string(raw), "\n") {
+ k, v, ok := strings.Cut(line, "=")
+ if !ok || !strings.HasPrefix(k, "EQUIPO_") {
+ continue
+ }
+ if strings.HasPrefix(v, `"`) {
+ v, err = strconv.Unquote(v)
+ executionMust(t, err)
+ }
+ env[k] = v
+ }
+ raw, err = os.ReadFile(env["EQUIPO_ACCOUNT_BINDINGS_PATH"])
+ executionMust(t, err)
+ var bindings []runner.AccountBinding
+ executionMust(t, json.Unmarshal(raw, &bindings))
+ var selected []runner.AccountBinding
+ for _, b := range bindings {
+ if b.LocalID == "claude-a" && b.Provider == "claude" && b.AccountID == "paul@tito.io" && b.ExpectedIdentity.ProviderVersion == "2.1.312" {
+ selected = append(selected, b)
+ }
+ }
+ if len(selected) != 1 {
+ t.Fatal("stage account selection: require dedicated claude-a / paul@tito.io / 2.1.312")
+ }
+ for key, name := range map[string]string{"EQUIPO_RUNNER_STATE_DIR": "state", "EQUIPO_WORKSPACE_ROOT": "work", "EQUIPO_SCRATCH_ROOT": "scratch"} {
+ env[key] = filepath.Join(root, name)
+ executionMust(t, os.Mkdir(env[key], 0700))
+ }
+ env["EQUIPO_ACCOUNT_BINDINGS_PATH"] = filepath.Join(root, "bindings.json")
+ raw, err = json.Marshal(selected)
+ executionMust(t, err)
+ executionMust(t, os.WriteFile(env["EQUIPO_ACCOUNT_BINDINGS_PATH"], raw, 0600))
+ // The coordinator can propose setup without any forge credential.
+ env["EQUIPO_AMADAN_CREDENTIAL_PATH"] = filepath.Join(root, "amadan.json")
+ executionMust(t, os.WriteFile(env["EQUIPO_AMADAN_CREDENTIAL_PATH"], []byte(`{"repositories":{"amadan.net/oficina/e2e-unknown-repo":""}}`), 0600))
+ return env
+}
+func liveBuild(t *testing.T, path, pkg, overlay string) {
+ t.Helper()
+ cmd := exec.Command("go", "build", "-overlay", overlay, "-o", path, pkg)
+ cmd.Dir = "../.."
+ cmd.Env = append(os.Environ(), "CGO_ENABLED=0")
+ if raw, err := cmd.CombinedOutput(); err != nil {
+ t.Fatalf("stage build %s: %v\n%s", pkg, err, raw)
+ }
+}
+func liveStart(t *testing.T, root string, env map[string]string, bin string, args ...string) string {
+ t.Helper()
+ path := filepath.Join(root, filepath.Base(bin)+".log")
+ f, err := os.OpenFile(path, os.O_CREATE|os.O_WRONLY, 0600)
+ executionMust(t, err)
+ cmd := exec.Command(bin, args...)
+ cmd.Dir = root
+ for _, entry := range os.Environ() {
+ k, _, _ := strings.Cut(entry, "=")
+ if !strings.HasPrefix(k, "EQUIPO_") && !strings.HasPrefix(k, "CARLOS_") && !strings.HasPrefix(k, "LISTEN_") {
+ cmd.Env = append(cmd.Env, entry)
+ }
+ }
+ for k, v := range env {
+ cmd.Env = append(cmd.Env, k+"="+v)
+ }
+ cmd.Stdout = f
+ cmd.Stderr = f
+ executionMust(t, cmd.Start())
+ t.Cleanup(func() {
+ cmd.Process.Signal(syscall.SIGTERM)
+ done := make(chan error, 1)
+ go func() { done <- cmd.Wait() }()
+ select {
+ case <-done:
+ case <-time.After(35 * time.Second):
+ cmd.Process.Kill()
+ <-done
+ }
+ f.Close()
+ })
+ return path
+}
+func liveWait(t *testing.T, stage string, limit time.Duration, ready func() bool) {
+ t.Helper()
+ deadline := time.Now().Add(limit)
+ for time.Now().Before(deadline) {
+ if ready() {
+ return
+ }
+ time.Sleep(250 * time.Millisecond)
+ }
+ t.Fatalf("stage %s: timed out after %s", stage, limit)
+}
diff --git a/internal/e2elivetest/e2e_live_record_test.go b/internal/e2elivetest/e2e_live_record_test.go
new file mode 100644
index 00000000..80bc0df1
--- /dev/null
+++ b/internal/e2elivetest/e2e_live_record_test.go
@@ -0,0 +1,123 @@
+//go:build e2elive
+
+package e2elivetest
+
+import (
+ "bytes"
+ "encoding/json"
+ "io"
+ "net/http"
+ "net/http/httptest"
+ "net/http/httputil"
+ "net/url"
+ "os"
+ "path/filepath"
+ "strings"
+ "sync"
+ "testing"
+)
+
+type livePacket struct {
+ Path string `json:"path"`
+ Request json.RawMessage `json:"request"`
+ Response json.RawMessage `json:"response"`
+}
+
+func liveRecordingProxy(t *testing.T, target string) (string, func()) {
+ t.Helper()
+ u, err := url.Parse(target)
+ executionMust(t, err)
+ proxy := httputil.NewSingleHostReverseProxy(u)
+ var mu sync.Mutex
+ packets := map[string]livePacket{}
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ // Nothing from headers (bearers, cookies or enrollment secrets) is recorded.
+ if !strings.HasPrefix(r.URL.Path, "/api/runner/v2/") {
+ proxy.ServeHTTP(w, r)
+ return
+ }
+ body, e := io.ReadAll(r.Body)
+ if e != nil {
+ http.Error(w, "read", 500)
+ return
+ }
+ r.Body = io.NopCloser(bytes.NewReader(body))
+ capture := httptest.NewRecorder()
+ proxy.ServeHTTP(capture, r)
+ for k, v := range capture.Header() {
+ w.Header()[k] = v
+ }
+ w.WriteHeader(capture.Code)
+ _, _ = w.Write(capture.Body.Bytes())
+ if capture.Code != 200 {
+ return
+ }
+ key := ""
+ switch r.URL.Path {
+ case "/api/runner/v2/heartbeat":
+ key = "heartbeat"
+ case "/api/runner/v2/coordinator/poll":
+ if !bytes.Contains(capture.Body.Bytes(), []byte(`"result":[]`)) {
+ key = "poll"
+ }
+ case "/api/runner/v2/coordinator/claim":
+ key = "claim"
+ case "/api/runner/v2/coordinator/tool":
+ if bytes.Contains(body, []byte(`"name":"post_message"`)) {
+ key = "reply"
+ }
+ case "/api/runner/v2/coordinator/event":
+ if bytes.Contains(body, []byte(`"kind":"coordinator.delivery"`)) {
+ key = "delivery"
+ }
+ }
+ if key != "" {
+ mu.Lock()
+ if _, ok := packets[key]; !ok {
+ packets[key] = livePacket{r.URL.Path, body, append([]byte(nil), capture.Body.Bytes()...)}
+ }
+ mu.Unlock()
+ }
+ }))
+ t.Cleanup(server.Close)
+ return server.URL, func() {
+ dir := os.Getenv("EQUIPO_E2E_RECORD")
+ if dir == "" {
+ return
+ }
+ mu.Lock()
+ defer mu.Unlock()
+ if len(packets) != 5 {
+ t.Fatalf("stage wire recording: got %d contracts", len(packets))
+ }
+ executionMust(t, os.MkdirAll(dir, 0700))
+ var claim struct {
+ Result struct {
+ Admission struct{ Dispatch struct{ Key string } }
+ }
+ }
+ executionMust(t, json.Unmarshal(packets["claim"].Response, &claim))
+ var beat struct {
+ Reports []struct {
+ Routing struct {
+ Home string `json:"credential_home_hash"`
+ }
+ }
+ }
+ executionMust(t, json.Unmarshal(packets["heartbeat"].Request, &beat))
+ for key, p := range packets {
+ raw, e := json.MarshalIndent(p, "", " ")
+ executionMust(t, e)
+ raw = bytes.ReplaceAll(raw, []byte("paul@tito.io"), []byte("owner@example.test"))
+ if claim.Result.Admission.Dispatch.Key != "" {
+ raw = bytes.ReplaceAll(raw, []byte(claim.Result.Admission.Dispatch.Key), []byte("fixture-admission-key"))
+ }
+ for _, report := range beat.Reports {
+ if report.Routing.Home != "" {
+ raw = bytes.ReplaceAll(raw, []byte(report.Routing.Home), []byte(strings.Repeat("b", 64)))
+ }
+ }
+ executionMust(t, os.WriteFile(filepath.Join(dir, key+".json"), append(raw, '\n'), 0600))
+ }
+ }
+}
diff --git a/internal/e2elivetest/e2e_live_test.go b/internal/e2elivetest/e2e_live_test.go
new file mode 100644
index 00000000..324d4d78
--- /dev/null
+++ b/internal/e2elivetest/e2e_live_test.go
@@ -0,0 +1,195 @@
+//go:build e2elive
+
+package e2elivetest
+
+import (
+ "context"
+ "encoding/json"
+ "fmt"
+ "io"
+ "log/slog"
+ "net"
+ "os"
+ "path/filepath"
+ "regexp"
+ "strings"
+ "testing"
+ "time"
+
+ "amadan.net/oficina/equipo/internal/equipo"
+ "amadan.net/oficina/equipo/internal/runnerproto"
+ "amadan.net/rastrillo/rastrillo/db"
+ "amadan.net/rastrillo/rastrillo/migrate"
+)
+
+// This seam exists only in a test binary. The served instance has no test routes.
+func TestCoordinatorE2ELive(t *testing.T) {
+ if os.Getenv("EQUIPO_E2E_LIVE") != "1" {
+ t.Skip("run make e2e-live")
+ }
+ ctx := context.Background()
+ root := t.TempDir()
+ env := liveEnvironment(t, root)
+ stage := "build"
+ check := func(err error) {
+ t.Helper()
+ if err != nil {
+ t.Fatalf("stage %s: %v", stage, err)
+ }
+ }
+ instance := filepath.Join(root, "equipo")
+ runnerBin := filepath.Join(root, "equipo-runner")
+
+ stage = "instance bootstrap"
+ listener, err := net.Listen("tcp", "127.0.0.1:0")
+ check(err)
+ addr := listener.Addr().String()
+ check(listener.Close())
+ origin, saveRecording := liveRecordingProxy(t, "http://"+addr)
+ env["EQUIPO_ORIGIN"] = origin
+ env["EQUIPO_EXECUTION_ENABLED"] = "1"
+ env["EQUIPO_ALLOW_LOGGED_MAIL"] = "1"
+ env["EQUIPO_ALWAYS_ON"] = "1"
+ env["EQUIPO_INSTANCE_KEY"] = "scratch-e2e-instance-key"
+ env["EQUIPO_OWNERS"] = "paul@tito.io"
+ env["EQUIPO_EXECUTION_MARKER_PATH"] = filepath.Join(root, "marker", "execution")
+ logger := slog.New(slog.NewTextHandler(io.Discard, nil))
+ path := filepath.Join(root, "instance.db")
+ d, err := db.Open(path, logger)
+ check(err)
+ t.Cleanup(func() { d.Close() })
+ _, err = migrate.Apply(ctx, d, equipo.BootSchema)
+ check(err)
+ s := equipo.NewStore(d)
+ cfg, err := equipo.LoadConfig(func(k string) string { return env[k] })
+ check(err)
+ x, err := equipo.OpenExecution(ctx, d, path, cfg, s)
+ check(err)
+ t.Cleanup(func() { x.Close() })
+ // Two prompts, at most six admitted model turns; no redispatch on failure.
+ stage = "runner enrolment"
+ code, key := beginDevice(t, s)
+ approveDevice(t, s, code, "paul@tito.io")
+ credential := claimDevice(t, s, code, key)
+ env["EQUIPO_INSTANCE_ID"] = code.InstanceID
+ raw, err := json.Marshal(runnerproto.CredentialRotation{Bearer: credential})
+ check(err)
+ check(os.WriteFile(filepath.Join(env["EQUIPO_RUNNER_STATE_DIR"], "credentials.json"), raw, 0600))
+ check(x.Close())
+ overlay := liveCertificate(t, root, env)
+ liveBuild(t, instance, "./cmd/equipo", overlay)
+ liveBuild(t, runnerBin, "./cmd/equipo-runner", overlay)
+ instanceLog := liveStart(t, root, env, instance, "-addr", addr, "-db", path)
+ c := signinClient(t, origin)
+ liveWait(t, "instance HTTP", 20*time.Second, func() bool {
+ r, e := c.Get(origin + "/signin")
+ if e != nil {
+ return false
+ }
+ r.Body.Close()
+ return r.StatusCode == 200
+ })
+ stage = "person sign-in"
+ beginEmail(t, c, origin, origin, "paul@tito.io")
+ var link string
+ liveWait(t, stage, 5*time.Second, func() bool {
+ b, _ := os.ReadFile(instanceLog)
+ link = regexp.MustCompile(`http://127\.0\.0\.1:[0-9]+/auth/verify\?[^\\\s"]+`).FindString(string(b))
+ return link != ""
+ })
+ m := &capturingMailer{bodies: []string{link}}
+ response := confirmEmail(t, c, origin, origin, m)
+ response.Body.Close()
+ if response.StatusCode != 303 {
+ t.Fatalf("stage %s: HTTP %d", stage, response.StatusCode)
+ }
+ stage = "runner heartbeat and certification"
+ runnerLog := liveStart(t, root, env, runnerBin, "run")
+ t.Cleanup(func() {
+ if t.Failed() {
+ raw, _ := os.ReadFile(runnerLog)
+ t.Logf("runner diagnostics: %s", raw)
+ }
+ })
+ liveWait(t, stage, 90*time.Second, func() bool {
+ var reports string
+ if d.Writer().QueryRow("SELECT reports_json FROM connections WHERE local_id='claude-a'").Scan(&reports) != nil {
+ return false
+ }
+ var r []runnerproto.ConnectionReport
+ check(json.Unmarshal([]byte(reports), &r))
+ if len(r) > 0 && !r[0].Available {
+ t.Fatalf("stage heartbeat certification: %s, policy %s", r[0].UnavailableReason, r[0].IsolationConfigHash)
+ }
+ return len(r) == 1 && r[0].Available && r[0].ReadIsolation
+ })
+ prompts := []struct{ body, query, feed string }{
+ {"Reply using post_message with exactly: e2e coordinator ready. Do not use any other tool.", "SELECT count(*) FROM conversation_messages WHERE author_kind='coordinator' AND body LIKE '%e2e coordinator ready%'", "e2e coordinator ready"},
+ {"Please work on https://amadan.net/oficina/e2e-unknown-repo. It is not set up here. Use propose_project with repository amadan.net/oficina/e2e-unknown-repo and why: requested for the local test. Do not create a task or run anything.", "SELECT count(*) FROM project_proposals WHERE repository='amadan.net/oficina/e2e-unknown-repo'", "e2e-unknown-repo"},
+ }
+ for i, p := range prompts {
+ stage = fmt.Sprintf("message %d HTTP form", i+1)
+ page := pageBody(t, c, origin, "/conversation")
+ fields := formFields(t, page, "/conversation")
+ fields.Set("body", p.body)
+ pagePost(t, c, origin, "/conversation", origin, fields, 303)
+ if i == 0 {
+ liveWait(t, "missing coordinator limits blocks claim", 40*time.Second, func() bool {
+ var state string
+ return d.Writer().QueryRow("SELECT state FROM coordinator_turns ORDER BY sequence DESC LIMIT 1").Scan(&state) == nil && state == "budget_needed"
+ })
+ teamPage := pageBody(t, c, origin, "/settings")
+ budget := formFields(t, teamPage, "/team/budgets")
+ for k, v := range map[string]string{"team_calls": "6", "team_input": "192000", "team_output": "24000", "team_seconds": "7200"} {
+ budget.Set(k, v)
+ }
+ pagePost(t, c, origin, "/team/budgets", origin, budget, 303)
+ settings := pageBody(t, c, origin, "/settings/coordinator")
+ limits := formFields(t, settings, "/settings/coordinator")
+ for k, v := range map[string]string{"action": "limits", "revision": "0", "calls": "6", "input_tokens": "192000", "output_tokens": "24000", "seconds": "7200"} {
+ limits.Set(k, v)
+ }
+ pagePost(t, c, origin, "/settings/coordinator", origin, limits, 303)
+ t.Log("missing budgets blocked claim; owner team and coordinator forms supplied the six-call budget")
+ }
+ liveWait(t, fmt.Sprintf("message %d claim, model turn and delivery", i+1), 150*time.Second, func() bool {
+ var count int
+ check(d.Writer().QueryRow(p.query).Scan(&count))
+ if count == 0 {
+ var state string
+ if d.Writer().QueryRow("SELECT state FROM coordinator_turns ORDER BY sequence DESC LIMIT 1").Scan(&state) == nil && (state == "uncertain" || state == "context_limit" || state == "context_unavailable" || state == "waiting_connection") {
+ t.Fatalf("stage message %d: coordinator state %s", i+1, state)
+ }
+ }
+ return count > 0
+ })
+ liveWait(t, "delivered turn", 30*time.Second, func() bool {
+ var n int
+ check(d.Writer().QueryRow("SELECT count(*) FROM coordinator_turns WHERE state='delivered'").Scan(&n))
+ return n == i+1
+ })
+ page = pageBody(t, c, origin, "/conversation")
+ if !strings.Contains(page, p.feed) {
+ t.Fatalf("stage rendered feed: missing %q", p.feed)
+ }
+ var renderedID string
+ marker := ""
+ if i == 0 {
+ check(d.Writer().QueryRow("SELECT id FROM conversation_messages WHERE author_kind='coordinator' AND body LIKE '%e2e coordinator ready%' LIMIT 1").Scan(&renderedID))
+ marker = `data-message="` + renderedID + `"`
+ } else {
+ check(d.Writer().QueryRow("SELECT id FROM project_proposals WHERE repository='amadan.net/oficina/e2e-unknown-repo'").Scan(&renderedID))
+ marker = `action="/conversation/projects/` + renderedID + `/answer"`
+ }
+ if !strings.Contains(page, marker) {
+ t.Fatalf("stage rendered feed: missing coordinator message or project setup form %s", renderedID)
+ }
+ t.Logf("message %d: form -> heartbeat -> poll -> claim -> Claude -> tool -> delivered -> feed", i+1)
+ }
+ saveRecording()
+ var turns int
+ check(d.Writer().QueryRow("SELECT count(*) FROM coordinator_turns WHERE job_id>0").Scan(&turns))
+ if turns != 2 {
+ t.Fatalf("stage turn budget: got %d claims", turns)
+ }
+}
diff --git a/internal/e2elivetest/http_helpers_test.go b/internal/e2elivetest/http_helpers_test.go
new file mode 100644
index 00000000..ae4313e5
--- /dev/null
+++ b/internal/e2elivetest/http_helpers_test.go
@@ -0,0 +1,231 @@
+//go:build e2elive
+
+package e2elivetest
+
+import (
+ "amadan.net/oficina/equipo/internal/equipo"
+ "amadan.net/oficina/equipo/internal/runnerproto"
+ "amadan.net/rastrillo/rastrillo/pow"
+ "context"
+ "crypto/ed25519"
+ "crypto/rand"
+ "encoding/base64"
+ "html"
+ "io"
+ "net/http"
+ "net/http/cookiejar"
+ "net/url"
+ "regexp"
+ "strings"
+ "sync"
+ "testing"
+ "time"
+)
+
+type capturingMailer struct {
+ mu sync.Mutex
+ bodies []string
+}
+
+func (m *capturingMailer) link(t *testing.T) string {
+ t.Helper()
+ m.mu.Lock()
+ defer m.mu.Unlock()
+ if len(m.bodies) == 0 {
+ t.Fatal("no email")
+ }
+ for _, word := range strings.Fields(m.bodies[len(m.bodies)-1]) {
+ if strings.Contains(word, "/auth/verify?") {
+ return word
+ }
+ }
+ t.Fatal("no link in email")
+ return ""
+}
+
+func mustURL(t *testing.T, s string) *url.URL {
+ t.Helper()
+ u, err := url.Parse(s)
+ if err != nil {
+ t.Fatal(err)
+ }
+ return u
+}
+
+func signinClient(t *testing.T, base string) *http.Client {
+ t.Helper()
+ jar, err := cookiejar.New(nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ return &http.Client{Jar: jar, Timeout: 10 * time.Second, CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }}
+}
+
+func clientGet(t *testing.T, c *http.Client, target string) *http.Response {
+ t.Helper()
+ res, err := c.Get(target)
+ if err != nil {
+ t.Fatal(err)
+ }
+ return res
+}
+
+func clientPost(t *testing.T, c *http.Client, target, origin string, form url.Values) *http.Response {
+ t.Helper()
+ req, err := http.NewRequest(http.MethodPost, target, strings.NewReader(form.Encode()))
+ if err != nil {
+ t.Fatal(err)
+ }
+ req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
+ if origin != "" {
+ req.Header.Set("Origin", origin)
+ }
+ res, err := c.Do(req)
+ if err != nil {
+ t.Fatal(err)
+ }
+ return res
+}
+
+func readBody(t *testing.T, res *http.Response) string {
+ t.Helper()
+ defer res.Body.Close()
+ b, err := io.ReadAll(res.Body)
+ if err != nil {
+ t.Fatal(err)
+ }
+ return string(b)
+}
+
+func formFields(t *testing.T, body, action string) url.Values {
+ t.Helper()
+ values := url.Values{}
+ found := false
+ for _, form := range regexp.MustCompile(`(?s)<form\b[^>]*>.*?</form>`).FindAllString(body, -1) {
+ if !strings.Contains(form, `action="`+action+`"`) {
+ continue
+ }
+ found = true
+ for _, input := range regexp.MustCompile(`<input\b[^>]*>`).FindAllString(form, -1) {
+ attrs := map[string]string{}
+ for _, pair := range regexp.MustCompile(`([a-z_-]+)="([^"]*)"`).FindAllStringSubmatch(input, -1) {
+ attrs[pair[1]] = html.UnescapeString(pair[2])
+ }
+ if attrs["name"] != "" {
+ values.Set(attrs["name"], attrs["value"])
+ }
+ }
+ }
+ if !found {
+ t.Fatalf("missing form %s", action)
+ }
+ return values
+}
+
+type emailChallenge struct {
+ values url.Values
+ ready time.Time
+}
+
+func prepareEmail(t *testing.T, c *http.Client, base, address string) emailChallenge {
+ t.Helper()
+ res := clientGet(t, c, base+"/signin?force=1")
+ if res.StatusCode != 200 {
+ t.Fatalf("signin page: %d", res.StatusCode)
+ }
+ values := formFields(t, readBody(t, res), "/auth/begin")
+ values.Set("address", address)
+ if values.Get("force") != "1" {
+ t.Fatal("email fallback not rendered")
+ }
+ return emailChallenge{values: values, ready: time.Now().Add(pow.DefaultMinAge + 50*time.Millisecond)}
+}
+
+func submitEmail(t *testing.T, c *http.Client, base, origin string, challenge emailChallenge) {
+ t.Helper()
+ time.Sleep(time.Until(challenge.ready))
+ res := clientPost(t, c, base+"/auth/begin", origin, challenge.values)
+ defer res.Body.Close()
+ if res.StatusCode != 303 || !strings.Contains(res.Header.Get("Location"), "sent=1") {
+ t.Fatalf("begin: %d %s", res.StatusCode, res.Header.Get("Location"))
+ }
+}
+
+func beginEmail(t *testing.T, c *http.Client, base, origin, address string) {
+ t.Helper()
+ submitEmail(t, c, base, origin, prepareEmail(t, c, base, address))
+}
+
+func confirmEmail(t *testing.T, c *http.Client, base, origin string, m *capturingMailer) *http.Response {
+ t.Helper()
+ link := mustURL(t, m.link(t))
+ local := mustURL(t, base).ResolveReference(&url.URL{Path: link.Path, RawQuery: link.RawQuery})
+ res := clientGet(t, c, local.String())
+ if res.StatusCode != 200 {
+ t.Fatalf("confirm: %d", res.StatusCode)
+ }
+ values := formFields(t, readBody(t, res), "/auth/verify")
+ return clientPost(t, c, base+"/auth/verify", origin, values)
+}
+
+// signinEmail is shared by HTTP, browser setup and performance callers.
+// The client keeps real cookies; every credential comes from the rendered flow.
+
+func machine(t *testing.T) (string, ed25519.PrivateKey) {
+ t.Helper()
+ pub, key, err := ed25519.GenerateKey(rand.Reader)
+ executionMust(t, err)
+ return base64.RawURLEncoding.EncodeToString(pub), key
+}
+
+func beginDevice(t *testing.T, s *equipo.Store) (runnerproto.DeviceCode, ed25519.PrivateKey) {
+ t.Helper()
+ pub, key := machine(t)
+ code, err := s.BeginEnrolment(context.Background(), pub, "Desk machine")
+ executionMust(t, err)
+ return code, key
+}
+
+func deviceProof(code runnerproto.DeviceCode, key ed25519.PrivateKey) runnerproto.ExchangeProof {
+ nonce := make([]byte, 32)
+ rand.Read(nonce)
+ p := runnerproto.ExchangeProof{EnrolmentID: code.EnrolmentID, Challenge: code.Challenge, ExchangeNonce: base64.RawURLEncoding.EncodeToString(nonce)}
+ p.Signature = base64.RawURLEncoding.EncodeToString(ed25519.Sign(key, runnerproto.EnrolmentProofMessage(code.InstanceID, p)))
+ return p
+}
+
+func approveDevice(t *testing.T, s *equipo.Store, code runnerproto.DeviceCode, person string) {
+ t.Helper()
+ if err := s.ApproveEnrolment(context.Background(), equipo.Actor{Address: person}, code.UserCode); err != nil {
+ t.Fatal(err)
+ }
+}
+
+func claimDevice(t *testing.T, s *equipo.Store, code runnerproto.DeviceCode, key ed25519.PrivateKey) runnerproto.RunnerCredential {
+ t.Helper()
+ c, err := s.ExchangeEnrolment(context.Background(), code.DeviceSecret, deviceProof(code, key))
+ executionMust(t, err)
+ return c
+}
+func executionMust(t *testing.T, err error) {
+ t.Helper()
+ if err != nil {
+ t.Fatal(err)
+ }
+}
+func pageBody(t *testing.T, c *http.Client, base, path string) string {
+ t.Helper()
+ res := clientGet(t, c, base+path)
+ if res.StatusCode != 200 {
+ t.Fatalf("stage page %s: HTTP %d", path, res.StatusCode)
+ }
+ return readBody(t, res)
+}
+func pagePost(t *testing.T, c *http.Client, base, path, origin string, fields url.Values, want int) {
+ t.Helper()
+ res := clientPost(t, c, base+path, origin, fields)
+ defer res.Body.Close()
+ if res.StatusCode != want {
+ t.Fatalf("stage form %s: HTTP %d", path, res.StatusCode)
+ }
+}
diff --git a/internal/equipo/conversation/coordinator_application.go b/internal/equipo/conversation/coordinator_application.go
index 31c21921..1b36fe85 100644
--- a/internal/equipo/conversation/coordinator_application.go
+++ b/internal/equipo/conversation/coordinator_application.go
@@ -87,6 +87,12 @@ func (s *Application) changeCoordinator(ctx context.Context, actor Actor, runner
if err != nil {
return err
}
+ if !reset {
+ candidate := BindingRecord{CoordinatorBinding: CoordinatorBinding{Person: actor.Address, RunnerID: runnerID, ConnectionID: connectionID}, MemberRevision: memberRevision, ConnectionRevision: connectionRevision}
+ if _, err := s.BindingSelection(tx, candidate); err != nil {
+ return err
+ }
+ }
var turns []TurnRecord
if exists {
if err = tx.Where("binding_id=? AND job_id>0 AND state<>'superseded'", b.ID).Find(&turns).Error; err != nil {
diff --git a/internal/equipo/conversation/settings.go b/internal/equipo/conversation/settings.go
index a33feadf..38adbb99 100644
--- a/internal/equipo/conversation/settings.go
+++ b/internal/equipo/conversation/settings.go
@@ -13,7 +13,10 @@ import (
"gorm.io/gorm"
)
-type CoordinatorConnection struct{ ID, RunnerID, Label string }
+type CoordinatorConnection struct {
+ ID, RunnerID, Label string
+ Available bool
+}
type CoordinatorPage struct {
Binding CoordinatorBinding
Connections []CoordinatorConnection
@@ -52,7 +55,17 @@ func (s *Application) CoordinatorPage(ctx context.Context, a Actor) (out Coordin
if len(reports) > 0 && reports[0].AccountLabel != "" {
label = reports[0].AccountLabel
}
- out.Connections = append(out.Connections, CoordinatorConnection{row.ID, row.RunnerID, label})
+ available := false
+ memberRevision, connectionRevision, err := s.BindingIdentity(tx, a, row.RunnerID, row.ID)
+ if err == nil {
+ candidate := BindingRecord{CoordinatorBinding: CoordinatorBinding{Person: a.Address, RunnerID: row.RunnerID, ConnectionID: row.ID}, MemberRevision: memberRevision, ConnectionRevision: connectionRevision}
+ _, err = s.BindingSelection(tx, candidate)
+ available = err == nil
+ }
+ if err != nil && !errors.Is(err, s.WaitingConnection) && !errors.Is(err, s.Forbidden) && !errors.Is(err, s.NotFound) {
+ return err
+ }
+ out.Connections = append(out.Connections, CoordinatorConnection{ID: row.ID, RunnerID: row.RunnerID, Label: label, Available: available})
}
var limits struct {
Revision int64
diff --git a/internal/equipo/conversation/views.go b/internal/equipo/conversation/views.go
index d69b6a6c..8c8795b5 100644
--- a/internal/equipo/conversation/views.go
+++ b/internal/equipo/conversation/views.go
@@ -1,6 +1,7 @@
package conversation
import (
+ sends "amadan.net/oficina/equipo/internal/chatsend"
"context"
"crypto/rand"
"encoding/json"
@@ -15,6 +16,7 @@ import (
)
type MessageView struct {
+ ClientRequestID string
Message
RouteID, ThreadURL string
AuthorName, AuthorIcon string
@@ -112,8 +114,12 @@ func (s *Application) View(ctx context.Context, a Actor, task, cursor string, pl
if page.NextCursor != "" {
out.NextURL = "?cursor=" + url.QueryEscape(page.NextCursor)
}
+ requests, err := sends.Requests(tx, a.Address, page.Messages, func(m Message) string { return m.ID })
+ if err != nil {
+ return err
+ }
for _, m := range page.Messages {
- mv := MessageView{Message: m, RouteID: rand.Text()}
+ mv := MessageView{Message: m, RouteID: rand.Text(), ClientRequestID: requests[m.ID]}
if task == "" {
var route routeRecord
e := tx.Where("notice_id=?", m.ID).Take(&route).Error
diff --git a/internal/equipo/copy.go b/internal/equipo/copy.go
index 17e3ed1e..53b70b2d 100644
--- a/internal/equipo/copy.go
+++ b/internal/equipo/copy.go
@@ -453,10 +453,16 @@ var pageCopy = map[string]string{
// COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context): conversation.title
"conversation.title": "Conversation",
// COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context): conversation.empty
- "conversation.empty": "Say what you want fixed. Equipo will recommend a project and set up what it needs when you confirm.",
- "conversation.age_minutes": "%d min", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
- "conversation.age_hours": "%d hr", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
- "conversation.age_days": "%d d", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
+ "conversation.empty": "Say what you want fixed. Equipo will recommend a project and set up what it needs when you confirm.",
+ "conversation.age_minutes": "%d min", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
+ "conversation.age_hours": "%d hr", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
+ "conversation.age_days": "%d d", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
+ // COPY REVIEW PENDING: coordinator.connection_unavailable
+ "coordinator.connection_unavailable": "Unavailable",
+ // COPY REVIEW PENDING: conversation.sending
+ "conversation.sending": "Sending",
+ // COPY REVIEW PENDING: conversation.retry
+ "conversation.retry": "Retry",
"conversation.send_short": "Send", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
"nav.queued": "queued", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
"nav.switch": "switch", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
diff --git a/internal/equipo/static/chat-send.js b/internal/equipo/static/chat-send.js
new file mode 100644
index 00000000..2c1681b4
--- /dev/null
+++ b/internal/equipo/static/chat-send.js
@@ -0,0 +1,95 @@
+(function () {
+ "use strict";
+ var chat = document.querySelector("[equipo-conversation]");
+ if (!chat || !window.fetch || !window.crypto || !crypto.randomUUID) return;
+ var pending = new Map(), confirmed = new Map();
+ function reconcile() {
+ var feed = chat.querySelector("[equipo-feed]");
+ if (!feed) return;
+ var requests = new Map(Array.from(feed.querySelectorAll("[data-request-id]")).map(function (n) { return [n.dataset.requestId, n]; }));
+ // A live fetch started before the POST can arrive after its response.
+ confirmed.forEach(function (node, id) {
+ if (requests.has(id)) confirmed.set(id, requests.get(id));
+ else feed.append(node);
+ });
+ pending.forEach(function (item, id) {
+ if (requests.has(id)) {
+ clearTimeout(item.timer);
+ confirmed.set(id, requests.get(id));
+ if (confirmed.size > 50) confirmed.delete(confirmed.keys().next().value);
+ item.node.remove();
+ pending.delete(id);
+ } else if (!feed.contains(item.node)) feed.append(item.node);
+ });
+ }
+ new MutationObserver(reconcile).observe(chat, { childList: true, subtree: true });
+ function send(item) {
+ if (item.busy) return;
+ item.busy = true;
+ item.status.replaceChildren();
+ item.timer = setTimeout(function () { if (pending.has(item.id)) item.status.textContent = item.sending; }, 500);
+ var form = document.getElementById("composer");
+ var input = form.querySelector("textarea"), button = form.querySelector("button[type=submit]");
+ form.setAttribute("aria-busy", "true");
+ input.readOnly = true;
+ button.disabled = true;
+ var abort = new AbortController();
+ var timeout = setTimeout(function () { abort.abort(); }, 30000);
+ fetch(item.url, {
+ method: "POST", body: new URLSearchParams(item.body), signal: abort.signal,
+ headers: { "Rastrillo-Page": location.pathname, "Rastrillo-Fragment": "conversation-feed notice" }
+ }).then(function (response) {
+ if (!response.ok || !response.headers.get("Rastrillo-Regions")) throw new Error("send");
+ return response.text();
+ }).then(function (body) {
+ var doc = new DOMParser().parseFromString(body, "text/html");
+ var feed = doc.getElementById("conversation-feed");
+ if (!feed || !Array.from(feed.querySelectorAll("[data-request-id]")).some(function (n) { return n.dataset.requestId === item.id; })) throw new Error("receipt");
+ chat.querySelector("#conversation-feed").replaceWith(feed);
+ reconcile();
+ }).catch(function () {
+ if (!pending.has(item.id)) return;
+ item.status.replaceChildren();
+ var retry = document.createElement("button");
+ retry.type = "button";
+ retry.textContent = item.retry;
+ retry.addEventListener("click", function () { send(item); });
+ item.status.append(retry);
+ }).finally(function () {
+ clearTimeout(timeout);
+ clearTimeout(item.timer);
+ item.busy = false;
+ form.removeAttribute("aria-busy");
+ input.readOnly = false;
+ button.disabled = false;
+ input.focus({ preventScroll: true });
+ });
+ }
+ chat.addEventListener("submit", function (event) {
+ var form = event.target;
+ if (form.id !== "composer") return;
+ event.preventDefault();
+ event.stopPropagation();
+ if (form.getAttribute("aria-busy") === "true") return;
+ var data = new FormData(form);
+ var id = data.get("request_id");
+ var node = document.createElement("li"), bubble = document.createElement("div"), text = document.createElement("p"), status = document.createElement("small");
+ node.dataset.pending = id;
+ node.setAttribute("equipo-message", "own");
+ bubble.setAttribute("equipo-bubble", "");
+ text.setAttribute("equipo-message-body", "");
+ text.textContent = data.get("body");
+ status.setAttribute("equipo-send-status", "");
+ status.setAttribute("role", "status");
+ bubble.append(text, status);
+ node.append(bubble);
+ var item = { id: id, node: node, status: status, body: new URLSearchParams(data), url: form.action, sending: form.dataset.sending, retry: form.dataset.retry };
+ pending.set(id, item);
+ reconcile();
+ form.querySelector("textarea").value = "";
+ form.querySelector('[name="request_id"]').value = crypto.randomUUID();
+ var scroll = chat.querySelector("[equipo-scroll]");
+ scroll.scrollTop = scroll.scrollHeight;
+ send(item);
+ }, true);
+})();
diff --git a/internal/equipo/static/equipo.css b/internal/equipo/static/equipo.css
index 38aa3777..58205117 100644
--- a/internal/equipo/static/equipo.css
+++ b/internal/equipo/static/equipo.css
@@ -167,3 +167,5 @@ html:has([equipo-conversation]) { overflow: hidden; scrollbar-gutter: auto; }
[equipo-system-note] [equipo-bubble] { background: transparent; color: var(--rst-text-muted); font-size: var(--rst-fs-sm); }
[equipo-system-note][equipo-card] { border: 0; background: transparent; color: var(--rst-text-muted); font-size: var(--rst-fs-sm); }
+[equipo-send-status] { display: block; color: var(--rst-text-muted); font-size: var(--rst-fs-sm); }
+[equipo-send-status]:empty { display: none; }
diff --git a/internal/equipo/templates/chrome.html b/internal/equipo/templates/chrome.html
index 91dcd60f..b8aa4b86 100644
--- a/internal/equipo/templates/chrome.html
+++ b/internal/equipo/templates/chrome.html
@@ -1,6 +1,6 @@
{{define "rail-brand"}}<span hidden></span>{{end}}
{{define "title"}}{{copy .Title}} · {{copy "brand"}}{{end}}
-{{define "head"}}{{.Live.Head (T "rastrillo.ui.live.paused") (T "rastrillo.ui.live.unconfirmed")}}<link rel="stylesheet" href="{{asset "static/equipo.css"}}">{{if eq .Key "conversation"}}<script defer blocking="render" src="{{asset "static/chat-navigation.js"}}"></script><script defer src="{{asset "static/chat.js"}}"></script>{{end}}{{end}}
+{{define "head"}}{{.Live.Head (T "rastrillo.ui.live.paused") (T "rastrillo.ui.live.unconfirmed")}}<link rel="stylesheet" href="{{asset "static/equipo.css"}}">{{if eq .Key "conversation"}}<script defer blocking="render" src="{{asset "static/chat-navigation.js"}}"></script><script defer src="{{asset "static/chat.js"}}"></script><script defer src="{{asset "static/chat-send.js"}}"></script>{{end}}{{end}}
{{define "up"}}/work{{if .Key}}#nav-{{.Key}}{{end}}{{end}}
{{define "up-label"}}{{.TeamName}}{{end}}
{{define "brand"}}<a rst-shell-brand href="/work">{{icon "users"}}{{.TeamName}}</a>{{end}}
diff --git a/internal/equipo/templates/conversation_card.html b/internal/equipo/templates/conversation_card.html
index c45fb98a..4db3b311 100644
--- a/internal/equipo/templates/conversation_card.html
+++ b/internal/equipo/templates/conversation_card.html
@@ -1,6 +1,6 @@
{{define "region:chat-composer"}}
<div id="chat-composer" {{.Live.Attrs .Conversation.Topic}}>
-<form data-chat-submit id="composer" data-live-form="conversation-feed" equipo-form method="post" action="{{if .Conversation.ThreadID}}/tasks/{{.Conversation.ThreadID}}/thread{{else}}/conversation{{end}}">
+<form data-sending="{{copy "conversation.sending"}}" data-retry="{{copy "conversation.retry"}}" data-chat-submit id="composer" data-live-form="conversation-feed" equipo-form method="post" action="{{if .Conversation.ThreadID}}/tasks/{{.Conversation.ThreadID}}/thread{{else}}/conversation{{end}}">
<input type="hidden" name="request_id" value="{{.Conversation.RequestID}}"><input type="hidden" name="revision" value="0">
<textarea id="chat-body" rst-input name="body" required maxlength="16384" rows="1" aria-label="{{if .Conversation.ThreadID}}{{copy "conversation.thread_reply"}}{{else}}{{copy "conversation.composer"}}{{end}}" placeholder="{{copy "conversation.placeholder"}}"></textarea>
<div equipo-composer-tools>{{if and .Conversation.Projects (not .Conversation.ThreadID)}}<select rst-input name="project_id" aria-label="{{copy "plan.project"}}"><option value="">{{copy "conversation.any_project"}}</option>{{range .Conversation.Projects}}<option value="{{.ID}}">{{.Name}}</option>{{end}}</select>{{end}}<button rst-btn="primary" type="submit">{{copy "conversation.send_short"}}</button></div>
@@ -14,7 +14,7 @@
{{$day := ""}}{{range .Conversation.Feed}}
{{if .Message}}{{$date := .Message.CreatedAt.Format "2006-01-02"}}{{if ne $date $day}}<li equipo-day><time datetime="{{$date}}">{{if eq $date $.Conversation.Today}}{{copy "conversation.today"}}{{else}}{{.Message.CreatedAt.Format "2 January 2006"}}{{end}}</time></li>{{$day = $date}}{{end}}{{end}}
{{if .Message}}{{with .Message}}
-<li {{if eq .AuthorKind "system"}}equipo-system-note{{end}} equipo-message="{{if .Own}}own{{else}}incoming{{end}}" data-message="{{.ID}}" data-sequence="{{.Sequence}}">
+<li {{if eq .AuthorKind "system"}}equipo-system-note{{end}} equipo-message="{{if .Own}}own{{else}}incoming{{end}}" data-message="{{.ID}}"{{if .ClientRequestID}} data-request-id="{{.ClientRequestID}}"{{end}} data-sequence="{{.Sequence}}">
<div equipo-message-meta><strong{{if .Own}} equipo-visually-hidden{{end}}>{{icon .AuthorIcon}}{{.AuthorName}}</strong><time datetime="{{.CreatedAt.Format "2006-01-02T15:04:05Z07:00"}}" title="{{.CreatedAt.Format "2006-01-02 15:04 MST"}}">{{.CreatedAt.Format "15:04"}}</time></div>
<div equipo-bubble><p equipo-message-body>{{.Body}}</p>
{{if .ThreadURL}}<a href="{{.ThreadURL}}">{{copy "conversation.thread_link"}}</a>{{end}}
@@ -53,6 +53,7 @@
{{if eq .Kind "coordinator"}}
{{if .WaitingTaskURL}}<p>{{copy "coordinator.waiting_label"}} <a href="{{.WaitingTaskURL}}">{{.WaitingLabel}}</a></p>{{else}}<p>{{copy .CopyKey}}</p>{{end}}
+{{if or (eq .CopyKey "coordinator.budget_needed") (eq .CopyKey "coordinator.waiting_connection")}}<a href="/settings/coordinator">{{copy "coordinator.settings"}}</a>{{end}}
{{if .ActionKeys}}<div equipo-actions><form method="post" action="/settings/coordinator"><input type="hidden" name="action" value="retry"><input type="hidden" name="request_id" value="{{.RequestID}}"><input type="hidden" name="revision" value="{{.Revision}}"><input type="hidden" name="turn_id" value="{{.ResourceID}}"><button rst-btn type="submit">{{copy "coordinator.retry"}}</button></form><form method="post" action="/settings/coordinator"><input type="hidden" name="action" value="reset"><input type="hidden" name="request_id" value="{{.ResetID}}"><input type="hidden" name="revision" value="{{.BindingRevision}}"><button rst-btn type="submit">{{copy "coordinator.reset"}}</button></form></div>{{end}}
{{end}}
{{if eq .Kind "suggest_playbook"}}<a href="/playbook-suggestions/{{.ResourceID}}">{{copy "playbooks.save_suggestion"}}</a>{{end}}
diff --git a/internal/equipo/templates/coordinator.html b/internal/equipo/templates/coordinator.html
index 3b858b12..ffb17c11 100644
--- a/internal/equipo/templates/coordinator.html
+++ b/internal/equipo/templates/coordinator.html
@@ -2,9 +2,9 @@
{{define "content"}}
<h1>{{copy "coordinator.settings"}}</h1>
{{with .Coordinator}}
-{{if .BudgetMissing}}<p equipo-note>{{copy "coordinator.budget_needed"}}</p>{{end}}
+{{if .BudgetMissing}}<p equipo-note>{{copy "coordinator.budget_needed"}}{{if .Owner}} <a href="/settings#budgets">{{copy "budget.team"}}</a>{{end}}</p>{{end}}
{{if not .Binding.ID}}<p equipo-note>{{copy "coordinator.unavailable"}}</p>{{end}}
-{{if .Connections}}<form equipo-form method="post" action="/settings/coordinator"><input type="hidden" name="action" value="bind"><input type="hidden" name="request_id" value="{{.RequestID}}"><input type="hidden" name="revision" value="{{.Binding.Revision}}"><label>{{copy "coordinator.connection"}}<select rst-input name="connection_id">{{$current := .Binding.ConnectionID}}{{range .Connections}}<option value="{{.ID}}" {{if eq .ID $current}}selected{{end}}>{{.Label}}</option>{{end}}</select></label><button rst-btn type="submit">{{copy "form.save"}}</button></form>{{else}}<a href="/connections">{{copy "nav.connections"}}</a>{{end}}
+{{if .Connections}}<form equipo-form method="post" action="/settings/coordinator"><input type="hidden" name="action" value="bind"><input type="hidden" name="request_id" value="{{.RequestID}}"><input type="hidden" name="revision" value="{{.Binding.Revision}}"><label>{{copy "coordinator.connection"}}<select rst-input name="connection_id">{{$current := .Binding.ConnectionID}}{{range .Connections}}<option {{if not .Available}}disabled{{end}} value="{{.ID}}" {{if eq .ID $current}}selected{{end}}>{{.Label}}{{if not .Available}} ({{copy "coordinator.connection_unavailable"}}){{end}}</option>{{end}}</select></label><button rst-btn type="submit">{{copy "form.save"}}</button></form>{{else}}<a href="/connections">{{copy "nav.connections"}}</a>{{end}}
{{if .Binding.ID}}<form equipo-form method="post" action="/settings/coordinator"><input type="hidden" name="action" value="reset"><input type="hidden" name="request_id" value="{{.ResetID}}"><input type="hidden" name="revision" value="{{.Binding.Revision}}"><button rst-btn type="submit">{{copy "coordinator.reset"}}</button></form>{{end}}
{{if .Owner}}<section equipo-card><h2>{{copy "coordinator.limits"}}</h2><form equipo-form method="post" action="/settings/coordinator"><input type="hidden" name="action" value="limits"><input type="hidden" name="request_id" value="{{.LimitsID}}"><input type="hidden" name="revision" value="{{.LimitsRevision}}">
<label>{{copy "budget.calls"}}<input rst-input type="number" min="1" name="calls" value="{{if not .BudgetMissing}}{{.Limits.Calls}}{{end}}" required></label><label>{{copy "budget.input"}}<input rst-input type="number" min="1" name="input_tokens" value="{{if not .BudgetMissing}}{{.Limits.InputTokens}}{{end}}" required></label><label>{{copy "budget.output"}}<input rst-input type="number" min="1" name="output_tokens" value="{{if not .BudgetMissing}}{{.Limits.OutputTokens}}{{end}}" required></label><label>{{copy "budget.seconds"}}<input rst-input type="number" min="1" name="seconds" value="{{if not .BudgetMissing}}{{.Limits.Seconds}}{{end}}" required></label><button rst-btn type="submit">{{copy "form.save"}}</button></form></section>{{end}}
diff --git a/internal/equipo/templates/settings.html b/internal/equipo/templates/settings.html
index 3b04eb13..4f261d77 100644
--- a/internal/equipo/templates/settings.html
+++ b/internal/equipo/templates/settings.html
@@ -9,7 +9,7 @@
<label>{{copy "account.label"}}<input rst-input name="label" value="{{.Account.Label}}" required></label><button rst-btn type="submit">{{copy "form.save"}}</button></form>{{end}}</section>{{end}}
{{if .Owner}}<section equipo-card><h2>{{copy "account.add"}}</h2><form method="post" action="/accounts" equipo-form>
<input type="hidden" name="id" value="0"><input type="hidden" name="revision" value="0"><label>{{copy "account.label"}}<input rst-input name="label" required></label><button rst-btn="primary" type="submit">{{copy "form.save"}}</button></form></section>{{end}}
-<section equipo-card><h2>{{copy "budget.title"}}</h2>
+<section id="budgets" equipo-card><h2>{{copy "budget.title"}}</h2>
{{if .Owner}}<p>{{copy "budget.note"}}</p><form method="post" action="/team/budgets" equipo-form><input type="hidden" name="revision" value="{{.Budget.Revision}}">
{{range .BudgetForms}}<fieldset><legend>{{.Name}}</legend>{{range .Fields}}<label>{{copy .CopyKey}}<input rst-input name="{{.Name}}" type="number" min="1" step="1" value="{{.Value}}"></label>{{end}}</fieldset>{{end}}
<button rst-btn="primary" type="submit">{{copy "form.save"}}</button></form>
diff --git a/internal/equipotest/optimistic_browser_test.go b/internal/equipotest/optimistic_browser_test.go
new file mode 100644
index 00000000..7e5104a4
--- /dev/null
+++ b/internal/equipotest/optimistic_browser_test.go
@@ -0,0 +1,83 @@
+//go:build browser
+
+package equipotest
+
+import (
+ "net/http"
+ "testing"
+
+ "amadan.net/oficina/equipo/internal/browsertest"
+ "amadan.net/oficina/equipo/internal/equipo"
+ "amadan.net/rastrillo/rastrillo/harness"
+ "github.com/chromedp/chromedp"
+ "github.com/chromedp/chromedp/kb"
+)
+
+func TestOptimisticChat(t *testing.T) {
+ d, _ := foundationDB(t)
+ mailer := &capturingMailer{}
+ var router http.Handler
+ rig := harness.New(t, func(origin string) http.Handler {
+ cfg := testConfig(origin)
+ cfg.AlwaysOn = true
+ var err error
+ router, err = equipo.Router(d, cfg, mailer, nil)
+ executionMust(t, err)
+ return equipo.Mux(router)
+ })
+ t.Cleanup(func() { equipo.CloseLive(router) })
+ browserSignin(t, rig, mailer)
+ rig.Run(chromedp.Navigate(rig.Origin + "/conversation"))
+ // Hold only the POST. Live refreshes still race with the optimistic bubble.
+ harness.Evaluate[bool](rig, `(()=>{window.beforeSend=document.getElementById('conversation-feed').cloneNode(true);const real=window.realFetch=window.fetch;window.posts=0;window.fetch=(u,o)=>{if(o&&o.method==='POST'){window.posts++;window.postedAt=performance.now();return new Promise((resolve,reject)=>{window.deliver=()=>real(u,o).then(resolve,reject);window.fail=()=>reject(new TypeError('offline'))})}return real(u,o)};return true})()`)
+ check := func(expression, why string) {
+ t.Helper()
+ if !harness.Evaluate[bool](rig, expression) {
+ t.Fatal(why)
+ }
+ }
+ rig.Run(chromedp.SendKeys(chromedp.CSS(`#chat-body`), "Immediate <safe> message"), chromedp.KeyEvent(kb.Enter))
+ check(`document.querySelector('[data-pending]').textContent.includes('Immediate <safe> message')`, "sent message missing before HTTP completes")
+ check(`document.querySelector('[data-pending] [equipo-send-status]').textContent===''`, "sending state appeared before 500 ms")
+ rig.Run(browsertest.Wait(`performance.now()-window.postedAt>=250`))
+ check(`document.querySelector('[data-pending] [equipo-send-status]').textContent===''`, "sending state appeared within 250 ms")
+ rig.Run(browsertest.Wait(`document.querySelector('[data-pending] [equipo-send-status]').textContent.length>0`))
+ harness.Evaluate[bool](rig, `(()=>{const feed=document.getElementById('conversation-feed');const copy=feed.cloneNode(true);copy.querySelectorAll('[data-pending]').forEach(n=>n.remove());feed.replaceWith(copy);return true})()`)
+ rig.Run(browsertest.Wait(`document.querySelectorAll('[data-pending]').length===1`))
+ harness.Evaluate[bool](rig, `(window.fail(),true)`)
+ rig.Run(browsertest.Wait(`!!document.querySelector('[data-pending] button')`))
+ rig.Run(chromedp.Click(chromedp.CSS(`[data-pending] button`)))
+ check(`window.posts===2`, "retry did not post")
+ harness.Evaluate[bool](rig, `(window.deliver(),true)`)
+ rig.Run(browsertest.Wait(`!document.querySelector('[data-pending]') && document.querySelector('[data-message] [equipo-message-body]').textContent==='Immediate <safe> message'`))
+ check(`document.querySelectorAll('[data-message]').length>=1 && !document.querySelector('safe')`, "message HTML was interpreted")
+ if scalar(t, d, "SELECT count(*) FROM conversation_messages WHERE body='Immediate <safe> message'") != 1 {
+ t.Fatal("retry duplicated message")
+ }
+ // A live GET started before the send can arrive after its POST response.
+ harness.Evaluate[bool](rig, `(document.getElementById('conversation-feed').replaceWith(window.beforeSend),true)`)
+ rig.Run(browsertest.Wait(`Array.from(document.querySelectorAll('[data-message] [equipo-message-body]')).filter(n=>n.textContent==='Immediate <safe> message').length===1`))
+ // Identical text in separate sends must keep separate identities.
+ harness.Evaluate[bool](rig, `(()=>{const real=window.fetch;window.fetch=(u,o)=>real(u,o);return true})()`)
+ rig.Run(chromedp.SendKeys(chromedp.CSS(`#chat-body`), "Same body"), chromedp.KeyEvent(kb.Enter))
+ harness.Evaluate[bool](rig, `(window.deliver(),true)`)
+ rig.Run(browsertest.Wait(`!document.querySelector('[data-pending]')`))
+ rig.Run(chromedp.SendKeys(chromedp.CSS(`#chat-body`), "Same body"), chromedp.KeyEvent(kb.Enter))
+ harness.Evaluate[bool](rig, `(window.deliver(),true)`)
+ rig.Run(browsertest.Wait(`!document.querySelector('[data-pending]')`))
+ if scalar(t, d, "SELECT count(*) FROM conversation_messages WHERE body='Same body'") != 2 {
+ t.Fatal("identical messages were conflated")
+ }
+ // A committed write with a lost response retries the original request ID.
+ harness.Evaluate[bool](rig, `(()=>{let drop=true;window.fetch=(u,o)=>{if(o&&o.method==='POST')return window.realFetch(u,o).then(r=>{if(drop){drop=false;throw new TypeError('lost response')}return r});if(o&&o.headers&&new Headers(o.headers).has('Rastrillo-Fragment'))return new Promise(()=>{});return window.realFetch(u,o)};return true})()`)
+ rig.Run(chromedp.SendKeys(chromedp.CSS("#chat-body"), "Committed once"), chromedp.KeyEvent(kb.Enter))
+ rig.Run(browsertest.Wait(`!!document.querySelector('[data-pending] button')`))
+ if scalar(t, d, "SELECT count(*) FROM conversation_messages WHERE body='Committed once'") != 1 {
+ t.Fatal("lost-response control did not commit")
+ }
+ rig.Run(chromedp.Click(chromedp.CSS(`[data-pending] button`)), browsertest.Wait(`!document.querySelector('[data-pending]')`))
+ if scalar(t, d, "SELECT count(*) FROM conversation_messages WHERE body='Committed once'") != 1 {
+ t.Fatal("lost-response retry duplicated message")
+ }
+
+}
diff --git a/internal/plan3test/coordinator_claim_gap_test.go b/internal/plan3test/coordinator_claim_gap_test.go
new file mode 100644
index 00000000..f24c6f3f
--- /dev/null
+++ b/internal/plan3test/coordinator_claim_gap_test.go
@@ -0,0 +1,22 @@
+package plan3test
+
+import (
+ "errors"
+ "testing"
+
+ "amadan.net/oficina/equipo/internal/equipo"
+)
+
+func TestCoordinatorRejectsUnavailableBinding(t *testing.T) {
+ f, _, p, b := coordinatorFixture(t)
+ f.exec(t, `UPDATE connections SET reports_json=json_set(reports_json,'$[0].Available',json('false'),'$[0].ReadIsolation',json('false')) WHERE id='codex'`)
+ _, err := f.Store.SaveCoordinatorBinding(ctx, owner, p.RunnerID, "codex", equipo.Mutation{RequestID: "offline-binding", Revision: b.Revision})
+ if !errors.Is(err, equipo.ErrUnavailable) {
+ t.Fatalf("unavailable binding accepted: %v", err)
+ }
+ current, err := f.Store.Coordinator(ctx, owner)
+ must(t, err)
+ if current.ConnectionID != b.ConnectionID || current.Generation != b.Generation {
+ t.Fatal("failed selection changed binding")
+ }
+}
diff --git a/internal/runner/containment/linux_test.go b/internal/runner/containment/linux_test.go
index 91077121..7ed0fc3e 100644
--- a/internal/runner/containment/linux_test.go
+++ b/internal/runner/containment/linux_test.go
@@ -125,6 +125,9 @@ func alive(t *testing.T, fd int) {
}
p := []unix.PollFd{{Fd: int32(fd), Events: unix.POLLIN}}
n, e := unix.Poll(p, 0)
+ for e == unix.EINTR {
+ n, e = unix.Poll(p, 0)
+ }
if e != nil || n != 0 {
t.Fatalf("owned unrelated control exited: %d %v", n, e)
}
diff --git a/internal/runner/transporttest/coordinator_contract_test.go b/internal/runner/transporttest/coordinator_contract_test.go
new file mode 100644
index 00000000..09b112f8
--- /dev/null
+++ b/internal/runner/transporttest/coordinator_contract_test.go
@@ -0,0 +1,124 @@
+package transporttest
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "io"
+ "net/http"
+ "net/http/httptest"
+ "path/filepath"
+ "strings"
+ "testing"
+ "time"
+
+ "amadan.net/oficina/equipo/internal/coordinatorcontract"
+ "amadan.net/oficina/equipo/internal/runner"
+ "amadan.net/oficina/equipo/internal/runner/heartbeat"
+ "amadan.net/oficina/equipo/internal/runnerproto"
+)
+
+func TestCoordinatorRecordedRunnerContract(t *testing.T) {
+ for _, name := range []string{"heartbeat", "poll", "claim", "delivery", "reply"} {
+ t.Run(name, func(t *testing.T) {
+ p, err := coordinatorcontract.Load(name)
+ if err != nil {
+ t.Fatal(err)
+ }
+ called := false
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ called = true
+ if r.URL.Path != p.Path || r.Method != "POST" || r.Header.Get("Authorization") != "Bearer fixture" {
+ t.Errorf("request routing drift: %s %s", r.Method, r.URL.Path)
+ }
+ body, err := io.ReadAll(r.Body)
+ if err != nil {
+ t.Error(err)
+ }
+ want := p.Request
+ if name == "heartbeat" {
+ var got, expected map[string]any
+ json.Unmarshal(body, &got)
+ json.Unmarshal(want, &expected)
+ if got["request_id"] == "" {
+ t.Error("heartbeat has no request ID")
+ }
+ got["request_id"] = expected["request_id"]
+ expected["repositories"] = []string{}
+ want, _ = json.Marshal(expected)
+ body, _ = json.Marshal(got)
+ }
+ if coordinatorcontract.Canonical(body) != coordinatorcontract.Canonical(want) {
+ t.Error("runner request differs from recorded instance contract")
+ }
+ w.Header().Set("Content-Type", "application/json")
+ w.Write(p.Response)
+ }))
+ defer server.Close()
+ j, err := runner.OpenJournal(context.Background(), filepath.Join(t.TempDir(), "runner", "journal.db"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer j.Close()
+ api, err := runner.NewHTTPInstance(server.URL+"/api/runner/v2", j, runnerproto.RunnerCredential{Token: "fixture", ExpiresAt: time.Now().Add(time.Hour)})
+ if err != nil {
+ t.Fatal(err)
+ }
+ var out any
+ if name == "heartbeat" {
+ var q runnerproto.HeartbeatRequest
+ if err = runnerproto.DecodeLimit(bytes.NewReader(p.Request), &q, 3<<20); err != nil {
+ t.Fatal(err)
+ }
+ var reports []runnerproto.ConnectionReport
+ if err = runnerproto.DecodeLimit(bytes.NewReader(q.Reports), &reports, 3<<20); err != nil {
+ t.Fatal(err)
+ }
+ built, buildErr := heartbeat.Request(reports, func() ([]string, error) { return q.Repositories, nil })
+ if buildErr != nil {
+ t.Fatal(buildErr)
+ }
+ built.RequestID = q.RequestID
+ raw, _ := runnerproto.Marshal(built)
+ if coordinatorcontract.Canonical(raw) != coordinatorcontract.Canonical(p.Request) {
+ t.Fatal("heartbeat builder drift")
+ }
+ err = api.Heartbeat(context.Background(), reports)
+ } else {
+ var q runnerproto.CoordinatorRequest
+ if err = runnerproto.DecodeLimit(bytes.NewReader(p.Request), &q, 3<<20); err != nil {
+ t.Fatal(err)
+ }
+ switch name {
+ case "poll":
+ out = &[]runnerproto.CoordinatorTurn{}
+ case "claim":
+ out = &runnerproto.CoordinatorClaim{}
+ case "reply":
+ out = &runnerproto.CoordinatorToolResult{}
+ }
+ op := strings.TrimPrefix(p.Path, "/api/runner/v2/coordinator/")
+ err = api.CoordinatorCall(context.Background(), op, q, out)
+ }
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !called {
+ t.Fatal("no HTTP request")
+ }
+ if out != nil {
+ var envelope struct {
+ Result json.RawMessage `json:"result"`
+ }
+ json.Unmarshal(p.Response, &envelope)
+ raw, err := runnerproto.Marshal(out)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if coordinatorcontract.Canonical(raw) != coordinatorcontract.Canonical(envelope.Result) {
+ t.Fatal("runner decoded response drift")
+ }
+ }
+ })
+ }
+}
diff --git a/internal/runnerproto/coordinator_contract_test.go b/internal/runnerproto/coordinator_contract_test.go
new file mode 100644
index 00000000..06fc3ecf
--- /dev/null
+++ b/internal/runnerproto/coordinator_contract_test.go
@@ -0,0 +1,124 @@
+package runnerproto_test
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "testing"
+
+ "amadan.net/oficina/equipo/internal/coordinatorcontract"
+ "amadan.net/oficina/equipo/internal/runnerproto"
+)
+
+type recordedExecution struct {
+ runnerproto.ExecutionAPI
+ t *testing.T
+ request runnerproto.CoordinatorRequest
+ result json.RawMessage
+ called bool
+}
+
+func (s *recordedExecution) PollCoordinator(context.Context, runnerproto.RunnerPrincipal) (v []runnerproto.CoordinatorTurn, err error) {
+ s.called = true
+ err = runnerproto.DecodeLimit(bytes.NewReader(s.result), &v, 3<<20)
+ return
+}
+func (s *recordedExecution) ClaimCoordinator(_ context.Context, _ runnerproto.RunnerPrincipal, id string, rev int64) (v runnerproto.CoordinatorClaim, err error) {
+ s.called = true
+ if id != s.request.TurnID || rev != s.request.Revision {
+ s.t.Error("claim request drift")
+ }
+ err = runnerproto.DecodeLimit(bytes.NewReader(s.result), &v, 3<<20)
+ return
+}
+func (s *recordedExecution) CoordinatorEvent(_ context.Context, _ runnerproto.RunnerPrincipal, c runnerproto.CoordinatorClaim, e runnerproto.Event) error {
+ s.called = true
+ s.equal(c, s.request.Claim)
+ s.equal(e, s.request.Event)
+ return nil
+}
+func (s *recordedExecution) CallCoordinatorTool(_ context.Context, _ runnerproto.RunnerPrincipal, c runnerproto.CoordinatorClaim, q runnerproto.CoordinatorToolCall) (v runnerproto.CoordinatorToolResult, err error) {
+ s.called = true
+ s.equal(c, s.request.Claim)
+ s.equal(q, s.request.ToolCall)
+ err = runnerproto.DecodeLimit(bytes.NewReader(s.result), &v, 3<<20)
+ return
+}
+func (s *recordedExecution) equal(a, b any) {
+ s.t.Helper()
+ x, _ := runnerproto.Marshal(a)
+ y, _ := runnerproto.Marshal(b)
+ if coordinatorcontract.Canonical(x) != coordinatorcontract.Canonical(y) {
+ s.t.Error("handler changed recorded payload")
+ }
+}
+func TestCoordinatorRecordedInstanceContract(t *testing.T) {
+ for _, name := range []string{"heartbeat", "poll", "claim", "delivery", "reply"} {
+ t.Run(name, func(t *testing.T) {
+ p, err := coordinatorcontract.Load(name)
+ if err != nil {
+ t.Fatal(err)
+ }
+ var envelope struct {
+ Result json.RawMessage `json:"result"`
+ }
+ if err = json.Unmarshal(p.Response, &envelope); err != nil {
+ t.Fatal(err)
+ }
+ e := &recordedExecution{t: t, result: envelope.Result}
+ if name != "heartbeat" {
+ if err = runnerproto.DecodeLimit(bytes.NewReader(p.Request), &e.request, 3<<20); err != nil {
+ t.Fatal(err)
+ }
+ }
+ h := runnerproto.Handler{Execution: func() runnerproto.ExecutionAPI { return e }, AuthenticateRunner: func(_ context.Context, token string) (runnerproto.RunnerPrincipal, error) {
+ if token != "fixture" {
+ t.Fatal("bearer changed")
+ }
+ return runnerproto.RunnerPrincipal{Person: "owner@example.test"}, nil
+ }, ReportConnections: func(_ context.Context, _ runnerproto.RunnerPrincipal, reports []runnerproto.ConnectionReport) error {
+ e.called = true
+ var q runnerproto.HeartbeatRequest
+ runnerproto.DecodeLimit(bytes.NewReader(p.Request), &q, 3<<20)
+ raw, _ := runnerproto.Marshal(reports)
+ if coordinatorcontract.Canonical(raw) != coordinatorcontract.Canonical(q.Reports) {
+ t.Error("heartbeat payload drift")
+ }
+ return nil
+ }, JSON: func(w http.ResponseWriter, status int, v any) {
+ raw, err := runnerproto.Marshal(v)
+ if err != nil {
+ t.Error(err)
+ }
+ w.WriteHeader(status)
+ w.Write(raw)
+ }, Failure: func(w http.ResponseWriter, err error) { http.Error(w, "refused", http.StatusUnprocessableEntity) }, Invalid: runnerproto.ErrInvalid, Forbidden: runnerproto.ErrInvalid, Unavailable: runnerproto.ErrInvalid}
+ req := httptest.NewRequest("POST", strings.TrimPrefix(p.Path, "/api/runner/v2"), bytes.NewReader(p.Request))
+ req.Header.Set("Authorization", "Bearer fixture")
+ req.Header.Set("Content-Type", "application/json")
+ w := httptest.NewRecorder()
+ h.Router().ServeHTTP(w, req)
+ if !e.called || w.Code != 200 || coordinatorcontract.Canonical(w.Body.Bytes()) != coordinatorcontract.Canonical(p.Response) {
+ t.Fatalf("instance response contract drift: HTTP %d, called=%v", w.Code, e.called)
+ }
+ // Recorded coordinator requests must never lose their capability guard.
+ if name != "heartbeat" {
+ e.called = false
+ q := e.request
+ q.Capabilities = nil
+ raw, _ := runnerproto.Marshal(q)
+ req = httptest.NewRequest("POST", strings.TrimPrefix(p.Path, "/api/runner/v2"), bytes.NewReader(raw))
+ req.Header.Set("Authorization", "Bearer fixture")
+ req.Header.Set("Content-Type", "application/json")
+ w = httptest.NewRecorder()
+ h.Router().ServeHTTP(w, req)
+ if e.called || w.Code == 200 {
+ t.Fatal("missing coordinator capability accepted")
+ }
+ }
+ })
+ }
+}
diff --git a/scripts/runner-reference-allowlist.json b/scripts/runner-reference-allowlist.json
index 56363b33..6e44b4b9 100644
--- a/scripts/runner-reference-allowlist.json
+++ b/scripts/runner-reference-allowlist.json
@@ -9889,5 +9889,131 @@
"match": "Trial",
"count": 1,
"reason": "Discovery regression requires the obsolete trial flag to remain false for certified direct connections."
+ },
+ {
+ "path": "docs/superpowers/plans/CODEX-BRIEF-e2e-coordinator.md",
+ "line_sha256": "065ba95afd39482e5297f4de65d2a902036b04ab750408ad58f2034b72b47743",
+ "match": "equipo-runner",
+ "count": 1,
+ "reason": "Coordinator controller brief or report referring to the retained runner executable and service."
+ },
+ {
+ "path": "internal/coordinatorcontract/testdata/heartbeat.json",
+ "line_sha256": "79cde92bd2706c6935da7956fa02a8b8c117059f99ef297aec7e64282a1d2440",
+ "match": "paseo",
+ "count": 1,
+ "reason": "Inert recorded coordinator HTTP fixture retaining the protocol trial_ready field; no execution authority."
+ },
+ {
+ "path": "internal/coordinatorcontract/testdata/heartbeat.json",
+ "line_sha256": "6698e0de46f1fe2b1e00adeaa540583d68d368d356938950b32ebbea291b3e6f",
+ "match": "trial",
+ "count": 1,
+ "reason": "Inert recorded coordinator HTTP fixture retaining the protocol trial_ready field; no execution authority."
+ },
+ {
+ "path": "internal/e2elivetest/e2e_live_helpers_test.go",
+ "line_sha256": "1356ea4ea54c3e49b7e401e888c6c56bb26e46f3a644ef5b861a44174873c18e",
+ "match": "equipo-runner",
+ "count": 1,
+ "reason": "Opt-in local end-to-end harness builds and runs the retained production runner executable in scratch storage."
+ },
+ {
+ "path": "internal/e2elivetest/e2e_live_test.go",
+ "line_sha256": "42adba2c78a77d30fa7c67ec13012b0e0326394b6acbb729b5ec11edd483c734",
+ "match": "equipo-runner",
+ "count": 1,
+ "reason": "Opt-in local end-to-end harness builds and runs the retained production runner executable in scratch storage."
+ },
+ {
+ "path": "internal/e2elivetest/e2e_live_test.go",
+ "line_sha256": "f11c813f4b7dc3f2f2bc3be850195594d64359b15d6394f17cd10dc9a7779ef8",
+ "match": "equipo-runner",
+ "count": 1,
+ "reason": "Opt-in local end-to-end harness builds and runs the retained production runner executable in scratch storage."
+ },
+ {
+ "path": "internal/equipo/static/chat-send.js",
+ "line_sha256": "24e6c89454841a23dce8540bb6058174baf37761b31bfb8d95a07aeab78ef5f1",
+ "match": "node",
+ "count": 1,
+ "reason": "Browser DOM node operations in the optimistic chat implementation or its browser test; no external runtime."
+ },
+ {
+ "path": "internal/equipo/static/chat-send.js",
+ "line_sha256": "58ed4c47e6ec831a3dcf8bce3eee7308489899547a61308010aa5165dd23edce",
+ "match": "node",
+ "count": 2,
+ "reason": "Browser DOM node operations in the optimistic chat implementation or its browser test; no external runtime."
+ },
+ {
+ "path": "internal/equipo/static/chat-send.js",
+ "line_sha256": "d37de8aa3fa23812818811d4cf2465b473eba7d5b3a4af8799553bfb3bb35349",
+ "match": "node",
+ "count": 1,
+ "reason": "Browser DOM node operations in the optimistic chat implementation or its browser test; no external runtime."
+ },
+ {
+ "path": "internal/equipo/static/chat-send.js",
+ "line_sha256": "bbcfe2aa2b9814b7b6b220738f48b52ed707f1eb1994194cc11762daaa4268af",
+ "match": "node",
+ "count": 1,
+ "reason": "Browser DOM node operations in the optimistic chat implementation or its browser test; no external runtime."
+ },
+ {
+ "path": "internal/equipo/static/chat-send.js",
+ "line_sha256": "d76421c61444a635110e62909c277e02effa7c6684d735fe0439361655a2634d",
+ "match": "node",
+ "count": 1,
+ "reason": "Browser DOM node operations in the optimistic chat implementation or its browser test; no external runtime."
+ },
+ {
+ "path": "internal/equipo/static/chat-send.js",
+ "line_sha256": "ca855e8941e0b90da55161e55a0e2195745739a216a14b552d701feb8ff4f746",
+ "match": "node",
+ "count": 1,
+ "reason": "Browser DOM node operations in the optimistic chat implementation or its browser test; no external runtime."
+ },
+ {
+ "path": "internal/equipo/static/chat-send.js",
+ "line_sha256": "7c18771334b0feb603e194783b1ea81483be004887cb73938d8d28d04fbadfbe",
+ "match": "node",
+ "count": 2,
+ "reason": "Browser DOM node operations in the optimistic chat implementation or its browser test; no external runtime."
+ },
+ {
+ "path": "internal/equipotest/optimistic_browser_test.go",
+ "line_sha256": "f5292f806516e2cc91a49573249aa237210f4035e88b419c1bb2e579e706070e",
+ "match": "Node",
+ "count": 1,
+ "reason": "Browser DOM node operations in the optimistic chat implementation or its browser test; no external runtime."
+ },
+ {
+ "path": "docs/superpowers/plans/CONTROLLER-REPORT-e2e-coordinator.md",
+ "line_sha256": "012afb80e4abcdf1f01d242b8b6fae41764f17bbb27a861aab11138b8f733dba",
+ "match": "equipo-runner",
+ "count": 1,
+ "reason": "Controller report references the retained runner service configuration; no execution authority."
+ },
+ {
+ "path": "internal/equipo/static/chat-send.js",
+ "line_sha256": "cd6fd4a9392f06fb3b99ab285f320a0d8c73415f42a946e1fabfd2a4a278a954",
+ "match": "node",
+ "count": 1,
+ "reason": "Browser DOM node operations in optimistic chat or its tests; no external runtime."
+ },
+ {
+ "path": "internal/equipo/static/chat-send.js",
+ "line_sha256": "cfb3324b6af27db9002195abd3dbb53e648acfb4867a02c57e49d790616500c7",
+ "match": "node",
+ "count": 1,
+ "reason": "Browser DOM node operations in optimistic chat or its tests; no external runtime."
+ },
+ {
+ "path": "internal/equipotest/optimistic_browser_test.go",
+ "line_sha256": "306c966eddd03b346567cda84dfc3c6de3c202b353dcec8c7fe78d5c9b9eff2c",
+ "match": "Node",
+ "count": 1,
+ "reason": "Browser DOM node operations in optimistic chat or its tests; no external runtime."
}
]