Abilities: fetch each person's board from Base and apply it
RefreshAbilities fetches GET <origin>/api/v1/abilities with the person's host token (5 s, outside any transaction, one fetch per person at a time) and applies it in one transaction by the spec's table: a 200 is the board, confirmed; a 404 with operations 200 renews the defaults as legacy until the origin has answered the board; a 401 revokes at once; anything else is a failure that changes nothing. A fetch started before the stored one's never overwrites it. A lower revision is applied and audited.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
4 files changed,
+665
−0
internal/equipo/chat/abilities_fetch.go+260 −0internal/equipo/chat/abilities_fetch_test.go+194 −0internal/equipo/chat/abilities_harness_test.go+208 −0internal/equipo/chat/store.go+3 −0
diff --git a/internal/equipo/chat/abilities_fetch.go b/internal/equipo/chat/abilities_fetch.go| new file mode 100644 |
| index 00000000..1d820bc0 |
| --- /dev/null |
| +++ b/internal/equipo/chat/abilities_fetch.go |
| @@ -0,0 +1,260 @@ |
| +package chat |
| + |
| +import ( |
| + "context" |
| + "encoding/json" |
| + "errors" |
| + "io" |
| + "net/http" |
| + "strings" |
| + "sync" |
| + "time" |
| + |
| + "amadan.net/oficina/equipo/internal/wire" |
| + "gorm.io/gorm" |
| +) |
| + |
| +// How Equipo learns a person's abilities from their Base (spec |
| +// 2026-11-26-assistant-abilities §5.3): with the member's host token, |
| +// over the host channel, never the member's own bearer. |
| + |
| +const ( |
| + // abilitiesBound bounds one fetch of the board (and of a legacy Base's |
| + // operations). |
| + abilitiesBound = 5 * time.Second |
| + // maxBoard is the most of Base's answer read. |
| + maxBoard = 16 << 10 |
| + // The audits of a board. |
| + auditAbilitiesRevisionDown = "assistant.abilities.revision_down" |
| + auditAbilitiesRevoked = "assistant.abilities.revoked" |
| +) |
| + |
| +// fetchOutcome is what Base's answer counts as (§5.3's table). |
| +type fetchOutcome int |
| + |
| +const ( |
| + // fetchFailed: no answer that counts (a 5xx, a timeout, a 404 once the |
| + // origin has answered the board). The stored copy stands until it |
| + // expires. |
| + fetchFailed fetchOutcome = iota |
| + // fetchOK: a 200 with a board. |
| + fetchOK |
| + // fetchLegacy: a Base older than the board (its board 404, its |
| + // operations 200), considered only until the origin answers the board. |
| + fetchLegacy |
| + // fetchRevoked: Base no longer honours the token (401 on either route). |
| + fetchRevoked |
| +) |
| + |
| +// abilityState is what the store keeps in memory about people's boards: |
| +// one fetch per person at a time (lock), the fetch order across them |
| +// (seq) and when each person was last fetched (for the hint's throttle). |
| +type abilityState struct { |
| + locks sync.Map // person -> *sync.Mutex |
| + mu sync.Mutex |
| + seq int64 |
| + last map[string]time.Time |
| +} |
| + |
| +// nextFetchSeq is a number above every one taken before in this process, |
| +// and above the wall clock's nanoseconds, so another process's fetch |
| +// started earlier has a lower one. |
| +func (s *Store) nextFetchSeq() int64 { |
| + s.abilities.mu.Lock() |
| + defer s.abilities.mu.Unlock() |
| + n := time.Now().UnixNano() |
| + if n <= s.abilities.seq { |
| + n = s.abilities.seq + 1 |
| + } |
| + s.abilities.seq = n |
| + return n |
| +} |
| + |
| +func (s *Store) personLock(person string) *sync.Mutex { |
| + m, _ := s.abilities.locks.LoadOrStore(person, &sync.Mutex{}) |
| + return m.(*sync.Mutex) |
| +} |
| + |
| +// boardClient calls a person's Base: no redirect followed, so the host |
| +// token goes nowhere but the registered origin. |
| +var boardClient = &http.Client{CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }} |
| + |
| +// fetchBoard asks origin for the board with token, bounded by |
| +// abilitiesBound, outside any transaction. With legacy (the origin has |
| +// never answered the board), a 404 is followed by the operations route, |
| +// whose 200 makes it fetchLegacy. err is set only with fetchFailed, and |
| +// never carries the token. |
| +func (s *Store) fetchBoard(ctx context.Context, origin, token string, legacy bool) (wire.AbilityBoard, fetchOutcome, error) { |
| + ctx, cancel := context.WithTimeout(ctx, abilitiesBound) |
| + defer cancel() |
| + var board wire.AbilityBoard |
| + status, body, err := getWithToken(ctx, origin+"/api/v1/abilities", token) |
| + switch { |
| + case err != nil: |
| + return board, fetchFailed, err |
| + case status == http.StatusUnauthorized: |
| + return board, fetchRevoked, nil |
| + case status == http.StatusOK: |
| + if err := json.Unmarshal(body, &board); err != nil || board.Revision < 0 || len(board.Ask) > 200 { |
| + return wire.AbilityBoard{}, fetchFailed, errors.New("abilities: Base's board was not understood") |
| + } |
| + return board, fetchOK, nil |
| + case status != http.StatusNotFound || !legacy: |
| + return board, fetchFailed, errors.New("abilities: Base answered " + http.StatusText(status)) |
| + } |
| + status, _, err = getWithToken(ctx, origin+"/api/v1/operations", token) |
| + switch { |
| + case err != nil: |
| + return board, fetchFailed, err |
| + case status == http.StatusUnauthorized: |
| + return board, fetchRevoked, nil |
| + case status == http.StatusOK: |
| + return board, fetchLegacy, nil |
| + } |
| + return board, fetchFailed, errors.New("abilities: Base answered " + http.StatusText(status)) |
| +} |
| + |
| +// getWithToken is one GET with the host token as bearer: its status and |
| +// the start of its body. A transport failure is reported without the |
| +// URL, which never holds the token but stays out of logs all the same. |
| +func getWithToken(ctx context.Context, url, token string) (int, []byte, error) { |
| + req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil) |
| + if err != nil { |
| + return 0, nil, errors.New("abilities: bad host origin") |
| + } |
| + req.Header.Set("Authorization", "Bearer "+token) |
| + req.Header.Set("Accept", "application/json") |
| + res, err := boardClient.Do(req) |
| + if err != nil { |
| + return 0, nil, errors.New("abilities: Base did not answer") |
| + } |
| + defer res.Body.Close() |
| + body, _ := io.ReadAll(io.LimitReader(res.Body, maxBoard)) |
| + return res.StatusCode, body, nil |
| +} |
| + |
| +// RefreshAbilities fetches the person's board from their registered Base |
| +// and applies it (§5.3), one fetch per person at a time, outside any |
| +// transaction but the one that applies it. revision is the board's |
| +// revision Equipo then holds; fresh says it applied a 200 or a legacy |
| +// renewal. A person with no host has nothing to fetch. |
| +func (s *Store) RefreshAbilities(ctx context.Context, person string) (revision int64, fresh bool, err error) { |
| + m := s.personLock(person) |
| + m.Lock() |
| + defer m.Unlock() |
| + origin, token, ok, err := s.Host(ctx, person) |
| + if err != nil || !ok { |
| + return 0, false, err |
| + } |
| + var seen []bool |
| + if err := s.read(ctx, func(tx *gorm.DB) error { |
| + return tx.Model(&abilitiesRecord{}).Where("person = ? AND origin = ?", person, origin).Pluck("coalesce(authoritative_seen, 0)", &seen).Error |
| + }); err != nil { |
| + return 0, false, err |
| + } |
| + seq := s.nextFetchSeq() |
| + s.abilities.mu.Lock() |
| + if s.abilities.last == nil { |
| + s.abilities.last = map[string]time.Time{} |
| + } |
| + s.abilities.last[person] = time.Now() |
| + s.abilities.mu.Unlock() |
| + board, outcome, ferr := s.fetchBoard(ctx, origin, token, len(seen) == 0 || !seen[0]) |
| + if outcome == fetchFailed { |
| + s.logAbilities(person, ferr) |
| + } |
| + var changed bool |
| + err = s.tx(ctx, func(t *txn) error { |
| + var err error |
| + changed, err = t.applyBoard(person, origin, seq, board, outcome) |
| + if err != nil { |
| + return err |
| + } |
| + var r abilitiesRecord |
| + if err := t.db.Where("person = ? AND origin = ?", person, origin).Limit(1).Find(&r).Error; err != nil { |
| + return err |
| + } |
| + revision = r.Revision |
| + return nil |
| + }) |
| + if err != nil { |
| + return 0, false, err |
| + } |
| + if changed { |
| + if ops := s.operations(); ops != nil { |
| + ops.Forget(person) |
| + } |
| + } |
| + return revision, outcome == fetchOK || outcome == fetchLegacy, nil |
| +} |
| + |
| +// logAbilities reports a fetch that failed: by person, never a token. |
| +func (s *Store) logAbilities(person string, err error) { |
| + if l := s.logger.Load(); l != nil && err != nil { |
| + l.Warn("abilities: fetch failed", "person", person, "err", err) |
| + } |
| +} |
| + |
| +// fetchedWithin reports whether the person's board was fetched less than |
| +// d ago (the hint's throttle). |
| +func (s *Store) fetchedWithin(person string, d time.Duration) bool { |
| + s.abilities.mu.Lock() |
| + defer s.abilities.mu.Unlock() |
| + at, ok := s.abilities.last[person] |
| + return ok && time.Since(at) < d |
| +} |
| + |
| +// applyBoard applies one fetch's outcome to the person's copy at origin, |
| +// by §5.3's table, unless a fetch started after it was applied first. |
| +// changed: what the person may do may have changed. |
| +func (t *txn) applyBoard(person, origin string, seq int64, b wire.AbilityBoard, outcome fetchOutcome) (changed bool, err error) { |
| + if outcome == fetchFailed { |
| + return false, nil |
| + } |
| + origin = strings.ToLower(origin) |
| + var r abilitiesRecord |
| + if err := t.db.Where("person = ? AND origin = ?", person, origin).Limit(1).Find(&r).Error; err != nil { |
| + return false, err |
| + } |
| + if r.Person != "" && r.FetchSeq > seq { |
| + return false, nil |
| + } |
| + prior := r |
| + r.Person, r.Origin, r.FetchSeq = person, origin, seq |
| + now := t.now() |
| + switch outcome { |
| + case fetchRevoked: |
| + r.RevokedAt = &now |
| + if r.Source == "" { |
| + r.Source, r.Abilities = SourceBase, "{}" |
| + } |
| + if err := t.db.Save(&r).Error; err != nil { |
| + return false, err |
| + } |
| + return prior.RevokedAt == nil, t.s.authority.Audit(t.db, person, auditAbilitiesRevoked, origin) |
| + case fetchLegacy: |
| + if r.AuthoritativeSeen { |
| + return false, nil |
| + } |
| + raw, _ := json.Marshal(defaultBoard()) |
| + r.Abilities, r.Admin, r.Ask, r.Source, r.Revision = string(raw), false, "", SourceLegacy, 0 |
| + case fetchOK: |
| + raw, err := json.Marshal(b.Abilities) |
| + if err != nil { |
| + return false, err |
| + } |
| + down := prior.Source == SourceBase && prior.Person != "" && b.Revision < prior.Revision |
| + r.Abilities, r.Admin, r.Ask, r.Source, r.Revision, r.AuthoritativeSeen = string(raw), b.Admin, b.Ask, SourceBase, b.Revision, true |
| + if down { |
| + if err := t.s.authority.Audit(t.db, person, auditAbilitiesRevisionDown, origin); err != nil { |
| + return false, err |
| + } |
| + } |
| + } |
| + r.ConfirmedAt, r.RevokedAt = &now, nil |
| + if err := t.db.Save(&r).Error; err != nil { |
| + return false, err |
| + } |
| + changed = prior.Person == "" || prior.Abilities != r.Abilities || prior.Admin != r.Admin || prior.RevokedAt != nil || prior.Source != r.Source |
| + return changed, nil |
| +} |
diff --git a/internal/equipo/chat/abilities_fetch_test.go b/internal/equipo/chat/abilities_fetch_test.go| new file mode 100644 |
| index 00000000..cbd56579 |
| --- /dev/null |
| +++ b/internal/equipo/chat/abilities_fetch_test.go |
| @@ -0,0 +1,194 @@ |
| +package chat |
| + |
| +import ( |
| + "context" |
| + "testing" |
| + "time" |
| +) |
| + |
| +func boardBase(t *testing.T) (*abilitiesHarness, *fakeBoardBase) { |
| + t.Helper() |
| + base := startBoardBase(t, "host-token-0123456789abcdef") |
| + h := newAbilitiesHarness(t, base.origin()) |
| + h.register(t, abPerson, base.origin(), base.token) |
| + return h, base |
| +} |
| + |
| +func refresh(t *testing.T, h *abilitiesHarness) (int64, bool) { |
| + t.Helper() |
| + rev, fresh, err := h.s.RefreshAbilities(context.Background(), abPerson) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + return rev, fresh |
| +} |
| + |
| +// A 200 is applied: the board, confirmed now, and the origin has now |
| +// answered the board. |
| +func TestAbilitiesFetchApplies200(t *testing.T) { |
| + h, base := boardBase(t) |
| + base.set(func(f *fakeBoardBase) { f.board.Revision, f.board.Abilities["web"], f.board.Admin = 7, false, true }) |
| + rev, fresh := refresh(t, h) |
| + r := h.row(t, abPerson, base.origin()) |
| + b, _ := r.board() |
| + if rev != 7 || !fresh || r.Source != SourceBase || !r.AuthoritativeSeen || r.ConfirmedAt == nil || !r.ConfirmedAt.Equal(h.now()) || |
| + b.Abilities["web"] || !b.Abilities["build"] || !b.Admin || b.Ask != "Paul" { |
| + t.Errorf("rev %d fresh %v row %+v board %+v", rev, fresh, r, b) |
| + } |
| + if got := base.tokens[0]; got != "Bearer "+base.token { |
| + t.Errorf("fetched with %q", got) |
| + } |
| +} |
| + |
| +// An unchanged board, answered again, keeps the copy confirmed: hours of |
| +// equal-revision 200s never let it expire. |
| +func TestUnchangedBoardStaysConfirmed(t *testing.T) { |
| + h, base := boardBase(t) |
| + refresh(t, h) |
| + for i := 0; i < 5; i++ { |
| + h.advance(time.Hour) |
| + refresh(t, h) |
| + } |
| + if r := h.row(t, abPerson, base.origin()); r.ConfirmedAt == nil || !r.ConfirmedAt.Equal(h.now()) || r.Revision != 1 { |
| + t.Errorf("row %+v", r) |
| + } |
| +} |
| + |
| +// A legacy row (an old Base) is replaced by the first 200, whatever its |
| +// revision. |
| +func TestLegacyPromotedByAnyRevision(t *testing.T) { |
| + h, base := boardBase(t) |
| + base.set(func(f *fakeBoardBase) { f.status = 404 }) |
| + refresh(t, h) |
| + if r := h.row(t, abPerson, base.origin()); r.Source != SourceLegacy || r.AuthoritativeSeen || r.ConfirmedAt == nil { |
| + t.Fatalf("legacy row %+v", r) |
| + } |
| + base.set(func(f *fakeBoardBase) { f.status, f.board.Revision, f.board.Abilities["build"] = 200, 0, false }) |
| + refresh(t, h) |
| + r := h.row(t, abPerson, base.origin()) |
| + b, _ := r.board() |
| + if r.Source != SourceBase || !r.AuthoritativeSeen || b.Abilities["build"] { |
| + t.Errorf("after Base's board: %+v %+v", r, b) |
| + } |
| +} |
| + |
| +// Two fetches overlap and the older one's answer comes last: it changes |
| +// nothing. |
| +func TestStaleFetchDoesNotOverwrite(t *testing.T) { |
| + h, base := boardBase(t) |
| + entered, release := base.holdNext() |
| + done := make(chan error, 1) |
| + go func() { |
| + _, _, err := h.s.RefreshAbilities(context.Background(), abPerson) |
| + done <- err |
| + }() |
| + <-entered |
| + // Meanwhile Base changes, and another process fetches it. |
| + base.set(func(f *fakeBoardBase) { f.board.Revision, f.board.Abilities["web"] = 2, false }) |
| + newer, outcome, err := h.s.fetchBoard(context.Background(), base.origin(), base.token, false) |
| + if err != nil || outcome != fetchOK { |
| + t.Fatal(outcome, err) |
| + } |
| + seq := h.s.nextFetchSeq() |
| + if err := h.s.tx(context.Background(), func(t *txn) error { |
| + _, err := t.applyBoard(abPerson, base.origin(), seq, newer, fetchOK) |
| + return err |
| + }); err != nil { |
| + t.Fatal(err) |
| + } |
| + // The old answer (revision 2 as well now: what matters is it started |
| + // first) arrives last. |
| + base.set(func(f *fakeBoardBase) { f.board.Revision, f.board.Abilities["web"] = 1, true }) |
| + release() |
| + if err := <-done; err != nil { |
| + t.Fatal(err) |
| + } |
| + r := h.row(t, abPerson, base.origin()) |
| + if b, _ := r.board(); r.Revision != 2 || b.Abilities["web"] { |
| + t.Errorf("the slow old answer overwrote the newer: %+v %+v", r, b) |
| + } |
| +} |
| + |
| +// A lower revision (a restored Base) is applied, as Base is the |
| +// authority, and audited. |
| +func TestRevisionDownAudited(t *testing.T) { |
| + h, base := boardBase(t) |
| + base.set(func(f *fakeBoardBase) { f.board.Revision = 9 }) |
| + refresh(t, h) |
| + base.set(func(f *fakeBoardBase) { f.board.Revision, f.board.Abilities["go_live"] = 4, false }) |
| + rev, _ := refresh(t, h) |
| + r := h.row(t, abPerson, base.origin()) |
| + if b, _ := r.board(); rev != 4 || b.Abilities["go_live"] { |
| + t.Errorf("lower revision not applied: %d %+v", rev, b) |
| + } |
| + if got := h.audited("assistant.abilities.revision_down"); len(got) != 1 { |
| + t.Errorf("audits %v", got) |
| + } |
| +} |
| + |
| +// A 401 revokes the copy at once. |
| +func TestAbilities401RevokesAtOnce(t *testing.T) { |
| + h, base := boardBase(t) |
| + refresh(t, h) |
| + base.set(func(f *fakeBoardBase) { f.token = "another-token-0123456789" }) |
| + if _, fresh := refresh(t, h); fresh { |
| + t.Error("a 401 counted as fresh") |
| + } |
| + if r := h.row(t, abPerson, base.origin()); r.RevokedAt == nil { |
| + t.Errorf("not revoked: %+v", r) |
| + } |
| + if got := h.audited("assistant.abilities.revoked"); len(got) != 1 { |
| + t.Errorf("audits %v", got) |
| + } |
| +} |
| + |
| +// Once Base has answered the board, a 404 is a failure (a rollback), not |
| +// a legacy Base: nothing changes, and nothing widens. |
| +func TestAbilities404AfterBoardIsFailure(t *testing.T) { |
| + h, base := boardBase(t) |
| + base.set(func(f *fakeBoardBase) { f.board.Abilities["build"] = false }) |
| + refresh(t, h) |
| + before := h.row(t, abPerson, base.origin()) |
| + h.advance(time.Minute) |
| + base.set(func(f *fakeBoardBase) { f.status = 404 }) |
| + if _, fresh := refresh(t, h); fresh { |
| + t.Error("a 404 after a board counted as fresh") |
| + } |
| + after := h.row(t, abPerson, base.origin()) |
| + if b, _ := after.board(); after.Source != SourceBase || !after.ConfirmedAt.Equal(*before.ConfirmedAt) || b.Abilities["build"] { |
| + t.Errorf("after the 404: %+v", after) |
| + } |
| + if _, ops := base.counts(); ops != 0 { |
| + t.Errorf("the operations route was asked %d times after a board", ops) |
| + } |
| +} |
| + |
| +// An old Base keeps its member on the defaults across several 10-minute |
| +// periods, renewed through its operations route; upgraded, its first 200 |
| +// is the board, and a later 404 is a failure. |
| +func TestLegacyBaseAcrossExpiry(t *testing.T) { |
| + h, base := boardBase(t) |
| + base.set(func(f *fakeBoardBase) { f.status = 404 }) |
| + for i := 0; i < 3; i++ { |
| + h.advance(10 * time.Minute) |
| + if _, fresh := refresh(t, h); !fresh { |
| + t.Fatalf("renewal %d not fresh", i) |
| + } |
| + if r := h.row(t, abPerson, base.origin()); r.Source != SourceLegacy || !r.ConfirmedAt.Equal(h.now()) { |
| + t.Fatalf("renewal %d: %+v", i, r) |
| + } |
| + } |
| + base.set(func(f *fakeBoardBase) { f.status = 200 }) |
| + refresh(t, h) |
| + if r := h.row(t, abPerson, base.origin()); r.Source != SourceBase || !r.AuthoritativeSeen { |
| + t.Fatalf("upgraded: %+v", r) |
| + } |
| + base.set(func(f *fakeBoardBase) { f.status = 404 }) |
| + h.advance(time.Minute) |
| + if _, fresh := refresh(t, h); fresh { |
| + t.Error("a 404 after the upgrade counted as fresh") |
| + } |
| + if r := h.row(t, abPerson, base.origin()); r.Source != SourceBase { |
| + t.Errorf("after the upgrade's 404: %+v", r) |
| + } |
| +} |
diff --git a/internal/equipo/chat/abilities_harness_test.go b/internal/equipo/chat/abilities_harness_test.go| new file mode 100644 |
| index 00000000..c5976421 |
| --- /dev/null |
| +++ b/internal/equipo/chat/abilities_harness_test.go |
| @@ -0,0 +1,208 @@ |
| +package chat |
| + |
| +import ( |
| + "context" |
| + "encoding/json" |
| + "io" |
| + "log/slog" |
| + "net/http" |
| + "net/http/httptest" |
| + "os" |
| + "path/filepath" |
| + "strings" |
| + "sync" |
| + "testing" |
| + "time" |
| + |
| + "amadan.net/oficina/equipo/internal/wire" |
| + "amadan.net/rastrillo/rastrillo/db" |
| + "gorm.io/gorm" |
| +) |
| + |
| +// fakeBoardBase is a person's Base as Equipo fetches their board from it |
| +// (GET /api/v1/abilities) and, for a Base older than the board, its |
| +// operations (GET /api/v1/operations), both with the member's host token. |
| +// Each route answers its scripted status; 200 on the board serves board. |
| +type fakeBoardBase struct { |
| + srv *httptest.Server |
| + |
| + mu sync.Mutex |
| + token string |
| + board wire.AbilityBoard |
| + status int // the board's status (200 by default) |
| + opsStatus int // the operations' status (200 by default) |
| + boardCalls int |
| + opsCalls int |
| + tokens []string |
| + // hold, when set, keeps the next board request until it is closed; |
| + // entered is closed when that request arrives. |
| + hold, entered chan struct{} |
| +} |
| + |
| +func startBoardBase(t *testing.T, token string) *fakeBoardBase { |
| + t.Helper() |
| + f := &fakeBoardBase{token: token, status: 200, opsStatus: 200, |
| + board: wire.AbilityBoard{Revision: 1, Ask: "Paul", Abilities: map[string]bool{"web": true, "apps_read": true, "apps_write": true, "build": true, "go_live": true, "services": true, "services_add": true}}} |
| + f.srv = httptest.NewServer(http.HandlerFunc(f.serve)) // 127.0.0.1 only |
| + t.Cleanup(f.srv.Close) |
| + return f |
| +} |
| + |
| +func (f *fakeBoardBase) origin() string { return f.srv.URL } |
| + |
| +func (f *fakeBoardBase) serve(w http.ResponseWriter, r *http.Request) { |
| + f.mu.Lock() |
| + f.tokens = append(f.tokens, r.Header.Get("Authorization")) |
| + authorized := r.Header.Get("Authorization") == "Bearer "+f.token |
| + var status int |
| + var body any |
| + hold, entered := f.hold, f.entered |
| + switch r.URL.Path { |
| + case "/api/v1/abilities": |
| + f.boardCalls++ |
| + status, body = f.status, f.board |
| + f.hold, f.entered = nil, nil |
| + case "/api/v1/operations": |
| + f.opsCalls++ |
| + status, body, hold = f.opsStatus, map[string]any{"operations": []any{}}, nil |
| + default: |
| + status, hold = 404, nil |
| + } |
| + f.mu.Unlock() |
| + if hold != nil { |
| + close(entered) |
| + <-hold |
| + } |
| + if !authorized { |
| + status = 401 |
| + } |
| + w.Header().Set("Content-Type", "application/json") |
| + w.WriteHeader(status) |
| + if status == 200 { |
| + _ = json.NewEncoder(w).Encode(body) |
| + } |
| +} |
| + |
| +func (f *fakeBoardBase) set(fn func(f *fakeBoardBase)) { |
| + f.mu.Lock() |
| + defer f.mu.Unlock() |
| + fn(f) |
| +} |
| + |
| +func (f *fakeBoardBase) counts() (board, ops int) { |
| + f.mu.Lock() |
| + defer f.mu.Unlock() |
| + return f.boardCalls, f.opsCalls |
| +} |
| + |
| +// holdNext keeps the next board request until release; entered is |
| +// closed when it arrives. |
| +func (f *fakeBoardBase) holdNext() (entered <-chan struct{}, release func()) { |
| + f.mu.Lock() |
| + defer f.mu.Unlock() |
| + f.hold, f.entered = make(chan struct{}), make(chan struct{}) |
| + hold := f.hold |
| + var once sync.Once |
| + return f.entered, func() { once.Do(func() { close(hold) }) } |
| +} |
| + |
| +// abilitiesHarness is a chat Store whose people's Bases are allowed hosts, |
| +// with a clock the test moves and an audit it reads. |
| +type abilitiesHarness struct { |
| + s *Store |
| + mu sync.Mutex |
| + at time.Time |
| + audits []string |
| +} |
| + |
| +const abPerson = "member@example.com" |
| + |
| +func newAbilitiesHarness(t *testing.T, hosts ...string) *abilitiesHarness { |
| + t.Helper() |
| + src, err := hkTemplatePath() |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + raw, err := os.ReadFile(src) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + path := filepath.Join(t.TempDir(), "abilities.db") |
| + if err := os.WriteFile(path, raw, 0o600); err != nil { |
| + t.Fatal(err) |
| + } |
| + d, err := db.Open(path, slog.New(slog.NewTextHandler(io.Discard, nil))) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + t.Cleanup(func() { _ = d.Close() }) |
| + h := &abilitiesHarness{at: time.Date(2026, 11, 28, 12, 0, 0, 0, time.UTC)} |
| + lowered := make([]string, len(hosts)) |
| + for i, o := range hosts { |
| + lowered[i] = strings.ToLower(o) |
| + } |
| + h.s = NewStore(d, Authority{ |
| + CurrentPerson: func(context.Context, *gorm.DB) error { return nil }, |
| + PrimaryRunner: func(*gorm.DB, string) (string, error) { return "RUNNER1", nil }, |
| + Audit: func(_ *gorm.DB, actor, kind, record string) error { |
| + h.mu.Lock() |
| + h.audits = append(h.audits, kind+" "+actor+" "+record) |
| + h.mu.Unlock() |
| + return nil |
| + }, |
| + Copy: func(key string) string { return key }, |
| + AssistantHosts: lowered, |
| + Seal: func(_ string, v any) (string, error) { |
| + raw, err := json.Marshal(v) |
| + return string(raw), err |
| + }, |
| + Open: func(_ string, sealed string, v any) error { return json.Unmarshal([]byte(sealed), v) }, |
| + }, nil) |
| + h.s.SetClock(h.now) |
| + return h |
| +} |
| + |
| +func (h *abilitiesHarness) now() time.Time { |
| + h.mu.Lock() |
| + defer h.mu.Unlock() |
| + return h.at |
| +} |
| + |
| +func (h *abilitiesHarness) advance(d time.Duration) { |
| + h.mu.Lock() |
| + h.at = h.at.Add(d) |
| + h.mu.Unlock() |
| +} |
| + |
| +func (h *abilitiesHarness) audited(kind string) []string { |
| + h.mu.Lock() |
| + defer h.mu.Unlock() |
| + var out []string |
| + for _, a := range h.audits { |
| + if strings.HasPrefix(a, kind+" ") { |
| + out = append(out, a) |
| + } |
| + } |
| + return out |
| +} |
| + |
| +// register stores origin and token as the person's Base host, as PUT host |
| +// left it, without asking Base. |
| +func (h *abilitiesHarness) register(t *testing.T, person, origin, token string) { |
| + t.Helper() |
| + sealed, _ := json.Marshal(token) |
| + rec := assistantHostRecord{Person: person, Origin: strings.ToLower(origin), Token: string(sealed), Revision: 1, UpdatedAt: h.now()} |
| + if err := h.s.db.G.Save(&rec).Error; err != nil { |
| + t.Fatal(err) |
| + } |
| +} |
| + |
| +// row is the person's stored board at origin. |
| +func (h *abilitiesHarness) row(t *testing.T, person, origin string) abilitiesRecord { |
| + t.Helper() |
| + var r abilitiesRecord |
| + if err := h.s.db.G.Where("person = ? AND origin = ?", person, strings.ToLower(origin)).Limit(1).Find(&r).Error; err != nil { |
| + t.Fatal(err) |
| + } |
| + return r |
| +} |
diff --git a/internal/equipo/chat/store.go b/internal/equipo/chat/store.go| index 2f6b0d87..423382f4 100644 |
| --- a/internal/equipo/chat/store.go |
| +++ b/internal/equipo/chat/store.go |
| @@ -126,6 +126,9 @@ type Store struct { |
| // projectJobHook stands in for projectJob in the minute's sweep (a |
| // test's failing card); nil projects as usual. |
| projectJobHook func(*txn, handoffRecord) error |
| + // abilities is what the store keeps in memory about people's boards |
| + // (abilities_fetch.go). |
| + abilities abilityState |
| } |
| // SetFrameTap sees every frame the instance sends a runner, as sent |