| 1 | package chat |
| 2 | |
| 3 | import ( |
| 4 | "encoding/json" |
| 5 | "errors" |
| 6 | "fmt" |
| 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 | // Housekeeping (spec 2026-11-08-equipo-housekeeping.md): the registry's |
| 16 | // detectors notice things; every finding is claimed in a ledger whose |
| 17 | // rows only move forward; anything the loop writes goes through the same |
| 18 | // store functions a person's request uses, under a housekeeping principal |
| 19 | // those functions check inside the transaction. This file holds the |
| 20 | // ledger, the principal and the executor; housekeeping_control.go the |
| 21 | // budget, Pause, quiet hours, the digest and recovery. |
| 22 | |
| 23 | // ErrHousekeepingForbidden: the housekeeping principal failed a check in |
| 24 | // a store function. The ledger row becomes refused and nothing else the |
| 25 | // action wrote survives. |
| 26 | var ErrHousekeepingForbidden = errors.New("chat: housekeeping_forbidden") |
| 27 | |
| 28 | // Principal is who acts when the loop writes: built by the instance from |
| 29 | // the ledger row, never from a frame or a tool argument. |
| 30 | type Principal struct { |
| 31 | Team, Person, Detector, FindingID string |
| 32 | // Reserved is what the row holds from the day's budget; a store |
| 33 | // function that would spend refuses without it. |
| 34 | Reserved housekeeping.Cost |
| 35 | // Dispatch lets the principal dispatch steps of its own person's tasks |
| 36 | // (needs-you triage: a retry, a rebase, a re-check). Nothing else may. |
| 37 | Dispatch bool |
| 38 | } |
| 39 | |
| 40 | // hkRecord is one ledger row (chat_housekeeping): what a finding became. |
| 41 | // Person is "" for a team subject, so (team, person, detector, key) is |
| 42 | // unique for both scopes. |
| 43 | type hkRecord struct { |
| 44 | ID string `gorm:"primaryKey"` |
| 45 | Team string `gorm:"uniqueIndex:chat_housekeeping_key,priority:1"` |
| 46 | Person string `gorm:"uniqueIndex:chat_housekeeping_key,priority:2;index:chat_housekeeping_person,priority:1"` |
| 47 | Detector string `gorm:"uniqueIndex:chat_housekeeping_key,priority:3"` |
| 48 | SubjectKind string |
| 49 | SubjectID string `gorm:"index:chat_housekeeping_subject"` |
| 50 | SubjectRevision int64 |
| 51 | FindingKey string `gorm:"uniqueIndex:chat_housekeeping_key,priority:4"` |
| 52 | Class string |
| 53 | State string |
| 54 | Reason string |
| 55 | ClaimedAt *time.Time |
| 56 | // Attempt is the dispatch the row made (a turn or step attempt), "" |
| 57 | // before any: recovery tells a claim that never left from one the |
| 58 | // runner holds. |
| 59 | Attempt string |
| 60 | ReservedTurns int64 |
| 61 | ReservedTokens int64 |
| 62 | ReservedRetries int64 |
| 63 | ChargedTurns int64 |
| 64 | ChargedTokens int64 |
| 65 | ChargedRetries int64 |
| 66 | // Rounds: automatic Engineering rounds (needs-you triage). |
| 67 | ReservedRounds int64 |
| 68 | ChargedRounds int64 |
| 69 | ChargedComplete bool |
| 70 | // Releasing: the reservation still counts against the day until the |
| 71 | // attempt's termination and its charge are in. |
| 72 | Releasing bool |
| 73 | // Evidence is the finding's housekeeping.Evidence JSON; Result the |
| 74 | // action's snapshot for Undo (hkResult JSON). |
| 75 | Evidence string |
| 76 | Result string |
| 77 | VisibleAt *time.Time |
| 78 | UndoUntil *time.Time |
| 79 | Recurrences int |
| 80 | At time.Time `gorm:"index:chat_housekeeping_person,priority:2"` |
| 81 | UndoneAt *time.Time |
| 82 | Revision int64 |
| 83 | } |
| 84 | |
| 85 | func (hkRecord) TableName() string { return "chat_housekeeping" } |
| 86 | |
| 87 | // hkFailureRecord counts a detector's failures for a person, written so |
| 88 | // that an error cannot erase its own record. |
| 89 | type hkFailureRecord struct { |
| 90 | ID int64 `gorm:"primaryKey"` |
| 91 | Person string `gorm:"index:chat_housekeeping_failure_person,priority:1"` |
| 92 | Detector string `gorm:"index:chat_housekeeping_failure_person,priority:2"` |
| 93 | Kind string |
| 94 | ActionID string |
| 95 | At time.Time `gorm:"index:chat_housekeeping_failure_person,priority:3"` |
| 96 | } |
| 97 | |
| 98 | func (hkFailureRecord) TableName() string { return "chat_housekeeping_failures" } |
| 99 | |
| 100 | // Failure kinds (spec §4, failure containment). |
| 101 | const ( |
| 102 | failureUndone = "undone" |
| 103 | failureFailed = "failed" |
| 104 | ) |
| 105 | |
| 106 | // hkResult is what an action did, enough to undo it exactly: the folded |
| 107 | // task's fields before the fold, and the destination. |
| 108 | type hkResult struct { |
| 109 | Action string `json:"action"` |
| 110 | Task string `json:"task"` |
| 111 | Into string `json:"into"` |
| 112 | Stage string `json:"stage"` |
| 113 | DuplicateOf string `json:"duplicate_of"` |
| 114 | TaskRev int64 `json:"task_revision"` |
| 115 | IntoRev int64 `json:"into_revision"` |
| 116 | CardID string `json:"card"` |
| 117 | } |
| 118 | |
| 119 | func (r hkRecord) reserved() housekeeping.Cost { |
| 120 | return housekeeping.Cost{Turns: r.ReservedTurns, Tokens: r.ReservedTokens, Retries: r.ReservedRetries, Rounds: r.ReservedRounds} |
| 121 | } |
| 122 | |
| 123 | func (r hkRecord) charged() housekeeping.Cost { |
| 124 | return housekeeping.Cost{Turns: r.ChargedTurns, Tokens: r.ChargedTokens, Retries: r.ChargedRetries, Rounds: r.ChargedRounds} |
| 125 | } |
| 126 | |
| 127 | // open: the reservation still counts in full (claimed, or releasing). |
| 128 | func (r hkRecord) open() bool { return r.State == wire.ActionClaimed || r.Releasing } |
| 129 | |
| 130 | // team is the instance's team: one instance belongs to one team. |
| 131 | func (t *txn) team() (string, error) { |
| 132 | t.s.hkMu.Lock() |
| 133 | defer t.s.hkMu.Unlock() |
| 134 | if t.s.teamID != "" { |
| 135 | return t.s.teamID, nil |
| 136 | } |
| 137 | var ids []string |
| 138 | if err := t.db.Raw("SELECT id FROM teams ORDER BY rowid LIMIT 1").Scan(&ids).Error; err != nil { |
| 139 | return "", err |
| 140 | } |
| 141 | if len(ids) == 0 { |
| 142 | return "", ErrUnavailable |
| 143 | } |
| 144 | t.s.teamID = ids[0] |
| 145 | return ids[0], nil |
| 146 | } |
| 147 | |
| 148 | // activeMember reports whether address is on the team now. |
| 149 | func (t *txn) activeMember(address string) (bool, error) { |
| 150 | var n int64 |
| 151 | err := t.db.Raw("SELECT COUNT(*) FROM members WHERE address = ? AND active = 1", address).Scan(&n).Error |
| 152 | return n > 0, err |
| 153 | } |
| 154 | |
| 155 | // --- The principal's checks, called inside the shared store functions. |
| 156 | |
| 157 | // hkForbid refuses what housekeeping may never do, whatever the subject: |
| 158 | // delete, merge or alter merge eligibility, change a setting, cancel. |
| 159 | func (t *txn) hkForbid(what string) error { |
| 160 | if t.hk == nil { |
| 161 | return nil |
| 162 | } |
| 163 | return fmt.Errorf("%w: %s", ErrHousekeepingForbidden, what) |
| 164 | } |
| 165 | |
| 166 | // hkOwns checks a task the principal is about to write: its creator is the |
| 167 | // principal's person, who is still a current member. |
| 168 | func (t *txn) hkOwns(creator string) error { |
| 169 | if t.hk == nil { |
| 170 | return nil |
| 171 | } |
| 172 | if creator != t.hk.Person { |
| 173 | return fmt.Errorf("%w: another person's task", ErrHousekeepingForbidden) |
| 174 | } |
| 175 | ok, err := t.activeMember(t.hk.Person) |
| 176 | if err != nil { |
| 177 | return err |
| 178 | } |
| 179 | if !ok { |
| 180 | return fmt.Errorf("%w: not a current member", ErrHousekeepingForbidden) |
| 181 | } |
| 182 | return nil |
| 183 | } |
| 184 | |
| 185 | // hkTaskWrite is saveTask's check under the principal: the person's own |
| 186 | // task, and none of the merge decisions or an ending. |
| 187 | func (t *txn) hkTaskWrite(k *taskRecord) error { |
| 188 | if t.hk == nil { |
| 189 | return nil |
| 190 | } |
| 191 | // Authority comes from the stored task, never the caller's copy. |
| 192 | var was taskRecord |
| 193 | if err := t.db.Where("id = ?", k.ID).First(&was).Error; err != nil { |
| 194 | return err |
| 195 | } |
| 196 | if err := t.hkOwns(was.Creator); err != nil { |
| 197 | return err |
| 198 | } |
| 199 | switch { |
| 200 | case k.Creator != was.Creator: |
| 201 | return fmt.Errorf("%w: a task's creator", ErrHousekeepingForbidden) |
| 202 | case k.Stage != was.Stage && (wire.FinalStage(k.Stage) || k.Stage == wire.StageMerging), |
| 203 | k.MergeEligible != was.MergeEligible, k.ReadySHA != was.ReadySHA, k.MergeAsked != was.MergeAsked, |
| 204 | k.MergedSHA != was.MergedSHA, k.CancelRequested != was.CancelRequested: |
| 205 | return fmt.Errorf("%w: merge or ending", ErrHousekeepingForbidden) |
| 206 | } |
| 207 | return nil |
| 208 | } |
| 209 | |
| 210 | // hkSpend is the check before anything that would spend under the |
| 211 | // principal: a turn or a step dispatched. Housekeeping's own detectors |
| 212 | // may not (slice 1 has no judgement turns); a needs-you triage action |
| 213 | // may dispatch steps of its own person's tasks and nothing else. |
| 214 | func (t *txn) hkSpend(person string) error { |
| 215 | if t.hk == nil || t.hk.Dispatch && person != "" && person == t.hk.Person { |
| 216 | return nil |
| 217 | } |
| 218 | return t.hkForbid("dispatch") |
| 219 | } |
| 220 | |
| 221 | // --- The ledger. |
| 222 | |
| 223 | func (t *txn) hkLoad(team, person, detector, key string) (hkRecord, bool, error) { |
| 224 | var r hkRecord |
| 225 | err := t.db.Where("team = ? AND person = ? AND detector = ? AND finding_key = ?", team, person, detector, key).First(&r).Error |
| 226 | if errors.Is(err, gorm.ErrRecordNotFound) { |
| 227 | return r, false, nil |
| 228 | } |
| 229 | return r, err == nil, err |
| 230 | } |
| 231 | |
| 232 | // reclaimable: a key that exists acts again only when it is held, failed |
| 233 | // with no recovery yet, or vetoed past its window with a recurrence left. |
| 234 | // An expired claim whose subject moved is a fresh finding on the new |
| 235 | // revision. |
| 236 | func (t *txn) reclaimable(r hkRecord) bool { |
| 237 | switch r.State { |
| 238 | case wire.ActionHeld: |
| 239 | return true |
| 240 | case wire.ActionFailed: |
| 241 | return r.Recurrences == 0 |
| 242 | case wire.ActionVetoed: |
| 243 | return r.Recurrences == 0 && r.UndoneAt != nil && t.hkNow().Sub(*r.UndoneAt) >= housekeeping.VetoWindow |
| 244 | case wire.ActionExpired: |
| 245 | return r.Reason == wire.ReasonSubjectMoved |
| 246 | } |
| 247 | return false |
| 248 | } |
| 249 | |
| 250 | // hkSave writes a row's transition and tells its person. |
| 251 | func (t *txn) hkSave(r *hkRecord, insert bool) error { |
| 252 | r.Revision++ |
| 253 | r.At = t.hkNow() |
| 254 | if insert { |
| 255 | if err := t.db.Create(r).Error; err != nil { |
| 256 | return err |
| 257 | } |
| 258 | } else if err := t.db.Model(&hkRecord{}).Where("id = ?", r.ID).Select("*").Omit("id").Updates(r).Error; err != nil { |
| 259 | return err |
| 260 | } |
| 261 | if r.Person == "" { |
| 262 | return nil |
| 263 | } |
| 264 | v, err := t.actionView(*r) |
| 265 | if err != nil { |
| 266 | return err |
| 267 | } |
| 268 | return t.event("", r.Person, wire.EventHousekeeping, "action", r.ID, r.Revision, "", "", 0, v) |
| 269 | } |
| 270 | |
| 271 | // hkRun claims a finding and, for an action that spends nothing, acts in |
| 272 | // the same transaction. It reports whether the subject changed (the |
| 273 | // caller reads the facts again). Errors are the ledger's own; an action's |
| 274 | // failure is recorded on the row and never breaks the caller's |
| 275 | // transaction (a person's record_task, a start-up tidy). |
| 276 | func (t *txn) hkRun(d housekeeping.Detector, f housekeeping.Finding) (bool, error) { |
| 277 | if t.hk != nil { |
| 278 | return false, fmt.Errorf("%w: housekeeping inside housekeeping", ErrHousekeepingForbidden) |
| 279 | } |
| 280 | team, err := t.team() |
| 281 | if err != nil { |
| 282 | return false, err |
| 283 | } |
| 284 | person := f.Owner |
| 285 | if person != "" { |
| 286 | set, err := t.hkSettings(person) |
| 287 | if err != nil { |
| 288 | return false, err |
| 289 | } |
| 290 | if set.Paused || set.disabledFor(d.ID) { |
| 291 | return false, nil |
| 292 | } |
| 293 | } |
| 294 | r, found, err := t.hkLoad(team, person, d.ID, f.Key) |
| 295 | if err != nil { |
| 296 | return false, err |
| 297 | } |
| 298 | if found && !t.reclaimable(r) { |
| 299 | return false, nil |
| 300 | } |
| 301 | ev, _ := json.Marshal(f.Evidence) |
| 302 | now := t.hkNow() |
| 303 | if !found { |
| 304 | r = hkRecord{ID: newID("hk_"), Team: team, Person: person, Detector: d.ID, FindingKey: f.Key} |
| 305 | } else if r.State == wire.ActionFailed || r.State == wire.ActionVetoed { |
| 306 | r.Recurrences++ |
| 307 | } |
| 308 | r.SubjectKind, r.SubjectID, r.SubjectRevision, r.Class, r.Evidence = f.Subject.Kind, f.Subject.ID, f.SubjectRevision, d.Class, string(ev) |
| 309 | r.Reason, r.Attempt, r.Result, r.UndoneAt, r.UndoUntil, r.VisibleAt = "", "", "", nil, nil, nil |
| 310 | r.ReservedTurns, r.ReservedTokens, r.ReservedRetries = 0, 0, 0 |
| 311 | r.ChargedTurns, r.ChargedTokens, r.ChargedRetries, r.ChargedComplete, r.Releasing = 0, 0, 0, false, false |
| 312 | |
| 313 | // Room: the day's ceiling of actions, then the budget, then the |
| 314 | // selected connection. Lacking any, the finding is held. |
| 315 | if why, err := t.hkRoom(person, d); err != nil { |
| 316 | return false, err |
| 317 | } else if why != "" { |
| 318 | r.State, r.Reason, r.ClaimedAt = wire.ActionHeld, why, nil |
| 319 | if err := t.hkSave(&r, !found); err != nil { |
| 320 | return false, err |
| 321 | } |
| 322 | return false, t.hkHeldCap(person) |
| 323 | } |
| 324 | r.ClaimedAt = &now |
| 325 | r.ReservedTurns, r.ReservedTokens, r.ReservedRetries = d.Cost.Turns, d.Cost.Tokens, d.Cost.Retries |
| 326 | if !d.Cost.Zero() { |
| 327 | // A spending action commits its claim first and is dispatched on |
| 328 | // its own; nothing in slice 1 spends. |
| 329 | r.State = wire.ActionClaimed |
| 330 | return false, t.hkSave(&r, !found) |
| 331 | } |
| 332 | // The class decides what a finding may become, before anything runs: |
| 333 | // a link or propose detector never combines. |
| 334 | if !hkClassActions[d.Class][f.Proposal.Action] { |
| 335 | r.State, r.Reason = wire.ActionRefused, wire.ReasonHousekeepingForbidden |
| 336 | return false, t.hkSave(&r, !found) |
| 337 | } |
| 338 | // Deterministic and free: claim and act in one transaction. The |
| 339 | // action runs in a savepoint so a refusal or an error takes back |
| 340 | // everything it wrote and leaves only the row. |
| 341 | p := Principal{Team: team, Person: person, Detector: d.ID, FindingID: r.ID, Reserved: r.reserved()} |
| 342 | var res hkResult |
| 343 | err = t.savepoint(func(in *txn) error { |
| 344 | in.hk = &p |
| 345 | var e error |
| 346 | res, e = in.hkAct(&r, f) |
| 347 | return e |
| 348 | }) |
| 349 | switch { |
| 350 | case err == nil: |
| 351 | r.State = wire.ActionDone |
| 352 | raw, _ := json.Marshal(res) |
| 353 | r.Result = string(raw) |
| 354 | if d.Class == housekeeping.ClassAct { |
| 355 | until := now.Add(housekeeping.UndoWindow) |
| 356 | r.UndoUntil = &until |
| 357 | } |
| 358 | return true, t.hkSave(&r, !found) |
| 359 | case errors.Is(err, errNotFoldable): |
| 360 | // The facts moved under the finding: nothing to record. |
| 361 | return false, nil |
| 362 | case errors.Is(err, ErrHousekeepingForbidden): |
| 363 | r.State, r.Reason = wire.ActionRefused, wire.ReasonHousekeepingForbidden |
| 364 | r.VisibleAt = nil |
| 365 | return false, t.hkSave(&r, !found) |
| 366 | } |
| 367 | r.State, r.Reason = wire.ActionFailed, clip(err.Error(), 200) |
| 368 | if err := t.hkSave(&r, !found); err != nil { |
| 369 | return false, err |
| 370 | } |
| 371 | // Counted in its own transaction after this one ends, whatever its |
| 372 | // outcome: an error cannot erase its own record. |
| 373 | t.failures = append(t.failures, hkFailureRecord{Person: person, Detector: d.ID, Kind: failureFailed, ActionID: r.ID, At: now}) |
| 374 | return false, nil |
| 375 | } |
| 376 | |
| 377 | // savepoint runs fn in a nested transaction (a SQLite savepoint): an error |
| 378 | // rolls back only what fn wrote. |
| 379 | func (t *txn) savepoint(fn func(*txn) error) error { |
| 380 | return t.db.Transaction(func(tx *gorm.DB) error { |
| 381 | in := *t |
| 382 | in.db = tx |
| 383 | return fn(&in) |
| 384 | }) |
| 385 | } |
| 386 | |
| 387 | // errUnknownAction: a finding asked for an action the store does not know. |
| 388 | var errUnknownAction = errors.New("chat: housekeeping action unknown") |
| 389 | |
| 390 | // hkClassActions is what each class may carry out (spec §3): act |
| 391 | // combines; link links; propose and ask carry out nothing in slice 1. |
| 392 | var hkClassActions = map[string]map[string]bool{ |
| 393 | housekeeping.ClassAct: {housekeeping.ActionCombine: true}, |
| 394 | housekeeping.ClassLink: {housekeeping.ActionLink: true}, |
| 395 | housekeeping.ClassPropose: {}, |
| 396 | housekeeping.ClassAsk: {}, |
| 397 | } |
| 398 | |
| 399 | // hkActions are the proposals the store knows how to carry out, each |
| 400 | // through the same store functions a person's request uses. |
| 401 | var hkActions = map[string]func(t *txn, r *hkRecord, f housekeeping.Finding) (hkResult, error){ |
| 402 | housekeeping.ActionCombine: hkCombine, |
| 403 | housekeeping.ActionLink: hkLink, |
| 404 | } |
| 405 | |
| 406 | // hkAct carries out a finding's proposal under the principal. |
| 407 | func (t *txn) hkAct(r *hkRecord, f housekeeping.Finding) (hkResult, error) { |
| 408 | act, ok := hkActions[f.Proposal.Action] |
| 409 | if !ok { |
| 410 | return hkResult{}, fmt.Errorf("%w: %q", errUnknownAction, f.Proposal.Action) |
| 411 | } |
| 412 | return act(t, r, f) |
| 413 | } |
| 414 | |
| 415 | // hkCombine folds the finding's task into the one that keeps the work; |
| 416 | // the receipt waits for quiet hours to end. |
| 417 | func hkCombine(t *txn, r *hkRecord, f housekeeping.Finding) (hkResult, error) { |
| 418 | k, err := t.loadTask(f.Proposal.Task) |
| 419 | if err != nil { |
| 420 | return hkResult{}, err |
| 421 | } |
| 422 | into, err := t.loadTask(f.Proposal.Into) |
| 423 | if err != nil { |
| 424 | return hkResult{}, err |
| 425 | } |
| 426 | res := hkResult{Action: f.Proposal.Action, Task: k.ID, Into: into.ID, Stage: k.Stage, DuplicateOf: k.DuplicateOf, TaskRev: k.Revision, IntoRev: into.Revision} |
| 427 | set, err := t.hkSettings(t.hk.Person) |
| 428 | if err != nil { |
| 429 | return hkResult{}, err |
| 430 | } |
| 431 | r.VisibleAt = set.quiet().VisibleAt(t.hkNow(), t.zone(t.hk.Person)) |
| 432 | res.CardID, err = t.fold(k, into, r.ID, r.VisibleAt) |
| 433 | return res, err |
| 434 | } |
| 435 | |
| 436 | // hkLink names a possible duplicate on the finding's task. |
| 437 | func hkLink(t *txn, _ *hkRecord, f housekeeping.Finding) (hkResult, error) { |
| 438 | k, err := t.loadTask(f.Proposal.Task) |
| 439 | if err != nil { |
| 440 | return hkResult{}, err |
| 441 | } |
| 442 | if k.DuplicateOf != "" { |
| 443 | return hkResult{}, errNotFoldable |
| 444 | } |
| 445 | into, err := t.loadTask(f.Proposal.Into) |
| 446 | if err != nil { |
| 447 | return hkResult{}, err |
| 448 | } |
| 449 | if wire.NormalKind(into.Kind) != wire.NormalKind(k.Kind) { |
| 450 | return hkResult{}, errNotFoldable |
| 451 | } |
| 452 | k.DuplicateOf = f.Proposal.Into |
| 453 | if err := t.saveTask(&k); err != nil { |
| 454 | return hkResult{}, err |
| 455 | } |
| 456 | return hkResult{Action: f.Proposal.Action, Task: k.ID, Into: f.Proposal.Into}, nil |
| 457 | } |
| 458 | |
| 459 | // hkRoom says why a finding must wait, or "" when it may be claimed now. |
| 460 | // The sums read in this transaction, so two claims racing the last unit |
| 461 | // cannot both pass. |
| 462 | func (t *txn) hkRoom(person string, d housekeeping.Detector) (string, error) { |
| 463 | if person == "" { |
| 464 | return "", nil |
| 465 | } |
| 466 | day := housekeeping.DayStart(t.hkNow(), t.zone(person)) |
| 467 | if d.Class == housekeeping.ClassAct { |
| 468 | var n int64 |
| 469 | if err := t.db.Model(&hkRecord{}).Where("person = ? AND class = ? AND state IN ? AND claimed_at >= ?", person, housekeeping.ClassAct, []string{wire.ActionClaimed, wire.ActionDone, wire.ActionUndone}, day).Count(&n).Error; err != nil { |
| 470 | return "", err |
| 471 | } |
| 472 | if n >= housekeeping.ActionsPerDay { |
| 473 | return wire.ReasonHeldCeiling, nil |
| 474 | } |
| 475 | } |
| 476 | if d.Cost.Zero() { |
| 477 | return "", nil |
| 478 | } |
| 479 | used, _, err := t.hkUsed(person, day) |
| 480 | if err != nil { |
| 481 | return "", err |
| 482 | } |
| 483 | if !housekeeping.Fits(used, d.Cost, housekeeping.Limits) { |
| 484 | return wire.ReasonHeldBudget, nil |
| 485 | } |
| 486 | h, err := t.selectedHeadroom(person) |
| 487 | if err != nil { |
| 488 | return "", err |
| 489 | } |
| 490 | if housekeeping.StandDown(h, t.hkNow()) != "" { |
| 491 | return wire.ReasonHeldStandDown, nil |
| 492 | } |
| 493 | return "", nil |
| 494 | } |
| 495 | |
| 496 | // hkUsed is what today's rows count against the budget (an open |
| 497 | // reservation in full, else what was charged), and the charged part alone. |
| 498 | func (t *txn) hkUsed(person string, day time.Time) (used, charged housekeeping.Cost, err error) { |
| 499 | var rows []hkRecord |
| 500 | if err = t.db.Where("person = ? AND claimed_at >= ? AND (reserved_turns > 0 OR reserved_tokens > 0 OR reserved_retries > 0 OR reserved_rounds > 0 OR charged_tokens > 0 OR charged_retries > 0 OR charged_rounds > 0)", person, day).Find(&rows).Error; err != nil { |
| 501 | return used, charged, err |
| 502 | } |
| 503 | for _, r := range rows { |
| 504 | c := r.charged() |
| 505 | if r.Class == classTriage { |
| 506 | // Needs-you triage records its steps' tokens; they are never a |
| 507 | // budget (spec 2026-11-11 needs-you triage §2.4). |
| 508 | c.Tokens = 0 |
| 509 | } |
| 510 | charged = charged.Add(c) |
| 511 | if r.open() { |
| 512 | res := r.reserved() |
| 513 | c = housekeeping.Cost{Turns: max(c.Turns, res.Turns), Tokens: max(c.Tokens, res.Tokens), Retries: max(c.Retries, res.Retries), Rounds: max(c.Rounds, res.Rounds)} |
| 514 | } |
| 515 | used = used.Add(c) |
| 516 | } |
| 517 | return used, charged, nil |
| 518 | } |
| 519 | |
| 520 | // hkHeldCap keeps at most HeldPerPerson held rows: the oldest expire. |
| 521 | func (t *txn) hkHeldCap(person string) error { |
| 522 | var held []hkRecord |
| 523 | if err := t.db.Where("person = ? AND state = ?", person, wire.ActionHeld).Order("at DESC, id DESC").Find(&held).Error; err != nil { |
| 524 | return err |
| 525 | } |
| 526 | for i := housekeeping.HeldPerPerson; i < len(held); i++ { |
| 527 | held[i].State, held[i].Reason = wire.ActionExpired, wire.ReasonHeldOverflow |
| 528 | if err := t.hkSave(&held[i], false); err != nil { |
| 529 | return err |
| 530 | } |
| 531 | } |
| 532 | return nil |
| 533 | } |
| 534 | |
| 535 | // hkSettle reconciles a spending row's reservation: charged is what the |
| 536 | // attempt's usage said (nil when no figure came, which charges the whole |
| 537 | // reservation), terminated whether its termination proof is in. Until |
| 538 | // both are in, the row stays releasing and counts in full. |
| 539 | func (t *txn) hkSettle(r *hkRecord, charged *housekeeping.Cost, complete, terminated bool) error { |
| 540 | if charged == nil { |
| 541 | res := r.reserved() |
| 542 | charged, complete = &res, false |
| 543 | } |
| 544 | r.ChargedTurns, r.ChargedTokens, r.ChargedRetries, r.ChargedComplete = charged.Turns, charged.Tokens, charged.Retries, complete |
| 545 | r.Releasing = !terminated |
| 546 | return t.hkSave(r, false) |
| 547 | } |
| 548 | |
| 549 | // --- The duplicate detectors' view and pass. |
| 550 | |
| 551 | // duplicateView reads one project's open tasks as the detectors see them. |
| 552 | func (t *txn) duplicateView(projectID string) (housekeeping.View, error) { |
| 553 | v := housekeeping.View{Project: projectID} |
| 554 | var open []taskRecord |
| 555 | if err := t.db.Where("project_id = ? AND stage NOT IN ? AND cancel_requested = ? AND (folded_into IS NULL OR folded_into = '')", projectID, []string{wire.StageDone, wire.StageCancelled}, false).Order("created_at, id").Find(&open).Error; err != nil { |
| 556 | return v, err |
| 557 | } |
| 558 | if len(open) < 2 { |
| 559 | return v, nil |
| 560 | } |
| 561 | ids := make([]string, len(open)) |
| 562 | for i, k := range open { |
| 563 | ids[i] = k.ID |
| 564 | } |
| 565 | var distinct []distinctRecord |
| 566 | if err := t.db.Where("a IN ? AND b IN ?", ids, ids).Find(&distinct).Error; err != nil { |
| 567 | return v, err |
| 568 | } |
| 569 | for _, d := range distinct { |
| 570 | v.Distinct = append(v.Distinct, [2]string{d.A, d.B}) |
| 571 | } |
| 572 | var steps []stepRecord |
| 573 | if err := t.db.Where("task_id IN ?", ids).Order("task_id, idx").Find(&steps).Error; err != nil { |
| 574 | return v, err |
| 575 | } |
| 576 | last := map[string]stepRecord{} |
| 577 | byTask := map[string][]stepRecord{} |
| 578 | for _, s := range steps { |
| 579 | last[s.TaskID] = s |
| 580 | byTask[s.TaskID] = append(byTask[s.TaskID], s) |
| 581 | } |
| 582 | // Decided: the task's newest merge card (one per SHA asked) was |
| 583 | // answered, and the SHA it asked about is still the candidate. Only |
| 584 | // the task's creator answers a merge card (answerMerge). |
| 585 | var merges []cardRecord |
| 586 | if err := t.db.Select("task_id", "state").Where("task_id IN ? AND kind = ?", ids, wire.CardMerge).Order("created_at, rowid").Find(&merges).Error; err != nil { |
| 587 | return v, err |
| 588 | } |
| 589 | answered := map[string]bool{} |
| 590 | for _, c := range merges { |
| 591 | answered[c.TaskID] = c.State == wire.CardAnswered |
| 592 | } |
| 593 | var carded []string |
| 594 | if err := t.db.Model(&cardRecord{}).Where("task_id IN ? AND state = ? AND kind <> ?", ids, wire.CardOpen, wire.CardTask).Pluck("task_id", &carded).Error; err != nil { |
| 595 | return v, err |
| 596 | } |
| 597 | isCarded := map[string]bool{} |
| 598 | for _, id := range carded { |
| 599 | isCarded[id] = true |
| 600 | } |
| 601 | hidden := t.s.authority.TestPerson |
| 602 | for _, k := range open { |
| 603 | s, ok := last[k.ID] |
| 604 | decided := answered[k.ID] && k.MergeAsked != "" && k.MergeAsked == progressFor(k, byTask[k.ID]).candidate |
| 605 | v.Tasks = append(v.Tasks, housekeeping.TaskFact{ID: k.ID, Title: k.Title, Brief: k.Brief, Creator: k.Creator, Stage: k.Stage, Revision: k.Revision, CreatedAt: k.CreatedAt, DuplicateOf: k.DuplicateOf, |
| 606 | Stopped: ok && s.State == wire.StepFailed, Busy: ok && (s.State == wire.StepRunning || s.State == wire.StepQueued), Carded: isCarded[k.ID], Decided: decided, Hidden: hidden != nil && hidden(k.Creator), Kind: wire.NormalKind(k.Kind)}) |
| 607 | } |
| 608 | return v, nil |
| 609 | } |
| 610 | |
| 611 | // housekeepingPass runs the detectors on trigger over one project until |
| 612 | // nothing more changes, re-reading the facts after each action. It |
| 613 | // returns how many tasks were combined. |
| 614 | func (t *txn) housekeepingPass(trigger, projectID string) (int, error) { |
| 615 | reg := t.s.registry() |
| 616 | combined := 0 |
| 617 | for range 20 { |
| 618 | v, err := t.duplicateView(projectID) |
| 619 | if err != nil { |
| 620 | return combined, err |
| 621 | } |
| 622 | moved := false |
| 623 | for _, f := range reg.Run(trigger, v) { |
| 624 | d, _ := reg.Get(f.Detector) |
| 625 | did, err := t.hkRun(d, f) |
| 626 | if err != nil { |
| 627 | return combined, err |
| 628 | } |
| 629 | if did { |
| 630 | if f.Proposal.Action == housekeeping.ActionCombine { |
| 631 | combined++ |
| 632 | } |
| 633 | moved = true |
| 634 | break |
| 635 | } |
| 636 | } |
| 637 | if !moved { |
| 638 | return combined, nil |
| 639 | } |
| 640 | } |
| 641 | return combined, nil |
| 642 | } |
| 643 | |