oficina / equipo Public

Let the Assistant answer a job's question with team_reply

team_reply {request, answer} answers the open question card of one of
the person's jobs, as the person, through answerQuestion: the answer
goes to the card's lane (the job thread, or lane "" for a legacy
hand-off). An answer must match an option (case and spacing ignored,
D17) or, without options, be 1 to 2000 characters; no words check.
Once per key (a stored reply action), audited by hand-off id only. It
clears the job's digest and projects the job card.

A team_update turn may now run team_reply and team_nudge for the job it
tells; every other write there stays not_asked. Budgets re-measured.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by paul@keymail.dev 471e0a7a9eb044fc90821aa18b553a081c87cb3c parent 0e97e2a
6 files changed, +504 −14
  • .rastrillo/budgets.txt +2 −2
  • internal/equipo/chat/assistant_tools.go +16 −5
  • internal/equipo/chat/handoff.go +130 −0
  • internal/equipo/chat/tools.go +7 −1
  • internal/thintest/assistant_outcome_contract_test.go +4 −6
  • internal/thintest/assistant_reply_contract_test.go +345 −0
diff --git a/.rastrillo/budgets.txt b/.rastrillo/budgets.txt
index 83d36c4f..d63a2e75 100644
--- a/.rastrillo/budgets.txt
+++ b/.rastrillo/budgets.txt
@@ -56,7 +56,7 @@ perf GET /api/v1/tasks/{id} skip Thin v1 person API: bearer-only JSON for device
perf GET /api/v1/assistant/snapshot skip Assistant person API: bearer-only JSON for Base's chat, not a browser screen.
perf GET /api/v1/assistant/messages skip Assistant person API: bearer-only JSON for Base's chat, not a browser screen.
perf GET /api/v1/assistant/events skip Assistant event stream (Server-Sent Events), bearer-only and long-lived; not a screen.
-size internal/equipo/chat 26415 - The instance store shares transaction and authority helpers. Adds job threads, their pages, titles, action ledger, job notes and job cards. Measured 26415 source lines.
+size internal/equipo/chat 26560 - The instance store shares transaction and authority helpers. Adds job threads, their pages, titles, action ledger, job notes, job cards and team_reply. Measured 26560 source lines.
perf GET /api/v1/questions/{id} skip Thin v1 person API: bearer-only JSON for devices; the browser reads questions on /tasks/{id}.
perf GET /api/v1/steps/{id}/log skip Thin v1 person API: bearer-only JSON for devices; the browser shows the log tail on /tasks/{id}.
perf GET /api/v1/connections/preference skip Connections slice 1 person API: bearer-only JSON for devices; the browser shows the preference on /conversation/connections.
@@ -71,7 +71,7 @@ perf GET /tasks/{id}/files/{file} skip Research kept images: the bytes of one im
perf GET /api/v1/runners skip Mac runners person API: bearer-only JSON for devices; the browser shows runners in the Team section.
time cmd/equipo-runner 60s TestReleaseRunnerHasNoFakeWorker builds the release runner and the thin package under testbuild (about 12s locally).
size internal/headless - 10368 End-to-end scenarios through a real runner and instance, browser drives and the Assistant's job threads included. Measured 10368 test lines.
-size internal/thintest - 26653 Contract and browser tests share one instance harness. Adds the job thread, card lane, page, title, job note and job card contracts. Measured 26653 test lines.
+size internal/thintest - 26996 Contract and browser tests share one instance harness. Adds the job thread, card lane, page, title, job note, job card and team_reply contracts. Measured 26996 test lines.
perf GET /api/v1/projects/{id}/merge-policy skip Merge authority person API: bearer-only JSON for devices; the browser reads the policy on /projects/{id}.
perf GET /api/v1/usage skip Thin v1 person API: bearer-only JSON for devices; the browser reads usage through /usage.
perf GET /api/v1/advice skip Thin v1 person API: bearer-only JSON for devices; the browser reads advice through /usage and /conversation.
diff --git a/internal/equipo/chat/assistant_tools.go b/internal/equipo/chat/assistant_tools.go
index 9436277b..01e49d2c 100644
--- a/internal/equipo/chat/assistant_tools.go
+++ b/internal/equipo/chat/assistant_tools.go
@@ -617,9 +617,10 @@ func (s *Store) runRemote(ctx context.Context, row toolCallRecord) (res wire.Too
if run, code := assist.Decide(op); !run {
return opRefused(code, ""), false
}
- // A turn the person did not start (a team_update) only looks.
+ // A turn the person did not start (a team_update) only looks, but for
+ // answering or nudging the job it tells (updateWrites).
if !op.ReadOnly {
- asked, err := s.asked(ctx, row)
+ asked, err := s.asked(ctx, row, op)
if err != nil {
return refused("unavailable", toolOpUnavailable), false
}
@@ -634,19 +635,29 @@ func (s *Store) runRemote(ctx context.Context, row toolCallRecord) (res wire.Too
return fitFrame(wire.ToolResult{Code: "used", Text: string(out)}), op.ReadOnly
}
-// asked: the call's turn is one the person started.
-func (s *Store) asked(ctx context.Context, row toolCallRecord) (bool, error) {
+// asked: the call's turn is one the person started, or op is one of the
+// team's updateWrites in a team_update turn (which job it may touch is
+// the operation's own check).
+func (s *Store) asked(ctx context.Context, row toolCallRecord, op assist.Operation) (bool, error) {
var kinds []string
err := s.read(ctx, func(tx *gorm.DB) error {
return tx.Model(&turnRecord{}).Where("id = ? AND person = ?", row.TurnID, row.Person).Pluck("coalesce(kind, '')", &kinds).Error
})
- return err == nil && len(kinds) == 1 && kinds[0] == wire.TurnPerson, err
+ if err != nil || len(kinds) != 1 {
+ return false, err
+ }
+ update := kinds[0] == wire.TurnTeamUpdate && op.Provider == teamProvider{}.Name() && slices.Contains(updateWrites, op.Name)
+ return kinds[0] == wire.TurnPerson || update, nil
}
// opFailed is a provider's or the registry's failure as a result. An
// operation unknown to a person with no host registered is one that is
// not connected: their Base was never asked.
func (s *Store) opFailed(ctx context.Context, person string, err error) wire.ToolResult {
+ var own teamRefusal
+ if errors.As(err, &own) {
+ return refused(own.code, own.text)
+ }
var f assist.Failure
if !errors.As(err, &f) {
return refused("unavailable", toolOpUnavailable)
diff --git a/internal/equipo/chat/handoff.go b/internal/equipo/chat/handoff.go
index 0537a3c6..8f6e8d44 100644
--- a/internal/equipo/chat/handoff.go
+++ b/internal/equipo/chat/handoff.go
@@ -39,6 +39,8 @@ const (
opTeamRequest = "team_request"
opTeamStatus = "team_status"
opTeamCancel = "team_cancel"
+ opTeamReply = "team_reply"
+ opTeamNudge = "team_nudge"
handoffOpen = "open"
// handoffStopping: cancelled while work it started could not be
@@ -49,6 +51,7 @@ const (
auditHandoff = "assistant.handoff"
auditTeamCancel = "assistant.team_cancel"
+ auditTeamReply = "assistant.team_reply"
// handoffKey is the instance's idempotency key space for a hand-off's
// Coordinator message (validKey keeps clients out of it).
@@ -60,6 +63,8 @@ const (
maxStatus = 10
// maxTitle is the most characters a job's title has (D10).
maxTitle = 60
+ // maxAnswer is the most characters team_reply's answer has.
+ maxAnswer = 2000
// minQuote is the fewest characters words may quote.
minQuote = 3
)
@@ -166,8 +171,16 @@ var teamOps = []assist.Operation{
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).",
Input: json.RawMessage(`{"type":"object","properties":{"request":{"type":"string"}},"required":["request"],"additionalProperties":false}`),
Output: json.RawMessage(`{"type":"object","properties":{"cancelled":{"type":"integer"},"still_running":{"type":"integer"}}}`)},
+ {Name: opTeamReply, App: "Team", Scope: "team", Idempotent: true,
+ 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.",
+ Input: json.RawMessage(`{"type":"object","properties":{"request":{"type":"string"},"answer":{"type":"string","maxLength":2000}},"required":["request","answer"],"additionalProperties":false}`),
+ Output: json.RawMessage(`{"type":"object","properties":{"request":{"type":"string"},"status":{"type":"string"}}}`)},
}
+// updateWrites are the team's writes a team_update turn may make, each
+// about the job the update tells (teamReply, and Task 11's team_nudge).
+var updateWrites = []string{opTeamReply, opTeamNudge}
+
func (p teamProvider) Invoke(ctx context.Context, person, operation string, input json.RawMessage, key string) (json.RawMessage, error) {
call, ok := callFrom(ctx)
if !ok || call.Person != person {
@@ -180,6 +193,8 @@ func (p teamProvider) Invoke(ctx context.Context, person, operation string, inpu
return p.s.teamStatus(ctx, person, input)
case opTeamCancel:
return p.s.teamCancel(ctx, call, input)
+ case opTeamReply:
+ return p.s.teamReply(ctx, call, input, key)
}
return nil, assist.Failure{Code: "unknown_operation"}
}
@@ -1262,3 +1277,118 @@ func (s *Store) teamCancel(ctx context.Context, call toolCallRecord, input json.
raw, _ := json.Marshal(map[string]int{"cancelled": n, "still_running": running})
return raw, nil
}
+
+// actionReply is a team_reply's handoffActionRecord kind.
+const actionReply = "reply"
+
+// teamRefusal is a refusal the team provider words itself: the model
+// reads its text as the instance's (opFailed), not as a provider's
+// message, which is reference only.
+type teamRefusal struct{ code, text string }
+
+func (r teamRefusal) Error() string { return r.code }
+
+// teamReply answers the open question on one of the person's jobs, as
+// the person, once per key, in one transaction: the call's turn live; a
+// reply made under the key before is its result again; the person's
+// hand-off, and in a team_update turn only the one it tells; the job's
+// open question card (never a go-ahead, Publish or a card that stops the
+// work); the answer (questionAnswer) through the card's own path
+// (answerQuestion: the card's lane, a legacy hand-off's in the person's
+// conversation); the action; the job's digest cleared, so what it is
+// told next is news, the same question asked again among it; its job
+// card. Audited by the hand-off alone. No words check: the answer may
+// come from anywhere in the conversation.
+func (s *Store) teamReply(ctx context.Context, call toolCallRecord, input json.RawMessage, key string) (json.RawMessage, error) {
+ var in struct {
+ Request string `json:"request"`
+ Answer string `json:"answer"`
+ }
+ if wire.Strict(input, &in) != nil || in.Request == "" || len(in.Request) > 200 || key == "" {
+ return nil, errBadTeamInput
+ }
+ var out json.RawMessage
+ err := s.tx(ctx, func(t *txn) error {
+ r, err := t.liveCall(call)
+ if err != nil {
+ return err
+ }
+ var done handoffActionRecord
+ if err := t.db.Where("ledger_key = ? AND person = ?", key, r.Person).Limit(1).Find(&done).Error; err != nil || done.LedgerKey != "" {
+ out = json.RawMessage(done.Result)
+ return err
+ }
+ var h handoffRecord
+ if err := t.db.Where("id = ? AND person = ?", in.Request, r.Person).Limit(1).Find(&h).Error; err != nil {
+ return err
+ }
+ if h.ID == "" {
+ return assist.Failure{Code: "not_found", Message: toolNoRequest}
+ }
+ if r.Kind != wire.TurnPerson {
+ var n int64
+ if err := t.db.Model(&handoffTurnRecord{}).Where("handoff_id = ? AND turn_id = ?", h.ID, r.ID).Count(&n).Error; err != nil {
+ return err
+ }
+ if n == 0 {
+ return teamRefusal{"not_asked", toolNotThisJob}
+ }
+ }
+ card, open, err := t.openQuestion(h)
+ if err != nil {
+ return err
+ }
+ if !open {
+ return teamRefusal{"no_question", toolNoQuestion}
+ }
+ answer, err := questionAnswer(card, in.Answer)
+ if err != nil {
+ return err
+ }
+ sent, _, err := t.answerQuestion(h.Person, card, wire.AnswerCard{Choice: answer, Revision: card.Revision})
+ if errors.Is(err, ErrRunnerTooOld) {
+ return assist.Failure{Code: "runner_too_old", Message: toolJobsTooOld}
+ }
+ if err != nil {
+ return err
+ }
+ now := t.now()
+ out, _ = json.Marshal(map[string]string{"request": h.ID, "status": "answered"})
+ 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 {
+ return err
+ }
+ if err := t.db.Model(&handoffRecord{}).Where("id = ?", h.ID).Updates(map[string]any{"digest": "", "updated_at": now}).Error; err != nil {
+ return err
+ }
+ h.Digest = ""
+ if err := t.projectJob(h); err != nil {
+ return err
+ }
+ return t.s.authority.Audit(t.db, h.Person, auditTeamReply, h.ID)
+ })
+ if err != nil {
+ return nil, err
+ }
+ return out, nil
+}
+
+// questionAnswer is answer as the question card c takes it: trimmed, 1
+// to maxAnswer characters with no NUL; with options, the option it
+// names, whatever its case and spacing, in the option's own text (D17).
+func questionAnswer(c cardRecord, answer string) (string, error) {
+ answer = strings.TrimSpace(answer)
+ if n := utf8.RuneCountInString(answer); n == 0 || n > maxAnswer || !utf8.ValidString(answer) || strings.ContainsRune(answer, 0) {
+ return "", errBadTeamInput
+ }
+ options, err := questionOptions(c)
+ if err != nil || len(options) == 0 {
+ return answer, err
+ }
+ want, _, _ := folded(answer)
+ for _, o := range options {
+ if got, _, _ := folded(strings.TrimSpace(o)); got == want {
+ return o, nil
+ }
+ }
+ return "", teamRefusal{"not_an_option", fmt.Sprintf(toolNotAnOption, quoted(options))}
+}
diff --git a/internal/equipo/chat/tools.go b/internal/equipo/chat/tools.go
index 2eefbe26..e6e3b34f 100644
--- a/internal/equipo/chat/tools.go
+++ b/internal/equipo/chat/tools.go
@@ -48,8 +48,14 @@ const (
// reference, never instructions.
toolOpFailed = "The operation failed. What it said: "
// The team's operations (handoff.go).
- toolTeamInput = "words is a string; title, when given, one line of at most 60 characters; context, when given, a string of at most 4000 bytes; request is a request id from team_request or team_status."
+ toolTeamInput = "words is a string; title, when given, one line of at most 60 characters; context, when given, a string of at most 4000 bytes; request is a request id from team_request or team_status; answer is 1 to 2000 characters."
toolNoRequest = "No request of this person's has that id. Use team_status to see their requests."
+ // team_reply's refusals (teamReply): no question open for the job, an
+ // answer none of its options (they follow, quoted), and another job's
+ // question in a team_update turn.
+ toolNoQuestion = "That job has no open question. Use team_status to see where it stands."
+ toolNotAnOption = "The answer must be one of the question's options: %s."
+ toolNotThisJob = "This update is about another job. Answer or nudge only the job it names."
// toolRequestCancelled: a hand-off's turn after the person cancelled
// the request (handoffFenced).
toolRequestCancelled = "Not done: the person cancelled this request, so start or record no more work for it. Finish this reply now in one line."
diff --git a/internal/thintest/assistant_outcome_contract_test.go b/internal/thintest/assistant_outcome_contract_test.go
index c3066f8d..7dd12379 100644
--- a/internal/thintest/assistant_outcome_contract_test.go
+++ b/internal/thintest/assistant_outcome_contract_test.go
@@ -723,12 +723,10 @@ func TestContractAssistantLaneLeaksNoMachinery(t *testing.T) {
}
answers = append(answers, out)
}
- // The thread's question is answered through its own card (Task 10:
- // team_reply).
- if card, revision := o.threadQuestion(request); card != "" {
- if _, err := o.client.Answer(o.ctx, card, "Web", revision); err != nil {
- t.Fatal(err)
- }
+ // The Assistant answers the thread's question itself (team_reply).
+ o.threadQuestion(request)
+ if res := o.use("ol-reply", "team_reply", map[string]any{"request": request, "answer": "Web"}); res.IsError {
+ t.Fatalf("team_reply %+v", res)
}
answer(outcome, wire.ChoiceMerge)
m := o.dispatched(wire.SpecialistMerge, base, cand, 0)
diff --git a/internal/thintest/assistant_reply_contract_test.go b/internal/thintest/assistant_reply_contract_test.go
new file mode 100644
index 00000000..5fe703b2
--- /dev/null
+++ b/internal/thintest/assistant_reply_contract_test.go
@@ -0,0 +1,345 @@
+package thintest
+
+import (
+ "encoding/json"
+ "slices"
+ "strings"
+ "testing"
+
+ "amadan.net/oficina/equipo/internal/wire"
+)
+
+// team_reply (jobs design §4; D17): the Assistant answers the open
+// question on one of the person's jobs, as the person, through the
+// question card's own path: an option when the question has options,
+// else its own words, with no words check. One answer per key, audited
+// without payload. Only a question card, and in a team_update turn only
+// the job the update is about.
+
+const loginQuestion = "Which login page?"
+
+// askedJob hands "Login is broken" to the team from a new Assistant turn,
+// has the job's thread ask question (with options, none when nil), ends
+// the thread's turn and the Assistant's, and returns the request, the
+// thread's turn and the team_update turn that tells the Assistant,
+// dispatched.
+func (o *teamRig) askedJob(key, question string, options []string) (request, asked, update string) {
+ o.t.Helper()
+ o.ask("Can we fix a bug in Tito? Login is broken")
+ request, cmd := o.handoff(key+"-h", "Login is broken", "")
+ args := map[string]any{"question": question}
+ if options != nil {
+ args["options"] = options
+ }
+ o.in(cmd.TurnID, func() {
+ if res := o.call(key+"-ask", wire.ToolAskPerson, args); res.Code != "asked" {
+ o.t.Fatalf("ask %+v", res)
+ }
+ })
+ o.reply(cmd.TurnID)
+ o.reply(o.turn)
+ u := o.message(wire.LaneAssistant)
+ if u.Kind != wire.TurnTeamUpdate {
+ o.t.Fatalf("update frame %+v", u)
+ }
+ return request, cmd.TurnID, u.TurnID
+}
+
+// teamReply is team_reply for request in the rig's turn.
+func (o *teamRig) teamReply(id, request, answer string) wire.ToolResult {
+ o.t.Helper()
+ return o.use(id, "team_reply", map[string]any{"request": request, "answer": answer})
+}
+
+// replied fails unless res is team_reply's answer for request.
+func replied(t *testing.T, res wire.ToolResult, request string) {
+ t.Helper()
+ want, _ := json.Marshal(map[string]string{"request": request, "status": "answered"})
+ if res.IsError || res.Code != "used" || res.Text != string(want) {
+ t.Fatalf("team_reply %+v, want %s", res, want)
+ }
+}
+
+// questionCard is the state, choice and revision of the request's newest
+// question card.
+func (o *teamRig) questionCard(request string) (state, choice string, revision int64) {
+ o.t.Helper()
+ q := "SELECT state, coalesce(choice, ''), revision FROM chat_cards c WHERE kind = ? AND (lane = ? OR turn_id IN (SELECT turn_id FROM chat_handoff_turns WHERE handoff_id = ?)) ORDER BY created_at DESC, rowid DESC LIMIT 1"
+ if err := o.inst.DB.Writer().QueryRow(q, wire.CardQuestion, wire.JobLane(request), request).Scan(&state, &choice, &revision); err != nil {
+ o.t.Fatal(err)
+ }
+ return state, choice, revision
+}
+
+// lastAudit is the newest audit row's id.
+func (o *teamRig) lastAudit() int {
+ return o.rows("SELECT coalesce(max(id), 0) FROM audit_events")
+}
+
+// TestContractTeamReply: in the team_update turn that tells it of the
+// job's question, the Assistant answers it with team_reply, in any case:
+// the question card is answered with the option's own text, which the
+// job's thread gets as the person's message, dispatched with the
+// question it answers. One audit row, with neither the answer nor the
+// question. The job card never shows asking after it, and the same
+// question asked again is told again.
+func TestContractTeamReply(t *testing.T) {
+ o := newTeamRig(t)
+ request, asked, update := o.askedJob("rp", loginQuestion, []string{"Web", "App"})
+ card := o.jobCardID(request)
+ events := len(o.jobEvents(card))
+ audit := o.lastAudit()
+ var res wire.ToolResult
+ o.in(update, func() { res = o.teamReply("rp-reply", request, " web ") })
+ replied(t, res, request)
+ if state, choice, _ := o.questionCard(request); state != wire.CardAnswered || choice != "Web" {
+ t.Fatalf("the question card %s %q", state, choice)
+ }
+ thread := o.thread(request)
+ if last := thread[len(thread)-1]; last.Role != wire.RolePerson || last.Text != "Web" || last.TurnID == asked {
+ t.Fatalf("the thread's last message %+v", last)
+ }
+ cmd := o.message(wire.JobLane(request))
+ if cmd.Text != `(My answer to your question "Which login page?") Web` || !slices.Equal(cmd.PersonText, []string{"Web"}) {
+ t.Fatalf("the answer's frame %+v", cmd)
+ }
+ if n := o.rows("SELECT count(*) FROM audit_events WHERE id > ? AND kind = 'assistant.team_reply' AND actor = ? AND record_id = ?", audit, Owner, request); n != 1 {
+ t.Fatalf("%d team_reply audits", n)
+ }
+ if n := o.rows("SELECT count(*) FROM audit_events WHERE id > ? AND (record_id LIKE '%Web%' OR record_id LIKE '%login page%')", audit); n != 0 {
+ t.Fatalf("%d audit rows carry the answer or the question", n)
+ }
+ o.reply(update)
+ o.jobOf(request, "working", func(c wire.AssistantCard) bool { return c.State == wire.JobWorking })
+ for _, c := range o.jobEvents(card)[events:] {
+ if c.State != wire.JobWorking {
+ t.Fatalf("the job card after the answer %+v", c)
+ }
+ }
+ // The same question asked again is news again.
+ o.in(cmd.TurnID, func() {
+ if res := o.call("rp-again", wire.ToolAskPerson, map[string]any{"question": loginQuestion, "options": []string{"Web", "App"}}); res.Code != "asked" {
+ t.Fatalf("ask again %+v", res)
+ }
+ })
+ o.reply(cmd.TurnID)
+ o.until("the second update", func() bool { ids, _, _ := o.updates(); return len(ids) == 2 })
+}
+
+// TestContractTeamReplyOptions: an answer that is none of the options is
+// not_an_option, naming them, and the card stays open; a question with
+// no options takes any words of 1 to 2000 characters (2001 and blank are
+// invalid_input); with no question open, no_question.
+func TestContractTeamReplyOptions(t *testing.T) {
+ t.Run("options", func(t *testing.T) {
+ o := newTeamRig(t)
+ request, _, update := o.askedJob("ro", loginQuestion, []string{"Web", "App"})
+ _, _, revision := o.questionCard(request)
+ o.in(update, func() {
+ res := o.teamReply("ro-desktop", request, "Desktop")
+ if !res.IsError || res.Code != "not_an_option" || res.Text != `The answer must be one of the question's options: "Web", "App".` {
+ t.Fatalf("not an option %+v", res)
+ }
+ })
+ if state, _, rev := o.questionCard(request); state != wire.CardOpen || rev != revision {
+ t.Fatalf("the card after a refusal %s %d", state, rev)
+ }
+ })
+ t.Run("free text", func(t *testing.T) {
+ o := newTeamRig(t)
+ request, _, update := o.askedJob("rf", "What should the button say?", nil)
+ o.in(update, func() {
+ for key, answer := range map[string]string{"rf-long": strings.Repeat("é", 2001), "rf-blank": " \n "} {
+ if res := o.teamReply(key, request, answer); !res.IsError || res.Code != "invalid_input" {
+ t.Fatalf("%s %+v", key, res)
+ }
+ }
+ if state, _, _ := o.questionCard(request); state != wire.CardOpen {
+ t.Fatalf("the card after refusals %s", state)
+ }
+ answer := strings.Repeat("é", 2000)
+ replied(t, o.teamReply("rf-ok", request, answer), request)
+ if state, choice, _ := o.questionCard(request); state != wire.CardAnswered || choice != answer {
+ t.Fatalf("the card %s, %d runes", state, len([]rune(choice)))
+ }
+ res := o.teamReply("rf-none", request, "Sign in")
+ if !res.IsError || res.Code != "no_question" || res.Text != "That job has no open question. Use team_status to see where it stands." {
+ t.Fatalf("no question %+v", res)
+ }
+ })
+ })
+}
+
+// TestContractTeamReplyFromContext: once the Assistant was told and the
+// job shows asking, it answers from the conversation in a turn the
+// person started, in words found in no message of theirs; the job card
+// is working again at once.
+func TestContractTeamReplyFromContext(t *testing.T) {
+ o := newTeamRig(t)
+ request, _, update := o.askedJob("rc", "What should the button say?", nil)
+ o.reply(update)
+ card := o.jobOf(request, "asking", func(c wire.AssistantCard) bool { return c.State == wire.JobAsking })
+ o.ask("Use the email one, like we said")
+ events := len(o.jobEvents(card.ID))
+ replied(t, o.teamReply("rc-reply", request, "Sign in with email"), request)
+ if state, choice, _ := o.questionCard(request); state != wire.CardAnswered || choice != "Sign in with email" {
+ t.Fatalf("the question card %s %q", state, choice)
+ }
+ after := o.jobEvents(card.ID)[events:]
+ if len(after) == 0 || after[0].State != wire.JobWorking {
+ t.Fatalf("the job card's events after the answer %+v", after)
+ }
+}
+
+// TestContractTeamReplyOnce: the same call under a new call id, then a
+// result lost before it was stored, in attempt 2: one answer, one
+// message in the thread, one action, one audit, equal results.
+func TestContractTeamReplyOnce(t *testing.T) {
+ o := newTeamRig(t)
+ request, _, update := o.askedJob("ron", loginQuestion, []string{"Web", "App"})
+ var first, again, lost wire.ToolResult
+ o.in(update, func() {
+ first = o.teamReply("ron-1", request, "Web")
+ again = o.teamReply("ron-2", request, "Web")
+ })
+ replied(t, first, request)
+ if again.IsError || !again.Replayed || again.Text != first.Text {
+ t.Fatalf("again %+v, first %+v", again, first)
+ }
+ o.runner.Send(o.ctx, "r-ron-wait", wire.FrameTurn, wire.TurnReport{TurnID: update, Attempt: 1, State: wire.TurnWaiting, Reason: "limited"})
+ o.runner.Send(o.ctx, "r-ron-run2", wire.FrameTurn, wire.TurnReport{TurnID: update, Attempt: 2, State: wire.TurnRunning})
+ o.until("attempt 2", func() bool {
+ return o.rows("SELECT count(*) FROM chat_turns WHERE id = ? AND attempt = 2 AND state = ?", update, wire.TurnRunning) == 1
+ })
+ // The ledger lost the result: the provider gets the same key again.
+ o.exec("UPDATE chat_tool_calls SET ledger_key = '' WHERE turn_id = ?", update)
+ o.in(update, func() {
+ o.attempt = 2
+ lost = o.teamReply("ron-3", request, "Web")
+ })
+ if lost.IsError || lost.Text != first.Text {
+ t.Fatalf("after a lost result %+v, first %+v", lost, first)
+ }
+ if n := o.rows("SELECT count(*) FROM chat_messages WHERE lane = ? AND role = ? AND text = 'Web'", wire.JobLane(request), wire.RolePerson); n != 1 {
+ t.Fatalf("%d answers in the thread", n)
+ }
+ if n := o.rows("SELECT count(*) FROM chat_handoff_actions WHERE handoff_id = ? AND kind = 'reply'", request); n != 1 {
+ t.Fatalf("%d reply actions", n)
+ }
+ if n := o.rows("SELECT count(*) FROM audit_events WHERE kind = 'assistant.team_reply'"); n != 1 {
+ t.Fatalf("%d team_reply audits", n)
+ }
+}
+
+// TestContractTeamReplyOnlyOwnJob: a team_update turn answers only the
+// job it is about (another job's is not_asked, and its card stays open);
+// another person's request is not_found; a turn the person started
+// answers any job of theirs.
+func TestContractTeamReplyOnlyOwnJob(t *testing.T) {
+ o := newTeamRig(t)
+ o.ask("Can we fix a bug in Tito? Login is broken, and the logo is blurry")
+ requests := map[string]string{}
+ for key, words := range map[string]string{"a": "Login is broken", "b": "the logo is blurry"} {
+ request, cmd := o.handoff("oj-"+key, words, "")
+ requests[key] = request
+ o.in(cmd.TurnID, func() {
+ if res := o.call("oj-ask-"+key, wire.ToolAskPerson, map[string]any{"question": "Which one?", "options": []string{"This", "That"}}); res.Code != "asked" {
+ t.Fatalf("ask %+v", res)
+ }
+ })
+ o.reply(cmd.TurnID)
+ }
+ o.reply(o.turn)
+ first := o.message(wire.LaneAssistant)
+ var mine, other string
+ for _, request := range requests {
+ if o.rows("SELECT count(*) FROM chat_handoff_turns WHERE handoff_id = ? AND turn_id = ?", request, first.TurnID) == 1 {
+ mine = request
+ } else {
+ other = request
+ }
+ }
+ if first.Kind != wire.TurnTeamUpdate || mine == "" || other == "" {
+ t.Fatalf("the first update %+v (%v)", first, requests)
+ }
+ _, _, revision := o.questionCard(other)
+ o.in(first.TurnID, func() {
+ res := o.teamReply("oj-other", other, "This")
+ if !res.IsError || res.Code != "not_asked" || res.Text != "This update is about another job. Answer or nudge only the job it names." {
+ t.Fatalf("another job's question %+v", res)
+ }
+ })
+ if state, _, rev := o.questionCard(other); state != wire.CardOpen || rev != revision {
+ t.Fatalf("the other job's card %s %d", state, rev)
+ }
+ o.reply(first.TurnID)
+ second := o.message(wire.LaneAssistant)
+ o.reply(second.TurnID)
+
+ mate := &teamRig{o.other("mate@example.com")}
+ mate.ask("Pick This for that one")
+ if res := mate.teamReply("oj-mate", mine, "This"); !res.IsError || res.Code != "not_found" {
+ t.Fatalf("another person's request %+v", res)
+ }
+
+ o.ask("This for both")
+ for _, request := range []string{other, mine} {
+ replied(t, o.teamReply("oj-own-"+request, request, "This"), request)
+ }
+}
+
+// TestContractTeamReplyOnlyQuestions: team_reply answers only a
+// question: with only a go-ahead open for the job it is no_question, and
+// the go-ahead stays open, unmerged.
+func TestContractTeamReplyOnlyQuestions(t *testing.T) {
+ o := newTeamRig(t)
+ o.ask("Can we fix a bug in Tito? Login is broken")
+ request, cmd := o.handoff("oq-h", "Login is broken", "")
+ base, cand := strings.Repeat("1", 40), strings.Repeat("2", 40)
+ var id string
+ o.in(cmd.TurnID, func() { id, _ = o.websiteReady("oqr", "Quick website", base, cand, false) })
+ outcome := o.assistantCard("the merge outcome", isMergeOutcome)
+ team := o.cardOf(id)
+ for i, answer := range []string{wire.ChoiceMerge, "Yes"} {
+ res := o.teamReply("oq-reply-"+itoa(i), request, answer)
+ if !res.IsError || res.Code != "no_question" {
+ t.Fatalf("team_reply %q on a go-ahead %+v", answer, res)
+ }
+ }
+ if got := o.cardOf(id); got.State != wire.CardOpen || got.Revision != team.Revision {
+ t.Fatalf("the go-ahead %+v", got)
+ }
+ if got := o.assistantCard("still open", func(c wire.AssistantCard) bool { return c.ID == outcome.ID }); got.State != wire.CardOpen || got.Revision != outcome.Revision {
+ t.Fatalf("the outcome %+v", got)
+ }
+ if n := o.rows("SELECT count(*) FROM chat_steps WHERE task_id = ? AND specialist = ?", id, wire.SpecialistMerge); n != 0 {
+ t.Fatal("merged on a team_reply")
+ }
+}
+
+// TestContractTeamReplyLegacy: a legacy hand-off's question, in the
+// person's own conversation, answered with team_reply: the answer goes
+// to lane "" with the question it answers, as slice 1's card answer did,
+// and its turn is the hand-off's.
+func TestContractTeamReplyLegacy(t *testing.T) {
+ o := newTeamRig(t)
+ o.ask("Can we fix a bug in Tito? Login is broken")
+ request, turn := o.legacyHandoff("lr", "Login is broken")
+ o.in(turn, func() {
+ if res := o.call("lr-ask", wire.ToolAskPerson, map[string]any{"question": loginQuestion, "options": []string{"Web", "App"}}); res.Code != "asked" {
+ t.Fatalf("ask %+v", res)
+ }
+ })
+ o.reply(turn)
+ replied(t, o.teamReply("lr-reply", request, "App"), request)
+ next := o.message(wire.LaneCoordinator)
+ if next.Text != `(My answer to your question "Which login page?") App` || o.laneOf(next.TurnID) != wire.LaneCoordinator {
+ t.Fatalf("the answer's frame %+v", next)
+ }
+ if n := o.rows("SELECT count(*) FROM chat_handoff_turns WHERE handoff_id = ? AND turn_id = ?", request, next.TurnID); n != 1 {
+ t.Fatal("the answer's turn is not the legacy hand-off's")
+ }
+ if n := o.rows("SELECT count(*) FROM chat_turns WHERE lane LIKE 'job:%'"); n != 0 {
+ t.Fatalf("%d turns in a job thread", n)
+ }
+}