oficina / equipo Public

instance: ask the implementer, one question of a task at a time

The task's creator asks the newest Engineering step, or Review when
the question addresses it or they choose it; teammates read. The
question, its event and the ask command are one transaction, and the
next question of the task goes only when the one with the runner ends.
Answers stream to every member like a chat reply; forward-only answer
reports from the step person's primary runner; cancel through the
runner; a sync that no longer holds an acked question fails it; a task
that ends stops its questions and tells the runner to forget its kept
sessions. read_task leaves the questions out. Migration 0045.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev 0bc2cddbaffd8d0305ac03b487494b24a36e53f5 parent a0be7c3
11 files changed, +979 −6
  • internal/equipo/chat/http.go +41 −0
  • internal/equipo/chat/models.go +1 −1
  • internal/equipo/chat/questions.go +512 −0
  • internal/equipo/chat/runner.go +8 −0
  • internal/equipo/chat/stream.go +1 −1
  • internal/equipo/chat/tasks.go +24 −3
  • internal/equipo/chat/tools.go +3 −0
  • internal/equipo/migrations/0045_thin_questions.sql +4 −0
  • internal/equipo/migrations/schema.sql +4 −1
  • internal/thintest/client.go +42 −0
  • internal/thintest/questions_contract_test.go +339 −0
