| 1 | package chat |
| 2 | |
| 3 | import ( |
| 4 | "encoding/json" |
| 5 | "errors" |
| 6 | "slices" |
| 7 | "strings" |
| 8 | |
| 9 | "gorm.io/gorm" |
| 10 | |
| 11 | "amadan.net/oficina/equipo/internal/specialist" |
| 12 | "amadan.net/oficina/equipo/internal/wire" |
| 13 | ) |
| 14 | |
| 15 | // Routing work to a maker specialist (dynamic specialists §1, Routing; |
| 16 | // §4, Budget; plan task 17). status lists the team's active specialists; |
| 17 | // start_task's specialist makes one of them the task's maker, and every |
| 18 | // Engineering step of the task (its first run, retries, fix rounds, Try |
| 19 | // again, and the task Build this makes) runs as that maker. A Design step |
| 20 | // goes only to a runner that can run Design, else it waits |
| 21 | // (wire.PlacementDesign). Without a word from its person a task runs at |
| 22 | // most wire.DesignRunLimit Design attempts; the next is held for them |
| 23 | // through the held-step card (wire.PlacementDesignLimit). Once its maker |
| 24 | // is removed and every attempt of its steps has ended with its end |
| 25 | // proven, its creator is asked once whether to hand it to Engineering |
| 26 | // (wire.CardMakerRemoved). |
| 27 | |
| 28 | // Tool results for start_task's specialist, read by the model. |
| 29 | const ( |
| 30 | toolStartNoSpecialist = "Refused: no active specialist has that id. Call status to see the team's specialists, or start the task without specialist and Engineering does the work. Nothing was started." |
| 31 | toolStartNotMaker = "Refused: that specialist does not change a task's files, so it cannot do a task's work. Start the task without specialist and Engineering does the work. Nothing was started." |
| 32 | toolStartOtherProject = "Refused: that specialist works on another project, not this task's. Call status to see which specialist covers this task's project. Nothing was started." |
| 33 | toolStartNoGrant = "Refused: that specialist cannot work on this task's project now: another specialist covers the project, or its approval no longer holds. Call status, then start the task with the one that covers it, or without specialist for Engineering. Nothing was started." |
| 34 | // toolStartedDesign is toolStarted for a task Design makes. |
| 35 | toolStartedDesign = "Design is working on it on the task's branch; then its work is reviewed, and the person decides what happens with it. Reply in one or two lines at the outcome level, naming the task as a markdown link, and do not wait." |
| 36 | ) |
| 37 | |
| 38 | // Why a Design step waits, on the step while it waits (its Reason; the |
| 39 | // task page's words for it are work.reason.<reason>): the runner it would |
| 40 | // run on is below wire.ProtocolDesign, its page renderer is not ok, the |
| 41 | // person has no Claude connection there, or the autonomy limit holds it. |
| 42 | const ( |
| 43 | reasonDesignProtocol = "design_runner_old" |
| 44 | reasonDesignRenderer = "design_renderer" |
| 45 | reasonDesignClaude = "design_no_claude" |
| 46 | reasonDesignLimit = "design_limit" |
| 47 | ) |
| 48 | |
| 49 | var designWaitReasons = []string{reasonDesignProtocol, reasonDesignRenderer, reasonDesignClaude, reasonDesignLimit} |
| 50 | |
| 51 | // makerProfile reports whether a profile makes a task's changes: it holds |
| 52 | // branch.edit (design-v1 does; research-v1 never does). |
| 53 | func makerProfile(profile string) bool { |
| 54 | p, ok := specialist.Lookup(profile) |
| 55 | return ok && slices.Contains(p.Capabilities, specialist.CapabilityBranchEdit) |
| 56 | } |
| 57 | |
| 58 | // routeMaker is the maker a person turn's start_task names: an active |
| 59 | // specialist whose profile is a maker, scoped to the task's project or |
| 60 | // the team, whose grant grantFor finds for the task's project now (so a |
| 61 | // team row is refused where the project has its own). A task the person |
| 62 | // cannot start is left to startTask, which refuses it as before. |
| 63 | func (t *txn) routeMaker(r turnRecord, task, id string) (string, *wire.ToolResult, error) { |
| 64 | k, res, err := t.ownTask(r.Person, task) |
| 65 | if res != nil || err != nil { |
| 66 | return "", nil, err |
| 67 | } |
| 68 | refuse := func(code, text string) (string, *wire.ToolResult, error) { |
| 69 | res := refused(code, text) |
| 70 | return "", &res, nil |
| 71 | } |
| 72 | var sp specialistRecord |
| 73 | if err := t.db.Where("id = ?", id).Limit(1).Find(&sp).Error; err != nil { |
| 74 | return "", nil, err |
| 75 | } |
| 76 | switch { |
| 77 | case sp.ID == "" || sp.State != wire.SpecialistActive: |
| 78 | return refuse("specialist_unknown", toolStartNoSpecialist) |
| 79 | case !makerProfile(sp.Profile): |
| 80 | return refuse("specialist_not_maker", toolStartNotMaker) |
| 81 | case sp.ProjectID != "" && sp.ProjectID != k.ProjectID: |
| 82 | return refuse("specialist_project", toolStartOtherProject) |
| 83 | } |
| 84 | found, err := t.grantFor(sp.Profile, k.ProjectID) |
| 85 | if err != nil { |
| 86 | return "", nil, err |
| 87 | } |
| 88 | if found == nil || found.ID != sp.ID { |
| 89 | return refuse("specialist_no_grant", toolStartNoGrant) |
| 90 | } |
| 91 | return sp.ID, nil, nil |
| 92 | } |
| 93 | |
| 94 | // designCause is why the runner a Design step of person would run on |
| 95 | // cannot run it now ("" when it can): it speaks wire.ProtocolDesign, its |
| 96 | // page renderer said ok, and the person has a Claude connection there |
| 97 | // that is not an API key's (the runner runs Design on Claude only). |
| 98 | func (t *txn) designCause(person, runner string) (string, error) { |
| 99 | var sess runnerSessionRecord |
| 100 | if err := t.db.Where("runner_id = ?", runner).Limit(1).Find(&sess).Error; err != nil { |
| 101 | return "", err |
| 102 | } |
| 103 | if sess.RunnerID == "" || sess.Protocol < wire.ProtocolDesign { |
| 104 | return reasonDesignProtocol, nil |
| 105 | } |
| 106 | var h wire.Hello |
| 107 | if sess.Hello == "" || json.Unmarshal([]byte(sess.Hello), &h) != nil || toolHealth(h).Renderer != wire.ToolHealthy { |
| 108 | return reasonDesignRenderer, nil |
| 109 | } |
| 110 | claude := func(c wire.HeldConnection) bool { |
| 111 | return c.Person == person && c.Provider == wire.ProviderClaude && c.Kind != wire.KindAPIKey |
| 112 | } |
| 113 | if !slices.ContainsFunc(h.Connections, claude) { |
| 114 | return reasonDesignClaude, nil |
| 115 | } |
| 116 | return "", nil |
| 117 | } |
| 118 | |
| 119 | // designGate decides, at a maker step's dispatch, whether it goes now: |
| 120 | // held for the person when the task ran wire.DesignRunLimit Design |
| 121 | // attempts since they last acted on it (the held-step card asks them), |
| 122 | // waiting when its runner cannot run Design; otherwise nothing of a wait |
| 123 | // stays on it. held reports that it does not go. The caller saves s. |
| 124 | func (t *txn) designGate(k *taskRecord, s *stepRecord) (held bool, err error) { |
| 125 | now := t.now() |
| 126 | if k.DesignRuns >= wire.DesignRunLimit { |
| 127 | s.RunnerID, s.Placement, s.Reason, s.WaitingSince = "", wire.PlacementDesignLimit, reasonDesignLimit, &now |
| 128 | if h := stepHold(*s); h == nil || h.Reason != wire.HoldDesignLimit || h.StepRevision != s.Attempt { |
| 129 | s.Hold, s.HeldAt = asJSON(wire.StepHold{Reason: wire.HoldDesignLimit, NeedsPerson: wire.HoldDesignLimit, StepRevision: s.Attempt}), &now |
| 130 | } |
| 131 | return true, t.heldCard(*k, *s) |
| 132 | } |
| 133 | if h := stepHold(*s); h != nil && h.Reason == wire.HoldDesignLimit { |
| 134 | s.Hold, s.HeldAt = "", nil |
| 135 | if err := t.closeHeldCards(k.ID, ""); err != nil { |
| 136 | return false, err |
| 137 | } |
| 138 | } |
| 139 | cause, err := t.designCause(s.Person, s.RunnerID) |
| 140 | if err != nil { |
| 141 | return false, err |
| 142 | } |
| 143 | if cause != "" { |
| 144 | s.RunnerID, s.Placement, s.Reason, s.WaitingSince = "", wire.PlacementDesign, cause, &now |
| 145 | return true, nil |
| 146 | } |
| 147 | if slices.Contains(designWaitReasons, s.Reason) { |
| 148 | s.Reason = "" |
| 149 | } |
| 150 | return false, nil |
| 151 | } |
| 152 | |
| 153 | // designRan counts one Design attempt sent for the task. |
| 154 | func (t *txn) designRan(k *taskRecord) error { |
| 155 | k.DesignRuns++ |
| 156 | return t.db.Model(&taskRecord{}).Where("id = ?", k.ID).UpdateColumn("design_runs", gorm.Expr("design_runs + 1")).Error |
| 157 | } |
| 158 | |
| 159 | // personActed is person (the session's) acting on task id (a message in |
| 160 | // its thread, an answer on one of its cards, Run it now): when they are |
| 161 | // the task's creator and an owner now, read in this transaction, its |
| 162 | // Design attempts count from none again and acted is true. Anyone else's |
| 163 | // act (a teammate following the thread) resets nothing, and the caller |
| 164 | // releases nothing: held Design work spends the creator's connections. |
| 165 | // It dispatches nothing (releaseDesignHeld does, after the act). |
| 166 | func (t *txn) personActed(id, person string) (acted bool, err error) { |
| 167 | k, err := t.loadTask(id) |
| 168 | if errors.Is(err, ErrNotFound) { |
| 169 | return false, nil |
| 170 | } |
| 171 | if err != nil || person == "" || k.Creator != person { |
| 172 | return false, err |
| 173 | } |
| 174 | if err := t.isOwner(person); errors.Is(err, ErrForbidden) { |
| 175 | return false, nil |
| 176 | } else if err != nil { |
| 177 | return false, err |
| 178 | } |
| 179 | return true, t.db.Model(&taskRecord{}).Where("id = ? AND design_runs <> 0", id).UpdateColumn("design_runs", 0).Error |
| 180 | } |
| 181 | |
| 182 | // releaseDesignHeld dispatches the task's steps the autonomy limit held, |
| 183 | // once its person acted on it. |
| 184 | func (t *txn) releaseDesignHeld(id string) error { |
| 185 | var rows []stepRecord |
| 186 | if err := t.db.Where("task_id = ? AND state = ? AND placement = ? AND coalesce(retired, 0) = 0", id, wire.StepQueued, wire.PlacementDesignLimit).Order("idx").Find(&rows).Error; err != nil || len(rows) == 0 { |
| 187 | return err |
| 188 | } |
| 189 | k, err := t.loadTask(id) |
| 190 | if err != nil { |
| 191 | return err |
| 192 | } |
| 193 | if wire.FinalStage(k.Stage) || k.CancelRequested || k.MoveProject != "" { |
| 194 | return nil |
| 195 | } |
| 196 | for i := range rows { |
| 197 | s := rows[i] |
| 198 | if err := t.dispatchStep(&k, &s); err != nil { |
| 199 | return err |
| 200 | } |
| 201 | if err := t.saveStep(&s, &k); err != nil { |
| 202 | return err |
| 203 | } |
| 204 | } |
| 205 | return nil |
| 206 | } |
| 207 | |
| 208 | // recoveryName binds a recovery card to the task's maker: one card per |
| 209 | // task and removed maker, ever. |
| 210 | func recoveryName(maker string) string { return "maker:" + maker } |
| 211 | |
| 212 | // recoverable reports whether the task waits for its creator to hand it |
| 213 | // to Engineering: open; its maker can no longer act for the task's |
| 214 | // project (grantFor no longer finds the maker's row there: revoked, its |
| 215 | // scope no longer the task's project after a move, its approver no |
| 216 | // longer an owner, its profile off the menu, or the row gone); every |
| 217 | // attempt of its maker's steps ended with its end proven (Terminated, |
| 218 | // whatever its state, done included); and nothing of the task at work |
| 219 | // (busy). |
| 220 | func (t *txn) recoverable(k taskRecord) (bool, error) { |
| 221 | gone, err := t.makerGone(k) |
| 222 | if err != nil || !gone { |
| 223 | return false, err |
| 224 | } |
| 225 | steps, err := t.steps(k.ID) |
| 226 | if err != nil { |
| 227 | return false, err |
| 228 | } |
| 229 | for _, s := range steps { |
| 230 | // Terminated is the end's proof; an attempt still at work has none. |
| 231 | if s.Specialist == wire.SpecialistEngineering && !s.Terminated { |
| 232 | return false, nil |
| 233 | } |
| 234 | } |
| 235 | return !busy(steps, false), nil |
| 236 | } |
| 237 | |
| 238 | // makerGone reports whether the task is open (not cancel-requested, not |
| 239 | // moving) and its maker no longer acts for its project: grantFor no |
| 240 | // longer finds the maker's row there. |
| 241 | func (t *txn) makerGone(k taskRecord) (bool, error) { |
| 242 | if k.MakerSpecialistID == "" || wire.FinalStage(k.Stage) || k.CancelRequested || k.MoveProject != "" { |
| 243 | return false, nil |
| 244 | } |
| 245 | var sp specialistRecord |
| 246 | if err := t.db.Where("id = ?", k.MakerSpecialistID).Limit(1).Find(&sp).Error; err != nil { |
| 247 | return false, err |
| 248 | } |
| 249 | if sp.ID != "" { |
| 250 | found, err := t.grantFor(sp.Profile, k.ProjectID) |
| 251 | if err != nil || found != nil && found.ID == sp.ID { |
| 252 | return false, err |
| 253 | } |
| 254 | } |
| 255 | return true, nil |
| 256 | } |
| 257 | |
| 258 | // settleUndispatched ends, as never started, the Engineering steps of a |
| 259 | // task whose maker is gone that were never given to a runner: queued, no |
| 260 | // runner, no attempt started (held by the autonomy limit, or waiting for |
| 261 | // a runner that can run Design). Nothing of them ran, so no termination |
| 262 | // proof is owed; their holds and held cards close. A step placed on a |
| 263 | // runner could have run and is left to its proof. |
| 264 | func (t *txn) settleUndispatched(k *taskRecord) error { |
| 265 | var rows []stepRecord |
| 266 | if err := t.db.Where("task_id = ? AND specialist = ? AND state = ? AND coalesce(runner_id, '') = '' AND started_at IS NULL AND coalesce(retired, 0) = 0", k.ID, wire.SpecialistEngineering, wire.StepQueued).Order("idx").Find(&rows).Error; err != nil || len(rows) == 0 { |
| 267 | return err |
| 268 | } |
| 269 | now := t.now() |
| 270 | for i := range rows { |
| 271 | s := &rows[i] |
| 272 | s.State, s.Reason, s.Terminated, s.FinishedAt, s.Placement, s.WaitingSince, s.Hold, s.HeldAt = wire.StepCancelled, reasonSpecialistNoGrant, true, &now, "", nil, "", nil |
| 273 | if err := t.saveStep(s, k); err != nil { |
| 274 | return err |
| 275 | } |
| 276 | } |
| 277 | return t.closeHeldCards(k.ID, "") |
| 278 | } |
| 279 | |
| 280 | // offerRecovery asks the task's creator, once, whether to hand the task |
| 281 | // to Engineering, when it is recoverable: first its steps that never |
| 282 | // reached a runner are settled (settleUndispatched). |
| 283 | func (t *txn) offerRecovery(id string) error { |
| 284 | k, err := t.loadTask(id) |
| 285 | if err != nil { |
| 286 | return err |
| 287 | } |
| 288 | gone, err := t.makerGone(k) |
| 289 | if err != nil || !gone { |
| 290 | return err |
| 291 | } |
| 292 | if err := t.settleUndispatched(&k); err != nil { |
| 293 | return err |
| 294 | } |
| 295 | ok, err := t.recoverable(k) |
| 296 | if err != nil || !ok { |
| 297 | return err |
| 298 | } |
| 299 | name := recoveryName(k.MakerSpecialistID) |
| 300 | var n int64 |
| 301 | if err := t.db.Model(&cardRecord{}).Where("task_id = ? AND kind = ? AND name = ?", k.ID, wire.CardMakerRemoved, name).Count(&n).Error; err != nil || n > 0 { |
| 302 | return err |
| 303 | } |
| 304 | var sp specialistRecord |
| 305 | if err := t.db.Where("id = ?", k.MakerSpecialistID).Limit(1).Find(&sp).Error; err != nil { |
| 306 | return err |
| 307 | } |
| 308 | who := t.words("chat.specialist.profile." + sp.Profile) |
| 309 | if who == "" { |
| 310 | who = sp.Name |
| 311 | } |
| 312 | question := t.words("chat.card.maker_removed", who) |
| 313 | options, _ := json.Marshal([]string{wire.ChoiceToEngineering}) |
| 314 | now := t.now() |
| 315 | c := cardRecord{ID: newID("c_"), Person: k.Creator, Kind: wire.CardMakerRemoved, State: wire.CardOpen, ProjectID: k.ProjectID, TaskID: k.ID, Name: name, Question: question, Options: string(options), Revision: 1, CreatedAt: now, UpdatedAt: now, Lane: k.Lane} |
| 316 | if err := t.db.Create(&c).Error; err != nil { |
| 317 | return err |
| 318 | } |
| 319 | return t.cardEvent(c) |
| 320 | } |
| 321 | |
| 322 | // offerRecoveriesAll offers the recovery card for every open task that |
| 323 | // has a maker: the placement pass's sweep, for a maker that stopped |
| 324 | // resolving with no step event (an approver demoted, a profile taken off |
| 325 | // the menu). |
| 326 | func (t *txn) offerRecoveriesAll() error { |
| 327 | var ids []string |
| 328 | if err := t.db.Model(&taskRecord{}).Where("maker_specialist_id <> '' AND stage NOT IN ?", []string{wire.StageDone, wire.StageCancelled}).Order("created_at, id").Pluck("id", &ids).Error; err != nil { |
| 329 | return err |
| 330 | } |
| 331 | for _, id := range ids { |
| 332 | if err := t.offerRecovery(id); err != nil { |
| 333 | return err |
| 334 | } |
| 335 | } |
| 336 | return nil |
| 337 | } |
| 338 | |
| 339 | // offerRecoveries offers the recovery card for every task sp made. |
| 340 | func (t *txn) offerRecoveries(sp specialistRecord) error { |
| 341 | var ids []string |
| 342 | if err := t.db.Model(&taskRecord{}).Where("maker_specialist_id = ?", sp.ID).Order("created_at, id").Pluck("id", &ids).Error; err != nil { |
| 343 | return err |
| 344 | } |
| 345 | for _, id := range ids { |
| 346 | if err := t.offerRecovery(id); err != nil { |
| 347 | return err |
| 348 | } |
| 349 | } |
| 350 | return nil |
| 351 | } |
| 352 | |
| 353 | // answerMakerRemoved is the creator's tap on the recovery card: checked |
| 354 | // again in its transaction (the task is still recoverable), it clears the |
| 355 | // maker and queues Engineering on the task, from the task's base as a |
| 356 | // Retry does. |
| 357 | func (t *txn) answerMakerRemoved(person string, c cardRecord, in wire.AnswerCard) (wire.Card, wire.Card, error) { |
| 358 | v, err := t.cardView(c) |
| 359 | if err != nil { |
| 360 | return wire.Card{}, wire.Card{}, err |
| 361 | } |
| 362 | if in.Choice != wire.ChoiceToEngineering { |
| 363 | return wire.Card{}, wire.Card{}, ErrInvalid |
| 364 | } |
| 365 | if c.State != wire.CardOpen || c.Revision != in.Revision { |
| 366 | return wire.Card{}, v, ErrCardConflict |
| 367 | } |
| 368 | k, err := t.loadTask(c.TaskID) |
| 369 | if err != nil { |
| 370 | return wire.Card{}, wire.Card{}, err |
| 371 | } |
| 372 | if k.Creator != person || c.Person != person { |
| 373 | return wire.Card{}, wire.Card{}, ErrForbidden |
| 374 | } |
| 375 | if err := t.isOwner(person); err != nil { |
| 376 | return wire.Card{}, wire.Card{}, err |
| 377 | } |
| 378 | ok, err := t.recoverable(k) |
| 379 | if err != nil { |
| 380 | return wire.Card{}, wire.Card{}, err |
| 381 | } |
| 382 | if !ok { |
| 383 | return wire.Card{}, v, ErrCardConflict |
| 384 | } |
| 385 | c.State, c.Choice = wire.CardAnswered, in.Choice |
| 386 | if err := t.saveCard(&c); err != nil { |
| 387 | return wire.Card{}, wire.Card{}, err |
| 388 | } |
| 389 | if err := t.db.Model(&taskRecord{}).Where("id = ?", k.ID).UpdateColumns(map[string]any{"maker_specialist_id": "", "design_runs": 0}).Error; err != nil { |
| 390 | return wire.Card{}, wire.Card{}, err |
| 391 | } |
| 392 | maker := k.MakerSpecialistID |
| 393 | k.MakerSpecialistID, k.DesignRuns = "", 0 |
| 394 | if err := t.withdrawDirection(k); err != nil { |
| 395 | return wire.Card{}, wire.Card{}, err |
| 396 | } |
| 397 | steps, err := t.steps(k.ID) |
| 398 | if err != nil { |
| 399 | return wire.Card{}, wire.Card{}, err |
| 400 | } |
| 401 | k.Stage, k.DirectionAsked = wire.StageInProgress, "" |
| 402 | if err := t.nextStep(&k, steps, stepRecord{Specialist: wire.SpecialistEngineering, Person: k.Creator}); err != nil { |
| 403 | return wire.Card{}, wire.Card{}, err |
| 404 | } |
| 405 | if err := t.audit(person, "task.maker_removed", k.ID+":"+maker); err != nil { |
| 406 | return wire.Card{}, wire.Card{}, err |
| 407 | } |
| 408 | out, err := t.cardView(c) |
| 409 | return out, wire.Card{}, err |
| 410 | } |
| 411 | |
| 412 | // specialistLine is one active specialist as status shows it: scope is |
| 413 | // team, or the name of the one project it works on. |
| 414 | type specialistLine struct { |
| 415 | ID string `json:"id"` |
| 416 | Profile string `json:"profile"` |
| 417 | Name string `json:"name"` |
| 418 | Brief string `json:"brief"` |
| 419 | Scope string `json:"scope"` |
| 420 | } |
| 421 | |
| 422 | // specialistLines are the team's active specialists, for status. |
| 423 | func (t *txn) specialistLines() ([]specialistLine, error) { |
| 424 | var rows []specialistRecord |
| 425 | if err := t.db.Where("state = ?", wire.SpecialistActive).Order("profile, project_id, id").Find(&rows).Error; err != nil { |
| 426 | return nil, err |
| 427 | } |
| 428 | out := []specialistLine{} |
| 429 | for _, sp := range rows { |
| 430 | line := specialistLine{ID: sp.ID, Profile: sp.Profile, Name: sp.Name, Brief: sp.Brief, Scope: "team"} |
| 431 | if sp.ProjectID != "" { |
| 432 | var p projectRecord |
| 433 | if err := t.db.Where("id = ?", sp.ProjectID).Limit(1).Find(&p).Error; err != nil { |
| 434 | return nil, err |
| 435 | } |
| 436 | line.Scope = strings.TrimSpace(ProjectName(p.Repo)) |
| 437 | if p.ID == "" { |
| 438 | line.Scope = sp.ProjectID |
| 439 | } |
| 440 | } |
| 441 | out = append(out, line) |
| 442 | } |
| 443 | return out, nil |
| 444 | } |
| 445 | |