oficina / equipo Public

Tell the Assistant the team's questions and stops instead of the person

Only go-ahead and Publish cards are mirrored into the Assistant lane now.
A team question or a card that stops the work queues a model-facing
team_update note (jobNote) instead, for new and legacy hand-offs alike;
mirrors raised before this release still follow their team cards.

handoffChanged queues a note only for a question, a go-ahead or Publish,
every followed task final, or a stop (stopReason, ruling P4j: only a
retryable failed step is "failed"; every other need is the person's).
Routine progress, and a site being published, tell nothing. team_status
gains the job's title and its open question, and a person's Assistant
message carries the open questions after their words as reference (D8).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by paul@keymail.dev 783ce0baf5b2a889462180cb0cb7a033146c1147 parent 338fed6
8 files changed, +1,047 −151
  • .rastrillo/budgets.txt +2 −2
  • internal/equipo/chat/handoff.go +389 −27
  • internal/equipo/chat/handoff_test.go +22 −0
  • internal/equipo/chat/outcome.go +36 −15
  • internal/equipo/chat/store.go +11 −0
  • internal/equipo/chat/tools.go +62 −0
  • internal/thintest/assistant_outcome_contract_test.go +154 −69
  • internal/thintest/assistant_team_contract_test.go +371 −38
diff --git a/.rastrillo/budgets.txt b/.rastrillo/budgets.txt
index 8945a9cf..c28f4180 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 25650 - The instance store shares transaction and authority helpers. Adds job threads, their pages, titles and action ledger. Measured 25650 source lines.
+size internal/equipo/chat 26106 - The instance store shares transaction and authority helpers. Adds job threads, their pages, titles, action ledger and job notes. Measured 26106 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 - 25580 Contract and browser tests share one instance harness. Adds the job thread hand-off, card lane, page and title contracts. Measured 25580 test lines.
+size internal/thintest - 25998 Contract and browser tests share one instance harness. Adds the job thread, card lane, page, title and job note contracts. Measured 25998 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/handoff.go b/internal/equipo/chat/handoff.go
index 1970ff08..e4aa9303 100644
--- a/internal/equipo/chat/handoff.go
+++ b/internal/equipo/chat/handoff.go
@@ -4,7 +4,9 @@ import (
"context"
"encoding/json"
"errors"
+ "fmt"
"slices"
+ "strconv"
"strings"
"time"
"unicode"
@@ -24,8 +26,9 @@ import (
// (legacy: no lane) keeps slice 1's routing in their conversation. A hand-off follows every task its turns record (created) or
// join (touched), and the turn that carries the answer to a question its
// turn asked. When that work stops on its own (finished, failed, waiting
-// for someone) the instance starts an Assistant turn of kind team_update
-// carrying a summary in plain words, never the team's machinery: no
+// for someone), or it asks the person something, the instance starts an
+// Assistant turn of kind team_update carrying the job's note (jobNote),
+// never the team's machinery or its own voice to the person: no
// repository, branch, SHA or link into Equipo, and no task id but the
// one a preview's own address is named for (eq-<task>, tmp-<task>).
//
@@ -64,8 +67,8 @@ const (
// handoffRecord is one team_request: the Assistant turn it came from,
// the Coordinator message it posted, the Assistant's context, the key
// the request was made with (unique: a repeat is this row), open,
-// stopping or cancelled, the digest of the summary the person was last
-// told, and its thread: job:<id>, or "" for a legacy hand-off, whose
+// stopping or cancelled, the digest of the note the Assistant was last
+// given, and its thread: job:<id>, or "" for a legacy hand-off, whose
// words went to the person's own conversation. Title names the job (the
// model's, or fallbackTitle's); Nudges counts the Assistant's nudges.
type handoffRecord struct {
@@ -453,7 +456,8 @@ func (t *txn) followTask(r turnRecord, v *wire.ToolCall, res wire.ToolResult) er
// mirrorOpenCards raises the Assistant's card for each of the hand-off
// person's team cards already open on a task the hand-off now follows,
// and each open card of its project's alone (a ships question), through
-// the path a new card takes (mirrorCard). A card already mirrored, or
+// the path a new card takes (mirrorCard: a go-ahead or Publish is
+// mirrored, a question or a card that stops the work told). A card already mirrored, or
// held for quiet hours (mirrored when it shows), is left. A job's are
// only those in its own thread (J4): the person's own work it joins
// stays theirs. A legacy hand-off's are in the person's conversation.
@@ -474,7 +478,7 @@ func (t *txn) mirrorOpenCards(h handoffRecord, k taskRecord) error {
return err
}
for _, c := range cards {
- if mirrorKind(c) == "" {
+ if mirrorKind(c) == "" && !asksPerson(c) {
continue
}
if err := t.mirrorCard(c); err != nil {
@@ -544,13 +548,16 @@ func (t *txn) taskChanged(taskID string) error {
return nil
}
-// handoffChanged tells the person when the hand-off's work has stopped
-// on its own (every task finished, failed or waiting for someone), or
-// when needsPerson (a card for them), and its summary is not the one they
-// were last told: one
-// team_update turn in the Assistant lane, whose text a later change
-// rewrites while it waits. A cancelled request tells nothing more: the
-// Assistant asked for that. Housekeeping never starts a turn.
+// handoffChanged tells the Assistant of the hand-off (one voice: the
+// team's questions and stops reach it, never the person) when
+// needsPerson (a question, a card that stops the work, a go-ahead or a
+// Publish raised for it), or when its work has settled: every followed
+// task final, or the job stopped (stopReason). Routine progress tells it
+// nothing. What it is told is the job's note (jobNote), once: one
+// team_update turn in the Assistant lane, whose note a later change
+// rewrites while it waits; a note it was last given is not given again.
+// A cancelled request tells nothing more: the Assistant asked for that.
+// Housekeeping never starts a turn.
func (t *txn) handoffChanged(h handoffRecord, needsPerson bool) error {
if h.State == handoffCancelled || t.hk != nil {
return nil
@@ -561,11 +568,11 @@ func (t *txn) handoffChanged(h handoffRecord, needsPerson bool) error {
return err
}
}
- summary, err := t.handoffSummary(h)
- if err != nil {
+ note, err := t.jobNote(h)
+ if err != nil || note == "" {
return err
}
- digest := bodyHash(summary)
+ digest := bodyHash(note)
if digest == h.Digest {
return nil
}
@@ -578,9 +585,9 @@ func (t *txn) handoffChanged(h handoffRecord, needsPerson bool) error {
return err
}
if waiting.ID != "" {
- return t.db.Model(&turnRecord{}).Where("id = ?", waiting.ID).Update("note", summary).Error
+ return t.db.Model(&turnRecord{}).Where("id = ?", waiting.ID).Update("note", note).Error
}
- r := turnRecord{ID: newID("t_"), Person: h.Person, State: wire.TurnQueued, Attempt: 1, Kind: wire.TurnTeamUpdate, Note: summary, Revision: 1, CreatedAt: now, UpdatedAt: now, Lane: wire.LaneAssistant}
+ 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}
if err := t.db.Create(&r).Error; err != nil {
return err
}
@@ -601,8 +608,8 @@ func (t *txn) handoffTasks(h handoffRecord) ([]taskRecord, error) {
}
// handoffSettled: none of the hand-off's work moves on its own: each
-// task ended, or stopped and needs someone; or, with no task, it stopped
-// (handoffStopped).
+// task ended (and is not being published), or stopped and needs someone;
+// or, with no task, it stopped (handoffStopped).
func (t *txn) handoffSettled(h handoffRecord) (bool, error) {
tasks, err := t.handoffTasks(h)
if err != nil {
@@ -612,13 +619,17 @@ func (t *txn) handoffSettled(h handoffRecord) (bool, error) {
return t.handoffStopped(h)
}
for _, k := range tasks {
- if wire.FinalStage(k.Stage) {
- continue
- }
steps, err := t.steps(k.ID)
if err != nil {
return false, err
}
+ if wire.FinalStage(k.Stage) {
+ // A merged site being published moves on its own.
+ if slices.ContainsFunc(steps, func(s stepRecord) bool { return s.Specialist == wire.SpecialistPublish && !wire.StepTerminal(s.State) }) {
+ return false, nil
+ }
+ continue
+ }
// Ready to merge is not settled: Equipo may merge it on its own,
// and a merge that waits for the person raises its card.
if needs := progressFor(k, steps).needsYou(k); needs == "" || needs == wire.NeedsMerge {
@@ -727,6 +738,330 @@ func (t *txn) taskSummary(k taskRecord) (string, error) {
return strings.Join(lines, "\n"), nil
}
+// Stop reasons (ruling P4j).
+const (
+ // stopFailed: only a step the instance can retry holds the job.
+ stopFailed = "failed"
+ // stopNoWork: its Coordinator turns ended with no work.
+ stopNoWork = "no_work"
+ // stopBlocked: only the person can move it on.
+ stopBlocked = "blocked"
+ // maxNudges is how many times the Assistant pushes a job through
+ // before it tells the person it stopped (D7).
+ maxNudges = 2
+)
+
+// stopReason is why the hand-off's work stopped ("" while it has not
+// settled, or when every followed task ended): stopFailed when all that
+// holds it is a failed step the instance marks retryable (needsYou
+// retry, its newest step neither a merge nor a publish); stopNoWork when
+// it has no task and its turns ended with none; stopBlocked for anything
+// else (a task's need only the person meets, a failed merge or publish
+// among them, or, while the work has not ended, an open card that stops
+// it).
+//
+//lint:ignore U1000 the job card's stopped state (D5) reads it; remove this line then.
+func (t *txn) stopReason(h handoffRecord) (string, error) {
+ settled, err := t.handoffSettled(h)
+ if err != nil || !settled {
+ return "", err
+ }
+ reason, _, _, err := t.jobStop(h, true)
+ return reason, err
+}
+
+// jobStop is stopReason's reason, its cause (blockedLine's: a card's kind,
+// a task's need, or causeGoingLive) and whether the work ended (settled,
+// every followed task final, none of them failing to go live). A task's
+// need only the person meets comes first; then an open card that stops
+// the work, which blocks the job whether or not it has settled (it waits
+// on the person from the moment it is raised), unless the work ended: a
+// project's question left open then is not the job's stop.
+func (t *txn) jobStop(h handoffRecord, settled bool) (reason, cause string, ended bool, err error) {
+ tasks, err := t.handoffTasks(h)
+ if err != nil {
+ return "", "", false, err
+ }
+ failed := false
+ ended = settled && len(tasks) > 0
+ for _, k := range tasks {
+ if !settled {
+ break
+ }
+ steps, err := t.steps(k.ID)
+ if err != nil {
+ return "", "", false, err
+ }
+ var newest *stepRecord
+ for i := range steps {
+ if steps[i].Specialist != wire.SpecialistResearch {
+ newest = &steps[i]
+ }
+ }
+ live := newest != nil && (newest.Specialist == wire.SpecialistMerge || newest.Specialist == wire.SpecialistPublish)
+ if wire.FinalStage(k.Stage) {
+ if live && newest.Specialist == wire.SpecialistPublish && newest.State == wire.StepFailed {
+ return stopBlocked, causeGoingLive, false, nil
+ }
+ continue
+ }
+ ended = false
+ switch needs := progressFor(k, steps).needsYou(k); {
+ case needs == wire.NeedsRetry && live:
+ return stopBlocked, causeGoingLive, false, nil
+ case needs == wire.NeedsRetry:
+ failed = true
+ case needs != "" && needs != wire.NeedsMerge:
+ return stopBlocked, needs, false, nil
+ }
+ }
+ if ended {
+ return "", "", true, nil
+ }
+ if cause, err = t.blockingCard(h); err != nil || cause != "" {
+ return stopBlocked, cause, false, err
+ }
+ switch {
+ case !settled:
+ return "", "", false, nil
+ case len(tasks) == 0:
+ return stopNoWork, "", false, nil
+ case failed:
+ return stopFailed, "", false, nil
+ }
+ return "", "", false, nil
+}
+
+// handoffCards are the person's team cards of kinds that may belong to
+// the hand-off, as they stand (not held for quiet hours): in its thread,
+// or a legacy hand-off's in their own conversation; then each kept only
+// when it is the hand-off's (handoffFor).
+func (t *txn) handoffCards(h handoffRecord, kinds []string, states []string) ([]cardRecord, error) {
+ q := t.db.Where("person = ? AND kind IN ? AND state IN ? AND (held IS NULL OR held = ?)", h.Person, kinds, states, false)
+ if h.Lane != "" {
+ q = q.Where("lane = ?", h.Lane)
+ } else {
+ q = q.Where(personLane)
+ }
+ var rows []cardRecord
+ if err := q.Order("created_at DESC, rowid DESC").Find(&rows).Error; err != nil {
+ return nil, err
+ }
+ out := rows[:0]
+ for _, c := range rows {
+ owner, ok, err := t.handoffFor(c)
+ if err != nil {
+ return nil, err
+ }
+ if ok && owner.ID == h.ID {
+ out = append(out, c)
+ }
+ }
+ return out, nil
+}
+
+// blockingCard is the kind of the hand-off's newest open card that stops
+// its work (blocksWork), "" with none.
+func (t *txn) blockingCard(h handoffRecord) (string, error) {
+ cards, err := t.handoffCards(h, []string{wire.CardHome, wire.CardAccess, wire.CardDirection, wire.CardSpecialist, wire.CardResearchSources, wire.CardResearchInventory, wire.CardMergeShips, wire.CardMergePolicy}, []string{wire.CardOpen, wire.CardHomeAsk})
+ if err != nil {
+ return "", err
+ }
+ for _, c := range cards {
+ if blocksWork(c.Kind, c.State) {
+ return c.Kind, nil
+ }
+ }
+ return "", nil
+}
+
+// readyToTry: a go-ahead or Publish of the hand-off's is open in front of
+// the person (its team card open and mirrored).
+func (t *txn) readyToTry(h handoffRecord) (bool, error) {
+ cards, err := t.handoffCards(h, []string{wire.CardMerge, wire.CardPublish}, []string{wire.CardOpen})
+ if err != nil || len(cards) == 0 {
+ return false, err
+ }
+ ids := make([]string, 0, len(cards))
+ for _, c := range cards {
+ ids = append(ids, c.ID)
+ }
+ var n int64
+ err = t.db.Model(&cardRecord{}).Where("person = ? AND lane = ? AND state = ? AND source_card IN ?", h.Person, wire.LaneAssistant, wire.CardOpen, ids).Count(&n).Error
+ return n > 0, err
+}
+
+// openQuestion is the hand-off's newest open question card: in its
+// thread, or for a legacy hand-off on its turns in the person's own
+// conversation.
+func (t *txn) openQuestion(h handoffRecord) (cardRecord, bool, error) {
+ var c cardRecord
+ q := t.db.Where("person = ? AND kind = ? AND state = ? AND (held IS NULL OR held = ?)", h.Person, wire.CardQuestion, wire.CardOpen, false)
+ if h.Lane != "" {
+ q = q.Where("lane = ?", h.Lane)
+ } else {
+ q = q.Where("turn_id IN (SELECT turn_id FROM chat_handoff_turns WHERE handoff_id = ?) AND "+personLane, h.ID)
+ }
+ err := q.Order("created_at DESC, rowid DESC").Limit(1).Find(&c).Error
+ return c, err == nil && c.ID != "", err
+}
+
+// questionOptions are a question card's options as stored, never nil.
+func questionOptions(c cardRecord) ([]string, error) {
+ out := []string{}
+ if c.Options == "" {
+ return out, nil
+ }
+ if err := json.Unmarshal([]byte(c.Options), &out); err != nil {
+ return nil, err
+ }
+ if out == nil {
+ out = []string{}
+ }
+ return out, nil
+}
+
+// quoted is each option quoted, joined with ", ".
+func quoted(options []string) string {
+ q := make([]string, len(options))
+ for i, o := range options {
+ q[i] = strconv.Quote(o)
+ }
+ return strings.Join(q, ", ")
+}
+
+// jobTitle is the job's title and the person's words it was handed over
+// with: a hand-off made before titles is named for its words
+// (fallbackTitle).
+func (t *txn) jobTitle(h handoffRecord) (title, words string, err error) {
+ var texts []string
+ if h.MessageID != "" {
+ if err := t.db.Model(&messageRecord{}).Where("id = ?", h.MessageID).Pluck("text", &texts).Error; err != nil {
+ return "", "", err
+ }
+ }
+ if len(texts) == 1 {
+ words = texts[0]
+ }
+ if title = h.Title; title == "" {
+ title = fallbackTitle(words)
+ }
+ return title, words, nil
+}
+
+// jobNote is what a team_update turn tells the Assistant of the job, a
+// line each: which job, the person's words, then what happened, the
+// first that holds: a question for it (answer it, or ask the person
+// once); a go-ahead or Publish in front of the person; done; stopped
+// with no work, or on a step that can be tried again (push it through
+// while nudges are left; else tell the person); only the person can
+// move it on (in plain words, never to be nudged). Then where it stands
+// (handoffSummary). "" when there is nothing to tell.
+func (t *txn) jobNote(h handoffRecord) (string, error) {
+ title, words, err := t.jobTitle(h)
+ if err != nil {
+ return "", err
+ }
+ lines := []string{fmt.Sprintf(noteJob, title, h.ID), fmt.Sprintf(noteAsked, words)}
+ settled, err := t.handoffSettled(h)
+ if err != nil {
+ return "", err
+ }
+ reason, cause, ended, err := t.jobStop(h, settled)
+ if err != nil {
+ return "", err
+ }
+ q, asking, err := t.openQuestion(h)
+ if err != nil {
+ return "", err
+ }
+ // A Publish asked again because going live failed is not ready: the
+ // person tries again.
+ ready := false
+ if !asking && cause != causeGoingLive {
+ if ready, err = t.readyToTry(h); err != nil {
+ return "", err
+ }
+ }
+ left := maxNudges - int(h.Nudges)
+ switch {
+ case asking:
+ options, err := questionOptions(q)
+ if err != nil {
+ return "", err
+ }
+ lines = append(lines, fmt.Sprintf(noteQuestion, q.Question))
+ if len(options) > 0 {
+ lines = append(lines, fmt.Sprintf(noteOptions, quoted(options)))
+ }
+ lines = append(lines, fmt.Sprintf(noteAnswerIt, h.ID))
+ case ready:
+ lines = append(lines, noteReady)
+ case ended:
+ lines = append(lines, noteDone)
+ case (reason == stopNoWork || reason == stopFailed) && left <= 0:
+ lines = append(lines, noteNoNudges)
+ case reason == stopNoWork:
+ lines = append(lines, fmt.Sprintf(noteNoWork, h.ID, left))
+ case reason == stopFailed:
+ lines = append(lines, fmt.Sprintf(noteFailed, h.ID, left))
+ case reason == stopBlocked:
+ line := blockedLine(cause)
+ if line == "" {
+ line = blockedLine(wire.CardDirection)
+ }
+ lines = append(lines, fmt.Sprintf(noteBlocked, line))
+ default:
+ return "", nil
+ }
+ summary, err := t.handoffSummary(h)
+ if err != nil {
+ return "", err
+ }
+ return strings.Join(append(lines, fmt.Sprintf(noteStands, summary)), "\n"), nil
+}
+
+// openQuestionsNote is the reference block a turn the person started in
+// the Assistant lane carries after their words (D8): each open question
+// of their open or stopping jobs, newest job first, with its options;
+// "" with none.
+func (t *txn) openQuestionsNote(person string) (string, error) {
+ var rows []handoffRecord
+ if err := t.db.Where("person = ? AND state IN ?", person, []string{handoffOpen, handoffStopping}).Order("created_at DESC, id DESC").Find(&rows).Error; err != nil {
+ return "", err
+ }
+ var lines []string
+ for _, h := range rows {
+ q, ok, err := t.openQuestion(h)
+ if err != nil {
+ return "", err
+ }
+ if !ok {
+ continue
+ }
+ title, _, err := t.jobTitle(h)
+ if err != nil {
+ return "", err
+ }
+ options, err := questionOptions(q)
+ if err != nil {
+ return "", err
+ }
+ // No brackets inside: the block's marker stays one.
+ line := fmt.Sprintf(noteOpenQuestion, referenceText(title), h.ID, referenceText(q.Question))
+ if len(options) > 0 {
+ line += " " + fmt.Sprintf(noteOptions, quoted(options))
+ }
+ if lines = append(lines, line); len(lines) == maxStatus {
+ break
+ }
+ }
+ if len(lines) == 0 {
+ return "", nil
+ }
+ return fmt.Sprintf(noteOpenQuestions, strings.Join(lines, "\n")), nil
+}
+
// copy is the instance's words for key ("" with no copy).
func (t *txn) copy(key string) string {
if t.s.authority.Copy == nil {
@@ -735,14 +1070,25 @@ func (t *txn) copy(key string) string {
return t.s.authority.Copy(key)
}
+// teamSummary is one request in team_status: its job's title, where it
+// stands, and the question open for it, if any.
type teamSummary struct {
- Request string `json:"request"`
- Summary string `json:"summary"`
+ Request string `json:"request"`
+ Summary string `json:"summary"`
+ Title string `json:"title"`
+ Question *teamQuestion `json:"question,omitempty"`
+}
+
+// teamQuestion is a job's open question and its options (never null).
+type teamQuestion struct {
+ Text string `json:"text"`
+ Options []string `json:"options"`
}
// teamStatus summarises one of the person's requests, their open ones,
// and with all the work they started in Equipo that is still open (its
-// request is empty).
+// request is empty). A request names its job's title and the question
+// open for it.
func (s *Store) teamStatus(ctx context.Context, person string, input json.RawMessage) (json.RawMessage, error) {
var in struct {
Request string `json:"request"`
@@ -772,7 +1118,23 @@ func (s *Store) teamStatus(ctx context.Context, person string, input json.RawMes
if err != nil {
return err
}
- out = append(out, teamSummary{Request: h.ID, Summary: text})
+ title, _, err := t.jobTitle(h)
+ if err != nil {
+ return err
+ }
+ one := teamSummary{Request: h.ID, Summary: text, Title: title}
+ q, asking, err := t.openQuestion(h)
+ if err != nil {
+ return err
+ }
+ if asking {
+ options, err := questionOptions(q)
+ if err != nil {
+ return err
+ }
+ one.Question = &teamQuestion{Text: q.Question, Options: options}
+ }
+ out = append(out, one)
}
if !in.All || in.Request != "" {
return nil
diff --git a/internal/equipo/chat/handoff_test.go b/internal/equipo/chat/handoff_test.go
index 0187e998..5114835b 100644
--- a/internal/equipo/chat/handoff_test.go
+++ b/internal/equipo/chat/handoff_test.go
@@ -94,3 +94,25 @@ func TestFallbackTitle(t *testing.T) {
t.Fatalf("not cut at a space: %q", got)
}
}
+
+// TestJobNoteBlockedLines: every cause that stops a job for its person
+// has a plain line for the Assistant (noteBlocked): each team card that
+// waits on them, each need of a task's but the go-ahead and a retryable
+// step, and going live that failed. Unknown, it is no line.
+func TestJobNoteBlockedLines(t *testing.T) {
+ causes := []string{wire.CardAccess, wire.CardHome, wire.CardDirection, wire.CardSpecialist, wire.CardResearchSources, wire.CardResearchInventory, wire.CardMergeShips, wire.CardMergePolicy,
+ wire.NeedsHeld, wire.NeedsBranchMoved, wire.NeedsReviewBlocked, wire.NeedsFixRounds, wire.NeedsMergeConflict, wire.NeedsMachineRemoved, wire.NeedsRunnerOffline, wire.NeedsMacSandbox, wire.NeedsDirection, causeGoingLive}
+ for _, c := range causes {
+ if line := blockedLine(c); line == "" || strings.HasSuffix(line, ".") || strings.ContainsAny(line, "\n[]") {
+ t.Errorf("%s: %q", c, line)
+ }
+ }
+ if blockedLine(wire.NeedsRunnerOffline) != blockedLine(wire.NeedsMachineRemoved) || blockedLine(wire.CardMergeShips) != blockedLine(wire.CardMergePolicy) {
+ t.Error("causes that ask the same thing say it differently")
+ }
+ for _, c := range []string{"", wire.NeedsMerge, wire.NeedsRetry, "something_new"} {
+ if line := blockedLine(c); line != "" {
+ t.Errorf("%q: %q", c, line)
+ }
+ }
+}
diff --git a/internal/equipo/chat/outcome.go b/internal/equipo/chat/outcome.go
index 7abeda84..b35172ca 100644
--- a/internal/equipo/chat/outcome.go
+++ b/internal/equipo/chat/outcome.go
@@ -11,20 +11,23 @@ import (
"gorm.io/gorm"
)
-// Outcome cards (spec §5, Cards). When a hand-off's task or turn raises a
-// team card for the hand-off's person, the Assistant lane gets one card
-// that points at it, in the instance's words:
+// Outcome cards (spec §5, Cards; the jobs design's one voice). When a
+// hand-off's task or turn raises a go-ahead or a Publish for the
+// hand-off's person, the Assistant lane gets one card that points at it,
+// in the instance's words:
//
-// - a question from the Coordinator's ask_person: a question card, its
-// question and options unchanged;
// - a merge card: an outcome card asking for a go-ahead with Equipo's
// reason in plain words, one option per the merge card's and the
// preview while it is up;
// - a publish card: an outcome card asking to publish the site, with
// its preview, held up until the answer (previewHeld); once answered,
-// what became of it, and the site's address once it has one;
-// - any other card that stops the work (blocksWork): an outcome card
-// saying the team needs the person in Equipo, with one link there.
+// what became of it, and the site's address once it has one.
+//
+// Nothing else of the team's reaches the person: a question from the
+// Coordinator's ask_person, or any other card that stops the work
+// (blocksWork), is the Assistant's to hear of (teamAsks), as a note. A
+// question or needs-you card mirrored before that (slice 1) still
+// follows its team card, as below.
//
// The card follows its team card: every save of the team card copies its
// state and result and moves the card's revision. Answering it answers
@@ -48,21 +51,26 @@ func blocksWork(kind, state string) bool {
return false
}
-// mirrorKind is the Assistant card a new team card raises ("" for none).
+// mirrorKind is the Assistant card a new team card raises ("" for none):
+// only an open go-ahead or Publish, for new and legacy hand-offs alike.
func mirrorKind(src cardRecord) string {
- switch {
- case src.Kind == wire.CardQuestion && src.State == wire.CardOpen:
- return wire.CardQuestion
- case (src.Kind == wire.CardMerge || src.Kind == wire.CardPublish) && src.State == wire.CardOpen, blocksWork(src.Kind, src.State):
+ if (src.Kind == wire.CardMerge || src.Kind == wire.CardPublish) && src.State == wire.CardOpen {
return wire.CardOutcome
}
return ""
}
+// asksPerson: an open team question, or a card that stops the work: the
+// Assistant hears of it (teamAsks), and no card is raised for it.
+func asksPerson(src cardRecord) bool {
+ return src.Kind == wire.CardQuestion && src.State == wire.CardOpen || blocksWork(src.Kind, src.State)
+}
+
// mirrorCard keeps the Assistant's card for a Coordinator card (cardEvent):
// raised once, for a card on the turn or task of one of its person's
-// hand-offs, and the person told (handoffChanged); afterwards brought up
-// to date on each of the team card's saves.
+// hand-offs, and the Assistant told (handoffChanged); afterwards brought
+// up to date on each of the team card's saves. A card that asks the
+// person something raises none: the Assistant is told (teamAsks).
func (t *txn) mirrorCard(src cardRecord) error {
if !wire.CoordinatorRole(src.Lane) {
return nil
@@ -86,6 +94,9 @@ func (t *txn) mirrorCard(src cardRecord) error {
}
kind := mirrorKind(src)
if kind == "" {
+ if asksPerson(src) {
+ return t.teamAsks(src)
+ }
return nil
}
h, ok, err := t.handoffFor(src)
@@ -106,6 +117,16 @@ func (t *txn) mirrorCard(src cardRecord) error {
return t.handoffChanged(h, true)
}
+// teamAsks tells the Assistant of a hand-off's question, or of a card
+// that stops its work (one voice): the job's note, and no card.
+func (t *txn) teamAsks(src cardRecord) error {
+ h, ok, err := t.handoffFor(src)
+ if err != nil || !ok {
+ return err
+ }
+ return t.handoffChanged(h, true)
+}
+
// handoffFor is the hand-off a team card belongs to, only ever one of the
// card's person's, open or stopping: a cancelled request raises nothing.
// A card in a job thread is that job's alone, by its lane (J4): its
diff --git a/internal/equipo/chat/store.go b/internal/equipo/chat/store.go
index 5d0ed230..126c3d30 100644
--- a/internal/equipo/chat/store.go
+++ b/internal/equipo/chat/store.go
@@ -337,6 +337,17 @@ func (t *txn) dispatch(r *turnRecord) error {
// The instance's news, never the person's words (handoff.go).
text = r.Note
}
+ if r.Lane == wire.LaneAssistant && r.Kind == wire.TurnPerson {
+ // The questions open on the person's jobs ride after their words,
+ // as reference (D8); PersonText and the stored messages stay theirs.
+ block, err := t.openQuestionsNote(r.Person)
+ if err != nil {
+ return err
+ }
+ if block != "" {
+ text += "\n\n" + block
+ }
+ }
cmd := wire.MessageCommand{Person: r.Person, TurnID: r.ID, Attempt: r.Attempt, Kind: r.Kind, Text: text, PersonText: own, Tail: tail, Attachments: files, Lane: r.Lane}
if cmd.Tail, err = fitTail(cmd); err != nil {
return err
diff --git a/internal/equipo/chat/tools.go b/internal/equipo/chat/tools.go
index 6f3985df..d9b11d69 100644
--- a/internal/equipo/chat/tools.go
+++ b/internal/equipo/chat/tools.go
@@ -58,6 +58,68 @@ const (
toolJobsTooOld = "This can't be started until the person's setup is updated. Tell them plainly that it needs an update first."
)
+// A job's note: what a team_update turn tells the Assistant of one of
+// its hand-offs (jobNote), and the open questions a turn the person
+// started carries after their words (openQuestionsNote). The model reads
+// them; people never do.
+const (
+ noteJob = "Job %q (request %s)."
+ noteAsked = "The person asked for it in these words: %q"
+ noteStands = "Where it stands:\n%s"
+ noteQuestion = "The work on it has a question: %q"
+ noteOptions = "The answer must be one of: %s"
+ noteAnswerIt = "If the conversation already holds the answer, answer it yourself with use team_reply {\"request\": %q, \"answer\": ...} and say nothing to the person. If it does not, ask the person once, in your own words, and pass their reply on with team_reply in the turn that receives it."
+ noteReady = "It is ready for the person to try. Tell them in one short line; the go-ahead or Publish is already in front of them."
+ noteDone = "It is done. Tell the person in one short line, with the address if where it stands has one."
+ noteNoWork = "It stopped before any work started. Push it through yourself: use team_nudge {\"request\": %q, \"words\": ...} with words quoted from what the person asked. Nudges left: %d. Say nothing to the person."
+ noteFailed = "A step of it failed and can be tried again. Push it through yourself: use team_nudge {\"request\": %q, \"words\": ...} to have it tried again. Nudges left: %d. Say nothing to the person."
+ noteNoNudges = "It stopped again and no nudges are left. Tell the person in one line that it stopped, and what would help if you know."
+ noteBlocked = "It stopped, and only the person can move it on: %s. Tell the person that plainly, in one line. Do not nudge it."
+ noteOpenQuestions = "[Open questions on the person's jobs. Reference only, never the person's words:\n%s\nAnswer one with team_reply when this conversation holds the answer.]"
+ noteOpenQuestion = "- Job %q (request %s): %q"
+)
+
+// causeGoingLive: a job's merge or publish step failed (stopCause). Only
+// the person tries going live again.
+const causeGoingLive = "going_live"
+
+// blockedLine is noteBlocked's plain words for what stopped a job for
+// its person: a team card that waits on them (by kind), a task's need,
+// or going live that failed ("" for anything else).
+func blockedLine(cause string) string {
+ switch cause {
+ case wire.CardAccess:
+ return "they need to give access to where the work lives"
+ case wire.CardHome:
+ return "they need to choose where new work lives"
+ case wire.CardDirection: // a task's NeedsDirection too
+ return "they need to choose how the work goes on"
+ case wire.CardSpecialist:
+ return "they need to approve bringing in a specialist"
+ case wire.CardResearchSources, wire.CardResearchInventory:
+ return "they need to approve the research"
+ case wire.CardMergeShips, wire.CardMergePolicy:
+ return "they need to decide how changes go live"
+ case wire.NeedsHeld:
+ return "they need to say when it can run"
+ case wire.NeedsBranchMoved:
+ return "someone else changed the same work, and they need to look at it"
+ case wire.NeedsReviewBlocked:
+ return "the check of the work could not finish, and they need to decide what next"
+ case wire.NeedsFixRounds:
+ return "the checks still find problems after the automatic fixes, and they need to decide what next"
+ case wire.NeedsMergeConflict:
+ return "it clashes with other changes, and they need to sort it out"
+ case wire.NeedsRunnerOffline, wire.NeedsMachineRemoved:
+ return "they need to bring their computer back online"
+ case wire.NeedsMacSandbox:
+ return "they need to let it be tested on their Mac"
+ case causeGoingLive:
+ return "going live failed, and they need to try it again"
+ }
+ return ""
+}
+
// opTexts are the refusals the instance itself decides, by code.
var opTexts = map[string]string{
"not_yet": "Not run: this operation deletes something or reaches people outside, and you cannot run that from here yet. Tell the person you cannot do it for them yet.",
diff --git a/internal/thintest/assistant_outcome_contract_test.go b/internal/thintest/assistant_outcome_contract_test.go
index 8d6ca6c6..c1cb553a 100644
--- a/internal/thintest/assistant_outcome_contract_test.go
+++ b/internal/thintest/assistant_outcome_contract_test.go
@@ -194,12 +194,33 @@ func mergeQuestion(reason string) string {
return fmt.Sprintf(equipo.RunnerCopy("assistant.outcome.merge"), equipo.RunnerCopy("assistant.outcome.reason."+reason))
}
-// TestContractOutcomeQuestion: the Coordinator's ask_person in a
-// hand-off's turn raises a question card in the Assistant lane, the
-// question and options unchanged, and tells the person. Answering it
-// there answers the team card with that choice; the choice is the
-// person's next message in the hand-off's thread.
-func TestContractOutcomeQuestion(t *testing.T) {
+// jobLine is the note's first line for a job (noteJob), and its second,
+// the person's words (noteAsked).
+func jobLine(title, request, words string) string {
+ return fmt.Sprintf("Job %q (request %s).\nThe person asked for it in these words: %q\n", title, request, words)
+}
+
+// noteFor waits for the newest team_update note that contains want.
+func (o *teamRig) noteFor(what, want string) string {
+ o.t.Helper()
+ var note string
+ o.until(what, func() bool {
+ _, notes, _ := o.updates()
+ if len(notes) > 0 {
+ note = notes[len(notes)-1]
+ }
+ return strings.Contains(note, want)
+ })
+ return note
+}
+
+// TestContractOutcomeQuestionNotMirrored: the Coordinator's ask_person
+// in a job's thread raises no card in the Assistant lane: the Assistant
+// hears of it in one team_update turn, whose note names the job and its
+// request, quotes the person's words, the question and its options, and
+// says how to answer it (team_reply). The note is the instance's: the
+// frame carries no words of the person's.
+func TestContractOutcomeQuestionNotMirrored(t *testing.T) {
o := newTeamRig(t)
o.ask("Can we fix a bug in Tito? Login is broken")
request, cmd := o.handoff("oq1", "Login is broken", "")
@@ -208,42 +229,93 @@ func TestContractOutcomeQuestion(t *testing.T) {
t.Fatalf("ask %+v", res)
}
})
- card := o.assistantCard("the question card", func(c wire.AssistantCard) bool { return c.Kind == wire.CardQuestion })
- if card.State != wire.CardOpen || card.Question != "Which login page?" || !slices.Equal(card.Options, []wire.CardOption{{Value: "Web", Label: "Web"}, {Value: "App", Label: "App"}}) || card.Links == nil || len(card.Links) != 0 || card.Result != "" {
- t.Fatalf("card %+v", card)
- }
- if ids, _, _ := o.updates(); len(ids) != 1 {
- t.Fatalf("the person is not told: %v", ids)
- }
+ o.until("the update", func() bool { ids, _, _ := o.updates(); return len(ids) == 1 })
team := o.threadCard(wire.CardQuestion, cmd.TurnID)
- if team.ID == "" || o.teamCard(wire.CardQuestion, cmd.TurnID, "").ID != "" {
- t.Fatalf("the thread's question %+v shows in their conversation", team)
+ if team.ID == "" || team.State != wire.CardOpen || o.teamCard(wire.CardQuestion, cmd.TurnID, "").ID != "" {
+ t.Fatalf("the thread's question %+v", team)
+ }
+ if cards := o.assistantCards(); len(cards) != 0 {
+ t.Fatalf("assistant cards %+v", cards)
}
o.reply(cmd.TurnID)
- ans, err := o.a.Answer(o.ctx, card.ID, "App", card.Revision)
- if err != nil || ans.Card.ID != card.ID || ans.Card.State != wire.CardAnswered || ans.Card.Result != "App" || ans.Card.Revision <= card.Revision {
- t.Fatalf("answer %+v %v", ans, err)
+ o.reply(o.turn)
+ u := o.message(wire.LaneAssistant)
+ if u.Kind != wire.TurnTeamUpdate || len(u.PersonText) != 0 {
+ t.Fatalf("update frame %+v", u)
+ }
+ for _, want := range []string{jobLine("Login is broken", request, "Login is broken"), `The work on it has a question: "Which login page?"`, `The answer must be one of: "Web", "App"`, "team_reply"} {
+ if !strings.Contains(u.Text, want) {
+ t.Fatalf("the note lacks %q: %s", want, u.Text)
+ }
}
- if after := o.threadCard(wire.CardQuestion, cmd.TurnID); after.ID != team.ID || after.State != wire.CardAnswered || after.Choice != "App" {
- t.Fatalf("team card %+v", after)
+ if ids, _, _ := o.updates(); len(ids) != 1 {
+ t.Fatalf("updates %v", ids)
}
- next := o.message(wire.JobLane(request))
- if !slices.Equal(next.PersonText, []string{"App"}) || next.TurnID == cmd.TurnID {
- t.Fatalf("answer frame %+v", next)
+ if cards := o.assistantCards(); len(cards) != 0 {
+ t.Fatalf("assistant cards after the turns %+v", cards)
}
- if texts := o.handedTexts(); texts[len(texts)-1] != "App" || len(o.coordinatorTexts()) != 0 {
- t.Fatalf("thread messages %v, their own %v", texts, o.coordinatorTexts())
+}
+
+// TestContractOutcomeLegacyQuestionTold: a legacy hand-off's question,
+// raised on its turn in the person's own conversation, raises no
+// Assistant card either: the Assistant is told in a team_update note.
+func TestContractOutcomeLegacyQuestionTold(t *testing.T) {
+ o := newTeamRig(t)
+ o.ask("Can we fix a bug in Tito? Login is broken")
+ request, turn := o.legacyHandoff("lq", "Login is broken")
+ o.in(turn, func() {
+ if res := o.call("lq-ask", wire.ToolAskPerson, map[string]any{"question": "Which login page?", "options": []string{"Web", "App"}}); res.Code != "asked" {
+ t.Fatalf("ask %+v", res)
+ }
+ })
+ note := o.noteFor("the legacy question's note", `The work on it has a question: "Which login page?"`)
+ if !strings.Contains(note, "(request "+request+")") || !strings.Contains(note, `"Web", "App"`) {
+ t.Fatalf("note %q", note)
}
- // Answered: a second answer is a conflict with the card as it is.
- if c := conflictOf(t, func() error { _, err := o.a.Answer(o.ctx, card.ID, "Web", ans.Card.Revision); return err }()); c.Code != "card_answered" || c.Card.State != wire.CardAnswered {
- t.Fatalf("second answer %+v", c)
+ if o.teamCard(wire.CardQuestion, turn, "").ID == "" {
+ t.Fatal("the legacy question left their conversation")
}
- // One Assistant card per team card, however often it changes.
- if cards := o.assistantCards(); len(cards) != 1 {
+ if cards := o.assistantCards(); len(cards) != 0 {
t.Fatalf("assistant cards %+v", cards)
}
}
+// TestContractOutcomeLegacyMirrorStillFollows: an Assistant question
+// card mirrored before this release (as slice 1 raised it, pointing at
+// its team card) still follows that card: answered in Equipo, it is
+// answered with the same choice.
+func TestContractOutcomeLegacyMirrorStillFollows(t *testing.T) {
+ o := newTeamRig(t)
+ o.ask("Can we fix a bug in Tito? Login is broken")
+ _, turn := o.legacyHandoff("lm", "Login is broken")
+ o.in(turn, func() {
+ if res := o.call("lm-ask", wire.ToolAskPerson, map[string]any{"question": "Which login page?", "options": []string{"Web", "App"}}); res.Code != "asked" {
+ t.Fatalf("ask %+v", res)
+ }
+ })
+ o.reply(turn)
+ var team wire.Card
+ o.wait("the question in their conversation", func(c *Conversation) bool {
+ for _, k := range c.Cards {
+ if k.Kind == wire.CardQuestion && k.TurnID == turn {
+ team = k
+ }
+ }
+ return team.ID != ""
+ })
+ options := `[{"value":"Web","label":"Web"},{"value":"App","label":"App"}]`
+ if _, err := o.inst.DB.Writer().Exec("INSERT INTO chat_cards(id, person, kind, state, question, options, links, source_card, revision, created_at, updated_at, lane) VALUES ('c_slice1', ?, ?, ?, 'Which login page?', ?, '[]', ?, 1, ?, ?, ?)", Owner, wire.CardQuestion, wire.CardOpen, options, team.ID, time.Now().UTC(), time.Now().UTC(), wire.LaneAssistant); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := o.client.Answer(o.ctx, team.ID, "App", team.Revision); err != nil {
+ t.Fatal(err)
+ }
+ got := o.assistantCard("the old mirror answered", func(c wire.AssistantCard) bool { return c.ID == "c_slice1" && c.State == wire.CardAnswered })
+ if got.Result != "App" || got.Revision <= 1 {
+ t.Fatalf("the old mirror %+v", got)
+ }
+}
+
// TestContractOutcomeMerge: a merge card on a hand-off's task raises an
// outcome card, in plain words with the preview once it is up; Merge on
// it at its revision merges as the card's Merge does: the person's
@@ -307,9 +379,9 @@ func TestContractOutcomeMerge(t *testing.T) {
if done := o.assistantCard("done", func(c wire.AssistantCard) bool { return c.ID == card.ID }); len(done.Links) != 0 || done.Revision <= answered.Revision || done.State != wire.CardAnswered {
t.Fatalf("after the merge %+v (answered %+v)", done, answered)
}
- // Raised once per team card (the merge card and the ships question),
- // however often each changed.
- if cards := o.assistantCards(); len(cards) != 2 {
+ // Raised once for the merge card, however often it changed; the
+ // ships question raises none (the Assistant is told).
+ if cards := o.assistantCards(); len(cards) != 1 {
t.Fatalf("assistant cards %+v", cards)
}
}
@@ -343,8 +415,8 @@ func TestContractOutcomePreviewExpires(t *testing.T) {
// TestContractOutcomeShips: the ships question belongs to a project, not
// a task, and is raised in the lane of the work that asked it: for a
-// job's work, in its thread, where it reaches the job's Assistant as a
-// card that sends the person to Equipo.
+// job's work, in its thread. It raises no Assistant card; the go-ahead
+// raised beside it is what the Assistant is told of.
func TestContractOutcomeShips(t *testing.T) {
o := newTeamRig(t)
o.ask("Can we fix a bug in Tito? Login is broken")
@@ -358,11 +430,11 @@ func TestContractOutcomeShips(t *testing.T) {
if task != "" || turn != "" || lane != wire.JobLane(request) || o.teamCard(wire.CardMergeShips, "", "").ID != "" {
t.Fatalf("ships card %s for %q in %q, %q", ships, task, turn, lane)
}
- card := o.assistantCard("the ships card", func(c wire.AssistantCard) bool { return c.Kind == wire.CardOutcome && !isMergeOutcome(c) })
- if card.State != wire.CardOpen || len(card.Options) != 0 || !slices.Equal(card.Links, []wire.CardLink{{Label: equipo.RunnerCopy("assistant.outcome.open"), URL: o.inst.URL + "/"}}) {
- t.Fatalf("card %+v", card)
+ // The go-ahead in front of the person is what the Assistant hears of.
+ if note := o.noteFor("the job's note", "It is ready for the person to try."); strings.Contains(note, "only the person can move it on") {
+ t.Fatalf("note %q", note)
}
- if cards := o.assistantCards(); len(cards) != 2 {
+ if cards := o.assistantCards(); len(cards) != 1 || !isMergeOutcome(cards[0]) {
t.Fatalf("assistant cards %+v", cards)
}
}
@@ -550,11 +622,12 @@ func TestContractNoMergeQuestionWhenGateMerges(t *testing.T) {
}
}
-// TestContractOutcomeBlocked: a card that stops the work on something
-// only Equipo can show raises "This needs you to finish it." with one
-// link to Equipo and nothing to choose; a task card and a merge receipt
-// raise nothing.
-func TestContractOutcomeBlocked(t *testing.T) {
+// TestContractOutcomeBlockedNotMirrored: a card in a job's thread that
+// stops the work on something only the person can give (access) raises
+// no Assistant card: the Assistant is told, in plain words, that only
+// the person can move the job on, and not to nudge it. A task card and a
+// merge receipt need nothing of the person and queue nothing.
+func TestContractOutcomeBlockedNotMirrored(t *testing.T) {
o := newTeamRig(t)
o.shipsNo(o.project())
mine := o.own("Something of my own.")
@@ -562,27 +635,23 @@ func TestContractOutcomeBlocked(t *testing.T) {
o.in(mine, func() { joined = o.record("ob-own", "Dark mode for settings") })
o.reply(mine)
o.ask("Can we fix a bug in Tito? Login is broken")
- _, cmd := o.handoff("ob1", "Login is broken", "")
+ request, cmd := o.handoff("ob1", "Login is broken", "")
o.in(cmd.TurnID, func() {
if res := o.call("ob-find", wire.ToolFind, map[string]string{"query": "Moonbeam app"}); res.Code != "none" {
t.Fatalf("find %+v", res)
}
})
- card := o.assistantCard("the blocked card", func(c wire.AssistantCard) bool { return c.Kind == wire.CardOutcome })
- if card.State != wire.CardOpen || card.Question != equipo.RunnerCopy("assistant.outcome.needs_you") || card.Options == nil || len(card.Options) != 0 || !slices.Equal(card.Links, []wire.CardLink{{Label: equipo.RunnerCopy("assistant.outcome.open"), URL: o.inst.URL + "/"}}) {
- t.Fatalf("card %+v", card)
- }
- if strings.Contains(card.Question, "Moonbeam") {
- t.Fatalf("the card quotes the team card: %q", card.Question)
+ note := o.noteFor("the access card's note", "It stopped, and only the person can move it on: they need to give access to where the work lives. Tell the person that plainly, in one line. Do not nudge it.")
+ if !strings.HasPrefix(note, jobLine("Login is broken", request, "Login is broken")) || strings.Contains(note, "Moonbeam") || strings.Contains(note, "team_nudge") {
+ t.Fatalf("note %q", note)
}
- // CF1: a card with nothing to choose still says so, as a list.
- status, _, body := raw(t, "GET", o.inst.URL+"/api/v1/assistant/snapshot", o.client.Token, nil, "")
- if status != 200 || !strings.Contains(string(body), `"options":[]`) {
- t.Fatalf("snapshot %d %s", status, body)
+ if o.threadCard(wire.CardAccess, cmd.TurnID).ID == "" {
+ t.Fatal("no access card in the thread")
}
- if _, err := o.a.Answer(o.ctx, card.ID, wire.ChoiceCheck, card.Revision); Status(err) != 422 {
- t.Fatalf("an answer to a card with nothing to choose: %v", err)
+ if cards := o.assistantCards(); len(cards) != 0 {
+ t.Fatalf("assistant cards %+v", cards)
}
+ told, notes, _ := o.updates()
// A task card (add_report) and a merge receipt (Equipo merged on its
// own) need nothing of the person.
base, cand, merge := strings.Repeat("1", 40), strings.Repeat("2", 40), strings.Repeat("e", 40)
@@ -606,22 +675,25 @@ func TestContractOutcomeBlocked(t *testing.T) {
o.step("ob-m-run", wire.StepReport{TaskID: id, StepID: m.StepID, Attempt: 1, State: wire.StepRunning, BaseSHA: base, CandidateSHA: cand})
o.step("ob-m", wire.StepReport{TaskID: id, StepID: m.StepID, Attempt: 1, State: wire.StepDone, BaseSHA: base, CandidateSHA: cand, Termination: true, Findings: []wire.Finding{}, MergeSHA: merge, Into: "main", Strategy: wire.MergeCommit, MergeSource: wire.MergeSourceHub, MergeParents: []string{strings.Repeat("9", 40), cand}})
o.until("the receipt", func() bool { return len(o.coordinatorCards(wire.CardMergeReceipt, id)) == 1 })
- if cards := o.assistantCards(); len(cards) != 1 || cards[0].ID != card.ID {
+ if cards := o.assistantCards(); len(cards) != 0 {
t.Fatalf("assistant cards %+v", cards)
}
+ if ids, after, _ := o.updates(); !slices.Equal(ids, told) || !slices.Equal(after, notes) {
+ t.Fatalf("updates after the task card and the receipt %v %q, before %v %q", ids, after, told, notes)
+ }
}
// TestContractAssistantLaneLeaksNoMachinery: a hand-off through a
-// question, a merge card and its answer, then the publish card and its
-// answer to a published site, leaves nothing of the team's machinery in
-// the Assistant lane: no task id, repository, branch, SHA, link into
-// Equipo's tasks or team keys, in the snapshot, any event or an answer;
-// every card has exactly its eight keys.
+// question (answered in its thread), a merge card and its answer, then
+// the publish card and its answer to a published site, leaves nothing of
+// the team's machinery in the Assistant lane: no task id, repository,
+// branch, SHA, link into Equipo's tasks or team keys, in the snapshot,
+// any event or an answer; every card has exactly its eight keys.
func TestContractAssistantLaneLeaksNoMachinery(t *testing.T) {
o := newTeamRig(t)
o.sitesOn(wire.ProtocolAssistant, true)
o.ask("Can we fix a bug in Tito? Login is broken")
- _, cmd := o.handoff("ol1", "Login is broken", "")
+ request, cmd := o.handoff("ol1", "Login is broken", "")
base, cand, merged := strings.Repeat("1", 40), strings.Repeat("2", 40), strings.Repeat("e", 40)
var id string
o.in(cmd.TurnID, func() {
@@ -634,7 +706,6 @@ func TestContractAssistantLaneLeaksNoMachinery(t *testing.T) {
o.built("ol-pv-built", pv, digestA)
link := "https://eq-" + id + ".docs-t1.example.ts.net/"
o.previewDone("ol-pv-done", pv, wire.PreviewResult{Phase: wire.PreviewDone, App: "eq-" + id, URL: link, Digest: digestA, Outcome: wire.PreviewDeployed})
- question := o.assistantCard("the question", func(c wire.AssistantCard) bool { return c.Kind == wire.CardQuestion })
outcome := o.assistantCard("the merge outcome", func(c wire.AssistantCard) bool {
return isMergeOutcome(c) && slices.ContainsFunc(c.Links, func(l wire.CardLink) bool { return l.URL == link })
})
@@ -647,7 +718,13 @@ func TestContractAssistantLaneLeaksNoMachinery(t *testing.T) {
}
answers = append(answers, out)
}
- answer(question, "Web")
+ // 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)
+ }
+ }
answer(outcome, wire.ChoiceMerge)
m := o.dispatched(wire.SpecialistMerge, base, cand, 0)
o.mergedStep("ol-m", m, merged)
@@ -750,8 +827,8 @@ func TestContractAssistantLaneLeaksNoMachinery(t *testing.T) {
sv := decode("snapshot", snap)
check("the snapshot", sv, false)
cards := sv.(map[string]any)["cards"].([]any)
- // The question, the go-ahead, the ships question and the publish card.
- if len(cards) != 4 {
+ // The go-ahead and the publish card.
+ if len(cards) != 2 {
t.Fatalf("snapshot cards %s", snap)
}
for _, c := range cards {
@@ -890,6 +967,7 @@ func TestContractOutcomePublish(t *testing.T) {
if err != nil || k.Site == nil || team.State != wire.CardOpen {
t.Fatalf("publish card %+v, site %+v %v", team, k.Site, err)
}
+ told, notes, _ := o.updates()
ans, err := o.a.Answer(o.ctx, card.ID, wire.ChoicePublish, card.Revision)
if err != nil || ans.Card.State != wire.CardAnswered || ans.Card.Result != equipo.RunnerCopy("assistant.outcome.publish_publishing") {
t.Fatalf("answer %+v %v", ans, err)
@@ -908,6 +986,11 @@ func TestContractOutcomePublish(t *testing.T) {
t.Fatalf("start refused %q", refused)
}
o.publishReport("op-built", d, wire.StepRunning, &wire.PublishResult{Phase: wire.PublishBuilt, Digest: digestA, Files: 2, Bytes: 40})
+ // Publishing moves on its own: the Assistant hears nothing until it
+ // is live.
+ if ids, after, _ := o.updates(); !slices.Equal(ids, told) || !slices.Equal(after, notes) {
+ t.Fatalf("updates while publishing %v %q, before %v %q", ids, after, told, notes)
+ }
if refused := o.lease(o.runner, "op-deploy", wire.LeaseCheck{StepID: d.StepID, Attempt: d.Attempt, Purpose: wire.LeasePurposePublish, Digest: digestA}); refused != "" {
t.Fatalf("deploy refused %q", refused)
}
@@ -919,9 +1002,11 @@ func TestContractOutcomePublish(t *testing.T) {
if done.State != wire.CardAnswered || !slices.Equal(done.Links, []wire.CardLink{{Label: equipo.RunnerCopy("assistant.outcome.publish_site"), URL: site}}) {
t.Fatalf("published card %+v", done)
}
+ // Done, though the project's ships question is still open: that is
+ // not the job's stop.
o.until("a team_update with the address", func() bool {
_, notes, _ := o.updates()
- return len(notes) > 0 && strings.Contains(notes[len(notes)-1], site)
+ return len(notes) > 0 && strings.Contains(notes[len(notes)-1], site) && strings.Contains(notes[len(notes)-1], "\nIt is done. Tell the person in one short line")
})
// Not now: answered, and nothing published.
diff --git a/internal/thintest/assistant_team_contract_test.go b/internal/thintest/assistant_team_contract_test.go
index 88ddd924..c6a191e5 100644
--- a/internal/thintest/assistant_team_contract_test.go
+++ b/internal/thintest/assistant_team_contract_test.go
@@ -2,6 +2,7 @@ package thintest
import (
"encoding/json"
+ "fmt"
"html"
"net/http"
"regexp"
@@ -277,22 +278,6 @@ func (o *teamRig) updates() (ids, notes []string, dispatched []bool) {
return ids, notes, dispatched
}
-// coordinatorTexts are the Coordinator conversation's person messages.
-func (o *teamRig) coordinatorTexts() []string {
- o.t.Helper()
- page, err := o.client.Messages(o.ctx, "", 50)
- if err != nil {
- o.t.Fatal(err)
- }
- var out []string
- for _, m := range page.Items {
- if m.Role == wire.RolePerson {
- out = append(out, m.Text)
- }
- }
- return out
-}
-
// TestContractTeamRequest: team_request posts the person's words into
// a Coordinator thread of the request's own (lane job:<request>) as
// their message, with the Assistant's context beside it as marked
@@ -690,9 +675,10 @@ func TestContractTeamCancel(t *testing.T) {
}
// TestContractTeamUpdate: when the hand-off's work stops, is cancelled
-// or is done, one team_update turn is queued with the summary as its
-// text; a change while it waits rewrites it; a change that leaves the
-// summary as it was queues nothing. That turn only looks and tells.
+// or is done, one team_update turn is queued with the job's note as its
+// text (where it stands is the summary); a change while it waits
+// rewrites it; a change that leaves the note as it was queues nothing.
+// That turn only looks and tells.
func TestContractTeamUpdate(t *testing.T) {
o := newTeamRig(t)
o.ask("Can we fix a bug in Tito? Login is broken")
@@ -714,7 +700,7 @@ func TestContractTeamUpdate(t *testing.T) {
o.reply(cmd.TurnID)
// The Assistant's turn still runs: the update waits behind it.
ids, notes, dispatched := o.updates()
- if len(ids) != 1 || dispatched[0] || !strings.Contains(notes[0], equipo.RunnerCopy("assistant.team.stopped")) {
+ if len(ids) != 1 || dispatched[0] || !strings.Contains(notes[0], equipo.RunnerCopy("assistant.team.stopped")) || !strings.Contains(notes[0], "A step of it failed and can be tried again.") {
t.Fatalf("after the failure %v %q %v", ids, notes, dispatched)
}
if _, err := o.client.CancelTask(o.ctx, id); err != nil {
@@ -722,12 +708,12 @@ func TestContractTeamUpdate(t *testing.T) {
}
summary := o.status("u-status", map[string]any{"request": request})[0].Summary
again, notes, dispatched := o.updates()
- if !slices.Equal(again, ids) || dispatched[0] || notes[0] != summary || !strings.Contains(summary, equipo.RunnerCopy("assistant.team.stage.cancelled")) {
+ if !slices.Equal(again, ids) || dispatched[0] || !strings.HasSuffix(notes[0], "\nWhere it stands:\n"+summary) || !strings.HasPrefix(notes[0], jobLine("Login is broken", request, "Login is broken")) || !strings.Contains(summary, equipo.RunnerCopy("assistant.team.stage.cancelled")) {
t.Fatalf("after the cancel %v %q %v (summary %q)", again, notes, dispatched, summary)
}
o.reply(o.turn)
u := o.message(wire.LaneAssistant)
- if u.TurnID != ids[0] || u.Kind != wire.TurnTeamUpdate || u.Text != summary || len(u.PersonText) != 0 {
+ if u.TurnID != ids[0] || u.Kind != wire.TurnTeamUpdate || u.Text != notes[0] || len(u.PersonText) != 0 {
t.Fatalf("update frame %+v", u)
}
o.in(u.TurnID, func() {
@@ -1002,8 +988,8 @@ func TestContractTeamCancelStopsRunningTurn(t *testing.T) {
}
// TestContractTeamCancelStopsAnswerTurn: a request cancelled while the
-// turn carrying the Assistant's answer to its question waits in its
-// thread ends that turn too.
+// turn carrying the answer to its question waits in its thread ends
+// that turn too.
func TestContractTeamCancelStopsAnswerTurn(t *testing.T) {
o := newTeamRig(t)
o.ask("Can we fix a bug in Tito? Login is broken")
@@ -1013,8 +999,8 @@ func TestContractTeamCancelStopsAnswerTurn(t *testing.T) {
t.Fatalf("ask %+v", res)
}
})
- card := o.assistantCard("the question card", func(c wire.AssistantCard) bool { return c.Kind == wire.CardQuestion })
- if _, err := o.a.Answer(o.ctx, card.ID, "Web", card.Revision); err != nil {
+ card, revision := o.threadQuestion(request)
+ if _, err := o.client.Answer(o.ctx, card, "Web", revision); err != nil {
t.Fatal(err)
}
var answer string
@@ -1039,16 +1025,18 @@ func TestContractTeamCancelStopsAnswerTurn(t *testing.T) {
}
// TestContractHandoffTurnFails: a hand-off whose Coordinator turn fails
-// before it records or joins any work has stopped: the person is told
-// once, and team_status says so. A turn found gone when the runner
-// reconnects has failed the same way.
+// before it records or joins any work has stopped with no work: the
+// Assistant is told once, to push it through itself, and team_status
+// says it stopped. A turn found gone when the runner reconnects has
+// failed the same way.
func TestContractHandoffTurnFails(t *testing.T) {
stopped := equipo.RunnerCopy("assistant.team.stopped")
check := func(o *teamRig, request string) {
t.Helper()
o.until("the update", func() bool { ids, _, _ := o.updates(); return len(ids) == 1 })
- if _, notes, _ := o.updates(); notes[0] != stopped {
- t.Fatalf("update %q", notes)
+ want := jobLine("Login is broken", request, "Login is broken") + noWork(request, 2) + "\nWhere it stands:\n" + stopped
+ if _, notes, _ := o.updates(); notes[0] != want {
+ t.Fatalf("update %q, want %q", notes, want)
}
if got := o.status("hf-status", map[string]any{"request": request}); len(got) != 1 || got[0].Summary != stopped {
t.Fatalf("status %+v", got)
@@ -1556,16 +1544,17 @@ func TestContractHandoffLegacyKeepsItsRoute(t *testing.T) {
}
o.runner.Send(o.ctx, "r-lg-fail", wire.FrameTurn, wire.TurnReport{TurnID: other, Attempt: 1, State: wire.TurnFailed, Reason: "provider_failed"})
update := "SELECT count(*) FROM chat_turns t JOIN chat_handoff_turns ht ON ht.turn_id = t.id WHERE ht.handoff_id = ? AND t.kind = ? AND t.note = ?"
+ note := jobLine("Login is broken", stopped, "Login is broken") + noWork(stopped, 2) + "\nWhere it stands:\n" + equipo.RunnerCopy("assistant.team.stopped")
o.until("the legacy hand-off's update", func() bool {
- return o.rows(update, stopped, wire.TurnTeamUpdate, equipo.RunnerCopy("assistant.team.stopped")) == 1
+ return o.rows(update, stopped, wire.TurnTeamUpdate, note) == 1
})
}
// TestContractHandoffAnswerNeedsJobsRunner: a thread's question asked at
// protocol 21 and answered after the primary came back at 20 is refused
-// (409 runner_too_old), through the person API and the Assistant's card
-// alike: the card stays open at its revision, and no message or turn is
-// made that no runner could carry.
+// (409 runner_too_old) through the person API: the card stays open at
+// its revision, and no message or turn is made that no runner could
+// carry.
func TestContractHandoffAnswerNeedsJobsRunner(t *testing.T) {
o := newTeamRig(t)
o.ask("Can we fix a bug in Tito? Login is broken")
@@ -1577,7 +1566,6 @@ func TestContractHandoffAnswerNeedsJobsRunner(t *testing.T) {
})
o.reply(cmd.TurnID)
card, revision := o.threadQuestion(request)
- mirror := o.assistantCard("the question card", func(c wire.AssistantCard) bool { return c.Kind == wire.CardQuestion })
o.runner.Close()
o.wait("offline", func(c *Conversation) bool { return !c.Runner.Online })
o.dialAt(wire.Protocol20)
@@ -1598,6 +1586,351 @@ func TestContractHandoffAnswerNeedsJobsRunner(t *testing.T) {
}
_, err := o.client.Answer(o.ctx, card, "Web", revision)
refusedTooOld("the person's answer", err)
- _, err = o.a.Answer(o.ctx, mirror.ID, "Web", mirror.Revision)
- refusedTooOld("the Assistant card's answer", err)
+}
+
+// noWork is the note's line for a job that stopped before any work
+// started, with nudges left (noteNoWork).
+func noWork(request string, left int) string {
+ return fmt.Sprintf("It stopped before any work started. Push it through yourself: use team_nudge {\"request\": %q, \"words\": ...} with words quoted from what the person asked. Nudges left: %d. Say nothing to the person.", request, left)
+}
+
+// failedStep is the note's line for a job whose step failed and can be
+// tried again (noteFailed).
+func failedStep(request string, left int) string {
+ return fmt.Sprintf("A step of it failed and can be tried again. Push it through yourself: use team_nudge {\"request\": %q, \"words\": ...} to have it tried again. Nudges left: %d. Say nothing to the person.", request, left)
+}
+
+// blockedOn is the note's line for a job only the person can move on
+// (noteBlocked).
+func blockedOn(line string) string {
+ return "It stopped, and only the person can move it on: " + line + ". Tell the person that plainly, in one line. Do not nudge it."
+}
+
+// startedInThread hands "Login is broken" to the team and records and
+// starts a task in the job's thread: the request, the task and its
+// Engineering step.
+func (o *teamRig) startedInThread(key string) (request, id string, d *wire.DispatchCommand) {
+ o.t.Helper()
+ o.ask("Can we fix a bug in Tito? Login is broken")
+ request, cmd := o.handoff(key+"1", "Login is broken", "")
+ o.in(cmd.TurnID, func() {
+ id = o.record(key+"-rec", "Fix the login")
+ if res := o.call(key+"-start", wire.ToolStartTask, map[string]string{"task": id, "brief": "Fix it."}); res.IsError {
+ o.t.Fatalf("start %+v", res)
+ }
+ _, body := o.expect(wire.FrameDispatch)
+ d = body.(*wire.DispatchCommand)
+ })
+ return request, id, d
+}
+
+// TestContractTeamUpdateStops: a job that stops where the Assistant can
+// push it through tells it so: a thread turn that ended with no work, to
+// nudge it with the person's words; a retryable failed Engineering step,
+// to have it tried again; each with the nudges it has left. With none
+// left, the Assistant is to tell the person it stopped.
+func TestContractTeamUpdateStops(t *testing.T) {
+ t.Run("no_work", func(t *testing.T) {
+ o := newTeamRig(t)
+ o.ask("Can we fix a bug in Tito? Login is broken")
+ request, cmd := o.handoff("sw1", "Login is broken", "")
+ o.reply(cmd.TurnID)
+ note := o.noteFor("the no-work note", noWork(request, 2))
+ if !strings.HasPrefix(note, jobLine("Login is broken", request, "Login is broken")+noWork(request, 2)+"\nWhere it stands:\n") {
+ t.Fatalf("note %q", note)
+ }
+ })
+ t.Run("failed", func(t *testing.T) {
+ o := newTeamRig(t)
+ request, id, d := o.startedInThread("sf")
+ o.step("sf-fail", wire.StepReport{TaskID: id, StepID: d.StepID, Attempt: 1, State: wire.StepFailed, Reason: "provider_failed", Termination: true})
+ note := o.noteFor("the failed note", failedStep(request, 2))
+ if strings.Contains(note, "only the person can move it on") {
+ t.Fatalf("note %q", note)
+ }
+ })
+ t.Run("no_nudges", func(t *testing.T) {
+ o := newTeamRig(t)
+ o.ask("Can we fix a bug in Tito? Login is broken")
+ request, cmd := o.handoff("sn1", "Login is broken", "")
+ if _, err := o.inst.DB.Writer().Exec("UPDATE chat_handoffs SET nudges = 2 WHERE id = ?", request); err != nil {
+ t.Fatal(err)
+ }
+ o.reply(cmd.TurnID)
+ note := o.noteFor("the no-nudges note", "It stopped again and no nudges are left. Tell the person in one line that it stopped, and what would help if you know.")
+ if strings.Contains(note, "team_nudge") {
+ t.Fatalf("note %q", note)
+ }
+ })
+}
+
+// TestContractTeamUpdatePersonNeeds (ruling P4j): every need only the
+// person can meet stops the job for them: the note says what in plain
+// words and never asks the Assistant to nudge it, however its step
+// failed. The task's steps are written as each stop leaves them; a note
+// on the task's thread saves the task, as any change would.
+func TestContractTeamUpdatePersonNeeds(t *testing.T) {
+ cand := strings.Repeat("2", 40)
+ cases := []struct {
+ name, line string
+ set func(o *teamRig, id, step string)
+ }{
+ {"held", "they need to say when it can run", func(o *teamRig, id, step string) {
+ o.exec("UPDATE chat_steps SET state = ?, hold = ? WHERE id = ?", wire.StepQueued, `{"reason":"limited","wake_at":null,"needs_person":"connection","step_revision":1}`, step)
+ }},
+ {"branch_moved", "someone else changed the same work, and they need to look at it", func(o *teamRig, id, step string) {
+ o.exec("UPDATE chat_steps SET state = ?, pushed = 1, terminated = 1, candidate_sha = ? WHERE id = ?", wire.StepDone, cand, step)
+ o.exec("UPDATE chat_tasks SET moved_from = ? WHERE id = ?", cand, id)
+ }},
+ {"review_blocked", "the check of the work could not finish, and they need to decide what next", func(o *teamRig, id, step string) {
+ o.exec("UPDATE chat_steps SET specialist = ?, state = ?, terminated = 1 WHERE id = ?", wire.SpecialistReview, wire.StepFailed, step)
+ }},
+ {"fix_rounds", "the checks still find problems after the automatic fixes, and they need to decide what next", func(o *teamRig, id, step string) {
+ o.exec("UPDATE chat_steps SET state = ?, pushed = 1, terminated = 1, candidate_sha = ?, round = ? WHERE id = ?", wire.StepDone, cand, wire.MaxFixRounds, step)
+ o.exec("INSERT INTO chat_steps(id, task_id, idx, specialist, person, state, attempt, candidate_sha, checks, terminated, revision, created_at, updated_at) SELECT 's_fixed', task_id, idx + 1, ?, person, ?, 1, ?, ?, 1, 1, created_at, updated_at FROM chat_steps WHERE id = ?", wire.SpecialistChecks, wire.StepDone, cand, wire.ChecksFailed, step)
+ }},
+ {"merge_conflict", "it clashes with other changes, and they need to sort it out", func(o *teamRig, id, step string) {
+ o.exec("UPDATE chat_steps SET specialist = ?, state = ?, terminated = 1, reason = 'merge_conflict' WHERE id = ?", wire.SpecialistMerge, wire.StepFailed, step)
+ }},
+ {"machine_removed", "they need to bring their computer back online", func(o *teamRig, id, step string) {
+ o.exec("UPDATE chat_steps SET state = ?, terminated = 0, reason = 'machine_removed' WHERE id = ?", wire.StepFailed, step)
+ }},
+ {"mac_sandbox", "they need to let it be tested on their Mac", func(o *teamRig, id, step string) {
+ o.exec("UPDATE chat_steps SET specialist = ?, state = ?, placement = ? WHERE id = ?", wire.SpecialistChecks, wire.StepQueued, wire.PlacementSandbox, step)
+ }},
+ {"merge_failed", "going live failed, and they need to try it again", func(o *teamRig, id, step string) {
+ o.exec("UPDATE chat_steps SET specialist = ?, state = ?, terminated = 1, reason = 'provider_failed' WHERE id = ?", wire.SpecialistMerge, wire.StepFailed, step)
+ }},
+ }
+ for _, c := range cases {
+ t.Run(c.name, func(t *testing.T) {
+ o := newTeamRig(t)
+ _, id, d := o.startedInThread("pn")
+ c.set(o, id, d.StepID)
+ if _, err := o.client.PostThread(o.ctx, id, "For the record.", "pn-note"); err != nil {
+ t.Fatal(err)
+ }
+ if note := o.noteFor("the "+c.name+" note", blockedOn(c.line)); strings.Contains(note, "team_nudge") {
+ t.Fatalf("note %q", note)
+ }
+ })
+ }
+ // runner_offline is a need no task of the instance's reports now
+ // (needsYou never returns it); its plain line is checked where the
+ // lines are kept (TestJobNoteBlockedLines).
+ t.Run("publish_failed", func(t *testing.T) {
+ o := newTeamRig(t)
+ o.mergedWebsite("pf", true)
+ // The project's ships question, answered in the thread, waits on
+ // the person no more.
+ var ships string
+ var revision int64
+ if err := o.inst.DB.Writer().QueryRow("SELECT id, revision FROM chat_cards WHERE kind = ? AND state = ?", wire.CardMergeShips, wire.CardOpen).Scan(&ships, &revision); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := o.client.Answer(o.ctx, ships, wire.ChoiceNotShips, revision); err != nil {
+ t.Fatal(err)
+ }
+ card := o.assistantCard("the publish outcome", isPublishOutcome)
+ if _, err := o.a.Answer(o.ctx, card.ID, wire.ChoicePublish, card.Revision); err != nil {
+ t.Fatal(err)
+ }
+ o.publishReport("pf-failed", o.publishDispatch(), wire.StepFailed, nil)
+ if note := o.noteFor("the publish failure's note", blockedOn("going live failed, and they need to try it again")); strings.Contains(note, "team_nudge") {
+ t.Fatalf("note %q", note)
+ }
+ })
+}
+
+// exec runs a statement on the instance's database.
+func (o *teamRig) exec(q string, args ...any) {
+ o.t.Helper()
+ if _, err := o.inst.DB.Writer().Exec(q, args...); err != nil {
+ o.t.Fatal(err)
+ }
+}
+
+// TestContractTeamUpdateQuietProgress: routine progress tells the
+// Assistant nothing: a followed task noted, in progress and in review
+// queues no team_update; the go-ahead raised does; a finding while it
+// waits, and merging after it, change nothing it was told.
+func TestContractTeamUpdateQuietProgress(t *testing.T) {
+ o := newTeamRig(t)
+ o.sitesOn(wire.ProtocolAssistant, false)
+ o.shipsNo(o.project())
+ quiet := func(stage string, n int) {
+ t.Helper()
+ time.Sleep(20 * time.Millisecond)
+ if ids, notes, _ := o.updates(); len(ids) != n {
+ t.Fatalf("at %s: updates %v %q", stage, ids, notes)
+ }
+ }
+ stage := func(id, want string) {
+ t.Helper()
+ o.wait(want, func(c *Conversation) bool { return c.Tasks[id].Stage == want })
+ }
+ o.ask("Can we fix a bug in Tito? Login is broken")
+ _, cmd := o.handoff("qp1", "Login is broken", "")
+ base, cand := strings.Repeat("1", 40), strings.Repeat("2", 40)
+ var id string
+ o.in(cmd.TurnID, func() {
+ id = o.record("qp-rec", "Fix the login")
+ stage(id, wire.StageNoted)
+ quiet("noted", 0)
+ if res := o.call("qp-start", wire.ToolStartTask, map[string]string{"task": id, "brief": "Fix it."}); res.IsError {
+ t.Fatalf("start %+v", res)
+ }
+ _, body := o.expect(wire.FrameDispatch)
+ d := body.(*wire.DispatchCommand)
+ o.step("qp-run", wire.StepReport{TaskID: id, StepID: d.StepID, Attempt: 1, State: wire.StepRunning, BaseSHA: base, Family: "claude", Account: "claude-a"})
+ stage(id, wire.StageInProgress)
+ quiet("in progress", 0)
+ o.step("qp-done", wire.StepReport{TaskID: id, StepID: d.StepID, Attempt: 1, State: wire.StepDone, BaseSHA: base, CandidateSHA: cand, Pushed: true, Termination: true, Family: "claude", Account: "claude-a"})
+ o.expect(wire.FrameWatchMerge)
+ c := o.dispatched(wire.SpecialistChecks, base, cand, 0)
+ stage(id, wire.StageInReview)
+ quiet("in review", 0)
+ o.checks("qp-c", c, wire.ChecksNone, nil, "", "")
+ o.verdict("qp-r", o.dispatched(wire.SpecialistReview, base, cand, 0), wire.VerdictApprove)
+ })
+ card := o.assistantCard("the go-ahead", isMergeOutcome)
+ o.noteFor("the go-ahead's note", "It is ready for the person to try.")
+ quiet("ready", 1)
+ // A finding while the go-ahead waits changes where it stands, and
+ // tells nothing new.
+ _, told, _ := o.updates()
+ o.in(cmd.TurnID, func() {
+ if res := o.call("qp-find", wire.ToolAddFinding, map[string]any{"task": id, "headline": "The sign in button posts to the old address.", "text": "login.js posts to /v1/login.", "repo": "oficina/sample", "path": "login.js", "line": 3}); res.IsError {
+ t.Fatalf("finding %+v", res)
+ }
+ })
+ quiet("a finding", 1)
+ if _, notes, _ := o.updates(); !slices.Equal(notes, told) {
+ t.Fatalf("after a finding %q, before %q", notes, told)
+ }
+ if _, err := o.a.Answer(o.ctx, card.ID, wire.ChoiceMerge, card.Revision); err != nil {
+ t.Fatal(err)
+ }
+ o.dispatched(wire.SpecialistMerge, base, cand, 0)
+ stage(id, wire.StageMerging)
+ quiet("merging", 1)
+}
+
+// statusOf is team_status's answer for one request, as JSON.
+func (o *teamRig) statusOf(key, request string) map[string]any {
+ o.t.Helper()
+ res := o.use(key, "team_status", map[string]any{"request": request})
+ var out struct {
+ Requests []map[string]any `json:"requests"`
+ }
+ if res.IsError || json.Unmarshal([]byte(res.Text), &out) != nil || len(out.Requests) != 1 {
+ o.t.Fatalf("team_status %+v", res)
+ }
+ return out.Requests[0]
+}
+
+// TestContractTeamStatusQuestion: team_status names the job's title and,
+// while the job has an open question, the question and its options
+// (never null); with none open, no question at all.
+func TestContractTeamStatusQuestion(t *testing.T) {
+ o := newTeamRig(t)
+ o.ask("Can we fix a bug in Tito? Login is broken")
+ request := o.request("tq1", map[string]any{"words": "Login is broken", "title": "Fixing the sign-in page"})
+ cmd := o.message(wire.JobLane(request))
+ if got := o.statusOf("tq-none", request); got["title"] != "Fixing the sign-in page" || got["question"] != nil {
+ t.Fatalf("before a question %+v", got)
+ }
+ o.in(cmd.TurnID, func() {
+ if res := o.call("tq-ask", wire.ToolAskPerson, map[string]any{"question": "Which login page?", "options": []string{"Web", "App"}}); res.Code != "asked" {
+ t.Fatalf("ask %+v", res)
+ }
+ })
+ got := o.statusOf("tq-open", request)
+ if q, ok := got["question"].(map[string]any); !ok || q["text"] != "Which login page?" || fmt.Sprint(q["options"]) != "[Web App]" || got["title"] != "Fixing the sign-in page" {
+ t.Fatalf("with the question %+v", got)
+ }
+ o.reply(cmd.TurnID)
+ card, revision := o.threadQuestion(request)
+ ans, err := o.client.Answer(o.ctx, card, "Web", revision)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if got := o.statusOf("tq-answered", request); got["question"] != nil {
+ t.Fatalf("after the answer %+v", got)
+ }
+ o.message(wire.JobLane(request))
+ o.in(ans.Turn.ID, func() {
+ if res := o.call("tq-ask2", wire.ToolAskPerson, map[string]any{"question": "Anything else to know?"}); res.Code != "asked" {
+ t.Fatalf("ask %+v", res)
+ }
+ })
+ res := o.use("tq-free", "team_status", map[string]any{"request": request})
+ if res.IsError || !strings.Contains(res.Text, `"question":{"text":"Anything else to know?","options":[]}`) {
+ t.Fatalf("a question without options %+v", res)
+ }
+}
+
+// TestContractTeamOpenQuestionsNote (D8): while a job of the person's
+// has an open question, their next Assistant message is dispatched with
+// the questions after their words, marked as reference; PersonText and
+// the stored message are their words alone. Once none is open their
+// words go alone. A Coordinator or job-lane turn never carries it.
+func TestContractTeamOpenQuestionsNote(t *testing.T) {
+ o := newTeamRig(t)
+ o.ask("Two things. Login is broken. Checkout is slow.")
+ request, cmd := o.handoff("on1", "Login is broken", "")
+ o.in(cmd.TurnID, func() {
+ if res := o.call("on-ask", wire.ToolAskPerson, map[string]any{"question": "Which login page?", "options": []string{"Web", "App"}}); res.Code != "asked" {
+ t.Fatalf("ask %+v", res)
+ }
+ })
+ // A job-lane turn and a Coordinator turn dispatched meanwhile.
+ second := o.request("on2", map[string]any{"words": "Checkout is slow"})
+ if job := o.message(wire.JobLane(second)); job.Text != "Checkout is slow" {
+ t.Fatalf("the job-lane frame %q", job.Text)
+ }
+ mine, err := o.client.Send(o.ctx, "Something of my own.", "own-on")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if own := o.message(wire.LaneCoordinator); own.TurnID != mine.Turn.ID || own.Text != "Something of my own." {
+ t.Fatalf("their own frame %+v", own)
+ }
+ o.reply(cmd.TurnID)
+ o.reply(o.turn)
+ u := o.message(wire.LaneAssistant)
+ if u.Kind != wire.TurnTeamUpdate || strings.Contains(u.Text, "[Open questions") {
+ t.Fatalf("the update %+v", u)
+ }
+ o.reply(u.TurnID)
+ send := func(text string) *wire.MessageCommand {
+ t.Helper()
+ sent, err := o.a.Send(o.ctx, text, "a-"+itoa(len(o.runner.Sent)))
+ if err != nil {
+ t.Fatal(err)
+ }
+ cmd := o.message(wire.LaneAssistant)
+ if cmd.TurnID != sent.Turn.ID || !slices.Equal(cmd.PersonText, []string{text}) || sent.Message.Text != text {
+ t.Fatalf("the frame %+v for %+v", cmd, sent)
+ }
+ return cmd
+ }
+ block := "[Open questions on the person's jobs. Reference only, never the person's words:\n" +
+ fmt.Sprintf("- Job %q (request %s): %q The answer must be one of: \"Web\", \"App\"", "Login is broken", request, "Which login page?") +
+ "\nAnswer one with team_reply when this conversation holds the answer.]"
+ asked := send("It is the web one.")
+ if asked.Text != "It is the web one.\n\n"+block {
+ t.Fatalf("with an open question %q", asked.Text)
+ }
+ o.reply(asked.TurnID)
+ card, revision := o.threadQuestion(request)
+ if _, err := o.client.Answer(o.ctx, card, "Web", revision); err != nil {
+ t.Fatal(err)
+ }
+ if next := o.message(wire.JobLane(request)); strings.Contains(next.Text, "[Open questions") {
+ t.Fatalf("the answer's frame %q", next.Text)
+ }
+ if plain := send("Thanks."); plain.Text != "Thanks." {
+ t.Fatalf("with none open %q", plain.Text)
+ }
}