package plan3test import ( "context" "crypto/ed25519" "crypto/rand" "encoding/base64" "encoding/json" "fmt" "io" "net/http/httptest" "net/url" "os" "path/filepath" "regexp" "strings" "testing" "time" "amadan.net/oficina/equipo/internal/equipo" "amadan.net/oficina/equipo/internal/equipo/personapi" "amadan.net/oficina/equipo/internal/runner" "amadan.net/oficina/equipo/internal/runner/provider" runnersetup "amadan.net/oficina/equipo/internal/runner/setup" "amadan.net/oficina/equipo/internal/runnerproto" "amadan.net/oficina/equipo/internal/taskplan" ) func TestCoordinatorAcceptance3B(t *testing.T) { t.Run("onboarding_to_plan", acceptanceOnboarding) t.Run("sourced_recommendation", func(t *testing.T) { planReadDelivery(t, false) }) t.Run("device_answer", acceptanceDeviceAnswer) } func acceptanceOnboarding(t *testing.T) { f := newFixture(t) in, secret := issueInvite(t, f, invitee.Address) inviteSession(t, f, invitee) request := func(method, path, body, key, rev string) *httptest.ResponseRecorder { t.Helper() w := apiRequest(t, f, invitee, method, "/api/v1"+path, body, key, rev) expectHTTP(t, w, 200) return w } request("POST", "/invites/"+in.ID+"/accept", jsonBody(t, personapi.AcceptInviteInput{Secret: secret}), "accept", `"1"`) welcome := request("POST", "/onboarding/advance", `{"step":"welcome"}`, "welcome", `"1"`) // A new application/router resumes persisted setup, including lost-response replay. notificationRouter(t, f, equipo.NewStore(f.DB)) replay := request("POST", "/onboarding/advance", `{"step":"welcome"}`, "welcome", `"1"`) if welcome.Body.String() != replay.Body.String() { t.Fatal("interrupted onboarding lost its saved result") } credential := acceptancePair(t, f, invitee) server := httptest.NewServer(f.Store.RunnerHandler()) t.Cleanup(server.Close) journal, err := runner.OpenJournal(ctx, filepath.Join(t.TempDir(), "state", "runner.db")) must(t, err) t.Cleanup(func() { must(t, journal.Close()) }) client, err := runner.NewHTTPInstance(server.URL, journal, credential) must(t, err) root := filepath.Join(t.TempDir(), "accounts") saved := map[string]provider.Binding{} for i, family := range []string{"claude", "claude", "codex"} { w := request("POST", "/account-setups", fmt.Sprintf(`{"runner_id":%q,"provider":%q,"label":%q}`, credential.RunnerID, family, fmt.Sprint("Personal ", i)), fmt.Sprint("setup-", i), "") setup := apiValue[map[string]any](t, w) id := setup["id"].(string) if setup["command"] != "equipo-runner account login --setup "+id { t.Fatal("missing interactive setup command", setup) } binary := acceptanceLoginCLI(t, family, fmt.Sprintf("account-%d@example.test", i)) driver := provider.NewLoginDriver(provider.LoginOptions{ClaudePath: binary, CodexPath: binary, Input: strings.NewReader("TERMINAL-SECRET\n"), Output: io.Discard, ErrorOutput: io.Discard}) login := &runnersetup.AccountLogin{Root: root, RunnerID: credential.RunnerID, Instance: client, Driver: driver, Probe: driver.(interface { Probe(context.Context, provider.Binding) (provider.Identity, error) }).Probe, Save: func(_ context.Context, s runnerproto.AccountSetup, b provider.Binding) error { if s.RunnerID != credential.RunnerID || b.ID != id || b.AccountID != fmt.Sprintf("account-%d@example.test", i) { return fmt.Errorf("wrong personal identity") } saved[id] = b return nil }, } must(t, runnersetup.RunAccountLogin(ctx, login, id)) result := request("GET", "/account-setups/"+id, "", "", "") if apiValue[map[string]any](t, result)["state"] != "connected" { t.Fatal("terminal login not reported") } expectHTTP(t, apiRequest(t, f, owner, "GET", "/api/v1/account-setups/"+id, "", "", ""), 404) } events, err := journal.Pending(ctx, 100) must(t, err) if len(events) != 0 { t.Fatal("terminal login entered the runner journal", len(events)) } homes, identities := map[string]bool{}, map[string]bool{} for _, b := range saved { stat, err := os.Stat(b.Home) must(t, err) if stat.Mode().Perm() != 0700 || homes[b.Home] || identities[b.Expected.HomeID] || b.Expected.HomeID == "" { t.Fatal("accounts share a home or identity") } homes[b.Home], identities[b.Expected.HomeID] = true, true } if len(saved) != 3 || f.count(t, "SELECT count(*) FROM connections WHERE person=?", invitee.Address) != 3 { t.Fatal("login replaced a personal account") } // Sign-in is not a certificate. Ordinary runner reports must still prove availability. connections := request("GET", "/connections", "", "", "") for _, secret := range []string{"TERMINAL-SECRET", "CREDENTIAL-SECRET", root} { if strings.Contains(connections.Body.String(), secret) { t.Fatal("credential leaked in person API") } if f.count(t, "SELECT count(*) FROM audit_events WHERE CAST(record_id AS TEXT) LIKE ?", "%"+secret+"%") != 0 { t.Fatal("credential leaked in audit") } } state, err := f.Store.Onboarding(ctx, invitee) must(t, err) _, err = f.Store.ChooseOnboardingProvider(ctx, invitee, "claude", equipo.Mutation{RequestID: "provider", Revision: state.Revision}) must(t, err) currentState := request("GET", "/onboarding", "", "", "") request("POST", "/onboarding/advance", `{"step":"account"}`, "account", currentState.Header().Get("ETag")) currentState = request("GET", "/onboarding", "", "", "") expectHTTP(t, apiRequest(t, f, invitee, "POST", "/api/v1/onboarding/advance", `{"step":"runner"}`, "uncertified-runner", currentState.Header().Get("ETag")), 409) // Availability is simulated only after proving sign-in itself grants none. var rows []struct{ ID, ReportsJSON string } must(t, f.DB.G.Table("connections").Where("person=?", invitee.Address).Find(&rows).Error) for _, row := range rows { var reports []equipo.ConnectionReport must(t, json.Unmarshal([]byte(row.ReportsJSON), &reports)) for i := range reports { reports[i].Available = true reports[i].ReadIsolation = true } raw, err := json.Marshal(reports) must(t, err) f.exec(t, "UPDATE connections SET reports_json=?,last_seen=? WHERE id=?", string(raw), time.Now(), row.ID) } request("POST", "/onboarding/advance", `{"step":"runner"}`, "runner", currentState.Header().Get("ETag")) installed := apiValue[personapi.Specialist](t, request("POST", "/templates/qa/install", `{"version":1}`, "specialist", "")) installed.Name = "Our acceptance QA" request("PATCH", "/specialists/"+installed.ID, jsonBody(t, installed.SpecialistInput), "specialist-edit", `"1"`) request("GET", "/specialists/"+installed.ID+"/template-diff", "", "", "") current := apiValue[personapi.Specialist](t, request("GET", "/specialists/"+installed.ID, "", "", "")) if current.Name != installed.Name || current.Revision != 2 { t.Fatal("template preview silently updated specialist") } pb := apiValue[personapi.Playbook](t, request("POST", "/templates/playbook_bug/install", `{"version":1}`, "playbook", "")) pb.Name, pb.Kind = "Bounded feature", "feature" pb.Steps[0].Action, pb.Steps[0].Specialist = "scope", "product" request("PATCH", "/playbooks/"+pb.ID, jsonBody(t, pb.PlaybookInput), "playbook-edit", `"1"`) request("GET", "/playbooks/"+pb.ID+"/template-diff", "", "", "") now := apiValue[personapi.Playbook](t, request("GET", "/playbooks/"+pb.ID, "", "", "")) if now.Name != pb.Name || now.Revision != 2 { t.Fatal("template preview silently updated playbook") } task := f.createTask(t) must(t, f.DB.G.Create(&equipo.DecisionOwner{ProjectID: task.ProjectID, Decision: "work", Address: invitee.Address}).Error) f.planConnections(t, task.ProjectID) notificationRouter(t, f, f.Store) var ids []string for _, row := range rows { var reports []equipo.ConnectionReport must(t, json.Unmarshal([]byte(row.ReportsJSON), &reports)) var template string must(t, f.DB.Writer().QueryRow("SELECT reports_json FROM connections WHERE id=?", reports[0].Provider).Scan(&template)) var certified []equipo.ConnectionReport must(t, json.Unmarshal([]byte(template), &certified)) certified[0].LocalID = reports[0].LocalID certified[0].Routing.BindingID = reports[0].LocalID b := saved[reports[0].LocalID] certified[0].Routing.AccountID = b.AccountID certified[0].Routing.ObservedAccountID = b.AccountID raw, err := json.Marshal(certified) must(t, err) f.exec(t, "UPDATE connections SET reports_json=? WHERE id=?", string(raw), row.ID) ids = append(ids, row.ID) } rawIDs, err := json.Marshal(ids) must(t, err) f.exec(t, "INSERT INTO connection_choices(person,project_id,revision,connection_ids_json,pinned_id,mode) VALUES(?,?,1,?,'','best_fit')", invitee.Address, task.ProjectID, string(rawIDs)) // The project owner chooses the shared default; invitation grants no owner powers. must(t, f.Store.SetPlaybookDefault(ctx, owner, task.ProjectID, taskplan.Feature, pb.ID, equipo.Mutation{RequestID: "default"})) plan, err := f.Store.ProposePlan(ctx, invitee, taskplan.Plan{Kind: taskplan.Feature, ProjectID: task.ProjectID}, equipo.Mutation{RequestID: "feature"}) must(t, err) if plan.PlaybookID != pb.ID || plan.PlaybookRevision != 2 { t.Fatal("feature ignored selected playbook") } for _, action := range []string{"review", "checks", "person"} { found := false for _, step := range plan.Steps { if step.Action == action { found = step.Required } } if !found { t.Fatal("mandatory publishing step absent", action) } } request("POST", "/tasks/"+plan.TaskID+"/plan/approve", `{}`, "approve", `"1"`) if f.count(t, "SELECT count(*) FROM notification_outbox WHERE resource_id=? AND resource_revision=1 AND recipient=?", plan.TaskID, invitee.Address) != 0 { t.Fatal("own proposal or approval created a notification") } request("POST", "/tasks/"+plan.TaskID+"/plan/approve", `{}`, "approve", `"1"`) if f.count(t, "SELECT count(*) FROM audit_events WHERE kind='plan.approve' AND actor=?", invitee.Address) != 1 { t.Fatal("approval replay duplicated effect") } request("POST", "/teams/links", `{"origin":"https://other.example.test","name":"Other team"}`, "team-link", "") teams := request("GET", "/teams", "", "", "") if !strings.Contains(teams.Body.String(), "other.example.test") { t.Fatal("remembered team missing") } page := f.get(t, invitee, "/onboarding") expectHTTP(t, page, 200) for _, word := range []string{"Mac", "coming later", "Hosted by Equipo"} { if !strings.Contains(page.Body.String(), word) { t.Fatal("unsupported runner claim", word) } } expectHTTP(t, inviteRequest(t, f, invitee, "POST", "/onboarding/hosted", nil, nil), 404) } func acceptancePair(t *testing.T, f *fixture, actor equipo.Actor) runnerproto.RunnerCredential { t.Helper() pub, key, err := ed25519.GenerateKey(rand.Reader) must(t, err) c, err := f.Store.BeginEnrolment(ctx, base64.RawURLEncoding.EncodeToString(pub), "Acceptance Linux machine") must(t, err) page := f.get(t, actor, "/runners/enrol?user_code="+c.UserCode) if strings.Contains(page.Body.String(), `value="`+c.UserCode+`"`) { t.Fatal("pairing link prefilled typed code") } form := url.Values{"user_code": {c.UserCode}, "action": {"inspect"}} page = inviteRequest(t, f, actor, "POST", "/runners/enrol", form, nil) expectHTTP(t, page, 200) if !strings.Contains(page.Body.String(), "Acceptance Linux machine") || !strings.Contains(page.Body.String(), time.Now().UTC().Format("2 Jan 2006")) { t.Fatal("pairing omitted machine label or server time") } proof := regexp.MustCompile(`name="confirmation" value="([^"]+)"`).FindStringSubmatch(page.Body.String()) if len(proof) != 2 { t.Fatal("missing inspected pairing proof") } form.Set("confirmation", proof[1]) form.Set("action", "approve") expectHTTP(t, inviteRequest(t, f, actor, "POST", "/runners/enrol", form, nil), 303) p := runnerproto.ExchangeProof{EnrolmentID: c.EnrolmentID, Challenge: c.Challenge, ExchangeNonce: base64.RawURLEncoding.EncodeToString(make([]byte, 32))} p.Signature = base64.RawURLEncoding.EncodeToString(ed25519.Sign(key, runnerproto.EnrolmentProofMessage(c.InstanceID, p))) credential, err := f.Store.ExchangeEnrolment(ctx, c.DeviceSecret, p) must(t, err) if credential.Person != actor.Address { t.Fatal("pairing attached another person") } return credential } func acceptanceDeviceAnswer(t *testing.T) { f, _, _, _, q := nativeConversationFixture(t) notificationRouter(t, f, f.Store) device := approvedDevice(t, f) sub := notificationSubscription(t, f, device) page := notificationFeed(t, f, device, sub.Cursor) var eventID string for _, n := range page.Items { if n.ResourceID == q.ID { eventID = n.ID } } if eventID == "" { t.Fatal("native question notification absent") } current := deviceRequest(t, f, device.Token, "GET", "/api/v1/questions/"+q.ID, "", "", "") expectHTTP(t, current, 200) body := `{"kind":"native","behavior":"allow","updated_input":{"answers":{"Which?":"Blue"}}}` for range 2 { expectHTTP(t, deviceRequest(t, f, device.Token, "POST", "/api/v1/questions/"+q.ID+"/answer", body, "answer", current.Header().Get("ETag")), 200) } if f.count(t, "SELECT count(*) FROM audit_events WHERE kind='question.answer' AND record_id=?", q.ID) != 1 { t.Fatal("device answer effect duplicated") } again := notificationFeed(t, f, device, sub.Cursor) if len(again.Items) != len(page.Items) { t.Fatal("answer duplicated question notification") } f.exec(t, "UPDATE notification_subscriptions SET expires_at=? WHERE id=?", time.Now().Add(-time.Second), sub.ID) expectHTTP(t, deviceRequest(t, f, device.Token, "GET", "/api/v1/notifications?cursor="+url.QueryEscape(sub.Cursor), "", "", ""), 410) if f.Store.AllowNotificationSubscription(ctx, owner, sub.ID) { t.Fatal("expired subscription remains live") } } func acceptanceLoginCLI(t *testing.T, name, account string) string { t.Helper() binary := filepath.Join(t.TempDir(), name) script := `#!/bin/sh set -eu umask 077 case "$*" in '--version') echo 'VERSION'; exit 0 ;; 'auth login --help'|'login --device-auth --help') exit 0 ;; 'auth status --json') test -f "$HOME/.credentials.json"; printf '%s' '{"loggedIn":true,"authMethod":"claude.ai","email":"ACCOUNT"}'; exit 0 ;; 'app-server --strict-config --listen stdio://') test -f "$HOME/auth.json" 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 printf '%s\n' '{"id":"2","result":{"account":{"type":"chatgpt","email":"ACCOUNT"}}}' exit 0 ;; 'auth login') test "$HOME" = "$CLAUDE_CONFIG_DIR"; test "$HOME" = "$CLAUDE_SECURESTORAGE_CONFIG_DIR"; file=.credentials.json ;; 'login --device-auth') test "$HOME" = "$CODEX_HOME"; file=auth.json ;; *) exit 9 ;; esac IFS= read -r code test "$code" = TERMINAL-SECRET printf '%s' '{"token":"CREDENTIAL-SECRET"}' > "$HOME/$file" ` version := "codex-cli 0.165.0" if name == "claude" { version = "2.1.312 (Claude Code)" } must(t, os.WriteFile(binary, []byte(strings.NewReplacer("VERSION", version, "ACCOUNT", account).Replace(script)), 0700)) return binary }