| 1 | package chat |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "encoding/json" |
| 6 | "errors" |
| 7 | "slices" |
| 8 | "strings" |
| 9 | |
| 10 | "amadan.net/oficina/equipo/internal/wire" |
| 11 | "gorm.io/gorm" |
| 12 | ) |
| 13 | |
| 14 | // Exploration tasks (spec 2026-11-12-equipo-exploration-tasks.md): |
| 15 | // mockups, prototypes, design options and spikes. Engineering builds, |
| 16 | // Review approves (no checks), the release preview runs as for any |
| 17 | // approved candidate, and the creator chooses a direction on one card |
| 18 | // per candidate: build this one (a new change task from the default |
| 19 | // branch), try again (a round with their note) or drop it. Never a merge: |
| 20 | // advanceTask routes an exploration here before any merge handling, and |
| 21 | // merge authority says never to one first. |
| 22 | |
| 23 | // ErrTaskBusy: the task is not at rest (a step queued or running, a |
| 24 | // merge unfinished, merging), so its kind cannot change now. |
| 25 | var ErrTaskBusy = errors.New("chat: task busy") |
| 26 | |
| 27 | // BarberTask is staging's mockups task (paulca/threatmin), recorded as a |
| 28 | // change before explorations existed: switched once at start-up. |
| 29 | const BarberTask = "tk5fen4uajpn" |
| 30 | |
| 31 | // needsExplore is an exploration's NeedsYou: a stop as for any task, the |
| 32 | // fix rounds, or its direction once Review approved its candidate. Its |
| 33 | // merge steps (from before it was one) are never read. |
| 34 | func (p progress) needsExplore(k taskRecord) string { |
| 35 | w := p.work |
| 36 | if wire.FinalStage(k.Stage) || k.CancelRequested || w == nil { |
| 37 | return "" |
| 38 | } |
| 39 | if p.moved { |
| 40 | return wire.NeedsBranchMoved |
| 41 | } |
| 42 | switch { |
| 43 | case w.State == wire.StepFailed && w.Reason == "machine_removed" && !w.Terminated: |
| 44 | return wire.NeedsMachineRemoved |
| 45 | case w.Specialist == wire.SpecialistEngineering && w.State == wire.StepDone && w.Publication == wire.PublicationFailed: |
| 46 | return wire.NeedsRetry |
| 47 | case w.State == wire.StepFailed && w.Terminated && w.Specialist == wire.SpecialistReview: |
| 48 | return wire.NeedsReviewBlocked |
| 49 | case w.State == wire.StepFailed && w.Terminated: |
| 50 | return wire.NeedsRetry |
| 51 | case w.State == wire.StepQueued && w.Placement == wire.PlacementMac: |
| 52 | // Waiting for a Mac, as any task (needsYou). |
| 53 | return wire.NeedsMacRunner |
| 54 | case w.State == wire.StepQueued && w.Placement == wire.PlacementMacEngineering: |
| 55 | return wire.NeedsMacEngineering |
| 56 | case macEngineeringNeeds(w) != "": |
| 57 | return macEngineeringNeeds(w) |
| 58 | case w.State != wire.StepDone || p.candidate == "": |
| 59 | return "" |
| 60 | } |
| 61 | _, _, verdict, _ := p.judged() |
| 62 | switch { |
| 63 | case verdict == wire.VerdictApprove: |
| 64 | return wire.NeedsDirection |
| 65 | case verdict == wire.VerdictChanges && p.eng != nil && p.eng.Round >= wire.MaxFixRounds && p.candidate == p.eng.CandidateSHA: |
| 66 | return wire.NeedsFixRounds |
| 67 | } |
| 68 | return "" |
| 69 | } |
| 70 | |
| 71 | // advanceExplore takes an exploration one step further: Review on a new |
| 72 | // candidate (no checks), the fix rounds, and on approval its preview and |
| 73 | // the direction card. Idempotent, like advance. |
| 74 | func (t *txn) advanceExplore(k *taskRecord) error { |
| 75 | steps, err := t.steps(k.ID) |
| 76 | if err != nil { |
| 77 | return err |
| 78 | } |
| 79 | p := progressFor(*k, steps) |
| 80 | if k.MergeAsked != "" { |
| 81 | if err := t.withdrawMergeCards(*k); err != nil { |
| 82 | return err |
| 83 | } |
| 84 | } |
| 85 | if k.DirectionAsked != "" && (k.DirectionAsked != p.candidate || p.moved) { |
| 86 | // A new candidate, or the branch moved: the card asked about |
| 87 | // something else. |
| 88 | if err := t.withdrawDirection(*k); err != nil { |
| 89 | return err |
| 90 | } |
| 91 | k.DirectionAsked = "" |
| 92 | if err := t.saveTask(k); err != nil { |
| 93 | return err |
| 94 | } |
| 95 | } |
| 96 | if p.candidate != "" && k.Watching != p.candidate && p.eng != nil { |
| 97 | if err := t.watch(k, p.eng.Person, p.candidate); err != nil { |
| 98 | return err |
| 99 | } |
| 100 | } |
| 101 | if p.moved { |
| 102 | if k.Stage == wire.StageReadyToMerge { |
| 103 | k.Stage = wire.StageInReview |
| 104 | return t.saveTask(k) |
| 105 | } |
| 106 | return nil |
| 107 | } |
| 108 | w := p.work |
| 109 | if w == nil || w.State != wire.StepDone || p.candidate == "" || p.eng == nil || awaitingPublication(w) { |
| 110 | return nil |
| 111 | } |
| 112 | _, _, verdict, _ := p.judged() |
| 113 | switch { |
| 114 | case p.review == nil: |
| 115 | if handled, err := t.copyBeforeChecks(k, p, steps); handled || err != nil { |
| 116 | return err |
| 117 | } |
| 118 | return t.judge(k, p, wire.SpecialistReview) |
| 119 | case verdict == wire.VerdictChanges: |
| 120 | return t.fixRound(k, p, steps) |
| 121 | case verdict != wire.VerdictApprove: |
| 122 | return nil |
| 123 | } |
| 124 | if k.Stage != wire.StageInReview { |
| 125 | k.Stage = wire.StageInReview |
| 126 | if err := t.saveTask(k); err != nil { |
| 127 | return err |
| 128 | } |
| 129 | } |
| 130 | if err := t.schedulePreview(k); err != nil { |
| 131 | return err |
| 132 | } |
| 133 | return t.raiseDirection(k, p) |
| 134 | } |
| 135 | |
| 136 | // raiseDirection asks the creator which direction to take, once per |
| 137 | // candidate. |
| 138 | func (t *txn) raiseDirection(k *taskRecord, p progress) error { |
| 139 | if k.DirectionAsked == p.candidate { |
| 140 | return nil |
| 141 | } |
| 142 | if err := t.withdrawDirection(*k); err != nil { |
| 143 | return err |
| 144 | } |
| 145 | now := t.now() |
| 146 | question := t.words("chat.card.direction", mdLabel(k.Title)) |
| 147 | if question == "" { |
| 148 | question = k.Title |
| 149 | } |
| 150 | options, _ := json.Marshal([]string{wire.ChoiceBuild, wire.ChoiceAgain, wire.ChoiceDrop}) |
| 151 | c := cardRecord{ID: newID("c_"), Person: k.Creator, Kind: wire.CardDirection, State: wire.CardOpen, ProjectID: k.ProjectID, TaskID: k.ID, Question: question, Options: string(options), Revision: 1, CreatedAt: now, UpdatedAt: now, Lane: k.Lane} |
| 152 | if err := t.db.Create(&c).Error; err != nil { |
| 153 | return err |
| 154 | } |
| 155 | if err := t.cardEvent(c); err != nil { |
| 156 | return err |
| 157 | } |
| 158 | k.DirectionAsked = p.candidate |
| 159 | return t.saveTask(k) |
| 160 | } |
| 161 | |
| 162 | // withdrawDirection resolves a task's open direction cards. |
| 163 | func (t *txn) withdrawDirection(k taskRecord) error { |
| 164 | var open []cardRecord |
| 165 | if err := t.db.Where("task_id = ? AND kind = ? AND state = ?", k.ID, wire.CardDirection, wire.CardOpen).Find(&open).Error; err != nil { |
| 166 | return err |
| 167 | } |
| 168 | for i := range open { |
| 169 | open[i].State = wire.CardResolved |
| 170 | if err := t.saveCard(&open[i]); err != nil { |
| 171 | return err |
| 172 | } |
| 173 | } |
| 174 | return nil |
| 175 | } |
| 176 | |
| 177 | // busy reports whether a step of the task is not settled: queued or |
| 178 | // running, withdrawn, or ended without its termination proof (a removed |
| 179 | // runner's attempt may still be running). previews says whether preview |
| 180 | // steps count; a preview queued or running is ancillary to an answer, |
| 181 | // but an unproven one never is. |
| 182 | func busy(steps []stepRecord, previews bool) bool { |
| 183 | for _, s := range steps { |
| 184 | if s.Specialist == wire.SpecialistResearch || s.Specialist == wire.SpecialistPublish { |
| 185 | // Research never touches the branch: it is not at work on it; |
| 186 | // nor does a site publish, which runs after the merge. |
| 187 | continue |
| 188 | } |
| 189 | running := s.State == wire.StepQueued || s.State == wire.StepRunning |
| 190 | unproven := s.Withdrawn || (s.State == wire.StepFailed || s.State == wire.StepCancelled) && !s.Terminated |
| 191 | if unproven || running && (previews || s.Specialist != wire.SpecialistPreview) { |
| 192 | return true |
| 193 | } |
| 194 | } |
| 195 | return false |
| 196 | } |
| 197 | |
| 198 | // answerDirection is the creator's answer on a direction card, valid only |
| 199 | // while it still asks about the task as it stands: an exploration whose |
| 200 | // newest candidate is the one asked about, approved, the branch at it and |
| 201 | // nothing at work. Build this one, Try again (with a note) or Drop it. |
| 202 | func (t *txn) answerDirection(person string, c cardRecord, in wire.AnswerCard) (wire.Card, wire.Card, error) { |
| 203 | v, err := t.cardView(c) |
| 204 | if err != nil { |
| 205 | return wire.Card{}, wire.Card{}, err |
| 206 | } |
| 207 | if !slices.Contains([]string{wire.ChoiceBuild, wire.ChoiceAgain, wire.ChoiceDrop}, in.Choice) { |
| 208 | return wire.Card{}, wire.Card{}, ErrInvalid |
| 209 | } |
| 210 | note := "" |
| 211 | // Try again needs the person's note; Build this may carry one |
| 212 | // (protocol 38: the option they want), bounded the same way. |
| 213 | if in.Choice == wire.ChoiceAgain || in.Choice == wire.ChoiceBuild && in.Note != "" { |
| 214 | var ok bool |
| 215 | if note, ok = cleanText(in.Note, wire.MaxDirectionNote); !ok { |
| 216 | return wire.Card{}, wire.Card{}, ErrInvalid |
| 217 | } |
| 218 | } |
| 219 | if c.State != wire.CardOpen || c.Revision != in.Revision { |
| 220 | return wire.Card{}, v, ErrCardConflict |
| 221 | } |
| 222 | k, err := t.loadTask(c.TaskID) |
| 223 | if err != nil { |
| 224 | return wire.Card{}, wire.Card{}, err |
| 225 | } |
| 226 | if k.Creator != person || c.Person != person { |
| 227 | return wire.Card{}, wire.Card{}, ErrForbidden |
| 228 | } |
| 229 | if err := t.isOwner(person); err != nil { |
| 230 | return wire.Card{}, wire.Card{}, err |
| 231 | } |
| 232 | steps, err := t.steps(k.ID) |
| 233 | if err != nil { |
| 234 | return wire.Card{}, wire.Card{}, err |
| 235 | } |
| 236 | p := progressFor(k, steps) |
| 237 | _, _, verdict, _ := p.judged() |
| 238 | if wire.NormalKind(k.Kind) != wire.KindExplore || wire.FinalStage(k.Stage) || k.CancelRequested || p.moved || p.candidate == "" || k.DirectionAsked != p.candidate || verdict != wire.VerdictApprove || busy(steps, false) || k.BuiltAs != "" { |
| 239 | return wire.Card{}, v, ErrCardConflict |
| 240 | } |
| 241 | if in.Choice == wire.ChoiceBuild && note == "" { |
| 242 | // With more than one option, the person says which (spec §5). |
| 243 | d, err := t.candidateDesign(p) |
| 244 | if err != nil { |
| 245 | return wire.Card{}, wire.Card{}, err |
| 246 | } |
| 247 | if d != nil && len(d.Options) > 1 { |
| 248 | return wire.Card{}, v, ErrDirectionNote |
| 249 | } |
| 250 | } |
| 251 | c.State, c.Choice = wire.CardAnswered, in.Choice |
| 252 | if err := t.saveCard(&c); err != nil { |
| 253 | return wire.Card{}, wire.Card{}, err |
| 254 | } |
| 255 | switch in.Choice { |
| 256 | case wire.ChoiceBuild: |
| 257 | if err := t.buildThisOne(&k, p, note); err != nil { |
| 258 | return wire.Card{}, wire.Card{}, err |
| 259 | } |
| 260 | case wire.ChoiceAgain: |
| 261 | s := stepRecord{Specialist: wire.SpecialistEngineering, Person: p.eng.Person, Round: max(k.RepairRound, p.eng.Round) + 1, BaseSHA: p.candidate, Note: note} |
| 262 | // Asked afresh after the round, even about the same commit. |
| 263 | k.Stage, k.DirectionAsked = wire.StageInProgress, "" |
| 264 | if err := t.nextStep(&k, steps, s); err != nil { |
| 265 | return wire.Card{}, wire.Card{}, err |
| 266 | } |
| 267 | latest, err := t.steps(k.ID) |
| 268 | if err != nil { |
| 269 | return wire.Card{}, wire.Card{}, err |
| 270 | } |
| 271 | if err := t.db.Create(&cardThreadRecord{ID: newID("ct_"), CardID: c.ID, Person: person, StepID: latest[len(latest)-1].ID, Text: note, CreatedAt: t.now()}).Error; err != nil { |
| 272 | return wire.Card{}, wire.Card{}, err |
| 273 | } |
| 274 | case wire.ChoiceDrop: |
| 275 | if _, err := t.cancelTask(person, k.ID); err != nil { |
| 276 | return wire.Card{}, wire.Card{}, err |
| 277 | } |
| 278 | } |
| 279 | out, err := t.cardView(c) |
| 280 | return out, wire.Card{}, err |
| 281 | } |
| 282 | |
| 283 | // buildThisOne makes the change an exploration chose, in the answer's |
| 284 | // transaction: a new task of the creator in the same project, inserted |
| 285 | // directly (no similarity check, no housekeeping pass) in the |
| 286 | // exploration's lane, whose brief names the explored branch and commit to |
| 287 | // read for the design. It starts from |
| 288 | // the default branch like any task, and is started at once. The |
| 289 | // exploration is done, linked to it. A request that follows the |
| 290 | // exploration follows the new task too, before anything of it is |
| 291 | // dispatched or told: as work it made when it made the exploration |
| 292 | // (team_cancel stops it), else as work it joined. The person's note, when |
| 293 | // they gave one (which option, with more than one), ends the brief, |
| 294 | // quoted as their own words under their name; the exploration's brief is |
| 295 | // cut to make room, never the note. |
| 296 | func (t *txn) buildThisOne(k *taskRecord, p progress, note string) error { |
| 297 | now := t.now() |
| 298 | title := t.words("work.explore.build_title", k.Title) |
| 299 | if title == "" { |
| 300 | title = "Build: " + k.Title |
| 301 | } |
| 302 | title = clipText(strings.TrimSpace(title), wire.MaxTaskTitle) |
| 303 | more := t.words("work.explore.build_brief", k.Branch, short(p.candidate), TaskLink(k.ID)) |
| 304 | if more == "" { |
| 305 | more = "Build the direction explored on branch " + k.Branch + " at " + short(p.candidate) + " (" + TaskLink(k.ID) + ")." |
| 306 | } |
| 307 | if note != "" { |
| 308 | name, _ := DisplayName(k.Creator) |
| 309 | said := t.words("work.explore.build_note", name, wire.QuotedData(note)) |
| 310 | if said == "" { |
| 311 | said = name + "'s note on which option to build, in their own words: " + wire.QuotedData(note) |
| 312 | } |
| 313 | more += "\n\n" + said |
| 314 | } |
| 315 | if len(more) > wire.MaxTaskBrief-2 { |
| 316 | // Only a note escaped far past its own bound gets here. |
| 317 | return ErrInvalid |
| 318 | } |
| 319 | brief := strings.TrimSpace(clipText(strings.TrimSpace(k.Brief), wire.MaxTaskBrief-len(more)-2) + "\n\n" + more) |
| 320 | // The exploration's maker builds it too (dynamic specialists §1). |
| 321 | n := taskRecord{ID: newTaskID(), ProjectID: k.ProjectID, Title: title, Brief: brief, Stage: wire.StageNoted, Creator: k.Creator, Kind: wire.KindChange, ExploredFrom: k.ID, Revision: 1, CreatedAt: now, UpdatedAt: now, Lane: k.Lane, MakerSpecialistID: k.MakerSpecialistID} |
| 322 | n.Branch = wire.TaskBranch(n.ID, title) |
| 323 | if err := t.db.Create(&n).Error; err != nil { |
| 324 | return err |
| 325 | } |
| 326 | if err := t.db.Exec("INSERT INTO chat_handoff_tasks(handoff_id, task_id, created) SELECT handoff_id, ?, created FROM chat_handoff_tasks WHERE task_id = ? AND handoff_id IN (SELECT id FROM chat_handoffs WHERE state = ?) ON CONFLICT DO NOTHING", n.ID, k.ID, handoffOpen).Error; err != nil { |
| 327 | return err |
| 328 | } |
| 329 | c := cardRecord{ID: newID("c_"), Person: n.Creator, Kind: wire.CardTask, State: wire.StageNoted, ProjectID: n.ProjectID, TaskID: n.ID, Options: "[]", Revision: 1, CreatedAt: now, UpdatedAt: now, Lane: n.Lane} |
| 330 | if err := t.db.Create(&c).Error; err != nil { |
| 331 | return err |
| 332 | } |
| 333 | if err := t.cardEvent(c); err != nil { |
| 334 | return err |
| 335 | } |
| 336 | s := stepRecord{ID: newID("s_"), TaskID: n.ID, Idx: 1, Specialist: wire.SpecialistEngineering, Person: n.Creator, State: wire.StepQueued, Attempt: 1, Kind: wire.KindChange, CreatedAt: now, UpdatedAt: now} |
| 337 | if err := t.db.Create(&s).Error; err != nil { |
| 338 | return err |
| 339 | } |
| 340 | if err := t.dispatchStep(&n, &s); err != nil { |
| 341 | return err |
| 342 | } |
| 343 | n.Stage = wire.StageInProgress |
| 344 | if err := t.saveStep(&s, &n); err != nil { |
| 345 | return err |
| 346 | } |
| 347 | k.BuiltAs, k.Stage = n.ID, wire.StageDone |
| 348 | return t.saveTask(k) |
| 349 | } |
| 350 | |
| 351 | // switchKind turns a task at rest into kind: not ended, cancel-requested |
| 352 | // or merging, no step of it queued or running (previews included) and no |
| 353 | // merge step unfinished. One transaction: to an exploration its merge |
| 354 | // cards are withdrawn and the merge decisions cleared, Ready to merge |
| 355 | // going back to In review; to a change its direction cards are withdrawn. |
| 356 | // Either way the direction is asked afresh, a thread note says so, and |
| 357 | // the task advances. by is the person, or "equipo" (the start-up switch). |
| 358 | func (t *txn) switchKind(k *taskRecord, kind, by string) error { |
| 359 | if wire.FinalStage(k.Stage) || k.CancelRequested || k.Stage == wire.StageMerging { |
| 360 | return ErrTaskBusy |
| 361 | } |
| 362 | steps, err := t.steps(k.ID) |
| 363 | if err != nil { |
| 364 | return err |
| 365 | } |
| 366 | if busy(steps, true) { |
| 367 | return ErrTaskBusy |
| 368 | } |
| 369 | if wire.NormalKind(k.Kind) == kind { |
| 370 | return nil |
| 371 | } |
| 372 | if kind == wire.KindExplore { |
| 373 | if err := t.withdrawMergeCards(*k); err != nil { |
| 374 | return err |
| 375 | } |
| 376 | if err := t.db.Model(&taskRecord{}).Where("id = ?", k.ID).Updates(map[string]any{"merge_asked": "", "ready_sha": "", "merge_eligible": ""}).Error; err != nil { |
| 377 | return err |
| 378 | } |
| 379 | k.MergeAsked, k.ReadySHA, k.MergeEligible = "", "", "" |
| 380 | if k.Stage == wire.StageReadyToMerge { |
| 381 | k.Stage = wire.StageInReview |
| 382 | } |
| 383 | } else { |
| 384 | if err := t.withdrawDirection(*k); err != nil { |
| 385 | return err |
| 386 | } |
| 387 | } |
| 388 | k.Kind, k.DirectionAsked = kind, "" |
| 389 | text := t.words("work.kind.note_" + kind) |
| 390 | if text == "" { |
| 391 | text = "Now a " + kind + "." |
| 392 | } |
| 393 | if err := t.db.Create(&entryRecord{ID: newID("e_"), TaskID: k.ID, IdempotencyKey: newID("kind:"), Kind: entryNote, Author: by, Text: text, CreatedAt: t.now()}).Error; err != nil { |
| 394 | return err |
| 395 | } |
| 396 | if err := t.saveTask(k); err != nil { |
| 397 | return err |
| 398 | } |
| 399 | return t.advance(k) |
| 400 | } |
| 401 | |
| 402 | // SetKind is the creator's switch between a change and an exploration |
| 403 | // (POST /api/v1/tasks/{id}/kind), at the task's current revision. |
| 404 | func (s *Store) SetKind(ctx context.Context, person, id string, in wire.SetKind) (out wire.Task, err error) { |
| 405 | if in.Kind != wire.KindChange && in.Kind != wire.KindExplore { |
| 406 | return out, ErrInvalid |
| 407 | } |
| 408 | err = s.tx(ctx, func(t *txn) error { |
| 409 | if err := s.authority.CurrentPerson(ctx, t.db); err != nil { |
| 410 | return err |
| 411 | } |
| 412 | if err := t.isOwner(person); err != nil { |
| 413 | return err |
| 414 | } |
| 415 | k, err := t.loadTask(id) |
| 416 | if err != nil { |
| 417 | return err |
| 418 | } |
| 419 | if k.Creator != person { |
| 420 | return ErrForbidden |
| 421 | } |
| 422 | if in.Revision != k.Revision { |
| 423 | return ErrRevision |
| 424 | } |
| 425 | if err := t.switchKind(&k, in.Kind, person); err != nil { |
| 426 | return err |
| 427 | } |
| 428 | fresh, err := t.loadTask(id) |
| 429 | if err != nil { |
| 430 | return err |
| 431 | } |
| 432 | out, err = t.taskView(fresh) |
| 433 | return err |
| 434 | }) |
| 435 | return out, err |
| 436 | } |
| 437 | |
| 438 | // ExploreOnce switches a task recorded as a change to an exploration, |
| 439 | // once ever (spec §4): a trusted start-up entry with no person. The |
| 440 | // ledger row (kind_switch, explore:<task>) is written with the switch, or |
| 441 | // alone when the task is missing, ended or merged; a task merging or at |
| 442 | // work writes nothing, so a later start looks again. Paul switching it |
| 443 | // back later is never undone. |
| 444 | func (s *Store) ExploreOnce(ctx context.Context, id string) (switched bool, err error) { |
| 445 | err = s.tx(ctx, func(t *txn) error { |
| 446 | team, err := t.team() |
| 447 | if err != nil { |
| 448 | return err |
| 449 | } |
| 450 | r, found, err := t.hkLoad(team, "", "kind_switch", "explore:"+id) |
| 451 | if err != nil || found { |
| 452 | return err |
| 453 | } |
| 454 | now := t.hkNow() |
| 455 | r = hkRecord{ID: newID("hk_"), Team: team, Detector: "kind_switch", FindingKey: "explore:" + id, SubjectKind: "task", SubjectID: id, Class: "kind", ClaimedAt: &now} |
| 456 | k, err := t.loadTask(id) |
| 457 | switch { |
| 458 | case errors.Is(err, ErrNotFound): |
| 459 | r.State, r.Reason = wire.ActionExpired, "missing" |
| 460 | return t.hkSave(&r, true) |
| 461 | case err != nil: |
| 462 | return err |
| 463 | case wire.FinalStage(k.Stage) || k.MergedSHA != "": |
| 464 | r.State, r.Reason = wire.ActionExpired, "ended" |
| 465 | return t.hkSave(&r, true) |
| 466 | } |
| 467 | switch err := t.switchKind(&k, wire.KindExplore, "equipo"); { |
| 468 | case errors.Is(err, ErrTaskBusy): |
| 469 | return nil |
| 470 | case err != nil: |
| 471 | return err |
| 472 | } |
| 473 | r.State, r.SubjectRevision, switched = wire.ActionDone, k.Revision, true |
| 474 | return t.hkSave(&r, true) |
| 475 | }) |
| 476 | return switched, err |
| 477 | } |
| 478 | |
| 479 | // directionView is what the direction card and the task page show: the |
| 480 | // candidate's deployed preview, else its branch on Amadan, and whether |
| 481 | // the primary (at protocol 10) says previews are off; and what the newest |
| 482 | // Design attempt kept, by option, with whether Build this needs a note. |
| 483 | func (t *txn) directionView(k taskRecord, repo string, steps []stepRecord, p progress) (*wire.TaskDirection, error) { |
| 484 | d := &wire.TaskDirection{BranchURL: BranchURL(repo, k.Branch)} |
| 485 | design, err := t.candidateDesign(p) |
| 486 | if err != nil { |
| 487 | return nil, err |
| 488 | } |
| 489 | if design != nil { |
| 490 | d.Options, d.NoteNeeded = design.Options, len(design.Options) > 1 |
| 491 | } |
| 492 | now := t.now() |
| 493 | for i := len(steps) - 1; i >= 0; i-- { |
| 494 | s := steps[i] |
| 495 | if s.Specialist != wire.SpecialistPreview || s.CandidateSHA != p.candidate || s.State != wire.StepDone { |
| 496 | continue |
| 497 | } |
| 498 | if r := decodePreview(s.Preview); r != nil && r.Outcome == wire.PreviewDeployed && r.URL != "" && (r.ExpiresAt == nil || r.ExpiresAt.After(now)) { |
| 499 | d.PreviewURL = r.URL |
| 500 | return d, nil |
| 501 | } |
| 502 | } |
| 503 | off, err := t.previewsOff(k.Creator) |
| 504 | d.PreviewsOff = off |
| 505 | return d, err |
| 506 | } |
| 507 | |
| 508 | // previewsOff: the person's primary speaks wire.ProtocolExplore and says |
| 509 | // it has no preview credential. Below it nothing is known. |
| 510 | func (t *txn) previewsOff(person string) (bool, error) { |
| 511 | primary, err := t.s.authority.PrimaryRunner(t.db, person) |
| 512 | if err != nil || primary == "" { |
| 513 | return false, err |
| 514 | } |
| 515 | rs, err := t.runners(person) |
| 516 | if err != nil { |
| 517 | return false, err |
| 518 | } |
| 519 | for _, r := range rs { |
| 520 | if r.ID == primary { |
| 521 | return r.Protocol >= wire.ProtocolExplore && (r.Hello.Capabilities == nil || !r.Hello.Capabilities.Previews), nil |
| 522 | } |
| 523 | } |
| 524 | return false, nil |
| 525 | } |
| 526 | |
| 527 | // taskRef names a linked task, nil when none or gone. |
| 528 | func (t *txn) taskRef(id string) (*wire.TaskRef, error) { |
| 529 | if id == "" { |
| 530 | return nil, nil |
| 531 | } |
| 532 | var d taskRecord |
| 533 | err := t.db.Select("id", "title", "stage", "creator").Where("id = ?", id).First(&d).Error |
| 534 | if errors.Is(err, gorm.ErrRecordNotFound) { |
| 535 | return nil, nil |
| 536 | } |
| 537 | if err != nil { |
| 538 | return nil, err |
| 539 | } |
| 540 | return &wire.TaskRef{ID: d.ID, Title: d.Title, Stage: d.Stage, Creator: d.Creator}, nil |
| 541 | } |
| 542 | |
| 543 | // helloPreviews reads a stored hello's previews capability. |
| 544 | func helloPreviews(raw string) bool { |
| 545 | var h struct { |
| 546 | Capabilities *struct { |
| 547 | Previews bool `json:"previews"` |
| 548 | } `json:"capabilities"` |
| 549 | } |
| 550 | return raw != "" && json.Unmarshal([]byte(raw), &h) == nil && h.Capabilities != nil && h.Capabilities.Previews |
| 551 | } |
| 552 | |
| 553 | // reschedulePreviews gives each of the person's open approved candidates |
| 554 | // its preview, once the primary says previews are on (schedulePreview is |
| 555 | // once per candidate). |
| 556 | func (t *txn) reschedulePreviews(person string) error { |
| 557 | var open []taskRecord |
| 558 | if err := t.db.Where("creator = ? AND stage NOT IN ? AND (cancel_requested IS NULL OR cancel_requested = ?)", person, []string{wire.StageDone, wire.StageCancelled}, false).Order("created_at, id").Find(&open).Error; err != nil { |
| 559 | return err |
| 560 | } |
| 561 | for i := range open { |
| 562 | if err := t.schedulePreview(&open[i]); err != nil { |
| 563 | return err |
| 564 | } |
| 565 | } |
| 566 | return nil |
| 567 | } |
| 568 | |