| 1 | package chat |
| 2 | |
| 3 | import ( |
| 4 | "encoding/json" |
| 5 | "errors" |
| 6 | "slices" |
| 7 | "strings" |
| 8 | "time" |
| 9 | |
| 10 | "amadan.net/oficina/equipo/internal/equipo/mergegate" |
| 11 | "amadan.net/oficina/equipo/internal/wire" |
| 12 | "gorm.io/gorm" |
| 13 | ) |
| 14 | |
| 15 | // Outcome cards (spec §5, Cards; the jobs design's one voice). When a |
| 16 | // hand-off's task or turn raises a go-ahead or a Publish for the |
| 17 | // hand-off's person, the Assistant lane gets one card that points at it, |
| 18 | // in the instance's words: |
| 19 | // |
| 20 | // - a merge card: an outcome card asking for a go-ahead with Equipo's |
| 21 | // reason in plain words, one option per the merge card's and the |
| 22 | // preview while it is up; |
| 23 | // - a publish card: an outcome card asking to publish the site, with |
| 24 | // its preview, held up until the answer (previewHeld); once answered, |
| 25 | // what became of it, and the site's address once it has one. |
| 26 | // |
| 27 | // Nothing else of the team's reaches the person: a question from the |
| 28 | // Coordinator's ask_person, or any other card that stops the work |
| 29 | // (blocksWork), is the Assistant's to hear of (teamAsks), as a note. A |
| 30 | // question or needs-you card mirrored before that (slice 1) still |
| 31 | // follows its team card, as below. |
| 32 | // |
| 33 | // The card follows its team card: every save of the team card copies its |
| 34 | // state and result and moves the card's revision. Answering it answers |
| 35 | // the team card through that card's own path, as the person, at the team |
| 36 | // card's revision, so the team card's rules hold (the merge gate, its |
| 37 | // creator, an owner). No tool reaches answerOutcome: the model answers |
| 38 | // nothing. The card never quotes the team card, and names no task, |
| 39 | // repository, branch or SHA. |
| 40 | |
| 41 | const auditAssistantOutcome = "assistant.outcome" |
| 42 | |
| 43 | // blocksWork: an open team card that waits on the person for something |
| 44 | // only Equipo can show them. |
| 45 | func blocksWork(kind, state string) bool { |
| 46 | switch kind { |
| 47 | case wire.CardHome: |
| 48 | return state == wire.CardHomeAsk |
| 49 | case wire.CardAccess, wire.CardDirection, wire.CardSpecialist, wire.CardResearchSources, wire.CardResearchInventory, wire.CardMergeShips, wire.CardMergePolicy, wire.CardMakerRemoved: |
| 50 | return state == wire.CardOpen |
| 51 | } |
| 52 | return false |
| 53 | } |
| 54 | |
| 55 | // mirrorKind is the Assistant card a new team card raises ("" for none): |
| 56 | // only an open go-ahead or Publish, for new and legacy hand-offs alike. |
| 57 | func mirrorKind(src cardRecord) string { |
| 58 | if (src.Kind == wire.CardMerge || src.Kind == wire.CardPublish) && src.State == wire.CardOpen { |
| 59 | return wire.CardOutcome |
| 60 | } |
| 61 | return "" |
| 62 | } |
| 63 | |
| 64 | // asksPerson: an open team question, or a card that stops the work: the |
| 65 | // Assistant hears of it (teamAsks), and no card is raised for it. |
| 66 | func asksPerson(src cardRecord) bool { |
| 67 | return src.Kind == wire.CardQuestion && src.State == wire.CardOpen || blocksWork(src.Kind, src.State) |
| 68 | } |
| 69 | |
| 70 | // mirrorCard keeps the Assistant's card for a Coordinator card (cardEvent): |
| 71 | // raised once, for a card on the turn or task of one of its person's |
| 72 | // hand-offs, and the Assistant told (handoffChanged); afterwards brought |
| 73 | // up to date on each of the team card's saves. A card that asks the |
| 74 | // person something raises none: the Assistant is told (teamAsks). |
| 75 | func (t *txn) mirrorCard(src cardRecord) error { |
| 76 | if !wire.CoordinatorRole(src.Lane) { |
| 77 | return nil |
| 78 | } |
| 79 | var m cardRecord |
| 80 | if err := t.db.Where("source_card = ? AND person = ?", src.ID, src.Person).Limit(1).Find(&m).Error; err != nil { |
| 81 | return err |
| 82 | } |
| 83 | if m.ID != "" { |
| 84 | if err := t.fillMirror(&m, src); err != nil { |
| 85 | return err |
| 86 | } |
| 87 | // Written here, not through saveCard: the card follows a change |
| 88 | // already made (housekeeping included), and makes none. |
| 89 | m.Revision++ |
| 90 | m.UpdatedAt = t.now() |
| 91 | if err := t.db.Model(&cardRecord{}).Where("id = ?", m.ID).Select("state", "question", "options", "links", "result", "revision", "updated_at").Updates(&m).Error; err != nil { |
| 92 | return err |
| 93 | } |
| 94 | if err := t.cardEvent(m); err != nil || m.HandoffID == "" { |
| 95 | return err |
| 96 | } |
| 97 | // Its job may be ready no more, or show the preview now. |
| 98 | var h handoffRecord |
| 99 | if err := t.db.Where("id = ? AND person = ?", m.HandoffID, m.Person).Limit(1).Find(&h).Error; err != nil || h.ID == "" { |
| 100 | return err |
| 101 | } |
| 102 | return t.projectJob(h) |
| 103 | } |
| 104 | kind := mirrorKind(src) |
| 105 | if kind == "" { |
| 106 | if asksPerson(src) { |
| 107 | return t.teamAsks(src) |
| 108 | } |
| 109 | // A card that stopped the work, answered or withdrawn: its job |
| 110 | // may work again. |
| 111 | if !blocksWork(src.Kind, wire.CardOpen) && !blocksWork(src.Kind, wire.CardHomeAsk) { |
| 112 | return nil |
| 113 | } |
| 114 | h, ok, err := t.handoffFor(src) |
| 115 | if err != nil || !ok { |
| 116 | return err |
| 117 | } |
| 118 | return t.projectJob(h) |
| 119 | } |
| 120 | if src.Kind == wire.CardMerge { |
| 121 | // Never a go-ahead for work that is already in. |
| 122 | if in, err := t.landed(src.TaskID); err != nil || in { |
| 123 | return err |
| 124 | } |
| 125 | } |
| 126 | h, ok, err := t.handoffFor(src) |
| 127 | if err != nil || !ok { |
| 128 | return err |
| 129 | } |
| 130 | now := t.now() |
| 131 | m = cardRecord{ID: newID("c_"), Person: src.Person, Kind: kind, SourceCard: src.ID, Options: "[]", Revision: 1, CreatedAt: now, UpdatedAt: now, Lane: wire.LaneAssistant, HandoffID: h.ID} |
| 132 | if err := t.fillMirror(&m, src); err != nil { |
| 133 | return err |
| 134 | } |
| 135 | if err := t.db.Create(&m).Error; err != nil { |
| 136 | return err |
| 137 | } |
| 138 | // The Assistant is told and the job card made ready first: the card |
| 139 | // names its job card, which Base has then (a legacy hand-off's is |
| 140 | // made now). |
| 141 | if err := t.handoffChanged(h, true); err != nil { |
| 142 | return err |
| 143 | } |
| 144 | return t.cardEvent(m) |
| 145 | } |
| 146 | |
| 147 | // teamAsks tells the Assistant of a hand-off's question, or of a card |
| 148 | // that stops its work (one voice): the job's note, and no card. |
| 149 | func (t *txn) teamAsks(src cardRecord) error { |
| 150 | h, ok, err := t.handoffFor(src) |
| 151 | if err != nil || !ok { |
| 152 | return err |
| 153 | } |
| 154 | return t.handoffChanged(h, true) |
| 155 | } |
| 156 | |
| 157 | // handoffFor is the hand-off a team card belongs to, only ever one of the |
| 158 | // card's person's, open or stopping: a cancelled request raises nothing. |
| 159 | // A card in a job thread is that job's alone, by its lane (J4): its |
| 160 | // cards follow the work the thread recorded. A card in the person's own |
| 161 | // conversation goes by slice 1's rules, which find only legacy hand-offs |
| 162 | // (J7): a new one's work is never there, and work of the person's own |
| 163 | // that it joined stays theirs. By its turn, while that hand-off is open |
| 164 | // (a card its turns raise after team_cancel is not the request's); else |
| 165 | // by its task: someone else's hand-off may follow the same task |
| 166 | // (add_report), and its card is not theirs to answer. A card of a |
| 167 | // project's alone (the ships question names no turn or task) belongs to |
| 168 | // the person's oldest followed hand-off that follows open work in that |
| 169 | // project: that work waits on it. One card either way: it is the person's |
| 170 | // to answer once. |
| 171 | func (t *txn) handoffFor(src cardRecord) (handoffRecord, bool, error) { |
| 172 | var h handoffRecord |
| 173 | followed := []string{handoffOpen, handoffStopping} |
| 174 | if id, ok := wire.JobOf(src.Lane); ok { |
| 175 | err := t.db.Where("id = ? AND person = ? AND state IN ?", id, src.Person, followed).Limit(1).Find(&h).Error |
| 176 | return h, err == nil && h.ID != "", err |
| 177 | } |
| 178 | if src.Lane != "" { |
| 179 | return h, false, nil |
| 180 | } |
| 181 | const legacy = "person = ? AND coalesce(lane, '') = '' AND " |
| 182 | if src.TurnID != "" { |
| 183 | if err := t.db.Where(legacy+"state = ? AND id IN (SELECT handoff_id FROM chat_handoff_turns WHERE turn_id = ?)", src.Person, handoffOpen, src.TurnID).Limit(1).Find(&h).Error; err != nil || h.ID != "" { |
| 184 | return h, h.ID != "", err |
| 185 | } |
| 186 | } |
| 187 | if src.TaskID != "" { |
| 188 | if err := t.db.Where(legacy+"state IN ? AND id IN (SELECT handoff_id FROM chat_handoff_tasks WHERE task_id = ?)", src.Person, followed, src.TaskID).Order("created_at").Limit(1).Find(&h).Error; err != nil { |
| 189 | return h, false, err |
| 190 | } |
| 191 | } |
| 192 | if src.TurnID == "" && src.TaskID == "" && src.ProjectID != "" { |
| 193 | open := "SELECT ht.handoff_id FROM chat_handoff_tasks ht JOIN chat_tasks k ON k.id = ht.task_id WHERE k.project_id = ? AND k.stage NOT IN ?" |
| 194 | if err := t.db.Where(legacy+"state IN ? AND id IN ("+open+")", src.Person, followed, src.ProjectID, []string{wire.StageDone, wire.StageCancelled}).Order("created_at").Limit(1).Find(&h).Error; err != nil { |
| 195 | return h, false, err |
| 196 | } |
| 197 | } |
| 198 | return h, h.ID != "", nil |
| 199 | } |
| 200 | |
| 201 | // fillMirror sets the Assistant card's words, options, links, state and |
| 202 | // result from its team card. The words and options are those of the team |
| 203 | // card while it is open, and stay as they were once it is not. Its links |
| 204 | // are those that do not change on their own (Equipo's, a published |
| 205 | // site's); a preview, which goes when the task ends or it expires, is |
| 206 | // read with the card (mirrorView). |
| 207 | func (t *txn) fillMirror(m *cardRecord, src cardRecord) error { |
| 208 | if src.Kind == wire.CardMerge { |
| 209 | // A go-ahead whose work has gone in asks nothing any more, however |
| 210 | // it went in (the person's tap, Equipo's own merge, by hand on the |
| 211 | // hub): closed words and nothing to answer. No link is stored; a |
| 212 | // preview held for a Publish still unanswered is read with the |
| 213 | // card (mirrorView). |
| 214 | in, err := t.landed(src.TaskID) |
| 215 | if err != nil { |
| 216 | return err |
| 217 | } |
| 218 | if in { |
| 219 | m.Question, m.Result, m.Links = t.copy("assistant.outcome.resolved"), t.copy("assistant.job.detail.done"), "[]" |
| 220 | m.State = wire.CardResolved |
| 221 | if src.State == wire.CardAnswered { |
| 222 | m.State = wire.CardAnswered |
| 223 | } |
| 224 | return nil |
| 225 | } |
| 226 | } |
| 227 | open := src.State == wire.CardOpen || src.Kind == wire.CardHome && src.State == wire.CardHomeAsk |
| 228 | links := []wire.CardLink{} |
| 229 | var options []wire.CardOption |
| 230 | switch src.Kind { |
| 231 | case wire.CardQuestion: |
| 232 | if open { |
| 233 | var values []string |
| 234 | if src.Options != "" { |
| 235 | if err := json.Unmarshal([]byte(src.Options), &values); err != nil { |
| 236 | return err |
| 237 | } |
| 238 | } |
| 239 | options = []wire.CardOption{} |
| 240 | for _, v := range values { |
| 241 | options = append(options, wire.CardOption{Value: v, Label: v}) |
| 242 | } |
| 243 | m.Question = src.Question |
| 244 | } |
| 245 | case wire.CardMerge: |
| 246 | if open { |
| 247 | question, opts, err := t.mergeOutcome(src) |
| 248 | if err != nil { |
| 249 | return err |
| 250 | } |
| 251 | m.Question, options = question, opts |
| 252 | } |
| 253 | case wire.CardPublish: |
| 254 | if open { |
| 255 | m.Question = t.copy("assistant.outcome.publish_question") |
| 256 | options = []wire.CardOption{{Value: wire.ChoicePublish, Label: t.copy("assistant.outcome.publish_option")}, {Value: wire.ChoiceNotNow, Label: t.copy("assistant.outcome.publish_not_now")}} |
| 257 | } |
| 258 | default: |
| 259 | m.Question = t.copy("assistant.outcome.needs_you") |
| 260 | links = append(links, wire.CardLink{Label: t.copy("assistant.outcome.open"), URL: strings.TrimSuffix(t.s.authority.Origin, "/") + "/"}) |
| 261 | } |
| 262 | if options != nil { |
| 263 | raw, _ := json.Marshal(options) |
| 264 | m.Options = string(raw) |
| 265 | } |
| 266 | switch { |
| 267 | case open: |
| 268 | m.State, m.Result = wire.CardOpen, "" |
| 269 | case src.State == wire.CardAnswered && (src.Kind == wire.CardQuestion || src.Kind == wire.CardMerge): |
| 270 | result, err := t.chosen(*m, src) |
| 271 | if err != nil { |
| 272 | return err |
| 273 | } |
| 274 | m.State, m.Result = wire.CardAnswered, result |
| 275 | case src.State == wire.CardAnswered && src.Kind == wire.CardPublish: |
| 276 | result, site, err := t.publishOutcome(src) |
| 277 | if err != nil { |
| 278 | return err |
| 279 | } |
| 280 | if site != "" { |
| 281 | links = append(links, wire.CardLink{Label: t.copy("assistant.outcome.publish_site"), URL: site}) |
| 282 | } |
| 283 | m.State, m.Result = wire.CardAnswered, result |
| 284 | default: |
| 285 | m.State, m.Result = wire.CardResolved, t.copy("assistant.outcome.resolved") |
| 286 | } |
| 287 | raw, _ := json.Marshal(links) |
| 288 | m.Links = string(raw) |
| 289 | return nil |
| 290 | } |
| 291 | |
| 292 | // landed: the task's work is on its default branch. A task is done only |
| 293 | // when its merge was confirmed (mergeDone) or the runner's watch saw it |
| 294 | // land (merged); an exploration is done once built as another task, |
| 295 | // which merges nothing of its own. |
| 296 | func (t *txn) landed(taskID string) (bool, error) { |
| 297 | if taskID == "" { |
| 298 | return false, nil |
| 299 | } |
| 300 | var k taskRecord |
| 301 | if err := t.db.Where("id = ?", taskID).Limit(1).Find(&k).Error; err != nil || k.ID == "" { |
| 302 | return false, err |
| 303 | } |
| 304 | return k.Stage == wire.StageDone && k.BuiltAs == "", nil |
| 305 | } |
| 306 | |
| 307 | // publishOutcome is what became of the person's answer on a publish |
| 308 | // card, and the site's address once there is one: declined; publishing |
| 309 | // until its step ends; then published, sent and not confirmed, or not |
| 310 | // published. A card asked again after a failed publish is a newer card: |
| 311 | // an older one's publish failed. |
| 312 | func (t *txn) publishOutcome(src cardRecord) (string, string, error) { |
| 313 | if src.Choice != wire.ChoicePublish { |
| 314 | return t.copy("assistant.outcome.publish_declined"), "", nil |
| 315 | } |
| 316 | var newest cardRecord |
| 317 | if err := t.db.Where("task_id = ? AND kind = ?", src.TaskID, wire.CardPublish).Order("created_at DESC, rowid DESC").Limit(1).Find(&newest).Error; err != nil || newest.ID != src.ID { |
| 318 | return t.copy("assistant.outcome.publish_failed"), "", err |
| 319 | } |
| 320 | steps, err := t.steps(src.TaskID) |
| 321 | if err != nil { |
| 322 | return "", "", err |
| 323 | } |
| 324 | for i := len(steps) - 1; i >= 0; i-- { |
| 325 | s := steps[i] |
| 326 | if s.Specialist != wire.SpecialistPublish { |
| 327 | continue |
| 328 | } |
| 329 | p := decodePublish(s.Publish) |
| 330 | switch { |
| 331 | case !wire.StepTerminal(s.State): |
| 332 | return t.copy("assistant.outcome.publish_publishing"), "", nil |
| 333 | case s.State == wire.StepDone && p != nil && p.Outcome == wire.PublishPublished: |
| 334 | return t.copy("assistant.outcome.publish_published"), p.URL, nil |
| 335 | case s.State == wire.StepDone && p != nil: |
| 336 | return t.copy("assistant.outcome.publish_unconfirmed"), p.URL, nil |
| 337 | case s.State == wire.StepDone: |
| 338 | return t.copy("assistant.outcome.publish_unconfirmed"), "", nil |
| 339 | } |
| 340 | return t.copy("assistant.outcome.publish_failed"), "", nil |
| 341 | } |
| 342 | return t.copy("assistant.outcome.publish_publishing"), "", nil |
| 343 | } |
| 344 | |
| 345 | // chosen is the label of the team card's answer on the Assistant card: a |
| 346 | // question's answer is its own label. |
| 347 | func (t *txn) chosen(m cardRecord, src cardRecord) (string, error) { |
| 348 | var options []wire.CardOption |
| 349 | if m.Options != "" { |
| 350 | if err := json.Unmarshal([]byte(m.Options), &options); err != nil { |
| 351 | return "", err |
| 352 | } |
| 353 | } |
| 354 | if i := slices.IndexFunc(options, func(o wire.CardOption) bool { return o.Value == src.Choice }); i >= 0 { |
| 355 | return options[i].Label, nil |
| 356 | } |
| 357 | if src.Kind == wire.CardQuestion { |
| 358 | return src.Choice, nil |
| 359 | } |
| 360 | return t.copy("assistant.outcome.option." + src.Choice), nil |
| 361 | } |
| 362 | |
| 363 | // mergeOutcome is a merge card's go-ahead question and options: Equipo's |
| 364 | // reason for asking in one plain sentence, never the merge card's words; |
| 365 | // one option per the merge card's, by its value. An option with no words |
| 366 | // is left out. |
| 367 | func (t *txn) mergeOutcome(src cardRecord) (string, []wire.CardOption, error) { |
| 368 | var values []string |
| 369 | if err := json.Unmarshal([]byte(src.Options), &values); err != nil { |
| 370 | return "", nil, err |
| 371 | } |
| 372 | options := []wire.CardOption{} |
| 373 | for _, v := range values { |
| 374 | if label := t.copy("assistant.outcome.option." + v); label != "" { |
| 375 | options = append(options, wire.CardOption{Value: v, Label: label}) |
| 376 | } |
| 377 | } |
| 378 | reason, err := t.mergeReason(src.TaskID) |
| 379 | if err != nil { |
| 380 | return "", nil, err |
| 381 | } |
| 382 | question := t.copy("assistant.outcome.merge_plain") |
| 383 | if why := t.copy("assistant.outcome.reason." + reason); reason != "" && why != "" { |
| 384 | question = t.words("assistant.outcome.merge", why) |
| 385 | } |
| 386 | return question, options, nil |
| 387 | } |
| 388 | |
| 389 | // mergeReason is the first rule that did not hold in the newest decision |
| 390 | // that asked about the task's asked SHA ("" when none is known). |
| 391 | func (t *txn) mergeReason(taskID string) (string, error) { |
| 392 | k, err := t.loadTask(taskID) |
| 393 | if err != nil { |
| 394 | return "", err |
| 395 | } |
| 396 | var a mergeAuditRecord |
| 397 | if err := t.db.Where("task_id = ? AND candidate_sha = ? AND kind IN ? AND class = ?", k.ID, k.MergeAsked, []string{auditDecision, auditRefresh}, mergegate.ClassAsk).Order("created_at DESC, rowid DESC").Limit(1).Find(&a).Error; err != nil || a.ID == "" { |
| 398 | return "", err |
| 399 | } |
| 400 | var rs []mergegate.Criterion |
| 401 | if err := json.Unmarshal([]byte(a.Reasons), &rs); err != nil { |
| 402 | return "", err |
| 403 | } |
| 404 | for _, r := range rs { |
| 405 | if !r.OK { |
| 406 | return r.Name, nil |
| 407 | } |
| 408 | } |
| 409 | return "", nil |
| 410 | } |
| 411 | |
| 412 | // mirrorView fills an Assistant card from its own options, links and |
| 413 | // result, both lists never null, the job card of its hand-off (a card |
| 414 | // mirrored before job cards names none), and a merge or publish card's |
| 415 | // preview as it is now: only while it is up (previewLink: until the task |
| 416 | // ends, held past it for a Publish not yet answered, or its expiry). |
| 417 | func (t *txn) mirrorView(v *wire.AssistantCard, c cardRecord) error { |
| 418 | v.Result = c.Result |
| 419 | job, err := t.jobOf(c) |
| 420 | if err != nil { |
| 421 | return err |
| 422 | } |
| 423 | v.Job = job |
| 424 | if c.Options != "" { |
| 425 | if err := json.Unmarshal([]byte(c.Options), &v.Options); err != nil { |
| 426 | return err |
| 427 | } |
| 428 | } |
| 429 | if c.Links != "" { |
| 430 | if err := json.Unmarshal([]byte(c.Links), &v.Links); err != nil { |
| 431 | return err |
| 432 | } |
| 433 | } |
| 434 | if v.Options == nil { |
| 435 | v.Options = []wire.CardOption{} |
| 436 | } |
| 437 | if v.Links == nil { |
| 438 | v.Links = []wire.CardLink{} |
| 439 | } |
| 440 | if c.Kind != wire.CardOutcome { |
| 441 | return nil |
| 442 | } |
| 443 | var src cardRecord |
| 444 | if err := t.db.Where("id = ? AND person = ?", c.SourceCard, c.Person).Limit(1).Find(&src).Error; err != nil { |
| 445 | return err |
| 446 | } |
| 447 | switch src.Kind { |
| 448 | case wire.CardMerge: |
| 449 | // A merge card's only link is its preview, and that is never read |
| 450 | // from what is stored: a stored one may be gone. |
| 451 | v.Links = []wire.CardLink{} |
| 452 | case wire.CardPublish: |
| 453 | // A publish card stores only its site's address. |
| 454 | default: |
| 455 | return nil |
| 456 | } |
| 457 | preview, err := t.taskPreview(src.TaskID) |
| 458 | if err != nil { |
| 459 | return err |
| 460 | } |
| 461 | if preview != "" { |
| 462 | v.Links = append(v.Links, wire.CardLink{Label: t.copy("assistant.outcome.preview"), URL: preview}) |
| 463 | } |
| 464 | return nil |
| 465 | } |
| 466 | |
| 467 | // touchOutcomes moves the Assistant cards of a task's merge cards that |
| 468 | // are no longer open when the task ends, so the person's lane hears that |
| 469 | // the preview went, and, when the task went in, that it did (landed); |
| 470 | // the open ones change with their merge card, which withdrawMergeCards |
| 471 | // resolves. |
| 472 | func (t *txn) touchOutcomes(k taskRecord) error { |
| 473 | var rows []cardRecord |
| 474 | if err := t.db.Where("lane = ? AND state <> ? AND source_card IN (SELECT id FROM chat_cards WHERE task_id = ? AND kind = ?)", wire.LaneAssistant, wire.CardOpen, k.ID, wire.CardMerge).Find(&rows).Error; err != nil { |
| 475 | return err |
| 476 | } |
| 477 | for i := range rows { |
| 478 | m := &rows[i] |
| 479 | var src cardRecord |
| 480 | if err := t.db.Where("id = ? AND person = ?", m.SourceCard, m.Person).Limit(1).Find(&src).Error; err != nil { |
| 481 | return err |
| 482 | } |
| 483 | if src.ID != "" { |
| 484 | if err := t.fillMirror(m, src); err != nil { |
| 485 | return err |
| 486 | } |
| 487 | } |
| 488 | m.Revision++ |
| 489 | m.UpdatedAt = t.now() |
| 490 | m.Links = "[]" |
| 491 | if err := t.db.Model(&cardRecord{}).Where("id = ?", m.ID).Select("state", "question", "options", "links", "result", "revision", "updated_at").Updates(m).Error; err != nil { |
| 492 | return err |
| 493 | } |
| 494 | if err := t.cardEvent(*m); err != nil { |
| 495 | return err |
| 496 | } |
| 497 | } |
| 498 | return nil |
| 499 | } |
| 500 | |
| 501 | // answerOutcome answers the person's Assistant card that points at a |
| 502 | // team card: open and at its revision, with one of its options (a |
| 503 | // question without options takes any words), then through the team |
| 504 | // card's own path as the person, at the team card's current revision. |
| 505 | // When the team card cannot take it now, the answer is refused as stale |
| 506 | // with the card as it stands. The answer itself needs no runner of the |
| 507 | // Assistant's: the team card's path decides what it needs. Audited by the |
| 508 | // card and the option's value alone. |
| 509 | func (t *txn) answerOutcome(person string, c cardRecord, in wire.AnswerCard) (out wire.AssistantAnswered, current wire.AssistantCard, err error) { |
| 510 | v, err := t.assistantCardView(c) |
| 511 | if err != nil { |
| 512 | return out, current, err |
| 513 | } |
| 514 | if c.State != wire.CardOpen || c.Revision != in.Revision { |
| 515 | return out, v, ErrCardConflict |
| 516 | } |
| 517 | option := slices.ContainsFunc(v.Options, func(o wire.CardOption) bool { return o.Value == in.Choice }) |
| 518 | if !option && (len(v.Options) > 0 || c.Kind != wire.CardQuestion) { |
| 519 | return out, current, ErrInvalid |
| 520 | } |
| 521 | var src cardRecord |
| 522 | if err := t.db.Where("id = ? AND person = ? AND "+coordinatorRole, c.SourceCard, c.Person).First(&src).Error; errors.Is(err, gorm.ErrRecordNotFound) { |
| 523 | return out, current, ErrNotFound |
| 524 | } else if err != nil { |
| 525 | return out, current, err |
| 526 | } |
| 527 | answer := wire.AnswerCard{Choice: in.Choice, Revision: src.Revision} |
| 528 | switch src.Kind { |
| 529 | case wire.CardQuestion: |
| 530 | _, _, err = t.answerQuestion(person, src, answer) |
| 531 | case wire.CardMerge: |
| 532 | _, _, err = t.answerMerge(person, src, answer) |
| 533 | case wire.CardPublish: |
| 534 | _, _, err = t.answerPublish(person, src, answer) |
| 535 | default: |
| 536 | return out, current, ErrInvalid |
| 537 | } |
| 538 | if errors.Is(err, ErrCardConflict) { |
| 539 | // The transaction is undone: the card is as v shows it. |
| 540 | return out, v, ErrCardConflict |
| 541 | } |
| 542 | if err != nil { |
| 543 | return out, current, err |
| 544 | } |
| 545 | if err := t.db.Where("id = ?", c.ID).First(&c).Error; err != nil { |
| 546 | return out, current, err |
| 547 | } |
| 548 | record := c.ID |
| 549 | if option { |
| 550 | record += ":" + in.Choice |
| 551 | } |
| 552 | if err := t.s.authority.Audit(t.db, person, auditAssistantOutcome, record); err != nil { |
| 553 | return out, current, err |
| 554 | } |
| 555 | out.Card, err = t.assistantCardView(c) |
| 556 | return out, current, err |
| 557 | } |
| 558 | |
| 559 | // Stale legacy questions (Paul's live check, 2026-11-14). A legacy |
| 560 | // hand-off (lane "") mirrored its team question into the Assistant lane |
| 561 | // as a question card (slice 1, kept by ruling P3j). The card follows its |
| 562 | // source while the source changes (mirrorCard), but the person may |
| 563 | // answer in the chat instead, and the source then stays open: the card |
| 564 | // stayed open for ever. settleLegacyQuestions resolves it, with the |
| 565 | // approved resolved line, once the hand-off is cancelled or its work has |
| 566 | // settled or stopped (handoffSettled), or once its source has been open |
| 567 | // for staleQuestion with no answer and none of the hand-off's work runs. |
| 568 | // A source no longer open that the card missed is followed now. The team |
| 569 | // card itself is never touched: it stays the Coordinator's. |
| 570 | |
| 571 | // staleQuestion is how long a legacy hand-off's question may wait |
| 572 | // unanswered, its work not running, before its mirror is resolved. |
| 573 | const staleQuestion = 24 * time.Hour |
| 574 | |
| 575 | // settleLegacyQuestions resolves the legacy hand-off's open mirrored |
| 576 | // question cards that no longer need an answer, each with its event. |
| 577 | func (t *txn) settleLegacyQuestions(h handoffRecord) error { |
| 578 | if h.Lane != "" { |
| 579 | return nil |
| 580 | } |
| 581 | var mirrors []cardRecord |
| 582 | if err := t.db.Where("handoff_id = ? AND person = ? AND lane = ? AND kind = ? AND state = ? AND coalesce(source_card, '') <> ''", h.ID, h.Person, wire.LaneAssistant, wire.CardQuestion, wire.CardOpen).Order("created_at, id").Find(&mirrors).Error; err != nil || len(mirrors) == 0 { |
| 583 | return err |
| 584 | } |
| 585 | ended := h.State == handoffCancelled || h.State == handoffStopping |
| 586 | if !ended { |
| 587 | settled, err := t.handoffSettled(h) |
| 588 | if err != nil { |
| 589 | return err |
| 590 | } |
| 591 | ended = settled |
| 592 | } |
| 593 | running, err := t.handoffRunning(h) |
| 594 | if err != nil { |
| 595 | return err |
| 596 | } |
| 597 | for _, m := range mirrors { |
| 598 | var src cardRecord |
| 599 | if err := t.db.Where("id = ? AND person = ?", m.SourceCard, m.Person).Limit(1).Find(&src).Error; err != nil { |
| 600 | return err |
| 601 | } |
| 602 | switch { |
| 603 | case src.ID == "" || ended: |
| 604 | m.State, m.Result = wire.CardResolved, t.copy("assistant.outcome.resolved") |
| 605 | case src.State != wire.CardOpen: |
| 606 | if err := t.fillMirror(&m, src); err != nil { |
| 607 | return err |
| 608 | } |
| 609 | case !running && src.CreatedAt.Before(t.now().Add(-staleQuestion)): |
| 610 | m.State, m.Result = wire.CardResolved, t.copy("assistant.outcome.resolved") |
| 611 | default: |
| 612 | continue |
| 613 | } |
| 614 | m.Revision++ |
| 615 | m.UpdatedAt = t.now() |
| 616 | if err := t.db.Model(&cardRecord{}).Where("id = ?", m.ID).Select("state", "question", "options", "links", "result", "revision", "updated_at").Updates(&m).Error; err != nil { |
| 617 | return err |
| 618 | } |
| 619 | if err := t.cardEvent(m); err != nil { |
| 620 | return err |
| 621 | } |
| 622 | } |
| 623 | return nil |
| 624 | } |
| 625 | |
| 626 | // handoffRunning: one of the hand-off's Coordinator turns has not ended, |
| 627 | // or a step of a task it follows is under way. |
| 628 | func (t *txn) handoffRunning(h handoffRecord) (bool, error) { |
| 629 | var n int64 |
| 630 | if err := t.handoffTurns(h).Where("state IN ?", wire.InFlight).Count(&n).Error; err != nil || n > 0 { |
| 631 | return n > 0, err |
| 632 | } |
| 633 | tasks, err := t.handoffTasks(h) |
| 634 | if err != nil { |
| 635 | return false, err |
| 636 | } |
| 637 | for _, k := range tasks { |
| 638 | steps, err := t.steps(k.ID) |
| 639 | if err != nil { |
| 640 | return false, err |
| 641 | } |
| 642 | if slices.ContainsFunc(steps, func(s stepRecord) bool { return !wire.StepTerminal(s.State) }) { |
| 643 | return true, nil |
| 644 | } |
| 645 | } |
| 646 | return false, nil |
| 647 | } |
| 648 | |
| 649 | // closeLandedOutcomes is the minute's look at go-aheads whose work has |
| 650 | // landed but whose card still reads as before (closed by an Equipo older |
| 651 | // than landed, or any path that missed touchOutcomes): each is filled |
| 652 | // afresh, once, its revision moved and its event sent. |
| 653 | func (t *txn) closeLandedOutcomes() error { |
| 654 | var rows []cardRecord |
| 655 | q := "lane = ? AND kind = ? AND coalesce(question, '') <> ? AND source_card IN (SELECT c.id FROM chat_cards c JOIN chat_tasks k ON k.id = c.task_id WHERE c.kind = ? AND k.stage = ? AND coalesce(k.built_as, '') = '')" |
| 656 | if err := t.db.Where(q, wire.LaneAssistant, wire.CardOutcome, t.copy("assistant.outcome.resolved"), wire.CardMerge, wire.StageDone).Order("created_at, id").Limit(200).Find(&rows).Error; err != nil { |
| 657 | return err |
| 658 | } |
| 659 | for i := range rows { |
| 660 | m := &rows[i] |
| 661 | var src cardRecord |
| 662 | if err := t.db.Where("id = ? AND person = ?", m.SourceCard, m.Person).Limit(1).Find(&src).Error; err != nil || src.ID == "" { |
| 663 | return err |
| 664 | } |
| 665 | if err := t.fillMirror(m, src); err != nil { |
| 666 | return err |
| 667 | } |
| 668 | m.Revision++ |
| 669 | m.UpdatedAt = t.now() |
| 670 | if err := t.db.Model(&cardRecord{}).Where("id = ?", m.ID).Select("state", "question", "options", "links", "result", "revision", "updated_at").Updates(m).Error; err != nil { |
| 671 | return err |
| 672 | } |
| 673 | if err := t.cardEvent(*m); err != nil { |
| 674 | return err |
| 675 | } |
| 676 | } |
| 677 | return nil |
| 678 | } |
| 679 | |
| 680 | // settleStaleLegacyQuestions is the minute's look at every legacy |
| 681 | // hand-off with an open mirrored question: nothing else may move one |
| 682 | // that waits for a day, or that settled before this rule. Mirrors slice |
| 683 | // 1 made carry no hand-off: each is linked through its source card |
| 684 | // (handoffFor), or, with no hand-off to follow it, resolved once its |
| 685 | // source is no longer open or is over staleQuestion old. |
| 686 | func (t *txn) settleStaleLegacyQuestions() error { |
| 687 | const open = "lane = ? AND kind = ? AND state = ? AND coalesce(source_card, '') <> ''" |
| 688 | var orphans []cardRecord |
| 689 | if err := t.db.Where(open+" AND coalesce(handoff_id, '') = ''", wire.LaneAssistant, wire.CardQuestion, wire.CardOpen).Order("created_at, id").Find(&orphans).Error; err != nil { |
| 690 | return err |
| 691 | } |
| 692 | for _, m := range orphans { |
| 693 | var src cardRecord |
| 694 | if err := t.db.Where("id = ? AND person = ?", m.SourceCard, m.Person).Limit(1).Find(&src).Error; err != nil { |
| 695 | return err |
| 696 | } |
| 697 | h, found, err := t.handoffFor(src) |
| 698 | if err != nil { |
| 699 | return err |
| 700 | } |
| 701 | if src.ID != "" && found { |
| 702 | if err := t.db.Model(&cardRecord{}).Where("id = ?", m.ID).Update("handoff_id", h.ID).Error; err != nil { |
| 703 | return err |
| 704 | } |
| 705 | continue |
| 706 | } |
| 707 | if src.ID != "" && src.State == wire.CardOpen && !src.CreatedAt.Before(t.now().Add(-staleQuestion)) { |
| 708 | continue |
| 709 | } |
| 710 | m.State, m.Result = wire.CardResolved, t.copy("assistant.outcome.resolved") |
| 711 | m.Revision++ |
| 712 | m.UpdatedAt = t.now() |
| 713 | if err := t.db.Model(&cardRecord{}).Where("id = ?", m.ID).Select("state", "result", "revision", "updated_at").Updates(&m).Error; err != nil { |
| 714 | return err |
| 715 | } |
| 716 | if err := t.cardEvent(m); err != nil { |
| 717 | return err |
| 718 | } |
| 719 | } |
| 720 | var ids []string |
| 721 | if err := t.db.Model(&cardRecord{}).Where(open+" AND coalesce(handoff_id, '') <> ''", wire.LaneAssistant, wire.CardQuestion, wire.CardOpen).Distinct().Order("handoff_id").Pluck("handoff_id", &ids).Error; err != nil || len(ids) == 0 { |
| 722 | return err |
| 723 | } |
| 724 | var rows []handoffRecord |
| 725 | if err := t.db.Where("id IN ? AND coalesce(lane, '') = ''", ids).Order("created_at, id").Find(&rows).Error; err != nil { |
| 726 | return err |
| 727 | } |
| 728 | for _, h := range rows { |
| 729 | if err := t.settleLegacyQuestions(h); err != nil { |
| 730 | return err |
| 731 | } |
| 732 | } |
| 733 | return nil |
| 734 | } |
| 735 | |