| 1 | package plan3test |
| 2 | |
| 3 | import ( |
| 4 | "amadan.net/oficina/equipo/internal/equipo" |
| 5 | "amadan.net/oficina/equipo/internal/equipo/team" |
| 6 | "amadan.net/oficina/equipo/internal/runnerproto" |
| 7 | "amadan.net/oficina/equipo/internal/taskplan" |
| 8 | "context" |
| 9 | "database/sql" |
| 10 | "encoding/json" |
| 11 | "strings" |
| 12 | "testing" |
| 13 | "time" |
| 14 | ) |
| 15 | |
| 16 | func TestPlanWorkflowRecommendation(t *testing.T) { |
| 17 | task := equipo.Task{ID: "task", TeamID: "team", Requester: owner.Address, ProjectID: 1, PlanRevision: 1} |
| 18 | project := equipo.Project{ID: 1, Repository: "amadan.net/test/fixture", DefaultBranch: "main"} |
| 19 | p := taskplan.Plan{TaskID: task.ID, Revision: 1, ProjectID: 1, Kind: taskplan.Recommendation, Steps: []taskplan.Step{{Key: "research", Specialist: "product", Action: "recommend"}, {Key: "merge", Action: "person"}}} |
| 20 | pol, err := team.RunnerPolicy("subscription", team.Limits{Calls: 24, InputTokens: 200000, OutputTokens: 40000}, team.Limits{Calls: 1, InputTokens: 32000, OutputTokens: 4000}, team.Rates{}) |
| 21 | must(t, err) |
| 22 | spec, err := equipo.PlanJobSpec(task, project, p, pol) |
| 23 | must(t, err) |
| 24 | if spec.Target.Kind != team.TargetProjectRead || spec.Target.Ref != "" || spec.Evidence.Predicate != "" || len(spec.Steps) != 1 || spec.Steps[0].Capability != team.CapResearch { |
| 25 | t.Fatalf("research gained write authority: %+v", spec) |
| 26 | } |
| 27 | } |
| 28 | func TestPlanWorkflowFeature(t *testing.T) { |
| 29 | task := equipo.Task{ID: "task", TeamID: "team", Requester: owner.Address, ProjectID: 1, PlanRevision: 1, ReviewRef: "equipo/task", BaseCommit: strings.Repeat("a", 40), CheckDefinitionHash: strings.Repeat("b", 64), BaselineTestSetHash: strings.Repeat("c", 64)} |
| 30 | project := equipo.Project{ID: 1, Repository: "amadan.net/test/fixture", DefaultBranch: "main"} |
| 31 | p := taskplan.BugPlan(task.ID, 1) |
| 32 | p.Kind = taskplan.Feature |
| 33 | p.Steps[0] = taskplan.Step{Key: "scope", Specialist: "product", Action: "scope"} |
| 34 | pol, err := team.RunnerPolicy("subscription", team.Limits{Calls: 24, InputTokens: 200000, OutputTokens: 40000}, team.Limits{Calls: 1, InputTokens: 32000, OutputTokens: 4000}, team.Rates{}) |
| 35 | must(t, err) |
| 36 | spec, err := equipo.PlanJobSpec(task, project, p, pol) |
| 37 | must(t, err) |
| 38 | if spec.Evidence.Predicate != team.PredicateSoftwareFeature || spec.Steps[0].Capability != team.CapScope { |
| 39 | t.Fatalf("feature used bug plan: %+v", spec) |
| 40 | } |
| 41 | } |
| 42 | func TestPlanWorkflowInvestigation(t *testing.T) { |
| 43 | p := taskplan.Plan{ProjectID: 1, Revision: 1, Kind: taskplan.Investigation, Steps: []taskplan.Step{{Key: "research", Specialist: "product", Action: "investigate"}, {Key: "merge", Action: "person"}}} |
| 44 | must(t, taskplan.Validate(p)) |
| 45 | p.Steps = append(p.Steps[:1], taskplan.Step{Key: "build", Specialist: "engineering", Action: "implement"}, p.Steps[1]) |
| 46 | if taskplan.Validate(p) == nil { |
| 47 | t.Fatal("investigation built without a new publication plan") |
| 48 | } |
| 49 | } |
| 50 | |
| 51 | func TestPlanWorkflowRecommendationDelivery(t *testing.T) { planReadDelivery(t, false) } |
| 52 | func TestPlanWorkflowInvestigationCheckpoint(t *testing.T) { planReadDelivery(t, true) } |
| 53 | func planReadDelivery(t *testing.T, investigation bool) { |
| 54 | f := newFixture(t) |
| 55 | p := proposed(t, f) |
| 56 | f.planConnections(t, p.ProjectID) |
| 57 | p.Kind = taskplan.Recommendation |
| 58 | if investigation { |
| 59 | p.Kind = taskplan.Investigation |
| 60 | } |
| 61 | p.Steps = []taskplan.Step{{Key: "research", Specialist: "product", Action: "recommend"}, {Key: "merge", Action: "person"}} |
| 62 | var err error |
| 63 | p, err = f.Store.EditPlan(ctx, owner, p, equipo.Mutation{RequestID: "read-plan", Revision: p.Revision}) |
| 64 | must(t, err) |
| 65 | // One personal family can research; the other account is absent. |
| 66 | if !investigation { |
| 67 | f.exec(t, "DELETE FROM connections WHERE id='codex'") |
| 68 | } |
| 69 | var path string |
| 70 | must(t, f.DB.Writer().QueryRow("SELECT file FROM pragma_database_list WHERE name='main'").Scan(&path)) |
| 71 | x, err := f.Store.AttachExecution(ctx, path, team.Options{Clock: team.RealClock{}, Authority: equipo.NewAuthority(f.Store, nil), Provenance: func(context.Context, *sql.Tx, team.Scope, team.Handle) (team.Provenance, error) { |
| 72 | return team.Provenance{Producer: "fixture", Provider: "claude", ModelFamily: "claude", Context: "session"}, nil |
| 73 | }}) |
| 74 | must(t, err) |
| 75 | t.Cleanup(func() { must(t, x.Core.Close()) }) |
| 76 | x.SetRunnerValidators(equipo.RunnerValidators{Artifact: func(context.Context, equipo.Assignment, equipo.RunnerRequest) error { return nil }}) |
| 77 | _, err = x.Core.Resume(ctx) |
| 78 | must(t, err) |
| 79 | 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()) |
| 80 | must(t, x.Sync(ctx)) |
| 81 | var id string |
| 82 | var rev int64 |
| 83 | must(t, f.DB.Writer().QueryRow("SELECT id,revision FROM runner_assignments WHERE task_id=? AND state='pending'", p.TaskID).Scan(&id, &rev)) |
| 84 | principal := equipo.RunnerPrincipal{RunnerID: "fixture-runner", Person: owner.Address, CredentialID: "fixture-credential"} |
| 85 | c, err := x.Claim(ctx, principal, equipo.ClaimRequest{Version: 2, AssignmentID: id, Revision: rev, RequestID: "claim"}) |
| 86 | must(t, err) |
| 87 | if c.Brief.Step.Action != "recommend" || c.Brief.Step.PlanRevision != p.Revision || len(c.Brief.Sources) != 1 || c.Brief.Target.Ref != "" { |
| 88 | t.Fatalf("read brief: %+v", c.Brief) |
| 89 | } |
| 90 | answer := team.AnswerResult{Body: "An answer from verified project material", Sources: []team.SourceRef{c.Brief.Sources[0].Ref}} |
| 91 | raw, _ := json.Marshal(answer) |
| 92 | q := equipo.RunnerRequest{Version: 2, AssignmentID: id, Scope: c.Scope, Handle: c.Handle, RequestID: "answer", Artifact: &team.ArtifactSpec{Role: team.RoleAnswer, MediaType: "application/json", Payload: raw}} |
| 93 | // A failed delivery must roll back artifact registration and step completion. |
| 94 | f.exec(t, "CREATE TRIGGER answer_failure BEFORE INSERT ON conversation_messages BEGIN SELECT RAISE(ABORT,'fixture delivery failure'); END") |
| 95 | if _, err = x.Mutate(ctx, principal, "artifacts", q); err == nil { |
| 96 | t.Fatal("delivery failure ignored") |
| 97 | } |
| 98 | if f.count(t, "SELECT count(*) FROM artifacts WHERE job_id=?", c.Scope.Job) != 0 || f.count(t, "SELECT count(*) FROM attempts WHERE id=? AND state='succeeded'", c.Handle.Attempt) != 0 { |
| 99 | t.Fatal("answer partially committed") |
| 100 | } |
| 101 | f.exec(t, "DROP TRIGGER answer_failure") |
| 102 | _, err = x.Mutate(ctx, principal, "artifacts", q) |
| 103 | must(t, err) |
| 104 | _, err = x.Mutate(ctx, principal, "artifacts", q) |
| 105 | must(t, err) |
| 106 | if f.count(t, "SELECT count(*) FROM conversation_messages WHERE author_kind='specialist'") != 1 || f.count(t, "SELECT count(*) FROM artifacts WHERE job_id=? AND role='answer'", c.Scope.Job) != 1 || f.count(t, "SELECT count(*) FROM attempts WHERE id=? AND state='succeeded'", c.Handle.Attempt) != 1 { |
| 107 | t.Fatal("answer was not delivered once with completion") |
| 108 | } |
| 109 | changed := q |
| 110 | changedArtifact := *q.Artifact |
| 111 | changedAnswer := answer |
| 112 | changedAnswer.Body = "a different answer" |
| 113 | changedArtifact.Payload, _ = json.Marshal(changedAnswer) |
| 114 | changed.Artifact = &changedArtifact |
| 115 | if _, err = x.Mutate(ctx, principal, "artifacts", changed); err == nil { |
| 116 | t.Fatal("changed answer replay accepted") |
| 117 | } |
| 118 | if investigation { |
| 119 | must(t, x.Core.ContainUntrusted(ctx, c.Scope, c.Handle)) |
| 120 | f.exec(t, "UPDATE runner_assignments SET state='contained' WHERE id=?", id) |
| 121 | conclude := q |
| 122 | conclude.RequestID = "conclude" |
| 123 | conclude.Artifact = nil |
| 124 | _, err = x.Mutate(ctx, principal, "conclude", conclude) |
| 125 | must(t, err) |
| 126 | task, err := f.Store.Task(ctx, owner, p.TaskID) |
| 127 | must(t, err) |
| 128 | if task.State != "waiting_checkpoint" { |
| 129 | t.Fatal("investigation skipped human checkpoint", task.State) |
| 130 | } |
| 131 | beforeJob := task.JobID |
| 132 | next := taskplan.BugPlan(p.TaskID, p.ProjectID) |
| 133 | next.Revision = p.Revision |
| 134 | next.Kind = taskplan.Feature |
| 135 | next.Steps[0] = taskplan.Step{Key: "research", Specialist: "product", Action: "scope"} |
| 136 | next, err = f.Store.EditPlan(ctx, owner, next, equipo.Mutation{RequestID: "explicit-build-revision", Revision: p.Revision}) |
| 137 | must(t, err) |
| 138 | task, err = f.Store.Task(ctx, owner, p.TaskID) |
| 139 | must(t, err) |
| 140 | if next.Revision != p.Revision+1 || task.State != "proposed" || task.JobID != 0 { |
| 141 | t.Fatal("checkpoint did not require fresh dispatch", task) |
| 142 | } |
| 143 | old, err := x.Core.GetJob(ctx, team.Scope{Account: team.AccountID(f.TeamID), Job: beforeJob}) |
| 144 | must(t, err) |
| 145 | if old.State != team.JobSucceeded { |
| 146 | t.Fatal("historical research changed") |
| 147 | } |
| 148 | |
| 149 | // A retained runner reconciliation record belongs to the old job too. |
| 150 | f.exec(t, "UPDATE runner_assignments SET state='reconcile' WHERE id=?", id) |
| 151 | // A completed investigation must not bind the replacement to its runner. |
| 152 | f.exec(t, "INSERT INTO runners(id,person,instance_id,revision) VALUES('second-runner',?,?,1)", owner.Address, f.TeamID) |
| 153 | f.exec(t, "UPDATE connections SET runner_id='second-runner',revision=revision+1") |
| 154 | f.exec(t, "INSERT INTO runner_credentials(id,runner_id,instance_id,audience,person,machine_key_hash,token_hash,expires_at) VALUES('second-credential','second-runner',?,?,?,'','second-token',?)", f.TeamID, runnerproto.RunnerAudience, owner.Address, time.Now().Add(time.Hour).UTC()) |
| 155 | must(t, x.Sync(ctx)) |
| 156 | task, err = f.Store.Task(ctx, owner, p.TaskID) |
| 157 | must(t, err) |
| 158 | if task.State != "preparing" { |
| 159 | t.Fatal("replacement did not prepare on new runner", task.State, task.WaitCode) |
| 160 | } |
| 161 | var project equipo.Project |
| 162 | must(t, f.DB.G.First(&project, p.ProjectID).Error) |
| 163 | second := equipo.RunnerPrincipal{RunnerID: "second-runner", Person: owner.Address, CredentialID: "second-credential"} |
| 164 | definition := []byte("checkpoint check") |
| 165 | task, err = f.Store.PrepareBug(ctx, second, p.TaskID, task.Revision, equipo.PreparedBug{Repository: project.Repository, DefaultBranch: project.DefaultBranch, BaseCommit: strings.Repeat("a", 40), CheckDefinition: definition, CheckDefinitionHash: team.ContentDigest(definition), BaselineTestSetHash: strings.Repeat("b", 64)}) |
| 166 | must(t, err) |
| 167 | task, err = f.Store.StartBug(ctx, second, p.TaskID, task.Revision) |
| 168 | must(t, err) |
| 169 | if task.JobID == beforeJob { |
| 170 | t.Fatal("replacement reused historical job") |
| 171 | } |
| 172 | must(t, x.Sync(ctx)) |
| 173 | var nextID string |
| 174 | must(t, f.DB.Writer().QueryRow("SELECT id,revision FROM runner_assignments WHERE task_id=? AND job_id=? AND step_key='research' AND state='pending'", p.TaskID, task.JobID).Scan(&nextID, &rev)) |
| 175 | nextClaim, err := x.Claim(ctx, second, equipo.ClaimRequest{Version: 2, AssignmentID: nextID, Revision: rev, RequestID: "replacement-claim"}) |
| 176 | must(t, err) |
| 177 | if nextClaim.Brief.Step.PlanRevision != next.Revision || nextClaim.Brief.Selection.RunnerID != "second-runner" { |
| 178 | t.Fatal("stale replacement dispatch", nextClaim.Brief.Step) |
| 179 | } |
| 180 | return |
| 181 | } |
| 182 | for _, column := range []string{"project", "budget", "plan", "choice"} { |
| 183 | var undo string |
| 184 | switch column { |
| 185 | case "project": |
| 186 | f.exec(t, "UPDATE projects SET revision=revision+1 WHERE id=?", p.ProjectID) |
| 187 | undo = "UPDATE projects SET revision=revision-1" |
| 188 | case "budget": |
| 189 | f.exec(t, "UPDATE budget_records SET revision=revision+1") |
| 190 | undo = "UPDATE budget_records SET revision=revision-1" |
| 191 | case "plan": |
| 192 | f.exec(t, "UPDATE tasks SET plan_revision=plan_revision+1 WHERE id=?", p.TaskID) |
| 193 | undo = "UPDATE tasks SET plan_revision=plan_revision-1" |
| 194 | case "choice": |
| 195 | f.exec(t, "UPDATE connection_choices SET revision=revision+1") |
| 196 | undo = "UPDATE connection_choices SET revision=revision-1" |
| 197 | } |
| 198 | if _, err = x.Mutate(ctx, principal, "artifacts", q); err == nil { |
| 199 | t.Fatal("changed dispatch identity accepted", column) |
| 200 | } |
| 201 | f.exec(t, undo) |
| 202 | } |
| 203 | f.exec(t, "UPDATE connections SET revision=revision+1 WHERE id='claude'") |
| 204 | if _, err = x.Mutate(ctx, principal, "artifacts", q); err == nil { |
| 205 | t.Fatal("replay ignored revoked selection") |
| 206 | } |
| 207 | } |
| 208 | |
| 209 | func TestPlanWorkflowConnectionPreference(t *testing.T) { |
| 210 | f := newFixture(t) |
| 211 | p := proposed(t, f) |
| 212 | f.planConnections(t, p.ProjectID) |
| 213 | f.exec(t, `INSERT INTO connections(id,runner_id,person,local_id,revision,last_seen,reports_json,security_hash) SELECT 'other-claude',runner_id,person,'other-local',revision,last_seen,reports_json,security_hash FROM connections WHERE id='claude'`) |
| 214 | f.exec(t, `UPDATE connection_choices SET pinned_id='',connection_ids_json='["claude","other-claude","codex"]'`) |
| 215 | p.Steps[0].ConnectionID = "other-claude" |
| 216 | var err error |
| 217 | p, err = f.Store.EditPlan(ctx, owner, p, equipo.Mutation{RequestID: "different-account", Revision: p.Revision}) |
| 218 | must(t, err) |
| 219 | must(t, f.Store.CheckPlanDispatch(ctx, owner, p.TaskID)) |
| 220 | var path string |
| 221 | must(t, f.DB.Writer().QueryRow("SELECT file FROM pragma_database_list WHERE name='main'").Scan(&path)) |
| 222 | x, err := f.Store.AttachExecution(ctx, path, team.Options{Clock: team.RealClock{}, Authority: equipo.NewAuthority(f.Store, nil)}) |
| 223 | must(t, err) |
| 224 | t.Cleanup(func() { must(t, x.Core.Close()) }) |
| 225 | _, err = x.Core.Resume(ctx) |
| 226 | must(t, err) |
| 227 | 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()) |
| 228 | must(t, x.Sync(ctx)) |
| 229 | var raw string |
| 230 | must(t, f.DB.Writer().QueryRow("SELECT selection FROM runner_assignments WHERE task_id=?", p.TaskID).Scan(&raw)) |
| 231 | var selected equipo.Selection |
| 232 | must(t, json.Unmarshal([]byte(raw), &selected)) |
| 233 | if selected.ConnectionID != "other-claude" { |
| 234 | t.Fatal("eligible preferred personal connection ignored", selected.ConnectionID) |
| 235 | } |
| 236 | } |
| 237 | |
| 238 | func TestPlanWorkflowRenderedSpec(t *testing.T) { |
| 239 | task := equipo.Task{ID: "task", TeamID: "team", Requester: owner.Address, ProjectID: 1, PlanRevision: 1, ReviewRef: "equipo/task", BaseCommit: strings.Repeat("a", 40), CheckDefinitionHash: strings.Repeat("b", 64), BaselineTestSetHash: strings.Repeat("c", 64)} |
| 240 | project := equipo.Project{ID: 1, Repository: "amadan.net/test/fixture", DefaultBranch: "main"} |
| 241 | p := taskplan.BugPlan(task.ID, 1) |
| 242 | p.Kind = taskplan.RenderedChange |
| 243 | p.Steps[1].Action = "copy" |
| 244 | pol, err := team.RunnerPolicy("subscription", team.Limits{Calls: 24, InputTokens: 200000, OutputTokens: 40000}, team.Limits{Calls: 1, InputTokens: 32000, OutputTokens: 4000}, team.Rates{}) |
| 245 | must(t, err) |
| 246 | spec, err := equipo.PlanJobSpec(task, project, p, pol) |
| 247 | must(t, err) |
| 248 | if !spec.Evidence.RequireBugFreeze { |
| 249 | t.Fatal("rendered reproduction cannot be frozen") |
| 250 | } |
| 251 | } |
| 252 | |
| 253 | func TestPlanWorkflowRenderedWait(t *testing.T) { |
| 254 | f := newFixture(t) |
| 255 | p := proposed(t, f) |
| 256 | f.planConnections(t, p.ProjectID) |
| 257 | p.Kind = taskplan.RenderedChange |
| 258 | p.Steps[1].Action = "copy" |
| 259 | var err error |
| 260 | p, err = f.Store.EditPlan(ctx, owner, p, equipo.Mutation{RequestID: "rendered", Revision: p.Revision}) |
| 261 | must(t, err) |
| 262 | var path string |
| 263 | must(t, f.DB.Writer().QueryRow("SELECT file FROM pragma_database_list WHERE name='main'").Scan(&path)) |
| 264 | x, err := f.Store.AttachExecution(ctx, path, team.Options{Clock: team.RealClock{}, Authority: equipo.NewAuthority(f.Store, nil)}) |
| 265 | must(t, err) |
| 266 | t.Cleanup(func() { must(t, x.Core.Close()) }) |
| 267 | _, err = x.Core.Resume(ctx) |
| 268 | must(t, err) |
| 269 | 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()) |
| 270 | must(t, x.Sync(ctx)) |
| 271 | principal := equipo.RunnerPrincipal{RunnerID: "fixture-runner", Person: owner.Address, CredentialID: "fixture-credential"} |
| 272 | var project equipo.Project |
| 273 | must(t, f.DB.G.First(&project, p.ProjectID).Error) |
| 274 | task, err := f.Store.Task(ctx, owner, p.TaskID) |
| 275 | must(t, err) |
| 276 | raw := []byte("fixture definition") |
| 277 | task, err = f.Store.PrepareBug(ctx, principal, p.TaskID, task.Revision, equipo.PreparedBug{Repository: project.Repository, DefaultBranch: project.DefaultBranch, BaseCommit: strings.Repeat("a", 40), CheckDefinition: raw, CheckDefinitionHash: team.ContentDigest(raw), BaselineTestSetHash: strings.Repeat("b", 64)}) |
| 278 | must(t, err) |
| 279 | task, err = f.Store.StartBug(ctx, principal, p.TaskID, task.Revision) |
| 280 | must(t, err) |
| 281 | // Only the publication-readiness gate is under test; no evidence or approval is fabricated. |
| 282 | f.exec(t, "UPDATE steps SET state='succeeded' WHERE job_id=? AND key<>'publish'", task.JobID) |
| 283 | f.exec(t, "UPDATE runner_assignments SET state='contained' WHERE task_id=?", task.ID) |
| 284 | must(t, x.Sync(ctx)) |
| 285 | task, err = f.Store.Task(ctx, owner, p.TaskID) |
| 286 | must(t, err) |
| 287 | if task.WaitCode != "evidence.awaiting_person" || f.count(t, "SELECT count(*) FROM runner_assignments WHERE task_id=? AND step_key='publish'", task.ID) != 0 { |
| 288 | t.Fatal("publication did not wait for evidence and rendered approval", task.WaitCode) |
| 289 | } |
| 290 | } |
| 291 | |