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 "crypto/rand"
6 "encoding/json"
7 "errors"
8 "fmt"
9 "path"
10 "regexp"
11 "slices"
12 "strings"
13 "time"
14 "unicode/utf8"
15
16 "amadan.net/oficina/equipo/internal/copydesk"
17 "amadan.net/oficina/equipo/internal/equipo/housekeeping"
18 "amadan.net/oficina/equipo/internal/equipo/mergegate"
19 "amadan.net/oficina/equipo/internal/wire"
20 "amadan.net/oficina/equipo/internal/wire/forgekey"
21 "gorm.io/gorm"
22)
23
24var (
25 // ErrTaskEnded means the task is done or cancelled.
26 ErrTaskEnded = errors.New("chat: task ended")
27 // ErrMerging means Equipo is merging the task: it cannot be cancelled
28 // until the hub's outcome is known (Done, or back at Ready to merge).
29 ErrMerging = errors.New("chat: task merging")
30 // ErrNotRetryable means the task's step has not ended with the
31 // runner's termination proof, or there is nothing to retry.
32 ErrNotRetryable = errors.New("chat: step not retryable")
33)
34
35// taskRecord is one piece of work under a project. Tasks are team
36// records: every active member sees them; the creator's turn noted it.
37type taskRecord struct {
38 MoveProject string `gorm:"index:chat_task_move,priority:2,where:move_project IS NOT NULL AND move_project <> ''"`
39 MoveBy string
40 MoveAbandoned bool
41 MoveRestart bool
42 MoveCount int64
43 CopyHold bool
44 RepairRound int
45 CopyRecovery string
46 ID string `gorm:"primaryKey"`
47 ProjectID string `gorm:"index:chat_task_project"`
48 Title string
49 Brief string
50 Stage string
51 Branch string
52 BaseSHA string
53 Creator string `gorm:"index:chat_task_move,priority:1,where:move_project IS NOT NULL AND move_project <> ''"`
54 TurnID string
55 CancelRequested bool
56 Revision int64
57 CreatedAt time.Time
58 UpdatedAt time.Time
59 // Watching is the candidate the runner was asked to watch for a merge.
60 Watching string
61 // MovedFrom is the candidate the task branch moved away from (to
62 // BranchHead, "" when the branch is gone); while it is the newest
63 // candidate, nothing judged of it applies.
64 MovedFrom string
65 BranchHead string
66 // MergeAsked is the candidate the merge card asked about (checks that
67 // could not run): asked once per SHA.
68 MergeAsked string
69 // Merged*: Equipo's merge of the task, once the hub confirmed it.
70 MergedSHA string
71 MergedInto string
72 MergeStrategy string
73 MergedWithoutChecks bool
74 MergedAt *time.Time
75 // ReadySHA is the candidate that first earned Ready to merge under the
76 // merge policy (or was Ready when the policy arrived: migration 0047);
77 // MergeEligible is the candidate Equipo may merge on its own, set only
78 // at that first time with checks passed. Leaving Ready and coming back
79 // grants nothing.
80 ReadySHA string
81 MergeEligible string
82 // DoneAt is when the task became done: its specialists can be asked
83 // about their work for wire.KeepMergedSessions after.
84 DoneAt *time.Time
85 // DuplicateOf is an open task that read like this one when it was
86 // recorded anyway, or the task it was folded into.
87 DuplicateOf string
88 // FoldedInto is the task Equipo combined this one into, FoldedStage the
89 // stage it had then (Undo restores it) and FoldedAt when.
90 FoldedInto string
91 FoldedStage string
92 FoldedAt *time.Time
93 // EngineeringRunner is pinned at the first Engineering step: fix
94 // rounds, retries and republishes go there, so two runners never
95 // touch one branch.
96 EngineeringRunner string
97 // MacNeeds are the Mac tags (JSON) the task's Engineering was first
98 // found to need: written once by placement (recordMacNeeds), never
99 // cleared and never in saveTask, so no later catalog, pin or
100 // removal makes it Linux work (migration 0120).
101 MacNeeds string
102 // Merge authority: MergeHold is the coordinator's hold (it can only
103 // stop Equipo merging on its own); MergeVerified, that the merge SHA
104 // came from the hub's own answer with the candidate as second parent
105 // (only then is Undo offered); RevertOf and RevertSHA make this task
106 // the revert of another task's merge commit.
107 MergeHold string
108 MergeVerified bool
109 RevertOf string
110 RevertSHA string
111 // Kind is wire.KindExplore for an exploration ("" or change otherwise):
112 // it ends at its creator's choice of direction, never a merge.
113 // DirectionAsked is the candidate the direction card asked about;
114 // BuiltAs the change task "Build this one" made of it, and on that
115 // task ExploredFrom this exploration.
116 Kind string
117 DirectionAsked string
118 BuiltAs string
119 ExploredFrom string
120 // The scheduler (connectors spec S3): the task's priority ("" is
121 // normal), its deadline, and who set them: the coordinator at the
122 // task's creation, or the creator's own tap.
123 Priority string
124 DueBy *time.Time
125 PrioritySetBy string
126 // PriorityRevision orders the priority and deadline: every change
127 // bumps it, and dispatches and priority frames carry it.
128 PriorityRevision int64
129 // PublishAsked is the merged commit the publish card asked about.
130 PublishAsked string
131 // Lane is the lane of the turn that recorded the task: job:<id> for a
132 // job thread's, "" for the person's own (J4). Its cards are raised
133 // there; a job that only joins it changes nothing.
134 Lane string `gorm:"index:chat_task_lane"`
135 // MakerSpecialistID is the data specialist that makes the task's
136 // changes ("" is Engineering): fix rounds, retries, Try again and the
137 // task Build makes of it use it. DesignRuns counts its Design attempts
138 // (first runs, retries, fix rounds) since the person last acted on
139 // the task.
140 MakerSpecialistID string `gorm:"not null;default:''"`
141 DesignRuns int64 `gorm:"not null;default:0"`
142}
143
144func (taskRecord) TableName() string { return "chat_tasks" }
145
146// stepRecord is one specialist's run on the task branch. Person is whose
147// runner executes it; Attempt grows with each Retry.
148type stepRecord struct {
149 Retired bool
150 CopyOwner string
151 CopyRevision int64
152 CopyResult string
153 FailureSignature string
154 ID string `gorm:"primaryKey"`
155 TaskID string `gorm:"index:chat_step_task"`
156 Idx int
157 Specialist string
158 // AbilityHeld marks an attempt the build hold refused at its start
159 // (resumeAbilityHold gives it a fresh attempt).
160 AbilityHeld bool
161 Person string
162 State string
163 Reason string
164 Attempt int64
165 BaseSHA string
166 CandidateSHA string
167 Pushed bool
168 Terminated bool
169 Summary string
170 Headline string
171 LogTail string
172 StartedAt *time.Time
173 FinishedAt *time.Time
174 Revision int64
175 CreatedAt time.Time
176 UpdatedAt time.Time
177 // Round is the fix round; Family and Account what ran it. Checks and
178 // review judge CandidateSHA, set when they are dispatched; their
179 // results are stored here, beside that SHA. Findings is JSON.
180 Round int
181 Family string
182 Account string
183 // Model is the model the step's newest attempt ran on, as its usage
184 // reported (§16.7: shown on the step).
185 Model string
186 Verdict string
187 ReviewLabel string
188 Findings string
189 Checks string
190 Gate string
191 ExitCode *int
192 Output string
193 // Republish pushes the commit FromAttempt recorded again, without
194 // running the specialist.
195 Republish bool
196 FromAttempt int64
197 // Askable: the runner kept the step's session, so it can be asked.
198 Askable bool
199 // Rebase: an Engineering round putting FromCandidate (made on
200 // FromBase) on top of the default branch's new tip.
201 Rebase bool
202 FromBase string
203 FromCandidate string
204 // Merge steps: the commit the hub made, where and how; WithoutChecks
205 // when the person chose to merge a SHA whose checks could not run.
206 MergeSHA string
207 MergeInto string
208 MergeStrategy string
209 WithoutChecks bool
210 // Switched is the wire.Switched JSON when the step moved connection.
211 Switched string
212 // Activity is the newest activity lines of the attempt (JSON).
213 Activity string
214 // RunnerID is the runner the current attempt is placed on ("" while
215 // Placement is waiting_runner). Needs is a JSON list of tags.
216 // RefusedBy lists runners that refused it (placement_refused).
217 // Withdrawn: the current attempt was withdrawn after it started; the
218 // next attempt is placed once its termination is proven.
219 RunnerID string `gorm:"index:chat_step_runner"`
220 Needs string
221 Placement string
222 WaitingSince *time.Time
223 RefusedBy string
224 Withdrawn bool
225 TerminationKind string
226 // Publication of a worker's Engineering candidate by the primary.
227 Publication string
228 PublicationID string
229 // PublicationRunner is the primary the publication was given to: only
230 // it may answer it (Mac runners slice F).
231 PublicationRunner string
232 // Apple: Engineering's change touched Apple files (its checks need
233 // macOS).
234 Apple bool
235 // ChecksSandbox is how a worker's checks were confined: seatbelt, or
236 // none when they ran outside the sandbox (Paul's ruling 2). "" is the
237 // primary's bubblewrap.
238 ChecksSandbox string
239 BaseChecks string
240 BaseChecksSHA string
241 // XcodeAccess is what a Mac worker's Engineering ran with
242 // (wire.XcodeAccessSandboxed or ""); OutcomePhase what its commit is
243 // (wire.OutcomeCommitted, OutcomeUnfinished, OutcomeNoShell), kept
244 // apart from Publication; SessionID the kept Engineering session
245 // (migration 0120).
246 XcodeAccess string
247 OutcomePhase string
248 SessionID string
249 // OnWorker: the current attempt was dispatched to a worker, not the
250 // person's main runner, as decided at its dispatch (migration 0120).
251 // Never recomputed against a later main runner.
252 OnWorker bool
253 // ChangeFacts is the review's measured change (wire.ChangeFacts JSON),
254 // kept only when it passed acceptance. DecidedBy is who decided a
255 // merge step ("policy", or "person:<address>"); MergeSource and
256 // MergeParents (JSON) where its SHA came from.
257 ChangeFiles string // Presentation only: bounded Engineering file list.
258 ChangeDiffExpiresAt *time.Time // Private retention marker, never projected into task tools.
259 ChangeDiffAttempt int64
260 ChangeFacts string
261 DecidedBy string
262 MergeSource string
263 MergeParents string
264 // RecheckBy is the runner whose arrival ran these checks again, after
265 // they waited for a Mac (macrecheck.go). Set only at creation.
266 RecheckBy string
267 // HostedCI is the binding of a checks verdict taken from the hub's
268 // hosted CI (wire.HostedResult JSON; ChecksSandbox is then hosted).
269 HostedCI string
270 // Kind is the task's kind this attempt was dispatched under (a Review
271 // counts only for it, or as a change); Note the person's words for an
272 // exploration's Try again round.
273 Kind string
274 Note string
275 // HasPreview: Review found a preview config on its candidate
276 // (scheduling evidence). Preview is a preview step's
277 // wire.PreviewResult JSON: built, then done.
278 HasPreview bool
279 Preview string
280 // Publish is a publish step's app, then its built export and outcome
281 // (wire.PublishResult as JSON).
282 Publish string
283 // SandboxRunner is the Mac checks wait for while Placement is
284 // waiting_sandbox. Unsandboxed*: the task creator's choice (who and
285 // when) to run attempt UnsandboxedAttempt on UnsandboxedRunner
286 // outside the sandbox (macsandbox.go); it holds for that attempt on
287 // that Mac only.
288 SandboxRunner string
289 UnsandboxedBy string
290 UnsandboxedAt *time.Time
291 UnsandboxedAttempt int64
292 UnsandboxedRunner string
293 // A Research step (research.go): Boundary is the fixed point it runs
294 // at ("start" or "round:<n>"), Question what the coordinator asked it
295 // to look for and RequestTurn the turn that asked; SourcesCard is the
296 // card asking about its proposed URLs, bound to them by SourcesHash.
297 Boundary string
298 Question string
299 RequestTurn string
300 SourcesCard string `gorm:"index:chat_step_sources_card"`
301 SourcesHash string
302 // ResearchGrant and ResearchGrantRevision are the grant a Research
303 // step was dispatched under and the specialist's revision then: its
304 // start authorization holds only while that grant is still the usable
305 // one at that revision (authorizeResearch).
306 ResearchGrant string
307 ResearchGrantRevision int64
308 // Hold is why the runner holds the step now (wire.StepHold JSON, ""
309 // when it does not): the scheduler's report. HousekeepingAttempt is
310 // the attempt housekeeping dispatched (0: none): that attempt counts
311 // as low and never spends, wherever and whenever it is placed.
312 Hold string
313 HousekeepingAttempt int64
314 // CoordinatorAttempt is the attempt the coordinator's retry_step
315 // started (0: none), for the task's timeline (RetriedBy).
316 CoordinatorAttempt int64
317 // HeldAt is when the runner first held the step without a break (nil
318 // while it is not held): advice's "waited a week".
319 HeldAt *time.Time
320 // The binding a data specialist's step was dispatched under: the
321 // specialist, its revision, its scope ("" the team) and its granted
322 // capabilities (JSON list). SpecialistID "" is no data specialist.
323 SpecialistID string `gorm:"not null;default:'';index:chat_step_specialist"`
324 SpecialistRevision int64 `gorm:"not null;default:0"`
325 SpecialistProject string `gorm:"not null;default:''"`
326 SpecialistCaps string `gorm:"not null;default:''"`
327 // DesignOptions are the options a done Design attempt's report named,
328 // kept with its captures (designKept JSON); "" is none.
329 DesignOptions string `gorm:"not null;default:''"`
330}
331
332func (stepRecord) TableName() string { return "chat_steps" }
333
334// entryRecord is a task's finding (Kind "finding") or a thread note.
335type entryRecord struct {
336 ID string `gorm:"primaryKey"`
337 TaskID string `gorm:"index:chat_entry_task;uniqueIndex:chat_entry_key,priority:1"`
338 IdempotencyKey string `gorm:"uniqueIndex:chat_entry_key,priority:2"`
339 Kind string
340 Author string
341 Text string
342 // Headline is a finding's one plain sentence (cleanHeadline).
343 Headline string
344 Repo string
345 Path string
346 Line int
347 CreatedAt time.Time
348 // FoldedFrom is the task this entry was copied from when Equipo
349 // combined that task into this one; Undo deletes exactly these.
350 FoldedFrom string
351}
352
353func (entryRecord) TableName() string { return "chat_task_entries" }
354
355const (
356 entryFinding = "finding"
357 entryNote = "note"
358 // entryReport is the person's report of the same problem again,
359 // attached by the coordinator (add_report) instead of a new task.
360 entryReport = "report"
361)
362
363// attachmentRecord is something a project is made of.
364type attachmentRecord struct {
365 ProjectID string `gorm:"primaryKey"`
366 Kind string `gorm:"primaryKey"`
367 Ref string `gorm:"primaryKey"`
368 Name string
369 CreatedAt time.Time
370}
371
372func (attachmentRecord) TableName() string { return "chat_project_attachments" }
373
374// Model-facing tool texts for tasks.
375const (
376 toolRecorded = "Recorded. Investigate with search_code and read_file, attach what you find with add_finding (a one-sentence headline for the person with no file paths, then the full finding with file and line: the details live on the task, not in your reply), then start_task to have Engineering make the change on the task's branch. In your reply, name the task as a markdown link: [title](link)."
377 toolNoTask = "No such task. Use the task id record_task returned."
378 toolTaskEnded = "That task is done or cancelled."
379 toolTaskStarted = "That task already has its Engineering step. Use read_task to see how it is going."
380 toolStarted = "Engineering is working on it on the task's branch; then the change is checked and reviewed, and the person decides whether it merges. Reply in one or two lines at the outcome level, naming the task as a markdown link, and do not wait."
381 toolFindingSaved = "Attached to the task."
382 toolCancelAsked = "Cancelling. The person sees it on the task card."
383 toolNotOwner = "Only an owner's runner can run work."
384 toolNotYours = "That task is another person's: you may read it, but only the person who asked for it can change, start or cancel it."
385 toolSimilar = "Nothing was recorded: these open tasks in the same project look like the same problem. If one of them is, call add_report with its task id and the person's words, then tell the person in one line that it is already logged, naming it as a markdown link [title](link), and where it stands. If this really is a different problem, call record_task again with separate: true."
386 toolReportAdded = "Added the person's report to this task. Tell them in one line that it is already logged, naming it as a markdown link [title](link), and where it stands. Do not record it again."
387 toolMerging = "Equipo is merging that task now, so it cannot be cancelled. It ends Done, or back at Ready to merge if the merge is refused."
388 toolTaskEndedReport = "That task is done or cancelled. If the problem is back, record a new task with record_task and separate: true."
389)
390
391var taskTitleBad = regexp.MustCompile("[\x00-\x1f\x7f]")
392
393func newTaskID() string { return "tk" + strings.ToLower(rand.Text()[:10]) }
394
395func validSHA(s string) bool {
396 if len(s) != 40 && len(s) != 64 {
397 return false
398 }
399 for _, c := range s {
400 if !(c >= '0' && c <= '9' || c >= 'a' && c <= 'f') {
401 return false
402 }
403 }
404 return true
405}
406
407func cleanText(s string, n int) (string, bool) {
408 s = strings.TrimSpace(s)
409 if s == "" || len(s) > n || !utf8.ValidString(s) || strings.ContainsRune(s, 0) {
410 return "", false
411 }
412 return s, true
413}
414
415// cleanPath accepts a repository-relative file path: no "..", no leading
416// slash or dash, no colon.
417func cleanPath(p string) (string, bool) {
418 p = strings.Trim(strings.TrimSpace(p), "/")
419 if p == "" || len(p) > 300 || strings.HasPrefix(p, "-") || strings.ContainsAny(p, ":\x00\r\n\\") || path.Clean(p) != p || strings.HasPrefix(p, "..") || strings.Contains(p, "/../") {
420 return "", false
421 }
422 return p, true
423}
424
425// ProjectTitle is the title a project takes from its repository, until
426// the person names it: the repository's name, capitalised (equipo is
427// Equipo). Never one of the catalog's other names: past the first they
428// are headings and capitalised words the README happens to repeat, and
429// for oficina/equipo the second was "Create" (hub oficina/equipo #49),
430// for oficina/base "Store". A repository named with a bare verb or
431// generic word (paulca/new) keeps its namespace.
432func ProjectTitle(repo string) string {
433 base := path.Base(repo)
434 if base == "" || base == "." || base == "/" {
435 return repo
436 }
437 title := strings.ToUpper(base[:1]) + base[1:]
438 if !UsableProjectTitle(title) {
439 return ProjectName(repo)
440 }
441 return title
442}
443
444// genericTitles are words that say nothing about which project it is:
445// bare verbs lifted from a request, and placeholders.
446var genericTitles = map[string]bool{
447 "create": true, "new": true, "add": true, "make": true, "build": true, "start": true, "fix": true,
448 "update": true, "change": true, "edit": true, "open": true, "run": true, "test": true, "tests": true,
449 "generate": true, "remove": true, "delete": true, "move": true, "use": true, "set": true, "check": true,
450 "project": true, "projects": true, "repo": true, "repository": true, "app": true, "apps": true,
451 "untitled": true, "task": true, "tasks": true, "work": true, "main": true, "default": true,
452 "code": true, "src": true, "site": true, "web": true, "website": true, "none": true, "todo": true,
453}
454
455// UsableProjectTitle reports whether a title Equipo chose (never one the
456// person typed) names a project: not empty, not a bare verb or generic
457// word such as Create, New or Project.
458func UsableProjectTitle(title string) bool {
459 t := strings.ToLower(strings.TrimSpace(title))
460 return t != "" && validProjectText(t, 120) && !genericTitles[t]
461}
462
463// TaskLink is a task's own page on this instance, as the coordinator
464// links it in a reply: [title](link).
465func TaskLink(id string) string { return "/tasks/" + id }
466
467// BranchURL opens a task branch on Amadan.
468func BranchURL(repo, branch string) string {
469 return forgekey.HubBranchURL(repo, branch)
470}
471
472func (t *txn) attachments(projectID string) ([]wire.Attachment, error) {
473 var rows []attachmentRecord
474 if err := t.db.Where("project_id = ?", projectID).Order("created_at, ref").Find(&rows).Error; err != nil {
475 return nil, err
476 }
477 out := make([]wire.Attachment, 0, len(rows))
478 for _, a := range rows {
479 out = append(out, wire.Attachment{Kind: a.Kind, Ref: a.Ref, Name: a.Name})
480 }
481 return out, nil
482}
483
484// attach records a repository attachment once.
485func (t *txn) attach(p projectRecord) error {
486 return t.db.Exec("INSERT INTO chat_project_attachments(project_id, kind, ref, name, created_at) VALUES (?,?,?,?,?) ON CONFLICT DO NOTHING", p.ID, wire.AttachmentRepo, p.Repo, ProjectName(p.Repo), t.now()).Error
487}
488
489func (t *txn) loadTask(id string) (taskRecord, error) {
490 var k taskRecord
491 err := t.db.Where("id = ?", id).First(&k).Error
492 if errors.Is(err, gorm.ErrRecordNotFound) {
493 return k, ErrNotFound
494 }
495 return k, err
496}
497
498// latestStep is the task's newest step that is not Research: Research
499// runs beside the task's sequence and is never its last word.
500func (t *txn) latestStep(taskID string) (stepRecord, bool, error) {
501 var s stepRecord
502 err := t.db.Where("task_id = ? AND specialist <> ? AND coalesce(retired, 0) = 0", taskID, wire.SpecialistResearch).Order("idx DESC").First(&s).Error
503 if errors.Is(err, gorm.ErrRecordNotFound) {
504 return s, false, nil
505 }
506 return s, err == nil, err
507}
508
509func stepView(s stepRecord) wire.Step {
510 return wire.Step{Hosted: stepHostedView(s), RunnerID: s.RunnerID, Needs: decodeList(s.Needs), Placement: s.Placement, Publication: s.Publication, TerminationKind: s.TerminationKind, ChecksSandbox: s.ChecksSandbox, ID: s.ID, Revision: s.Revision, TaskID: s.TaskID, Index: s.Idx, Specialist: s.Specialist, State: s.State, Reason: s.Reason, Attempt: s.Attempt, BaseSHA: s.BaseSHA, CandidateSHA: s.CandidateSHA, Pushed: s.Pushed, Terminated: s.Terminated, Summary: s.Summary, Headline: s.Headline, LogTail: s.LogTail, StartedAt: s.StartedAt, FinishedAt: s.FinishedAt,
511 Round: s.Round, Family: s.Family, Account: s.Account, Model: s.Model, Verdict: s.Verdict, ReviewLabel: s.ReviewLabel, Findings: decodeFindings(s.Findings), BaseChecks: s.BaseChecks, Checks: s.Checks, Gate: s.Gate, ExitCode: s.ExitCode, Askable: s.Askable,
512 Rebase: s.Rebase, MergeSHA: s.MergeSHA, Into: s.MergeInto, Strategy: s.MergeStrategy, WithoutChecks: s.WithoutChecks, Activity: decodeActivity(s.Activity), Preview: decodePreview(s.Preview), Publish: decodePublish(s.Publish), RetriedBy: retriedBy(s)}
513}
514
515// stepHostedView projects only names already visible in the task's CI log.
516func stepHostedView(s stepRecord) *wire.StepHosted {
517 if s.Gate != wire.GateHosted || s.HostedCI == "" {
518 return nil
519 }
520 var result wire.HostedResult
521 if json.Unmarshal([]byte(s.HostedCI), &result) != nil {
522 return nil
523 }
524 return &wire.StepHosted{Failed: result.Failed}
525}
526
527// retriedBy says who started the step's current attempt, when it was the
528// coordinator (retry_step).
529func retriedBy(s stepRecord) string {
530 if s.CoordinatorAttempt != 0 && s.CoordinatorAttempt == s.Attempt {
531 return wire.RetriedByCoordinator
532 }
533 return ""
534}
535
536// stepViewSwitched adds the switched line, when the step moved, and the
537// scheduler's hold.
538func stepViewSwitched(s stepRecord) wire.Step {
539 v := stepView(s)
540 v.Hold = stepHold(s)
541 if s.Switched != "" {
542 v.Switched = &wire.Switched{}
543 if json.Unmarshal([]byte(s.Switched), v.Switched) != nil {
544 v.Switched = nil
545 }
546 }
547 return v
548}
549
550// taskView is the task with its project, findings, steps and thread.
551func (t *txn) taskView(k taskRecord) (wire.Task, error) {
552 return t.taskViewWith(k, taskViewOptions{})
553}
554
555// Large presentation facts are opt-in for the device detail read. All tools,
556// lists, snapshots, events and ordinary reads use taskView's compact default.
557type taskViewOptions struct{ changeFiles bool }
558
559func (t *txn) taskViewWith(k taskRecord, options taskViewOptions) (wire.Task, error) {
560 v := wire.Task{Stopping: k.MoveAbandoned && k.CancelRequested && !wire.FinalStage(k.Stage), PreparingProject: strings.HasPrefix(k.MoveProject, "new:"), Moving: k.MoveProject != "", CopyHold: k.CopyHold, ID: k.ID, Revision: k.Revision, ProjectID: k.ProjectID, Title: k.Title, Brief: k.Brief, Stage: k.Stage, Branch: k.Branch, BaseSHA: k.BaseSHA, Creator: k.Creator, TurnID: k.TurnID, Findings: []wire.Finding{}, Steps: []wire.Step{}, Thread: []wire.ThreadEntry{}, CreatedAt: k.CreatedAt, UpdatedAt: k.UpdatedAt}
561 if k.DoneAt != nil {
562 done := k.DoneAt.UTC()
563 v.DoneAt = &done
564 }
565 var p projectRecord
566 if err := t.db.Where("id = ?", k.ProjectID).First(&p).Error; err != nil {
567 return v, err
568 }
569 v.Repo, v.Project = p.Repo, p.shownTitle()
570 var entries []entryRecord
571 if err := t.db.Where("task_id = ?", k.ID).Order("created_at, id").Find(&entries).Error; err != nil {
572 return v, err
573 }
574 for _, e := range entries {
575 if e.Kind == entryFinding {
576 v.Findings = append(v.Findings, wire.Finding{ID: e.ID, Headline: e.Headline, Text: e.Text, Repo: e.Repo, Path: e.Path, Line: e.Line, At: e.CreatedAt})
577 } else if len(v.Thread) < wire.MaxThread {
578 v.Thread = append(v.Thread, wire.ThreadEntry{ID: e.ID, Author: e.Author, Text: e.Text, At: e.CreatedAt})
579 }
580 }
581 var steps []stepRecord
582 if err := t.db.Where("task_id = ? AND coalesce(retired, 0) = 0", k.ID).Order("idx").Find(&steps).Error; err != nil {
583 return v, err
584 }
585 var err error
586 if v.Maker, err = t.maker(k.MakerSpecialistID); err != nil {
587 return v, err
588 }
589 for _, s := range steps {
590 sv := stepViewSwitched(s)
591 if options.changeFiles {
592 sv.ChangeFiles = stepChangeFilesView(s)
593 }
594 if sv.Maker, err = t.stepMaker(k, s); err != nil {
595 return v, err
596 }
597 t.stepWaitView(&sv, s)
598 sv.Paused = t.stepPaused(k, s)
599 if s.Specialist == wire.SpecialistResearch && (s.State == wire.StepDone || s.State == wire.StepFailed || s.State == wire.StepCancelled) {
600 rv, err := t.researchView(s)
601 if err != nil {
602 return v, err
603 }
604 sv.Research = rv
605 }
606 if s.Specialist == wire.SpecialistEngineering && s.DesignOptions != "" {
607 dv, err := t.designView(s)
608 if err != nil {
609 return v, err
610 }
611 sv.Design = dv
612 }
613 v.Steps = append(v.Steps, sv)
614 if s.Pushed {
615 v.URL = BranchURL(p.Repo, k.Branch)
616 }
617 }
618 var earlier []stepRecord
619 if err := t.db.Where("task_id = ? AND retired = ?", k.ID, true).Order("created_at, idx").Find(&earlier).Error; err != nil {
620 return v, err
621 }
622 for _, st := range earlier {
623 sv := stepView(st)
624 if options.changeFiles {
625 sv.ChangeFiles = stepChangeFilesView(st)
626 }
627 if sv.Maker, err = t.stepMaker(k, st); err != nil {
628 return v, err
629 }
630 v.EarlierSteps = append(v.EarlierSteps, sv)
631 }
632 pr := progressFor(k, steps)
633 for i := len(steps) - 1; i >= 0; i-- {
634 st := steps[i]
635 if st.Specialist != wire.SpecialistCopy || st.CandidateSHA != pr.candidate || st.State != wire.StepDone {
636 continue
637 }
638 var result wire.CopyResult
639 if json.Unmarshal([]byte(st.CopyResult), &result) == nil && result.Suggestions {
640 for _, word := range result.Review.Strings {
641 v.CopyFlags = append(v.CopyFlags, wire.CopyFlag{Key: word.Key, Text: word.Text, Flag: word.Flag})
642 }
643 }
644 break
645 }
646 if pr.last != nil {
647 v.CopyCanSkip = copyCanSkip(*pr.last)
648 }
649 var copyRows []copyReviewRecord
650 if err := t.db.Where("task_id = ?", k.ID).Order("created_at DESC, id DESC").Find(&copyRows).Error; err != nil {
651 return v, err
652 }
653 seenCopy := map[string]bool{}
654 for _, c := range copyRows {
655 if seenCopy[c.Key] {
656 continue
657 }
658 seenCopy[c.Key] = true
659 if c.Flag == "" || c.Candidate != pr.candidate {
660 continue
661 }
662 v.CopyFlags = append(v.CopyFlags, wire.CopyFlag{ID: c.ID, Key: c.Key, Text: c.Text, Flag: c.Flag})
663 }
664 if pr.repeated {
665 current := pr.checks
666 for i := len(steps) - 1; i >= 0; i-- {
667 previous := steps[i]
668 if previous.Idx >= current.Idx || previous.Specialist != wire.SpecialistChecks || previous.Checks != wire.ChecksFailed {
669 continue
670 }
671 var signature copydesk.Signature
672 _ = json.Unmarshal([]byte(current.FailureSignature), &signature)
673 v.CopyRepeat = &wire.CopyRepeat{Before: wire.CopyAttempt{Step: previous.ID, Attempt: previous.Attempt, Candidate: previous.CandidateSHA}, After: wire.CopyAttempt{Step: current.ID, Attempt: current.Attempt, Candidate: current.CandidateSHA}, Signature: signature}
674 break
675 }
676 }
677 v.CandidateSHA = pr.candidate
678 if pr.moved {
679 v.BranchHead = k.BranchHead
680 }
681 v.Checks, v.ChecksReason, v.Verdict, v.ReviewLabel = pr.judged()
682 if (v.Checks == wire.ChecksPassed || v.Checks == wire.ChecksFailed) && pr.checks != nil {
683 v.ChecksSandbox = pr.checks.ChecksSandbox
684 }
685 v.NeedsYou = pr.needsYou(k)
686 if v.NeedsYou == "" && !wire.FinalStage(k.Stage) && !k.CancelRequested {
687 // Research is never the task's last word, but a held Research step
688 // that needs its person is Needs you all the same (§8).
689 for _, st := range steps {
690 if h := stepHold(st); st.Specialist == wire.SpecialistResearch && h != nil && h.NeedsPerson != "" && !wire.StepTerminal(st.State) {
691 v.NeedsYou = wire.NeedsHeld
692 }
693 }
694 }
695 v.Priority = taskPriority(k)
696 // The task itself shows no devbox preview once it ended; the cards
697 // that still ask about it show one held for its Publish.
698 v.PreviewURL = previewLink(k, steps, pr.candidate, t.now(), false)
699 if v.PreviewURL != "" {
700 v.PreviewURL = t.previewWrapperURL(k.ID)
701 }
702 site, err := t.siteView(k, steps)
703 if err != nil {
704 return v, err
705 }
706 v.Site = site
707 if pr.eng != nil {
708 v.FixRounds = pr.eng.Round
709 }
710 qs, err := t.questions(k.ID)
711 if err != nil {
712 return v, err
713 }
714 v.Questions = qs
715 v.Merged = mergedView(k)
716 v.AskOpen = askOpen(k, t.now())
717 v.MergeHold, v.RevertOf = k.MergeHold, k.RevertOf
718 if v.MergeDecision, err = t.mergeDecisionView(k.ID); err != nil {
719 return v, err
720 }
721 if v.UndoOffered, err = t.undoOffered(k); err != nil {
722 return v, err
723 }
724 if v.MergeOffered, err = t.mergeOffered(k, pr); err != nil {
725 return v, err
726 }
727 v.EngineeringRunner = k.EngineeringRunner
728 if v.Reports, err = reportCount(t.db, k.ID); err != nil {
729 return v, err
730 }
731 if err := t.triageView(&v, k, steps, pr); err != nil {
732 return v, err
733 }
734 if pr.explore {
735 v.Kind, v.MergeOffered = wire.KindExplore, false
736 if v.NeedsYou == wire.NeedsDirection {
737 if v.Direction, err = t.directionView(k, p.Repo, steps, pr); err != nil {
738 return v, err
739 }
740 }
741 }
742 if v.ExploredFrom, err = t.taskRef(k.ExploredFrom); err != nil {
743 return v, err
744 }
745 if v.BuiltAs, err = t.taskRef(k.BuiltAs); err != nil {
746 return v, err
747 }
748 if v.Moving {
749 if v.MoveHoldReason, err = t.moveHoldReason(k); err != nil {
750 return v, err
751 }
752 v.NeedsYou = ""
753 v.MergeOffered = false
754 v.CopyHold = false
755 v.CopyCanSkip = false
756 v.PreviewURL = ""
757 }
758 return v, t.taskExtras(&v, k, steps)
759}
760
761// members are the active team members, who all see team records.
762func (t *txn) members() ([]string, error) {
763 var out []string
764 err := t.db.Raw("SELECT address FROM members WHERE active = 1 ORDER BY address").Scan(&out).Error
765 return out, err
766}
767
768// saveTask bumps the task's revision and tells every active member.
769func (t *txn) saveTask(k *taskRecord) error {
770 if err := t.hkTaskWrite(k); err != nil {
771 return err
772 }
773 var before string
774 if err := t.db.Model(&taskRecord{}).Where("id = ?", k.ID).Pluck("stage", &before).Error; err != nil {
775 return err
776 }
777 k.Revision++
778 k.UpdatedAt = t.now()
779 if k.Stage == wire.StageDone && before != wire.StageDone {
780 now := t.now()
781 k.DoneAt = &now
782 }
783 if err := t.db.Model(&taskRecord{}).Where("id = ?", k.ID).Select("revert_of", "revert_sha", "move_project", "move_by", "move_restart", "move_abandoned", "move_count", "project_id", "branch", "copy_hold", "repair_round", "copy_recovery", "stage", "base_sha", "cancel_requested", "revision", "updated_at", "moved_from", "branch_head", "merged_sha", "merged_into", "merge_strategy", "merged_without_checks", "merged_at", "engineering_runner", "ready_sha", "merge_eligible", "merge_asked", "done_at", "duplicate_of", "merge_hold", "merge_verified", "kind", "direction_asked", "built_as", "publish_asked").Updates(k).Error; err != nil {
784 return err
785 }
786 if wire.FinalStage(k.Stage) && !wire.FinalStage(before) {
787 if err := t.taskEnded(*k); err != nil {
788 return err
789 }
790 // Before the open merge cards resolve: those change on their own.
791 if err := t.touchOutcomes(*k); err != nil {
792 return err
793 }
794 if err := t.withdrawMergeCards(*k); err != nil {
795 return err
796 }
797 if err := t.endResearch(*k); err != nil {
798 return err
799 }
800 }
801 if err := t.taskEvent(*k); err != nil {
802 return err
803 }
804 // A hand-off following the task may have news for the Assistant.
805 return t.taskChanged(k.ID)
806}
807
808func (t *txn) taskEvent(k taskRecord) error {
809 v, err := t.taskView(k)
810 if err != nil {
811 return err
812 }
813 members, err := t.members()
814 if err != nil {
815 return err
816 }
817 for _, m := range members {
818 if err := t.event("", m, wire.EventTask, "task", k.ID, k.Revision, k.TurnID, "", 0, v); err != nil {
819 return err
820 }
821 }
822 if slices.Contains(members, k.Creator) {
823 return t.pushTask(v)
824 }
825 return nil
826}
827
828// saveStep bumps the step's revision, tells every member, and bumps the
829// task so its resource carries the step.
830func (t *txn) saveStep(s *stepRecord, k *taskRecord) error {
831 if err := t.writeStep(s); err != nil {
832 return err
833 }
834 if err := t.discardOldChangeDiffs(*k, *s); err != nil {
835 return err
836 }
837 if err := t.saveTask(k); err != nil {
838 return err
839 }
840 if s.Specialist == wire.SpecialistEngineering && s.SpecialistID != "" && wire.StepTerminal(s.State) {
841 // A maker's attempt ended, however it ended: what it sent and its
842 // report did not keep goes.
843 if err := t.dropUnkept(s.ID); err != nil {
844 return err
845 }
846 }
847 if s.Specialist == wire.SpecialistResearch && wire.StepTerminal(s.State) {
848 // Research ended, however it ended: the Engineering it held goes.
849 return t.releaseResearch(k)
850 }
851 return nil
852}
853
854// writeStep bumps the step's revision and tells every member, without
855// saving its task.
856func (t *txn) writeStep(s *stepRecord) error {
857 // A step changes under housekeeping only for a reserved retry.
858 if err := t.hkSpend(s.Person); err != nil {
859 return err
860 }
861 s.Revision++
862 s.UpdatedAt = t.now()
863 if err := t.db.Model(&stepRecord{}).Where("id = ?", s.ID).Select("base_checks", "base_checks_sha", "copy_owner", "copy_revision", "copy_result", "failure_signature", "state", "reason", "attempt", "base_sha", "candidate_sha", "pushed", "terminated", "summary", "log_tail", "started_at", "finished_at", "revision", "updated_at", "headline", "family", "account", "verdict", "review_label", "findings", "checks", "gate", "exit_code", "output", "republish", "from_attempt", "askable", "rebase", "from_base", "from_candidate", "merge_sha", "merge_into", "merge_strategy", "without_checks", "switched", "activity", "runner_id", "needs", "placement", "waiting_since", "refused_by", "withdrawn", "termination_kind", "publication", "publication_id", "apple", "checks_sandbox", "change_files", "change_facts", "decided_by", "merge_source", "merge_parents", "hosted_ci", "kind", "note", "sandbox_runner", "unsandboxed_by", "unsandboxed_at", "unsandboxed_attempt", "unsandboxed_runner", "has_preview", "preview", "boundary", "question", "request_turn", "sources_card", "sources_hash", "research_grant", "research_grant_revision", "specialist_id", "specialist_revision", "specialist_project", "specialist_caps", "design_options", "hold", "housekeeping_attempt", "coordinator_attempt", "held_at", "publish", "model", "xcode_access", "outcome_phase", "session_id", "publication_runner", "on_worker", "ability_held").Updates(s).Error; err != nil {
864 return err
865 }
866 if s.Retired {
867 return nil
868 }
869 members, err := t.members()
870 if err != nil {
871 return err
872 }
873 // The step's maker, as the task view has it: events and snapshots
874 // name a Design step the same way.
875 var k taskRecord
876 if s.SpecialistID == "" && s.Specialist == wire.SpecialistEngineering {
877 if err := t.db.Select("id", "maker_specialist_id").Where("id = ?", s.TaskID).Limit(1).Find(&k).Error; err != nil {
878 return err
879 }
880 }
881 maker, err := t.stepMaker(k, *s)
882 if err != nil {
883 return err
884 }
885 for _, m := range members {
886 sv := stepViewSwitched(*s)
887 sv.Maker = maker
888 t.stepWaitView(&sv, *s)
889 if err := t.event("", m, wire.EventStep, "step", s.ID, s.Revision, "", "", s.Attempt, sv); err != nil {
890 return err
891 }
892 }
893 return nil
894}
895
896// recordTask notes a task the moment the person reports something: under
897// the project for repo (added if needed), stage noted, in the turn's lane
898// (the person's conversation or a job thread), with a task card there.
899func (t *txn) recordTask(r turnRecord, repo, title, brief, kind string, separate bool) (wire.ToolResult, error) {
900 if p, err := t.namedProject(r.Person, repo); err != nil {
901 return wire.ToolResult{}, err
902 } else if p != nil {
903 repo = p.Repo
904 } else if !repoRef.MatchString(ProjectName(NormalizeRepo(repo))) {
905 return t.askNamedProject(r, repo, nil)
906 }
907 if !separate {
908 // The same problem reported again goes on the open task, not a new
909 // one: look before recording.
910 var existing projectRecord
911 err := t.db.Where("repo = ? AND state = ?", NormalizeRepo(repo), wire.ProjectActive).First(&existing).Error
912 if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
913 return wire.ToolResult{}, err
914 }
915 if err == nil {
916 similar, err := t.similarTasks(r.Person, existing.ID, title, brief, kind)
917 if err != nil {
918 return wire.ToolResult{}, err
919 }
920 if len(similar) > 0 {
921 return similarResult(similar), nil
922 }
923 }
924 }
925 p, added, err := t.addProject(r.Person, repo)
926 if errors.Is(err, ErrForbidden) {
927 return refused("owner_required", t.s.authority.Copy("projects.owner_add")), nil
928 }
929 if errors.Is(err, ErrNotAllowed) {
930 return t.toolAddProject(r, repo)
931 }
932 if err != nil {
933 return wire.ToolResult{}, err
934 }
935 state := wire.CardWorking
936 if added {
937 state = wire.CardAdded
938 }
939 if err := t.projectCard(r, p, state); err != nil {
940 return wire.ToolResult{}, err
941 }
942 now := t.now()
943 k := taskRecord{ID: newTaskID(), ProjectID: p.ID, Title: title, Brief: brief, Stage: wire.StageNoted, Creator: r.Person, TurnID: r.ID, Kind: wire.NormalKind(kind), Revision: 1, CreatedAt: now, UpdatedAt: now, Lane: r.Lane}
944 k.Branch = wire.TaskBranch(k.ID, title)
945 if separate {
946 // Recorded anyway: the most similar open task is named as a
947 // possible duplicate, for the person to fold it if it is one.
948 similar, err := t.similarTasks(r.Person, p.ID, title, brief, kind)
949 if err != nil {
950 return wire.ToolResult{}, err
951 }
952 if len(similar) > 0 {
953 k.DuplicateOf = similar[0].ID
954 }
955 // The coordinator saw them and judged this one different: Equipo
956 // never combines these pairs on its own.
957 for _, o := range similar {
958 if err := t.markDistinct(k.ID, o.ID); err != nil {
959 return wire.ToolResult{}, err
960 }
961 }
962 }
963 if err := t.db.Create(&k).Error; err != nil {
964 return wire.ToolResult{}, err
965 }
966 if err := t.taskEvent(k); err != nil {
967 return wire.ToolResult{}, err
968 }
969 if err := t.accessNeedPassed(r, p.Repo); err != nil {
970 return wire.ToolResult{}, err
971 }
972 if _, err := t.housekeepingPass(housekeeping.TriggerRecordTask, p.ID); err != nil {
973 return wire.ToolResult{}, err
974 }
975 c := cardRecord{ID: newID("c_"), Person: r.Person, Kind: wire.CardTask, State: wire.StageNoted, TurnID: r.ID, ProjectID: p.ID, TaskID: k.ID, Options: "[]", Revision: 1, CreatedAt: now, UpdatedAt: now, Lane: k.Lane}
976 if err := t.db.Create(&c).Error; err != nil {
977 return wire.ToolResult{}, err
978 }
979 if err := t.cardEvent(c); err != nil {
980 return wire.ToolResult{}, err
981 }
982 raw, _ := json.Marshal(map[string]string{"task": k.ID, "title": k.Title, "link": TaskLink(k.ID), "branch": k.Branch, "stage": k.Stage, "project": ProjectName(p.Repo), "note": toolRecorded})
983 return wire.ToolResult{Code: "recorded", Repo: p.Repo, Text: string(raw)}, nil
984}
985
986// ownTask loads a task a person's coordinator may act on: tasks are
987// shared within the team, acting on one is its creator's alone.
988// Refusals are tool results.
989func (t *txn) ownTask(person, id string) (taskRecord, *wire.ToolResult, error) {
990 k, err := t.loadTask(strings.TrimSpace(id))
991 if errors.Is(err, ErrNotFound) {
992 res := refused("not_found", toolNoTask)
993 return k, &res, nil
994 }
995 if err != nil {
996 return k, nil, err
997 }
998 if k.Creator != person {
999 res := refused("not_yours", toolNotYours)
1000 return k, &res, nil
1001 }
1002 if wire.FinalStage(k.Stage) || k.CancelRequested {
1003 res := refused("task_ended", toolTaskEnded)
1004 return k, &res, nil
1005 }
1006 return k, nil, nil
1007}
1008
1009// addFinding attaches what the coordinator found: a diagnosis with the
1010// file and line in a repository it can read.
1011func (t *txn) addFinding(r turnRecord, args json.RawMessage) (wire.ToolResult, error) {
1012 var in struct {
1013 Task string `json:"task"`
1014 Headline string `json:"headline"`
1015 Text string `json:"text"`
1016 Repo string `json:"repo"`
1017 Path string `json:"path"`
1018 Line int `json:"line"`
1019 }
1020 if wire.Strict(args, &in) != nil || in.Line < 0 || in.Line > 1_000_000 {
1021 return refused("invalid", toolBadInput), nil
1022 }
1023 text, ok := cleanText(in.Text, wire.MaxFindingText)
1024 if !ok {
1025 return refused("invalid", toolBadInput), nil
1026 }
1027 repo, p := "", ""
1028 if in.Repo != "" || in.Path != "" {
1029 h, err := t.hello(r.Person)
1030 if err != nil {
1031 return wire.ToolResult{}, err
1032 }
1033 repo = NormalizeRepo(in.Repo)
1034 if !catalogHas(h, repo) {
1035 return refused("unreachable", toolUnreachable), nil
1036 }
1037 if p, ok = cleanPath(in.Path); !ok {
1038 return refused("invalid", toolBadInput), nil
1039 }
1040 }
1041 k, res, err := t.ownTask(r.Person, in.Task)
1042 if res != nil || err != nil {
1043 return deref(res), err
1044 }
1045 var n int64
1046 if err := t.db.Model(&entryRecord{}).Where("task_id = ? AND kind = ?", k.ID, entryFinding).Count(&n).Error; err != nil {
1047 return wire.ToolResult{}, err
1048 }
1049 if n >= wire.MaxFindings {
1050 return refused("too_many", toolBadInput), nil
1051 }
1052 id := newID("f_")
1053 if err := t.db.Create(&entryRecord{ID: id, TaskID: k.ID, IdempotencyKey: id, Kind: entryFinding, Author: r.Person, Text: text, Headline: cleanHeadline(in.Headline), Repo: repo, Path: p, Line: in.Line, CreatedAt: t.now()}).Error; err != nil {
1054 return wire.ToolResult{}, err
1055 }
1056 if k.Stage == wire.StageNoted {
1057 k.Stage = wire.StageInvestigated
1058 }
1059 if err := t.saveTask(&k); err != nil {
1060 return wire.ToolResult{}, err
1061 }
1062 return wire.ToolResult{Code: "finding", Text: toolFindingSaved}, nil
1063}
1064
1065func deref(r *wire.ToolResult) wire.ToolResult {
1066 if r == nil {
1067 return wire.ToolResult{}
1068 }
1069 return *r
1070}
1071
1072func catalogHas(h wire.Hello, repo string) bool {
1073 for _, e := range h.Catalog {
1074 if e.Repo == repo {
1075 return true
1076 }
1077 }
1078 return false
1079}
1080
1081// startable reports whether start_task would start the task now: no
1082// step yet, still noted or investigated.
1083func (t *txn) startable(k taskRecord) bool {
1084 if wire.FinalStage(k.Stage) || k.CancelRequested || k.Stage != wire.StageNoted && k.Stage != wire.StageInvestigated {
1085 return false
1086 }
1087 _, found, err := t.latestStep(k.ID)
1088 return err == nil && !found
1089}
1090
1091// startTask dispatches the task's Engineering step to the person's own
1092// runner: the step, the dispatch command and the task event in one
1093// transaction.
1094func (t *txn) startTask(r turnRecord, id, brief, maker string) (wire.ToolResult, error) {
1095 k, res, err := t.ownTask(r.Person, id)
1096 if res != nil || err != nil {
1097 return deref(res), err
1098 }
1099 if _, found, err := t.latestStep(k.ID); err != nil {
1100 return wire.ToolResult{}, err
1101 } else if found || k.Stage != wire.StageNoted && k.Stage != wire.StageInvestigated {
1102 return refused("started", toolTaskStarted), nil
1103 }
1104 if err := t.isOwner(r.Person); err != nil {
1105 return refused("not_owner", toolNotOwner), nil
1106 }
1107 if maker != "" {
1108 // The task's maker, checked by the caller (startMaker): its steps
1109 // are that specialist's from now on.
1110 k.MakerSpecialistID = maker
1111 if err := t.db.Model(&taskRecord{}).Where("id = ?", k.ID).Update("maker_specialist_id", maker).Error; err != nil {
1112 return wire.ToolResult{}, err
1113 }
1114 }
1115 if b, ok := cleanText(brief, wire.MaxTaskBrief); ok {
1116 if k.Brief != "" {
1117 b = k.Brief + "\n\n" + b
1118 }
1119 k.Brief = clipText(b, wire.MaxTaskBrief)
1120 if err := t.db.Model(&taskRecord{}).Where("id = ?", k.ID).Update("brief", k.Brief).Error; err != nil {
1121 return wire.ToolResult{}, err
1122 }
1123 }
1124 // The task's start is a fixed point: Research requested for it runs
1125 // now, and Engineering waits for it.
1126 held, err := t.researchAt(&k, boundaryStart)
1127 if err != nil {
1128 return wire.ToolResult{}, err
1129 }
1130 steps, err := t.steps(k.ID)
1131 if err != nil {
1132 return wire.ToolResult{}, err
1133 }
1134 now := t.now()
1135 s := stepRecord{ID: newID("s_"), TaskID: k.ID, Idx: nextIdx(steps), Specialist: wire.SpecialistEngineering, Person: r.Person, State: wire.StepQueued, Attempt: 1, Revision: 0, Kind: wire.NormalKind(k.Kind), CreatedAt: now, UpdatedAt: now}
1136 if held {
1137 s.Placement = wire.PlacementResearch
1138 }
1139 if err := t.db.Create(&s).Error; err != nil {
1140 return wire.ToolResult{}, err
1141 }
1142 if !held {
1143 if err := t.dispatchStep(&k, &s); err != nil {
1144 return wire.ToolResult{}, err
1145 }
1146 }
1147 k.Stage = wire.StageInProgress
1148 if err := t.saveStep(&s, &k); err != nil {
1149 return wire.ToolResult{}, err
1150 }
1151 note := toolStarted
1152 if k.MakerSpecialistID != "" {
1153 note = toolStartedDesign
1154 }
1155 raw, _ := json.Marshal(map[string]string{"task": k.ID, "title": k.Title, "link": TaskLink(k.ID), "note": note})
1156 return wire.ToolResult{Code: "started", Text: string(raw)}, nil
1157}
1158
1159// dispatchStep queues the dispatch command for the step's attempt on the
1160// runner it is placed on, with the task's findings. The caller saves s.
1161func (t *txn) dispatchStep(k *taskRecord, s *stepRecord) error {
1162 if k.MoveProject != "" || s.Retired {
1163 return ErrConflict
1164 }
1165 // Housekeeping dispatches only within its reservation, on a connection
1166 // that is not standing down.
1167 if err := t.hkSpend(s.Person); err != nil {
1168 return err
1169 }
1170 if t.hk != nil {
1171 // Its provenance is kept on the record: a placement after this
1172 // pass still dispatches it as housekeeping's.
1173 s.HousekeepingAttempt = s.Attempt
1174 }
1175 if s.Specialist == wire.SpecialistResearch {
1176 return t.dispatchResearch(k, s)
1177 }
1178 // A maker step of a task with a data specialist as its maker runs as
1179 // that specialist, bound to its grant now (makerGrant); with no
1180 // usable grant it ends cancelled here, and never runs as plain
1181 // Engineering.
1182 var maker *specialistRecord
1183 if s.Specialist == wire.SpecialistEngineering && k.MakerSpecialistID != "" {
1184 var err error
1185 if maker, err = t.makerGrant(*k, *s); err != nil {
1186 return err
1187 }
1188 if maker == nil {
1189 now := t.now()
1190 s.State, s.Reason, s.Terminated, s.FinishedAt, s.Placement, s.WaitingSince, s.RunnerID = wire.StepCancelled, reasonSpecialistNoGrant, true, &now, "", nil, ""
1191 return nil
1192 }
1193 bind(s, *maker)
1194 }
1195 var copyCommand *wire.CopyDispatch
1196 if s.Specialist == wire.SpecialistCopy {
1197 var err error
1198 copyCommand, err = t.copyDispatch(k, s)
1199 if err != nil || copyCommand == nil {
1200 return err
1201 }
1202 }
1203 placed, err := t.place(k, s)
1204 if err != nil || !placed {
1205 return err
1206 }
1207 if s.RunnerID == "" {
1208 // No runner at all (no primary yet): it waits, and is placed when
1209 // one connects. Nothing is ever sent to nobody.
1210 now := t.now()
1211 s.Placement = wire.PlacementWaiting
1212 if s.WaitingSince == nil {
1213 s.WaitingSince = &now
1214 }
1215 return nil
1216 }
1217 if maker != nil {
1218 // Design goes only within the autonomy limit, and only to a runner
1219 // that can run it; otherwise it waits (design_routing.go).
1220 if held, err := t.designGate(k, s); err != nil || held {
1221 return err
1222 }
1223 }
1224 var p projectRecord
1225 if err := t.db.Where("id = ?", k.ProjectID).First(&p).Error; err != nil {
1226 return err
1227 }
1228 v, err := t.taskView(*k)
1229 if err != nil {
1230 return err
1231 }
1232 base := s.BaseSHA
1233 if base == "" && !s.Rebase {
1234 base = k.BaseSHA
1235 }
1236 brief, err := t.stepBrief(*k, *s)
1237 if err != nil {
1238 return err
1239 }
1240 cmd := wire.DispatchCommand{Copy: copyCommand, Person: s.Person, TaskID: k.ID, StepID: s.ID, Attempt: s.Attempt, Specialist: s.Specialist, Repo: p.Repo, Branch: k.Branch, BaseSHA: base, Title: k.Title, Brief: brief, Findings: v.Findings, Round: s.Round, Republish: s.Republish, FromAttempt: s.FromAttempt}
1241 if s.Specialist == wire.SpecialistEngineering || s.Specialist == wire.SpecialistReview {
1242 words, err := t.personWords(*k, "")
1243 if err != nil {
1244 return err
1245 }
1246 cmd.PersonWords = boundedPersonWords(words)
1247 }
1248 if s.Specialist == wire.SpecialistPreview {
1249 cmd.PreviewUnsafeDigest = previewGrant(*s).Digest
1250 }
1251 // The scheduler's facts (protocol 14; Encode drops them for an older
1252 // runner): the task's priority and deadline, and a Run now written for
1253 // this attempt. Housekeeping's own dispatches count as low and carry
1254 // no release: they never spend (§7, Housekeeping).
1255 if err := t.schedulerFields(*k, *s, &cmd); err != nil {
1256 return err
1257 }
1258 if s.Specialist != wire.SpecialistEngineering || s.Republish {
1259 cmd.CandidateSHA = s.CandidateSHA
1260 }
1261 if s.Specialist == wire.SpecialistPublish {
1262 // The confirmed place the creator's tap was bound to, its app and
1263 // mode, and the branch the merged commit went into (protocol 31;
1264 // Encode refuses it below). A step whose place, binding or reach
1265 // moved since is sent with no target: the runner refuses it and
1266 // its start check withdraws it.
1267 snap := stepSnapshot(s.Publish)
1268 if snap != nil {
1269 refused, err := t.sitePhase(*k, s, *snap, "", s.RunnerID)
1270 if err != nil {
1271 return err
1272 }
1273 if refused == "" {
1274 cmd.Publish = &wire.PublishDispatch{App: snap.App, Into: k.MergedInto, Console: snap.Console, Account: snap.Sqid, AccountName: snap.Name, Place: snap.Place, PlaceRevision: snap.PlaceRevision, BindingRevision: snap.BindingRevision, Destination: snap.Destination, Mode: snap.Mode, DeployName: snap.DeployName}
1275 }
1276 }
1277 }
1278 if s.Specialist == wire.SpecialistReview {
1279 cmd.AvoidAccount = s.Account
1280 // The family Engineering's attempt recorded (protocol 18; Encode
1281 // drops it for an older runner): Review's family rule reads it,
1282 // never the connection's, which may allow several models (§16.5).
1283 steps, err := t.steps(k.ID)
1284 if err != nil {
1285 return err
1286 }
1287 for _, e := range steps {
1288 if (e.Specialist == wire.SpecialistCopy || e.Specialist == wire.SpecialistEngineering) && e.Family != "" && e.Pushed {
1289 cmd.AvoidFamilies = append(cmd.AvoidFamilies, e.Family)
1290 }
1291 if e.Specialist == wire.SpecialistEngineering && e.Account == s.Account && e.Family != "" {
1292 cmd.AvoidFamily = e.Family
1293 }
1294 }
1295 hasCopy := false
1296 for _, e := range steps {
1297 hasCopy = hasCopy || e.Specialist == wire.SpecialistCopy && e.Pushed && e.Family != ""
1298 }
1299 if !hasCopy {
1300 cmd.AvoidFamilies = nil
1301 }
1302 // A revert task's review measures whether it reverts exactly that.
1303 cmd.RevertSHA = k.RevertSHA
1304 }
1305 if !s.Rebase && !s.Republish {
1306 // A fix round: its feedback apart, for a runner that resumes the
1307 // session that made the commit before.
1308 steps, err := t.steps(k.ID)
1309 if err != nil {
1310 return err
1311 }
1312 fb := fixNote(steps, *s)
1313 if wire.NormalKind(k.Kind) == wire.KindExplore && s.Specialist == wire.SpecialistEngineering && s.Round > 0 {
1314 // A resumed session reads only this: the exploration's rule too.
1315 fb = strings.TrimSpace(fb + "\n\n" + exploreEngineering)
1316 }
1317 cmd.Feedback = clipText(fb, wire.MaxTaskBrief+4000)
1318 }
1319 if s.Rebase {
1320 // The runner takes the default branch's tip and puts the change
1321 // (FromBase..FromCandidate) on it.
1322 cmd.Rebase, cmd.FromBase, cmd.CandidateSHA = true, s.FromBase, s.FromCandidate
1323 }
1324 if s.Specialist == wire.SpecialistEngineering || s.Specialist == wire.SpecialistReview {
1325 // The task's latest Research findings, as data (protocol 13;
1326 // Encode drops them for an older runner).
1327 if cmd.ResearchNote, err = t.researchNote(k.ID); err != nil {
1328 return err
1329 }
1330 }
1331 primary, err := t.s.authority.PrimaryRunner(t.db, s.Person)
1332 if err != nil {
1333 return err
1334 }
1335 if s.Specialist == wire.SpecialistCopy && copyRecovery(*s) {
1336 cmd.FromBase = s.FromBase
1337 }
1338 cmd.RunnerID = s.RunnerID
1339 // The person's recorded choice to run this attempt on this Mac
1340 // outside the sandbox (protocol 7; Encode drops it for older peers).
1341 if s.Specialist == wire.SpecialistChecks {
1342 // Never on a Mac holding a model credential (D1).
1343 if cmd.Unsandboxed, err = t.unsandboxedOK(*s, s.RunnerID); err != nil {
1344 return err
1345 }
1346 }
1347 // The primary may take the hub's hosted CI verdict for checks (a
1348 // protocol 5 runner; Encode drops the offer for older ones).
1349 cmd.HostedChecks = s.Specialist == wire.SpecialistChecks && s.RunnerID == primary
1350 if s.Specialist == wire.SpecialistEngineering {
1351 // Only this attempt's grant counts (below, on a worker).
1352 s.XcodeAccess = ""
1353 }
1354 // Where this attempt runs, kept for its view ("Made on").
1355 s.OnWorker = s.RunnerID != primary
1356 if s.RunnerID != primary {
1357 // Placed on a worker: what it needs, and the candidate relayed
1358 // from the primary as a pack in an inbound transfer.
1359 cmd.Needs = decodeList(s.Needs)
1360 switch s.Specialist {
1361 case wire.SpecialistChecks:
1362 if _, err := t.openTransfer(*k, *s, primary, s.RunnerID, wire.TransferHeader{Direction: wire.TransferInbound, BaseSHA: cmd.BaseSHA, CandidateSHA: s.CandidateSHA}); err != nil {
1363 return err
1364 }
1365 case wire.SpecialistEngineering:
1366 // Mac Engineering (slice F): Xcode's services only as the
1367 // proof allows, and the commits it starts from, base bound
1368 // (placeEngineering), relayed in an Engineering transfer: the
1369 // base, and for a rebase round the old base and the candidate.
1370 if cmd.XcodeAccess, err = t.xcodeAccess(s.Person, s.RunnerID); err != nil {
1371 return err
1372 }
1373 s.XcodeAccess = cmd.XcodeAccess
1374 if !s.Republish {
1375 h := wire.TransferHeader{Direction: wire.TransferInbound, Kind: wire.TransferKindEngineering, BaseSHA: cmd.BaseSHA}
1376 if s.Rebase {
1377 h.OldBaseSHA, h.CandidateSHA = s.FromBase, s.FromCandidate
1378 }
1379 if !h.Valid() {
1380 return fmt.Errorf("%w: engineering transfer for %s", ErrInvalid, s.ID)
1381 }
1382 if _, err := t.openTransfer(*k, *s, primary, s.RunnerID, h); err != nil {
1383 return err
1384 }
1385 }
1386 }
1387 }
1388 if s.Specialist == wire.SpecialistCopy {
1389 if err := t.reserveCopy(*k, *s); err != nil {
1390 return err
1391 }
1392 }
1393 if maker != nil {
1394 // The step's full binding (protocol 38; Encode refuses the
1395 // dispatch below it, so it never runs there as plain
1396 // Engineering), and the grant's use audited.
1397 boundDispatch(&cmd, *maker, *k)
1398 if err := t.specialistUsed(*maker, *k, *s); err != nil {
1399 return err
1400 }
1401 if err := t.designRan(k); err != nil {
1402 return err
1403 }
1404 }
1405 return t.commandTo(s.RunnerID, s.Person, wire.FrameDispatch, cmd)
1406}
1407
1408// readTask is what the coordinator sees of a task.
1409func (t *txn) readTask(person, id string) (wire.ToolResult, error) {
1410 k, err := t.loadTask(strings.TrimSpace(id))
1411 if errors.Is(err, ErrNotFound) {
1412 return refused("not_found", toolNoTask), nil
1413 }
1414 if err != nil {
1415 return wire.ToolResult{}, err
1416 }
1417 v, err := t.taskView(k)
1418 if err != nil {
1419 return wire.ToolResult{}, err
1420 }
1421 for i := range v.Steps {
1422 v.Steps[i].LogTail = clipText(v.Steps[i].LogTail, 1000)
1423 }
1424 // The questions and answers are the person's with the specialists;
1425 // the coordinator points people there and never relays them.
1426 v.Questions = []wire.Question{}
1427 // Whether each step retry_step may run again can run now, and if not
1428 // why (a fixed reason), for this turn's person.
1429 retry, err := t.retryViews(k, person)
1430 if err != nil {
1431 return wire.ToolResult{}, err
1432 }
1433 raw, _ := json.Marshal(struct {
1434 Link string `json:"link"`
1435 Retry []retryView `json:"retry,omitempty"`
1436 wire.Task
1437 }{TaskLink(v.ID), retry, v})
1438 return wire.ToolResult{Code: "task", Text: clipText(string(raw), 16<<10)}, nil
1439}
1440
1441// cancelTask ends a task: at once when no step runs, else by asking the
1442// runner, which reports the attempt's termination. Only the task's
1443// creator may cancel it.
1444func (t *txn) cancelTask(person, id string) (int64, error) {
1445 // Housekeeping never cancels or deletes a task; a fold is its only
1446 // ending, and Undo restores it.
1447 if err := t.hkForbid("cancel"); err != nil {
1448 return 0, err
1449 }
1450 if err := t.isOwner(person); err != nil {
1451 return 0, err
1452 }
1453 k, err := t.loadTask(id)
1454 if err != nil {
1455 return 0, err
1456 }
1457 if k.Creator != person {
1458 return 0, ErrForbidden
1459 }
1460 if wire.FinalStage(k.Stage) || k.CancelRequested {
1461 return 0, ErrTaskEnded
1462 }
1463 s, found, err := t.latestStep(k.ID)
1464 if err != nil {
1465 return 0, err
1466 }
1467 if k.Stage == wire.StageMerging || found && s.Specialist == wire.SpecialistMerge && !wire.StepTerminal(s.State) {
1468 // A merge request may already be with the hub: the runner settles
1469 // it from the default branch, and a cancel must not hide a merge.
1470 return 0, ErrMerging
1471 }
1472 if k.Watching != "" {
1473 if err := t.watch(&k, s.Person, ""); err != nil {
1474 return 0, err
1475 }
1476 }
1477 if !found || wire.StepTerminal(s.State) {
1478 k.Stage = wire.StageCancelled
1479 return s.Attempt, t.saveTask(&k)
1480 }
1481 if s.RunnerID == "" {
1482 // Waiting for a runner and never dispatched: nothing runs, so it
1483 // ends here.
1484 now := t.now()
1485 s.State, s.Reason, s.Terminated, s.FinishedAt, s.Placement, s.WaitingSince = wire.StepCancelled, "cancelled", true, &now, "", nil
1486 k.Stage = wire.StageCancelled
1487 return s.Attempt, t.saveStep(&s, &k)
1488 }
1489 k.CancelRequested = true
1490 if err := t.saveTask(&k); err != nil {
1491 return 0, err
1492 }
1493 return s.Attempt, t.commandTo(s.RunnerID, s.Person, wire.FrameCancelStep, wire.CancelStepCommand{Person: s.Person, TaskID: k.ID, StepID: s.ID, Attempt: s.Attempt})
1494}
1495
1496// stepReport applies a runner's step report: only the current attempt,
1497// only forward, the base and candidate set once per attempt.
1498func (t *txn) stepReport(l Lease, v *wire.StepReport) error {
1499 if v.BaseSHA != "" && !validSHA(v.BaseSHA) || v.CandidateSHA != "" && !validSHA(v.CandidateSHA) {
1500 return ErrInvalid
1501 }
1502 if !wire.StepReasons[v.Reason] || wire.DoneOnlyReasons[v.Reason] && v.State != wire.StepDone {
1503 // A reason this instance does not know (a newer runner), or a
1504 // done-only reason on a step that is not done, is recorded as
1505 // unknown: refusing it would close the connection and the durable
1506 // report would be refused again on every replay.
1507 v.Reason = wire.ReasonUnknown
1508 }
1509 switch v.State {
1510 case wire.StepRunning, wire.StepDone, wire.StepFailed, wire.StepCancelled:
1511 default:
1512 return ErrInvalid
1513 }
1514 var s stepRecord
1515 if err := t.db.Where("id = ? AND task_id = ?", v.StepID, v.TaskID).First(&s).Error; errors.Is(err, gorm.ErrRecordNotFound) {
1516 return ErrNotFound
1517 } else if err != nil {
1518 return err
1519 }
1520 if s.Person != l.Runner.Person {
1521 return ErrNotFound
1522 }
1523 // Only the runner the step is placed on reports it.
1524 if s.RunnerID != l.Runner.RunnerID {
1525 return ErrRefused
1526 }
1527 if s.Specialist == wire.SpecialistEngineering && l.Protocol < wire.ProtocolMacEngineering {
1528 // A worker's Engineering report below 37 would lose what only 37
1529 // carries (its outcome, its kept session): the whole transition
1530 // is refused before anything changes, and the report stays in
1531 // the worker's outbox until it is back at 37.
1532 if role, err := t.s.authority.RunnerRole(t.db, l.Runner.RunnerID); err != nil {
1533 return err
1534 } else if role != wire.RolePrimary {
1535 return fmt.Errorf("%w: a worker's Engineering report below protocol %d", ErrHeld, wire.ProtocolMacEngineering)
1536 }
1537 }
1538 advanced := false
1539 switch {
1540 case v.Attempt == s.Attempt:
1541 case v.Attempt == s.Attempt+1 && v.State == wire.StepRunning && !wire.StepTerminal(s.State):
1542 // The runner moved the step to its next attempt after the provider
1543 // refused this one and its exit was proven (spec §3): same brief,
1544 // another connection.
1545 advanced = true
1546 default:
1547 return nil
1548 }
1549 k, err := t.loadTask(s.TaskID)
1550 if err != nil {
1551 return err
1552 }
1553 if s.Retired {
1554 if k.MoveAbandoned {
1555 return t.abandonedReport(l, &k, &s, v, advanced)
1556 }
1557 return nil
1558 }
1559 if k.MoveProject != "" {
1560 return t.moveReport(l, &k, &s, v, advanced)
1561 }
1562 if s.Specialist == wire.SpecialistCopy && v.State == wire.StepDone {
1563 if err := t.copyAuthorized(k, s); errors.Is(err, ErrForbidden) {
1564 v.State = wire.StepCancelled
1565 v.Reason = "withdrawn"
1566 v.Pushed = false
1567 } else if err != nil {
1568 return err
1569 }
1570 }
1571 role, err := t.s.authority.RunnerRole(t.db, l.Runner.RunnerID)
1572 if err != nil {
1573 return err
1574 }
1575 if s.Specialist == wire.SpecialistResearch {
1576 return t.researchReport(l, &k, &s, v, advanced)
1577 }
1578 if v.Pushed && role != wire.RolePrimary {
1579 // Only the primary publishes: a worker's pushed is refused.
1580 return fmt.Errorf("%w: a worker reported pushed", ErrRefused)
1581 }
1582 if v.TerminationKind != "" && s.TerminationKind == "" && (v.TerminationKind == wire.TerminationNamespace || v.TerminationKind == wire.TerminationProcessGroup) {
1583 s.TerminationKind = v.TerminationKind
1584 }
1585 if s.Withdrawn && s.Specialist == wire.SpecialistPreview && v.State == wire.StepDone && v.Termination && !advanced {
1586 // A withdrawn preview may still have published before it stopped:
1587 // its outcome is kept (deployed, or could not be confirmed), and no
1588 // other attempt follows it.
1589 if done, ok := acceptPreviewDone(l, role, &s, v); ok && v.CandidateSHA == s.CandidateSHA {
1590 now := t.now()
1591 s.Preview, s.Reason, s.State, s.Terminated, s.FinishedAt, s.Withdrawn = done, v.Reason, wire.StepDone, true, &now, false
1592 if err := t.auditPreview(l.Runner.RunnerID, "preview."+decodePreview(done).Outcome, &s, "withdrawn"); err != nil {
1593 return err
1594 }
1595 if err := t.saveStep(&s, &k); err != nil {
1596 return err
1597 }
1598 return t.removalProgress(l.Runner.RunnerID)
1599 }
1600 }
1601 if s.Withdrawn && s.Specialist == wire.SpecialistPublish && v.State == wire.StepDone && v.Termination && !advanced {
1602 // A withdrawn publish may still have deployed before it stopped:
1603 // its outcome is kept, and no other attempt follows it.
1604 if done, ok := acceptPublishDone(l, role, &s, v); ok {
1605 now := t.now()
1606 s.Publish, s.Reason, s.State, s.Terminated, s.FinishedAt, s.Withdrawn = done, v.Reason, wire.StepDone, true, &now, false
1607 if err := t.saveStep(&s, &k); err != nil {
1608 return err
1609 }
1610 if err := t.publishEnded(&k, &s); err != nil {
1611 return err
1612 }
1613 return t.removalProgress(l.Runner.RunnerID)
1614 }
1615 }
1616 if s.Withdrawn {
1617 // A withdrawn attempt's results never count, whatever arrives first;
1618 // only its termination proof does, and it places the next attempt.
1619 if advanced || !wire.StepTerminal(v.State) || !v.Termination {
1620 return nil
1621 }
1622 return t.withdrawnEnded(&k, &s)
1623 }
1624 if advanced && s.Specialist == wire.SpecialistEngineering && k.MakerSpecialistID != "" {
1625 // A failover the runner made is a new Design attempt, counted
1626 // here once (a replay is no longer an advance). At the autonomy
1627 // limit it is not launched: the runner's start of it is refused
1628 // (the attempt moves on), and the step is held for the person
1629 // through the held-step card (designGate, via the dispatch).
1630 if k.DesignRuns >= wire.DesignRunLimit {
1631 s.Attempt = v.Attempt
1632 if err := t.replace(&k, &s); err != nil {
1633 return err
1634 }
1635 return t.saveStep(&s, &k)
1636 }
1637 if err := t.designRan(&k); err != nil {
1638 return err
1639 }
1640 }
1641 if !wire.StepTerminal(s.State) && wire.StepTerminal(v.State) && v.State != wire.StepDone && v.Termination {
1642 switch {
1643 case v.State == wire.StepFailed && v.Reason == "placement_refused":
1644 // It lacks a need: place it again without that runner.
1645 s.RefusedBy = encodeList(append(decodeList(s.RefusedBy), l.Runner.RunnerID))
1646 if err := t.replace(&k, &s); err != nil {
1647 return err
1648 }
1649 return t.saveStep(&s, &k)
1650 case v.State == wire.StepFailed && v.Reason == wire.ReasonSandboxUnproven && s.Specialist == wire.SpecialistChecks && role == wire.RoleWorker:
1651 // The Mac ran nothing: its sandbox is not proven and nobody
1652 // chose to run outside it. Never a failure and no taint: the
1653 // next attempt waits for its sandbox.
1654 if err := t.sandboxUnproven(l.Runner.RunnerID); err != nil {
1655 return err
1656 }
1657 if err := t.replace(&k, &s); err != nil {
1658 return err
1659 }
1660 return t.saveStep(&s, &k)
1661 }
1662 }
1663 now := t.now()
1664 changed := false
1665 wasTerminal := wire.StepTerminal(s.State)
1666 // previewed: a preview came up; the merge card asking about its
1667 // candidate shows it once the step is saved.
1668 previewed := false
1669 if advanced {
1670 s.Attempt, changed = v.Attempt, true
1671 }
1672 if wire.StepTerminal(s.State) {
1673 // Only the termination proof may still arrive for an ended attempt.
1674 if v.State == s.State && v.Termination && !s.Terminated {
1675 s.Terminated, changed = true, true
1676 }
1677 } else {
1678 if s.Specialist == wire.SpecialistCopy {
1679 if err := t.copyUsageReport(k, s, v); err != nil {
1680 return err
1681 }
1682 }
1683 // The scheduler's hold: kept while the runner holds the step,
1684 // cleared by any report without it.
1685 if acceptHold(&s, v, t.now()) {
1686 changed = true
1687 }
1688 if wire.StepTerminal(v.State) {
1689 if s.Specialist == wire.SpecialistCopy && v.Copy != nil && v.Copy.Input == s.CandidateSHA && v.Copy.Owner == s.CopyOwner && v.Copy.Delegation == s.CopyRevision {
1690 raw, _ := json.Marshal(v.Copy)
1691 s.CopyResult = string(raw)
1692 }
1693 if err := t.recordUsage(l, s.Person, s.Specialist, s.TaskID, s.ID, "", s.Round, v.Usage); err != nil {
1694 return err
1695 }
1696 }
1697 if v.Switched != nil {
1698 // The first refusal says what the step moved from; a later
1699 // report adds where it went.
1700 var had wire.Switched
1701 if s.Switched == "" || json.Unmarshal([]byte(s.Switched), &had) == nil && had.To == "" && v.Switched.To != "" {
1702 if s.Switched != "" {
1703 v.Switched.From, v.Switched.ResetsAt, v.Switched.Window = had.From, had.ResetsAt, had.Window
1704 }
1705 s.Switched, changed = asJSON(v.Switched), true
1706 }
1707 }
1708 if s.BaseSHA == "" && v.BaseSHA != "" {
1709 s.BaseSHA, changed = v.BaseSHA, true
1710 if k.BaseSHA == "" {
1711 k.BaseSHA = v.BaseSHA
1712 }
1713 }
1714 if s.CandidateSHA == "" && v.CandidateSHA != "" {
1715 s.CandidateSHA, changed = v.CandidateSHA, true
1716 if role != wire.RolePrimary && s.Specialist == wire.SpecialistEngineering && !s.Republish && l.Protocol >= wire.ProtocolMacEngineering {
1717 // A worker's commit: what it is (unfinished, no shell) is kept
1718 // for its publication, which alone ends the step that way.
1719 s.OutcomePhase = workerOutcome(v.OutcomePhase)
1720 }
1721 }
1722 if v.Family != "" && s.Family != v.Family || v.Account != "" && s.Account != v.Account {
1723 s.Family, s.Account, changed = firstSet(v.Family, s.Family), firstSet(v.Account, s.Account), true
1724 }
1725 if n := len(v.Usage); n > 0 && v.Usage[n-1].PriceVersion != "" && v.Usage[n-1].Model != "" && v.Usage[n-1].Model != s.Model && len(v.Usage[n-1].Model) <= wire.MaxModelName {
1726 // A metered step's model (one chosen per step, §16.7).
1727 s.Model, changed = v.Usage[n-1].Model, true
1728 }
1729 switch v.State {
1730 case wire.StepRunning:
1731 if s.State == wire.StepQueued && v.Hold == nil {
1732 // A held step is still queued: it starts when it runs.
1733 s.State, s.StartedAt, changed = wire.StepRunning, &now, true
1734 }
1735 if previewBuilt(l, role, &s, v) {
1736 changed = true
1737 if err := t.auditPreview(l.Runner.RunnerID, "preview.built", &s, shortDigest(v.Preview.Digest)); err != nil {
1738 return err
1739 }
1740 }
1741 if publishBuilt(l, role, &s, v) {
1742 changed = true
1743 if err := t.auditPublish("runner:"+l.Runner.RunnerID, "publish.built", k.ID, decodePublish(s.Publish).App, s.CandidateSHA, s.ID+"/"+itoa64(s.Attempt)+":"+shortDigest(v.Publish.Digest)); err != nil {
1744 return err
1745 }
1746 }
1747 case wire.StepDone:
1748 switch s.Specialist {
1749 case wire.SpecialistPreview:
1750 // Done only for this task's app and the export recorded as
1751 // built: deployed (with its URL) or unconfirmed.
1752 done, ok := acceptPreviewDone(l, role, &s, v)
1753 if !ok || v.CandidateSHA != s.CandidateSHA {
1754 return nil
1755 }
1756 s.Preview, s.Reason = done, v.Reason
1757 kind := "preview.deployed"
1758 if decodePreview(done).Outcome != wire.PreviewDeployed {
1759 kind = "preview.unconfirmed"
1760 }
1761 if err := t.auditPreview(l.Runner.RunnerID, kind, &s, s.Reason); err != nil {
1762 return err
1763 }
1764 previewed = kind == "preview.deployed"
1765 case wire.SpecialistPublish:
1766 // Done only for the step's app and the export recorded as
1767 // built: published (with its URL) or unconfirmed.
1768 done, ok := acceptPublishDone(l, role, &s, v)
1769 if !ok {
1770 return nil
1771 }
1772 s.Publish, s.Reason = done, v.Reason
1773 case wire.SpecialistCopy:
1774 if err := t.copyDone(l, &k, &s, v); err != nil {
1775 return err
1776 }
1777 if v.Reason == "proposal_failed" {
1778 s.Reason = v.Reason
1779 }
1780 case wire.SpecialistEngineering:
1781 // Done is only for the attempt's own candidate: pushed by the
1782 // primary, or committed by a worker (the primary publishes it).
1783 if s.CandidateSHA == "" || v.CandidateSHA != s.CandidateSHA || !v.Pushed && role == wire.RolePrimary {
1784 return nil
1785 }
1786 // Pushed is the primary's word: for a worker's commit only the
1787 // primary's published report sets it, and this report keeps it.
1788 if role == wire.RolePrimary {
1789 // step_timeout: the step ran out of time and the runner
1790 // pushed the work it had done; checks and review judge it,
1791 // and it is never taken for finished.
1792 // shell_unavailable: a fix round without a working shell,
1793 // which does not count against the task's rounds.
1794 if v.Reason == "proposal_failed" || v.Reason == reasonUnfinished || v.Reason == wire.ReasonShellUnavailable {
1795 s.Reason = v.Reason
1796 }
1797 s.Pushed = true
1798 }
1799 if role == wire.RolePrimary {
1800 s.ChangeFiles = acceptChangeFiles(l, role, s, v.ChangeFiles)
1801 if err := t.acceptChangeDiffs(l, s, v.ChangeDiffs, l.Runner.RunnerID); err != nil {
1802 return err
1803 }
1804 } else {
1805 // A worker's commit is measured by the primary when it
1806 // publishes (published): this report never sets or clears
1807 // its files or diffs, and its outcome's reason waits for
1808 // that publication too.
1809 takeOutcome(&s)
1810 }
1811 s.Apple = v.Apple
1812 s.Askable = v.Askable
1813 // The kept session the runner names (protocol 37): a question
1814 // about this attempt resumes exactly it.
1815 s.SessionID = ""
1816 if v.Askable {
1817 s.SessionID = keptSessionID(v.SessionID)
1818 }
1819 if s.SpecialistID != "" {
1820 // A maker's attempt: its captures are kept only now,
1821 // if its options check, and never otherwise.
1822 if err := t.keepCaptures(&k, &s, v.Options); err != nil {
1823 return err
1824 }
1825 }
1826 if s.Rebase && s.BaseSHA != "" {
1827 // The change sits on the new tip now: review reads it from
1828 // there, and a later rebase starts from there.
1829 k.BaseSHA = s.BaseSHA
1830 }
1831 case wire.SpecialistMerge:
1832 // Done only once the hub confirmed a merge of the SHA this
1833 // step was asked to merge.
1834 if v.CandidateSHA != s.CandidateSHA || !validSHA(v.MergeSHA) || !wire.ValidBranchName(v.Into) || v.Strategy != wire.MergeCommit && v.Strategy != wire.MergeSquash || !v.Termination {
1835 return nil
1836 }
1837 if err := t.mergeDone(&k, &s, v); err != nil {
1838 return err
1839 }
1840 default:
1841 // A judgement counts only for the SHA it was asked to judge.
1842 if !judgement(s.Specialist, v) || v.CandidateSHA != s.CandidateSHA || !v.Termination {
1843 return nil
1844 }
1845 var pr projectRecord
1846 if err := t.db.Where("id = ?", k.ProjectID).First(&pr).Error; err != nil {
1847 return err
1848 }
1849 hosted, ok := acceptHosted(l, role, s, pr.Repo, k.Branch, v)
1850 if !ok {
1851 return nil
1852 }
1853 s.Reason, s.Verdict, s.ReviewLabel, s.Checks, s.Gate, s.ExitCode = v.Reason, v.Verdict, v.ReviewLabel, v.Checks, v.Gate, v.ExitCode
1854 if s.Specialist == wire.SpecialistChecks && role == wire.RolePrimary && l.Protocol >= wire.ProtocolInjectionDefences {
1855 switch v.BaseChecks {
1856 case wire.ChecksPassed, wire.ChecksFailed, wire.ChecksCannotRun:
1857 s.BaseChecks = v.BaseChecks
1858 }
1859 if s.BaseChecks == wire.ChecksFailed {
1860 s.Checks, s.Reason = wire.ChecksFailed, "base_checks_failed"
1861 if s.ExitCode != nil && *s.ExitCode == 0 {
1862 s.ExitCode = nil
1863 }
1864 }
1865 }
1866 if s.Specialist == wire.SpecialistChecks && role == wire.RoleWorker {
1867 // A worker's word on how its checks were confined;
1868 // anything but seatbelt is outside the sandbox, and a
1869 // runner that once ran checks outside it never again
1870 // counts as sandboxed (the instance's record, which the
1871 // runner cannot clear).
1872 tainted, err := t.tainted(l.Runner.RunnerID)
1873 if err != nil {
1874 return err
1875 }
1876 s.ChecksSandbox = wire.SandboxNone
1877 if v.ChecksSandbox == wire.SandboxSeatbelt && !tainted {
1878 s.ChecksSandbox = wire.SandboxSeatbelt
1879 }
1880 if s.ChecksSandbox == wire.SandboxNone {
1881 if err := t.markTainted(l.Runner.RunnerID); err != nil {
1882 return err
1883 }
1884 }
1885 }
1886 if s.Specialist == wire.SpecialistChecks && l.Protocol >= wire.ProtocolCopy && v.Failure != nil {
1887 raw, _ := json.Marshal(v.Failure)
1888 s.FailureSignature = string(raw)
1889 }
1890 s.BaseChecksSHA = acceptBaseChecks(l, role, s, v)
1891 s.Output = clipText(v.Output, wire.MaxChecksOutput)
1892 if hosted != "" {
1893 s.HostedCI, s.ChecksSandbox = hosted, wire.SandboxHosted
1894 }
1895 // Merge authority: the review's measured change, kept only
1896 // when it is exactly this attempt's, whole, from the primary.
1897 s.ChangeFacts = acceptFacts(l, role, s, pr.Repo, v.Change)
1898 found := cleanFindings(v.Findings)
1899 for i := range found {
1900 found[i].Repo, found[i].At = pr.Repo, now
1901 }
1902 raw, _ := json.Marshal(found)
1903 s.Findings = string(raw)
1904 s.Askable = v.Askable && s.Specialist == wire.SpecialistReview
1905 // Review's word that the candidate has a preview config, from
1906 // the primary at protocol 9 only (scheduling evidence).
1907 s.HasPreview = s.Specialist == wire.SpecialistReview && v.HasPreview && role == wire.RolePrimary && l.Protocol >= wire.ProtocolPreview
1908 }
1909 s.State, s.Terminated, s.FinishedAt, changed = wire.StepDone, v.Termination, &now, true
1910 default:
1911 s.State, s.Reason, s.Terminated, s.FinishedAt, changed = v.State, v.Reason, v.Termination, &now, true
1912 if s.Specialist == wire.SpecialistPreview {
1913 if err := t.auditPreview(l.Runner.RunnerID, "preview.failed", &s, v.State+":"+v.Reason); err != nil {
1914 return err
1915 }
1916 }
1917 if s.Reason == "" {
1918 s.Reason = v.State
1919 }
1920 }
1921 if wire.StepTerminal(s.State) {
1922 s.Summary, s.LogTail = clipText(v.Summary, wire.MaxStepSummary), clipText(v.LogTail, wire.MaxLogTail)
1923 s.Headline = cleanHeadline(v.Headline)
1924 }
1925 }
1926 if !changed {
1927 return nil
1928 }
1929 if role != wire.RolePrimary && s.Specialist == wire.SpecialistEngineering && s.CandidateSHA != "" && v.Phase == phaseCommitted {
1930 if err := t.candidateCommitted(k, &s); err != nil {
1931 return err
1932 }
1933 }
1934 if wire.StepTerminal(s.State) && k.MoveProject == "" && k.CancelRequested && !wire.FinalStage(k.Stage) && (s.State == wire.StepCancelled || s.Terminated) {
1935 k.Stage = wire.StageCancelled
1936 }
1937 if err := t.saveStep(&s, &k); err != nil {
1938 return err
1939 }
1940 if k.MoveProject != "" {
1941 return t.finishMove(&k)
1942 }
1943 if previewed {
1944 // The merge card asking about this candidate shows it now.
1945 if err := t.touchMergeCards(k); err != nil {
1946 return err
1947 }
1948 }
1949 if s.Specialist == wire.SpecialistPublish && !wasTerminal && wire.StepTerminal(s.State) {
1950 if err := t.publishEnded(&k, &s); err != nil {
1951 return err
1952 }
1953 }
1954 // Needs you for a hold where the creator's input changes the outcome
1955 // (connectors spec §8), or the card withdrawn once it does not.
1956 if err := t.heldCard(k, s); err != nil {
1957 return err
1958 }
1959 if err := t.advance(&k); err != nil {
1960 return err
1961 }
1962 if k.MakerSpecialistID != "" {
1963 // An attempt's end (or its proof) may be the last a removed
1964 // maker's task waited for.
1965 return t.offerRecovery(k.ID)
1966 }
1967 return nil
1968}
1969
1970func firstSet(a, b string) string {
1971 if a != "" {
1972 return a
1973 }
1974 return b
1975}
1976
1977// judgement reports whether a done report carries a whole result for a
1978// checks or review step.
1979// acceptHosted judges a checks report's hosted CI binding (release slice
1980// 1): none, and no hosted gate, is an ordinary report (ok, ""). With one,
1981// it counts only from the primary on a protocol 5 connection, for exactly
1982// the project's repository, the task's branch and the step's candidate,
1983// with a report time, its failing units within bounds and its state
1984// matching the outcome; then ok and the binding to store.
1985func acceptHosted(l Lease, role string, s stepRecord, repo, branch string, v *wire.StepReport) (string, bool) {
1986 h := v.Hosted
1987 if h == nil {
1988 return "", v.Gate != wire.GateHosted
1989 }
1990 if s.Specialist != wire.SpecialistChecks || role != wire.RolePrimary || l.Protocol < wire.ProtocolHostedChecks {
1991 return "", false
1992 }
1993 if h.Repo != repo || h.Branch != branch || h.SHA != s.CandidateSHA || h.ReportedAt <= 0 || len(h.Failed) > wire.MaxHostedFailed {
1994 return "", false
1995 }
1996 for _, name := range h.Failed {
1997 if _, ok := cleanText(name, wire.MaxHostedName); !ok || strings.ContainsAny(name, "\n\r") {
1998 return "", false
1999 }
2000 }
2001 var fits bool
2002 switch h.State {
2003 case wire.HostedSuccess:
2004 fits = v.Checks == wire.ChecksPassed && v.Gate == wire.GateHosted
2005 case wire.HostedFailure:
2006 fits = v.Checks == wire.ChecksFailed && v.Gate == wire.GateHosted
2007 case "skipped":
2008 fits = v.Checks == wire.ChecksNone
2009 case "lost", "stale":
2010 fits = v.Checks == wire.ChecksCannotRun && v.Reason == "checks_unavailable"
2011 }
2012 if !fits {
2013 return "", false
2014 }
2015 raw, _ := json.Marshal(wire.HostedResult{Repo: h.Repo, Branch: h.Branch, SHA: h.SHA, State: h.State, ReportedAt: h.ReportedAt, Failed: append([]string{}, h.Failed...)})
2016 return string(raw), true
2017}
2018
2019func judgement(specialist string, v *wire.StepReport) bool {
2020 switch specialist {
2021 case wire.SpecialistChecks:
2022 switch v.Checks {
2023 case wire.ChecksPassed:
2024 return v.ExitCode != nil && *v.ExitCode == 0 && v.Gate != ""
2025 case wire.ChecksFailed:
2026 return v.ExitCode != nil && *v.ExitCode != 0 && v.Gate != ""
2027 case wire.ChecksNone:
2028 return v.Gate == ""
2029 case wire.ChecksCannotRun:
2030 return v.Reason != ""
2031 }
2032 case wire.SpecialistReview:
2033 switch v.ReviewLabel {
2034 case wire.ReviewOtherFamily, wire.ReviewSameFamily, wire.ReviewSameAccount:
2035 default:
2036 return false
2037 }
2038 return v.Verdict == wire.VerdictApprove || v.Verdict == wire.VerdictChanges
2039 }
2040 return false
2041}
2042
2043// cleanFindings keeps review findings within bounds: plain text, a clean
2044// repository path or none, a sane line.
2045func cleanFindings(in []wire.Finding) []wire.Finding {
2046 out := []wire.Finding{}
2047 for _, f := range in {
2048 text, ok := cleanText(f.Text, wire.MaxFindingText)
2049 if !ok || len(out) >= wire.MaxStepFindings {
2050 continue
2051 }
2052 p := ""
2053 if f.Path != "" {
2054 if p, ok = cleanPath(f.Path); !ok {
2055 p = ""
2056 }
2057 }
2058 line := f.Line
2059 if line < 0 || line > 1_000_000 || p == "" {
2060 line = 0
2061 }
2062 out = append(out, wire.Finding{ID: newID("rf_"), Headline: cleanHeadline(f.Headline), Text: text, Path: p, Line: line})
2063 }
2064 return out
2065}
2066
2067// syncSteps settles steps the person's runner no longer holds. The
2068// runner's sync lists every attempt it still has a record of (running,
2069// a report not yet acked, or a termination still unverified), so absence
2070// means it has nothing left to report and verified at start that no
2071// namespace of an earlier process survives: the step has ended. A
2072// dispatch it has not acked is still on its way.
2073func (t *txn) syncSteps(l Lease, held []wire.StepRun) error {
2074 // The runner holds a step at this attempt or a later one it moved to
2075 // itself (a failover the instance has not heard of yet).
2076 have := map[string]int64{}
2077 for _, h := range held {
2078 have[h.StepID] = max(have[h.StepID], h.Attempt)
2079 }
2080 // Only this runner's own steps: a worker's sync never settles the
2081 // primary's work, nor a Linux attempt awaiting its termination proof.
2082 var rows []stepRecord
2083 if err := t.db.Where("runner_id = ? AND person = ? AND (state IN ? OR (coalesce(terminated, 0) = 0 AND task_id IN (SELECT id FROM chat_tasks WHERE (coalesce(move_project, '') <> '' OR coalesce(move_abandoned, 0) = 1))))", l.Runner.RunnerID, l.Runner.Person, []string{wire.StepQueued, wire.StepRunning}).Find(&rows).Error; err != nil {
2084 return err
2085 }
2086 for i := range rows {
2087 s := rows[i]
2088 if have[s.ID] >= s.Attempt {
2089 continue
2090 }
2091 var unacked int64
2092 if err := t.db.Model(&commandRecord{}).Where("runner_id = ? AND person = ? AND kind = ? AND acked_at IS NULL AND body LIKE ?", l.Runner.RunnerID, s.Person, wire.FrameDispatch, `%"step_id":"`+s.ID+`","attempt":`+itoa64(s.Attempt)+`,%`).Count(&unacked).Error; err != nil {
2093 return err
2094 }
2095 if unacked != 0 {
2096 continue
2097 }
2098 k, err := t.loadTask(s.TaskID)
2099 if err != nil {
2100 return err
2101 }
2102 if k.MoveAbandoned {
2103 now := t.now()
2104 s.State, s.Terminated, s.FinishedAt = wire.StepCancelled, true, &now
2105 if err := t.saveStep(&s, &k); err != nil {
2106 return err
2107 }
2108 if err := t.finishAbandon(&k); err != nil {
2109 return err
2110 }
2111 continue
2112 }
2113 if k.MoveProject != "" {
2114 // Absence in this authenticated sync proves the dispatched
2115 // attempt has ended, including a lost final termination report.
2116 now := t.now()
2117 if !wire.StepTerminal(s.State) {
2118 s.State, s.Reason = wire.StepCancelled, "cancelled"
2119 }
2120 s.Terminated, s.FinishedAt = true, &now
2121 if err := t.saveStep(&s, &k); err != nil {
2122 return err
2123 }
2124 if err := t.finishMove(&k); err != nil {
2125 return err
2126 }
2127 continue
2128 }
2129 if s.Withdrawn {
2130 // Its runner holds nothing of it and verified none survives:
2131 // the withdrawn attempt is over, and the next one is placed.
2132 if err := t.withdrawnEnded(&k, &s); err != nil {
2133 return err
2134 }
2135 continue
2136 }
2137 now := t.now()
2138 s.State, s.Reason, s.Terminated, s.FinishedAt = wire.StepFailed, "interrupted", true, &now
2139 if k.CancelRequested && s.Specialist != wire.SpecialistResearch {
2140 s.State, s.Reason = wire.StepCancelled, "cancelled"
2141 k.Stage = wire.StageCancelled
2142 }
2143 if err := t.saveStep(&s, &k); err != nil {
2144 return err
2145 }
2146 // A worker's sync never reaches advanceAll: triage the stop here.
2147 if err := t.triage(&k); err != nil {
2148 return err
2149 }
2150 if k.MakerSpecialistID != "" {
2151 if err := t.offerRecovery(k.ID); err != nil {
2152 return err
2153 }
2154 }
2155 }
2156 return nil
2157}
2158
2159func itoa64(n int64) string { raw, _ := json.Marshal(n); return string(raw) }
2160
2161// Tasks lists the team's tasks, newest first.
2162func (s *Store) Tasks(ctx context.Context, person string) (wire.TaskList, error) {
2163 out, _, err := s.TasksWithSourceCap(ctx, person)
2164 return out, err
2165}
2166
2167// TasksWithSourceCap also reports whether the source reached its cap before
2168// visibility filtering. A shorter visible list need not be complete.
2169func (s *Store) TasksWithSourceCap(ctx context.Context, person string) (out wire.TaskList, capped bool, err error) {
2170 err = s.read(ctx, func(tx *gorm.DB) error {
2171 if err := s.authority.CurrentPerson(ctx, tx); err != nil {
2172 return err
2173 }
2174 out.Items, err = (&txn{s: s, db: tx}).recentTasks(wire.MaxTaskList)
2175 if err != nil {
2176 return err
2177 }
2178 capped = len(out.Items) >= wire.MaxTaskList
2179 // A test person's tasks are listed to itself only.
2180 if hide := s.authority.TestPerson; hide != nil {
2181 out.Items = slices.DeleteFunc(out.Items, func(k wire.Task) bool { return k.Creator != person && hide(k.Creator) })
2182 }
2183 return nil
2184 })
2185 return out, capped, err
2186}
2187
2188func (t *txn) recentTasks(limit int) ([]wire.Task, error) {
2189 var rows []taskRecord
2190 if err := t.db.Order("created_at DESC, id DESC").Limit(limit).Find(&rows).Error; err != nil {
2191 return nil, err
2192 }
2193 out := make([]wire.Task, 0, len(rows))
2194 for _, k := range rows {
2195 v, err := t.taskView(k)
2196 if err != nil {
2197 return nil, err
2198 }
2199 out = append(out, v)
2200 }
2201 return out, nil
2202}
2203
2204// Task reads one task.
2205func (s *Store) Task(ctx context.Context, person, id string) (wire.Task, error) {
2206 return s.readTaskView(ctx, person, id, taskViewOptions{})
2207}
2208
2209// TaskDetail is the device's GET /tasks/{id} projection, including bounded
2210// file facts. It shares Task's current-member and task-read authorization.
2211func (s *Store) TaskDetail(ctx context.Context, person, id string) (wire.Task, error) {
2212 return s.readTaskView(ctx, person, id, taskViewOptions{changeFiles: true})
2213}
2214
2215func (s *Store) readTaskView(ctx context.Context, person, id string, options taskViewOptions) (out wire.Task, err error) {
2216 err = s.read(ctx, func(tx *gorm.DB) error {
2217 out, err = s.taskAt(ctx, tx, id, options)
2218 return err
2219 })
2220 return out, err
2221}
2222
2223// TaskAt uses task-read authority on the caller's transaction. Preview grants
2224// need that same read atomically with their credential and single-use checks.
2225func (s *Store) TaskAt(ctx context.Context, tx *gorm.DB, id string) (wire.Task, error) {
2226 return s.taskAt(ctx, tx, id, taskViewOptions{})
2227}
2228
2229func (s *Store) taskAt(ctx context.Context, tx *gorm.DB, id string, options taskViewOptions) (wire.Task, error) {
2230 if err := s.authority.CurrentPerson(ctx, tx); err != nil {
2231 return wire.Task{}, err
2232 }
2233 t := &txn{s: s, db: tx}
2234 k, err := t.loadTask(id)
2235 if err != nil {
2236 return wire.Task{}, err
2237 }
2238 return t.taskViewWith(k, options)
2239}
2240
2241// CancelTask is POST /tasks/{id}/cancel: owners only.
2242func (s *Store) CancelTask(ctx context.Context, person, id string) (attempt int64, err error) {
2243 err = s.tx(ctx, func(t *txn) error {
2244 if err := s.authority.CurrentPerson(ctx, t.db); err != nil {
2245 return err
2246 }
2247 attempt, err = t.cancelTask(person, id)
2248 return err
2249 })
2250 return attempt, err
2251}
2252
2253// RetryTask is POST /tasks/{id}/retry: a new attempt of the last step,
2254// only once the runner confirmed termination of the current one.
2255func (s *Store) RetryTask(ctx context.Context, person, id string) (attempt int64, err error) {
2256 return s.retryTask(ctx, person, id, "")
2257}
2258
2259// RetryStep is the person's Retry of one step of a task (the task page's
2260// Retry on a failed preview behind a newer step): the checks and the new
2261// attempt RetryTask makes, for that step.
2262func (s *Store) RetryStep(ctx context.Context, person, id, step string) (attempt int64, err error) {
2263 if step == "" {
2264 return 0, ErrInvalid
2265 }
2266 return s.retryTask(ctx, person, id, step)
2267}
2268
2269func (s *Store) retryTask(ctx context.Context, person, id, step string) (attempt int64, err error) {
2270 err = s.tx(ctx, func(t *txn) error {
2271 if err := s.authority.CurrentPerson(ctx, t.db); err != nil {
2272 return err
2273 }
2274 attempt, err = t.personRetry(person, id, step, false)
2275 return err
2276 })
2277 return attempt, err
2278}
2279
2280// personRetry is the person's Retry of the task's step ("" for its newest
2281// step): an owner, the task's creator, a task not cancelled; on a done
2282// task only its preview (retryStepOf). The coordinator's retry_step makes
2283// exactly these checks for its person (coordinator), on RetryStepKinds
2284// only. A refusal carries its fixed reason (retryRefusal).
2285func (t *txn) personRetry(person, id, step string, coordinator bool) (int64, error) {
2286 if err := t.isOwner(person); errors.Is(err, ErrForbidden) {
2287 return 0, refuseRetry(ErrForbidden, retryNotOwner)
2288 } else if err != nil {
2289 return 0, err
2290 }
2291 k, err := t.loadTask(id)
2292 if err != nil {
2293 return 0, err
2294 }
2295 // Only the task's creator retries it, onto their own runner.
2296 if k.Creator != person {
2297 return 0, refuseRetry(ErrForbidden, retryNotYours)
2298 }
2299 if k.Stage == wire.StageCancelled || k.CancelRequested {
2300 return 0, refuseRetry(ErrTaskEnded, retryTaskCancelled)
2301 }
2302 return t.retryStepOf(&k, person, step, coordinator)
2303}
2304
2305// retryStep runs the task's newest step again as its next attempt, once
2306// the runner confirmed termination of the current one: the person's Retry
2307// (RetryTask) and needs-you triage's automatic retry of a passing stop,
2308// under the housekeeping principal, which refuses a merge step.
2309func (t *txn) retryStep(k *taskRecord, person string) (attempt int64, err error) {
2310 return t.retryStepOf(k, person, "", false)
2311}
2312
2313// retryStepOf is retryStep for a named step: the newest step, or a failed
2314// preview behind it (retryPreview). "" is the newest step. A preview, the
2315// newest or not, runs again only as retryPreview says.
2316//
2317// coordinator is the coordinator's retry_step: the same checks, never on
2318// a step outside wire.RetryStepKinds (a merge, a publish, the work), and
2319// the attempt it starts is recorded as its own (CoordinatorAttempt).
2320func (t *txn) retryStepOf(k *taskRecord, person, step string, coordinator bool) (attempt int64, err error) {
2321 st, found, err := t.latestStep(k.ID)
2322 if err != nil {
2323 return 0, err
2324 }
2325 if step != "" {
2326 var named stepRecord
2327 if err := t.db.Where("id = ? AND task_id = ? AND coalesce(retired, 0) = 0", step, k.ID).First(&named).Error; errors.Is(err, gorm.ErrRecordNotFound) {
2328 return 0, refuseRetry(ErrNotRetryable, retryNoStep)
2329 } else if err != nil {
2330 return 0, err
2331 }
2332 if named.Specialist != wire.SpecialistPreview && (!found || named.ID != st.ID) {
2333 if k.Stage == wire.StageDone {
2334 return 0, refuseRetry(ErrTaskEnded, retryTaskDone)
2335 }
2336 return 0, refuseRetry(ErrNotRetryable, retryNotNewest)
2337 }
2338 st, found = named, true
2339 }
2340 if coordinator && (!found || !slices.Contains(wire.RetryStepKinds, st.Specialist)) {
2341 return 0, ErrForbidden
2342 }
2343 if found && st.Specialist == wire.SpecialistPreview {
2344 return t.retryPreview(k, &st, person, coordinator)
2345 }
2346 if wire.FinalStage(k.Stage) {
2347 // A done task runs only its preview again; its merge, checks and
2348 // review stay as they are.
2349 return 0, refuseRetry(ErrTaskEnded, retryTaskDone)
2350 }
2351 if found && st.Specialist == wire.SpecialistEngineering && st.State == wire.StepDone && st.Publication == wire.PublicationFailed {
2352 // A worker's commit the primary could not push: publish the
2353 // recorded commit again, without running Engineering.
2354 var tr transferRecord
2355 err := t.db.Where("step_id = ? AND attempt = ? AND direction = ?", st.ID, st.Attempt, wire.TransferOutbound).Order("created_at DESC").First(&tr).Error
2356 if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
2357 return 0, err
2358 }
2359 pruned := err != nil
2360 st.Reason = ""
2361 primary, err := t.s.authority.PrimaryRunner(t.db, st.Person)
2362 if err != nil {
2363 return 0, err
2364 }
2365 if pruned && primary == "" {
2366 // Its transfer is gone and no primary is there: it waits for
2367 // one, which asks the worker again (reconcileUnpublished).
2368 now := t.now()
2369 st.Publication, st.Placement, st.WaitingSince = "", wire.PlacementWaiting, &now
2370 if err := t.saveStep(&st, k); err != nil {
2371 return 0, err
2372 }
2373 } else if pruned || primary != "" && tr.ToRunner != primary {
2374 // Its transfer was pruned (the worker keeps its candidate
2375 // under KeepUntil), or went to a primary since replaced: the
2376 // worker sends it again, to this one, which publishes it.
2377 st.Publication = ""
2378 if err := t.saveStep(&st, k); err != nil {
2379 return 0, err
2380 }
2381 if _, err := t.openTransfer(*k, st, st.RunnerID, primary, wire.TransferHeader{Direction: wire.TransferOutbound, BaseSHA: st.BaseSHA, CandidateSHA: st.CandidateSHA}); err != nil {
2382 return 0, err
2383 }
2384 } else if err := t.publish(k, &st, tr); err != nil {
2385 return 0, err
2386 }
2387 k.Stage = wire.StageInProgress
2388 attempt = st.Attempt
2389 return attempt, t.saveTask(k)
2390 }
2391 if reason := endedReason(st, found); reason != "" {
2392 return 0, refuseRetry(ErrNotRetryable, reason)
2393 }
2394 if st.Person != person {
2395 return 0, refuseRetry(ErrForbidden, retryNotYours)
2396 }
2397 if st.Specialist == wire.SpecialistMerge {
2398 // Never merge a SHA that is not the judged one, as it stands; a
2399 // person's Retry is their decision, through the gate.
2400 if err := t.hkForbid("merge"); err != nil {
2401 return 0, err
2402 }
2403 steps, err := t.steps(k.ID)
2404 if err != nil {
2405 return 0, err
2406 }
2407 p := progressFor(*k, steps)
2408 if p.candidate != st.CandidateSHA || !p.mergeAllowed(st.WithoutChecks) {
2409 return 0, refuseRetry(ErrNotRetryable, retryCommitChanged)
2410 }
2411 _, protocol, err := t.primaryState(st.Person)
2412 if err != nil {
2413 return 0, err
2414 }
2415 if d, err := t.authorizeMerge(k, p, atDispatch, person, protocol); err != nil {
2416 return 0, err
2417 } else if d.Class != mergegate.ClassAct {
2418 return 0, ErrNotRetryable
2419 }
2420 st.DecidedBy = decidedPerson + person
2421 }
2422 primary, err := t.s.authority.PrimaryRunner(t.db, st.Person)
2423 if err != nil {
2424 return 0, err
2425 }
2426 if primary == "" {
2427 return 0, refuseRetry(ErrNotRetryable, retryNoRunner)
2428 }
2429 from := st.Attempt
2430 st.Attempt++
2431 candidate := st.CandidateSHA
2432 // A failed push publishes the commit it recorded again instead of
2433 // running Engineering anew (chained to the attempt that made it).
2434 republish := st.Specialist == wire.SpecialistEngineering && st.Reason == "push_failed" && candidate != ""
2435 if republish && !st.Republish {
2436 st.FromAttempt = from
2437 }
2438 st.Republish = republish
2439 st.State, st.Reason, st.Pushed, st.Terminated, st.Summary, st.LogTail, st.StartedAt, st.FinishedAt = wire.StepQueued, "", false, false, "", "", nil, nil
2440 st.Headline = ""
2441 st.Verdict, st.ReviewLabel, st.Findings, st.Checks, st.Gate, st.ExitCode, st.Output, st.Askable = "", "", "", "", "", nil, "", false
2442 st.SessionID = ""
2443 st.Activity = ""
2444 if st.Specialist == wire.SpecialistEngineering && !republish {
2445 // Engineering runs again from the step's base: a new candidate.
2446 st.CandidateSHA, st.OutcomePhase = "", ""
2447 }
2448 if !republish {
2449 st.FromAttempt = 0
2450 }
2451 if st.BaseSHA == "" && !st.Rebase {
2452 st.BaseSHA = k.BaseSHA
2453 }
2454 if st.Specialist == wire.SpecialistMerge {
2455 st.MergeSHA, st.MergeInto, st.MergeStrategy, st.MergeSource, st.MergeParents = "", "", "", "", ""
2456 }
2457 st.Withdrawn, st.RefusedBy = false, ""
2458 if coordinator {
2459 st.CoordinatorAttempt = st.Attempt
2460 }
2461 // Run again under the task's kind as it is now.
2462 st.Kind = wire.NormalKind(k.Kind)
2463 if err := t.dispatchStep(k, &st); err != nil {
2464 return 0, err
2465 }
2466 k.Stage = wire.StageInProgress
2467 switch st.Specialist {
2468 case wire.SpecialistMerge:
2469 k.Stage = wire.StageMerging
2470 case wire.SpecialistChecks, wire.SpecialistReview:
2471 k.Stage = wire.StageInReview
2472 }
2473 attempt = st.Attempt
2474 return attempt, t.saveStep(&st, k)
2475}
2476
2477// StepLog reads a step's log tail.
2478func (s *Store) StepLog(ctx context.Context, person, id string) (out wire.StepLog, err error) {
2479 err = s.read(ctx, func(tx *gorm.DB) error {
2480 if err := s.authority.CurrentPerson(ctx, tx); err != nil {
2481 return err
2482 }
2483 var st stepRecord
2484 if err := tx.Where("id = ?", id).First(&st).Error; errors.Is(err, gorm.ErrRecordNotFound) {
2485 return ErrNotFound
2486 } else if err != nil {
2487 return err
2488 }
2489 // Resolve the parent through the same read shape as GET /tasks/{id}.
2490 // Team visibility is intentional; an orphaned or unreadable task
2491 // must never leave its log independently readable.
2492 t := &txn{s: s, db: tx}
2493 k, err := t.loadTask(st.TaskID)
2494 if err != nil {
2495 return err
2496 }
2497 if _, err := t.taskView(k); err != nil {
2498 return err
2499 }
2500 // Checks keep their last 200 lines beside the SHA; other steps a tail.
2501 out = wire.StepLog{StepID: st.ID, Attempt: st.Attempt, Tail: firstSet(st.Output, st.LogTail)}
2502 return nil
2503 })
2504 return out, err
2505}
2506
2507// PostThread adds the person's note to a task's thread, once per key.
2508func (s *Store) PostThread(ctx context.Context, person, id string, in wire.PostThread) (out wire.ThreadEntry, err error) {
2509 text, ok := cleanText(in.Text, wire.MaxThreadText)
2510 if !ok || in.IdempotencyKey == "" || len(in.IdempotencyKey) > 128 || !utf8.ValidString(in.IdempotencyKey) {
2511 return out, ErrInvalid
2512 }
2513 err = s.tx(ctx, func(t *txn) error {
2514 if err := s.authority.CurrentPerson(ctx, t.db); err != nil {
2515 return err
2516 }
2517 k, err := t.loadTask(id)
2518 if err != nil {
2519 return err
2520 }
2521 key := "note:" + person + ":" + in.IdempotencyKey
2522 var prior entryRecord
2523 if err := t.db.Where("task_id = ? AND idempotency_key = ?", k.ID, key).First(&prior).Error; err == nil {
2524 if prior.Text != text {
2525 return ErrConflict
2526 }
2527 out = wire.ThreadEntry{ID: prior.ID, Author: prior.Author, Text: prior.Text, At: prior.CreatedAt}
2528 return nil
2529 } else if !errors.Is(err, gorm.ErrRecordNotFound) {
2530 return err
2531 }
2532 var n int64
2533 if err := t.db.Model(&entryRecord{}).Where("task_id = ? AND kind = ?", k.ID, entryNote).Count(&n).Error; err != nil {
2534 return err
2535 }
2536 if n >= wire.MaxThread {
2537 return ErrInvalid
2538 }
2539 e := entryRecord{ID: newID("e_"), TaskID: k.ID, IdempotencyKey: key, Kind: entryNote, Author: person, Text: text, CreatedAt: t.now()}
2540 if err := t.db.Create(&e).Error; err != nil {
2541 return err
2542 }
2543 out = wire.ThreadEntry{ID: e.ID, Author: e.Author, Text: e.Text, At: e.CreatedAt}
2544 if err := t.saveTask(&k); err != nil {
2545 return err
2546 }
2547 // A message in its thread from its creator is its person acting on
2548 // it: Design's attempts count from none, and one the limit held
2549 // goes now. Another member's message does neither.
2550 acted, err := t.personActed(k.ID, person)
2551 if err != nil || !acted {
2552 return err
2553 }
2554 return t.releaseDesignHeld(k.ID)
2555 })
2556 return out, err
2557}
2558
2559// taskTool runs the coordinator's task tools. A task the turn records or
2560// joins is followed by the turn's hand-off, if it has one.
2561func (t *txn) taskTool(r turnRecord, v *wire.ToolCall) (wire.ToolResult, error) {
2562 res, err := t.runTaskTool(r, v)
2563 if err != nil || res.IsError {
2564 return res, err
2565 }
2566 return res, t.followTask(r, v, res)
2567}
2568
2569func (t *txn) runTaskTool(r turnRecord, v *wire.ToolCall) (wire.ToolResult, error) {
2570 switch v.Name {
2571 case wire.ToolRecordTask:
2572 var in struct {
2573 Repo string `json:"repo"`
2574 Title string `json:"title"`
2575 Brief string `json:"brief"`
2576 Separate bool `json:"separate"`
2577 Kind string `json:"kind"`
2578 // The scheduler (protocol 14): low or normal, and a deadline,
2579 // from what the person said.
2580 Priority string `json:"priority"`
2581 By string `json:"by"`
2582 }
2583 if wire.Strict(v.Args, &in) != nil || in.Kind != "" && in.Kind != wire.KindChange && in.Kind != wire.KindExplore || in.Repo == "" || len(in.Repo) > 300 || strings.ContainsAny(in.Repo, "\x00\r\n") {
2584 return refused("invalid", toolBadInput), nil
2585 }
2586 priority, by, ok := toolPriority(in.Priority, in.By, t.now())
2587 if !ok {
2588 return refused("invalid", toolBadPriority), nil
2589 }
2590 title, ok := cleanText(in.Title, wire.MaxTaskTitle)
2591 if !ok || taskTitleBad.MatchString(title) {
2592 return refused("invalid", toolBadInput), nil
2593 }
2594 brief := strings.TrimSpace(in.Brief)
2595 if len(brief) > wire.MaxTaskBrief || !utf8.ValidString(brief) || strings.ContainsRune(brief, 0) {
2596 return refused("invalid", toolBadInput), nil
2597 }
2598 if r.Kind == wire.TurnSpecialistAdded {
2599 // Only in the card's project: never another, a new one, or
2600 // one this call would add.
2601 if res, err := t.boundProject(r, in.Repo); res != nil || err != nil {
2602 return deref(res), err
2603 }
2604 }
2605 res, err := t.recordTask(r, in.Repo, title, brief, in.Kind, in.Separate)
2606 if err != nil || res.Code != "recorded" {
2607 return res, err
2608 }
2609 var rec struct {
2610 Task string `json:"task"`
2611 }
2612 if r.Kind == wire.TurnSpecialistAdded {
2613 // Its one task, bound in this transaction: a record it cannot
2614 // bind is not made.
2615 if err := json.Unmarshal([]byte(res.Text), &rec); err != nil || rec.Task == "" {
2616 return wire.ToolResult{}, errors.Join(ErrConflict, err)
2617 }
2618 if err := t.bindTask(r, rec.Task); err != nil {
2619 return wire.ToolResult{}, err
2620 }
2621 }
2622 if json.Unmarshal([]byte(res.Text), &rec) == nil {
2623 k, err := t.loadTask(rec.Task)
2624 if err != nil {
2625 return res, err
2626 }
2627
2628 if err := t.coordinatorSetsPriority(&k, r, priority, by); err != nil {
2629 return res, err
2630 }
2631 }
2632 return res, nil
2633 case wire.ToolAddReport:
2634 return t.addReport(r, v.Args)
2635 case wire.ToolHoldMerge:
2636 return t.holdMerge(r, v.Args)
2637 case wire.ToolSetMergePolicy:
2638 return t.setMergePolicy(r, v.Args)
2639 case wire.ToolOfferRetry:
2640 return t.offerRetry(r, v.Args)
2641 case wire.ToolRetryStep:
2642 return t.retryStepTool(r, v.Args)
2643 case wire.ToolAddFinding:
2644 return t.addFinding(r, v.Args)
2645 case wire.ToolStartTask:
2646 var in struct {
2647 Task string `json:"task"`
2648 Brief string `json:"brief"`
2649 Priority string `json:"priority"`
2650 By string `json:"by"`
2651 // Specialist (protocol 38) is the maker's id, "" Engineering
2652 // (startMaker: a specialist_added turn's is the card's, any
2653 // other's is held to the routing rules).
2654 Specialist string `json:"specialist"`
2655 }
2656 if wire.Strict(v.Args, &in) != nil {
2657 return refused("invalid", toolBadInput), nil
2658 }
2659 maker, refusal, err := t.startMaker(r, strings.TrimSpace(in.Task), strings.TrimSpace(in.Specialist))
2660 if refusal != nil || err != nil {
2661 return deref(refusal), err
2662 }
2663 priority, by, ok := toolPriority(in.Priority, in.By, t.now())
2664 if !ok {
2665 return refused("invalid", toolBadPriority), nil
2666 }
2667 if priority != "" || by != nil {
2668 // Only on a task this turn recorded, nobody set before, and not
2669 // started yet: the coordinator sets them at creation, never
2670 // later (§6). A start that will be refused writes nothing.
2671 if k, err := t.loadTask(strings.TrimSpace(in.Task)); err == nil && k.Creator == r.Person && t.startable(k) {
2672 if err := t.coordinatorSetsPriority(&k, r, priority, by); err != nil {
2673 return wire.ToolResult{}, err
2674 }
2675 }
2676 }
2677 return t.startTask(r, in.Task, in.Brief, maker)
2678 case wire.ToolReadTask:
2679 var in struct {
2680 Task string `json:"task"`
2681 }
2682 if wire.Strict(v.Args, &in) != nil {
2683 return refused("invalid", toolBadInput), nil
2684 }
2685 return t.readTask(r.Person, in.Task)
2686 case wire.ToolCancelTask:
2687 var in struct {
2688 Task string `json:"task"`
2689 }
2690 if wire.Strict(v.Args, &in) != nil {
2691 return refused("invalid", toolBadInput), nil
2692 }
2693 _, err := t.cancelTask(r.Person, strings.TrimSpace(in.Task))
2694 switch {
2695 case errors.Is(err, ErrNotFound):
2696 return refused("not_found", toolNoTask), nil
2697 case errors.Is(err, ErrTaskEnded):
2698 return refused("task_ended", toolTaskEnded), nil
2699 case errors.Is(err, ErrMerging):
2700 return refused("merging", toolMerging), nil
2701 case errors.Is(err, ErrForbidden):
2702 return refused("not_yours", toolNotYours), nil
2703 case err != nil:
2704 return wire.ToolResult{}, err
2705 }
2706 return wire.ToolResult{Code: "cancelling", Text: toolCancelAsked}, nil
2707 }
2708 return refused("unknown_tool", toolUnknown), nil
2709}
2710
2711// makerProfiles caches specialists' profiles by id (txn.makers).
2712type makerProfiles map[string]string
2713
2714// maker is the data-defined specialist id names, with its profile (nil
2715// for "", or a specialist no longer on record).
2716func (t *txn) maker(id string) (*wire.Maker, error) {
2717 if id == "" {
2718 return nil, nil
2719 }
2720 if t.makers == nil {
2721 t.makers = makerProfiles{}
2722 }
2723 profile, ok := t.makers[id]
2724 if !ok {
2725 var sp specialistRecord
2726 if err := t.db.Select("id", "profile").Where("id = ?", id).Limit(1).Find(&sp).Error; err != nil {
2727 return nil, err
2728 }
2729 profile, t.makers[id] = sp.Profile, sp.Profile
2730 }
2731 if profile == "" {
2732 return nil, nil
2733 }
2734 return &wire.Maker{ID: id, Profile: profile}, nil
2735}
2736
2737// stepMaker is the data-defined specialist that makes step s: the one its
2738// binding names, or, for an Engineering-kind step not yet bound (before
2739// its dispatch), its task's maker.
2740func (t *txn) stepMaker(k taskRecord, s stepRecord) (*wire.Maker, error) {
2741 if s.SpecialistID != "" {
2742 return t.maker(s.SpecialistID)
2743 }
2744 if s.Specialist == wire.SpecialistEngineering {
2745 return t.maker(k.MakerSpecialistID)
2746 }
2747 return nil, nil
2748}
2749