| 1 | package chat |
| 2 | |
| 3 | import ( |
| 4 | "encoding/json" |
| 5 | "errors" |
| 6 | "fmt" |
| 7 | "slices" |
| 8 | "strconv" |
| 9 | "strings" |
| 10 | "time" |
| 11 | |
| 12 | "amadan.net/oficina/equipo/internal/wire" |
| 13 | ) |
| 14 | |
| 15 | // The continuation after an owner's Add on a specialist card for one |
| 16 | // project (spec 2026-11-28-dynamic-specialists.md, section 1, Routing). |
| 17 | // The Add, in its transaction, queues one coordinator turn of kind |
| 18 | // wire.TurnSpecialistAdded in the proposing turn's lane, keyed by the |
| 19 | // card: a second Add, a double tap or a retry queues nothing. Its opening |
| 20 | // is Equipo's record of the Add, from canonical names only, under |
| 21 | // Equipo's label; the project's title and the name the coordinator chose |
| 22 | // quoted under their sources; and the proposing turn's messages, complete, |
| 23 | // each under its source: the person's own typed words, or a choice they |
| 24 | // tapped among options the model wrote (AGENTS.md, model text and |
| 25 | // authority, rules 1 and 3). When they cannot all be carried, nothing is |
| 26 | // queued and Equipo asks the person what next. The turn is bound to the |
| 27 | // card: it may record one task, only in the card's project, and start |
| 28 | // only that task, only with the card's specialist, while grantFor still |
| 29 | // finds it; every other mutation, and every lookup that would raise a |
| 30 | // card, is refused. A team-wide Add queues nothing. |
| 31 | |
| 32 | // specialistTurnRecord binds a specialist_added turn to the card whose |
| 33 | // Add queued it: one per card (the key), one card per turn. SpecialistID |
| 34 | // and ProjectID are the card's specialist and its scope; AskedTurn is the |
| 35 | // proposing turn; Words its messages the opening carries, complete (JSON |
| 36 | // addedWord list), so nothing depends on the conversation's tail. TaskID |
| 37 | // is the one task the turn recorded, bound by its first record_task. |
| 38 | type specialistTurnRecord struct { |
| 39 | CardID string `gorm:"primaryKey"` |
| 40 | TurnID string `gorm:"uniqueIndex:chat_specialist_turn"` |
| 41 | Person string |
| 42 | SpecialistID string |
| 43 | ProjectID string |
| 44 | AskedTurn string |
| 45 | Words string `gorm:"not null;default:''"` |
| 46 | TaskID string `gorm:"not null;default:''"` |
| 47 | CreatedAt time.Time |
| 48 | } |
| 49 | |
| 50 | func (specialistTurnRecord) TableName() string { return "chat_specialist_turns" } |
| 51 | |
| 52 | // addedWord is one message of the proposing turn, by its source: person |
| 53 | // (typed by the person: composer origin, from their own session) or |
| 54 | // choice (anything else: an option they tapped among the model's, or an |
| 55 | // answer sent for them), with the question it answered, if any. |
| 56 | type addedWord struct { |
| 57 | Source string `json:"source"` |
| 58 | Text string `json:"text"` |
| 59 | Question string `json:"question,omitempty"` |
| 60 | Tapped bool `json:"tapped,omitempty"` |
| 61 | } |
| 62 | |
| 63 | const ( |
| 64 | wordPerson = "person" |
| 65 | wordChoice = "choice" |
| 66 | ) |
| 67 | |
| 68 | // The continuation's opening, read by the model. Equipo's record and its |
| 69 | // instructions are labelled as Equipo's and hold no model-written or |
| 70 | // project text; such text is only quoted (fenced) under its source. |
| 71 | const ( |
| 72 | noteAddedRecord = "[Equipo's record, not the person's words: %s]" |
| 73 | noteAddedProject = "[Equipo: the project is %s, repository %s. Its title, as the team set it, quoted: %s. The name you proposed for the specialist, quoted: %s. Its id is %s.]" |
| 74 | noteAddedAsked = "The person's own words, typed by them in the message that led you to propose it, quoted: %s" |
| 75 | noteAddedTapped = "[Equipo: not the person's words. On your question %s they tapped %s, one of the options you wrote: a choice among your words.]" |
| 76 | noteAddedSent = "[Equipo: not the person's words. A reply sent for them, not typed by them, quoted: %s]" |
| 77 | noteAddedNone = "[Equipo: that message had no words.]" |
| 78 | noteAddedDo = "[Equipo: continue that request now, in this turn only. Record one task in repository %s with record_task, then start that task with start_task, passing \"specialist\": %s. This turn can do nothing else: no other project, no second task, no other specialist, and no other change. If the request needs more than that, say so to the person in one line.]" |
| 79 | ) |
| 80 | |
| 81 | // addedOpeningBytes bounds the continuation's opening as the frame |
| 82 | // carries it (JSON): one that does not fit is never cut short; the Add |
| 83 | // stands and Equipo asks the person what next (addedTooLong). |
| 84 | const addedOpeningBytes = 96 << 10 |
| 85 | |
| 86 | // Tool results for a specialist_added turn, read by the model. |
| 87 | const ( |
| 88 | toolBoundOther = "Refused: this turn continues the request a specialist was just added for. It can only record that task in the specialist's project and start it with that specialist. Nothing was done." |
| 89 | toolBoundProject = "Refused: in this turn you can only record a task in the project the specialist was added for, which is already one of the team's projects. Nothing was recorded." |
| 90 | toolBoundOneTask = "Refused: this turn already recorded its one task, %s. Start that task; nothing else can be recorded in this turn." |
| 91 | toolBoundTask = "Refused: in this turn you can only start the one task you recorded in this turn, in the specialist's project. Nothing was started." |
| 92 | toolBoundSpecialist = "Refused: in this turn you can only start the task with the specialist that was just added, passing its id as specialist. Nothing was started." |
| 93 | toolBoundGone = "Refused: that specialist is no longer on the team, so the task was not started. Tell the person in one line." |
| 94 | // toolBoundLookup: find in a bound turn, where an answer would raise |
| 95 | // a card (an access or project question). |
| 96 | toolBoundLookup = "Nothing Equipo can reach matches %s, and this turn cannot ask the person about it. Use the specialist's project; if the request needs another, say so to the person in one line." |
| 97 | ) |
| 98 | |
| 99 | // boundTools are the tools a specialist_added turn may call: it reads, |
| 100 | // records the card's task and starts it. Everything else, every other |
| 101 | // mutation (wire.MutationKinds, wire.WriteTools) included, is refused. |
| 102 | // An allowlist, so a tool added later is refused here until it is named. |
| 103 | // Of these, only find can raise a card (an access or project question); |
| 104 | // in a bound turn it answers those branches without one (readOnlyTurn). |
| 105 | var boundTools = []string{wire.ToolStatus, wire.ToolFind, wire.ToolSearchCode, wire.ToolReadFile, wire.ToolReadNotes, wire.ToolReadTask, wire.ToolRecordTask, wire.ToolStartTask} |
| 106 | |
| 107 | // boundAllowed reports whether a specialist_added turn may call tool at |
| 108 | // all; record_task and start_task are then held to the card (boundProject, |
| 109 | // startMaker). |
| 110 | func boundAllowed(tool string) bool { return slices.Contains(boundTools, tool) } |
| 111 | |
| 112 | // readOnlyTurn: a turn whose lookups raise no card. |
| 113 | func readOnlyTurn(r turnRecord) bool { return r.Kind == wire.TurnSpecialistAdded } |
| 114 | |
| 115 | // fenced quotes text from a source other than Equipo for an opening: a Go |
| 116 | // string literal in which the brackets that open and close Equipo's |
| 117 | // labels are escaped too (\u005b, \u005d), so quoted text can never end |
| 118 | // the label it sits in, or start one. |
| 119 | func fenced(text string) string { |
| 120 | return strings.NewReplacer("[", `\u005b`, "]", `\u005d`).Replace(strconv.Quote(text)) |
| 121 | } |
| 122 | |
| 123 | // queueSpecialistAdded queues the continuation for card c, whose Add |
| 124 | // approver just made sp active for its project, in the Add's transaction. |
| 125 | // Once per card: a card that already has its turn, or its question, |
| 126 | // queues nothing. |
| 127 | func (t *txn) queueSpecialistAdded(c cardRecord, sp specialistRecord, approver string) error { |
| 128 | if sp.ProjectID == "" { |
| 129 | return nil |
| 130 | } |
| 131 | var n int64 |
| 132 | if err := t.db.Model(&specialistTurnRecord{}).Where("card_id = ?", c.ID).Count(&n).Error; err != nil || n > 0 { |
| 133 | return err |
| 134 | } |
| 135 | // A project removed since the proposal has no task to record: the |
| 136 | // Add still stands (it comes back with the project), and nothing is |
| 137 | // queued. |
| 138 | var p projectRecord |
| 139 | if err := t.db.Where("id = ?", sp.ProjectID).Limit(1).Find(&p).Error; err != nil || p.State != wire.ProjectActive { |
| 140 | return err |
| 141 | } |
| 142 | // The proposing turn's lane (a card keeps its turn's, and moves with |
| 143 | // it when the turn is tried again). |
| 144 | lane := c.Lane |
| 145 | var asked turnRecord |
| 146 | if err := t.db.Where("id = ? AND person = ?", c.TurnID, c.Person).Limit(1).Find(&asked).Error; err != nil { |
| 147 | return err |
| 148 | } |
| 149 | if asked.ID != "" { |
| 150 | lane = asked.Lane |
| 151 | } |
| 152 | words, err := t.askedWords(c, lane) |
| 153 | if err != nil { |
| 154 | return err |
| 155 | } |
| 156 | note := t.addedOpening(approver, sp, p, words) |
| 157 | if raw, _ := json.Marshal(note); len(raw) > addedOpeningBytes { |
| 158 | return t.addedTooLong(c, lane, approver, sp) |
| 159 | } |
| 160 | raw, err := json.Marshal(words) |
| 161 | if err != nil { |
| 162 | return err |
| 163 | } |
| 164 | now := t.now() |
| 165 | r := turnRecord{ID: newID("t_"), Person: c.Person, State: wire.TurnQueued, Attempt: 1, Kind: wire.TurnSpecialistAdded, Note: note, Revision: 1, CreatedAt: now, UpdatedAt: now, Lane: lane} |
| 166 | if err := t.db.Create(&r).Error; err != nil { |
| 167 | return err |
| 168 | } |
| 169 | if err := t.db.Create(&specialistTurnRecord{CardID: c.ID, TurnID: r.ID, Person: c.Person, SpecialistID: sp.ID, ProjectID: sp.ProjectID, AskedTurn: c.TurnID, Words: string(raw), CreatedAt: now}).Error; err != nil { |
| 170 | return err |
| 171 | } |
| 172 | if err := t.turnEvent(r); err != nil { |
| 173 | return err |
| 174 | } |
| 175 | return t.dispatchNext(c.Person, lane) |
| 176 | } |
| 177 | |
| 178 | // askedWords are the proposing turn's messages, complete and oldest |
| 179 | // first: the person's words it carried from turns that failed before it |
| 180 | // (their own typing), then its own. Only a composer message, sent from |
| 181 | // the person's session, is their words; anything else in the turn under |
| 182 | // their name (a tapped option, an answer sent for them) is a choice. |
| 183 | func (t *txn) askedWords(c cardRecord, lane string) ([]addedWord, error) { |
| 184 | var carried []messageRecord |
| 185 | if err := t.db.Where("person = ? AND role = ? AND origin = ? AND coalesce(lane, '') = ? AND id IN (SELECT message_id FROM chat_turn_carried WHERE turn_id = ? AND person = ?)", c.Person, wire.RolePerson, originComposer, lane, c.TurnID, c.Person).Order("seq").Find(&carried).Error; err != nil { |
| 186 | return nil, err |
| 187 | } |
| 188 | var own []messageRecord |
| 189 | if err := t.db.Where("turn_id = ? AND person = ? AND role = ?", c.TurnID, c.Person, wire.RolePerson).Order("seq").Find(&own).Error; err != nil { |
| 190 | return nil, err |
| 191 | } |
| 192 | out := []addedWord{} |
| 193 | for _, m := range append(carried, own...) { |
| 194 | if m.Origin == originComposer { |
| 195 | out = append(out, addedWord{Source: wordPerson, Text: m.Text}) |
| 196 | continue |
| 197 | } |
| 198 | w := addedWord{Source: wordChoice, Text: m.Text} |
| 199 | var q cardRecord |
| 200 | if err := t.db.Where("person = ? AND answer_message = ?", m.Person, m.ID).Limit(1).Find(&q).Error; err != nil { |
| 201 | return nil, err |
| 202 | } |
| 203 | if q.ID != "" { |
| 204 | var options []string |
| 205 | _ = json.Unmarshal([]byte(q.Options), &options) |
| 206 | w.Question, w.Tapped = q.Question, slices.Contains(options, m.Text) |
| 207 | } |
| 208 | out = append(out, w) |
| 209 | } |
| 210 | return out, nil |
| 211 | } |
| 212 | |
| 213 | // addedRecord is Equipo's record of the Add from canonical names only: |
| 214 | // the approver's display name, from their verified address, and the |
| 215 | // profile's own name on the menu (copy), never the name the coordinator |
| 216 | // wrote or the project's title. |
| 217 | func (t *txn) addedRecord(approver string, sp specialistRecord) string { |
| 218 | who, _ := DisplayName(approver) |
| 219 | who = strings.NewReplacer("[", "(", "]", ")").Replace(who) |
| 220 | profile := t.words("chat.specialist.profile." + sp.Profile) |
| 221 | if profile == "" { |
| 222 | profile = sp.Profile |
| 223 | } |
| 224 | record := t.words("chat.specialist.added_record", who, profile) |
| 225 | if record == "" { |
| 226 | record = who + " added " + profile + " for a project." |
| 227 | } |
| 228 | return record |
| 229 | } |
| 230 | |
| 231 | // addedOpening is the continuation's text: Equipo's record of the Add, |
| 232 | // the project and the specialist (variable text fenced under its |
| 233 | // source), the proposing turn's messages, each under its source, and |
| 234 | // what this turn may do. |
| 235 | func (t *txn) addedOpening(approver string, sp specialistRecord, p projectRecord, words []addedWord) string { |
| 236 | var b strings.Builder |
| 237 | b.WriteString(fmt.Sprintf(noteAddedRecord, t.addedRecord(approver, sp)) + "\n") |
| 238 | b.WriteString(fmt.Sprintf(noteAddedProject, p.ID, fenced(p.Repo), fenced(p.shownTitle()), fenced(sp.Name), sp.ID) + "\n") |
| 239 | said := false |
| 240 | for _, w := range words { |
| 241 | switch { |
| 242 | case w.Text == "": |
| 243 | continue |
| 244 | case w.Source == wordPerson: |
| 245 | b.WriteString(fmt.Sprintf(noteAddedAsked, fenced(w.Text)) + "\n") |
| 246 | case w.Tapped: |
| 247 | b.WriteString(fmt.Sprintf(noteAddedTapped, fenced(w.Question), fenced(w.Text)) + "\n") |
| 248 | default: |
| 249 | b.WriteString(fmt.Sprintf(noteAddedSent, fenced(w.Text)) + "\n") |
| 250 | } |
| 251 | said = true |
| 252 | } |
| 253 | if !said { |
| 254 | b.WriteString(noteAddedNone + "\n") |
| 255 | } |
| 256 | b.WriteString(fmt.Sprintf(noteAddedDo, fenced(p.Repo), fenced(sp.ID))) |
| 257 | return b.String() |
| 258 | } |
| 259 | |
| 260 | // addedTooLong is the Add whose proposing turn's messages cannot all be |
| 261 | // carried: nothing is queued (never a request cut short), and Equipo |
| 262 | // posts its record and asks the person what to do next, once per card. |
| 263 | // The message is stored in the coordinator's role and comes back to the |
| 264 | // model in the conversation's tail as its own words, so it holds no |
| 265 | // variable text but the canonical record: never the project's title or |
| 266 | // the name the coordinator wrote (the card above it names them). |
| 267 | func (t *txn) addedTooLong(c cardRecord, lane, approver string, sp specialistRecord) error { |
| 268 | key := "reply:specialist-added:" + c.ID |
| 269 | var n int64 |
| 270 | if err := t.db.Model(&messageRecord{}).Where("person = ? AND coalesce(lane, '') = ? AND idempotency_key = ?", c.Person, lane, key).Count(&n).Error; err != nil || n > 0 { |
| 271 | return err |
| 272 | } |
| 273 | ask := t.words("chat.specialist.added_ask") |
| 274 | text := t.addedRecord(approver, sp) |
| 275 | if ask != "" { |
| 276 | text += "\n" + ask |
| 277 | } |
| 278 | m := messageRecord{ID: newID("m_"), Person: c.Person, Lane: lane, TurnID: c.TurnID, IdempotencyKey: key, Origin: originGenerated, Role: wire.RoleCoordinator, Text: text, Revision: 1, CreatedAt: t.now()} |
| 279 | if err := t.db.Create(&m).Error; err != nil { |
| 280 | return err |
| 281 | } |
| 282 | return t.messageEvent(m) |
| 283 | } |
| 284 | |
| 285 | // bindTask binds the one task a specialist_added turn records, in the |
| 286 | // record's transaction: only while none is bound, else the call fails and |
| 287 | // the transaction (the record with it) rolls back. |
| 288 | func (t *txn) bindTask(r turnRecord, task string) error { |
| 289 | res := t.db.Model(&specialistTurnRecord{}).Where("turn_id = ? AND person = ? AND task_id = ''", r.ID, r.Person).Update("task_id", task) |
| 290 | if res.Error != nil { |
| 291 | return res.Error |
| 292 | } |
| 293 | if res.RowsAffected != 1 { |
| 294 | return ErrConflict |
| 295 | } |
| 296 | return nil |
| 297 | } |
| 298 | |
| 299 | // boundTurn is the card a specialist_added turn is bound to. A turn of |
| 300 | // that kind with no binding (none recorded, or another person's) is |
| 301 | // refused everything: errNoBinding. |
| 302 | func (t *txn) boundTurn(r turnRecord) (specialistTurnRecord, error) { |
| 303 | var b specialistTurnRecord |
| 304 | if err := t.db.Where("turn_id = ? AND person = ?", r.ID, r.Person).Limit(1).Find(&b).Error; err != nil { |
| 305 | return b, err |
| 306 | } |
| 307 | if b.CardID == "" || b.ProjectID == "" || b.SpecialistID == "" { |
| 308 | return b, errNoBinding |
| 309 | } |
| 310 | return b, nil |
| 311 | } |
| 312 | |
| 313 | var errNoBinding = errors.New("chat: specialist_added turn without its card") |
| 314 | |
| 315 | // boundProject refuses record_task in a specialist_added turn unless repo |
| 316 | // names one of the team's active projects, the card's (never another |
| 317 | // project, a new one, or one the call would add), and while the turn has |
| 318 | // not recorded its one task (bindTask). |
| 319 | func (t *txn) boundProject(r turnRecord, repo string) (*wire.ToolResult, error) { |
| 320 | b, err := t.boundTurn(r) |
| 321 | if errors.Is(err, errNoBinding) { |
| 322 | res := refused("bound_turn", toolBoundOther) |
| 323 | return &res, nil |
| 324 | } |
| 325 | if err != nil { |
| 326 | return nil, err |
| 327 | } |
| 328 | p, err := t.namedProject(r.Person, repo) |
| 329 | if err != nil { |
| 330 | return nil, err |
| 331 | } |
| 332 | if p == nil || p.ID != b.ProjectID || p.State != wire.ProjectActive { |
| 333 | res := refused("bound_project", toolBoundProject) |
| 334 | return &res, nil |
| 335 | } |
| 336 | if b.TaskID != "" { |
| 337 | // Its one task is recorded (an exact repeat of that call is |
| 338 | // answered from the ledger before it gets here). |
| 339 | res := refused("bound_one_task", fmt.Sprintf(toolBoundOneTask, b.TaskID)) |
| 340 | return &res, nil |
| 341 | } |
| 342 | return nil, nil |
| 343 | } |
| 344 | |
| 345 | // startMaker is the maker start_task starts a task with, by turn. A |
| 346 | // specialist_added turn starts only the one task it recorded (bound to |
| 347 | // it), in the card's project, only with the card's specialist, and only while grantFor |
| 348 | // still finds that specialist for the project; its maker is that |
| 349 | // specialist. Any other turn names one with specialist, held to the |
| 350 | // routing rules (routeMaker); without one it is Engineering (""). |
| 351 | func (t *txn) startMaker(r turnRecord, task, specialistID string) (string, *wire.ToolResult, error) { |
| 352 | if r.Kind != wire.TurnSpecialistAdded { |
| 353 | if specialistID == "" { |
| 354 | return "", nil, nil |
| 355 | } |
| 356 | return t.routeMaker(r, task, specialistID) |
| 357 | } |
| 358 | b, err := t.boundTurn(r) |
| 359 | if errors.Is(err, errNoBinding) { |
| 360 | res := refused("bound_turn", toolBoundOther) |
| 361 | return "", &res, nil |
| 362 | } |
| 363 | if err != nil { |
| 364 | return "", nil, err |
| 365 | } |
| 366 | k, err := t.loadTask(task) |
| 367 | if errors.Is(err, ErrNotFound) { |
| 368 | res := refused("bound_task", toolBoundTask) |
| 369 | return "", &res, nil |
| 370 | } |
| 371 | if err != nil { |
| 372 | return "", nil, err |
| 373 | } |
| 374 | if b.TaskID == "" || k.ID != b.TaskID || k.TurnID != r.ID || k.ProjectID != b.ProjectID { |
| 375 | res := refused("bound_task", toolBoundTask) |
| 376 | return "", &res, nil |
| 377 | } |
| 378 | if specialistID != b.SpecialistID { |
| 379 | res := refused("bound_specialist", toolBoundSpecialist) |
| 380 | return "", &res, nil |
| 381 | } |
| 382 | var sp specialistRecord |
| 383 | if err := t.db.Where("id = ?", b.SpecialistID).Limit(1).Find(&sp).Error; err != nil { |
| 384 | return "", nil, err |
| 385 | } |
| 386 | found, err := t.grantFor(sp.Profile, b.ProjectID) |
| 387 | if err != nil { |
| 388 | return "", nil, err |
| 389 | } |
| 390 | if sp.ID == "" || found == nil || found.ID != b.SpecialistID { |
| 391 | res := refused("specialist_gone", toolBoundGone) |
| 392 | return "", &res, nil |
| 393 | } |
| 394 | if !makerProfile(sp.Profile) { |
| 395 | res := refused("specialist_not_maker", toolStartNotMaker) |
| 396 | return "", &res, nil |
| 397 | } |
| 398 | return b.SpecialistID, nil, nil |
| 399 | } |
| 400 | |