| 1 | package chat |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "encoding/json" |
| 6 | "errors" |
| 7 | "regexp" |
| 8 | "strings" |
| 9 | "time" |
| 10 | "unicode/utf8" |
| 11 | |
| 12 | "amadan.net/oficina/equipo/internal/wire" |
| 13 | "gorm.io/gorm" |
| 14 | ) |
| 15 | |
| 16 | // Asking the implementer: a task's creator asks the specialist that did |
| 17 | // the work, and the runner resumes that step's own session read-only. |
| 18 | // Questions are team records like their task: every active member sees |
| 19 | // them and their streamed answers; only the creator asks or cancels. One |
| 20 | // question of a task is with the runner at a time; the runner runs it |
| 21 | // only between steps, never beside a step that writes. |
| 22 | |
| 23 | // ErrNotAskable means no step of the task has a session kept to ask. |
| 24 | var ErrNotAskable = errors.New("chat: no step to ask") |
| 25 | |
| 26 | // RunnerOfflineError is ErrRunnerOffline for a question: the runner that |
| 27 | // holds the session, by its label ("" when it has none). |
| 28 | type RunnerOfflineError struct{ Label string } |
| 29 | |
| 30 | func (e *RunnerOfflineError) Error() string { return ErrRunnerOffline.Error() } |
| 31 | func (e *RunnerOfflineError) Is(target error) bool { return target == ErrRunnerOffline } |
| 32 | |
| 33 | // questionRecord is one question and its answer. |
| 34 | type questionRecord struct { |
| 35 | ID string `gorm:"primaryKey"` |
| 36 | TaskID string `gorm:"index:chat_question_task;uniqueIndex:chat_question_key,priority:1"` |
| 37 | Asker string `gorm:"uniqueIndex:chat_question_key,priority:2"` |
| 38 | IdempotencyKey string `gorm:"uniqueIndex:chat_question_key,priority:3"` |
| 39 | StepID string |
| 40 | Specialist string |
| 41 | // Chosen is the specialist the person chose ("" when Equipo chose), |
| 42 | // kept for the idempotency comparison. |
| 43 | Chosen string |
| 44 | Text string |
| 45 | State string |
| 46 | Reason string |
| 47 | Attempt int64 |
| 48 | Dispatched bool |
| 49 | Answer string |
| 50 | Timing string |
| 51 | Revision int64 |
| 52 | CreatedAt time.Time |
| 53 | UpdatedAt time.Time |
| 54 | // The runner a question is asked of and the pair it is about, and for |
| 55 | // an Engineering question the attempt, account binding and kept |
| 56 | // session it resumes: frozen when the question is created (migration |
| 57 | // 0120, Mac runners slice F), never moved with its step. Zero on every |
| 58 | // question made before; those read the step (questionRunner). |
| 59 | EngAttempt int64 |
| 60 | EngAccount string |
| 61 | EngSession string |
| 62 | RunnerID string |
| 63 | BaseSHA string |
| 64 | CandidateSHA string |
| 65 | } |
| 66 | |
| 67 | func (questionRecord) TableName() string { return "chat_questions" } |
| 68 | |
| 69 | func questionView(q questionRecord) wire.Question { |
| 70 | v := wire.Question{ID: q.ID, Revision: q.Revision, TaskID: q.TaskID, StepID: q.StepID, Specialist: q.Specialist, Asker: q.Asker, Text: q.Text, State: q.State, Reason: q.Reason, Attempt: q.Attempt, Answer: q.Answer, CreatedAt: q.CreatedAt, UpdatedAt: q.UpdatedAt} |
| 71 | if q.Timing != "" && q.State == wire.QuestionAnswered { |
| 72 | v.Timing = &wire.TurnTiming{} |
| 73 | if json.Unmarshal([]byte(q.Timing), v.Timing) != nil { |
| 74 | v.Timing = nil |
| 75 | } |
| 76 | } |
| 77 | return v |
| 78 | } |
| 79 | |
| 80 | func (t *txn) questions(taskID string) ([]wire.Question, error) { |
| 81 | var rows []questionRecord |
| 82 | if err := t.db.Where("task_id = ?", taskID).Order("created_at, id").Find(&rows).Error; err != nil { |
| 83 | return nil, err |
| 84 | } |
| 85 | out := make([]wire.Question, 0, len(rows)) |
| 86 | for _, q := range rows { |
| 87 | out = append(out, questionView(q)) |
| 88 | } |
| 89 | return out, nil |
| 90 | } |
| 91 | |
| 92 | // saveQuestion bumps the question's revision and tells every member. |
| 93 | func (t *txn) saveQuestion(q *questionRecord) error { |
| 94 | q.Revision++ |
| 95 | q.UpdatedAt = t.now() |
| 96 | if err := t.db.Model(&questionRecord{}).Where("id = ?", q.ID).Select("step_id", "specialist", "state", "reason", "attempt", "dispatched", "answer", "timing", "revision", "updated_at").Updates(q).Error; err != nil { |
| 97 | return err |
| 98 | } |
| 99 | return t.questionEvent(*q) |
| 100 | } |
| 101 | |
| 102 | func (t *txn) questionEvent(q questionRecord) error { |
| 103 | members, err := t.members() |
| 104 | if err != nil { |
| 105 | return err |
| 106 | } |
| 107 | v := questionView(q) |
| 108 | for _, m := range members { |
| 109 | if err := t.event("", m, wire.EventQuestion, wire.ResourceQuestion, q.ID, q.Revision, "", "", q.Attempt, v); err != nil { |
| 110 | return err |
| 111 | } |
| 112 | } |
| 113 | return nil |
| 114 | } |
| 115 | |
| 116 | // askTarget is the step a question goes to: the newest askable step of |
| 117 | // the specialist the person chose, or, when they did not, Review if the |
| 118 | // question addresses it and it can answer, else Engineering. |
| 119 | func askTarget(steps []stepRecord, chosen, text string) (stepRecord, bool) { |
| 120 | newest := func(specialist string) (stepRecord, bool) { |
| 121 | for i := len(steps) - 1; i >= 0; i-- { |
| 122 | if s := steps[i]; s.Specialist == specialist && s.Askable && s.State == wire.StepDone { |
| 123 | return s, true |
| 124 | } |
| 125 | } |
| 126 | return stepRecord{}, false |
| 127 | } |
| 128 | switch chosen { |
| 129 | case wire.SpecialistEngineering, wire.SpecialistReview: |
| 130 | return newest(chosen) |
| 131 | } |
| 132 | if wire.AddressesReview(text) { |
| 133 | if s, ok := newest(wire.SpecialistReview); ok { |
| 134 | return s, true |
| 135 | } |
| 136 | } |
| 137 | return newest(wire.SpecialistEngineering) |
| 138 | } |
| 139 | |
| 140 | // Ask is POST /tasks/{id}/questions: the task's creator asks one of its |
| 141 | // specialists. The question, its event and (when no other question of |
| 142 | // the task is with the runner) the ask command are one transaction. |
| 143 | func (s *Store) Ask(ctx context.Context, person, taskID string, in wire.AskQuestion) (out wire.Question, err error) { |
| 144 | text, ok := cleanText(in.Text, wire.MaxQuestionText) |
| 145 | if !ok || in.IdempotencyKey == "" || len(in.IdempotencyKey) > 128 || !utf8.ValidString(in.IdempotencyKey) { |
| 146 | return out, ErrInvalid |
| 147 | } |
| 148 | switch in.Specialist { |
| 149 | case "", wire.SpecialistEngineering, wire.SpecialistReview: |
| 150 | default: |
| 151 | return out, ErrInvalid |
| 152 | } |
| 153 | err = s.tx(ctx, func(t *txn) error { |
| 154 | if err := s.authority.CurrentPerson(ctx, t.db); err != nil { |
| 155 | return err |
| 156 | } |
| 157 | k, err := t.loadTask(taskID) |
| 158 | if err != nil { |
| 159 | return err |
| 160 | } |
| 161 | // Only the person who asked for the task asks its specialists, |
| 162 | // on their own runner; teammates read the thread. |
| 163 | if k.Creator != person { |
| 164 | return ErrForbidden |
| 165 | } |
| 166 | if err := t.isOwner(person); err != nil { |
| 167 | return err |
| 168 | } |
| 169 | var prior questionRecord |
| 170 | if err := t.db.Where("task_id = ? AND asker = ? AND idempotency_key = ?", k.ID, person, in.IdempotencyKey).First(&prior).Error; err == nil { |
| 171 | if prior.Text != text || prior.Chosen != in.Specialist { |
| 172 | return ErrConflict |
| 173 | } |
| 174 | out = questionView(prior) |
| 175 | return nil |
| 176 | } else if !errors.Is(err, gorm.ErrRecordNotFound) { |
| 177 | return err |
| 178 | } |
| 179 | if !askOpen(k, t.now()) { |
| 180 | return ErrTaskEnded |
| 181 | } |
| 182 | steps, err := t.steps(k.ID) |
| 183 | if err != nil { |
| 184 | return err |
| 185 | } |
| 186 | target, ok := askTarget(steps, in.Specialist, text) |
| 187 | if !ok || target.Person != person { |
| 188 | return ErrNotAskable |
| 189 | } |
| 190 | // The session lives on the runner that ran the step: offline, the |
| 191 | // person is told so now, naming it (ask again when it is back). |
| 192 | if online, err := t.runnerOnline(person, target.RunnerID); err != nil { |
| 193 | return err |
| 194 | } else if !online { |
| 195 | return &RunnerOfflineError{Label: t.runnerLabel(target.RunnerID)} |
| 196 | } |
| 197 | var n int64 |
| 198 | if err := t.db.Model(&questionRecord{}).Where("task_id = ?", k.ID).Count(&n).Error; err != nil { |
| 199 | return err |
| 200 | } |
| 201 | if n >= wire.MaxQuestions { |
| 202 | return ErrInvalid |
| 203 | } |
| 204 | now := t.now() |
| 205 | q := questionRecord{ID: newID("q_"), TaskID: k.ID, Asker: person, IdempotencyKey: in.IdempotencyKey, StepID: target.ID, Specialist: target.Specialist, Chosen: in.Specialist, Text: text, State: wire.QuestionQueued, Attempt: 1, Revision: 1, CreatedAt: now, UpdatedAt: now, |
| 206 | RunnerID: target.RunnerID, BaseSHA: askBase(k, target), CandidateSHA: target.CandidateSHA} |
| 207 | if target.Specialist == wire.SpecialistEngineering { |
| 208 | // Exactly the attempt asked about: its account and the session |
| 209 | // it kept, whatever the step does after. |
| 210 | q.EngAttempt, q.EngAccount, q.EngSession = target.Attempt, target.Account, target.SessionID |
| 211 | } |
| 212 | if err := t.db.Create(&q).Error; err != nil { |
| 213 | return err |
| 214 | } |
| 215 | if err := t.questionEvent(q); err != nil { |
| 216 | return err |
| 217 | } |
| 218 | if err := t.nextQuestion(k); err != nil { |
| 219 | return err |
| 220 | } |
| 221 | if err := t.db.Where("id = ?", q.ID).First(&q).Error; err != nil { |
| 222 | return err |
| 223 | } |
| 224 | out = questionView(q) |
| 225 | return nil |
| 226 | }) |
| 227 | return out, err |
| 228 | } |
| 229 | |
| 230 | // nextQuestion sends the task's oldest waiting question to the runner, |
| 231 | // unless one is already there. |
| 232 | func (t *txn) nextQuestion(k taskRecord) error { |
| 233 | if !askOpen(k, t.now()) { |
| 234 | return nil |
| 235 | } |
| 236 | var open int64 |
| 237 | if err := t.db.Model(&questionRecord{}).Where("task_id = ? AND dispatched = ? AND state IN ?", k.ID, true, []string{wire.QuestionQueued, wire.QuestionRunning}).Count(&open).Error; err != nil { |
| 238 | return err |
| 239 | } |
| 240 | if open > 0 { |
| 241 | return nil |
| 242 | } |
| 243 | var q questionRecord |
| 244 | err := t.db.Where("task_id = ? AND state = ? AND dispatched = ?", k.ID, wire.QuestionQueued, false).Order("created_at, id").First(&q).Error |
| 245 | if errors.Is(err, gorm.ErrRecordNotFound) { |
| 246 | return nil |
| 247 | } |
| 248 | if err != nil { |
| 249 | return err |
| 250 | } |
| 251 | var s stepRecord |
| 252 | if err := t.db.Where("id = ?", q.StepID).First(&s).Error; err != nil { |
| 253 | return err |
| 254 | } |
| 255 | var p projectRecord |
| 256 | if err := t.db.Where("id = ?", k.ProjectID).First(&p).Error; err != nil { |
| 257 | return err |
| 258 | } |
| 259 | base, candidate := q.BaseSHA, q.CandidateSHA |
| 260 | if q.RunnerID == "" { |
| 261 | // Asked before questions were frozen: the step as it stands. |
| 262 | base, candidate = askBase(k, s), s.CandidateSHA |
| 263 | } |
| 264 | cmd := wire.AskCommand{Person: s.Person, TaskID: k.ID, StepID: s.ID, QuestionID: q.ID, Attempt: q.Attempt, Specialist: s.Specialist, Repo: p.Repo, Branch: k.Branch, BaseSHA: base, CandidateSHA: candidate, Title: k.Title, Text: q.Text, |
| 265 | EngAttempt: q.EngAttempt, EngAccount: q.EngAccount, EngSession: q.EngSession} |
| 266 | // Asked of the runner that holds the session, never another. |
| 267 | if err := t.commandTo(questionRunner(q, s), s.Person, wire.FrameAsk, cmd); err != nil { |
| 268 | return err |
| 269 | } |
| 270 | q.Dispatched = true |
| 271 | return t.saveQuestion(&q) |
| 272 | } |
| 273 | |
| 274 | // askBase is the commit a question's change starts from: an Engineering |
| 275 | // step's own base, else the task's. |
| 276 | func askBase(k taskRecord, s stepRecord) string { |
| 277 | if s.BaseSHA != "" && s.Specialist == wire.SpecialistEngineering { |
| 278 | return s.BaseSHA |
| 279 | } |
| 280 | return k.BaseSHA |
| 281 | } |
| 282 | |
| 283 | // sessionIDPattern is a kept session's id as a runner names it: a Claude |
| 284 | // UUID, a Pi or OpenCode session id. |
| 285 | var sessionIDPattern = regexp.MustCompile(`^[A-Za-z0-9_-]{1,128}$`) |
| 286 | |
| 287 | // keptSessionID is the kept session id a runner reported, as stored: a |
| 288 | // plain id, else none. |
| 289 | func keptSessionID(id string) string { |
| 290 | if !sessionIDPattern.MatchString(id) { |
| 291 | return "" |
| 292 | } |
| 293 | return id |
| 294 | } |
| 295 | |
| 296 | // questionRunner is the runner a question is asked of: the one frozen |
| 297 | // when it was created, or the step's for a question made before. |
| 298 | func questionRunner(q questionRecord, s stepRecord) string { |
| 299 | if q.RunnerID != "" { |
| 300 | return q.RunnerID |
| 301 | } |
| 302 | return s.RunnerID |
| 303 | } |
| 304 | |
| 305 | // Question reads one question. |
| 306 | func (s *Store) Question(ctx context.Context, person, id string) (out wire.Question, err error) { |
| 307 | err = s.read(ctx, func(tx *gorm.DB) error { |
| 308 | if err := s.authority.CurrentPerson(ctx, tx); err != nil { |
| 309 | return err |
| 310 | } |
| 311 | var q questionRecord |
| 312 | if err := tx.Where("id = ?", id).First(&q).Error; errors.Is(err, gorm.ErrRecordNotFound) { |
| 313 | return ErrNotFound |
| 314 | } else if err != nil { |
| 315 | return err |
| 316 | } |
| 317 | out = questionView(q) |
| 318 | return nil |
| 319 | }) |
| 320 | return out, err |
| 321 | } |
| 322 | |
| 323 | // CancelQuestion is POST /questions/{id}/cancel: the asker stops it. One |
| 324 | // still waiting ends at once; one with the runner ends when the runner |
| 325 | // reports the attempt stopped. |
| 326 | func (s *Store) CancelQuestion(ctx context.Context, person, id string) (attempt int64, err error) { |
| 327 | err = s.tx(ctx, func(t *txn) error { |
| 328 | if err := s.authority.CurrentPerson(ctx, t.db); err != nil { |
| 329 | return err |
| 330 | } |
| 331 | var q questionRecord |
| 332 | if err := t.db.Where("id = ?", id).First(&q).Error; errors.Is(err, gorm.ErrRecordNotFound) { |
| 333 | return ErrNotFound |
| 334 | } else if err != nil { |
| 335 | return err |
| 336 | } |
| 337 | if q.Asker != person { |
| 338 | return ErrForbidden |
| 339 | } |
| 340 | if wire.QuestionTerminal(q.State) { |
| 341 | return ErrTerminal |
| 342 | } |
| 343 | attempt = q.Attempt |
| 344 | return t.stopQuestion(&q, "cancelled") |
| 345 | }) |
| 346 | return attempt, err |
| 347 | } |
| 348 | |
| 349 | // stopQuestion cancels a question: at once when the runner never had it, |
| 350 | // else by asking the runner (once). |
| 351 | func (t *txn) stopQuestion(q *questionRecord, reason string) error { |
| 352 | if !q.Dispatched { |
| 353 | q.State, q.Reason = wire.QuestionCancelled, reason |
| 354 | return t.saveQuestion(q) |
| 355 | } |
| 356 | var s stepRecord |
| 357 | if err := t.db.Where("id = ?", q.StepID).First(&s).Error; err != nil { |
| 358 | return err |
| 359 | } |
| 360 | return t.commandTo(questionRunner(*q, s), s.Person, wire.FrameCancelAsk, wire.CancelAskCommand{Person: s.Person, TaskID: q.TaskID, QuestionID: q.ID, Attempt: q.Attempt}) |
| 361 | } |
| 362 | |
| 363 | // ownQuestion loads a question for a runner frame: only the step's |
| 364 | // person's primary runner may move it. |
| 365 | func (t *txn) ownQuestion(l Lease, id string) (questionRecord, error) { |
| 366 | var q questionRecord |
| 367 | if err := t.db.Where("id = ?", id).First(&q).Error; errors.Is(err, gorm.ErrRecordNotFound) { |
| 368 | return q, ErrNotFound |
| 369 | } else if err != nil { |
| 370 | return q, err |
| 371 | } |
| 372 | var s stepRecord |
| 373 | if err := t.db.Where("id = ?", q.StepID).First(&s).Error; err != nil { |
| 374 | return q, err |
| 375 | } |
| 376 | if s.Person != l.Runner.Person { |
| 377 | return q, ErrNotFound |
| 378 | } |
| 379 | // Only the runner that holds the question's session answers for it. |
| 380 | if questionRunner(q, s) != l.Runner.RunnerID { |
| 381 | return q, ErrRefused |
| 382 | } |
| 383 | return q, nil |
| 384 | } |
| 385 | |
| 386 | func isQuestionID(id string) bool { return strings.HasPrefix(id, "q_") } |
| 387 | |
| 388 | // questionDelta streams answer text to every member, like a turn's. |
| 389 | func (t *txn) questionDelta(l Lease, d *wire.DeltaReport) error { |
| 390 | q, err := t.ownQuestion(l, d.TurnID) |
| 391 | if errors.Is(err, ErrNotFound) { |
| 392 | return nil |
| 393 | } |
| 394 | if err != nil { |
| 395 | return err |
| 396 | } |
| 397 | if wire.QuestionTerminal(q.State) || d.Attempt != q.Attempt || d.Offset < 0 || d.Text == "" || len(d.Text) > wire.MaxMessageBytes { |
| 398 | return nil |
| 399 | } |
| 400 | members, err := t.members() |
| 401 | if err != nil { |
| 402 | return err |
| 403 | } |
| 404 | for _, m := range members { |
| 405 | if err := t.event("", m, wire.EventDelta, wire.ResourceQuestion, q.ID, 0, q.ID, "", q.Attempt, wire.Delta{TurnID: q.ID, Offset: d.Offset, Text: d.Text}); err != nil { |
| 406 | return err |
| 407 | } |
| 408 | } |
| 409 | return nil |
| 410 | } |
| 411 | |
| 412 | // questionTools are the activities an answering session may show: it |
| 413 | // reads the code or looks at the change, or thinks. |
| 414 | var questionTools = map[string]bool{wire.ToolReadFile: true, wire.ToolSearchCode: true, ToolReadChange: true} |
| 415 | |
| 416 | // ToolReadChange is the activity of an answering session's read-only git |
| 417 | // tools (git_log, git_diff, git_show). |
| 418 | const ToolReadChange = "read_change" |
| 419 | |
| 420 | func (t *txn) questionActivity(l Lease, a *wire.ActivityReport) error { |
| 421 | q, err := t.ownQuestion(l, a.TurnID) |
| 422 | if errors.Is(err, ErrNotFound) { |
| 423 | return nil |
| 424 | } |
| 425 | if err != nil { |
| 426 | return err |
| 427 | } |
| 428 | if wire.QuestionTerminal(q.State) || a.Attempt != q.Attempt { |
| 429 | return nil |
| 430 | } |
| 431 | tool := "" |
| 432 | switch a.Kind { |
| 433 | case wire.ActivityThink: |
| 434 | case wire.ActivityTool: |
| 435 | tool = "other" |
| 436 | if questionTools[a.Tool] { |
| 437 | tool = a.Tool |
| 438 | } |
| 439 | default: |
| 440 | return nil |
| 441 | } |
| 442 | v := wire.Activity{TurnID: q.ID, Attempt: q.Attempt, Kind: a.Kind, Tool: tool} |
| 443 | members, err := t.members() |
| 444 | if err != nil { |
| 445 | return err |
| 446 | } |
| 447 | for _, m := range members { |
| 448 | subject := "" |
| 449 | if tool == ToolReadChange { |
| 450 | subject = t.activityTask(m, q.TaskID, true) |
| 451 | } |
| 452 | if t.s.authority.ActivityLabel != nil { |
| 453 | v.Label = t.s.authority.ActivityLabel(v, wire.ResourceQuestion, subject) |
| 454 | } |
| 455 | if err := t.event("", m, wire.EventActivity, wire.ResourceQuestion, q.ID, 0, q.ID, "", q.Attempt, v); err != nil { |
| 456 | return err |
| 457 | } |
| 458 | } |
| 459 | return nil |
| 460 | } |
| 461 | |
| 462 | // answer applies the runner's report on a question: only the current |
| 463 | // attempt, only forward; an ended question lets the task's next one go. |
| 464 | func (t *txn) answer(l Lease, v *wire.AnswerReport) error { |
| 465 | if !wire.AnswerReasons[v.Reason] { |
| 466 | return ErrInvalid |
| 467 | } |
| 468 | q, err := t.ownQuestion(l, v.QuestionID) |
| 469 | if err != nil { |
| 470 | return err |
| 471 | } |
| 472 | if q.TaskID != v.TaskID { |
| 473 | return ErrNotFound |
| 474 | } |
| 475 | if wire.QuestionTerminal(q.State) || v.Attempt != q.Attempt { |
| 476 | return nil |
| 477 | } |
| 478 | switch v.State { |
| 479 | case wire.QuestionRunning: |
| 480 | if q.State == wire.QuestionRunning { |
| 481 | return nil |
| 482 | } |
| 483 | q.State, q.Reason = wire.QuestionRunning, "" |
| 484 | return t.saveQuestion(&q) |
| 485 | case wire.QuestionQueued: |
| 486 | // Held by its metered connection's guard (connectors spec §7): |
| 487 | // it waits on that connection, never moved; the reason says why. |
| 488 | if v.Reason != wire.HoldBusy && v.Reason != wire.HoldBudget && v.Reason != wire.HoldSpendUnknown { |
| 489 | return ErrInvalid |
| 490 | } |
| 491 | if q.State != wire.QuestionQueued || q.Reason == v.Reason { |
| 492 | return nil |
| 493 | } |
| 494 | q.Reason = v.Reason |
| 495 | return t.saveQuestion(&q) |
| 496 | case wire.QuestionAnswered: |
| 497 | answer := strings.TrimSpace(v.Text) |
| 498 | if answer == "" { |
| 499 | q.State, q.Reason = wire.QuestionFailed, "provider_failed" |
| 500 | break |
| 501 | } |
| 502 | q.State, q.Reason, q.Answer = wire.QuestionAnswered, "", clipText(answer, wire.MaxAnswerText) |
| 503 | round, err := t.stepRound(q.StepID) |
| 504 | if err != nil { |
| 505 | return err |
| 506 | } |
| 507 | if err := t.recordUsage(l, q.Asker, "ask", q.TaskID, q.ID, "", round, v.Usage); err != nil { |
| 508 | return err |
| 509 | } |
| 510 | if v.Timing != nil { |
| 511 | raw, _ := json.Marshal(v.Timing) |
| 512 | q.Timing = string(raw) |
| 513 | } |
| 514 | case wire.QuestionFailed, wire.QuestionCancelled: |
| 515 | q.State, q.Reason = v.State, firstSet(v.Reason, v.State) |
| 516 | // What an unanswered attempt used is recorded too. |
| 517 | round, err := t.stepRound(q.StepID) |
| 518 | if err != nil { |
| 519 | return err |
| 520 | } |
| 521 | if err := t.recordUsage(l, q.Asker, "ask", q.TaskID, q.ID, "", round, v.Usage); err != nil { |
| 522 | return err |
| 523 | } |
| 524 | default: |
| 525 | return ErrInvalid |
| 526 | } |
| 527 | if err := t.saveQuestion(&q); err != nil { |
| 528 | return err |
| 529 | } |
| 530 | k, err := t.loadTask(q.TaskID) |
| 531 | if err != nil { |
| 532 | return err |
| 533 | } |
| 534 | return t.nextQuestion(k) |
| 535 | } |
| 536 | |
| 537 | // syncQuestions settles questions the person's runner no longer holds, |
| 538 | // like syncSteps: a question whose ask command was acked but which the |
| 539 | // runner does not list has ended without an answer. |
| 540 | func (t *txn) syncQuestions(l Lease, held []wire.AskRun) error { |
| 541 | have := map[string]bool{} |
| 542 | for _, h := range held { |
| 543 | have[h.QuestionID+"/"+itoa64(h.Attempt)] = true |
| 544 | } |
| 545 | var rows []questionRecord |
| 546 | if err := t.db.Where("dispatched = ? AND state IN ?", true, []string{wire.QuestionQueued, wire.QuestionRunning}).Find(&rows).Error; err != nil { |
| 547 | return err |
| 548 | } |
| 549 | for i := range rows { |
| 550 | q := rows[i] |
| 551 | if have[q.ID+"/"+itoa64(q.Attempt)] { |
| 552 | continue |
| 553 | } |
| 554 | var s stepRecord |
| 555 | if err := t.db.Where("id = ?", q.StepID).First(&s).Error; err != nil { |
| 556 | return err |
| 557 | } |
| 558 | if s.Person != l.Runner.Person || questionRunner(q, s) != l.Runner.RunnerID { |
| 559 | continue |
| 560 | } |
| 561 | var unacked int64 |
| 562 | if err := t.db.Model(&commandRecord{}).Where("person = ? AND kind = ? AND acked_at IS NULL AND body LIKE ?", s.Person, wire.FrameAsk, `%"question_id":"`+q.ID+`","attempt":`+itoa64(q.Attempt)+`,%`).Count(&unacked).Error; err != nil { |
| 563 | return err |
| 564 | } |
| 565 | if unacked != 0 { |
| 566 | continue |
| 567 | } |
| 568 | q.State, q.Reason = wire.QuestionFailed, "interrupted" |
| 569 | if err := t.saveQuestion(&q); err != nil { |
| 570 | return err |
| 571 | } |
| 572 | k, err := t.loadTask(q.TaskID) |
| 573 | if err != nil { |
| 574 | return err |
| 575 | } |
| 576 | if err := t.nextQuestion(k); err != nil { |
| 577 | return err |
| 578 | } |
| 579 | } |
| 580 | return nil |
| 581 | } |
| 582 | |
| 583 | // taskEnded runs once when a task becomes done or cancelled: its open |
| 584 | // questions stop, and the runner may delete the sessions it kept. |
| 585 | func (t *txn) taskEnded(k taskRecord) error { |
| 586 | if k.Stage == wire.StageDone { |
| 587 | // Done (merged): its specialists can still be asked about their |
| 588 | // work for KeepMergedSessions (Paul, 2026-11-08); the runner keeps |
| 589 | // their sessions until then and removes them after. |
| 590 | keep := t.now().Add(wire.KeepMergedSessions) |
| 591 | return t.forgetTask(k, &keep) |
| 592 | } |
| 593 | var open []questionRecord |
| 594 | if err := t.db.Where("task_id = ? AND state IN ?", k.ID, []string{wire.QuestionQueued, wire.QuestionRunning}).Find(&open).Error; err != nil { |
| 595 | return err |
| 596 | } |
| 597 | for i := range open { |
| 598 | if err := t.stopQuestion(&open[i], "task_ended"); err != nil { |
| 599 | return err |
| 600 | } |
| 601 | } |
| 602 | return t.forgetTask(k, nil) |
| 603 | } |
| 604 | |
| 605 | // forgetTask tells the runners that kept the task's sessions to drop |
| 606 | // them, now or after keep, and its preview to come down unless it is held |
| 607 | // for a Publish not yet answered (previewHeld; releasePreview tells them |
| 608 | // again once it is). |
| 609 | func (t *txn) forgetTask(k taskRecord, keep *time.Time) error { |
| 610 | var persons []string |
| 611 | if err := t.db.Model(&stepRecord{}).Distinct("person").Where("task_id = ?", k.ID).Pluck("person", &persons).Error; err != nil { |
| 612 | return err |
| 613 | } |
| 614 | steps, err := t.steps(k.ID) |
| 615 | if err != nil { |
| 616 | return err |
| 617 | } |
| 618 | held, err := t.previewHeld(k, steps) |
| 619 | if err != nil { |
| 620 | return err |
| 621 | } |
| 622 | for _, p := range persons { |
| 623 | cmd := wire.ForgetTaskCommand{Person: p, TaskID: k.ID, KeepUntil: keep, KeepPreview: held} |
| 624 | if err := t.command(p, wire.FrameForgetTask, cmd); err != nil { |
| 625 | return err |
| 626 | } |
| 627 | // A worker that ran the task's steps holds what they kept there |
| 628 | // (a Mac's Engineering sessions and candidates, Mac runners slice |
| 629 | // F): it is told too. |
| 630 | primary, err := t.s.authority.PrimaryRunner(t.db, p) |
| 631 | if err != nil { |
| 632 | return err |
| 633 | } |
| 634 | sent := map[string]bool{primary: true, "": true} |
| 635 | for _, s := range steps { |
| 636 | if s.Person != p || sent[s.RunnerID] { |
| 637 | continue |
| 638 | } |
| 639 | sent[s.RunnerID] = true |
| 640 | if err := t.commandTo(s.RunnerID, p, wire.FrameForgetTask, cmd); err != nil { |
| 641 | return err |
| 642 | } |
| 643 | } |
| 644 | } |
| 645 | return nil |
| 646 | } |
| 647 | |
| 648 | // askOpen reports whether the task's specialists may be asked: until it |
| 649 | // ends, and for KeepMergedSessions after it is done; never once cancelled. |
| 650 | func askOpen(k taskRecord, now time.Time) bool { |
| 651 | switch { |
| 652 | case k.CancelRequested || k.Stage == wire.StageCancelled: |
| 653 | return false |
| 654 | case k.Stage == wire.StageDone: |
| 655 | return k.DoneAt != nil && now.Before(k.DoneAt.Add(wire.KeepMergedSessions)) |
| 656 | } |
| 657 | return true |
| 658 | } |
| 659 | |