| 1 | package chat |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "encoding/json" |
| 6 | "errors" |
| 7 | "time" |
| 8 | |
| 9 | "gorm.io/gorm" |
| 10 | |
| 11 | "amadan.net/oficina/equipo/internal/equipo/housekeeping" |
| 12 | "amadan.net/oficina/equipo/internal/wire" |
| 13 | ) |
| 14 | |
| 15 | // Equipo tidies duplicate tasks on its own (Paul, 2026-11-08: "Can Equipo |
| 16 | // itself tidy up the duplicates?"), as the housekeeping loop's first |
| 17 | // detectors (housekeeping.DuplicateSameCreator and DuplicatePossible, |
| 18 | // run by housekeepingPass). Within a project, two open tasks that |
| 19 | // read alike are a pair. When one person filed both, they read very much |
| 20 | // alike, neither is merging and the weaker one has no open card and no |
| 21 | // step at work, the weaker is combined into the one that is furthest |
| 22 | // along, or at one stage the one whose merge card its creator answered |
| 23 | // (an open card on the one kept, a merge card say, does not block): |
| 24 | // its report, findings and thread are copied onto the survivor |
| 25 | // (marked as folded from it) and it is cancelled without merging. Nothing |
| 26 | // is deleted, so Undo restores it exactly. Any other pair is only named: |
| 27 | // the weaker task's DuplicateOf is the stronger one. A pair someone undid, |
| 28 | // or the coordinator recorded as separate, is never touched again. |
| 29 | |
| 30 | // distinctRecord is a pair of tasks that are not the same work, a < b. |
| 31 | type distinctRecord struct { |
| 32 | A string `gorm:"primaryKey"` |
| 33 | B string `gorm:"primaryKey"` |
| 34 | CreatedAt time.Time |
| 35 | } |
| 36 | |
| 37 | func (distinctRecord) TableName() string { return "chat_task_distinct" } |
| 38 | |
| 39 | func (t *txn) markDistinct(a, b string) error { |
| 40 | if a > b { |
| 41 | a, b = b, a |
| 42 | } |
| 43 | return t.db.Exec("INSERT INTO chat_task_distinct(a, b, created_at) VALUES (?,?,?) ON CONFLICT DO NOTHING", a, b, t.now()).Error |
| 44 | } |
| 45 | |
| 46 | // TidyDuplicates runs the duplicate detectors over every project's open |
| 47 | // tasks: at start and at the daily sweep. |
| 48 | func (s *Store) TidyDuplicates(ctx context.Context) (folded int, err error) { |
| 49 | var projects []string |
| 50 | if err := s.read(ctx, func(tx *gorm.DB) error { |
| 51 | return tx.Model(&taskRecord{}).Where("stage NOT IN ?", []string{wire.StageDone, wire.StageCancelled}).Distinct().Order("project_id").Pluck("project_id", &projects).Error |
| 52 | }); err != nil { |
| 53 | return 0, err |
| 54 | } |
| 55 | for _, p := range projects { |
| 56 | err := s.tx(ctx, func(t *txn) error { |
| 57 | n, err := t.housekeepingPass(housekeeping.TriggerSweep, p) |
| 58 | folded += n |
| 59 | return err |
| 60 | }) |
| 61 | if err != nil { |
| 62 | return folded, err |
| 63 | } |
| 64 | } |
| 65 | return folded, nil |
| 66 | } |
| 67 | |
| 68 | // errNotFoldable: the pair fails a check fold makes in its own |
| 69 | // transaction; it stays a "Possible duplicate of" link. |
| 70 | var errNotFoldable = errors.New("chat: not foldable") |
| 71 | |
| 72 | // foldable re-reads both tasks inside the fold's transaction and checks |
| 73 | // everything a fold needs (Astra, housekeeping review): one creator who |
| 74 | // is still an active member, one project, neither ended, merging or |
| 75 | // already folded, no open card on the one folded (a decision still to |
| 76 | // make; a card on the one kept stays open and does not block), and |
| 77 | // nothing at work on the one folded. Anything else never touches the |
| 78 | // other task. |
| 79 | func (t *txn) foldable(k, into taskRecord) (taskRecord, taskRecord, error) { |
| 80 | var err error |
| 81 | if k, err = t.loadTask(k.ID); err != nil { |
| 82 | return k, into, err |
| 83 | } |
| 84 | if into, err = t.loadTask(into.ID); err != nil { |
| 85 | return k, into, err |
| 86 | } |
| 87 | // Under the housekeeping principal both tasks, the destination too, |
| 88 | // are the principal's person's, who is still on the team. |
| 89 | if err := t.hkOwns(k.Creator); err != nil { |
| 90 | return k, into, err |
| 91 | } |
| 92 | if err := t.hkOwns(into.Creator); err != nil { |
| 93 | return k, into, err |
| 94 | } |
| 95 | switch { |
| 96 | case k.ID == into.ID, k.Creator != into.Creator, k.ProjectID != into.ProjectID, |
| 97 | wire.FinalStage(k.Stage), wire.FinalStage(into.Stage), k.CancelRequested, into.CancelRequested, |
| 98 | k.Stage == wire.StageMerging, into.Stage == wire.StageMerging, k.FoldedInto != "", into.FoldedInto != "", |
| 99 | wire.NormalKind(k.Kind) != wire.NormalKind(into.Kind): |
| 100 | return k, into, errNotFoldable |
| 101 | } |
| 102 | var active int64 |
| 103 | if err := t.db.Raw("SELECT COUNT(*) FROM members WHERE address = ? AND active = 1", k.Creator).Scan(&active).Error; err != nil { |
| 104 | return k, into, err |
| 105 | } |
| 106 | var cards int64 |
| 107 | if err := t.db.Model(&cardRecord{}).Where("task_id = ? AND state = ? AND kind <> ?", k.ID, wire.CardOpen, wire.CardTask).Count(&cards).Error; err != nil { |
| 108 | return k, into, err |
| 109 | } |
| 110 | var busy int64 |
| 111 | if err := t.db.Model(&stepRecord{}).Where("task_id = ? AND state IN ?", k.ID, []string{wire.StepQueued, wire.StepRunning}).Count(&busy).Error; err != nil { |
| 112 | return k, into, err |
| 113 | } |
| 114 | if active == 0 || cards > 0 || busy > 0 { |
| 115 | return k, into, errNotFoldable |
| 116 | } |
| 117 | return k, into, nil |
| 118 | } |
| 119 | |
| 120 | // fold combines k into into: k's report, findings and thread are copied |
| 121 | // onto into, marked as folded from k; k is cancelled without merging, |
| 122 | // keeping the stage it had for Undo; the creator gets a quiet receipt, |
| 123 | // held until visibleAt in quiet hours. It returns the receipt's id. |
| 124 | func (t *txn) fold(k, into taskRecord, actionID string, visibleAt *time.Time) (string, error) { |
| 125 | k, into, err := t.foldable(k, into) |
| 126 | if err != nil { |
| 127 | return "", err |
| 128 | } |
| 129 | now := t.now() |
| 130 | var entries []entryRecord |
| 131 | if err := t.db.Where("task_id = ? AND (folded_from IS NULL OR folded_from = '')", k.ID).Order("created_at, id").Find(&entries).Error; err != nil { |
| 132 | return "", err |
| 133 | } |
| 134 | report := k.Title |
| 135 | if k.Brief != "" { |
| 136 | report += "\n\n" + k.Brief |
| 137 | } |
| 138 | copies := []entryRecord{{ID: newID("e_"), TaskID: into.ID, IdempotencyKey: "fold:" + k.ID, Kind: entryReport, Author: k.Creator, Text: clip(report, wire.MaxThreadText), CreatedAt: k.CreatedAt, FoldedFrom: k.ID}} |
| 139 | for _, e := range entries { |
| 140 | c := e |
| 141 | c.ID, c.TaskID, c.IdempotencyKey, c.FoldedFrom = newID("e_"), into.ID, "fold:"+k.ID+":"+e.ID, k.ID |
| 142 | copies = append(copies, c) |
| 143 | } |
| 144 | if err := t.db.Create(&copies).Error; err != nil { |
| 145 | return "", err |
| 146 | } |
| 147 | k.FoldedInto, k.FoldedStage, k.FoldedAt, k.DuplicateOf = into.ID, k.Stage, &now, into.ID |
| 148 | k.Stage = wire.StageCancelled |
| 149 | k.Revision++ |
| 150 | k.UpdatedAt = now |
| 151 | // Not saveTask: a fold is no ending. The runner keeps the task's |
| 152 | // sessions and nothing is withdrawn, so Undo finds it as it was. |
| 153 | if err := t.db.Model(&taskRecord{}).Where("id = ?", k.ID).Select("stage", "folded_into", "folded_stage", "folded_at", "duplicate_of", "revision", "updated_at").Updates(&k).Error; err != nil { |
| 154 | return "", err |
| 155 | } |
| 156 | if err := t.taskEvent(k); err != nil { |
| 157 | return "", err |
| 158 | } |
| 159 | if err := t.saveTask(&into); err != nil { |
| 160 | return "", err |
| 161 | } |
| 162 | opts, _ := json.Marshal([]string{wire.ChoiceUndo}) |
| 163 | c := cardRecord{ID: newID("c_"), Person: k.Creator, Kind: wire.CardCombined, State: wire.CardOpen, ProjectID: k.ProjectID, TaskID: k.ID, Name: k.Title, Question: t.words("chat.card.combined", k.Title, into.Title), Options: string(opts), Revision: 1, CreatedAt: now, UpdatedAt: now, ActionID: actionID, VisibleAt: visibleAt, Held: visibleAt != nil, Lane: k.Lane} |
| 164 | if err := t.db.Create(&c).Error; err != nil { |
| 165 | return "", err |
| 166 | } |
| 167 | return c.ID, t.cardEvent(c) |
| 168 | } |
| 169 | |
| 170 | // unfold restores a combined task exactly as it was and keeps the pair |
| 171 | // apart from then on. |
| 172 | func (t *txn) unfold(person string, k taskRecord) (taskRecord, error) { |
| 173 | if k.FoldedInto == "" { |
| 174 | return k, ErrConflict |
| 175 | } |
| 176 | if k.Creator != person { |
| 177 | return k, ErrForbidden |
| 178 | } |
| 179 | // The housekeeping action behind the fold, if Equipo made it: Undo |
| 180 | // only within its window; it becomes a retained veto. |
| 181 | action, err := t.foldAction(k) |
| 182 | if err != nil { |
| 183 | return k, err |
| 184 | } |
| 185 | if action != nil && (action.State != wire.ActionDone || action.UndoUntil != nil && !t.hkNow().Before(*action.UndoUntil)) { |
| 186 | return k, ErrActionConflict |
| 187 | } |
| 188 | // Undo restores the task exactly: its link as it was before the fold |
| 189 | // too, from the action's snapshot. |
| 190 | restore := "" |
| 191 | if action != nil { |
| 192 | var res hkResult |
| 193 | if json.Unmarshal([]byte(action.Result), &res) == nil { |
| 194 | restore = res.DuplicateOf |
| 195 | } |
| 196 | } |
| 197 | into, err := t.loadTask(k.FoldedInto) |
| 198 | survivor := err == nil |
| 199 | if err != nil && !errors.Is(err, ErrNotFound) { |
| 200 | return k, err |
| 201 | } |
| 202 | if err := t.db.Where("task_id = ? AND folded_from = ?", k.FoldedInto, k.ID).Delete(&entryRecord{}).Error; err != nil { |
| 203 | return k, err |
| 204 | } |
| 205 | if err := t.markDistinct(k.ID, k.FoldedInto); err != nil { |
| 206 | return k, err |
| 207 | } |
| 208 | k.Stage, k.FoldedInto, k.FoldedStage, k.FoldedAt, k.DuplicateOf = k.FoldedStage, "", "", nil, restore |
| 209 | k.Revision++ |
| 210 | k.UpdatedAt = t.now() |
| 211 | if err := t.db.Model(&taskRecord{}).Where("id = ?", k.ID).Select("stage", "folded_into", "folded_stage", "folded_at", "duplicate_of", "revision", "updated_at").Updates(&k).Error; err != nil { |
| 212 | return k, err |
| 213 | } |
| 214 | if err := t.taskEvent(k); err != nil { |
| 215 | return k, err |
| 216 | } |
| 217 | if survivor { |
| 218 | if err := t.saveTask(&into); err != nil { |
| 219 | return k, err |
| 220 | } |
| 221 | } |
| 222 | var cards []cardRecord |
| 223 | if err := t.db.Where("task_id = ? AND kind = ? AND state = ?", k.ID, wire.CardCombined, wire.CardOpen).Find(&cards).Error; err != nil { |
| 224 | return k, err |
| 225 | } |
| 226 | for i := range cards { |
| 227 | cards[i].State, cards[i].Choice = wire.CardAnswered, wire.ChoiceUndo |
| 228 | if err := t.saveCard(&cards[i]); err != nil { |
| 229 | return k, err |
| 230 | } |
| 231 | } |
| 232 | if action != nil { |
| 233 | return k, t.hkUndone(action) |
| 234 | } |
| 235 | return k, nil |
| 236 | } |
| 237 | |
| 238 | // foldAction is the housekeeping action that folded k, or nil when the |
| 239 | // fold was older than the ledger. |
| 240 | func (t *txn) foldAction(k taskRecord) (*hkRecord, error) { |
| 241 | var rows []hkRecord |
| 242 | if err := t.db.Where("subject_id = ? AND detector = ? AND state IN ?", k.ID, housekeeping.DuplicateSameCreatorID, []string{wire.ActionDone, wire.ActionUndone}).Order("at DESC").Find(&rows).Error; err != nil { |
| 243 | return nil, err |
| 244 | } |
| 245 | for i := range rows { |
| 246 | var res hkResult |
| 247 | if json.Unmarshal([]byte(rows[i].Result), &res) == nil && res.Task == k.ID && res.Into == k.FoldedInto && rows[i].State == wire.ActionDone { |
| 248 | return &rows[i], nil |
| 249 | } |
| 250 | } |
| 251 | return nil, nil |
| 252 | } |
| 253 | |
| 254 | // Uncombine is Undo on a combined task: its creator only. |
| 255 | func (s *Store) Uncombine(ctx context.Context, person, id string) (out wire.Task, err error) { |
| 256 | err = s.tx(ctx, func(t *txn) error { |
| 257 | if err := s.authority.CurrentPerson(ctx, t.db); err != nil { |
| 258 | return err |
| 259 | } |
| 260 | k, err := t.loadTask(id) |
| 261 | if err != nil { |
| 262 | return err |
| 263 | } |
| 264 | if k, err = t.unfold(person, k); err != nil { |
| 265 | return err |
| 266 | } |
| 267 | out, err = t.taskView(k) |
| 268 | return err |
| 269 | }) |
| 270 | return out, err |
| 271 | } |
| 272 | |
| 273 | // answerCombined is Undo on the combined receipt card. |
| 274 | func (t *txn) answerCombined(person string, c cardRecord, in wire.AnswerCard) (wire.Card, wire.Card, error) { |
| 275 | v, err := t.cardView(c) |
| 276 | if err != nil { |
| 277 | return wire.Card{}, wire.Card{}, err |
| 278 | } |
| 279 | if in.Choice != wire.ChoiceUndo { |
| 280 | return wire.Card{}, wire.Card{}, ErrInvalid |
| 281 | } |
| 282 | if c.State != wire.CardOpen || c.Revision != in.Revision { |
| 283 | return wire.Card{}, v, ErrCardConflict |
| 284 | } |
| 285 | if c.Person != person { |
| 286 | return wire.Card{}, wire.Card{}, ErrForbidden |
| 287 | } |
| 288 | k, err := t.loadTask(c.TaskID) |
| 289 | if err != nil { |
| 290 | return wire.Card{}, wire.Card{}, err |
| 291 | } |
| 292 | if _, err := t.unfold(person, k); err != nil { |
| 293 | return wire.Card{}, wire.Card{}, err |
| 294 | } |
| 295 | if err := t.db.Where("id = ?", c.ID).First(&c).Error; err != nil { |
| 296 | return wire.Card{}, wire.Card{}, err |
| 297 | } |
| 298 | out, err := t.cardView(c) |
| 299 | return out, out, err |
| 300 | } |
| 301 | |
| 302 | // foldViews fills the task's fold: where it went, and what came into it. |
| 303 | func (t *txn) foldViews(v *wire.Task, k taskRecord) error { |
| 304 | if k.FoldedInto != "" && k.FoldedAt != nil { |
| 305 | var into taskRecord |
| 306 | err := t.db.Select("id", "title", "stage", "creator").Where("id = ?", k.FoldedInto).First(&into).Error |
| 307 | if err == nil { |
| 308 | v.Folded = &wire.TaskFold{Into: wire.TaskRef{ID: into.ID, Title: into.Title, Stage: into.Stage, Creator: into.Creator}, At: *k.FoldedAt} |
| 309 | } else if !errors.Is(err, gorm.ErrRecordNotFound) { |
| 310 | return err |
| 311 | } |
| 312 | } |
| 313 | var in []taskRecord |
| 314 | if err := t.db.Select("id", "title", "stage", "creator").Where("folded_into = ?", k.ID).Order("folded_at DESC, id").Find(&in).Error; err != nil { |
| 315 | return err |
| 316 | } |
| 317 | v.Combined = []wire.TaskRef{} |
| 318 | for _, f := range in { |
| 319 | v.Combined = append(v.Combined, wire.TaskRef{ID: f.ID, Title: f.Title, Stage: f.Stage, Creator: f.Creator}) |
| 320 | } |
| 321 | return nil |
| 322 | } |
| 323 | |