| 1 | package runner |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "encoding/json" |
| 6 | "errors" |
| 7 | "path/filepath" |
| 8 | "strings" |
| 9 | "time" |
| 10 | |
| 11 | "amadan.net/oficina/equipo/internal/equipo/team" |
| 12 | "amadan.net/oficina/equipo/internal/runner/checks" |
| 13 | "amadan.net/oficina/equipo/internal/runner/containment" |
| 14 | "amadan.net/oficina/equipo/internal/runner/forge" |
| 15 | |
| 16 | "amadan.net/oficina/equipo/internal/runner/planflow" |
| 17 | "amadan.net/oficina/equipo/internal/runner/provider" |
| 18 | "amadan.net/oficina/equipo/internal/runner/workspace" |
| 19 | "amadan.net/oficina/equipo/internal/runnerproto" |
| 20 | ) |
| 21 | |
| 22 | type BugWorkflowConfig struct { |
| 23 | UploadBlob func(context.Context, RunClaim, string, []byte) error |
| 24 | Launchers map[string]provider.Launcher |
| 25 | Namespaces *containment.Manager |
| 26 | Launch func(context.Context, RunClaim, workspace.Workspace, *ToolProxy) (provider.Launch, func() error, error) |
| 27 | |
| 28 | Workspaces *workspace.Manager |
| 29 | Witness *Witness |
| 30 | Policy func(context.Context, provider.Selection) (provider.ReadPolicy, error) |
| 31 | Executor func(context.Context, RunClaim, checks.Definition, checks.Reproduction, time.Time) (*checks.Executor, error) |
| 32 | Publisher *forge.Publisher |
| 33 | PublisherFor func(context.Context, runnerproto.PublicationAuthorization) (*forge.Publisher, error) |
| 34 | StateDir, Executable, InstanceID string |
| 35 | Copy ToolCopy |
| 36 | } |
| 37 | type PlanWorkflow struct{ cfg BugWorkflowConfig } |
| 38 | type BugWorkflow = PlanWorkflow |
| 39 | |
| 40 | func NewBugWorkflow(c BugWorkflowConfig) (*BugWorkflow, error) { return NewPlanWorkflow(c) } |
| 41 | func (w *PlanWorkflow) Run(ctx context.Context, s *Supervisor, c RunClaim) error { |
| 42 | if s == nil || s.workflow != w { |
| 43 | return provider.ErrContract |
| 44 | } |
| 45 | return s.Run(ctx, c) |
| 46 | } |
| 47 | |
| 48 | func NewPlanWorkflow(c BugWorkflowConfig) (*PlanWorkflow, error) { |
| 49 | if c.Workspaces == nil || (len(c.Launchers) != 2 || c.Launchers["claude"] == nil || c.Launchers["codex"] == nil || c.Namespaces == nil || c.Launch == nil) || c.Witness == nil || c.Policy == nil || c.Executor == nil || (c.Publisher == nil && c.PublisherFor == nil) || !filepath.IsAbs(c.StateDir) || filepath.Clean(c.StateDir) != c.StateDir || !filepath.IsAbs(c.Executable) || filepath.Clean(c.Executable) != c.Executable || c.InstanceID == "" { |
| 50 | return nil, provider.ErrContract |
| 51 | } |
| 52 | return &BugWorkflow{cfg: c}, nil |
| 53 | } |
| 54 | func selection(a runnerproto.Assignment) provider.Selection { |
| 55 | return provider.Selection{ConnectionID: a.Selection.ConnectionID, Provider: a.Selection.Provider, Family: a.Selection.Family, Model: a.Selection.Model, AccountID: a.Selection.AccountID} |
| 56 | } |
| 57 | func (w *BugWorkflow) run(ctx context.Context, s *Supervisor, r *attemptState, l *leaseGuard) (runErr error) { |
| 58 | defer func() { |
| 59 | if runErr != nil { |
| 60 | runErr = errors.Join(runErr, context.Cause(ctx)) |
| 61 | } |
| 62 | }() |
| 63 | if r.Direct { |
| 64 | ctx = s.namespaceContext(ctx, r) |
| 65 | key := attemptKey(r.Claim.Scope, r.Claim.Handle) |
| 66 | if err := s.namespaceEvent(ctx, r, "namespace.owner", key, key, map[string]string{"owner": key}); err != nil { |
| 67 | return err |
| 68 | } |
| 69 | } |
| 70 | if r.Claim.Assignment.Kind == "prepare" { |
| 71 | r.Owner = ProcessOwner{LocalOnly: true, Attempt: r.Claim.Handle.Attempt, Fence: r.Claim.Handle.Fence, Marker: r.Claim.Assignment.ID, Workspace: provider.Workspace{Path: w.cfg.Workspaces.PreparationDirectory()}} |
| 72 | if err := s.save(ctx, r); err != nil { |
| 73 | return err |
| 74 | } |
| 75 | |
| 76 | prepared, err := w.cfg.Witness.PrepareBug(ctx, w.cfg.Workspaces, r.Claim.Assignment, r.Claim.Brief.Target) |
| 77 | if err != nil { |
| 78 | return err |
| 79 | } |
| 80 | q := r.request("prepare") |
| 81 | q.Prepared, err = json.Marshal(prepared) |
| 82 | if err != nil { |
| 83 | return err |
| 84 | } |
| 85 | s.stopLeaseWatch() |
| 86 | if err = s.api.Call(ctx, "prepare", q, nil); err != nil { |
| 87 | return err |
| 88 | } |
| 89 | r.Phase = "prepared" |
| 90 | return s.save(ctx, r) |
| 91 | } |
| 92 | if r.Claim.Brief.Step.PlanRevision == 0 { |
| 93 | r.Claim.Brief.Step = planflow.LegacyStep(r.Claim.Assignment.StepKey) |
| 94 | r.Claim.Brief.Step.ArtifactHashes = append([]string(nil), r.Claim.Brief.ArtifactHashes...) |
| 95 | } |
| 96 | profile, err := planflow.Validate(r.Claim.Assignment, r.Claim.Brief) |
| 97 | if err != nil { |
| 98 | return err |
| 99 | } |
| 100 | step := profile.Action |
| 101 | readWork := r.Claim.Brief.Target.Kind == team.TargetProjectRead |
| 102 | if readWork && profile.Submission != "submit_answer" { |
| 103 | return provider.ErrPolicy |
| 104 | } |
| 105 | r.Owner = ProcessOwner{LocalOnly: true, Attempt: r.Claim.Handle.Attempt, Fence: r.Claim.Handle.Fence, Marker: attemptKey(r.Claim.Scope, r.Claim.Handle), Workspace: provider.Workspace{Path: w.cfg.Workspaces.PreparationDirectory()}} |
| 106 | r.Phase = "creating-workspace" |
| 107 | if err := s.save(ctx, r); err != nil { |
| 108 | return err |
| 109 | } |
| 110 | |
| 111 | ws, err := w.cfg.Workspaces.Create(ctx, r.Claim.Assignment, r.Claim.Brief) |
| 112 | if err != nil { |
| 113 | return err |
| 114 | } |
| 115 | r.Owner = ProcessOwner{Attempt: r.Claim.Handle.Attempt, Fence: r.Claim.Handle.Fence, Marker: attemptKey(r.Claim.Scope, r.Claim.Handle), Workspace: ws.Record} |
| 116 | r.Phase = "workspace" |
| 117 | if err = s.save(ctx, r); err != nil { |
| 118 | return err |
| 119 | } |
| 120 | |
| 121 | r.WorkspacePath = ws.Path |
| 122 | if err = s.save(ctx, r); err != nil { |
| 123 | return err |
| 124 | } |
| 125 | |
| 126 | policy, err := w.cfg.Policy(ctx, selection(r.Claim.Assignment)) |
| 127 | if err != nil { |
| 128 | return err |
| 129 | } |
| 130 | current := func(ctx context.Context) error { |
| 131 | _, err := l.checkClock(s.clock) |
| 132 | if err != nil { |
| 133 | return err |
| 134 | } |
| 135 | if err = retryAuthority(ctx, func() error { return remoteError(w.cfg.Workspaces.ValidateTurn(ctx, r.Claim.Assignment, ws)) }); err != nil { |
| 136 | return err |
| 137 | } |
| 138 | if err = retryAuthority(ctx, func() error { return s.api.Call(ctx, "validate", r.request("validate"), nil) }); err != nil { |
| 139 | return err |
| 140 | } |
| 141 | return nil |
| 142 | } |
| 143 | s.mu.Lock() |
| 144 | s.activeCurrent = current |
| 145 | s.mu.Unlock() |
| 146 | var artifacts []team.Artifact |
| 147 | if err = s.api.Call(ctx, "evidence", r.request("evidence"), &artifacts); err != nil { |
| 148 | return err |
| 149 | } |
| 150 | for i, art := range artifacts { |
| 151 | q := r.request("evidence") |
| 152 | q.ArtifactID = art.ID |
| 153 | var full team.Artifact |
| 154 | if err = s.api.Call(ctx, "evidence", q, &full); err != nil { |
| 155 | return err |
| 156 | } |
| 157 | if full.ID != art.ID || full.Hash != art.Hash || team.ContentDigest(full.Payload) != art.Hash { |
| 158 | return provider.ErrIdentity |
| 159 | } |
| 160 | artifacts[i] = full |
| 161 | } |
| 162 | if err = planflow.Artifacts(r.Claim.Brief, artifacts); err != nil { |
| 163 | return err |
| 164 | } |
| 165 | var definition checks.Definition |
| 166 | if !readWork && json.Unmarshal(r.Claim.Brief.CheckDefinition, &definition) != nil { |
| 167 | return provider.ErrIdentity |
| 168 | } |
| 169 | var reproduction checks.Reproduction |
| 170 | var candidate team.GitCandidate |
| 171 | var candidateHash string |
| 172 | for _, a := range artifacts { |
| 173 | switch a.Role { |
| 174 | case team.RoleReproduction, team.RoleAcceptance: |
| 175 | if json.Unmarshal(a.Payload, &reproduction) != nil { |
| 176 | return provider.ErrIdentity |
| 177 | } |
| 178 | case team.RoleCandidate: |
| 179 | if json.Unmarshal(a.Payload, &candidate) != nil { |
| 180 | return provider.ErrIdentity |
| 181 | } |
| 182 | candidateHash = a.Hash |
| 183 | } |
| 184 | } |
| 185 | if step == "review" || (profile.Render && candidateHash != "") { |
| 186 | if candidateHash == "" { |
| 187 | return provider.ErrIdentity |
| 188 | } |
| 189 | if err = w.cfg.Workspaces.ContinueCandidate(ctx, ws, candidate, profile.Render); err != nil { |
| 190 | return err |
| 191 | } |
| 192 | } |
| 193 | |
| 194 | if profile.Submission != "" { |
| 195 | if err = w.directModel(ctx, s, r, l, current, ws, policy, artifacts); err != nil { |
| 196 | return err |
| 197 | } |
| 198 | } |
| 199 | if err = current(ctx); err != nil { |
| 200 | return err |
| 201 | } |
| 202 | register := func(role team.Role, value any) (team.Artifact, error) { |
| 203 | raw, err := json.Marshal(value) |
| 204 | if err != nil { |
| 205 | return team.Artifact{}, err |
| 206 | } |
| 207 | spec := team.ArtifactSpec{Role: role, MediaType: "application/json", Payload: raw} |
| 208 | if role == team.RoleRender || role == team.RoleBaseResult || role == team.RoleCandidateResult || role == team.RoleRepositoryChecks { |
| 209 | if _, err = w.cfg.Witness.ExecutorEvidence(ctx, nil, r.Claim.Scope, r.Claim.Handle, spec); err != nil { |
| 210 | return team.Artifact{}, err |
| 211 | } |
| 212 | } |
| 213 | if role == team.RoleCandidate { |
| 214 | spec.MediaType = team.GitCandidateMediaType |
| 215 | } |
| 216 | if role == team.RoleAnswer { |
| 217 | if err = w.cfg.Witness.record(ctx, "read-answer", attemptKey(r.Claim.Scope, r.Claim.Handle), spec); err != nil { |
| 218 | return team.Artifact{}, err |
| 219 | } |
| 220 | } |
| 221 | if err = w.cfg.Witness.recordArtifact(ctx, r.Claim, spec); err != nil { |
| 222 | return team.Artifact{}, err |
| 223 | } |
| 224 | q := r.request("artifact-" + string(role)) |
| 225 | q.Artifact = &spec |
| 226 | var result team.Artifact |
| 227 | err = s.api.Call(ctx, "artifacts", q, &result) |
| 228 | return result, err |
| 229 | } |
| 230 | if profile.Submission != "" { |
| 231 | tools, err := s.journal.ToolSubmissions(ctx, 128) |
| 232 | if err != nil { |
| 233 | return err |
| 234 | } |
| 235 | var submission *ToolSubmission |
| 236 | want := profile.Submission |
| 237 | for i := range tools { |
| 238 | t := &tools[i] |
| 239 | if t.Attempt == int64(r.Claim.Handle.Attempt) && t.Fence == r.Claim.Handle.Fence && t.TaskID == r.Claim.Assignment.TaskID && t.Agent == r.Agent && t.Name == want { |
| 240 | if submission != nil { |
| 241 | return provider.ErrIdentity |
| 242 | } |
| 243 | submission = t |
| 244 | } |
| 245 | } |
| 246 | if submission == nil { |
| 247 | return provider.ErrUncertain |
| 248 | } |
| 249 | switch profile.Submission { |
| 250 | case "submit_reproduction", "submit_acceptance": |
| 251 | if err = json.Unmarshal(submission.Arguments, &reproduction); err != nil { |
| 252 | return err |
| 253 | } |
| 254 | role := team.RoleReproduction |
| 255 | if step == "scope" { |
| 256 | role = team.RoleAcceptance |
| 257 | } |
| 258 | art, err := register(role, reproduction) |
| 259 | if err != nil { |
| 260 | return err |
| 261 | } |
| 262 | q := r.request("freeze") |
| 263 | q.Prepared, _ = json.Marshal(runnerproto.FreezeRequest{ExpectedSymptom: reproduction.ExpectedSymptom, DefinitionHash: checks.Digest(marshal(definition)), ReproductionHash: art.Hash}) |
| 264 | if err = s.api.Call(ctx, map[bool]string{true: "freeze_feature", false: "freeze"}[step == "scope"], q, nil); err != nil { |
| 265 | return err |
| 266 | } |
| 267 | case "submit_candidate": |
| 268 | var submitted CandidateSubmission |
| 269 | if json.Unmarshal(submission.Arguments, &submitted) != nil { |
| 270 | return provider.ErrIdentity |
| 271 | } |
| 272 | candidate, err = w.cfg.Workspaces.CaptureCandidate(ctx, ws, r.Claim.Brief.Target) |
| 273 | if err != nil { |
| 274 | return err |
| 275 | } |
| 276 | if candidate.Commit != submitted.Commit { |
| 277 | return provider.ErrIdentity |
| 278 | } |
| 279 | art, err := register(team.RoleCandidate, candidate) |
| 280 | if err != nil { |
| 281 | return err |
| 282 | } |
| 283 | if err = w.renderRequested(ctx, s, r, tools, candidate, art.Hash, definition, reproduction, register); err != nil { |
| 284 | return err |
| 285 | } |
| 286 | case "submit_answer": |
| 287 | r.Phase = "delivering-answer" |
| 288 | if err = s.save(ctx, r); err != nil { |
| 289 | return err |
| 290 | } |
| 291 | s.stopLeaseWatch() |
| 292 | var answer team.AnswerResult |
| 293 | if json.Unmarshal(submission.Arguments, &answer) != nil { |
| 294 | return provider.ErrIdentity |
| 295 | } |
| 296 | if _, err = register(team.RoleAnswer, answer); err != nil { |
| 297 | return err |
| 298 | } |
| 299 | |
| 300 | case "submit_review": |
| 301 | var review ReviewSubmission |
| 302 | if json.Unmarshal(submission.Arguments, &review) != nil || review.Candidate != candidate.Commit { |
| 303 | return provider.ErrIdentity |
| 304 | } |
| 305 | if _, err = register(team.RoleReview, team.Review{SubjectHash: candidateHash, Verdict: reviewVerdict(review.Decision), Notes: strings.Join(review.Findings, "\n")}); err != nil { |
| 306 | return err |
| 307 | } |
| 308 | if review.Decision != string(team.VerdictApprove) { |
| 309 | return team.ErrEvidence |
| 310 | } |
| 311 | } |
| 312 | if err = s.journal.AckTool(ctx, *submission); err != nil { |
| 313 | return err |
| 314 | } |
| 315 | if readWork { |
| 316 | r.Phase = "completed" |
| 317 | return s.save(ctx, r) |
| 318 | } |
| 319 | } |
| 320 | if step == "checks" || step == "publish" { |
| 321 | provenance := team.Provenance{Producer: "equipo-runner", Provider: r.Claim.Assignment.Selection.Provider, ModelFamily: r.Claim.Assignment.Selection.Family, Context: attemptKey(r.Claim.Scope, r.Claim.Handle)} |
| 322 | if err = w.cfg.Witness.record(ctx, "runner-provenance", attemptKey(r.Claim.Scope, r.Claim.Handle), provenance); err != nil { |
| 323 | return err |
| 324 | } |
| 325 | } |
| 326 | if step == "reproduce" || step == "scope" || step == "checks" { |
| 327 | |
| 328 | executor, err := w.cfg.Executor(ctx, r.Claim, definition, reproduction, r.Claim.AttemptDeadline) |
| 329 | if err != nil { |
| 330 | return err |
| 331 | } |
| 332 | w.cfg.Witness.installExecutor(r.Claim, executor) |
| 333 | commit, subject := definition.Base, "" |
| 334 | role := team.RoleBaseResult |
| 335 | if step == "checks" { |
| 336 | commit, subject, role = candidate.Commit, candidateHash, team.RoleCandidateResult |
| 337 | } |
| 338 | result, err := executor.Reproduce(ctx, definition, reproduction, commit, subject) |
| 339 | if err != nil { |
| 340 | return err |
| 341 | } |
| 342 | if _, err = register(role, result); err != nil { |
| 343 | return err |
| 344 | } |
| 345 | if step == "checks" { |
| 346 | result, err := executor.RepositoryChecks(ctx, definition, candidate, candidateHash) |
| 347 | if err != nil { |
| 348 | return err |
| 349 | } |
| 350 | if _, err = register(team.RoleRepositoryChecks, result); err != nil { |
| 351 | return err |
| 352 | } |
| 353 | } |
| 354 | } |
| 355 | if step == "publish" { |
| 356 | if err = w.publish(ctx, s, r, current); err != nil { |
| 357 | return err |
| 358 | } |
| 359 | } |
| 360 | if err = current(ctx); err != nil { |
| 361 | return err |
| 362 | } |
| 363 | r.Phase = "completing" |
| 364 | if err = s.save(ctx, r); err != nil { |
| 365 | return err |
| 366 | } |
| 367 | q := r.request("complete") |
| 368 | q.Result = &team.AttemptResult{Outcome: team.OutcomeSuccess} |
| 369 | s.stopLeaseWatch() |
| 370 | if err = s.api.Call(ctx, "complete", q, nil); err != nil { |
| 371 | return err |
| 372 | } |
| 373 | r.Phase = "completed" |
| 374 | return s.save(ctx, r) |
| 375 | } |
| 376 | func marshal(v any) []byte { b, _ := json.Marshal(v); return b } |
| 377 | |
| 378 | func reviewVerdict(decision string) team.Verdict { |
| 379 | if decision == "approve" { |
| 380 | return team.VerdictApprove |
| 381 | } |
| 382 | return team.VerdictReject |
| 383 | } |
| 384 | |
| 385 | type attemptCancellation struct { |
| 386 | operation string |
| 387 | cause error |
| 388 | } |
| 389 | |
| 390 | func (e attemptCancellation) Error() string { |
| 391 | return string(marshal(map[string]string{"operation": e.operation, "cause": e.cause.Error()})) |
| 392 | } |
| 393 | func (e attemptCancellation) Unwrap() error { return e.cause } |
| 394 | |