oficina / equipo Public

Lookups: storage, the question pack, and a live runner call

Task 3.6: chat_lookups (migration 0117 completed); lookupPack builds the
query writer's pack from this turn's composer message, and only for a
follow-up (isFollowUp, a fixed marker within 6 words) up to 2 earlier
lookup questions from the last 30 minutes, never before a reset, with
the zone's city and date (AD7), cut to 4 KiB. lookupStep sends a step
live to the person's primary on its current connection (protocol 36),
never to runner_commands, accepts only its nonce's answer from that
connection, and fails when the connection ends or after 20 s.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by paul@keymail.dev 67986c43744f5afb69306916e0bed3473bb8b978 parent 02ed231
10 files changed, +552 −1
  • internal/equipo/chat/lookup_followup.go +33 −0
  • internal/equipo/chat/lookup_live.go +141 −0
  • internal/equipo/chat/lookup_models.go +33 −0
  • internal/equipo/chat/lookup_pack.go +91 −0
  • internal/equipo/chat/lookup_pack_test.go +234 −0
  • internal/equipo/chat/models.go +1 −1
  • internal/equipo/chat/store.go +2 −0
  • internal/equipo/chat/stream.go +6 −0
  • internal/equipo/migrations/0117_lookups.sql +8 −0
  • internal/equipo/migrations/schema.sql +3 −0
