oficina / equipo Public

Keep every job tracked, shown and asked about to the end

The final whole-branch review's five Important findings:

- Build on a job's exploration links the new change to the request
  (chat_handoff_tasks, its created flag inherited) in the answer's
  transaction, before dispatch and projection: status, retry nudges
  and team_cancel reach it, and the job no longer says done early.
- The job card takes its stop from jobStop, as the note does: a
  blocker only the person clears (research sources) stops it before
  the work settles, after the Assistant's team_update (P5j); ready
  and R18 keep precedence. A cleared blocker reprojects its job.
- A ready job card's preview is revalidated on read (jobPreview);
  the minute's tick reprojects ready jobs whose preview expired or
  went and moves the go-ahead under them, so the stream drops it.
- The Assistant snapshot keeps working, asking and ready job cards
  and the cards open under them past the newest-50 cutoff.
- The open-questions note says how many more jobs are asking;
  team_status pages open requests ten at a time (next, after).

Budgets: internal/equipo/chat 26962 source, internal/thintest 27907
test lines. No migration.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by paul@keymail.dev c86357e74e9a13c13bef83a2f7397e22bf40a531 parent daa2edd
9 files changed, +465 −26
  • .rastrillo/budgets.txt +2 −2
  • internal/equipo/chat/explore.go +7 −1
  • internal/equipo/chat/handoff.go +47 −13
  • internal/equipo/chat/housekeeping_control.go +7 −3
  • internal/equipo/chat/jobs.go +83 −6
  • internal/equipo/chat/lane.go +30 −0
  • internal/equipo/chat/outcome.go +10 −1
  • internal/equipo/chat/tools.go +2 −0
  • internal/thintest/assistant_job_track_contract_test.go +277 −0
