oficina / equipo Public

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

Plain git — no account needed to clone.

Download

Download this file

1package team
2
3import (
4 "context"
5 "encoding/json"
6 "fmt"
7 "strconv"
8 "strings"
9 "sync"
10 "unicode"
11)
12
13// This file is the offline fixture: a trusted check definition over a
14// tiny deterministic language, fake provider/forge/tracker adapters, and
15// the workflow driver TestFixture runs. Nothing here is a product
16// surface; it exists so the durable core can be exercised end to end
17// without a model, a forge or a network.
18
19// CheckDefinition is the trusted check definition the fixture pins by
20// hash. A check result registered under another hash is refused.
21const CheckDefinition = "fixturecheck/v1: parse the subject as `func Sum(a, b int) int { return <expr> }` with integer literals, a, b, + - * and parentheses; run every reproduction case; a case fails when Sum(a, b) != want"
22
23// CheckDefinitionHash is CheckDefinition's content hash.
24var CheckDefinitionHash = hashBytes([]byte(CheckDefinition))
25
26// FixtureCase is one reproduction case: Sum(A, B) must equal Want.
27type FixtureCase struct {
28 Name string `json:"name"`
29 A int64 `json:"a"`
30 B int64 `json:"b"`
31 Want int64 `json:"want"`
32 Skip bool `json:"skip,omitempty"`
33}
34
35// RunCheck executes the reproduction (a JSON list of FixtureCase) against
36// the subject source under CheckDefinition and reports what happened. It
37// is the fixture's verifier: it reads only the bytes it is given.
38func RunCheck(reproduction, subject []byte) CheckResult {
39 cr := CheckResult{ReproductionHash: hashBytes(reproduction), SubjectHash: hashBytes(subject), CheckDefinitionHash: CheckDefinitionHash}
40 var cases []FixtureCase
41 if err := strictJSON(reproduction, &cases); err != nil || len(cases) == 0 {
42 cr.Outcome = CheckNoTests
43 return cr
44 }
45 fn, err := parseSum(string(subject))
46 if err != nil {
47 cr.Outcome, cr.FailureMessage = CheckCompileError, err.Error()
48 return cr
49 }
50 var msgs []string
51 for _, c := range cases {
52 if c.Skip {
53 continue
54 }
55 cr.TestsRun++
56 got := fn(c.A, c.B)
57 if got != c.Want {
58 cr.TestsFailed++
59 msgs = append(msgs, fmt.Sprintf("%s: Sum(%d, %d) = %d, want %d", c.Name, c.A, c.B, got, c.Want))
60 }
61 }
62 switch {
63 case cr.TestsRun == 0:
64 cr.Outcome = CheckSkipped
65 case cr.TestsFailed > 0:
66 cr.Outcome, cr.FailureMessage = CheckFail, strings.Join(msgs, "; ")
67 default:
68 cr.Outcome = CheckPass
69 }
70 return cr
71}
72
73// parseSum compiles the one-function subject language.
74func parseSum(src string) (func(a, b int64) int64, error) {
75 const head = "func Sum(a, b int) int {"
76 s := strings.TrimSpace(src)
77 if !strings.HasPrefix(s, head) || !strings.HasSuffix(s, "}") {
78 return nil, fmt.Errorf("compile: expected %q ... \"}\"", head)
79 }
80 body := strings.TrimSpace(strings.TrimSuffix(strings.TrimPrefix(s, head), "}"))
81 if !strings.HasPrefix(body, "return ") {
82 return nil, fmt.Errorf("compile: body must be a return statement")
83 }
84 p := &exprParser{src: strings.TrimPrefix(body, "return ")}
85 node, err := p.expr()
86 if err != nil {
87 return nil, err
88 }
89 p.skip()
90 if p.pos != len(p.src) {
91 return nil, fmt.Errorf("compile: unexpected %q", p.src[p.pos:])
92 }
93 return node, nil
94}
95
96type exprParser struct {
97 src string
98 pos int
99}
100
101func (p *exprParser) skip() {
102 for p.pos < len(p.src) && unicode.IsSpace(rune(p.src[p.pos])) {
103 p.pos++
104 }
105}
106
107func (p *exprParser) expr() (func(a, b int64) int64, error) {
108 left, err := p.term()
109 if err != nil {
110 return nil, err
111 }
112 for {
113 p.skip()
114 if p.pos >= len(p.src) || (p.src[p.pos] != '+' && p.src[p.pos] != '-') {
115 return left, nil
116 }
117 op := p.src[p.pos]
118 p.pos++
119 right, err := p.term()
120 if err != nil {
121 return nil, err
122 }
123 l := left
124 if op == '+' {
125 left = func(a, b int64) int64 { return l(a, b) + right(a, b) }
126 } else {
127 left = func(a, b int64) int64 { return l(a, b) - right(a, b) }
128 }
129 }
130}
131
132func (p *exprParser) term() (func(a, b int64) int64, error) {
133 left, err := p.factor()
134 if err != nil {
135 return nil, err
136 }
137 for {
138 p.skip()
139 if p.pos >= len(p.src) || p.src[p.pos] != '*' {
140 return left, nil
141 }
142 p.pos++
143 right, err := p.factor()
144 if err != nil {
145 return nil, err
146 }
147 l := left
148 left = func(a, b int64) int64 { return l(a, b) * right(a, b) }
149 }
150}
151
152func (p *exprParser) factor() (func(a, b int64) int64, error) {
153 p.skip()
154 if p.pos >= len(p.src) {
155 return nil, fmt.Errorf("compile: unexpected end of expression")
156 }
157 switch c := p.src[p.pos]; {
158 case c == '(':
159 p.pos++
160 n, err := p.expr()
161 if err != nil {
162 return nil, err
163 }
164 p.skip()
165 if p.pos >= len(p.src) || p.src[p.pos] != ')' {
166 return nil, fmt.Errorf("compile: missing )")
167 }
168 p.pos++
169 return n, nil
170 case c == 'a' || c == 'b':
171 p.pos++
172 if c == 'a' {
173 return func(a, _ int64) int64 { return a }, nil
174 }
175 return func(_, b int64) int64 { return b }, nil
176 case c >= '0' && c <= '9':
177 start := p.pos
178 for p.pos < len(p.src) && p.src[p.pos] >= '0' && p.src[p.pos] <= '9' {
179 p.pos++
180 }
181 v, err := strconv.ParseInt(p.src[start:p.pos], 10, 64)
182 if err != nil {
183 return nil, fmt.Errorf("compile: %v", err)
184 }
185 return func(_, _ int64) int64 { return v }, nil
186 }
187 return nil, fmt.Errorf("compile: unexpected %q", p.src[p.pos:])
188}
189
190// FakeProvider answers provider.call dispatches from a canned table keyed
191// by the payload's "task". It reports usage from byte counts so the
192// ledger has something to settle. Unavailable makes every call a
193// definitive failure receipt (the provider refused; nothing ran).
194type FakeProvider struct {
195 Name string
196 Model string
197
198 mu sync.Mutex
199 responses map[string]string
200 unavailable bool
201 loseReply bool
202 calls int
203}
204
205// NewFakeProvider returns a provider with the given canned responses.
206func NewFakeProvider(name, model string, responses map[string]string) *FakeProvider {
207 r := map[string]string{}
208 for k, v := range responses {
209 r[k] = v
210 }
211 return &FakeProvider{Name: name, Model: model, responses: r}
212}
213
214// Respond sets the canned answer for task.
215func (p *FakeProvider) Respond(task, answer string) {
216 p.mu.Lock()
217 defer p.mu.Unlock()
218 p.responses[task] = answer
219}
220
221// SetUnavailable toggles refusal.
222func (p *FakeProvider) SetUnavailable(v bool) {
223 p.mu.Lock()
224 defer p.mu.Unlock()
225 p.unavailable = v
226}
227
228// SetLoseReply makes Execute run the call (and count it) but lose the
229// reply, the paid-inference lost-response case.
230func (p *FakeProvider) SetLoseReply(v bool) {
231 p.mu.Lock()
232 defer p.mu.Unlock()
233 p.loseReply = v
234}
235
236// Calls counts executed dispatches.
237func (p *FakeProvider) Calls() int {
238 p.mu.Lock()
239 defer p.mu.Unlock()
240 return p.calls
241}
242
243func (p *FakeProvider) Classify(op Operation) (ReplayClass, error) {
244 if op != OpProviderCall {
245 return "", fail(CodeUnknownKind, "provider cannot %s", op)
246 }
247 return ReplayUnsafe, nil // paid inference: never replay blind
248}
249
250type providerPayload struct {
251 Task string `json:"task"`
252 Prompt string `json:"prompt"`
253}
254
255func (p *FakeProvider) Execute(ctx context.Context, d Dispatch) (Receipt, error) {
256 var in providerPayload
257 if err := strictJSON(d.Payload, &in); err != nil {
258 return Receipt{}, err
259 }
260 p.mu.Lock()
261 defer p.mu.Unlock()
262 p.calls++
263 id := "prov-" + p.Name + "-" + short(d.Hash)
264 if p.unavailable {
265 return Receipt{ID: id, Outcome: OutcomeFailure, Provider: p.Name, Model: p.Model, Usage: &Usage{Calls: 1}, Detail: "provider unavailable"}, nil
266 }
267 out, ok := p.responses[in.Task]
268 if !ok {
269 return Receipt{ID: id, Outcome: OutcomeFailure, Provider: p.Name, Model: p.Model, Usage: &Usage{Calls: 1}, Detail: "no canned answer for " + in.Task}, nil
270 }
271 if p.loseReply {
272 return Receipt{}, fmt.Errorf("stream closed before the final usage event")
273 }
274 return Receipt{ID: id, Outcome: OutcomeSuccess, Provider: p.Name, Model: p.Model, Effort: "fixture",
275 Usage: &Usage{Calls: 1, InputTokens: int64(len(in.Prompt)), OutputTokens: int64(len(out)), CostMicros: int64(len(in.Prompt) + 3*len(out))},
276 Fields: map[string]string{"output": out}}, nil
277}
278
279func (p *FakeProvider) Reconcile(ctx context.Context, d Dispatch) (ReconcileResult, error) {
280 // Paid inference has no key-based lookup in this fixture: nothing is
281 // definitive, so an uncertain call stays uncertain.
282 return ReconcileResult{}, nil
283}
284
285// FakeForge records publications by logical key. LoseReply makes Execute
286// perform the publication and then fail to answer, the lost-reply case.
287// Definitive controls whether Reconcile may assert absence.
288type FakeForge struct {
289 mu sync.Mutex
290 published map[string]Receipt
291 loseReply bool
292 definitive bool
293}
294
295// NewFakeForge returns a forge whose Reconcile answers definitively.
296func NewFakeForge() *FakeForge {
297 return &FakeForge{published: map[string]Receipt{}, definitive: true}
298}
299
300// SetLoseReply toggles the lost-reply fault.
301func (f *FakeForge) SetLoseReply(v bool) {
302 f.mu.Lock()
303 defer f.mu.Unlock()
304 f.loseReply = v
305}
306
307// SetDefinitive toggles whether an absent key is a definitive answer.
308func (f *FakeForge) SetDefinitive(v bool) {
309 f.mu.Lock()
310 defer f.mu.Unlock()
311 f.definitive = v
312}
313
314// Published returns the receipt recorded for key, if any.
315func (f *FakeForge) Published(key string) (Receipt, bool) {
316 f.mu.Lock()
317 defer f.mu.Unlock()
318 r, ok := f.published[key]
319 return r, ok
320}
321
322func (f *FakeForge) Classify(op Operation) (ReplayClass, error) {
323 if op != OpForgePublish {
324 return "", fail(CodeUnknownKind, "forge cannot %s", op)
325 }
326 return ReplayReconcilable, nil
327}
328
329func (f *FakeForge) Execute(ctx context.Context, d Dispatch) (Receipt, error) {
330 var p publication
331 if err := strictJSON(d.Payload, &p); err != nil {
332 return Receipt{}, err
333 }
334 f.mu.Lock()
335 defer f.mu.Unlock()
336 if r, ok := f.published[d.Key]; ok {
337 return r, nil
338 }
339 r := Receipt{ID: "forge-" + short(d.Hash), Outcome: OutcomeSuccess, Provider: "fake-forge", Usage: &Usage{Calls: 1},
340 Fields: map[string]string{"repository": p.Repository, "ref": p.Ref, "head": p.Head, "review_url": "fake://" + p.Repository + "/review/" + short(p.Head)}}
341 if p.DescriptionHash != "" {
342 r.Fields["description_hash"] = p.DescriptionHash
343 r.Fields["candidate_hash"] = p.CandidateHash
344 r.Fields["qualified_ref"] = "refs/heads/" + p.Ref
345 r.Fields["agent"] = "fixture~operator@example.test"
346 }
347 f.published[d.Key] = r
348 if f.loseReply {
349 return Receipt{}, fmt.Errorf("connection reset after publish")
350 }
351 return r, nil
352}
353
354func (f *FakeForge) Reconcile(ctx context.Context, d Dispatch) (ReconcileResult, error) {
355 f.mu.Lock()
356 defer f.mu.Unlock()
357 if r, ok := f.published[d.Key]; ok {
358 return ReconcileResult{Receipt: &r, Definitive: true}, nil
359 }
360 return ReconcileResult{Definitive: f.definitive}, nil
361}
362
363// FakeTracker is the outbox destination: milestone events published
364// under idempotent keys through the same action path.
365type FakeTracker struct {
366 mu sync.Mutex
367 events map[string]Receipt
368}
369
370// NewFakeTracker returns an empty tracker.
371func NewFakeTracker() *FakeTracker { return &FakeTracker{events: map[string]Receipt{}} }
372
373// Events returns the number of distinct published events.
374func (t *FakeTracker) Events() int {
375 t.mu.Lock()
376 defer t.mu.Unlock()
377 return len(t.events)
378}
379
380func (t *FakeTracker) Classify(op Operation) (ReplayClass, error) {
381 if op != OpTrackerPublish {
382 return "", fail(CodeUnknownKind, "tracker cannot %s", op)
383 }
384 return ReplayIdempotent, nil
385}
386
387func (t *FakeTracker) Execute(ctx context.Context, d Dispatch) (Receipt, error) {
388 t.mu.Lock()
389 defer t.mu.Unlock()
390 if r, ok := t.events[d.Key]; ok {
391 return r, nil
392 }
393 r := Receipt{ID: "tracker-" + short(d.Hash), Outcome: OutcomeSuccess, Provider: "fake-tracker", Usage: &Usage{Calls: 1}}
394 t.events[d.Key] = r
395 return r, nil
396}
397
398func (t *FakeTracker) Reconcile(ctx context.Context, d Dispatch) (ReconcileResult, error) {
399 t.mu.Lock()
400 defer t.mu.Unlock()
401 if r, ok := t.events[d.Key]; ok {
402 return ReconcileResult{Receipt: &r, Definitive: true}, nil
403 }
404 return ReconcileResult{Definitive: true}, nil
405}
406
407// The fixture bug: Sum subtracts.
408const (
409 FixtureBaseSource = "func Sum(a, b int) int { return a - b }"
410 FixtureFixedSource = "func Sum(a, b int) int { return a + b }"
411 FixtureSymptom = "Sum(2, 3) = -1, want 5"
412)
413
414// FixtureReproduction is the reproduction the reproduce step freezes.
415var FixtureReproduction = mustJSON([]FixtureCase{
416 {Name: "sum_2_3", A: 2, B: 3, Want: 5},
417 {Name: "sum_0_0", A: 0, B: 0, Want: 0},
418 {Name: "sum_neg", A: -4, B: 1, Want: -3},
419})
420
421func mustJSON(v any) []byte {
422 b, err := json.Marshal(v)
423 if err != nil {
424 panic(err)
425 }
426 return b
427}
428
429// Workflow drives the fixture against a Store. Every step is a runner
430// in this process: claim, provider calls through the broker, artifact
431// registration under the current fence, completion and containment. Log
432// receives a transcript line per visible transition.
433type Workflow struct {
434 Store *Store
435 Scope Scope
436 Implementer *FakeProvider
437 Reviewer *FakeProvider
438 Forge *FakeForge
439 Tracker *FakeTracker
440 Supervisor string
441 Log func(format string, args ...any)
442}
443
444func (w *Workflow) logf(format string, args ...any) {
445 if w.Log != nil {
446 w.Log(format, args...)
447 }
448}
449
450// claim claims the step and returns the handle.
451func (w *Workflow) claim(ctx context.Context, step, runner, workspace string) (Handle, error) {
452 h, err := w.Store.Claim(ctx, w.Scope, step, runner, workspace)
453 if err != nil {
454 return h, err
455 }
456 w.logf("claim %-9s attempt=%d fence=%d runner=%s workspace=%s", step, h.Attempt, h.Fence, runner, workspace)
457 return h, nil
458}
459
460// call runs one provider call through intent, admission and dispatch and
461// returns the provider's output.
462func (w *Workflow) call(ctx context.Context, h Handle, key, task, prompt string) (string, Receipt, error) {
463 payload := mustJSON(providerPayload{Task: task, Prompt: prompt})
464 id, err := w.Store.Intend(ctx, w.Scope, h, IntentSpec{Key: key, Operation: OpProviderCall, Payload: payload,
465 Reserve: Usage{InputTokens: 32_000, OutputTokens: 4_000}})
466 if err != nil {
467 return "", Receipt{}, err
468 }
469 rc, err := w.Store.Dispatch(ctx, w.Scope, id)
470 if err != nil {
471 return "", Receipt{}, err
472 }
473 w.logf(" call %s action=%d receipt=%s outcome=%s usage=%+v", key, id, rc.ID, rc.Outcome, *rc.Usage)
474 if rc.Outcome != OutcomeSuccess {
475 return "", rc, fail(CodeState, "provider: %s", rc.Detail)
476 }
477 return rc.Fields["output"], rc, nil
478}
479
480// finish completes the attempt and has the supervisor contain it.
481func (w *Workflow) finish(ctx context.Context, h Handle, r AttemptResult) error {
482 if err := w.Store.Complete(ctx, w.Scope, h, r); err != nil {
483 return err
484 }
485 w.logf(" complete attempt=%d outcome=%s %s", h.Attempt, r.Outcome, r.Detail)
486 return w.Store.Contain(ctx, w.Scope, h.Attempt, w.Supervisor)
487}
488
489// Reproduce freezes the reproduction and records the base failure.
490func (w *Workflow) Reproduce(ctx context.Context, base []byte) (Artifact, CheckResult, error) {
491 h, err := w.claim(ctx, "reproduce", "runner-a", "ws-reproduce-"+strconv.Itoa(int(w.Scope.Job)))
492 if err != nil {
493 return Artifact{}, CheckResult{}, err
494 }
495 prov := Provenance{Producer: "runner-a", Provider: w.Implementer.Name, Model: w.Implementer.Model, Context: "ctx-reproduce"}
496 repro, err := w.Store.Register(ctx, w.Scope, h, ArtifactSpec{Role: RoleReproduction, MediaType: "application/json", Payload: FixtureReproduction, Provenance: prov})
497 if err != nil {
498 return Artifact{}, CheckResult{}, err
499 }
500 w.logf(" reproduction frozen hash=%s", short(repro.Hash))
501 cr := RunCheck(FixtureReproduction, base)
502 w.logf(" base check: %s run=%d failed=%d %q", cr.Outcome, cr.TestsRun, cr.TestsFailed, cr.FailureMessage)
503 if _, err := w.Store.Register(ctx, w.Scope, h, ArtifactSpec{Role: RoleBaseResult, MediaType: "application/json", Payload: mustJSON(cr), Provenance: prov}); err != nil {
504 return repro, cr, err
505 }
506 outcome := OutcomeSuccess
507 if cr.Outcome != CheckFail {
508 outcome = OutcomeFailure
509 }
510 return repro, cr, w.finish(ctx, h, AttemptResult{Outcome: outcome, Detail: "base " + string(cr.Outcome)})
511}
512
513// Implement asks the implementation provider for a candidate and
514// registers it. step names the implement step to claim.
515func (w *Workflow) Implement(ctx context.Context, step, workspace string) (Artifact, error) {
516 h, err := w.claim(ctx, step, "runner-a", workspace)
517 if err != nil {
518 return Artifact{}, err
519 }
520 out, rc, err := w.call(ctx, h, step+"/call-1", "implement", "fix Sum so that "+FixtureSymptom+" passes")
521 if err != nil {
522 return Artifact{}, err
523 }
524 prov := Provenance{Producer: "runner-a", Provider: rc.Provider, Model: rc.Model, Context: "ctx-" + step}
525 cand, err := w.Store.Register(ctx, w.Scope, h, ArtifactSpec{Role: RoleCandidate, MediaType: "text/x-fixture", Payload: []byte(out), Provenance: prov})
526 if err != nil {
527 return Artifact{}, err
528 }
529 w.logf(" candidate hash=%s by %s/%s", short(cand.Hash), prov.Provider, prov.Context)
530 return cand, w.finish(ctx, h, AttemptResult{Outcome: OutcomeSuccess, Detail: "candidate " + short(cand.Hash)})
531}
532
533// ReviewCandidate obtains an independent review of the latest candidate.
534// A provider refusal releases the attempt and leaves the job waiting on
535// the provider.
536func (w *Workflow) ReviewCandidate(ctx context.Context, workspace string, subject Artifact) (Artifact, error) {
537 h, err := w.claim(ctx, "review", "runner-b", workspace)
538 if err != nil {
539 return Artifact{}, err
540 }
541 out, rc, err := w.call(ctx, h, "review/call-"+workspace, "review", "review candidate "+subject.Hash+" against the brief")
542 if err != nil {
543 if rc.Outcome == OutcomeFailure {
544 w.logf(" reviewer unavailable: %s; releasing attempt %d", rc.Detail, h.Attempt)
545 if rerr := w.Store.Release(ctx, w.Scope, h, WaitProviderLimit, rc.Detail); rerr != nil {
546 return Artifact{}, rerr
547 }
548 return Artifact{}, errorsJoin(err, w.Store.Contain(ctx, w.Scope, h.Attempt, w.Supervisor))
549 }
550 return Artifact{}, err
551 }
552 verdict := VerdictReject
553 if strings.HasPrefix(out, "approve") {
554 verdict = VerdictApprove
555 }
556 prov := Provenance{Producer: "runner-b", Provider: rc.Provider, Model: rc.Model, Context: "ctx-review-" + workspace}
557 rv, err := w.Store.Register(ctx, w.Scope, h, ArtifactSpec{Role: RoleReview, MediaType: "application/json",
558 Payload: mustJSON(Review{SubjectHash: subject.Hash, Verdict: verdict, Notes: out}), Provenance: prov})
559 if err != nil {
560 return Artifact{}, err
561 }
562 w.logf(" review %s of %s by %s/%s", verdict, short(subject.Hash), prov.Provider, prov.Context)
563 return rv, w.finish(ctx, h, AttemptResult{Outcome: OutcomeSuccess, Detail: "review " + string(verdict)})
564}
565
566// Verify runs the frozen reproduction (fetched from the store, not the
567// workspace) on the candidate and registers the result.
568func (w *Workflow) Verify(ctx context.Context, repro Artifact, candidate Artifact) (CheckResult, error) {
569 h, err := w.claim(ctx, "verify", "runner-c", "ws-verify-"+strconv.Itoa(int(w.Scope.Job)))
570 if err != nil {
571 return CheckResult{}, err
572 }
573 frozen, err := w.Store.Artifact(ctx, w.Scope, repro.ID)
574 if err != nil {
575 return CheckResult{}, err
576 }
577 cr := RunCheck(frozen.Payload, candidate.Payload)
578 w.logf(" candidate check: %s run=%d failed=%d %q (reproduction %s on %s)", cr.Outcome, cr.TestsRun, cr.TestsFailed, cr.FailureMessage, short(cr.ReproductionHash), short(cr.SubjectHash))
579 prov := Provenance{Producer: "runner-c", Provider: "fixture-check", Context: "ctx-verify"}
580 if _, err := w.Store.Register(ctx, w.Scope, h, ArtifactSpec{Role: RoleCandidateResult, MediaType: "application/json", Payload: mustJSON(cr), Provenance: prov}); err != nil {
581 return cr, err
582 }
583 outcome := OutcomeSuccess
584 if cr.Outcome != CheckPass {
585 outcome = OutcomeFailure
586 }
587 return cr, w.finish(ctx, h, AttemptResult{Outcome: outcome, Detail: "candidate " + string(cr.Outcome)})
588}
589
590// Publish publishes the candidate to the bound review branch and then
591// the milestone to the tracker, both through the action path. It returns
592// the publish action id; on a lost reply the attempt is left open with
593// the action uncertain so the test can reconcile it.
594func (w *Workflow) Publish(ctx context.Context, candidate Artifact) (Handle, ActionID, error) {
595 h, err := w.claim(ctx, "publish", "runner-a", "ws-publish-"+strconv.Itoa(int(w.Scope.Job)))
596 if err != nil {
597 return h, 0, err
598 }
599 job, err := w.Store.GetJob(ctx, w.Scope)
600 if err != nil {
601 return h, 0, err
602 }
603 payload := mustJSON(publication{Repository: job.Target.Repository, Ref: job.Target.Ref, Head: candidate.Hash})
604 id, err := w.Store.Intend(ctx, w.Scope, h, IntentSpec{Key: "publish/" + short(candidate.Hash), Operation: OpForgePublish, Payload: payload})
605 if err != nil {
606 return h, 0, err
607 }
608 rc, err := w.Store.Dispatch(ctx, w.Scope, id)
609 if err != nil {
610 w.logf(" publish action=%d: %v", id, err)
611 return h, id, err
612 }
613 w.logf(" published head=%s receipt=%s %s", short(candidate.Hash), rc.ID, rc.Fields["review_url"])
614 return h, id, w.FinishPublish(ctx, h, candidate, rc)
615}
616
617// FinishPublish publishes the milestone event and completes the attempt.
618func (w *Workflow) FinishPublish(ctx context.Context, h Handle, candidate Artifact, forge Receipt) error {
619 ev := mustJSON(map[string]string{"event": "review_opened", "head": candidate.Hash, "receipt": forge.ID})
620 id, err := w.Store.Intend(ctx, w.Scope, h, IntentSpec{Key: "milestone/review_opened/" + short(candidate.Hash), Operation: OpTrackerPublish, Payload: ev})
621 if err != nil {
622 return err
623 }
624 rc, err := w.Store.Dispatch(ctx, w.Scope, id)
625 if err != nil {
626 return err
627 }
628 w.logf(" milestone published action=%d receipt=%s", id, rc.ID)
629 return w.finish(ctx, h, AttemptResult{Outcome: OutcomeSuccess, Detail: "published " + forge.ID})
630}
631
632// Conclude evaluates the evidence and logs the report.
633func (w *Workflow) Conclude(ctx context.Context) (EvidenceReport, error) {
634 rep, err := w.Store.Conclude(ctx, w.Scope, "coordinator")
635 if rep.Satisfied {
636 w.logf("conclude: SATISFIED reproduction=%s base=%s candidate=%s result=%s review=%s(%s) publication=%d/%s",
637 short(rep.Reproduction), short(rep.BaseResult), short(rep.Candidate), short(rep.CandidateResult), short(rep.Review), rep.Reviewer.Provider, rep.Publication, rep.PublishReceipt)
638 } else {
639 w.logf("conclude: NOT SATISFIED: %s", rep.Reason)
640 }
641 return rep, err
642}
643
644func errorsJoin(a, b error) error {
645 if b != nil {
646 return b
647 }
648 return a
649}
650
651// SoftwareSteps is the fixture's software graph. withRework adds a second
652// implement step after review, the post-review edit case.
653func SoftwareSteps(withRework bool) []StepSpec {
654 steps := []StepSpec{
655 {Key: "reproduce", Capability: CapReproduce, Version: 1},
656 {Key: "implement", Capability: CapImplement, Version: 1, DependsOn: []string{"reproduce"}},
657 {Key: "review", Capability: CapReview, Version: 1, DependsOn: []string{"implement"}},
658 }
659 verifyDeps := []string{"review"}
660 if withRework {
661 steps = append(steps, StepSpec{Key: "rework", Capability: CapImplement, Version: 1, DependsOn: []string{"review"}})
662 verifyDeps = []string{"rework"}
663 }
664 return append(steps,
665 StepSpec{Key: "verify", Capability: CapVerify, Version: 1, DependsOn: verifyDeps},
666 StepSpec{Key: "publish", Capability: CapPublish, Version: 1, DependsOn: []string{"verify"}},
667 )
668}
669
670// BusinessSteps is the Oficina-shaped graph: collect, reconcile, review.
671func BusinessSteps() []StepSpec {
672 return []StepSpec{
673 {Key: "collect", Capability: CapCollect, Version: 1},
674 {Key: "reconcile", Capability: CapReconcile, Version: 1, DependsOn: []string{"collect"}},
675 {Key: "review", Capability: CapReview, Version: 1, DependsOn: []string{"reconcile"}},
676 }
677}
678