package runner import ( "context" "encoding/json" "errors" "path/filepath" "strings" "time" "amadan.net/oficina/equipo/internal/equipo/team" "amadan.net/oficina/equipo/internal/runner/checks" "amadan.net/oficina/equipo/internal/runner/containment" "amadan.net/oficina/equipo/internal/runner/forge" "amadan.net/oficina/equipo/internal/runner/planflow" "amadan.net/oficina/equipo/internal/runner/provider" "amadan.net/oficina/equipo/internal/runner/workspace" "amadan.net/oficina/equipo/internal/runnerproto" ) type BugWorkflowConfig struct { UploadBlob func(context.Context, RunClaim, string, []byte) error Launchers map[string]provider.Launcher Namespaces *containment.Manager Launch func(context.Context, RunClaim, workspace.Workspace, *ToolProxy) (provider.Launch, func() error, error) Workspaces *workspace.Manager Witness *Witness Policy func(context.Context, provider.Selection) (provider.ReadPolicy, error) Executor func(context.Context, RunClaim, checks.Definition, checks.Reproduction, time.Time) (*checks.Executor, error) Publisher *forge.Publisher PublisherFor func(context.Context, runnerproto.PublicationAuthorization) (*forge.Publisher, error) StateDir, Executable, InstanceID string Copy ToolCopy } type PlanWorkflow struct{ cfg BugWorkflowConfig } type BugWorkflow = PlanWorkflow func NewBugWorkflow(c BugWorkflowConfig) (*BugWorkflow, error) { return NewPlanWorkflow(c) } func (w *PlanWorkflow) Run(ctx context.Context, s *Supervisor, c RunClaim) error { if s == nil || s.workflow != w { return provider.ErrContract } return s.Run(ctx, c) } func NewPlanWorkflow(c BugWorkflowConfig) (*PlanWorkflow, error) { 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 == "" { return nil, provider.ErrContract } return &BugWorkflow{cfg: c}, nil } func selection(a runnerproto.Assignment) provider.Selection { return provider.Selection{ConnectionID: a.Selection.ConnectionID, Provider: a.Selection.Provider, Family: a.Selection.Family, Model: a.Selection.Model, AccountID: a.Selection.AccountID} } func (w *BugWorkflow) run(ctx context.Context, s *Supervisor, r *attemptState, l *leaseGuard) (runErr error) { defer func() { if runErr != nil { runErr = errors.Join(runErr, context.Cause(ctx)) } }() if r.Direct { ctx = s.namespaceContext(ctx, r) key := attemptKey(r.Claim.Scope, r.Claim.Handle) if err := s.namespaceEvent(ctx, r, "namespace.owner", key, key, map[string]string{"owner": key}); err != nil { return err } } if r.Claim.Assignment.Kind == "prepare" { 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()}} if err := s.save(ctx, r); err != nil { return err } prepared, err := w.cfg.Witness.PrepareBug(ctx, w.cfg.Workspaces, r.Claim.Assignment, r.Claim.Brief.Target) if err != nil { return err } q := r.request("prepare") q.Prepared, err = json.Marshal(prepared) if err != nil { return err } s.stopLeaseWatch() if err = s.api.Call(ctx, "prepare", q, nil); err != nil { return err } r.Phase = "prepared" return s.save(ctx, r) } if r.Claim.Brief.Step.PlanRevision == 0 { r.Claim.Brief.Step = planflow.LegacyStep(r.Claim.Assignment.StepKey) r.Claim.Brief.Step.ArtifactHashes = append([]string(nil), r.Claim.Brief.ArtifactHashes...) } profile, err := planflow.Validate(r.Claim.Assignment, r.Claim.Brief) if err != nil { return err } step := profile.Action readWork := r.Claim.Brief.Target.Kind == team.TargetProjectRead if readWork && profile.Submission != "submit_answer" { return provider.ErrPolicy } 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()}} r.Phase = "creating-workspace" if err := s.save(ctx, r); err != nil { return err } ws, err := w.cfg.Workspaces.Create(ctx, r.Claim.Assignment, r.Claim.Brief) if err != nil { return err } r.Owner = ProcessOwner{Attempt: r.Claim.Handle.Attempt, Fence: r.Claim.Handle.Fence, Marker: attemptKey(r.Claim.Scope, r.Claim.Handle), Workspace: ws.Record} r.Phase = "workspace" if err = s.save(ctx, r); err != nil { return err } r.WorkspacePath = ws.Path if err = s.save(ctx, r); err != nil { return err } policy, err := w.cfg.Policy(ctx, selection(r.Claim.Assignment)) if err != nil { return err } current := func(ctx context.Context) error { _, err := l.checkClock(s.clock) if err != nil { return err } if err = retryAuthority(ctx, func() error { return remoteError(w.cfg.Workspaces.ValidateTurn(ctx, r.Claim.Assignment, ws)) }); err != nil { return err } if err = retryAuthority(ctx, func() error { return s.api.Call(ctx, "validate", r.request("validate"), nil) }); err != nil { return err } return nil } s.mu.Lock() s.activeCurrent = current s.mu.Unlock() var artifacts []team.Artifact if err = s.api.Call(ctx, "evidence", r.request("evidence"), &artifacts); err != nil { return err } for i, art := range artifacts { q := r.request("evidence") q.ArtifactID = art.ID var full team.Artifact if err = s.api.Call(ctx, "evidence", q, &full); err != nil { return err } if full.ID != art.ID || full.Hash != art.Hash || team.ContentDigest(full.Payload) != art.Hash { return provider.ErrIdentity } artifacts[i] = full } if err = planflow.Artifacts(r.Claim.Brief, artifacts); err != nil { return err } var definition checks.Definition if !readWork && json.Unmarshal(r.Claim.Brief.CheckDefinition, &definition) != nil { return provider.ErrIdentity } var reproduction checks.Reproduction var candidate team.GitCandidate var candidateHash string for _, a := range artifacts { switch a.Role { case team.RoleReproduction, team.RoleAcceptance: if json.Unmarshal(a.Payload, &reproduction) != nil { return provider.ErrIdentity } case team.RoleCandidate: if json.Unmarshal(a.Payload, &candidate) != nil { return provider.ErrIdentity } candidateHash = a.Hash } } if step == "review" || (profile.Render && candidateHash != "") { if candidateHash == "" { return provider.ErrIdentity } if err = w.cfg.Workspaces.ContinueCandidate(ctx, ws, candidate, profile.Render); err != nil { return err } } if profile.Submission != "" { if err = w.directModel(ctx, s, r, l, current, ws, policy, artifacts); err != nil { return err } } if err = current(ctx); err != nil { return err } register := func(role team.Role, value any) (team.Artifact, error) { raw, err := json.Marshal(value) if err != nil { return team.Artifact{}, err } spec := team.ArtifactSpec{Role: role, MediaType: "application/json", Payload: raw} if role == team.RoleRender || role == team.RoleBaseResult || role == team.RoleCandidateResult || role == team.RoleRepositoryChecks { if _, err = w.cfg.Witness.ExecutorEvidence(ctx, nil, r.Claim.Scope, r.Claim.Handle, spec); err != nil { return team.Artifact{}, err } } if role == team.RoleCandidate { spec.MediaType = team.GitCandidateMediaType } if role == team.RoleAnswer { if err = w.cfg.Witness.record(ctx, "read-answer", attemptKey(r.Claim.Scope, r.Claim.Handle), spec); err != nil { return team.Artifact{}, err } } if err = w.cfg.Witness.recordArtifact(ctx, r.Claim, spec); err != nil { return team.Artifact{}, err } q := r.request("artifact-" + string(role)) q.Artifact = &spec var result team.Artifact err = s.api.Call(ctx, "artifacts", q, &result) return result, err } if profile.Submission != "" { tools, err := s.journal.ToolSubmissions(ctx, 128) if err != nil { return err } var submission *ToolSubmission want := profile.Submission for i := range tools { t := &tools[i] 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 { if submission != nil { return provider.ErrIdentity } submission = t } } if submission == nil { return provider.ErrUncertain } switch profile.Submission { case "submit_reproduction", "submit_acceptance": if err = json.Unmarshal(submission.Arguments, &reproduction); err != nil { return err } role := team.RoleReproduction if step == "scope" { role = team.RoleAcceptance } art, err := register(role, reproduction) if err != nil { return err } q := r.request("freeze") q.Prepared, _ = json.Marshal(runnerproto.FreezeRequest{ExpectedSymptom: reproduction.ExpectedSymptom, DefinitionHash: checks.Digest(marshal(definition)), ReproductionHash: art.Hash}) if err = s.api.Call(ctx, map[bool]string{true: "freeze_feature", false: "freeze"}[step == "scope"], q, nil); err != nil { return err } case "submit_candidate": var submitted CandidateSubmission if json.Unmarshal(submission.Arguments, &submitted) != nil { return provider.ErrIdentity } candidate, err = w.cfg.Workspaces.CaptureCandidate(ctx, ws, r.Claim.Brief.Target) if err != nil { return err } if candidate.Commit != submitted.Commit { return provider.ErrIdentity } art, err := register(team.RoleCandidate, candidate) if err != nil { return err } if err = w.renderRequested(ctx, s, r, tools, candidate, art.Hash, definition, reproduction, register); err != nil { return err } case "submit_answer": r.Phase = "delivering-answer" if err = s.save(ctx, r); err != nil { return err } s.stopLeaseWatch() var answer team.AnswerResult if json.Unmarshal(submission.Arguments, &answer) != nil { return provider.ErrIdentity } if _, err = register(team.RoleAnswer, answer); err != nil { return err } case "submit_review": var review ReviewSubmission if json.Unmarshal(submission.Arguments, &review) != nil || review.Candidate != candidate.Commit { return provider.ErrIdentity } if _, err = register(team.RoleReview, team.Review{SubjectHash: candidateHash, Verdict: reviewVerdict(review.Decision), Notes: strings.Join(review.Findings, "\n")}); err != nil { return err } if review.Decision != string(team.VerdictApprove) { return team.ErrEvidence } } if err = s.journal.AckTool(ctx, *submission); err != nil { return err } if readWork { r.Phase = "completed" return s.save(ctx, r) } } if step == "checks" || step == "publish" { 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)} if err = w.cfg.Witness.record(ctx, "runner-provenance", attemptKey(r.Claim.Scope, r.Claim.Handle), provenance); err != nil { return err } } if step == "reproduce" || step == "scope" || step == "checks" { executor, err := w.cfg.Executor(ctx, r.Claim, definition, reproduction, r.Claim.AttemptDeadline) if err != nil { return err } w.cfg.Witness.installExecutor(r.Claim, executor) commit, subject := definition.Base, "" role := team.RoleBaseResult if step == "checks" { commit, subject, role = candidate.Commit, candidateHash, team.RoleCandidateResult } result, err := executor.Reproduce(ctx, definition, reproduction, commit, subject) if err != nil { return err } if _, err = register(role, result); err != nil { return err } if step == "checks" { result, err := executor.RepositoryChecks(ctx, definition, candidate, candidateHash) if err != nil { return err } if _, err = register(team.RoleRepositoryChecks, result); err != nil { return err } } } if step == "publish" { if err = w.publish(ctx, s, r, current); err != nil { return err } } if err = current(ctx); err != nil { return err } r.Phase = "completing" if err = s.save(ctx, r); err != nil { return err } q := r.request("complete") q.Result = &team.AttemptResult{Outcome: team.OutcomeSuccess} s.stopLeaseWatch() if err = s.api.Call(ctx, "complete", q, nil); err != nil { return err } r.Phase = "completed" return s.save(ctx, r) } func marshal(v any) []byte { b, _ := json.Marshal(v); return b } func reviewVerdict(decision string) team.Verdict { if decision == "approve" { return team.VerdictApprove } return team.VerdictReject } type attemptCancellation struct { operation string cause error } func (e attemptCancellation) Error() string { return string(marshal(map[string]string{"operation": e.operation, "cause": e.cause.Error()})) } func (e attemptCancellation) Unwrap() error { return e.cause }