feat: show and guard per-step personal model choices
30 files changed,
+1,372
−225
docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md+90 −0internal/equipo/app.go+1 −0internal/equipo/connection_handlers.go+15 −1internal/equipo/connection_models.go+5 −33internal/equipo/connection_selection.go+34 −11internal/equipo/connection_views.go+6 −40internal/equipo/connections.go+9 −21internal/equipo/copy.go+32 −0internal/equipo/migrations/0026_connection_modes.sql+2 −0internal/equipo/migrations/schema.sql+3 −1internal/equipo/plan_execution.go+5 −96internal/equipo/plan_selection.go+59 −0internal/equipo/planning/approval_settings.go+5 −1internal/equipo/planning/connection_models.go+81 −0internal/equipo/planning/connection_views.go+53 −0internal/equipo/planning/plans.go+4 −1internal/equipo/planning/selection.go+194 −0internal/equipo/planning/selection_policy.go+217 −0internal/equipo/planning/selection_rank.go+57 −0internal/equipo/planning/views.go+9 −0internal/equipo/plans.go+7 −2internal/equipo/runner_execution.go+21 −1internal/equipo/task_prepare.go+5 −11internal/equipo/task_views.go+16 −1internal/equipo/task_wait.go+2 −2internal/equipo/templates/connections.html+2 −2internal/equipo/templates/conversation_card.html+1 −1internal/equipo/templates/plan.html+8 −0internal/plan3test/plan_model_choice_migration_test.go+50 −0internal/plan3test/plan_model_choice_test.go+379 −0
CI failed — run details
diff --git a/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md b/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md| index d14188b0..2e6cd752 100644 |
| --- a/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md |
| +++ b/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md |
| @@ -3650,3 +3650,93 @@ Ten guards were broken one at a time and restored. The required-tail mutation wa |
| ### Copy and handoff |
| 31 new runtime entries are individually marked `COPY REVIEW REQUIRED` in `internal/equipo/copy.go`; the full inventory is in `.superpowers/sdd/2026-11-04-equipo-plan-3-coordinator/task-13-report.md`. The commit subject is `feat: add editable playbooks and project defaults`, with author `codex <codex~paul@keymail.dev>`. No push, merge, deployment, live provider run, sign-in, enrolment, agent delegation or copy-review server. No `.claude/HANDOFF.md`. The existing live-release blockers remain. |
| + |
| + |
| +## Task 14 |
| + |
| +Status: DONE_WITH_CONCERNS. Implementation subject: `feat: show and guard per-step personal model choices`. Required author: `codex <codex~paul@keymail.dev>`. |
| + |
| +Implemented `best_fit`, `pinned`, and `ask` on personal project choices. Migration `0026_connection_modes.sql` defaults old rows to `best_fit` and preserves ticks, pins and revisions. `plan_selections` holds revocable pre-start selections; claimed assignments remain the actual record. Models are registered through the existing root aliases and `planning.Models`, and the schema snapshot matches both fresh and upgraded databases. |
| + |
| +`SelectPlanStep` and `ConfirmPlanSelection` share transaction-bound planning operations. They recheck the person and current roster before replay, compare canonical request inputs, validate the plan revision, fence pending assignments, append audit records and update the conversation card in the same transaction. The confirmation form derives the actor from the verified browser session. Plan approval does not confirm an ask pick. Selection records retain connection, choice and specialist revisions, family, runner, model, reason and allowance-known state. |
| + |
| +Selection intersects the person's project ticks, specialist allowed models, known families, current runner/connection eligibility, pins and explicit step preferences. Review cannot use the builder family, even with a pin. The existing project-pin exception applies only when choosing the other family; an explicit same-family Review pick is rejected. Required Review cannot be replaced by a custom specialist. Unsupported custom execution profiles remain closed. |
| + |
| +Eligible alternatives to the coordinator connection rank before reported headroom. Fixed pins, explicit step preferences and confirmed ask selections remain binding. Unknown remaining allowance never becomes a known zero; supported known flags and amounts are retained from the authenticated connection report. With equal information, connection/provider/model ordering is deterministic. Recorded reasons describe confirmation, pin, proposal, coordinator availability, reported headroom or the stable fallback. Model-proposed explanation text remains a proposal and does not grant consent or bypass eligibility. |
| + |
| +Claim and every runner turn retain current choice, specialist and connection revision checks and add exact ask-confirmation checks. An existing step's actual account, model and reason remain immutable after settings change. A stale or unavailable active selection stops rather than moving accounts. The existing coordinator shared-home waiting/card/status and clean-boundary lease release paths are reused. The tests cover alternate, pin, ask, family-excluded and no-alternative selections, plus queued admission refusal and fresh admission after the blocking specialist's containment/release. |
| + |
| +Connection forms expose all three modes. Plan forms offer separate selection confirmation, show recorded reasons and mark stale picks. Conversation and task/journey views use saved selections or actual assignments; nullable usage/allowance and explicit person API projections remain intact. No credential paths or routing material were added to person API responses. |
| + |
| +To retain the unchanged source ceiling, connection choice models/views, validation, selection policy, ranking and pure preparation comparison/step resolution live in `planning`; root aliases and small wrappers preserve existing APIs. Counts of all Go files in each directory: `internal/equipo` 10,797 source / 437 test, `planning` 1,988 source / 57 test, `plan3test` 446 source / 7,646 test. No budget exception was raised. The required targeted tests fit the existing time caps; no full-suite timing is claimed. |
| + |
| +### TDD and regression evidence |
| + |
| +The required red command was run before implementing the methods or Mode field: |
| + |
| +`CGO_ENABLED=0 go test ./internal/plan3test -run '^TestPlanModelChoice' -count=1` |
| + |
| +Exit 1: `f.Store.SelectPlanStep undefined`, `f.Store.ConfirmPlanSelection undefined`, and `unknown field Mode in struct literal of type equipo.ConnectionChoice`. The same command passed after implementation and again after restoring all guard mutations and extracting the policy. |
| + |
| +Further test-first integration checks caught two real failures. `TestPlanModelChoiceClaimAndTurn` failed at Sync with the ask refusal; Sync needed to distinguish an expected selection wait from an infrastructure error. `TestPlanModelChoiceAskBuilder` then failed at claim with the ask refusal because the future-reviewer availability probe was incorrectly demanding that review's explicit consent before preparation. The probe now checks availability only; admission of the actual Review step still requires its own ask confirmation. |
| + |
| +An initial broad targeted regression command, `CGO_ENABLED=0 go test ./internal/equipotest -run '^Test(ConnectionSelection|RunnerSelectionGuards|BugPreparation|BugPreparedRetry)' -count=1`, exited 1 with `link crash not observed <nil>` in the preparation integration variants. An untouched-HEAD comparison of `^TestBugPreparationIntegration$` passed (9.612s), confirming a task regression. Temporary diagnostic output exposed the swallowed injected audit failure. The fix retains exact matching for ordinary `ErrUnavailable` and adds only the two explicit selection-wait errors; wrapped database failures propagate and roll back. The final preparation regression command above passes. All temporary baseline replacements and diagnostics were restored. That first broad selector also matched the existing `TestBugPreparationHostTmp`, which creates and removes its own `/tmp` directory; later commands explicitly exclude it. All scratch created directly by this task stayed under `$TMPDIR`. |
| + |
| +| Command | Result | |
| +| --- | --- | |
| +| `CGO_ENABLED=0 go test ./internal/plan3test -run '^TestPlanModelChoice' -count=1` | PASS, final 4.450s after extraction | |
| +| `CGO_ENABLED=0 go test ./internal/plan3test -run '^TestPlanWorkflow(RecommendationDelivery\|InvestigationCheckpoint\|ConnectionPreference)\|^TestCoordinatorConnectionWaiting$\|^TestSpecialistMigration$\|^TestPlaybookMigration$' -count=1` | PASS, 2.316s | |
| +| `CGO_ENABLED=0 go test ./internal/equipotest -run '^TestBugPreparationIntegration$\|^TestBugPreparationCrashRealProtocolLocalGit$\|^TestConnectionSelection\|^TestRunnerSelectionGuards$\|^TestBugPreparedRetry$' -count=1` | PASS, 30.023s | |
| +| `make migration-check` | PASS; targeted `TestMigrationModels`, 0.330s | |
| +| `CGO_ENABLED=0 go vet ./internal/equipo ./internal/equipo/planning ./internal/plan3test` | PASS, exit 0 | |
| +| `CGO_ENABLED=0 go run honnef.co/go/tools/cmd/staticcheck@v0.7.0 ./internal/equipo ./internal/equipo/planning ./internal/plan3test` | PASS, exit 0 | |
| +| `gofmt -l internal/equipo internal/plan3test` | PASS, no output | |
| +| `git diff --check` | PASS, no output | |
| + |
| +### Guard mutations |
| + |
| +| Guard | Targeted command | Exit and observed failure | Restoration | |
| +| --- | --- | --- | --- | |
| +| person filter | `CGO_ENABLED=0 go test ./internal/plan3test -run '^TestPlanModelChoiceOwnAccounts$' -count=1` | 1: plan_model_choice_test.go:39: borrowed another person's account | Restored in `finally`; final required command passed | |
| +| allowed models | `CGO_ENABLED=0 go test ./internal/plan3test -run '^TestPlanModelChoiceReviewFamily$' -count=1` | 1: plan_model_choice_test.go:115: allowed-family intersection bypassed | Restored in `finally`; final required command passed | |
| +| independent family | `CGO_ENABLED=0 go test ./internal/plan3test -run '^TestPlanModelChoiceReviewFamily$' -count=1` | 1: plan_model_choice_test.go:106: same-family review accepted | Restored in `finally`; final required command passed | |
| +| review pin exception | `CGO_ENABLED=0 go test ./internal/plan3test -run '^TestPlanModelChoiceReviewFamily$' -count=1` | 1: plan_model_choice_test.go:109: Enable a connection from another model family for review. | Restored in `finally`; final required command passed | |
| +| unknown allowance | `CGO_ENABLED=0 go test ./internal/plan3test -run '^TestPlanModelChoiceUnavailable$' -count=1` | 1: plan_model_choice_test.go:138: unknown allowance became known | Restored in `finally`; final required command passed | |
| +| actual immutability | `CGO_ENABLED=0 go test ./internal/plan3test -run '^TestPlanModelChoiceImmutableStep$' -count=1` | 1: plan_model_choice_test.go:126: This record changed. Reload the page and try again. | Restored in `finally`; final required command passed | |
| +| ask confirmation | `CGO_ENABLED=0 go test ./internal/plan3test -run '^TestPlanModelChoiceModes$/ask$' -count=1` | 1: plan_model_choice_test.go:63: ask selected without confirmation | Restored in `finally`; final required command passed | |
| +| coordinator preference | `CGO_ENABLED=0 go test ./internal/plan3test -run '^TestPlanModelChoiceCoordinatorConnection$/best_fit$' -count=1` | 1: plan_model_choice_test.go:177: coordinator preference overrode eligibility or consent | Restored in `finally`; final required command passed | |
| +| claim confirmation | `CGO_ENABLED=0 go test ./internal/plan3test -run '^TestPlanModelChoiceClaimAndTurn$/claim/confirmation$' -count=1` | 0: PASS: the independent dispatch check still refused the claim | Restored in `finally`; final required command passed | |
| +| turn confirmation | `CGO_ENABLED=0 go test ./internal/plan3test -run '^TestPlanModelChoiceClaimAndTurn$/turn/confirmation$' -count=1` | 1: plan_model_choice_test.go:240: stale selection reached turn | Restored in `finally`; final required command passed | |
| +| choice revision | `CGO_ENABLED=0 go test ./internal/plan3test -run '^TestPlanModelChoiceClaimAndTurn$/turn/choice$' -count=1` | 1: plan_model_choice_test.go:240: stale selection reached turn | Restored in `finally`; final required command passed | |
| +| audit rollback | `CGO_ENABLED=0 go test ./internal/plan3test -run '^TestPlanModelChoiceAuthorityAndRollback$' -count=1` | 1: plan_model_choice_test.go:309: selection ignored failed audit | Restored in `finally`; final required command passed | |
| + |
| +Eleven mutations failed as expected. The additional claim-confirmation probe stayed green because dispatch independently checks consent; the turn-boundary mutation failed. All mutations were restored. Final policy/ranking extraction preserves these predicates and all final commands above passed after extraction. |
| + |
| +### Copy and concerns |
| + |
| +| Key | Draft text | |
| +| --- | --- | |
| +| `connections.add` | Add a connection | |
| +| `connections.label` | Connection label | |
| +| `connections.remaining_unknown` | Remaining allowance is unknown. | |
| +| `connections.counted_usage` | Usage counted by Equipo | |
| +| `connections.best_fit` | Best fit for this step | |
| +| `connections.pinned` | Use the pinned connection | |
| +| `connections.ask` | Confirm this step’s connection | |
| +| `connections.reason` | Selection reason | |
| +| `connections.second_family` | Enable a connection from another model family for review. | |
| +| `connections.selection_changed` | The selection changed. Confirm it again. | |
| +| `connections.reason_best_fit` | First eligible choice in a stable order. Remaining allowance is unknown. | |
| +| `connections.reason_headroom` | Selected using reported remaining allowance. | |
| +| `connections.reason_alternative` | Keeps the coordinator connection free for conversation. | |
| +| `connections.reason_pinned` | Uses your pinned connection within the required model family. | |
| +| `connections.reason_proposed` | Uses the proposed connection after checking your allowed choices. | |
| +| `connections.reason_confirmed` | You confirmed this connection and model for this step. | |
| + |
| +- All 16 new copy entries remain individually marked `COPY REVIEW REQUIRED`; this task does not approve them for release. |
| +- This task adds no live allowance reader. It preserves the existing authenticated report contract: absent supported observations remain unknown; a model's headroom claim cannot supply an observation. |
| +- Existing Plan 2b/3 live-release certification blockers and custom-profile restrictions remain. Only recorded/local fixtures were used. No provider session, sign-in, enrolment, push, merge or deployment occurred. |
| +- The root source ceiling has only three lines of headroom. Future root changes should continue extracting feature code rather than raising that ceiling. |
| +- `.superpowers` is ignored by the repository. The requested full report is saved there; the controller evidence and source changes are committed. Task 20 retains ownership of the remaining person API lifecycle/selection route wiring; this task supplies the shared selection operations and browser confirmation route. |
| + |
| +Full report: `.superpowers/sdd/2026-11-04-equipo-plan-3-coordinator/task-14-report.md`. |
diff --git a/internal/equipo/app.go b/internal/equipo/app.go| index 1ee7093a..b113d53e 100644 |
| --- a/internal/equipo/app.go |
| +++ b/internal/equipo/app.go |
| @@ -186,6 +186,7 @@ func RouterWithStore(d *db.DB, cfg Config, mailer mail.Sender, logger *slog.Logg |
| a.preferenceHandler().Routes(r) |
| a.conversationHandler().Routes(r) |
| a.planHandler().Routes(r) |
| + r.Post("/tasks/{id}/steps/{key}/selection", a.confirmPlanSelection) |
| r.Get("/work", a.index) |
| for _, path := range []string{"/needs-you", "/journey", "/connections"} { |
| r.Get(path, a.taskList) |
diff --git a/internal/equipo/connection_handlers.go b/internal/equipo/connection_handlers.go| index 0eca5094..65a23e84 100644 |
| --- a/internal/equipo/connection_handlers.go |
| +++ b/internal/equipo/connection_handlers.go |
| @@ -36,10 +36,24 @@ func (a *application) saveConnectionChoice(w http.ResponseWriter, r *http.Reques |
| a.failure(w, r, ErrInvalid) |
| return |
| } |
| - choice := ConnectionChoice{ProjectID: project, Revision: revision, ConnectionIDs: r.PostForm["connection_id"], PinnedID: r.PostForm.Get("pinned_id")} |
| + choice := ConnectionChoice{ProjectID: project, Revision: revision, ConnectionIDs: r.PostForm["connection_id"], PinnedID: r.PostForm.Get("pinned_id"), Mode: r.PostForm.Get("mode")} |
| if err := a.store.SaveConnectionChoice(r.Context(), actor, choice); err != nil { |
| a.failure(w, r, err) |
| return |
| } |
| http.Redirect(w, r, "/connections", http.StatusSeeOther) |
| } |
| + |
| +func (a *application) confirmPlanSelection(w http.ResponseWriter, r *http.Request) { |
| + actor, revision, ok := a.connectionForm(w, r) |
| + if !ok { |
| + return |
| + } |
| + id := chi.URLParam(r, "id") |
| + _, err := a.store.ConfirmPlanSelection(r.Context(), actor, id, chi.URLParam(r, "key"), r.PostForm.Get("connection_id"), r.PostForm.Get("model"), Mutation{RequestID: r.PostForm.Get("request_id"), Revision: revision}) |
| + if err != nil { |
| + a.failure(w, r, err) |
| + return |
| + } |
| + http.Redirect(w, r, "/tasks/"+id+"/plan", http.StatusSeeOther) |
| +} |
diff --git a/internal/equipo/connection_models.go b/internal/equipo/connection_models.go| index 63e4a7ec..58e69484 100644 |
| --- a/internal/equipo/connection_models.go |
| +++ b/internal/equipo/connection_models.go |
| @@ -4,6 +4,7 @@ import ( |
| "slices" |
| "time" |
| + "amadan.net/oficina/equipo/internal/equipo/planning" |
| "amadan.net/oficina/equipo/internal/equipo/team" |
| "amadan.net/oficina/equipo/internal/runnerproto" |
| ) |
| @@ -15,39 +16,10 @@ type ConnectionRouting = runnerproto.ConnectionRouting |
| type ConnectionReport = runnerproto.ConnectionReport |
| -type Connection struct { |
| - ID string `gorm:"primaryKey"` |
| - RunnerID string `gorm:"uniqueIndex:connection_local"` |
| - Person string `gorm:"index:connection_person"` |
| - LocalID string `gorm:"uniqueIndex:connection_local"` |
| - Revision int64 |
| - LastSeen time.Time |
| - Reports []ConnectionReport `gorm:"-"` |
| -} |
| - |
| -type connectionRecord struct { |
| - Connection `gorm:"embedded"` |
| - ReportsJSON string |
| - SecurityHash string |
| -} |
| - |
| -func (connectionRecord) TableName() string { return "connections" } |
| - |
| -type ConnectionChoice struct { |
| - ProjectID, Revision int64 |
| - ConnectionIDs []string |
| - PinnedID string |
| -} |
| - |
| -type connectionChoiceRecord struct { |
| - Person string `gorm:"primaryKey"` |
| - ProjectID int64 `gorm:"primaryKey;autoIncrement:false"` |
| - Revision int64 |
| - ConnectionIDsJSON string |
| - PinnedID string |
| -} |
| - |
| -func (connectionChoiceRecord) TableName() string { return "connection_choices" } |
| +type Connection = planning.Connection |
| +type connectionRecord = planning.ConnectionRecord |
| +type ConnectionChoice = planning.ConnectionChoice |
| +type connectionChoiceRecord = planning.ConnectionChoiceRecord |
| type IsolationAcknowledgement struct { |
| ID string `gorm:"primaryKey"` |
diff --git a/internal/equipo/connection_selection.go b/internal/equipo/connection_selection.go| index 419086fc..77c5020a 100644 |
| --- a/internal/equipo/connection_selection.go |
| +++ b/internal/equipo/connection_selection.go |
| @@ -1,7 +1,9 @@ |
| package equipo |
| import ( |
| + "amadan.net/oficina/equipo/internal/equipo/conversation" |
| "amadan.net/oficina/equipo/internal/equipo/library" |
| + "amadan.net/oficina/equipo/internal/equipo/planning" |
| "amadan.net/oficina/equipo/internal/taskplan" |
| "context" |
| "errors" |
| @@ -60,6 +62,10 @@ func (s *Store) selectConnectionOnRunnerAt(tx *gorm.DB, person string, projectID |
| return s.selectStepConnection(tx, person, projectID, specialist, excludedFamily, runnerID, taskplan.Step{}, true) |
| } |
| func (s *Store) selectStepConnection(tx *gorm.DB, person string, projectID int64, specialist, excludedFamily, runnerID string, step taskplan.Step, requirePair bool) (Selection, error) { |
| + return s.selectStepConnectionConfirmed(tx, person, projectID, specialist, excludedFamily, runnerID, step, requirePair, false) |
| +} |
| + |
| +func (s *Store) selectStepConnectionConfirmed(tx *gorm.DB, person string, projectID int64, specialist, excludedFamily, runnerID string, step taskplan.Step, requirePair, confirmed bool) (Selection, error) { |
| var result Selection |
| err := func() error { |
| m, err := currentRunnerMember(tx, person) |
| @@ -110,15 +116,12 @@ func (s *Store) selectStepConnection(tx *gorm.DB, person string, projectID int64 |
| } |
| } |
| now := s.runnerClock.Now().UTC() |
| - pin := choice.PinnedID |
| - if step.ConnectionID != "" { |
| - if pin != "" && pin != step.ConnectionID && excludedFamily == "" { |
| - return ErrConflict |
| - } |
| - pin = step.ConnectionID |
| + if choice.Mode == "ask" && !confirmed { |
| + return errPlanSelectionAsk |
| } |
| - // A builder-family pin cannot choose the reviewer. Within the other family, |
| - // a pin still waits rather than silently moving to another account. |
| + pin := choice.PinnedID |
| + // A project pin applies within its family. Review still needs another |
| + // family; an explicit step pick never receives this exception. |
| if excludedFamily != "" { |
| for _, c := range rows { |
| if c.ID == pin && len(c.Reports) > 0 && c.Reports[0].Family == excludedFamily { |
| @@ -126,6 +129,19 @@ func (s *Store) selectStepConnection(tx *gorm.DB, person string, projectID int64 |
| } |
| } |
| } |
| + if step.ConnectionID != "" { |
| + if pin != "" && pin != step.ConnectionID { |
| + return ErrConflict |
| + } |
| + pin = step.ConnectionID |
| + } |
| + var binding conversation.BindingRecord |
| + bindingErr := tx.Where("person=?", m.Address).Take(&binding).Error |
| + if bindingErr != nil && !errors.Is(bindingErr, gorm.ErrRecordNotFound) { |
| + return bindingErr |
| + } |
| + var candidates []Selection |
| + |
| for _, c := range rows { |
| if pin != "" && c.ID != pin { |
| continue |
| @@ -176,11 +192,18 @@ func (s *Store) selectStepConnection(tx *gorm.DB, person string, projectID int64 |
| if pin != "" { |
| reason = "pinned" |
| } |
| - result = Selection{ConnectionID: c.ID, RunnerID: c.RunnerID, Person: m.Address, Provider: r.Provider, Family: r.Family, Model: r.Model, AccountLabel: r.AccountLabel, AccountID: r.Routing.AccountID, Revision: c.Revision, ChoiceRevision: choice.Revision, SpecialistRevision: sp.Revision, Reason: reason, MaxConcurrent: sp.MaxConcurrent, AllowanceKnown: r.AllowanceKnown, AllowanceRemaining: r.AllowanceRemaining, Isolation: snapshot} |
| - return nil |
| + selected := Selection{ConnectionID: c.ID, RunnerID: c.RunnerID, Person: m.Address, Provider: r.Provider, Family: r.Family, Model: r.Model, AccountLabel: r.AccountLabel, AccountID: r.Routing.AccountID, Revision: c.Revision, ChoiceRevision: choice.Revision, SpecialistRevision: sp.Revision, Reason: reason, MaxConcurrent: sp.MaxConcurrent, AllowanceKnown: r.AllowanceKnown, AllowanceRemaining: r.AllowanceRemaining, Isolation: snapshot} |
| + if !selected.AllowanceKnown { |
| + selected.AllowanceRemaining = 0 |
| + } |
| + candidates = append(candidates, selected) |
| } |
| } |
| - return ErrUnavailable |
| + if len(candidates) == 0 { |
| + return ErrUnavailable |
| + } |
| + result = planning.RankSelections(candidates, binding.ConnectionID, step.Key != "", pin, choice.PinnedID) |
| + return nil |
| }() |
| if err != nil { |
| return Selection{}, err |
diff --git a/internal/equipo/connection_views.go b/internal/equipo/connection_views.go| index cd838580..399e6d36 100644 |
| --- a/internal/equipo/connection_views.go |
| +++ b/internal/equipo/connection_views.go |
| @@ -1,11 +1,9 @@ |
| package equipo |
| import ( |
| - "encoding/json" |
| - "errors" |
| "net/http" |
| - "slices" |
| + "amadan.net/oficina/equipo/internal/equipo/planning" |
| "amadan.net/oficina/equipo/internal/equipo/team" |
| "gorm.io/gorm" |
| @@ -17,16 +15,8 @@ type ConnectionView struct { |
| Report ConnectionReport |
| Unconfined, Unverified, Acknowledged, Available bool |
| } |
| -type ProjectConnectionView struct { |
| - Project Project |
| - Revision int64 |
| - PinnedID string |
| - Options []ConnectionOption |
| -} |
| -type ConnectionOption struct { |
| - ID, Label string |
| - Enabled bool |
| -} |
| +type ProjectConnectionView = planning.ProjectConnectionView |
| +type ConnectionOption = planning.ProjectConnectionOption |
| func (a *application) connectionsPage(w http.ResponseWriter, r *http.Request, data pageData) { |
| err := a.store.readTeam(r.Context(), Actor{Address: data.Address}, func(tx *gorm.DB, instance Team) error { |
| @@ -54,33 +44,9 @@ func (a *application) connectionsPage(w http.ResponseWriter, r *http.Request, da |
| data.Connections = append(data.Connections, ConnectionView{Isolation: iso, Connection: row.Connection, Report: report, Unverified: !a.store.confined(report), Available: available}) |
| } |
| } |
| - var projects []Project |
| - if err := tx.Order("id").Find(&projects).Error; err != nil { |
| - return storeError(err) |
| - } |
| - for _, p := range projects { |
| - v := ProjectConnectionView{Project: p} |
| - var choice connectionChoiceRecord |
| - err := tx.Where("person=? AND project_id=?", data.Address, p.ID).Take(&choice).Error |
| - if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) { |
| - return storeError(err) |
| - } |
| - var ids []string |
| - if err == nil { |
| - if json.Unmarshal([]byte(choice.ConnectionIDsJSON), &ids) != nil { |
| - return ErrUnavailable |
| - } |
| - v.Revision = choice.Revision |
| - v.PinnedID = choice.PinnedID |
| - } |
| - for _, row := range rows { |
| - if row.Person == data.Address { |
| - v.Options = append(v.Options, ConnectionOption{ID: row.ID, Label: row.LocalID, Enabled: slices.Contains(ids, row.ID)}) |
| - } |
| - } |
| - data.Choices = append(data.Choices, v) |
| - } |
| - return nil |
| + var err error |
| + data.Choices, err = planning.ConnectionChoices(tx, data.Address, rows) |
| + return storeError(err) |
| }) |
| if err != nil { |
| a.failure(w, r, err) |
diff --git a/internal/equipo/connections.go b/internal/equipo/connections.go| index 8e94f02e..7102abc2 100644 |
| --- a/internal/equipo/connections.go |
| +++ b/internal/equipo/connections.go |
| @@ -12,6 +12,7 @@ import ( |
| "strings" |
| "time" |
| + "amadan.net/oficina/equipo/internal/equipo/planning" |
| "amadan.net/oficina/equipo/internal/equipo/team" |
| "amadan.net/oficina/equipo/internal/runnerproto" |
| "gorm.io/gorm" |
| @@ -271,28 +272,15 @@ func (s *Store) Connections(ctx context.Context, actor Actor) ([]Connection, err |
| return result, nil |
| } |
| func choiceAt(tx *gorm.DB, person string, project int64) (connectionChoiceRecord, []string, error) { |
| - var c connectionChoiceRecord |
| - if err := tx.Where("person = ? AND project_id = ?", person, project).First(&c).Error; err != nil { |
| - return c, nil, storeError(err) |
| - } |
| - var ids []string |
| - err := json.Unmarshal([]byte(c.ConnectionIDsJSON), &ids) |
| + c, ids, err := planning.ConnectionChoiceAt(tx, person, project) |
| return c, ids, storeError(err) |
| } |
| func (s *Store) SaveConnectionChoice(ctx context.Context, actor Actor, choice ConnectionChoice) error { |
| - if choice.ProjectID <= 0 || choice.Revision < 0 || len(choice.ConnectionIDs) > 256 { |
| - return ErrInvalid |
| - } |
| - ids := slices.Clone(choice.ConnectionIDs) |
| - sort.Strings(ids) |
| - for i, id := range ids { |
| - if id == "" || (i > 0 && ids[i-1] == id) { |
| - return ErrInvalid |
| - } |
| - } |
| - if choice.PinnedID != "" && !slices.Contains(ids, choice.PinnedID) { |
| - return ErrInvalid |
| + choice, err := planning.NormalizeConnectionChoice(choice, ErrInvalid) |
| + if err != nil { |
| + return err |
| } |
| + ids := choice.ConnectionIDs |
| return s.write(ctx, func(tx *gorm.DB) error { |
| m, err := currentRunnerMember(tx, actor.Address) |
| if err != nil { |
| @@ -320,9 +308,9 @@ func (s *Store) SaveConnectionChoice(ctx context.Context, actor Actor, choice Co |
| } |
| } |
| raw, _ := json.Marshal(ids) |
| - c := connectionChoiceRecord{Person: m.Address, ProjectID: project.ID, Revision: old.Revision + 1, ConnectionIDsJSON: string(raw), PinnedID: choice.PinnedID} |
| + c := connectionChoiceRecord{Person: m.Address, ProjectID: project.ID, Revision: old.Revision + 1, ConnectionIDsJSON: string(raw), PinnedID: choice.PinnedID, Mode: choice.Mode} |
| if exists { |
| - if err := tx.Model(&connectionChoiceRecord{}).Where("person = ? AND project_id = ?", m.Address, project.ID).Select("Revision", "ConnectionIDsJSON", "PinnedID").Updates(&c).Error; err != nil { |
| + if err := tx.Model(&connectionChoiceRecord{}).Where("person = ? AND project_id = ?", m.Address, project.ID).Select("Revision", "ConnectionIDsJSON", "PinnedID", "Mode").Updates(&c).Error; err != nil { |
| return storeError(err) |
| } |
| } else if err := tx.Create(&c).Error; err != nil { |
| @@ -340,7 +328,7 @@ func (s *Store) SaveConnectionChoice(ctx context.Context, actor Actor, choice Co |
| } |
| } |
| for _, id := range oldIDs { |
| - if !slices.Contains(ids, id) || old.PinnedID != choice.PinnedID { |
| + if !slices.Contains(ids, id) || old.PinnedID != choice.PinnedID || old.Mode != choice.Mode { |
| var row connectionRecord |
| if err := tx.Where("id = ?", id).First(&row).Error; err != nil { |
| return storeError(err) |
diff --git a/internal/equipo/copy.go b/internal/equipo/copy.go| index 29afab38..b28dfb1d 100644 |
| --- a/internal/equipo/copy.go |
| +++ b/internal/equipo/copy.go |
| @@ -781,6 +781,38 @@ var runnerDraftCopy = map[string]string{ |
| "usage.tokens": "Input and output tokens", |
| // COPY REVIEW REQUIRED: counts.unavailable |
| "counts.unavailable": "Unavailable", |
| + // COPY REVIEW REQUIRED: connections.add |
| + "connections.add": "Add a connection", |
| + // COPY REVIEW REQUIRED: connections.label |
| + "connections.label": "Connection label", |
| + // COPY REVIEW REQUIRED: connections.remaining_unknown |
| + "connections.remaining_unknown": "Remaining allowance is unknown.", |
| + // COPY REVIEW REQUIRED: connections.counted_usage |
| + "connections.counted_usage": "Usage counted by Equipo", |
| + // COPY REVIEW REQUIRED: connections.best_fit |
| + "connections.best_fit": "Best fit for this step", |
| + // COPY REVIEW REQUIRED: connections.pinned |
| + "connections.pinned": "Use the pinned connection", |
| + // COPY REVIEW REQUIRED: connections.ask |
| + "connections.ask": "Confirm this step’s connection", |
| + // COPY REVIEW REQUIRED: connections.reason |
| + "connections.reason": "Selection reason", |
| + // COPY REVIEW REQUIRED: connections.second_family |
| + "connections.second_family": "Enable a connection from another model family for review.", |
| + // COPY REVIEW REQUIRED: connections.selection_changed |
| + "connections.selection_changed": "The selection changed. Confirm it again.", |
| + // COPY REVIEW REQUIRED: connections.reason_best_fit |
| + "connections.reason_best_fit": "First eligible choice in a stable order. Remaining allowance is unknown.", |
| + // COPY REVIEW REQUIRED: connections.reason_headroom |
| + "connections.reason_headroom": "Selected using reported remaining allowance.", |
| + // COPY REVIEW REQUIRED: connections.reason_alternative |
| + "connections.reason_alternative": "Keeps the coordinator connection free for conversation.", |
| + // COPY REVIEW REQUIRED: connections.reason_pinned |
| + "connections.reason_pinned": "Uses your pinned connection within the required model family.", |
| + // COPY REVIEW REQUIRED: connections.reason_proposed |
| + "connections.reason_proposed": "Uses the proposed connection after checking your allowed choices.", |
| + // COPY REVIEW REQUIRED: connections.reason_confirmed |
| + "connections.reason_confirmed": "You confirmed this connection and model for this step.", |
| // COPY REVIEW REQUIRED: connections.versions |
| "connections.versions": "Provider, launcher and containment versions", |
| // COPY REVIEW REQUIRED: connections.personal |
diff --git a/internal/equipo/migrations/0026_connection_modes.sql b/internal/equipo/migrations/0026_connection_modes.sql| new file mode 100644 |
| index 00000000..09c82cc2 |
| --- /dev/null |
| +++ b/internal/equipo/migrations/0026_connection_modes.sql |
| @@ -0,0 +1,2 @@ |
| +ALTER TABLE connection_choices ADD COLUMN mode text NOT NULL DEFAULT "best_fit"; |
| +CREATE TABLE plan_selections (task_id text,step_key text,plan_revision integer,confirmed numeric,selection text,PRIMARY KEY (task_id,step_key)); |
diff --git a/internal/equipo/migrations/schema.sql b/internal/equipo/migrations/schema.sql| index 5e3ec9f0..1a115147 100644 |
| --- a/internal/equipo/migrations/schema.sql |
| +++ b/internal/equipo/migrations/schema.sql |
| @@ -278,7 +278,7 @@ CREATE TABLE connection_choices ( |
| project_id integer, |
| revision integer, |
| connection_ids_json text, |
| - pinned_id text, |
| + pinned_id text, mode text NOT NULL DEFAULT "best_fit", |
| PRIMARY KEY(person, project_id) |
| ); |
| CREATE TABLE isolation_acknowledgements ( |
| @@ -392,3 +392,5 @@ CREATE TABLE playbook_defaults (team_id text, project_id integer, kind text, pla |
| CREATE TABLE playbook_snapshots (task_id text, playbook_id text, plan text, PRIMARY KEY (task_id,playbook_id)); |
| CREATE TABLE playbook_requests (team_id text, principal text, operation text, resource text, request_id text, input_hash text, result text, PRIMARY KEY (team_id,principal,operation,resource,request_id)); |
| CREATE TABLE playbook_suggestions (id text, playbook_id text, PRIMARY KEY (id)); |
| + |
| +CREATE TABLE plan_selections (task_id text,step_key text,plan_revision integer,confirmed numeric,selection text,PRIMARY KEY (task_id,step_key)); |
diff --git a/internal/equipo/plan_execution.go b/internal/equipo/plan_execution.go| index bdb68a65..239452cf 100644 |
| --- a/internal/equipo/plan_execution.go |
| +++ b/internal/equipo/plan_execution.go |
| @@ -1,7 +1,6 @@ |
| package equipo |
| import ( |
| - "encoding/json" |
| "strconv" |
| "amadan.net/oficina/equipo/internal/equipo/planning" |
| @@ -39,101 +38,11 @@ func (s *Store) stepAt(tx *gorm.DB, t Task, key string) (taskplan.Plan, taskplan |
| if err != nil { |
| return p, taskplan.Step{}, err |
| } |
| - if key == "prepare" { |
| - for _, st := range p.Steps { |
| - if st.Specialist != "" { |
| - return p, st, nil |
| - } |
| - } |
| - } |
| - for _, st := range p.Steps { |
| - if st.Key == key { |
| - return p, st, nil |
| - } |
| - } |
| - if key == "publish" && taskplan.Publication(p.Kind) { |
| - return p, taskplan.Step{Key: key, Action: "publish"}, nil |
| - } |
| - return p, taskplan.Step{}, ErrInvalid |
| -} |
| -func executionSpecialist(st taskplan.Step) string { |
| - if st.Specialist != "" { |
| - return st.Specialist |
| - } |
| - if st.Action == "checks" || st.Action == "publish" { |
| - return "review" |
| - } |
| - return "engineering" |
| -} |
| -func (s *Store) planPair(tx *gorm.DB, t Task, p taskplan.Plan) (Selection, Selection, error) { |
| - var first taskplan.Step |
| - for _, st := range p.Steps { |
| - if st.Specialist != "" { |
| - first = st |
| - break |
| - } |
| - } |
| - selected, err := s.selectStepConnection(tx, t.Requester, t.ProjectID, executionSpecialist(first), "", "", first, false) |
| - if err != nil { |
| - return selected, Selection{}, err |
| - } |
| - if err = subscriptionSelection(tx, selected); err != nil { |
| - return selected, Selection{}, err |
| - } |
| - // Scope and research can begin with one family. Builders require a reviewer. |
| - if !taskplan.Candidate(first) && first.Action != "reproduce" { |
| - return selected, Selection{}, nil |
| - } |
| - review, err := s.selectStepConnection(tx, t.Requester, t.ProjectID, "review", selected.Family, selected.RunnerID, taskplan.Step{}, false) |
| - if err == nil { |
| - err = subscriptionSelection(tx, review) |
| - } |
| - return selected, review, err |
| + st, err := planning.ResolveStep(p, key, ErrInvalid) |
| + return p, st, err |
| } |
| + |
| +func executionSpecialist(st taskplan.Step) string { return planning.ExecutionSpecialist(st) } |
| func (s *Store) dispatchSelection(tx *gorm.DB, t Task, st taskplan.Step, first Selection) (Selection, error) { |
| - runnerID := first.RunnerID |
| - var assignments []runnerAssignment |
| - if err := tx.Where("task_id=? AND claim_request<>''", t.ID).Order("id").Find(&assignments).Error; err != nil { |
| - return Selection{}, err |
| - } |
| - families := map[string]bool{} |
| - for _, a := range assignments { |
| - var b RunnerBrief |
| - if json.Unmarshal([]byte(a.Brief), &b) != nil { |
| - return Selection{}, ErrUnavailable |
| - } |
| - if a.RunnerID != runnerID { |
| - return Selection{}, ErrConflict |
| - } |
| - if taskplan.Candidate(taskplan.Step{Action: b.Step.Action}) { |
| - families[b.Selection.Family] = true |
| - } |
| - } |
| - excluded := "" |
| - if st.Action == "review" || st.Action == "checks" || st.Action == "publish" { |
| - if len(families) != 1 { |
| - return Selection{}, ErrUnavailable |
| - } |
| - for f := range families { |
| - excluded = f |
| - } |
| - } |
| - specialist := executionSpecialist(st) |
| - if st.Action == "publish" { |
| - specialist = "review" |
| - } |
| - sel, err := s.selectStepConnection(tx, t.Requester, t.ProjectID, specialist, excluded, runnerID, st, false) |
| - if err != nil { |
| - return sel, err |
| - } |
| - if taskplan.Candidate(st) || st.Action == "reproduce" { |
| - families[sel.Family] = true |
| - if len(families) > 1 { |
| - return sel, ErrUnavailable |
| - } |
| - if _, err = s.selectStepConnection(tx, t.Requester, t.ProjectID, "review", sel.Family, runnerID, taskplan.Step{}, false); err != nil { |
| - return sel, err |
| - } |
| - } |
| - return sel, subscriptionSelection(tx, sel) |
| + return s.selectionPolicy().Dispatch(tx, t, st, first) |
| } |
diff --git a/internal/equipo/plan_selection.go b/internal/equipo/plan_selection.go| new file mode 100644 |
| index 00000000..effbb5e9 |
| --- /dev/null |
| +++ b/internal/equipo/plan_selection.go |
| @@ -0,0 +1,59 @@ |
| +package equipo |
| + |
| +import ( |
| + "context" |
| + "errors" |
| + |
| + "amadan.net/oficina/equipo/internal/equipo/planning" |
| + "amadan.net/oficina/equipo/internal/taskplan" |
| + "gorm.io/gorm" |
| +) |
| + |
| +var errPlanSelectionAsk = &refusal{copyText("connections.ask"), ErrUnavailable} |
| +var errPlanSecondFamily = &refusal{copyText("connections.second_family"), ErrUnavailable} |
| + |
| +func selectionWaitCode(err error) string { |
| + if errors.Is(err, errPlanSelectionAsk) { |
| + return "connections.ask" |
| + } |
| + if errors.Is(err, errPlanSecondFamily) { |
| + return "connections.second_family" |
| + } |
| + return "task.wait.setup" |
| +} |
| + |
| +func (s *Store) SelectPlanStep(ctx context.Context, actor Actor, taskID, stepKey string, m Mutation) (Selection, error) { |
| + return s.planSelection(ctx, actor, taskID, stepKey, "", "", false, m) |
| +} |
| +func (s *Store) ConfirmPlanSelection(ctx context.Context, actor Actor, taskID, stepKey, connectionID, model string, m Mutation) (Selection, error) { |
| + return s.planSelection(ctx, actor, taskID, stepKey, connectionID, model, true, m) |
| +} |
| +func (s *Store) planSelection(ctx context.Context, actor Actor, taskID, key, connection, model string, confirm bool, m Mutation) (out Selection, err error) { |
| + actor.Address = normalizeAddress(actor.Address) |
| + err = s.write(ctx, func(tx *gorm.DB) error { |
| + out, err = s.planningAt(tx).Select(actor, taskID, key, connection, model, confirm, m) |
| + return err |
| + }) |
| + return |
| +} |
| + |
| +func (s *Store) selectionPolicy() planning.SelectionPolicy { |
| + return planning.SelectionPolicy{ |
| + Select: s.selectStepConnectionConfirmed, Current: s.selectionCurrent, Subscription: subscriptionSelection, |
| + ChoiceRevision: func(tx *gorm.DB, person string, project int64) (int64, error) { |
| + c, _, err := choiceAt(tx, person, project) |
| + return c.Revision, err |
| + }, |
| + SpecialistRevision: func(tx *gorm.DB, key string) (int64, error) { |
| + sp, err := specialistAt(tx, key) |
| + return sp.Revision, err |
| + }, |
| + Unavailable: ErrUnavailable, Conflict: ErrConflict, SecondFamily: errPlanSecondFamily, |
| + } |
| +} |
| +func (s *Store) choosePlanSelection(tx *gorm.DB, t Task, p taskplan.Plan, st taskplan.Step, confirm bool) (Selection, error) { |
| + return s.selectionPolicy().Choose(tx, t, p, st, confirm) |
| +} |
| +func (s *Store) selectPlanConnection(tx *gorm.DB, t Task, st taskplan.Step, excluded, runner string, availability bool) (Selection, error) { |
| + return s.selectionPolicy().ForStep(tx, t, st, excluded, runner, availability) |
| +} |
diff --git a/internal/equipo/planning/approval_settings.go b/internal/equipo/planning/approval_settings.go| index f6e56e65..24bdd3a3 100644 |
| --- a/internal/equipo/planning/approval_settings.go |
| +++ b/internal/equipo/planning/approval_settings.go |
| @@ -111,7 +111,11 @@ func (s *Store) Approve(actor kernel.Actor, id string, m kernel.Mutation) (Task, |
| if m.Revision <= 0 || p.Revision != m.Revision { |
| return result, s.deps.Conflict |
| } |
| - if err = s.deps.Ready(s.tx, t, p); err != nil { |
| + ready := s.deps.ApprovalReady |
| + if ready == nil { |
| + ready = s.deps.Ready |
| + } |
| + if err = ready(s.tx, t, p); err != nil { |
| return result, err |
| } |
| if t.PlanRevision == 0 { |
diff --git a/internal/equipo/planning/connection_models.go b/internal/equipo/planning/connection_models.go| new file mode 100644 |
| index 00000000..9adebacd |
| --- /dev/null |
| +++ b/internal/equipo/planning/connection_models.go |
| @@ -0,0 +1,81 @@ |
| +package planning |
| + |
| +import ( |
| + "amadan.net/oficina/equipo/internal/runnerproto" |
| + "encoding/json" |
| + "gorm.io/gorm" |
| + "slices" |
| + "sort" |
| + "time" |
| +) |
| + |
| +type Connection struct { |
| + ID string `gorm:"primaryKey"` |
| + RunnerID string `gorm:"uniqueIndex:connection_local"` |
| + Person string `gorm:"index:connection_person"` |
| + LocalID string `gorm:"uniqueIndex:connection_local"` |
| + Revision int64 |
| + LastSeen time.Time |
| + Reports []runnerproto.ConnectionReport `gorm:"-"` |
| +} |
| + |
| +type ConnectionRecord struct { |
| + Connection `gorm:"embedded"` |
| + ReportsJSON string |
| + SecurityHash string |
| +} |
| + |
| +func (ConnectionRecord) TableName() string { return "connections" } |
| + |
| +type ConnectionChoice struct { |
| + ProjectID, Revision int64 |
| + ConnectionIDs []string |
| + PinnedID string |
| + Mode string |
| +} |
| + |
| +type ConnectionChoiceRecord struct { |
| + Person string `gorm:"primaryKey"` |
| + ProjectID int64 `gorm:"primaryKey;autoIncrement:false"` |
| + Revision int64 |
| + ConnectionIDsJSON string |
| + PinnedID string |
| + Mode string `gorm:"not null;default:best_fit"` |
| +} |
| + |
| +func (ConnectionChoiceRecord) TableName() string { return "connection_choices" } |
| + |
| +func ConnectionChoiceAt(tx *gorm.DB, person string, project int64) (ConnectionChoiceRecord, []string, error) { |
| + var c ConnectionChoiceRecord |
| + if err := tx.Where("person = ? AND project_id = ?", person, project).First(&c).Error; err != nil { |
| + return c, nil, err |
| + } |
| + var ids []string |
| + err := json.Unmarshal([]byte(c.ConnectionIDsJSON), &ids) |
| + return c, ids, err |
| +} |
| + |
| +func NormalizeConnectionChoice(choice ConnectionChoice, invalid error) (ConnectionChoice, error) { |
| + if choice.Mode == "" { |
| + choice.Mode = "best_fit" |
| + } |
| + if choice.Mode != "best_fit" && choice.Mode != "pinned" && choice.Mode != "ask" || choice.Mode == "pinned" && choice.PinnedID == "" { |
| + return choice, invalid |
| + } |
| + if choice.ProjectID <= 0 || choice.Revision < 0 || len(choice.ConnectionIDs) > 256 { |
| + return choice, invalid |
| + } |
| + ids := slices.Clone(choice.ConnectionIDs) |
| + sort.Strings(ids) |
| + for i, id := range ids { |
| + if id == "" || (i > 0 && ids[i-1] == id) { |
| + return choice, invalid |
| + } |
| + } |
| + if choice.PinnedID != "" && !slices.Contains(ids, choice.PinnedID) { |
| + return choice, invalid |
| + } |
| + |
| + choice.ConnectionIDs = ids |
| + return choice, nil |
| +} |
diff --git a/internal/equipo/planning/connection_views.go b/internal/equipo/planning/connection_views.go| new file mode 100644 |
| index 00000000..39d01aa6 |
| --- /dev/null |
| +++ b/internal/equipo/planning/connection_views.go |
| @@ -0,0 +1,53 @@ |
| +package planning |
| + |
| +import ( |
| + "amadan.net/oficina/equipo/internal/equipo/kernel" |
| + "encoding/json" |
| + "errors" |
| + "gorm.io/gorm" |
| + "slices" |
| +) |
| + |
| +type ProjectConnectionView struct { |
| + Project kernel.Project |
| + Revision int64 |
| + PinnedID string |
| + Mode string |
| + Options []ProjectConnectionOption |
| +} |
| +type ProjectConnectionOption struct { |
| + ID, Label string |
| + Enabled bool |
| +} |
| + |
| +func ConnectionChoices(tx *gorm.DB, person string, rows []ConnectionRecord) ([]ProjectConnectionView, error) { |
| + var result []ProjectConnectionView |
| + var projects []kernel.Project |
| + if err := tx.Order("id").Find(&projects).Error; err != nil { |
| + return nil, err |
| + } |
| + for _, p := range projects { |
| + v := ProjectConnectionView{Project: p, Mode: "best_fit"} |
| + var choice ConnectionChoiceRecord |
| + err := tx.Where("person=? AND project_id=?", person, p.ID).Take(&choice).Error |
| + if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) { |
| + return nil, err |
| + } |
| + var ids []string |
| + if err == nil { |
| + if err = json.Unmarshal([]byte(choice.ConnectionIDsJSON), &ids); err != nil { |
| + return nil, err |
| + } |
| + v.Revision = choice.Revision |
| + v.PinnedID = choice.PinnedID |
| + v.Mode = choice.Mode |
| + } |
| + for _, row := range rows { |
| + if row.Person == person { |
| + v.Options = append(v.Options, ProjectConnectionOption{ID: row.ID, Label: row.LocalID, Enabled: slices.Contains(ids, row.ID)}) |
| + } |
| + } |
| + result = append(result, v) |
| + } |
| + return result, nil |
| +} |
diff --git a/internal/equipo/planning/plans.go b/internal/equipo/planning/plans.go| index f13479b4..a46b57a4 100644 |
| --- a/internal/equipo/planning/plans.go |
| +++ b/internal/equipo/planning/plans.go |
| @@ -10,6 +10,7 @@ import ( |
| "amadan.net/oficina/equipo/internal/equipo/kernel" |
| "amadan.net/oficina/equipo/internal/equipo/team" |
| + "amadan.net/oficina/equipo/internal/runnerproto" |
| "amadan.net/oficina/equipo/internal/taskplan" |
| "gorm.io/gorm" |
| ) |
| @@ -52,13 +53,15 @@ type Request struct { |
| func (Request) TableName() string { return "plan_requests" } |
| -var Models = []any{&Revision{}, &Request{}, &ApprovalSetting{}} |
| +var Models = []any{&Revision{}, &Request{}, &ApprovalSetting{}, &SelectionRecord{}} |
| type Access struct { |
| TeamID, MergeOwner string |
| ProjectRevision int64 |
| } |
| type Dependencies struct { |
| + ApprovalReady func(*gorm.DB, Task, taskplan.Plan) error |
| + Choose func(*gorm.DB, Task, taskplan.Plan, taskplan.Step, bool) (runnerproto.Selection, error) |
| PlaybookDetails func(*gorm.DB, string, taskplan.Plan) (string, []string, error) |
| ResolvePlaybook func(*gorm.DB, kernel.Actor, taskplan.Plan) (taskplan.Plan, error) |
| Specialists func(*gorm.DB, string, taskplan.Plan, map[string]bool) error |
diff --git a/internal/equipo/planning/selection.go b/internal/equipo/planning/selection.go| new file mode 100644 |
| index 00000000..ed1f904d |
| --- /dev/null |
| +++ b/internal/equipo/planning/selection.go |
| @@ -0,0 +1,194 @@ |
| +package planning |
| + |
| +import ( |
| + "encoding/json" |
| + "errors" |
| + |
| + "amadan.net/oficina/equipo/internal/equipo/kernel" |
| + "amadan.net/oficina/equipo/internal/runnerproto" |
| + "amadan.net/oficina/equipo/internal/taskplan" |
| + "gorm.io/gorm" |
| + "gorm.io/gorm/clause" |
| +) |
| + |
| +// SelectionRecord is a revocable pre-start choice. Assignments retain actuals. |
| +type SelectionRecord struct { |
| + TaskID string `gorm:"primaryKey"` |
| + StepKey string `gorm:"primaryKey"` |
| + PlanRevision int64 |
| + Confirmed bool |
| + Selection string |
| +} |
| + |
| +func (SelectionRecord) TableName() string { return "plan_selections" } |
| + |
| +func ActualSelection(tx *gorm.DB, taskID, key string) (runnerproto.Selection, bool, error) { |
| + var row struct{ Selection string } |
| + err := tx.Table("runner_assignments").Select("selection").Where("task_id=? AND step_key=? AND claim_request<>''", taskID, key).Order("id").Take(&row).Error |
| + if errors.Is(err, gorm.ErrRecordNotFound) { |
| + return runnerproto.Selection{}, false, nil |
| + } |
| + if err != nil { |
| + return runnerproto.Selection{}, false, err |
| + } |
| + var sel runnerproto.Selection |
| + err = json.Unmarshal([]byte(row.Selection), &sel) |
| + return sel, true, err |
| +} |
| + |
| +func (s *Store) Select(actor kernel.Actor, id, key, connection, model string, confirm bool, m kernel.Mutation) (runnerproto.Selection, error) { |
| + var result runnerproto.Selection |
| + t, err := s.task(actor, id) |
| + if err != nil { |
| + return result, err |
| + } |
| + if t.Requester != actor.Address || s.coordinator != "" { |
| + return result, s.deps.Forbidden |
| + } |
| + p, err := s.Plan(t) |
| + if err != nil { |
| + return result, err |
| + } |
| + var step taskplan.Step |
| + for _, st := range p.Steps { |
| + if st.Key == key { |
| + step = st |
| + } |
| + } |
| + if step.Specialist == "" || !m.Valid() || confirm && (connection == "" || model == "") { |
| + return result, s.deps.Invalid |
| + } |
| + op := "plan.select" |
| + if confirm { |
| + op = "plan.confirm_selection" |
| + } |
| + q, replay, err := s.request(actor, op, id+"/"+key, m, struct { |
| + Connection, Model string |
| + Revision int64 |
| + }{connection, model, m.Revision}, &result) |
| + if err != nil { |
| + return result, err |
| + } |
| + actual, started, err := ActualSelection(s.tx, id, key) |
| + if err != nil { |
| + return result, err |
| + } |
| + if started { |
| + if confirm && (connection != actual.ConnectionID || model != actual.Model) { |
| + return result, s.deps.Conflict |
| + } |
| + if replay { |
| + return result, nil |
| + } |
| + if auditErr := s.deps.Audit(s.tx, actor, op, id+"/"+key); auditErr != nil { |
| + return result, auditErr |
| + } |
| + return actual, s.save(q, actual) |
| + } |
| + if err != nil || replay { |
| + return result, err |
| + } |
| + if m.Revision != p.Revision { |
| + return result, s.deps.Conflict |
| + } |
| + if confirm { |
| + step.ConnectionID = connection |
| + step.Model = model |
| + } |
| + result, err = s.deps.Choose(s.tx, t, p, step, confirm) |
| + if err != nil { |
| + return result, err |
| + } |
| + raw, err := json.Marshal(result) |
| + if err != nil { |
| + return result, err |
| + } |
| + row := SelectionRecord{TaskID: id, StepKey: key, PlanRevision: p.Revision, Confirmed: confirm, Selection: string(raw)} |
| + // Reading a previously confirmed choice must not revoke its consent. |
| + var old SelectionRecord |
| + err = s.tx.First(&old, "task_id=? AND step_key=?", id, key).Error |
| + if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) { |
| + return result, err |
| + } |
| + if err == nil && old.PlanRevision == row.PlanRevision && old.Confirmed { |
| + var previous runnerproto.Selection |
| + if err = json.Unmarshal([]byte(old.Selection), &previous); err != nil { |
| + return result, err |
| + } |
| + if previous.ConnectionID == result.ConnectionID && previous.Model == result.Model && previous.Revision == result.Revision && previous.ChoiceRevision == result.ChoiceRevision && previous.SpecialistRevision == result.SpecialistRevision { |
| + row.Confirmed = true |
| + } |
| + } |
| + err = s.tx.Clauses(clause.OnConflict{Columns: []clause.Column{{Name: "task_id"}, {Name: "step_key"}}, DoUpdates: clause.AssignmentColumns([]string{"plan_revision", "confirmed", "selection"})}).Create(&row).Error |
| + if err != nil { |
| + return result, err |
| + } |
| + if err = s.deps.Fence(s.tx, id); err != nil { |
| + return result, err |
| + } |
| + if err = s.deps.Audit(s.tx, actor, op, id+"/"+key); err != nil { |
| + return result, err |
| + } |
| + if err = s.deps.Card(s.tx, t); err != nil { |
| + return result, err |
| + } |
| + return result, s.save(q, result) |
| +} |
| + |
| +// SelectionView excludes routing, account identity hashes and credential data. |
| +type SelectionView struct { |
| + ConnectionID, Model, Account, Reason string |
| + AllowanceRemaining *int64 |
| + Actual, Confirmed, Stale bool |
| +} |
| + |
| +func SavedSelection(tx *gorm.DB, t Task, key string) (runnerproto.Selection, bool, bool, error) { |
| + sel, actual, err := ActualSelection(tx, t.ID, key) |
| + if err != nil || actual { |
| + return sel, actual, true, err |
| + } |
| + var row SelectionRecord |
| + err = tx.First(&row, "task_id=? AND step_key=? AND plan_revision=?", t.ID, key, t.PlanRevision).Error |
| + if errors.Is(err, gorm.ErrRecordNotFound) { |
| + return sel, false, false, nil |
| + } |
| + if err != nil { |
| + return sel, false, false, err |
| + } |
| + err = json.Unmarshal([]byte(row.Selection), &sel) |
| + return sel, false, row.Confirmed, err |
| +} |
| +func (s *Store) selectionView(a kernel.Actor, t Task, key string) (*SelectionView, error) { |
| + sel, actual, confirmed, err := SavedSelection(s.tx, t, key) |
| + if err != nil || sel.ConnectionID == "" { |
| + return nil, err |
| + } |
| + v := &SelectionView{Model: sel.Model, Reason: sel.Reason, Actual: actual, Confirmed: confirmed} |
| + if !actual { |
| + p, e := s.Plan(t) |
| + if e != nil { |
| + return nil, e |
| + } |
| + specialist := "" |
| + for _, st := range p.Steps { |
| + if st.Key == key { |
| + specialist = st.Specialist |
| + } |
| + } |
| + var n int64 |
| + e = s.tx.Table("connections c").Joins("JOIN connection_choices choice ON choice.person=c.person AND choice.project_id=?", t.ProjectID).Joins("JOIN specialists sp ON sp.key=?", specialist).Where("c.id=? AND c.person=? AND c.revision=? AND choice.revision=? AND sp.revision=?", sel.ConnectionID, t.Requester, sel.Revision, sel.ChoiceRevision, sel.SpecialistRevision).Count(&n).Error |
| + if e != nil { |
| + return nil, e |
| + } |
| + v.Stale = n != 1 |
| + } |
| + if a.Address == t.Requester { |
| + v.ConnectionID = sel.ConnectionID |
| + v.Account = sel.AccountLabel |
| + if sel.AllowanceKnown { |
| + n := sel.AllowanceRemaining |
| + v.AllowanceRemaining = &n |
| + } |
| + } |
| + return v, nil |
| +} |
diff --git a/internal/equipo/planning/selection_policy.go b/internal/equipo/planning/selection_policy.go| new file mode 100644 |
| index 00000000..d28b723f |
| --- /dev/null |
| +++ b/internal/equipo/planning/selection_policy.go |
| @@ -0,0 +1,217 @@ |
| +package planning |
| + |
| +import ( |
| + "amadan.net/oficina/equipo/internal/runnerproto" |
| + "amadan.net/oficina/equipo/internal/taskplan" |
| + "encoding/json" |
| + "errors" |
| + "gorm.io/gorm" |
| +) |
| + |
| +type Selection = runnerproto.Selection |
| + |
| +// SelectionPolicy uses transaction-bound application authority and eligibility. |
| +type SelectionPolicy struct { |
| + Select func(*gorm.DB, string, int64, string, string, string, taskplan.Step, bool, bool) (Selection, error) |
| + Current func(*gorm.DB, Task, string, Selection) (Selection, error) |
| + Subscription func(*gorm.DB, Selection) error |
| + ChoiceRevision func(*gorm.DB, string, int64) (int64, error) |
| + SpecialistRevision func(*gorm.DB, string) (int64, error) |
| + Unavailable, Conflict, SecondFamily error |
| +} |
| + |
| +func ExecutionSpecialist(st taskplan.Step) string { |
| + if st.Specialist != "" { |
| + return st.Specialist |
| + } |
| + if st.Action == "checks" || st.Action == "publish" { |
| + return "review" |
| + } |
| + return "engineering" |
| +} |
| + |
| +// Choose validates a proposal inside the same transaction as the saved choice. |
| +func (s SelectionPolicy) Choose(tx *gorm.DB, t Task, p taskplan.Plan, step taskplan.Step, confirm bool) (Selection, error) { |
| + excluded := "" |
| + if step.Action == "review" { |
| + families := map[string]bool{} |
| + for _, st := range p.Steps { |
| + if !taskplan.Candidate(st) { |
| + continue |
| + } |
| + sel, started, err := ActualSelection(tx, t.ID, st.Key) |
| + if err != nil { |
| + return Selection{}, err |
| + } |
| + if !started { |
| + sel, err = s.ForStep(tx, t, st, "", "", false) |
| + if err != nil { |
| + return Selection{}, err |
| + } |
| + } |
| + families[sel.Family] = true |
| + } |
| + if len(families) != 1 { |
| + return Selection{}, s.SecondFamily |
| + } |
| + for f := range families { |
| + excluded = f |
| + } |
| + } |
| + if confirm { |
| + sel, err := s.Select(tx, t.Requester, t.ProjectID, ExecutionSpecialist(step), excluded, "", step, false, true) |
| + if err != nil { |
| + return sel, err |
| + } |
| + sel.Reason = "connections.reason_confirmed" |
| + return sel, nil |
| + } |
| + return s.ForStep(tx, t, step, excluded, "", false) |
| +} |
| + |
| +func (s SelectionPolicy) ForStep(tx *gorm.DB, t Task, st taskplan.Step, excluded, runner string, availabilityOnly bool) (Selection, error) { |
| + actual, started, err := ActualSelection(tx, t.ID, st.Key) |
| + if err != nil { |
| + return Selection{}, err |
| + } |
| + if started { |
| + return s.Current(tx, t, st.Key, actual) |
| + } |
| + choice, err := s.ChoiceRevision(tx, t.Requester, t.ProjectID) |
| + if err != nil { |
| + return Selection{}, err |
| + } |
| + var row SelectionRecord |
| + err = tx.First(&row, "task_id=? AND step_key=?", t.ID, st.Key).Error |
| + if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) { |
| + return Selection{}, err |
| + } |
| + var saved Selection |
| + valid := err == nil && row.PlanRevision == t.PlanRevision |
| + if valid { |
| + if err = json.Unmarshal([]byte(row.Selection), &saved); err != nil { |
| + return Selection{}, err |
| + } |
| + sp, e := s.SpecialistRevision(tx, ExecutionSpecialist(st)) |
| + if e != nil { |
| + return Selection{}, e |
| + } |
| + valid = saved.ChoiceRevision == choice && saved.SpecialistRevision == sp |
| + if valid { |
| + var c struct { |
| + Revision int64 |
| + Person string |
| + } |
| + e = tx.Table("connections").First(&c, "id=?", saved.ConnectionID).Error |
| + if e != nil && !errors.Is(e, gorm.ErrRecordNotFound) { |
| + return Selection{}, e |
| + } |
| + valid = e == nil && c.Revision == saved.Revision && c.Person == t.Requester |
| + } |
| + } |
| + confirmed := valid && row.Confirmed |
| + if valid { |
| + st.ConnectionID = saved.ConnectionID |
| + st.Model = saved.Model |
| + } |
| + // Availability checks for a future reviewer do not confer ask consent. |
| + sel, err := s.Select(tx, t.Requester, t.ProjectID, ExecutionSpecialist(st), excluded, runner, st, false, confirmed || availabilityOnly) |
| + if err != nil { |
| + if excluded != "" && err == s.Unavailable { |
| + return sel, s.SecondFamily |
| + } |
| + return sel, err |
| + } |
| + if valid { |
| + sel.Reason = saved.Reason |
| + |
| + } |
| + return sel, nil |
| +} |
| +func (s SelectionPolicy) Pair(tx *gorm.DB, t Task, p taskplan.Plan, approval bool) (Selection, Selection, error) { |
| + var first taskplan.Step |
| + for _, st := range p.Steps { |
| + if st.Specialist != "" { |
| + first = st |
| + break |
| + } |
| + } |
| + selected, err := s.ForStep(tx, t, first, "", "", approval) |
| + if err != nil { |
| + return selected, Selection{}, err |
| + } |
| + if err = s.Subscription(tx, selected); err != nil { |
| + return selected, Selection{}, err |
| + } |
| + // Scope and research can begin with one family. Builders require a reviewer. |
| + if !taskplan.Candidate(first) && first.Action != "reproduce" { |
| + return selected, Selection{}, nil |
| + } |
| + review, err := s.ForStep(tx, t, taskplan.Step{Specialist: "review", Action: "review"}, selected.Family, selected.RunnerID, true) |
| + if err == nil { |
| + err = s.Subscription(tx, review) |
| + } |
| + return selected, review, err |
| +} |
| +func (s SelectionPolicy) Dispatch(tx *gorm.DB, t Task, st taskplan.Step, first Selection) (Selection, error) { |
| + runnerID := first.RunnerID |
| + var assignments []struct{ Brief, RunnerID string } |
| + if err := tx.Table("runner_assignments").Where("task_id=? AND claim_request<>''", t.ID).Order("id").Find(&assignments).Error; err != nil { |
| + return Selection{}, err |
| + } |
| + families := map[string]bool{} |
| + for _, a := range assignments { |
| + var b runnerproto.RunnerBrief |
| + if json.Unmarshal([]byte(a.Brief), &b) != nil { |
| + return Selection{}, s.Unavailable |
| + } |
| + if a.RunnerID != runnerID { |
| + return Selection{}, s.Conflict |
| + } |
| + if taskplan.Candidate(taskplan.Step{Action: b.Step.Action}) { |
| + families[b.Selection.Family] = true |
| + } |
| + } |
| + excluded := "" |
| + if st.Action == "review" || st.Action == "checks" || st.Action == "publish" { |
| + if len(families) != 1 { |
| + return Selection{}, s.Unavailable |
| + } |
| + for f := range families { |
| + excluded = f |
| + } |
| + } |
| + sel, err := s.ForStep(tx, t, st, excluded, runnerID, st.Action == "checks" || st.Action == "publish") |
| + if err != nil { |
| + return sel, err |
| + } |
| + if taskplan.Candidate(st) || st.Action == "reproduce" { |
| + families[sel.Family] = true |
| + if len(families) > 1 { |
| + return sel, s.Unavailable |
| + } |
| + if _, err = s.ForStep(tx, t, taskplan.Step{Specialist: "review", Action: "review"}, sel.Family, runnerID, true); err != nil { |
| + return sel, err |
| + } |
| + } |
| + return sel, s.Subscription(tx, sel) |
| +} |
| + |
| +func ResolveStep(p taskplan.Plan, key string, invalid error) (taskplan.Step, error) { |
| + if key == "prepare" { |
| + for _, st := range p.Steps { |
| + if st.Specialist != "" { |
| + return st, nil |
| + } |
| + } |
| + } |
| + for _, st := range p.Steps { |
| + if st.Key == key { |
| + return st, nil |
| + } |
| + } |
| + if key == "publish" && taskplan.Publication(p.Kind) { |
| + return taskplan.Step{Key: key, Action: "publish"}, nil |
| + } |
| + return taskplan.Step{}, invalid |
| +} |
diff --git a/internal/equipo/planning/selection_rank.go b/internal/equipo/planning/selection_rank.go| new file mode 100644 |
| index 00000000..3be2a7b8 |
| --- /dev/null |
| +++ b/internal/equipo/planning/selection_rank.go |
| @@ -0,0 +1,57 @@ |
| +package planning |
| + |
| +import ( |
| + "reflect" |
| + "sort" |
| +) |
| + |
| +func RankSelections(candidates []Selection, coordinator string, rankHeadroom bool, pin, projectPin string) Selection { |
| + sort.SliceStable(candidates, func(i, j int) bool { |
| + a, b := candidates[i], candidates[j] |
| + if (a.ConnectionID == coordinator) != (b.ConnectionID == coordinator) { |
| + return a.ConnectionID != coordinator |
| + } |
| + // Unknown observations are not zero. Compare headroom only when |
| + // both observations explicitly report a known remaining amount. |
| + if rankHeadroom && a.AllowanceKnown != b.AllowanceKnown { |
| + return a.AllowanceKnown |
| + } |
| + if rankHeadroom && a.AllowanceKnown && b.AllowanceKnown && a.AllowanceRemaining != b.AllowanceRemaining { |
| + return a.AllowanceRemaining > b.AllowanceRemaining |
| + } |
| + if a.ConnectionID != b.ConnectionID { |
| + return a.ConnectionID < b.ConnectionID |
| + } |
| + if a.Provider != b.Provider { |
| + return a.Provider < b.Provider |
| + } |
| + return a.Model < b.Model |
| + }) |
| + result := candidates[0] |
| + if rankHeadroom { |
| + result.Reason = "connections.reason_best_fit" |
| + if result.AllowanceKnown { |
| + result.Reason = "connections.reason_headroom" |
| + } |
| + if coordinator != "" && result.ConnectionID != coordinator { |
| + result.Reason = "connections.reason_alternative" |
| + } |
| + if pin != "" { |
| + result.Reason = "connections.reason_proposed" |
| + } |
| + if pin != "" && pin == projectPin { |
| + result.Reason = "connections.reason_pinned" |
| + } |
| + } |
| + return result |
| +} |
| + |
| +func SamePreparationSelection(a, b Selection) bool { |
| + // Heartbeat, allowance and the human account label do not change authority. |
| + a.AllowanceKnown = b.AllowanceKnown |
| + a.AllowanceRemaining = b.AllowanceRemaining |
| + a.AccountLabel = b.AccountLabel |
| + a.Isolation = b.Isolation |
| + a.Reason = b.Reason |
| + return reflect.DeepEqual(a, b) |
| +} |
diff --git a/internal/equipo/planning/views.go b/internal/equipo/planning/views.go| index 7d971875..cf90c90b 100644 |
| --- a/internal/equipo/planning/views.go |
| +++ b/internal/equipo/planning/views.go |
| @@ -16,12 +16,15 @@ type ProjectOption struct { |
| Name string |
| } |
| type StepView struct { |
| + Pick *SelectionView |
| + ConfirmID string |
| taskplan.Step |
| Index, Position int |
| State, Account, Actual, Depends string |
| Locked bool |
| } |
| type Page struct { |
| + CanSelect bool |
| PlaybookName string |
| PlaybookChanges []string |
| Connections []ConnectionOption |
| @@ -53,6 +56,7 @@ func (s *Store) Page(a kernel.Actor, id string) (out Page, err error) { |
| } |
| _, accessErr := s.deps.Access(s.tx, a, out.Task.ProjectID) |
| out.CanEdit = accessErr == nil |
| + out.CanSelect = out.CanEdit && a.Address == out.Task.Requester |
| out.Owner = s.deps.Member(s.tx, a, true) == nil |
| out.RequestID, out.ApproveID, out.CorrectID = rand.Text(), rand.Text(), rand.Text() |
| out.ProjectSettingID, out.PersonalSettingID = rand.Text(), rand.Text() |
| @@ -139,6 +143,11 @@ func (s *Store) Page(a kernel.Actor, id string) (out Page, err error) { |
| } |
| } |
| } |
| + v.Pick, err = s.selectionView(a, out.Task, st.Key) |
| + if err != nil { |
| + return |
| + } |
| + v.ConfirmID = rand.Text() |
| out.Steps = append(out.Steps, v) |
| } |
| return |
diff --git a/internal/equipo/plans.go b/internal/equipo/plans.go| index 73e4b55a..9246c4cb 100644 |
| --- a/internal/equipo/plans.go |
| +++ b/internal/equipo/plans.go |
| @@ -18,6 +18,8 @@ const ( |
| func (s *Store) planningAt(tx *gorm.DB) *planning.Store { |
| deps := planning.Dependencies{ |
| + Choose: s.choosePlanSelection, |
| + ApprovalReady: func(tx *gorm.DB, t Task, p taskplan.Plan) error { return s.planReadyFor(tx, t, p, true) }, |
| PlaybookDetails: func(tx *gorm.DB, teamID string, p taskplan.Plan) (string, []string, error) { |
| return s.libraryAt(tx).PlanDetails(teamID, p) |
| }, |
| @@ -81,6 +83,9 @@ func (s *Store) planningAt(tx *gorm.DB) *planning.Store { |
| return planning.New(tx.Statement.Context, tx, deps) |
| } |
| func (s *Store) planReady(tx *gorm.DB, t Task, p taskplan.Plan) error { |
| + return s.planReadyFor(tx, t, p, false) |
| +} |
| +func (s *Store) planReadyFor(tx *gorm.DB, t Task, p taskplan.Plan, approval bool) error { |
| if _, err := bugAuthority(tx, Actor{Address: t.Requester}, t.ProjectID); err != nil { |
| return err |
| } |
| @@ -102,7 +107,7 @@ func (s *Store) planReady(tx *gorm.DB, t Task, p taskplan.Plan) error { |
| if err = team.CheckPlanBudgetTx(tx.Statement.Context, raw, team.AccountID(t.TeamID), team.ProjectID(t.ProjectID), team.BudgetSet{Revision: budget.Revision, Team: budget.Team, Projects: budget.Projects}, team.PeriodLimits{Calls: 1, InputTokens: policy.PerCall.InputTokens, OutputTokens: policy.PerCall.OutputTokens, Seconds: int64(policy.AttemptSeconds)}, s.runnerClock.Now()); err != nil { |
| return err |
| } |
| - _, _, err = s.planPair(tx, t, p) |
| + _, _, err = s.selectionPolicy().Pair(tx, t, p, approval) |
| return err |
| } |
| func (s *Store) planningApplication() *planning.Application { |
| @@ -127,7 +132,7 @@ func (s *Store) preparePlanOutbox(tx *gorm.DB, t Task) error { |
| if err != nil { |
| return err |
| } |
| - eng, rev, err := s.planPair(tx, t, p) |
| + eng, rev, err := s.selectionPolicy().Pair(tx, t, p, false) |
| if err != nil { |
| return err |
| } |
diff --git a/internal/equipo/runner_execution.go b/internal/equipo/runner_execution.go| index c6f048c8..18ce35b4 100644 |
| --- a/internal/equipo/runner_execution.go |
| +++ b/internal/equipo/runner_execution.go |
| @@ -11,6 +11,7 @@ import ( |
| "strconv" |
| "time" |
| + "amadan.net/oficina/equipo/internal/equipo/planning" |
| "amadan.net/oficina/equipo/internal/equipo/team" |
| "amadan.net/oficina/equipo/internal/runnerproto" |
| "amadan.net/oficina/equipo/internal/taskplan" |
| @@ -63,6 +64,19 @@ func (s *Store) selectionCurrent(tx *gorm.DB, task Task, step string, sel Select |
| if !slices.Contains(ids, sel.ConnectionID) || choice.Revision != sel.ChoiceRevision { |
| return sel, ErrConflict |
| } |
| + if choice.Mode == "ask" && st.Specialist != "" { |
| + var confirmed planning.SelectionRecord |
| + if err := tx.First(&confirmed, "task_id=? AND step_key=?", task.ID, st.Key).Error; err != nil { |
| + if !errors.Is(err, gorm.ErrRecordNotFound) { |
| + return sel, storeError(err) |
| + } |
| + return sel, ErrConflict |
| + } |
| + var saved Selection |
| + if !confirmed.Confirmed || confirmed.PlanRevision != task.PlanRevision || json.Unmarshal([]byte(confirmed.Selection), &saved) != nil || saved.ConnectionID != sel.ConnectionID || saved.Model != sel.Model || saved.ChoiceRevision != sel.ChoiceRevision || saved.Revision != sel.Revision || saved.SpecialistRevision != sel.SpecialistRevision { |
| + return sel, ErrConflict |
| + } |
| + } |
| var sp Specialist |
| if err := tx.First(&sp, "key=?", specialist).Error; err != nil { |
| return sel, storeError(err) |
| @@ -160,7 +174,7 @@ func (e *Execution) assignmentCurrent(ctx context.Context, tx *gorm.DB, p Runner |
| } |
| } |
| if taskplan.Candidate(step) || step.Action == "reproduce" { |
| - if _, err = e.store.selectStepConnection(tx, task.Requester, task.ProjectID, "review", sel.Family, sel.RunnerID, taskplan.Step{}, false); err != nil { |
| + if _, err = e.store.selectPlanConnection(tx, task, taskplan.Step{Specialist: "review", Action: "review"}, sel.Family, sel.RunnerID, true); err != nil { |
| return value, err |
| } |
| } |
| @@ -204,6 +218,9 @@ func (e *Execution) Sync(ctx context.Context) error { |
| for _, task := range proposed { |
| if err := e.store.preparePlanOutbox(tx, task); err != nil { |
| if taskRefusal(err) { |
| + if waitErr := taskWait(tx, task.ID, selectionWaitCode(err)); waitErr != nil { |
| + return waitErr |
| + } |
| continue |
| } |
| return err |
| @@ -363,6 +380,9 @@ func (e *Execution) Sync(ctx context.Context) error { |
| sel, err = e.store.dispatchSelection(tx, task, st, eng) |
| if err != nil { |
| if taskRefusal(err) { |
| + if waitErr := taskWait(tx, task.ID, selectionWaitCode(err)); waitErr != nil { |
| + return waitErr |
| + } |
| continue |
| } |
| return err |
diff --git a/internal/equipo/task_prepare.go b/internal/equipo/task_prepare.go| index fdc6c03c..d9c13424 100644 |
| --- a/internal/equipo/task_prepare.go |
| +++ b/internal/equipo/task_prepare.go |
| @@ -5,8 +5,8 @@ import ( |
| "crypto/sha256" |
| "encoding/hex" |
| "encoding/json" |
| - "reflect" |
| + "amadan.net/oficina/equipo/internal/equipo/planning" |
| "amadan.net/oficina/equipo/internal/equipo/team" |
| "amadan.net/oficina/equipo/internal/runnerproto" |
| "gorm.io/gorm" |
| @@ -25,15 +25,9 @@ func validPreparedBug(p PreparedBug, project Project) bool { |
| hash := sha256.Sum256(p.CheckDefinition) |
| return p.Repository == project.Repository && p.DefaultBranch == project.DefaultBranch && (hexDigest(p.BaseCommit, 40) || hexDigest(p.BaseCommit, 64)) && len(p.CheckDefinition) > 0 && len(p.CheckDefinition) <= team.MaxArtifactBytes && p.CheckDefinitionHash == hex.EncodeToString(hash[:]) && hexDigest(p.BaselineTestSetHash, 64) |
| } |
| -func samePreparationSelection(a, b Selection) bool { |
| - // Heartbeat, allowance and the human account label do not change authority. |
| - a.AllowanceKnown = b.AllowanceKnown |
| - a.AllowanceRemaining = b.AllowanceRemaining |
| - a.AccountLabel = b.AccountLabel |
| - a.Isolation = b.Isolation |
| - a.Reason = b.Reason |
| - return reflect.DeepEqual(a, b) |
| -} |
| + |
| +var samePreparationSelection = planning.SamePreparationSelection |
| + |
| func (s *Store) bugPreparationAt(tx *gorm.DB, principal RunnerPrincipal, id string) (Task, taskOutbox, Project, error) { |
| var task Task |
| var outbox taskOutbox |
| @@ -75,7 +69,7 @@ func (s *Store) bugPreparationAt(tx *gorm.DB, principal RunnerPrincipal, id stri |
| if err != nil { |
| return task, outbox, project, err |
| } |
| - first, currentReview, err := s.planPair(tx, task, p) |
| + first, currentReview, err := s.selectionPolicy().Pair(tx, task, p, false) |
| if err != nil { |
| return task, outbox, project, err |
| } |
diff --git a/internal/equipo/task_views.go b/internal/equipo/task_views.go| index f7c732d8..45b8149f 100644 |
| --- a/internal/equipo/task_views.go |
| +++ b/internal/equipo/task_views.go |
| @@ -228,6 +228,13 @@ func (s *Store) taskViewAt(tx *gorm.DB, actor Actor, task Task) (TaskViewData, e |
| if plan.Specialist == "review" { |
| sel = review |
| } |
| + saved, actual, _, pickErr := planning.SavedSelection(tx, task, plan.Key) |
| + if pickErr != nil { |
| + return v, pickErr |
| + } |
| + if saved.ConnectionID != "" { |
| + sel = saved |
| + } |
| for _, assignment := range assignments { |
| if assignment.StepKey == plan.Key && assignment.Selection != "" { |
| if err := json.Unmarshal([]byte(assignment.Selection), &sel); err != nil { |
| @@ -237,7 +244,13 @@ func (s *Store) taskViewAt(tx *gorm.DB, actor Actor, task Task) (TaskViewData, e |
| } |
| if person == "" { |
| card.Model = sel.Model |
| - if plan.Model != "" { |
| + if sel.Reason != "" { |
| + card.Reason = sel.Reason |
| + if text := copyText(sel.Reason); text != "" { |
| + card.Reason = text |
| + } |
| + } |
| + if !actual && saved.ConnectionID == "" && plan.Model != "" { |
| card.Model = plan.Model |
| } |
| card.AllowanceKnown = sel.AllowanceKnown |
| @@ -416,6 +429,8 @@ func (s *Store) taskViewAt(tx *gorm.DB, actor Actor, task Task) (TaskViewData, e |
| } |
| func waitCopyKey(wait string) string { |
| switch wait { |
| + case "connections.ask", "connections.second_family", "connections.selection_changed": |
| + return wait |
| case "task.wait.family", "family", "different_family", "review_family": |
| return "task.wait.family" |
| default: |
diff --git a/internal/equipo/task_wait.go b/internal/equipo/task_wait.go| index 564cc757..6e441aee 100644 |
| --- a/internal/equipo/task_wait.go |
| +++ b/internal/equipo/task_wait.go |
| @@ -9,7 +9,7 @@ import ( |
| ) |
| func taskRefusal(err error) bool { |
| - return err == ErrUnavailable || errors.Is(err, ErrConflict) || errors.Is(err, ErrForbidden) || errors.Is(err, ErrNotFound) || errors.Is(err, team.ErrBudget) || errors.Is(err, team.ErrGrantRevoked) || errors.Is(err, team.ErrGrantStale) |
| + return err == ErrUnavailable || err == errPlanSelectionAsk || err == errPlanSecondFamily || errors.Is(err, ErrConflict) || errors.Is(err, ErrForbidden) || errors.Is(err, ErrNotFound) || errors.Is(err, team.ErrBudget) || errors.Is(err, team.ErrGrantRevoked) || errors.Is(err, team.ErrGrantStale) |
| } |
| func taskWait(tx *gorm.DB, id, code string) error { |
| if code == "" { |
| @@ -91,7 +91,7 @@ func (s *Store) refreshPendingPair(tx *gorm.DB, task Task, out *taskOutbox) erro |
| if err != nil { |
| return err |
| } |
| - eng, rev, err := s.planPair(tx, task, plan) |
| + eng, rev, err := s.selectionPolicy().Pair(tx, task, plan, false) |
| if err != nil { |
| return err |
| } |
diff --git a/internal/equipo/templates/connections.html b/internal/equipo/templates/connections.html| index b3944e6c..5150c370 100644 |
| --- a/internal/equipo/templates/connections.html |
| +++ b/internal/equipo/templates/connections.html |
| @@ -1,3 +1,3 @@ |
| {{define "content"}}<h1>{{copy "nav.connections"}}</h1><a rst-btn href="/runners/enrol">{{copy "connections.enrol"}}</a>{{template "region:activity" .}} |
| -<h2>{{copy "connections.personal"}}</h2>{{range .Choices}}<form equipo-form method="post" action="/projects/{{.Project.ID}}/connections"><h3>{{.Project.Name}}</h3><input type="hidden" name="revision" value="{{.Revision}}">{{range .Options}}<label><input type="checkbox" name="connection_id" value="{{.ID}}"{{if .Enabled}} checked{{end}}>{{copy "connections.enable"}}: {{.Label}}</label>{{end}}<label>{{copy "connections.pin"}}<select rst-input name="pinned_id"><option value="">{{copy "value.none"}}</option>{{$pinned:=.PinnedID}}{{range .Options}}<option value="{{.ID}}"{{if eq .ID $pinned}} selected{{end}}>{{.Label}}</option>{{end}}</select></label><button rst-btn>{{copy "form.save"}}</button></form>{{end}}{{end}} |
| -{{define "region:activity"}}<div id="activity" {{.Live.Attrs .Topic}}>{{range .Connections}}<section equipo-card><h2>{{.Report.AccountLabel}}</h2><p>{{.Person}}</p>{{if not .Available}}<p>{{copy "runner.preflight.unavailable"}}</p>{{end}}{{template "trial-label" .Isolation}}<p>{{copy "connections.versions"}}: {{.Report.Provider}} {{.Report.ProviderVersion}} / {{.Report.LauncherVersion}} / {{.Report.BwrapVersion}}</p>{{if .Unverified}}<p>{{copy "isolation.unverified"}}</p>{{else}}<p>{{copy "isolation.confined"}}</p>{{end}}</section>{{else}}<p data-empty-state="connections.empty">{{copy "connections.empty"}}</p>{{end}}</div>{{end}} |
| +<h2>{{copy "connections.personal"}}</h2>{{range .Choices}}<form equipo-form method="post" action="/projects/{{.Project.ID}}/connections"><h3>{{.Project.Name}}</h3><input type="hidden" name="revision" value="{{.Revision}}">{{range .Options}}<label><input type="checkbox" name="connection_id" value="{{.ID}}"{{if .Enabled}} checked{{end}}>{{copy "connections.enable"}}: {{.Label}}</label>{{end}}<label>{{copy "connections.reason"}}<select rst-input name="mode"><option value="best_fit"{{if eq .Mode "best_fit"}} selected{{end}}>{{copy "connections.best_fit"}}</option><option value="pinned"{{if eq .Mode "pinned"}} selected{{end}}>{{copy "connections.pinned"}}</option><option value="ask"{{if eq .Mode "ask"}} selected{{end}}>{{copy "connections.ask"}}</option></select></label><label>{{copy "connections.pin"}}<select rst-input name="pinned_id"><option value="">{{copy "value.none"}}</option>{{$pinned:=.PinnedID}}{{range .Options}}<option value="{{.ID}}"{{if eq .ID $pinned}} selected{{end}}>{{.Label}}</option>{{end}}</select></label><button rst-btn>{{copy "form.save"}}</button></form>{{end}}{{end}} |
| +{{define "region:activity"}}<div id="activity" {{.Live.Attrs .Topic}}>{{range .Connections}}<section equipo-card><h2>{{.Report.AccountLabel}}</h2><p>{{.Person}}</p><p>{{copy "connections.counted_usage"}}</p>{{if .Report.AllowanceKnown}}<span equipo-value>{{.Report.AllowanceRemaining}}</span>{{else}}<p>{{copy "connections.remaining_unknown"}}</p>{{end}}{{if not .Available}}<p>{{copy "runner.preflight.unavailable"}}</p>{{end}}{{template "trial-label" .Isolation}}<p>{{copy "connections.versions"}}: {{.Report.Provider}} {{.Report.ProviderVersion}} / {{.Report.LauncherVersion}} / {{.Report.BwrapVersion}}</p>{{if .Unverified}}<p>{{copy "isolation.unverified"}}</p>{{else}}<p>{{copy "isolation.confined"}}</p>{{end}}</section>{{else}}<p data-empty-state="connections.empty">{{copy "connections.empty"}}</p>{{end}}</div>{{end}} |
diff --git a/internal/equipo/templates/conversation_card.html b/internal/equipo/templates/conversation_card.html| index a8c02b9e..b7c67520 100644 |
| --- a/internal/equipo/templates/conversation_card.html |
| +++ b/internal/equipo/templates/conversation_card.html |
| @@ -26,7 +26,7 @@ |
| <p equipo-secondary>{{copy "plan.project"}}: {{.Project}}</p> |
| <p><span equipo-badge>{{copy "plan.revision"}} {{.Plan.Revision}}</span> <span equipo-badge>{{if eq .Task.ApprovalRevision .Plan.Revision}}{{copy "plan.approved"}}{{else}}{{copy "plan.proposed"}}{{end}}</span></p> |
| {{if .Plan.PlaybookID}}<p equipo-secondary>{{copy "plan.playbook"}}: {{.PlaybookName}} <span equipo-value>{{.Plan.PlaybookRevision}}</span></p>{{end}} |
| -<ol equipo-plan-steps>{{range .Steps}}<li equipo-plan-step><strong>{{if .Specialist}}{{copy (printf "nav.%s" .Specialist)}}{{else}}{{copy (printf "plan.action.%s" .Action)}}{{end}}</strong><span equipo-secondary>{{copy (printf "plan.action.%s" .Action)}}</span><span equipo-badge>{{copy (printf "step.%s" .State)}}</span><span equipo-value>{{.Model}} {{.Account}}</span>{{if .SelectionReason}}<span equipo-secondary title="{{.SelectionReason}}">{{.SelectionReason}}</span>{{end}}{{if .Actual}}<span equipo-secondary>{{copy "task.actual"}}: {{.Actual}}</span>{{end}}</li>{{end}}</ol> |
| +<ol equipo-plan-steps>{{range .Steps}}<li equipo-plan-step><strong>{{if .Specialist}}{{copy (printf "nav.%s" .Specialist)}}{{else}}{{copy (printf "plan.action.%s" .Action)}}{{end}}</strong><span equipo-secondary>{{copy (printf "plan.action.%s" .Action)}}</span><span equipo-badge>{{copy (printf "step.%s" .State)}}</span><span equipo-value>{{.Model}} {{.Account}}</span>{{if .Pick}}<span equipo-value>{{.Pick.Model}} {{.Pick.Account}}</span><span equipo-secondary>{{copy .Pick.Reason}}</span>{{end}}{{if .SelectionReason}}<span equipo-secondary title="{{.SelectionReason}}">{{.SelectionReason}}</span>{{end}}{{if .Actual}}<span equipo-secondary>{{copy "task.actual"}}: {{.Actual}}</span>{{end}}</li>{{end}}</ol> |
| <a href="/tasks/{{.Task.ID}}/plan#project">{{copy "plan.correct_project"}}</a> <a href="/tasks/{{.Task.ID}}/plan">{{copy "plan.edit"}}</a> <a href="/tasks/{{.Task.ID}}/thread">{{copy "conversation.thread_link"}}</a> |
| {{end}} |
| {{with .Question}} |
diff --git a/internal/equipo/templates/plan.html b/internal/equipo/templates/plan.html| index 75f94103..0b4c8f5d 100644 |
| --- a/internal/equipo/templates/plan.html |
| +++ b/internal/equipo/templates/plan.html |
| @@ -20,6 +20,7 @@ |
| <label>{{copy "plan.position"}}<input rst-input name="step_{{.Index}}_position" type="number" min="1" max="16" value="{{.Position}}" {{if .Locked}}readonly{{end}} required></label> |
| <label>{{copy "plan.instructions"}}<textarea rst-input name="step_{{.Index}}_instructions" rows="3" {{if .Locked}}readonly{{end}}>{{.Instructions}}</textarea></label> |
| <label>{{copy "plan.model"}}<input rst-input name="step_{{.Index}}_model" value="{{.Model}}" {{if .Locked}}readonly{{end}}></label>{{if .Locked}}<input type="hidden" name="step_{{.Index}}_connection" value="{{.ConnectionID}}"><span equipo-value>{{.Account}}</span>{{else}}<label>{{copy "plan.connection"}}<select rst-input name="step_{{.Index}}_connection">{{$connection := .ConnectionID}}{{if .ConnectionID}}<option value="{{.ConnectionID}}" selected>{{if .Account}}{{.Account}}{{else}}{{copy "plan.current_selection"}}{{end}}</option>{{end}}<option value="">{{copy "plan.unselected"}}</option>{{range $.Plan.Connections}}{{if ne .ID $connection}}<option value="{{.ID}}">{{.Label}}</option>{{end}}{{end}}</select></label>{{end}}<label>{{copy "plan.reason"}}<input rst-input name="step_{{.Index}}_reason" value="{{.SelectionReason}}" {{if .Locked}}readonly{{end}}></label> |
| +{{if .Pick}}{{if .Pick.Stale}}<p equipo-note>{{copy "connections.selection_changed"}}</p>{{end}}<p equipo-secondary>{{copy "connections.reason"}}: {{copy .Pick.Reason}}</p><span equipo-value>{{.Pick.Model}} {{.Pick.Account}}</span>{{if not .Pick.AllowanceRemaining}}<p>{{copy "connections.remaining_unknown"}}</p>{{end}}{{end}} |
| {{if .Actual}}<p equipo-secondary>{{copy "task.actual"}}: {{.Actual}}</p>{{end}} |
| {{if and (not .Locked) (not .Required)}}<label equipo-checkbox><input type="checkbox" name="step_{{.Index}}_remove" value="1">{{copy "plan.remove_step"}}</label>{{end}} |
| </fieldset> |
| @@ -31,6 +32,13 @@ |
| </fieldset></details>{{end}} |
| <button rst-btn="primary" type="submit">{{copy "form.save"}}</button> |
| </form> |
| +{{if .CanSelect}}{{range .Steps}}{{if and .Specialist (not .Locked)}} |
| +<form method="post" action="/tasks/{{$.Plan.Task.ID}}/steps/{{.Key}}/selection" equipo-form> |
| +<input type="hidden" name="request_id" value="{{.ConfirmID}}"><input type="hidden" name="revision" value="{{$.Plan.Plan.Revision}}"> |
| +<label>{{copy (printf "plan.action.%s" .Action)}}: {{copy "plan.connection"}}<select rst-input name="connection_id">{{range $.Plan.Connections}}<option value="{{.ID}}">{{.Label}}</option>{{end}}</select></label> |
| +<label>{{copy "plan.model"}}<input rst-input name="model" value="{{if .Pick}}{{.Pick.Model}}{{else}}{{.Model}}{{end}}" required></label> |
| +<button rst-btn>{{copy "connections.ask"}}</button></form> |
| +{{end}}{{end}}{{end}} |
| <form method="post" action="/tasks/{{.Task.ID}}/plan/approve" equipo-form><input type="hidden" name="request_id" value="{{.ApproveID}}"><input type="hidden" name="revision" value="{{.Plan.Revision}}"><button rst-btn type="submit">{{copy "plan.approve"}}</button></form> |
| <section id="project" equipo-card><h2>{{copy "plan.project"}}</h2><form method="post" action="/tasks/{{.Task.ID}}/project" equipo-form><input type="hidden" name="request_id" value="{{.CorrectID}}"><input type="hidden" name="revision" value="{{.Task.Revision}}"><label>{{copy "plan.correct_project"}}<select rst-input name="project_id">{{$project := .Plan.ProjectID}}{{range .Projects}}<option value="{{.ID}}" {{if eq .ID $project}}selected{{end}}>{{.Name}}</option>{{end}}</select></label><button rst-btn type="submit">{{copy "plan.correct_project"}}</button></form></section> |
| {{else}}<ol equipo-plan-steps>{{range .Steps}}<li equipo-plan-step data-plan-step="{{.Key}}"><strong>{{copy (printf "plan.action.%s" .Action)}}</strong><span equipo-badge>{{copy (printf "step.%s" .State)}}</span><p>{{.Instructions}}</p><span equipo-value>{{.Model}} {{.Account}}</span><span equipo-secondary title="{{.SelectionReason}}">{{.SelectionReason}}</span></li>{{end}}</ol>{{end}} |
diff --git a/internal/plan3test/plan_model_choice_migration_test.go b/internal/plan3test/plan_model_choice_migration_test.go| new file mode 100644 |
| index 00000000..260679c1 |
| --- /dev/null |
| +++ b/internal/plan3test/plan_model_choice_migration_test.go |
| @@ -0,0 +1,50 @@ |
| +package plan3test |
| + |
| +import ( |
| + "io" |
| + "log/slog" |
| + "path/filepath" |
| + "testing" |
| + |
| + "amadan.net/oficina/equipo/internal/equipo" |
| + "amadan.net/rastrillo/rastrillo/db" |
| + "amadan.net/rastrillo/rastrillo/migrate" |
| +) |
| + |
| +func TestPlanModelChoiceMigration(t *testing.T) { |
| + d, err := db.Open(filepath.Join(t.TempDir(), "choices.db"), slog.New(slog.NewTextHandler(io.Discard, nil))) |
| + must(t, err) |
| + t.Cleanup(func() { must(t, d.Close()) }) |
| + old := &migrate.Set{} |
| + for _, m := range equipo.BootSchema.All() { |
| + if m.ID != "equipo/0026_connection_modes" { |
| + old.Add(m) |
| + } |
| + } |
| + _, err = migrate.Apply(ctx, d, old) |
| + must(t, err) |
| + f := &fixture{DB: d} |
| + f.exec(t, `INSERT INTO connection_choices(person,project_id,revision,connection_ids_json,pinned_id) VALUES('saved',7,9,'["a","b"]','b')`) |
| + f.exec(t, `INSERT INTO audit_events(actor,kind,record_id) VALUES('saved','saved.audit','record')`) |
| + result, err := migrate.Apply(ctx, d, equipo.BootSchema) |
| + must(t, err) |
| + if len(result.Applied) != 1 || result.Applied[0] != "equipo/0026_connection_modes" { |
| + t.Fatal(result.Applied) |
| + } |
| + if f.count(t, `SELECT count(*) FROM connection_choices WHERE person='saved' AND project_id=7 AND revision=9 AND connection_ids_json='["a","b"]' AND pinned_id='b' AND mode='best_fit'`) != 1 || f.count(t, `SELECT count(*) FROM audit_events WHERE kind='saved.audit'`) != 1 { |
| + t.Fatal("migration changed ticks, pin or history") |
| + } |
| + fresh := newFixture(t) |
| + upgraded, err := migrate.Read(ctx, d.Writer()) |
| + must(t, err) |
| + clean, err := migrate.Read(ctx, fresh.DB.Writer()) |
| + must(t, err) |
| + if !upgraded.Equal(clean) { |
| + t.Fatal(upgraded.Diff(clean)) |
| + } |
| + result, err = migrate.Apply(ctx, d, equipo.BootSchema) |
| + must(t, err) |
| + if len(result.Applied) != 0 { |
| + t.Fatal("migration repeated") |
| + } |
| +} |
diff --git a/internal/plan3test/plan_model_choice_test.go b/internal/plan3test/plan_model_choice_test.go| new file mode 100644 |
| index 00000000..879c2f6f |
| --- /dev/null |
| +++ b/internal/plan3test/plan_model_choice_test.go |
| @@ -0,0 +1,379 @@ |
| +package plan3test |
| + |
| +import ( |
| + "amadan.net/oficina/equipo/internal/equipo/team" |
| + "amadan.net/oficina/equipo/internal/runnerproto" |
| + "encoding/json" |
| + "errors" |
| + "net/url" |
| + "reflect" |
| + "strconv" |
| + "strings" |
| + "testing" |
| + "time" |
| + |
| + "amadan.net/oficina/equipo/internal/equipo" |
| + "amadan.net/oficina/equipo/internal/taskplan" |
| +) |
| + |
| +func modelChoiceFixture(t *testing.T) (*fixture, taskplan.Plan) { |
| + t.Helper() |
| + f := newFixture(t) |
| + p := proposed(t, f) |
| + f.planConnections(t, p.ProjectID) |
| + f.exec(t, `INSERT INTO connections(id,runner_id,person,local_id,revision,last_seen,reports_json,security_hash) SELECT 'claude-two',runner_id,person,'claude-two',revision,last_seen,reports_json,security_hash FROM connections WHERE id='claude'`) |
| + f.exec(t, `UPDATE connection_choices SET pinned_id='',connection_ids_json='["claude","claude-two","codex"]'`) |
| + return f, p |
| +} |
| +func pick(t *testing.T, f *fixture, p taskplan.Plan, key string) equipo.Selection { |
| + t.Helper() |
| + s, e := f.Store.SelectPlanStep(ctx, owner, p.TaskID, key, equipo.Mutation{RequestID: "pick-" + key, Revision: p.Revision}) |
| + must(t, e) |
| + return s |
| +} |
| +func TestPlanModelChoiceOwnAccounts(t *testing.T) { |
| + f, p := modelChoiceFixture(t) |
| + f.exec(t, `UPDATE connections SET person=? WHERE id='claude'`, peer.Address) |
| + s := pick(t, f, p, "reproduce") |
| + if s.ConnectionID != "claude-two" || s.Person != owner.Address { |
| + t.Fatal("borrowed another person's account", s) |
| + } |
| + if _, e := f.Store.SelectPlanStep(ctx, peer, p.TaskID, "reproduce", equipo.Mutation{RequestID: "peer", Revision: p.Revision}); e == nil { |
| + t.Fatal("peer selected owner's account") |
| + } |
| + f.exec(t, `UPDATE connection_choices SET connection_ids_json='["codex"]',revision=revision+1`) |
| + if _, e := f.Store.ConfirmPlanSelection(ctx, owner, p.TaskID, "reproduce", "claude-two", "fixture-model", equipo.Mutation{RequestID: "unticked", Revision: p.Revision}); e == nil { |
| + t.Fatal("unticked account accepted") |
| + } |
| + f.exec(t, `UPDATE specialists SET allowed_models='[{"Provider":"codex","Family":"gpt","Model":"fixture-model"}]' WHERE key='engineering'`) |
| + s = pick(t, f, p, "implement") |
| + if s.Provider != "codex" || s.Family != "gpt" { |
| + t.Fatal("allowed model intersection ignored", s) |
| + } |
| +} |
| +func TestPlanModelChoiceModes(t *testing.T) { |
| + for _, mode := range []string{"best_fit", "pinned", "ask"} { |
| + t.Run(mode, func(t *testing.T) { |
| + f, p := modelChoiceFixture(t) |
| + must(t, f.Store.SaveConnectionChoice(ctx, owner, equipo.ConnectionChoice{ProjectID: p.ProjectID, Revision: 1, ConnectionIDs: []string{"claude", "claude-two", "codex"}, Mode: mode, PinnedID: map[string]string{"pinned": "claude-two"}[mode]})) |
| + m := equipo.Mutation{RequestID: "select", Revision: p.Revision} |
| + s, e := f.Store.SelectPlanStep(ctx, owner, p.TaskID, "reproduce", m) |
| + if mode == "ask" { |
| + if e == nil { |
| + t.Fatal("ask selected without confirmation") |
| + } |
| + // A plan proposal is not consent to an ask-each-pick selection. |
| + p.Steps[0].ConnectionID = "claude" |
| + p, e = f.Store.EditPlan(ctx, owner, p, equipo.Mutation{RequestID: "proposal-pick", Revision: p.Revision}) |
| + must(t, e) |
| + if _, e = f.Store.SelectPlanStep(ctx, owner, p.TaskID, "reproduce", equipo.Mutation{RequestID: "proposal-not-consent", Revision: p.Revision}); e == nil { |
| + t.Fatal("plan edit confirmed ask") |
| + } |
| + m = equipo.Mutation{RequestID: "confirm", Revision: p.Revision} |
| + s, e = f.Store.ConfirmPlanSelection(ctx, owner, p.TaskID, "reproduce", "claude-two", "fixture-model", m) |
| + must(t, e) |
| + again, e := f.Store.ConfirmPlanSelection(ctx, owner, p.TaskID, "reproduce", "claude-two", "fixture-model", m) |
| + must(t, e) |
| + if !reflect.DeepEqual(s, again) { |
| + t.Fatal("confirmation replay changed") |
| + } |
| + if _, e = f.Store.ConfirmPlanSelection(ctx, owner, p.TaskID, "reproduce", "claude", "fixture-model", m); !errors.Is(e, equipo.ErrConflict) { |
| + t.Fatal("changed replay accepted", e) |
| + } |
| + if s.Reason != "connections.reason_confirmed" { |
| + t.Fatal("missing confirmed reason", s) |
| + } |
| + } else { |
| + must(t, e) |
| + want := "claude" |
| + if mode == "pinned" { |
| + want = "claude-two" |
| + } |
| + if s.ConnectionID != want { |
| + t.Fatal("mode ignored", s) |
| + } |
| + } |
| + if s.AllowanceKnown || s.AllowanceRemaining != 0 || s.ChoiceRevision != 2 || s.SpecialistRevision == 0 || s.Revision == 0 { |
| + t.Fatal("unknown or revision lost", s) |
| + } |
| + }) |
| + } |
| +} |
| +func TestPlanModelChoiceReviewFamily(t *testing.T) { |
| + f, p := modelChoiceFixture(t) |
| + pick(t, f, p, "implement") |
| + if _, e := f.Store.ConfirmPlanSelection(ctx, owner, p.TaskID, "review", "claude", "fixture-model", equipo.Mutation{RequestID: "same-family", Revision: p.Revision}); e == nil { |
| + t.Fatal("same-family review accepted") |
| + } |
| + must(t, f.Store.SaveConnectionChoice(ctx, owner, equipo.ConnectionChoice{ProjectID: p.ProjectID, Revision: 1, ConnectionIDs: []string{"claude", "claude-two", "codex"}, Mode: "pinned", PinnedID: "claude"})) |
| + s := pick(t, f, p, "review") |
| + if s.Family != "gpt" { |
| + t.Fatal("pin defeated independent review", s) |
| + } |
| + f.exec(t, `UPDATE specialists SET allowed_models='[{"Provider":"claude","Family":"claude","Model":"fixture-model"}]' WHERE key='review'`) |
| + if _, e := f.Store.SelectPlanStep(ctx, owner, p.TaskID, "review", equipo.Mutation{RequestID: "family-restricted", Revision: p.Revision}); e == nil { |
| + t.Fatal("allowed-family intersection bypassed") |
| + } |
| +} |
| +func TestPlanModelChoiceImmutableStep(t *testing.T) { |
| + f, p := modelChoiceFixture(t) |
| + s := pick(t, f, p, "reproduce") |
| + raw, e := json.Marshal(s) |
| + must(t, e) |
| + f.exec(t, `INSERT INTO runner_assignments(id,task_id,step_key,claim_request,selection,state) VALUES('actual',?,'reproduce','claimed',?,'claimed')`, p.TaskID, string(raw)) |
| + must(t, f.Store.SaveConnectionChoice(ctx, owner, equipo.ConnectionChoice{ProjectID: p.ProjectID, Revision: 1, ConnectionIDs: []string{"claude-two", "codex"}, Mode: "pinned", PinnedID: "claude-two"})) |
| + actual, e := f.Store.SelectPlanStep(ctx, owner, p.TaskID, "reproduce", equipo.Mutation{RequestID: "after-change", Revision: p.Revision}) |
| + must(t, e) |
| + if actual.ConnectionID != s.ConnectionID || actual.Model != s.Model || actual.Reason != s.Reason { |
| + t.Fatal("actual selection rewritten", actual) |
| + } |
| + if _, e = f.Store.ConfirmPlanSelection(ctx, owner, p.TaskID, "reproduce", "claude-two", "fixture-model", equipo.Mutation{RequestID: "switch", Revision: p.Revision}); e == nil { |
| + t.Fatal("active work switched accounts") |
| + } |
| +} |
| +func TestPlanModelChoiceUnavailable(t *testing.T) { |
| + f, p := modelChoiceFixture(t) |
| + s := pick(t, f, p, "implement") |
| + if s.AllowanceKnown { |
| + t.Fatal("unknown allowance became known") |
| + } |
| + f.exec(t, `DELETE FROM connections WHERE id='codex'`) |
| + if _, e := f.Store.SelectPlanStep(ctx, owner, p.TaskID, "review", equipo.Mutation{RequestID: "missing-family", Revision: p.Revision}); e == nil { |
| + t.Fatal("missing second family ignored") |
| + } |
| + f.exec(t, `DROP TABLE connection_choices`) |
| + if _, e := f.Store.SelectPlanStep(ctx, owner, p.TaskID, "reproduce", equipo.Mutation{RequestID: "query-failure", Revision: p.Revision}); e == nil { |
| + t.Fatal("query error treated as empty choices") |
| + } |
| +} |
| +func TestPlanModelChoiceCoordinatorConnection(t *testing.T) { |
| + for _, mode := range []string{"best_fit", "pinned", "ask", "excluded", "alone"} { |
| + t.Run(mode, func(t *testing.T) { |
| + f, p := modelChoiceFixture(t) |
| + f.exec(t, `INSERT INTO coordinator_bindings(id,person,runner_id,connection_id,revision,generation) VALUES('binding',?,'fixture-runner','claude',1,1)`, owner.Address) |
| + if mode == "pinned" || mode == "ask" { |
| + must(t, f.Store.SaveConnectionChoice(ctx, owner, equipo.ConnectionChoice{ProjectID: p.ProjectID, Revision: 1, ConnectionIDs: []string{"claude", "claude-two", "codex"}, Mode: mode, PinnedID: "claude"})) |
| + } |
| + if mode == "excluded" { |
| + f.exec(t, `UPDATE connection_choices SET connection_ids_json='["claude","codex"]'`) |
| + f.exec(t, `UPDATE specialists SET allowed_models='[{"Provider":"claude","Family":"claude","Model":"fixture-model"}]' WHERE key='engineering'`) |
| + } |
| + if mode == "alone" { |
| + f.exec(t, `UPDATE connection_choices SET connection_ids_json='["claude"]'`) |
| + } |
| + var s equipo.Selection |
| + if mode == "ask" { |
| + var e error |
| + s, e = f.Store.ConfirmPlanSelection(ctx, owner, p.TaskID, "reproduce", "claude", "fixture-model", equipo.Mutation{RequestID: "ask-shared", Revision: p.Revision}) |
| + must(t, e) |
| + } else { |
| + s = pick(t, f, p, "reproduce") |
| + } |
| + want := "claude" |
| + if mode == "best_fit" { |
| + want = "claude-two" |
| + } |
| + if s.ConnectionID != want { |
| + t.Fatal("coordinator preference overrode eligibility or consent", s) |
| + } |
| + }) |
| + } |
| + t.Run("waiting-and-release", TestCoordinatorConnectionWaiting) |
| +} |
| + |
| +func TestPlanModelChoiceClaimAndTurn(t *testing.T) { |
| + for _, boundary := range []string{"claim", "turn"} { |
| + for _, change := range []string{"choice", "connection", "specialist", "confirmation"} { |
| + t.Run(boundary+"/"+change, func(t *testing.T) { |
| + f, p := modelChoiceFixture(t) |
| + p.Kind = taskplan.Recommendation |
| + p.Steps = []taskplan.Step{{Key: "research", Specialist: "product", Action: "recommend"}, {Key: "merge", Action: "person"}} |
| + var err error |
| + p, err = f.Store.EditPlan(ctx, owner, p, equipo.Mutation{RequestID: "research", Revision: p.Revision}) |
| + must(t, err) |
| + must(t, f.Store.SaveConnectionChoice(ctx, owner, equipo.ConnectionChoice{ProjectID: p.ProjectID, Revision: 1, ConnectionIDs: []string{"claude", "claude-two", "codex"}, Mode: "ask"})) |
| + var path string |
| + must(t, f.DB.Writer().QueryRow("SELECT file FROM pragma_database_list WHERE name='main'").Scan(&path)) |
| + x, err := f.Store.AttachExecution(ctx, path, team.Options{Clock: team.RealClock{}, Authority: equipo.NewAuthority(f.Store, nil)}) |
| + must(t, err) |
| + t.Cleanup(func() { must(t, x.Core.Close()) }) |
| + _, err = x.Core.Resume(ctx) |
| + must(t, err) |
| + f.exec(t, "INSERT INTO runner_credentials(id,runner_id,instance_id,audience,person,machine_key_hash,token_hash,expires_at) VALUES('fixture-credential','fixture-runner',?,?,?,'','fixture-token',?)", f.TeamID, runnerproto.RunnerAudience, owner.Address, time.Now().Add(time.Hour).UTC()) |
| + principal := equipo.RunnerPrincipal{RunnerID: "fixture-runner", Person: owner.Address, CredentialID: "fixture-credential"} |
| + _, err = f.Store.ApprovePlan(ctx, owner, p.TaskID, equipo.Mutation{RequestID: "approve", Revision: p.Revision}) |
| + must(t, err) |
| + if err = f.Store.CheckPlanDispatch(ctx, owner, p.TaskID); err == nil { |
| + t.Fatal("plan approval confirmed ask") |
| + } |
| + _, err = f.Store.ConfirmPlanSelection(ctx, owner, p.TaskID, "research", "claude", "fixture-model", equipo.Mutation{RequestID: "confirm-research", Revision: p.Revision}) |
| + must(t, err) |
| + must(t, x.Sync(ctx)) |
| + var id string |
| + var revision int64 |
| + must(t, f.DB.Writer().QueryRow("SELECT id,revision FROM runner_assignments WHERE task_id=? AND state='pending'", p.TaskID).Scan(&id, &revision)) |
| + claim := equipo.ClaimRequest{Version: 2, AssignmentID: id, Revision: revision, RequestID: "claim"} |
| + var q equipo.RunnerRequest |
| + if boundary == "turn" { |
| + c, e := x.Claim(ctx, principal, claim) |
| + must(t, e) |
| + q = equipo.RunnerRequest{Version: 2, AssignmentID: id, Scope: c.Scope, Handle: c.Handle, RequestID: "validate"} |
| + _, e = x.Mutate(ctx, principal, "validate", q) |
| + must(t, e) |
| + } |
| + switch change { |
| + case "choice": |
| + f.exec(t, "UPDATE connection_choices SET revision=revision+1") |
| + case "connection": |
| + f.exec(t, "UPDATE connections SET revision=revision+1 WHERE id='claude'") |
| + case "specialist": |
| + f.exec(t, "UPDATE specialists SET revision=revision+1 WHERE key='product'") |
| + case "confirmation": |
| + f.exec(t, "UPDATE plan_selections SET confirmed=false") |
| + } |
| + if boundary == "claim" { |
| + _, err = x.Claim(ctx, principal, claim) |
| + } else { |
| + _, err = x.Mutate(ctx, principal, "validate", q) |
| + } |
| + if err == nil { |
| + t.Fatal("stale selection reached " + boundary) |
| + } |
| + }) |
| + } |
| + } |
| +} |
| + |
| +func TestPlanModelChoiceHeadroom(t *testing.T) { |
| + f, p := modelChoiceFixture(t) |
| + f.exec(t, `UPDATE connections SET reports_json=json_set(reports_json,'$[0].AllowanceKnown',json('true'),'$[0].AllowanceRemaining',50) WHERE id='claude-two'`) |
| + f.exec(t, `UPDATE connections SET reports_json=json_set(reports_json,'$[0].AllowanceRemaining',9999) WHERE id='claude'`) |
| + s := pick(t, f, p, "reproduce") |
| + if s.ConnectionID != "claude-two" || !s.AllowanceKnown || s.AllowanceRemaining != 50 { |
| + t.Fatal("known headroom ignored or unknown treated as known", s) |
| + } |
| + f.exec(t, `INSERT INTO coordinator_bindings(id,person,runner_id,connection_id,revision,generation) VALUES('binding',?,'fixture-runner','claude-two',1,1)`, owner.Address) |
| + s = pick(t, f, p, "implement") |
| + if s.ConnectionID != "claude" || s.AllowanceKnown || s.AllowanceRemaining != 0 { |
| + t.Fatal("headroom defeated coordinator preference or invented allowance", s) |
| + } |
| +} |
| + |
| +func TestPlanModelChoiceForms(t *testing.T) { |
| + f, p := modelChoiceFixture(t) |
| + apiRouter(t, f, nil) |
| + v := url.Values{"revision": {"1"}, "mode": {"ask"}, "connection_id": {"claude", "claude-two", "codex"}} |
| + expectHTTP(t, formPost(t, f, owner, "/projects/"+strconv.FormatInt(p.ProjectID, 10)+"/connections", v), 303) |
| + w := f.get(t, owner, "/connections") |
| + expectHTTP(t, w, 200) |
| + if !strings.Contains(w.Body.String(), `value="ask" selected`) || !strings.Contains(w.Body.String(), "Remaining allowance is unknown.") { |
| + t.Fatal("mode or unknown allowance absent") |
| + } |
| + w = f.get(t, owner, "/tasks/"+p.TaskID+"/plan") |
| + expectHTTP(t, w, 200) |
| + if !strings.Contains(w.Body.String(), "/steps/reproduce/selection") { |
| + t.Fatal("plan has no independent confirmation form") |
| + } |
| + v = actionForm("form-confirm", p.Revision) |
| + v.Set("connection_id", "claude") |
| + v.Set("model", "fixture-model") |
| + expectHTTP(t, formPost(t, f, owner, "/tasks/"+p.TaskID+"/steps/reproduce/selection", v), 303) |
| + expectHTTP(t, formPost(t, f, owner, "/tasks/"+p.TaskID+"/steps/reproduce/selection", v), 303) |
| + w = f.get(t, owner, "/tasks/"+p.TaskID+"/plan") |
| + expectHTTP(t, w, 200) |
| + if !strings.Contains(w.Body.String(), "Selection reason") { |
| + t.Fatal("recorded reason absent") |
| + } |
| + expectHTTP(t, formPost(t, f, peer, "/tasks/"+p.TaskID+"/steps/reproduce/selection", v), 403) |
| + f.exec(t, "UPDATE connection_choices SET revision=revision+1") |
| + w = f.get(t, owner, "/tasks/"+p.TaskID+"/plan") |
| + expectHTTP(t, w, 200) |
| + if !strings.Contains(w.Body.String(), "The selection changed. Confirm it again.") { |
| + t.Fatal("stale pick looks confirmed") |
| + } |
| + |
| + // Task and journey projections keep unknown values nullable and omit routing. |
| + w = apiRequest(t, f, owner, "GET", "/api/v1/tasks/"+p.TaskID, "", "", "") |
| + expectHTTP(t, w, 200) |
| + body := w.Body.String() |
| + if !strings.Contains(body, `"allowance_remaining":null`) || !strings.Contains(body, `"usage":null`) || strings.Contains(body, "CredentialHome") || strings.Contains(body, "ObservedAccount") { |
| + t.Fatal("unsafe or invented person projection", body) |
| + } |
| +} |
| + |
| +func TestPlanModelChoiceAuthorityAndRollback(t *testing.T) { |
| + f, p := modelChoiceFixture(t) |
| + m := equipo.Mutation{RequestID: "atomic", Revision: p.Revision} |
| + f.exec(t, `CREATE TRIGGER reject_selection_audit BEFORE INSERT ON audit_events WHEN NEW.kind='plan.confirm_selection' BEGIN SELECT RAISE(ABORT,'fixture audit failure'); END`) |
| + if _, err := f.Store.ConfirmPlanSelection(ctx, owner, p.TaskID, "reproduce", "claude", "fixture-model", m); err == nil { |
| + t.Fatal("selection ignored failed audit") |
| + } |
| + if f.count(t, "SELECT count(*) FROM plan_selections") != 0 { |
| + t.Fatal("failed audit left selection") |
| + } |
| + f.exec(t, "DROP TRIGGER reject_selection_audit") |
| + _, err := f.Store.ConfirmPlanSelection(ctx, owner, p.TaskID, "reproduce", "claude", "fixture-model", m) |
| + must(t, err) |
| + f.exec(t, "UPDATE members SET active=false WHERE address=?", owner.Address) |
| + if _, err = f.Store.ConfirmPlanSelection(ctx, owner, p.TaskID, "reproduce", "claude", "fixture-model", m); err == nil { |
| + t.Fatal("replay ignored removed membership") |
| + } |
| +} |
| + |
| +func TestPlanModelChoiceAskBuilder(t *testing.T) { |
| + f, p := modelChoiceFixture(t) |
| + must(t, f.Store.SaveConnectionChoice(ctx, owner, equipo.ConnectionChoice{ProjectID: p.ProjectID, Revision: 1, ConnectionIDs: []string{"claude", "claude-two", "codex"}, Mode: "ask"})) |
| + _, err := f.Store.ConfirmPlanSelection(ctx, owner, p.TaskID, "reproduce", "claude", "fixture-model", equipo.Mutation{RequestID: "confirm-reproduce", Revision: p.Revision}) |
| + must(t, err) |
| + var path string |
| + must(t, f.DB.Writer().QueryRow("SELECT file FROM pragma_database_list WHERE name='main'").Scan(&path)) |
| + x, err := f.Store.AttachExecution(ctx, path, team.Options{Clock: team.RealClock{}, Authority: equipo.NewAuthority(f.Store, nil)}) |
| + must(t, err) |
| + t.Cleanup(func() { must(t, x.Core.Close()) }) |
| + _, err = x.Core.Resume(ctx) |
| + must(t, err) |
| + f.exec(t, "INSERT INTO runner_credentials(id,runner_id,instance_id,audience,person,machine_key_hash,token_hash,expires_at) VALUES('fixture-credential','fixture-runner',?,?,?,'','fixture-token',?)", f.TeamID, runnerproto.RunnerAudience, owner.Address, time.Now().Add(time.Hour).UTC()) |
| + principal := equipo.RunnerPrincipal{RunnerID: "fixture-runner", Person: owner.Address, CredentialID: "fixture-credential"} |
| + must(t, x.Sync(ctx)) |
| + var id string |
| + var revision int64 |
| + must(t, f.DB.Writer().QueryRow("SELECT id,revision FROM runner_assignments WHERE task_id=? AND state='pending'", p.TaskID).Scan(&id, &revision)) |
| + _, err = x.Claim(ctx, principal, equipo.ClaimRequest{Version: 2, AssignmentID: id, Revision: revision, RequestID: "prepare-claim"}) |
| + must(t, err) |
| +} |
| + |
| +func TestPlanModelChoicePinAndCustomReview(t *testing.T) { |
| + f, p := modelChoiceFixture(t) |
| + bad := equipo.ConnectionChoice{ProjectID: p.ProjectID, Revision: 1, ConnectionIDs: []string{"claude", "claude-two", "codex"}, Mode: "pinned"} |
| + if err := f.Store.SaveConnectionChoice(ctx, owner, bad); err == nil { |
| + t.Fatal("pinned mode accepted without a pin") |
| + } |
| + bad.Mode = "invented" |
| + if err := f.Store.SaveConnectionChoice(ctx, owner, bad); err == nil { |
| + t.Fatal("unknown mode accepted") |
| + } |
| + bad.Mode = "pinned" |
| + bad.PinnedID = "claude" |
| + must(t, f.Store.SaveConnectionChoice(ctx, owner, bad)) |
| + f.exec(t, `UPDATE connections SET reports_json=json_set(reports_json,'$[0].Available',json('false')) WHERE id='claude'`) |
| + if _, err := f.Store.SelectPlanStep(ctx, owner, p.TaskID, "reproduce", equipo.Mutation{RequestID: "unavailable-pin", Revision: p.Revision}); err == nil { |
| + t.Fatal("unavailable pin silently switched") |
| + } |
| + f.exec(t, `UPDATE connections SET reports_json=json_set(reports_json,'$[0].Available',json('true')) WHERE id='claude'`) |
| + var sp equipo.Specialist |
| + must(t, f.DB.G.First(&sp, "key='review'").Error) |
| + sp.Key = "custom-review" |
| + sp.Name = "Custom review" |
| + sp.Required = false |
| + sp.Role = "" |
| + must(t, f.DB.G.Create(&sp).Error) |
| + for i := range p.Steps { |
| + if p.Steps[i].Action == "review" { |
| + p.Steps[i].Specialist = sp.Key |
| + } |
| + } |
| + var err error |
| + if _, err = f.Store.EditPlan(ctx, owner, p, equipo.Mutation{RequestID: "custom-review", Revision: p.Revision}); err == nil { |
| + t.Fatal("custom specialist replaced required independent Review") |
| + } |
| +} |