oficina / equipo Public

Resolve a legacy hand-off's mirrored question once it is moot

A legacy hand-off (lane "") mirrored its team question into the
Assistant lane as a question card (slice 1, kept by ruling P3j). Paul
answered his in the chat instead, so the source stayed open and so did
the card, for ever.

settleLegacyQuestions now resolves such a card, with the approved
resolved line and a card event, when the hand-off is cancelled or
stopping, or its work has settled or stopped (handoffSettled); when its
source is no longer open the card follows it (withdrawn: resolved;
answered: answered, as before); and when the source has been open for
24 h with no answer and none of the hand-off's work runs (no turn in
flight, no step under way). It runs on handoffChanged, on team_cancel,
and on the housekeeping minute, which also catches cards that went
stale before this change. The team's own card is never touched.

Contract tests (TestContractAssistantLegacyQuestion*): Cancelled,
Settled, Stopped, SourceAnswered, SourceWithdrawn, Stale.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by paul@keymail.dev 9ebeb9e57e7c610cc63eea8dbc316d2534a769cc parent d01b70e
4 files changed, +345 −1
  • internal/equipo/chat/handoff.go +6 −0
  • internal/equipo/chat/housekeeping_control.go +7 −1
  • internal/equipo/chat/outcome.go +111 −0
  • internal/thintest/assistant_legacy_question_contract_test.go +221 −0