diff --git a/.rastrillo/budgets.txt b/.rastrillo/budgets.txt
index 13e4d5cd..f37f2e07 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 26800 - The instance store shares transaction and authority helpers. Adds job threads, pages, titles, action ledger, job notes, cards, team_reply and team_nudge. Measured 26800 source lines.
+size internal/equipo/chat 26962 - The instance store shares transaction and authority helpers. Adds job threads, titles, action ledger, notes, cards, team_reply, team_nudge and job tracking. Measured 26962 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 - 10637 End-to-end scenarios through a real runner and instance, browser drives and the Assistant's job threads included (answered and nudged jobs). Measured 10637 test lines.
-size internal/thintest - 27630 Contract and browser tests share one instance harness. Adds the job thread, card lane, page, title, job note, job card, team_reply and team_nudge contracts. Measured 27630 test lines.
+size internal/thintest - 27907 Contract and browser tests share one instance harness. Adds the job thread, card lane, page, title, note, job card, tracking, team_reply and team_nudge contracts. Measured 27907 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/explore.go b/internal/equipo/chat/explore.go
index dd5716b7..7fb57087 100644
--- a/internal/equipo/chat/explore.go
+++ b/internal/equipo/chat/explore.go
@@ -257,7 +257,10 @@ func (t *txn) answerDirection(person string, c cardRecord, in wire.AnswerCard) (
// exploration's lane, whose brief names the explored branch and commit to
// read for the design. It starts from
// the default branch like any task, and is started at once. The
-// exploration is done, linked to it.
+// exploration is done, linked to it. A request that follows the
+// exploration follows the new task too, before anything of it is
+// dispatched or told: as work it made when it made the exploration
+// (team_cancel stops it), else as work it joined.
func (t *txn) buildThisOne(k *taskRecord, p progress) error {
now := t.now()
title := t.words("work.explore.build_title", k.Title)
@@ -275,6 +278,9 @@ func (t *txn) buildThisOne(k *taskRecord, p progress) error {
if err := t.db.Create(&n).Error; err != nil {
return err
}
+ if err := t.db.Exec("INSERT INTO chat_handoff_tasks(handoff_id, task_id, created) SELECT handoff_id, ?, created FROM chat_handoff_tasks WHERE task_id = ? AND handoff_id IN (SELECT id FROM chat_handoffs WHERE state = ?) ON CONFLICT DO NOTHING", n.ID, k.ID, handoffOpen).Error; err != nil {
+ return err
+ }
c := cardRecord{ID: newID("c_"), Person: n.Creator, Kind: wire.CardTask, State: wire.StageNoted, ProjectID: n.ProjectID, TaskID: n.ID, Options: "[]", Revision: 1, CreatedAt: now, UpdatedAt: now, Lane: n.Lane}
if err := t.db.Create(&c).Error; err != nil {
return err
diff --git a/internal/equipo/chat/handoff.go b/internal/equipo/chat/handoff.go
index 32837760..21a1978f 100644
--- a/internal/equipo/chat/handoff.go
+++ b/internal/equipo/chat/handoff.go
@@ -168,9 +168,9 @@ var teamOps = []assist.Operation{
Input: json.RawMessage(`{"type":"object","properties":{"words":{"type":"string","description":"The person's own words from their message in this turn, quoted exactly."},"context":{"type":"string","maxLength":4000,"description":"What you know that helps: kept apart from the person's words, as reference."},"title":{"type":"string","maxLength":60,"description":"A short name for this job, in the person's terms, such as \"Fixing the sign-in page\"."}},"required":["words"],"additionalProperties":false}`),
Output: json.RawMessage(`{"type":"object","properties":{"request":{"type":"string"},"status":{"type":"string"},"title":{"type":"string"}}}`)},
{Name: opTeamStatus, App: "Team", Scope: "team", ReadOnly: true, Idempotent: true,
- Description: "Read-only: where the work handed to the team stands, in plain words: one request (request), the person's open requests (none given), or those and the work they started with the team themselves (all).",
- Input: json.RawMessage(`{"type":"object","properties":{"request":{"type":"string"},"all":{"type":"boolean"}},"additionalProperties":false}`),
- Output: json.RawMessage(`{"type":"object","properties":{"requests":{"type":"array","items":{"type":"object","properties":{"request":{"type":"string"},"summary":{"type":"string"}}}}}}`)},
+ Description: "Read-only: where the work handed to the team stands, in plain words, with each job's open question: one request (request), the person's open requests (none given), or those and the work they started with the team themselves (all). Open requests come ten at a time, newest first; when more are open, next is set: pass it as after to read the ten after them.",
+ Input: json.RawMessage(`{"type":"object","properties":{"request":{"type":"string"},"all":{"type":"boolean"},"after":{"type":"string","description":"The next of the page before, to read on."}},"additionalProperties":false}`),
+ Output: json.RawMessage(`{"type":"object","properties":{"requests":{"type":"array","items":{"type":"object","properties":{"request":{"type":"string"},"summary":{"type":"string"},"title":{"type":"string"},"question":{"type":"object","properties":{"text":{"type":"string"},"options":{"type":"array","items":{"type":"string"}}}}}}},"next":{"type":"string"}}}`)},
{Name: opTeamCancel, App: "Team", Scope: "team", Idempotent: true,
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}`),
@@ -1128,14 +1128,16 @@ func (t *txn) jobNote(h handoffRecord) (string, error) {
// 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.
+// of their open or stopping jobs, newest job first, with its options, at
+// most maxStatus of them, then how many more there are and where to read
+// them (team_status); "" 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
+ more := 0
for _, h := range rows {
q, ok, err := t.openQuestion(h)
if err != nil {
@@ -1144,6 +1146,10 @@ func (t *txn) openQuestionsNote(person string) (string, error) {
if !ok {
continue
}
+ if len(lines) == maxStatus {
+ more++
+ continue
+ }
title, _, err := t.jobTitle(h)
if err != nil {
return "", err
@@ -1157,13 +1163,17 @@ func (t *txn) openQuestionsNote(person string) (string, error) {
if len(options) > 0 {
line += " " + fmt.Sprintf(noteOptions, quoted(options))
}
- if lines = append(lines, line); len(lines) == maxStatus {
- break
- }
+ lines = append(lines, line)
}
if len(lines) == 0 {
return "", nil
}
+ switch {
+ case more == 1:
+ lines = append(lines, noteMoreQuestion)
+ case more > 1:
+ lines = append(lines, fmt.Sprintf(noteMoreQuestions, more))
+ }
return fmt.Sprintf(noteOpenQuestions, strings.Join(lines, "\n")), nil
}
@@ -1193,16 +1203,20 @@ type teamQuestion struct {
// 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). A request names its job's title and the question
-// open for it.
+// open for it. Open requests come maxStatus at a time, newest first: a
+// page with more after it names its last request as next, and after
+// reads on from there (the person's own work only on the first page).
func (s *Store) teamStatus(ctx context.Context, person string, input json.RawMessage) (json.RawMessage, error) {
var in struct {
Request string `json:"request"`
All bool `json:"all"`
+ After string `json:"after"`
}
- if wire.Strict(input, &in) != nil || len(in.Request) > 200 {
+ if wire.Strict(input, &in) != nil || len(in.Request) > 200 || len(in.After) > 200 || in.Request != "" && in.After != "" {
return nil, errBadTeamInput
}
out := []teamSummary{}
+ next := ""
err := s.read(ctx, func(tx *gorm.DB) error {
t := &txn{s: s, ctx: ctx, db: tx}
var rows []handoffRecord
@@ -1212,12 +1226,28 @@ func (s *Store) teamStatus(ctx context.Context, person string, input json.RawMes
} else {
q = q.Where("state IN ?", []string{handoffOpen, handoffStopping})
}
- if err := q.Order("created_at DESC, id DESC").Limit(maxStatus).Find(&rows).Error; err != nil {
+ // The open requests ten at a time, newest first: after a page's
+ // last (its next), the ones older than it.
+ if in.After != "" {
+ var from handoffRecord
+ if err := tx.Where("id = ? AND person = ?", in.After, person).Limit(1).Find(&from).Error; err != nil {
+ return err
+ }
+ if from.ID == "" {
+ return assist.Failure{Code: "not_found", Message: toolNoRequest}
+ }
+ q = q.Where("(created_at < ? OR created_at = ? AND id < ?)", from.CreatedAt, from.CreatedAt, from.ID)
+ }
+ if err := q.Order("created_at DESC, id DESC").Limit(maxStatus + 1).Find(&rows).Error; err != nil {
return err
}
if in.Request != "" && len(rows) == 0 {
return assist.Failure{Code: "not_found", Message: toolNoRequest}
}
+ if len(rows) > maxStatus {
+ rows = rows[:maxStatus]
+ next = rows[maxStatus-1].ID
+ }
for _, h := range rows {
text, err := t.handoffSummary(h)
if err != nil {
@@ -1241,7 +1271,7 @@ func (s *Store) teamStatus(ctx context.Context, person string, input json.RawMes
}
out = append(out, one)
}
- if !in.All || in.Request != "" {
+ if !in.All || in.Request != "" || in.After != "" {
return nil
}
var own []taskRecord
@@ -1260,7 +1290,11 @@ func (s *Store) teamStatus(ctx context.Context, person string, input json.RawMes
if err != nil {
return nil, err
}
- raw, err := json.Marshal(map[string]any{"requests": out})
+ page := map[string]any{"requests": out}
+ if next != "" {
+ page["next"] = next
+ }
+ raw, err := json.Marshal(page)
return raw, err
}
diff --git a/internal/equipo/chat/housekeeping_control.go b/internal/equipo/chat/housekeeping_control.go
index 7c7baf8c..ac73e471 100644
--- a/internal/equipo/chat/housekeeping_control.go
+++ b/internal/equipo/chat/housekeeping_control.go
@@ -461,13 +461,17 @@ func (t *txn) subjectRevision(kind, id string) (int64, error) {
}
// HousekeepingTick is the loop's minute: receipts whose quiet hours ended
-// show; stale claims are revalidated; the daily sweep runs once per day
-// at 03:00 and held findings are looked at again; each person gets their
-// digest once a day from 08:00 when something happened.
+// show; a job's preview that expired is offered no more; stale claims
+// are revalidated; the daily sweep runs once per day at 03:00 and held
+// findings are looked at again; each person gets their digest once a
+// day from 08:00 when something happened.
func (s *Store) HousekeepingTick(ctx context.Context) error {
if err := s.tx(ctx, func(t *txn) error { return t.hkRelease("", t.hkNow()) }); err != nil {
return err
}
+ if err := s.tx(ctx, func(t *txn) error { return t.expirePreviews() }); err != nil {
+ return err
+ }
if _, _, err := s.RecoverHousekeeping(ctx, true); err != nil {
return err
}
diff --git a/internal/equipo/chat/jobs.go b/internal/equipo/chat/jobs.go
index 00c8004d..84c590c5 100644
--- a/internal/equipo/chat/jobs.go
+++ b/internal/equipo/chat/jobs.go
@@ -3,6 +3,7 @@ package chat
import (
"context"
"encoding/json"
+ "slices"
"strings"
"time"
"unicode/utf8"
@@ -226,7 +227,9 @@ func (t *txn) jobState(h handoffRecord) (state, key string, first *wire.CardLink
if err != nil {
return "", "", nil, err
}
- _, _, ended, err := t.jobStop(h, settled)
+ // The job's note's stop (jobStop): a blocker only the person clears
+ // stops it before its work settles too.
+ reason, _, ended, err := t.jobStop(h, settled)
if err != nil {
return "", "", nil, err
}
@@ -259,9 +262,8 @@ func (t *txn) jobState(h handoffRecord) (state, key string, first *wire.CardLink
if err != nil || asking {
return wire.JobAsking, "", nil, err
}
- reason, err := t.stopReason(h)
- if err != nil || reason != "" {
- return wire.JobStopped, "", nil, err
+ if reason != "" {
+ return wire.JobStopped, "", nil, nil
}
}
tasks, err := t.handoffTasks(h)
@@ -367,7 +369,10 @@ func (t *txn) updateEnded(turnID string) error {
}
// jobCardView fills an Assistant job card: its status, detail and links as
-// stored, and when its hand-off was made.
+// stored, and when its hand-off was made. A ready job's preview is read
+// as it is now (jobPreview): one that expired or went since the card was
+// written is offered no more, before the minute's tick moves the card
+// (expirePreviews).
func (t *txn) jobCardView(v *wire.AssistantCard, c cardRecord) error {
v.Result, v.Detail = c.Result, c.Detail
if c.Links != "" {
@@ -379,11 +384,83 @@ func (t *txn) jobCardView(v *wire.AssistantCard, c cardRecord) error {
v.Links = []wire.CardLink{}
}
var h handoffRecord
- if err := t.db.Select("id", "created_at").Where("id = ? AND person = ?", c.HandoffID, c.Person).Limit(1).Find(&h).Error; err != nil || h.ID == "" {
+ if err := t.db.Where("id = ? AND person = ?", c.HandoffID, c.Person).Limit(1).Find(&h).Error; err != nil || h.ID == "" {
return err
}
at := h.CreatedAt
v.StartedAt = &at
+ if c.State != wire.JobReady || !slices.ContainsFunc(v.Links, isPreview) {
+ return nil
+ }
+ preview, err := t.jobPreview(h)
+ v.Links = slices.DeleteFunc(v.Links, func(l wire.CardLink) bool { return isPreview(l) && l.URL != preview })
+ return err
+}
+
+// isPreview: a ready job card's link to its preview (its only link with
+// no rel).
+func isPreview(l wire.CardLink) bool { return l.Rel == "" }
+
+// jobPreview is the preview of the go-ahead or Publish the hand-off's
+// job waits on while it is up (taskPreview), "" for none.
+func (t *txn) jobPreview(h handoffRecord) (string, error) {
+ src, ready, err := t.readyCard(h)
+ if err != nil || !ready {
+ return "", err
+ }
+ return t.taskPreview(src.TaskID)
+}
+
+// expirePreviews moves each ready job card whose preview expired or went
+// with nothing else changing (the minute's tick): projected afresh, and
+// the go-ahead or Publish open under it moved too, so a client that only
+// follows the stream offers the preview no more.
+func (t *txn) expirePreviews() error {
+ var cards []cardRecord
+ if err := t.db.Where("lane = ? AND kind = ? AND state = ?", wire.LaneAssistant, wire.CardJob, wire.JobReady).Order("created_at, id").Find(&cards).Error; err != nil {
+ return err
+ }
+ for _, c := range cards {
+ var links []wire.CardLink
+ if err := json.Unmarshal([]byte(c.Links), &links); err != nil {
+ return err
+ }
+ i := slices.IndexFunc(links, isPreview)
+ if i < 0 {
+ continue
+ }
+ var h handoffRecord
+ if err := t.db.Where("id = ? AND person = ?", c.HandoffID, c.Person).Limit(1).Find(&h).Error; err != nil {
+ return err
+ }
+ if h.ID == "" {
+ continue
+ }
+ preview, err := t.jobPreview(h)
+ if err != nil {
+ return err
+ }
+ if preview == links[i].URL {
+ continue
+ }
+ if err := t.projectJob(h); err != nil {
+ return err
+ }
+ var mirrors []cardRecord
+ if err := t.db.Where("handoff_id = ? AND person = ? AND lane = ? AND state = ? AND coalesce(source_card, '') <> ''", h.ID, h.Person, wire.LaneAssistant, wire.CardOpen).Find(&mirrors).Error; err != nil {
+ return err
+ }
+ for _, m := range mirrors {
+ m.Revision++
+ m.UpdatedAt = t.now()
+ if err := t.db.Model(&cardRecord{}).Where("id = ?", m.ID).Select("revision", "updated_at").Updates(&m).Error; err != nil {
+ return err
+ }
+ if err := t.cardEvent(m); err != nil {
+ return err
+ }
+ }
+ }
return nil
}
diff --git a/internal/equipo/chat/lane.go b/internal/equipo/chat/lane.go
index 0f803251..280ec603 100644
--- a/internal/equipo/chat/lane.go
+++ b/internal/equipo/chat/lane.go
@@ -193,6 +193,9 @@ func (l *LaneStore) Snapshot(ctx context.Context, person string) (out wire.Assis
return e
}
rows, e := t.laneCards(person, l.lane)
+ if e == nil && l.lane == wire.LaneAssistant {
+ rows, e = t.withActiveJobs(person, rows)
+ }
if e != nil {
return e
}
@@ -209,6 +212,33 @@ func (l *LaneStore) Snapshot(ctx context.Context, person string) (out wire.Assis
return out, err
}
+// withActiveJobs is the Assistant lane's newest cards (rows, newest
+// first) with every unfinished job card (working, asking or ready) and
+// each card open under one (D2), however old, newest first: newer cards
+// never push a job that still moves, or its go-ahead, off the snapshot.
+func (t *txn) withActiveJobs(person string, rows []cardRecord) ([]cardRecord, error) {
+ active := []string{wire.JobWorking, wire.JobAsking, wire.JobReady}
+ var more []cardRecord
+ err := t.db.Where("person = ? AND lane = ? AND (held IS NULL OR held = ?)", person, wire.LaneAssistant, false).
+ Where("(kind = ? AND state IN ? OR state = ? AND coalesce(source_card, '') <> '' AND handoff_id IN (SELECT handoff_id FROM chat_cards WHERE person = ? AND lane = ? AND kind = ? AND state IN ?))", wire.CardJob, active, wire.CardOpen, person, wire.LaneAssistant, wire.CardJob, active).
+ Find(&more).Error
+ if err != nil {
+ return nil, err
+ }
+ for _, c := range more {
+ if !slices.ContainsFunc(rows, func(r cardRecord) bool { return r.ID == c.ID }) {
+ rows = append(rows, c)
+ }
+ }
+ slices.SortStableFunc(rows, func(a, b cardRecord) int {
+ if c := b.CreatedAt.Compare(a.CreatedAt); c != 0 {
+ return c
+ }
+ return strings.Compare(b.ID, a.ID)
+ })
+ return rows, nil
+}
+
// Answer answers one of the lane's question cards. The answer becomes
// the person's next message in the lane. A stale revision or a card
// already answered is a conflict carrying the card as it is. A job card
diff --git a/internal/equipo/chat/outcome.go b/internal/equipo/chat/outcome.go
index ac8cda8d..f41f7a7a 100644
--- a/internal/equipo/chat/outcome.go
+++ b/internal/equipo/chat/outcome.go
@@ -105,7 +105,16 @@ func (t *txn) mirrorCard(src cardRecord) error {
if asksPerson(src) {
return t.teamAsks(src)
}
- return nil
+ // A card that stopped the work, answered or withdrawn: its job
+ // may work again.
+ if !blocksWork(src.Kind, wire.CardOpen) && !blocksWork(src.Kind, wire.CardHomeAsk) {
+ return nil
+ }
+ h, ok, err := t.handoffFor(src)
+ if err != nil || !ok {
+ return err
+ }
+ return t.projectJob(h)
}
h, ok, err := t.handoffFor(src)
if err != nil || !ok {
diff --git a/internal/equipo/chat/tools.go b/internal/equipo/chat/tools.go
index f00c887d..e12fc895 100644
--- a/internal/equipo/chat/tools.go
+++ b/internal/equipo/chat/tools.go
@@ -96,6 +96,8 @@ const (
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"
+ noteMoreQuestion = "1 more job has an open question not listed here: team_status lists every open request with its question, ten at a time (pass its next as after to read on)."
+ noteMoreQuestions = "%d more jobs have open questions not listed here: team_status lists every open request with its question, ten at a time (pass its next as after to read on)."
)
// causeGoingLive: a job's merge or publish step failed (stopCause). Only
diff --git a/internal/thintest/assistant_job_track_contract_test.go b/internal/thintest/assistant_job_track_contract_test.go
new file mode 100644
index 00000000..43a36098
--- /dev/null
+++ b/internal/thintest/assistant_job_track_contract_test.go
@@ -0,0 +1,277 @@
+package thintest
+
+import (
+ "encoding/json"
+ "fmt"
+ "slices"
+ "strings"
+ "testing"
+ "time"
+
+ "amadan.net/oficina/equipo/internal/equipo"
+ "amadan.net/oficina/equipo/internal/wire"
+)
+
+// What a job keeps track of past its first task: the change an
+// exploration it made becomes, a blocker only the person can clear
+// before work starts, a preview that goes, every open question, and its
+// card in a long Assistant lane.
+
+// TestContractHandoffExploreBuildFollowed: Build on a job's exploration
+// makes a change the job follows, as work it made, in the answer's own
+// transaction: the job works on while the change is built (never done),
+// team_status tells of it, a failed build step is the job's to push
+// through, and team_cancel stops it.
+func TestContractHandoffExploreBuildFollowed(t *testing.T) {
+ o := newTeamRig(t)
+ o.ask("Make me some mockups for the barber app")
+ request, cmd := o.handoff("xb1", "mockups for the barber app", "")
+ var id string
+ o.in(cmd.TurnID, func() {
+ id, _ = o.explored("xb", "Barber app mockups", candX)
+ o.approved("xb", candX, true)
+ })
+ var card wire.Card
+ o.until("the direction card", func() bool {
+ card = o.jobCard(request, wire.CardDirection, id)
+ return card.State == wire.CardOpen
+ })
+ if _, err := o.client.Answer(o.ctx, card.ID, wire.ChoiceBuild, card.Revision); err != nil {
+ t.Fatal(err)
+ }
+ d := o.nextDispatch()
+ build := d.TaskID
+ if d.Specialist != wire.SpecialistEngineering || build == id {
+ t.Fatalf("the build's dispatch %+v", d)
+ }
+ if linked := o.linked(request); len(linked) != 2 || !linked[id] || !linked[build] {
+ t.Fatalf("the job follows %v, not the exploration %s and its build %s", linked, id, build)
+ }
+ building, _ := jobStatus("building")
+ job := o.jobOf(request, "building", func(c wire.AssistantCard) bool { return c.State == wire.JobWorking && c.Result == building })
+ for _, e := range o.jobEvents(job.ID) {
+ if e.State == wire.JobDone {
+ t.Fatalf("the job said done while its build ran: %+v", e)
+ }
+ }
+ if got := o.status("xb-st", map[string]any{"request": request}); len(got) != 1 || !strings.Contains(got[0].Summary, equipo.RunnerCopy("assistant.team.stage."+wire.StageInProgress)) {
+ t.Fatalf("team_status %+v", got)
+ }
+ // Its build fails: the job's to push through.
+ o.step("xb-fail", wire.StepReport{TaskID: build, StepID: d.StepID, Attempt: 1, State: wire.StepFailed, Reason: "provider_failed", Termination: true})
+ o.noteFor("the failed note", failedStep(request, 2))
+ o.reply(o.turn)
+ u := o.message(wire.LaneAssistant)
+ o.in(u.TurnID, func() { nudged(t, o.teamNudge("xb-nudge", request, "mockups for the barber app"), request, 1) })
+ _, body := o.expect(wire.FrameDispatch)
+ if again := body.(*wire.DispatchCommand); again.TaskID != build || again.StepID != d.StepID || again.Attempt != 2 {
+ t.Fatalf("the retry's dispatch %+v", again)
+ }
+ o.reply(u.TurnID)
+ // team_cancel stops the build.
+ o.ask("Stop the barber app")
+ if res := o.use("xb-cancel", "team_cancel", map[string]any{"request": request}); res.IsError || res.Text != `{"cancelled":1,"still_running":0}` {
+ t.Fatalf("cancel %+v", res)
+ }
+ if n := o.rows("SELECT count(*) FROM chat_tasks WHERE id = ? AND (cancel_requested = 1 OR stage = ?)", build, wire.StageCancelled); n != 1 {
+ t.Fatalf("the build goes on after team_cancel: %+v", o.task(build))
+ }
+}
+
+// TestContractTeamJobStoppedBeforeWork (D5, D6, ruling P5j): a job whose
+// research waits for the person to approve its sources before any work
+// starts is stopped, as its note says, once the Assistant's team_update
+// about it ends, and not before; working again once they approve.
+func TestContractTeamJobStoppedBeforeWork(t *testing.T) {
+ o := newTeamRig(t)
+ o.in(o.own("Bring in research"), func() { o.researchOn() })
+ o.ask(personWords)
+ request, cmd := o.handoff("rb1", "Make mockups for the barber shop.", "")
+ var id string
+ o.in(cmd.TurnID, func() {
+ id = o.shopTask("rb")
+ if res := o.research("rb-r", id, "https://maps.example.org/place/barber-shop-on-main-street"); res.IsError {
+ t.Fatalf("research %+v", res)
+ }
+ })
+ o.reply(cmd.TurnID)
+ o.noteFor("the blocked note", blockedOn("they need to approve the research"))
+ o.reply(o.turn)
+ u := o.message(wire.LaneAssistant)
+ if u.Kind != wire.TurnTeamUpdate {
+ t.Fatalf("update frame %+v", u)
+ }
+ if now := o.jobOf(request, "the job card", nil); now.State != wire.JobWorking {
+ t.Fatalf("while the Assistant's turn runs %+v", now)
+ }
+ o.reply(u.TurnID)
+ stopped := o.jobOf(request, "stopped", func(c wire.AssistantCard) bool { return c.State == wire.JobStopped })
+ if status, detail := jobWords(wire.JobStopped); stopped.Result != status || stopped.Detail != detail {
+ t.Fatalf("stopped %+v", stopped)
+ }
+ card := o.jobCard(request, wire.CardResearchSources, id)
+ if _, err := o.client.Answer(o.ctx, card.ID, wire.ChoiceAllow, card.Revision); err != nil {
+ t.Fatal(err)
+ }
+ o.jobOf(request, "working once approved", func(c wire.AssistantCard) bool { return c.State == wire.JobWorking })
+}
+
+// TestContractTeamJobPreviewExpires: a preview that expires while its
+// go-ahead waits is offered no more, with nothing else changed: a fresh
+// snapshot drops "Try it" from the job card at once, and the minute's
+// tick moves the job card and its go-ahead, once each, so the stream
+// drops it too.
+func TestContractTeamJobPreviewExpires(t *testing.T) {
+ o := newTeamRig(t)
+ o.sitesOn(wire.ProtocolAssistant, false)
+ o.ask("Can we fix a bug in Tito? Login is broken")
+ request, cmd := o.handoff("pe1", "Login is broken", "")
+ base, cand := strings.Repeat("1", 40), strings.Repeat("2", 40)
+ var id string
+ o.in(cmd.TurnID, func() { id, _ = o.websiteReady("pe", "Quick website", base, cand, true) })
+ pv := o.previewDispatch(cand)
+ o.built("pe-pv-built", pv, digestA)
+ expires := time.Now().Add(time.Hour)
+ link := "https://eq-" + id + ".docs-t1.example.ts.net/"
+ o.previewDone("pe-pv-done", pv, wire.PreviewResult{Phase: wire.PreviewDone, App: "eq-" + id, URL: link, Digest: digestA, ExpiresAt: &expires, Outcome: wire.PreviewDeployed})
+ ready := o.jobOf(request, "ready to try", func(c wire.AssistantCard) bool { return c.State == wire.JobReady && len(c.Links) == 2 })
+ if !slices.Equal(ready.Links, []wire.CardLink{{Label: equipo.RunnerCopy("assistant.outcome.preview"), URL: link}, o.equipoLink(request)}) {
+ t.Fatalf("ready %+v", ready)
+ }
+ ahead := o.assistantCard("the go-ahead", func(c wire.AssistantCard) bool { return isMergeOutcome(c) && len(c.Links) == 1 })
+ jobs, aheads := len(o.jobEvents(ready.ID)), len(o.jobEvents(ahead.ID))
+ o.inst.Store.Chat().SetClock(func() time.Time { return time.Now().UTC().Add(2 * time.Hour) })
+ t.Cleanup(func() { o.inst.Store.Chat().SetClock(func() time.Time { return time.Now().UTC() }) })
+ if got := o.jobOf(request, "expired", nil); got.State != wire.JobReady || !slices.Equal(got.Links, []wire.CardLink{o.equipoLink(request)}) {
+ t.Fatalf("a fresh snapshot after the preview expired %+v", got)
+ }
+ for range 2 {
+ if err := o.inst.Store.Chat().HousekeepingTick(o.ctx); err != nil {
+ t.Fatal(err)
+ }
+ }
+ job, mirror := o.jobEvents(ready.ID), o.jobEvents(ahead.ID)
+ if len(job) != jobs+1 || job[len(job)-1].Revision <= ready.Revision || !slices.Equal(job[len(job)-1].Links, []wire.CardLink{o.equipoLink(request)}) {
+ t.Fatalf("job card events after the preview expired %+v (ready %+v)", job[jobs:], ready)
+ }
+ if len(mirror) != aheads+1 || mirror[len(mirror)-1].Revision <= ahead.Revision || len(mirror[len(mirror)-1].Links) != 0 || mirror[len(mirror)-1].State != wire.CardOpen {
+ t.Fatalf("go-ahead events after the preview expired %+v (was %+v)", mirror[aheads:], ahead)
+ }
+}
+
+// TestContractTeamJobSnapshotKeepsActiveJobs: an unfinished job and the
+// go-ahead open under it stay in the Assistant's snapshot however many
+// newer cards there are, oldest first as ever; a stopped job older than
+// the newest cards does not.
+func TestContractTeamJobSnapshotKeepsActiveJobs(t *testing.T) {
+ o := newTeamRig(t)
+ o.ask("Can we fix a bug in Tito? Login is broken")
+ request, cmd := o.handoff("sk1", "Login is broken", "")
+ base, cand := strings.Repeat("1", 40), strings.Repeat("2", 40)
+ o.in(cmd.TurnID, func() { o.websiteReady("sk", "Quick website", base, cand, false) })
+ job := o.jobOf(request, "ready", func(c wire.AssistantCard) bool { return c.State == wire.JobReady })
+ ahead := o.assistantCard("the go-ahead", isMergeOutcome)
+ cancelled, _ := o.handoff("sk2", "Can we fix a bug", "")
+ if res := o.use("sk-cancel", "team_cancel", map[string]any{"request": cancelled}); res.IsError {
+ t.Fatalf("cancel %+v", res)
+ }
+ stopped := o.jobOf(cancelled, "stopped", func(c wire.AssistantCard) bool { return c.State == wire.JobStopped })
+ newer := time.Now().UTC().Add(time.Minute)
+ for i := range wire.MaxProjectCards {
+ o.exec("INSERT INTO chat_cards(id, person, kind, state, question, options, links, choice, revision, created_at, updated_at, held, lane) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)",
+ "c_newer"+itoa(i), Owner, wire.CardQuestion, wire.CardAnswered, "Which one?", "[]", "[]", "This one", 2, newer.Add(time.Duration(i)*time.Second), newer, false, wire.LaneAssistant)
+ }
+ snap, err := o.a.Snapshot(o.ctx)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if n := len(snap.Cards); n != wire.MaxProjectCards+2 || snap.Cards[0].ID != job.ID || snap.Cards[1].ID != ahead.ID || snap.Cards[n-1].ID != "c_newer"+itoa(wire.MaxProjectCards-1) {
+ t.Fatalf("%d cards, the first %+v %+v; the job %s and its go-ahead %s", n, snap.Cards[0], snap.Cards[1], job.ID, ahead.ID)
+ }
+ if slices.ContainsFunc(snap.Cards, func(c wire.AssistantCard) bool { return c.ID == stopped.ID }) {
+ t.Fatalf("a stopped job beyond the newest cards %+v", stopped)
+ }
+}
+
+// statusPage is one team_status answer: its requests, each with its
+// question, and where the next page starts ("" on the last).
+type statusPage struct {
+ Requests []struct {
+ Request string `json:"request"`
+ Question *struct {
+ Text string `json:"text"`
+ } `json:"question"`
+ } `json:"requests"`
+ Next string `json:"next"`
+}
+
+// TestContractTeamElevenQuestions (D8): with eleven jobs asking, the
+// person's next message carries the newest ten questions and says one
+// more is open and how to read it; team_status reads every open
+// request, ten at a time, each question with its request id, the next
+// page after the last one's cursor.
+func TestContractTeamElevenQuestions(t *testing.T) {
+ o := newTeamRig(t)
+ words := make([]string, 11)
+ for i := range words {
+ words[i] = fmt.Sprintf("job number %02d", i+1)
+ }
+ o.ask(strings.Join(words, ", "))
+ asked := map[string]string{}
+ var requests []string
+ for i, w := range words {
+ request, cmd := o.handoff("eq"+itoa(i), w, "")
+ requests = append(requests, request)
+ asked[request] = "Which page for " + w + "?"
+ o.in(cmd.TurnID, func() {
+ if res := o.call("eq-ask"+itoa(i), wire.ToolAskPerson, map[string]any{"question": asked[request]}); res.Code != "asked" {
+ t.Fatalf("ask %+v", res)
+ }
+ })
+ }
+ page := func(key string, in map[string]any) statusPage {
+ t.Helper()
+ res := o.use(key, "team_status", in)
+ var out statusPage
+ if res.IsError || json.Unmarshal([]byte(res.Text), &out) != nil {
+ t.Fatalf("team_status %+v", res)
+ }
+ return out
+ }
+ first := page("eq-st1", map[string]any{})
+ second := page("eq-st2", map[string]any{"after": first.Next})
+ if len(first.Requests) != 10 || first.Next != first.Requests[9].Request || len(second.Requests) != 1 || second.Next != "" {
+ t.Fatalf("pages %+v then %+v", first, second)
+ }
+ seen := map[string]bool{}
+ for _, r := range append(first.Requests, second.Requests...) {
+ if r.Question == nil || r.Question.Text != asked[r.Request] || seen[r.Request] {
+ t.Fatalf("request %s with %+v", r.Request, r.Question)
+ }
+ seen[r.Request] = true
+ }
+ if second.Requests[0].Request != requests[0] {
+ t.Fatalf("the second page %+v, not the oldest %s", second, requests[0])
+ }
+ if res := o.use("eq-st3", "team_status", map[string]any{"after": "h_nosuchrequest"}); !res.IsError || res.Code != "not_found" {
+ t.Fatalf("after an unknown request %+v", res)
+ }
+ // Every team_update told, the person's next message carries the
+ // newest ten and the count of the rest.
+ o.reply(o.turn)
+ for range words {
+ u := o.message(wire.LaneAssistant)
+ if u.Kind != wire.TurnTeamUpdate {
+ t.Fatalf("update frame %+v", u)
+ }
+ o.reply(u.TurnID)
+ }
+ sent, err := o.a.Send(o.ctx, "Which one first?", "eq-next")
+ if err != nil {
+ t.Fatal(err)
+ }
+ cmd := o.message(wire.LaneAssistant)
+ if cmd.TurnID != sent.Turn.ID || strings.Count(cmd.Text, "\n- Job ") != 10 || strings.Contains(cmd.Text, requests[0]) || !strings.Contains(cmd.Text, "\n1 more job has an open question not listed here: team_status lists every open request with its question, ten at a time (pass its next as after to read on).\n") {
+ t.Fatalf("the person's next frame %q", cmd.Text)
+ }
+}