oficina / equipo Public

Clone
git clone https://amadan.net/oficina/equipo

Plain git — no account needed to clone.

Download

Download this file

1package runner
2
3import (
4 "amadan.net/oficina/equipo/internal/equipo/team"
5 "amadan.net/oficina/equipo/internal/runner/checks"
6 "amadan.net/oficina/equipo/internal/runner/containment"
7 "amadan.net/oficina/equipo/internal/runner/forge"
8 "amadan.net/oficina/equipo/internal/testci"
9
10 "context"
11 "database/sql"
12 "encoding/json"
13 "fmt"
14 "os"
15 "os/exec"
16 "path/filepath"
17 "strings"
18 "testing"
19 "time"
20
21 "amadan.net/oficina/equipo/internal/runner/provider"
22 "amadan.net/oficina/equipo/internal/runner/workspace"
23 "amadan.net/oficina/equipo/internal/runnerproto"
24)
25
26func runDirectBugGraph(t *testing.T) { runDirectPlanGraph(t, false, false, false) }
27func TestPlanWorkflowFeature(t *testing.T) {
28 t.Parallel()
29 runDirectPlanGraph(t, true, false, false)
30}
31func TestPlanWorkflowCandidateOrder(t *testing.T) {
32 t.Parallel()
33 runDirectPlanGraph(t, true, true, false)
34}
35func TestPlanWorkflowRecommendation(t *testing.T) {
36 t.Parallel()
37 runDirectPlanGraph(t, false, false, true)
38}
39func runDirectPlanGraph(t *testing.T, feature, extra, readWork bool) {
40 ctx := context.Background()
41 root, err := os.MkdirTemp(os.Getenv("TMPDIR"), "e15-")
42 wfMust(t, err)
43 t.Cleanup(func() { os.RemoveAll(root) })
44 state := filepath.Join(root, "s")
45 private := filepath.Join(root, "p")
46 works := filepath.Join(root, "w")
47 scratch := filepath.Join(root, "c")
48 seed := filepath.Join(root, "seed")
49 for _, p := range []string{state, private, works, scratch, seed} {
50 wfMust(t, os.Mkdir(p, 0700))
51 }
52 j, err := OpenJournal(ctx, filepath.Join(state, "j.db"))
53 wfMust(t, err)
54 defer j.Close()
55 w, err := NewWitness(j)
56 wfMust(t, err)
57 policy := provider.ReadPolicy{ConfigHash: strings.Repeat("a", 64), DeniedPaths: []string{state, private}}
58 helper, err := os.Executable()
59 wfMust(t, err)
60 namespaces, err := containment.New(containment.Config{Binary: "/usr/bin/bwrap", RunnerBinary: helper, ScratchRoot: scratch, ProviderNetworks: []provider.NetworkContract{{Provider: "claude"}, {Provider: "codex"}}})
61 wfMust(t, err)
62 _, err = j.ReconcileDirect(ctx, namespaces)
63 wfMust(t, err)
64 host := NewDirectHost(j, namespaces)
65 // The original bug graph retains the capture backpressure exercise.
66 // Plan variants need timeline events but do not repeat its volume test.
67 progressFrames := 200
68 if feature || readWork {
69 progressFrames = 2
70 }
71 registry, launch := fakeDirectGraph(t, j, host, root, scratch, helper, progressFrames)
72 wfMust(t, os.WriteFile(filepath.Join(seed, "go.mod"), []byte("module fixture\n\ngo 1.26.0\n"), 0600))
73 wfMust(t, os.WriteFile(filepath.Join(seed, "value.go"), []byte("package fixture\nfunc Value() int {return 1}\n"), 0600))
74 wfMust(t, os.WriteFile(filepath.Join(seed, "old_test.go"), []byte("package fixture\nimport \"testing\"\nfunc TestOld(t *testing.T) {}\n"), 0600))
75 cmd := runnerproto.CheckCommand{Argv: []string{"go", "test", "-json", "-count=1", "./..."}, Dir: ".", Parser: "go-test-json", TimeoutSeconds: 120}
76 wfMust(t, os.Mkdir(filepath.Join(seed, ".equipo"), 0700))
77 definition := checks.Definition{Version: 1, Commands: []checks.Command{cmd}, Reproduction: cmd}
78 if extra {
79 definition.Render = &runnerproto.RenderRecipe{Version: 1, Command: checks.Command{Argv: []string{"sh", "render.sh"}, Dir: ".", Parser: "exit", TimeoutSeconds: 10}}
80 definition.TrustedPaths = []string{"render.sh"}
81 wfMust(t, os.WriteFile(filepath.Join(seed, "render.sh"), []byte("printf '%s' 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVQIHWP4z8DwHwAFgAI/ScLttAAAAABJRU5ErkJggg==' | base64 -d\n"), 0600))
82 }
83 wfMust(t, os.WriteFile(filepath.Join(seed, ".equipo/checks.json"), marshal(definition), 0600))
84 wfGit(t, seed, "init", "-b", "main")
85 wfGit(t, seed, "add", ".")
86 wfGit(t, seed, "commit", "-m", "base")
87 base := wfGit(t, seed, "rev-parse", "HEAD")
88 remote := filepath.Join(root, "remote.git")
89 wfGit(t, root, "clone", "--bare", seed, remote)
90 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")}
91 testci.Tools(t, "codex", "bwrap", "python3", "git")
92 codex, err := exec.LookPath("codex")
93 wfMust(t, err)
94 goCommand := exec.Command("go", "env", "GOROOT")
95 goCommand.Env = append(os.Environ(), "GOROOT=", "GOTOOLCHAIN="+checks.GoVersion)
96 goOutput, err := goCommand.Output()
97 wfMust(t, err)
98 goRoot := strings.TrimSpace(string(goOutput))
99 wfMust(t, os.Mkdir(filepath.Join(root, "modules"), 0700))
100 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")})
101 wfMust(t, err)
102 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"}}}
103 target := team.TargetBinding{Kind: team.TargetRepository, Repository: "amadan.net/test/fixture", DefaultRef: "main", Ref: "equipo/test", BaseRevision: base}
104 var manager *workspace.Manager
105 var pinned checks.Definition
106 var repo string
107 executorCalls := 0
108 executor := func(ctx context.Context, c RunClaim, d checks.Definition, r checks.Reproduction, deadline time.Time) (*checks.Executor, error) {
109 executorCalls++
110 if c.Handle.Attempt > 0 && !deadline.Equal(c.AttemptDeadline) {
111 return nil, fmt.Errorf("executor got lease snapshot instead of attempt deadline")
112 }
113 recipeHash := ""
114 if d.Render != nil {
115 recipeHash = checks.Digest(marshal(d.Render))
116 }
117 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) {
118 arts, err := apiArtifacts(ctx, w, c)
119 if err != nil {
120 return team.GitCandidate{}, err
121 }
122 for _, a := range arts {
123 var v team.GitCandidate
124 if a.Role == team.RoleCandidate && checks.CandidateHash(decodeCandidate(a.Payload)) == hash {
125 json.Unmarshal(a.Payload, &v)
126 return v, nil
127 }
128 }
129 return team.GitCandidate{}, provider.ErrIdentity
130 }, Export: func(ctx context.Context, commit, dest string) error {
131 if commit == base {
132 return checks.ExportBase(ctx, repo, base, dest)
133 }
134 arts, err := apiArtifacts(ctx, w, c)
135 if err != nil {
136 return err
137 }
138 for _, a := range arts {
139 v := decodeCandidate(a.Payload)
140 if a.Role == team.RoleCandidate && v.Commit == commit {
141 return manager.ExportCandidate(ctx, v, dest)
142 }
143 }
144 return provider.ErrIdentity
145 }}, sandbox)
146 }
147 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) {
148 repo = repository
149 d, err := checks.LoadBaseDefinition(ctx, repository, tgt.Repository, tgt.BaseRevision, scratch)
150 if err != nil {
151 t.Log("preparation callback", err)
152 return runnerproto.PreparedBug{}, err
153 }
154 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))
155 if err != nil {
156 t.Log("preparation callback", err)
157 return runnerproto.PreparedBug{}, err
158 }
159 d.Baseline, err = e.CaptureBaseline(ctx, d)
160 if err != nil {
161 t.Log("preparation callback", err)
162 return runnerproto.PreparedBug{}, err
163 }
164 pinned = d
165 raw := marshal(d)
166 return runnerproto.PreparedBug{CheckDefinition: raw, CheckDefinitionHash: checks.Digest(raw), BaselineTestSetHash: d.Baseline.Hash}, nil
167 }})
168 wfMust(t, err)
169 var prepared runnerproto.PreparedBug
170 if !readWork {
171 prepared, err = manager.Prepare(ctx, target)
172 wfMust(t, err)
173 }
174 source := runnerproto.SourceSnapshot{Ref: team.SourceRef{Kind: "project", ID: "1", Revision: 1, Hash: team.ContentDigest([]byte(`{"name":"fixture"}`))}, Payload: json.RawMessage(`{"name":"fixture"}`)}
175 clock := team.RealClock{}
176 auth := team.NewFakeAuthority(clock, 5*time.Second)
177 auth.Issue("grant", team.Grant{Account: "team", Operations: map[team.Operation]bool{team.OpProviderCall: true, team.OpForgePublish: true, team.OpJobContinue: true, team.OpAttemptContinue: true}})
178 api := &directCoreAPI{coreWorkflowAPI: &coreWorkflowAPI{t: t, w: w, assignments: map[string]runnerproto.Assignment{}}}
179 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 {
180 if ref != source.Ref {
181 return team.ErrEvidence
182 }
183 return nil
184 }, ExecutorEvidence: w.ExecutorEvidence, Provenance: func(ctx context.Context, tx *sql.Tx, scope team.Scope, h team.Handle) (team.Provenance, error) {
185 p, err := w.Provenance(ctx, tx, scope, h)
186 if err == nil {
187 for _, a := range api.assignments {
188 if a.WorkspaceKey == fmt.Sprint(h.Attempt) {
189 p.Isolation = a.Selection.Isolation
190 p.ConnectionID = a.Selection.ConnectionID
191 }
192 }
193 }
194 return p, err
195 }, Adapters: map[team.Operation]team.Adapter{team.OpProviderCall: team.NewFakeProvider("claude", "model", nil), team.OpForgePublish: team.NewFakeForge()}})
196 wfMust(t, err)
197 defer core.Close()
198 api.core = core
199 _, err = core.Resume(ctx)
200 wfMust(t, err)
201 limits := team.Limits{Calls: 24, InputTokens: 200000, OutputTokens: 40000}
202 pol, err := team.RunnerPolicy("subscription", limits, team.Limits{Calls: 1, InputTokens: 32000, OutputTokens: 4000}, team.Rates{})
203 wfMust(t, err)
204 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"}}}}
205 if feature {
206 spec.Evidence = team.EvidenceRequirement{Predicate: team.PredicateSoftwareFeature, CheckDefinitionHash: prepared.CheckDefinitionHash, BaselineTestSetHash: prepared.BaselineTestSetHash}
207 spec.Steps[0].Key = "scope"
208 spec.Steps[0].Capability = team.CapScope
209 spec.Steps[1].DependsOn = []string{"scope"}
210 }
211 if extra {
212 spec.Evidence = team.EvidenceRequirement{Predicate: team.PredicateRenderedChange, ExpectedSymptom: "wrong value", CheckDefinitionHash: prepared.CheckDefinitionHash, BaselineTestSetHash: prepared.BaselineTestSetHash, RequireBugFreeze: true, RequiredDecisions: []string{"copy", "design"}}
213 spec.Steps[0].Key = "reproduce"
214 spec.Steps[0].Capability = team.CapReproduce
215 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:]...)...)
216 spec.Steps[3].DependsOn = []string{"layout"}
217 }
218 if readWork {
219 target = team.TargetBinding{Kind: team.TargetProjectRead, Repository: "amadan.net/test/fixture", BaseRevision: "project/1"}
220 spec.Target = target
221 spec.Evidence = team.EvidenceRequirement{}
222 spec.Steps = []team.StepSpec{{Key: "research", Version: 1, Capability: team.CapResearch}}
223 }
224 period := team.PeriodLimits{Calls: limits.Calls, InputTokens: limits.InputTokens, OutputTokens: limits.OutputTokens, Seconds: 10000}
225 wfMust(t, core.ConfigureBudgets(ctx, "team", 0, team.BudgetSet{Team: period, Projects: map[team.ProjectID]team.PeriodLimits{1: period}}))
226 job, err := core.CreateJob(ctx, spec)
227 wfMust(t, err)
228 scope := team.Scope{Account: job.Account, Job: job.ID}
229
230 pubroot := filepath.Join(root, "pub")
231 policy.DeniedPaths = append(policy.DeniedPaths, pubroot)
232 gitSpy := filepath.Join(root, "publish-git")
233 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))
234 status, err := core.Status(ctx)
235 wfMust(t, err)
236 var publisher *forge.Publisher
237 if !readWork {
238 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 {
239 return core.ValidateHandle(ctx, a.Ticket.Scope, a.Ticket.Handle)
240 }, Export: manager.ExportCandidate, Credential: func(context.Context, string) (forge.Credential, error) {
241 return forge.Credential{Remote: "https://amadan.net/test/fixture", Agent: "test~person@example.test", Bearer: "fixture-only", GitPassword: "git-fixture-only"}, nil
242 }, Description: &workflowDescription{}})
243 wfMust(t, err)
244 }
245 workflow, err := NewPlanWorkflow(BugWorkflowConfig{UploadBlob: func(_ context.Context, _ RunClaim, hash string, raw []byte) error {
246 if team.ContentDigest(raw) != hash {
247 return provider.ErrIdentity
248 }
249 return nil
250 }, Publisher: publisher, PublisherFor: func(context.Context, runnerproto.PublicationAuthorization) (*forge.Publisher, error) {
251 if !readWork {
252 return publisher, nil
253 }
254 t.Fatal("research invoked publisher")
255 return nil, provider.ErrPolicy
256 }, 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"}})
257 wfMust(t, err)
258 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 }})
259 wfMust(t, err)
260 wfMust(t, s.Recover(ctx))
261 api.beforeComplete = func() error {
262 select {
263 case <-s.leaseDone:
264 return nil
265 default:
266 return fmt.Errorf("completion while lease watchdog was still live")
267 }
268 }
269 keys := []string{"reproduce", "implement", "review", "verify", "publish"}
270 if feature {
271 keys[0] = "scope"
272 }
273 if extra {
274 keys = []string{"reproduce", "words", "layout", "implement", "review", "verify", "publish"}
275 }
276 if readWork {
277 keys = []string{"research"}
278 }
279 for i, step := range keys {
280 if extra && step == "publish" {
281 arts, err := core.Artifacts(ctx, scope)
282 wfMust(t, err)
283 var render team.RenderResult
284 for _, a := range arts {
285 if a.Role == team.RoleRender {
286 full, err := core.Artifact(ctx, scope, a.ID)
287 wfMust(t, err)
288 wfMust(t, json.Unmarshal(full.Payload, &render))
289 }
290 }
291 for _, decision := range []string{"copy", "design"} {
292 job, err := core.GetJob(ctx, scope)
293 wfMust(t, err)
294 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}))
295 }
296 }
297 h, err := core.Claim(ctx, scope, step, "runner", fmt.Sprint(i+1))
298 wfMust(t, err)
299 sel := runnerproto.Selection{ConnectionID: step, Provider: "claude", Family: "claude", Model: "model", AccountID: "account", Isolation: iso}
300 if step == "review" || step == "verify" {
301 sel.Provider = "codex"
302 sel.Family = "gpt"
303
304 }
305 a := runnerproto.Assignment{ID: step, TaskID: "task", StepKey: step, WorkspaceKey: fmt.Sprint(h.Attempt), Scope: scope, Kind: "step", Selection: sel}
306 api.assignments[step] = a
307 arts, err := core.Artifacts(ctx, scope)
308 wfMust(t, err)
309 for i, art := range arts {
310 arts[i], err = core.Artifact(ctx, scope, art.ID)
311 wfMust(t, err)
312 }
313 wfMust(t, w.record(ctx, "artifacts", attemptKey(scope, h), arts))
314 hashes := []string{prepared.CheckDefinitionHash}
315 for _, art := range arts {
316 hashes = append(hashes, art.Hash)
317 }
318 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)}}
319 if feature || readWork {
320 action := step
321 if readWork {
322 action = "recommend"
323 claim.Brief.CheckDefinition = nil
324 claim.Brief.ArtifactHashes = nil
325 hashes = nil
326 claim.Brief.Sources = []runnerproto.SourceSnapshot{source}
327 }
328 if step == "verify" {
329 action = "checks"
330 }
331 if step == "words" {
332 action = "copy"
333 }
334 if step == "layout" {
335 action = "design"
336 }
337 specialist := "engineering"
338 if step == "review" {
339 specialist = "review"
340 }
341 claim.Brief.Step = runnerproto.StepBrief{PlanRevision: 1, StepKey: step, Action: action, SpecialistKey: specialist, SpecialistRevision: 1, ArtifactHashes: hashes}
342 }
343 if err = workflow.Run(ctx, s, claim); err != nil {
344 t.Fatalf("%s (%s): %v", step, s.states[attemptKey(scope, h)].FailurePhase, err)
345 }
346 }
347
348 entries, err := os.ReadDir(filepath.Join(state, "admissions"))
349 wfMust(t, err)
350 consumed := 0
351 for _, entry := range entries {
352 if strings.HasSuffix(entry.Name(), ".consumed") {
353 consumed++
354 }
355 }
356 wantConsumed := len(keys) - 1
357 if readWork {
358 wantConsumed = 1
359 }
360 if consumed != wantConsumed {
361 t.Fatal("dispatch bypassed durable ticket consumption", consumed)
362 }
363 wantAdmissions := len(keys) - 2
364 if readWork {
365 wantAdmissions = 1
366 }
367 if api.admissions != wantAdmissions {
368 t.Fatal("model admission count", api.admissions)
369 }
370 wantQuestions := 1
371 if readWork {
372 wantQuestions = 0
373 }
374 if api.questions != wantQuestions {
375 t.Fatal("ask_person produced duplicate questions", api.questions)
376 }
377 if readWork {
378 if executorCalls != 0 {
379 t.Fatal("research invoked checks", executorCalls)
380 }
381 if _, err := os.Stat(pubroot); !os.IsNotExist(err) {
382 t.Fatal("research invoked publisher")
383 }
384 entries, err := os.ReadDir(works)
385 wfMust(t, err)
386 for _, entry := range entries {
387 if !strings.HasPrefix(entry.Name(), "read-") {
388 t.Fatal("mutable checkout created", entry.Name())
389 }
390 if _, err = os.Stat(filepath.Join(works, entry.Name(), ".git")); !os.IsNotExist(err) {
391 t.Fatal("research created git ref")
392 }
393 }
394 }
395 finished, err := core.GetJob(ctx, scope)
396 wfMust(t, err)
397 if finished.State != team.JobSucceeded {
398 t.Fatal("publication not concluded", finished.State)
399 }
400 attempts, err := core.Attempts(ctx, scope)
401 wfMust(t, err)
402 if len(attempts) != len(keys) {
403 t.Fatal("attempt count", len(attempts))
404 }
405 for _, a := range attempts {
406 if a.State != team.AttemptSucceeded || a.Containment != team.ContainmentContained {
407 t.Fatalf("unfinished %+v", a)
408 }
409 }
410}
411
412type directCoreAPI struct {
413 beforeComplete func() error
414 *coreWorkflowAPI
415 questions int
416}
417
418func (a *directCoreAPI) Call(ctx context.Context, op string, q runnerproto.RunnerRequest, out any) error {
419 if op == "artifacts" && q.Artifact != nil && q.Artifact.Role == team.RoleCandidate {
420 if err := a.coreWorkflowAPI.Call(ctx, op, q, out); err != nil {
421 return err
422 }
423 arts, err := a.core.Artifacts(ctx, q.Scope)
424 if err != nil {
425 return err
426 }
427 for i, art := range arts {
428 arts[i], err = a.core.Artifact(ctx, q.Scope, art.ID)
429 if err != nil {
430 return err
431 }
432 }
433 return a.w.record(ctx, "artifacts", attemptKey(q.Scope, q.Handle), arts)
434 }
435 if op == "artifacts" && q.Artifact != nil && q.Artifact.Role == team.RoleAnswer {
436 if err := a.coreWorkflowAPI.Call(ctx, op, q, out); err != nil {
437 return err
438 }
439 return a.core.Complete(ctx, q.Scope, q.Handle, team.AttemptResult{Outcome: team.OutcomeSuccess})
440 }
441 if op == "complete" && a.beforeComplete != nil {
442 if err := a.beforeComplete(); err != nil {
443 return err
444 }
445 }
446 if op == "freeze_feature" {
447 var v runnerproto.FreezeRequest
448 if err := json.Unmarshal(q.Prepared, &v); err != nil {
449 return err
450 }
451 return a.core.FreezeFeatureEvidence(ctx, q.Scope, q.Handle, v.ReproductionHash, v.DefinitionHash)
452 }
453 if op == "questions" {
454 a.questions++
455 }
456 if op == "answers" && a.question == nil {
457 return json.Unmarshal([]byte(`[]`), out)
458 }
459 if op == "events" {
460 var e Event
461 if runnerproto.DecodeLimit(strings.NewReader(string(q.Event)), &e, runnerproto.MaxEventBytes+4096) != nil {
462 return runnerproto.ErrInvalid
463 }
464 if e.Kind == "turn.completed" || e.Kind == "turn.failed" {
465 if err := a.w.Events(ctx, a.assignments[q.AssignmentID], q); err != nil {
466 return err
467 }
468 var payload struct {
469 Usage *team.Usage `json:"usage"`
470 }
471 if json.Unmarshal(e.Payload, &payload) != nil {
472 return runnerproto.ErrInvalid
473 }
474 return a.core.Record(ctx, q.Scope, q.ActionID, team.Receipt{ID: e.TurnID, Outcome: team.OutcomeSuccess, Usage: payload.Usage})
475 }
476 }
477 return a.coreWorkflowAPI.Call(ctx, op, q, out)
478}
479