oficina / equipo Public

feat: create idempotent bug tasks with a fixed review plan

codex agent, operated by paul@keymail.dev pushed by claude agent, operated by paul@keymail.dev 7a5ca9b69fda4c5dd8685c67724fbde8dfc6a2ed parent 2df9871
21 files changed, +1,623 −60
  • internal/equipo/app.go +1 −0
  • internal/equipo/connection_selection.go +8 −1
  • internal/equipo/execution_models.go +4 −2
  • internal/equipo/migrations/0012_tasks.sql +7 −0
  • internal/equipo/migrations/schema.sql +7 −0
  • internal/equipo/models.go +1 −1
  • internal/equipo/task_handlers.go +37 −0
  • internal/equipo/task_prepare.go +276 −0
  • internal/equipo/tasks.go +176 −0
  • internal/equipo/team/actions.go +3 −0
  • internal/equipo/team/bug_evidence.go +97 −0
  • internal/equipo/team/evidence.go +24 −0
  • internal/equipo/team/harness_test.go +4 −0
  • internal/equipo/team/job_retry_test.go +311 −0
  • internal/equipo/team/jobs.go +44 −12
  • internal/equipo/team/model.go +14 −10
  • internal/equipo/team/scheduler.go +9 −2
  • internal/equipo/team/shared.go +3 −2
  • internal/equipo/team/store.go +38 −23
  • internal/equipotest/execution_schema_test.go +48 −7
  • internal/equipotest/tasks_test.go +511 −0

CI failed — run details