diff --git a/internal/equipo/chat/http.go b/internal/equipo/chat/http.go
index 530f000a..8601a740 100644
--- a/internal/equipo/chat/http.go
+++ b/internal/equipo/chat/http.go
@@ -73,6 +73,9 @@ func (h *HTTP) Mount(r chi.Router) {
r.Post("/tasks/{id}/retry", h.bearer(h.retryTask))
r.Post("/tasks/{id}/thread", h.bearer(h.postThread))
r.Get("/steps/{id}/log", h.bearer(h.stepLog))
+ r.Post("/tasks/{id}/questions", h.bearer(h.ask))
+ r.Get("/questions/{id}", h.bearer(h.question))
+ r.Post("/questions/{id}/cancel", h.bearer(h.cancelQuestion))
r.Get("/needs-you", h.thinOr("GET /needs-you", deviceClient, h.bearer(h.needsYou)))
r.Get("/events", h.events)
}
@@ -122,6 +125,8 @@ func (h *HTTP) fail(w http.ResponseWriter, r *http.Request, err error) {
personapi.WriteError(w, r, 409, "task_ended", nil)
case errors.Is(err, ErrNotRetryable):
personapi.WriteError(w, r, 409, "not_retryable", nil)
+ case errors.Is(err, ErrNotAskable):
+ personapi.WriteError(w, r, 409, "not_askable", nil)
default:
h.Failure(w, r, err)
}
@@ -462,3 +467,39 @@ func (h *HTTP) stepLog(w http.ResponseWriter, r *http.Request, p personapi.Perso
}
writeJSON(w, 200, out)
}
+
+func (h *HTTP) ask(w http.ResponseWriter, r *http.Request, p personapi.PersonPrincipal) {
+ var in wire.AskQuestion
+ if err := readJSON(r, &in); err != nil {
+ h.fail(w, r, err)
+ return
+ }
+ out, err := h.Store.Ask(r.Context(), p.Address, chi.URLParam(r, "id"), in)
+ if err != nil {
+ h.fail(w, r, err)
+ return
+ }
+ writeJSON(w, http.StatusAccepted, out)
+}
+
+func (h *HTTP) question(w http.ResponseWriter, r *http.Request, p personapi.PersonPrincipal) {
+ out, err := h.Store.Question(r.Context(), p.Address, chi.URLParam(r, "id"))
+ if err != nil {
+ h.fail(w, r, err)
+ return
+ }
+ writeJSON(w, 200, out)
+}
+
+func (h *HTTP) cancelQuestion(w http.ResponseWriter, r *http.Request, p personapi.PersonPrincipal) {
+ attempt, err := h.Store.CancelQuestion(r.Context(), p.Address, chi.URLParam(r, "id"))
+ if errors.Is(err, ErrTerminal) {
+ personapi.WriteError(w, r, http.StatusConflict, "question_ended", nil)
+ return
+ }
+ if err != nil {
+ h.fail(w, r, err)
+ return
+ }
+ writeJSON(w, http.StatusAccepted, wire.TaskAccepted{Attempt: attempt})
+}
diff --git a/internal/equipo/chat/models.go b/internal/equipo/chat/models.go
index b03274ac..4f410749 100644
--- a/internal/equipo/chat/models.go
+++ b/internal/equipo/chat/models.go
@@ -7,7 +7,7 @@ package chat
import "time"
// Models are the tables this package owns, for the migration check.
-var Models = []any{&turnRecord{}, &messageRecord{}, &eventRecord{}, &commandRecord{}, &inboxRecord{}, &runnerSessionRecord{}, &projectRecord{}, &cardRecord{}, &toolCallRecord{}, &settingRecord{}, &coordinatorRecord{}, &notebookRecord{}, &taskRecord{}, &stepRecord{}, &entryRecord{}, &attachmentRecord{}}
+var Models = []any{&turnRecord{}, &messageRecord{}, &eventRecord{}, &commandRecord{}, &inboxRecord{}, &runnerSessionRecord{}, &projectRecord{}, &cardRecord{}, &toolCallRecord{}, &settingRecord{}, &coordinatorRecord{}, &notebookRecord{}, &taskRecord{}, &stepRecord{}, &entryRecord{}, &attachmentRecord{}, &questionRecord{}}
type turnRecord struct {
ID string `gorm:"primaryKey"`
diff --git a/internal/equipo/chat/questions.go b/internal/equipo/chat/questions.go
new file mode 100644
index 00000000..a34f7198
--- /dev/null
+++ b/internal/equipo/chat/questions.go
@@ -0,0 +1,512 @@
+package chat
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "strings"
+ "time"
+ "unicode/utf8"
+
+ "amadan.net/oficina/equipo/internal/wire"
+ "gorm.io/gorm"
+)
+
+// Asking the implementer: a task's creator asks the specialist that did
+// the work, and the runner resumes that step's own session read-only.
+// Questions are team records like their task: every active member sees
+// them and their streamed answers; only the creator asks or cancels. One
+// question of a task is with the runner at a time; the runner runs it
+// only between steps, never beside a step that writes.
+
+// ErrNotAskable means no step of the task has a session kept to ask.
+var ErrNotAskable = errors.New("chat: no step to ask")
+
+// questionRecord is one question and its answer.
+type questionRecord struct {
+ ID string `gorm:"primaryKey"`
+ TaskID string `gorm:"index:chat_question_task;uniqueIndex:chat_question_key,priority:1"`
+ Asker string `gorm:"uniqueIndex:chat_question_key,priority:2"`
+ IdempotencyKey string `gorm:"uniqueIndex:chat_question_key,priority:3"`
+ StepID string
+ Specialist string
+ // Chosen is the specialist the person chose ("" when Equipo chose),
+ // kept for the idempotency comparison.
+ Chosen string
+ Text string
+ State string
+ Reason string
+ Attempt int64
+ Dispatched bool
+ Answer string
+ Timing string
+ Revision int64
+ CreatedAt time.Time
+ UpdatedAt time.Time
+}
+
+func (questionRecord) TableName() string { return "chat_questions" }
+
+func questionView(q questionRecord) wire.Question {
+ v := wire.Question{ID: q.ID, Revision: q.Revision, TaskID: q.TaskID, StepID: q.StepID, Specialist: q.Specialist, Asker: q.Asker, Text: q.Text, State: q.State, Reason: q.Reason, Attempt: q.Attempt, Answer: q.Answer, CreatedAt: q.CreatedAt, UpdatedAt: q.UpdatedAt}
+ if q.Timing != "" && q.State == wire.QuestionAnswered {
+ v.Timing = &wire.TurnTiming{}
+ if json.Unmarshal([]byte(q.Timing), v.Timing) != nil {
+ v.Timing = nil
+ }
+ }
+ return v
+}
+
+func (t *txn) questions(taskID string) ([]wire.Question, error) {
+ var rows []questionRecord
+ if err := t.db.Where("task_id = ?", taskID).Order("created_at, id").Find(&rows).Error; err != nil {
+ return nil, err
+ }
+ out := make([]wire.Question, 0, len(rows))
+ for _, q := range rows {
+ out = append(out, questionView(q))
+ }
+ return out, nil
+}
+
+// saveQuestion bumps the question's revision and tells every member.
+func (t *txn) saveQuestion(q *questionRecord) error {
+ q.Revision++
+ q.UpdatedAt = t.now()
+ if err := t.db.Model(&questionRecord{}).Where("id = ?", q.ID).Select("step_id", "specialist", "state", "reason", "attempt", "dispatched", "answer", "timing", "revision", "updated_at").Updates(q).Error; err != nil {
+ return err
+ }
+ return t.questionEvent(*q)
+}
+
+func (t *txn) questionEvent(q questionRecord) error {
+ members, err := t.members()
+ if err != nil {
+ return err
+ }
+ v := questionView(q)
+ for _, m := range members {
+ if err := t.event(m, wire.EventQuestion, wire.ResourceQuestion, q.ID, q.Revision, "", "", q.Attempt, v); err != nil {
+ return err
+ }
+ }
+ return nil
+}
+
+// askTarget is the step a question goes to: the newest askable step of
+// the specialist the person chose, or, when they did not, Review if the
+// question addresses it and it can answer, else Engineering.
+func askTarget(steps []stepRecord, chosen, text string) (stepRecord, bool) {
+ newest := func(specialist string) (stepRecord, bool) {
+ for i := len(steps) - 1; i >= 0; i-- {
+ if s := steps[i]; s.Specialist == specialist && s.Askable && s.State == wire.StepDone {
+ return s, true
+ }
+ }
+ return stepRecord{}, false
+ }
+ switch chosen {
+ case wire.SpecialistEngineering, wire.SpecialistReview:
+ return newest(chosen)
+ }
+ if wire.AddressesReview(text) {
+ if s, ok := newest(wire.SpecialistReview); ok {
+ return s, true
+ }
+ }
+ return newest(wire.SpecialistEngineering)
+}
+
+// Ask is POST /tasks/{id}/questions: the task's creator asks one of its
+// specialists. The question, its event and (when no other question of
+// the task is with the runner) the ask command are one transaction.
+func (s *Store) Ask(ctx context.Context, person, taskID string, in wire.AskQuestion) (out wire.Question, err error) {
+ text, ok := cleanText(in.Text, wire.MaxQuestionText)
+ if !ok || in.IdempotencyKey == "" || len(in.IdempotencyKey) > 128 || !utf8.ValidString(in.IdempotencyKey) {
+ return out, ErrInvalid
+ }
+ switch in.Specialist {
+ case "", wire.SpecialistEngineering, wire.SpecialistReview:
+ default:
+ return out, ErrInvalid
+ }
+ err = s.tx(ctx, func(t *txn) error {
+ if err := s.authority.CurrentPerson(ctx, t.db); err != nil {
+ return err
+ }
+ k, err := t.loadTask(taskID)
+ if err != nil {
+ return err
+ }
+ // Only the person who asked for the task asks its specialists,
+ // on their own runner; teammates read the thread.
+ if k.Creator != person {
+ return ErrForbidden
+ }
+ if err := t.isOwner(person); err != nil {
+ return err
+ }
+ var prior questionRecord
+ if err := t.db.Where("task_id = ? AND asker = ? AND idempotency_key = ?", k.ID, person, in.IdempotencyKey).First(&prior).Error; err == nil {
+ if prior.Text != text || prior.Chosen != in.Specialist {
+ return ErrConflict
+ }
+ out = questionView(prior)
+ return nil
+ } else if !errors.Is(err, gorm.ErrRecordNotFound) {
+ return err
+ }
+ if wire.FinalStage(k.Stage) || k.CancelRequested {
+ return ErrTaskEnded
+ }
+ steps, err := t.steps(k.ID)
+ if err != nil {
+ return err
+ }
+ target, ok := askTarget(steps, in.Specialist, text)
+ if !ok || target.Person != person {
+ return ErrNotAskable
+ }
+ var n int64
+ if err := t.db.Model(&questionRecord{}).Where("task_id = ?", k.ID).Count(&n).Error; err != nil {
+ return err
+ }
+ if n >= wire.MaxQuestions {
+ return ErrInvalid
+ }
+ now := t.now()
+ q := questionRecord{ID: newID("q_"), TaskID: k.ID, Asker: person, IdempotencyKey: in.IdempotencyKey, StepID: target.ID, Specialist: target.Specialist, Chosen: in.Specialist, Text: text, State: wire.QuestionQueued, Attempt: 1, Revision: 1, CreatedAt: now, UpdatedAt: now}
+ if err := t.db.Create(&q).Error; err != nil {
+ return err
+ }
+ if err := t.questionEvent(q); err != nil {
+ return err
+ }
+ if err := t.nextQuestion(k); err != nil {
+ return err
+ }
+ if err := t.db.Where("id = ?", q.ID).First(&q).Error; err != nil {
+ return err
+ }
+ out = questionView(q)
+ return nil
+ })
+ return out, err
+}
+
+// nextQuestion sends the task's oldest waiting question to the runner,
+// unless one is already there.
+func (t *txn) nextQuestion(k taskRecord) error {
+ if wire.FinalStage(k.Stage) || k.CancelRequested {
+ return nil
+ }
+ var open int64
+ if err := t.db.Model(&questionRecord{}).Where("task_id = ? AND dispatched = ? AND state IN ?", k.ID, true, []string{wire.QuestionQueued, wire.QuestionRunning}).Count(&open).Error; err != nil {
+ return err
+ }
+ if open > 0 {
+ return nil
+ }
+ var q questionRecord
+ err := t.db.Where("task_id = ? AND state = ? AND dispatched = ?", k.ID, wire.QuestionQueued, false).Order("created_at, id").First(&q).Error
+ if errors.Is(err, gorm.ErrRecordNotFound) {
+ return nil
+ }
+ if err != nil {
+ return err
+ }
+ var s stepRecord
+ if err := t.db.Where("id = ?", q.StepID).First(&s).Error; err != nil {
+ return err
+ }
+ var p projectRecord
+ if err := t.db.Where("id = ?", k.ProjectID).First(&p).Error; err != nil {
+ return err
+ }
+ base := k.BaseSHA
+ if s.BaseSHA != "" && s.Specialist == wire.SpecialistEngineering {
+ base = s.BaseSHA
+ }
+ cmd := wire.AskCommand{Person: s.Person, TaskID: k.ID, StepID: s.ID, QuestionID: q.ID, Attempt: q.Attempt, Specialist: s.Specialist, Repo: p.Repo, Branch: k.Branch, BaseSHA: base, CandidateSHA: s.CandidateSHA, Title: k.Title, Text: q.Text}
+ if err := t.command(s.Person, wire.FrameAsk, cmd); err != nil {
+ return err
+ }
+ q.Dispatched = true
+ return t.saveQuestion(&q)
+}
+
+// Question reads one question.
+func (s *Store) Question(ctx context.Context, person, id string) (out wire.Question, err error) {
+ err = s.read(ctx, func(tx *gorm.DB) error {
+ if err := s.authority.CurrentPerson(ctx, tx); err != nil {
+ return err
+ }
+ var q questionRecord
+ if err := tx.Where("id = ?", id).First(&q).Error; errors.Is(err, gorm.ErrRecordNotFound) {
+ return ErrNotFound
+ } else if err != nil {
+ return err
+ }
+ out = questionView(q)
+ return nil
+ })
+ return out, err
+}
+
+// CancelQuestion is POST /questions/{id}/cancel: the asker stops it. One
+// still waiting ends at once; one with the runner ends when the runner
+// reports the attempt stopped.
+func (s *Store) CancelQuestion(ctx context.Context, person, id string) (attempt int64, err error) {
+ err = s.tx(ctx, func(t *txn) error {
+ if err := s.authority.CurrentPerson(ctx, t.db); err != nil {
+ return err
+ }
+ var q questionRecord
+ if err := t.db.Where("id = ?", id).First(&q).Error; errors.Is(err, gorm.ErrRecordNotFound) {
+ return ErrNotFound
+ } else if err != nil {
+ return err
+ }
+ if q.Asker != person {
+ return ErrForbidden
+ }
+ if wire.QuestionTerminal(q.State) {
+ return ErrTerminal
+ }
+ attempt = q.Attempt
+ return t.stopQuestion(&q, "cancelled")
+ })
+ return attempt, err
+}
+
+// stopQuestion cancels a question: at once when the runner never had it,
+// else by asking the runner (once).
+func (t *txn) stopQuestion(q *questionRecord, reason string) error {
+ if !q.Dispatched {
+ q.State, q.Reason = wire.QuestionCancelled, reason
+ return t.saveQuestion(q)
+ }
+ var s stepRecord
+ if err := t.db.Where("id = ?", q.StepID).First(&s).Error; err != nil {
+ return err
+ }
+ return t.command(s.Person, wire.FrameCancelAsk, wire.CancelAskCommand{Person: s.Person, TaskID: q.TaskID, QuestionID: q.ID, Attempt: q.Attempt})
+}
+
+// ownQuestion loads a question for a runner frame: only the step's
+// person's primary runner may move it.
+func (t *txn) ownQuestion(l Lease, id string) (questionRecord, error) {
+ var q questionRecord
+ if err := t.db.Where("id = ?", id).First(&q).Error; errors.Is(err, gorm.ErrRecordNotFound) {
+ return q, ErrNotFound
+ } else if err != nil {
+ return q, err
+ }
+ var s stepRecord
+ if err := t.db.Where("id = ?", q.StepID).First(&s).Error; err != nil {
+ return q, err
+ }
+ if s.Person != l.Runner.Person {
+ return q, ErrNotFound
+ }
+ primary, err := t.s.authority.PrimaryRunner(t.db, s.Person)
+ if err != nil {
+ return q, err
+ }
+ if primary != l.Runner.RunnerID {
+ return q, ErrForbidden
+ }
+ return q, nil
+}
+
+func isQuestionID(id string) bool { return strings.HasPrefix(id, "q_") }
+
+// questionDelta streams answer text to every member, like a turn's.
+func (t *txn) questionDelta(l Lease, d *wire.DeltaReport) error {
+ q, err := t.ownQuestion(l, d.TurnID)
+ if errors.Is(err, ErrNotFound) {
+ return nil
+ }
+ if err != nil {
+ return err
+ }
+ if wire.QuestionTerminal(q.State) || d.Attempt != q.Attempt || d.Offset < 0 || d.Text == "" || len(d.Text) > wire.MaxMessageBytes {
+ return nil
+ }
+ members, err := t.members()
+ if err != nil {
+ return err
+ }
+ for _, m := range members {
+ if err := t.event(m, wire.EventDelta, wire.ResourceQuestion, q.ID, 0, q.ID, "", q.Attempt, wire.Delta{TurnID: q.ID, Offset: d.Offset, Text: d.Text}); err != nil {
+ return err
+ }
+ }
+ return nil
+}
+
+// questionTools are the activities an answering session may show: it
+// reads the code or looks at the change, or thinks.
+var questionTools = map[string]bool{wire.ToolReadFile: true, wire.ToolSearchCode: true, ToolReadChange: true}
+
+// ToolReadChange is the activity of an answering session's read-only git
+// tools (git_log, git_diff, git_show).
+const ToolReadChange = "read_change"
+
+func (t *txn) questionActivity(l Lease, a *wire.ActivityReport) error {
+ q, err := t.ownQuestion(l, a.TurnID)
+ if errors.Is(err, ErrNotFound) {
+ return nil
+ }
+ if err != nil {
+ return err
+ }
+ if wire.QuestionTerminal(q.State) || a.Attempt != q.Attempt {
+ return nil
+ }
+ tool := ""
+ switch a.Kind {
+ case wire.ActivityThink:
+ case wire.ActivityTool:
+ tool = "other"
+ if questionTools[a.Tool] {
+ tool = a.Tool
+ }
+ default:
+ return nil
+ }
+ v := wire.Activity{TurnID: q.ID, Attempt: q.Attempt, Kind: a.Kind, Tool: tool}
+ if t.s.authority.ActivityLabel != nil {
+ v.Label = t.s.authority.ActivityLabel(v, wire.ResourceQuestion)
+ }
+ members, err := t.members()
+ if err != nil {
+ return err
+ }
+ for _, m := range members {
+ if err := t.event(m, wire.EventActivity, wire.ResourceQuestion, q.ID, 0, q.ID, "", q.Attempt, v); err != nil {
+ return err
+ }
+ }
+ return nil
+}
+
+// answer applies the runner's report on a question: only the current
+// attempt, only forward; an ended question lets the task's next one go.
+func (t *txn) answer(l Lease, v *wire.AnswerReport) error {
+ if !wire.AnswerReasons[v.Reason] {
+ return ErrInvalid
+ }
+ q, err := t.ownQuestion(l, v.QuestionID)
+ if err != nil {
+ return err
+ }
+ if q.TaskID != v.TaskID {
+ return ErrNotFound
+ }
+ if wire.QuestionTerminal(q.State) || v.Attempt != q.Attempt {
+ return nil
+ }
+ switch v.State {
+ case wire.QuestionRunning:
+ if q.State == wire.QuestionRunning {
+ return nil
+ }
+ q.State = wire.QuestionRunning
+ return t.saveQuestion(&q)
+ case wire.QuestionAnswered:
+ answer := strings.TrimSpace(v.Text)
+ if answer == "" {
+ q.State, q.Reason = wire.QuestionFailed, "provider_failed"
+ break
+ }
+ q.State, q.Reason, q.Answer = wire.QuestionAnswered, "", clipText(answer, wire.MaxAnswerText)
+ if v.Timing != nil {
+ raw, _ := json.Marshal(v.Timing)
+ q.Timing = string(raw)
+ }
+ case wire.QuestionFailed, wire.QuestionCancelled:
+ q.State, q.Reason = v.State, firstSet(v.Reason, v.State)
+ default:
+ return ErrInvalid
+ }
+ if err := t.saveQuestion(&q); err != nil {
+ return err
+ }
+ k, err := t.loadTask(q.TaskID)
+ if err != nil {
+ return err
+ }
+ return t.nextQuestion(k)
+}
+
+// syncQuestions settles questions the person's runner no longer holds,
+// like syncSteps: a question whose ask command was acked but which the
+// runner does not list has ended without an answer.
+func (t *txn) syncQuestions(l Lease, held []wire.AskRun) error {
+ have := map[string]bool{}
+ for _, h := range held {
+ have[h.QuestionID+"/"+itoa64(h.Attempt)] = true
+ }
+ var rows []questionRecord
+ if err := t.db.Where("dispatched = ? AND state IN ?", true, []string{wire.QuestionQueued, wire.QuestionRunning}).Find(&rows).Error; err != nil {
+ return err
+ }
+ for i := range rows {
+ q := rows[i]
+ if have[q.ID+"/"+itoa64(q.Attempt)] {
+ continue
+ }
+ var s stepRecord
+ if err := t.db.Where("id = ?", q.StepID).First(&s).Error; err != nil {
+ return err
+ }
+ if s.Person != l.Runner.Person {
+ continue
+ }
+ var unacked int64
+ if err := t.db.Model(&commandRecord{}).Where("person = ? AND kind = ? AND acked_at IS NULL AND body LIKE ?", s.Person, wire.FrameAsk, `%"question_id":"`+q.ID+`","attempt":`+itoa64(q.Attempt)+`,%`).Count(&unacked).Error; err != nil {
+ return err
+ }
+ if unacked != 0 {
+ continue
+ }
+ q.State, q.Reason = wire.QuestionFailed, "interrupted"
+ if err := t.saveQuestion(&q); err != nil {
+ return err
+ }
+ k, err := t.loadTask(q.TaskID)
+ if err != nil {
+ return err
+ }
+ if err := t.nextQuestion(k); err != nil {
+ return err
+ }
+ }
+ return nil
+}
+
+// taskEnded runs once when a task becomes done or cancelled: its open
+// questions stop, and the runner may delete the sessions it kept.
+func (t *txn) taskEnded(k taskRecord) error {
+ var open []questionRecord
+ if err := t.db.Where("task_id = ? AND state IN ?", k.ID, []string{wire.QuestionQueued, wire.QuestionRunning}).Find(&open).Error; err != nil {
+ return err
+ }
+ for i := range open {
+ if err := t.stopQuestion(&open[i], "task_ended"); err != nil {
+ return err
+ }
+ }
+ var persons []string
+ if err := t.db.Model(&stepRecord{}).Distinct("person").Where("task_id = ?", k.ID).Pluck("person", &persons).Error; err != nil {
+ return err
+ }
+ for _, p := range persons {
+ if err := t.command(p, wire.FrameForgetTask, wire.ForgetTaskCommand{Person: p, TaskID: k.ID}); err != nil {
+ return err
+ }
+ }
+ return nil
+}
diff --git a/internal/equipo/chat/runner.go b/internal/equipo/chat/runner.go
index 5be6ceec..2469ed52 100644
--- a/internal/equipo/chat/runner.go
+++ b/internal/equipo/chat/runner.go
@@ -216,6 +216,8 @@ func (s *Store) Apply(ctx context.Context, l Lease, f wire.Frame, body any) erro
return t.stepReport(l, v)
case *wire.MergedReport:
return t.merged(l, v)
+ case *wire.AnswerReport:
+ return t.answer(l, v)
}
return ErrInvalid
})
@@ -276,6 +278,9 @@ func (t *txn) ack(l Lease, id string) error {
}
func (t *txn) delta(l Lease, d *wire.DeltaReport) error {
+ if isQuestionID(d.TurnID) {
+ return t.questionDelta(l, d)
+ }
r, err := t.ownTurn(l, d.TurnID)
if errors.Is(err, ErrNotFound) {
return nil
@@ -380,6 +385,9 @@ func (t *txn) sync(l Lease, v *wire.Sync) error {
if err := t.syncSteps(l, v.Steps); err != nil {
return err
}
+ if err := t.syncQuestions(l, v.Asks); err != nil {
+ return err
+ }
if err := t.advanceAll(l.Runner.Person); err != nil {
return err
}
diff --git a/internal/equipo/chat/stream.go b/internal/equipo/chat/stream.go
index a2b4dd41..2894fb8e 100644
--- a/internal/equipo/chat/stream.go
+++ b/internal/equipo/chat/stream.go
@@ -153,7 +153,7 @@ func (rc *runnerConn) read(ctx context.Context) websocket.StatusCode {
switch v := body.(type) {
case *wire.Hello:
err = store.Heartbeat(ctx, rc.lease, *v)
- case *wire.Sync, *wire.Ack, *wire.DeltaReport, *wire.Reply, *wire.TurnReport, *wire.ToolCall, *wire.ActivityReport, *wire.MoveIn, *wire.NotebookReport, *wire.StepReport, *wire.MergedReport:
+ case *wire.Sync, *wire.Ack, *wire.DeltaReport, *wire.Reply, *wire.TurnReport, *wire.ToolCall, *wire.ActivityReport, *wire.MoveIn, *wire.NotebookReport, *wire.StepReport, *wire.MergedReport, *wire.AnswerReport:
err = store.Apply(ctx, rc.lease, f, body)
case *wire.LeaseCheck:
// Answered only while this connection holds the lease.
diff --git a/internal/equipo/chat/tasks.go b/internal/equipo/chat/tasks.go
index bc83cc7d..4e0dafef 100644
--- a/internal/equipo/chat/tasks.go
+++ b/internal/equipo/chat/tasks.go
@@ -84,6 +84,8 @@ type stepRecord struct {
// running the specialist.
Republish bool
FromAttempt int64
+ // Askable: the runner kept the step's session, so it can be asked.
+ Askable bool
}
func (stepRecord) TableName() string { return "chat_steps" }
@@ -236,7 +238,7 @@ func (t *txn) latestStep(taskID string) (stepRecord, bool, error) {
func stepView(s stepRecord) wire.Step {
return wire.Step{ID: s.ID, Revision: s.Revision, TaskID: s.TaskID, Index: s.Idx, Specialist: s.Specialist, State: s.State, Reason: s.Reason, Attempt: s.Attempt, BaseSHA: s.BaseSHA, CandidateSHA: s.CandidateSHA, Pushed: s.Pushed, Terminated: s.Terminated, Summary: s.Summary, LogTail: s.LogTail, StartedAt: s.StartedAt, FinishedAt: s.FinishedAt,
- Round: s.Round, Family: s.Family, Account: s.Account, Verdict: s.Verdict, ReviewLabel: s.ReviewLabel, Findings: decodeFindings(s.Findings), Checks: s.Checks, Gate: s.Gate, ExitCode: s.ExitCode}
+ Round: s.Round, Family: s.Family, Account: s.Account, Verdict: s.Verdict, ReviewLabel: s.ReviewLabel, Findings: decodeFindings(s.Findings), Checks: s.Checks, Gate: s.Gate, ExitCode: s.ExitCode, Askable: s.Askable}
}
// taskView is the task with its project, findings, steps and thread.
@@ -278,6 +280,11 @@ func (t *txn) taskView(k taskRecord) (wire.Task, error) {
if pr.eng != nil {
v.FixRounds = pr.eng.Round
}
+ qs, err := t.questions(k.ID)
+ if err != nil {
+ return v, err
+ }
+ v.Questions = qs
return v, nil
}
@@ -290,11 +297,20 @@ func (t *txn) members() ([]string, error) {
// saveTask bumps the task's revision and tells every active member.
func (t *txn) saveTask(k *taskRecord) error {
+ var before string
+ if err := t.db.Model(&taskRecord{}).Where("id = ?", k.ID).Pluck("stage", &before).Error; err != nil {
+ return err
+ }
k.Revision++
k.UpdatedAt = t.now()
if err := t.db.Model(&taskRecord{}).Where("id = ?", k.ID).Select("stage", "base_sha", "cancel_requested", "revision", "updated_at").Updates(k).Error; err != nil {
return err
}
+ if wire.FinalStage(k.Stage) && !wire.FinalStage(before) {
+ if err := t.taskEnded(*k); err != nil {
+ return err
+ }
+ }
return t.taskEvent(*k)
}
@@ -320,7 +336,7 @@ func (t *txn) taskEvent(k taskRecord) error {
func (t *txn) saveStep(s *stepRecord, k *taskRecord) error {
s.Revision++
s.UpdatedAt = t.now()
- if err := t.db.Model(&stepRecord{}).Where("id = ?", s.ID).Select("state", "reason", "attempt", "base_sha", "candidate_sha", "pushed", "terminated", "summary", "log_tail", "started_at", "finished_at", "revision", "updated_at", "family", "account", "verdict", "review_label", "findings", "checks", "gate", "exit_code", "output", "republish", "from_attempt").Updates(s).Error; err != nil {
+ if err := t.db.Model(&stepRecord{}).Where("id = ?", s.ID).Select("state", "reason", "attempt", "base_sha", "candidate_sha", "pushed", "terminated", "summary", "log_tail", "started_at", "finished_at", "revision", "updated_at", "family", "account", "verdict", "review_label", "findings", "checks", "gate", "exit_code", "output", "republish", "from_attempt", "askable").Updates(s).Error; err != nil {
return err
}
members, err := t.members()
@@ -553,6 +569,9 @@ func (t *txn) readTask(id string) (wire.ToolResult, error) {
for i := range v.Steps {
v.Steps[i].LogTail = clipText(v.Steps[i].LogTail, 1000)
}
+ // The questions and answers are the person's with the specialists;
+ // the coordinator points people there and never relays them.
+ v.Questions = []wire.Question{}
raw, _ := json.Marshal(struct {
Link string `json:"link"`
wire.Task
@@ -664,6 +683,7 @@ func (t *txn) stepReport(l Lease, v *wire.StepReport) error {
return nil
}
s.Pushed = true
+ s.Askable = v.Askable
default:
// A judgement counts only for the SHA it was asked to judge.
if !judgement(s.Specialist, v) || v.CandidateSHA != s.CandidateSHA || !v.Termination {
@@ -681,6 +701,7 @@ func (t *txn) stepReport(l Lease, v *wire.StepReport) error {
}
raw, _ := json.Marshal(found)
s.Findings = string(raw)
+ s.Askable = v.Askable && s.Specialist == wire.SpecialistReview
}
s.State, s.Terminated, s.FinishedAt, changed = wire.StepDone, v.Termination, &now, true
default:
@@ -914,7 +935,7 @@ func (s *Store) RetryTask(ctx context.Context, person, id string) (attempt int64
}
st.Republish = republish
st.State, st.Reason, st.Pushed, st.Terminated, st.Summary, st.LogTail, st.StartedAt, st.FinishedAt = wire.StepQueued, "", false, false, "", "", nil, nil
- st.Verdict, st.ReviewLabel, st.Findings, st.Checks, st.Gate, st.ExitCode, st.Output = "", "", "", "", "", nil, ""
+ st.Verdict, st.ReviewLabel, st.Findings, st.Checks, st.Gate, st.ExitCode, st.Output, st.Askable = "", "", "", "", "", nil, "", false
if st.Specialist == wire.SpecialistEngineering && !republish {
// Engineering runs again from the step's base: a new candidate.
st.CandidateSHA = ""
diff --git a/internal/equipo/chat/tools.go b/internal/equipo/chat/tools.go
index 3b4c228e..53cd5cbc 100644
--- a/internal/equipo/chat/tools.go
+++ b/internal/equipo/chat/tools.go
@@ -399,6 +399,9 @@ func (t *txn) askPerson(r turnRecord, question string, options []string) (wire.T
// activity records what the coordinator started doing, as an event with
// a label from the instance's copy. Tool input never reaches it.
func (t *txn) activity(l Lease, a *wire.ActivityReport) error {
+ if isQuestionID(a.TurnID) {
+ return t.questionActivity(l, a)
+ }
r, err := t.ownTurn(l, a.TurnID)
if errors.Is(err, ErrNotFound) {
return nil
diff --git a/internal/equipo/migrations/0045_thin_questions.sql b/internal/equipo/migrations/0045_thin_questions.sql
new file mode 100644
index 00000000..abb9e5a5
--- /dev/null
+++ b/internal/equipo/migrations/0045_thin_questions.sql
@@ -0,0 +1,4 @@
+ALTER TABLE chat_steps ADD COLUMN askable numeric;
+CREATE TABLE chat_questions (id text PRIMARY KEY, task_id text, asker text, idempotency_key text, step_id text, specialist text, chosen text, text text, state text, reason text, attempt integer, dispatched numeric, answer text, timing text, revision integer, created_at datetime, updated_at datetime);
+CREATE INDEX chat_question_task ON chat_questions(task_id);
+CREATE UNIQUE INDEX chat_question_key ON chat_questions(task_id, asker, idempotency_key);
diff --git a/internal/equipo/migrations/schema.sql b/internal/equipo/migrations/schema.sql
index 6d965628..2470074b 100644
--- a/internal/equipo/migrations/schema.sql
+++ b/internal/equipo/migrations/schema.sql
@@ -594,8 +594,11 @@ CREATE INDEX chat_card_task ON chat_cards(task_id);
CREATE TABLE chat_project_attachments (project_id text, kind text, ref text, name text, created_at datetime, PRIMARY KEY (project_id, kind, ref));
CREATE TABLE chat_tasks (id text PRIMARY KEY, project_id text, title text, brief text, stage text, branch text, base_sha text, creator text, turn_id text, cancel_requested numeric, revision integer, created_at datetime, updated_at datetime, watching text);
CREATE INDEX chat_task_project ON chat_tasks(project_id);
-CREATE TABLE chat_steps (id text PRIMARY KEY, task_id text, idx integer, specialist text, person text, state text, reason text, attempt integer, base_sha text, candidate_sha text, pushed numeric, terminated numeric, summary text, log_tail text, started_at datetime, finished_at datetime, revision integer, created_at datetime, updated_at datetime, round integer, family text, account text, verdict text, review_label text, findings text, checks text, gate text, exit_code integer, output text, republish numeric, from_attempt integer);
+CREATE TABLE chat_steps (id text PRIMARY KEY, task_id text, idx integer, specialist text, person text, state text, reason text, attempt integer, base_sha text, candidate_sha text, pushed numeric, terminated numeric, summary text, log_tail text, started_at datetime, finished_at datetime, revision integer, created_at datetime, updated_at datetime, round integer, family text, account text, verdict text, review_label text, findings text, checks text, gate text, exit_code integer, output text, republish numeric, from_attempt integer, askable numeric);
CREATE INDEX chat_step_task ON chat_steps(task_id);
CREATE TABLE chat_task_entries (id text PRIMARY KEY, task_id text, idempotency_key text, kind text, author text, text text, repo text, path text, line integer, created_at datetime);
CREATE INDEX chat_entry_task ON chat_task_entries(task_id);
CREATE UNIQUE INDEX chat_entry_key ON chat_task_entries(task_id, idempotency_key);
+CREATE TABLE chat_questions (id text PRIMARY KEY, task_id text, asker text, idempotency_key text, step_id text, specialist text, chosen text, text text, state text, reason text, attempt integer, dispatched numeric, answer text, timing text, revision integer, created_at datetime, updated_at datetime);
+CREATE INDEX chat_question_task ON chat_questions(task_id);
+CREATE UNIQUE INDEX chat_question_key ON chat_questions(task_id, asker, idempotency_key);
diff --git a/internal/thintest/client.go b/internal/thintest/client.go
index 108c7837..3d44843f 100644
--- a/internal/thintest/client.go
+++ b/internal/thintest/client.go
@@ -148,6 +148,21 @@ func (c *Client) PostThread(ctx context.Context, id, text, key string) (out wire
return out, c.do(ctx, "POST", "/api/v1/tasks/"+id+"/thread", wire.PostThread{Text: text, IdempotencyKey: key}, &out)
}
+// Ask asks one of a task's specialists a question.
+func (c *Client) Ask(ctx context.Context, task, text, specialist, key string) (out wire.Question, err error) {
+ return out, c.do(ctx, "POST", "/api/v1/tasks/"+task+"/questions", wire.AskQuestion{Text: text, IdempotencyKey: key, Specialist: specialist}, &out)
+}
+
+// Question reads one question and its answer.
+func (c *Client) Question(ctx context.Context, id string) (out wire.Question, err error) {
+ return out, c.do(ctx, "GET", "/api/v1/questions/"+id, nil, &out)
+}
+
+// CancelQuestion stops a question.
+func (c *Client) CancelQuestion(ctx context.Context, id string) (out wire.TaskAccepted, err error) {
+ return out, c.do(ctx, "POST", "/api/v1/questions/"+id+"/cancel", nil, &out)
+}
+
// Stream is one open SSE connection.
type Stream struct {
Events <-chan wire.Event
@@ -237,6 +252,11 @@ type Conversation struct {
// FirstActivity when its first activity line did.
FirstDelta map[string]time.Time
FirstActivity map[string]time.Time
+ // Questions are the task questions seen, by id; their streamed
+ // answers are in Drafts under the question's id until answered.
+ Questions map[string]wire.Question
+ // DeltaResources counts deltas by event resource (turn, question).
+ DeltaResources map[string]int
// Coordinator is whether the coordinator has moved in.
Coordinator wire.Coordinator
Applied int
@@ -257,6 +277,7 @@ func (c *Conversation) Reset(s wire.Snapshot) {
c.Messages, c.Order, c.Turns, c.Drafts = map[string]wire.Message{}, nil, map[string]wire.Turn{}, map[string]string{}
c.Cards, c.Projects = map[string]wire.Card{}, map[string]wire.Project{}
c.Tasks, c.Steps, c.Stages = map[string]wire.Task{}, map[string]wire.Step{}, map[string][]string{}
+ c.Questions, c.DeltaResources = map[string]wire.Question{}, map[string]int{}
for _, k := range s.Tasks {
c.applyTask(k)
}
@@ -290,6 +311,21 @@ func (c *Conversation) applyTask(k wire.Task) bool {
c.Steps[s.ID] = s
}
}
+ for _, q := range k.Questions {
+ c.applyQuestion(q)
+ }
+ return true
+}
+
+// applyQuestion keeps the newer revision; an ended question's draft goes.
+func (c *Conversation) applyQuestion(q wire.Question) bool {
+ if old, ok := c.Questions[q.ID]; ok && q.Revision <= old.Revision {
+ return false
+ }
+ c.Questions[q.ID] = q
+ if wire.QuestionTerminal(q.State) {
+ delete(c.Drafts, q.ID)
+ }
return true
}
@@ -340,8 +376,14 @@ func (c *Conversation) Apply(e wire.Event) bool {
c.FirstDelta[d.TurnID] = time.Now()
}
c.Drafts[d.TurnID] += d.Text
+ c.DeltaResources[e.Resource]++
applied = true
}
+ case wire.EventQuestion:
+ var q wire.Question
+ if json.Unmarshal(e.Data, &q) == nil {
+ applied = c.applyQuestion(q)
+ }
case wire.EventTask:
var k wire.Task
if json.Unmarshal(e.Data, &k) == nil {
diff --git a/internal/thintest/questions_contract_test.go b/internal/thintest/questions_contract_test.go
new file mode 100644
index 00000000..80b69b1a
--- /dev/null
+++ b/internal/thintest/questions_contract_test.go
@@ -0,0 +1,339 @@
+package thintest
+
+import (
+ "encoding/json"
+ "net/http"
+ "net/url"
+ "strings"
+ "testing"
+
+ "amadan.net/oficina/equipo/internal/equipo"
+ "amadan.net/oficina/equipo/internal/wire"
+)
+
+// answer sends one answer report and waits for its ack.
+func (r *toolRig) answer(id string, rep wire.AnswerReport) {
+ r.t.Helper()
+ r.step2(id, wire.FrameAnswer, rep)
+}
+
+// step2 sends a durable runner frame and waits for its ack, holding any
+// command it caused for expect.
+func (r *toolRig) step2(id, kind string, body any) {
+ r.t.Helper()
+ if err := r.runner.Send(r.ctx, id, kind, body); err != nil {
+ r.t.Fatal(err)
+ }
+ for {
+ f, b, err := r.runner.Next(r.ctx)
+ if err != nil {
+ r.t.Fatal(err)
+ }
+ if a, ok := b.(*wire.Ack); ok && f.Type == wire.FrameAck && a.ID == id {
+ return
+ }
+ if f.Type != wire.FrameAck {
+ r.held = append(r.held, heldFrame{f: f, body: b, raw: r.runner.Received[len(r.runner.Received)-1]})
+ }
+ }
+}
+
+// heldKinds counts the frames of kind held for expect.
+func (r *toolRig) heldKinds(kind string) int {
+ n := 0
+ for _, h := range r.held {
+ if h.f.Type == kind {
+ n++
+ }
+ }
+ return n
+}
+
+// askableTask is a task whose Engineering step pushed cand and whose
+// review approved it, both with their sessions kept.
+func (r *toolRig) askableTask(key, base, cand string) (id string, eng, rev *wire.DispatchCommand) {
+ r.t.Helper()
+ id = taskID(r.t, r.call(key+"-rec", wire.ToolRecordTask, map[string]string{"repo": "oficina/sample", "title": "Fix the README typo", "brief": "The README says teh."}))
+ r.call(key+"-start", wire.ToolStartTask, map[string]string{"task": id, "brief": "Fix it."})
+ _, body := r.expect(wire.FrameDispatch)
+ eng = body.(*wire.DispatchCommand)
+ r.step(key+"-run", wire.StepReport{TaskID: id, StepID: eng.StepID, Attempt: 1, State: wire.StepRunning, BaseSHA: base, Family: "claude", Account: "claude-a"})
+ r.step(key+"-done", wire.StepReport{TaskID: id, StepID: eng.StepID, Attempt: 1, State: wire.StepDone, BaseSHA: base, CandidateSHA: cand, Pushed: true, Termination: true, Family: "claude", Account: "claude-a", Askable: true})
+ r.expect(wire.FrameWatchMerge)
+ c := r.dispatched(wire.SpecialistChecks, base, cand, 0)
+ r.checks(key+"-c", c, wire.ChecksPassed, exit(0), "", "ok\n")
+ rev = r.dispatched(wire.SpecialistReview, base, cand, 0)
+ r.step(key+"-r", wire.StepReport{TaskID: id, StepID: rev.StepID, Attempt: 1, State: wire.StepDone, BaseSHA: base, CandidateSHA: cand, Termination: true, Family: "claude", Account: "claude-a", Verdict: wire.VerdictApprove, ReviewLabel: wire.ReviewSameAccount, Findings: []wire.Finding{}, Summary: "Fine.", Askable: true})
+ r.wait("ready to merge", func(c *Conversation) bool { return c.Tasks[id].Stage == wire.StageReadyToMerge })
+ return id, eng, rev
+}
+
+// TestContractAskImplementer: the task's creator asks the specialist
+// that did the work. The question goes to the newest Engineering step by
+// default, or to Review when it addresses Review; it reaches the runner
+// with the step and the exact commit; its answer streams to every
+// member like a chat reply and is committed on the question. One
+// question of a task is with the runner at a time; the next waits.
+// Teammates read and never ask; cancel goes through the runner; a sync
+// that no longer holds an acked question fails it; the task's end stops
+// questions and lets the runner forget its sessions.
+func TestContractAskImplementer(t *testing.T) {
+ r := newToolRig(t)
+ ctx := r.ctx
+ base, cand := strings.Repeat("1", 40), strings.Repeat("2", 40)
+ // The teammate is an owner with a runner of their own: still not
+ // the task's creator.
+ mate := personToolRig(t, r, "mate@example.com", equipo.RoleOwner)
+ id, eng, rev := r.askableTask("a", base, cand)
+ if k, _ := r.client.Task(ctx, id); !k.Steps[0].Askable || !k.Steps[2].Askable || k.Steps[1].Askable || len(k.Questions) != 0 {
+ t.Fatalf("askable steps %+v", k.Steps)
+ }
+
+ // A teammate reads the task and cannot ask.
+ if _, err := mate.client.Ask(ctx, id, "What did you change?", "", "m1"); Status(err) != http.StatusForbidden {
+ t.Fatalf("teammate asked: %v", err)
+ }
+ // Bad input.
+ if _, err := r.client.Ask(ctx, id, " ", "", "k0"); Status(err) != 422 {
+ t.Fatalf("empty question: %v", err)
+ }
+ if _, err := r.client.Ask(ctx, id, "Why?", "checks", "k0"); Status(err) != 422 {
+ t.Fatalf("checks asked: %v", err)
+ }
+
+ // The creator asks; by default Engineering answers, on its commit.
+ q1, err := r.client.Ask(ctx, id, "What did you change and why?", "", "k1")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if q1.StepID != eng.StepID || q1.Specialist != wire.SpecialistEngineering || q1.State != wire.QuestionQueued || q1.Asker != Owner {
+ t.Fatalf("question %+v", q1)
+ }
+ _, body := r.expect(wire.FrameAsk)
+ shape(t, "frames/ask.json", r.runner.Received[len(r.runner.Received)-1])
+ a1 := body.(*wire.AskCommand)
+ if a1.QuestionID != q1.ID || a1.StepID != eng.StepID || a1.CandidateSHA != cand || a1.BaseSHA != base || a1.Person != Owner || a1.Repo != "amadan.net/oficina/sample" || a1.Text != "What did you change and why?" || a1.Specialist != wire.SpecialistEngineering {
+ t.Fatalf("ask %+v", a1)
+ }
+ // The same key is the same question; another body under it is 409.
+ if again, err := r.client.Ask(ctx, id, "What did you change and why?", "", "k1"); err != nil || again.ID != q1.ID {
+ t.Fatalf("repeat %+v %v", again, err)
+ }
+ if _, err := r.client.Ask(ctx, id, "Something else", "", "k1"); Status(err) != http.StatusConflict {
+ t.Fatalf("conflict: %v", err)
+ }
+
+ // A second question, addressed to Review, waits for the first.
+ q2, err := r.client.Ask(ctx, id, "Review, anything you were unsure about?", "", "k2")
+ if err != nil || q2.StepID != rev.StepID || q2.Specialist != wire.SpecialistReview || q2.State != wire.QuestionQueued {
+ t.Fatalf("second question %+v %v", q2, err)
+ }
+ // Chosen explicitly, even without the word.
+ q3, err := r.client.Ask(ctx, id, "Anything else?", wire.SpecialistReview, "k3")
+ if err != nil || q3.StepID != rev.StepID {
+ t.Fatalf("third question %+v %v", q3, err)
+ }
+
+ // Another person's runner cannot answer it.
+ mate.answer("m-q1", wire.AnswerReport{TaskID: id, QuestionID: q1.ID, Attempt: 1, State: wire.QuestionAnswered, Text: "Not mine to say."})
+ if q, _ := r.client.Question(ctx, q1.ID); q.State != wire.QuestionQueued || q.Answer != "" {
+ t.Fatalf("another runner answered: %+v", q)
+ }
+
+ // The answer streams to every member, the thinking line included.
+ r.answer("r-q1-run", wire.AnswerReport{TaskID: id, QuestionID: q1.ID, Attempt: 1, State: wire.QuestionRunning})
+ r.wait("running", func(c *Conversation) bool { return c.Questions[q1.ID].State == wire.QuestionRunning })
+ // Neither later question went to the runner while the first is there.
+ if n := r.heldKinds(wire.FrameAsk); n != 0 {
+ t.Fatalf("%d more questions went to the runner beside the first", n)
+ }
+ if err := r.runner.Send(ctx, "r-q1-act", wire.FrameActivity, wire.ActivityReport{TurnID: q1.ID, Attempt: 1, Kind: wire.ActivityTool, Tool: "read_change"}); err != nil {
+ t.Fatal(err)
+ }
+ if err := r.runner.Send(ctx, "r-q1-d1", wire.FrameDelta, wire.DeltaReport{TurnID: q1.ID, Attempt: 1, Offset: 0, Text: "I fixed "}); err != nil {
+ t.Fatal(err)
+ }
+ if err := r.runner.Send(ctx, "r-q1-d2", wire.FrameDelta, wire.DeltaReport{TurnID: q1.ID, Attempt: 1, Offset: 8, Text: "the typo."}); err != nil {
+ t.Fatal(err)
+ }
+ for _, who := range []*toolRig{r, mate} {
+ who.wait("the draft", func(c *Conversation) bool {
+ return c.Drafts[q1.ID] == "I fixed the typo." && c.DeltaResources[wire.ResourceQuestion] == 2 && len(c.Activity[q1.ID]) == 1
+ })
+ }
+ var act wire.Activity
+ r.conv.Locked(func(c *Conversation) { act = c.Activity[q1.ID][0] })
+ if act.Tool != "read_change" || act.Label == "" {
+ t.Fatalf("activity %+v", act)
+ }
+ // Nothing streams into anyone's conversation.
+ r.conv.Locked(func(c *Conversation) {
+ if c.DeltaResources["turn"] != 0 {
+ t.Fatalf("question text streamed as a turn: %v", c.DeltaResources)
+ }
+ })
+ r.answer("r-q1-done", wire.AnswerReport{TaskID: id, QuestionID: q1.ID, Attempt: 1, State: wire.QuestionAnswered, Text: "I fixed the typo.", Timing: &wire.TurnTiming{FirstTextMs: 900, ResultMs: 1200}})
+ for _, who := range []*toolRig{r, mate} {
+ who.wait("answered", func(c *Conversation) bool {
+ q := c.Questions[q1.ID]
+ _, draft := c.Drafts[q1.ID]
+ return q.State == wire.QuestionAnswered && q.Answer == "I fixed the typo." && !draft
+ })
+ }
+ // A late report for the ended question changes nothing.
+ r.answer("r-q1-late", wire.AnswerReport{TaskID: id, QuestionID: q1.ID, Attempt: 1, State: wire.QuestionFailed, Reason: "provider_failed"})
+ q, _ := r.client.Question(ctx, q1.ID)
+ if q.State != wire.QuestionAnswered || q.Timing == nil || q.Timing.ResultMs != 1200 {
+ t.Fatalf("answered question %+v", q)
+ }
+ shape(t, "api/question.json", q)
+
+ // Then the second goes to the runner, to Review's step.
+ _, body = r.expect(wire.FrameAsk)
+ if a2 := body.(*wire.AskCommand); a2.QuestionID != q2.ID || a2.StepID != rev.StepID || a2.Specialist != wire.SpecialistReview || a2.CandidateSHA != cand {
+ t.Fatalf("second ask %+v", a2)
+ }
+ // Teammates cannot cancel it; the asker can, through the runner.
+ if _, err := mate.client.CancelQuestion(ctx, q2.ID); Status(err) != http.StatusForbidden {
+ t.Fatalf("teammate cancelled: %v", err)
+ }
+ if acc, err := r.client.CancelQuestion(ctx, q2.ID); err != nil || acc.Attempt != 1 {
+ t.Fatalf("cancel %+v %v", acc, err)
+ }
+ _, body = r.expect(wire.FrameCancelAsk)
+ shape(t, "frames/cancel_ask.json", r.runner.Received[len(r.runner.Received)-1])
+ if c := body.(*wire.CancelAskCommand); c.QuestionID != q2.ID || c.Attempt != 1 {
+ t.Fatalf("cancel_ask %+v", c)
+ }
+ if q, _ := r.client.Question(ctx, q2.ID); q.State != wire.QuestionQueued {
+ t.Fatalf("cancelled before the runner said so: %+v", q)
+ }
+ r.answer("r-q2-x", wire.AnswerReport{TaskID: id, QuestionID: q2.ID, Attempt: 1, State: wire.QuestionCancelled, Reason: "cancelled"})
+ r.wait("cancelled", func(c *Conversation) bool { return c.Questions[q2.ID].State == wire.QuestionCancelled })
+ if _, err := r.client.CancelQuestion(ctx, q2.ID); Status(err) != http.StatusConflict {
+ t.Fatalf("cancel of an ended question: %v", err)
+ }
+
+ // The third goes next; a sync that no longer holds it fails it.
+ _, body = r.expect(wire.FrameAsk)
+ if a3 := body.(*wire.AskCommand); a3.QuestionID != q3.ID {
+ t.Fatalf("third ask %+v", a3)
+ }
+ if err := r.runner.Send(ctx, "r-sync", wire.FrameSync, wire.Sync{Sessions: []wire.SessionState{}, Runs: []wire.Run{{TurnID: r.turn, Attempt: 1, State: "running"}}, Steps: []wire.StepRun{}, Asks: []wire.AskRun{}}); err != nil {
+ t.Fatal(err)
+ }
+ r.wait("interrupted", func(c *Conversation) bool {
+ q := c.Questions[q3.ID]
+ return q.State == wire.QuestionFailed && q.Reason == "interrupted"
+ })
+
+ // A task with no session kept cannot be asked.
+ plain, _ := r.pushed("b", "Another typo", base, strings.Repeat("4", 40))
+ if _, err := r.client.Ask(ctx, plain, "Why?", "", "k4"); Status(err) != http.StatusConflict || !strings.Contains(err.Error(), "not_askable") {
+ t.Fatalf("asked a step with no session: %v", err)
+ }
+
+ // The task ends (merged): a waiting question stops, the runner may
+ // forget the task's sessions, and nobody can ask any more.
+ q5, err := r.client.Ask(ctx, id, "One more thing?", "", "k5")
+ if err != nil {
+ t.Fatal(err)
+ }
+ _, body = r.expect(wire.FrameAsk)
+ if a5 := body.(*wire.AskCommand); a5.QuestionID != q5.ID {
+ t.Fatalf("fifth ask %+v", a5)
+ }
+ q6, err := r.client.Ask(ctx, id, "And another?", "", "k6")
+ if err != nil {
+ t.Fatal(err)
+ }
+ r.step2("r-merged", wire.FrameMerged, wire.MergedReport{TaskID: id, CandidateSHA: cand})
+ r.wait("done", func(c *Conversation) bool {
+ return c.Tasks[id].Stage == wire.StageDone && c.Questions[q6.ID].State == wire.QuestionCancelled
+ })
+ _, body = r.expect(wire.FrameCancelAsk)
+ if c := body.(*wire.CancelAskCommand); c.QuestionID != q5.ID {
+ t.Fatalf("cancel_ask on the end %+v", c)
+ }
+ _, body = r.expect(wire.FrameForgetTask)
+ shape(t, "frames/forget_task.json", r.runner.Received[len(r.runner.Received)-1])
+ if f := body.(*wire.ForgetTaskCommand); f.TaskID != id || f.Person != Owner {
+ t.Fatalf("forget %+v", f)
+ }
+ if _, err := r.client.Ask(ctx, id, "Too late?", "", "k7"); Status(err) != http.StatusConflict || !strings.Contains(err.Error(), "task_ended") {
+ t.Fatalf("asked an ended task: %v", err)
+ }
+ // The task carries its thread of questions.
+ k, _ := mate.client.Task(ctx, id)
+ if len(k.Questions) != 5 || k.Questions[0].Answer != "I fixed the typo." {
+ t.Fatalf("task questions %+v", k.Questions)
+ }
+}
+
+// TestPagesTaskThread: the task page's thread is the same questions a
+// device reads. The creator's composer asks (Asking Engineering, with
+// change between the specialists that can answer); an answered question
+// is a reply the stream can settle into; a waiting one is a thinking
+// line; an ended one says why. A teammate reads the thread, and their
+// composer adds a note; asking from the page is the creator's alone.
+func TestPagesTaskThread(t *testing.T) {
+ r := newToolRig(t)
+ owner := r.inst.Cookie()
+ base, cand := strings.Repeat("1", 40), strings.Repeat("2", 40)
+ id, _, _ := r.askableTask("a", base, cand)
+ page := r.get(owner, "/tasks/"+id, 200)
+ for _, want := range []string{`data-chat-stream data-task="` + id + `"`, `action="/tasks/` + id + `/ask"`, "Asking Engineering", "data-ask-change", `data-choices="engineering,review"`, "No questions or notes yet.", `id="chat-composer"`} {
+ if !strings.Contains(page, want) {
+ t.Fatalf("creator's thread lacks %q: %s", want, page)
+ }
+ }
+ // Asked from the page, in the background like the chat.
+ req, _ := http.NewRequest("POST", r.inst.URL+"/tasks/"+id+"/ask", strings.NewReader(url.Values{"body": {"What did you change?"}, "request_id": {"pg1"}, "specialist": {""}}.Encode()))
+ req.AddCookie(owner)
+ req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
+ req.Header.Set("Origin", r.inst.URL)
+ req.Header.Set("Sec-Fetch-Site", "same-origin")
+ req.Header.Set("Accept", "application/json")
+ res, err := http.DefaultClient.Do(req)
+ if err != nil {
+ t.Fatal(err)
+ }
+ var sent struct {
+ Message struct {
+ ID string `json:"id"`
+ } `json:"message"`
+ }
+ json.NewDecoder(res.Body).Decode(&sent)
+ res.Body.Close()
+ if res.StatusCode != 200 || !strings.HasPrefix(sent.Message.ID, "q_") {
+ t.Fatalf("ask from the page: %d %+v", res.StatusCode, sent)
+ }
+ r.expect(wire.FrameAsk)
+ q2, _ := r.client.Ask(r.ctx, id, "And the review?", wire.SpecialistReview, "pg2")
+ page = r.get(owner, "/tasks/"+id, 200)
+ if !strings.Contains(page, `data-message="`+sent.Message.ID+`"`) || !strings.Contains(page, `equipo-thinking data-turn="`+sent.Message.ID+`"`) || !strings.Contains(page, `equipo-thinking data-turn="`+q2.ID+`"`) || !strings.Contains(page, "Waiting for its turn…") {
+ t.Fatalf("waiting questions: %s", page)
+ }
+ r.answer("r-pg1", wire.AnswerReport{TaskID: id, QuestionID: sent.Message.ID, Attempt: 1, State: wire.QuestionAnswered, Text: "I changed **teh** to the."})
+ r.expect(wire.FrameAsk)
+ r.answer("r-pg2", wire.AnswerReport{TaskID: id, QuestionID: q2.ID, Attempt: 1, State: wire.QuestionFailed, Reason: "session_gone"})
+ page = r.get(owner, "/tasks/"+id, 200)
+ if !strings.Contains(page, `data-turn-id="`+sent.Message.ID+`"`) || !strings.Contains(page, "<strong>teh</strong>") || !strings.Contains(page, "Review couldn&#39;t answer: its session for this work is no longer kept.") {
+ t.Fatalf("answered and failed questions: %s", page)
+ }
+ // A teammate reads it all; their composer adds a note, never asks.
+ mate := r.memberCookie()
+ page = r.get(mate, "/tasks/"+id, 200)
+ if !strings.Contains(page, "<strong>teh</strong>") || strings.Contains(page, "/ask\"") || strings.Contains(page, "equipo-ask-target") || !strings.Contains(page, `action="/tasks/`+id+`/notes"`) {
+ t.Fatalf("teammate's thread: %s", page)
+ }
+ if code, _ := r.post(mate, "/tasks/"+id+"/ask", url.Values{"body": {"Why?"}, "request_id": {"m1"}}); code != http.StatusForbidden {
+ t.Fatalf("teammate asked from the page: %d", code)
+ }
+ if code, _ := r.post(mate, "/tasks/"+id+"/notes", url.Values{"body": {"Looks good to me."}, "request_id": {"m2"}}); code != http.StatusSeeOther {
+ t.Fatalf("teammate's note: %d", code)
+ }
+ if page = r.get(owner, "/tasks/"+id, 200); !strings.Contains(page, "Looks good to me.") {
+ t.Fatalf("the note is not in the thread: %s", page)
+ }
+}