diff --git a/internal/equipo/chat/lookup_followup.go b/internal/equipo/chat/lookup_followup.go
new file mode 100644
index 00000000..03754ed4
--- /dev/null
+++ b/internal/equipo/chat/lookup_followup.go
@@ -0,0 +1,33 @@
+package chat
+
+import (
+ "slices"
+ "strings"
+ "unicode"
+)
+
+// followUpMarkers open a follow-up question, compared in lower case after
+// any leading punctuation (so "¿y" is "y").
+var followUpMarkers = [][]string{{"and", "for"}, {"what", "about"}, {"how", "about"}, {"same", "for"}, {"y", "para"}, {"qué", "tal"}, {"que", "tal"}, {"and"}, {"y"}}
+
+// maxFollowUpWords is the most words a follow-up has.
+const maxFollowUpWords = 6
+
+// isFollowUp is the instance's conservative rule for a lookup question
+// that follows on from an earlier one (plan Task 3.6): at most 6 words,
+// starting with a fixed follow-up marker. Shortness alone never makes a
+// follow-up; when in doubt it is not one.
+func isFollowUp(message string) bool {
+ words := strings.FieldsFunc(strings.ToLower(message), func(r rune) bool {
+ return unicode.IsSpace(r) || unicode.IsPunct(r) && r != '\'' || unicode.IsSymbol(r)
+ })
+ if len(words) == 0 || len(words) > maxFollowUpWords {
+ return false
+ }
+ for _, m := range followUpMarkers {
+ if len(words) >= len(m) && slices.Equal(words[:len(m)], m) {
+ return true
+ }
+ }
+ return false
+}
diff --git a/internal/equipo/chat/lookup_live.go b/internal/equipo/chat/lookup_live.go
new file mode 100644
index 00000000..aa719c78
--- /dev/null
+++ b/internal/equipo/chat/lookup_live.go
@@ -0,0 +1,141 @@
+package chat
+
+import (
+ "context"
+ "strconv"
+ "sync"
+ "time"
+
+ "amadan.net/oficina/equipo/internal/wire"
+ "gorm.io/gorm"
+)
+
+// The lookups' live channel (spec 2026-11-26-assistant-abilities §4.2
+// step 3; plan AD8): a lookup step goes to the person's primary runner on
+// its current connection only, never to runner_commands, and its answer
+// is accepted only from that connection, for that lookup, attempt, nonce
+// and stage. A connection that ends fails the steps waiting on it; a
+// step isn't resent.
+
+// lookupStepWait is the most a lookup step is waited for.
+const lookupStepWait = 20 * time.Second
+
+// liveConn is one runner connection's live channel.
+type liveConn struct {
+ runner string
+ protocol int
+ send func(ctx context.Context, f wire.Frame) error
+ done chan struct{}
+}
+
+// lookupWaiter is a lookup step waiting on its answer.
+type lookupWaiter struct {
+ conn *liveConn
+ ch chan wire.LookupResult
+}
+
+// lookupLive is the store's live channels and waiters.
+type lookupLive struct {
+ mu sync.Mutex
+ conns map[string]*liveConn
+ waiters map[string]*lookupWaiter
+ seq int64
+}
+
+func lookupKey(lookup string, attempt int, nonce, stage string) string {
+ return lookup + "\x00" + strconv.Itoa(attempt) + "\x00" + nonce + "\x00" + stage
+}
+
+// attachLive makes runner's connection, at protocol, the one its lookup
+// steps go to, until detach: then every step waiting on it fails.
+func (s *Store) attachLive(runner string, protocol int, send func(context.Context, wire.Frame) error) (detach func()) {
+ c := &liveConn{runner: runner, protocol: protocol, send: send, done: make(chan struct{})}
+ l := &s.live
+ l.mu.Lock()
+ if l.conns == nil {
+ l.conns, l.waiters = map[string]*liveConn{}, map[string]*lookupWaiter{}
+ }
+ if old := l.conns[runner]; old != nil {
+ close(old.done)
+ }
+ l.conns[runner] = c
+ l.mu.Unlock()
+ return func() {
+ l.mu.Lock()
+ defer l.mu.Unlock()
+ if l.conns[runner] == c {
+ delete(l.conns, runner)
+ close(c.done)
+ }
+ }
+}
+
+// deliverLookup hands a lookup_result from runner to the step waiting on
+// it, when there is one on that same connection; anything else (stale,
+// from another connection, unasked) is dropped.
+func (s *Store) deliverLookup(runner string, r wire.LookupResult) {
+ l := &s.live
+ l.mu.Lock()
+ defer l.mu.Unlock()
+ key := lookupKey(r.Lookup, r.Attempt, r.Nonce, r.Stage)
+ w := l.waiters[key]
+ if w == nil || w.conn != l.conns[runner] || w.conn == nil {
+ return
+ }
+ delete(l.waiters, key)
+ w.ch <- r
+}
+
+// lookupStep sends step to the person's primary runner, live, at
+// protocol 36 or later, and waits at most lookupStepWait for its answer.
+// No primary, an older one, a connection that ends or no answer in time
+// is code lookup_failed. The nonce is the store's.
+func (s *Store) lookupStep(ctx context.Context, person string, step wire.LookupStep) (wire.LookupResult, error) {
+ failed := wire.LookupResult{Lookup: step.Lookup, Attempt: step.Attempt, Stage: step.Stage, Code: wire.CodeLookupFailed}
+ var runner string
+ if err := s.read(ctx, func(tx *gorm.DB) error {
+ var err error
+ runner, err = s.authority.PrimaryRunner(tx, person)
+ return err
+ }); err != nil || runner == "" {
+ return failed, err
+ }
+ l := &s.live
+ l.mu.Lock()
+ c := l.conns[runner]
+ if c == nil || c.protocol < wire.ProtocolLookup {
+ l.mu.Unlock()
+ return failed, nil
+ }
+ l.seq++
+ step.Person, step.Nonce = person, newID("n")+strconv.FormatInt(l.seq, 36)
+ failed.Nonce = step.Nonce
+ key := lookupKey(step.Lookup, step.Attempt, step.Nonce, step.Stage)
+ w := &lookupWaiter{conn: c, ch: make(chan wire.LookupResult, 1)}
+ l.waiters[key] = w
+ l.mu.Unlock()
+ defer func() {
+ l.mu.Lock()
+ if l.waiters[key] == w {
+ delete(l.waiters, key)
+ }
+ l.mu.Unlock()
+ }()
+ f, err := wire.NewFrame("lk"+newID(""), wire.FrameLookupStep, step)
+ if err != nil {
+ return failed, err
+ }
+ wctx, cancel := context.WithTimeout(ctx, lookupStepWait)
+ defer cancel()
+ if err := c.send(wctx, f); err != nil {
+ return failed, nil
+ }
+ select {
+ case r := <-w.ch:
+ return r, nil
+ case <-c.done:
+ return failed, nil
+ case <-wctx.Done():
+ return failed, nil
+ }
+}
diff --git a/internal/equipo/chat/lookup_models.go b/internal/equipo/chat/lookup_models.go
index 13753bd9..985c7c4c 100644
--- a/internal/equipo/chat/lookup_models.go
+++ b/internal/equipo/chat/lookup_models.go
@@ -1,5 +1,38 @@
package chat
+import "time"
+
+// lookupRecord is one lookup (spec 2026-11-26-assistant-abilities §4.7):
+// its turn and attempt, its order in the turn, the call it answered, its
+// state (running, shown or failed), the queries and the backends that
+// answered them ([{q, backend}]), the reads ([{url, final_url, status,
+// bytes, sha256, code}]), the answer and its sources, and its code.
+// Never page text.
+type lookupRecord struct {
+ ID string `gorm:"primaryKey"`
+ Person string `gorm:"not null;index:chat_lookup_person,priority:1"`
+ TurnID string `gorm:"not null;index:chat_lookup_turn,priority:1"`
+ Attempt int64 `gorm:"not null;index:chat_lookup_turn,priority:2"`
+ Seq int64 `gorm:"not null;index:chat_lookup_turn,priority:3"`
+ CallID string `gorm:"not null"`
+ State string `gorm:"not null"`
+ Queries string
+ Reads string
+ Answer string
+ Sources string
+ Code string
+ CreatedAt time.Time `gorm:"not null;index:chat_lookup_person,priority:2"`
+}
+
+func (lookupRecord) TableName() string { return "chat_lookups" }
+
+// A lookup's states.
+const (
+ lookupRunning = "running"
+ lookupShown = "shown"
+ lookupFailed = "failed"
+)
+
// webSearchUsageRecord is one search backend's queries in one UTC month,
// against its cap (websearch.DBUsage reads and writes it).
type webSearchUsageRecord struct {
diff --git a/internal/equipo/chat/lookup_pack.go b/internal/equipo/chat/lookup_pack.go
new file mode 100644
index 00000000..34fd2847
--- /dev/null
+++ b/internal/equipo/chat/lookup_pack.go
@@ -0,0 +1,91 @@
+package chat
+
+import (
+ "encoding/json"
+ "strings"
+ "time"
+
+ "amadan.net/oficina/equipo/internal/wire"
+)
+
+// lookupWindow is how far back an earlier lookup question may come from.
+const lookupWindow = 30 * time.Minute
+
+// lookupPack is what the query writer sees (spec 2026-11-26-assistant-
+// abilities §4.2 step 1): this turn's newest composer message in the
+// Assistant lane and, only when it is a follow-up (isFollowUp), up to 2
+// earlier composer messages from turns that ran a lookup (shown or
+// failed) in the last 30 minutes, newest first, never from before the
+// person's last reset; the second only when the first was a follow-up
+// itself. The city and date are the person's zone's (AD7). It is cut to
+// 4 KiB, the oldest earlier question first. With no composer message in
+// the turn there is no pack (ok false).
+func (t *txn) lookupPack(person string, turn turnRecord, now time.Time) (wire.LookupPack, bool, error) {
+ var pack wire.LookupPack
+ var mine messageRecord
+ if err := t.db.Where("turn_id = ? AND person = ? AND role = ? AND origin = ? AND lane = ?", turn.ID, person, wire.RolePerson, originComposer, wire.LaneAssistant).Order("seq DESC").Limit(1).Find(&mine).Error; err != nil || mine.ID == "" {
+ return pack, false, err
+ }
+ pack.Question = mine.Text
+ loc := t.zone(person)
+ pack.City, pack.Date = zoneCity(loc.String()), now.In(loc).Format("2006-01-02, Monday")
+ if isFollowUp(mine.Text) {
+ since := now.Add(-lookupWindow)
+ var reset []time.Time
+ if err := t.db.Model(&commandRecord{}).Where("person = ? AND kind = ?", person, wire.FrameReset).Order("created_at DESC").Limit(1).Pluck("created_at", &reset).Error; err != nil {
+ return pack, false, err
+ }
+ if len(reset) == 1 && reset[0].After(since) {
+ since = reset[0]
+ }
+ var earlier []messageRecord
+ if err := t.db.Where("person = ? AND role = ? AND origin = ? AND lane = ? AND seq < ? AND created_at >= ? AND turn_id IN (SELECT turn_id FROM chat_lookups WHERE person = ? AND state IN ?)", person, wire.RolePerson, originComposer, wire.LaneAssistant, mine.Seq, since, person, []string{lookupShown, lookupFailed}).Order("seq DESC").Limit(2).Find(&earlier).Error; err != nil {
+ return pack, false, err
+ }
+ for i, m := range earlier {
+ pack.Earlier = append(pack.Earlier, m.Text)
+ if i == 0 && !isFollowUp(m.Text) {
+ break
+ }
+ }
+ }
+ for packSize(pack) > wire.MaxLookupPack && len(pack.Earlier) > 0 {
+ pack.Earlier = pack.Earlier[:len(pack.Earlier)-1]
+ }
+ if len(pack.Earlier) == 0 {
+ pack.Earlier = nil
+ }
+ for packSize(pack) > wire.MaxLookupPack && pack.Question != "" {
+ pack.Question = cutRunes(pack.Question, len(pack.Question)-(packSize(pack)-wire.MaxLookupPack)-8)
+ }
+ return pack, true, nil
+}
+
+func packSize(p wire.LookupPack) int {
+ raw, _ := json.Marshal(p)
+ return len(raw)
+}
+
+// cutRunes is s at most n bytes, on a rune boundary.
+func cutRunes(s string, n int) string {
+ if n <= 0 {
+ return ""
+ }
+ if len(s) <= n {
+ return s
+ }
+ for n > 0 && n < len(s) && s[n]&0xc0 == 0x80 {
+ n--
+ }
+ return s[:n]
+}
+
+// zoneCity is a zone's city (AD7): its last path element with
+// underscores as spaces ("Europe/Dublin" is "Dublin"); none for UTC and
+// Etc/*.
+func zoneCity(zone string) string {
+ if zone == "" || zone == "UTC" || zone == "Local" || strings.HasPrefix(zone, "Etc/") || !strings.Contains(zone, "/") {
+ return ""
+ }
+ return strings.ReplaceAll(zone[strings.LastIndex(zone, "/")+1:], "_", " ")
+}
diff --git a/internal/equipo/chat/lookup_pack_test.go b/internal/equipo/chat/lookup_pack_test.go
new file mode 100644
index 00000000..37fb5c36
--- /dev/null
+++ b/internal/equipo/chat/lookup_pack_test.go
@@ -0,0 +1,234 @@
+package chat
+
+import (
+ "bytes"
+ "context"
+ "log/slog"
+ "strconv"
+ "strings"
+ "testing"
+ "time"
+
+ "amadan.net/oficina/equipo/internal/wire"
+)
+
+// packRig is a person's Assistant conversation to build packs from.
+type packRig struct {
+ t *testing.T
+ h *abilitiesHarness
+ n int
+ now time.Time
+}
+
+func newPackRig(t *testing.T) *packRig {
+ h := newAbilitiesHarness(t)
+ r := &packRig{t: t, h: h, now: time.Date(2026, 11, 28, 9, 30, 0, 0, time.UTC)}
+ if err := h.s.db.G.Create(&zoneRecord{Person: abPerson, Zone: "Europe/Dublin", Source: ZoneDevice, UpdatedAt: r.now}).Error; err != nil {
+ t.Fatal(err)
+ }
+ return r
+}
+
+// say is a person turn at ago before now with one composer message;
+// looked marks it as having run a lookup in state.
+func (r *packRig) say(text string, ago time.Duration, looked string) turnRecord {
+ r.t.Helper()
+ r.n++
+ at := r.now.Add(-ago)
+ turn := turnRecord{ID: "t" + strconv.Itoa(r.n), Person: abPerson, State: wire.TurnReplied, Kind: wire.TurnPerson, Lane: wire.LaneAssistant, CreatedAt: at, UpdatedAt: at}
+ m := messageRecord{ID: "m" + strconv.Itoa(r.n), Person: abPerson, IdempotencyKey: "k" + strconv.Itoa(r.n), Role: wire.RolePerson, Origin: originComposer, Text: text, TurnID: turn.ID, Lane: wire.LaneAssistant, CreatedAt: at}
+ for _, row := range []any{&turn, &m} {
+ if err := r.h.s.db.G.Create(row).Error; err != nil {
+ r.t.Fatal(err)
+ }
+ }
+ if looked != "" {
+ if err := r.h.s.db.G.Create(&lookupRecord{ID: "lk" + strconv.Itoa(r.n), Person: abPerson, TurnID: turn.ID, Attempt: 1, CallID: "c" + strconv.Itoa(r.n), State: looked, CreatedAt: at}).Error; err != nil {
+ r.t.Fatal(err)
+ }
+ }
+ return turn
+}
+
+func (r *packRig) pack(turn turnRecord) wire.LookupPack {
+ r.t.Helper()
+ var out wire.LookupPack
+ if err := r.h.s.tx(context.Background(), func(t *txn) error {
+ var err error
+ var ok bool
+ out, ok, err = t.lookupPack(abPerson, turn, r.now)
+ if err == nil && !ok {
+ r.t.Fatal("no pack")
+ }
+ return err
+ }); err != nil {
+ r.t.Fatal(err)
+ }
+ return out
+}
+
+// The pack is the question now, the zone's city and today's date there.
+func TestQuestionPackContents(t *testing.T) {
+ r := newPackRig(t)
+ p := r.pack(r.say("What's the weather in Dublin?", 0, ""))
+ if p.Question != "What's the weather in Dublin?" || p.City != "Dublin" || p.Date != "2026-11-28, Saturday" || p.Earlier != nil {
+ t.Errorf("pack %+v", p)
+ }
+}
+
+// Earlier messages that didn't run a lookup, or are older than 30
+// minutes, never reach the pack, even for a follow-up.
+func TestPackExcludesUnrelatedHistory(t *testing.T) {
+ r := newPackRig(t)
+ r.say("My test results came back, what do they mean?", 10*time.Minute, "")
+ r.say("What's the weather in Galway?", 40*time.Minute, lookupShown)
+ if p := r.pack(r.say("And tomorrow?", 0, "")); p.Earlier != nil {
+ t.Errorf("pack %+v", p)
+ }
+}
+
+func TestPackFollowUpOnly(t *testing.T) {
+ r := newPackRig(t)
+ r.say("What's the weather in Dublin?", 5*time.Minute, lookupShown)
+ for _, q := range []string{"And tomorrow?", "What about Cork?", "¿Y mañana?"} {
+ if p := r.pack(r.say(q, 0, "")); len(p.Earlier) != 1 || p.Earlier[0] != "What's the weather in Dublin?" {
+ t.Errorf("%q: %+v", q, p)
+ }
+ }
+ r = newPackRig(t)
+ r.say("Is the medical clinic on Main Street open?", 5*time.Minute, lookupShown)
+ for _, q := range []string{"How much is a flight to Lisbon?", "Bitcoin price?", "Dublin weather?", "Tomorrow?", "And can you also tell me what the best way to get there would be?", "Andorra weather"} {
+ if p := r.pack(r.say(q, 0, "")); p.Earlier != nil {
+ t.Errorf("%q held %v", q, p.Earlier)
+ }
+ }
+ // A chain of follow-ups holds at most 2, the second only because the
+ // first was a follow-up itself.
+ r = newPackRig(t)
+ r.say("What's the weather in Dublin?", 9*time.Minute, lookupShown)
+ r.say("And tomorrow?", 6*time.Minute, lookupShown)
+ r.say("And Sunday?", 3*time.Minute, lookupFailed)
+ if p := r.pack(r.say("And Monday?", 0, "")); len(p.Earlier) != 2 || p.Earlier[0] != "And Sunday?" || p.Earlier[1] != "And tomorrow?" {
+ t.Errorf("chain: %+v", p.Earlier)
+ }
+ r = newPackRig(t)
+ r.say("Weather in Cork?", 6*time.Minute, lookupShown)
+ r.say("What's the weather in Dublin?", 3*time.Minute, lookupShown)
+ if p := r.pack(r.say("And tomorrow?", 0, "")); len(p.Earlier) != 1 {
+ t.Errorf("the second came though the first wasn't a follow-up: %+v", p.Earlier)
+ }
+}
+
+// A message from before the person's last reset never comes in.
+func TestPackAfterReset(t *testing.T) {
+ r := newPackRig(t)
+ r.say("What's the weather in Dublin?", 10*time.Minute, lookupShown)
+ if err := r.h.s.db.G.Create(&commandRecord{Person: abPerson, Kind: wire.FrameReset, Body: "{}", CreatedAt: r.now.Add(-5 * time.Minute)}).Error; err != nil {
+ t.Fatal(err)
+ }
+ if p := r.pack(r.say("And tomorrow?", 0, "")); p.Earlier != nil {
+ t.Errorf("before the reset: %+v", p.Earlier)
+ }
+}
+
+func TestPackZoneCityAndDate(t *testing.T) {
+ for zone, want := range map[string]string{"Europe/Dublin": "Dublin", "America/Argentina/Buenos_Aires": "Buenos Aires", "UTC": "", "Etc/GMT+3": ""} {
+ if got := zoneCity(zone); got != want {
+ t.Errorf("%s: %q", zone, got)
+ }
+ }
+ r := newPackRig(t)
+ r.now = time.Date(2026, 11, 28, 23, 30, 0, 0, time.UTC)
+ if err := r.h.s.db.G.Model(&zoneRecord{}).Where("person = ?", abPerson).Update("zone", "Pacific/Auckland").Error; err != nil {
+ t.Fatal(err)
+ }
+ if p := r.pack(r.say("Weather?", 0, "")); p.City != "Auckland" || p.Date != "2026-11-29, Sunday" {
+ t.Errorf("pack %+v", p)
+ }
+}
+
+func TestPackFourKiB(t *testing.T) {
+ r := newPackRig(t)
+ r.say(strings.Repeat("Dublin weather today? ", 210), 5*time.Minute, lookupShown)
+ p := r.pack(r.say("And tomorrow?", 0, ""))
+ if packSize(p) > wire.MaxLookupPack || p.Question != "And tomorrow?" || p.Earlier != nil {
+ t.Errorf("%d bytes, %+v", packSize(p), p.Earlier)
+ }
+ r = newPackRig(t)
+ p = r.pack(r.say(strings.Repeat("é", 4000), 0, ""))
+ if packSize(p) > wire.MaxLookupPack || !strings.HasPrefix(p.Question, "éé") {
+ t.Errorf("%d bytes", packSize(p))
+ }
+}
+
+func TestPackRespectsEpoch(t *testing.T) {
+ t.Skip("MCP Task 34 (the lane epoch) has not landed; the reset rule (TestPackAfterReset) stands in until it does")
+}
+
+// A lookup step goes live to the primary's current connection: never to
+// runner_commands or a log; its answer counts only from that connection
+// and for that nonce; a connection that ends fails it, and nothing is
+// resent.
+func TestLookupStepEphemeral(t *testing.T) {
+ h := newAbilitiesHarness(t)
+ var logs bytes.Buffer
+ h.s.SetLogger(slog.New(slog.NewTextHandler(&logs, nil)))
+ const sentinel = "SENTINEL-PAGE-TEXT-77"
+ sent := make(chan wire.LookupStep, 4)
+ detach := h.s.attachLive("RUNNER1", wire.ProtocolLookup, func(_ context.Context, f wire.Frame) error {
+ body, err := f.Decode()
+ if err == nil && f.Type == wire.FrameLookupStep && !f.Durable() {
+ sent <- *body.(*wire.LookupStep)
+ }
+ return err
+ })
+ step := wire.LookupStep{Lookup: "lk1", Attempt: 1, Stage: wire.LookupStageAnswer, Pages: []wire.LookupPage{{URL: "https://www.met.ie/", Text: sentinel}}, Results: []wire.SearchResult{{}}}
+ done := make(chan wire.LookupResult, 1)
+ go func() {
+ r, _ := h.s.lookupStep(context.Background(), abPerson, step)
+ done <- r
+ }()
+ got := <-sent
+ if got.Person != abPerson || got.Nonce == "" {
+ t.Fatalf("step %+v", got)
+ }
+ // A stale answer (another nonce), and one from another runner, are
+ // dropped; the right one is taken.
+ h.s.deliverLookup("RUNNER1", wire.LookupResult{Lookup: "lk1", Attempt: 1, Nonce: "old", Stage: wire.LookupStageAnswer, Answer: "stale"})
+ h.s.deliverLookup("RUNNER2", wire.LookupResult{Lookup: "lk1", Attempt: 1, Nonce: got.Nonce, Stage: wire.LookupStageAnswer, Answer: "elsewhere"})
+ h.s.deliverLookup("RUNNER1", wire.LookupResult{Lookup: "lk1", Attempt: 1, Nonce: got.Nonce, Stage: wire.LookupStageAnswer, Answer: "Rain."})
+ if r := <-done; r.Answer != "Rain." || r.Code != "" {
+ t.Errorf("result %+v", r)
+ }
+ var n int64
+ if err := h.s.db.G.Model(&commandRecord{}).Where("body LIKE ?", "%"+sentinel+"%").Count(&n).Error; err != nil || n != 0 {
+ t.Errorf("runner_commands holds the page: %d %v", n, err)
+ }
+ // The connection ends while a step waits: it fails, and isn't sent
+ // again.
+ go func() {
+ r, _ := h.s.lookupStep(context.Background(), abPerson, wire.LookupStep{Lookup: "lk2", Attempt: 1, Stage: wire.LookupStageQuery})
+ done <- r
+ }()
+ <-sent
+ detach()
+ if r := <-done; r.Code != wire.CodeLookupFailed {
+ t.Errorf("after the connection ended: %+v", r)
+ }
+ select {
+ case s := <-sent:
+ t.Errorf("resent: %+v", s)
+ default:
+ }
+ // No connection, or one below 36: failed at once.
+ if r, _ := h.s.lookupStep(context.Background(), abPerson, step); r.Code != wire.CodeLookupFailed {
+ t.Errorf("no connection: %+v", r)
+ }
+ defer h.s.attachLive("RUNNER1", wire.Protocol35, func(context.Context, wire.Frame) error { t.Error("sent below 36"); return nil })()
+ if r, _ := h.s.lookupStep(context.Background(), abPerson, step); r.Code != wire.CodeLookupFailed {
+ t.Errorf("below 36: %+v", r)
+ }
+ if strings.Contains(logs.String(), sentinel) {
+ t.Error("a log line holds the page")
+ }
+}
diff --git a/internal/equipo/chat/models.go b/internal/equipo/chat/models.go
index d18a5504..a303a105 100644
--- a/internal/equipo/chat/models.go
+++ b/internal/equipo/chat/models.go
@@ -11,7 +11,7 @@ import (
)
// Models are the tables this package owns, for the migration check.
-var Models = append([]any{&changeDiffRecord{}, &notificationReceipt{}, &projectNameRecord{}, &cardVisibility{}, &cardThreadRecord{}, &copyAttemptRecord{}, &copyReviewRecord{}, &copyFeedbackRecord{}, &turnRecord{}, &messageRecord{}, &eventRecord{}, &commandRecord{}, &inboxRecord{}, &runnerSessionRecord{}, &projectRecord{}, &cardRecord{}, &toolCallRecord{}, &settingRecord{}, &coordinatorRecord{}, &notebookRecord{}, &taskRecord{}, &stepRecord{}, &entryRecord{}, &attachmentRecord{}, &starRecord{}, &questionRecord{}, &connectionRecord{}, &usageRecord{}, &distinctRecord{}, &hkRecord{}, &hkFailureRecord{}, &hkSettingsRecord{}, &fileRecord{}, &fileDataRecord{}, &transferRecord{}, &mergePolicyRecord{}, &mergeAuditRecord{}, &specialistRecord{}, &grantRecord{}, &specialistAuditRecord{}, &researchSourceRecord{}, &researchAddressRecord{}, &researchPrefixRecord{}, &researchInventoryRecord{}, &instancePrefixRecord{}, &instanceAddressRecord{}, &instanceInventoryCardRecord{}, &webSearchUsageRecord{}, &researchRecord{}, &researchFetchRecord{}, &taskFileRecord{}, &taskFileDataRecord{}, &releaseRecord{}, &adviceRecord{}, &assistantHostRecord{}, &abilitiesRecord{}, &handoffRecord{}, &handoffTurnRecord{}, &handoffTaskRecord{}, &handoffActionRecord{}, &connectTurnRecord{}, &carriedRecord{}, &zoneRecord{}, &placeRecord{}, &projectPlaceRecord{}}, push.Models...)
+var Models = append([]any{&changeDiffRecord{}, &notificationReceipt{}, &projectNameRecord{}, &cardVisibility{}, &cardThreadRecord{}, &copyAttemptRecord{}, &copyReviewRecord{}, &copyFeedbackRecord{}, &turnRecord{}, &messageRecord{}, &eventRecord{}, &commandRecord{}, &inboxRecord{}, &runnerSessionRecord{}, &projectRecord{}, &cardRecord{}, &toolCallRecord{}, &settingRecord{}, &coordinatorRecord{}, &notebookRecord{}, &taskRecord{}, &stepRecord{}, &entryRecord{}, &attachmentRecord{}, &starRecord{}, &questionRecord{}, &connectionRecord{}, &usageRecord{}, &distinctRecord{}, &hkRecord{}, &hkFailureRecord{}, &hkSettingsRecord{}, &fileRecord{}, &fileDataRecord{}, &transferRecord{}, &mergePolicyRecord{}, &mergeAuditRecord{}, &specialistRecord{}, &grantRecord{}, &specialistAuditRecord{}, &researchSourceRecord{}, &researchAddressRecord{}, &researchPrefixRecord{}, &researchInventoryRecord{}, &instancePrefixRecord{}, &instanceAddressRecord{}, &instanceInventoryCardRecord{}, &webSearchUsageRecord{}, &lookupRecord{}, &researchRecord{}, &researchFetchRecord{}, &taskFileRecord{}, &taskFileDataRecord{}, &releaseRecord{}, &adviceRecord{}, &assistantHostRecord{}, &abilitiesRecord{}, &handoffRecord{}, &handoffTurnRecord{}, &handoffTaskRecord{}, &handoffActionRecord{}, &connectTurnRecord{}, &carriedRecord{}, &zoneRecord{}, &placeRecord{}, &projectPlaceRecord{}}, push.Models...)
type turnRecord struct {
CreateRepo string
diff --git a/internal/equipo/chat/store.go b/internal/equipo/chat/store.go
index 5d22c430..ab7558e8 100644
--- a/internal/equipo/chat/store.go
+++ b/internal/equipo/chat/store.go
@@ -120,6 +120,8 @@ type Store struct {
// scan; ifaceAddrs replaces net.InterfaceAddrs in tests.
instance instanceNet
ifaceAddrs func() ([]net.Addr, error)
+ // live is the lookups' live channel to each runner (lookup_live.go).
+ live lookupLive
// ops is the Assistant's registry (SetOperations); remote wakes
// ServeRemoteCalls after a commit that stored a pending call.
ops atomic.Pointer[Operations]
diff --git a/internal/equipo/chat/stream.go b/internal/equipo/chat/stream.go
index 52e69c3c..31ce1ec7 100644
--- a/internal/equipo/chat/stream.go
+++ b/internal/equipo/chat/stream.go
@@ -135,6 +135,9 @@ func (rc *runnerConn) serve() {
if rc.send(ctx, welcome) != nil {
return
}
+ // Lookup steps go to this connection, live, until it ends.
+ detach := store.attachLive(rc.principal.RunnerID, rc.lease.Protocol, rc.send)
+ defer detach()
rc.seen = make(chan struct{}, 1)
closeCode := make(chan websocket.StatusCode, 1)
go func() {
@@ -179,6 +182,9 @@ 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.LookupResult:
+ // Live only: handed to the step waiting on it, never stored.
+ store.deliverLookup(rc.principal.RunnerID, *v)
case *wire.ChangeDiffUpload, *wire.AccessReport, *wire.Sync, *wire.Ack, *wire.DeltaReport, *wire.Reply, *wire.TurnReport, *wire.ToolCall, *wire.ActivityReport, *wire.MoveIn, *wire.NotebookReport, *wire.StepReport, *wire.MergedReport, *wire.AnswerReport, *wire.BranchReport, *wire.ConnectionReport, *wire.UsageReport, *wire.StepActivityReport, *wire.Blob, *wire.PublishedReport, *wire.ResearchFile, *wire.GlanceReport:
err = store.Apply(ctx, rc.lease, f, body)
case *wire.LeaseCheck:
diff --git a/internal/equipo/migrations/0117_lookups.sql b/internal/equipo/migrations/0117_lookups.sql
index 0ed5310b..fe9fc7ce 100644
--- a/internal/equipo/migrations/0117_lookups.sql
+++ b/internal/equipo/migrations/0117_lookups.sql
@@ -1,3 +1,11 @@
-- Lookups (spec 2026-11-26-assistant-abilities §4): each search backend's
-- queries per UTC calendar month, against the operator's monthly cap.
CREATE TABLE chat_web_search_usage (backend text, month text, used integer NOT NULL DEFAULT 0, PRIMARY KEY (backend, month));
+-- Each lookup: its turn, attempt and order, the call it answered, its
+-- state (running, shown or failed), the queries and reads as JSON, the
+-- answer and sources, its code. Page text is never stored.
+CREATE TABLE chat_lookups (id text PRIMARY KEY, person text NOT NULL, turn_id text NOT NULL, attempt integer NOT NULL,
+ seq integer NOT NULL, call_id text NOT NULL, state text NOT NULL, queries text, reads text, answer text,
+ sources text, code text, created_at datetime NOT NULL);
+CREATE INDEX chat_lookup_turn ON chat_lookups(turn_id, attempt, seq);
+CREATE INDEX chat_lookup_person ON chat_lookups(person, created_at);
diff --git a/internal/equipo/migrations/schema.sql b/internal/equipo/migrations/schema.sql
index b5fcf727..886c4bf2 100644
--- a/internal/equipo/migrations/schema.sql
+++ b/internal/equipo/migrations/schema.sql
@@ -663,6 +663,9 @@ CREATE TABLE instance_prefixes (prefix text PRIMARY KEY, confirmed_by text, conf
CREATE TABLE instance_addresses (address text PRIMARY KEY, seen_at datetime);
CREATE TABLE chat_instance_inventory (card_id text PRIMARY KEY, prefixes text, addresses text, created_at datetime);
CREATE TABLE chat_web_search_usage (backend text, month text, used integer NOT NULL DEFAULT 0, PRIMARY KEY (backend, month));
+CREATE TABLE chat_lookups (id text PRIMARY KEY, person text NOT NULL, turn_id text NOT NULL, attempt integer NOT NULL, seq integer NOT NULL, call_id text NOT NULL, state text NOT NULL, queries text, reads text, answer text, sources text, code text, created_at datetime NOT NULL);
+CREATE INDEX chat_lookup_turn ON chat_lookups(turn_id, attempt, seq);
+CREATE INDEX chat_lookup_person ON chat_lookups(person, created_at);
CREATE TABLE chat_research (step_id text, attempt integer, task_id text, revision integer, findings text, created_at datetime, PRIMARY KEY (step_id, attempt));
CREATE INDEX chat_research_task ON chat_research(task_id);
CREATE TABLE chat_research_fetches (step_id text, attempt integer, idx integer, task_id text, source_id text, origin text, parent text, url text, hops text, address text, status integer, type text, bytes integer, sha256 text, millis integer, reason text, PRIMARY KEY (step_id, attempt, idx));