diff --git a/internal/equipo/chat/handoff.go b/internal/equipo/chat/handoff.go
index 4065fae4..ec379930 100644
--- a/internal/equipo/chat/handoff.go
+++ b/internal/equipo/chat/handoff.go
@@ -641,6 +641,9 @@ func (t *txn) handoffChanged(h handoffRecord, needsPerson bool) error {
if err := t.tellAssistant(h, needsPerson); err != nil {
return err
}
+ if err := t.settleLegacyQuestions(h); err != nil {
+ return err
+ }
return t.projectJob(h)
}
@@ -1362,6 +1365,9 @@ func (s *Store) teamCancel(ctx context.Context, call toolCallRecord, input json.
return err
}
h.State = state
+ if err := t.settleLegacyQuestions(h); err != nil {
+ return err
+ }
return t.projectJob(h)
})
if err != nil {
diff --git a/internal/equipo/chat/housekeeping_control.go b/internal/equipo/chat/housekeeping_control.go
index ac73e471..ed8db0a6 100644
--- a/internal/equipo/chat/housekeeping_control.go
+++ b/internal/equipo/chat/housekeeping_control.go
@@ -461,7 +461,9 @@ func (t *txn) subjectRevision(kind, id string) (int64, error) {
}
// HousekeepingTick is the loop's minute: receipts whose quiet hours ended
-// show; a job's preview that expired is offered no more; stale claims
+// show; a job's preview that expired is offered no more; a legacy
+// hand-off's mirrored question that needs no answer now is resolved;
+// 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.
@@ -472,6 +474,10 @@ func (s *Store) HousekeepingTick(ctx context.Context) error {
if err := s.tx(ctx, func(t *txn) error { return t.expirePreviews() }); err != nil {
return err
}
+ // A legacy hand-off's mirrored question nobody will answer now.
+ if err := s.tx(ctx, func(t *txn) error { return t.settleStaleLegacyQuestions() }); err != nil {
+ return err
+ }
if _, _, err := s.RecoverHousekeeping(ctx, true); err != nil {
return err
}
diff --git a/internal/equipo/chat/outcome.go b/internal/equipo/chat/outcome.go
index f41f7a7a..f13d09be 100644
--- a/internal/equipo/chat/outcome.go
+++ b/internal/equipo/chat/outcome.go
@@ -5,6 +5,7 @@ import (
"errors"
"slices"
"strings"
+ "time"
"amadan.net/oficina/equipo/internal/equipo/mergegate"
"amadan.net/oficina/equipo/internal/wire"
@@ -504,3 +505,113 @@ func (t *txn) answerOutcome(person string, c cardRecord, in wire.AnswerCard) (ou
out.Card, err = t.assistantCardView(c)
return out, current, err
}
+
+// Stale legacy questions (Paul's live check, 2026-11-14). A legacy
+// hand-off (lane "") mirrored its team question into the Assistant lane
+// as a question card (slice 1, kept by ruling P3j). The card follows its
+// source while the source changes (mirrorCard), but the person may
+// answer in the chat instead, and the source then stays open: the card
+// stayed open for ever. settleLegacyQuestions resolves it, with the
+// approved resolved line, once the hand-off is cancelled or its work has
+// settled or stopped (handoffSettled), or once its source has been open
+// for staleQuestion with no answer and none of the hand-off's work runs.
+// A source no longer open that the card missed is followed now. The team
+// card itself is never touched: it stays the Coordinator's.
+
+// staleQuestion is how long a legacy hand-off's question may wait
+// unanswered, its work not running, before its mirror is resolved.
+const staleQuestion = 24 * time.Hour
+
+// settleLegacyQuestions resolves the legacy hand-off's open mirrored
+// question cards that no longer need an answer, each with its event.
+func (t *txn) settleLegacyQuestions(h handoffRecord) error {
+ if h.Lane != "" {
+ return nil
+ }
+ var mirrors []cardRecord
+ if err := t.db.Where("handoff_id = ? AND person = ? AND lane = ? AND kind = ? AND state = ? AND coalesce(source_card, '') <> ''", h.ID, h.Person, wire.LaneAssistant, wire.CardQuestion, wire.CardOpen).Order("created_at, id").Find(&mirrors).Error; err != nil || len(mirrors) == 0 {
+ return err
+ }
+ ended := h.State == handoffCancelled || h.State == handoffStopping
+ if !ended {
+ settled, err := t.handoffSettled(h)
+ if err != nil {
+ return err
+ }
+ ended = settled
+ }
+ running, err := t.handoffRunning(h)
+ if err != nil {
+ return err
+ }
+ for _, m := range mirrors {
+ var src cardRecord
+ if err := t.db.Where("id = ? AND person = ?", m.SourceCard, m.Person).Limit(1).Find(&src).Error; err != nil {
+ return err
+ }
+ switch {
+ case src.ID == "" || ended:
+ m.State, m.Result = wire.CardResolved, t.copy("assistant.outcome.resolved")
+ case src.State != wire.CardOpen:
+ if err := t.fillMirror(&m, src); err != nil {
+ return err
+ }
+ case !running && src.CreatedAt.Before(t.now().Add(-staleQuestion)):
+ m.State, m.Result = wire.CardResolved, t.copy("assistant.outcome.resolved")
+ default:
+ continue
+ }
+ m.Revision++
+ m.UpdatedAt = t.now()
+ if err := t.db.Model(&cardRecord{}).Where("id = ?", m.ID).Select("state", "question", "options", "links", "result", "revision", "updated_at").Updates(&m).Error; err != nil {
+ return err
+ }
+ if err := t.cardEvent(m); err != nil {
+ return err
+ }
+ }
+ return nil
+}
+
+// handoffRunning: one of the hand-off's Coordinator turns has not ended,
+// or a step of a task it follows is under way.
+func (t *txn) handoffRunning(h handoffRecord) (bool, error) {
+ var n int64
+ if err := t.handoffTurns(h).Where("state IN ?", wire.InFlight).Count(&n).Error; err != nil || n > 0 {
+ return n > 0, err
+ }
+ tasks, err := t.handoffTasks(h)
+ if err != nil {
+ return false, err
+ }
+ for _, k := range tasks {
+ steps, err := t.steps(k.ID)
+ if err != nil {
+ return false, err
+ }
+ if slices.ContainsFunc(steps, func(s stepRecord) bool { return !wire.StepTerminal(s.State) }) {
+ return true, nil
+ }
+ }
+ return false, nil
+}
+
+// settleStaleLegacyQuestions is the minute's look at every legacy
+// hand-off with an open mirrored question: nothing else may move one
+// that waits for a day, or that settled before this rule.
+func (t *txn) settleStaleLegacyQuestions() error {
+ var ids []string
+ if err := t.db.Model(&cardRecord{}).Where("lane = ? AND kind = ? AND state = ? AND coalesce(source_card, '') <> '' AND coalesce(handoff_id, '') <> ''", wire.LaneAssistant, wire.CardQuestion, wire.CardOpen).Distinct().Order("handoff_id").Pluck("handoff_id", &ids).Error; err != nil || len(ids) == 0 {
+ return err
+ }
+ var rows []handoffRecord
+ if err := t.db.Where("id IN ? AND coalesce(lane, '') = ''", ids).Order("created_at, id").Find(&rows).Error; err != nil {
+ return err
+ }
+ for _, h := range rows {
+ if err := t.settleLegacyQuestions(h); err != nil {
+ return err
+ }
+ }
+ return nil
+}
diff --git a/internal/thintest/assistant_legacy_question_contract_test.go b/internal/thintest/assistant_legacy_question_contract_test.go
new file mode 100644
index 00000000..0d1f759f
--- /dev/null
+++ b/internal/thintest/assistant_legacy_question_contract_test.go
@@ -0,0 +1,221 @@
+package thintest
+
+import (
+ "testing"
+ "time"
+
+ "amadan.net/oficina/equipo/internal/equipo"
+ "amadan.net/oficina/equipo/internal/wire"
+)
+
+// Stale legacy question cards (Paul's live check, 2026-11-14). A legacy
+// hand-off (lane "") mirrored its team question into the Assistant lane
+// as a question card (slice 1, kept by ruling P3j). Such a card follows
+// its source while the source changes; it is resolved, with the approved
+// resolved line, once the hand-off is cancelled or its work has settled
+// or stopped, or once its source has been open for a day with no answer
+// and none of the hand-off's work is running. Each time the card's
+// event in the Assistant lane carries the resolution.
+
+const legacyQuestion = "Which login page?"
+
+// legacyMirror is a legacy hand-off whose turn asked the person a
+// question, that turn ended, and the question mirrored into the
+// Assistant lane as slice 1 did: request, the turn, the team question
+// card and its Assistant mirror. With task, the turn records a task
+// first (its id is task's).
+func (o *teamRig) legacyMirror(key string, task *string) (request, turn, source, mirror string) {
+ o.t.Helper()
+ o.ask("Can we fix a bug in Tito? Login is broken")
+ request, turn = o.legacyHandoff(key, "Login is broken")
+ o.in(turn, func() {
+ if task != nil {
+ *task = o.record(key+"-rec", "Login page")
+ }
+ if res := o.call(key+"-ask", wire.ToolAskPerson, map[string]any{"question": legacyQuestion, "options": []string{"Web", "App"}}); res.Code != "asked" {
+ o.t.Fatalf("ask %+v", res)
+ }
+ })
+ o.reply(turn)
+ source = o.teamCard(wire.CardQuestion, turn, "").ID
+ if source == "" {
+ o.t.Fatal("no team question")
+ }
+ mirror = "c_mirror" + key
+ o.exec("INSERT INTO chat_cards(id, person, kind, state, turn_id, question, options, revision, created_at, updated_at, lane, source_card, links, result, handoff_id) SELECT ?, person, kind, state, turn_id, question, '[{\"value\":\"Web\",\"label\":\"Web\"},{\"value\":\"App\",\"label\":\"App\"}]', 1, created_at, updated_at, ?, id, '[]', '', ? FROM chat_cards WHERE id = ?", mirror, wire.LaneAssistant, request, source)
+ if c := o.mirrorCard(mirror); c.State != wire.CardOpen {
+ o.t.Fatalf("the mirror %+v is not open", c)
+ }
+ return request, turn, source, mirror
+}
+
+// mirrorCard is the Assistant snapshot's card id (zero when absent).
+func (o *teamRig) mirrorCard(id string) wire.AssistantCard {
+ o.t.Helper()
+ for _, c := range o.assistantCards() {
+ if c.ID == id {
+ return c
+ }
+ }
+ return wire.AssistantCard{}
+}
+
+// cardState is a card's state as stored.
+func (o *teamRig) cardState(id string) string {
+ o.t.Helper()
+ var st string
+ if err := o.inst.DB.Writer().QueryRow("SELECT state FROM chat_cards WHERE id = ?", id).Scan(&st); err != nil {
+ o.t.Fatal(err)
+ }
+ return st
+}
+
+// tick is the instance's housekeeping minute.
+func (o *teamRig) tick() {
+ o.t.Helper()
+ if err := o.inst.Store.Chat().HousekeepingTick(o.ctx); err != nil {
+ o.t.Fatal(err)
+ }
+}
+
+// resolvedMirror fails unless the mirror is resolved with the approved
+// line, gone from the open cards, and its newest event says so.
+func (o *teamRig) resolvedMirror(id string) {
+ o.t.Helper()
+ line := equipo.RunnerCopy("assistant.outcome.resolved")
+ o.until("the mirror resolved", func() bool { return o.mirrorCard(id).State == wire.CardResolved })
+ if c := o.mirrorCard(id); c.Result != line || c.Options == nil || c.Links == nil {
+ o.t.Fatalf("the resolved mirror %+v", c)
+ }
+ events := o.jobEvents(id)
+ if len(events) == 0 {
+ o.t.Fatal("no event for the mirror")
+ }
+ if last := events[len(events)-1]; last.State != wire.CardResolved || last.Result != line {
+ o.t.Fatalf("the mirror's event %+v", last)
+ }
+}
+
+// openMirror fails unless the mirror is still open and no event moved it.
+func (o *teamRig) openMirror(id string) {
+ o.t.Helper()
+ if c := o.mirrorCard(id); c.State != wire.CardOpen {
+ o.t.Fatalf("the mirror %+v closed", c)
+ }
+ for _, e := range o.jobEvents(id) {
+ if e.State != wire.CardOpen {
+ o.t.Fatalf("an event closed the mirror: %+v", e)
+ }
+ }
+}
+
+// TestContractAssistantLegacyQuestionCancelled: the person's request
+// cancelled, its mirrored question is resolved.
+func TestContractAssistantLegacyQuestionCancelled(t *testing.T) {
+ o := newTeamRig(t)
+ request, _, _, mirror := o.legacyMirror("qc", nil)
+ o.in(o.turn, func() {
+ if res := o.use("qc-cancel", "team_cancel", map[string]any{"request": request}); res.IsError {
+ t.Fatalf("team_cancel %+v", res)
+ }
+ })
+ o.resolvedMirror(mirror)
+}
+
+// TestContractAssistantLegacyQuestionSettled: the hand-off's work
+// settled (its task ended), its mirrored question is resolved.
+func TestContractAssistantLegacyQuestionSettled(t *testing.T) {
+ o := newTeamRig(t)
+ var id string
+ request, _, _, mirror := o.legacyMirror("qs", &id)
+ if !o.linked(request)[id] {
+ t.Fatal("the task is not the hand-off's")
+ }
+ o.openMirror(mirror)
+ o.exec("UPDATE chat_tasks SET stage = ? WHERE id = ?", wire.StageDone, id)
+ o.tick()
+ o.resolvedMirror(mirror)
+}
+
+// TestContractAssistantLegacyQuestionStopped: the hand-off's work
+// stopped and needs someone (a step failed, its end proven), its
+// mirrored question is
+// resolved when the hand-off hears of it.
+func TestContractAssistantLegacyQuestionStopped(t *testing.T) {
+ o := newTeamRig(t)
+ var id string
+ request, _, _, mirror := o.legacyMirror("qp", &id)
+ if !o.linked(request)[id] {
+ t.Fatal("the task is not the hand-off's")
+ }
+ o.exec("INSERT INTO chat_steps(id, task_id, specialist, state, terminated, attempt, created_at, updated_at) VALUES ('s_qp', ?, ?, ?, 1, 1, datetime('now'), datetime('now'))", id, wire.SpecialistEngineering, wire.StepFailed)
+ o.tick()
+ o.resolvedMirror(mirror)
+}
+
+// TestContractAssistantLegacyQuestionSourceAnswered: the source question
+// answered (here by team_reply), the mirror follows it out of the open
+// cards, and its event says so.
+func TestContractAssistantLegacyQuestionSourceAnswered(t *testing.T) {
+ o := newTeamRig(t)
+ request, _, source, mirror := o.legacyMirror("qa", nil)
+ replied(t, o.teamReply("qa-reply", request, "App"), request)
+ o.until("the source answered", func() bool { return o.cardState(source) == wire.CardAnswered })
+ o.until("the mirror closed", func() bool { return o.mirrorCard(mirror).State != wire.CardOpen })
+ if c := o.mirrorCard(mirror); c.State != wire.CardAnswered {
+ t.Fatalf("the mirror %+v", c)
+ }
+ events := o.jobEvents(mirror)
+ if len(events) == 0 || events[len(events)-1].State != wire.CardAnswered {
+ t.Fatalf("the mirror's events %+v", events)
+ }
+}
+
+// TestContractAssistantLegacyQuestionSourceWithdrawn: a source question
+// no longer open but not answered (withdrawn) leaves its mirror
+// resolved, even when nothing moved the mirror at the time and the
+// hand-off's work still runs.
+func TestContractAssistantLegacyQuestionSourceWithdrawn(t *testing.T) {
+ o := newTeamRig(t)
+ var id string
+ _, _, source, mirror := o.legacyMirror("qw", &id)
+ o.exec("INSERT INTO chat_steps(id, task_id, specialist, state, attempt, created_at, updated_at) VALUES ('s_qw', ?, ?, ?, 1, datetime('now'), datetime('now'))", id, wire.SpecialistEngineering, wire.StepRunning)
+ o.exec("UPDATE chat_cards SET state = ? WHERE id = ?", wire.CardResolved, source)
+ o.tick()
+ o.resolvedMirror(mirror)
+}
+
+// TestContractAssistantLegacyQuestionStale: a source question open for
+// more than a day with no answer is resolved when none of the hand-off's
+// work runs; before the day is out, or while its work runs (a step under
+// way), it stays.
+func TestContractAssistantLegacyQuestionStale(t *testing.T) {
+ o := newTeamRig(t)
+ var id string
+ request, _, source, mirror := o.legacyMirror("qx", &id)
+ if !o.linked(request)[id] {
+ t.Fatal("the task is not the hand-off's")
+ }
+ var asked time.Time
+ if err := o.inst.DB.Writer().QueryRow("SELECT created_at FROM chat_cards WHERE id = ?", source).Scan(&asked); err != nil {
+ t.Fatal(err)
+ }
+ // Its work does not run (a step done, the task not settled), but the
+ // question is under a day old: it stays.
+ o.exec("INSERT INTO chat_steps(id, task_id, specialist, state, attempt, created_at, updated_at) VALUES ('s_qx', ?, ?, ?, 1, datetime('now'), datetime('now'))", id, wire.SpecialistEngineering, wire.StepDone)
+ o.exec("UPDATE chat_cards SET created_at = ? WHERE id = ?", asked.Add(-23*time.Hour), source)
+ o.tick()
+ o.openMirror(mirror)
+ // A day old, but its work runs again: it stays.
+ o.exec("UPDATE chat_steps SET state = ? WHERE id = 's_qx'", wire.StepRunning)
+ o.exec("UPDATE chat_cards SET created_at = ? WHERE id = ?", asked.Add(-25*time.Hour), source)
+ o.tick()
+ o.openMirror(mirror)
+ // The work no longer runs: resolved; the team's own question stays.
+ o.exec("UPDATE chat_steps SET state = ? WHERE id = 's_qx'", wire.StepDone)
+ o.tick()
+ o.resolvedMirror(mirror)
+ if st := o.cardState(source); st != wire.CardOpen {
+ t.Fatalf("the team's own question moved to %s", st)
+ }
+}