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 "encoding/json"
5 "errors"
6 "strings"
7 "time"
8
9 "amadan.net/oficina/equipo/internal/wire"
10)
11
12// Previews on finished tasks (Paul, 2026-11-26: "Retry the Neary's
13// preview" was refused because both tasks were merged and done). A
14// preview is ancillary, so it may run again after its task ended: on a
15// task Equipo merged it builds the merged commit, otherwise the approved
16// candidate, as a new preview step; the task's stage, merge and other
17// steps stay as they are. It is published only through the preview's own
18// checks (previewRefusal). A preview that ended unconfirmed, or whose link
19// is gone, counts as one to run again, like a failed one.
20
21// Why a retry is refused, in fixed words: retry_step's result and
22// read_task's retry say them; people see the conflict, never these.
23const (
24 retryTaskCancelled = "task_cancelled"
25 retryTaskDone = "task_done"
26 retryNotEnded = "not_ended"
27 retryCompleted = "completed"
28 retryNotFailed = "not_failed"
29 retryNotNewest = "not_newest"
30 retryCommitChanged = "commit_changed"
31 retryNotApproved = "not_approved"
32 retryNoRunner = "no_runner"
33 retryNotYours = "not_yours"
34 retryNotOwner = "not_owner"
35 retryNoStep = "no_step"
36 // Notes beside a retry that can run (read_task's retry, retry_step's
37 // result): the merged commit could not be proven to be the merge of
38 // the approved candidate, so the approved candidate is built instead;
39 // a devbox link brought up after the task was done stays up until the
40 // next run replaces it.
41 retryMergeUnverified = "merge_unverified"
42 retryDevboxStaysUp = "devbox_stays_up"
43 // previewHostAuthority's reasons are used as they are:
44 // wire.ReasonRunnerOutdated, preview_host, preview_public_disabled.
45)
46
47// retryNotes is what the model reads back for each reason.
48var retryNotes = map[string]string{
49 retryTaskCancelled: "The task was cancelled: nothing of it runs again.",
50 retryTaskDone: "The task is done: only its preview can run again (step: preview). Its checks, review and merge stay as they are.",
51 retryNotEnded: "That step has not ended yet (queued or running, or its end is not proven). Wait for it; read_task shows it.",
52 retryCompleted: "That step did its work (its checks or review finished, or its preview link is up). There is nothing to run again.",
53 retryNotFailed: "That step was stopped, not failed: there is nothing to run again.",
54 retryNotNewest: "A newer step of that kind came after it: only the newest runs again.",
55 retryCommitChanged: "The commit it would judge or show is no longer the task's (the branch moved, or a new candidate came). read_task shows where it stands.",
56 retryNotApproved: "Review has not approved the task's commit, so no preview of it runs.",
57 retryNoRunner: "The person has no primary runner connected to run it on.",
58 retryNotYours: "That task is another person's: only the person who asked for it can run its steps again.",
59 retryNotOwner: "Only an owner's runner can run work.",
60 retryNoStep: "That task has no step of that kind yet.",
61 retryMergeUnverified: "Equipo could not prove the merged commit is exactly the merge of the approved commit, so a preview builds the approved commit itself, which Review approved, not the merged one.",
62 retryDevboxStaysUp: "Its preview link on the person's tailnet came up after the task was done; it stays up until the next preview of the task replaces it.",
63 wire.ReasonRunnerOutdated: "The person's primary runner is too old to make previews: it needs an update first.",
64 "preview_host": "The person's primary runner has no preview host now.",
65 "preview_public_disabled": "This project does not allow public previews now; an owner can turn them on in Settings.",
66 "not_retryable": toolStepNotRetried,
67}
68
69// retryRefusal is a refused retry with its fixed reason: errors.Is
70// matches its kind (ErrNotRetryable, ErrTaskEnded or ErrForbidden).
71type retryRefusal struct {
72 kind error
73 reason string
74}
75
76func (e retryRefusal) Error() string { return e.kind.Error() + ": " + e.reason }
77func (e retryRefusal) Unwrap() error { return e.kind }
78func refuseRetry(kind error, reason string) error { return retryRefusal{kind, reason} }
79
80// retryReasonOf is err's fixed reason, fallback when it has none.
81func retryReasonOf(err error, fallback string) string {
82 var r retryRefusal
83 if errors.As(err, &r) {
84 return r.reason
85 }
86 return fallback
87}
88
89// refusedRetry is retry_step's refusal: the code, and the reason with
90// what it means.
91func refusedRetry(code, reason string) wire.ToolResult {
92 note, ok := retryNotes[reason]
93 if !ok {
94 reason, note = "not_retryable", toolStepNotRetried
95 }
96 raw, _ := json.Marshal(map[string]string{"reason": reason, "note": note})
97 return refused(code, string(raw))
98}
99
100// approvedCandidate reports whether Review approved the task's candidate.
101func approvedCandidate(p progress) bool {
102 return p.candidate != "" && p.review != nil && p.review.State == wire.StepDone && p.review.Verdict == wire.VerdictApprove
103}
104
105// previewTarget is the commit a new preview of the task builds now: on a
106// done task Equipo merged, its merged commit when that is proven to be the
107// merge of the approved candidate (verifiedMerge), else the approved
108// candidate itself, which Review approved (note says merge_unverified);
109// otherwise the approved candidate while the branch is at it. "" when
110// there is none.
111func previewTarget(k taskRecord, p progress) (sha, note string) {
112 if !approvedCandidate(p) {
113 return "", ""
114 }
115 if k.Stage == wire.StageDone && k.MergedSHA != "" {
116 if m := verifiedMerge(k, p); m != "" {
117 return m, ""
118 }
119 // The candidate landed (the hub or the runner said so), so it is
120 // on the default branch's history whatever the branch did since.
121 return p.candidate, retryMergeUnverified
122 }
123 if p.moved {
124 return "", ""
125 }
126 return p.candidate, ""
127}
128
129// verifiedMerge is the task's merged commit when it is proven to bring in
130// exactly the approved candidate: the candidate itself (it landed as it
131// is), or the hub's own answer to this merge request, a merge commit whose
132// second parent is the candidate (MergeVerified, its parents recorded on
133// the merge step). "" otherwise: a reconciled or cached landing names the
134// commit the runner found, and past its 200-commit search the default
135// branch's tip, which may hold later work that nobody reviewed here.
136func verifiedMerge(k taskRecord, p progress) string {
137 m := p.merge
138 if k.Stage != wire.StageDone || k.MergedSHA == "" || m == nil || m.State != wire.StepDone || m.MergeSHA != k.MergedSHA || m.CandidateSHA != p.candidate {
139 return ""
140 }
141 if k.MergedSHA == p.candidate {
142 return k.MergedSHA
143 }
144 var parents []string
145 if json.Unmarshal([]byte(m.MergeParents), &parents) != nil {
146 return ""
147 }
148 if !k.MergeVerified || m.MergeSource != wire.MergeSourceHub || len(parents) != 2 || parents[1] != p.candidate || parents[0] == p.candidate || parents[0] == k.MergedSHA {
149 return ""
150 }
151 return k.MergedSHA
152}
153
154// previewMayBuild reports whether a preview of sha may run and publish
155// for the task now: the approved candidate while the branch is at it,
156// or, once the task is done, previewTarget.
157func previewMayBuild(k taskRecord, p progress, sha string) bool {
158 if sha == "" || !approvedCandidate(p) {
159 return false
160 }
161 target, _ := previewTarget(k, p)
162 return sha == p.candidate && !p.moved || k.Stage == wire.StageDone && sha == target
163}
164
165// previewOfTask reports whether a preview of sha stands for the task: of
166// its candidate cand, or of its merged commit once done (a preview of it
167// is only ever placed when verifiedMerge proved it).
168func previewOfTask(k taskRecord, cand, sha string) bool {
169 return sha != "" && (sha == cand || k.Stage == wire.StageDone && k.MergedSHA != "" && sha == k.MergedSHA)
170}
171
172// previewUp reports whether a preview step's link is served now:
173// deployed, before any expiry, and a devbox link only while its task runs
174// or is held for Publish (previewHeld), or one that came up after its task
175// was done (devboxAfterDone).
176func previewUp(k taskRecord, s stepRecord, now time.Time, held bool) bool {
177 r := decodePreview(s.Preview)
178 if s.State != wire.StepDone || r == nil || r.Outcome != wire.PreviewDeployed || r.URL == "" {
179 return false
180 }
181 if r.ExpiresAt != nil && !r.ExpiresAt.After(now) {
182 return false
183 }
184 if strings.HasPrefix(r.App, "eq-") && wire.FinalStage(k.Stage) && !held {
185 return devboxAfterDone(k, s)
186 }
187 return true
188}
189
190// devboxAfterDone: a devbox link that came up after its task was done (a
191// preview run again on a merged task). Nothing takes it down by itself:
192// the task's next preview replaces it, or the existing paths unshare it
193// (a known gap, retryDevboxStaysUp).
194func devboxAfterDone(k taskRecord, s stepRecord) bool {
195 r := decodePreview(s.Preview)
196 return r != nil && strings.HasPrefix(r.App, "eq-") && k.Stage == wire.StageDone && k.DoneAt != nil && s.FinishedAt != nil && s.FinishedAt.After(*k.DoneAt)
197}
198
199// previewRetryCheck is why a preview step cannot run again for person
200// now ("" when it can), and the commit it would build: the person's, on a
201// task not cancelled, the task's newest preview, ended and not up (failed,
202// cancelled, unconfirmed, expired, or a devbox link gone with its task),
203// a commit previewTarget names, on a primary whose preview host the
204// project allows now.
205func (t *txn) previewRetryCheck(k taskRecord, st stepRecord, person string) (reason, target string, err error) {
206 if st.Person != person {
207 return retryNotYours, "", nil
208 }
209 if k.CancelRequested || k.Stage == wire.StageCancelled {
210 return retryTaskCancelled, "", nil
211 }
212 steps, err := t.steps(k.ID)
213 if err != nil {
214 return "", "", err
215 }
216 for _, s := range steps {
217 if s.Specialist == wire.SpecialistPreview && s.Idx > st.Idx {
218 return retryNotNewest, "", nil
219 }
220 }
221 if !wire.StepTerminal(st.State) || !st.Terminated {
222 return retryNotEnded, "", nil
223 }
224 held := false
225 if wire.FinalStage(k.Stage) {
226 if held, err = t.previewHeld(k, steps); err != nil {
227 return "", "", err
228 }
229 }
230 // Up: nothing to run again, except a devbox link brought up after the
231 // task was done, which only the next run replaces.
232 if previewUp(k, st, t.now(), held) && !devboxAfterDone(k, st) {
233 return retryCompleted, "", nil
234 }
235 p := progressFor(k, steps)
236 if !approvedCandidate(p) {
237 return retryNotApproved, "", nil
238 }
239 target, _ = previewTarget(k, p)
240 if target == "" || k.Stage != wire.StageDone && st.CandidateSHA != target {
241 return retryCommitChanged, "", nil
242 }
243 primary, err := t.s.authority.PrimaryRunner(t.db, st.Person)
244 if err != nil || primary == "" {
245 return retryNoRunner, "", err
246 }
247 rs, err := t.runners(st.Person)
248 if err != nil {
249 return "", "", err
250 }
251 for _, r := range rs {
252 if r.ID == primary {
253 reason, err := t.previewHostAuthority(k.ProjectID, r)
254 return reason, target, err
255 }
256 }
257 return retryNoRunner, "", nil
258}
259
260// endedReason is why a step other than a preview cannot run again for
261// its state ("" when it failed and ended).
262func endedReason(st stepRecord, found bool) string {
263 switch {
264 case !found:
265 return retryNoStep
266 case !wire.StepTerminal(st.State) || !st.Terminated:
267 return retryNotEnded
268 case st.State == wire.StepDone:
269 return retryCompleted
270 case st.State == wire.StepCancelled:
271 return retryNotFailed
272 }
273 return ""
274}
275
276// retryReason is why person cannot run st again now ("" when they can),
277// as personRetry would decide for the coordinator: read_task's retry.
278func (t *txn) retryReason(k taskRecord, st stepRecord, person string) (string, error) {
279 if err := t.isOwner(person); errors.Is(err, ErrForbidden) {
280 return retryNotOwner, nil
281 } else if err != nil {
282 return "", err
283 }
284 if k.Creator != person {
285 return retryNotYours, nil
286 }
287 if k.CancelRequested || k.Stage == wire.StageCancelled {
288 return retryTaskCancelled, nil
289 }
290 if st.Specialist == wire.SpecialistPreview {
291 reason, _, err := t.previewRetryCheck(k, st, person)
292 return reason, err
293 }
294 if k.Stage == wire.StageDone {
295 return retryTaskDone, nil
296 }
297 latest, found, err := t.latestStep(k.ID)
298 if err != nil {
299 return "", err
300 }
301 if !found || latest.ID != st.ID {
302 return retryNotNewest, nil
303 }
304 if r := endedReason(st, true); r != "" {
305 return r, nil
306 }
307 if st.Person != person {
308 return retryNotYours, nil
309 }
310 primary, err := t.s.authority.PrimaryRunner(t.db, st.Person)
311 if err != nil || primary == "" {
312 return retryNoRunner, err
313 }
314 return "", nil
315}
316
317// retryView is read_task's word on running the task's newest step of a
318// kind again (wire.RetryStepKinds): Reason is "" when it can run.
319type retryView struct {
320 Step string `json:"step"`
321 StepID string `json:"step_id"`
322 Retryable bool `json:"retryable"`
323 Reason string `json:"reason,omitempty"`
324 // Note is a fixed note beside it (retryMergeUnverified,
325 // retryDevboxStaysUp), NoteText what it means.
326 Note string `json:"note,omitempty"`
327 NoteText string `json:"note_text,omitempty"`
328}
329
330func (t *txn) retryViews(k taskRecord, person string) ([]retryView, error) {
331 var out []retryView
332 for _, kind := range wire.RetryStepKinds {
333 var st stepRecord
334 res := t.db.Where("task_id = ? AND specialist = ? AND coalesce(retired, 0) = 0", k.ID, kind).Order("idx DESC").Limit(1).Find(&st)
335 if res.Error != nil {
336 return nil, res.Error
337 }
338 if res.RowsAffected == 0 {
339 continue
340 }
341 reason, err := t.retryReason(k, st, person)
342 if err != nil {
343 return nil, err
344 }
345 v := retryView{Step: kind, StepID: st.ID, Retryable: reason == "", Reason: reason}
346 if kind == wire.SpecialistPreview {
347 if v.Note, err = t.previewNote(k, st); err != nil {
348 return nil, err
349 }
350 v.NoteText = retryNotes[v.Note]
351 }
352 out = append(out, v)
353 }
354 return out, nil
355}
356
357// rerunPreview places a new preview step of target on a finished task,
358// beside its other steps (the timeline shows it after them); the task's
359// stage and its merge are untouched.
360func (t *txn) rerunPreview(k *taskRecord, st *stepRecord, target string, coordinator bool) (int64, error) {
361 steps, err := t.steps(k.ID)
362 if err != nil {
363 return 0, err
364 }
365 s := stepRecord{Specialist: wire.SpecialistPreview, Person: st.Person, Round: st.Round, BaseSHA: st.BaseSHA, CandidateSHA: target}
366 if coordinator {
367 s.CoordinatorAttempt = 1
368 }
369 if err := t.nextStep(k, steps, s); err != nil {
370 return 0, err
371 }
372 return 1, nil
373}
374
375// previewNote is the fixed note beside a task's newest preview: its link
376// on a done task stays up until replaced, or a new preview would build the
377// approved commit because the merged one is not proven.
378func (t *txn) previewNote(k taskRecord, st stepRecord) (string, error) {
379 if devboxAfterDone(k, st) && previewUp(k, st, t.now(), false) {
380 return retryDevboxStaysUp, nil
381 }
382 steps, err := t.steps(k.ID)
383 if err != nil {
384 return "", err
385 }
386 _, note := previewTarget(k, progressFor(k, steps))
387 return note, nil
388}
389