Make coordinator setup and provider logins self-healing
Co-Authored-By: Astra <noreply@openai.com>
63 files changed,
+1,225
−196
Makefile+1 −0docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md+5 −0docs/superpowers/plans/CONTROLLER-REPORT-self-heal.md+167 −0internal/agentsetuptest/autobind_test.go+17 −6internal/agentsetuptest/flow_test.go+1 −1internal/coordinator/self_heal_test.go+15 −0internal/coordinator/tools.go+4 −0internal/coordinator/tools_test.go+1 −1internal/coordinator/types.go+3 −0internal/e2elivetest/e2e_live_test.go+3 −3internal/e2elivetest/self_heal_browser_test.go+72 −0internal/e2elivetest/self_heal_diagnostics_test.go+44 −0internal/equipo/conversation/chatstate/cards.go+15 −1internal/equipo/conversation/coordinator_fallback.go+25 −13internal/equipo/conversation/coordinator_poll.go+5 −14internal/equipo/conversation/coordinator_setup.go+16 −31internal/equipo/conversation/self_heal_notes.go+13 −0internal/equipo/conversation/settings.go+1 −13internal/equipo/conversation/store.go+1 −3internal/equipo/conversation/tools.go+14 −0internal/equipo/copy.go+15 −12internal/equipo/ownermode/login_notes.go+50 −0internal/equipo/ownermode/ranking.go+38 −0internal/equipo/ownermode/self_heal_status.go+62 −0internal/equipo/task_prepare.go+1 −1internal/equipo/tasks.go+0 −3internal/equipo/team/budget.go+1 −4internal/equipo/team/jobs.go+2 −2internal/equipo/team/periodbudget.go+11 −8internal/equipo/team/periodbudget_test.go+1 −1internal/equipo/team/self_heal_test.go+19 −0internal/equipo/templates/conversation_card.html+1 −1internal/equipo/templates/coordinator.html+2 −2internal/ownermodetest/self_heal_test.go+104 −0internal/plan3test/chat_feel_fixture.go+2 −2internal/plan3test/conversation_browser_test.go+3 −2internal/plan3test/conversation_forms_test.go+4 −4internal/plan3test/conversation_test.go+6 −6internal/plan3test/coordinator_continuity_test.go+2 −2internal/plan3test/owner_mode_fixture.go+6 −6internal/plan3test/self_heal_fixture.go+8 −0internal/plan3test/self_heal_test.go+101 −0internal/release/manifest.json+2 −2internal/runner/certification_inputs.go+2 −1internal/runner/certified/discovery.go+1 −1internal/runner/certified/discoverytest/connection_available_test.go+2 −2internal/runner/certified/owner.go+7 −0internal/runner/certified_network_test.go+5 −4internal/runner/connections.go+2 −18internal/runner/diagnostics.go+1 −1internal/runner/provider/accounts.go+30 −1internal/runner/provider/actions.go+1 −1internal/runner/provider/login.go+17 −0internal/runner/provider/login_probe.go+54 −5internal/runner/provider/refresh_cli_test.go+97 −0internal/runner/provider/source_refresh_test.go+85 −0internal/runner/residual_outcome_test.go+1 −1internal/runner/runtime_direct.go+11 −8internal/runner/setup/account_login.go+1 −4internal/runner/setup/account_resume.go+1 −4internal/runner/workspace/security_paths.go+20 −0internal/runnerproto/types.go+2 −1scripts/runner-reference-allowlist.json+21 −0
Intent
diff --git a/Makefile b/Makefile| index 2ea9736a..fa90ea52 100644 |
| --- a/Makefile |
| +++ b/Makefile |
| @@ -185,4 +185,5 @@ release-runner: copy-release-check direct-release-check |
| .PHONY: e2e-live |
| e2e-live: |
| + CGO_ENABLED=0 go test ./internal/runner/provider -run '^Test(Refresh|SourceRefresh)' -count=1 |
| EQUIPO_E2E_LIVE=1 go test -tags e2elive,browser ./internal/e2elivetest -run '^TestCoordinatorE2ELive$$' -count=1 -timeout=10m -v |
diff --git a/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md b/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md| index fa864bb0..246aefe1 100644 |
| --- a/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md |
| +++ b/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md |
| @@ -5199,6 +5199,11 @@ records remain unchanged. |
| | `isolation.owner_mode` | owner mode | Owner mode | Runtime; COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context) | |
| | `connections.owner_mode` | Your runner uses the sandbox without requiring an exact policy certificate for your work. | Owner mode | Runtime; COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context) | |
| | `coordinator.admission_denied` | Your coordinator cannot start work yet. Check the team settings. | Owner mode | Runtime; COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context) | |
| +| `coordinator.login_required` | %s needs a new sign-in. Run this on your runner: %s | Self-healing coordinator | COPY REVIEW REQUIRED | |
| +| `coordinator.runner_required` | Add your machine in Connections, then run equipo-runner enrol on that machine. | Self-healing coordinator | COPY REVIEW REQUIRED | |
| +| `coordinator.tool.equipo_status` | Read your runner, connection availability, budgets and project setup. No secrets are included. | Self-healing coordinator | COPY REVIEW REQUIRED | |
| +| `coordinator.automatic` | Equipo chooses a healthy connection from your runner and switches when it is busy or unavailable. | Self-healing coordinator | COPY REVIEW REQUIRED | |
| +| `coordinator.waiting_connection_label` | Waiting for %s… | Self-healing coordinator | COPY REVIEW REQUIRED | |
| ## Task 21 |
diff --git a/docs/superpowers/plans/CONTROLLER-REPORT-self-heal.md b/docs/superpowers/plans/CONTROLLER-REPORT-self-heal.md| new file mode 100644 |
| index 00000000..e86a19c9 |
| --- /dev/null |
| +++ b/docs/superpowers/plans/CONTROLLER-REPORT-self-heal.md |
| @@ -0,0 +1,167 @@ |
| +# Self-healing coordinator |
| + |
| +Implemented on `self-heal`, from the dispatched brief commit `cac8b11` |
| +(main base `80c15d0`). Commit only; no push, merge or deployment. |
| +New runtime copy is individually marked `COPY REVIEW PENDING` in |
| +`internal/equipo/copy.go` and listed in the existing copy inventory. |
| +No copy-review server was started. README prose is unchanged. |
| + |
| +## Changes |
| + |
| +The runner runs the pinned official CLI in the dedicated source home while |
| +holding the existing directory lock, before staging any runtime login. |
| +Claude 2.1.312 uses `auth status --json`; its startup performs and awaits |
| +native refresh. Codex 0.165.0 uses app-server `account/read` with |
| +`refreshToken:true`, after initialization. Neither path starts a model turn. |
| +Equipo consumes account metadata only and does not extract refresh tokens. |
| +The executable digests are checked before maintenance. |
| + |
| +Saved-account setup and generic discovery also probe the locked source home. |
| +An unconfined native CLI probe rejects a staged binding. This closes the setup |
| +path as well as the dispatch path. |
| + |
| +The source lock stays held throughout the attempt, so maintenance cannot |
| +run alongside a turn. Runtime copies expire after 25 minutes, which covers |
| +the existing 20-minute coordinator attempt limit. A production lease cannot |
| +commit runtime credentials back to its source. Runtime network policy still |
| +excludes the refresh hosts; Claude refresh uses platform.claude.com and Codex |
| +uses auth.openai.com. Owner mode uses the same isolation and needs no new |
| +certification. Certified mode continues to enforce its policy hashes. |
| + |
| +Temporary maintenance failures remain retryable. A native missing-login result |
| +or a recognized terminal refresh rejection produces `account.sign_in_again`. |
| +That connection gets one conversation note containing its exact command, |
| +including the dedicated-home environment, pinned executable and directory lock. |
| +Repeated polls do not repeat that note. No credentials are included in reports. |
| + |
| +Coordinator settings now show the current connection and the automatic-selection |
| +reason. The binding picker and its Save/Reset controls are gone; the obsolete |
| +binding form action is rejected. Recovery reset actions remain available for |
| +uncertain work. On each new message and poll, selection prefers a currently |
| +healthy report, then fewer active tasks, then the latest report. Only the |
| +person's own enrolled runners qualify. An admitted attempt with pending |
| +containment cannot be moved or cancelled by automatic selection. |
| + |
| +Projects without an explicit budget inherit the team ceiling. Job creation, |
| +plan admission, reservation headroom, usage reads and bug preparation agree |
| +on this rule. Explicit project caps and aggregate team caps still apply. |
| +Temporary connection and admission waits stay in the thinking bubble, name |
| +the connection and retry on polling. Missing bindings are retried when a |
| +runner becomes available. Routine fallback no longer adds system notes. |
| + |
| +`equipo_status` accepts no caller-supplied scope. The normal claim, handle and |
| +current-roster checks apply before it returns the person's runners and |
| +connections, team budgets, coordinator usage and permitted projects. It excludes |
| +credentials, home paths, machine keys and other people's connections. Stale |
| +heartbeats are reported as unavailable. A deleted selected connection still |
| +renders a waiting conversation; database failures remain errors. |
| + |
| +## Verification |
| + |
| +Behavioral failures observed before implementation: |
| + |
| +- `CGO_ENABLED=0 go test ./internal/equipo/team -run TestSelfHeal -count=1`: |
| + failed with `job needs configured project`; passed after inheritance. |
| +- `CGO_ENABLED=0 go test ./internal/runner/provider -run TestSourceRefresh -count=1`: |
| + failed because staging retained the old login and failed refresh still staged. |
| +- `CGO_ENABLED=0 go test ./internal/coordinator -run TestEquipoStatusSchema -count=1`: |
| + rejected the new read-only tool before implementation. |
| +- `CGO_ENABLED=0 go test ./internal/plan3test -run TestSelfHeal -count=1`: |
| + failed for the missing live wait bubble and the remaining picker. |
| +- `CGO_ENABLED=0 go test ./internal/runner/provider -run TestSourceRefreshLease -count=1`: |
| + admitted an expired staged lease before the lifetime guard. |
| +- `CGO_ENABLED=0 go test ./internal/runner/provider -run TestRefreshRevocationCodes -count=1`: |
| + failed to distinguish terminal refresh rejections before classification. |
| +- `CGO_ENABLED=0 go test ./internal/runner/provider -run TestRefreshUsesOfficialCLIWithoutTurn -count=1`: |
| + the added staged-home case failed because an unconfined CLI accepted the copy. |
| +- `CGO_ENABLED=0 go test ./internal/ownermodetest -run TestSelfHealRemovedConnection -count=1`: |
| + returned a not-found error for the waiting conversation before correction. |
| + |
| +Each mutation below was applied alone, tested with `CGO_ENABLED=0 go test` |
| +and `-count=1`, and restored immediately. All eleven tests failed at their |
| +behavior assertion, not at compilation: |
| + |
| +| Broken guard | Package and test | |
| +| --- | --- | |
| +| Skip source refresh | `./internal/runner/provider -run ^TestSourceRefreshBeforeStageUnderLock$` | |
| +| Remove source flock | Same test | |
| +| Ignore changed identity | `./internal/runner/provider -run ^TestSourceRefreshFailureDoesNotStage$` | |
| +| Ignore staged lifetime | `./internal/runner/provider -run ^TestSourceRefreshLeaseExpiresAndCannotWriteBack$` | |
| +| Permit runtime writeback | Same test | |
| +| Send Codex refreshToken:false | `./internal/runner/provider -run ^TestRefreshUsesOfficialCLIWithoutTurn$` | |
| +| Repeat sign-in note | `./internal/plan3test -run ^TestSelfHealRevokedLoginNotifiedOnce$` (subsequently moved to `./internal/ownermodetest`) | |
| +| Prefer the busier connection | `./internal/plan3test -run ^TestSelfHealBusyConnectionFailsOver$` | |
| +| Permit active-turn fallback | `./internal/plan3test -run ^TestSelfHealFailoverDoesNotMoveActiveTurn$`; caught cancellation of the active job | |
| +| Remove the status runner-person filter | `./internal/ownermodetest -run ^TestSelfHealStatusIsScopedAndRevocationApplies$`; caught another person's runner label | |
| +| Treat a stale heartbeat as available | `./internal/ownermodetest -run ^TestSelfHealStatusDoesNotCallStaleReportsAvailable$` | |
| + |
| +Restored targeted tests cover source refresh and CLI failures, picker removal, |
| +status scope and roster revocation, one-time login notices, busy failover, |
| +active-attempt fencing, inherited budgets and project-card-to-work admission. |
| +Existing tests were updated where they required the removed picker, repeated |
| +setup notes, or rejection of an unset project budget. Their authority, |
| +transaction rollback and accounting assertions remain. |
| + |
| +## Live proof |
| + |
| +Only the authorized paul@tito.io `claude-a` home was used. With the production |
| +runner briefly stopped and the source directory exclusively locked, pinned |
| +Claude `auth status --json` exited 0, reported the expected identity, and |
| +changed the credential file's modification time. The proof inspected metadata |
| +only; it did not read, print or copy credential contents. The runner was |
| +restarted immediately. The brief reported this login as expired. The proof used |
| +it unchanged; no credential was edited to manufacture an expiry. Codex refresh |
| +is covered by fake CLI tests; |
| +no live Codex account was used. |
| + |
| +`CGO_ENABLED=0 make e2e-live` passed twice, in 91.8 seconds and 95.6 seconds. |
| +Its fake CLI prerequisites passed too. The final browser run confirmed no |
| +coordinator picker, proposed a project, clicked Set up, then received a second |
| +admitted coordinator reply with `Projects:null` still in the budget record. |
| +The coordinator called `equipo_status` successfully. Each passing run used two |
| +coordinator turns. No specialist model work ran. |
| + |
| +Other live harness attempts consumed five coordinator turns. One stopped on |
| +a browser-helper error. Two encountered the setup card being replaced by a |
| +late live update. One two-turn run created the project but its subsequent |
| +reply became contained and uncertain. That run did not silently redispatch. |
| +The final test waits for containment, opens the settled conversation, and |
| +explicitly requires the reply through `post_message`. Metadata-only failure |
| +diagnostics are now included in the harness. Total live coordinator turns: |
| +nine, below the authorized twenty. The production runner was left active. |
| + |
| +## Final gates and handoff |
| + |
| +The first `CGO_ENABLED=0 make -k ci` completed all lanes. It failed the |
| +reference inventory, size gate and tests that still expected the previous |
| +setup notes, picker and coordinator inventory. It also caught an onboarding |
| +probe error regression and a synthetic-policy test that now crossed the new |
| +executable verification boundary. Targeted checks pass after correction. |
| +The synthetic test now enters the shared policy builder with its synthetic |
| +lease; production still verifies executable digests before source maintenance. |
| +The two changed coordinator inventory hashes remain explicitly uncertified. |
| + |
| +Build, vet, staticcheck, govulncheck, gitleaks, adapter checks, namespace checks, |
| +migration checks and performance passed in that first full run. Local timing |
| +notes reflect shared-machine load; no budget ceilings were raised. The size |
| +gate passes after moving diagnostics and test helpers to their feature packages. |
| +The reference inventory contains three new exact entries, including the |
| +controller's authorization in the original brief. |
| + |
| +Both permitted full reruns passed every gate with exit 0. Exactly three full |
| +`CGO_ENABLED=0 make -k ci` runs were made. The final run tested 41 packages, |
| +with zero failures, then passed adapter, namespace, migration and performance |
| +checks. Cold boot had a 167 ms median against the 500 ms limit. All screen |
| +performance checks passed. |
| + |
| +The final local run reported timing advisories: runner 371.68 s against 330 s, |
| +discovery tests 10.662 s against 10 s, provider 22.654 s against 15 s, Claude |
| +49.786 s against 45 s, and Codex 41.921 s against 35 s. These are advisory |
| +locally but become failures when CI or AMADAN_CI is set. No ceilings were raised. |
| +The last two status mutations were made after the full gate, restored byte for |
| +byte, and followed by passing targeted status and refresh tests. |
| + |
| +Scratch logs and disposable test environments are removed. No review server |
| +or test process remains. The pre-existing production runner is active, as |
| +required. The controller can review and push this local commit; pending copy |
| +still needs its release review. Nothing was pushed, merged or deployed. |
diff --git a/internal/agentsetuptest/autobind_test.go b/internal/agentsetuptest/autobind_test.go| index 46622a77..8d22cdd7 100644 |
| --- a/internal/agentsetuptest/autobind_test.go |
| +++ b/internal/agentsetuptest/autobind_test.go |
| @@ -34,7 +34,13 @@ func TestCoordinatorFailureVisible(t *testing.T) { |
| f.exec(t, "UPDATE coordinator_turns SET state=? WHERE id=?", state, turn.ID) |
| page, err := f.Store.Conversation(ctx, owner, "", 50) |
| must(t, err) |
| - if len(page.Cards) != 1 || page.Cards[0].CopyKey != "coordinator."+state { |
| + visible := len(page.Cards) == 1 |
| + if visible && state == "waiting_connection" { |
| + visible = page.Cards[0].Thinking |
| + } else if visible { |
| + visible = page.Cards[0].CopyKey == "coordinator."+state |
| + } |
| + if !visible { |
| t.Fatal("silent turn", state, page.Cards) |
| } |
| }) |
| @@ -96,8 +102,13 @@ func TestCoordinatorAutoBind(t *testing.T) { |
| must(t, err) |
| page, err := f.Store.Conversation(ctx, owner, "", 50) |
| must(t, err) |
| - if len(page.Messages) != 2 || page.Messages[1].AuthorKind != "system" { |
| - t.Fatal("missing system note", page.Messages) |
| + human := scenario == "foreign" || scenario == "revoked" || scenario == "wrong-runner-owner" || scenario == "connection-revoked" |
| + wantMessages := 1 |
| + if human { |
| + wantMessages = 2 |
| + } |
| + if len(page.Messages) != wantMessages { |
| + t.Fatal("unexpected setup notes", page.Messages) |
| } |
| if scenario != "eligible" && scenario != "deterministic" { |
| if f.count(t, "SELECT count(*) FROM coordinator_bindings") != 0 { |
| @@ -114,7 +125,7 @@ func TestCoordinatorAutoBind(t *testing.T) { |
| if b.ConnectionID != want || b.Person != owner.Address || b.Generation != 1 || f.count(t, "SELECT count(*) FROM coordinator_turns WHERE state='queued'") != 1 { |
| t.Fatal("wrong binding or turn", b) |
| } |
| - if !strings.Contains(page.Messages[1].Body, "Your coordinator uses My Claude.") || f.count(t, "SELECT count(*) FROM audit_events WHERE kind='coordinator.auto_bind' AND actor=?", owner.Address) != 1 { |
| + if f.count(t, "SELECT count(*) FROM audit_events WHERE kind='coordinator.auto_bind' AND actor=?", owner.Address) != 1 { |
| t.Fatal("missing attribution") |
| } |
| }) |
| @@ -191,8 +202,8 @@ func TestCoordinatorExistingOfflineNote(t *testing.T) { |
| must(t, err) |
| page, err := f.Store.Conversation(ctx, owner, "", 50) |
| must(t, err) |
| - if len(page.Messages) != 2 || !strings.Contains(page.Messages[1].Body, "runner") { |
| - t.Fatal("existing offline binding stayed silent", page.Messages) |
| + if len(page.Messages) != 1 { |
| + t.Fatal("temporary offline binding added system note", page.Messages) |
| } |
| after, err := f.Store.Coordinator(ctx, owner) |
| must(t, err) |
diff --git a/internal/agentsetuptest/flow_test.go b/internal/agentsetuptest/flow_test.go| index 22c4a9c8..e19ebb27 100644 |
| --- a/internal/agentsetuptest/flow_test.go |
| +++ b/internal/agentsetuptest/flow_test.go |
| @@ -98,7 +98,7 @@ func TestAgentSetupFakeCLI(t *testing.T) { |
| if message == "What can you work on?" { |
| page, err := f.Store.Conversation(ctx, owner, "", 50) |
| must(t, err) |
| - if len(page.Messages) != 3 || page.Messages[1].AuthorKind != "system" || page.Messages[2].Body != "I can help with your repositories. Tell me what you want fixed." { |
| + if len(page.Messages) != 2 || page.Messages[1].Body != "I can help with your repositories. Tell me what you want fixed." { |
| t.Fatal("first message did not auto-bind and reply", page.Messages) |
| } |
| return |
diff --git a/internal/coordinator/self_heal_test.go b/internal/coordinator/self_heal_test.go| new file mode 100644 |
| index 00000000..9b0dfec3 |
| --- /dev/null |
| +++ b/internal/coordinator/self_heal_test.go |
| @@ -0,0 +1,15 @@ |
| +package coordinator |
| + |
| +import ( |
| + "encoding/json" |
| + "testing" |
| +) |
| + |
| +func TestEquipoStatusSchema(t *testing.T) { |
| + for _, raw := range []string{`{}`, `{"person":"other"}`, `{"runner_id":"other"}`, `{"project_id":1}`} { |
| + _, err := Validate(CoordinatorToolCall{Name: "equipo_status", RequestID: "status", Arguments: json.RawMessage(raw)}) |
| + if (err == nil) != (raw == `{}`) { |
| + t.Fatalf("status scope: %s: %v", raw, err) |
| + } |
| + } |
| +} |
diff --git a/internal/coordinator/tools.go b/internal/coordinator/tools.go| index 294cd289..03e12b55 100644 |
| --- a/internal/coordinator/tools.go |
| +++ b/internal/coordinator/tools.go |
| @@ -14,6 +14,8 @@ import ( |
| func Names() []string { return provider.CoordinatorTools() } |
| func argument(name string) any { |
| switch name { |
| + case "equipo_status": |
| + return &EquipoStatus{} |
| case "read_project": |
| return &ReadProject{} |
| case "read_task": |
| @@ -58,6 +60,8 @@ func Validate(call CoordinatorToolCall) (any, error) { |
| } |
| valid := false |
| switch a := v.(type) { |
| + case *EquipoStatus: |
| + valid = true |
| case *ReadProject: |
| valid = a.ProjectID > 0 |
| case *ReadTask: |
diff --git a/internal/coordinator/tools_test.go b/internal/coordinator/tools_test.go| index bef4af33..3968c1a7 100644 |
| --- a/internal/coordinator/tools_test.go |
| +++ b/internal/coordinator/tools_test.go |
| @@ -7,7 +7,7 @@ import ( |
| ) |
| func TestCoordinatorToolAllowlist(t *testing.T) { |
| - want := []string{"read_project", "read_task", "propose_project", "propose_plan", "ask_person", "route_to_task", "post_message", "suggest_preference", "suggest_specialist", "suggest_playbook"} |
| + want := []string{"equipo_status", "read_project", "read_task", "propose_project", "propose_plan", "ask_person", "route_to_task", "post_message", "suggest_preference", "suggest_specialist", "suggest_playbook"} |
| if !reflect.DeepEqual(Names(), want) { |
| t.Fatal("unexpected tool inventory", Names()) |
| } |
diff --git a/internal/coordinator/types.go b/internal/coordinator/types.go| index 4d626522..18d97749 100644 |
| --- a/internal/coordinator/types.go |
| +++ b/internal/coordinator/types.go |
| @@ -83,3 +83,6 @@ type SuggestDraft struct { |
| SourceMessageIDs []string `json:"source_message_ids"` |
| Draft Draft `json:"draft"` |
| } |
| + |
| +// EquipoStatus accepts no scope supplied by the model. |
| +type EquipoStatus struct{} |
diff --git a/internal/e2elivetest/e2e_live_test.go b/internal/e2elivetest/e2e_live_test.go| index 4fc1046a..6e0fa5e9 100644 |
| --- a/internal/e2elivetest/e2e_live_test.go |
| +++ b/internal/e2elivetest/e2e_live_test.go |
| @@ -28,6 +28,7 @@ func TestCoordinatorE2ELive(t *testing.T) { |
| } |
| ctx := context.Background() |
| root := t.TempDir() |
| + liveSelfHealDiagnostics(t, root) |
| env := liveEnvironment(t, root) |
| stage := "build" |
| check := func(err error) { |
| @@ -143,7 +144,7 @@ func TestCoordinatorE2ELive(t *testing.T) { |
| t.Logf("local turn: state=%s generation=%d sequence=%d pending=%v recent=%v", state, generation, sequence, claim.Context.Pending, claim.Context.Recent) |
| } |
| }) |
| - liveChatFeel(t, c, origin, d, func() { |
| + liveSelfHeal(t, c, origin, d, func() { |
| runnerLog, stopRunner = liveProcess(t, root, env, runnerBin, "run") |
| }) |
| var defaults int |
| @@ -158,8 +159,7 @@ func TestCoordinatorE2ELive(t *testing.T) { |
| t.Fatalf("stage turn budget: got %d claims", turns) |
| } |
| stopRunner() |
| - stage = "local implement branch" |
| - runLiveImplement(t, root, env) |
| + |
| } |
| func runLiveImplement(t *testing.T, root string, env map[string]string) { |
diff --git a/internal/e2elivetest/self_heal_browser_test.go b/internal/e2elivetest/self_heal_browser_test.go| new file mode 100644 |
| index 00000000..bec341c5 |
| --- /dev/null |
| +++ b/internal/e2elivetest/self_heal_browser_test.go |
| @@ -0,0 +1,72 @@ |
| +//go:build e2elive && browser |
| + |
| +package e2elivetest |
| + |
| +import ( |
| + "context" |
| + "net/http" |
| + "net/url" |
| + "testing" |
| + "time" |
| + |
| + "amadan.net/oficina/equipo/internal/browsertest" |
| + "amadan.net/rastrillo/rastrillo/db" |
| + "amadan.net/rastrillo/rastrillo/harness" |
| + "github.com/chromedp/cdproto/cdp" |
| + "github.com/chromedp/cdproto/network" |
| + "github.com/chromedp/chromedp" |
| +) |
| + |
| +func liveSelfHeal(t *testing.T, c *http.Client, origin string, d *db.DB, startRunner func()) { |
| + t.Helper() |
| + rig := harness.New(t, func(string) http.Handler { return http.NotFoundHandler() }) |
| + u, _ := url.Parse(origin) |
| + rig.Run(chromedp.Func(func(ctx context.Context, target *chromedp.Target) error { |
| + cookies := []*network.CookieParam{} |
| + for _, cookie := range c.Jar.Cookies(u) { |
| + cookies = append(cookies, &network.CookieParam{Name: cookie.Name, Value: cookie.Value, URL: origin}) |
| + } |
| + _, err := cdp.Call(ctx, target, network.SetCookies, network.SetCookiesParams{Cookies: cookies}) |
| + return err |
| + }), chromedp.Navigate(origin+"/settings/coordinator"), browsertest.Wait(`!!document.querySelector('h1')`)) |
| + if !harness.Evaluate[bool](rig, `!document.querySelector('[name="connection_id"], [value="bind"], [value="reset"]')`) { |
| + t.Fatal("coordinator picker remains") |
| + } |
| + rig.Run(chromedp.Navigate(origin+"/conversation"), browsertest.Wait(`!!document.querySelector('#composer')`)) |
| + if !harness.Evaluate[bool](rig, `(()=>{const f=document.querySelector('#composer');f.querySelector('textarea').value='Please set up amadan.net/oficina/e2e-unknown-repo. Use propose_project, then post_message asking me to use the setup card. After I accept the card, first call equipo_status, then call post_message with body exactly: Project ready with an inherited team budget. Deliver that reply through post_message, never a direct assistant response. Do not propose a plan or start specialist work.';f.requestSubmit();return !!document.querySelector('[equipo-thinking]')})()`) { |
| + t.Fatal("thinking bubble missing") |
| + } |
| + startRunner() |
| + delivered := func(n int) { |
| + liveWait(t, "self-heal coordinator reply", 150*time.Second, func() bool { |
| + var uncertain int |
| + executionMust(t, d.Writer().QueryRow("SELECT count(*) FROM coordinator_turns WHERE state='uncertain'").Scan(&uncertain)) |
| + if uncertain > 0 { |
| + t.Fatal("coordinator turn became uncertain") |
| + } |
| + var count int |
| + executionMust(t, d.Writer().QueryRow("SELECT count(*) FROM coordinator_turns WHERE state='delivered'").Scan(&count)) |
| + return count == n |
| + }) |
| + } |
| + delivered(1) |
| + liveWait(t, "first turn contained", 30*time.Second, func() bool { |
| + var count int |
| + executionMust(t, d.Writer().QueryRow("SELECT count(*) FROM coordinator_turns t JOIN attempts a ON a.id=t.attempt_id WHERE t.state='delivered' AND a.containment='contained'").Scan(&count)) |
| + return count == 1 |
| + }) |
| + rig.Run(chromedp.Navigate(origin + "/conversation")) |
| + rig.Run(browsertest.Wait(`!!document.querySelector('form[action^="/conversation/projects/"]') && !document.querySelector('ol [equipo-thinking]')`)) |
| + rig.Run(browsertest.Click(`form[action^="/conversation/projects/"] button[value="setup"]`)) |
| + t.Log("project setup card submitted") |
| + delivered(2) |
| + var projects, denied, defaults, statusCalls int |
| + executionMust(t, d.Writer().QueryRow("SELECT count(*) FROM project_proposals WHERE state='created' AND project_id>0").Scan(&projects)) |
| + executionMust(t, d.Writer().QueryRow("SELECT count(*) FROM coordinator_turns WHERE state='admission_denied'").Scan(&denied)) |
| + executionMust(t, d.Writer().QueryRow("SELECT count(*) FROM budget_records WHERE json_extract(config,'$.Projects') IS NULL").Scan(&defaults)) |
| + executionMust(t, d.Writer().QueryRow("SELECT count(*) FROM conversation_requests WHERE operation='coordinator.tool' AND input_hash<>'' AND result LIKE '%coordinator_limits%'").Scan(&statusCalls)) |
| + if projects != 1 || denied != 0 || defaults != 1 || statusCalls < 1 { |
| + t.Fatalf("self heal: projects=%d denied=%d inherited=%d status=%d", projects, denied, defaults, statusCalls) |
| + } |
| + t.Log("no picker; project created by card; subsequent turn admitted with inherited budget; equipo_status used") |
| +} |
diff --git a/internal/e2elivetest/self_heal_diagnostics_test.go b/internal/e2elivetest/self_heal_diagnostics_test.go| new file mode 100644 |
| index 00000000..ca342dab |
| --- /dev/null |
| +++ b/internal/e2elivetest/self_heal_diagnostics_test.go |
| @@ -0,0 +1,44 @@ |
| +//go:build e2elive |
| + |
| +package e2elivetest |
| + |
| +import ( |
| + "database/sql" |
| + "path/filepath" |
| + "testing" |
| +) |
| + |
| +func liveSelfHealDiagnostics(t *testing.T, root string) { |
| + t.Helper() |
| + t.Cleanup(func() { |
| + if !t.Failed() { |
| + return |
| + } |
| + journal, err := sql.Open("sqlite", "file:"+filepath.Join(root, "state", "journal.db")+"?mode=ro") |
| + if err != nil { |
| + return |
| + } |
| + defer journal.Close() |
| + for _, query := range []string{ |
| + `SELECT json_extract(body,'$.Kind'),count(*) FROM direct_events GROUP BY 1`, |
| + `SELECT json_extract(body,'$.type'),json_extract(body,'$.subtype'),json_extract(body,'$.is_error'),json_extract(body,'$.stop_reason') FROM direct_frames WHERE json_extract(body,'$.type')='result'`, |
| + } { |
| + rows, err := journal.Query(query) |
| + if err != nil { |
| + continue |
| + } |
| + columns, _ := rows.Columns() |
| + for rows.Next() { |
| + values := make([]any, len(columns)) |
| + ptrs := make([]any, len(columns)) |
| + for i := range ptrs { |
| + ptrs[i] = &values[i] |
| + } |
| + if rows.Scan(ptrs...) == nil { |
| + t.Log("provider result metadata", values) |
| + } |
| + } |
| + rows.Close() |
| + } |
| + }) |
| +} |
diff --git a/internal/equipo/conversation/chatstate/cards.go b/internal/equipo/conversation/chatstate/cards.go| index ed35916d..66c22219 100644 |
| --- a/internal/equipo/conversation/chatstate/cards.go |
| +++ b/internal/equipo/conversation/chatstate/cards.go |
| @@ -2,11 +2,13 @@ package chatstate |
| import ( |
| "amadan.net/oficina/equipo/internal/equipo/ownermode" |
| + "errors" |
| "gorm.io/gorm" |
| ) |
| type Card struct { |
| - Thinking bool `json:",omitempty"` |
| + Thinking bool `json:",omitempty"` |
| + ConnectionLabel string |
| PartialText string `json:",omitempty"` |
| Sequence int64 `json:"-"` |
| ActionKeys []string `json:",omitempty"` |
| @@ -44,6 +46,18 @@ func Status(tx *gorm.DB, binding, person string, generation int64) ([]Card, erro |
| } |
| queuedSequence = turn.Sequence |
| } |
| + if turn.State == "waiting_connection" || turn.State == "waiting_task" || turn.State == "admission_denied" { |
| + var connection struct{ Label, LocalID string } |
| + if err := tx.Table("connections c").Select("c.label,c.local_id").Joins("JOIN coordinator_bindings b ON b.connection_id=c.id").Where("b.id=? AND c.person=?", binding, person).Take(&connection).Error; err != nil && !errors.Is(err, gorm.ErrRecordNotFound) { |
| + return nil, err |
| + } |
| + label := connection.Label |
| + if label == "" { |
| + label = connection.LocalID |
| + } |
| + cards = append(cards, Card{ID: turn.ID, Kind: "coordinator", ResourceID: turn.ID, Revision: turn.Revision, Thinking: true, ConnectionLabel: label, Sequence: turn.Sequence}) |
| + continue |
| + } |
| state, actions, show, err := ownermode.TurnStatus(tx, turn.State, turn.AttemptID, turn.Claim) |
| if err != nil { |
| return nil, err |
diff --git a/internal/equipo/conversation/coordinator_fallback.go b/internal/equipo/conversation/coordinator_fallback.go| index 5c778857..b1db7d54 100644 |
| --- a/internal/equipo/conversation/coordinator_fallback.go |
| +++ b/internal/equipo/conversation/coordinator_fallback.go |
| @@ -6,11 +6,23 @@ import ( |
| ) |
| func (s *Application) FallbackCoordinator(tx *gorm.DB, actor Actor, b BindingRecord) (BindingRecord, error) { |
| - _, err := s.BindingSelection(tx, b) |
| - if err == nil { |
| - return b, nil |
| + // Never move an admitted turn to another account while it may still run. |
| + var active int64 |
| + if b.ID != "" { |
| + if err := tx.Table("coordinator_turns t").Where("t.binding_id=? AND t.attempt_id IN (SELECT id FROM attempts WHERE containment='pending')", b.ID).Count(&active).Error; err != nil { |
| + return b, err |
| + } |
| + if active > 0 { |
| + return b, nil |
| + } |
| + } |
| + if b.ID != "" { |
| + if err := s.loginNotes(tx, actor, b); err != nil { |
| + return b, err |
| + } |
| } |
| - if !errors.Is(err, s.WaitingConnection) && !errors.Is(err, s.Forbidden) { |
| + _, err := s.BindingSelection(tx, b) |
| + if b.ID != "" && err != nil && !errors.Is(err, s.WaitingConnection) && !errors.Is(err, s.Forbidden) { |
| return b, err |
| } |
| next, note, err := s.autoCoordinator(tx, actor) |
| @@ -21,16 +33,16 @@ func (s *Application) FallbackCoordinator(tx *gorm.DB, actor Actor, b BindingRec |
| return b, err |
| } |
| if next.ID == "" { |
| - return b, nil |
| - } |
| - if note != "" { |
| - var main Main |
| - if err = tx.Where("person=? AND team_id=?", actor.Address, b.TeamID).First(&main).Error; err != nil { |
| - return b, err |
| - } |
| - if err = s.Conversation(tx).SystemNote(main.ID, note); err != nil { |
| - return b, err |
| + if note != "" && b.ID != "" { |
| + var main Main |
| + if err = tx.Where("person=? AND team_id=?", actor.Address, b.TeamID).Take(&main).Error; err != nil { |
| + return b, err |
| + } |
| + if err = s.humanNote(tx, actor, main.ID, note); err != nil { |
| + return b, err |
| + } |
| } |
| + return b, nil |
| } |
| return next, nil |
| } |
diff --git a/internal/equipo/conversation/coordinator_poll.go b/internal/equipo/conversation/coordinator_poll.go| index 86b21d69..f83443f5 100644 |
| --- a/internal/equipo/conversation/coordinator_poll.go |
| +++ b/internal/equipo/conversation/coordinator_poll.go |
| @@ -7,7 +7,6 @@ import ( |
| "amadan.net/oficina/equipo/internal/equipo/team" |
| "context" |
| "errors" |
| - "fmt" |
| "gorm.io/gorm" |
| "gorm.io/gorm/clause" |
| "strconv" |
| @@ -21,10 +20,7 @@ func (e *Engine) PollCoordinator(ctx context.Context, p RunnerPrincipal) ([]Coor |
| return err |
| } |
| b, err := e.Conversation(tx).Binding(kernel.Actor{Address: p.Person}) |
| - if errors.Is(err, e.NotFound) { |
| - return nil |
| - } |
| - if err != nil { |
| + if err != nil && !errors.Is(err, e.NotFound) { |
| return err |
| } |
| if e.Rebind != nil { |
| @@ -33,6 +29,9 @@ func (e *Engine) PollCoordinator(ctx context.Context, p RunnerPrincipal) ([]Coor |
| return err |
| } |
| } |
| + if b.ID == "" { |
| + return nil |
| + } |
| if b.RunnerID != p.RunnerID { |
| return nil |
| } |
| @@ -137,14 +136,6 @@ func (e *Engine) waitCoordinator(tx *gorm.DB, b BindingRecord, row TurnRecord, s |
| if err := tx.Model(&Main{}).Where("id=?", row.ConversationID).Select("revision").Updates(map[string]any{"revision": gorm.Expr("revision+1")}).Error; err != nil { |
| return err |
| } |
| - if e.Copy != nil && row.State != state { |
| - note := e.Copy("coordinator." + state) |
| - if state == "waiting_task" { |
| - note = fmt.Sprintf(note, taskID) |
| - } |
| - if err := e.Conversation(tx).SystemNote(row.ConversationID, note); err != nil { |
| - return err |
| - } |
| - } |
| + |
| return e.Audit(tx, b, "coordinator."+state, row.ID) |
| } |
diff --git a/internal/equipo/conversation/coordinator_setup.go b/internal/equipo/conversation/coordinator_setup.go| index 6d72dae2..fb75cd33 100644 |
| --- a/internal/equipo/conversation/coordinator_setup.go |
| +++ b/internal/equipo/conversation/coordinator_setup.go |
| @@ -5,7 +5,6 @@ import ( |
| "amadan.net/oficina/equipo/internal/release" |
| "crypto/rand" |
| "errors" |
| - "fmt" |
| "gorm.io/gorm" |
| "strconv" |
| ) |
| @@ -21,21 +20,7 @@ func (s *Application) setupMessage(tx *gorm.DB, actor Actor, msg Message) error |
| note := "" |
| exists := err == nil |
| if exists { |
| - _, err = s.BindingSelection(tx, b) |
| - switch { |
| - case errors.Is(err, s.WaitingConnection), errors.Is(err, s.Forbidden): |
| - key := "coordinator.setup_offline" |
| - if errors.Is(err, s.Forbidden) { |
| - key = "coordinator.setup_binding" |
| - } |
| - b, err = s.FallbackCoordinator(tx, actor, b) |
| - if err == nil { |
| - if _, selectionErr := s.BindingSelection(tx, b); selectionErr != nil { |
| - note = s.Copy(key) |
| - } |
| - } |
| - |
| - } |
| + b, err = s.FallbackCoordinator(tx, actor, b) |
| } |
| if errors.Is(err, s.NotFound) { |
| b, note, err = s.autoCoordinator(tx, actor) |
| @@ -49,7 +34,7 @@ func (s *Application) setupMessage(tx *gorm.DB, actor Actor, msg Message) error |
| } |
| } |
| if note != "" { |
| - if err = cs.SystemNote(msg.ConversationID, note); err != nil { |
| + if err = s.humanNote(tx, actor, msg.ConversationID, note); err != nil { |
| return err |
| } |
| } |
| @@ -66,6 +51,9 @@ func (s *Application) autoCoordinator(tx *gorm.DB, actor Actor) (BindingRecord, |
| if err != nil { |
| return empty, "", err |
| } |
| + if key == "coordinator.setup_runner" { |
| + return empty, s.Copy("coordinator.runner_required"), nil |
| + } |
| if key != "" { |
| return empty, s.Copy(key), nil |
| } |
| @@ -74,14 +62,15 @@ func (s *Application) autoCoordinator(tx *gorm.DB, actor Actor) (BindingRecord, |
| if s.BindingRelease != nil { |
| manifest = *s.BindingRelease |
| } |
| - certified := false |
| + if err = ownermode.RankConnections(tx, connections, s.Now(), s.DecodeConnection); err != nil { |
| + return empty, "", err |
| + } |
| for _, c := range connections { |
| if err = s.DecodeConnection(&c); err != nil { |
| return empty, "", err |
| } |
| for _, r := range c.Reports { |
| - allowed, known, err := ownermode.AutoCandidate(tx, c, r, manifest, s.BindingEligible) |
| - certified = certified || known |
| + allowed, _, err := ownermode.AutoCandidate(tx, c, r, manifest, s.BindingEligible) |
| if err != nil { |
| return empty, "", err |
| } |
| @@ -95,6 +84,9 @@ func (s *Application) autoCoordinator(tx *gorm.DB, actor Actor) (BindingRecord, |
| } |
| b := BindingRecord{CoordinatorBinding: CoordinatorBinding{ID: rand.Text(), Person: actor.Address, RunnerID: c.RunnerID, ConnectionID: c.ID, Generation: 1, Revision: 1}, TeamID: teamID, PersonKey: actor.Address, MemberRevision: memberRevision, ConnectionRevision: connectionRevision} |
| old, oldErr := s.Conversation(tx).Binding(actor) |
| + if oldErr == nil && old.ConnectionID == c.ID && old.RunnerID == c.RunnerID && old.MemberRevision == memberRevision && old.ConnectionRevision == connectionRevision { |
| + return old, "", nil |
| + } |
| if oldErr == nil { |
| changed, changeErr := s.changeCoordinator(tx.Statement.Context, actor, c.RunnerID, c.ID, false, Mutation{Revision: old.Revision, RequestID: "fallback:" + old.ID + ":" + strconv.FormatInt(old.Revision, 10) + ":" + c.ID + ":" + strconv.FormatInt(c.Revision, 10)}) |
| if changeErr != nil { |
| @@ -114,18 +106,11 @@ func (s *Application) autoCoordinator(tx *gorm.DB, actor Actor) (BindingRecord, |
| if err = s.Audit(tx, actor, "coordinator.auto_bind", b.ID); err != nil { |
| return empty, "", err |
| } |
| - label := c.Label |
| - if label == "" { |
| - label = r.AccountLabel |
| - } |
| - if label == "" { |
| - label = c.LocalID |
| - } |
| - return b, fmt.Sprintf(s.Copy("coordinator.auto_bound"), label), nil |
| + return b, "", nil |
| } |
| } |
| - if !certified { |
| - return empty, s.Copy("coordinator.setup_certified"), nil |
| + if err = s.loginNotes(tx, actor, BindingRecord{TeamID: teamID}); err != nil { |
| + return empty, "", err |
| } |
| - return empty, s.Copy("coordinator.setup_offline"), nil |
| + return empty, "", nil |
| } |
diff --git a/internal/equipo/conversation/self_heal_notes.go b/internal/equipo/conversation/self_heal_notes.go| new file mode 100644 |
| index 00000000..5490712f |
| --- /dev/null |
| +++ b/internal/equipo/conversation/self_heal_notes.go |
| @@ -0,0 +1,13 @@ |
| +package conversation |
| + |
| +import ( |
| + "amadan.net/oficina/equipo/internal/equipo/ownermode" |
| + "gorm.io/gorm" |
| +) |
| + |
| +func (s *Application) humanNote(tx *gorm.DB, _ Actor, conversation, note string) error { |
| + return ownermode.HumanNote(tx, conversation, note, s.Conversation(tx).SystemNote) |
| +} |
| +func (s *Application) loginNotes(tx *gorm.DB, actor Actor, b BindingRecord) error { |
| + return ownermode.LoginNotes(tx, actor.Address, b.TeamID, s.DecodeConnection, s.Copy, s.Conversation(tx).SystemNote) |
| +} |
diff --git a/internal/equipo/conversation/settings.go b/internal/equipo/conversation/settings.go| index 38adbb99..92488267 100644 |
| --- a/internal/equipo/conversation/settings.go |
| +++ b/internal/equipo/conversation/settings.go |
| @@ -113,19 +113,7 @@ func (h *Handler) SaveSettings(w http.ResponseWriter, r *http.Request) { |
| m, err := planning.ReadMutation(w, r, h.App.Invalid) |
| if err == nil { |
| switch r.PostForm.Get("action") { |
| - case "bind": |
| - // The connection's runner is resolved from the person's safe projection. |
| - var page CoordinatorPage |
| - page, err = h.App.CoordinatorPage(r.Context(), a) |
| - if err == nil { |
| - err = h.App.Invalid |
| - for _, c := range page.Connections { |
| - if c.ID == r.PostForm.Get("connection_id") { |
| - _, err = h.App.SaveCoordinatorBinding(r.Context(), a, c.RunnerID, c.ID, m) |
| - break |
| - } |
| - } |
| - } |
| + |
| case "reset": |
| _, err = h.App.ResetCoordinator(r.Context(), a, m) |
| case "retry": |
diff --git a/internal/equipo/conversation/store.go b/internal/equipo/conversation/store.go| index 965f8a5e..9f0511f3 100644 |
| --- a/internal/equipo/conversation/store.go |
| +++ b/internal/equipo/conversation/store.go |
| @@ -67,9 +67,7 @@ func (s *Store) Conversation(actor kernel.Actor, cursor string, limit int) (Conv |
| if err != nil { |
| return page, err |
| } |
| - if b.WaitingTaskID != "" { |
| - page.Cards = append(page.Cards, Card{ID: b.ID, Kind: "coordinator", ResourceID: b.ID, Revision: page.Revision, CopyKey: "coordinator.waiting_task", WaitingTaskID: b.WaitingTaskID, WaitingTaskURL: b.WaitingTaskURL}) |
| - } |
| + |
| cards, err := chatstate.Status(s.tx, b.ID, b.Person, b.Generation) |
| page.Cards = append(page.Cards, cards...) |
| return page, err |
diff --git a/internal/equipo/conversation/tools.go b/internal/equipo/conversation/tools.go| index a1a8c886..b7f1e767 100644 |
| --- a/internal/equipo/conversation/tools.go |
| +++ b/internal/equipo/conversation/tools.go |
| @@ -9,6 +9,7 @@ import ( |
| "time" |
| "amadan.net/oficina/equipo/internal/coordinator" |
| + "amadan.net/oficina/equipo/internal/equipo/ownermode" |
| "amadan.net/oficina/equipo/internal/equipo/planning" |
| "amadan.net/oficina/equipo/internal/equipo/team" |
| "amadan.net/oficina/equipo/internal/runnerproto" |
| @@ -79,6 +80,19 @@ func (e *Engine) CallCoordinatorTool(ctx context.Context, p RunnerPrincipal, c C |
| return e.Invalid |
| } |
| switch a := args.(type) { |
| + case *coordinator.EquipoStatus: |
| + projects, readErr := e.projects(tx, b.Person, c.Brief.Selection) |
| + if readErr != nil { |
| + return readErr |
| + } |
| + status, readErr := ownermode.Status(ctx, tx, e.Core, b.CoordinatorBinding, b.TeamID, e.Now(), projects, row.State) |
| + if readErr != nil { |
| + return readErr |
| + } |
| + out, err = result(b.ID, b.Revision, status) |
| + if err != nil { |
| + return err |
| + } |
| case *coordinator.ProposeProject: |
| safe := *a |
| if err = json.Unmarshal(e.Redact(mustCoordinatorJSON(a)), &safe); err != nil { |
diff --git a/internal/equipo/copy.go b/internal/equipo/copy.go| index 5f16c1ff..16ecb970 100644 |
| --- a/internal/equipo/copy.go |
| +++ b/internal/equipo/copy.go |
| @@ -46,20 +46,27 @@ const BootLog = "Equipo could not start." |
| // COPY APPROVED BY DELEGATION (Luna pass, 2026-11-01, house rules). |
| var pageCopy = map[string]string{ |
| + // COPY REVIEW PENDING |
| + "coordinator.login_required": "%s needs a new sign-in. Run this on your runner: %s", |
| + // COPY REVIEW PENDING |
| + "coordinator.runner_required": "Add your machine in Connections, then run equipo-runner enrol on that machine.", |
| + |
| + // COPY REVIEW PENDING |
| + "coordinator.tool.equipo_status": "Read your runner, connection availability, budgets and project setup. No secrets are included.", |
| + // COPY REVIEW PENDING |
| + "coordinator.automatic": "Equipo chooses a healthy connection from your runner and switches when it is busy or unavailable.", |
| + // COPY REVIEW PENDING |
| + "coordinator.waiting_connection_label": "Waiting for %s…", |
| + |
| // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context): coordinator.admission_denied |
| "coordinator.admission_denied": "Your coordinator cannot start work yet. Check the team settings.", |
| // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context): isolation.owner_mode |
| "isolation.owner_mode": "owner mode", |
| // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context): connections.owner_mode |
| "connections.owner_mode": "Your runner uses the sandbox without requiring an exact policy certificate for your work.", |
| - "coordinator.setup_binding": "Your coordinator connection changed. Choose your connection again in Your coordinator.", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context) |
| - "coordinator.auto_bound": "Your coordinator uses %s. Change it in Your coordinator.", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context) |
| - "coordinator.setup_runner": "Your coordinator needs a runner. Add your machine in Connections.", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context) |
| - "coordinator.setup_connection": "Your coordinator needs a model connection. Connect an account in Connections.", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context) |
| - "coordinator.setup_certified": "None of your connections has a certified coordinator policy. Ask the team owner to enable a certified coordinator release.", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context) |
| - "coordinator.setup_offline": "Your coordinator cannot use your runner connection. Start or update your runner in Connections.", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context) |
| - "coordinator.fenced": "This coordinator turn stopped. Choose Try this turn again.", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context) |
| - "coordinator.timed_out": "Your coordinator took too long to reply. Restart your runner in Connections to finish stopping the turn.", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context) |
| + "coordinator.setup_connection": "Your coordinator needs a model connection. Connect an account in Connections.", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context) |
| + "coordinator.fenced": "This coordinator turn stopped. Choose Try this turn again.", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context) |
| + "coordinator.timed_out": "Your coordinator took too long to reply. Restart your runner in Connections to finish stopping the turn.", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context) |
| // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context): project_setup.heading |
| "project_setup.heading": "Set up %s (%s)?", |
| @@ -465,8 +472,6 @@ var pageCopy = map[string]string{ |
| "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 ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context): coordinator.connection_unavailable |
| - "coordinator.connection_unavailable": "Unavailable", |
| // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context): conversation.sending |
| "conversation.sending": "Sending", |
| // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context): conversation.retry |
| @@ -770,8 +775,6 @@ var runnerDraftCopy = map[string]string{ |
| "runner.requested_format": "2 Jan 2006, 15:04 UTC", |
| // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context): runner.waiting_accounts |
| "runner.waiting_accounts": "Waiting for a model account.", |
| - // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context): coordinator.connection |
| - "coordinator.connection": "Coordinator connection", |
| // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context): coordinator.unavailable |
| "coordinator.unavailable": "Your coordinator is unavailable.", |
| // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context): coordinator.budget_needed |
diff --git a/internal/equipo/ownermode/login_notes.go b/internal/equipo/ownermode/login_notes.go| new file mode 100644 |
| index 00000000..1f0da44b |
| --- /dev/null |
| +++ b/internal/equipo/ownermode/login_notes.go |
| @@ -0,0 +1,50 @@ |
| +package ownermode |
| + |
| +import ( |
| + "amadan.net/oficina/equipo/internal/equipo/planning" |
| + "errors" |
| + "fmt" |
| + "gorm.io/gorm" |
| +) |
| + |
| +func HumanNote(tx *gorm.DB, conversation, note string, emit func(string, string) error) error { |
| + var count int64 |
| + if err := tx.Table("conversation_messages").Where("conversation_id=? AND author_kind='system' AND body=?", conversation, note).Count(&count).Error; err != nil { |
| + return err |
| + } |
| + if count > 0 { |
| + return nil |
| + } |
| + return emit(conversation, note) |
| +} |
| +func LoginNotes(tx *gorm.DB, person, teamID string, decode func(*planning.ConnectionRecord) error, copy func(string) string, emit func(string, string) error) error { |
| + connections, _, err := OwnConnections(tx, person, teamID) |
| + if err != nil { |
| + return err |
| + } |
| + var main struct{ ID string } |
| + if err = tx.Table("conversations").Where("person=? AND team_id=?", person, teamID).Take(&main).Error; err != nil { |
| + if errors.Is(err, gorm.ErrRecordNotFound) { |
| + return nil |
| + } |
| + return err |
| + } |
| + for _, c := range connections { |
| + if err = decode(&c); err != nil { |
| + return err |
| + } |
| + for _, r := range c.Reports { |
| + if r.UnavailableReason != "account.sign_in_again" || r.SignInCommand == "" { |
| + continue |
| + } |
| + label := c.Label |
| + if label == "" { |
| + label = c.LocalID |
| + } |
| + if err = HumanNote(tx, main.ID, fmt.Sprintf(copy("coordinator.login_required"), label, r.SignInCommand), emit); err != nil { |
| + return err |
| + } |
| + } |
| + } |
| + return nil |
| +} |
diff --git a/internal/equipo/ownermode/ranking.go b/internal/equipo/ownermode/ranking.go| new file mode 100644 |
| index 00000000..35e1727c |
| --- /dev/null |
| +++ b/internal/equipo/ownermode/ranking.go |
| @@ -0,0 +1,38 @@ |
| +package ownermode |
| + |
| +import ( |
| + "amadan.net/oficina/equipo/internal/equipo/planning" |
| + "gorm.io/gorm" |
| + "sort" |
| + "time" |
| +) |
| + |
| +func RankConnections(tx *gorm.DB, connections []planning.ConnectionRecord, now time.Time, decode func(*planning.ConnectionRecord) error) error { |
| + busy := map[string]int64{} |
| + healthy := map[string]bool{} |
| + for i := range connections { |
| + c := &connections[i] |
| + if err := decode(c); err != nil { |
| + return err |
| + } |
| + for _, r := range c.Reports { |
| + healthy[c.ID] = healthy[c.ID] || r.Available && !c.LastSeen.After(now) && now.Sub(c.LastSeen) < 90*time.Second |
| + } |
| + var n int64 |
| + if err := tx.Table("runner_assignments").Where("person=? AND state IN ('claimed','reconcile','fenced') AND attempt_id IN (SELECT id FROM attempts WHERE containment='pending') AND json_extract(selection,'$.ConnectionID')=?", c.Person, c.ID).Count(&n).Error; err != nil { |
| + return err |
| + } |
| + busy[c.ID] = n |
| + } |
| + sort.SliceStable(connections, func(i, j int) bool { |
| + a, b := connections[i], connections[j] |
| + if healthy[a.ID] != healthy[b.ID] { |
| + return healthy[a.ID] |
| + } |
| + if busy[a.ID] != busy[b.ID] { |
| + return busy[a.ID] < busy[b.ID] |
| + } |
| + return a.LastSeen.After(b.LastSeen) |
| + }) |
| + return nil |
| +} |
diff --git a/internal/equipo/ownermode/self_heal_status.go b/internal/equipo/ownermode/self_heal_status.go| new file mode 100644 |
| index 00000000..eee917fb |
| --- /dev/null |
| +++ b/internal/equipo/ownermode/self_heal_status.go |
| @@ -0,0 +1,62 @@ |
| +package ownermode |
| + |
| +import ( |
| + "amadan.net/oficina/equipo/internal/equipo/kernel" |
| + "amadan.net/oficina/equipo/internal/equipo/team" |
| + "amadan.net/oficina/equipo/internal/runnerproto" |
| + "context" |
| + "encoding/json" |
| + "gorm.io/gorm" |
| + "time" |
| +) |
| + |
| +func Status(ctx context.Context, tx *gorm.DB, core *team.Store, b runnerproto.CoordinatorBinding, teamID string, now time.Time, projects any, state string) (map[string]any, error) { |
| + var runners []struct { |
| + ID, Label string |
| + RevokedAt *string |
| + } |
| + if err := tx.Table("runners").Select("id,label,revoked_at").Where("person=? AND instance_id=?", b.Person, teamID).Find(&runners).Error; err != nil { |
| + return nil, err |
| + } |
| + var rows []struct { |
| + ID, RunnerID, LocalID, Label, ReportsJSON string |
| + LastSeen time.Time |
| + } |
| + if err := tx.Table("connections").Select("id,runner_id,local_id,label,reports_json,last_seen").Where("person=? AND revoked_at IS NULL AND runner_id IN (SELECT id FROM runners WHERE person=? AND instance_id=? AND revoked_at IS NULL)", b.Person, b.Person, teamID).Find(&rows).Error; err != nil { |
| + return nil, err |
| + } |
| + type connection struct { |
| + ID, RunnerID, Label, Provider string |
| + Available bool |
| + LastSeen time.Time |
| + Reason string |
| + } |
| + connections := []connection{} |
| + for _, c := range rows { |
| + var reports []runnerproto.ConnectionReport |
| + if err := json.Unmarshal([]byte(c.ReportsJSON), &reports); err != nil { |
| + return nil, err |
| + } |
| + for _, r := range reports { |
| + connections = append(connections, connection{c.ID, c.RunnerID, c.Label, r.Provider, r.Available && !c.LastSeen.After(now) && now.Sub(c.LastSeen) < 90*time.Second, c.LastSeen, r.UnavailableReason}) |
| + } |
| + } |
| + var budget kernel.BudgetRecord |
| + if err := tx.Where("team_id=?", teamID).Take(&budget).Error; err != nil { |
| + return nil, err |
| + } |
| + var config kernel.BudgetConfig |
| + if err := json.Unmarshal([]byte(budget.Config), &config); err != nil { |
| + return nil, err |
| + } |
| + limits, _, err := core.CoordinatorLimits(ctx, team.AccountID(teamID), b.Person) |
| + if err != nil { |
| + return nil, err |
| + } |
| + usage, err := core.CoordinatorUsage(ctx, team.AccountID(teamID), b.Person, now) |
| + if err != nil { |
| + return nil, err |
| + } |
| + |
| + return map[string]any{"runner_id": b.RunnerID, "connection_id": b.ConnectionID, "runners": runners, "connections": connections, "budgets": config, "project_budget_default": config.Team, "coordinator_limits": limits, "coordinator_usage": usage, "projects": projects, "turn_state": state}, nil |
| +} |
diff --git a/internal/equipo/task_prepare.go b/internal/equipo/task_prepare.go| index d9c13424..438ce069 100644 |
| --- a/internal/equipo/task_prepare.go |
| +++ b/internal/equipo/task_prepare.go |
| @@ -86,7 +86,7 @@ func bugPolicy(tx *gorm.DB, task Task) (team.Policy, error) { |
| if err != nil { |
| return team.Policy{}, err |
| } |
| - p := b.Projects[team.ProjectID(task.ProjectID)] |
| + p := (team.BudgetSet{Team: b.Team, Projects: b.Projects}).ProjectLimits(team.ProjectID(task.ProjectID)) |
| limits := team.Limits{Calls: min(24, b.Team.Calls, p.Calls), InputTokens: min(200000, b.Team.InputTokens, p.InputTokens), OutputTokens: min(40000, b.Team.OutputTokens, p.OutputTokens)} |
| return team.RunnerPolicy("subscription", limits, team.Limits{Calls: 1, InputTokens: min(32000, limits.InputTokens), OutputTokens: min(4000, limits.OutputTokens)}, team.Rates{}) |
| } |
diff --git a/internal/equipo/tasks.go b/internal/equipo/tasks.go| index 760a7e2d..f8394d71 100644 |
| --- a/internal/equipo/tasks.go |
| +++ b/internal/equipo/tasks.go |
| @@ -53,9 +53,6 @@ func bugBudget(tx *gorm.DB, teamID string, projectID int64) (BudgetConfig, error |
| if (team.BudgetSet{Revision: config.Revision, Team: config.Team, Projects: config.Projects}).Validate() != nil { |
| return config, ErrUnavailable |
| } |
| - if _, ok := config.Projects[team.ProjectID(projectID)]; !ok { |
| - return config, ErrUnavailable |
| - } |
| return config, nil |
| } |
| func (s *Store) CreateBug(ctx context.Context, actor Actor, projectID int64, description, requestID string) (Task, error) { |
diff --git a/internal/equipo/team/budget.go b/internal/equipo/team/budget.go| index 5b70f527..c503fdbc 100644 |
| --- a/internal/equipo/team/budget.go |
| +++ b/internal/equipo/team/budget.go |
| @@ -432,10 +432,7 @@ func boundedTurn(ctx context.Context, tx *sql.Tx, j jobRow, now time.Time) (Usag |
| } |
| } |
| } else if configured { |
| - project, ok := b.Projects[j.Project] |
| - if !ok { |
| - return want, fail(CodeBudget, "project budget unavailable") |
| - } |
| + project := b.ProjectLimits(j.Project) |
| for _, c := range []struct { |
| id ProjectID |
| cap PeriodLimits |
diff --git a/internal/equipo/team/jobs.go b/internal/equipo/team/jobs.go| index 149d6cc3..eff62399 100644 |
| --- a/internal/equipo/team/jobs.go |
| +++ b/internal/equipo/team/jobs.go |
| @@ -216,7 +216,7 @@ func (s *Store) CreateJob(ctx context.Context, spec JobSpec) (Job, error) { |
| return fail(CodeQuota, "job depth %d exceeds policy depth %d", depth, spec.Policy.MaxDepth) |
| } |
| } |
| - b, configured, err := loadBudgets(ctx, tx, spec.Account) |
| + _, configured, err := loadBudgets(ctx, tx, spec.Account) |
| if err != nil { |
| return err |
| } |
| @@ -228,7 +228,7 @@ func (s *Store) CreateJob(ctx context.Context, spec JobSpec) (Job, error) { |
| return err |
| } |
| } else if configured { |
| - if _, ok := b.Projects[spec.Project]; !ok || spec.Project <= 0 { |
| + if spec.Project <= 0 { |
| return fail(CodeBudget, "job needs configured project") |
| } |
| } |
diff --git a/internal/equipo/team/periodbudget.go b/internal/equipo/team/periodbudget.go| index 32cf3709..dcdf24d7 100644 |
| --- a/internal/equipo/team/periodbudget.go |
| +++ b/internal/equipo/team/periodbudget.go |
| @@ -46,6 +46,14 @@ func (p PeriodLimits) validate() error { |
| } |
| return nil |
| } |
| + |
| +// ProjectLimits inherits the team ceiling until a project has an explicit limit. |
| +func (b BudgetSet) ProjectLimits(id ProjectID) PeriodLimits { |
| + if p, ok := b.Projects[id]; ok { |
| + return p |
| + } |
| + return b.Team |
| +} |
| func (b BudgetSet) Validate() error { |
| if b.Revision < 0 { |
| return fail(CodeInvalid, "negative budget revision") |
| @@ -267,18 +275,13 @@ func (s *Store) PeriodUsage(ctx context.Context, account AccountID, project Proj |
| return sum, fail(CodeInvalid, "period usage scope") |
| } |
| err := s.read(ctx, func(tx *sql.Tx) error { |
| - b, configured, err := loadBudgets(ctx, tx, account) |
| + _, configured, err := loadBudgets(ctx, tx, account) |
| if err != nil { |
| return err |
| } |
| if !configured { |
| return fail(CodeBudget, "period budgets unavailable") |
| } |
| - if project != 0 { |
| - if _, ok := b.Projects[project]; !ok { |
| - return fail(CodeScope, "unknown budget project") |
| - } |
| - } |
| sum, err = periodSum(ctx, tx, account, project, at) |
| return err |
| }) |
| @@ -306,8 +309,8 @@ func CheckPlanBudgetTx(ctx context.Context, tx *sql.Tx, account AccountID, proje |
| if err := b.Validate(); err != nil { |
| return err |
| } |
| - p, ok := b.Projects[project] |
| - if !ok || project <= 0 { |
| + p := b.ProjectLimits(project) |
| + if project <= 0 { |
| return fail(CodeBudget, "job has no configured project") |
| } |
| for _, limit := range []struct { |
diff --git a/internal/equipo/team/periodbudget_test.go b/internal/equipo/team/periodbudget_test.go| index 1f6bd158..81715302 100644 |
| --- a/internal/equipo/team/periodbudget_test.go |
| +++ b/internal/equipo/team/periodbudget_test.go |
| @@ -383,7 +383,7 @@ func TestPeriodBudgetConfiguration(t *testing.T) { |
| } |
| wantCode(t, e.store.ConfigureBudgets(e.ctx, acctA, 0, bad), CodeOverflow) |
| must(t, e.store.ConfigureBudgets(e.ctx, acctA, 0, b)) |
| - for _, p := range []ProjectID{0, 99} { |
| + for _, p := range []ProjectID{0} { |
| spec := softwareSpec(SoftwareSteps(false)) |
| spec.Project = p |
| _, err = e.store.CreateJob(e.ctx, spec) |
diff --git a/internal/equipo/team/self_heal_test.go b/internal/equipo/team/self_heal_test.go| new file mode 100644 |
| index 00000000..6484f6fe |
| --- /dev/null |
| +++ b/internal/equipo/team/self_heal_test.go |
| @@ -0,0 +1,19 @@ |
| +package team |
| + |
| +import "testing" |
| + |
| +func TestSelfHealProjectInheritsTeamBudget(t *testing.T) { |
| + e := newEnv(t) |
| + b := periodSet() |
| + b.Projects = nil |
| + b.Team.Calls = 1 |
| + must(t, e.store.ConfigureBudgets(e.ctx, acctA, 0, b)) |
| + scope, h := periodJob(e, 17) |
| + _, err := e.store.Intend(e.ctx, scope, h, intent("first", Usage{InputTokens: 1, OutputTokens: 1})) |
| + must(t, err) |
| + if periodUsage(e, 17).Reserved.Calls != 1 { |
| + t.Fatal("inherited usage missing") |
| + } |
| + _, err = e.store.Intend(e.ctx, scope, h, intent("second", Usage{InputTokens: 1, OutputTokens: 1})) |
| + wantCode(t, err, CodeBudget) |
| +} |
diff --git a/internal/equipo/templates/conversation_card.html b/internal/equipo/templates/conversation_card.html| index 20e7fcfd..600620f8 100644 |
| --- a/internal/equipo/templates/conversation_card.html |
| +++ b/internal/equipo/templates/conversation_card.html |
| @@ -31,7 +31,7 @@ |
| </section> |
| {{end}} |
| {{define "conversation-card"}} |
| -{{if .Thinking}}<div equipo-message="incoming" equipo-thinking data-turn="{{.ID}}" aria-busy="true"><div equipo-message-meta><strong>{{icon "message-circle"}}{{copy "conversation.coordinator"}}</strong></div><div equipo-bubble>{{if .PartialText}}<div equipo-markdown data-stream-text>{{chatMarkdown .PartialText}}</div>{{else}}<span equipo-visually-hidden>{{copy "conversation.thinking"}}</span>{{end}}<span equipo-thinking-dots aria-hidden="true"><i></i><i></i><i></i></span></div></div>{{else}} |
| +{{if .Thinking}}<div equipo-message="incoming" equipo-thinking data-turn="{{.ID}}" aria-busy="true"><div equipo-message-meta><strong>{{icon "message-circle"}}{{copy "conversation.coordinator"}}</strong></div><div equipo-bubble>{{if .ConnectionLabel}}<span>{{printf (copy "coordinator.waiting_connection_label") .ConnectionLabel}}</span>{{else if .PartialText}}<div equipo-markdown data-stream-text>{{chatMarkdown .PartialText}}</div>{{else}}<span equipo-visually-hidden>{{copy "conversation.thinking"}}</span>{{end}}<span equipo-thinking-dots aria-hidden="true"><i></i><i></i><i></i></span></div></div>{{else}} |
| <article {{if eq .Kind "coordinator"}}equipo-system-note{{end}} equipo-card data-card="{{.ID}}"{{if or .NativeQuestion .Question}} equipo-question{{end}}> |
| {{with .ProjectProposal}} |
| <h2>{{printf (copy "project_setup.heading") .Name .Repository}}</h2><p>{{.Why}}</p> |
diff --git a/internal/equipo/templates/coordinator.html b/internal/equipo/templates/coordinator.html| index ffb17c11..c7989068 100644 |
| --- a/internal/equipo/templates/coordinator.html |
| +++ b/internal/equipo/templates/coordinator.html |
| @@ -4,8 +4,8 @@ |
| {{with .Coordinator}} |
| {{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 {{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}} |
| +<p equipo-note>{{copy "coordinator.automatic"}}</p> |
| +{{$current := .Binding.ConnectionID}}{{range .Connections}}{{if eq .ID $current}}<p>{{.Label}}</p>{{end}}{{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}} |
| <form equipo-form method="post" action="/settings/coordinator"><input type="hidden" name="action" value="landing"><input type="hidden" name="request_id" value="{{.SettingsID}}"><input type="hidden" name="revision" value="{{.Settings.Revision}}"><label>{{copy "settings.landing"}}<select rst-input name="landing"><option value="conversation" {{if eq .Settings.Landing "conversation"}}selected{{end}}>{{copy "nav.conversation"}}</option><option value="work" {{if eq .Settings.Landing "work"}}selected{{end}}>{{copy "nav.work"}}</option></select></label><button rst-btn type="submit">{{copy "form.save"}}</button></form> |
diff --git a/internal/ownermodetest/self_heal_test.go b/internal/ownermodetest/self_heal_test.go| new file mode 100644 |
| index 00000000..24925f29 |
| --- /dev/null |
| +++ b/internal/ownermodetest/self_heal_test.go |
| @@ -0,0 +1,104 @@ |
| +package ownermodetest |
| + |
| +import ( |
| + "amadan.net/oficina/equipo/internal/equipo" |
| + "amadan.net/oficina/equipo/internal/plan3test" |
| + "amadan.net/oficina/equipo/internal/runnerproto" |
| + "context" |
| + "encoding/json" |
| + "net/http/httptest" |
| + "strings" |
| + "testing" |
| +) |
| + |
| +func mustSelfHeal(t *testing.T, err error) { |
| + t.Helper() |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| +} |
| +func TestSelfHealNoCoordinatorPicker(t *testing.T) { |
| + f, _, _, _ := plan3test.SelfHealFixture(t) |
| + plan3test.SelfHealRouter(t, f, nil) |
| + req := httptest.NewRequest("GET", "/settings/coordinator", nil) |
| + req.AddCookie(f.Cookies["owner@example.com"]) |
| + response := httptest.NewRecorder() |
| + f.Handler.ServeHTTP(response, req) |
| + if response.Code != 200 { |
| + t.Fatalf("settings: %d", response.Code) |
| + } |
| + for _, needle := range []string{`name="connection_id"`, `value="bind"`, `value="reset"`} { |
| + if strings.Contains(response.Body.String(), needle) { |
| + t.Fatalf("manual coordinator control: %s", needle) |
| + } |
| + } |
| +} |
| + |
| +func TestSelfHealStatusIsScopedAndRevocationApplies(t *testing.T) { |
| + f, x, p, c := plan3test.SelfHealClaim(t) |
| + mustSelfHeal(t, f.DB.G.Exec("INSERT INTO runners(id,person,instance_id,label,revision,machine_key_hash) VALUES('other-runner','other@example.invalid',?,'foreign-runner-secret',1,'private-machine-key')", f.TeamID).Error) |
| + out := plan3test.SelfHealTool(t, x, p, c, "status", "equipo_status", map[string]any{}) |
| + if strings.Contains(string(out.Value), "MachineKeyHash") || strings.Contains(string(out.Value), "AccountID") || strings.Contains(string(out.Value), "foreign-runner-secret") || strings.Contains(string(out.Value), "private-machine-key") { |
| + t.Fatal("status exposed private fields") |
| + } |
| + if !strings.Contains(string(out.Value), "coordinator_limits") || !strings.Contains(string(out.Value), "projects") { |
| + t.Fatal("status incomplete") |
| + } |
| + mustSelfHeal(t, f.DB.G.Exec("UPDATE members SET active=0 WHERE address=?", "owner@example.com").Error) |
| + if _, err := x.CallCoordinatorTool(context.Background(), p, c, runnerproto.CoordinatorToolCall{RequestID: "revoked", Name: "equipo_status", Arguments: json.RawMessage(`{}`)}); err == nil { |
| + t.Fatal("revoked member read status") |
| + } |
| +} |
| + |
| +func TestSelfHealRevokedLoginNotifiedOnce(t *testing.T) { |
| + f, x, p, _ := plan3test.SelfHealFixture(t) |
| + plan3test.SelfHealOwnerReports(t, f) |
| + plan3test.SelfHealQueue(t, f, "hello", "revoked-login") |
| + mustSelfHeal(t, f.DB.G.Exec(`UPDATE connections SET reports_json=json_set(reports_json,'$[0].Available',json('false'),'$[0].UnavailableReason','account.sign_in_again','$[0].SignInCommand','flock home env CLAUDE_CONFIG_DIR=home claude auth login') WHERE id='claude'`).Error) |
| + for i := 0; i < 3; i++ { |
| + _, err := x.PollCoordinator(context.Background(), p) |
| + mustSelfHeal(t, err) |
| + } |
| + var count int |
| + mustSelfHeal(t, f.DB.Writer().QueryRow(`SELECT count(*) FROM conversation_messages WHERE author_kind='system' AND body LIKE '%flock home env CLAUDE_CONFIG_DIR=home claude auth login%'`).Scan(&count)) |
| + if count != 1 { |
| + t.Fatal("revoked login action missing or repeated") |
| + } |
| +} |
| + |
| +func TestSelfHealStatusDoesNotCallStaleReportsAvailable(t *testing.T) { |
| + f, x, p, c := plan3test.SelfHealClaim(t) |
| + mustSelfHeal(t, f.DB.G.Exec("UPDATE connections SET last_seen='2000-01-01' WHERE id='codex'").Error) |
| + out := plan3test.SelfHealTool(t, x, p, c, "stale-status", "equipo_status", map[string]any{}) |
| + var result struct { |
| + Result struct { |
| + Connections []struct { |
| + ID string |
| + Available bool |
| + } |
| + } |
| + } |
| + mustSelfHeal(t, json.Unmarshal(out.Value, &result)) |
| + found := false |
| + for _, connection := range result.Result.Connections { |
| + if connection.ID == "codex" { |
| + found = true |
| + if connection.Available { |
| + t.Fatal("stale connection advertised available") |
| + } |
| + } |
| + } |
| + if !found { |
| + t.Fatal("missing own unavailable connection") |
| + } |
| +} |
| + |
| +func TestSelfHealRemovedConnectionStillRendersWait(t *testing.T) { |
| + f, x, p, _ := plan3test.SelfHealFixture(t) |
| + plan3test.SelfHealQueue(t, f, "hello", "removed-connection") |
| + mustSelfHeal(t, f.DB.G.Exec("DELETE FROM connections WHERE id='claude'").Error) |
| + _, err := x.PollCoordinator(context.Background(), p) |
| + mustSelfHeal(t, err) |
| + _, err = f.Store.Conversation(context.Background(), equipo.Actor{Address: p.Person}, "", 50) |
| + mustSelfHeal(t, err) |
| +} |
diff --git a/internal/plan3test/chat_feel_fixture.go b/internal/plan3test/chat_feel_fixture.go| index ed8f901e..470658e2 100644 |
| --- a/internal/plan3test/chat_feel_fixture.go |
| +++ b/internal/plan3test/chat_feel_fixture.go |
| @@ -105,8 +105,8 @@ func RunChatFeelPendingAndProjectCard(t *testing.T) { |
| cards, err = f.Store.ConversationCards(ctx, owner) |
| must(t, err) |
| for _, card := range cards { |
| - if card.ID == c.Turn.ID && (card.Thinking || card.CopyKey != "coordinator.waiting_connection") { |
| - t.Fatal("blocked turn did not replace thinking with note") |
| + if card.ID == c.Turn.ID && (!card.Thinking || card.ConnectionLabel == "") { |
| + t.Fatal("blocked turn lost live waiting bubble") |
| } |
| } |
| f.exec(t, "UPDATE coordinator_turns SET state='running' WHERE id=?", c.Turn.ID) |
diff --git a/internal/plan3test/conversation_browser_test.go b/internal/plan3test/conversation_browser_test.go| index 531fe3bd..b9ead11c 100644 |
| --- a/internal/plan3test/conversation_browser_test.go |
| +++ b/internal/plan3test/conversation_browser_test.go |
| @@ -81,10 +81,11 @@ func TestConversationScriptless(t *testing.T) { |
| must(t, f.DB.G.First(&waiting).Error) |
| raw, _ := json.Marshal(waiting.ID) |
| f.exec(t, "INSERT INTO conversation_requests(principal,operation,resource,request_id,input_hash,result) VALUES(?,?,?,?,?,?)", owner.Address, "coordinator.waiting", c.Binding.ID, "current", "fixture", string(raw)) |
| + f.exec(t, "UPDATE coordinator_turns SET state='waiting_task' WHERE id=?", c.Turn.ID) |
| w := f.get(t, owner, "/conversation") |
| expectHTTP(t, w, 200) |
| - if !strings.Contains(w.Body.String(), `href="/tasks/`+waiting.ID+`"`) || !strings.Contains(w.Body.String(), "Waiting for") { |
| - t.Fatal("waiting card lacks blocking task link") |
| + if !strings.Contains(w.Body.String(), "equipo-thinking") || !strings.Contains(w.Body.String(), "Waiting for claude") { |
| + t.Fatal("waiting bubble lacks connection status") |
| } |
| }) |
| } |
diff --git a/internal/plan3test/conversation_forms_test.go b/internal/plan3test/conversation_forms_test.go| index e2644b58..fec37c8f 100644 |
| --- a/internal/plan3test/conversation_forms_test.go |
| +++ b/internal/plan3test/conversation_forms_test.go |
| @@ -46,17 +46,17 @@ func TestConversationScriptlessSettings(t *testing.T) { |
| liveFixture(t, f) |
| w := f.get(t, owner, "/settings/coordinator") |
| expectHTTP(t, w, 200) |
| - if !strings.Contains(w.Body.String(), `value="claude" selected`) || !strings.Contains(w.Body.String(), `name="calls" value="24"`) { |
| + if !strings.Contains(w.Body.String(), `<p>claude</p>`) || !strings.Contains(w.Body.String(), `name="calls" value="24"`) { |
| t.Fatal("coordinator settings missing", w.Body.String()) |
| } |
| v := actionForm("binding", b.Revision) |
| v.Set("action", "bind") |
| v.Set("connection_id", "codex") |
| - expectHTTP(t, formPost(t, f, owner, "/settings/coordinator", v), 303) |
| + expectHTTP(t, formPost(t, f, owner, "/settings/coordinator", v), 422) |
| got, err := f.Store.Coordinator(ctx, owner) |
| must(t, err) |
| - if got.ConnectionID != "codex" { |
| - t.Fatal("binding ignored") |
| + if got.ConnectionID != "claude" { |
| + t.Fatal("manual binding changed automatic coordinator") |
| } |
| v = actionForm("reset", got.Revision) |
| v.Set("action", "reset") |
diff --git a/internal/plan3test/conversation_test.go b/internal/plan3test/conversation_test.go| index 6f28d5ac..f2b43e39 100644 |
| --- a/internal/plan3test/conversation_test.go |
| +++ b/internal/plan3test/conversation_test.go |
| @@ -89,15 +89,15 @@ func TestConversationMessageReplay(t *testing.T) { |
| if _, e = f.Store.SendMessage(ctx, owner, "", "rollback", equipo.Mutation{RequestID: "rollback"}); e == nil { |
| t.Fatal("audit failure ignored") |
| } |
| - if f.count(t, "SELECT count(*) FROM conversation_messages") != 4 || f.count(t, "SELECT count(*) FROM conversation_outboxes") != 4 || f.count(t, "SELECT count(*) FROM conversation_requests") != 4 { |
| + if f.count(t, "SELECT count(*) FROM conversation_messages") != 3 || f.count(t, "SELECT count(*) FROM conversation_outboxes") != 3 || f.count(t, "SELECT count(*) FROM conversation_requests") != 4 { |
| t.Fatal("audit failure did not roll back") |
| } |
| f.exec(t, "DROP TRIGGER fail_conversation_audit") |
| - if m = send(t, f, owner, "", "rollback", "rollback"); m.Sequence != 5 { |
| + if m = send(t, f, owner, "", "rollback", "rollback"); m.Sequence != 4 { |
| t.Fatal("rollback consumed sequence") |
| } |
| send(t, f, peer, "", "different principal", "once") |
| - if f.count(t, "SELECT count(*) FROM conversation_messages") != 8 { |
| + if f.count(t, "SELECT count(*) FROM conversation_messages") != 6 { |
| t.Fatal("request keys not principal scoped") |
| } |
| f.createTask(t) |
| @@ -107,7 +107,7 @@ func TestConversationMessageReplay(t *testing.T) { |
| expectHTTP(t, formPost(t, f, owner, "/conversation", v), 303) |
| page, e = f.Store.Conversation(ctx, owner, "", 50) |
| must(t, e) |
| - if page.Messages[len(page.Messages)-2].Body != "fixture\n\nCheck the invoice" { |
| + if page.Messages[len(page.Messages)-1].Body != "fixture\n\nCheck the invoice" { |
| t.Fatal("selected project missing from message") |
| } |
| v.Set("request_id", "missing-project") |
| @@ -140,7 +140,7 @@ func TestConversationRouteOnce(t *testing.T) { |
| must(t, e) |
| shared, e := f.Store.TaskThread(ctx, peer, task.ID, "", 50) |
| must(t, e) |
| - if len(main.Messages) != 5 || main.Messages[4].AuthorKind != "system" || len(main.Cards) != 1 || main.Cards[0].ResourceID != task.ID || len(shared.Messages) != 1 || shared.Messages[0].Body != "selected reply" { |
| + if len(main.Messages) != 4 || main.Messages[3].AuthorKind != "system" || len(main.Cards) != 1 || main.Cards[0].ResourceID != task.ID || len(shared.Messages) != 1 || shared.Messages[0].Body != "selected reply" { |
| t.Fatal("route did not leave exactly one reply and notice", main, shared) |
| } |
| if shared.Messages[0].ConversationID != "" || shared.Messages[0].ID == secret.ID || len(shared.Cards) != 0 { |
| @@ -245,7 +245,7 @@ func TestConversationPageBounds(t *testing.T) { |
| for e := range errs { |
| must(t, e) |
| } |
| - if len(seen) != 210 { |
| + if len(seen) != 106 { |
| t.Fatal("inserts changed snapshot", len(seen)) |
| } |
| if _, e = f.Store.Conversation(ctx, owner, "guessed", 50); !errors.Is(e, equipo.ErrNotFound) { |
diff --git a/internal/plan3test/coordinator_continuity_test.go b/internal/plan3test/coordinator_continuity_test.go| index 581cb892..9d293810 100644 |
| --- a/internal/plan3test/coordinator_continuity_test.go |
| +++ b/internal/plan3test/coordinator_continuity_test.go |
| @@ -39,12 +39,12 @@ func TestCoordinatorConnectionWaiting(t *testing.T) { |
| must(t, err) |
| found := false |
| for _, card := range page.Cards { |
| - if card.Kind == "coordinator" && card.WaitingTaskID == "blocking-task" && card.WaitingTaskURL == "/tasks/blocking-task" && card.CopyKey == "coordinator.waiting_task" { |
| + if card.Kind == "coordinator" && card.Thinking && card.ConnectionLabel == "claude" { |
| found = true |
| } |
| } |
| if !found { |
| - t.Fatal("conversation omitted linked waiting card") |
| + t.Fatal("conversation omitted live waiting bubble") |
| } |
| if f.count(t, "SELECT count(*) FROM admission_tickets") != 1 { |
| t.Fatal("waiting dispatched a provider") |
diff --git a/internal/plan3test/owner_mode_fixture.go b/internal/plan3test/owner_mode_fixture.go| index e1d67505..703da64c 100644 |
| --- a/internal/plan3test/owner_mode_fixture.go |
| +++ b/internal/plan3test/owner_mode_fixture.go |
| @@ -71,8 +71,8 @@ func RunOwnerModeFallback(t *testing.T) { |
| if f.count(t, "SELECT count(*) FROM coordinator_bindings WHERE id=? AND connection_id='claude' AND generation=2", b.ID) != 1 { |
| t.Fatal("fallback binding not saved") |
| } |
| - if f.count(t, "SELECT count(*) FROM conversation_messages WHERE author_kind='system' AND body LIKE '%coordinator%'") == 0 { |
| - t.Fatal("fallback note absent") |
| + if f.count(t, "SELECT count(*) FROM conversation_messages WHERE author_kind='system' AND body LIKE '%coordinator%'") != 0 { |
| + t.Fatal("automatic fallback added system note") |
| } |
| } |
| @@ -91,8 +91,8 @@ func RunOwnerModeDenialNote(t *testing.T) { |
| if len(page.Cards) == 0 { |
| t.Fatal("blocked turn missing conversation card") |
| } |
| - if f.count(t, "SELECT count(*) FROM conversation_messages WHERE author_kind='system' AND body LIKE '%connection%'") == 0 { |
| - t.Fatal("denial note absent") |
| + if f.count(t, "SELECT count(*) FROM conversation_messages WHERE author_kind='system' AND body LIKE '%connection%'") != 0 { |
| + t.Fatal("temporary connection denial added system note") |
| } |
| } |
| @@ -120,8 +120,8 @@ func RunOwnerModePausedNote(t *testing.T) { |
| if len(offers) > 0 || f.count(t, "SELECT count(*) FROM coordinator_turns WHERE state='admission_denied'") != 1 { |
| t.Fatal("paused admission not visible") |
| } |
| - if f.count(t, "SELECT count(*) FROM conversation_messages WHERE author_kind='system' AND body LIKE '%cannot start%'") != 1 { |
| - t.Fatal("admission note absent") |
| + if f.count(t, "SELECT count(*) FROM conversation_messages WHERE author_kind='system' AND body LIKE '%cannot start%'") != 0 { |
| + t.Fatal("admission wait added system note") |
| } |
| } |
diff --git a/internal/plan3test/self_heal_fixture.go b/internal/plan3test/self_heal_fixture.go| new file mode 100644 |
| index 00000000..c97e03ca |
| --- /dev/null |
| +++ b/internal/plan3test/self_heal_fixture.go |
| @@ -0,0 +1,8 @@ |
| +package plan3test |
| + |
| +var SelfHealFixture = coordinatorFixture |
| +var SelfHealRouter = apiRouter |
| +var SelfHealClaim = claimTools |
| +var SelfHealTool = toolCall |
| +var SelfHealOwnerReports = ownerReports |
| +var SelfHealQueue = queueCoordinator |
diff --git a/internal/plan3test/self_heal_test.go b/internal/plan3test/self_heal_test.go| new file mode 100644 |
| index 00000000..2385829d |
| --- /dev/null |
| +++ b/internal/plan3test/self_heal_test.go |
| @@ -0,0 +1,101 @@ |
| +package plan3test |
| + |
| +import ( |
| + "amadan.net/oficina/equipo/internal/equipo" |
| + "testing" |
| +) |
| + |
| +func TestSelfHealWaitIsLiveAndRetries(t *testing.T) { |
| + f, x, p, _ := coordinatorFixture(t) |
| + ownerReports(t, f) |
| + queueCoordinator(t, f, "hello", "self-heal-wait") |
| + before := f.count(t, "SELECT count(*) FROM conversation_messages WHERE author_kind='system'") |
| + f.exec(t, "UPDATE connections SET reports_json=json_set(reports_json,'$[0].Available',json('false'))") |
| + offers, err := x.PollCoordinator(ctx, p) |
| + must(t, err) |
| + if len(offers) != 0 { |
| + t.Fatal("unavailable admitted") |
| + } |
| + page, err := f.Store.Conversation(ctx, owner, "", 50) |
| + must(t, err) |
| + thinking := false |
| + for _, card := range page.Cards { |
| + thinking = thinking || card.Thinking |
| + } |
| + if !thinking { |
| + t.Fatal("temporary wait has no thinking bubble") |
| + } |
| + if f.count(t, "SELECT count(*) FROM conversation_messages WHERE author_kind='system'") != before { |
| + t.Fatal("temporary wait added system note") |
| + } |
| + f.exec(t, "UPDATE connections SET reports_json=json_set(reports_json,'$[0].Available',json('true')) WHERE id='claude'") |
| + offers, err = x.PollCoordinator(ctx, p) |
| + must(t, err) |
| + if len(offers) != 1 { |
| + t.Fatal("recovered connection did not retry") |
| + } |
| +} |
| + |
| +func TestSelfHealFailoverDoesNotMoveActiveTurn(t *testing.T) { |
| + f, x, p, b := coordinatorFixture(t) |
| + ownerReports(t, f) |
| + turn := queueCoordinator(t, f, "hello", "active") |
| + claim, err := x.ClaimCoordinator(ctx, p, turn.ID, turn.Revision) |
| + must(t, err) |
| + before, err := x.Core.GetJob(ctx, claim.Scope) |
| + must(t, err) |
| + f.exec(t, `UPDATE connections SET reports_json=json_set(reports_json,'$[0].OwnerMode',json('true'),'$[0].LauncherVersion','direct-v3','$[0].PolicyVersion','direct-v1') WHERE id='codex'`) |
| + f.exec(t, "UPDATE connections SET reports_json=json_set(reports_json,'$[0].Available',json('false')) WHERE id='claude'") |
| + _, err = x.PollCoordinator(ctx, p) |
| + must(t, err) |
| + job, err := x.Core.GetJob(ctx, claim.Scope) |
| + must(t, err) |
| + if job.State != before.State { |
| + t.Fatal("automatic fallback cancelled active job") |
| + } |
| + after, err := f.Store.Coordinator(ctx, owner) |
| + must(t, err) |
| + if after.ConnectionID != b.ConnectionID || after.Generation != b.Generation { |
| + t.Fatal("active turn moved") |
| + } |
| +} |
| + |
| +func TestSelfHealBusyConnectionFailsOver(t *testing.T) { |
| + f, x, p, _ := coordinatorFixture(t) |
| + ownerReports(t, f) |
| + first := queueCoordinator(t, f, "first", "busy-first") |
| + c, err := x.ClaimCoordinator(ctx, p, first.ID, first.Revision) |
| + must(t, err) |
| + f.exec(t, `UPDATE coordinator_turns SET state='delivered',attempt_id=0,job_id=0 WHERE id=?`, first.ID) |
| + f.exec(t, `INSERT INTO runner_assignments(id,task_id,person,state,attempt_id,selection) VALUES('busy','busy-task',?,'claimed',?,?)`, owner.Address, c.Handle.Attempt, `{"ConnectionID":"claude"}`) |
| + f.exec(t, `UPDATE connections SET reports_json=json_set(reports_json,'$[0].OwnerMode',json('true'),'$[0].LauncherVersion','direct-v3','$[0].PolicyVersion','direct-v1') WHERE id='codex'`) |
| + queueCoordinator(t, f, "second", "busy-second") |
| + turns, err := x.PollCoordinator(ctx, p) |
| + must(t, err) |
| + if len(turns) != 1 { |
| + t.Fatal("idle connection was not offered", turns) |
| + } |
| + b, err := f.Store.Coordinator(ctx, owner) |
| + must(t, err) |
| + if b.ConnectionID != "codex" { |
| + t.Fatal("busy connection retained", b.ConnectionID) |
| + } |
| +} |
| + |
| +func TestSelfHealProjectCardThenWorkAdmitted(t *testing.T) { |
| + f, x, p, c := claimTools(t) |
| + f.exec(t, "INSERT INTO runner_repositories(runner_id,repository) VALUES(?,?)", p.RunnerID, "amadan.net/oficina/self-heal-app") |
| + proposal := toolCall(t, x, p, c, "setup", "propose_project", map[string]any{"repository": "amadan.net/oficina/self-heal-app", "why": "Requested"}) |
| + must(t, f.Store.AnswerProjectProposal(ctx, owner, proposal.ResourceID, true, equipo.Mutation{RequestID: "accept", Revision: proposal.Revision})) |
| + var project int64 |
| + must(t, f.DB.Writer().QueryRow("SELECT project_id FROM project_proposals WHERE id=?", proposal.ResourceID).Scan(&project)) |
| + budgets, err := f.Store.Budgets(ctx) |
| + must(t, err) |
| + budgets.Projects = nil |
| + must(t, f.Store.SaveBudgets(ctx, owner, budgets)) |
| + task, err := f.Store.CreateBug(ctx, owner, project, "Fix this project", "new-project-work") |
| + must(t, err) |
| + if task.ProjectID != project { |
| + t.Fatal("work lost project") |
| + } |
| +} |
diff --git a/internal/release/manifest.json b/internal/release/manifest.json| index fe51be81..60c1cdf1 100644 |
| --- a/internal/release/manifest.json |
| +++ b/internal/release/manifest.json |
| @@ -3,7 +3,7 @@ |
| { |
| "provider": "claude", |
| "action": "coordinate", |
| - "inventory_hash": "632bf1ab06eb74fe0f67b0710aa854a2f2e4198ef89fd950b6dfff39a71b2f9b", |
| + "inventory_hash": "a969da21173a24ed2d824dd1e64a46793b8f8aaa4759e33333820eb55fa7224c", |
| "status": "uncertified" |
| }, |
| { |
| @@ -93,7 +93,7 @@ |
| { |
| "provider": "codex", |
| "action": "coordinate", |
| - "inventory_hash": "26a6d7dbb36a6787f651a22ae9785ac827e02bb8de8b89f93a0b403108577a86", |
| + "inventory_hash": "7517e40a2c993d2bd46836ce546f2006d474d702d4483c831f1937318263eb63", |
| "status": "uncertified" |
| } |
| ], |
diff --git a/internal/runner/certification_inputs.go b/internal/runner/certification_inputs.go| index 9da493f2..99c184fd 100644 |
| --- a/internal/runner/certification_inputs.go |
| +++ b/internal/runner/certification_inputs.go |
| @@ -1,6 +1,7 @@ |
| package runner |
| import ( |
| + "amadan.net/oficina/equipo/internal/runner/certified" |
| "amadan.net/oficina/equipo/internal/runner/egress" |
| "amadan.net/oficina/equipo/internal/runner/provider" |
| "amadan.net/oficina/equipo/internal/runner/provider/claude" |
| @@ -45,7 +46,7 @@ func CertificationInputs(ctx context.Context, c Config, s provider.Selection, bi |
| if err != nil { |
| return provider.PolicyInputs{}, err |
| } |
| - in := provider.PolicyInputs{Action: step, Workspace: work, Scratch: policyScratch, RuntimeFiles: runtimeFiles, DeniedPaths: denies.DeniedPaths, EgressHosts: network.Hosts, LauncherVersion: directLauncherVersion(), BwrapVersion: "0.11.0", Tools: profile.MCPTools()} |
| + in := provider.PolicyInputs{Action: step, Workspace: work, Scratch: policyScratch, RuntimeFiles: runtimeFiles, DeniedPaths: denies.DeniedPaths, EgressHosts: network.Hosts, LauncherVersion: certified.LauncherVersion(), BwrapVersion: "0.11.0", Tools: profile.MCPTools()} |
| if s.Provider == "claude" { |
| in, err = claude.PolicyInputs(binding, in, profile.Specialist, s.Model) |
| } else { |
diff --git a/internal/runner/certified/discovery.go b/internal/runner/certified/discovery.go| index 54ce78d3..ff56816e 100644 |
| --- a/internal/runner/certified/discovery.go |
| +++ b/internal/runner/certified/discovery.go |
| @@ -80,7 +80,7 @@ func connectionReport(ctx context.Context, b runnersetup.AccountBinding, m relea |
| if err != nil && owner { |
| report.UnavailableReason = "preflight_failed" |
| } |
| - if errors.Is(err, provider.ErrAccountMaintenance) { |
| + if errors.Is(err, provider.ErrLoginRequired) { |
| report.UnavailableReason = "account.sign_in_again" |
| } |
| if report.Available || err != nil { |
diff --git a/internal/runner/certified/discoverytest/connection_available_test.go b/internal/runner/certified/discoverytest/connection_available_test.go| index 8826e859..441f2967 100644 |
| --- a/internal/runner/certified/discoverytest/connection_available_test.go |
| +++ b/internal/runner/certified/discoverytest/connection_available_test.go |
| @@ -164,8 +164,8 @@ func TestConnectionAvailableGuards(t *testing.T) { |
| if !want && kind != "preflight" && kind != "maintenance" && calls != 0 { |
| t.Fatal("uncertified route probed") |
| } |
| - if kind == "maintenance" && report.UnavailableReason != "account.sign_in_again" { |
| - t.Fatal("maintenance reason lost") |
| + if kind == "maintenance" && report.UnavailableReason == "account.sign_in_again" { |
| + t.Fatal("maintenance incorrectly required sign-in") |
| } |
| if want { |
| action := "coordinate" |
diff --git a/internal/runner/certified/owner.go b/internal/runner/certified/owner.go| index 327ebe93..f2b6e291 100644 |
| --- a/internal/runner/certified/owner.go |
| +++ b/internal/runner/certified/owner.go |
| @@ -15,3 +15,10 @@ func OwnerConnectionReport(ctx context.Context, b runnersetup.AccountBinding, m |
| func OwnerRoute(person, runner string, s runnerproto.Selection) bool { |
| return s.Isolation.Mode == "owner mode" && s.Isolation.Status == "confined" && !s.Isolation.RunnerTainted && s.Person != "" && s.Person == person && s.RunnerID != "" && s.RunnerID == runner |
| } |
| + |
| +func LauncherVersion() string { |
| + if v := release.BuildManifest().LauncherVersion; v != "" { |
| + return v |
| + } |
| + return provider.PolicyVersion |
| +} |
diff --git a/internal/runner/certified_network_test.go b/internal/runner/certified_network_test.go| index bea9bfea..e669019b 100644 |
| --- a/internal/runner/certified_network_test.go |
| +++ b/internal/runner/certified_network_test.go |
| @@ -82,7 +82,6 @@ func TestPolicyHashIndependentOfReleaseManifest(t *testing.T) { |
| b, in := certificationPolicyFixture(t) |
| p, err := certified.BuildPolicy(b, in, release.Manifest{}) |
| mustJournal(t, err) |
| - // Both runtime files are independent of the manifest's bytes and runner stamp. |
| altered := release.BuildManifest() |
| altered.GateEvidence = []string{"changed release manifest"} |
| changed, err := certified.BuildPolicy(b, in, altered) |
| @@ -98,7 +97,6 @@ func TestPolicyHashIndependentOfReleaseManifest(t *testing.T) { |
| t.Fatal("tool proxy digest omitted from policy") |
| } |
| } |
| - |
| func TestRuntimeMountsStandaloneToolProxy(t *testing.T) { |
| b, in := certificationPolicyFixture(t) |
| lease, err := b.AccountLease() |
| @@ -119,7 +117,11 @@ func TestRuntimeMountsStandaloneToolProxy(t *testing.T) { |
| mustJournal(t, os.WriteFile(c.AccountBindingsPath, marshal([]AccountBinding{binding}), 0600)) |
| r := Runtime{cfg: c} |
| build := func() provider.Policy { |
| - l, cleanup, err := r.constructDirect(context.Background(), provider.Selection{Provider: b.Provider, Family: "gpt", Model: "model", AccountID: b.AccountID}, c.WorkspaceRoot, "implement") |
| + source, err := c.DirectBinding(binding) |
| + mustJournal(t, err) |
| + account, err := provider.OpenAccount(context.Background(), source) |
| + mustJournal(t, err) |
| + l, cleanup, err := r.constructDirectLease(context.Background(), provider.Selection{Provider: b.Provider, Family: "gpt", Model: "model", AccountID: b.AccountID}, c.WorkspaceRoot, "implement", release.BuildManifest(), account) |
| if cleanup != nil { |
| defer cleanup() |
| } |
| @@ -150,7 +152,6 @@ func TestRuntimeMountsStandaloneToolProxy(t *testing.T) { |
| t.Fatal("helper digest not bound to policy") |
| } |
| } |
| - |
| func TestCertifiedNetworkConflictDiagnostic(t *testing.T) { |
| m := release.BuildManifest() |
| for i, host := range []string{"auth.first.invalid", "auth.second.invalid"} { |
diff --git a/internal/runner/connections.go b/internal/runner/connections.go| index c608614d..c06e3fed 100644 |
| --- a/internal/runner/connections.go |
| +++ b/internal/runner/connections.go |
| @@ -29,26 +29,13 @@ func (c Config) securityPaths(bs []AccountBinding) workspace.SecurityPaths { |
| } |
| return workspace.SecurityPaths{RunnerState: c.StateDir, RunnerConfig: c.AccountBindingsPath, Journal: filepath.Join(c.StateDir, "journal.db"), Bearer: filepath.Join(c.StateDir, "credentials.json"), Cleanup: filepath.Join(c.StateDir, "credentials.json"), ForgeCredential: c.AmadanCredentialPath, LegacyHome: filepath.Join(home, ".paseo"), SSH: filepath.Join(home, ".ssh"), ProviderHomes: homes} |
| } |
| -func canonicalSecurityPath(path string) (string, error) { |
| - tail := "" |
| - for parent := path; ; parent = filepath.Dir(parent) { |
| - real, err := filepath.EvalSymlinks(parent) |
| - if err == nil { |
| - return filepath.Join(real, tail), nil |
| - } |
| - if !os.IsNotExist(err) || parent == filepath.Dir(parent) { |
| - return "", provider.ErrPolicy |
| - } |
| - tail = filepath.Join(filepath.Base(parent), tail) |
| - } |
| -} |
| func bindingPolicy(c Config, bs []AccountBinding, b AccountBinding) (provider.ReadPolicy, error) { |
| s := c.securityPaths(bs) |
| paths := append([]string{s.RunnerState, s.RunnerConfig, s.Journal, s.Bearer, s.Cleanup, s.ForgeCredential, s.LegacyHome, s.SSH}, s.ProviderHomes...) |
| paths = append(paths, filepath.Join(c.StateDir, "private")) |
| var denied []string |
| for _, p := range paths { |
| - real, err := canonicalSecurityPath(p) |
| + real, err := workspace.CanonicalSecurityPath(p, provider.ErrPolicy) |
| if err != nil { |
| return provider.ReadPolicy{}, err |
| } |
| @@ -126,14 +113,11 @@ func loadDirectBindings(path string) ([]AccountBinding, error) { |
| // a no-prompt account-status probe. The dispatch path must open a fresh lease. |
| func DiscoverDirect(ctx context.Context, c Config, probe func(context.Context, provider.Binding) (provider.Identity, error)) ([]DirectAccount, error) { |
| return discoverDirect(ctx, c, func(ctx context.Context, b provider.Binding) (provider.Identity, error) { |
| - l, e := provider.OpenAccount(ctx, b) |
| + l, e := provider.OpenAccountRefreshing(ctx, b, probe) |
| if e != nil { |
| return provider.Identity{}, e |
| } |
| defer l.Close() |
| - if e = l.Preflight(ctx, probe); e != nil { |
| - return provider.Identity{}, e |
| - } |
| return l.Identity(), nil |
| }) |
| } |
diff --git a/internal/runner/diagnostics.go b/internal/runner/diagnostics.go| index 330f3a09..e7e1f75d 100644 |
| --- a/internal/runner/diagnostics.go |
| +++ b/internal/runner/diagnostics.go |
| @@ -55,7 +55,7 @@ func Diagnostic(err error) (string, string) { |
| code = "runner.timeout" |
| case errors.As(err, &network): |
| code = "runner.network" |
| - case errors.Is(err, provider.ErrAccountMaintenance): |
| + case errors.Is(err, provider.ErrLoginRequired): |
| code = "account.sign_in_again" |
| case errors.Is(err, provider.ErrIdentity): |
| code = "runner.identity" |
diff --git a/internal/runner/provider/accounts.go b/internal/runner/provider/accounts.go| index a0f45039..e4d2a1c8 100644 |
| --- a/internal/runner/provider/accounts.go |
| +++ b/internal/runner/provider/accounts.go |
| @@ -107,6 +107,7 @@ func privateDirectory(f *os.File) bool { |
| // confirms CLI-observed metadata at enrolment. It is not remote attestation. |
| type AccountLease struct { |
| mu sync.Mutex |
| + sourceFreshUntil time.Time |
| source Binding |
| rules HomeRules |
| dir *os.File |
| @@ -126,7 +127,16 @@ type AccountLease struct { |
| func OpenAccount(ctx context.Context, b Binding) (*AccountLease, error) { |
| return openAccount(ctx, b, DefaultHomeRules()) |
| } |
| -func openAccount(ctx context.Context, b Binding, r HomeRules) (_ *AccountLease, err error) { |
| + |
| +// OpenAccountRefreshing runs the official CLI in the locked source home before |
| +// making a runtime copy. The lock remains held through the attempt. |
| +func OpenAccountRefreshing(ctx context.Context, b Binding, refresh func(context.Context, Binding) (Identity, error)) (*AccountLease, error) { |
| + return openAccountRefreshing(ctx, b, DefaultHomeRules(), refresh) |
| +} |
| +func openAccount(ctx context.Context, b Binding, r HomeRules) (*AccountLease, error) { |
| + return openAccountRefreshing(ctx, b, r, nil) |
| +} |
| +func openAccountRefreshing(ctx context.Context, b Binding, r HomeRules, refresh func(context.Context, Binding) (Identity, error)) (_ *AccountLease, err error) { |
| if e := ctx.Err(); e != nil { |
| return nil, e |
| } |
| @@ -168,6 +178,19 @@ func openAccount(ctx context.Context, b Binding, r HomeRules) (_ *AccountLease, |
| if r.RefusesPath(b.RuntimeRoot) || !cleanPath(b.RuntimeRoot) || withinPath(b.RuntimeRoot, b.Home) || withinPath(b.Home, b.RuntimeRoot) { |
| return nil, ErrPolicy |
| } |
| + if refresh != nil { |
| + id, err := refresh(ctx, b) |
| + if err != nil { |
| + return nil, err |
| + } |
| + if !observedIdentityMatches(b, id) { |
| + return nil, ErrIdentity |
| + } |
| + if _, _, err = l.snapshot(); err != nil { |
| + return nil, err |
| + } |
| + l.sourceFreshUntil = time.Now().Add(25 * time.Minute) |
| + } |
| root, e := makePrivateRoot(b.RuntimeRoot) |
| if e != nil { |
| return nil, e |
| @@ -451,6 +474,9 @@ func (l *AccountLease) latch(err error) { |
| } |
| } |
| func (l *AccountLease) validate(ctx context.Context) (err error) { |
| + if !l.sourceFreshUntil.IsZero() && !time.Now().Before(l.sourceFreshUntil) { |
| + return ErrPreflightRequired |
| + } |
| defer func() { l.latch(err) }() |
| if l.contained { |
| return accountContainment("latched") |
| @@ -508,6 +534,9 @@ func (l *AccountLease) Preflight(ctx context.Context, probe func(context.Context |
| // private runtime home. The adapter must observe the same identity without |
| // prompting. A successful commit still requires Preflight before another turn. |
| func (l *AccountLease) CommitRefresh(ctx context.Context, probe func(context.Context, Binding) (Identity, error)) error { |
| + if !l.sourceFreshUntil.IsZero() { |
| + return ErrPolicy |
| + } |
| return l.check(ctx, probe, true) |
| } |
| func (l *AccountLease) check(ctx context.Context, probe func(context.Context, Binding) (Identity, error), refresh bool) error { |
diff --git a/internal/runner/provider/actions.go b/internal/runner/provider/actions.go| index eb2335ca..95859da8 100644 |
| --- a/internal/runner/provider/actions.go |
| +++ b/internal/runner/provider/actions.go |
| @@ -50,7 +50,7 @@ func (p ActionProfile) MCPTools() []string { |
| } |
| func CoordinatorTools() []string { |
| - return []string{"read_project", "read_task", "propose_project", "propose_plan", "ask_person", "route_to_task", "post_message", "suggest_preference", "suggest_specialist", "suggest_playbook"} |
| + return []string{"equipo_status", "read_project", "read_task", "propose_project", "propose_plan", "ask_person", "route_to_task", "post_message", "suggest_preference", "suggest_specialist", "suggest_playbook"} |
| } |
| // Codex 0.165.0 registers these whenever MCP is configured. The coordinator's |
diff --git a/internal/runner/provider/login.go b/internal/runner/provider/login.go| index e4ba39c9..61c1dd06 100644 |
| --- a/internal/runner/provider/login.go |
| +++ b/internal/runner/provider/login.go |
| @@ -3,6 +3,7 @@ package provider |
| import ( |
| "context" |
| "os" |
| + "strings" |
| "time" |
| ) |
| @@ -20,6 +21,8 @@ type LoginResult struct { |
| Identity Identity |
| } |
| +const ErrLoginRequired Error = "account.sign_in_again" |
| + |
| const ErrLoginUnavailable Error = "account_setup.unavailable" |
| // NewLoginHome allocates an empty private home. Existing accounts are never |
| @@ -57,3 +60,17 @@ func CheckLoginHome(home string) error { |
| } |
| return nil |
| } |
| + |
| +// SignInCommand contains paths only, never credentials or an authorization URL. |
| +func SignInCommand(name, home string, options LoginOptions) string { |
| + quote := func(s string) string { return "'" + strings.ReplaceAll(s, "'", "'\"'\"'") + "'" } |
| + prefix := "flock --exclusive --close " + quote(home) + " env HOME=" + quote(home) |
| + if name == "claude" { |
| + return prefix + " DISABLE_AUTOUPDATER=1 CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC=1 CLAUDE_CONFIG_DIR=" + quote(home) + " CLAUDE_SECURESTORAGE_CONFIG_DIR=" + quote(home) + " " + quote(options.ClaudePath) + " auth login" |
| + } |
| + return prefix + " CODEX_HOME=" + quote(home) + " " + quote(options.CodexPath) + " login --device-auth" |
| +} |
| + |
| +func OpenAccountWithCLI(ctx context.Context, b Binding, options LoginOptions) (*AccountLease, error) { |
| + return OpenAccountRefreshing(ctx, b, func(ctx context.Context, b Binding) (Identity, error) { return RefreshLogin(ctx, b, options) }) |
| +} |
diff --git a/internal/runner/provider/login_probe.go b/internal/runner/provider/login_probe.go| index 3ff19407..e5a5dbd6 100644 |
| --- a/internal/runner/provider/login_probe.go |
| +++ b/internal/runner/provider/login_probe.go |
| @@ -22,15 +22,27 @@ func (b *limitedLoginOutput) Write(p []byte) (int, error) { |
| } |
| // Probe uses the Plan 2b identity readback contracts, never login output. |
| -// The same function is used again on the OpenAccount lease's staged home. |
| +// Unconfined CLI probes run only in source homes, under the caller's lock. |
| func (d *terminalLoginDriver) Probe(ctx context.Context, b Binding) (Identity, error) { |
| + return d.probe(ctx, b, false) |
| +} |
| + |
| +// RefreshLogin uses only CLI account metadata. Tokens remain private to the CLI. |
| +func RefreshLogin(ctx context.Context, b Binding, options LoginOptions) (Identity, error) { |
| + return (&terminalLoginDriver{options: options}).probe(ctx, b, true) |
| +} |
| + |
| +func (d *terminalLoginDriver) probe(ctx context.Context, b Binding, refresh bool) (Identity, error) { |
| + if b.provenance != nil { |
| + return Identity{}, ErrPolicy |
| + } |
| if ctx.Err() != nil { |
| return Identity{}, ctx.Err() |
| } |
| if !d.Supported(b.Provider) { |
| return Identity{}, ErrLoginUnavailable |
| } |
| - ctx, cancel := context.WithTimeout(ctx, 10*time.Second) |
| + ctx, cancel := context.WithTimeout(ctx, 30*time.Second) |
| defer cancel() |
| if b.Provider == "claude" { |
| cmd := exec.CommandContext(ctx, d.binary(b.Provider), "auth", "status", "--json") |
| @@ -38,8 +50,21 @@ func (d *terminalLoginDriver) Probe(ctx context.Context, b Binding) (Identity, e |
| cmd.Dir = b.Home |
| out := &limitedLoginOutput{} |
| cmd.Stdout = out |
| - if cmd.Run() != nil { |
| - return Identity{}, ErrIdentity |
| + err := cmd.Run() |
| + if ctx.Err() != nil { |
| + return Identity{}, ctx.Err() |
| + } |
| + var status struct { |
| + LoggedIn *bool `json:"loggedIn"` |
| + } |
| + if refresh && json.Unmarshal(out.Bytes(), &status) == nil && status.LoggedIn != nil && !*status.LoggedIn { |
| + return Identity{}, ErrLoginRequired |
| + } |
| + if err != nil { |
| + if !refresh { |
| + return Identity{}, ErrIdentity |
| + } |
| + return Identity{}, ErrLoginUnavailable |
| } |
| return ClaudeLoginIdentity(out.Bytes()) |
| } |
| @@ -94,6 +119,9 @@ func (d *terminalLoginDriver) Probe(ctx context.Context, b Binding) (Identity, e |
| startupNoticeSeen = true |
| continue |
| } |
| + if refresh && method == "account/read" && string(r.ID) == strconv.Quote(id) && r.Method == "" && refreshRevoked(r.Error) { |
| + return nil, ErrLoginRequired |
| + } |
| if string(r.ID) != strconv.Quote(id) || r.Method != "" || len(r.Error) != 0 { |
| return nil, ErrIdentity |
| } |
| @@ -109,10 +137,18 @@ func (d *terminalLoginDriver) Probe(ctx context.Context, b Binding) (Identity, e |
| if _, err = io.WriteString(in, "{\"method\":\"initialized\",\"params\":{}}\n"); err != nil { |
| return Identity{}, ErrIdentity |
| } |
| - raw, err = call("2", "account/read", map[string]bool{"refreshToken": false}) |
| + raw, err = call("2", "account/read", map[string]bool{"refreshToken": refresh}) |
| if err != nil { |
| return Identity{}, err |
| } |
| + if refresh { |
| + var status struct { |
| + Account json.RawMessage `json:"account"` |
| + } |
| + if json.Unmarshal(raw, &status) == nil && string(status.Account) == "null" { |
| + return Identity{}, ErrLoginRequired |
| + } |
| + } |
| return CodexLoginIdentity(raw) |
| } |
| @@ -135,3 +171,16 @@ func CodexLoginIdentity(raw []byte) (Identity, error) { |
| } |
| return Identity{AccountID: v.Account.Email, ProviderVersion: LoginVersion("codex")}, nil |
| } |
| + |
| +func refreshRevoked(raw []byte) bool { |
| + var reply struct{ Message string } |
| + if json.Unmarshal(raw, &reply) != nil { |
| + return false |
| + } |
| + for _, reason := range []string{"refresh_token_expired", "refresh_token_reused", "refresh_token_invalidated", "invalid_grant", "your refresh token has expired", "your refresh token was already used", "your refresh token was revoked"} { |
| + if strings.Contains(reply.Message, reason) { |
| + return true |
| + } |
| + } |
| + return false |
| +} |
diff --git a/internal/runner/provider/refresh_cli_test.go b/internal/runner/provider/refresh_cli_test.go| new file mode 100644 |
| index 00000000..b8553181 |
| --- /dev/null |
| +++ b/internal/runner/provider/refresh_cli_test.go |
| @@ -0,0 +1,97 @@ |
| +package provider |
| + |
| +import ( |
| + "context" |
| + "errors" |
| + "os" |
| + "path/filepath" |
| + "strings" |
| + "testing" |
| +) |
| + |
| +func TestRefreshUsesOfficialCLIWithoutTurn(t *testing.T) { |
| + for _, name := range []string{"claude", "codex"} { |
| + t.Run(name, func(t *testing.T) { |
| + root := t.TempDir() |
| + binary := filepath.Join(root, name) |
| + script := `#!/bin/sh |
| +case "$*" in |
| + '--version') echo 'VERSION'; exit 0;; |
| + 'auth login --help'|'login --device-auth --help') exit 0;; |
| +esac |
| +[ "$PWD" = "$HOME" ] || exit 20 |
| +case "$*" in |
| + 'auth status --json') |
| + [ "$CLAUDE_CONFIG_DIR" = "$HOME" ] || exit 21 |
| + echo '{"loggedIn":true,"authMethod":"claude.ai","email":"fixture@example.invalid"}' |
| + echo refreshed > "$HOME/fresh" |
| + ;; |
| + 'app-server --strict-config --listen stdio://') |
| + [ "$CODEX_HOME" = "$HOME" ] || exit 22 |
| + IFS= read -r line |
| + printf '{"id":"1","result":{"userAgent":"equipo/0.165.0 fixture","codexHome":"%s"}}\n' "$CODEX_HOME" |
| + IFS= read -r line |
| + IFS= read -r line |
| + case "$line" in *'"account/read"'*'"refreshToken":true'*) ;; *) exit 23;; esac |
| + echo refreshed > "$HOME/fresh" |
| + echo '{"id":"2","result":{"account":{"type":"chatgpt","email":"fixture@example.invalid"}}}' |
| + ;; |
| + *) exit 24;; |
| +esac |
| +` |
| + version := "2.1.312 (Claude Code)" |
| + if name == "codex" { |
| + version = "codex-cli 0.165.0" |
| + } |
| + script = strings.ReplaceAll(script, "VERSION", version) |
| + if err := os.WriteFile(binary, []byte(script), 0700); err != nil { |
| + t.Fatal(err) |
| + } |
| + id, err := RefreshLogin(context.Background(), Binding{Home: root, Provider: name}, LoginOptions{ClaudePath: binary, CodexPath: binary}) |
| + if err != nil || id.AccountID != "fixture@example.invalid" { |
| + t.Fatal(id, err) |
| + } |
| + if _, err := os.Stat(filepath.Join(root, "fresh")); err != nil { |
| + t.Fatal("no refresh", err) |
| + } |
| + if name == "codex" { |
| + b, rules := accountFixture(t) |
| + lease := openFixture(t, b, rules) |
| + _, err := RefreshLogin(context.Background(), lease.Binding(), LoginOptions{CodexPath: binary}) |
| + if !errors.Is(err, ErrPolicy) { |
| + t.Fatal("unconfined CLI accepted a staged home", err) |
| + } |
| + } |
| + }) |
| + } |
| +} |
| + |
| +func TestRefreshTransientIsNotSignInAgain(t *testing.T) { |
| + for _, revoked := range []bool{false, true} { |
| + t.Run(map[bool]string{false: "transient", true: "revoked"}[revoked], func(t *testing.T) { |
| + root := t.TempDir() |
| + binary := filepath.Join(root, "claude") |
| + reply := "exit 1" |
| + if revoked { |
| + reply = `echo '{"loggedIn":false}'; exit 1` |
| + } |
| + script := "#!/bin/sh\ncase \"$*\" in '--version') echo '2.1.312 (Claude Code)'; exit 0;; 'auth login --help') exit 0;; esac\n" + reply + "\n" |
| + if err := os.WriteFile(binary, []byte(script), 0700); err != nil { |
| + t.Fatal(err) |
| + } |
| + _, err := RefreshLogin(context.Background(), Binding{Home: root, Provider: "claude"}, LoginOptions{ClaudePath: binary}) |
| + if err == nil || errors.Is(err, ErrLoginRequired) != revoked { |
| + t.Fatal("wrong refresh classification", err) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +func TestRefreshRevocationCodes(t *testing.T) { |
| + for _, code := range []string{"refresh_token_expired", "refresh_token_reused", "refresh_token_invalidated", "upstream_unavailable"} { |
| + raw := []byte(`{"code":-32000,"message":"` + code + `"}`) |
| + if refreshRevoked(raw) != (code != "upstream_unavailable") { |
| + t.Fatal("wrong refresh classification", code) |
| + } |
| + } |
| +} |
diff --git a/internal/runner/provider/source_refresh_test.go b/internal/runner/provider/source_refresh_test.go| new file mode 100644 |
| index 00000000..e6b14bea |
| --- /dev/null |
| +++ b/internal/runner/provider/source_refresh_test.go |
| @@ -0,0 +1,85 @@ |
| +package provider |
| + |
| +import ( |
| + "context" |
| + "errors" |
| + "os" |
| + "path/filepath" |
| + "testing" |
| + "time" |
| +) |
| + |
| +func TestSourceRefreshBeforeStageUnderLock(t *testing.T) { |
| + b, rules := accountFixture(t) |
| + calls := 0 |
| + refresh := func(ctx context.Context, source Binding) (Identity, error) { |
| + calls++ |
| + if source.Home != b.Home { |
| + t.Fatal("refresh ran outside source home") |
| + } |
| + if other, err := openAccount(ctx, b, rules); !errors.Is(err, ErrAccountBusy) { |
| + if other != nil { |
| + other.Close() |
| + } |
| + t.Fatalf("source not locked: %v", err) |
| + } |
| + writeFake(t, filepath.Join(source.Home, "auth.json"), `{"token":"fresh"}`) |
| + return b.Expected, nil |
| + } |
| + l, err := openAccountRefreshing(context.Background(), b, rules, refresh) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + defer l.Close() |
| + raw, err := os.ReadFile(filepath.Join(l.Binding().Home, "auth.json")) |
| + if err != nil || string(raw) != `{"token":"fresh"}` || calls != 1 { |
| + t.Fatal("staged stale login", err, calls) |
| + } |
| + if other, err := openAccountRefreshing(context.Background(), b, rules, refresh); !errors.Is(err, ErrAccountBusy) { |
| + if other != nil { |
| + other.Close() |
| + } |
| + t.Fatalf("active lease refreshed: %v", err) |
| + } |
| + if calls != 1 { |
| + t.Fatal("refresh ran while leased") |
| + } |
| +} |
| + |
| +func TestSourceRefreshFailureDoesNotStage(t *testing.T) { |
| + for _, kind := range []string{"transient", "identity"} { |
| + t.Run(kind, func(t *testing.T) { |
| + b, rules := accountFixture(t) |
| + l, err := openAccountRefreshing(context.Background(), b, rules, func(context.Context, Binding) (Identity, error) { |
| + if kind == "transient" { |
| + return Identity{}, ErrLoginUnavailable |
| + } |
| + return Identity{AccountID: "other"}, nil |
| + }) |
| + if err == nil || l != nil { |
| + t.Fatal("failed refresh staged") |
| + } |
| + entries, _ := os.ReadDir(b.RuntimeRoot) |
| + if len(entries) != 0 { |
| + t.Fatal("failed refresh left runtime credentials") |
| + } |
| + }) |
| + } |
| +} |
| + |
| +func TestSourceRefreshLeaseExpiresAndCannotWriteBack(t *testing.T) { |
| + b, rules := accountFixture(t) |
| + l, err := openAccountRefreshing(context.Background(), b, rules, func(context.Context, Binding) (Identity, error) { return b.Expected, nil }) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + defer l.Close() |
| + preflightFixture(t, l) |
| + l.sourceFreshUntil = time.Now().Add(-time.Second) |
| + if err = l.BeginTurn(context.Background()); err == nil { |
| + t.Fatal("expired staging began turn") |
| + } |
| + if err = l.CommitRefresh(context.Background(), func(context.Context, Binding) (Identity, error) { return b.Expected, nil }); err == nil { |
| + t.Fatal("staged refresh could overwrite source") |
| + } |
| +} |
diff --git a/internal/runner/residual_outcome_test.go b/internal/runner/residual_outcome_test.go| index 3ffd1b44..29623735 100644 |
| --- a/internal/runner/residual_outcome_test.go |
| +++ b/internal/runner/residual_outcome_test.go |
| @@ -28,7 +28,7 @@ func TestDeterministicAttemptErrorsFailWithReason(t *testing.T) { |
| reason string |
| }{ |
| {context.Canceled, "runner.cancelled"}, {context.DeadlineExceeded, "runner.timeout"}, |
| - {provider.ErrAccountMaintenance, "account.sign_in_again"}, |
| + {provider.ErrAccountMaintenance, "runner.unavailable"}, {provider.ErrLoginRequired, "account.sign_in_again"}, |
| {provider.ErrIdentity, "runner.identity"}, {ErrPromptTooLarge, "runner.prompt_too_large"}, |
| {team.ErrEvidence, "runner.evidence"}, {team.ErrQuota, "runner.quota"}, |
| {team.ErrBudget, "runner.budget"}, {team.ErrReplayUnsafe, "runner.replay"}, |
diff --git a/internal/runner/runtime_direct.go b/internal/runner/runtime_direct.go| index 60f472ee..bb887698 100644 |
| --- a/internal/runner/runtime_direct.go |
| +++ b/internal/runner/runtime_direct.go |
| @@ -13,12 +13,6 @@ import ( |
| "amadan.net/oficina/equipo/internal/runnerproto" |
| ) |
| -func directLauncherVersion() string { |
| - if v := release.BuildManifest().LauncherVersion; v != "" { |
| - return v |
| - } |
| - return provider.PolicyVersion |
| -} |
| func (r *Runtime) constructDirect(ctx context.Context, s provider.Selection, work, step string) (provider.Launch, func() error, error) { |
| return r.constructDirectManifest(ctx, s, work, step, release.BuildManifest()) |
| } |
| @@ -32,16 +26,22 @@ func (r *Runtime) constructDirectManifest(ctx context.Context, s provider.Select |
| if err != nil { |
| return provider.Launch{}, nil, err |
| } |
| - lease, err := provider.OpenAccount(ctx, binding) |
| + if err = r.verifyRelease(); err != nil { |
| + return provider.Launch{}, nil, err |
| + } |
| + lease, err := provider.OpenAccountWithCLI(ctx, binding, provider.LoginOptions{ClaudePath: r.cfg.ClaudePath, CodexPath: r.cfg.CodexPath}) |
| if err != nil { |
| return provider.Launch{}, nil, err |
| } |
| + return r.constructDirectLease(ctx, s, work, step, manifest, lease) |
| +} |
| +func (r *Runtime) constructDirectLease(ctx context.Context, s provider.Selection, work, step string, manifest release.Manifest, lease *provider.AccountLease) (provider.Launch, func() error, error) { |
| policyScratch, err := os.MkdirTemp(r.cfg.ScratchRoot, "policy-") |
| if err != nil { |
| return provider.Launch{}, lease.Close, err |
| } |
| cleanup := func() error { return errors.Join(lease.Close(), os.RemoveAll(policyScratch)) } |
| - binding = lease.Binding() |
| + binding := lease.Binding() |
| in, err := CertificationInputs(ctx, r.cfg, s, binding, work, step, policyScratch) |
| if err != nil { |
| return provider.Launch{}, cleanup, err |
| @@ -165,6 +165,9 @@ func (r *Runtime) discoverNamespaces(ctx context.Context) ([]runnerproto.Connect |
| if err = r.journal.prunePreflights(ctx, r.namespaces.Forget); err != nil { |
| return nil, err |
| } |
| + if report.UnavailableReason == "account.sign_in_again" { |
| + report.SignInCommand = provider.SignInCommand(b.Provider, b.ProviderHome, provider.LoginOptions{ClaudePath: r.cfg.ClaudePath, CodexPath: r.cfg.CodexPath}) |
| + } |
| reports = append(reports, report) |
| } |
| return reports, nil |
diff --git a/internal/runner/setup/account_login.go b/internal/runner/setup/account_login.go| index d6b4e04a..b01af8b7 100644 |
| --- a/internal/runner/setup/account_login.go |
| +++ b/internal/runner/setup/account_login.go |
| @@ -251,14 +251,11 @@ func (l *AccountLogin) verify(ctx context.Context, id provider.Identity) (provid |
| if err != nil || ce != nil { |
| return b, provider.ErrIdentity |
| } |
| - lease, err := provider.OpenAccount(ctx, b) |
| + lease, err := provider.OpenAccountRefreshing(ctx, b, l.Probe) |
| if err != nil { |
| return b, err |
| } |
| defer lease.Close() |
| - if err = lease.Preflight(ctx, l.Probe); err != nil { |
| - return b, provider.ErrIdentity |
| - } |
| return b, nil |
| } |
| func (l *AccountLogin) Cancel(ctx context.Context) error { |
diff --git a/internal/runner/setup/account_resume.go b/internal/runner/setup/account_resume.go| index ee9449ed..2b37f60d 100644 |
| --- a/internal/runner/setup/account_resume.go |
| +++ b/internal/runner/setup/account_resume.go |
| @@ -36,14 +36,11 @@ func ResumeSavedAccount(ctx context.Context, path, person string, s runnerproto. |
| return true, provider.ErrIdentity |
| } |
| b := provider.Binding{ID: row.ID, Home: row.ProviderHome, AccountID: row.AccountID, Provider: row.Provider, Expected: row.ExpectedIdentity, RuntimeRoot: filepath.Join(filepath.Dir(path), "accounts", "runtime")} |
| - lease, err := provider.OpenAccount(ctx, b) |
| + lease, err := provider.OpenAccountRefreshing(ctx, b, probe) |
| if err != nil { |
| return true, err |
| } |
| defer lease.Close() |
| - if err = lease.Preflight(ctx, probe); err != nil { |
| - return true, provider.ErrIdentity |
| - } |
| _, err = instance.ReportAccountSetup(ctx, runnerproto.AccountSetupResult{ID: s.ID, Revision: s.Revision, State: "connected", AccountID: b.AccountID, ProviderVersion: b.Expected.ProviderVersion}) |
| return true, err |
| } |
diff --git a/internal/runner/workspace/security_paths.go b/internal/runner/workspace/security_paths.go| new file mode 100644 |
| index 00000000..da5359c8 |
| --- /dev/null |
| +++ b/internal/runner/workspace/security_paths.go |
| @@ -0,0 +1,20 @@ |
| +package workspace |
| + |
| +import ( |
| + "os" |
| + "path/filepath" |
| +) |
| + |
| +func CanonicalSecurityPath(path string, invalid error) (string, error) { |
| + tail := "" |
| + for parent := path; ; parent = filepath.Dir(parent) { |
| + real, err := filepath.EvalSymlinks(parent) |
| + if err == nil { |
| + return filepath.Join(real, tail), nil |
| + } |
| + if !os.IsNotExist(err) || parent == filepath.Dir(parent) { |
| + return "", invalid |
| + } |
| + tail = filepath.Join(filepath.Base(parent), tail) |
| + } |
| +} |
diff --git a/internal/runnerproto/types.go b/internal/runnerproto/types.go| index 337cf116..0355622f 100644 |
| --- a/internal/runnerproto/types.go |
| +++ b/internal/runnerproto/types.go |
| @@ -121,7 +121,8 @@ type ConnectionRouting struct { |
| } |
| type ConnectionReport struct { |
| - OwnerMode bool `json:",omitempty"` |
| + SignInCommand string `json:",omitempty"` |
| + OwnerMode bool `json:",omitempty"` |
| LauncherVersion, BwrapVersion, PolicyVersion string |
| TrialReady bool |
| ProviderVersionSource string |
diff --git a/scripts/runner-reference-allowlist.json b/scripts/runner-reference-allowlist.json| index 0619823d..2d34bc9f 100644 |
| --- a/scripts/runner-reference-allowlist.json |
| +++ b/scripts/runner-reference-allowlist.json |
| @@ -10078,5 +10078,26 @@ |
| "match": "node", |
| "count": 1, |
| "reason": "Markdown syntax tree node traversal in the Go renderer; no external runtime." |
| + }, |
| + { |
| + "path": "docs/superpowers/plans/CODEX-BRIEF-self-heal.md", |
| + "line_sha256": "d298baade4464399c3f96ed314ae30d1420b28f8b115d053a13da3da6638a131", |
| + "match": "equipo-runner", |
| + "count": 1, |
| + "reason": "Self-heal dispatch or review evidence refers to the authorized Go runner service and commands." |
| + }, |
| + { |
| + "path": "docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md", |
| + "line_sha256": "7aa4058b22ebc80d9e8de7612aa7ce9177ac8896b406318e868ac193c0ae9807", |
| + "match": "equipo-runner", |
| + "count": 1, |
| + "reason": "Self-heal dispatch or review evidence refers to the authorized Go runner service and commands." |
| + }, |
| + { |
| + "path": "internal/equipo/copy.go", |
| + "line_sha256": "44c7f2446bab2ba2f7dbef227b9a61a033b7df50b7e74ffafb32dbbad28558d1", |
| + "match": "equipo-runner", |
| + "count": 1, |
| + "reason": "Pending self-heal setup action invokes the existing Go runner enrollment command." |
| } |
| ] |