package runner import ( "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/testci" "context" "database/sql" "encoding/json" "fmt" "os" "os/exec" "path/filepath" "strings" "testing" "time" "amadan.net/oficina/equipo/internal/runner/provider" "amadan.net/oficina/equipo/internal/runner/workspace" "amadan.net/oficina/equipo/internal/runnerproto" ) func runDirectBugGraph(t *testing.T) { runDirectPlanGraph(t, false, false, false) } func TestPlanWorkflowFeature(t *testing.T) { t.Parallel() runDirectPlanGraph(t, true, false, false) } func TestPlanWorkflowCandidateOrder(t *testing.T) { t.Parallel() runDirectPlanGraph(t, true, true, false) } func TestPlanWorkflowRecommendation(t *testing.T) { t.Parallel() runDirectPlanGraph(t, false, false, true) } func runDirectPlanGraph(t *testing.T, feature, extra, readWork bool) { ctx := context.Background() root, err := os.MkdirTemp(os.Getenv("TMPDIR"), "e15-") wfMust(t, err) t.Cleanup(func() { os.RemoveAll(root) }) state := filepath.Join(root, "s") private := filepath.Join(root, "p") works := filepath.Join(root, "w") scratch := filepath.Join(root, "c") seed := filepath.Join(root, "seed") for _, p := range []string{state, private, works, scratch, seed} { wfMust(t, os.Mkdir(p, 0700)) } j, err := OpenJournal(ctx, filepath.Join(state, "j.db")) wfMust(t, err) defer j.Close() w, err := NewWitness(j) wfMust(t, err) policy := provider.ReadPolicy{ConfigHash: strings.Repeat("a", 64), DeniedPaths: []string{state, private}} helper, err := os.Executable() wfMust(t, err) namespaces, err := containment.New(containment.Config{Binary: "/usr/bin/bwrap", RunnerBinary: helper, ScratchRoot: scratch, ProviderNetworks: []provider.NetworkContract{{Provider: "claude"}, {Provider: "codex"}}}) wfMust(t, err) _, err = j.ReconcileDirect(ctx, namespaces) wfMust(t, err) host := NewDirectHost(j, namespaces) // The original bug graph retains the capture backpressure exercise. // Plan variants need timeline events but do not repeat its volume test. progressFrames := 200 if feature || readWork { progressFrames = 2 } registry, launch := fakeDirectGraph(t, j, host, root, scratch, helper, progressFrames) wfMust(t, os.WriteFile(filepath.Join(seed, "go.mod"), []byte("module fixture\n\ngo 1.26.0\n"), 0600)) wfMust(t, os.WriteFile(filepath.Join(seed, "value.go"), []byte("package fixture\nfunc Value() int {return 1}\n"), 0600)) wfMust(t, os.WriteFile(filepath.Join(seed, "old_test.go"), []byte("package fixture\nimport \"testing\"\nfunc TestOld(t *testing.T) {}\n"), 0600)) cmd := runnerproto.CheckCommand{Argv: []string{"go", "test", "-json", "-count=1", "./..."}, Dir: ".", Parser: "go-test-json", TimeoutSeconds: 120} wfMust(t, os.Mkdir(filepath.Join(seed, ".equipo"), 0700)) definition := checks.Definition{Version: 1, Commands: []checks.Command{cmd}, Reproduction: cmd} if extra { definition.Render = &runnerproto.RenderRecipe{Version: 1, Command: checks.Command{Argv: []string{"sh", "render.sh"}, Dir: ".", Parser: "exit", TimeoutSeconds: 10}} definition.TrustedPaths = []string{"render.sh"} wfMust(t, os.WriteFile(filepath.Join(seed, "render.sh"), []byte("printf '%s' 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVQIHWP4z8DwHwAFgAI/ScLttAAAAABJRU5ErkJggg==' | base64 -d\n"), 0600)) } wfMust(t, os.WriteFile(filepath.Join(seed, ".equipo/checks.json"), marshal(definition), 0600)) wfGit(t, seed, "init", "-b", "main") wfGit(t, seed, "add", ".") wfGit(t, seed, "commit", "-m", "base") base := wfGit(t, seed, "rev-parse", "HEAD") remote := filepath.Join(root, "remote.git") wfGit(t, root, "clone", "--bare", seed, remote) protected := workspace.SecurityPaths{RunnerState: state, RunnerConfig: filepath.Join(state, "config"), Journal: filepath.Join(state, "j.db"), Bearer: filepath.Join(state, "bearer"), Cleanup: filepath.Join(state, "cleanup"), ForgeCredential: filepath.Join(state, "forge"), LegacyHome: filepath.Join(state, "paseo"), ProviderHomes: []string{filepath.Join(state, "provider")}, SSH: filepath.Join(state, "ssh")} testci.Tools(t, "codex", "bwrap", "python3", "git") codex, err := exec.LookPath("codex") wfMust(t, err) goCommand := exec.Command("go", "env", "GOROOT") goCommand.Env = append(os.Environ(), "GOROOT=", "GOTOOLCHAIN="+checks.GoVersion) goOutput, err := goCommand.Output() wfMust(t, err) goRoot := strings.TrimSpace(string(goOutput)) wfMust(t, os.Mkdir(filepath.Join(root, "modules"), 0700)) sandbox, err := checks.NewCodexSandbox(ctx, checks.SandboxConfig{Binary: codex, ScratchRoot: scratch, GoRoot: goRoot, GoBinary: filepath.Join(goRoot, "bin/go"), Protected: protected, Host: host, Bwrap: "/usr/bin/bwrap", RunnerBinary: helper, ModuleCache: filepath.Join(root, "modules")}) wfMust(t, err) iso := team.IsolationSnapshot{Status: "confined", ObservedTuples: []team.IsolationTuple{{Provider: "claude", ProviderVersion: "2.1.312", LauncherVersion: "direct-v2", BwrapVersion: "0.11.0", PolicyVersion: "direct-v1", IsolationConfigHash: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"}}} target := team.TargetBinding{Kind: team.TargetRepository, Repository: "amadan.net/test/fixture", DefaultRef: "main", Ref: "equipo/test", BaseRevision: base} var manager *workspace.Manager var pinned checks.Definition var repo string executorCalls := 0 executor := func(ctx context.Context, c RunClaim, d checks.Definition, r checks.Reproduction, deadline time.Time) (*checks.Executor, error) { executorCalls++ if c.Handle.Attempt > 0 && !deadline.Equal(c.AttemptDeadline) { return nil, fmt.Errorf("executor got lease snapshot instead of attempt deadline") } recipeHash := "" if d.Render != nil { recipeHash = checks.Digest(marshal(d.Render)) } return checks.New(checks.Config{RenderRecipeHash: recipeHash, ScratchRoot: works, Scope: c.Scope, Handle: c.Handle, Deadline: deadline, Policy: policy, DefinitionHash: checks.Digest(marshal(d)), ReproductionHash: checks.Digest(marshal(r)), Reproduction: func(context.Context, string) (checks.Reproduction, error) { return r, nil }, Isolation: func(context.Context) (team.IsolationSnapshot, error) { return c.Brief.Selection.Isolation, nil }, ResolveCandidate: func(ctx context.Context, hash string) (team.GitCandidate, error) { arts, err := apiArtifacts(ctx, w, c) if err != nil { return team.GitCandidate{}, err } for _, a := range arts { var v team.GitCandidate if a.Role == team.RoleCandidate && checks.CandidateHash(decodeCandidate(a.Payload)) == hash { json.Unmarshal(a.Payload, &v) return v, nil } } return team.GitCandidate{}, provider.ErrIdentity }, Export: func(ctx context.Context, commit, dest string) error { if commit == base { return checks.ExportBase(ctx, repo, base, dest) } arts, err := apiArtifacts(ctx, w, c) if err != nil { return err } for _, a := range arts { v := decodeCandidate(a.Payload) if a.Role == team.RoleCandidate && v.Commit == commit { return manager.ExportCandidate(ctx, v, dest) } } return provider.ErrIdentity }}, sandbox) } manager, err = workspace.New(workspace.Config{Protected: protected, PrivateRoot: private, WorkspaceRoot: works, GitPath: "/usr/bin/git", Forge: localRead{remote}, Policy: func(context.Context, provider.Selection) (provider.ReadPolicy, error) { return policy, nil }, Definitions: func(ctx context.Context, tgt team.TargetBinding, repository string) (runnerproto.PreparedBug, error) { repo = repository d, err := checks.LoadBaseDefinition(ctx, repository, tgt.Repository, tgt.BaseRevision, scratch) if err != nil { t.Log("preparation callback", err) return runnerproto.PreparedBug{}, err } e, err := executor(ctx, RunClaim{ClaimResponse: runnerproto.ClaimResponse{Brief: runnerproto.RunnerBrief{Selection: runnerproto.Selection{Isolation: iso}}}}, d, checks.Reproduction{}, time.Now().Add(2*time.Minute)) if err != nil { t.Log("preparation callback", err) return runnerproto.PreparedBug{}, err } d.Baseline, err = e.CaptureBaseline(ctx, d) if err != nil { t.Log("preparation callback", err) return runnerproto.PreparedBug{}, err } pinned = d raw := marshal(d) return runnerproto.PreparedBug{CheckDefinition: raw, CheckDefinitionHash: checks.Digest(raw), BaselineTestSetHash: d.Baseline.Hash}, nil }}) wfMust(t, err) var prepared runnerproto.PreparedBug if !readWork { prepared, err = manager.Prepare(ctx, target) wfMust(t, err) } source := runnerproto.SourceSnapshot{Ref: team.SourceRef{Kind: "project", ID: "1", Revision: 1, Hash: team.ContentDigest([]byte(`{"name":"fixture"}`))}, Payload: json.RawMessage(`{"name":"fixture"}`)} clock := team.RealClock{} auth := team.NewFakeAuthority(clock, 5*time.Second) auth.Issue("grant", team.Grant{Account: "team", Operations: map[team.Operation]bool{team.OpProviderCall: true, team.OpForgePublish: true, team.OpJobContinue: true, team.OpAttemptContinue: true}}) api := &directCoreAPI{coreWorkflowAPI: &coreWorkflowAPI{t: t, w: w, assignments: map[string]runnerproto.Assignment{}}} core, err := team.Open(ctx, filepath.Join(state, "core.db"), team.Options{Clock: clock, Authority: auth, RenderedApproval: func(context.Context, *sql.Tx, team.ProjectID, team.RenderedApproval) error { return nil }, SourceReference: func(_ context.Context, _ *sql.Tx, _ team.Scope, ref team.SourceRef) error { if ref != source.Ref { return team.ErrEvidence } return nil }, ExecutorEvidence: w.ExecutorEvidence, Provenance: func(ctx context.Context, tx *sql.Tx, scope team.Scope, h team.Handle) (team.Provenance, error) { p, err := w.Provenance(ctx, tx, scope, h) if err == nil { for _, a := range api.assignments { if a.WorkspaceKey == fmt.Sprint(h.Attempt) { p.Isolation = a.Selection.Isolation p.ConnectionID = a.Selection.ConnectionID } } } return p, err }, Adapters: map[team.Operation]team.Adapter{team.OpProviderCall: team.NewFakeProvider("claude", "model", nil), team.OpForgePublish: team.NewFakeForge()}}) wfMust(t, err) defer core.Close() api.core = core _, err = core.Resume(ctx) wfMust(t, err) limits := team.Limits{Calls: 24, InputTokens: 200000, OutputTokens: 40000} pol, err := team.RunnerPolicy("subscription", limits, team.Limits{Calls: 1, InputTokens: 32000, OutputTokens: 4000}, team.Rates{}) wfMust(t, err) spec := team.JobSpec{Project: 1, Account: "team", Requester: "person", GrantRef: "grant", Target: target, Evidence: team.EvidenceRequirement{Predicate: team.PredicateSoftwareFix, ExpectedSymptom: "wrong value", CheckDefinitionHash: prepared.CheckDefinitionHash, BaselineTestSetHash: prepared.BaselineTestSetHash, RequireBugFreeze: true}, Policy: pol, Steps: []team.StepSpec{{Key: "reproduce", Version: 1, Capability: team.CapReproduce}, {Key: "implement", Version: 1, Capability: team.CapImplement, DependsOn: []string{"reproduce"}}, {Key: "review", Version: 1, Capability: team.CapReview, DependsOn: []string{"implement"}}, {Key: "verify", Version: 1, Capability: team.CapVerify, DependsOn: []string{"review"}}, {Key: "publish", Version: 1, Capability: team.CapPublish, DependsOn: []string{"verify"}}}} if feature { spec.Evidence = team.EvidenceRequirement{Predicate: team.PredicateSoftwareFeature, CheckDefinitionHash: prepared.CheckDefinitionHash, BaselineTestSetHash: prepared.BaselineTestSetHash} spec.Steps[0].Key = "scope" spec.Steps[0].Capability = team.CapScope spec.Steps[1].DependsOn = []string{"scope"} } if extra { spec.Evidence = team.EvidenceRequirement{Predicate: team.PredicateRenderedChange, ExpectedSymptom: "wrong value", CheckDefinitionHash: prepared.CheckDefinitionHash, BaselineTestSetHash: prepared.BaselineTestSetHash, RequireBugFreeze: true, RequiredDecisions: []string{"copy", "design"}} spec.Steps[0].Key = "reproduce" spec.Steps[0].Capability = team.CapReproduce spec.Steps = append(spec.Steps[:1], append([]team.StepSpec{{Key: "words", Version: 1, Capability: team.CapImplement, DependsOn: []string{"reproduce"}}, {Key: "layout", Version: 1, Capability: team.CapImplement, DependsOn: []string{"words"}}}, spec.Steps[1:]...)...) spec.Steps[3].DependsOn = []string{"layout"} } if readWork { target = team.TargetBinding{Kind: team.TargetProjectRead, Repository: "amadan.net/test/fixture", BaseRevision: "project/1"} spec.Target = target spec.Evidence = team.EvidenceRequirement{} spec.Steps = []team.StepSpec{{Key: "research", Version: 1, Capability: team.CapResearch}} } period := team.PeriodLimits{Calls: limits.Calls, InputTokens: limits.InputTokens, OutputTokens: limits.OutputTokens, Seconds: 10000} wfMust(t, core.ConfigureBudgets(ctx, "team", 0, team.BudgetSet{Team: period, Projects: map[team.ProjectID]team.PeriodLimits{1: period}})) job, err := core.CreateJob(ctx, spec) wfMust(t, err) scope := team.Scope{Account: job.Account, Job: job.ID} pubroot := filepath.Join(root, "pub") policy.DeniedPaths = append(policy.DeniedPaths, pubroot) gitSpy := filepath.Join(root, "publish-git") wfMust(t, os.WriteFile(gitSpy, []byte("#!/bin/bash\nargs=()\nfor arg in \"$@\"; do\n if [[ \"$arg\" == https://amadan.net/test/fixture ]]; then args+=("+fmt.Sprintf("%q", remote)+"); else args+=(\"$arg\"); fi\ndone\nexec /usr/bin/git -c protocol.file.allow=always \"${args[@]}\"\n"), 0700)) status, err := core.Status(ctx) wfMust(t, err) var publisher *forge.Publisher if !readWork { publisher, err = forge.New(forge.Config{Root: pubroot, GitPath: gitSpy, Runner: "runner", Incarnation: status.Incarnation, Clock: time.Now, Authorize: w.PublicationAuthorization, Revalidate: func(ctx context.Context, a forge.Authorization) error { return core.ValidateHandle(ctx, a.Ticket.Scope, a.Ticket.Handle) }, Export: manager.ExportCandidate, Credential: func(context.Context, string) (forge.Credential, error) { return forge.Credential{Remote: "https://amadan.net/test/fixture", Agent: "test~person@example.test", Bearer: "fixture-only", GitPassword: "git-fixture-only"}, nil }, Description: &workflowDescription{}}) wfMust(t, err) } workflow, err := NewPlanWorkflow(BugWorkflowConfig{UploadBlob: func(_ context.Context, _ RunClaim, hash string, raw []byte) error { if team.ContentDigest(raw) != hash { return provider.ErrIdentity } return nil }, Publisher: publisher, PublisherFor: func(context.Context, runnerproto.PublicationAuthorization) (*forge.Publisher, error) { if !readWork { return publisher, nil } t.Fatal("research invoked publisher") return nil, provider.ErrPolicy }, Workspaces: manager, Launchers: registry, Namespaces: namespaces, Launch: launch, Witness: w, Policy: func(context.Context, provider.Selection) (provider.ReadPolicy, error) { return policy, nil }, Executor: executor, StateDir: state, Executable: "/bin/false", InstanceID: "instance", Copy: ToolCopy{Accepted: "accepted", Rejected: "rejected"}}) wfMust(t, err) s, err := NewSupervisor(SupervisorConfig{Journal: j, Namespaces: namespaces, API: api, Workflow: workflow, CredentialsPath: filepath.Join(state, "credentials"), InstallCredentials: func(context.Context, runnerproto.CredentialRotation, string) error { return nil }}) wfMust(t, err) wfMust(t, s.Recover(ctx)) api.beforeComplete = func() error { select { case <-s.leaseDone: return nil default: return fmt.Errorf("completion while lease watchdog was still live") } } keys := []string{"reproduce", "implement", "review", "verify", "publish"} if feature { keys[0] = "scope" } if extra { keys = []string{"reproduce", "words", "layout", "implement", "review", "verify", "publish"} } if readWork { keys = []string{"research"} } for i, step := range keys { if extra && step == "publish" { arts, err := core.Artifacts(ctx, scope) wfMust(t, err) var render team.RenderResult for _, a := range arts { if a.Role == team.RoleRender { full, err := core.Artifact(ctx, scope, a.ID) wfMust(t, err) wfMust(t, json.Unmarshal(full.Payload, &render)) } } for _, decision := range []string{"copy", "design"} { job, err := core.GetJob(ctx, scope) wfMust(t, err) wfMust(t, core.RecordRenderedApproval(ctx, scope, job.Revision, team.RenderedApproval{CandidateHash: render.CandidateHash, DiffHash: render.DiffHash, RenderHash: render.RenderHash, Decision: decision, Person: "person", DecisionRevision: 1})) } } h, err := core.Claim(ctx, scope, step, "runner", fmt.Sprint(i+1)) wfMust(t, err) sel := runnerproto.Selection{ConnectionID: step, Provider: "claude", Family: "claude", Model: "model", AccountID: "account", Isolation: iso} if step == "review" || step == "verify" { sel.Provider = "codex" sel.Family = "gpt" } a := runnerproto.Assignment{ID: step, TaskID: "task", StepKey: step, WorkspaceKey: fmt.Sprint(h.Attempt), Scope: scope, Kind: "step", Selection: sel} api.assignments[step] = a arts, err := core.Artifacts(ctx, scope) wfMust(t, err) for i, art := range arts { arts[i], err = core.Artifact(ctx, scope, art.ID) wfMust(t, err) } wfMust(t, w.record(ctx, "artifacts", attemptKey(scope, h), arts)) hashes := []string{prepared.CheckDefinitionHash} for _, art := range arts { hashes = append(hashes, art.Hash) } claim := RunClaim{Assignment: a, ClaimResponse: runnerproto.ClaimResponse{Scope: scope, Handle: h, Brief: runnerproto.RunnerBrief{Target: target, Selection: sel, Policy: pol, CheckDefinition: marshal(pinned), RenderRecipe: pinned.Render, ArtifactHashes: hashes}, AttemptDeadline: time.Now().Add(20 * time.Minute), LeaseDeadline: time.Now().Add(60 * time.Second)}} if feature || readWork { action := step if readWork { action = "recommend" claim.Brief.CheckDefinition = nil claim.Brief.ArtifactHashes = nil hashes = nil claim.Brief.Sources = []runnerproto.SourceSnapshot{source} } if step == "verify" { action = "checks" } if step == "words" { action = "copy" } if step == "layout" { action = "design" } specialist := "engineering" if step == "review" { specialist = "review" } claim.Brief.Step = runnerproto.StepBrief{PlanRevision: 1, StepKey: step, Action: action, SpecialistKey: specialist, SpecialistRevision: 1, ArtifactHashes: hashes} } if err = workflow.Run(ctx, s, claim); err != nil { t.Fatalf("%s (%s): %v", step, s.states[attemptKey(scope, h)].FailurePhase, err) } } entries, err := os.ReadDir(filepath.Join(state, "admissions")) wfMust(t, err) consumed := 0 for _, entry := range entries { if strings.HasSuffix(entry.Name(), ".consumed") { consumed++ } } wantConsumed := len(keys) - 1 if readWork { wantConsumed = 1 } if consumed != wantConsumed { t.Fatal("dispatch bypassed durable ticket consumption", consumed) } wantAdmissions := len(keys) - 2 if readWork { wantAdmissions = 1 } if api.admissions != wantAdmissions { t.Fatal("model admission count", api.admissions) } wantQuestions := 1 if readWork { wantQuestions = 0 } if api.questions != wantQuestions { t.Fatal("ask_person produced duplicate questions", api.questions) } if readWork { if executorCalls != 0 { t.Fatal("research invoked checks", executorCalls) } if _, err := os.Stat(pubroot); !os.IsNotExist(err) { t.Fatal("research invoked publisher") } entries, err := os.ReadDir(works) wfMust(t, err) for _, entry := range entries { if !strings.HasPrefix(entry.Name(), "read-") { t.Fatal("mutable checkout created", entry.Name()) } if _, err = os.Stat(filepath.Join(works, entry.Name(), ".git")); !os.IsNotExist(err) { t.Fatal("research created git ref") } } } finished, err := core.GetJob(ctx, scope) wfMust(t, err) if finished.State != team.JobSucceeded { t.Fatal("publication not concluded", finished.State) } attempts, err := core.Attempts(ctx, scope) wfMust(t, err) if len(attempts) != len(keys) { t.Fatal("attempt count", len(attempts)) } for _, a := range attempts { if a.State != team.AttemptSucceeded || a.Containment != team.ContainmentContained { t.Fatalf("unfinished %+v", a) } } } type directCoreAPI struct { beforeComplete func() error *coreWorkflowAPI questions int } func (a *directCoreAPI) Call(ctx context.Context, op string, q runnerproto.RunnerRequest, out any) error { if op == "artifacts" && q.Artifact != nil && q.Artifact.Role == team.RoleCandidate { if err := a.coreWorkflowAPI.Call(ctx, op, q, out); err != nil { return err } arts, err := a.core.Artifacts(ctx, q.Scope) if err != nil { return err } for i, art := range arts { arts[i], err = a.core.Artifact(ctx, q.Scope, art.ID) if err != nil { return err } } return a.w.record(ctx, "artifacts", attemptKey(q.Scope, q.Handle), arts) } if op == "artifacts" && q.Artifact != nil && q.Artifact.Role == team.RoleAnswer { if err := a.coreWorkflowAPI.Call(ctx, op, q, out); err != nil { return err } return a.core.Complete(ctx, q.Scope, q.Handle, team.AttemptResult{Outcome: team.OutcomeSuccess}) } if op == "complete" && a.beforeComplete != nil { if err := a.beforeComplete(); err != nil { return err } } if op == "freeze_feature" { var v runnerproto.FreezeRequest if err := json.Unmarshal(q.Prepared, &v); err != nil { return err } return a.core.FreezeFeatureEvidence(ctx, q.Scope, q.Handle, v.ReproductionHash, v.DefinitionHash) } if op == "questions" { a.questions++ } if op == "answers" && a.question == nil { return json.Unmarshal([]byte(`[]`), out) } if op == "events" { var e Event if runnerproto.DecodeLimit(strings.NewReader(string(q.Event)), &e, runnerproto.MaxEventBytes+4096) != nil { return runnerproto.ErrInvalid } if e.Kind == "turn.completed" || e.Kind == "turn.failed" { if err := a.w.Events(ctx, a.assignments[q.AssignmentID], q); err != nil { return err } var payload struct { Usage *team.Usage `json:"usage"` } if json.Unmarshal(e.Payload, &payload) != nil { return runnerproto.ErrInvalid } return a.core.Record(ctx, q.Scope, q.ActionID, team.Receipt{ID: e.TurnID, Outcome: team.OutcomeSuccess, Usage: payload.Usage}) } } return a.coreWorkflowAPI.Call(ctx, op, q, out) }