diff --git a/internal/equipo/app.go b/internal/equipo/app.go
index ac2ff3f4..24a668e3 100644
--- a/internal/equipo/app.go
+++ b/internal/equipo/app.go
@@ -115,6 +115,7 @@ func Router(d *db.DB, cfg Config, mailer mail.Sender, logger *slog.Logger) (chi.
r.Get("/projects/{id}/edit", a.projectForm)
r.Get("/people", a.people)
r.Get("/runners/enrol", a.enrolmentPage)
+ r.Post("/tasks", a.createBug)
r.Post("/runners/enrol", a.approveEnrolment)
r.Post("/runners/{id}/revoke", a.revokeRunner)
r.Post("/projects/{id}/connections", a.saveConnectionChoice)
diff --git a/internal/equipo/connection_selection.go b/internal/equipo/connection_selection.go
index 39a57cd6..410673aa 100644
--- a/internal/equipo/connection_selection.go
+++ b/internal/equipo/connection_selection.go
@@ -85,6 +85,9 @@ func (s *Store) SelectConnection(ctx context.Context, person string, projectID i
// The assignment service can reuse this check in its admission transaction.
func (s *Store) selectConnectionAt(tx *gorm.DB, person string, projectID int64, specialist, excludedFamily string) (Selection, error) {
+ return s.selectConnectionOnRunnerAt(tx, person, projectID, specialist, excludedFamily, "")
+}
+func (s *Store) selectConnectionOnRunnerAt(tx *gorm.DB, person string, projectID int64, specialist, excludedFamily, runnerID string) (Selection, error) {
var result Selection
err := func() error {
m, err := currentRunnerMember(tx, person)
@@ -107,7 +110,11 @@ func (s *Store) selectConnectionAt(tx *gorm.DB, person string, projectID int64,
return ErrUnavailable
}
var rows []connectionRecord
- if err := tx.Where("person = ? AND id IN ?", m.Address, ids).Order("id").Find(&rows).Error; err != nil {
+ query := tx.Where("person = ? AND id IN ?", m.Address, ids)
+ if runnerID != "" {
+ query = query.Where("runner_id = ?", runnerID)
+ }
+ if err := query.Order("id").Find(&rows).Error; err != nil {
return storeError(err)
}
for i := range rows {
diff --git a/internal/equipo/execution_models.go b/internal/equipo/execution_models.go
index 99d06c9d..c7e05ed4 100644
--- a/internal/equipo/execution_models.go
+++ b/internal/equipo/execution_models.go
@@ -83,12 +83,14 @@ type executionEvents struct {
func (executionEvents) TableName() string { return "events" }
type executionJobs struct {
+ RequestKey string `gorm:"type:text;not null;default:'';uniqueIndex:jobs_request,priority:3,where:request_key <> ''"`
+ RequestHash string `gorm:"type:text;not null;default:''"`
GrantStale int64 `gorm:"type:integer;not null;default:0"`
ID int64 `gorm:"column:id;type:integer;primaryKey;autoIncrement:false"`
- Account string `gorm:"column:account;type:text;not null;index:jobs_account,priority:1"`
+ Account string `gorm:"column:account;type:text;not null;index:jobs_account,priority:1;uniqueIndex:jobs_request,priority:1,where:request_key <> ''"`
Parent int64 `gorm:"column:parent;type:integer;not null"`
Depth int64 `gorm:"column:depth;type:integer;not null"`
- Requester string `gorm:"column:requester;type:text;not null"`
+ Requester string `gorm:"column:requester;type:text;not null;uniqueIndex:jobs_request,priority:2,where:request_key <> ''"`
Target string `gorm:"column:target;type:text;not null"`
Evidence string `gorm:"column:evidence;type:text;not null"`
PolicyVersion int64 `gorm:"column:policy_version;type:integer;not null"`
diff --git a/internal/equipo/migrations/0012_tasks.sql b/internal/equipo/migrations/0012_tasks.sql
new file mode 100644
index 00000000..a2d21682
--- /dev/null
+++ b/internal/equipo/migrations/0012_tasks.sql
@@ -0,0 +1,7 @@
+CREATE TABLE tasks (id text, requester text, description text, request_id text, project_id integer, revision integer, job_id integer, state text, wait_code text, base_commit text, review_ref text, check_definition_hash text, team_id text, merge_owner text, baseline_test_set_hash text, PRIMARY KEY (id));
+CREATE UNIQUE INDEX task_request ON tasks(requester, request_id);
+CREATE TABLE task_outboxes (task_id text, state text, project_revision integer, budget_revision integer, engineering text, review text, prepared text, job_spec text, PRIMARY KEY (task_id));
+ALTER TABLE jobs ADD COLUMN request_key TEXT NOT NULL DEFAULT "";
+ALTER TABLE jobs ADD COLUMN request_hash TEXT NOT NULL DEFAULT "";
+CREATE UNIQUE INDEX jobs_request ON jobs(account, requester, request_key) WHERE request_key <> '';
+UPDATE service SET schema_version=6 WHERE id=1;
diff --git a/internal/equipo/migrations/schema.sql b/internal/equipo/migrations/schema.sql
index 3ee022bc..470c4afe 100644
--- a/internal/equipo/migrations/schema.sql
+++ b/internal/equipo/migrations/schema.sql
@@ -83,6 +83,8 @@ CREATE TABLE events (
);
CREATE TABLE jobs (
+ request_key TEXT NOT NULL DEFAULT "",
+ request_hash TEXT NOT NULL DEFAULT "",
grant_stale INTEGER NOT NULL DEFAULT 0,
id INTEGER PRIMARY KEY,
account TEXT NOT NULL,
@@ -301,3 +303,8 @@ CREATE TABLE connection_invalidations (
at datetime
);
CREATE INDEX connection_invalidation ON connection_invalidations(connection_id);
+
+CREATE TABLE tasks (id text, requester text, description text, request_id text, project_id integer, revision integer, job_id integer, state text, wait_code text, base_commit text, review_ref text, check_definition_hash text, team_id text, merge_owner text, baseline_test_set_hash text, PRIMARY KEY (id));
+CREATE UNIQUE INDEX task_request ON tasks(requester, request_id);
+CREATE TABLE task_outboxes (task_id text, state text, project_revision integer, budget_revision integer, engineering text, review text, prepared text, job_spec text, PRIMARY KEY (task_id));
+CREATE UNIQUE INDEX jobs_request ON jobs(account, requester, request_key) WHERE request_key <> '';
diff --git a/internal/equipo/models.go b/internal/equipo/models.go
index 8a480ca7..ded2f4b1 100644
--- a/internal/equipo/models.go
+++ b/internal/equipo/models.go
@@ -2,7 +2,7 @@ package equipo
import "time"
-var Models = append([]any{&Team{}, &Member{}, &AuditEvent{}, &Account{}, &Project{}, &DecisionOwner{}, &projectRequest{}, &budgetRecord{}, &Specialist{}, &runnerRecord{}, &runnerEnrolment{}, &runnerCredentialRecord{}, &runnerRate{}, &connectionRecord{}, &connectionChoiceRecord{}, &isolationAcknowledgementRecord{}, &ConnectionInvalidation{}}, executionModels...)
+var Models = append([]any{&Task{}, &taskOutbox{}, &Team{}, &Member{}, &AuditEvent{}, &Account{}, &Project{}, &DecisionOwner{}, &projectRequest{}, &budgetRecord{}, &Specialist{}, &runnerRecord{}, &runnerEnrolment{}, &runnerCredentialRecord{}, &runnerRate{}, &connectionRecord{}, &connectionChoiceRecord{}, &isolationAcknowledgementRecord{}, &ConnectionInvalidation{}}, executionModels...)
type Role string
diff --git a/internal/equipo/task_handlers.go b/internal/equipo/task_handlers.go
new file mode 100644
index 00000000..db6e8168
--- /dev/null
+++ b/internal/equipo/task_handlers.go
@@ -0,0 +1,37 @@
+package equipo
+
+import (
+ "amadan.net/rastrillo/rastrillo/auth"
+ "net/http"
+ "strconv"
+)
+
+func (a *application) createBug(w http.ResponseWriter, r *http.Request) {
+ r.Body = http.MaxBytesReader(w, r.Body, 64*1024)
+ if r.ParseForm() != nil || len(r.URL.Query()) != 0 {
+ a.failure(w, r, ErrInvalid)
+ return
+ }
+ for key, values := range r.PostForm {
+ if len(values) != 1 || key != "project_id" && key != "description" && key != "request_id" {
+ a.failure(w, r, ErrInvalid)
+ return
+ }
+ }
+ id, ok := auth.From(r)
+ if !ok {
+ a.failure(w, r, ErrForbidden)
+ return
+ }
+ projectID, err := strconv.ParseInt(r.PostForm.Get("project_id"), 10, 64)
+ if err != nil {
+ a.failure(w, r, ErrInvalid)
+ return
+ }
+ task, err := a.store.CreateBug(r.Context(), Actor{Address: id.Address}, projectID, r.PostForm.Get("description"), r.PostForm.Get("request_id"))
+ if err != nil {
+ a.failure(w, r, err)
+ return
+ }
+ http.Redirect(w, r, "/projects/"+strconv.FormatInt(task.ProjectID, 10), http.StatusSeeOther)
+}
diff --git a/internal/equipo/task_prepare.go b/internal/equipo/task_prepare.go
new file mode 100644
index 00000000..a8a53175
--- /dev/null
+++ b/internal/equipo/task_prepare.go
@@ -0,0 +1,276 @@
+package equipo
+
+import (
+ "context"
+ "crypto/sha256"
+ "encoding/hex"
+ "encoding/json"
+ "reflect"
+
+ "amadan.net/oficina/equipo/internal/equipo/team"
+ "gorm.io/gorm"
+)
+
+type PreparedBug struct {
+ Repository, DefaultBranch, BaseCommit string
+ CheckDefinition []byte
+ CheckDefinitionHash, BaselineTestSetHash string
+}
+type BugPreparer interface {
+ Prepare(context.Context, TargetBinding) (PreparedBug, error)
+}
+
+func hexDigest(s string, n int) bool {
+ b, err := hex.DecodeString(s)
+ return err == nil && len(b) == n/2 && hex.EncodeToString(b) == s
+}
+func (p PreparedBug) valid(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
+ return reflect.DeepEqual(a, b)
+}
+func (s *Store) bugPreparationAt(tx *gorm.DB, principal RunnerPrincipal, id string) (Task, taskOutbox, Project, error) {
+ var task Task
+ var outbox taskOutbox
+ runner, err := runnerPrincipalAt(tx, principal, s.runnerClock.Now().UTC())
+ if err != nil {
+ return task, outbox, Project{}, err
+ }
+ if err := tx.First(&task, "id=?", id).Error; err != nil {
+ return task, outbox, Project{}, storeError(err)
+ }
+ if runner.Person != task.Requester {
+ return task, outbox, Project{}, ErrForbidden
+ }
+ project, err := bugAuthority(tx, Actor{Address: task.Requester}, task.ProjectID)
+ if err != nil {
+ return task, outbox, project, err
+ }
+ if err := tx.First(&outbox, "task_id=?", id).Error; err != nil {
+ return task, outbox, project, storeError(err)
+ }
+ if project.Revision != outbox.ProjectRevision {
+ return task, outbox, project, ErrConflict
+ }
+ config, err := bugBudget(tx, task.TeamID, task.ProjectID)
+ if err != nil {
+ return task, outbox, project, err
+ }
+ if config.Revision != outbox.BudgetRevision {
+ return task, outbox, project, ErrConflict
+ }
+ var eng, rev Selection
+ if json.Unmarshal([]byte(outbox.Engineering), &eng) != nil || json.Unmarshal([]byte(outbox.Review), &rev) != nil {
+ return task, outbox, project, ErrUnavailable
+ }
+ if eng.RunnerID != runner.ID || rev.RunnerID != runner.ID {
+ return task, outbox, project, ErrForbidden
+ }
+ currentEng, err := s.selectConnectionAt(tx, task.Requester, task.ProjectID, "engineering", "")
+ if err != nil {
+ return task, outbox, project, err
+ }
+ currentRev, err := s.selectConnectionOnRunnerAt(tx, task.Requester, task.ProjectID, "review", eng.Family, eng.RunnerID)
+ if err != nil {
+ return task, outbox, project, err
+ }
+ if !samePreparationSelection(eng, currentEng) || !samePreparationSelection(rev, currentRev) {
+ return task, outbox, project, ErrConflict
+ }
+ if err := subscriptionSelection(tx, currentEng); err != nil {
+ return task, outbox, project, err
+ }
+ if err := subscriptionSelection(tx, currentRev); err != nil {
+ return task, outbox, project, err
+ }
+ return task, outbox, project, nil
+}
+func bugPolicy(tx *gorm.DB, task Task) (team.Policy, error) {
+ b, err := bugBudget(tx, task.TeamID, task.ProjectID)
+ if err != nil {
+ return team.Policy{}, err
+ }
+ p := b.Projects[team.ProjectID(task.ProjectID)]
+ limits := team.Limits{Calls: min(24, b.Team.Calls, p.Calls), InputTokens: min(200000, b.Team.InputTokens, p.InputTokens), OutputTokens: min(40000, b.Team.OutputTokens, p.OutputTokens)}
+ return team.RunnerPolicy("subscription", limits, team.Limits{Calls: 1, InputTokens: min(32000, limits.InputTokens), OutputTokens: min(4000, limits.OutputTokens)}, team.Rates{})
+}
+func (s *Store) PrepareBug(ctx context.Context, principal RunnerPrincipal, taskID string, expectedRevision int64, prepared PreparedBug) (Task, error) {
+ var result Task
+ err := s.write(ctx, func(tx *gorm.DB) error {
+ task, outbox, project, err := s.bugPreparationAt(tx, principal, taskID)
+ if err != nil {
+ return err
+ }
+ if !prepared.valid(project) {
+ return ErrInvalid
+ }
+ raw, _ := json.Marshal(prepared)
+ if outbox.State != "prepare" {
+ if outbox.Prepared != string(raw) {
+ return ErrConflict
+ }
+ if expectedRevision != task.Revision && expectedRevision != 1 {
+ return ErrConflict
+ }
+ result = task
+ return nil
+ }
+ if task.Revision != expectedRevision {
+ return ErrConflict
+ }
+ task.BaseCommit = prepared.BaseCommit
+ task.CheckDefinitionHash = prepared.CheckDefinitionHash
+ task.BaselineTestSetHash = prepared.BaselineTestSetHash
+ task.Revision++
+ task.State = "prepared"
+ policy, err := bugPolicy(tx, task)
+ if err != nil {
+ return err
+ }
+ spec, err := BugJobSpec(task, project, policy, task.Description)
+ if err != nil {
+ return err
+ }
+ specRaw, _ := json.Marshal(spec)
+ outbox.State = "job"
+ outbox.Prepared = string(raw)
+ outbox.JobSpec = string(specRaw)
+ update := tx.Model(&Task{}).Where("id=? AND revision=?", task.ID, expectedRevision).Select("BaseCommit", "CheckDefinitionHash", "BaselineTestSetHash", "Revision", "State").Updates(&task)
+ if update.Error != nil {
+ return storeError(update.Error)
+ }
+ if update.RowsAffected != 1 {
+ return ErrConflict
+ }
+ if err := tx.Model(&taskOutbox{}).Where("task_id=? AND state=?", task.ID, "prepare").Select("State", "Prepared", "JobSpec").Updates(&outbox).Error; err != nil {
+ return storeError(err)
+ }
+ if err := appendAudit(tx, Actor{Address: principal.Person}, "task.prepare", task.ID); err != nil {
+ return err
+ }
+ result = task
+ return nil
+ })
+ if err != nil {
+ return Task{}, err
+ }
+ return result, nil
+}
+
+// StartBug retries the durable job request, then acknowledges the app link.
+// Production boot never attaches execution until the runner supervisor exists.
+func (s *Store) StartBug(ctx context.Context, principal RunnerPrincipal, taskID string, expectedRevision int64) (Task, error) {
+ if s.execution == nil {
+ return Task{}, ErrUnavailable
+ }
+ var task Task
+ var spec team.JobSpec
+ err := s.write(ctx, func(tx *gorm.DB) error {
+ var outbox taskOutbox
+ var err error
+ task, outbox, _, err = s.bugPreparationAt(tx, principal, taskID)
+ if err != nil {
+ return err
+ }
+ if outbox.State == "done" {
+ if expectedRevision != task.Revision && expectedRevision != task.Revision-1 {
+ return ErrConflict
+ }
+ return nil
+ }
+ if outbox.State != "job" || task.Revision != expectedRevision {
+ return ErrConflict
+ }
+ return storeError(json.Unmarshal([]byte(outbox.JobSpec), &spec))
+ })
+ if err != nil {
+ return Task{}, err
+ }
+ if task.JobID != 0 {
+ return task, nil
+ }
+ job, err := s.execution.Core.CreateJob(ctx, spec)
+ if err != nil {
+ return Task{}, err
+ }
+ err = s.write(ctx, func(tx *gorm.DB) error {
+ current, outbox, _, err := s.bugPreparationAt(tx, principal, taskID)
+ if err != nil {
+ return err
+ }
+ if outbox.State == "done" {
+ if current.JobID != job.ID {
+ return ErrConflict
+ }
+ task = current
+ return nil
+ }
+ if current.Revision != expectedRevision || outbox.State != "job" {
+ return ErrConflict
+ }
+ current.JobID = job.ID
+ current.Revision++
+ current.State = "queued"
+ update := tx.Model(&Task{}).Where("id=? AND revision=?", taskID, expectedRevision).Select("JobID", "Revision", "State").Updates(&current)
+ if update.Error != nil {
+ return storeError(update.Error)
+ }
+ if update.RowsAffected != 1 {
+ return ErrConflict
+ }
+ if err := tx.Model(&taskOutbox{}).Where("task_id=?", taskID).Select("State").Updates(&taskOutbox{State: "done"}).Error; err != nil {
+ return storeError(err)
+ }
+ if err := appendAudit(tx, Actor{Address: principal.Person}, "task.link", taskID); err != nil {
+ return err
+ }
+ task = current
+ return nil
+ })
+ if err != nil {
+ return Task{}, err
+ }
+ return task, nil
+}
+func BugJobSpec(task Task, project Project, policy team.Policy, expectedSymptom string) (team.JobSpec, error) {
+ if task.ID == "" || task.TeamID == "" || task.ProjectID <= 0 || task.ProjectID != project.ID || task.ReviewRef != "equipo/"+task.ID || task.ReviewRef == project.DefaultBranch || !validBugDescription(expectedSymptom) || !validAddress(task.Requester) || !(hexDigest(task.BaseCommit, 40) || hexDigest(task.BaseCommit, 64)) || !hexDigest(task.CheckDefinitionHash, 64) || !hexDigest(task.BaselineTestSetHash, 64) {
+ return team.JobSpec{}, ErrInvalid
+ }
+ repository, err := canonicalRepository(project.Repository)
+ if err != nil || repository != project.Repository {
+ return team.JobSpec{}, ErrInvalid
+ }
+ if _, err := CanonicalBranch(project.DefaultBranch); err != nil {
+ return team.JobSpec{}, err
+ }
+ if _, err := CanonicalBranch(task.ReviewRef); err != nil {
+ return team.JobSpec{}, err
+ }
+ if policy.Version != team.PolicyVersion || policy.MaxDepth != 0 || !policy.RequireDistinctReviewFamily || policy.Validate() != nil {
+ return team.JobSpec{}, ErrInvalid
+ }
+ caps := []team.Capability{team.CapReproduce, team.CapImplement, team.CapReview, team.CapVerify, team.CapPublish}
+ steps := make([]team.StepSpec, len(caps))
+ for i, cap := range caps {
+ steps[i] = team.StepSpec{Key: string(cap), Capability: cap, Version: 1}
+ if i > 0 {
+ steps[i].DependsOn = []string{steps[i-1].Key}
+ }
+ }
+ return team.JobSpec{Account: team.AccountID(task.TeamID), Project: team.ProjectID(project.ID), Requester: task.Requester, RequestKey: task.ID, GrantRef: GrantRef(project.ID, task.Requester), Target: team.TargetBinding{Kind: team.TargetRepository, Repository: project.Repository, App: project.AppName, DefaultRef: project.DefaultBranch, Ref: task.ReviewRef, BaseRevision: task.BaseCommit}, Evidence: team.EvidenceRequirement{Predicate: team.PredicateSoftwareFix, ExpectedSymptom: expectedSymptom, CheckDefinitionHash: task.CheckDefinitionHash, BaselineTestSetHash: task.BaselineTestSetHash, RequireBugFreeze: true}, Policy: policy, Steps: steps}, nil
+}
+
+type BugPlanStep struct {
+ Key, Specialist, Person string
+ RunnerOnly bool
+}
+
+func BugPlan(task Task) []BugPlanStep {
+ return []BugPlanStep{{Key: "reproduce", Specialist: "engineering"}, {Key: "implement", Specialist: "engineering"}, {Key: "review", Specialist: "review"}, {Key: "verify", Specialist: "review"}, {Key: "publish", RunnerOnly: true}, {Key: "merge", Person: task.MergeOwner}}
+}
diff --git a/internal/equipo/tasks.go b/internal/equipo/tasks.go
new file mode 100644
index 00000000..5ca31d29
--- /dev/null
+++ b/internal/equipo/tasks.go
@@ -0,0 +1,176 @@
+package equipo
+
+import (
+ "context"
+ "crypto/rand"
+ "encoding/json"
+ "errors"
+ "strings"
+ "unicode/utf8"
+
+ "amadan.net/oficina/equipo/internal/equipo/team"
+ "gorm.io/gorm"
+)
+
+type JobID = team.JobID
+type TargetBinding = team.TargetBinding
+
+type Task struct {
+ ID string `gorm:"primaryKey"`
+ Requester string `gorm:"uniqueIndex:task_request,priority:1"`
+ Description string
+ RequestID string `gorm:"uniqueIndex:task_request,priority:2"`
+ ProjectID, Revision int64
+ JobID JobID
+ State, WaitCode, BaseCommit, ReviewRef, CheckDefinitionHash string
+ TeamID, MergeOwner, BaselineTestSetHash string
+}
+type taskOutbox struct {
+ TaskID string `gorm:"primaryKey"`
+ State string
+ ProjectRevision, BudgetRevision int64
+ Engineering, Review, Prepared, JobSpec string
+}
+
+func (taskOutbox) TableName() string { return "task_outboxes" }
+
+func validBugDescription(s string) bool { return utf8.ValidString(s) && len(s) >= 1 && len(s) <= 16384 }
+func bugAuthority(tx *gorm.DB, actor Actor, projectID int64) (Project, error) {
+ member, err := currentRunnerMember(tx, actor.Address)
+ if err != nil {
+ return Project{}, err
+ }
+ var p Project
+ if err := tx.First(&p, projectID).Error; err != nil {
+ return p, storeError(err)
+ }
+ if member.Role != RoleOwner {
+ var owner DecisionOwner
+ if err := tx.Where("project_id=? AND decision=?", projectID, "work").First(&owner).Error; err != nil {
+ return p, storeError(err)
+ }
+ if owner.Address != member.Address {
+ return p, ErrForbidden
+ }
+ }
+ return p, nil
+}
+func bugBudget(tx *gorm.DB, teamID string, projectID int64) (BudgetConfig, error) {
+ var row budgetRecord
+ if err := tx.Where("team_id=?", teamID).First(&row).Error; err != nil {
+ return BudgetConfig{}, storeError(err)
+ }
+ var config BudgetConfig
+ if json.Unmarshal([]byte(row.Config), &config) != nil || config.Revision != row.Revision || config.Revision <= 0 {
+ return config, ErrUnavailable
+ }
+ if (team.BudgetSet{Revision: config.Revision, Team: config.Team, Projects: config.Projects}).Validate() != nil {
+ return config, ErrUnavailable
+ }
+ if _, ok := config.Projects[team.ProjectID(projectID)]; !ok {
+ return config, ErrUnavailable
+ }
+ return config, nil
+}
+func (s *Store) CreateBug(ctx context.Context, actor Actor, projectID int64, description, requestID string) (Task, error) {
+ if projectID <= 0 || !validBugDescription(description) || strings.TrimSpace(requestID) == "" || len(requestID) > 256 || !utf8.ValidString(requestID) {
+ return Task{}, ErrInvalid
+ }
+ var task Task
+ err := s.write(ctx, func(tx *gorm.DB) error {
+ project, err := bugAuthority(tx, actor, projectID)
+ if err != nil {
+ return err
+ }
+ requester := normalizeAddress(actor.Address)
+ err = tx.Where("requester=? AND request_id=?", requester, requestID).First(&task).Error
+ if err == nil {
+ if task.ProjectID != projectID || task.Description != description {
+ return ErrConflict
+ }
+ return nil
+ }
+ if !errors.Is(err, gorm.ErrRecordNotFound) {
+ return storeError(err)
+ }
+ var instance Team
+ if err := tx.First(&instance).Error; err != nil {
+ return storeError(err)
+ }
+ budget, err := bugBudget(tx, instance.ID, projectID)
+ if err != nil {
+ return err
+ }
+ engineering, err := s.selectConnectionAt(tx, requester, projectID, "engineering", "")
+ if err != nil {
+ return err
+ }
+ review, err := s.selectConnectionOnRunnerAt(tx, requester, projectID, "review", engineering.Family, engineering.RunnerID)
+ if err != nil {
+ return err
+ }
+ if engineering.RunnerID != review.RunnerID {
+ return ErrUnavailable
+ }
+ if err := subscriptionSelection(tx, engineering); err != nil {
+ return err
+ }
+ if err := subscriptionSelection(tx, review); err != nil {
+ return err
+ }
+ var merge DecisionOwner
+ if err := tx.Where("project_id=? AND decision=?", projectID, "merge").First(&merge).Error; err != nil {
+ return storeError(err)
+ }
+ if _, err := currentRunnerMember(tx, merge.Address); err != nil {
+ return err
+ }
+ task = Task{ID: rand.Text(), Requester: requester, Description: description, RequestID: requestID, ProjectID: projectID, Revision: 1, State: "preparing", TeamID: instance.ID, MergeOwner: merge.Address}
+ task.ReviewRef = "equipo/" + task.ID
+ eng, _ := json.Marshal(engineering)
+ rev, _ := json.Marshal(review)
+ outbox := taskOutbox{TaskID: task.ID, State: "prepare", ProjectRevision: project.Revision, BudgetRevision: budget.Revision, Engineering: string(eng), Review: string(rev)}
+ if err := tx.Create(&task).Error; err != nil {
+ return storeError(err)
+ }
+ if err := tx.Create(&outbox).Error; err != nil {
+ return storeError(err)
+ }
+ return appendAudit(tx, actor, "task.create", task.ID)
+ })
+ if err != nil {
+ return Task{}, err
+ }
+ return task, nil
+}
+func (s *Store) Task(ctx context.Context, actor Actor, id string) (Task, error) {
+ var task Task
+ err := s.write(ctx, func(tx *gorm.DB) error {
+ if _, err := currentRunnerMember(tx, actor.Address); err != nil {
+ return err
+ }
+ return storeError(tx.First(&task, "id=?", id).Error)
+ })
+ if err != nil {
+ return Task{}, err
+ }
+ return task, nil
+}
+
+// The app has no saved API price schedule yet. Do not account an API turn as
+// subscription usage; the pure plan builder still accepts a priced v2 policy.
+func subscriptionSelection(tx *gorm.DB, selected Selection) error {
+ var c connectionRecord
+ if err := tx.First(&c, "id=?", selected.ConnectionID).Error; err != nil {
+ return storeError(err)
+ }
+ if err := decodeConnection(&c); err != nil {
+ return err
+ }
+ for _, r := range c.Reports {
+ if r.Provider == selected.Provider && r.Model == selected.Model && r.Kind == "subscription" {
+ return nil
+ }
+ }
+ return ErrUnavailable
+}
diff --git a/internal/equipo/team/actions.go b/internal/equipo/team/actions.go
index c6102425..fb2a014d 100644
--- a/internal/equipo/team/actions.go
+++ b/internal/equipo/team/actions.go
@@ -167,6 +167,9 @@ func (s *Store) Intend(ctx context.Context, scope Scope, h Handle, in IntentSpec
if err != nil {
return err
}
+ if hd.job.Evidence.RequireBugFreeze && hd.step.Capability == CapPublish && in.Operation == OpProviderCall {
+ return fail(CodeScope, "bug_publish_is_runner_only")
+ }
if !operationAllowed(hd.step.Capability, in.Operation) {
return fail(CodeScope, "capability %s cannot perform %s", hd.step.Capability, in.Operation)
}
diff --git a/internal/equipo/team/bug_evidence.go b/internal/equipo/team/bug_evidence.go
new file mode 100644
index 00000000..fefb492e
--- /dev/null
+++ b/internal/equipo/team/bug_evidence.go
@@ -0,0 +1,97 @@
+package team
+
+import (
+ "context"
+ "database/sql"
+ "encoding/json"
+ "strings"
+ "unicode/utf8"
+)
+
+// ExecutorEvidenceValidator verifies a trusted executor attestation, using the
+// enclosing transaction. A missing validator refuses bug check results.
+type ExecutorEvidenceValidator func(context.Context, *sql.Tx, Scope, Handle, ArtifactSpec) (Provenance, error)
+
+func (s *Store) FreezeBugEvidence(ctx context.Context, scope Scope, h Handle, expectedSymptom, definitionHash, reproductionHash string) error {
+ if !utf8.ValidString(expectedSymptom) || len(expectedSymptom) < 1 || len(expectedSymptom) > 16384 {
+ return fail(CodeInvalid, "invalid_bug_symptom")
+ }
+ return s.tx(ctx, func(tx *sql.Tx) error {
+ if err := admissionOpen(ctx, tx); err != nil {
+ return err
+ }
+ hd, err := current(ctx, tx, scope, h, s.clock.Now())
+ if err != nil {
+ return err
+ }
+ if hd.job.Revision != h.Revision {
+ return fail(CodeRevision, "bug_revision_changed")
+ }
+ if hd.step.Capability != CapReproduce || !hd.job.Evidence.RequireBugFreeze {
+ return fail(CodeScope, "bug_reproduce_required")
+ }
+ if definitionHash != hd.job.Evidence.CheckDefinitionHash {
+ return fail(CodeEvidence, "check_definition_changed")
+ }
+ cand, err := latestAny(ctx, tx, scope.Job, RoleCandidate)
+ if err != nil {
+ return err
+ }
+ if cand != nil {
+ return fail(CodeState, "candidate_exists")
+ }
+ repro, err := latestAny(ctx, tx, scope.Job, RoleReproduction)
+ if err != nil {
+ return err
+ }
+ if repro == nil || repro.Hash != reproductionHash || repro.Attempt != h.Attempt || repro.Fence != h.Fence {
+ return fail(CodeEvidence, "attempt_reproduction_required")
+ }
+ evidence := hd.job.Evidence
+ if evidence.FrozenReproductionHash != "" {
+ if evidence.FrozenReproductionHash != reproductionHash || evidence.ExpectedSymptom != expectedSymptom {
+ return fail(CodeConflict, "bug_evidence_already_frozen")
+ }
+ return nil
+ }
+ evidence.ExpectedSymptom = expectedSymptom
+ evidence.FrozenReproductionHash = reproductionHash
+ raw, err := json.Marshal(evidence)
+ if err != nil {
+ return err
+ }
+ result, err := tx.ExecContext(ctx, `UPDATE jobs SET evidence=?, revision=revision+1, updated_at=? WHERE id=? AND revision=?`, string(raw), ts(s.clock.Now()), scope.Job, h.Revision)
+ if err != nil {
+ return err
+ }
+ if n, _ := result.RowsAffected(); n != 1 {
+ return fail(CodeRevision, "bug_revision_changed")
+ }
+ return appendEvent(ctx, tx, scope, "bug.evidence_frozen", h.Runner, map[string]string{"reproduction": reproductionHash, "definition": definitionHash}, s.clock.Now())
+ })
+}
+func completedBugReproduction(ctx context.Context, tx *sql.Tx, hd holder) error {
+ e := hd.job.Evidence
+ if e.FrozenReproductionHash == "" {
+ return fail(CodeEvidence, "bug_evidence_not_frozen")
+ }
+ repro, err := latestAny(ctx, tx, hd.job.ID, RoleReproduction)
+ if err != nil {
+ return err
+ }
+ if repro == nil || repro.Hash != e.FrozenReproductionHash || repro.Attempt != hd.attempt.ID {
+ return fail(CodeEvidence, "attempt_reproduction_required")
+ }
+ base, err := latestAny(ctx, tx, hd.job.ID, RoleBaseResult)
+ if err != nil {
+ return err
+ }
+ if base == nil || base.Attempt != hd.attempt.ID {
+ return fail(CodeEvidence, "attempt_base_failure_required")
+ }
+ var result CheckResult
+ if strictJSON(base.Payload, &result) != nil || result.ReproductionHash != e.FrozenReproductionHash || result.CheckDefinitionHash != e.CheckDefinitionHash || result.SubjectHash != hd.job.Target.BaseRevision || result.Outcome != CheckFail || result.TestsRun <= 0 || result.TestsFailed <= 0 || result.TestsFailed > result.TestsRun || !strings.Contains(result.FailureMessage, e.ExpectedSymptom) {
+ return fail(CodeEvidence, "frozen_base_failure_required")
+ }
+ return nil
+}
diff --git a/internal/equipo/team/evidence.go b/internal/equipo/team/evidence.go
index 3e09e3a3..19d2df1c 100644
--- a/internal/equipo/team/evidence.go
+++ b/internal/equipo/team/evidence.go
@@ -103,6 +103,21 @@ func (s *Store) Register(ctx context.Context, scope Scope, h Handle, spec Artifa
} else if err := spec.Provenance.validate(); err != nil {
return err
}
+ if hd.job.Evidence.RequireBugFreeze && (spec.Role == RoleBaseResult || spec.Role == RoleCandidateResult || spec.Role == RoleRepositoryChecks) {
+ if s.executorEvidence == nil {
+ return fail(CodeEvidence, "executor_attestation_missing")
+ }
+ executor, err := s.executorEvidence(ctx, tx, scope, h, spec)
+ if err != nil {
+ return err
+ }
+ if err := executor.validate(); err != nil {
+ return err
+ }
+ // Exposure comes from the instance observation, even for executor evidence.
+ executor.Isolation = spec.Provenance.Isolation
+ spec.Provenance = executor
+ }
if err := validateArtifact(ctx, tx, hd.job, spec, hash); err != nil {
return err
}
@@ -123,6 +138,9 @@ func (s *Store) Register(ctx context.Context, scope Scope, h Handle, spec Artifa
func validateArtifact(ctx context.Context, tx *sql.Tx, j jobRow, spec ArtifactSpec, hash string) error {
switch spec.Role {
case RoleReproduction:
+ if j.Evidence.FrozenReproductionHash != "" && hash != j.Evidence.FrozenReproductionHash {
+ return fail(CodeEvidence, "frozen_reproduction_changed")
+ }
cand, err := latestAny(ctx, tx, j.ID, RoleCandidate)
if err != nil {
return err
@@ -200,6 +218,9 @@ func validateArtifact(ctx context.Context, tx *sql.Tx, j jobRow, spec ArtifactSp
}
return validateRepositoryChecks(spec.Payload, cand, j)
case RoleCandidate:
+ if j.Evidence.RequireBugFreeze && j.Evidence.FrozenReproductionHash == "" {
+ return fail(CodeEvidence, "bug_evidence_not_frozen")
+ }
if j.Policy.Version == 2 {
_, err := gitCandidate(&Artifact{MediaType: spec.MediaType, Payload: spec.Payload, Hash: hash}, j)
return err
@@ -341,6 +362,9 @@ func evaluateSoftwareFix(ctx context.Context, tx *sql.Tx, j jobRow, ready bool)
if repro == nil {
return miss("no frozen reproduction from a completed attempt")
}
+ if j.Evidence.RequireBugFreeze && repro.Hash != j.Evidence.FrozenReproductionHash {
+ return miss("frozen_reproduction_mismatch")
+ }
rep.Reproduction = repro.Hash
base, err := latestArtifact(ctx, tx, j.ID, RoleBaseResult)
if err != nil {
diff --git a/internal/equipo/team/harness_test.go b/internal/equipo/team/harness_test.go
index 1aa359b1..bf5208a4 100644
--- a/internal/equipo/team/harness_test.go
+++ b/internal/equipo/team/harness_test.go
@@ -175,6 +175,10 @@ func dropRecoverySchema(t *testing.T, db *sql.DB) {
func dropRunnerPolicySchema(t *testing.T, db *sql.DB) {
t.Helper()
+ for _, q := range []string{"DROP INDEX jobs_request", "ALTER TABLE jobs DROP COLUMN request_key", "ALTER TABLE jobs DROP COLUMN request_hash"} {
+ _, err := db.Exec(q)
+ must(t, err)
+ }
for _, q := range []string{"DROP INDEX reservations_period_account", "DROP INDEX reservations_period_project", "DROP INDEX time_period_account", "DROP INDEX time_period_project", "DROP INDEX recovery_charges_scope", "ALTER TABLE reservations DROP COLUMN project_id", "ALTER TABLE reservations DROP COLUMN period", "ALTER TABLE reservations DROP COLUMN cost_unavailable", "ALTER TABLE reservations DROP COLUMN s_cached", "ALTER TABLE period_budgets DROP COLUMN content_hash"} {
_, err := db.Exec(q)
must(t, err)
diff --git a/internal/equipo/team/job_retry_test.go b/internal/equipo/team/job_retry_test.go
new file mode 100644
index 00000000..098635c3
--- /dev/null
+++ b/internal/equipo/team/job_retry_test.go
@@ -0,0 +1,311 @@
+package team
+
+import (
+ "context"
+ "database/sql"
+ "encoding/json"
+ "testing"
+)
+
+func TestJobRequestKey(t *testing.T) {
+ e := newEnv(t)
+ spec := softwareSpec(SoftwareSteps(false))
+ spec.RequestKey = "request-1"
+ first, scope := e.createJob(spec)
+ again, _ := e.createJob(spec)
+ if first.ID != again.ID {
+ t.Fatal("retry duplicated job")
+ }
+ spec.Target.Ref = "other"
+ _, err := e.store.CreateJob(e.ctx, spec)
+ wantCode(t, err, CodeConflict)
+ spec.Target.Ref = first.Target.Ref
+ spec.Requester = "other"
+ other, _ := e.createJob(spec)
+ if other.ID == first.ID {
+ t.Fatal("key crossed requester")
+ }
+ spec.Requester = first.Requester
+ spec.Steps[0].DependsOn = []string{}
+ again, _ = e.createJob(spec)
+ if again.ID != first.ID {
+ t.Fatal("nil/empty dependencies not canonical")
+ }
+ events, err := e.store.Events(e.ctx, scope, 0)
+ must(t, err)
+ if len(events) != 1 {
+ t.Fatal("retry appended events")
+ }
+ must(t, e.store.Close())
+ e.open()
+ again, _ = e.createJob(spec)
+ if again.ID != first.ID {
+ t.Fatal("reopen lost request key")
+ }
+}
+func TestBugFreezeEvidence(t *testing.T) {
+ e := newEnv(t)
+ spec := softwareSpec(SoftwareSteps(false))
+ spec.Evidence.RequireBugFreeze = true
+ _, scope := e.createJob(spec)
+ h := e.claim(scope, "reproduce", "runner", "fresh")
+ if err := e.store.Complete(e.ctx, scope, h, AttemptResult{Outcome: OutcomeSuccess}); err == nil {
+ t.Fatal("reproduce completed without frozen base failure")
+ }
+ if err := e.store.FreezeBugEvidence(e.ctx, scope, h, FixtureSymptom, CheckDefinitionHash, "missing"); err == nil {
+ t.Fatal("unregistered reproduction frozen")
+ }
+ repro, err := e.store.Register(e.ctx, scope, h, reproSpec(h))
+ must(t, err)
+ stale := h
+ stale.Revision--
+ if err := e.store.FreezeBugEvidence(e.ctx, scope, stale, FixtureSymptom, CheckDefinitionHash, repro.Hash); err == nil {
+ t.Fatal("stale revision frozen")
+ }
+ must(t, e.store.FreezeBugEvidence(e.ctx, scope, h, FixtureSymptom, CheckDefinitionHash, repro.Hash))
+ changed := reproSpec(h)
+ changed.Payload = []byte("different")
+ if _, err := e.store.Register(e.ctx, scope, h, changed); err == nil {
+ t.Fatal("frozen reproduction changed")
+ }
+ base := CheckResult{SubjectHash: spec.Target.BaseRevision, ReproductionHash: repro.Hash, CheckDefinitionHash: CheckDefinitionHash, Outcome: CheckFail, TestsRun: 1, TestsFailed: 1, FailureMessage: FixtureSymptom}
+ raw, _ := json.Marshal(base)
+ a := ArtifactSpec{Role: RoleBaseResult, MediaType: "application/json", Payload: raw, Provenance: Provenance{Producer: "executor", Provider: "local", Context: "check"}}
+ if _, err := e.store.Register(e.ctx, scope, h, a); err == nil {
+ t.Fatal("unattested base accepted")
+ }
+ e.store.executorEvidence = fakeBugExecutor
+ _, err = e.store.Register(e.ctx, scope, h, a)
+ must(t, err)
+ must(t, e.store.Complete(e.ctx, scope, h, AttemptResult{Outcome: OutcomeSuccess}))
+ must(t, e.store.Contain(e.ctx, scope, h.Attempt, "supervisor"))
+ h = e.claim(scope, "implement", "runner", "fresh-implement")
+ if err := e.store.FreezeBugEvidence(e.ctx, scope, h, "changed", CheckDefinitionHash, repro.Hash); err == nil {
+ t.Fatal("implement froze evidence")
+ }
+}
+
+func TestBugFreezeGuards(t *testing.T) {
+ for _, guard := range []string{"revision", "capability", "definition", "attempt", "fence", "candidate", "symptom", "frozen_symptom", "frozen_hash", "base_hash", "base_subject", "base_symptom", "base_outcome", "base_counts", "executor"} {
+ t.Run(guard, func(t *testing.T) {
+ e := newEnv(t)
+ spec := softwareSpec(SoftwareSteps(false))
+ spec.Evidence.RequireBugFreeze = true
+ _, scope := e.createJob(spec)
+ h := e.claim(scope, "reproduce", "runner", "workspace")
+ repro, err := e.store.Register(e.ctx, scope, h, reproSpec(h))
+ must(t, err)
+ symptom, def, hash := FixtureSymptom, CheckDefinitionHash, repro.Hash
+ switch guard {
+ case "revision":
+ h.Revision++
+ case "capability":
+ _, err = e.store.db.Exec("UPDATE steps SET capability='implement' WHERE key='reproduce'")
+ must(t, err)
+ case "definition":
+ def = "wrong"
+ case "attempt":
+ _, err = e.store.db.Exec("UPDATE artifacts SET attempt_id=999")
+ must(t, err)
+ case "fence":
+ _, err = e.store.db.Exec("UPDATE artifacts SET fence=fence+1")
+ must(t, err)
+ case "candidate":
+ _, err = e.store.db.Exec("INSERT INTO artifacts(job_id,step_id,attempt_id,fence,role,hash,media_type,size,provenance,payload,created_at) SELECT job_id,step_id,attempt_id,fence,'candidate',hash,media_type,size,provenance,payload,created_at FROM artifacts")
+ must(t, err)
+ case "symptom":
+ symptom = ""
+ }
+ if guard == "revision" || guard == "capability" || guard == "definition" || guard == "attempt" || guard == "fence" || guard == "candidate" || guard == "symptom" {
+ if err := e.store.FreezeBugEvidence(e.ctx, scope, h, symptom, def, hash); err == nil {
+ t.Fatal("freeze guard bypassed", guard)
+ }
+ return
+ }
+ must(t, e.store.FreezeBugEvidence(e.ctx, scope, h, symptom, def, hash))
+ h.Revision = e.job(scope).Revision
+ if guard == "frozen_symptom" || guard == "frozen_hash" {
+ if guard == "frozen_symptom" {
+ symptom = "different"
+ } else {
+ hash = "different"
+ }
+ if err := e.store.FreezeBugEvidence(e.ctx, scope, h, symptom, def, hash); err == nil {
+ t.Fatal("frozen evidence changed", guard)
+ }
+ return
+ }
+ must(t, e.store.FreezeBugEvidence(e.ctx, scope, h, symptom, def, hash))
+ base := CheckResult{SubjectHash: spec.Target.BaseRevision, ReproductionHash: repro.Hash, CheckDefinitionHash: def, Outcome: CheckFail, TestsRun: 1, TestsFailed: 1, FailureMessage: symptom}
+ e.store.executorEvidence = fakeBugExecutor
+ raw, _ := json.Marshal(base)
+ a := ArtifactSpec{Role: RoleBaseResult, MediaType: "application/json", Payload: raw, Provenance: Provenance{Producer: "executor", Provider: "local", Context: "check"}}
+ if guard == "executor" {
+ e.store.executorEvidence = func(context.Context, *sql.Tx, Scope, Handle, ArtifactSpec) (Provenance, error) {
+ return Provenance{Producer: "executor", Provider: "local", Context: "check"}, ErrEvidence
+ }
+ if _, err := e.store.Register(e.ctx, scope, h, a); err == nil {
+ t.Fatal("executor refusal ignored")
+ }
+ return
+ }
+ _, err = e.store.Register(e.ctx, scope, h, a)
+ must(t, err)
+ // Corrupt persisted evidence to independently exercise completion validation.
+ switch guard {
+ case "base_hash":
+ base.ReproductionHash = "wrong"
+ case "base_subject":
+ base.SubjectHash = "wrong"
+ case "base_symptom":
+ base.FailureMessage = "wrong"
+ case "base_outcome":
+ base.Outcome = CheckPass
+ case "base_counts":
+ base.TestsFailed = 0
+ }
+ raw, _ = json.Marshal(base)
+ _, err = e.store.db.Exec("UPDATE artifacts SET payload=? WHERE role='base_result'", raw)
+ must(t, err)
+ if err := e.store.Complete(e.ctx, scope, h, AttemptResult{Outcome: OutcomeSuccess}); err == nil {
+ t.Fatal("base failure guard bypassed", guard)
+ }
+ })
+ }
+}
+
+func fakeBugExecutor(context.Context, *sql.Tx, Scope, Handle, ArtifactSpec) (Provenance, error) {
+ return Provenance{Producer: "trusted-executor", Provider: "local", Context: "check-run"}, nil
+}
+
+func TestJobRequestKeyScopesAndPayload(t *testing.T) {
+ for _, change := range []string{"project", "target", "grant", "policy", "evidence", "steps", "parent"} {
+ t.Run(change, func(t *testing.T) {
+ e := newEnv(t)
+ spec := softwareSpec(SoftwareSteps(false))
+ spec.RequestKey = "key"
+ e.createJob(spec)
+ switch change {
+ case "project":
+ spec.Project = 1
+ case "target":
+ spec.Target.Ref = "other"
+ case "grant":
+ e.auth.Issue("other", Grant{Account: acctA, Operations: map[Operation]bool{OpJobContinue: true}})
+ spec.GrantRef = "other"
+ case "policy":
+ spec.Policy.Job.Calls--
+ case "evidence":
+ spec.Evidence.ExpectedSymptom = "changed"
+ case "steps":
+ spec.Steps[0].Version++
+ case "parent":
+ spec.Parent = 1
+ }
+ _, err := e.store.CreateJob(e.ctx, spec)
+ wantCode(t, err, CodeConflict)
+ })
+ }
+ t.Run("account", func(t *testing.T) {
+ e := newEnv(t)
+ spec := softwareSpec(SoftwareSteps(false))
+ spec.RequestKey = "key"
+ first, _ := e.createJob(spec)
+ e.auth.Issue(grant, Grant{Account: acctB, Operations: map[Operation]bool{OpJobContinue: true}})
+ spec.Account = acctB
+ other, _ := e.createJob(spec)
+ if first.ID == other.ID {
+ t.Fatal("key crossed account")
+ }
+ })
+ t.Run("empty legacy key", func(t *testing.T) {
+ e := newEnv(t)
+ spec := softwareSpec(SoftwareSteps(false))
+ a, _ := e.createJob(spec)
+ b, _ := e.createJob(spec)
+ if a.ID == b.ID {
+ t.Fatal("empty key deduplicated legacy job")
+ }
+ })
+ t.Run("concurrent", func(t *testing.T) {
+ e := newEnv(t)
+ spec := softwareSpec(SoftwareSteps(false))
+ spec.RequestKey = "key"
+ type result struct {
+ j Job
+ err error
+ }
+ results := make(chan result, 6)
+ for i := 0; i < 6; i++ {
+ go func() { j, err := e.store.CreateJob(e.ctx, spec); results <- result{j, err} }()
+ }
+ var id JobID
+ for i := 0; i < 6; i++ {
+ r := <-results
+ must(t, r.err)
+ if id != 0 && id != r.j.ID {
+ t.Fatal("concurrent job duplicated")
+ }
+ id = r.j.ID
+ }
+ })
+}
+func TestBugExecutorProvenance(t *testing.T) {
+ g := newGitEnv(t)
+ j := g.job(g.scope)
+ j.Evidence.RequireBugFreeze = true
+ raw, _ := json.Marshal(j.Evidence)
+ _, err := g.store.db.Exec("UPDATE jobs SET evidence=? WHERE id=?", string(raw), j.ID)
+ must(t, err)
+ h := g.claimStep("reproduce")
+ repro, err := g.register(h, RoleReproduction, FixtureReproduction)
+ must(t, err)
+ must(t, g.store.FreezeBugEvidence(g.ctx, g.scope, h, FixtureSymptom, CheckDefinitionHash, repro.Hash))
+ base := CheckResult{SubjectHash: j.Target.BaseRevision, ReproductionHash: repro.Hash, CheckDefinitionHash: CheckDefinitionHash, Outcome: CheckFail, TestsRun: 1, TestsFailed: 1, FailureMessage: FixtureSymptom}
+ raw, _ = json.Marshal(base)
+ g.store.executorEvidence = func(context.Context, *sql.Tx, Scope, Handle, ArtifactSpec) (Provenance, error) {
+ return Provenance{}, nil
+ }
+ if _, err := g.register(h, RoleBaseResult, raw); err == nil {
+ t.Fatal("invalid executor provenance accepted")
+ }
+ g.store.executorEvidence = fakeBugExecutor
+ a, err := g.register(h, RoleBaseResult, raw)
+ must(t, err)
+ if a.Provenance.Producer != "trusted-executor" || !a.Provenance.Isolation.RunnerTainted || a.Provenance.Isolation.Status != "unconfined" {
+ t.Fatal("executor identity or exposure lost", a.Provenance)
+ }
+ g.finish(h)
+ if _, err := g.store.Claim(g.ctx, g.scope, "implement", "runner", "ws-reproduce"); err == nil {
+ t.Fatal("workspace reused")
+ }
+}
+
+func TestBugPublishIsRunnerOnly(t *testing.T) {
+ e := newEnv(t)
+ spec := softwareSpec([]StepSpec{{Key: "publish", Capability: CapPublish, Version: 1}})
+ spec.Evidence.RequireBugFreeze = true
+ _, scope := e.createJob(spec)
+ h := e.claim(scope, "publish", "runner", "publication")
+ _, err := e.store.Intend(e.ctx, scope, h, IntentSpec{Key: "agent-publish", Operation: OpProviderCall, Payload: []byte(`{"task":"implement","prompt":"publish"}`), Reserve: Usage{InputTokens: 1, OutputTokens: 1}})
+ if err == nil {
+ t.Fatal("publish allowed an agent turn")
+ }
+ if _, err := e.store.CreateJob(e.ctx, softwareSpec([]StepSpec{{Key: "merge", Capability: Capability("merge"), Version: 1}})); err == nil {
+ t.Fatal("core accepted merge execution")
+ }
+}
+
+func TestBugCandidateRequiresFreeze(t *testing.T) {
+ g := newGitEnv(t)
+ j := g.job(g.scope)
+ j.Evidence.RequireBugFreeze = true
+ raw, _ := json.Marshal(j.Evidence)
+ _, err := g.store.db.Exec("UPDATE jobs SET evidence=? WHERE id=?", string(raw), j.ID)
+ must(t, err)
+ h := g.claimStep("implement")
+ raw, _ = json.Marshal(g.candidate)
+ if _, err := g.register(h, RoleCandidate, raw); err == nil {
+ t.Fatal("candidate accepted before freeze")
+ }
+}
diff --git a/internal/equipo/team/jobs.go b/internal/equipo/team/jobs.go
index 67ce8019..3ff4bf40 100644
--- a/internal/equipo/team/jobs.go
+++ b/internal/equipo/team/jobs.go
@@ -8,6 +8,7 @@ import (
"errors"
"fmt"
"io"
+ "sort"
"time"
)
@@ -16,15 +17,16 @@ import (
// version and epoch as the job's snapshot. Parent, when set, must be a
// non-terminal job of the same account within the policy's depth.
type JobSpec struct {
- Project ProjectID
- Account AccountID
- Parent JobID
- Requester string
- GrantRef string
- Target TargetBinding
- Evidence EvidenceRequirement
- Policy Policy
- Steps []StepSpec
+ RequestKey string
+ Project ProjectID
+ Account AccountID
+ Parent JobID
+ Requester string
+ GrantRef string
+ Target TargetBinding
+ Evidence EvidenceRequirement
+ Policy Policy
+ Steps []StepSpec
}
func (js JobSpec) validate() error {
@@ -122,12 +124,42 @@ func (s *Store) CreateJob(ctx context.Context, spec JobSpec) (Job, error) {
if err != nil {
return Job{}, err
}
+ // Canonicalize graph order and empty dependencies without changing caller slices.
+ canonicalSpec := spec
+ canonicalSpec.Steps = append([]StepSpec(nil), spec.Steps...)
+ for i := range canonicalSpec.Steps {
+ deps := append([]string{}, canonicalSpec.Steps[i].DependsOn...)
+ sort.Strings(deps)
+ canonicalSpec.Steps[i].DependsOn = deps
+ }
+ sort.Slice(canonicalSpec.Steps, func(i, j int) bool { return canonicalSpec.Steps[i].Key < canonicalSpec.Steps[j].Key })
+ input, err := json.Marshal(canonicalSpec)
+ if err != nil {
+ return Job{}, err
+ }
+ inputHash := hashBytes(input)
now := s.clock.Now()
target, _ := json.Marshal(spec.Target)
evidence, _ := json.Marshal(spec.Evidence)
policy, _ := json.Marshal(spec.Policy)
var job Job
err = s.tx(ctx, func(tx *sql.Tx) error {
+ if spec.RequestKey != "" {
+ var id JobID
+ var savedHash string
+ err := tx.QueryRowContext(ctx, `SELECT id, request_hash FROM jobs WHERE account=? AND requester=? AND request_key=?`, spec.Account, spec.Requester, spec.RequestKey).Scan(&id, &savedHash)
+ if err == nil {
+ if savedHash != inputHash {
+ return fail(CodeConflict, "job request input changed")
+ }
+ prior, err := loadJob(ctx, tx, Scope{Account: spec.Account, Job: id})
+ job = prior.Job
+ return err
+ }
+ if !errors.Is(err, sql.ErrNoRows) {
+ return err
+ }
+ }
if err := admissionOpen(ctx, tx); err != nil {
return err
}
@@ -180,10 +212,10 @@ func (s *Store) CreateJob(ctx context.Context, spec JobSpec) (Job, error) {
if spec.Project < 0 {
return fail(CodeInvalid, "negative project")
}
- res, err := tx.ExecContext(ctx, `INSERT INTO jobs(project_id, account, parent, depth, requester, target, evidence, policy_version, policy,
+ res, err := tx.ExecContext(ctx, `INSERT INTO jobs(request_key, request_hash, project_id, account, parent, depth, requester, target, evidence, policy_version, policy,
grant_ref, grant_version, grant_epoch, grant_observed_at, state, wait, revision, outcome, created_at, updated_at)
- VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,1,'',?,?)`,
- int64(spec.Project), string(spec.Account), int64(spec.Parent), depth, spec.Requester, string(target), string(evidence), spec.Policy.Version, string(policy),
+ VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,1,'',?,?)`,
+ spec.RequestKey, inputHash, int64(spec.Project), string(spec.Account), int64(spec.Parent), depth, spec.Requester, string(target), string(evidence), spec.Policy.Version, string(policy),
spec.GrantRef, adm.Version, adm.Epoch, ts(now), string(JobQueued), "", ts(now), ts(now))
if err != nil {
return fail(CodeInvalid, "insert job: %v", err)
diff --git a/internal/equipo/team/model.go b/internal/equipo/team/model.go
index f77e8009..67206508 100644
--- a/internal/equipo/team/model.go
+++ b/internal/equipo/team/model.go
@@ -275,11 +275,13 @@ func (p Predicate) Valid() bool {
// CheckDefinitionHash pins the trusted check definition every result must
// have run under. BaselineTestSetHash pins the executor's required test set.
type EvidenceRequirement struct {
- BaselineTestSetHash string `json:"baseline_test_set_hash,omitempty"`
- Predicate Predicate `json:"predicate"`
- ExpectedSymptom string `json:"expected_symptom,omitempty"`
- CheckDefinitionHash string `json:"check_definition_hash,omitempty"`
- RequiredSources int `json:"required_sources,omitempty"`
+ RequireBugFreeze bool `json:"require_bug_freeze,omitempty"`
+ FrozenReproductionHash string `json:"frozen_reproduction_hash,omitempty"`
+ BaselineTestSetHash string `json:"baseline_test_set_hash,omitempty"`
+ Predicate Predicate `json:"predicate"`
+ ExpectedSymptom string `json:"expected_symptom,omitempty"`
+ CheckDefinitionHash string `json:"check_definition_hash,omitempty"`
+ RequiredSources int `json:"required_sources,omitempty"`
}
func (e EvidenceRequirement) validate(kind TargetKind) error {
@@ -457,12 +459,14 @@ type Attempt struct {
}
// Handle is what a runner presents on every call after a claim. The store
-// never trusts it: each field is compared with the stored attempt and step,
-// and a mismatch is ErrFence. It carries no authority.
+// compares the attempt, fence and runner with stored rows; a mismatch is
+// ErrFence. Revision is the job revision checked by FreezeBugEvidence.
+// A handle carries no authority.
type Handle struct {
- Attempt AttemptID
- Fence int64
- Runner string
+ Revision int64
+ Attempt AttemptID
+ Fence int64
+ Runner string
}
// Outcome closes the ways an attempt or action can end.
diff --git a/internal/equipo/team/scheduler.go b/internal/equipo/team/scheduler.go
index 34b9cf39..434bfcba 100644
--- a/internal/equipo/team/scheduler.go
+++ b/internal/equipo/team/scheduler.go
@@ -193,11 +193,13 @@ func (s *Store) Claim(ctx context.Context, scope Scope, stepKey, runner, workspa
return fail(CodeInvalid, "update step: %v", err)
}
if j.State == JobQueued || j.State == JobWaiting {
- if _, err := bumpJob(ctx, tx, j, JobRunning, WaitNone, j.Outcome, now); err != nil {
+ var err error
+ j, err = bumpJob(ctx, tx, j, JobRunning, WaitNone, j.Outcome, now)
+ if err != nil {
return err
}
}
- h = Handle{Attempt: AttemptID(id), Fence: fence, Runner: runner}
+ h = Handle{Revision: j.Revision, Attempt: AttemptID(id), Fence: fence, Runner: runner}
return appendEvent(ctx, tx, scope, "attempt.claimed", runner, map[string]any{"step": st.Key, "attempt": id, "fence": fence, "workspace": workspace}, now)
})
return h, err
@@ -298,6 +300,11 @@ func (s *Store) Complete(ctx context.Context, scope Scope, h Handle, r AttemptRe
if err != nil {
return err
}
+ if r.Outcome == OutcomeSuccess && hd.step.Capability == CapReproduce && hd.job.Evidence.RequireBugFreeze {
+ if err := completedBugReproduction(ctx, tx, hd); err != nil {
+ return err
+ }
+ }
var open int
if err := tx.QueryRowContext(ctx, `SELECT COUNT(*) FROM actions WHERE attempt_id=? AND state IN ('intent','dispatching','uncertain')`, int64(hd.attempt.ID)).Scan(&open); err != nil {
return fail(CodeInvalid, "open actions: %v", err)
diff --git a/internal/equipo/team/shared.go b/internal/equipo/team/shared.go
index 74dfcd61..db2bb668 100644
--- a/internal/equipo/team/shared.go
+++ b/internal/equipo/team/shared.go
@@ -23,7 +23,7 @@ func OpenShared(ctx context.Context, writer *sql.DB, path string, o Options) (*S
if err != nil {
return nil, err
}
- s := &Store{db: writer, path: path, marker: o.Marker, clock: o.Clock, auth: o.Authority, adapters: o.Adapters, provenance: o.Provenance, commitHook: o.commitHook}
+ s := &Store{db: writer, path: path, marker: o.Marker, clock: o.Clock, auth: o.Authority, adapters: o.Adapters, provenance: o.Provenance, executorEvidence: o.ExecutorEvidence, commitHook: o.commitHook}
if s.adapters == nil {
s.adapters = map[Operation]Adapter{}
}
@@ -110,7 +110,7 @@ func (s *Store) checkSharedSchema(ctx context.Context) error {
var sharedSchemaQueries = []string{
`SELECT release_required,recovery_revision,reconciled_revision,clock_high_water FROM service LIMIT 0`,
- `SELECT grant_stale FROM jobs LIMIT 0`,
+ `SELECT grant_stale,request_key,request_hash FROM jobs LIMIT 0`,
`SELECT elapsed_unknown FROM time_reservations LIMIT 0`,
`SELECT ref,version,epoch FROM grant_fences LIMIT 0`,
`SELECT key,account,project_id,reserved,actor,reason,incarnation,created_at FROM recovery_charges LIMIT 0`,
@@ -275,6 +275,7 @@ var sharedSchemaIndexes = []string{
"attempts_job",
"attempts_one_live",
"jobs_account",
+ "jobs_request",
"reservations_account",
"reservations_job",
"time_reservations_account",
diff --git a/internal/equipo/team/store.go b/internal/equipo/team/store.go
index 5f3af981..850818e0 100644
--- a/internal/equipo/team/store.go
+++ b/internal/equipo/team/store.go
@@ -19,7 +19,7 @@ import (
// SchemaVersion is the one schema this binary writes. A database with a
// newer version is refused (ErrStaleStore): the binary would not know the
// rows it was reading.
-const SchemaVersion = 5
+const SchemaVersion = 6
// Adapter executes one operation class against an external system. Execute
// runs an admitted dispatch and returns its receipt; an error from Execute
@@ -38,32 +38,34 @@ type Adapter interface {
// the incarnation marker kept outside the database; it defaults to the
// database path plus ".incarnation".
type Options struct {
- Provenance ProvenanceResolver
- Clock Clock
- Authority Authority
- Adapters map[Operation]Adapter
- Marker string
- commitHook func(string) error // tests terminate a process at exact commit boundaries
+ ExecutorEvidence ExecutorEvidenceValidator
+ Provenance ProvenanceResolver
+ Clock Clock
+ Authority Authority
+ Adapters map[Operation]Adapter
+ Marker string
+ commitHook func(string) error // tests terminate a process at exact commit boundaries
}
// Store is the durable core. A process-shared guard serializes each SQLite
// commit with its external witness. Open launches no goroutine or network
// connection. The database, witness and lock live in trusted local storage.
type Store struct {
- provenance ProvenanceResolver
- db *sql.DB
- ownsDB bool
- closed bool
- path string
- marker string
- clock Clock
- auth Authority
- adapters map[Operation]Adapter
- incarnation int64
- recoveryMu sync.Mutex
- commitHook func(string) error
- writeMu sync.Mutex
- broken error // guarded by writeMu; only a new Open can recover it
+ executorEvidence ExecutorEvidenceValidator
+ provenance ProvenanceResolver
+ db *sql.DB
+ ownsDB bool
+ closed bool
+ path string
+ marker string
+ clock Clock
+ auth Authority
+ adapters map[Operation]Adapter
+ incarnation int64
+ recoveryMu sync.Mutex
+ commitHook func(string) error
+ writeMu sync.Mutex
+ broken error // guarded by writeMu; only a new Open can recover it
}
// Open opens or creates the database at path. Admission is paused on every
@@ -92,7 +94,7 @@ func Open(ctx context.Context, path string, o Options) (*Store, error) {
return nil, fail(CodeInvalid, "open: %v", err)
}
db.SetMaxOpenConns(4)
- s := &Store{db: db, ownsDB: true, path: path, marker: o.Marker, clock: o.Clock, auth: o.Authority, adapters: o.Adapters, provenance: o.Provenance}
+ s := &Store{db: db, ownsDB: true, path: path, marker: o.Marker, clock: o.Clock, auth: o.Authority, adapters: o.Adapters, provenance: o.Provenance, executorEvidence: o.ExecutorEvidence}
if s.adapters == nil {
s.adapters = map[Operation]Adapter{}
}
@@ -312,7 +314,7 @@ func (s *Store) migrate(ctx context.Context) error {
return err
}
v = 2
- case v != 2 && v != 3 && v != 4 && v != SchemaVersion:
+ case v != 2 && v != 3 && v != 4 && v != 5 && v != SchemaVersion:
return fail(CodeStaleStore, "unsupported schema %d", v)
}
rows, err := tx.QueryContext(ctx, `PRAGMA table_info(jobs)`)
@@ -367,6 +369,12 @@ func (s *Store) migrate(ctx context.Context) error {
if v < 5 {
_, err = tx.ExecContext(ctx, runnerPolicySchema)
}
+ if err != nil {
+ return err
+ }
+ if v < 6 {
+ _, err = tx.ExecContext(ctx, jobRequestSchema)
+ }
return err
})
}
@@ -659,3 +667,10 @@ CREATE INDEX time_period_project ON time_reservations(account,project_id,state,p
CREATE INDEX recovery_charges_scope ON recovery_charges(account,project_id);
UPDATE service SET schema_version=5 WHERE id=1;
`
+
+const jobRequestSchema = `
+ALTER TABLE jobs ADD COLUMN request_key TEXT NOT NULL DEFAULT "";
+ALTER TABLE jobs ADD COLUMN request_hash TEXT NOT NULL DEFAULT "";
+CREATE UNIQUE INDEX jobs_request ON jobs(account, requester, request_key) WHERE request_key <> '';
+UPDATE service SET schema_version=6 WHERE id=1;
+`
diff --git a/internal/equipotest/execution_schema_test.go b/internal/equipotest/execution_schema_test.go
index a3de2831..9d6c2267 100644
--- a/internal/equipotest/execution_schema_test.go
+++ b/internal/equipotest/execution_schema_test.go
@@ -145,7 +145,7 @@ func TestExecutionSchemaParity(t *testing.T) {
defer old.Close()
before := &migrate.Set{}
for _, m := range equipo.BootSchema.All() {
- if m.ID != "equipo/0007_execution" && m.ID != "equipo/0008_recovery" && m.ID != "equipo/0009_runner_policy" {
+ if m.ID != "equipo/0012_tasks" && m.ID != "equipo/0007_execution" && m.ID != "equipo/0008_recovery" && m.ID != "equipo/0009_runner_policy" {
before.Add(m)
}
}
@@ -154,7 +154,7 @@ func TestExecutionSchemaParity(t *testing.T) {
executionMust(t, old.G.Create(&equipo.Account{Label: "existing account"}).Error)
result, err := migrate.Apply(ctx, old, equipo.BootSchema)
executionMust(t, err)
- if !reflect.DeepEqual(result.Applied, []string{"equipo/0007_execution", "equipo/0008_recovery", "equipo/0009_runner_policy"}) {
+ if !reflect.DeepEqual(result.Applied, []string{"equipo/0007_execution", "equipo/0008_recovery", "equipo/0009_runner_policy", "equipo/0012_tasks"}) {
t.Fatalf("upgrade migrations: %v", result.Applied)
}
var account equipo.Account
@@ -174,7 +174,7 @@ func TestExecutionSchemaParity(t *testing.T) {
defer old.Close()
before := &migrate.Set{}
for _, m := range equipo.BootSchema.All() {
- if m.ID != "equipo/0008_recovery" && m.ID != "equipo/0009_runner_policy" {
+ if m.ID != "equipo/0012_tasks" && m.ID != "equipo/0008_recovery" && m.ID != "equipo/0009_runner_policy" {
before.Add(m)
}
}
@@ -185,7 +185,7 @@ func TestExecutionSchemaParity(t *testing.T) {
executionMust(t, err)
result, err := migrate.Apply(ctx, old, equipo.BootSchema)
executionMust(t, err)
- if !reflect.DeepEqual(result.Applied, []string{"equipo/0008_recovery", "equipo/0009_runner_policy"}) {
+ if !reflect.DeepEqual(result.Applied, []string{"equipo/0008_recovery", "equipo/0009_runner_policy", "equipo/0012_tasks"}) {
t.Fatalf("task one upgrade migrations: %v", result.Applied)
}
var evidence string
@@ -207,7 +207,7 @@ func TestExecutionSchemaParity(t *testing.T) {
defer old.Close()
before := &migrate.Set{}
for _, m := range equipo.BootSchema.All() {
- if m.ID != "equipo/0009_runner_policy" {
+ if m.ID != "equipo/0012_tasks" && m.ID != "equipo/0009_runner_policy" {
before.Add(m)
}
}
@@ -233,7 +233,7 @@ func TestExecutionSchemaParity(t *testing.T) {
return
}
executionMust(t, err)
- if !reflect.DeepEqual(result.Applied, []string{"equipo/0009_runner_policy"}) {
+ if !reflect.DeepEqual(result.Applied, []string{"equipo/0009_runner_policy", "equipo/0012_tasks"}) {
t.Fatal("wrong task two upgrade", result.Applied)
}
var project, input, cost int
@@ -250,6 +250,41 @@ func TestExecutionSchemaParity(t *testing.T) {
})
}
+ t.Run("task six upgrade", func(t *testing.T) {
+ old, err := db.Open(filepath.Join(t.TempDir(), "task6.db"), slog.New(slog.NewTextHandler(io.Discard, nil)))
+ executionMust(t, err)
+ defer old.Close()
+ before := &migrate.Set{}
+ for _, m := range equipo.BootSchema.All() {
+ if m.ID != "equipo/0012_tasks" {
+ before.Add(m)
+ }
+ }
+ _, err = migrate.Apply(ctx, old, before)
+ executionMust(t, err)
+ executionMust(t, seedExecutionJob(old.Writer()))
+ result, err := migrate.Apply(ctx, old, equipo.BootSchema)
+ executionMust(t, err)
+ if !reflect.DeepEqual(result.Applied, []string{"equipo/0012_tasks"}) {
+ t.Fatal("task six upgrade migrations", result.Applied)
+ }
+ var key, hash string
+ executionMust(t, old.Writer().QueryRow("SELECT request_key,request_hash FROM jobs WHERE id=1").Scan(&key, &hash))
+ if key != "" || hash != "" {
+ t.Fatal("legacy request identity invented")
+ }
+ if scalar(t, old, "SELECT schema_version FROM service") != 6 {
+ t.Fatal("core version not six")
+ }
+ for i := 0; i < 2; i++ {
+ result, err = migrate.Apply(ctx, old, equipo.BootSchema)
+ executionMust(t, err)
+ if len(result.Applied) != 0 {
+ t.Fatal("migration replayed")
+ }
+ }
+ })
+
coreNames := map[string]bool{"grant_fences": true, "recovery_charges": true, "recovery_events": true, "service": true, "jobs": true, "steps": true, "attempts": true, "reservations": true, "actions": true, "events": true, "artifacts": true, "period_budgets": true, "time_reservations": true}
var appCore migrate.Snapshot
for _, table := range expected.Tables {
@@ -260,7 +295,7 @@ func TestExecutionSchemaParity(t *testing.T) {
if len(appCore.Tables) != len(coreNames) {
t.Fatalf("execution tables = %d, want %d", len(appCore.Tables), len(coreNames))
}
- for _, version := range []int{1, 2, 3, 4, 5} {
+ for _, version := range []int{1, 2, 3, 4, 5, 6} {
t.Run(fmt.Sprint(version), func(t *testing.T) {
standalonePath := filepath.Join(t.TempDir(), "core.db")
core, err := team.Open(ctx, standalonePath, executionOptions())
@@ -271,6 +306,12 @@ func TestExecutionSchemaParity(t *testing.T) {
defer raw.Close()
raw.SetMaxOpenConns(1)
executionMust(t, seedExecutionJob(raw))
+ if version < 6 {
+ for _, q := range []string{"DROP INDEX jobs_request", "ALTER TABLE jobs DROP COLUMN request_key", "ALTER TABLE jobs DROP COLUMN request_hash"} {
+ _, err = raw.Exec(q)
+ executionMust(t, err)
+ }
+ }
if version < 5 {
for _, q := range []string{"DROP INDEX reservations_period_account", "DROP INDEX reservations_period_project", "DROP INDEX time_period_account", "DROP INDEX time_period_project", "DROP INDEX recovery_charges_scope", "ALTER TABLE reservations DROP COLUMN project_id", "ALTER TABLE reservations DROP COLUMN period", "ALTER TABLE reservations DROP COLUMN cost_unavailable", "ALTER TABLE reservations DROP COLUMN s_cached", "ALTER TABLE period_budgets DROP COLUMN content_hash"} {
_, err = raw.Exec(q)
diff --git a/internal/equipotest/tasks_test.go b/internal/equipotest/tasks_test.go
new file mode 100644
index 00000000..9e29c335
--- /dev/null
+++ b/internal/equipotest/tasks_test.go
@@ -0,0 +1,511 @@
+package equipotest
+
+import (
+ "context"
+ "crypto/sha256"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "net/http/httptest"
+ "net/url"
+ "strconv"
+ "strings"
+ "testing"
+
+ "amadan.net/oficina/equipo/internal/equipo"
+ "amadan.net/oficina/equipo/internal/equipo/team"
+ "gorm.io/gorm"
+)
+
+func bugFixture(t *testing.T) connectionFixture {
+ t.Helper()
+ f := connectionStore(t)
+ f.ack(t)
+ f.choice(t, f.ids["claude"])
+ l := team.PeriodLimits{Calls: 24, InputTokens: 200000, OutputTokens: 40000, Seconds: 10000}
+ executionMust(t, f.s.SaveBudgets(connectionContext, ownerActor, equipo.BudgetConfig{Team: l, Projects: map[team.ProjectID]team.PeriodLimits{team.ProjectID(f.project.ID): l}}))
+ return f
+}
+func bugTask(t *testing.T, f connectionFixture) equipo.Task {
+ t.Helper()
+ task, err := f.s.CreateBug(connectionContext, ownerActor, f.project.ID, "the total is wrong", "request-1")
+ executionMust(t, err)
+ return task
+}
+func bugPrepared(f connectionFixture) equipo.PreparedBug {
+ b := []byte("trusted check definition")
+ return equipo.PreparedBug{Repository: f.project.Repository, DefaultBranch: f.project.DefaultBranch, BaseCommit: strings.Repeat("a", 40), CheckDefinition: b, CheckDefinitionHash: fmt.Sprintf("%x", sha256.Sum256(b)), BaselineTestSetHash: strings.Repeat("b", 64)}
+}
+func TestBugSubmissionRetry(t *testing.T) {
+ f := bugFixture(t)
+ task := bugTask(t, f)
+ again := bugTask(t, f)
+ if again.ID != task.ID || task.ReviewRef != "equipo/"+task.ID || task.Requester != ownerAddress {
+ t.Fatal("submission identity changed")
+ }
+ if _, err := f.s.CreateBug(connectionContext, ownerActor, f.project.ID, "changed", "request-1"); !errors.Is(err, equipo.ErrConflict) {
+ t.Fatalf("changed payload accepted: %v", err)
+ }
+ if scalar(t, f.d, "SELECT count(*) FROM tasks") != 1 || scalar(t, f.d, "SELECT count(*) FROM task_outboxes") != 1 || scalar(t, f.d, "SELECT count(*) FROM audit_events WHERE kind='task.create'") != 1 {
+ t.Fatal("duplicate submission writes")
+ }
+ for _, s := range []string{"", strings.Repeat("a", 16385), string([]byte{0xff})} {
+ if _, err := f.s.CreateBug(connectionContext, ownerActor, f.project.ID, s, "bad"); !errors.Is(err, equipo.ErrInvalid) {
+ t.Fatal("description accepted", err)
+ }
+ }
+ if _, err := f.s.CreateBug(connectionContext, ownerActor, f.project.ID, strings.Repeat("é", 8192), "max"); err != nil {
+ t.Fatal(err)
+ }
+ setMember(t, f.s, "reader@example.com", equipo.RoleMember, true)
+ if _, err := f.s.CreateBug(connectionContext, equipo.Actor{Address: "reader@example.com"}, f.project.ID, "bug", "reader"); !errors.Is(err, equipo.ErrForbidden) {
+ t.Fatal("reader started task", err)
+ }
+ if _, err := f.s.Task(connectionContext, equipo.Actor{Address: "reader@example.com"}, task.ID); err != nil {
+ t.Fatal("member cannot read", err)
+ }
+ mustSQL(t, f.d, "UPDATE members SET active=0 WHERE address=?", ownerAddress)
+ if _, err := f.s.CreateBug(connectionContext, ownerActor, f.project.ID, task.Description, task.RequestID); !errors.Is(err, equipo.ErrForbidden) {
+ t.Fatal("removed requester retry", err)
+ }
+}
+func TestBugFormCannotChooseAuthority(t *testing.T) {
+ f := bugFixture(t)
+ m := &capturingMailer{}
+ h, err := equipo.App(f.d, testConfig(testOrigin), m, nil)
+ executionMust(t, err)
+ server := httptest.NewServer(h)
+ t.Cleanup(server.Close)
+ c := signinClient(t, server.URL)
+ signinEmail(t, c, server.URL, testOrigin, m, ownerAddress)
+ form := url.Values{"project_id": {strconv.FormatInt(f.project.ID, 10)}, "description": {"bug"}, "request_id": {"form"}}
+ for _, key := range []string{"requester", "repository", "grant", "budget", "ref", "kind", "actor", "connection_id", "runner_id", "policy", "steps"} {
+ form.Set(key, "forged")
+ res := clientPost(t, c, server.URL+"/tasks", testOrigin, form)
+ res.Body.Close()
+ if res.StatusCode != 422 {
+ t.Fatalf("forged %s accepted: %d", key, res.StatusCode)
+ }
+ form.Del(key)
+ }
+ if scalar(t, f.d, "SELECT count(*) FROM tasks") != 0 {
+ t.Fatal("forged forms wrote tasks")
+ }
+ res := clientPost(t, c, server.URL+"/tasks", "http://wrong.invalid", form)
+ res.Body.Close()
+ if res.StatusCode != 403 {
+ t.Fatal("CSRF accepted")
+ }
+}
+func TestFixedBugPlan(t *testing.T) {
+ f := bugFixture(t)
+ task := bugTask(t, f)
+ task, err := f.s.PrepareBug(connectionContext, f.principal, task.ID, task.Revision, bugPrepared(f))
+ executionMust(t, err)
+ policy, err := team.RunnerPolicy("subscription", team.Limits{Calls: 24, InputTokens: 200000, OutputTokens: 40000}, team.Limits{Calls: 1, InputTokens: 32000, OutputTokens: 4000}, team.Rates{})
+ executionMust(t, err)
+ spec, err := equipo.BugJobSpec(task, f.project, policy, task.Description)
+ executionMust(t, err)
+ caps := []team.Capability{team.CapReproduce, team.CapImplement, team.CapReview, team.CapVerify, team.CapPublish}
+ if len(spec.Steps) != 5 || spec.RequestKey != task.ID || spec.Project != team.ProjectID(task.ProjectID) || spec.GrantRef != equipo.GrantRef(task.ProjectID, task.Requester) || !spec.Evidence.RequireBugFreeze {
+ t.Fatal("wrong fixed plan", spec)
+ }
+ for i, cap := range caps {
+ st := spec.Steps[i]
+ if st.Capability != cap || i > 0 && (len(st.DependsOn) != 1 || st.DependsOn[0] != spec.Steps[i-1].Key) {
+ t.Fatal("wrong dependency", st)
+ }
+ }
+ plan := equipo.BugPlan(task)
+ if len(plan) != 6 || plan[5].Key != "merge" || plan[5].Person == "" || !plan[4].RunnerOnly {
+ t.Fatal("human/runner plan", plan)
+ }
+ wrong := f.project
+ wrong.ID++
+ if _, err := equipo.BugJobSpec(task, wrong, policy, task.Description); err == nil {
+ t.Fatal("project/grant split")
+ }
+}
+func TestBugPreparationCrash(t *testing.T) {
+ for _, stage := range []string{"prepare", "link"} {
+ t.Run(stage, func(t *testing.T) {
+ f := bugFixture(t)
+ task := bugTask(t, f)
+ prep := bugPrepared(f)
+ var seq int
+ var name, path string
+ executionMust(t, f.d.Writer().QueryRow("PRAGMA database_list").Scan(&seq, &name, &path))
+ x, err := f.s.AttachExecution(connectionContext, path, team.Options{Clock: f.clock, Authority: equipo.NewAuthority(f.s, f.clock)})
+ executionMust(t, err)
+ t.Cleanup(func() { x.Core.Close() })
+ _, err = x.Core.Resume(connectionContext)
+ executionMust(t, err)
+ reopen := func() {
+ executionMust(t, x.Core.Close())
+ f.s = equipo.NewStore(f.d, equipo.WithRunnerClock(f.clock), equipo.WithVerifiedIsolationTuples([]team.IsolationTuple{connectionTuple(f.reports[0])}))
+ x, err = f.s.AttachExecution(connectionContext, path, team.Options{Clock: f.clock, Authority: equipo.NewAuthority(f.s, f.clock)})
+ executionMust(t, err)
+ _, err = x.Core.Resume(connectionContext)
+ executionMust(t, err)
+ }
+ fail := func(kind string) {
+ executionMust(t, f.d.G.Callback().Create().Before("gorm:create").Register("task7_crash", func(tx *gorm.DB) {
+ if tx.Statement.Table == "audit_events" {
+ if ev, ok := tx.Statement.Dest.(*equipo.AuditEvent); ok && ev.Kind == kind {
+ tx.AddError(errors.New("crash before acknowledgement"))
+ }
+ }
+ }))
+ }
+ if stage == "prepare" {
+ fail("task.prepare")
+ if _, err := f.s.PrepareBug(connectionContext, f.principal, task.ID, task.Revision, prep); err == nil {
+ t.Fatal("prepare crash not injected")
+ }
+ executionMust(t, f.d.G.Callback().Create().Remove("task7_crash"))
+ if scalar(t, f.d, "SELECT revision FROM tasks WHERE id=?", task.ID) != 1 {
+ t.Fatal("partial preparation")
+ }
+ reopen()
+ }
+ task, err = f.s.PrepareBug(connectionContext, f.principal, task.ID, task.Revision, prep)
+ executionMust(t, err)
+ reopen()
+ if stage == "link" {
+ fail("task.link")
+ if _, err := f.s.StartBug(connectionContext, f.principal, task.ID, task.Revision); err == nil {
+ t.Fatal("link crash not injected")
+ }
+ executionMust(t, f.d.G.Callback().Create().Remove("task7_crash"))
+ if scalar(t, f.d, "SELECT count(*) FROM jobs") != 1 || scalar(t, f.d, "SELECT job_id FROM tasks WHERE id=?", task.ID) != 0 {
+ t.Fatal("wrong crash boundary")
+ }
+ reopen()
+ }
+ linked, err := f.s.StartBug(connectionContext, f.principal, task.ID, task.Revision)
+ executionMust(t, err)
+ reopen()
+ again, err := f.s.StartBug(connectionContext, f.principal, task.ID, task.Revision)
+ executionMust(t, err)
+ if linked.JobID == 0 || linked.JobID != again.JobID || scalar(t, f.d, "SELECT count(*) FROM jobs") != 1 || scalar(t, f.d, "SELECT count(*) FROM task_outboxes WHERE state='done'") != 1 {
+ t.Fatal("outbox recovery duplicated job")
+ }
+ })
+ }
+}
+func TestBugPreparationGuards(t *testing.T) {
+ for _, guard := range []string{"project", "connection", "review", "choice", "credential", "person", "revision", "repository", "default", "base", "definition", "baseline", "budget", "budget_revision", "review_snapshot", "roster"} {
+ t.Run(guard, func(t *testing.T) {
+ f := bugFixture(t)
+ task := bugTask(t, f)
+ prep := bugPrepared(f)
+ principal := f.principal
+ rev := task.Revision
+ switch guard {
+ case "project":
+ mustSQL(t, f.d, "UPDATE projects SET revision=revision+1")
+ case "connection":
+ mustSQL(t, f.d, "UPDATE connections SET revision=revision+1 WHERE id=?", f.ids["claude"])
+ case "review":
+ mustSQL(t, f.d, "UPDATE connections SET revision=revision+1 WHERE id=?", f.ids["codex"])
+ case "choice":
+ mustSQL(t, f.d, "UPDATE connection_choices SET revision=revision+1")
+ case "credential":
+ mustSQL(t, f.d, "UPDATE runner_credentials SET revoked_at=?", f.clock.Now())
+ case "person":
+ principal.Person = "member@example.com"
+ case "revision":
+ rev++
+ case "repository":
+ prep.Repository = "amadan.net/other/repo"
+ case "default":
+ prep.DefaultBranch = "other"
+ case "base":
+ prep.BaseCommit = "mutable-ref"
+ case "definition":
+ prep.CheckDefinitionHash = strings.Repeat("c", 64)
+ case "baseline":
+ prep.BaselineTestSetHash = ""
+ case "review_snapshot":
+ mustSQL(t, f.d, "UPDATE task_outboxes SET review=json_set(review,'$.Revision',99)")
+ case "budget_revision":
+ config, err := f.s.Budgets(connectionContext)
+ executionMust(t, err)
+ executionMust(t, f.s.SaveBudgets(connectionContext, ownerActor, config))
+ case "budget":
+ mustSQL(t, f.d, "DELETE FROM budget_records")
+ case "roster":
+ mustSQL(t, f.d, "UPDATE members SET active=0 WHERE address=?", ownerAddress)
+ }
+ if _, err := f.s.PrepareBug(context.Background(), principal, task.ID, rev, prep); err == nil {
+ t.Fatal("preparation guard bypassed", guard)
+ }
+ if scalar(t, f.d, "SELECT revision FROM tasks WHERE id=?", task.ID) != 1 {
+ t.Fatal("failed preparation mutated task")
+ }
+ })
+ }
+}
+
+func TestBugSubmissionAtomicAndConcurrent(t *testing.T) {
+ f := bugFixture(t)
+ executionMust(t, f.d.G.Callback().Create().Before("gorm:create").Register("task7_create_fail", func(tx *gorm.DB) {
+ if tx.Statement.Table == "audit_events" {
+ tx.AddError(errors.New("audit unavailable"))
+ }
+ }))
+ if _, err := f.s.CreateBug(connectionContext, ownerActor, f.project.ID, "bug", "atomic"); err == nil {
+ t.Fatal("audit failure accepted")
+ }
+ executionMust(t, f.d.G.Callback().Create().Remove("task7_create_fail"))
+ if scalar(t, f.d, "SELECT count(*) FROM tasks") != 0 || scalar(t, f.d, "SELECT count(*) FROM task_outboxes") != 0 {
+ t.Fatal("partial creation")
+ }
+ results := make(chan equipo.Task, 6)
+ errs := make(chan error, 6)
+ for i := 0; i < 6; i++ {
+ go func() {
+ task, err := f.s.CreateBug(connectionContext, ownerActor, f.project.ID, "bug", "concurrent")
+ results <- task
+ errs <- err
+ }()
+ }
+ var id string
+ for i := 0; i < 6; i++ {
+ task := <-results
+ executionMust(t, <-errs)
+ if id != "" && id != task.ID {
+ t.Fatal("concurrent duplicate")
+ }
+ id = task.ID
+ }
+ if scalar(t, f.d, "SELECT count(*) FROM tasks") != 1 {
+ t.Fatal("concurrent duplicate rows")
+ }
+}
+func TestBugWorkOwner(t *testing.T) {
+ f := bugFixture(t)
+ setMember(t, f.s, "ack@example.com", equipo.RoleOwner, true)
+ executionMust(t, f.s.RevokeIsolationAcknowledgement(connectionContext, ownerActor, f.ids["codex"], 1))
+ executionMust(t, f.s.AcknowledgeUnconfined(connectionContext, equipo.Actor{Address: "ack@example.com"}, f.ids["codex"], 1))
+ member, err := f.s.Member(connectionContext, ownerAddress)
+ executionMust(t, err)
+ executionMust(t, f.s.SetMember(connectionContext, equipo.Actor{Address: "ack@example.com"}, ownerAddress, equipo.RoleMember, true, member.Revision))
+ task := bugTask(t, f)
+ if task.Requester != ownerAddress {
+ t.Fatal("work owner attribution")
+ }
+ mustSQL(t, f.d, "UPDATE decision_owners SET address=? WHERE decision='work'", "member@example.com")
+ if _, err := f.s.CreateBug(connectionContext, ownerActor, f.project.ID, task.Description, task.RequestID); !errors.Is(err, equipo.ErrForbidden) {
+ t.Fatal("changed work owner retried", err)
+ }
+}
+func TestBugPreparedRetryIsImmutable(t *testing.T) {
+ f := bugFixture(t)
+ task := bugTask(t, f)
+ p := bugPrepared(f)
+ prepared, err := f.s.PrepareBug(connectionContext, f.principal, task.ID, task.Revision, p)
+ executionMust(t, err)
+ again, err := f.s.PrepareBug(connectionContext, f.principal, task.ID, task.Revision, p)
+ executionMust(t, err)
+ if prepared.Revision != again.Revision || scalar(t, f.d, "SELECT count(*) FROM audit_events WHERE kind='task.prepare'") != 1 {
+ t.Fatal("prepare retry changed state")
+ }
+ p.BaseCommit = strings.Repeat("c", 40)
+ if _, err := f.s.PrepareBug(connectionContext, f.principal, task.ID, prepared.Revision, p); !errors.Is(err, equipo.ErrConflict) {
+ t.Fatal("base mutated", err)
+ }
+}
+
+func TestBugPreparationLookupFailure(t *testing.T) {
+ for _, table := range []string{"members", "projects", "budget_records", "connection_choices", "connections", "runner_credentials", "task_outboxes"} {
+ t.Run(table, func(t *testing.T) {
+ f := bugFixture(t)
+ task := bugTask(t, f)
+ executionMust(t, f.d.G.Callback().Query().Before("gorm:query").Register("task7_lookup", func(tx *gorm.DB) {
+ if tx.Statement.Table == table {
+ tx.AddError(errors.New("lookup unavailable"))
+ }
+ }))
+ _, err := f.s.PrepareBug(connectionContext, f.principal, task.ID, task.Revision, bugPrepared(f))
+ executionMust(t, f.d.G.Callback().Query().Remove("task7_lookup"))
+ if err == nil {
+ t.Fatal("lookup failure granted preparation", table)
+ }
+ if scalar(t, f.d, "SELECT revision FROM tasks WHERE id=?", task.ID) != 1 {
+ t.Fatal("lookup failure mutated task")
+ }
+ })
+ }
+}
+func TestBugPreparationOtherMachine(t *testing.T) {
+ f := bugFixture(t)
+ task := bugTask(t, f)
+ code, key := beginDevice(t, f.s)
+ approveDevice(t, f.s, code, ownerAddress)
+ credential := claimDevice(t, f.s, code, key)
+ p, err := f.s.AuthenticateRunner(connectionContext, credential.Token)
+ executionMust(t, err)
+ if _, err := f.s.PrepareBug(connectionContext, p, task.ID, task.Revision, bugPrepared(f)); !errors.Is(err, equipo.ErrForbidden) {
+ t.Fatal("other machine prepared", err)
+ }
+}
+func TestBugSubmissionWaitsForConnectionsAndBudget(t *testing.T) {
+ for _, guard := range []string{"budget", "engineering", "review", "api"} {
+ t.Run(guard, func(t *testing.T) {
+ f := bugFixture(t)
+ switch guard {
+ case "budget":
+ mustSQL(t, f.d, "DELETE FROM budget_records")
+ case "engineering":
+ mustSQL(t, f.d, "UPDATE connection_choices SET pinned_id='missing'")
+ case "review":
+ executionMust(t, f.s.RevokeIsolationAcknowledgement(connectionContext, ownerActor, f.ids["codex"], 1))
+ case "api":
+ f.reports[0].Kind = "api"
+ f.reports[0].LocalID = "api-claude"
+ f.reports[0].Routing.BindingID = "api-claude"
+ executionMust(t, f.s.ReportConnections(connectionContext, f.principal, f.reports))
+ connections, err := f.s.Connections(connectionContext, ownerActor)
+ executionMust(t, err)
+ for _, c := range connections {
+ if c.LocalID == "api-claude" {
+ f.ids["claude"] = c.ID
+ }
+ }
+ executionMust(t, f.s.SaveConnectionChoice(connectionContext, ownerActor, equipo.ConnectionChoice{ProjectID: f.project.ID, Revision: 1, ConnectionIDs: []string{f.ids["claude"], f.ids["codex"]}, PinnedID: f.ids["claude"]}))
+ }
+ if _, err := f.s.CreateBug(connectionContext, ownerActor, f.project.ID, "bug", "refused"); err == nil {
+ t.Fatal("unfunded or unavailable submission accepted", guard)
+ }
+ if scalar(t, f.d, "SELECT count(*) FROM tasks") != 0 {
+ t.Fatal("refused submission persisted")
+ }
+ })
+ }
+}
+
+type fakeBugPreparer struct {
+ t *testing.T
+ f connectionFixture
+}
+
+func (p fakeBugPreparer) Prepare(_ context.Context, target equipo.TargetBinding) (equipo.PreparedBug, error) {
+ if scalar(p.t, p.f.d, "SELECT count(*) FROM tasks") != 1 || scalar(p.t, p.f.d, "SELECT count(*) FROM task_outboxes WHERE state='prepare'") != 1 || scalar(p.t, p.f.d, "SELECT count(*) FROM audit_events WHERE kind='task.create'") != 1 {
+ p.t.Fatal("preparation before durable request")
+ }
+ if target.Repository != p.f.project.Repository || target.DefaultRef != p.f.project.DefaultBranch {
+ p.t.Fatal("wrong preparation target")
+ }
+ return bugPrepared(p.f), nil
+}
+func TestBugPreparationFake(t *testing.T) {
+ f := bugFixture(t)
+ task := bugTask(t, f)
+ var preparer equipo.BugPreparer = fakeBugPreparer{t, f}
+ observed, err := preparer.Prepare(connectionContext, equipo.TargetBinding{Kind: team.TargetRepository, Repository: f.project.Repository, DefaultRef: f.project.DefaultBranch, Ref: task.ReviewRef})
+ executionMust(t, err)
+ _, err = f.s.PrepareBug(connectionContext, f.principal, task.ID, task.Revision, observed)
+ executionMust(t, err)
+}
+
+func attachBugExecution(t *testing.T, f connectionFixture) *equipo.Execution {
+ t.Helper()
+ var seq int
+ var name, path string
+ executionMust(t, f.d.Writer().QueryRow("PRAGMA database_list").Scan(&seq, &name, &path))
+ x, err := f.s.AttachExecution(connectionContext, path, team.Options{Clock: f.clock, Authority: equipo.NewAuthority(f.s, f.clock)})
+ executionMust(t, err)
+ t.Cleanup(func() { x.Core.Close() })
+ _, err = x.Core.Resume(connectionContext)
+ executionMust(t, err)
+ return x
+}
+func TestBugStartGuards(t *testing.T) {
+ for _, guard := range []string{"project", "choice", "review", "requester", "credential", "revision", "budget"} {
+ t.Run(guard, func(t *testing.T) {
+ f := bugFixture(t)
+ task := bugTask(t, f)
+ task, err := f.s.PrepareBug(connectionContext, f.principal, task.ID, task.Revision, bugPrepared(f))
+ executionMust(t, err)
+ attachBugExecution(t, f)
+ switch guard {
+ case "project":
+ mustSQL(t, f.d, "UPDATE projects SET revision=revision+1")
+ case "choice":
+ mustSQL(t, f.d, "UPDATE connection_choices SET revision=revision+1")
+ case "review":
+ mustSQL(t, f.d, "UPDATE task_outboxes SET review=json_set(review,'$.Revision',99)")
+ case "requester":
+ mustSQL(t, f.d, "UPDATE members SET active=0 WHERE address=?", ownerAddress)
+ case "credential":
+ mustSQL(t, f.d, "UPDATE runner_credentials SET revoked_at=?", f.clock.Now())
+ case "revision":
+ task.Revision++
+ case "budget":
+ mustSQL(t, f.d, "DELETE FROM budget_records")
+ }
+ if _, err := f.s.StartBug(connectionContext, f.principal, task.ID, task.Revision); err == nil {
+ t.Fatal("stale preparation started", guard)
+ }
+ if scalar(t, f.d, "SELECT count(*) FROM jobs") != 0 {
+ t.Fatal("job created before current checks")
+ }
+ })
+ }
+}
+func TestJobRequestKeySharedSchema(t *testing.T) {
+ for _, missing := range []string{"index", "column"} {
+ t.Run(missing, func(t *testing.T) {
+ d, path := executionDB(t)
+ mustSQL(t, d, "DROP INDEX jobs_request")
+ if missing == "column" {
+ mustSQL(t, d, "ALTER TABLE jobs DROP COLUMN request_hash")
+ mustSQL(t, d, "CREATE UNIQUE INDEX jobs_request ON jobs(account,requester,request_key) WHERE request_key <> ''")
+ }
+ x, err := equipo.NewStore(d).AttachExecution(connectionContext, path, executionOptions())
+ if err == nil {
+ x.Core.Close()
+ t.Fatal("incomplete v6 schema opened", missing)
+ }
+ })
+ }
+}
+
+func TestBugReviewUsesSelectedMachine(t *testing.T) {
+ f := bugFixture(t)
+ code, key := beginDevice(t, f.s)
+ approveDevice(t, f.s, code, ownerAddress)
+ credential := claimDevice(t, f.s, code, key)
+ p, err := f.s.AuthenticateRunner(connectionContext, credential.Token)
+ executionMust(t, err)
+ executionMust(t, f.s.ReportConnections(connectionContext, p, []equipo.ConnectionReport{f.reports[1]}))
+ // Make the other machine's eligible reviewer sort first, independent of random IDs.
+ mustSQL(t, f.d, "UPDATE connections SET id='000-other-reviewer' WHERE runner_id=?", p.RunnerID)
+ executionMust(t, f.s.AcknowledgeUnconfined(connectionContext, ownerActor, "000-other-reviewer", 1))
+ executionMust(t, f.s.SaveConnectionChoice(connectionContext, ownerActor, equipo.ConnectionChoice{ProjectID: f.project.ID, Revision: 1, ConnectionIDs: []string{f.ids["claude"], f.ids["codex"], "000-other-reviewer"}, PinnedID: f.ids["claude"]}))
+ task := bugTask(t, f)
+ var review string
+ executionMust(t, f.d.Writer().QueryRow("SELECT review FROM task_outboxes WHERE task_id=?", task.ID).Scan(&review))
+ var selected equipo.Selection
+ executionMust(t, json.Unmarshal([]byte(review), &selected))
+ if selected.RunnerID != f.principal.RunnerID || selected.ConnectionID != f.ids["codex"] {
+ t.Fatal("review crossed selected machine", selected)
+ }
+ _, err = f.s.PrepareBug(connectionContext, f.principal, task.ID, task.Revision, bugPrepared(f))
+ executionMust(t, err)
+}
+
+func TestFixedBugPlanRejectsZeroProject(t *testing.T) {
+ f := bugFixture(t)
+ task := bugTask(t, f)
+ task, err := f.s.PrepareBug(connectionContext, f.principal, task.ID, task.Revision, bugPrepared(f))
+ executionMust(t, err)
+ policy, err := team.RunnerPolicy("subscription", team.Limits{Calls: 24, InputTokens: 200000, OutputTokens: 40000}, team.Limits{Calls: 1, InputTokens: 32000, OutputTokens: 4000}, team.Rates{})
+ executionMust(t, err)
+ task.ProjectID = 0
+ f.project.ID = 0
+ if _, err := equipo.BugJobSpec(task, f.project, policy, task.Description); err == nil {
+ t.Fatal("zero project produced an empty grant")
+ }
+}