oficina / equipo Public

Clone
git clone https://amadan.net/oficina/equipo

Plain git — no account needed to clone.

Download

Download this file

1package chat
2
3import (
4 "context"
5 "encoding/json"
6 "errors"
7 "fmt"
8 "slices"
9 "strconv"
10 "strings"
11 "time"
12 "unicode"
13 "unicode/utf8"
14
15 "amadan.net/oficina/equipo/internal/equipo/assist"
16 "amadan.net/oficina/equipo/internal/wire"
17 "gorm.io/gorm"
18)
19
20// The hand-off (spec §5, and the jobs design's job threads). The
21// Assistant hands software work to the person's team with team_request:
22// the instance posts the person's own words, quoted from the Assistant
23// turn, as their message into a Coordinator thread of the hand-off's own
24// (lane job:<id>), never their own conversation, and the Coordinator
25// works there as it does today. A hand-off made before job threads
26// (legacy: no lane) keeps slice 1's routing in their conversation. A hand-off follows every task its turns record (created) or
27// join (touched), and the turn that carries the answer to a question its
28// turn asked. When that work stops on its own (finished, failed, waiting
29// for someone), or it asks the person something, the instance starts an
30// Assistant turn of kind team_update carrying the job's note (jobNote),
31// never the team's machinery or its own voice to the person: no
32// repository, branch or SHA. Preview links open the Equipo wrapper, which
33// checks the current preview and limits browser navigation.
34//
35// The team provider runs in this process, but outside a transaction like
36// every provider (ServeRemoteCalls): each operation opens its own.
37
38const (
39 opTeamRequest = "team_request"
40 opTeamStatus = "team_status"
41 opTeamCancel = "team_cancel"
42 opTeamReply = "team_reply"
43 opTeamNudge = "team_nudge"
44
45 handoffOpen = "open"
46 // handoffStopping: cancelled while work it started could not be
47 // stopped. It is followed until that work ends, and nothing new
48 // joins it.
49 handoffStopping = "stopping"
50 handoffCancelled = "cancelled"
51
52 auditHandoff = "assistant.handoff"
53 auditTeamCancel = "assistant.team_cancel"
54 auditTeamReply = "assistant.team_reply"
55 auditTeamNudge = "assistant.team_nudge"
56
57 // handoffKey is the instance's idempotency key space for a hand-off's
58 // Coordinator message (validKey keeps clients out of it).
59 handoffKey = "handoff:"
60 // maxContext bounds team_request's context; maxStatus the requests
61 // (and the pieces of the person's own work) team_status reports, so
62 // its answer fits one tool result.
63 maxContext = 4000
64 maxStatus = 10
65 // maxTitle is the most characters a job's title has (D10).
66 maxTitle = 60
67 // maxAnswer is the most characters team_reply's answer has.
68 maxAnswer = 2000
69 // minQuote is the fewest characters words may quote.
70 minQuote = 3
71 // maxQuoted is how many of the person's newest Assistant messages
72 // team_nudge's words may quote (quoteAny).
73 maxQuoted = 200
74)
75
76// handoffRecord is one team_request: the Assistant turn it came from,
77// the Coordinator message it posted, the Assistant's context, the key
78// the request was made with (unique: a repeat is this row), open,
79// stopping or cancelled, the digest of the note the Assistant was last
80// given, and its thread: job:<id>, or "" for a legacy hand-off, whose
81// words went to the person's own conversation. Title names the job (the
82// model's, or fallbackTitle's); Nudges counts the Assistant's nudges.
83type handoffRecord struct {
84 ID string `gorm:"primaryKey"`
85 Person string `gorm:"index:chat_handoff_person"`
86 AssistantTurn string
87 MessageID string `gorm:"index:chat_handoff_message"`
88 Context string
89 LedgerKey string `gorm:"uniqueIndex:chat_handoff_key"`
90 State string
91 Digest string
92 CreatedAt time.Time
93 UpdatedAt time.Time
94 Lane string
95 Title string
96 Nudges int64 `gorm:"not null;default:0"`
97 // AbilityHeldAt is when the job's work was first held because its
98 // person can't have building done (spec §6.3): set once, cleared only
99 // by the person's Try again (resumeAbilityHold).
100 AbilityHeldAt *time.Time
101}
102
103func (handoffRecord) TableName() string { return "chat_handoffs" }
104
105// handoffActionRecord is a reply or a nudge the Assistant made for a
106// hand-off, once per key: the instance's ledger key, its kind ("reply"
107// or "nudge"), the Assistant's context, the message it posted, if any,
108// and its stored result.
109type handoffActionRecord struct {
110 LedgerKey string `gorm:"primaryKey"`
111 HandoffID string `gorm:"not null;index:chat_handoff_action_handoff"`
112 Person string `gorm:"not null"`
113 Kind string `gorm:"not null"`
114 Context string
115 MessageID string `gorm:"index:chat_handoff_action_message"`
116 Result string
117 CreatedAt time.Time
118}
119
120func (handoffActionRecord) TableName() string { return "chat_handoff_actions" }
121
122// handoffTurnRecord is one of a hand-off's turns: the Coordinator turn
123// that carries its words or an answer to its question, or a team_update
124// turn telling the person about it. A turn belongs to one hand-off.
125type handoffTurnRecord struct {
126 HandoffID string `gorm:"index:chat_handoff_turn_handoff"`
127 TurnID string `gorm:"primaryKey"`
128}
129
130func (handoffTurnRecord) TableName() string { return "chat_handoff_turns" }
131
132// handoffTaskRecord is a task a hand-off follows; Created when one of
133// its turns recorded it (only those may team_cancel cancel).
134type handoffTaskRecord struct {
135 HandoffID string `gorm:"primaryKey"`
136 TaskID string `gorm:"primaryKey;index:chat_handoff_task"`
137 Created bool
138}
139
140func (handoffTaskRecord) TableName() string { return "chat_handoff_tasks" }
141
142// callKey carries the Assistant call an operation runs for (withCall).
143type callKey struct{}
144
145// withCall is ctx for an operation run for one of the Assistant's calls:
146// the team provider reads its turn from it.
147func withCall(ctx context.Context, row toolCallRecord) context.Context {
148 return context.WithValue(ctx, callKey{}, row)
149}
150
151func callFrom(ctx context.Context) (toolCallRecord, bool) {
152 row, ok := ctx.Value(callKey{}).(toolCallRecord)
153 return row, ok
154}
155
156// TeamProvider is the team's operations, registered after Base's.
157func (s *Store) TeamProvider() assist.Provider { return teamProvider{s} }
158
159type teamProvider struct{ s *Store }
160
161func (teamProvider) Name() string { return "team" }
162
163func (teamProvider) List(context.Context, string) ([]assist.Operation, error) {
164 return slices.Clone(teamOps), nil
165}
166
167// teamOps are the team's operations. Their descriptions are for the
168// model; people never read them.
169var teamOps = []assist.Operation{
170 {Name: opTeamRequest, App: "Team", Scope: "team", Idempotent: true,
171 Description: "Hand software work (build, fix or change an app or site) to the person's team, who take it from there. words quotes the person's own message in this turn, word for word; context is anything you know that helps, kept apart from their words as your reference. The job can't see the person's attached files: when their message had some, files_left_behind says how many, and you tell the person the team works without them. A message of files with no words has nothing to quote: ask the person, in words, what they want done. Returns the request id.",
172 Input: json.RawMessage(`{"type":"object","properties":{"words":{"type":"string","description":"The person's own words from their message in this turn, quoted exactly."},"context":{"type":"string","maxLength":4000,"description":"What you know that helps: kept apart from the person's words, as reference."},"title":{"type":"string","maxLength":60,"description":"A short name for this job, in the person's terms, such as \"Fixing the sign-in page\"."}},"required":["words"],"additionalProperties":false}`),
173 Output: json.RawMessage(`{"type":"object","properties":{"request":{"type":"string"},"status":{"type":"string"},"title":{"type":"string"},"files_left_behind":{"type":"integer"}}}`)},
174 {Name: opTeamStatus, App: "Team", Scope: "team", ReadOnly: true, Idempotent: true,
175 Description: "Read-only: where the work handed to the team stands, in plain words, with each job's open question: one request (request), the person's open requests (none given), or those and the work they started with the team themselves (all). Open requests come ten at a time, newest first; when more are open, next is set: pass it as after to read the ten after them.",
176 Input: json.RawMessage(`{"type":"object","properties":{"request":{"type":"string"},"all":{"type":"boolean"},"after":{"type":"string","description":"The next of the page before, to read on."}},"additionalProperties":false}`),
177 Output: json.RawMessage(`{"type":"object","properties":{"requests":{"type":"array","items":{"type":"object","properties":{"request":{"type":"string"},"summary":{"type":"string"},"title":{"type":"string"},"question":{"type":"object","properties":{"text":{"type":"string"},"options":{"type":"array","items":{"type":"string"}}}}}}},"next":{"type":"string"}}}`)},
178 {Name: opTeamCancel, App: "Team", Scope: "team", Idempotent: true,
179 Description: "Stop the work a request started, when the person asks you to: only what the request itself started stops. Returns how many pieces of work were stopped (cancelled) and how many could not be stopped and go on (still_running: say so; the request is still followed).",
180 Input: json.RawMessage(`{"type":"object","properties":{"request":{"type":"string"}},"required":["request"],"additionalProperties":false}`),
181 Output: json.RawMessage(`{"type":"object","properties":{"cancelled":{"type":"integer"},"still_running":{"type":"integer"}}}`)},
182 {Name: opTeamReply, App: "Team", Scope: "team", Idempotent: true,
183 Description: "Answer the open question on one of the person's jobs, as the person. answer must be one of the question's options when it has options; otherwise your own words, at most 2000 characters. Use it when the conversation already holds the answer, or to pass on the person's reply. Returns the request id.",
184 Input: json.RawMessage(`{"type":"object","properties":{"request":{"type":"string"},"answer":{"type":"string","maxLength":2000}},"required":["request","answer"],"additionalProperties":false}`),
185 Output: json.RawMessage(`{"type":"object","properties":{"request":{"type":"string"},"status":{"type":"string"}}}`)},
186 {Name: opTeamNudge, App: "Team", Scope: "team", Idempotent: true,
187 Description: "Push one of the person's stopped jobs through: it is started again with what the person asked, or a failed step is tried again. words quotes the person's own words from this conversation, word for word; context is your reference, kept apart from their words. At most two nudges per job until the person says something new about it. Returns the request id and the nudges left.",
188 Input: json.RawMessage(`{"type":"object","properties":{"request":{"type":"string"},"words":{"type":"string"},"context":{"type":"string","maxLength":4000}},"required":["request","words"],"additionalProperties":false}`),
189 Output: json.RawMessage(`{"type":"object","properties":{"request":{"type":"string"},"status":{"type":"string"},"nudges_left":{"type":"integer"}}}`)},
190}
191
192// updateWrites are the team's writes a team_update turn may make, each
193// about the job the update tells (teamReply, teamNudge).
194var updateWrites = []string{opTeamReply, opTeamNudge}
195
196func (p teamProvider) Invoke(ctx context.Context, person, operation string, input json.RawMessage, key string) (json.RawMessage, error) {
197 call, ok := callFrom(ctx)
198 if !ok || call.Person != person {
199 return nil, assist.Failure{Code: "unavailable"}
200 }
201 switch operation {
202 case opTeamRequest:
203 return p.s.teamRequest(ctx, call, input, key)
204 case opTeamStatus:
205 return p.s.teamStatus(ctx, person, input)
206 case opTeamCancel:
207 return p.s.teamCancel(ctx, call, input)
208 case opTeamReply:
209 return p.s.teamReply(ctx, call, input, key)
210 case opTeamNudge:
211 return p.s.teamNudge(ctx, call, input, key)
212 }
213 return nil, assist.Failure{Code: "unknown_operation"}
214}
215
216var errBadTeamInput = assist.Failure{Code: "invalid_input", Message: toolTeamInput}
217
218// teamRequest hands the person's words to a Coordinator thread of the
219// request's own, once per key, in one transaction: the words checked
220// against the Assistant turn's messages, the person's primary able to
221// carry the thread (protocol 22), the hand-off with its title (the
222// model's, else fallbackTitle's), the thread's message and its turn.
223func (s *Store) teamRequest(ctx context.Context, call toolCallRecord, input json.RawMessage, key string) (json.RawMessage, error) {
224 var in struct {
225 Words string `json:"words"`
226 Context string `json:"context"`
227 Title string `json:"title"`
228 }
229 // Raw bytes first: the decoder turns malformed UTF-8 into U+FFFD.
230 if !utf8.Valid(input) || wire.Strict(input, &in) != nil || len(in.Words) > wire.MaxMessageBytes || len(in.Context) > maxContext || !utf8.ValidString(in.Words+in.Context) || strings.ContainsRune(in.Words+in.Context, 0) || !validTitle(in.Title) || key == "" {
231 return nil, errBadTeamInput
232 }
233 var out json.RawMessage
234 err := s.tx(ctx, func(t *txn) error {
235 var h handoffRecord
236 if err := t.db.Where("ledger_key = ? AND person = ?", key, call.Person).Limit(1).Find(&h).Error; err != nil || h.ID != "" {
237 if err == nil {
238 out, err = t.requestResult(h)
239 }
240 return err
241 }
242 r, err := t.liveCall(call)
243 if err != nil {
244 return err
245 }
246 if err := t.requireBuild(r.Person); err != nil {
247 return err
248 }
249 left, err := t.turnFiles(r)
250 if err != nil {
251 return err
252 }
253 words, err := t.quote(r, in.Words)
254 if err != nil {
255 if wordless, e := t.filesOnlyTurn(r); e != nil {
256 return e
257 } else if wordless {
258 return errFilesNoWords
259 }
260 return err
261 }
262 // The same words handed over again in this turn, in other
263 // arguments, are the same request.
264 if err := t.db.Where("assistant_turn = ? AND person = ? AND EXISTS (SELECT 1 FROM chat_messages m WHERE m.id = chat_handoffs.message_id AND m.text = ?)", r.ID, r.Person, words).Limit(1).Find(&h).Error; err != nil || h.ID != "" {
265 if err == nil {
266 out, err = t.requestResult(h)
267 }
268 return err
269 }
270 switch err := t.jobRunner(r.Person); {
271 case errors.Is(err, ErrRunnerTooOld):
272 return assist.Failure{Code: "runner_too_old", Message: toolJobsTooOld}
273 case err != nil:
274 return err
275 }
276 now := t.now()
277 // The job can't see the person's files (R6): its context says so,
278 // as the instance's own reference.
279 reference := strings.TrimSpace(in.Context)
280 if left > 0 {
281 reference = strings.TrimSpace(reference + " " + filesLeftBehind(left))
282 }
283 h = handoffRecord{ID: newID("h_"), Person: r.Person, AssistantTurn: r.ID, Context: referenceText(reference), LedgerKey: key, State: handoffOpen, Title: strings.TrimSpace(in.Title), CreatedAt: now, UpdatedAt: now}
284 if h.Title == "" {
285 h.Title = fallbackTitle(words)
286 }
287 h.Lane = wire.JobLane(h.ID)
288 if err := t.db.Create(&h).Error; err != nil {
289 return err
290 }
291 if _, _, err := t.send(h.Lane, r.Person, handoffKey+h.ID, words, nil, func(m messageRecord) error {
292 h.MessageID = m.ID
293 if err := t.db.Model(&handoffRecord{}).Where("id = ?", h.ID).Update("message_id", m.ID).Error; err != nil {
294 return err
295 }
296 return t.db.Create(&handoffTurnRecord{HandoffID: h.ID, TurnID: m.TurnID}).Error
297 }); err != nil {
298 return err
299 }
300 if out, err = t.requestResult(h); err != nil {
301 return err
302 }
303 if err := t.s.authority.Audit(t.db, r.Person, auditHandoff, h.ID); err != nil {
304 return err
305 }
306 return t.projectJob(h)
307 })
308 return out, err
309}
310
311// requestResult is team_request's answer for h: with files_left_behind
312// when the Assistant turn it came from carried files the job can't see.
313func (t *txn) requestResult(h handoffRecord) (json.RawMessage, error) {
314 out := map[string]any{"request": h.ID, "status": "sent", "title": h.Title}
315 left, err := t.turnFiles(turnRecord{ID: h.AssistantTurn, Person: h.Person})
316 if err != nil {
317 return nil, err
318 }
319 if left > 0 {
320 out["files_left_behind"] = left
321 }
322 raw, _ := json.Marshal(out)
323 return raw, nil
324}
325
326// filesLeftBehind is the instance's line in a job's reference when the
327// person's request carried n files: told to the Coordinator, never the
328// person's words.
329func filesLeftBehind(n int64) string {
330 files, them := strconv.FormatInt(n, 10)+" files", "them"
331 if n == 1 {
332 files, them = "1 file", "it"
333 }
334 return "The person attached " + files + " to this request in their conversation. This job cannot see " + them + "."
335}
336
337// errFilesNoWords: the turn's messages are files with no words, so there
338// is nothing of the person's to hand over.
339var errFilesNoWords = assist.Failure{Code: "invalid_input", Message: "The person's message has files and no words, so there is nothing of theirs to hand over. Ask them, in words, what they want done."}
340
341// turnFiles counts the files on the person's messages in turn r.
342func (t *txn) turnFiles(r turnRecord) (int64, error) {
343 var n int64
344 err := t.db.Model(&fileRecord{}).Where("person = ? AND message_id IN (SELECT id FROM chat_messages WHERE turn_id = ? AND person = ? AND role = ?)", r.Person, r.ID, r.Person, wire.RolePerson).Count(&n).Error
345 return n, err
346}
347
348// filesOnlyTurn says the person's messages in turn r have files and no
349// words at all.
350func (t *txn) filesOnlyTurn(r turnRecord) (bool, error) {
351 var worded int64
352 if err := t.db.Model(&messageRecord{}).Where("turn_id = ? AND person = ? AND role = ? AND text <> ''", r.ID, r.Person, wire.RolePerson).Count(&worded).Error; err != nil || worded > 0 {
353 return false, err
354 }
355 n, err := t.turnFiles(r)
356 return n > 0, err
357}
358
359// validTitle says a title the model gave is one line of at most maxTitle
360// characters: no control characters (a newline or tab among them) and
361// no line or paragraph separator. An empty or blank one is no title.
362func validTitle(title string) bool {
363 return utf8.RuneCountInString(title) <= maxTitle && !strings.ContainsFunc(title, func(c rune) bool {
364 return unicode.IsControl(c) || unicode.In(c, unicode.Zl, unicode.Zp)
365 })
366}
367
368// fallbackTitle names a job the model gave no title (D10): the person's
369// words on one line, whole when they have at most maxTitle characters,
370// otherwise their first maxTitle-1 cut at the last space, plus "…".
371func fallbackTitle(words string) string {
372 r := []rune(strings.Join(strings.Fields(words), " "))
373 if len(r) <= maxTitle {
374 return string(r)
375 }
376 head := string(r[:maxTitle-1])
377 if i := strings.LastIndexByte(head, ' '); i > 0 {
378 head = head[:i]
379 }
380 return head + "…"
381}
382
383// liveCall is the call's Assistant turn, still running at the call's
384// attempt for a person with a primary runner (an active owner): the
385// roster, checked in the write's own transaction.
386func (t *txn) liveCall(call toolCallRecord) (turnRecord, error) {
387 ok, err := t.deliverable(call)
388 if err != nil {
389 return turnRecord{}, err
390 }
391 var r turnRecord
392 if ok {
393 err = t.db.Where("id = ? AND person = ? AND lane = ?", call.TurnID, call.Person, wire.LaneAssistant).Limit(1).Find(&r).Error
394 }
395 if err == nil && r.ID == "" {
396 err = assist.Failure{Code: "turn_ended"}
397 }
398 return r, err
399}
400
401// quote is words as the person wrote them in one of the turn's
402// messages, or one it carried from a turn that failed before the model
403// saw it (carriedRecord): found there compared lower-cased with each run
404// of whitespace as one space, at least minQuote characters. Only a turn
405// the person started has their words (a team_update turn has none).
406func (t *txn) quote(r turnRecord, words string) (string, error) {
407 refuse := assist.Failure{Code: "not_their_words"}
408 w, _, _ := folded(words)
409 w = strings.TrimSpace(w)
410 if r.Kind != wire.TurnPerson || utf8.RuneCountInString(w) < minQuote {
411 return "", refuse
412 }
413 var texts []string
414 if err := t.db.Model(&messageRecord{}).Where("turn_id = ? AND person = ? AND role = ?", r.ID, r.Person, wire.RolePerson).Order("seq").Pluck("text", &texts).Error; err != nil {
415 return "", err
416 }
417 // Exactly the messages dispatch carried: the person's own, in the lane.
418 var carried []string
419 if err := t.db.Model(&messageRecord{}).Where("person = ? AND role = ? AND origin = ? AND coalesce(lane, '') = ? AND id IN (SELECT message_id FROM chat_turn_carried WHERE turn_id = ? AND person = ?)", r.Person, wire.RolePerson, originComposer, r.Lane, r.ID, r.Person).Order("seq").Pluck("text", &carried).Error; err != nil {
420 return "", err
421 }
422 for _, text := range append(texts, carried...) {
423 if found, ok := quoteIn(text, w); ok {
424 return found, nil
425 }
426 }
427 return "", refuse
428}
429
430// quoteAny is words as the person wrote them in one of their newest
431// maxQuoted messages to the Assistant, compared as quote does, and the
432// message quoted: the newest that holds them.
433func (t *txn) quoteAny(person, words string) (text string, from messageRecord, err error) {
434 refuse := teamRefusal{"not_their_words", toolNudgeWords}
435 w, _, _ := folded(words)
436 w = strings.TrimSpace(w)
437 if utf8.RuneCountInString(w) < minQuote {
438 return "", from, refuse
439 }
440 var rows []messageRecord
441 if err := t.db.Where("person = ? AND lane = ? AND role = ?", person, wire.LaneAssistant, wire.RolePerson).Order("seq DESC").Limit(maxQuoted).Find(&rows).Error; err != nil {
442 return "", from, err
443 }
444 for _, m := range rows {
445 if found, ok := quoteIn(m.Text, w); ok {
446 return found, m, nil
447 }
448 }
449 return "", from, refuse
450}
451
452// quoteIn is the span of text that folds to w (folded, trimmed), as
453// written.
454func quoteIn(text, w string) (string, bool) {
455 f, starts, ends := folded(text)
456 if i := strings.Index(f, w); i >= 0 {
457 return text[starts[i]:ends[i+len(w)-1]], true
458 }
459 return "", false
460}
461
462// folded is s lower-cased with each run of whitespace one space, and
463// for each of its bytes the span of s it came from.
464func folded(s string) (string, []int, []int) {
465 var b strings.Builder
466 var starts, ends []int
467 space := false
468 for i, c := range s {
469 end := i + utf8.RuneLen(c)
470 if unicode.IsSpace(c) {
471 if space {
472 ends[len(ends)-1] = end
473 continue
474 }
475 space, c = true, ' '
476 } else {
477 space, c = false, unicode.ToLower(c)
478 }
479 n := b.Len()
480 b.WriteRune(c)
481 for range b.Len() - n {
482 starts, ends = append(starts, i), append(ends, end)
483 }
484 }
485 return b.String(), starts, ends
486}
487
488// referenceText is the Assistant's context as kept: no brackets, so the
489// marker around it in the Coordinator's frame stays one.
490func referenceText(s string) string {
491 return strings.NewReplacer("[", "(", "]", ")").Replace(strings.TrimSpace(s))
492}
493
494// handoffContext is a Coordinator message's text as dispatched: a
495// hand-off's (in its thread, or a legacy one's in the person's
496// conversation) carries the Assistant's context after it, marked as
497// reference; a nudge's carries the nudge's context, or with none
498// nudgeReference. The stored message stays the person's words.
499func (t *txn) handoffContext(m messageRecord, text string) (string, error) {
500 if !wire.CoordinatorRole(m.Lane) {
501 return text, nil
502 }
503 var h handoffRecord
504 if err := t.db.Where("message_id = ? AND person = ?", m.ID, m.Person).Limit(1).Find(&h).Error; err != nil || h.ID != "" {
505 return marked(text, h.Context), err
506 }
507 var nudge handoffActionRecord
508 if err := t.db.Where("message_id = ? AND person = ? AND kind IN ?", m.ID, m.Person, []string{actionNudge, actionResume}).Limit(1).Find(&nudge).Error; err != nil || nudge.LedgerKey == "" {
509 return text, err
510 }
511 if nudge.Kind == actionResume {
512 // The request given again: the hand-off's own context.
513 return marked(text, nudge.Context), nil
514 }
515 if nudge.Context == "" {
516 nudge.Context = nudgeReference
517 }
518 return marked(text, nudge.Context), nil
519}
520
521// marked is text with the Assistant's reference after it, marked as not
522// the person's words (text alone with none).
523func marked(text, reference string) string {
524 if reference == "" {
525 return text
526 }
527 return text + "\n\n[Reference from the Assistant, not the person's words: " + reference + "]"
528}
529
530// handoffOf is the hand-off a Coordinator turn or, failing that, a task
531// belongs to. A turn in a job thread is that hand-off's; any other turn
532// is the one it is linked to (a legacy hand-off's, or a team_update's).
533func (t *txn) handoffOf(turnID, taskID string) (handoffRecord, bool, error) {
534 var h handoffRecord
535 if turnID != "" {
536 var lanes []string
537 if err := t.db.Model(&turnRecord{}).Where("id = ?", turnID).Pluck("coalesce(lane, '')", &lanes).Error; err != nil {
538 return h, false, err
539 }
540 if len(lanes) == 1 {
541 if id, ok := wire.JobOf(lanes[0]); ok {
542 err := t.db.Where("id = ?", id).Limit(1).Find(&h).Error
543 return h, h.ID != "", err
544 }
545 }
546 if err := t.db.Where("id IN (SELECT handoff_id FROM chat_handoff_turns WHERE turn_id = ?)", turnID).Limit(1).Find(&h).Error; err != nil || h.ID != "" {
547 return h, h.ID != "", err
548 }
549 }
550 if taskID != "" {
551 if err := t.db.Where("id IN (SELECT handoff_id FROM chat_handoff_tasks WHERE task_id = ?)", taskID).Order("created_at").Limit(1).Find(&h).Error; err != nil {
552 return h, false, err
553 }
554 }
555 return h, h.ID != "", nil
556}
557
558// workTools create, start or change work: once the person cancels a
559// request (stopping or cancelled), its turns may run none of them.
560var workTools = []string{wire.ToolRecordTask, wire.ToolStartTask, wire.ToolAddFinding, wire.ToolAddReport, wire.ToolHoldMerge, wire.ToolSetMergePolicy, wire.ToolProposeSpecialist, wire.ToolResearch, wire.ToolOfferRetry, wire.ToolRetryStep}
561
562// handoffFenced: the turn belongs to a request the person cancelled and
563// the tool would create or start work. Checked in the tool's own
564// transaction, so a cancel and a write never cross.
565func (t *txn) handoffFenced(r turnRecord, tool string) (bool, error) {
566 if !slices.Contains(workTools, tool) {
567 return false, nil
568 }
569 h, ok, err := t.handoffOf(r.ID, "")
570 return ok && h.State != handoffOpen, err
571}
572
573// followTask links a task a Coordinator tool recorded (created) or
574// joined, started or added a finding to (touched) to the hand-off its
575// turn belongs to, while the request is open: nothing done after
576// team_cancel is the request's. A task it first links may already wait
577// on the person: its open cards are mirrored then (mirrorOpenCards).
578func (t *txn) followTask(r turnRecord, v *wire.ToolCall, res wire.ToolResult) error {
579 var created bool
580 switch v.Name {
581 case wire.ToolRecordTask:
582 created = res.Code == "recorded"
583 if !created {
584 return nil
585 }
586 case wire.ToolAddReport, wire.ToolAddFinding, wire.ToolStartTask:
587 default:
588 return nil
589 }
590 h, ok, err := t.handoffOf(r.ID, "")
591 if err != nil || !ok || h.State != handoffOpen {
592 return err
593 }
594 var in struct {
595 Task string `json:"task"`
596 }
597 if json.Unmarshal([]byte(res.Text), &in) != nil || in.Task == "" {
598 _ = json.Unmarshal(v.Args, &in)
599 }
600 k, err := t.loadTask(strings.TrimSpace(in.Task))
601 if errors.Is(err, ErrNotFound) {
602 return nil
603 }
604 if err != nil {
605 return err
606 }
607 linked := t.db.Exec("INSERT INTO chat_handoff_tasks(handoff_id, task_id, created) VALUES (?,?,?) ON CONFLICT DO NOTHING", h.ID, k.ID, created)
608 if linked.Error != nil || linked.RowsAffected == 0 {
609 return linked.Error
610 }
611 return t.mirrorOpenCards(h, k)
612}
613
614// mirrorOpenCards raises the Assistant's card for each of the hand-off
615// person's team cards already open on a task the hand-off now follows,
616// and each open card of its project's alone (a ships question), through
617// the path a new card takes (mirrorCard: a go-ahead or Publish is
618// mirrored, a question or a card that stops the work told). A card already mirrored, or
619// held for quiet hours (mirrored when it shows), is left. A job's are
620// only those in its own thread (J4): the person's own work it joins
621// stays theirs. A legacy hand-off's are in the person's conversation.
622func (t *txn) mirrorOpenCards(h handoffRecord, k taskRecord) error {
623 q := t.db.Where("person = ? AND (held IS NULL OR held = ?) AND NOT EXISTS (SELECT 1 FROM chat_cards m WHERE m.source_card = chat_cards.id AND m.person = chat_cards.person)", h.Person, false)
624 if h.Lane != "" {
625 q = q.Where("lane = ?", h.Lane)
626 } else {
627 q = q.Where(personLane)
628 }
629 if k.ProjectID != "" {
630 q = q.Where("task_id = ? OR project_id = ? AND coalesce(task_id, '') = '' AND coalesce(turn_id, '') = ''", k.ID, k.ProjectID)
631 } else {
632 q = q.Where("task_id = ?", k.ID)
633 }
634 var cards []cardRecord
635 if err := q.Order("created_at, id").Find(&cards).Error; err != nil {
636 return err
637 }
638 for _, c := range cards {
639 if mirrorKind(c) == "" && !asksPerson(c) {
640 continue
641 }
642 if err := t.mirrorCard(c); err != nil {
643 return err
644 }
645 }
646 return nil
647}
648
649// handoffMessage: a message by key that starts a turn of its own (send):
650// a hand-off's words, or the answer to a card raised in a hand-off's
651// turn, so the turn holds the hand-off's work and nothing of the
652// person's.
653func (t *txn) handoffMessage(key string) (bool, error) {
654 if strings.HasPrefix(key, handoffKey) {
655 return true, nil
656 }
657 card, ok := strings.CutPrefix(key, "card:")
658 if !ok {
659 return false, nil
660 }
661 var turns []string
662 if err := t.db.Model(&cardRecord{}).Where("id = ?", card).Pluck("turn_id", &turns).Error; err != nil || len(turns) == 0 || turns[0] == "" {
663 return false, err
664 }
665 _, found, err := t.handoffOf(turns[0], "")
666 return found, err
667}
668
669// followAnswer makes the turn that carries the answer to a card raised
670// in a legacy hand-off's turn that hand-off's too, while the request is
671// open: work started after a question is answered is followed. A job
672// thread's answer is in the thread, so the hand-off's already.
673func (t *txn) followAnswer(c cardRecord, m messageRecord) error {
674 h, ok, err := t.handoffOf(c.TurnID, "")
675 if err != nil || !ok || h.State != handoffOpen || h.Lane != "" {
676 return err
677 }
678 return t.db.Exec("INSERT INTO chat_handoff_turns(handoff_id, turn_id) VALUES (?,?) ON CONFLICT DO NOTHING", h.ID, m.TurnID).Error
679}
680
681// handoffTurnEnded tells the hand-off of a Coordinator turn that ended
682// (saveTurn): a hand-off whose turns all ended with no work has stopped.
683func (t *txn) handoffTurnEnded(turnID string) error {
684 h, ok, err := t.handoffOf(turnID, "")
685 if err != nil || !ok {
686 return err
687 }
688 return t.handoffChanged(h, false)
689}
690
691// taskChanged tells each hand-off following the task (saveTask).
692func (t *txn) taskChanged(taskID string) error {
693 var ids []string
694 if err := t.db.Model(&handoffTaskRecord{}).Where("task_id = ?", taskID).Pluck("handoff_id", &ids).Error; err != nil || len(ids) == 0 {
695 return err
696 }
697 var rows []handoffRecord
698 if err := t.db.Where("id IN ?", ids).Order("created_at").Find(&rows).Error; err != nil {
699 return err
700 }
701 for _, h := range rows {
702 if err := t.handoffChanged(h, false); err != nil {
703 return err
704 }
705 }
706 return nil
707}
708
709// handoffChanged tells the Assistant of the hand-off (one voice: the
710// team's questions and stops reach it, never the person) when
711// needsPerson (a question, a card that stops the work, a go-ahead or a
712// Publish raised for it), or when its work has settled: every followed
713// task final, or the job stopped (stopReason). Routine progress tells it
714// nothing. What it is told is the job's note (jobNote), once: one
715// team_update turn in the Assistant lane, whose note a later change
716// rewrites while it waits; a note it was last given is not given again.
717// A cancelled request tells nothing more: the Assistant asked for that.
718// Housekeeping never starts a turn. Either way the job card follows, last
719// (projectJob; ruling P5j): it is never asking or stopped while the turn
720// that tells the Assistant so waits or runs.
721func (t *txn) handoffChanged(h handoffRecord, needsPerson bool) error {
722 if err := t.tellAssistant(h, needsPerson); err != nil {
723 return err
724 }
725 if err := t.settleLegacyQuestions(h); err != nil {
726 return err
727 }
728 return t.projectJob(h)
729}
730
731// tellAssistant is handoffChanged's team_update turn: queued, or its note
732// rewritten while it waits, when there is news.
733func (t *txn) tellAssistant(h handoffRecord, needsPerson bool) error {
734 if h.State == handoffCancelled || t.hk != nil {
735 return nil
736 }
737 if !needsPerson {
738 settled, err := t.handoffSettled(h)
739 if err != nil || !settled {
740 return err
741 }
742 }
743 note, err := t.jobNote(h)
744 if err != nil || note == "" {
745 return err
746 }
747 digest := bodyHash(note)
748 if digest == h.Digest {
749 return nil
750 }
751 now := t.now()
752 if err := t.db.Model(&handoffRecord{}).Where("id = ?", h.ID).Updates(map[string]any{"digest": digest, "updated_at": now}).Error; err != nil {
753 return err
754 }
755 var waiting turnRecord
756 if err := t.db.Where("id IN (SELECT turn_id FROM chat_handoff_turns WHERE handoff_id = ?) AND person = ? AND lane = ? AND kind = ? AND dispatched = ? AND state = ?", h.ID, h.Person, wire.LaneAssistant, wire.TurnTeamUpdate, false, wire.TurnQueued).Limit(1).Find(&waiting).Error; err != nil {
757 return err
758 }
759 if waiting.ID != "" {
760 return t.db.Model(&turnRecord{}).Where("id = ?", waiting.ID).Update("note", note).Error
761 }
762 r := turnRecord{ID: newID("t_"), Person: h.Person, State: wire.TurnQueued, Attempt: 1, Kind: wire.TurnTeamUpdate, Note: note, Revision: 1, CreatedAt: now, UpdatedAt: now, Lane: wire.LaneAssistant}
763 if err := t.db.Create(&r).Error; err != nil {
764 return err
765 }
766 if err := t.db.Create(&handoffTurnRecord{HandoffID: h.ID, TurnID: r.ID}).Error; err != nil {
767 return err
768 }
769 if err := t.turnEvent(r); err != nil {
770 return err
771 }
772 return t.dispatchNext(h.Person, wire.LaneAssistant)
773}
774
775// handoffTasks are the tasks the hand-off follows, oldest first.
776func (t *txn) handoffTasks(h handoffRecord) ([]taskRecord, error) {
777 var rows []taskRecord
778 err := t.db.Where("id IN (SELECT task_id FROM chat_handoff_tasks WHERE handoff_id = ?)", h.ID).Order("created_at, id").Find(&rows).Error
779 return rows, err
780}
781
782// handoffSettled: none of the hand-off's work moves on its own: each
783// task ended (and is not being published), or stopped and needs someone
784// (a merge that failed back at Ready to merge among them); or, with no
785// task, it stopped (handoffStopped).
786func (t *txn) handoffSettled(h handoffRecord) (bool, error) {
787 tasks, err := t.handoffTasks(h)
788 if err != nil {
789 return false, err
790 }
791 if len(tasks) == 0 {
792 return t.handoffStopped(h)
793 }
794 for _, k := range tasks {
795 steps, err := t.steps(k.ID)
796 if err != nil {
797 return false, err
798 }
799 if wire.FinalStage(k.Stage) {
800 // A merged site being published moves on its own.
801 if slices.ContainsFunc(steps, func(s stepRecord) bool { return s.Specialist == wire.SpecialistPublish && !wire.StepTerminal(s.State) }) {
802 return false, nil
803 }
804 continue
805 }
806 // Ready to merge is not settled: Equipo may merge it on its own,
807 // and a merge that waits for the person raises its card. Once the
808 // merge the person or Equipo started failed, nothing merges it on
809 // its own (autoMerge never tries a SHA again): it waits on them.
810 pr := progressFor(k, steps)
811 if needs := pr.needsYou(k); needs == "" || needs == wire.NeedsMerge && !mergeFailed(k, pr) {
812 return false, nil
813 }
814 }
815 return true, nil
816}
817
818// noAccess: s is a merge step refused for want of access to publish to
819// the repository: the runner had no usable credential for it (merge_credential),
820// or the hub said the agent may not merge there (merge_forbidden).
821func noAccess(s *stepRecord) bool {
822 return s != nil && s.Specialist == wire.SpecialistMerge && (s.Reason == wire.ReasonMergeCredential || s.Reason == "merge_forbidden")
823}
824
825// goingLiveCause is why going live stopped on the failed step s:
826// causeNoAccess when it is a merge refused for want of access (trying
827// again cannot help), else causeGoingLive.
828func goingLiveCause(s *stepRecord) string {
829 if noAccess(s) {
830 return causeNoAccess
831 }
832 return causeGoingLive
833}
834
835// mergeFailed: the task is back at Ready to merge because its candidate's
836// merge failed and ended (merge.go's mergeFailed): only the person's
837// Merge tries it again.
838func mergeFailed(k taskRecord, p progress) bool {
839 return k.Stage == wire.StageReadyToMerge && p.merge != nil && p.merge.State == wire.StepFailed && p.merge.Terminated
840}
841
842// publishFailed: the task's newest publish step ended without publishing
843// (failed, or cancelled before it was sent): its site did not go live.
844func publishFailed(steps []stepRecord) bool {
845 for i := len(steps) - 1; i >= 0; i-- {
846 if s := steps[i]; s.Specialist == wire.SpecialistPublish {
847 return s.State == wire.StepFailed || s.State == wire.StepCancelled
848 }
849 }
850 return false
851}
852
853// handoffStopped: the hand-off's Coordinator turns all ended, having
854// recorded or joined no work, and none left a question open for the
855// person (its card asks them). A turn that failed, or that the runner
856// no longer held when it came back, has ended too.
857func (t *txn) handoffStopped(h handoffRecord) (bool, error) {
858 var turns []turnRecord
859 if err := t.handoffTurns(h).Select("id", "state").Find(&turns).Error; err != nil || len(turns) == 0 {
860 return false, err
861 }
862 ids := make([]string, 0, len(turns))
863 for _, r := range turns {
864 if !wire.Terminal(r.State) {
865 return false, nil
866 }
867 ids = append(ids, r.ID)
868 }
869 var asking int64
870 err := t.db.Model(&cardRecord{}).Where("turn_id IN ? AND person = ? AND kind = ? AND state = ? AND "+coordinatorRole, ids, h.Person, wire.CardQuestion, wire.CardOpen).Count(&asking).Error
871 return asking == 0, err
872}
873
874// handoffTurns selects the hand-off's Coordinator turns: every turn of
875// its thread, or a legacy hand-off's turns linked to it in the person's
876// conversation.
877func (t *txn) handoffTurns(h handoffRecord) *gorm.DB {
878 if h.Lane != "" {
879 return t.db.Model(&turnRecord{}).Where("person = ? AND lane = ?", h.Person, h.Lane)
880 }
881 return t.db.Model(&turnRecord{}).Where("id IN (SELECT turn_id FROM chat_handoff_turns WHERE handoff_id = ?) AND person = ? AND "+personLane, h.ID, h.Person)
882}
883
884// handoffSummary is what the person is told of the hand-off: each task's
885// stage in plain words, its findings' headlines, its preview while it is
886// up and its published address; with no task, received, stopped or
887// cancelled. The words are the instance's copy.
888func (t *txn) handoffSummary(h handoffRecord) (string, error) {
889 tasks, err := t.handoffTasks(h)
890 if err != nil {
891 return "", err
892 }
893 if len(tasks) == 0 {
894 if h.State == handoffCancelled {
895 return t.copy("assistant.team.stage." + wire.StageCancelled), nil
896 }
897 if stopped, err := t.handoffStopped(h); err != nil || stopped {
898 return t.copy("assistant.team.stopped"), err
899 }
900 return t.copy("assistant.team.received"), nil
901 }
902 parts := make([]string, 0, len(tasks))
903 for _, k := range tasks {
904 part, err := t.taskSummary(k)
905 if err != nil {
906 return "", err
907 }
908 parts = append(parts, part)
909 }
910 return strings.Join(parts, "\n\n"), nil
911}
912
913func (t *txn) taskSummary(k taskRecord) (string, error) {
914 steps, err := t.steps(k.ID)
915 if err != nil {
916 return "", err
917 }
918 pr := progressFor(k, steps)
919 stage := "assistant.team.stage." + k.Stage
920 switch needs := pr.needsYou(k); {
921 case wire.FinalStage(k.Stage):
922 case (needs == wire.NeedsMerge || needs == wire.NeedsRetry) && !k.CancelRequested && pr.merge != nil && pr.merge.State == wire.StepFailed && pr.merge.Terminated && noAccess(pr.merge):
923 // Going live was refused for want of access: what is missing,
924 // never "waits for a go-ahead".
925 stage = "assistant.team.no_access"
926 case needs != "" && needs != wire.NeedsMerge:
927 stage = "assistant.team.stopped"
928 case !slices.Contains(wire.Stages, k.Stage) || k.CancelRequested:
929 stage = "assistant.team.stage." + wire.StageInProgress
930 }
931 lines := []string{t.copy(stage)}
932 var headlines []string
933 if err := t.db.Model(&entryRecord{}).Where("task_id = ? AND kind = ? AND coalesce(headline, '') <> ''", k.ID, entryFinding).Order("created_at, id").Pluck("headline", &headlines).Error; err != nil {
934 return "", err
935 }
936 for _, line := range headlines {
937 lines = append(lines, "- "+line)
938 }
939 held, err := t.previewHeld(k, steps)
940 if err != nil {
941 return "", err
942 }
943 if link := previewLink(k, steps, pr.candidate, t.now(), held); link != "" {
944 lines = append(lines, strings.Replace(t.copy("assistant.team.preview"), "%s", t.previewWrapperURL(k.ID), 1))
945 }
946 site, err := t.siteView(k, steps)
947 if err != nil {
948 return "", err
949 }
950 if site != nil && site.State == wire.SitePublished && site.URL != "" {
951 lines = append(lines, strings.Replace(t.copy("assistant.team.published"), "%s", site.URL, 1))
952 }
953 return strings.Join(lines, "\n"), nil
954}
955
956// Stop reasons (ruling P4j).
957const (
958 // stopFailed: only a step the instance can retry holds the job.
959 stopFailed = "failed"
960 // stopNoWork: its Coordinator turns ended with no work.
961 stopNoWork = "no_work"
962 // stopBlocked: only the person can move it on.
963 stopBlocked = "blocked"
964 // stopCancelled: every followed task ended cancelled (D5): not done.
965 stopCancelled = "cancelled"
966 // maxNudges is how many times the Assistant pushes a job through
967 // before it tells the person it stopped (D7).
968 maxNudges = 2
969)
970
971// stopReason is why the hand-off's work stopped ("" while it has not
972// settled, or when every followed task ended): stopFailed when all that
973// holds it is a failed step the instance marks retryable (needsYou
974// retry, its newest step neither a merge nor a publish); stopNoWork when
975// it has no task and its turns ended with none; stopBlocked for anything
976// else (a task's need only the person meets, a failed merge or a site
977// that did not go live among them, or, while the work has not ended, an
978// open card that stops it).
979func (t *txn) stopReason(h handoffRecord) (string, error) {
980 settled, err := t.handoffSettled(h)
981 if err != nil || !settled {
982 return "", err
983 }
984 reason, _, _, err := t.jobStop(h, true)
985 return reason, err
986}
987
988// jobStop is stopReason's reason, its cause (blockedLine's: a card's kind,
989// a task's need, or causeGoingLive) and whether the work ended (settled,
990// every followed task final, at least one done, none of them failing to
991// go live; all of them cancelled is stopCancelled). A task's
992// need only the person meets comes first; then an open card that stops
993// the work, which blocks the job whether or not it has settled (it waits
994// on the person from the moment it is raised), unless the work ended: a
995// project's question left open then is not the job's stop.
996func (t *txn) jobStop(h handoffRecord, settled bool) (reason, cause string, ended bool, err error) {
997 reason, cause, ended, err = t.firstStop(h, settled)
998 if err != nil || cause != causeGoingLive {
999 return reason, cause, ended, err
1000 }
1001 // Going live failed: refused for want of access on any of its tasks
1002 // says so, whichever came first, so the person is never told to try
1003 // again what cannot work until access is set up.
1004 tasks, err := t.handoffTasks(h)
1005 if err != nil {
1006 return "", "", false, err
1007 }
1008 for _, k := range tasks {
1009 if wire.FinalStage(k.Stage) {
1010 continue
1011 }
1012 steps, err := t.steps(k.ID)
1013 if err != nil {
1014 return "", "", false, err
1015 }
1016 var newest *stepRecord
1017 for i := range steps {
1018 if steps[i].Specialist != wire.SpecialistResearch {
1019 newest = &steps[i]
1020 }
1021 }
1022 pr := progressFor(k, steps)
1023 switch needs := pr.needsYou(k); {
1024 case needs == wire.NeedsMerge && mergeFailed(k, pr) && noAccess(pr.merge), needs == wire.NeedsRetry && noAccess(newest):
1025 return reason, causeNoAccess, ended, nil
1026 }
1027 }
1028 return reason, cause, ended, nil
1029}
1030
1031// firstStop is jobStop's stop from the first task (oldest first) that
1032// stops the job, before any access refusal among them is looked for.
1033func (t *txn) firstStop(h handoffRecord, settled bool) (reason, cause string, ended bool, err error) {
1034 tasks, err := t.handoffTasks(h)
1035 if err != nil {
1036 return "", "", false, err
1037 }
1038 failed, done := false, false
1039 ended = settled && len(tasks) > 0
1040 for _, k := range tasks {
1041 if !settled {
1042 break
1043 }
1044 steps, err := t.steps(k.ID)
1045 if err != nil {
1046 return "", "", false, err
1047 }
1048 var newest *stepRecord
1049 for i := range steps {
1050 if steps[i].Specialist != wire.SpecialistResearch {
1051 newest = &steps[i]
1052 }
1053 }
1054 live := newest != nil && (newest.Specialist == wire.SpecialistMerge || newest.Specialist == wire.SpecialistPublish)
1055 if wire.FinalStage(k.Stage) {
1056 // Merged, and its site did not go live, whatever step came
1057 // after its publish.
1058 if k.Stage == wire.StageDone && publishFailed(steps) {
1059 return stopBlocked, causeGoingLive, false, nil
1060 }
1061 done = done || k.Stage == wire.StageDone
1062 continue
1063 }
1064 ended = false
1065 pr := progressFor(k, steps)
1066 switch needs := pr.needsYou(k); {
1067 case needs == wire.NeedsMerge && mergeFailed(k, pr):
1068 return stopBlocked, goingLiveCause(pr.merge), false, nil
1069 case needs == wire.NeedsRetry && live:
1070 return stopBlocked, goingLiveCause(newest), false, nil
1071 case needs == wire.NeedsRetry:
1072 failed = true
1073 case needs != "" && needs != wire.NeedsMerge:
1074 return stopBlocked, needs, false, nil
1075 }
1076 }
1077 // Ruling R18: once every followed task ended, a project's card left
1078 // open (a stale ships question) is not the job's stop.
1079 switch {
1080 case ended && done:
1081 return "", "", true, nil
1082 case ended:
1083 return stopCancelled, "", false, nil
1084 }
1085 if cause, err = t.blockingCard(h); err != nil || cause != "" {
1086 return stopBlocked, cause, false, err
1087 }
1088 switch {
1089 case !settled:
1090 return "", "", false, nil
1091 case len(tasks) == 0:
1092 return stopNoWork, "", false, nil
1093 case failed:
1094 return stopFailed, "", false, nil
1095 }
1096 return "", "", false, nil
1097}
1098
1099// handoffCards are the person's team cards of kinds that may belong to
1100// the hand-off, as they stand (not held for quiet hours): in its thread,
1101// or a legacy hand-off's in their own conversation; then each kept only
1102// when it is the hand-off's (handoffFor).
1103func (t *txn) handoffCards(h handoffRecord, kinds []string, states []string) ([]cardRecord, error) {
1104 q := t.db.Where("person = ? AND kind IN ? AND state IN ? AND (held IS NULL OR held = ?)", h.Person, kinds, states, false)
1105 if h.Lane != "" {
1106 q = q.Where("lane = ?", h.Lane)
1107 } else {
1108 q = q.Where(personLane)
1109 }
1110 var rows []cardRecord
1111 if err := q.Order("created_at DESC, rowid DESC").Find(&rows).Error; err != nil {
1112 return nil, err
1113 }
1114 out := rows[:0]
1115 for _, c := range rows {
1116 owner, ok, err := t.handoffFor(c)
1117 if err != nil {
1118 return nil, err
1119 }
1120 if ok && owner.ID == h.ID {
1121 out = append(out, c)
1122 }
1123 }
1124 return out, nil
1125}
1126
1127// blockingCard is the kind of the hand-off's newest open card that stops
1128// its work (blocksWork), "" with none.
1129func (t *txn) blockingCard(h handoffRecord) (string, error) {
1130 cards, err := t.handoffCards(h, []string{wire.CardHome, wire.CardAccess, wire.CardDirection, wire.CardSpecialist, wire.CardResearchSources, wire.CardResearchInventory, wire.CardMergeShips, wire.CardMergePolicy, wire.CardMakerRemoved}, []string{wire.CardOpen, wire.CardHomeAsk})
1131 if err != nil {
1132 return "", err
1133 }
1134 for _, c := range cards {
1135 if blocksWork(c.Kind, c.State) {
1136 return c.Kind, nil
1137 }
1138 }
1139 return "", nil
1140}
1141
1142// readyToTry: a go-ahead or Publish of the hand-off's is open in front of
1143// the person (readyCard).
1144func (t *txn) readyToTry(h handoffRecord) (bool, error) {
1145 _, ok, err := t.readyCard(h)
1146 return ok, err
1147}
1148
1149// readyCard is the hand-off's newest go-ahead or Publish open in front of
1150// the person: its team card open and mirrored, the mirror open.
1151func (t *txn) readyCard(h handoffRecord) (cardRecord, bool, error) {
1152 cards, err := t.handoffCards(h, []string{wire.CardMerge, wire.CardPublish}, []string{wire.CardOpen})
1153 if err != nil {
1154 return cardRecord{}, false, err
1155 }
1156 for _, c := range cards {
1157 var n int64
1158 if err := t.db.Model(&cardRecord{}).Where("person = ? AND lane = ? AND state = ? AND source_card = ?", h.Person, wire.LaneAssistant, wire.CardOpen, c.ID).Count(&n).Error; err != nil || n > 0 {
1159 return c, n > 0, err
1160 }
1161 }
1162 return cardRecord{}, false, nil
1163}
1164
1165// openQuestion is the hand-off's newest open question card: in its
1166// thread, or for a legacy hand-off on its turns in the person's own
1167// conversation.
1168func (t *txn) openQuestion(h handoffRecord) (cardRecord, bool, error) {
1169 var c cardRecord
1170 q := t.db.Where("person = ? AND kind = ? AND state = ? AND (held IS NULL OR held = ?)", h.Person, wire.CardQuestion, wire.CardOpen, false)
1171 if h.Lane != "" {
1172 q = q.Where("lane = ?", h.Lane)
1173 } else {
1174 q = q.Where("turn_id IN (SELECT turn_id FROM chat_handoff_turns WHERE handoff_id = ?) AND "+personLane, h.ID)
1175 }
1176 err := q.Order("created_at DESC, rowid DESC").Limit(1).Find(&c).Error
1177 return c, err == nil && c.ID != "", err
1178}
1179
1180// questionOptions are a question card's options as stored, never nil.
1181func questionOptions(c cardRecord) ([]string, error) {
1182 out := []string{}
1183 if c.Options == "" {
1184 return out, nil
1185 }
1186 if err := json.Unmarshal([]byte(c.Options), &out); err != nil {
1187 return nil, err
1188 }
1189 if out == nil {
1190 out = []string{}
1191 }
1192 return out, nil
1193}
1194
1195// quoted is each option quoted, joined with ", ".
1196func quoted(options []string) string {
1197 q := make([]string, len(options))
1198 for i, o := range options {
1199 q[i] = strconv.Quote(o)
1200 }
1201 return strings.Join(q, ", ")
1202}
1203
1204// jobTitle is the job's title and the person's words it was handed over
1205// with: a hand-off made before titles is named for its words
1206// (fallbackTitle).
1207func (t *txn) jobTitle(h handoffRecord) (title, words string, err error) {
1208 var texts []string
1209 if h.MessageID != "" {
1210 if err := t.db.Model(&messageRecord{}).Where("id = ?", h.MessageID).Pluck("text", &texts).Error; err != nil {
1211 return "", "", err
1212 }
1213 }
1214 if len(texts) == 1 {
1215 words = texts[0]
1216 }
1217 if title = h.Title; title == "" {
1218 title = fallbackTitle(words)
1219 }
1220 return title, words, nil
1221}
1222
1223// jobNote is what a team_update turn tells the Assistant of the job, a
1224// line each: which job, the person's words, then what happened, the
1225// first that holds: a question for it (answer it, or ask the person
1226// once); a go-ahead or Publish in front of the person; done; cancelled
1227// (said only if the person did not cancel it themselves); stopped
1228// with no work, or on a step that can be tried again (push it through
1229// while nudges are left; else tell the person); only the person can
1230// move it on (in plain words, never to be nudged). Then where it stands
1231// (handoffSummary). "" when there is nothing to tell.
1232func (t *txn) jobNote(h handoffRecord) (string, error) {
1233 title, words, err := t.jobTitle(h)
1234 if err != nil {
1235 return "", err
1236 }
1237 lines := []string{fmt.Sprintf(noteJob, title, h.ID), fmt.Sprintf(noteAsked, words)}
1238 settled, err := t.handoffSettled(h)
1239 if err != nil {
1240 return "", err
1241 }
1242 reason, cause, ended, err := t.jobStop(h, settled)
1243 if err != nil {
1244 return "", err
1245 }
1246 q, asking, err := t.openQuestion(h)
1247 if err != nil {
1248 return "", err
1249 }
1250 // A Publish asked again because going live failed is not ready: the
1251 // person tries again. Nor is going live refused for want of access.
1252 ready := false
1253 if !asking && cause != causeGoingLive && cause != causeNoAccess {
1254 if ready, err = t.readyToTry(h); err != nil {
1255 return "", err
1256 }
1257 }
1258 left := maxNudges - int(h.Nudges)
1259 switch {
1260 case asking:
1261 options, err := questionOptions(q)
1262 if err != nil {
1263 return "", err
1264 }
1265 lines = append(lines, fmt.Sprintf(noteQuestion, q.Question))
1266 if len(options) > 0 {
1267 lines = append(lines, fmt.Sprintf(noteOptions, quoted(options)))
1268 }
1269 lines = append(lines, fmt.Sprintf(noteAnswerIt, h.ID))
1270 case ready:
1271 lines = append(lines, noteReady)
1272 case ended:
1273 lines = append(lines, noteDone)
1274 case reason == stopCancelled:
1275 lines = append(lines, noteCancelled)
1276 case (reason == stopNoWork || reason == stopFailed) && left <= 0:
1277 lines = append(lines, noteNoNudges)
1278 case reason == stopNoWork:
1279 lines = append(lines, fmt.Sprintf(noteNoWork, h.ID, left))
1280 case reason == stopFailed:
1281 lines = append(lines, fmt.Sprintf(noteFailed, h.ID, left))
1282 case reason == stopBlocked:
1283 line := blockedLine(cause)
1284 if line == "" {
1285 line = blockedLine(wire.CardDirection)
1286 }
1287 lines = append(lines, fmt.Sprintf(noteBlocked, line))
1288 default:
1289 return "", nil
1290 }
1291 summary, err := t.handoffSummary(h)
1292 if err != nil {
1293 return "", err
1294 }
1295 return strings.Join(append(lines, fmt.Sprintf(noteStands, summary)), "\n"), nil
1296}
1297
1298// openQuestionsNote is the reference block a turn the person started in
1299// the Assistant lane carries after their words (D8): each open question
1300// of their open or stopping jobs, newest job first, with its options, at
1301// most maxStatus of them, then how many more there are and where to read
1302// them (team_status); "" with none. asked is every one of those
1303// questions' cards, listed or not: the Assistant answers them itself
1304// (team_reply), so the waiting-cards note leaves them out.
1305func (t *txn) openQuestionsNote(person string) (block string, asked []string, err error) {
1306 var rows []handoffRecord
1307 if err := t.db.Where("person = ? AND state IN ?", person, []string{handoffOpen, handoffStopping}).Order("created_at DESC, id DESC").Find(&rows).Error; err != nil {
1308 return "", nil, err
1309 }
1310 var lines []string
1311 more := 0
1312 for _, h := range rows {
1313 q, ok, err := t.openQuestion(h)
1314 if err != nil {
1315 return "", nil, err
1316 }
1317 if !ok {
1318 continue
1319 }
1320 asked = append(asked, q.ID)
1321 if len(lines) == maxStatus {
1322 more++
1323 continue
1324 }
1325 title, _, err := t.jobTitle(h)
1326 if err != nil {
1327 return "", nil, err
1328 }
1329 options, err := questionOptions(q)
1330 if err != nil {
1331 return "", nil, err
1332 }
1333 // No brackets inside: the block's marker stays one.
1334 line := fmt.Sprintf(noteOpenQuestion, referenceText(title), h.ID, referenceText(q.Question))
1335 if len(options) > 0 {
1336 line += " " + fmt.Sprintf(noteOptions, quoted(options))
1337 }
1338 lines = append(lines, line)
1339 }
1340 if len(lines) == 0 {
1341 return "", asked, nil
1342 }
1343 switch {
1344 case more == 1:
1345 lines = append(lines, noteMoreQuestion)
1346 case more > 1:
1347 lines = append(lines, fmt.Sprintf(noteMoreQuestions, more))
1348 }
1349 return fmt.Sprintf(noteOpenQuestions, strings.Join(lines, "\n")), asked, nil
1350}
1351
1352// copy is the instance's words for key ("" with no copy).
1353func (t *txn) copy(key string) string {
1354 if t.s.authority.Copy == nil {
1355 return ""
1356 }
1357 return t.s.authority.Copy(key)
1358}
1359
1360// teamSummary is one request in team_status: its job's title, where it
1361// stands, and the question open for it, if any.
1362type teamSummary struct {
1363 Request string `json:"request"`
1364 Summary string `json:"summary"`
1365 Title string `json:"title"`
1366 Question *teamQuestion `json:"question,omitempty"`
1367}
1368
1369// teamQuestion is a job's open question and its options (never null).
1370type teamQuestion struct {
1371 Text string `json:"text"`
1372 Options []string `json:"options"`
1373}
1374
1375// teamStatus summarises one of the person's requests, their open ones,
1376// and with all the work they started in Equipo that is still open (its
1377// request is empty). A request names its job's title and the question
1378// open for it. Open requests come maxStatus at a time, newest first: a
1379// page with more after it names its last request as next, and after
1380// reads on from there (the person's own work only on the first page).
1381func (s *Store) teamStatus(ctx context.Context, person string, input json.RawMessage) (json.RawMessage, error) {
1382 var in struct {
1383 Request string `json:"request"`
1384 All bool `json:"all"`
1385 After string `json:"after"`
1386 }
1387 if wire.Strict(input, &in) != nil || len(in.Request) > 200 || len(in.After) > 200 || in.Request != "" && in.After != "" {
1388 return nil, errBadTeamInput
1389 }
1390 out := []teamSummary{}
1391 next := ""
1392 err := s.read(ctx, func(tx *gorm.DB) error {
1393 t := &txn{s: s, ctx: ctx, db: tx}
1394 var rows []handoffRecord
1395 q := tx.Where("person = ?", person)
1396 if in.Request != "" {
1397 q = q.Where("id = ?", in.Request)
1398 } else {
1399 q = q.Where("state IN ?", []string{handoffOpen, handoffStopping})
1400 }
1401 // The open requests ten at a time, newest first: after a page's
1402 // last (its next), the ones older than it.
1403 if in.After != "" {
1404 var from handoffRecord
1405 if err := tx.Where("id = ? AND person = ?", in.After, person).Limit(1).Find(&from).Error; err != nil {
1406 return err
1407 }
1408 if from.ID == "" {
1409 return assist.Failure{Code: "not_found", Message: toolNoRequest}
1410 }
1411 q = q.Where("(created_at < ? OR created_at = ? AND id < ?)", from.CreatedAt, from.CreatedAt, from.ID)
1412 }
1413 if err := q.Order("created_at DESC, id DESC").Limit(maxStatus + 1).Find(&rows).Error; err != nil {
1414 return err
1415 }
1416 if in.Request != "" && len(rows) == 0 {
1417 return assist.Failure{Code: "not_found", Message: toolNoRequest}
1418 }
1419 if len(rows) > maxStatus {
1420 rows = rows[:maxStatus]
1421 next = rows[maxStatus-1].ID
1422 }
1423 for _, h := range rows {
1424 text, err := t.handoffSummary(h)
1425 if err != nil {
1426 return err
1427 }
1428 title, _, err := t.jobTitle(h)
1429 if err != nil {
1430 return err
1431 }
1432 one := teamSummary{Request: h.ID, Summary: text, Title: title}
1433 q, asking, err := t.openQuestion(h)
1434 if err != nil {
1435 return err
1436 }
1437 if asking {
1438 options, err := questionOptions(q)
1439 if err != nil {
1440 return err
1441 }
1442 one.Question = &teamQuestion{Text: q.Question, Options: options}
1443 }
1444 out = append(out, one)
1445 }
1446 if !in.All || in.Request != "" || in.After != "" {
1447 return nil
1448 }
1449 var own []taskRecord
1450 if err := tx.Where("creator = ? AND stage NOT IN ? AND id NOT IN (SELECT task_id FROM chat_handoff_tasks WHERE handoff_id IN (SELECT id FROM chat_handoffs WHERE person = ?))", person, []string{wire.StageDone, wire.StageCancelled}, person).Order("created_at DESC, id DESC").Limit(maxStatus).Find(&own).Error; err != nil {
1451 return err
1452 }
1453 for _, k := range own {
1454 text, err := t.taskSummary(k)
1455 if err != nil {
1456 return err
1457 }
1458 out = append(out, teamSummary{Summary: strings.Replace(t.copy("assistant.team.own_work"), "%s", k.Title, 1) + "\n" + text})
1459 }
1460 return nil
1461 })
1462 if err != nil {
1463 return nil, err
1464 }
1465 page := map[string]any{"requests": out}
1466 if next != "" {
1467 page["next"] = next
1468 }
1469 raw, err := json.Marshal(page)
1470 return raw, err
1471}
1472
1473// teamCancel cancels the tasks the person's request created, and none it
1474// only joined, and ends its Coordinator turns still queued or running
1475// (as the person's own cancel would), in one transaction. A task it
1476// cannot stop (merging, or no longer the person's to stop) is still
1477// running: the request stays followed while one is (stopping), and is
1478// cancelled only once none is. Either way nothing done after it joins
1479// the request (followTask, followAnswer, handoffFor).
1480func (s *Store) teamCancel(ctx context.Context, call toolCallRecord, input json.RawMessage) (json.RawMessage, error) {
1481 var in struct {
1482 Request string `json:"request"`
1483 }
1484 if wire.Strict(input, &in) != nil || in.Request == "" || len(in.Request) > 200 {
1485 return nil, errBadTeamInput
1486 }
1487 n, running := 0, 0
1488 err := s.tx(ctx, func(t *txn) error {
1489 r, err := t.liveCall(call)
1490 if err != nil {
1491 return err
1492 }
1493 var h handoffRecord
1494 if err := t.db.Where("id = ? AND person = ?", in.Request, r.Person).Limit(1).Find(&h).Error; err != nil {
1495 return err
1496 }
1497 if h.ID == "" {
1498 return assist.Failure{Code: "not_found", Message: toolNoRequest}
1499 }
1500 var ids []string
1501 if err := t.db.Model(&handoffTaskRecord{}).Where("handoff_id = ? AND created = ?", h.ID, true).Order("task_id").Pluck("task_id", &ids).Error; err != nil {
1502 return err
1503 }
1504 for _, id := range ids {
1505 switch _, err := t.cancelTask(r.Person, id); {
1506 case err == nil:
1507 n++
1508 case errors.Is(err, ErrNotFound), errors.Is(err, ErrTaskEnded):
1509 case errors.Is(err, ErrMerging), errors.Is(err, ErrForbidden):
1510 running++
1511 default:
1512 return err
1513 }
1514 }
1515 state := handoffCancelled
1516 if running > 0 {
1517 state = handoffStopping
1518 }
1519 if err := t.db.Model(&handoffRecord{}).Where("id = ?", h.ID).Updates(map[string]any{"state": state, "updated_at": t.now()}).Error; err != nil {
1520 return err
1521 }
1522 // Its turns end once it is marked: a turn's end tells a
1523 // cancelled request nothing.
1524 var turns []turnRecord
1525 if err := t.handoffTurns(h).Where("state IN ?", wire.InFlight).Order("created_at, id").Find(&turns).Error; err != nil {
1526 return err
1527 }
1528 for _, turn := range turns {
1529 if err := t.cancelTurn(turn); err != nil {
1530 return err
1531 }
1532 }
1533 if err := t.s.authority.Audit(t.db, r.Person, auditTeamCancel, h.ID); err != nil {
1534 return err
1535 }
1536 h.State = state
1537 if err := t.settleLegacyQuestions(h); err != nil {
1538 return err
1539 }
1540 return t.projectJob(h)
1541 })
1542 if err != nil {
1543 return nil, err
1544 }
1545 raw, _ := json.Marshal(map[string]int{"cancelled": n, "still_running": running})
1546 return raw, nil
1547}
1548
1549// actionReply is a team_reply's handoffActionRecord kind.
1550const actionReply = "reply"
1551
1552// teamRefusal is a refusal the team provider words itself: the model
1553// reads its text as the instance's (opFailed), not as a provider's
1554// message, which is reference only.
1555type teamRefusal struct{ code, text string }
1556
1557func (r teamRefusal) Error() string { return r.code }
1558
1559// teamReply answers the open question on one of the person's jobs, as
1560// the person, once per key, in one transaction: the call's turn live; a
1561// reply made under the key before is its result again; the person's
1562// hand-off, and in a team_update turn only the one it tells; the job's
1563// open question card (never a go-ahead, Publish or a card that stops the
1564// work); the answer (questionAnswer) through the card's own path
1565// (answerQuestion: the card's lane, a legacy hand-off's in the person's
1566// conversation); the action; the job's digest cleared, so what it is
1567// told next is news, the same question asked again among it; its job
1568// card. Audited by the hand-off alone. No words check: the answer may
1569// come from anywhere in the conversation.
1570func (s *Store) teamReply(ctx context.Context, call toolCallRecord, input json.RawMessage, key string) (json.RawMessage, error) {
1571 var in struct {
1572 Request string `json:"request"`
1573 Answer string `json:"answer"`
1574 }
1575 // Raw bytes first: the decoder turns malformed UTF-8 into U+FFFD.
1576 if !utf8.Valid(input) || wire.Strict(input, &in) != nil || in.Request == "" || len(in.Request) > 200 || key == "" {
1577 return nil, errBadTeamInput
1578 }
1579 var out json.RawMessage
1580 err := s.tx(ctx, func(t *txn) error {
1581 r, err := t.liveCall(call)
1582 if err != nil {
1583 return err
1584 }
1585 if err := t.requireBuild(r.Person); err != nil {
1586 return err
1587 }
1588 var done handoffActionRecord
1589 if err := t.db.Where("ledger_key = ? AND person = ?", key, r.Person).Limit(1).Find(&done).Error; err != nil || done.LedgerKey != "" {
1590 out = json.RawMessage(done.Result)
1591 return err
1592 }
1593 var h handoffRecord
1594 if err := t.db.Where("id = ? AND person = ?", in.Request, r.Person).Limit(1).Find(&h).Error; err != nil {
1595 return err
1596 }
1597 if h.ID == "" {
1598 return assist.Failure{Code: "not_found", Message: toolNoRequest}
1599 }
1600 if err := t.aboutJob(r, h); err != nil {
1601 return err
1602 }
1603 card, open, err := t.openQuestion(h)
1604 if err != nil {
1605 return err
1606 }
1607 if !open {
1608 return teamRefusal{"no_question", toolNoQuestion}
1609 }
1610 answer, err := questionAnswer(card, in.Answer)
1611 if err != nil {
1612 return err
1613 }
1614 sent, _, err := t.answerQuestion(h.Person, card, wire.AnswerCard{Choice: answer, Revision: card.Revision})
1615 if errors.Is(err, ErrRunnerTooOld) {
1616 return assist.Failure{Code: "runner_too_old", Message: toolJobsTooOld}
1617 }
1618 if err != nil {
1619 return err
1620 }
1621 now := t.now()
1622 out, _ = json.Marshal(map[string]string{"request": h.ID, "status": "answered"})
1623 if err := t.db.Create(&handoffActionRecord{LedgerKey: key, HandoffID: h.ID, Person: h.Person, Kind: actionReply, MessageID: sent.Message.ID, Result: string(out), CreatedAt: now}).Error; err != nil {
1624 return err
1625 }
1626 if err := t.db.Model(&handoffRecord{}).Where("id = ?", h.ID).Updates(map[string]any{"digest": "", "updated_at": now}).Error; err != nil {
1627 return err
1628 }
1629 h.Digest = ""
1630 if err := t.projectJob(h); err != nil {
1631 return err
1632 }
1633 return t.s.authority.Audit(t.db, h.Person, auditTeamReply, h.ID)
1634 })
1635 if err != nil {
1636 return nil, err
1637 }
1638 return out, nil
1639}
1640
1641// questionAnswer is answer as the question card c takes it: trimmed, 1
1642// to maxAnswer characters with no NUL; with options, the option it
1643// names, whatever its case and spacing, in the option's own text (D17).
1644func questionAnswer(c cardRecord, answer string) (string, error) {
1645 answer = strings.TrimSpace(answer)
1646 if n := utf8.RuneCountInString(answer); n == 0 || n > maxAnswer || !utf8.ValidString(answer) || strings.ContainsRune(answer, 0) {
1647 return "", errBadTeamInput
1648 }
1649 options, err := questionOptions(c)
1650 if err != nil || len(options) == 0 {
1651 return answer, err
1652 }
1653 want, _, _ := folded(answer)
1654 for _, o := range options {
1655 if got, _, _ := folded(strings.TrimSpace(o)); got == want {
1656 return o, nil
1657 }
1658 }
1659 return "", teamRefusal{"not_an_option", fmt.Sprintf(toolNotAnOption, quoted(options))}
1660}
1661
1662// aboutJob refuses a turn the person did not start (a team_update) that
1663// does not tell the hand-off (not_asked); a turn they started may touch
1664// any job of theirs.
1665func (t *txn) aboutJob(r turnRecord, h handoffRecord) error {
1666 if r.Kind == wire.TurnPerson {
1667 return nil
1668 }
1669 var n int64
1670 if err := t.db.Model(&handoffTurnRecord{}).Where("handoff_id = ? AND turn_id = ?", h.ID, r.ID).Count(&n).Error; err != nil {
1671 return err
1672 }
1673 if n == 0 {
1674 return teamRefusal{"not_asked", toolNotThisJob}
1675 }
1676 return nil
1677}
1678
1679// actionNudge is a team_nudge's handoffActionRecord kind.
1680const actionNudge = "nudge"
1681
1682// errNeedsPerson: only the person can move the job on (D6: no fallback
1683// nudge).
1684var errNeedsPerson = teamRefusal{"needs_person", toolNeedsPerson}
1685
1686// teamNudge pushes one of the person's stopped jobs through, once per
1687// key, in one transaction: the call's turn live; a nudge made under the
1688// key before is its result again; the person's open hand-off, and in a
1689// team_update turn only the one it tells; the job stopped where the
1690// Assistant may push it (stopReason: with no work, or on a failed step
1691// the instance retries; any other stop is the person's); the words
1692// quoted from the person's messages to the Assistant (quoteAny); the cap
1693// (D7, ruling P1j): the count starts again only when the words quote a
1694// message newer than the job's last nudge, and a job nudged maxNudges
1695// times is nudge_limit. Then a failed step is tried again (retryFailed),
1696// or the words go to the job's thread (lane "" for a legacy hand-off)
1697// under the hand-off's key and the provider's key (ruling P2j), its turn
1698// the hand-off's, the action holding the context it is dispatched with
1699// (handoffContext). The job's digest cleared, its card, the audit by the
1700// hand-off alone.
1701func (s *Store) teamNudge(ctx context.Context, call toolCallRecord, input json.RawMessage, key string) (json.RawMessage, error) {
1702 var in struct {
1703 Request string `json:"request"`
1704 Words string `json:"words"`
1705 Context string `json:"context"`
1706 }
1707 // Raw bytes first: the decoder turns malformed UTF-8 into U+FFFD.
1708 if !utf8.Valid(input) || wire.Strict(input, &in) != nil || in.Request == "" || len(in.Request) > 200 || len(in.Words) > wire.MaxMessageBytes || len(in.Context) > maxContext || strings.ContainsRune(in.Words+in.Context, 0) || key == "" {
1709 return nil, errBadTeamInput
1710 }
1711 var out json.RawMessage
1712 err := s.tx(ctx, func(t *txn) error {
1713 r, err := t.liveCall(call)
1714 if err != nil {
1715 return err
1716 }
1717 var done handoffActionRecord
1718 if err := t.db.Where("ledger_key = ? AND person = ?", key, r.Person).Limit(1).Find(&done).Error; err != nil || done.LedgerKey != "" {
1719 out = json.RawMessage(done.Result)
1720 return err
1721 }
1722 var h handoffRecord
1723 if err := t.db.Where("id = ? AND person = ?", in.Request, r.Person).Limit(1).Find(&h).Error; err != nil {
1724 return err
1725 }
1726 if h.ID == "" {
1727 return assist.Failure{Code: "not_found", Message: toolNoRequest}
1728 }
1729 if h.State != handoffOpen {
1730 return assist.Failure{Code: "turn_ended"}
1731 }
1732 if err := t.aboutJob(r, h); err != nil {
1733 return err
1734 }
1735 if h.AbilityHeldAt != nil && r.Kind == wire.TurnPerson {
1736 // A job held while building was off: the person asking, in
1737 // their own words, to push it on is their Carry on now
1738 // (abilities AD4). The words are checked as any nudge's.
1739 if _, _, err := t.quoteAny(h.Person, in.Words); err != nil {
1740 return err
1741 }
1742 if err := t.resumeAbilityHold(h); errors.Is(err, ErrAbilityOff) {
1743 return t.requireBuild(h.Person)
1744 } else if err != nil {
1745 return err
1746 }
1747 out, _ = json.Marshal(map[string]any{"request": h.ID, "status": "nudged", "nudges_left": maxNudges - h.Nudges})
1748 if err := t.db.Create(&handoffActionRecord{LedgerKey: key, HandoffID: h.ID, Person: h.Person, Kind: actionNudge, Context: referenceText(in.Context), Result: string(out), CreatedAt: t.now()}).Error; err != nil {
1749 return err
1750 }
1751 return t.s.authority.Audit(t.db, h.Person, auditTeamNudge, h.ID)
1752 }
1753 if err := t.requireBuild(h.Person); err != nil {
1754 return err
1755 }
1756 reason, err := t.stopReason(h)
1757 switch {
1758 case err != nil:
1759 return err
1760 case reason == "":
1761 return teamRefusal{"not_stopped", toolNotStopped}
1762 case reason != stopNoWork && reason != stopFailed:
1763 return errNeedsPerson
1764 case reason == stopNoWork && h.Lane != "":
1765 if err := t.jobRunner(h.Person); errors.Is(err, ErrRunnerTooOld) {
1766 return assist.Failure{Code: "runner_too_old", Message: toolJobsTooOld}
1767 } else if err != nil {
1768 return err
1769 }
1770 }
1771 words, from, err := t.quoteAny(h.Person, in.Words)
1772 if err != nil {
1773 return err
1774 }
1775 var last handoffActionRecord
1776 if err := t.db.Where("handoff_id = ? AND kind = ?", h.ID, actionNudge).Order("created_at DESC").Limit(1).Find(&last).Error; err != nil {
1777 return err
1778 }
1779 nudges := h.Nudges
1780 if last.LedgerKey == "" || from.CreatedAt.After(last.CreatedAt) {
1781 nudges = 0
1782 }
1783 if nudges >= maxNudges {
1784 return teamRefusal{"nudge_limit", toolNudgeLimit}
1785 }
1786 nudges++
1787 now := t.now()
1788 if err := t.db.Model(&handoffRecord{}).Where("id = ?", h.ID).Updates(map[string]any{"nudges": nudges, "digest": "", "updated_at": now}).Error; err != nil {
1789 return err
1790 }
1791 h.Nudges, h.Digest = nudges, ""
1792 out, _ = json.Marshal(map[string]any{"request": h.ID, "status": "nudged", "nudges_left": maxNudges - nudges})
1793 action := handoffActionRecord{LedgerKey: key, HandoffID: h.ID, Person: h.Person, Kind: actionNudge, Context: referenceText(in.Context), Result: string(out), CreatedAt: now}
1794 if reason == stopFailed {
1795 if err := t.retryFailed(h); err != nil {
1796 return err
1797 }
1798 if err := t.db.Create(&action).Error; err != nil {
1799 return err
1800 }
1801 } else if _, _, err := t.send(h.Lane, h.Person, handoffKey+h.ID+":nudge:"+key, words, nil, func(m messageRecord) error {
1802 action.MessageID = m.ID
1803 if err := t.db.Create(&action).Error; err != nil {
1804 return err
1805 }
1806 return t.db.Create(&handoffTurnRecord{HandoffID: h.ID, TurnID: m.TurnID}).Error
1807 }); err != nil {
1808 return err
1809 }
1810 if err := t.projectJob(h); err != nil {
1811 return err
1812 }
1813 return t.s.authority.Audit(t.db, h.Person, auditTeamNudge, h.ID)
1814 })
1815 if err != nil {
1816 return nil, err
1817 }
1818 return out, nil
1819}
1820
1821// retryFailed tries again exactly one task (ruling R22), as the person's
1822// Retry would (retryStep): the hand-off's earliest that a failed step the
1823// instance can retry holds (needsYou retry) and that the person, an
1824// owner, created. With none, the job is the person's (errNeedsPerson).
1825func (t *txn) retryFailed(h handoffRecord) error {
1826 if err := t.isOwner(h.Person); errors.Is(err, ErrForbidden) {
1827 return errNeedsPerson
1828 } else if err != nil {
1829 return err
1830 }
1831 tasks, err := t.handoffTasks(h)
1832 if err != nil {
1833 return err
1834 }
1835 for _, k := range tasks {
1836 if k.Creator != h.Person || wire.FinalStage(k.Stage) {
1837 continue
1838 }
1839 steps, err := t.steps(k.ID)
1840 if err != nil {
1841 return err
1842 }
1843 if progressFor(k, steps).needsYou(k) != wire.NeedsRetry {
1844 continue
1845 }
1846 switch _, err := t.retryStep(&k, h.Person); {
1847 case errors.Is(err, ErrNotRetryable), errors.Is(err, ErrForbidden):
1848 continue
1849 case err != nil:
1850 return err
1851 }
1852 return nil
1853 }
1854 return errNeedsPerson
1855}
1856