oficina / equipo Public

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

Plain git — no account needed to clone.

Download

Download this file

1package chat
2
3import (
4 "context"
5 "encoding/json"
6 "errors"
7 "fmt"
8 "strconv"
9 "strings"
10 "time"
11
12 "amadan.net/oficina/equipo/internal/equipo/housekeeping"
13 "amadan.net/oficina/equipo/internal/equipo/triage"
14 "amadan.net/oficina/equipo/internal/wire"
15 "gorm.io/gorm"
16)
17
18// Needs-you triage, thin v1 (spec 2026-11-11-equipo-needs-you-triage.md):
19// Needs you holds only decisions only the person can make. At the end of
20// advance, at start-up and on the tick, triage.Classify sorts what a task
21// needs; three deterministic actions run here, each a housekeeping ledger
22// row under the housekeeping principal (which may dispatch steps of its
23// own person's tasks and nothing else: never a merge, a merge card or an
24// ending). Everything else stays in Needs you with a recommendation
25// (triageView).
26
27// Triage's ledger detectors and class.
28const (
29 detTriageRetry = "triage_retry"
30 detTriageRebase = "triage_rebase"
31 detTriageRecheck = "triage_recheck"
32 detTriageStall = "triage_stall"
33 detTriageKick = "triage_kick"
34 classTriage = "triage"
35 // recheckHosted marks checks triage ran again on the same candidate
36 // for hosted CI (chat_steps.recheck_by; a Mac re-run names its runner).
37 recheckHosted = "hosted"
38)
39
40// errTriageStale: the situation that raised a triage key is gone (a
41// person's Retry, Cancel or hold, or a new step): nothing happens.
42var errTriageStale = errors.New("chat: triage source moved")
43
44// errTriageIdle: a stall sweep's kick found nothing to move on; the key
45// is consumed all the same, so it is not looked at every minute.
46var errTriageIdle = errors.New("chat: nothing to move on")
47
48var triageDetector = map[string]string{triage.ActRetry: detTriageRetry, triage.ActRebase: detTriageRebase, triage.ActRecheck: detTriageRecheck, triage.ActUnstick: detTriageStall, triage.ActKick: detTriageKick}
49
50// triageCost is what an action reserves and is charged: a retry, an
51// automatic round, or nothing (a re-check, once per candidate).
52func triageCost(action string) housekeeping.Cost {
53 switch action {
54 case triage.ActRetry, triage.ActUnstick:
55 return housekeeping.Cost{Retries: 1}
56 case triage.ActRebase:
57 return housekeeping.Cost{Rounds: 1}
58 }
59 return housekeeping.Cost{}
60}
61
62// triageKey is the ledger key of the action the facts call for: the step
63// and attempt it retries, or the candidate it rebases or re-checks.
64func triageKey(action string, p progress) string {
65 switch action {
66 case triage.ActRetry:
67 return "retry:" + p.last.ID + ":" + strconv.FormatInt(p.last.Attempt, 10)
68 case triage.ActRebase:
69 return "rebase:" + p.taskID + ":" + p.candidate
70 case triage.ActRecheck:
71 return "recheck:" + p.taskID + ":" + p.candidate
72 }
73 return ""
74}
75
76// triageEvidence is what an action row shows: the task, and the source
77// that raised it, recorded once when the row is first written and never
78// replaced: the newest step and attempt, its state and reason, and the
79// candidate. A held row acts later only if the task is still exactly
80// there.
81type triageEvidence struct {
82 housekeeping.Evidence
83 Reason string `json:"reason,omitempty"`
84 Source triageSource `json:"source"`
85}
86
87type triageSource struct {
88 Step string `json:"step"`
89 Attempt int64 `json:"attempt"`
90 State string `json:"state"`
91 Reason string `json:"reason"`
92 Candidate string `json:"candidate"`
93}
94
95func sourceOf(p progress) triageSource {
96 src := triageSource{Candidate: p.candidate}
97 if l := p.last; l != nil {
98 src.Step, src.Attempt, src.State, src.Reason = l.ID, l.Attempt, l.State, l.Reason
99 }
100 return src
101}
102
103// triageFacts reads what Classify needs of a task.
104func (t *txn) triageFacts(k taskRecord, p progress) (triage.Facts, error) {
105 f := triage.Facts{NeedsYou: p.needsYou(k), Ended: wire.FinalStage(k.Stage), CancelRequested: k.CancelRequested, Folded: k.FoldedInto != "", Merging: k.Stage == wire.StageMerging, Held: k.MergeHold != "", Ready: k.Stage == wire.StageReadyToMerge}
106 if l := p.last; l != nil {
107 f.Specialist, f.Reason, f.Terminated = l.Specialist, l.Reason, l.Terminated
108 f.OnWorker = t.onWorker(*l)
109 n, err := t.triageRows(k, detTriageRetry, "retry:"+l.ID+":%")
110 if err != nil {
111 return f, err
112 }
113 f.Retried = n > 0
114 }
115 if c := p.checks; c != nil && c.State == wire.StepDone && !p.moved {
116 f.Checks, f.ChecksReason = c.Checks, c.Reason
117 stale, err := t.checksStale(k, *c)
118 if err != nil {
119 return f, err
120 }
121 f.Stale = stale
122 var again int64
123 if err := t.db.Model(&stepRecord{}).Where("task_id = ? AND specialist = ? AND candidate_sha = ? AND recheck_by = ?", k.ID, wire.SpecialistChecks, p.candidate, recheckHosted).Count(&again).Error; err != nil {
124 return f, err
125 }
126 n, err := t.triageRows(k, detTriageRecheck, "recheck:"+k.ID+":"+p.candidate)
127 if err != nil {
128 return f, err
129 }
130 f.Rechecked = again > 0 || n > 0
131 }
132 if f.NeedsYou == wire.NeedsMergeConflict {
133 n, err := t.triageRows(k, detTriageRebase, "rebase:"+k.ID+":"+p.candidate)
134 if err != nil {
135 return f, err
136 }
137 all, err := t.triageRows(k, detTriageRebase, "rebase:%")
138 if err != nil {
139 return f, err
140 }
141 f.Rebased, f.Rebases = n > 0, int(all)
142 }
143 return f, nil
144}
145
146// triageRows counts the task's triage rows of detector whose key matches
147// (a LIKE pattern) and that acted or tried to: a held row has not.
148func (t *txn) triageRows(k taskRecord, detector, key string) (int64, error) {
149 var n int64
150 err := t.db.Model(&hkRecord{}).Where("subject_id = ? AND detector = ? AND finding_key LIKE ? AND state <> ?", k.ID, detector, key, wire.ActionHeld).Count(&n).Error
151 return n, err
152}
153
154// checksStale: checks that could not run, with no hosted binding, that
155// ended before the project's first hosted CI verdict. A project with no
156// hosted verdict is not a hosted-CI project, so nothing is stale there.
157func (t *txn) checksStale(k taskRecord, c stepRecord) (bool, error) {
158 if c.Checks != wire.ChecksCannotRun || c.HostedCI != "" || c.ChecksSandbox == wire.SandboxHosted || c.FinishedAt == nil {
159 return false, nil
160 }
161 var first []time.Time
162 if err := t.db.Raw("SELECT s.finished_at FROM chat_steps s JOIN chat_tasks k ON k.id = s.task_id WHERE k.project_id = ? AND s.checks_sandbox = ? AND s.finished_at IS NOT NULL ORDER BY s.finished_at LIMIT 1", k.ProjectID, wire.SandboxHosted).Scan(&first).Error; err != nil {
163 return false, err
164 }
165 return len(first) == 1 && c.FinishedAt.Before(first[0]), nil
166}
167
168// triage runs needs-you triage on a task: the action its facts call for,
169// claimed and carried out once (its key), or nothing. Never under the
170// principal; never for a creator who left the team, is not an owner, has
171// no primary runner (execution off, or no runner at all), or paused their
172// housekeeping.
173func (t *txn) triage(k *taskRecord) error {
174 if t.hk != nil || wire.FinalStage(k.Stage) || k.CancelRequested {
175 return nil
176 }
177 steps, err := t.steps(k.ID)
178 if err != nil {
179 return err
180 }
181 p := progressFor(*k, steps)
182 f, err := t.triageFacts(*k, p)
183 if err != nil {
184 return err
185 }
186 v := triage.Classify(f)
187 if v.Action == triage.ActNone {
188 return nil
189 }
190 if ok, err := t.triageMay(k.Creator); err != nil || !ok {
191 return err
192 }
193 return t.triageAct(k, v.Action, triageKey(v.Action, p), sourceOf(p))
194}
195
196// triageMay: the creator is a current member and owner with a primary
197// runner (execution on), whose housekeeping is not paused.
198func (t *txn) triageMay(person string) (bool, error) {
199 if ok, err := t.activeMember(person); err != nil || !ok {
200 return false, err
201 }
202 if t.isOwner(person) != nil {
203 return false, nil
204 }
205 if primary, err := t.s.authority.PrimaryRunner(t.db, person); err != nil || primary == "" {
206 return false, err
207 }
208 set, err := t.hkSettings(person)
209 if err != nil || set.Paused {
210 return false, err
211 }
212 return true, nil
213}
214
215// onWorker: the step is placed on a runner other than its person's
216// primary (a worker, a Mac), or one this instance cannot place: triage
217// leaves it to the person and the worker rules (the offline rule, the Mac
218// checks gate). Fails safe: an unknown runner counts as a worker.
219func (t *txn) onWorker(s stepRecord) bool {
220 if s.RunnerID == "" {
221 return false
222 }
223 role, err := t.s.authority.RunnerRole(t.db, s.RunnerID)
224 return err != nil || role != wire.RolePrimary
225}
226
227// stallStep is what the stall sweep reads of the newest step.
228func (t *txn) stallStep(l *stepRecord) (triage.Step, error) {
229 if l == nil {
230 return triage.Step{}, nil
231 }
232 s := triage.Step{Specialist: l.Specialist, State: l.State, Withdrawn: l.Withdrawn, Waiting: l.Placement == wire.PlacementWaiting || l.RunnerID == "", Worker: t.onWorker(*l), StartedAt: l.StartedAt, FinishedAt: l.FinishedAt, UpdatedAt: l.UpdatedAt}
233 if l.RunnerID != "" {
234 var n int64
235 if err := t.db.Model(&runnerSessionRecord{}).Where("runner_id = ? AND connected = ?", l.RunnerID, true).Count(&n).Error; err != nil {
236 return s, err
237 }
238 s.Online = n > 0
239 }
240 return s, nil
241}
242
243// stallAction is the stall sweep's action for a task now, and its key.
244func (t *txn) stallAction(k taskRecord, p progress) (string, string, error) {
245 f, err := t.triageFacts(k, p)
246 if err != nil || p.last == nil {
247 return "", "", err
248 }
249 s, err := t.stallStep(p.last)
250 if err != nil {
251 return "", "", err
252 }
253 action := triage.Stalled(f, s, f.NeedsYou, t.hkNow())
254 if action == triage.ActNone {
255 return "", "", nil
256 }
257 if action == triage.ActUnstick {
258 // Once per step, as a retry: an attempt placed again that stalls
259 // again is not taken back again.
260 return action, action + ":" + p.last.ID, nil
261 }
262 return action, action + ":" + p.last.ID + ":" + strconv.FormatInt(p.last.Attempt, 10), nil
263}
264
265// SweepStalled is the stall sweep, on housekeeping's minute (no polling of
266// runners): open tasks with no progress for a while get triage again; an
267// attempt running or waiting far past its time on an online runner is
268// taken back (the next attempt is placed, as a retry); a task left with
269// nothing scheduled is moved on. Each finding is keyed and acts once,
270// within the same budgets, under the principal (never a merge, a cancel or
271// a held task).
272func (s *Store) SweepStalled(ctx context.Context) (n int, err error) {
273 var ids []string
274 err = s.read(ctx, func(tx *gorm.DB) error {
275 quiet := s.hkClock().Add(-min(triage.StallQueued, triage.StallIdle))
276 return tx.Model(&taskRecord{}).Where("stage NOT IN ? AND (cancel_requested IS NULL OR cancel_requested = ?) AND updated_at < ?", []string{wire.StageDone, wire.StageCancelled}, false, quiet).Order("created_at, id").Pluck("id", &ids).Error
277 })
278 if err != nil {
279 return 0, err
280 }
281 for _, id := range ids {
282 if err := s.tx(ctx, func(t *txn) error {
283 k, err := t.loadTask(id)
284 if errors.Is(err, ErrNotFound) {
285 return nil
286 }
287 if err != nil {
288 return err
289 }
290 before := k.Revision
291 if err := t.sweepTask(&k); err != nil {
292 return err
293 }
294 if k.Revision != before {
295 n++
296 }
297 return nil
298 }); err != nil {
299 return n, err
300 }
301 }
302 return n, nil
303}
304
305func (t *txn) sweepTask(k *taskRecord) error {
306 if t.hk != nil || wire.FinalStage(k.Stage) || k.CancelRequested {
307 return nil
308 }
309 steps, err := t.steps(k.ID)
310 if err != nil {
311 return err
312 }
313 p := progressFor(*k, steps)
314 if p.needsYou(*k) != "" {
315 // A stopped task: the triage it may have missed.
316 return t.triage(k)
317 }
318 action, key, err := t.stallAction(*k, p)
319 if err != nil || action == "" {
320 return err
321 }
322 if ok, err := t.triageMay(k.Creator); err != nil || !ok {
323 return err
324 }
325 return t.triageAct(k, action, key, sourceOf(p))
326}
327
328// triageAct claims the action's ledger row and carries it out in a
329// savepoint under the principal. A row exists once per key and only a held
330// one is claimed again: done, failed and refused rows are consumed for
331// good and keep their charges. Lacking the day's budget, the row is held.
332func (t *txn) triageAct(k *taskRecord, action, key string, src triageSource) error {
333 team, err := t.team()
334 if err != nil {
335 return err
336 }
337 det, cost, person := triageDetector[action], triageCost(action), k.Creator
338 r, found, err := t.hkLoad(team, person, det, key)
339 if err != nil {
340 return err
341 }
342 if found && r.State != wire.ActionHeld {
343 return nil
344 }
345 now := t.hkNow()
346 if !found {
347 r = hkRecord{ID: newID("hk_"), Team: team, Person: person, Detector: det, FindingKey: key}
348 reason := src.Reason
349 if action == triage.ActUnstick {
350 // Said as a step that ran out of time.
351 reason = "step_timeout"
352 }
353 ev, _ := json.Marshal(triageEvidence{Evidence: housekeeping.Evidence{Tasks: []housekeeping.TaskRef{{ID: k.ID, Title: k.Title, Creator: k.Creator}}}, Reason: reason, Source: src})
354 r.SubjectKind, r.SubjectID, r.SubjectRevision, r.Class, r.Evidence = housekeeping.SubjectTask, k.ID, k.Revision, classTriage, string(ev)
355 } else {
356 // A held row keeps the source it was raised for.
357 var ev triageEvidence
358 if json.Unmarshal([]byte(r.Evidence), &ev) != nil || ev.Source.Step == "" {
359 return nil
360 }
361 src = ev.Source
362 }
363 r.Reason, r.Attempt, r.ReservedRetries, r.ReservedRounds = "", "", 0, 0
364 day := housekeeping.DayStart(now, t.zone(person))
365 used, _, err := t.hkUsed(person, day)
366 if err != nil {
367 return err
368 }
369 if !triageFits(used, cost) {
370 r.State, r.Reason, r.ClaimedAt = wire.ActionHeld, wire.ReasonHeldBudget, nil
371 return t.hkSave(&r, !found)
372 }
373 r.ClaimedAt = &now
374 pr := Principal{Team: team, Person: person, Detector: det, FindingID: r.ID, Reserved: cost, Dispatch: true}
375 var started string
376 err = t.savepoint(func(in *txn) error {
377 in.hk = &pr
378 var e error
379 started, e = in.triageDo(k.ID, action, key, src)
380 return e
381 })
382 switch {
383 case errors.Is(err, errTriageIdle):
384 r.State, r.Reason, r.ClaimedAt = wire.ActionExpired, "idle", nil
385 return t.hkSave(&r, !found)
386 case errors.Is(err, errTriageStale):
387 if !found {
388 return nil
389 }
390 // A held key whose situation moved on: it never acts.
391 r.State, r.Reason, r.ClaimedAt = wire.ActionExpired, wire.ReasonSubjectMoved, nil
392 return t.hkSave(&r, false)
393 case err == nil:
394 r.State, r.Attempt = wire.ActionDone, started
395 case errors.Is(err, ErrHousekeepingForbidden):
396 r.State, r.Reason = wire.ActionRefused, wire.ReasonHousekeepingForbidden
397 default:
398 r.State, r.Reason = wire.ActionFailed, clip(err.Error(), 200)
399 }
400 // The dispatch is the action: its unit is charged at once, and a
401 // failure is consumed too, so it cannot buy another try.
402 r.ReservedRetries, r.ReservedRounds = cost.Retries, cost.Rounds
403 r.ChargedRetries, r.ChargedRounds = cost.Retries, cost.Rounds
404 if err := t.hkSave(&r, !found); err != nil {
405 return err
406 }
407 if r.State != wire.ActionDone {
408 return nil
409 }
410 // The caller's copy of the task is behind what the action wrote.
411 fresh, err := t.loadTask(k.ID)
412 if err != nil {
413 return err
414 }
415 *k = fresh
416 return nil
417}
418
419// triageFits: the action's unit fits today's retries and automatic
420// rounds. Tokens are recorded on the rows, never a gate here (spec §2.4).
421func triageFits(used, c housekeeping.Cost) bool {
422 return used.Retries+c.Retries <= housekeeping.Limits.Retries && used.Rounds+c.Rounds <= housekeeping.Limits.Rounds
423}
424
425// triageDo carries out an action under the principal, after reading the
426// task afresh and checking that its facts still call for this very key:
427// a person's Retry (a new attempt), Cancel, hold or any new step makes it
428// stale. It returns the step attempt it started (step:<id>:<attempt>).
429func (t *txn) triageDo(id, action, key string, src triageSource) (string, error) {
430 k, err := t.loadTask(id)
431 if err != nil {
432 return "", err
433 }
434 steps, err := t.steps(k.ID)
435 if err != nil {
436 return "", err
437 }
438 p := progressFor(k, steps)
439 f, err := t.triageFacts(k, p)
440 if err != nil {
441 return "", err
442 }
443 if action == triage.ActUnstick || action == triage.ActKick {
444 if a, kk, err := t.stallAction(k, p); err != nil {
445 return "", err
446 } else if a != action || kk != key || sourceOf(p) != src {
447 return "", errTriageStale
448 }
449 } else if v := triage.Classify(f); v.Action != action || triageKey(action, p) != key || sourceOf(p) != src || t.isOwner(k.Creator) != nil {
450 return "", errTriageStale
451 }
452 switch action {
453 case triage.ActUnstick:
454 l := *p.last
455 if l.Specialist == wire.SpecialistMerge {
456 return "", fmt.Errorf("%w: merge", ErrHousekeepingForbidden)
457 }
458 if err := t.withdraw(&k, &l); err != nil {
459 return "", err
460 }
461 case triage.ActKick:
462 before := k.Revision
463 if err := t.advanceTask(&k); err != nil {
464 return "", err
465 }
466 fresh, err := t.loadTask(k.ID)
467 if err != nil {
468 return "", err
469 }
470 if fresh.Revision == before {
471 return "", errTriageIdle
472 }
473 case triage.ActRetry:
474 if p.last.Specialist == wire.SpecialistMerge {
475 // Never, by construction: Classify does not pick merge steps and
476 // the principal refuses them in retryStep. A third guard here.
477 return "", fmt.Errorf("%w: merge", ErrHousekeepingForbidden)
478 }
479 if _, err := t.retryStep(&k, k.Creator); err != nil {
480 return "", err
481 }
482 case triage.ActRebase:
483 if p.eng == nil {
484 return "", errTriageStale
485 }
486 s := stepRecord{Specialist: wire.SpecialistEngineering, Person: p.eng.Person, Round: p.eng.Round, Rebase: true, FromBase: k.BaseSHA, FromCandidate: p.candidate}
487 k.Stage = wire.StageInProgress
488 if err := t.nextStep(&k, steps, s); err != nil {
489 return "", err
490 }
491 case triage.ActRecheck:
492 if p.eng == nil || p.merge != nil {
493 return "", errTriageStale
494 }
495 s := stepRecord{Specialist: wire.SpecialistChecks, Person: p.eng.Person, Round: p.eng.Round, BaseSHA: k.BaseSHA, CandidateSHA: p.candidate, RecheckBy: recheckHosted}
496 k.Stage = wire.StageInReview
497 if err := t.nextStep(&k, steps, s); err != nil {
498 return "", err
499 }
500 default:
501 return "", errTriageStale
502 }
503 s, found, err := t.latestStep(k.ID)
504 if err != nil || !found {
505 return "", err
506 }
507 return stepAttempt(s), nil
508}
509
510func stepAttempt(s stepRecord) string {
511 return "step:" + s.ID + ":" + strconv.FormatInt(s.Attempt, 10)
512}
513
514// triageSettle records the tokens a triage action's step attempt spent,
515// recomputed whenever usage for it arrives (a late or replayed report
516// changes nothing twice): its usage rows counted as rowSpend counts them (Claude's
517// cache reads and writes included), incomplete when any figure is
518// missing, never zero for unknown (the row says incomplete).
519func (t *txn) triageSettle(person, step string, attempt int64) error {
520 s := stepRecord{ID: step, Attempt: attempt}
521 var r hkRecord
522 err := t.db.Where("person = ? AND class = ? AND attempt = ?", person, classTriage, stepAttempt(s)).First(&r).Error
523 if errors.Is(err, gorm.ErrRecordNotFound) {
524 return nil
525 }
526 if err != nil {
527 return err
528 }
529 var rows []usageRecord
530 if err := t.db.Where("step_id = ? AND attempt = ?", s.ID, s.Attempt).Find(&rows).Error; err != nil {
531 return err
532 }
533 var tokens int64
534 complete := len(rows) > 0
535 for _, u := range rows {
536 sp := rowSpend(u)
537 tokens += sp.Tokens
538 complete = complete && !sp.Partial
539 }
540 if r.ChargedTokens == tokens && r.ChargedComplete == complete {
541 return nil
542 }
543 r.ChargedTokens, r.ChargedComplete = tokens, complete
544 return t.hkSave(&r, false)
545}
546
547// Retriage passes over open tasks once (spec §3): at start-up every open
548// task, and on the tick those with a held triage row. One transaction per
549// task; the keys make it idempotent.
550func (s *Store) Retriage(ctx context.Context, heldOnly bool) (n int, err error) {
551 var ids []string
552 err = s.read(ctx, func(tx *gorm.DB) error {
553 if heldOnly {
554 return tx.Model(&hkRecord{}).Distinct("subject_id").Where("class = ? AND state = ?", classTriage, wire.ActionHeld).Pluck("subject_id", &ids).Error
555 }
556 return tx.Model(&taskRecord{}).Where("stage NOT IN ? AND (cancel_requested IS NULL OR cancel_requested = ?)", []string{wire.StageDone, wire.StageCancelled}, false).Order("created_at, id").Pluck("id", &ids).Error
557 })
558 if err != nil {
559 return 0, err
560 }
561 for _, id := range ids {
562 if err := s.tx(ctx, func(t *txn) error {
563 k, err := t.loadTask(id)
564 if errors.Is(err, ErrNotFound) {
565 return nil
566 }
567 if err != nil {
568 return err
569 }
570 before := k.Revision
571 if err := t.triage(&k); err != nil {
572 return err
573 }
574 if k.Revision != before {
575 n++
576 }
577 return nil
578 }); err != nil {
579 return n, err
580 }
581 }
582 return n, nil
583}
584
585// triageView is what the task shows of triage: what Equipo is doing about
586// it while its action's step runs, or, when it needs its person, Equipo's
587// recommendation, why it did not act, and what Review and hosted CI said
588// last.
589func (t *txn) triageView(v *wire.Task, k taskRecord, steps []stepRecord, p progress) error {
590 if wire.FinalStage(k.Stage) {
591 return nil
592 }
593 if l := p.last; l != nil && !wire.StepTerminal(l.State) {
594 // The action that started this attempt: a retry names it; a stall's
595 // take-back names the attempt it withdrew, which the next replaced.
596 prev := *l
597 prev.Attempt--
598 var r hkRecord
599 err := t.db.Where("subject_id = ? AND class = ? AND state = ? AND (attempt = ? OR detector = ? AND attempt = ?)", k.ID, classTriage, wire.ActionDone, stepAttempt(*l), detTriageStall, stepAttempt(prev)).Order("at DESC, id DESC").First(&r).Error
600 if errors.Is(err, gorm.ErrRecordNotFound) {
601 return nil
602 }
603 if err != nil {
604 return err
605 }
606 kind := map[string]string{detTriageRetry: wire.TriageRetrying, detTriageStall: wire.TriageRetrying, detTriageRebase: wire.TriageRebasing, detTriageRecheck: wire.TriageRechecking}[r.Detector]
607 if kind == "" {
608 return nil
609 }
610 var ev triageEvidence
611 _ = json.Unmarshal([]byte(r.Evidence), &ev)
612 at := r.At
613 v.Triage = &wire.TaskTriage{Kind: kind, Reason: ev.Reason, Since: &at}
614 return nil
615 }
616 if v.NeedsYou == "" {
617 return nil
618 }
619 f, err := t.triageFacts(k, p)
620 if err != nil {
621 return err
622 }
623 verdict := triage.Classify(f)
624 if verdict.Waiting != "" {
625 v.Triage = &wire.TaskTriage{Kind: wire.TriageWaiting, Reason: verdict.Waiting}
626 return nil
627 }
628 out := wire.TaskTriage{Kind: wire.TriageAsking, Recommend: verdict.Recommend, Why: verdict.Why}
629 if verdict.Action != triage.ActNone {
630 // It would act but has not: held for today's budget, or about to.
631 team, err := t.team()
632 if err != nil {
633 return err
634 }
635 r, found, err := t.hkLoad(team, k.Creator, triageDetector[verdict.Action], triageKey(verdict.Action, p))
636 if err != nil {
637 return err
638 }
639 if !found || r.State != wire.ActionHeld {
640 return nil
641 }
642 out.Why = wire.TriageWhyBudget
643 out.Recommend = map[string]string{triage.ActRetry: wire.RecommendRetry, triage.ActRebase: wire.RecommendRebase}[verdict.Action]
644 }
645 out.Said, out.Failed = lastWord(steps, p)
646 if out.Recommend == "" && out.Why == "" {
647 return nil
648 }
649 v.Triage = &out
650 return nil
651}
652
653// lastWord is what Review said last (its first finding's headline, else
654// its summary, in one line) when it asked for changes, and hosted CI's
655// failing units on the judged checks.
656func lastWord(steps []stepRecord, p progress) (said string, failed []string) {
657 for i := len(steps) - 1; i >= 0; i-- {
658 r := steps[i]
659 kind := wire.KindChange
660 if p.explore {
661 kind = wire.KindExplore
662 }
663 if r.Specialist != wire.SpecialistReview || r.State != wire.StepDone || r.Verdict == "" || !counts(&r, kind) {
664 continue
665 }
666 if r.Verdict == wire.VerdictChanges {
667 for _, f := range decodeFindings(r.Findings) {
668 if said = headline(f); said != "" {
669 break
670 }
671 }
672 if said == "" {
673 said = strings.Join(strings.Fields(r.Summary), " ")
674 }
675 }
676 break
677 }
678 said = clipText(said, wire.MaxTriageSaid)
679 if c := p.checks; c != nil && c.Checks == wire.ChecksFailed && c.HostedCI != "" {
680 var h wire.HostedResult
681 if json.Unmarshal([]byte(c.HostedCI), &h) == nil {
682 failed = h.Failed
683 }
684 }
685 return said, failed
686}
687
688// headline is a finding's one plain line: its headline, else its text's
689// first line.
690func headline(f wire.Finding) string {
691 if h := strings.TrimSpace(f.Headline); h != "" {
692 return h
693 }
694 line, _, _ := strings.Cut(strings.TrimSpace(f.Text), "\n")
695 return strings.TrimSpace(line)
696}
697
698// RoundTask is Try another round (POST /api/v1/tasks/{id}/round): the
699// creator, an owner, sends Engineering one more round on a task Review or
700// the checks still object to after the automatic rounds, with their last
701// feedback, or one more rebase of a candidate that conflicts with the
702// default branch. The person's tap: never budgeted.
703func (s *Store) RoundTask(ctx context.Context, person, id string) (attempt int64, err error) {
704 err = s.tx(ctx, func(t *txn) error {
705 if err := s.authority.CurrentPerson(ctx, t.db); err != nil {
706 return err
707 }
708 if err := t.isOwner(person); err != nil {
709 return err
710 }
711 k, err := t.loadTask(id)
712 if err != nil {
713 return err
714 }
715 if k.Creator != person {
716 return ErrForbidden
717 }
718 if wire.FinalStage(k.Stage) || k.CancelRequested {
719 return ErrTaskEnded
720 }
721 steps, err := t.steps(k.ID)
722 if err != nil {
723 return err
724 }
725 p := progressFor(k, steps)
726 if p.eng == nil || p.candidate == "" {
727 return ErrNotRetryable
728 }
729 var st stepRecord
730 switch p.needsYou(k) {
731 case wire.NeedsFixRounds:
732 st = stepRecord{Specialist: wire.SpecialistEngineering, Person: p.eng.Person, Round: max(k.RepairRound, p.eng.Round) + 1, BaseSHA: p.candidate}
733 case wire.NeedsMergeConflict:
734 st = stepRecord{Specialist: wire.SpecialistEngineering, Person: p.eng.Person, Round: p.eng.Round, Rebase: true, FromBase: k.BaseSHA, FromCandidate: p.candidate}
735 default:
736 return ErrNotRetryable
737 }
738 k.Stage = wire.StageInProgress
739 if err := t.nextStep(&k, steps, st); err != nil {
740 return err
741 }
742 attempt = 1
743 return nil
744 })
745 return attempt, err
746}
747