| 1 | package chat |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "encoding/json" |
| 6 | "errors" |
| 7 | "fmt" |
| 8 | "slices" |
| 9 | "strings" |
| 10 | |
| 11 | "amadan.net/oficina/equipo/internal/equipo/housekeeping" |
| 12 | "amadan.net/oficina/equipo/internal/equipo/mergegate" |
| 13 | "amadan.net/oficina/equipo/internal/wire" |
| 14 | "gorm.io/gorm" |
| 15 | ) |
| 16 | |
| 17 | // The coordinator's side merges (Paul, 2026-11-07, overruling "Equipo |
| 18 | // never merges"): a deterministic instance policy, not a model's choice. |
| 19 | // A task whose checks passed and whose review approved, both on the task |
| 20 | // branch's current head, is merged by its person's runner at once |
| 21 | // (stage merging, then done with the commit). Checks that could not run |
| 22 | // (or none found) are not a pass: the creator is asked once, with a |
| 23 | // quiet card, whether to merge without them. A merge that conflicts with |
| 24 | // the default branch sends Engineering one rebase round, whose new |
| 25 | // candidate is checked and reviewed afresh; only a judged SHA is ever |
| 26 | // merged, and the runner checks the head again right before. |
| 27 | |
| 28 | // merging reports whether s is a merge of the judged candidate the |
| 29 | // policy allows: approved, and checks passed or the person chose to |
| 30 | // merge without them. |
| 31 | func (p progress) mergeAllowed(withoutChecks bool) bool { |
| 32 | checks, _, verdict, _ := p.judged() |
| 33 | if p.moved || p.candidate == "" || verdict != wire.VerdictApprove { |
| 34 | return false |
| 35 | } |
| 36 | return checks == wire.ChecksPassed || withoutChecks && (checks == wire.ChecksCannotRun || checks == wire.ChecksNone) |
| 37 | } |
| 38 | |
| 39 | // checksOutsideSandbox: the judged checks ran on a worker outside the |
| 40 | // sandbox (Paul's ruling 2). Until the slice 4c rule for them exists |
| 41 | // (passed only for repositories the creator owns, spec §4.3), Equipo |
| 42 | // never merges those on its own: the creator is asked, "Merge <title>?". |
| 43 | func (p progress) checksOutsideSandbox() bool { |
| 44 | // Hosted CI's verdict counts as checks that ran, but the hub cannot |
| 45 | // yet say where it ran (release slice 1), so it is never sandboxed. |
| 46 | return p.checks != nil && (p.checks.ChecksSandbox == wire.SandboxNone || p.checks.ChecksSandbox == wire.SandboxHosted) |
| 47 | } |
| 48 | |
| 49 | // startMerge dispatches the merge step for the judged candidate, decided |
| 50 | // by decidedBy ("policy" or "person:<address>"). Only authorizeMerge's act |
| 51 | // leads here (autoMerge, the card's Merge, MergeTask, Retry). |
| 52 | func (t *txn) startMerge(k *taskRecord, p progress, steps []stepRecord, withoutChecks bool, decidedBy string) error { |
| 53 | // Housekeeping never merges. |
| 54 | if err := t.hkForbid("merge"); err != nil { |
| 55 | return err |
| 56 | } |
| 57 | if p.eng == nil || p.candidate == "" || p.moved || wire.NormalKind(k.Kind) == wire.KindExplore { |
| 58 | return ErrNotMergeable |
| 59 | } |
| 60 | s := stepRecord{Specialist: wire.SpecialistMerge, Person: p.eng.Person, Round: p.eng.Round, BaseSHA: k.BaseSHA, CandidateSHA: p.candidate, WithoutChecks: withoutChecks, DecidedBy: decidedBy} |
| 61 | k.Stage = wire.StageMerging |
| 62 | return t.nextStep(k, steps, s) |
| 63 | } |
| 64 | |
| 65 | // personMerge is a person's Merge of the judged candidate (card, task |
| 66 | // page): decided through authorizeMerge, then a new merge step, or the |
| 67 | // failed, ended one attempted again. |
| 68 | func (t *txn) personMerge(k *taskRecord, p progress, steps []stepRecord, person string) error { |
| 69 | online, protocol, err := t.primaryState(p.eng.Person) |
| 70 | if err != nil { |
| 71 | return err |
| 72 | } |
| 73 | if !online { |
| 74 | protocol = 0 |
| 75 | } |
| 76 | d, err := t.authorizeMerge(k, p, atDispatch, person, protocol) |
| 77 | if err != nil { |
| 78 | return err |
| 79 | } |
| 80 | if d.Class != mergegate.ClassAct || d.DecidedBy != mergegate.DecidedPerson { |
| 81 | return ErrNotMergeable |
| 82 | } |
| 83 | checks, _, _, _ := p.judged() |
| 84 | if checks == wire.ChecksPassed { |
| 85 | k.MergeEligible = p.candidate |
| 86 | } |
| 87 | if m := p.merge; m != nil { |
| 88 | if m.State != wire.StepFailed || !m.Terminated { |
| 89 | return ErrNotMergeable |
| 90 | } |
| 91 | return t.retryMerge(k, m, decidedPerson+person, checks != wire.ChecksPassed) |
| 92 | } |
| 93 | return t.startMerge(k, p, steps, checks != wire.ChecksPassed, decidedPerson+person) |
| 94 | } |
| 95 | |
| 96 | // retryMerge runs a failed, ended merge step again as its next attempt. |
| 97 | func (t *txn) retryMerge(k *taskRecord, st *stepRecord, decidedBy string, withoutChecks bool) error { |
| 98 | if err := t.hkForbid("merge"); err != nil { |
| 99 | return err |
| 100 | } |
| 101 | st.Attempt++ |
| 102 | st.State, st.Reason, st.Terminated, st.Summary, st.LogTail, st.StartedAt, st.FinishedAt, st.Headline, st.Activity = wire.StepQueued, "", false, "", "", nil, nil, "", "" |
| 103 | st.MergeSHA, st.MergeInto, st.MergeStrategy, st.MergeSource, st.MergeParents = "", "", "", "", "" |
| 104 | st.Withdrawn, st.RefusedBy, st.DecidedBy, st.WithoutChecks = false, "", decidedBy, withoutChecks |
| 105 | k.Stage = wire.StageMerging |
| 106 | if err := t.dispatchStep(k, st); err != nil { |
| 107 | return err |
| 108 | } |
| 109 | return t.saveStep(st, k) |
| 110 | } |
| 111 | |
| 112 | // answerMerge is the creator's answer on a merge card: Merge merges the |
| 113 | // SHA the card asked about, labelled without checks; Wait leaves the task |
| 114 | // at Ready to merge. A card whose SHA is no longer the task's judged one |
| 115 | // answers nothing. |
| 116 | func (t *txn) answerMerge(person string, c cardRecord, in wire.AnswerCard) (wire.Card, wire.Card, error) { |
| 117 | if err := t.hkForbid("merge"); err != nil { |
| 118 | return wire.Card{}, wire.Card{}, err |
| 119 | } |
| 120 | v, err := t.cardView(c) |
| 121 | if err != nil { |
| 122 | return wire.Card{}, wire.Card{}, err |
| 123 | } |
| 124 | var options []string |
| 125 | _ = json.Unmarshal([]byte(c.Options), &options) |
| 126 | if !slices.Contains(options, in.Choice) { |
| 127 | return wire.Card{}, wire.Card{}, ErrInvalid |
| 128 | } |
| 129 | if c.State != wire.CardOpen || c.Revision != in.Revision { |
| 130 | return wire.Card{}, v, ErrCardConflict |
| 131 | } |
| 132 | k, err := t.loadTask(c.TaskID) |
| 133 | if err != nil { |
| 134 | return wire.Card{}, wire.Card{}, err |
| 135 | } |
| 136 | // Only the task's creator answers: the card sits in their conversation |
| 137 | // and the task is theirs. |
| 138 | if k.Creator != person || c.Person != person { |
| 139 | return wire.Card{}, wire.Card{}, ErrForbidden |
| 140 | } |
| 141 | if in.Choice == wire.ChoiceMerge { |
| 142 | if err := t.requireGoLive(person, k.ID); err != nil { |
| 143 | return wire.Card{}, wire.Card{}, err |
| 144 | } |
| 145 | } |
| 146 | if err := t.isOwner(person); err != nil { |
| 147 | return wire.Card{}, wire.Card{}, err |
| 148 | } |
| 149 | steps, err := t.steps(k.ID) |
| 150 | if err != nil { |
| 151 | return wire.Card{}, wire.Card{}, err |
| 152 | } |
| 153 | p := progressFor(k, steps) |
| 154 | if wire.FinalStage(k.Stage) || k.CancelRequested || k.Stage != wire.StageReadyToMerge || p.candidate != k.MergeAsked || !mergeRetryable(p.merge) || !p.mergeAllowed(true) { |
| 155 | // Not now: the branch is away from the SHA (the card stays for when |
| 156 | // it is back), or the task moved on (withdrawMergeCards resolves |
| 157 | // the card for a new candidate or an end). |
| 158 | return wire.Card{}, v, ErrCardConflict |
| 159 | } |
| 160 | c.State, c.Choice = wire.CardAnswered, in.Choice |
| 161 | if err := t.saveCard(&c); err != nil { |
| 162 | return wire.Card{}, wire.Card{}, err |
| 163 | } |
| 164 | if in.Choice == wire.ChoiceMerge { |
| 165 | if err := t.personMerge(&k, p, steps, person); errors.Is(err, ErrNotMergeable) { |
| 166 | return wire.Card{}, v, ErrCardConflict |
| 167 | } else if err != nil { |
| 168 | return wire.Card{}, wire.Card{}, err |
| 169 | } |
| 170 | } |
| 171 | out, err := t.cardView(c) |
| 172 | return out, wire.Card{}, err |
| 173 | } |
| 174 | |
| 175 | // touchMergeCards gives a task's open merge cards a new revision: the |
| 176 | // branch moved, so an answer given before it did is refused as stale. |
| 177 | func (t *txn) touchMergeCards(k taskRecord) error { |
| 178 | var open []cardRecord |
| 179 | if err := t.db.Where("task_id = ? AND kind = ? AND state = ?", k.ID, wire.CardMerge, wire.CardOpen).Find(&open).Error; err != nil { |
| 180 | return err |
| 181 | } |
| 182 | for i := range open { |
| 183 | if err := t.saveCard(&open[i]); err != nil { |
| 184 | return err |
| 185 | } |
| 186 | } |
| 187 | return nil |
| 188 | } |
| 189 | |
| 190 | // withdrawMergeCards resolves a task's open merge cards: the SHA they |
| 191 | // asked about is no longer the one to merge, or the task ended. |
| 192 | func (t *txn) withdrawMergeCards(k taskRecord) error { |
| 193 | var open []cardRecord |
| 194 | if err := t.db.Where("task_id = ? AND kind = ? AND state = ?", k.ID, wire.CardMerge, wire.CardOpen).Find(&open).Error; err != nil { |
| 195 | return err |
| 196 | } |
| 197 | for i := range open { |
| 198 | open[i].State = wire.CardResolved |
| 199 | if err := t.saveCard(&open[i]); err != nil { |
| 200 | return err |
| 201 | } |
| 202 | } |
| 203 | return nil |
| 204 | } |
| 205 | |
| 206 | // mergeDone applies the runner's confirmed merge: the task is done, with |
| 207 | // the commit on the default branch and how it was merged, and the |
| 208 | // coordinator says so in the creator's conversation, at the outcome level. |
| 209 | func (t *txn) mergeDone(k *taskRecord, s *stepRecord, v *wire.StepReport) error { |
| 210 | now := t.now() |
| 211 | s.MergeSHA, s.MergeInto, s.MergeStrategy = v.MergeSHA, v.Into, v.Strategy |
| 212 | k.Stage = wire.StageDone |
| 213 | k.MergedSHA, k.MergedInto, k.MergeStrategy, k.MergedWithoutChecks, k.MergedAt = v.MergeSHA, v.Into, v.Strategy, s.WithoutChecks, &now |
| 214 | var pr projectRecord |
| 215 | if err := t.db.Where("id = ?", k.ProjectID).First(&pr).Error; err != nil { |
| 216 | return err |
| 217 | } |
| 218 | project := pr.shownTitle() |
| 219 | k.MergeVerified = mergeVerified(v, s.CandidateSHA) |
| 220 | parents, _ := json.Marshal(v.MergeParents) |
| 221 | s.MergeSource, s.MergeParents = v.MergeSource, string(parents) |
| 222 | audit := auditMerged |
| 223 | if mergeByPolicy(*s) && s.WithoutChecks && !k.MergeVerified { |
| 224 | audit = auditUnverified |
| 225 | } |
| 226 | if err := t.auditRow(mergeAuditRecord{ProjectID: k.ProjectID, TaskID: k.ID, Kind: audit, At: "hub", CandidateSHA: s.CandidateSHA, MergeSHA: v.MergeSHA, DecidedBy: s.DecidedBy, Inputs: fmt.Sprintf(`{"source":%q,"parents":%s,"without_checks":%t}`, v.MergeSource, parents, s.WithoutChecks)}); err != nil { |
| 227 | return err |
| 228 | } |
| 229 | if mergeByPolicy(*s) && s.WithoutChecks { |
| 230 | // Equipo's own merge without checks: a receipt, with Undo when the |
| 231 | // hub named the merge commit. |
| 232 | if _, err := t.mergeReceipt(k, project, s, k.MergeVerified); err != nil { |
| 233 | return err |
| 234 | } |
| 235 | return t.offerPublish(k, s) |
| 236 | } |
| 237 | key := "merged_without_checks" |
| 238 | if !s.WithoutChecks { |
| 239 | key = "merged" |
| 240 | } |
| 241 | if err := t.mergedLine(k, key, project); err != nil { |
| 242 | return err |
| 243 | } |
| 244 | // A merged website: its creator is asked, separately, whether to |
| 245 | // publish it. |
| 246 | return t.offerPublish(k, s) |
| 247 | } |
| 248 | |
| 249 | // mergedLine says the merge in the creator's conversation, once. |
| 250 | func (t *txn) mergedLine(k *taskRecord, key, project string) error { |
| 251 | text := t.words("chat."+key, mdLabel(k.Title), TaskLink(k.ID), project) |
| 252 | if text == "" { |
| 253 | return nil |
| 254 | } |
| 255 | var n int64 |
| 256 | if err := t.db.Model(&messageRecord{}).Where("person = ? AND idempotency_key = ?", k.Creator, "merged:"+k.ID).Count(&n).Error; err != nil || n > 0 { |
| 257 | return err |
| 258 | } |
| 259 | m := messageRecord{ID: newID("m_"), Person: k.Creator, IdempotencyKey: "merged:" + k.ID, Role: wire.RoleCoordinator, Text: text, Revision: 1, CreatedAt: t.now()} |
| 260 | if err := t.db.Create(&m).Error; err != nil { |
| 261 | return err |
| 262 | } |
| 263 | return t.messageEvent(m) |
| 264 | } |
| 265 | |
| 266 | // mdLabel keeps a title from breaking out of a markdown link's label. |
| 267 | func mdLabel(s string) string { |
| 268 | return strings.NewReplacer("[", "(", "]", ")", "\n", " ", "\r", " ").Replace(s) |
| 269 | } |
| 270 | |
| 271 | // words is the instance's copy for key, formatted with args; "" when the |
| 272 | // store has no copy. |
| 273 | func (t *txn) words(key string, args ...any) string { |
| 274 | if t.s.authority.Copy == nil { |
| 275 | return "" |
| 276 | } |
| 277 | text := t.s.authority.Copy(key) |
| 278 | if text == "" { |
| 279 | return "" |
| 280 | } |
| 281 | if len(args) > 0 { |
| 282 | return fmt.Sprintf(text, args...) |
| 283 | } |
| 284 | return text |
| 285 | } |
| 286 | |
| 287 | // mergeFailed handles a merge the hub refused: a conflict sends |
| 288 | // Engineering one rebase round; anything else leaves the task at Ready to |
| 289 | // merge with the reason and Retry. |
| 290 | func (t *txn) mergeFailed(k *taskRecord, p progress, steps []stepRecord) error { |
| 291 | if p.last.Reason == "merge_conflict" && rebaseRounds(steps) < wire.MaxRebaseRounds && p.eng != nil { |
| 292 | s := stepRecord{Specialist: wire.SpecialistEngineering, Person: p.eng.Person, Round: p.eng.Round, Rebase: true, FromBase: k.BaseSHA, FromCandidate: p.candidate} |
| 293 | k.Stage = wire.StageInProgress |
| 294 | return t.nextStep(k, steps, s) |
| 295 | } |
| 296 | // The SHA is still the judged one (the branch is back at it, or the |
| 297 | // hub refused for another reason): Ready to merge, with the reason |
| 298 | // and Retry. |
| 299 | if k.Stage != wire.StageReadyToMerge && p.merge != nil && p.mergeAllowed(p.merge.WithoutChecks) { |
| 300 | k.Stage = wire.StageReadyToMerge |
| 301 | return t.saveTask(k) |
| 302 | } |
| 303 | return nil |
| 304 | } |
| 305 | |
| 306 | func rebaseRounds(steps []stepRecord) int { |
| 307 | n := 0 |
| 308 | for _, s := range steps { |
| 309 | if s.Rebase { |
| 310 | n++ |
| 311 | } |
| 312 | } |
| 313 | return n |
| 314 | } |
| 315 | |
| 316 | // Duplicates: Paul's coordinator filed one bug three times. record_task |
| 317 | // first looks for open tasks in the same project that read like the same |
| 318 | // problem (a cheap word overlap of titles and briefs) and returns them |
| 319 | // instead of recording; the coordinator adds the new report to one of |
| 320 | // them with add_report, or records anyway (separate) when it is |
| 321 | // different. |
| 322 | |
| 323 | // significant and overlap are record_task's similarity, shared with the |
| 324 | // housekeeping detectors. |
| 325 | var ( |
| 326 | significant = housekeeping.Significant |
| 327 | overlap = housekeeping.Overlap |
| 328 | ) |
| 329 | |
| 330 | // similarTasks are the open tasks of project that read like title and |
| 331 | // brief, best first. |
| 332 | func (t *txn) similarTasks(person, projectID, title, brief, kind string) ([]taskRecord, error) { |
| 333 | var open []taskRecord |
| 334 | if err := t.db.Where("project_id = ? AND stage NOT IN ? AND cancel_requested = ?", projectID, []string{wire.StageDone, wire.StageCancelled}, false).Order("created_at DESC").Limit(200).Find(&open).Error; err != nil { |
| 335 | return nil, err |
| 336 | } |
| 337 | nt, nb := significant(title), significant(title+" "+brief) |
| 338 | type scored struct { |
| 339 | k taskRecord |
| 340 | score float64 |
| 341 | } |
| 342 | var hits []scored |
| 343 | hidden := t.s.authority.TestPerson |
| 344 | for _, k := range open { |
| 345 | // A test person's work never meets anyone else's, and an |
| 346 | // exploration never meets a change. |
| 347 | if k.Creator != person && hidden != nil && (hidden(k.Creator) || hidden(person)) || wire.NormalKind(k.Kind) != wire.NormalKind(kind) { |
| 348 | continue |
| 349 | } |
| 350 | ts, tn := overlap(nt, significant(k.Title)) |
| 351 | bs, bn := overlap(nb, significant(k.Title+" "+k.Brief)) |
| 352 | score := max(ts, bs*0.9) |
| 353 | if ts >= 0.6 && tn >= 2 || bs >= 0.5 && bn >= 3 { |
| 354 | hits = append(hits, scored{k, score}) |
| 355 | } |
| 356 | } |
| 357 | slices.SortStableFunc(hits, func(a, b scored) int { |
| 358 | switch { |
| 359 | case a.score > b.score: |
| 360 | return -1 |
| 361 | case a.score < b.score: |
| 362 | return 1 |
| 363 | } |
| 364 | return 0 |
| 365 | }) |
| 366 | out := []taskRecord{} |
| 367 | for _, h := range hits[:min(len(hits), wire.MaxSimilarTasks)] { |
| 368 | out = append(out, h.k) |
| 369 | } |
| 370 | return out, nil |
| 371 | } |
| 372 | |
| 373 | // addReport attaches the person's new report to an open team task, as a |
| 374 | // report on its thread, and shows the task in this turn. |
| 375 | func (t *txn) addReport(r turnRecord, args json.RawMessage) (wire.ToolResult, error) { |
| 376 | var in struct { |
| 377 | Task string `json:"task"` |
| 378 | Text string `json:"text"` |
| 379 | } |
| 380 | if wire.Strict(args, &in) != nil { |
| 381 | return refused("invalid", toolBadInput), nil |
| 382 | } |
| 383 | text, ok := cleanText(in.Text, wire.MaxThreadText) |
| 384 | if !ok { |
| 385 | return refused("invalid", toolBadInput), nil |
| 386 | } |
| 387 | k, err := t.loadTask(strings.TrimSpace(in.Task)) |
| 388 | if errors.Is(err, ErrNotFound) { |
| 389 | return refused("not_found", toolNoTask), nil |
| 390 | } |
| 391 | if err != nil { |
| 392 | return wire.ToolResult{}, err |
| 393 | } |
| 394 | if wire.FinalStage(k.Stage) || k.CancelRequested { |
| 395 | return refused("task_ended", toolTaskEndedReport), nil |
| 396 | } |
| 397 | var n int64 |
| 398 | if err := t.db.Model(&entryRecord{}).Where("task_id = ? AND kind <> ?", k.ID, entryFinding).Count(&n).Error; err != nil { |
| 399 | return wire.ToolResult{}, err |
| 400 | } |
| 401 | if n >= wire.MaxThread { |
| 402 | return refused("too_many", toolBadInput), nil |
| 403 | } |
| 404 | now := t.now() |
| 405 | key := "report:" + r.ID + ":" + newID("") |
| 406 | if err := t.db.Create(&entryRecord{ID: newID("e_"), TaskID: k.ID, IdempotencyKey: key, Kind: entryReport, Author: r.Person, Text: text, CreatedAt: now}).Error; err != nil { |
| 407 | return wire.ToolResult{}, err |
| 408 | } |
| 409 | if err := t.saveTask(&k); err != nil { |
| 410 | return wire.ToolResult{}, err |
| 411 | } |
| 412 | // The person sees the task this report joined, in this turn (its lane: |
| 413 | // the task keeps its own). |
| 414 | c := cardRecord{ID: newID("c_"), Person: r.Person, Kind: wire.CardTask, State: k.Stage, TurnID: r.ID, ProjectID: k.ProjectID, TaskID: k.ID, Options: "[]", Revision: 1, CreatedAt: now, UpdatedAt: now, Lane: r.Lane} |
| 415 | if err := t.db.Create(&c).Error; err != nil { |
| 416 | return wire.ToolResult{}, err |
| 417 | } |
| 418 | if err := t.cardEvent(c); err != nil { |
| 419 | return wire.ToolResult{}, err |
| 420 | } |
| 421 | raw, _ := json.Marshal(map[string]string{"task": k.ID, "title": k.Title, "link": TaskLink(k.ID), "stage": k.Stage, "note": toolReportAdded}) |
| 422 | return wire.ToolResult{Code: "reported", Text: string(raw)}, nil |
| 423 | } |
| 424 | |
| 425 | // similarResult is record_task's answer when open tasks read like the |
| 426 | // new report: nothing is recorded. |
| 427 | func similarResult(similar []taskRecord) wire.ToolResult { |
| 428 | type hit struct { |
| 429 | Task string `json:"task"` |
| 430 | Title string `json:"title"` |
| 431 | Link string `json:"link"` |
| 432 | Stage string `json:"stage"` |
| 433 | } |
| 434 | out := struct { |
| 435 | Similar []hit `json:"similar"` |
| 436 | Note string `json:"note"` |
| 437 | }{Similar: []hit{}, Note: toolSimilar} |
| 438 | for _, k := range similar { |
| 439 | out.Similar = append(out.Similar, hit{k.ID, k.Title, TaskLink(k.ID), k.Stage}) |
| 440 | } |
| 441 | raw, _ := json.Marshal(out) |
| 442 | return wire.ToolResult{Code: "similar", Text: string(raw)} |
| 443 | } |
| 444 | |
| 445 | // mergedView is a task's merge as the API shows it, nil until Equipo |
| 446 | // merged it. |
| 447 | func mergedView(k taskRecord) *wire.Merged { |
| 448 | if k.MergedSHA == "" || k.MergedAt == nil { |
| 449 | return nil |
| 450 | } |
| 451 | return &wire.Merged{SHA: k.MergedSHA, Into: k.MergedInto, Strategy: k.MergeStrategy, WithoutChecks: k.MergedWithoutChecks, At: *k.MergedAt} |
| 452 | } |
| 453 | |
| 454 | // reportCount counts the reports attached to a task. |
| 455 | func reportCount(tx *gorm.DB, id string) (int, error) { |
| 456 | var n int64 |
| 457 | err := tx.Model(&entryRecord{}).Where("task_id = ? AND kind = ?", id, entryReport).Count(&n).Error |
| 458 | return int(n), err |
| 459 | } |
| 460 | |
| 461 | // mergeRetryable reports whether a person may merge given the newest |
| 462 | // merge step of the candidate: none yet, or one that failed and ended. |
| 463 | func mergeRetryable(m *stepRecord) bool { |
| 464 | return m == nil || m.State == wire.StepFailed && m.Terminated |
| 465 | } |
| 466 | |
| 467 | // ErrNotMergeable means the task cannot be merged now: not Ready to |
| 468 | // merge, the branch is not at the judged SHA, or a merge ran already. |
| 469 | var ErrNotMergeable = errors.New("chat: task not mergeable") |
| 470 | |
| 471 | // mergeOffered reports whether the creator's Merge action applies now. |
| 472 | func (t *txn) mergeOffered(k taskRecord, p progress) (bool, error) { |
| 473 | if k.Stage != wire.StageReadyToMerge || k.CancelRequested || p.moved || !mergeRetryable(p.merge) || !p.mergeAllowed(true) { |
| 474 | return false, nil |
| 475 | } |
| 476 | var open int64 |
| 477 | err := t.db.Model(&cardRecord{}).Where("task_id = ? AND kind = ? AND state = ?", k.ID, wire.CardMerge, wire.CardOpen).Count(&open).Error |
| 478 | return open == 0, err |
| 479 | } |
| 480 | |
| 481 | // MergeTask is the creator's Merge on a task left at Ready to merge (Not |
| 482 | // now on its card, or Wait for checks): validated afresh (the branch at |
| 483 | // the judged SHA as last seen, approved, no merge yet); a candidate with |
| 484 | // checks passed is recorded eligible at that moment. The runner checks |
| 485 | // the head again right before merging. |
| 486 | func (s *Store) MergeTask(ctx context.Context, person, id string) (attempt int64, err error) { |
| 487 | s.refreshBeforeAct(ctx, person) |
| 488 | err = s.tx(ctx, func(t *txn) error { |
| 489 | if err := s.authority.CurrentPerson(ctx, t.db); err != nil { |
| 490 | return err |
| 491 | } |
| 492 | if err := t.isOwner(person); err != nil { |
| 493 | return err |
| 494 | } |
| 495 | k, err := t.loadTask(id) |
| 496 | if err != nil { |
| 497 | return err |
| 498 | } |
| 499 | if k.Creator != person { |
| 500 | return ErrForbidden |
| 501 | } |
| 502 | if wire.FinalStage(k.Stage) || k.CancelRequested { |
| 503 | return ErrTaskEnded |
| 504 | } |
| 505 | if err := t.requireGoLive(person, k.ID); err != nil { |
| 506 | return err |
| 507 | } |
| 508 | steps, err := t.steps(k.ID) |
| 509 | if err != nil { |
| 510 | return err |
| 511 | } |
| 512 | p := progressFor(k, steps) |
| 513 | if ok, err := t.mergeOffered(k, p); err != nil { |
| 514 | return err |
| 515 | } else if !ok { |
| 516 | return ErrNotMergeable |
| 517 | } |
| 518 | if err := t.personMerge(&k, p, steps, person); err != nil { |
| 519 | return err |
| 520 | } |
| 521 | attempt = 1 |
| 522 | return nil |
| 523 | }) |
| 524 | return attempt, err |
| 525 | } |
| 526 | |