oficina / equipo Public

Abilities: refresh at turn start, every minute, before acts; the hint

A copy older than a minute is fetched again before a person turn starts
(messages, card answers), every minute for people with a turn in flight
or an open job, and before an act outside a turn (Store.Allowed, which
then reads the switches). POST /api/v1/assistant/abilities/refresh is
Base's hint: fetched within the call, 200 {revision}, or 202 when it
failed or ran less than 5 s ago. GET /api/v1/assistant/abilities is the
caller's own board, with the fixed keys and who to ask.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by paul@keymail.dev 4c837ca13daea6f0302c3c5601b6b5aa26c8003f parent c96da97
5 files changed, +302 −0
  • internal/equipo/app.go +9 −0
  • internal/equipo/chat/abilities_harness_test.go +11 −0
  • internal/equipo/chat/abilities_refresh.go +162 −0
  • internal/equipo/chat/abilities_refresh_test.go +116 −0
  • internal/equipo/chat/assistant_http.go +4 −0
diff --git a/internal/equipo/app.go b/internal/equipo/app.go
index 6d74ae69..991bb145 100644
--- a/internal/equipo/app.go
+++ b/internal/equipo/app.go
@@ -109,6 +109,15 @@ func (a *application) startBackground() *background.Group {
a.logger.Error(copyChatSweep, "err", err)
}
})
+ // The board of everyone with work under way, when a minute old
+ // (spec 2026-11-26-assistant-abilities §5.3).
+ a.background.Loop(context.Background(), time.Minute, func() {
+ ctx, cancel := context.WithTimeout(context.Background(), 50*time.Second)
+ defer cancel()
+ if err := a.store.Chat().RefreshActiveAbilities(ctx); err != nil {
+ a.logger.Warn("abilities refresh", "err", err)
+ }
+ })
a.background.Loop(context.Background(), time.Hour, func() {
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
diff --git a/internal/equipo/chat/abilities_harness_test.go b/internal/equipo/chat/abilities_harness_test.go
index 9dcb8018..09614852 100644
--- a/internal/equipo/chat/abilities_harness_test.go
+++ b/internal/equipo/chat/abilities_harness_test.go
@@ -3,6 +3,7 @@ package chat
import (
"context"
"encoding/json"
+ "errors"
"io"
"log/slog"
"net/http"
@@ -14,6 +15,7 @@ import (
"testing"
"time"
+ "amadan.net/oficina/equipo/internal/equipo/assist"
"amadan.net/oficina/equipo/internal/wire"
"amadan.net/rastrillo/rastrillo/db"
"gorm.io/gorm"
@@ -243,3 +245,12 @@ func (h *abilitiesHarness) switchesOf(t *testing.T, person string) Switches {
}
return sw
}
+
+// refusalCode is err's assist.Failure code, "" for none.
+func refusalCode(err error) string {
+ var f assist.Failure
+ if errors.As(err, &f) {
+ return f.Code
+ }
+ return ""
+}
diff --git a/internal/equipo/chat/abilities_refresh.go b/internal/equipo/chat/abilities_refresh.go
new file mode 100644
index 00000000..47a5c7e4
--- /dev/null
+++ b/internal/equipo/chat/abilities_refresh.go
@@ -0,0 +1,162 @@
+package chat
+
+import (
+ "context"
+ "net/http"
+ "time"
+
+ "amadan.net/oficina/equipo/internal/equipo/assist"
+ "amadan.net/oficina/equipo/internal/equipo/personapi"
+ "amadan.net/oficina/equipo/internal/wire"
+ "gorm.io/gorm"
+)
+
+// When a person's board is fetched again (spec 2026-11-26-assistant-
+// abilities §5.3): on Base's hint, at the start of a person turn, every
+// minute for people with work under way, and before an act outside a
+// turn, each when the copy is older than a minute.
+
+const (
+ // abilitiesStale is how old a copy may be before an act fetches again.
+ abilitiesStale = 60 * time.Second
+ // hintThrottle is how soon after a fetch the hint fetches again.
+ hintThrottle = 5 * time.Second
+)
+
+// refreshIfStale fetches the person's board, outside any transaction and
+// bounded as every fetch is, when their copy is older than a minute or
+// missing. A person with no host, or an instance without
+// EQUIPO_ASSISTANT_HOSTS, has nothing to fetch.
+func (s *Store) refreshIfStale(ctx context.Context, person string) error {
+ if len(s.authority.AssistantHosts) == 0 {
+ return nil
+ }
+ var stale bool
+ err := s.read(ctx, func(tx *gorm.DB) error {
+ var h assistantHostRecord
+ if err := tx.Where("person = ?", person).Limit(1).Find(&h).Error; err != nil || h.Origin == "" {
+ return err
+ }
+ var r abilitiesRecord
+ if err := tx.Where("person = ? AND origin = ?", person, h.Origin).Limit(1).Find(&r).Error; err != nil {
+ return err
+ }
+ stale = r.ConfirmedAt == nil || s.now().Sub(*r.ConfirmedAt) > abilitiesStale
+ return nil
+ })
+ if err != nil || !stale {
+ return err
+ }
+ _, _, err = s.RefreshAbilities(ctx, person)
+ return err
+}
+
+// AbilitiesHint is Base's hint that the person's switches changed:
+// fetched within the call, unless a fetch ran less than hintThrottle ago.
+// status is 200 with the revision Equipo now holds, or 202 when it
+// couldn't fetch or didn't try. The hint carries no data.
+func (s *Store) AbilitiesHint(ctx context.Context, person string) (revision int64, status int, err error) {
+ if s.fetchedWithin(person, hintThrottle) {
+ return 0, http.StatusAccepted, nil
+ }
+ revision, fresh, err := s.RefreshAbilities(ctx, person)
+ if err != nil || !fresh {
+ return 0, http.StatusAccepted, err
+ }
+ return revision, http.StatusOK, nil
+}
+
+// RefreshActiveAbilities refreshes, when stale, the board of every person
+// with a turn in flight or a job not finished: housekeeping's minute. A
+// person whose fetch fails is logged and the rest go on.
+func (s *Store) RefreshActiveAbilities(ctx context.Context) error {
+ if len(s.authority.AssistantHosts) == 0 {
+ return nil
+ }
+ var people []string
+ if err := s.read(ctx, func(tx *gorm.DB) error {
+ return tx.Raw(`SELECT person FROM chat_turns WHERE state IN ? UNION SELECT person FROM chat_handoffs WHERE state = ?`, wire.InFlight, handoffOpen).Scan(&people).Error
+ }); err != nil {
+ return err
+ }
+ for _, p := range people {
+ if ctx.Err() != nil {
+ return ctx.Err()
+ }
+ if err := s.refreshIfStale(ctx, p); err != nil {
+ s.logAbilities(p, err)
+ }
+ }
+ return nil
+}
+
+// Allowed checks the person may use ability now, for an act outside a
+// turn (connecting Oficina, Oficina's authenticated reads): a stale copy
+// is fetched first, outside any transaction, then the switches are read
+// in a short one. A refusal is an assist.Failure with ability_off, or
+// unavailable when there is no copy that counts.
+func (s *Store) Allowed(ctx context.Context, person, ability string) error {
+ if err := s.refreshIfStale(ctx, person); err != nil {
+ s.logAbilities(person, err)
+ }
+ var sw Switches
+ if err := s.read(ctx, func(tx *gorm.DB) error {
+ var err error
+ sw, err = (&txn{s: s, ctx: ctx, db: tx}).switches(person)
+ return err
+ }); err != nil {
+ return assist.Failure{Code: "unavailable", Message: "Abilities could not be read."}
+ }
+ if !sw.Can(ability) {
+ return assist.Failure{Code: sw.Refusal(ability)}
+ }
+ return nil
+}
+
+// OwnAbilities is the person's own effective abilities (GET
+// /api/v1/assistant/abilities).
+func (s *Store) OwnAbilities(ctx context.Context, person string) (out wire.AssistantAbilities, err error) {
+ err = s.read(ctx, func(tx *gorm.DB) error {
+ var err error
+ out, err = (&txn{s: s, ctx: ctx, db: tx}).ownAbilities(person)
+ return err
+ })
+ return out, err
+}
+
+// ownAbilitiesRoute is GET abilities: the caller's own board, as Base's
+// Settings line shows it.
+func (h *HTTP) ownAbilitiesRoute(w http.ResponseWriter, r *http.Request, p personapi.PersonPrincipal) {
+ if err := h.Store.refreshIfStale(r.Context(), p.Address); err != nil && h.Logger != nil {
+ h.Logger.Warn("abilities refresh", "err", err)
+ }
+ out, err := h.Store.OwnAbilities(r.Context(), p.Address)
+ if err != nil {
+ h.fail(w, r, err)
+ return
+ }
+ writeJSON(w, http.StatusOK, out)
+}
+
+// abilitiesHint is POST abilities/refresh, with an empty body: 200
+// {revision} once fetched, 202 otherwise.
+func (h *HTTP) abilitiesHint(w http.ResponseWriter, r *http.Request, p personapi.PersonPrincipal) {
+ rev, status, err := h.Store.AbilitiesHint(r.Context(), p.Address)
+ if err != nil && h.Logger != nil {
+ h.Logger.Warn("abilities hint", "err", err)
+ }
+ if status != http.StatusOK {
+ w.WriteHeader(http.StatusAccepted)
+ return
+ }
+ writeJSON(w, http.StatusOK, wire.AbilitiesRefreshed{Revision: rev})
+}
+
+// turnStartRefresh fetches the person's board, when stale, before a
+// request that starts a person turn. The request never waits on it
+// failing: the turn's acts read whatever copy there is.
+func (h *HTTP) turnStartRefresh(r *http.Request, p personapi.PersonPrincipal) {
+ if err := h.Store.refreshIfStale(r.Context(), p.Address); err != nil && h.Logger != nil {
+ h.Logger.Warn("abilities refresh", "err", err)
+ }
+}
diff --git a/internal/equipo/chat/abilities_refresh_test.go b/internal/equipo/chat/abilities_refresh_test.go
new file mode 100644
index 00000000..8aa85c9f
--- /dev/null
+++ b/internal/equipo/chat/abilities_refresh_test.go
@@ -0,0 +1,116 @@
+package chat
+
+import (
+ "context"
+ "testing"
+ "time"
+
+ "amadan.net/oficina/equipo/internal/wire"
+)
+
+// The hint fetches from the person's Base within the call: data only ever
+// comes from Base, the 200 carries the revision now held, and a fetch
+// that failed or one less than 5 s after the last answers 202.
+func TestAbilitiesHintFetches(t *testing.T) {
+ h, base := boardBase(t)
+ base.set(func(f *fakeBoardBase) { f.board.Revision = 5 })
+ rev, status, err := h.s.AbilitiesHint(context.Background(), abPerson)
+ if err != nil || status != 200 || rev != 5 {
+ t.Fatalf("hint: %d %d %v", rev, status, err)
+ }
+ if _, status, _ := h.s.AbilitiesHint(context.Background(), abPerson); status != 202 {
+ t.Errorf("a second hint at once: %d", status)
+ }
+ if n, _ := base.counts(); n != 1 {
+ t.Errorf("throttled hint fetched: %d", n)
+ }
+ h.s.abilities.mu.Lock()
+ h.s.abilities.last[abPerson] = time.Now().Add(-6 * time.Second)
+ h.s.abilities.mu.Unlock()
+ base.set(func(f *fakeBoardBase) { f.status = 503 })
+ if _, status, _ := h.s.AbilitiesHint(context.Background(), abPerson); status != 202 {
+ t.Errorf("a failed fetch: %d", status)
+ }
+ // Someone with no host has nothing to fetch.
+ if _, status, _ := h.s.AbilitiesHint(context.Background(), "owner@example.com"); status != 202 {
+ t.Errorf("no host: %d", status)
+ }
+}
+
+// A person turn starts with a fresh board when the copy is older than
+// 60 s, and not otherwise.
+func TestAbilitiesTurnStartRefresh(t *testing.T) {
+ h, base := boardBase(t)
+ refresh(t, h)
+ if err := h.s.refreshIfStale(context.Background(), abPerson); err != nil {
+ t.Fatal(err)
+ }
+ if n, _ := base.counts(); n != 1 {
+ t.Errorf("fresh copy fetched again: %d", n)
+ }
+ h.advance(61 * time.Second)
+ if err := h.s.refreshIfStale(context.Background(), abPerson); err != nil {
+ t.Fatal(err)
+ }
+ if n, _ := base.counts(); n != 2 {
+ t.Errorf("stale copy not fetched: %d", n)
+ }
+}
+
+// Every minute, people with a turn in flight or an unfinished job are
+// refreshed; an idle person isn't.
+func TestAbilitiesActiveRefreshEvery60s(t *testing.T) {
+ base := startBoardBase(t, "host-token-0123456789abcdef")
+ h := newAbilitiesHarness(t, base.origin())
+ for _, p := range []string{"turn@example.com", "job@example.com", "idle@example.com"} {
+ h.register(t, p, base.origin(), base.token)
+ }
+ if err := h.s.db.G.Create(&turnRecord{ID: "t_run", Person: "turn@example.com", State: wire.TurnRunning, CreatedAt: h.now(), UpdatedAt: h.now()}).Error; err != nil {
+ t.Fatal(err)
+ }
+ if err := h.s.db.G.Create(&handoffRecord{ID: "h_open", Person: "job@example.com", State: handoffOpen, LedgerKey: "k1", CreatedAt: h.now(), UpdatedAt: h.now()}).Error; err != nil {
+ t.Fatal(err)
+ }
+ if err := h.s.RefreshActiveAbilities(context.Background()); err != nil {
+ t.Fatal(err)
+ }
+ for p, want := range map[string]bool{"turn@example.com": true, "job@example.com": true, "idle@example.com": false} {
+ if got := h.row(t, p, base.origin()).ConfirmedAt != nil; got != want {
+ t.Errorf("%s refreshed %v, want %v", p, got, want)
+ }
+ }
+}
+
+// Allowed refreshes a stale copy first, outside any transaction, then
+// reads it: an idle person's first act after a failed hint sees the new
+// board.
+func TestIdleEntryPointRefreshes(t *testing.T) {
+ h, base := boardBase(t)
+ refresh(t, h)
+ if err := h.s.Allowed(context.Background(), abPerson, wire.AbilityAppsRead); err != nil {
+ t.Fatal(err)
+ }
+ base.set(func(f *fakeBoardBase) { f.board.Abilities["apps_read"], f.board.Revision = false, 2 })
+ h.advance(2 * time.Minute)
+ err := h.s.Allowed(context.Background(), abPerson, wire.AbilityAppsRead)
+ if code := refusalCode(err); code != wire.CodeAbilityOff {
+ t.Errorf("after Base turned it off: %v", err)
+ }
+}
+
+// The person's own abilities: every key, the fixed ones, and who to ask.
+func TestOwnAbilitiesRoute(t *testing.T) {
+ h, base := boardBase(t)
+ base.set(func(f *fakeBoardBase) { f.board.Abilities["go_live"] = false })
+ refresh(t, h)
+ fixed, _ := ParseFixed("web=off")
+ h.s.SetFixed(fixed)
+ out, err := h.s.OwnAbilities(context.Background(), abPerson)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(out.Abilities) != len(wire.Abilities) || out.Abilities["web"] || out.Abilities["go_live"] || !out.Abilities["build"] ||
+ len(out.Fixed) != 1 || out.Fixed[0] != "web" || out.Ask != "Paul" {
+ t.Errorf("own abilities %+v", out)
+ }
+}
diff --git a/internal/equipo/chat/assistant_http.go b/internal/equipo/chat/assistant_http.go
index 682c8d9b..9d848703 100644
--- a/internal/equipo/chat/assistant_http.go
+++ b/internal/equipo/chat/assistant_http.go
@@ -39,14 +39,18 @@ func (h *HTTP) MountAssistant(r chi.Router) {
h.messagesWith(w, r, p, lane.Messages)
}))
r.Post("/messages", h.assistantBearer(func(w http.ResponseWriter, r *http.Request, p personapi.PersonPrincipal) {
+ h.turnStartRefresh(r, p)
h.sendWith(w, r, p, lane.Send)
}))
r.Post("/turns/{id}/cancel", h.assistantBearer(func(w http.ResponseWriter, r *http.Request, p personapi.PersonPrincipal) {
h.cancelWith(w, r, p, lane.Cancel)
}))
r.Post("/cards/{id}/answer", h.assistantBearer(func(w http.ResponseWriter, r *http.Request, p personapi.PersonPrincipal) {
+ h.turnStartRefresh(r, p)
h.assistantAnswer(w, r, p, lane)
}))
+ r.Get("/abilities", h.assistantBearer(h.ownAbilitiesRoute))
+ r.Post("/abilities/refresh", h.assistantBearer(h.abilitiesHint))
r.Get("/events", h.assistantBearer(func(w http.ResponseWriter, r *http.Request, p personapi.PersonPrincipal) {
h.oficinaCatchUp(r, p)
h.warmAssistant(r, p)