| 1 | package chat |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "encoding/json" |
| 6 | "errors" |
| 7 | "fmt" |
| 8 | "slices" |
| 9 | "strings" |
| 10 | "time" |
| 11 | |
| 12 | "amadan.net/oficina/equipo/internal/wire" |
| 13 | "gorm.io/gorm" |
| 14 | ) |
| 15 | |
| 16 | // The scheduler on the instance (connectors spec 2026-11-12 rev 3.1, §6 |
| 17 | // and §8, slice S3). A task has a priority and an optional deadline: the |
| 18 | // coordinator may set low or normal, and by, only when it creates the |
| 19 | // task; every later change and every urgent is the task creator's own |
| 20 | // tap. The runner holds steps and says why; the task shows the hold, and |
| 21 | // asks its creator only where their input changes the outcome (the |
| 22 | // deadline check, no reset in sight, nothing that can run it), with |
| 23 | // Equipo's recommendation. Run now is the creator's leave for one step |
| 24 | // revision: a durable release the runner consumes with the admission it |
| 25 | // causes. |
| 26 | |
| 27 | // releaseRecord is one Run now: at most one per step revision. |
| 28 | type releaseRecord struct { |
| 29 | ID string `gorm:"primaryKey"` |
| 30 | TaskID string `gorm:"index:chat_release_task"` |
| 31 | StepID string `gorm:"uniqueIndex:chat_release_step,priority:1"` |
| 32 | StepRevision int64 `gorm:"uniqueIndex:chat_release_step,priority:2"` |
| 33 | Person string |
| 34 | RunnerID string |
| 35 | // Connection pins it (protocol 29): the runner's local id of the one |
| 36 | // connection the person was told Run now would use; "" is leave on |
| 37 | // any (an older runner, or a Run now nobody was promised anything for). |
| 38 | Connection string |
| 39 | CreatedAt time.Time |
| 40 | } |
| 41 | |
| 42 | func (releaseRecord) TableName() string { return "chat_releases" } |
| 43 | |
| 44 | // ErrAlreadyReleased: Run now was already written for this hold; it is |
| 45 | // on its way (or the runner could not honour it, and the step waits). |
| 46 | var ErrAlreadyReleased = errors.New("chat: run now is already on its way") |
| 47 | |
| 48 | // ErrHoldBar: Run now cannot pass a spending bar (the budget, the spend |
| 49 | // unknown); the hold offers Raise the budget or Resume instead. |
| 50 | var ErrHoldBar = errors.New("chat: run now cannot pass this hold") |
| 51 | |
| 52 | // Choices on the held card. |
| 53 | const ( |
| 54 | ChoiceWait = "wait_reset" |
| 55 | ChoiceRunNow = "run_now" |
| 56 | ) |
| 57 | |
| 58 | // toolPriority reads the coordinator's priority and deadline on |
| 59 | // record_task or start_task: low or normal (never urgent), and a |
| 60 | // deadline in the future, at most a year ahead. ok false: refused. |
| 61 | func toolPriority(priority, by string, now time.Time) (string, *time.Time, bool) { |
| 62 | if priority != "" && !wire.CoordinatorPriority(priority) { |
| 63 | return "", nil, false |
| 64 | } |
| 65 | if by == "" { |
| 66 | return priority, nil, true |
| 67 | } |
| 68 | t, err := time.Parse(time.RFC3339, by) |
| 69 | if err != nil { |
| 70 | d, derr := time.Parse("2006-01-02", by) |
| 71 | if derr != nil { |
| 72 | return "", nil, false |
| 73 | } |
| 74 | // A date is the end of that day, UTC until a zone is known. |
| 75 | t = d.Add(24*time.Hour - time.Second) |
| 76 | } |
| 77 | if !t.After(now) || t.Sub(now) > wire.MaxByAhead { |
| 78 | return "", nil, false |
| 79 | } |
| 80 | t = t.UTC() |
| 81 | return priority, &t, true |
| 82 | } |
| 83 | |
| 84 | // coordinatorSetsPriority records the coordinator's priority and deadline |
| 85 | // on a task it is creating (in this turn, nothing set before). Anything |
| 86 | // else is refused: the model can describe, never loosen (§6). |
| 87 | func (t *txn) coordinatorSetsPriority(k *taskRecord, r turnRecord, priority string, by *time.Time) error { |
| 88 | if priority == "" && by == nil { |
| 89 | return nil |
| 90 | } |
| 91 | if k.TurnID != r.ID || k.PrioritySetBy != "" { |
| 92 | return nil |
| 93 | } |
| 94 | k.Priority, k.DueBy, k.PrioritySetBy = priority, by, wire.PrioritySetByCoordinator |
| 95 | k.PriorityRevision++ |
| 96 | return t.db.Model(&taskRecord{}).Where("id = ?", k.ID).Updates(map[string]any{"priority": k.Priority, "due_by": k.DueBy, "priority_set_by": k.PrioritySetBy, "priority_revision": k.PriorityRevision}).Error |
| 97 | } |
| 98 | |
| 99 | // taskPriority is a task's priority on its read shape; absent while it |
| 100 | // is the default (normal, no deadline, nobody set it). |
| 101 | func taskPriority(k taskRecord) *wire.TaskPriority { |
| 102 | if k.Priority == "" && k.DueBy == nil && k.PrioritySetBy == "" { |
| 103 | return nil |
| 104 | } |
| 105 | p := k.Priority |
| 106 | if p == "" { |
| 107 | p = wire.PriorityNormal |
| 108 | } |
| 109 | return &wire.TaskPriority{Priority: p, By: k.DueBy, SetBy: k.PrioritySetBy} |
| 110 | } |
| 111 | |
| 112 | // stepHold is a step's hold as stored ("" none). |
| 113 | func stepHold(s stepRecord) *wire.StepHold { |
| 114 | if s.Hold == "" { |
| 115 | return nil |
| 116 | } |
| 117 | var h wire.StepHold |
| 118 | if json.Unmarshal([]byte(s.Hold), &h) != nil { |
| 119 | return nil |
| 120 | } |
| 121 | return &h |
| 122 | } |
| 123 | |
| 124 | // acceptHold records a held step's hold from its runner's report, or |
| 125 | // clears it. A hold the instance cannot read is not kept. HeldAt is when |
| 126 | // the hold began (now, for a step not held before); it goes with it. |
| 127 | func acceptHold(s *stepRecord, v *wire.StepReport, now time.Time) bool { |
| 128 | if v.Hold == nil || wire.StepTerminal(v.State) { |
| 129 | changed := s.Hold != "" |
| 130 | s.Hold, s.HeldAt = "", nil |
| 131 | return changed |
| 132 | } |
| 133 | h := *v.Hold |
| 134 | if !wire.HoldReasons[h.Reason] || !wire.HoldNeeds[h.NeedsPerson] || len(h.Connection) > 200 || len(h.Provider) > 40 || h.StepRevision < 0 { |
| 135 | return false |
| 136 | } |
| 137 | raw := asJSON(h) |
| 138 | changed := raw != s.Hold |
| 139 | if s.Hold == "" || s.HeldAt == nil { |
| 140 | at := now.UTC() |
| 141 | s.HeldAt = &at |
| 142 | } |
| 143 | s.Hold = raw |
| 144 | return changed |
| 145 | } |
| 146 | |
| 147 | // SetPriority is the task creator's priority and deadline (PUT |
| 148 | // /api/v1/tasks/{id}/priority): the actor from the session, the roster |
| 149 | // checked in the transaction, against the task's revision. A step the |
| 150 | // runner holds takes it at once (the durable priority frame). |
| 151 | func (s *Store) SetPriority(ctx context.Context, person, id string, in wire.SetPriority) (out wire.Task, err error) { |
| 152 | if !wire.ValidPriority(in.Priority) { |
| 153 | return out, ErrInvalid |
| 154 | } |
| 155 | err = s.tx(ctx, func(t *txn) error { |
| 156 | if err := s.authority.CurrentPerson(ctx, t.db); err != nil { |
| 157 | return err |
| 158 | } |
| 159 | out, err = t.setPriority(person, id, in) |
| 160 | return err |
| 161 | }) |
| 162 | return out, err |
| 163 | } |
| 164 | |
| 165 | // setPriority is SetPriority in t (advice's Make them low priority and |
| 166 | // Make them normal act through it, task by task). |
| 167 | func (t *txn) setPriority(person, id string, in wire.SetPriority) (out wire.Task, err error) { |
| 168 | if !wire.ValidPriority(in.Priority) { |
| 169 | return out, ErrInvalid |
| 170 | } |
| 171 | if err := t.isOwner(person); err != nil { |
| 172 | return out, err |
| 173 | } |
| 174 | k, err := t.loadTask(id) |
| 175 | if err != nil { |
| 176 | return out, err |
| 177 | } |
| 178 | if k.Creator != person { |
| 179 | return out, ErrForbidden |
| 180 | } |
| 181 | if wire.FinalStage(k.Stage) || k.CancelRequested { |
| 182 | return out, ErrTaskEnded |
| 183 | } |
| 184 | if in.Revision != k.Revision { |
| 185 | return out, ErrConflict |
| 186 | } |
| 187 | var by *time.Time |
| 188 | if in.By != nil { |
| 189 | b := in.By.UTC() |
| 190 | unchanged := k.DueBy != nil && k.DueBy.Equal(b) |
| 191 | // A deadline newly given must be ahead; the one the task has may |
| 192 | // have passed (an overdue task can still change priority). |
| 193 | if !unchanged && (!b.After(t.now()) || b.Sub(t.now()) > wire.MaxByAhead) { |
| 194 | return out, ErrInvalid |
| 195 | } |
| 196 | by = &b |
| 197 | } |
| 198 | k.Priority, k.DueBy, k.PrioritySetBy = in.Priority, by, wire.PrioritySetByPerson |
| 199 | k.PriorityRevision++ |
| 200 | if err := t.db.Model(&taskRecord{}).Where("id = ?", k.ID).Select("priority", "due_by", "priority_set_by", "priority_revision").Updates(&k).Error; err != nil { |
| 201 | return out, err |
| 202 | } |
| 203 | if err := t.saveTask(&k); err != nil { |
| 204 | return out, err |
| 205 | } |
| 206 | if err := t.audit(person, "task.priority", k.ID+"@"+in.Priority); err != nil { |
| 207 | return out, err |
| 208 | } |
| 209 | if err := t.sendPriority(k); err != nil { |
| 210 | return out, err |
| 211 | } |
| 212 | return t.taskView(k) |
| 213 | } |
| 214 | |
| 215 | // sendPriority tells the runner of the task's queued or running step its |
| 216 | // new priority (a runner below the scheduler's protocol never spends, |
| 217 | // and takes the priority with its next dispatch). |
| 218 | func (t *txn) sendPriority(k taskRecord) error { |
| 219 | var held []stepRecord |
| 220 | if err := t.db.Where("task_id = ? AND state IN ? AND runner_id <> ''", k.ID, []string{wire.StepQueued, wire.StepRunning}).Find(&held).Error; err != nil { |
| 221 | return err |
| 222 | } |
| 223 | sent := map[string]bool{} |
| 224 | for _, st := range held { |
| 225 | if sent[st.RunnerID] { |
| 226 | continue |
| 227 | } |
| 228 | sent[st.RunnerID] = true |
| 229 | proto, err := t.runnerProtocol(st.Person, st.RunnerID) |
| 230 | if err != nil { |
| 231 | return err |
| 232 | } |
| 233 | if proto < wire.ProtocolScheduler { |
| 234 | continue |
| 235 | } |
| 236 | p := k.Priority |
| 237 | if p == "" { |
| 238 | p = wire.PriorityNormal |
| 239 | } |
| 240 | if err := t.commandTo(st.RunnerID, st.Person, wire.FramePriority, wire.PriorityCommand{Person: st.Person, TaskID: k.ID, Priority: p, By: k.DueBy, Revision: k.PriorityRevision}); err != nil { |
| 241 | return err |
| 242 | } |
| 243 | } |
| 244 | return nil |
| 245 | } |
| 246 | |
| 247 | // RunNow is the task creator's Run it now anyway (POST |
| 248 | // /api/v1/tasks/{id}/run-now): leave for the held step at the revision |
| 249 | // its hold shows, written as a durable release (one per step revision; |
| 250 | // a second tap answers the first). It never passes a spending bar, and |
| 251 | // an older runner is refused rather than handed it. |
| 252 | func (s *Store) RunNow(ctx context.Context, person, id string, in wire.RunNow) (out wire.RunNowAccepted, err error) { |
| 253 | err = s.tx(ctx, func(t *txn) error { |
| 254 | if err := s.authority.CurrentPerson(ctx, t.db); err != nil { |
| 255 | return err |
| 256 | } |
| 257 | if err := t.isOwner(person); err != nil { |
| 258 | return err |
| 259 | } |
| 260 | k, err := t.loadTask(id) |
| 261 | if err != nil { |
| 262 | return err |
| 263 | } |
| 264 | if k.Creator != person { |
| 265 | return ErrForbidden |
| 266 | } |
| 267 | if wire.FinalStage(k.Stage) || k.CancelRequested { |
| 268 | return ErrTaskEnded |
| 269 | } |
| 270 | var prior int64 |
| 271 | if err := t.db.Model(&releaseRecord{}).Where("step_id = ? AND step_revision = ?", in.Step, in.StepRevision).Count(&prior).Error; err != nil { |
| 272 | return err |
| 273 | } |
| 274 | if prior > 0 { |
| 275 | // S2: a second tap is told, not answered with the first. |
| 276 | return ErrAlreadyReleased |
| 277 | } |
| 278 | rel, err := t.release(k, person, in.Step, in.StepRevision, &in.Offer) |
| 279 | out.Release = rel |
| 280 | return err |
| 281 | }) |
| 282 | return out, err |
| 283 | } |
| 284 | |
| 285 | // ErrOfferChanged: the Run now the person was shown is not what Run now |
| 286 | // would do now (review R1); nothing is written, and the page shows the |
| 287 | // offer as it is. |
| 288 | var ErrOfferChanged = errors.New("chat: what run now would use has changed") |
| 289 | |
| 290 | // release writes the release for the task's held step at revision, in t. |
| 291 | // shown is what the person was shown (wire.RunNow.Offer): Run now is |
| 292 | // predicted again and must be that, or ErrOfferChanged; the release is |
| 293 | // pinned to it. nil is the held card's Run it now, which names nothing. |
| 294 | func (t *txn) release(k taskRecord, person, step string, revision int64, shown *string) (string, error) { |
| 295 | var st stepRecord |
| 296 | if err := t.db.Where("id = ? AND task_id = ?", step, k.ID).First(&st).Error; errors.Is(err, gorm.ErrRecordNotFound) { |
| 297 | return "", ErrNotFound |
| 298 | } else if err != nil { |
| 299 | return "", err |
| 300 | } |
| 301 | var prior releaseRecord |
| 302 | err := t.db.Where("step_id = ? AND step_revision = ?", st.ID, revision).First(&prior).Error |
| 303 | if err == nil { |
| 304 | return prior.ID, nil |
| 305 | } |
| 306 | if !errors.Is(err, gorm.ErrRecordNotFound) { |
| 307 | return "", err |
| 308 | } |
| 309 | h := stepHold(st) |
| 310 | if wire.StepTerminal(st.State) || h == nil || h.StepRevision != revision { |
| 311 | // Not held, or held at another revision now: stale. |
| 312 | return "", ErrConflict |
| 313 | } |
| 314 | if h.Reason == wire.HoldDesignLimit { |
| 315 | // The autonomy limit's hold: nothing was sent, so there is no |
| 316 | // release; the go-ahead is the person acting on the task, and the |
| 317 | // step is dispatched now. |
| 318 | if err := t.closeHeldCards(k.ID, ChoiceRunNow); err != nil { |
| 319 | return "", err |
| 320 | } |
| 321 | if err := t.audit(person, "task.design_go_ahead", st.ID+"@"+itoa64(revision)); err != nil { |
| 322 | return "", err |
| 323 | } |
| 324 | acted, err := t.personActed(k.ID, person) |
| 325 | if err != nil || !acted { |
| 326 | return "", err |
| 327 | } |
| 328 | return "", t.releaseDesignHeld(k.ID) |
| 329 | } |
| 330 | if h.Reason == wire.HoldBudget || h.Reason == wire.HoldSpendUnknown || housekeepingAttempt(st) { |
| 331 | // Never past a spending bar, and never for housekeeping's own |
| 332 | // attempt, which does not spend. |
| 333 | return "", ErrHoldBar |
| 334 | } |
| 335 | proto, err := t.runnerProtocol(st.Person, st.RunnerID) |
| 336 | if err != nil { |
| 337 | return "", err |
| 338 | } |
| 339 | if proto < wire.ProtocolScheduler { |
| 340 | return "", ErrRunnerTooOld |
| 341 | } |
| 342 | // Pinned to what the person was shown (protocol 29), read again now: |
| 343 | // the same answer, or refused. |
| 344 | pin := "" |
| 345 | recs, err := t.connections(st.Person) |
| 346 | if err != nil { |
| 347 | return "", err |
| 348 | } |
| 349 | var mine []connectionRecord |
| 350 | for _, r := range recs { |
| 351 | if r.RunnerID == st.RunnerID && r.LocalID != "" && labelled(connectionView(r)) { |
| 352 | mine = append(mine, r) |
| 353 | } |
| 354 | } |
| 355 | o, local := t.predictRunNow(k, st, h, mine) |
| 356 | switch { |
| 357 | case shown == nil: |
| 358 | // The held card's Run it now: pinned when there is a prediction. |
| 359 | if o != nil && !o.Plain { |
| 360 | pin = local |
| 361 | } |
| 362 | case o == nil: |
| 363 | return "", ErrOfferChanged |
| 364 | case o.Plain: |
| 365 | if *shown != wire.RunNowPlain { |
| 366 | return "", ErrOfferChanged |
| 367 | } |
| 368 | case *shown != o.Connection: |
| 369 | return "", ErrOfferChanged |
| 370 | default: |
| 371 | pin = local |
| 372 | } |
| 373 | r := releaseRecord{ID: newID("rl_"), TaskID: k.ID, StepID: st.ID, StepRevision: revision, Person: person, RunnerID: st.RunnerID, Connection: pin, CreatedAt: t.now()} |
| 374 | if err := t.db.Create(&r).Error; err != nil { |
| 375 | return "", err |
| 376 | } |
| 377 | if err := t.audit(person, "task.run_now", st.ID+"@"+itoa64(revision)); err != nil { |
| 378 | return "", err |
| 379 | } |
| 380 | // The held card for this step is answered by the tap too. |
| 381 | if err := t.closeHeldCards(k.ID, ChoiceRunNow); err != nil { |
| 382 | return "", err |
| 383 | } |
| 384 | return r.ID, t.commandTo(st.RunnerID, st.Person, wire.FrameRelease, wire.ReleaseCommand{ID: r.ID, Person: st.Person, TaskID: k.ID, StepID: st.ID, StepRevision: revision, Connection: pin}) |
| 385 | } |
| 386 | |
| 387 | // schedulerFields puts the scheduler's facts on a step's dispatch (protocol |
| 388 | // 14; Encode drops them for an older runner): the task's priority, |
| 389 | // deadline and priority revision, and a Run now written for this |
| 390 | // attempt. An attempt housekeeping dispatched counts as low, carries no |
| 391 | // release and says so, wherever and whenever it is placed (§7, |
| 392 | // Housekeeping). |
| 393 | func (t *txn) schedulerFields(k taskRecord, s stepRecord, cmd *wire.DispatchCommand) error { |
| 394 | cmd.Priority, cmd.By, cmd.PriorityRevision = k.Priority, k.DueBy, k.PriorityRevision |
| 395 | if housekeepingAttempt(s) { |
| 396 | cmd.Priority, cmd.Housekeeping = wire.PriorityLow, true |
| 397 | return nil |
| 398 | } |
| 399 | var err error |
| 400 | cmd.Release, cmd.ReleaseConnection, err = t.openRelease(s) |
| 401 | return err |
| 402 | } |
| 403 | |
| 404 | // housekeepingAttempt reports whether the step's current attempt is one |
| 405 | // housekeeping dispatched. |
| 406 | func housekeepingAttempt(s stepRecord) bool { |
| 407 | return s.HousekeepingAttempt != 0 && s.HousekeepingAttempt == s.Attempt |
| 408 | } |
| 409 | |
| 410 | // openRelease is an unconsumed release the instance wrote for the step's |
| 411 | // dispatched attempt (a step placed again carries it). |
| 412 | func (t *txn) openRelease(s stepRecord) (string, string, error) { |
| 413 | var r releaseRecord |
| 414 | err := t.db.Where("step_id = ? AND step_revision = ?", s.ID, s.Attempt).First(&r).Error |
| 415 | if errors.Is(err, gorm.ErrRecordNotFound) { |
| 416 | return "", "", nil |
| 417 | } |
| 418 | return r.ID, r.Connection, err |
| 419 | } |
| 420 | |
| 421 | // heldCard asks the task's creator about a held step where their input |
| 422 | // changes the outcome (§8), once per step revision and need, with |
| 423 | // Equipo's recommendation; a hold that no longer needs them resolves it. |
| 424 | func (t *txn) heldCard(k taskRecord, s stepRecord) error { |
| 425 | h := stepHold(s) |
| 426 | if h == nil || h.NeedsPerson == "" || wire.FinalStage(k.Stage) || k.CancelRequested { |
| 427 | return t.closeHeldCards(k.ID, "") |
| 428 | } |
| 429 | name := heldName(s.ID, h) |
| 430 | var n int64 |
| 431 | if err := t.db.Model(&cardRecord{}).Where("task_id = ? AND kind = ? AND name = ?", k.ID, wire.CardHeld, name).Count(&n).Error; err != nil || n > 0 { |
| 432 | return err |
| 433 | } |
| 434 | if err := t.closeHeldCards(k.ID, ""); err != nil { |
| 435 | return err |
| 436 | } |
| 437 | options := []string{ChoiceWait, ChoiceRunNow} |
| 438 | switch { |
| 439 | case h.Reason == wire.HoldDesignLimit: |
| 440 | // Held for the person alone: only their go-ahead runs it (any |
| 441 | // answer on the task is their act, so Wait would run it too). |
| 442 | options = []string{ChoiceRunNow} |
| 443 | case h.Reason == wire.HoldBudget || h.Reason == wire.HoldSpendUnknown || housekeepingAttempt(s): |
| 444 | // Run now cannot pass a spending bar, nor give housekeeping's own |
| 445 | // attempt leave: the hold's own actions are on the task. |
| 446 | options = []string{ChoiceWait} |
| 447 | } |
| 448 | opts, _ := json.Marshal(options) |
| 449 | now := t.now() |
| 450 | c := cardRecord{ID: newID("c_"), Person: k.Creator, Kind: wire.CardHeld, State: wire.CardOpen, ProjectID: k.ProjectID, TaskID: k.ID, Name: name, Question: t.heldQuestion(k, s.RunnerID, h, now), Options: string(opts), Revision: 1, CreatedAt: now, UpdatedAt: now, Lane: k.Lane} |
| 451 | if err := t.db.Create(&c).Error; err != nil { |
| 452 | return err |
| 453 | } |
| 454 | return t.cardEvent(c) |
| 455 | } |
| 456 | |
| 457 | // heldName binds a held card to its step, revision and need. |
| 458 | func heldName(step string, h *wire.StepHold) string { |
| 459 | return step + "@" + itoa64(h.StepRevision) + ":" + h.NeedsPerson |
| 460 | } |
| 461 | |
| 462 | // closeHeldCards resolves the task's open held cards (answered with |
| 463 | // choice when given, else withdrawn). |
| 464 | func (t *txn) closeHeldCards(task, choice string) error { |
| 465 | var open []cardRecord |
| 466 | if err := t.db.Where("task_id = ? AND kind = ? AND state = ?", task, wire.CardHeld, wire.CardOpen).Find(&open).Error; err != nil { |
| 467 | return err |
| 468 | } |
| 469 | for _, c := range open { |
| 470 | c.State, c.Choice = wire.CardResolved, choice |
| 471 | if choice != "" { |
| 472 | c.State = wire.CardAnswered |
| 473 | } |
| 474 | if err := t.saveCard(&c); err != nil { |
| 475 | return err |
| 476 | } |
| 477 | } |
| 478 | return nil |
| 479 | } |
| 480 | |
| 481 | // heldQuestion is the card's words, Equipo's recommendation (merge |
| 482 | // authority §4.1), stored with the card: its times are the creator's |
| 483 | // local clock, without how long until them (that goes stale). |
| 484 | func (t *txn) heldQuestion(k taskRecord, runner string, h *wire.StepHold, now time.Time) string { |
| 485 | name := providerWord(h.Provider) |
| 486 | if h.Provider != "" { |
| 487 | name = t.heldLabel(k.Creator, runner, h).Text |
| 488 | } |
| 489 | loc := t.zone(k.Creator) |
| 490 | return HeldWords(t.copy, name, h, k.DueBy, now, func(at time.Time) string { return at.In(loc).Format("Mon 15:04") }, func(at time.Time) string { return day(at.In(loc)) }) |
| 491 | } |
| 492 | |
| 493 | // HeldWords is a held step's recommendation (§8): wait when a reset |
| 494 | // comes in time, run it now when none does or nothing else can run it. |
| 495 | // name is the connection's; when words a reset, day a deadline. |
| 496 | func HeldWords(copy func(string) string, name string, h *wire.StepHold, dueBy *time.Time, now time.Time, when, day func(time.Time) string) string { |
| 497 | words := func(key string, args ...any) string { return fmt.Sprintf(copy(key), args...) } |
| 498 | switch { |
| 499 | case h.Reason == wire.HoldDesignLimit: |
| 500 | return words("chat.held.design_limit", wire.DesignRunLimit) |
| 501 | case h.NeedsPerson == wire.HoldNeedsNoConnection: |
| 502 | return copy("chat.held.run.no_connection") |
| 503 | case h.ResetsAt != nil && dueBy != nil && h.ResetsAt.Before(*dueBy): |
| 504 | return words("chat.held.wait.before", name, when(*h.ResetsAt), day(*dueBy)) |
| 505 | case h.ResetsAt != nil && h.ResetsAt.Sub(now) <= 72*time.Hour && h.NeedsPerson != wire.HoldNeedsDeadline: |
| 506 | return words("chat.held.wait.reset", name, when(*h.ResetsAt)) |
| 507 | case h.ResetsAt != nil && dueBy != nil: |
| 508 | return words("chat.held.run.after_by", name, when(*h.ResetsAt), day(*dueBy)) |
| 509 | case h.Reason == wire.HoldSpendUnknown: |
| 510 | return words("chat.held.spend_unknown", name) |
| 511 | case h.Reason == wire.HoldBudget: |
| 512 | return words("chat.held.budget", name) |
| 513 | } |
| 514 | return words("chat.held.run.no_reset", name) |
| 515 | } |
| 516 | |
| 517 | // providerWord is a provider as people say it. |
| 518 | func providerWord(p string) string { |
| 519 | switch p { |
| 520 | case wire.ProviderClaude: |
| 521 | return "Claude" |
| 522 | case wire.ProviderCodex: |
| 523 | return "Codex" |
| 524 | case wire.ProviderTensorX: |
| 525 | return "TensorX" |
| 526 | case wire.ProviderOpenCodeGo: |
| 527 | return "OpenCode Go" |
| 528 | case "": |
| 529 | return "Equipo" |
| 530 | } |
| 531 | return strings.ToUpper(p[:1]) + p[1:] |
| 532 | } |
| 533 | |
| 534 | func day(t time.Time) string { return t.Format("Monday 2 Jan") } |
| 535 | |
| 536 | // answerHeld is the creator's answer on a held card: Wait closes it; Run |
| 537 | // it now writes the release for the step revision the card asked about. |
| 538 | func (t *txn) answerHeld(person string, c cardRecord, in wire.AnswerCard) (wire.Card, wire.Card, error) { |
| 539 | if err := t.hkForbid("run now"); err != nil { |
| 540 | return wire.Card{}, wire.Card{}, err |
| 541 | } |
| 542 | v, err := t.cardView(c) |
| 543 | if err != nil { |
| 544 | return wire.Card{}, wire.Card{}, err |
| 545 | } |
| 546 | var options []string |
| 547 | _ = json.Unmarshal([]byte(c.Options), &options) |
| 548 | if !slices.Contains(options, in.Choice) { |
| 549 | return wire.Card{}, wire.Card{}, ErrInvalid |
| 550 | } |
| 551 | if c.State != wire.CardOpen || c.Revision != in.Revision { |
| 552 | return wire.Card{}, v, ErrCardConflict |
| 553 | } |
| 554 | k, err := t.loadTask(c.TaskID) |
| 555 | if err != nil { |
| 556 | return wire.Card{}, wire.Card{}, err |
| 557 | } |
| 558 | if k.Creator != person || c.Person != person { |
| 559 | return wire.Card{}, wire.Card{}, ErrForbidden |
| 560 | } |
| 561 | if err := t.isOwner(person); err != nil { |
| 562 | return wire.Card{}, wire.Card{}, err |
| 563 | } |
| 564 | if in.Choice == ChoiceRunNow { |
| 565 | step, rest, _ := strings.Cut(c.Name, "@") |
| 566 | rev, _, _ := strings.Cut(rest, ":") |
| 567 | var revision int64 |
| 568 | for _, ch := range rev { |
| 569 | revision = revision*10 + int64(ch-'0') |
| 570 | } |
| 571 | if _, err := t.release(k, person, step, revision, nil); errors.Is(err, ErrConflict) || errors.Is(err, ErrHoldBar) { |
| 572 | return wire.Card{}, v, ErrCardConflict |
| 573 | } else if err != nil { |
| 574 | return wire.Card{}, wire.Card{}, err |
| 575 | } |
| 576 | fresh, err := t.loadCard(c.ID) |
| 577 | if err != nil { |
| 578 | return wire.Card{}, wire.Card{}, err |
| 579 | } |
| 580 | out, err := t.cardView(fresh) |
| 581 | return out, wire.Card{}, err |
| 582 | } |
| 583 | c.State, c.Choice = wire.CardAnswered, in.Choice |
| 584 | if err := t.saveCard(&c); err != nil { |
| 585 | return wire.Card{}, wire.Card{}, err |
| 586 | } |
| 587 | out, err := t.cardView(c) |
| 588 | return out, wire.Card{}, err |
| 589 | } |
| 590 | |
| 591 | func (t *txn) loadCard(id string) (cardRecord, error) { |
| 592 | var c cardRecord |
| 593 | err := t.db.Where("id = ?", id).First(&c).Error |
| 594 | return c, err |
| 595 | } |
| 596 | |