package plan3test import ( "amadan.net/oficina/equipo/internal/equipo" "amadan.net/oficina/equipo/internal/equipo/team" "amadan.net/oficina/equipo/internal/runnerproto" "amadan.net/oficina/equipo/internal/taskplan" "context" "database/sql" "encoding/json" "strings" "testing" "time" ) func TestPlanWorkflowRecommendation(t *testing.T) { task := equipo.Task{ID: "task", TeamID: "team", Requester: owner.Address, ProjectID: 1, PlanRevision: 1} project := equipo.Project{ID: 1, Repository: "amadan.net/test/fixture", DefaultBranch: "main"} 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"}}} pol, err := team.RunnerPolicy("subscription", team.Limits{Calls: 24, InputTokens: 200000, OutputTokens: 40000}, team.Limits{Calls: 1, InputTokens: 32000, OutputTokens: 4000}, team.Rates{}) must(t, err) spec, err := equipo.PlanJobSpec(task, project, p, pol) must(t, err) if spec.Target.Kind != team.TargetProjectRead || spec.Target.Ref != "" || spec.Evidence.Predicate != "" || len(spec.Steps) != 1 || spec.Steps[0].Capability != team.CapResearch { t.Fatalf("research gained write authority: %+v", spec) } } func TestPlanWorkflowFeature(t *testing.T) { 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)} project := equipo.Project{ID: 1, Repository: "amadan.net/test/fixture", DefaultBranch: "main"} p := taskplan.BugPlan(task.ID, 1) p.Kind = taskplan.Feature p.Steps[0] = taskplan.Step{Key: "scope", Specialist: "product", Action: "scope"} pol, err := team.RunnerPolicy("subscription", team.Limits{Calls: 24, InputTokens: 200000, OutputTokens: 40000}, team.Limits{Calls: 1, InputTokens: 32000, OutputTokens: 4000}, team.Rates{}) must(t, err) spec, err := equipo.PlanJobSpec(task, project, p, pol) must(t, err) if spec.Evidence.Predicate != team.PredicateSoftwareFeature || spec.Steps[0].Capability != team.CapScope { t.Fatalf("feature used bug plan: %+v", spec) } } func TestPlanWorkflowInvestigation(t *testing.T) { p := taskplan.Plan{ProjectID: 1, Revision: 1, Kind: taskplan.Investigation, Steps: []taskplan.Step{{Key: "research", Specialist: "product", Action: "investigate"}, {Key: "merge", Action: "person"}}} must(t, taskplan.Validate(p)) p.Steps = append(p.Steps[:1], taskplan.Step{Key: "build", Specialist: "engineering", Action: "implement"}, p.Steps[1]) if taskplan.Validate(p) == nil { t.Fatal("investigation built without a new publication plan") } } func TestPlanWorkflowRecommendationDelivery(t *testing.T) { planReadDelivery(t, false) } func TestPlanWorkflowInvestigationCheckpoint(t *testing.T) { planReadDelivery(t, true) } func planReadDelivery(t *testing.T, investigation bool) { f := newFixture(t) p := proposed(t, f) f.planConnections(t, p.ProjectID) p.Kind = taskplan.Recommendation if investigation { p.Kind = taskplan.Investigation } 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: "read-plan", Revision: p.Revision}) must(t, err) // One personal family can research; the other account is absent. if !investigation { f.exec(t, "DELETE FROM connections WHERE id='codex'") } 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), Provenance: func(context.Context, *sql.Tx, team.Scope, team.Handle) (team.Provenance, error) { return team.Provenance{Producer: "fixture", Provider: "claude", ModelFamily: "claude", Context: "session"}, nil }}) must(t, err) t.Cleanup(func() { must(t, x.Core.Close()) }) x.SetRunnerValidators(equipo.RunnerValidators{Artifact: func(context.Context, equipo.Assignment, equipo.RunnerRequest) error { return nil }}) _, 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()) must(t, x.Sync(ctx)) var id string var rev int64 must(t, f.DB.Writer().QueryRow("SELECT id,revision FROM runner_assignments WHERE task_id=? AND state='pending'", p.TaskID).Scan(&id, &rev)) principal := equipo.RunnerPrincipal{RunnerID: "fixture-runner", Person: owner.Address, CredentialID: "fixture-credential"} c, err := x.Claim(ctx, principal, equipo.ClaimRequest{Version: 2, AssignmentID: id, Revision: rev, RequestID: "claim"}) must(t, err) if c.Brief.Step.Action != "recommend" || c.Brief.Step.PlanRevision != p.Revision || len(c.Brief.Sources) != 1 || c.Brief.Target.Ref != "" { t.Fatalf("read brief: %+v", c.Brief) } answer := team.AnswerResult{Body: "An answer from verified project material", Sources: []team.SourceRef{c.Brief.Sources[0].Ref}} raw, _ := json.Marshal(answer) 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}} // A failed delivery must roll back artifact registration and step completion. f.exec(t, "CREATE TRIGGER answer_failure BEFORE INSERT ON conversation_messages BEGIN SELECT RAISE(ABORT,'fixture delivery failure'); END") if _, err = x.Mutate(ctx, principal, "artifacts", q); err == nil { t.Fatal("delivery failure ignored") } 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 { t.Fatal("answer partially committed") } f.exec(t, "DROP TRIGGER answer_failure") _, err = x.Mutate(ctx, principal, "artifacts", q) must(t, err) _, err = x.Mutate(ctx, principal, "artifacts", q) must(t, err) 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 { t.Fatal("answer was not delivered once with completion") } changed := q changedArtifact := *q.Artifact changedAnswer := answer changedAnswer.Body = "a different answer" changedArtifact.Payload, _ = json.Marshal(changedAnswer) changed.Artifact = &changedArtifact if _, err = x.Mutate(ctx, principal, "artifacts", changed); err == nil { t.Fatal("changed answer replay accepted") } if investigation { must(t, x.Core.ContainUntrusted(ctx, c.Scope, c.Handle)) f.exec(t, "UPDATE runner_assignments SET state='contained' WHERE id=?", id) conclude := q conclude.RequestID = "conclude" conclude.Artifact = nil _, err = x.Mutate(ctx, principal, "conclude", conclude) must(t, err) task, err := f.Store.Task(ctx, owner, p.TaskID) must(t, err) if task.State != "waiting_checkpoint" { t.Fatal("investigation skipped human checkpoint", task.State) } beforeJob := task.JobID next := taskplan.BugPlan(p.TaskID, p.ProjectID) next.Revision = p.Revision next.Kind = taskplan.Feature next.Steps[0] = taskplan.Step{Key: "research", Specialist: "product", Action: "scope"} next, err = f.Store.EditPlan(ctx, owner, next, equipo.Mutation{RequestID: "explicit-build-revision", Revision: p.Revision}) must(t, err) task, err = f.Store.Task(ctx, owner, p.TaskID) must(t, err) if next.Revision != p.Revision+1 || task.State != "proposed" || task.JobID != 0 { t.Fatal("checkpoint did not require fresh dispatch", task) } old, err := x.Core.GetJob(ctx, team.Scope{Account: team.AccountID(f.TeamID), Job: beforeJob}) must(t, err) if old.State != team.JobSucceeded { t.Fatal("historical research changed") } // A retained runner reconciliation record belongs to the old job too. f.exec(t, "UPDATE runner_assignments SET state='reconcile' WHERE id=?", id) // A completed investigation must not bind the replacement to its runner. f.exec(t, "INSERT INTO runners(id,person,instance_id,revision) VALUES('second-runner',?,?,1)", owner.Address, f.TeamID) f.exec(t, "UPDATE connections SET runner_id='second-runner',revision=revision+1") 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()) must(t, x.Sync(ctx)) task, err = f.Store.Task(ctx, owner, p.TaskID) must(t, err) if task.State != "preparing" { t.Fatal("replacement did not prepare on new runner", task.State, task.WaitCode) } var project equipo.Project must(t, f.DB.G.First(&project, p.ProjectID).Error) second := equipo.RunnerPrincipal{RunnerID: "second-runner", Person: owner.Address, CredentialID: "second-credential"} definition := []byte("checkpoint check") 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)}) must(t, err) task, err = f.Store.StartBug(ctx, second, p.TaskID, task.Revision) must(t, err) if task.JobID == beforeJob { t.Fatal("replacement reused historical job") } must(t, x.Sync(ctx)) var nextID string 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)) nextClaim, err := x.Claim(ctx, second, equipo.ClaimRequest{Version: 2, AssignmentID: nextID, Revision: rev, RequestID: "replacement-claim"}) must(t, err) if nextClaim.Brief.Step.PlanRevision != next.Revision || nextClaim.Brief.Selection.RunnerID != "second-runner" { t.Fatal("stale replacement dispatch", nextClaim.Brief.Step) } return } for _, column := range []string{"project", "budget", "plan", "choice"} { var undo string switch column { case "project": f.exec(t, "UPDATE projects SET revision=revision+1 WHERE id=?", p.ProjectID) undo = "UPDATE projects SET revision=revision-1" case "budget": f.exec(t, "UPDATE budget_records SET revision=revision+1") undo = "UPDATE budget_records SET revision=revision-1" case "plan": f.exec(t, "UPDATE tasks SET plan_revision=plan_revision+1 WHERE id=?", p.TaskID) undo = "UPDATE tasks SET plan_revision=plan_revision-1" case "choice": f.exec(t, "UPDATE connection_choices SET revision=revision+1") undo = "UPDATE connection_choices SET revision=revision-1" } if _, err = x.Mutate(ctx, principal, "artifacts", q); err == nil { t.Fatal("changed dispatch identity accepted", column) } f.exec(t, undo) } f.exec(t, "UPDATE connections SET revision=revision+1 WHERE id='claude'") if _, err = x.Mutate(ctx, principal, "artifacts", q); err == nil { t.Fatal("replay ignored revoked selection") } } func TestPlanWorkflowConnectionPreference(t *testing.T) { 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 'other-claude',runner_id,person,'other-local',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","other-claude","codex"]'`) p.Steps[0].ConnectionID = "other-claude" var err error p, err = f.Store.EditPlan(ctx, owner, p, equipo.Mutation{RequestID: "different-account", Revision: p.Revision}) must(t, err) must(t, f.Store.CheckPlanDispatch(ctx, owner, p.TaskID)) 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()) must(t, x.Sync(ctx)) var raw string must(t, f.DB.Writer().QueryRow("SELECT selection FROM runner_assignments WHERE task_id=?", p.TaskID).Scan(&raw)) var selected equipo.Selection must(t, json.Unmarshal([]byte(raw), &selected)) if selected.ConnectionID != "other-claude" { t.Fatal("eligible preferred personal connection ignored", selected.ConnectionID) } } func TestPlanWorkflowRenderedSpec(t *testing.T) { 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)} project := equipo.Project{ID: 1, Repository: "amadan.net/test/fixture", DefaultBranch: "main"} p := taskplan.BugPlan(task.ID, 1) p.Kind = taskplan.RenderedChange p.Steps[1].Action = "copy" pol, err := team.RunnerPolicy("subscription", team.Limits{Calls: 24, InputTokens: 200000, OutputTokens: 40000}, team.Limits{Calls: 1, InputTokens: 32000, OutputTokens: 4000}, team.Rates{}) must(t, err) spec, err := equipo.PlanJobSpec(task, project, p, pol) must(t, err) if !spec.Evidence.RequireBugFreeze { t.Fatal("rendered reproduction cannot be frozen") } } func TestPlanWorkflowRenderedWait(t *testing.T) { f := newFixture(t) p := proposed(t, f) f.planConnections(t, p.ProjectID) p.Kind = taskplan.RenderedChange p.Steps[1].Action = "copy" var err error p, err = f.Store.EditPlan(ctx, owner, p, equipo.Mutation{RequestID: "rendered", 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()) must(t, x.Sync(ctx)) principal := equipo.RunnerPrincipal{RunnerID: "fixture-runner", Person: owner.Address, CredentialID: "fixture-credential"} var project equipo.Project must(t, f.DB.G.First(&project, p.ProjectID).Error) task, err := f.Store.Task(ctx, owner, p.TaskID) must(t, err) raw := []byte("fixture definition") 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)}) must(t, err) task, err = f.Store.StartBug(ctx, principal, p.TaskID, task.Revision) must(t, err) // Only the publication-readiness gate is under test; no evidence or approval is fabricated. f.exec(t, "UPDATE steps SET state='succeeded' WHERE job_id=? AND key<>'publish'", task.JobID) f.exec(t, "UPDATE runner_assignments SET state='contained' WHERE task_id=?", task.ID) must(t, x.Sync(ctx)) task, err = f.Store.Task(ctx, owner, p.TaskID) must(t, err) if task.WaitCode != "evidence.awaiting_person" || f.count(t, "SELECT count(*) FROM runner_assignments WHERE task_id=? AND step_key='publish'", task.ID) != 0 { t.Fatal("publication did not wait for evidence and rendered approval", task.WaitCode) } }