oficina / equipo Public

instance: advice ledger and actions, usage totals, API

The forward-only chat_advice table (migration 0074, with chat_steps
held_at), refreshed each housekeeping minute: withdrawn silently when its
facts stop holding, held through quiet hours, one quiet card in the
conversation, never Needs you. Actions are the ordinary budget,
preference and priority calls in the advice's transaction, revision-
checked and audited with source advice and the key. GET /advice, POST
/advice/{id}/act and /dismiss, GET /usage.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by paul@keymail.dev 5a64ad0117b11550d267b87e0d21d3a20ce70c66 parent dc29038
15 files changed, +1,419 −117
  • internal/equipo/chat/advice.go +551 −0
  • internal/equipo/chat/advice_store_test.go +450 −0
  • internal/equipo/chat/connections.go +48 −42
  • internal/equipo/chat/housekeeping_control.go +16 −3
  • internal/equipo/chat/http.go +1 −0
  • internal/equipo/chat/metered.go +26 −21
  • internal/equipo/chat/models.go +1 −1
  • internal/equipo/chat/projects.go +12 −0
  • internal/equipo/chat/research.go +1 −1
  • internal/equipo/chat/schedule.go +59 −45
  • internal/equipo/chat/tasks.go +5 −2
  • internal/equipo/chat/usage.go +242 −0
  • internal/equipo/migrations/0074_thin_advice.sql +3 −0
  • internal/equipo/migrations/schema.sql +3 −1
  • internal/plan3test/person_api_contract_test.go +1 −1
diff --git a/internal/equipo/chat/advice.go b/internal/equipo/chat/advice.go
new file mode 100644
index 00000000..136c7f9c
--- /dev/null
+++ b/internal/equipo/chat/advice.go
@@ -0,0 +1,551 @@
+package chat
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "slices"
+ "strconv"
+ "time"
+
+ "gorm.io/gorm"
+
+ "amadan.net/oficina/equipo/internal/advice"
+ "amadan.net/oficina/equipo/internal/wire"
+)
+
+// Advice on the instance (connectors spec 2026-11-12 rev 3.2 §9, slice
+// S4). advice.Compute turns the person's recorded facts into advice; the
+// rules here keep at most one card open, at most one new card a day,
+// silence a key after Not now, withdraw advice whose facts stopped
+// holding without a word, and hold a card made in quiet hours until they
+// end (housekeeping's VisibleAt). A card is never Needs you and never a
+// push. Its action is the ordinary call, revision-checked, in the same
+// transaction as the advice it answers, and recorded with source advice
+// and the key. The coordinator cannot create, change or dismiss advice.
+
+// adviceRecord is one piece of advice shown to a person. The table only
+// moves forward: open, then acted, dismissed or withdrawn. Facts is the
+// action as the person saw it (advice.Advice JSON); ShownAt the time it
+// counts for (its visible time); CardID its quiet card.
+type adviceRecord struct {
+ ID string `gorm:"primaryKey"`
+ Person string `gorm:"index:chat_advice_person,priority:1"`
+ Key string `gorm:"index:chat_advice_person,priority:2"`
+ Kind string
+ State string
+ Subject string
+ Facts string
+ Text string
+ Act string
+ Dismiss string
+ CardID string
+ Revision int64
+ CreatedAt time.Time
+ UpdatedAt time.Time
+ VisibleAt *time.Time
+ ShownAt time.Time
+ DismissedAt *time.Time
+}
+
+func (adviceRecord) TableName() string { return "chat_advice" }
+
+func adviceView(r adviceRecord) wire.Advice {
+ v := wire.Advice{ID: r.ID, Kind: r.Kind, Key: r.Key, State: r.State, Text: r.Text, Act: r.Act, Dismiss: r.Dismiss, Revision: r.Revision, CreatedAt: r.CreatedAt, VisibleAt: r.VisibleAt}
+ _ = json.Unmarshal([]byte(r.Subject), &v.Subject)
+ return v
+}
+
+// Money is an amount of micro-units in words: $1, $0.84, $6.20.
+func Money(micros int64, currency string) string {
+ amount := strconv.FormatInt(micros/1_000_000, 10)
+ if micros%1_000_000 != 0 {
+ amount = strconv.FormatFloat(float64(micros)/1e6, 'f', 2, 64)
+ }
+ if currency == "USD" || currency == "" {
+ return "$" + amount
+ }
+ return amount + " " + currency
+}
+
+// adviceDay is a day as advice says it: Thu 19 Nov.
+func adviceDay(t time.Time) string { return t.UTC().Format("Mon 2 Jan") }
+
+// adviceFacts are the person's facts as advice reads them: their own
+// connections, preference, open tasks and those tasks' queued steps.
+func (t *txn) adviceFacts(person string) (advice.Facts, map[string]connectionRecord, error) {
+ f := advice.Facts{}
+ conns, err := t.connections(person)
+ if err != nil {
+ return f, nil, err
+ }
+ byID := map[string]connectionRecord{}
+ for _, r := range conns {
+ if r.State == wire.ConnConnecting || r.LocalID == "" {
+ continue
+ }
+ byID[r.ID] = r
+ c := advice.Conn{ID: r.ID, Provider: r.Provider, Runner: r.RunnerID, State: r.State, Billing: r.Billing}
+ if c.Billing == "" {
+ c.Billing = wire.BillingSubscription
+ }
+ var h wire.Headroom
+ if r.Headroom != "" && json.Unmarshal([]byte(r.Headroom), &h) == nil {
+ for _, w := range h.Windows {
+ c.Windows = append(c.Windows, advice.Window{Used: w.UsedPercent / 100, ResetsAt: w.ResetsAt})
+ }
+ if len(c.Windows) == 0 && h.Utilization != nil {
+ c.Windows = append(c.Windows, advice.Window{Used: *h.Utilization, ResetsAt: h.ResetsAt})
+ }
+ }
+ if b, ok := budgetOf(r); ok {
+ c.BudgetDay, c.BudgetMonth, c.BudgetRevision, c.Currency = b.Day, b.Month, b.Revision, b.Currency
+ }
+ var sp wire.Spend
+ if r.Spend != "" && json.Unmarshal([]byte(r.Spend), &sp) == nil {
+ c.SpendDay, c.SpendMonth, c.SpendUnknown = sp.Day, sp.Month, sp.Unknown
+ } else if c.Billing == wire.BillingMetered {
+ // No spend reported yet: nothing is near.
+ c.SpendUnknown = true
+ }
+ f.Conns = append(f.Conns, c)
+ }
+ pref, err := t.preferenceOf(person)
+ if err != nil {
+ return f, nil, err
+ }
+ f.Preference = advice.Preference{Provider: pref.Provider, Until: pref.Until, Revision: pref.Revision}
+ if t.s.authority.PrimaryRunner != nil {
+ if f.Primary, err = t.s.authority.PrimaryRunner(t.db, person); err != nil {
+ f.Primary = ""
+ }
+ }
+ var tasks []taskRecord
+ if err := t.db.Where("creator = ? AND cancel_requested = ? AND (folded_into IS NULL OR folded_into = '')", person, false).Find(&tasks).Error; err != nil {
+ return f, nil, err
+ }
+ open := map[string]bool{}
+ var ids []string
+ for _, k := range tasks {
+ if wire.FinalStage(k.Stage) {
+ continue
+ }
+ open[k.ID] = true
+ ids = append(ids, k.ID)
+ f.Tasks = append(f.Tasks, advice.Task{ID: k.ID, CreatedAt: k.CreatedAt, Priority: k.Priority, By: k.DueBy, Revision: k.Revision})
+ }
+ if len(ids) == 0 {
+ return f, byID, nil
+ }
+ var steps []stepRecord
+ if err := t.db.Where("task_id IN ? AND state = ?", ids, wire.StepQueued).Order("task_id, id").Find(&steps).Error; err != nil {
+ return f, nil, err
+ }
+ for _, s := range steps {
+ st := advice.Step{Task: s.TaskID, Role: s.Specialist, Runner: s.RunnerID, Housekeeping: housekeepingAttempt(s)}
+ if h := stepHold(s); h != nil {
+ st.Hold, st.HoldResets, st.HeldSince = h.Reason, h.ResetsAt, s.HeldAt
+ }
+ f.Steps = append(f.Steps, st)
+ }
+ return f, byID, nil
+}
+
+// adviceWords are a card's fixed words: its line, its action and its
+// Not now.
+func (t *txn) adviceWords(a advice.Advice, conns map[string]connectionRecord) (text, act, dismiss string) {
+ dismiss = t.words("advice.not_now")
+ n := len(a.Tasks)
+ switch a.Kind {
+ case wire.AdviceBudgetNear:
+ name := providerWord(conns[a.Connection].Provider)
+ dismiss = t.words("advice.leave_it")
+ if a.Window == advice.BudgetDay {
+ return t.words("advice.budget_near.day", name, Money(a.Spend, a.Currency), Money(a.Budget, a.Currency)), t.words("advice.budget_near.raise_day", Money(a.Raise, a.Currency)), dismiss
+ }
+ return t.words("advice.budget_near.month", name, Money(a.Spend, a.Currency), Money(a.Budget, a.Currency)), t.words("advice.budget_near.raise_month", Money(a.Raise, a.Currency)), dismiss
+ case wire.AdvicePreferSwitch:
+ from, to, until := providerWord(a.From), providerWord(a.To), adviceDay(a.Until)
+ return t.words("advice.prefer_switch", from, until, to, to), t.words("advice.prefer_switch.act", to, until), dismiss
+ case wire.AdviceDeferTasks:
+ act = t.words("advice.defer_tasks.act_many")
+ if n == 1 {
+ act = t.words("advice.defer_tasks.act_one")
+ }
+ switch {
+ case n == 1 && a.ResetsAt != nil:
+ return t.words("advice.defer_tasks.one", adviceDay(*a.ResetsAt)), act, dismiss
+ case n == 1:
+ return t.words("advice.defer_tasks.one_no_reset"), act, dismiss
+ case a.ResetsAt != nil:
+ return t.words("advice.defer_tasks.many", n, adviceDay(*a.ResetsAt)), act, dismiss
+ }
+ return t.words("advice.defer_tasks.many_no_reset", n), act, dismiss
+ case wire.AdviceHeldLong:
+ if n == 1 {
+ return t.words("advice.held_long.one"), t.words("advice.held_long.act_one"), dismiss
+ }
+ return t.words("advice.held_long.many", n), t.words("advice.held_long.act_many"), dismiss
+ }
+ return "", "", dismiss
+}
+
+// adviceRows are every piece of advice the person was shown, oldest
+// first.
+func (t *txn) adviceRows(person string) ([]adviceRecord, error) {
+ var rows []adviceRecord
+ err := t.db.Where("person = ?", person).Order("created_at, id").Find(&rows).Error
+ return rows, err
+}
+
+// RefreshAdvice looks at the person's facts now: open advice whose facts
+// stopped holding is withdrawn silently (its words follow facts that
+// moved but still hold); with none open, the first eligible key not
+// silenced becomes the day's one new card, held until quiet hours end.
+// It runs on the housekeeping loop's minute, so on fact changes and at
+// 08:00.
+func (s *Store) RefreshAdvice(ctx context.Context, person string) error {
+ return s.tx(ctx, func(t *txn) error { return t.refreshAdvice(person) })
+}
+
+func (t *txn) refreshAdvice(person string) error {
+ if ok, err := t.activeMember(person); err != nil || !ok {
+ return err
+ }
+ now := t.hkNow()
+ f, conns, err := t.adviceFacts(person)
+ if err != nil {
+ return err
+ }
+ eligible := advice.Compute(f, now)
+ rows, err := t.adviceRows(person)
+ if err != nil {
+ return err
+ }
+ open := false
+ for i := range rows {
+ r := &rows[i]
+ if r.State != wire.AdviceOpen {
+ continue
+ }
+ a, holds := advice.Holds(eligible, r.Key)
+ if !holds {
+ if err := t.closeAdvice(r, wire.AdviceWithdrawn, ""); err != nil {
+ return err
+ }
+ continue
+ }
+ open = true
+ if err := t.followAdvice(r, a, conns); err != nil {
+ return err
+ }
+ }
+ set, err := t.hkSettings(person)
+ if err != nil {
+ return err
+ }
+ loc := t.zone(person)
+ visible := set.quiet().VisibleAt(now, loc)
+ shown := now
+ if visible != nil {
+ shown = *visible
+ }
+ past := make([]advice.Past, 0, len(rows))
+ for _, r := range rows {
+ past = append(past, advice.Past{Key: r.Key, State: r.State, Shown: r.ShownAt, DismissedAt: r.DismissedAt})
+ }
+ pick := advice.Choose(eligible, past, open, now, shown, loc)
+ if pick == nil {
+ return nil
+ }
+ return t.newAdvice(person, *pick, conns, now, visible)
+}
+
+// newAdvice writes the day's card: the advice row and its quiet card in
+// the conversation, held until visible when it is quiet hours.
+func (t *txn) newAdvice(person string, a advice.Advice, conns map[string]connectionRecord, now time.Time, visible *time.Time) error {
+ text, act, dismiss := t.adviceWords(a, conns)
+ r := adviceRecord{ID: newID("ad_"), Person: person, Key: a.Key, Kind: a.Kind, State: wire.AdviceOpen, Subject: asJSON(a.Subject), Facts: asJSON(a), Text: text, Act: act, Dismiss: dismiss, Revision: 1, CreatedAt: now, UpdatedAt: now, VisibleAt: visible, ShownAt: now}
+ if visible != nil {
+ r.ShownAt = *visible
+ }
+ opts, _ := json.Marshal([]string{wire.ChoiceAct, wire.ChoiceDismiss})
+ c := cardRecord{ID: newID("c_"), Person: person, Kind: wire.CardAdvice, State: wire.CardOpen, Question: text, Options: string(opts), Revision: 1, CreatedAt: now, UpdatedAt: now, VisibleAt: visible, Held: visible != nil}
+ r.CardID = c.ID
+ if err := t.db.Create(&r).Error; err != nil {
+ return err
+ }
+ if err := t.db.Create(&c).Error; err != nil {
+ return err
+ }
+ return t.cardEvent(c)
+}
+
+// followAdvice keeps open advice in step with facts that moved but still
+// hold (a spend figure, a task's revision): its words and action are the
+// facts now, at a new revision; the card's line follows.
+func (t *txn) followAdvice(r *adviceRecord, a advice.Advice, conns map[string]connectionRecord) error {
+ facts := asJSON(a)
+ text, act, dismiss := t.adviceWords(a, conns)
+ if facts == r.Facts && text == r.Text && act == r.Act {
+ return nil
+ }
+ r.Facts, r.Text, r.Act, r.Dismiss = facts, text, act, dismiss
+ r.Revision++
+ r.UpdatedAt = t.hkNow()
+ if err := t.db.Model(&adviceRecord{}).Where("id = ?", r.ID).Select("facts", "text", "act", "dismiss", "revision", "updated_at").Updates(r).Error; err != nil {
+ return err
+ }
+ c, err := t.loadCard(r.CardID)
+ if err != nil {
+ return err
+ }
+ c.Question = text
+ c.Revision++
+ c.UpdatedAt = r.UpdatedAt
+ if err := t.db.Model(&cardRecord{}).Where("id = ?", c.ID).Select("question", "revision", "updated_at").Updates(&c).Error; err != nil {
+ return err
+ }
+ return t.cardEvent(c)
+}
+
+// closeAdvice moves advice forward to state (acted, dismissed or
+// withdrawn) and its card with it: answered with the choice, or resolved
+// (withdrawn: the conversation shows nothing more of it).
+func (t *txn) closeAdvice(r *adviceRecord, state, choice string) error {
+ if r.State != wire.AdviceOpen {
+ return ErrConflict
+ }
+ now := t.hkNow()
+ r.State, r.UpdatedAt = state, now
+ if state == wire.AdviceDismissed {
+ r.DismissedAt = &now
+ }
+ r.Revision++
+ if err := t.db.Model(&adviceRecord{}).Where("id = ? AND state = ?", r.ID, wire.AdviceOpen).Select("state", "updated_at", "dismissed_at", "revision").Updates(r).Error; err != nil {
+ return err
+ }
+ c, err := t.loadCard(r.CardID)
+ if errors.Is(err, gorm.ErrRecordNotFound) {
+ return nil
+ }
+ if err != nil {
+ return err
+ }
+ c.State, c.Choice = wire.CardAnswered, choice
+ if state == wire.AdviceWithdrawn {
+ c.State = wire.CardResolved
+ }
+ c.Revision++
+ c.UpdatedAt = now
+ if err := t.db.Model(&cardRecord{}).Where("id = ?", c.ID).Select("state", "choice", "revision", "updated_at").Updates(&c).Error; err != nil {
+ return err
+ }
+ return t.cardEvent(c)
+}
+
+// Advice is GET /api/v1/advice: the person's open advice that may show
+// now (at most one).
+func (s *Store) Advice(ctx context.Context, person string) (out wire.AdviceList, err error) {
+ out.Items = []wire.Advice{}
+ err = s.read(ctx, func(tx *gorm.DB) error {
+ if err := s.authority.CurrentPerson(ctx, tx); err != nil {
+ return err
+ }
+ var rows []adviceRecord
+ if err := tx.Where("person = ? AND state = ?", person, wire.AdviceOpen).Order("created_at, id").Find(&rows).Error; err != nil {
+ return err
+ }
+ now := s.hkClock()
+ for _, r := range rows {
+ if r.VisibleAt != nil && r.VisibleAt.After(now) {
+ continue
+ }
+ out.Items = append(out.Items, adviceView(r))
+ }
+ return nil
+ })
+ return out, err
+}
+
+// ownAdvice is one of the person's advice rows, open and visible now, at
+// the revision they saw; otherwise ErrConflict with it as it is.
+func (t *txn) ownAdvice(person, id string, revision int64) (adviceRecord, error) {
+ var r adviceRecord
+ err := t.db.Where("id = ? AND person = ?", id, person).First(&r).Error
+ if errors.Is(err, gorm.ErrRecordNotFound) {
+ return r, ErrNotFound
+ }
+ if err != nil {
+ return r, err
+ }
+ if r.State != wire.AdviceOpen || r.Revision != revision || r.VisibleAt != nil && r.VisibleAt.After(t.hkNow()) {
+ return r, ErrConflict
+ }
+ return r, nil
+}
+
+// ActAdvice is the advice's one action (POST /api/v1/advice/{id}/act):
+// the ordinary call with the facts the person saw, revision-checked, in
+// one transaction with the advice moving to acted. Advice whose facts no
+// longer hold acts on nothing (ErrConflict; the next look withdraws it).
+func (s *Store) ActAdvice(ctx context.Context, person, id string, in wire.AdviceAction) (out wire.Advice, err error) {
+ err = s.tx(ctx, func(t *txn) error {
+ if err := s.authority.CurrentPerson(ctx, t.db); err != nil {
+ return err
+ }
+ r, err := t.ownAdvice(person, id, in.Revision)
+ if err != nil {
+ out = adviceView(r)
+ return err
+ }
+ if err := t.actAdvice(person, &r); err != nil {
+ return err
+ }
+ out = adviceView(r)
+ return nil
+ })
+ return out, err
+}
+
+func (t *txn) actAdvice(person string, r *adviceRecord) error {
+ f, _, err := t.adviceFacts(person)
+ if err != nil {
+ return err
+ }
+ if _, holds := advice.Holds(advice.Compute(f, t.hkNow()), r.Key); !holds {
+ return ErrConflict
+ }
+ var a advice.Advice
+ if err := json.Unmarshal([]byte(r.Facts), &a); err != nil {
+ return err
+ }
+ switch a.Kind {
+ case wire.AdviceBudgetNear:
+ c, err := t.ownConnection(person, a.Connection)
+ if err != nil {
+ return err
+ }
+ b, _ := budgetOf(c)
+ in := wire.SetBudget{Day: b.Day, Month: b.Month, Revision: a.BudgetRevision}
+ if a.Window == advice.BudgetDay {
+ in.Day = a.Raise
+ } else {
+ in.Month = a.Raise
+ }
+ if _, err := t.setBudget(person, a.Connection, in); err != nil {
+ return err
+ }
+ case wire.AdvicePreferSwitch:
+ until := a.Until
+ if _, err := t.setPreference(person, wire.Preferences{Provider: a.To, Until: &until, Revision: a.PreferenceRevision}); err != nil {
+ return err
+ }
+ case wire.AdviceDeferTasks, wire.AdviceHeldLong:
+ to := wire.PriorityLow
+ if a.Kind == wire.AdviceHeldLong {
+ to = wire.PriorityNormal
+ }
+ for _, k := range a.Tasks {
+ task, err := t.loadTask(k.ID)
+ if err != nil {
+ return err
+ }
+ if _, err := t.setPriority(person, k.ID, wire.SetPriority{Priority: to, By: task.DueBy, Revision: k.Revision}); err != nil {
+ return err
+ }
+ }
+ default:
+ return ErrInvalid
+ }
+ if err := t.closeAdvice(r, wire.AdviceActed, wire.ChoiceAct); err != nil {
+ return err
+ }
+ // The ordinary call wrote its own audit; this one says advice made it.
+ return t.audit(person, "advice.act", "source=advice id="+r.ID+" key="+r.Key)
+}
+
+// DismissAdvice is Not now (or Leave it): POST /api/v1/advice/{id}/dismiss.
+// The key is silenced for 14 days, and for 60 after a second Not now.
+func (s *Store) DismissAdvice(ctx context.Context, person, id string, in wire.AdviceAction) (out wire.Advice, err error) {
+ err = s.tx(ctx, func(t *txn) error {
+ if err := s.authority.CurrentPerson(ctx, t.db); err != nil {
+ return err
+ }
+ r, err := t.ownAdvice(person, id, in.Revision)
+ if err != nil {
+ out = adviceView(r)
+ return err
+ }
+ if err := t.dismissAdvice(person, &r); err != nil {
+ return err
+ }
+ out = adviceView(r)
+ return nil
+ })
+ return out, err
+}
+
+func (t *txn) dismissAdvice(person string, r *adviceRecord) error {
+ if err := t.closeAdvice(r, wire.AdviceDismissed, wire.ChoiceDismiss); err != nil {
+ return err
+ }
+ return t.audit(person, "advice.dismiss", "source=advice id="+r.ID+" key="+r.Key)
+}
+
+// answerAdvice is the conversation card's answer: its action or Not now,
+// for the advice the card shows.
+func (t *txn) answerAdvice(person string, c cardRecord, in wire.AnswerCard) (wire.Card, wire.Card, error) {
+ current := func() wire.Card {
+ v, _ := t.cardView(c)
+ return v
+ }
+ if c.Person != person {
+ return wire.Card{}, wire.Card{}, ErrNotFound
+ }
+ if c.State != wire.CardOpen || c.Revision != in.Revision || !slices.Contains([]string{wire.ChoiceAct, wire.ChoiceDismiss}, in.Choice) {
+ return wire.Card{}, current(), ErrCardConflict
+ }
+ var r adviceRecord
+ if err := t.db.Where("card_id = ? AND person = ?", c.ID, person).First(&r).Error; errors.Is(err, gorm.ErrRecordNotFound) {
+ return wire.Card{}, wire.Card{}, ErrNotFound
+ } else if err != nil {
+ return wire.Card{}, wire.Card{}, err
+ }
+ if r, err := t.ownAdvice(person, r.ID, r.Revision); err != nil {
+ if errors.Is(err, ErrConflict) {
+ return wire.Card{}, current(), ErrCardConflict
+ }
+ return wire.Card{}, wire.Card{}, err
+ } else if in.Choice == wire.ChoiceAct {
+ err = t.actAdvice(person, &r)
+ if errors.Is(err, ErrConflict) {
+ return wire.Card{}, current(), ErrCardConflict
+ }
+ if err != nil {
+ return wire.Card{}, wire.Card{}, err
+ }
+ } else if err := t.dismissAdvice(person, &r); err != nil {
+ return wire.Card{}, wire.Card{}, err
+ }
+ c, err := t.loadCard(c.ID)
+ if err != nil {
+ return wire.Card{}, wire.Card{}, err
+ }
+ v, err := t.cardView(c)
+ return v, wire.Card{}, err
+}
+
+// cardAdvice is an advice card's advice, for its view.
+func (t *txn) cardAdvice(c cardRecord) (*wire.Advice, error) {
+ var r adviceRecord
+ err := t.db.Where("card_id = ?", c.ID).First(&r).Error
+ if errors.Is(err, gorm.ErrRecordNotFound) {
+ return nil, nil
+ }
+ if err != nil {
+ return nil, err
+ }
+ v := adviceView(r)
+ return &v, nil
+}
diff --git a/internal/equipo/chat/advice_store_test.go b/internal/equipo/chat/advice_store_test.go
new file mode 100644
index 00000000..bc8bd5e2
--- /dev/null
+++ b/internal/equipo/chat/advice_store_test.go
@@ -0,0 +1,450 @@
+package chat
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "slices"
+ "strings"
+ "testing"
+ "time"
+
+ "amadan.net/oficina/equipo/internal/wire"
+)
+
+const adviceOwner = "owner@example.com"
+
+// adviceRig is the metered rig with one clock for the store and the
+// housekeeping loop, and the TensorX connection's spend set.
+type adviceRig struct {
+ *meteredRig
+ at time.Time
+ ctx context.Context
+}
+
+func newAdviceRig(t *testing.T) *adviceRig {
+ r := &adviceRig{meteredRig: newMeteredRig(t), at: time.Date(2026, 11, 12, 9, 0, 0, 0, time.UTC), ctx: context.Background()}
+ r.s.now = func() time.Time { return r.at }
+ r.s.SetHousekeepingClock(func() time.Time { return r.at })
+ r.spend(840_000, 6_200_000)
+ // The person's primary runner, at the current protocol.
+ for _, q := range []string{
+ "CREATE TABLE IF NOT EXISTS runners (id text PRIMARY KEY, person text, role text, label text, removing_at datetime, tainted_at datetime, revoked_at datetime)",
+ "INSERT INTO runners(id, person, role) VALUES ('RUNNER1', 'owner@example.com', 'primary')",
+ } {
+ if err := r.s.db.G.Exec(q).Error; err != nil {
+ t.Fatal(err)
+ }
+ }
+ if err := r.s.db.G.Create(&runnerSessionRecord{RunnerID: "RUNNER1", Generation: 1, Connected: true, Protocol: wire.ProtocolCurrent, SeenAt: r.at}).Error; err != nil {
+ t.Fatal(err)
+ }
+ return r
+}
+
+func (r *adviceRig) spend(day, month int64) {
+ r.t.Helper()
+ raw := asJSON(wire.Spend{Day: day, Month: month, Currency: "USD"})
+ if err := r.s.db.G.Exec("UPDATE chat_connections SET spend = ? WHERE id = 'cn_made'", raw).Error; err != nil {
+ r.t.Fatal(err)
+ }
+}
+
+func (r *adviceRig) refresh() {
+ r.t.Helper()
+ if err := r.s.RefreshAdvice(r.ctx, adviceOwner); err != nil {
+ r.t.Fatal(err)
+ }
+}
+
+func (r *adviceRig) rows() []adviceRecord {
+ r.t.Helper()
+ var rows []adviceRecord
+ if err := r.s.db.G.Where("person = ?", adviceOwner).Order("created_at, id").Find(&rows).Error; err != nil {
+ r.t.Fatal(err)
+ }
+ return rows
+}
+
+func (r *adviceRig) card(id string) cardRecord {
+ r.t.Helper()
+ var c cardRecord
+ if err := r.s.db.G.Where("id = ?", id).First(&c).Error; err != nil {
+ r.t.Fatal(err)
+ }
+ return c
+}
+
+func (r *adviceRig) commands(kind string) []commandRecord {
+ var cs []commandRecord
+ r.s.db.G.Where("kind = ?", kind).Order("seq").Find(&cs)
+ return cs
+}
+
+// budget_near end to end in the store: one card, at the top of the
+// day's advice and as one quiet conversation card that is never Needs
+// you; a stale revision acts on nothing; its action is the ordinary
+// budget call at the budget's revision, in the advice's transaction,
+// audited as the call and as advice with its key; no day shows two.
+func TestAdviceStoreActsThroughTheOrdinaryCall(t *testing.T) {
+ r := newAdviceRig(t)
+ r.refresh()
+ r.refresh()
+ rows := r.rows()
+ if len(rows) != 1 || rows[0].Kind != wire.AdviceBudgetNear || rows[0].Key != "budget_near:cn_made" || rows[0].State != wire.AdviceOpen || rows[0].VisibleAt != nil {
+ t.Fatalf("rows %+v", rows)
+ }
+ a := rows[0]
+ c := r.card(a.CardID)
+ if c.Kind != wire.CardAdvice || c.State != wire.CardOpen || c.Held || c.TaskID != "" || c.Options != `["act","dismiss"]` {
+ t.Fatalf("card %+v", c)
+ }
+ if !strings.HasPrefix(a.Act, "advice.budget_near.raise_day") || !strings.HasPrefix(a.Dismiss, "advice.leave_it") {
+ t.Fatalf("words %q %q", a.Act, a.Dismiss)
+ }
+ list, err := r.s.Advice(r.ctx, adviceOwner)
+ if err != nil || len(list.Items) != 1 || list.Items[0].ID != a.ID || list.Items[0].Subject.Connection != "cn_made" {
+ t.Fatalf("list %+v %v", list, err)
+ }
+ if needs, err := r.s.NeedsYou(r.ctx, adviceOwner); err != nil || len(needs.Items) != 0 {
+ t.Fatalf("advice was Needs you: %+v %v", needs.Items, err)
+ }
+ // The coordinator has no write: no tool names advice.
+ for _, tool := range append(slices.Clone(wire.ConverseTools), wire.WriteTools...) {
+ if strings.Contains(tool, "advice") {
+ t.Fatalf("the coordinator has %s", tool)
+ }
+ }
+ r.audits = nil
+ if _, err := r.s.ActAdvice(r.ctx, adviceOwner, a.ID, wire.AdviceAction{Revision: a.Revision + 1}); !errors.Is(err, ErrConflict) {
+ t.Fatalf("a stale revision: %v", err)
+ }
+ if _, err := r.s.ActAdvice(r.ctx, "member@example.com", a.ID, wire.AdviceAction{Revision: a.Revision}); !errors.Is(err, ErrNotFound) {
+ t.Fatalf("another person's act: %v", err)
+ }
+ if len(r.commands(wire.FrameBudget)) != 0 || len(r.audits) != 0 {
+ t.Fatal("a refused act changed something")
+ }
+ // Facts that stopped holding since the last look act on nothing.
+ r.spend(100_000, 1_000_000)
+ if _, err := r.s.ActAdvice(r.ctx, adviceOwner, a.ID, wire.AdviceAction{Revision: a.Revision}); !errors.Is(err, ErrConflict) || len(r.commands(wire.FrameBudget)) != 0 {
+ t.Fatalf("acted on facts that no longer hold: %v", err)
+ }
+ r.spend(840_000, 6_200_000)
+ out, err := r.s.ActAdvice(r.ctx, adviceOwner, a.ID, wire.AdviceAction{Revision: a.Revision})
+ if err != nil || out.State != wire.AdviceActed {
+ t.Fatalf("act: %+v %v", out, err)
+ }
+ cmds := r.commands(wire.FrameBudget)
+ var cmd wire.BudgetCommand
+ if len(cmds) != 1 || json.Unmarshal([]byte(cmds[0].Body), &cmd) != nil || cmd.Budget.Day != 2_000_000 || cmd.Budget.Month != 10_000_000 || cmd.Budget.Revision != 2 {
+ t.Fatalf("budget frames %+v", cmds)
+ }
+ if !slices.Contains(r.audits, adviceOwner+" connection.budget cn_made@2") || !slices.Contains(r.audits, adviceOwner+" advice.act source=advice id="+a.ID+" key=budget_near:cn_made") {
+ t.Fatalf("audits %v", r.audits)
+ }
+ if c := r.card(a.CardID); c.State != wire.CardAnswered || c.Choice != wire.ChoiceAct {
+ t.Fatalf("card after act %+v", c)
+ }
+ if _, err := r.s.ActAdvice(r.ctx, adviceOwner, a.ID, wire.AdviceAction{Revision: out.Revision}); !errors.Is(err, ErrConflict) {
+ t.Fatalf("acted twice: %v", err)
+ }
+ // Still near the month's budget later that day: no second card today.
+ r.spend(840_000, 9_000_000)
+ r.at = r.at.Add(3 * time.Hour)
+ r.refresh()
+ if n := len(r.rows()); n != 1 {
+ t.Fatalf("%d cards in a day", n)
+ }
+ r.at = r.at.Add(21 * time.Hour)
+ r.refresh()
+ if rows := r.rows(); len(rows) != 2 || rows[1].Key != "budget_near:cn_made" {
+ t.Fatalf("the next day: %+v", rows)
+ }
+}
+
+// Not now silences the key for 14 days, then 60 after a second Not now;
+// advice whose facts stop holding is withdrawn without a word (its card
+// resolved, nothing said) and still counts as the day's card.
+func TestAdviceStoreNotNowAndWithdrawal(t *testing.T) {
+ r := newAdviceRig(t)
+ r.refresh()
+ a := r.rows()[0]
+ if _, err := r.s.DismissAdvice(r.ctx, adviceOwner, a.ID, wire.AdviceAction{Revision: a.Revision}); err != nil {
+ t.Fatal(err)
+ }
+ if c := r.card(a.CardID); c.State != wire.CardAnswered || c.Choice != wire.ChoiceDismiss {
+ t.Fatalf("card %+v", c)
+ }
+ if !slices.Contains(r.audits, adviceOwner+" advice.dismiss source=advice id="+a.ID+" key=budget_near:cn_made") {
+ t.Fatalf("audits %v", r.audits)
+ }
+ day := func(d int) {
+ r.at = time.Date(2026, 11, 12, 9, 0, 0, 0, time.UTC).AddDate(0, 0, d)
+ r.refresh()
+ }
+ day(1)
+ day(13)
+ if n := len(r.rows()); n != 1 {
+ t.Fatalf("shown again within 14 days: %d", n)
+ }
+ day(14)
+ rows := r.rows()
+ if len(rows) != 2 {
+ t.Fatalf("not shown after 14 days: %d", len(rows))
+ }
+ if _, err := r.s.DismissAdvice(r.ctx, adviceOwner, rows[1].ID, wire.AdviceAction{Revision: rows[1].Revision}); err != nil {
+ t.Fatal(err)
+ }
+ day(28)
+ day(73)
+ if n := len(r.rows()); n != 2 {
+ t.Fatalf("shown again within 60 days of the second Not now: %d", n)
+ }
+ day(74)
+ rows = r.rows()
+ if len(rows) != 3 {
+ t.Fatalf("not shown 60 days after the second Not now: %d", len(rows))
+ }
+ // The facts stop holding: withdrawn, its card resolved, and no
+ // other card that day.
+ events := func() int64 {
+ var n int64
+ r.s.db.G.Model(&eventRecord{}).Where("type = ?", wire.EventCard).Count(&n)
+ return n
+ }
+ r.spend(100_000, 1_000_000)
+ before := events()
+ r.refresh()
+ rows = r.rows()
+ if rows[2].State != wire.AdviceWithdrawn || len(rows) != 3 {
+ t.Fatalf("withdrawal %+v", rows)
+ }
+ if c := r.card(rows[2].CardID); c.State != wire.CardResolved || c.Choice != "" {
+ t.Fatalf("withdrawn card %+v", c)
+ }
+ if events() != before+1 {
+ t.Fatal("the withdrawal said more than its card's change")
+ }
+ if list, _ := r.s.Advice(r.ctx, adviceOwner); len(list.Items) != 0 {
+ t.Fatalf("withdrawn advice listed %+v", list.Items)
+ }
+ if _, err := r.s.ActAdvice(r.ctx, adviceOwner, rows[2].ID, wire.AdviceAction{Revision: rows[2].Revision}); !errors.Is(err, ErrConflict) {
+ t.Fatalf("withdrawn advice acted: %v", err)
+ }
+ r.spend(900_000, 1_000_000)
+ r.refresh()
+ if n := len(r.rows()); n != 3 {
+ t.Fatalf("a second card the day one was withdrawn: %d", n)
+ }
+}
+
+// Quiet hours (housekeeping's VisibleAt): a card made at 23:00 waits,
+// held, until 08:00; it is not listed or answerable before then, and the
+// loop's minute shows it.
+func TestAdviceStoreQuietHours(t *testing.T) {
+ r := newAdviceRig(t)
+ // Today's card came and went this morning; tonight's facts may make
+ // tomorrow's card, held until 08:00.
+ r.refresh()
+ first := r.rows()[0]
+ if _, err := r.s.DismissAdvice(r.ctx, adviceOwner, first.ID, wire.AdviceAction{Revision: first.Revision}); err != nil {
+ t.Fatal(err)
+ }
+ r.s.db.G.Exec("UPDATE chat_advice SET key = 'budget_near:older', state = 'acted' WHERE id = ?", first.ID)
+ r.at = time.Date(2026, 11, 12, 23, 0, 0, 0, time.UTC)
+ r.refresh()
+ rows := r.rows()[1:]
+ morning := time.Date(2026, 11, 13, 8, 0, 0, 0, time.UTC)
+ if len(rows) != 1 || rows[0].VisibleAt == nil || !rows[0].VisibleAt.Equal(morning) || !rows[0].ShownAt.Equal(morning) {
+ t.Fatalf("rows %+v", rows)
+ }
+ if c := r.card(rows[0].CardID); !c.Held {
+ t.Fatal("the card was not held for quiet hours")
+ }
+ if list, _ := r.s.Advice(r.ctx, adviceOwner); len(list.Items) != 0 {
+ t.Fatal("listed in quiet hours")
+ }
+ if _, err := r.s.ActAdvice(r.ctx, adviceOwner, rows[0].ID, wire.AdviceAction{Revision: rows[0].Revision}); !errors.Is(err, ErrConflict) {
+ t.Fatalf("acted in quiet hours: %v", err)
+ }
+ r.at = morning.Add(time.Minute)
+ if err := r.s.HousekeepingTick(r.ctx); err != nil {
+ t.Fatal(err)
+ }
+ if c := r.card(rows[0].CardID); c.Held {
+ t.Fatal("still held after quiet hours")
+ }
+ if list, _ := r.s.Advice(r.ctx, adviceOwner); len(list.Items) != 1 {
+ t.Fatal("not listed after quiet hours")
+ }
+ r.at = morning.Add(time.Hour)
+ r.refresh()
+ if n := len(r.rows()); n != 2 {
+ t.Fatalf("the morning brought a second card: %d", n)
+ }
+}
+
+// A hold's start is kept while the step stays held, whatever the runner
+// says of it again; it goes with the hold, and a new hold starts anew.
+func TestAcceptHoldKeepsHeldSince(t *testing.T) {
+ t0 := time.Date(2026, 11, 1, 9, 0, 0, 0, time.UTC)
+ s := stepRecord{State: wire.StepQueued}
+ report := func(h *wire.StepHold, at time.Time) {
+ acceptHold(&s, &wire.StepReport{State: wire.StepRunning, Hold: h}, at)
+ }
+ wake := t0.Add(time.Hour)
+ report(&wire.StepHold{Reason: wire.HoldHeadroom, StepRevision: 1}, t0)
+ report(&wire.StepHold{Reason: wire.HoldHeadroom, WakeAt: &wake, StepRevision: 1}, t0.Add(2*time.Hour))
+ report(&wire.StepHold{Reason: wire.HoldBudget, StepRevision: 1}, t0.Add(48*time.Hour))
+ if s.HeldAt == nil || !s.HeldAt.Equal(t0) {
+ t.Fatalf("held since %v", s.HeldAt)
+ }
+ report(nil, t0.Add(49*time.Hour))
+ if s.HeldAt != nil || s.Hold != "" {
+ t.Fatal("the hold's start stayed after the hold")
+ }
+ report(&wire.StepHold{Reason: wire.HoldHeadroom, StepRevision: 2}, t0.Add(50*time.Hour))
+ if s.HeldAt == nil || !s.HeldAt.Equal(t0.Add(50*time.Hour)) {
+ t.Fatalf("a new hold since %v", s.HeldAt)
+ }
+}
+
+// defer_tasks and held_long act task by task through the priority call,
+// each at the revision the advice read; a task that moved since acts on
+// nothing, the others included.
+func TestAdviceStoreTaskActions(t *testing.T) {
+ r := newAdviceRig(t)
+ r.spend(0, 0)
+ g := r.s.db.G
+ now := r.at
+ if err := g.Create(&projectRecord{ID: "p_1", Repo: "amadan.net/oficina/sample", State: wire.ProjectActive, CreatedAt: now, UpdatedAt: now}).Error; err != nil {
+ t.Fatal(err)
+ }
+ reset := now.Add(50 * time.Hour)
+ held := asJSON(wire.StepHold{Reason: wire.HoldHeadroom, Provider: wire.ProviderClaude, ResetsAt: &reset, StepRevision: 1})
+ for i, k := range []taskRecord{
+ {ID: "tk1", Priority: wire.PriorityUrgent, Revision: 4},
+ {ID: "tk2", Priority: wire.PriorityNormal, Revision: 7},
+ {ID: "tk3", Revision: 1},
+ } {
+ k.ProjectID, k.Title, k.Stage, k.Creator, k.CreatedAt, k.UpdatedAt = "p_1", k.ID, wire.StageInProgress, adviceOwner, now.Add(time.Duration(i)*time.Minute), now
+ if err := g.Create(&k).Error; err != nil {
+ t.Fatal(err)
+ }
+ s := stepRecord{ID: "s" + k.ID, TaskID: k.ID, Idx: 1, Specialist: wire.SpecialistEngineering, Person: adviceOwner, State: wire.StepQueued, Attempt: 1, RunnerID: "RUNNER1", Revision: 1, CreatedAt: now, UpdatedAt: now}
+ if k.ID != "tk3" {
+ s.Hold, s.HeldAt = held, &now
+ }
+ if err := g.Create(&s).Error; err != nil {
+ t.Fatal(err)
+ }
+ }
+ r.refresh()
+ rows := r.rows()
+ if len(rows) != 1 || rows[0].Key != "defer_tasks:tk2,tk3" || !strings.HasPrefix(rows[0].Text, "advice.defer_tasks.many") {
+ t.Fatalf("rows %+v", rows)
+ }
+ a := rows[0]
+ // tk3 moved after the advice read it: nothing changes, tk2 included.
+ g.Exec("UPDATE chat_tasks SET revision = 2 WHERE id = 'tk3'")
+ if _, err := r.s.ActAdvice(r.ctx, adviceOwner, a.ID, wire.AdviceAction{Revision: a.Revision}); !errors.Is(err, ErrConflict) {
+ t.Fatalf("a moved task: %v", err)
+ }
+ var tk2 taskRecord
+ g.Where("id = 'tk2'").First(&tk2)
+ if tk2.Priority != wire.PriorityNormal {
+ t.Fatal("a refused act changed a task")
+ }
+ // The next look follows the facts (a new revision); then it acts.
+ r.refresh()
+ a = r.rows()[0]
+ if a.Revision != 2 {
+ t.Fatalf("revision %d", a.Revision)
+ }
+ r.audits = nil
+ if _, err := r.s.ActAdvice(r.ctx, adviceOwner, a.ID, wire.AdviceAction{Revision: a.Revision}); err != nil {
+ t.Fatal(err)
+ }
+ for _, id := range []string{"tk2", "tk3"} {
+ var k taskRecord
+ g.Where("id = ?", id).First(&k)
+ if k.Priority != wire.PriorityLow || k.PrioritySetBy != wire.PrioritySetByPerson {
+ t.Fatalf("%s: %+v", id, k)
+ }
+ }
+ if !slices.Contains(r.audits, adviceOwner+" task.priority tk2@low") || !slices.Contains(r.audits, adviceOwner+" task.priority tk3@low") || !slices.Contains(r.audits, adviceOwner+" advice.act source=advice id="+a.ID+" key=defer_tasks:tk2,tk3") {
+ t.Fatalf("audits %v", r.audits)
+ }
+
+ // A week later, the low tasks still held: held_long, Make them
+ // normal through the card in the conversation.
+ r.at = now.AddDate(0, 0, 8)
+ g.Exec("UPDATE chat_steps SET hold = ?, held_at = ? WHERE task_id IN ('tk2','tk3')", held, now)
+ g.Exec("UPDATE chat_steps SET hold = '', held_at = NULL WHERE task_id = 'tk1'")
+ r.refresh()
+ rows = r.rows()
+ if len(rows) != 2 || rows[1].Key != "held_long:tk2,tk3" {
+ t.Fatalf("rows %+v", rows)
+ }
+ c := r.card(rows[1].CardID)
+ if _, _, err := r.s.Answer(r.ctx, adviceOwner, c.ID, wire.AnswerCard{Choice: wire.ChoiceAct, Revision: c.Revision}); err != nil {
+ t.Fatal(err)
+ }
+ for _, id := range []string{"tk2", "tk3"} {
+ var k taskRecord
+ g.Where("id = ?", id).First(&k)
+ if k.Priority != wire.PriorityNormal {
+ t.Fatalf("%s: %s", id, k.Priority)
+ }
+ }
+ if rows := r.rows(); rows[1].State != wire.AdviceActed {
+ t.Fatalf("after the card: %+v", rows[1])
+ }
+}
+
+// prefer_switch acts as PUT /connections/preference with an end: the
+// other provider until the preferred one's window resets, revision-
+// checked, sent to the runner.
+func TestAdviceStorePreferSwitch(t *testing.T) {
+ r := newAdviceRig(t)
+ r.spend(0, 0)
+ g := r.s.db.G
+ now := r.at
+ resets, soon := now.Add(50*time.Hour), now.Add(3*time.Hour)
+ for _, c := range []connectionRecord{
+ {ID: "cn_cl", Person: adviceOwner, RunnerID: "RUNNER1", LocalID: "claude-1", Provider: wire.ProviderClaude, Kind: wire.KindSubscription, State: wire.ConnHealthy, Headroom: asJSON(wire.Headroom{Windows: []wire.Window{{Name: "seven_day", UsedPercent: 85, Minutes: 10080, ResetsAt: &resets}}}), Revision: 1, CreatedAt: now, UpdatedAt: now},
+ {ID: "cn_cx", Person: adviceOwner, RunnerID: "RUNNER1", LocalID: "codex-1", Provider: wire.ProviderCodex, Kind: wire.KindSubscription, State: wire.ConnHealthy, Headroom: asJSON(wire.Headroom{Windows: []wire.Window{{Name: "primary", UsedPercent: 20, Minutes: 300, ResetsAt: &soon}}}), Revision: 1, CreatedAt: now, UpdatedAt: now},
+ } {
+ if err := g.Create(&c).Error; err != nil {
+ t.Fatal(err)
+ }
+ }
+ pref, err := r.s.SetPreference(r.ctx, adviceOwner, wire.Preferences{Provider: wire.ProviderClaude})
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := g.Create(&projectRecord{ID: "p_1", Repo: "amadan.net/oficina/sample", State: wire.ProjectActive, CreatedAt: now, UpdatedAt: now}).Error; err != nil {
+ t.Fatal(err)
+ }
+ g.Create(&taskRecord{ID: "tk1", ProjectID: "p_1", Title: "T", Stage: wire.StageInProgress, Creator: adviceOwner, Revision: 1, CreatedAt: now, UpdatedAt: now})
+ g.Create(&stepRecord{ID: "s1", TaskID: "tk1", Idx: 1, Specialist: wire.SpecialistEngineering, Person: adviceOwner, State: wire.StepQueued, Attempt: 1, Revision: 1, CreatedAt: now, UpdatedAt: now})
+ r.refresh()
+ rows := r.rows()
+ if len(rows) != 1 || rows[0].Key != "prefer_switch:engineering/cn_cx" {
+ t.Fatalf("rows %+v", rows)
+ }
+ a := rows[0]
+ if _, err := r.s.ActAdvice(r.ctx, adviceOwner, a.ID, wire.AdviceAction{Revision: a.Revision}); err != nil {
+ t.Fatal(err)
+ }
+ got, _ := r.s.Preference(r.ctx, adviceOwner)
+ if got.Provider != wire.ProviderCodex || got.Until == nil || !got.Until.Equal(resets) || got.Revision != pref.Revision+1 {
+ t.Fatalf("preference %+v", got)
+ }
+ var cmd wire.PreferenceCommand
+ cmds := r.commands(wire.FramePreference)
+ if len(cmds) == 0 || json.Unmarshal([]byte(cmds[len(cmds)-1].Body), &cmd) != nil || cmd.Provider != wire.ProviderCodex || cmd.Until == nil {
+ t.Fatalf("preference frames %+v", cmds)
+ }
+}
diff --git a/internal/equipo/chat/connections.go b/internal/equipo/chat/connections.go
index c695f6e3..ffd75638 100644
--- a/internal/equipo/chat/connections.go
+++ b/internal/equipo/chat/connections.go
@@ -484,53 +484,59 @@ func (s *Store) SetPreference(ctx context.Context, person string, in wire.Prefer
if err := s.authority.CurrentPerson(ctx, t.db); err != nil {
return err
}
- value, _, revision, err := t.settingRevision(preferenceKey(person))
- if err != nil {
- return err
- }
- if in.Revision != revision {
- return ErrConflict
- }
- until := ""
- if in.Until != nil {
- at := in.Until.UTC().Truncate(time.Second)
- if !at.After(t.now()) || at.Sub(t.now()) > wire.MaxByAhead {
- return ErrInvalid
- }
- primary, err := t.s.authority.PrimaryRunner(t.db, person)
- if err != nil {
- return err
- }
- if proto, err := t.runnerProtocol(person, primary); err != nil {
- return err
- } else if proto < wire.ProtocolScheduler {
- return ErrRunnerTooOld
- }
- in.Until, until = &at, at.Format(time.RFC3339)
+ out, err = t.setPreference(person, in)
+ return err
+ })
+ return out, err
+}
+
+// setPreference is SetPreference in t (advice's Prefer acts through it).
+func (t *txn) setPreference(person string, in wire.Preferences) (out wire.Preferences, err error) {
+ value, _, revision, err := t.settingRevision(preferenceKey(person))
+ if err != nil {
+ return out, err
+ }
+ if in.Revision != revision {
+ return out, ErrConflict
+ }
+ until := ""
+ if in.Until != nil {
+ at := in.Until.UTC().Truncate(time.Second)
+ if !at.After(t.now()) || at.Sub(t.now()) > wire.MaxByAhead {
+ return out, ErrInvalid
}
- held, _, _, err := t.settingRevision(preferenceUntilKey(person))
+ primary, err := t.s.authority.PrimaryRunner(t.db, person)
if err != nil {
- return err
- }
- if value == in.Provider && held == until && revision > 0 {
- out, err = t.preferenceOf(person)
- return err
+ return out, err
}
- if revision, err = t.setSetting(preferenceKey(person), in.Provider, person); err != nil {
- return err
+ if proto, err := t.runnerProtocol(person, primary); err != nil {
+ return out, err
+ } else if proto < wire.ProtocolScheduler {
+ return out, ErrRunnerTooOld
}
- if held != until {
- if _, err = t.setSetting(preferenceUntilKey(person), until, person); err != nil {
- return err
- }
- }
- out = wire.Preferences{Provider: in.Provider, Revision: revision, Until: in.Until}
- if err := t.event(person, wire.EventPreference, "preference", person, revision, "", "", 0, out); err != nil {
- return err
+ in.Until, until = &at, at.Format(time.RFC3339)
+ }
+ held, _, _, err := t.settingRevision(preferenceUntilKey(person))
+ if err != nil {
+ return out, err
+ }
+ if value == in.Provider && held == until && revision > 0 {
+ out, err = t.preferenceOf(person)
+ return out, err
+ }
+ if revision, err = t.setSetting(preferenceKey(person), in.Provider, person); err != nil {
+ return out, err
+ }
+ if held != until {
+ if _, err = t.setSetting(preferenceUntilKey(person), until, person); err != nil {
+ return out, err
}
- return t.command(person, wire.FramePreference, wire.PreferenceCommand{Person: person, Provider: in.Provider, Revision: revision, Until: in.Until})
- })
- return out, err
+ }
+ out = wire.Preferences{Provider: in.Provider, Revision: revision, Until: in.Until}
+ if err := t.event(person, wire.EventPreference, "preference", person, revision, "", "", 0, out); err != nil {
+ return out, err
+ }
+ return out, t.command(person, wire.FramePreference, wire.PreferenceCommand{Person: person, Provider: in.Provider, Revision: revision, Until: in.Until})
}
// Connections lists the person's own connections, every runner.
diff --git a/internal/equipo/chat/housekeeping_control.go b/internal/equipo/chat/housekeeping_control.go
index 5c8003e7..0a71d558 100644
--- a/internal/equipo/chat/housekeeping_control.go
+++ b/internal/equipo/chat/housekeeping_control.go
@@ -489,9 +489,10 @@ func (s *Store) HousekeepingTick(ctx context.Context) error {
return err
}
}
- return s.tx(ctx, func(t *txn) error {
- people, err := t.members()
- if err != nil {
+ var people []string
+ err = s.tx(ctx, func(t *txn) error {
+ var err error
+ if people, err = t.members(); err != nil {
return err
}
for _, p := range people {
@@ -501,6 +502,18 @@ func (s *Store) HousekeepingTick(ctx context.Context) error {
}
return nil
})
+ if err != nil {
+ return err
+ }
+ // Advice looks again each minute (connectors spec §9: on fact changes
+ // and at 08:00), each person in their own transaction.
+ var first error
+ for _, p := range people {
+ if err := s.RefreshAdvice(ctx, p); err != nil && first == nil {
+ first = err
+ }
+ }
+ return first
}
// sweepDue marks today's sweep as run when it is due (03:00 or later and
diff --git a/internal/equipo/chat/http.go b/internal/equipo/chat/http.go
index 63a04a59..b5a1d4e6 100644
--- a/internal/equipo/chat/http.go
+++ b/internal/equipo/chat/http.go
@@ -117,6 +117,7 @@ func (h *HTTP) Mount(r chi.Router) {
r.Get("/specialists", h.thinOr("GET /specialists", deviceClient, h.bearer(h.specialists)))
r.Post("/specialists/{id}/revoke", h.bearer(h.revokeSpecialist))
h.mountHousekeeping(r)
+ h.mountUsage(r)
r.Get("/events", h.events)
}
diff --git a/internal/equipo/chat/metered.go b/internal/equipo/chat/metered.go
index 96ce3dd8..59462cfb 100644
--- a/internal/equipo/chat/metered.go
+++ b/internal/equipo/chat/metered.go
@@ -192,31 +192,36 @@ func (s *Store) SetBudget(ctx context.Context, person, id string, in wire.SetBud
if err := s.authority.CurrentPerson(ctx, t.db); err != nil {
return err
}
- r, err := t.meteredConnection(person, id)
- if err != nil {
- return err
- }
- b, _ := budgetOf(r)
- if in.Revision != b.Revision {
- return ErrConflict
- }
- next := wire.Budget{Day: in.Day, Month: in.Month, Currency: b.Currency, Revision: b.Revision + 1}
- if !wire.ValidBudget(next) {
- return ErrInvalid
- }
- r.Budget = asJSON(next)
- if err := t.saveConnection(&r, false); err != nil {
- return err
- }
- if err := t.audit(person, "connection.budget", r.ID+"@"+strconv.FormatInt(next.Revision, 10)); err != nil {
- return err
- }
- out = connectionView(r)
- return t.commandTo(r.RunnerID, person, wire.FrameBudget, wire.BudgetCommand{Connection: r.ID, Person: person, LocalID: r.LocalID, Budget: next})
+ out, err = t.setBudget(person, id, in)
+ return err
})
return out, err
}
+// setBudget is SetBudget in t (advice's Raise acts through it too).
+func (t *txn) setBudget(person, id string, in wire.SetBudget) (wire.Connection, error) {
+ r, err := t.meteredConnection(person, id)
+ if err != nil {
+ return wire.Connection{}, err
+ }
+ b, _ := budgetOf(r)
+ if in.Revision != b.Revision {
+ return wire.Connection{}, ErrConflict
+ }
+ next := wire.Budget{Day: in.Day, Month: in.Month, Currency: b.Currency, Revision: b.Revision + 1}
+ if !wire.ValidBudget(next) {
+ return wire.Connection{}, ErrInvalid
+ }
+ r.Budget = asJSON(next)
+ if err := t.saveConnection(&r, false); err != nil {
+ return wire.Connection{}, err
+ }
+ if err := t.audit(person, "connection.budget", r.ID+"@"+strconv.FormatInt(next.Revision, 10)); err != nil {
+ return wire.Connection{}, err
+ }
+ return connectionView(r), t.commandTo(r.RunnerID, person, wire.FrameBudget, wire.BudgetCommand{Connection: r.ID, Person: person, LocalID: r.LocalID, Budget: next})
+}
+
// ResumeSpend is the person's Resume of a connection whose spend is
// unknown, after looking at the provider's dashboard. It is bound to the
// pause they saw: the runner consumes it once, only while that pause is
diff --git a/internal/equipo/chat/models.go b/internal/equipo/chat/models.go
index 02eabb74..3167b3a8 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{}, &starRecord{}, &questionRecord{}, &connectionRecord{}, &usageRecord{}, &distinctRecord{}, &hkRecord{}, &hkFailureRecord{}, &hkSettingsRecord{}, &fileRecord{}, &fileDataRecord{}, &transferRecord{}, &mergePolicyRecord{}, &mergeAuditRecord{}, &specialistRecord{}, &grantRecord{}, &specialistAuditRecord{}, &researchSourceRecord{}, &researchAddressRecord{}, &researchPrefixRecord{}, &researchInventoryRecord{}, &researchRecord{}, &researchFetchRecord{}, &taskFileRecord{}, &taskFileDataRecord{}, &releaseRecord{}}
+var Models = []any{&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{}, &researchRecord{}, &researchFetchRecord{}, &taskFileRecord{}, &taskFileDataRecord{}, &releaseRecord{}, &adviceRecord{}}
type turnRecord struct {
ID string `gorm:"primaryKey"`
diff --git a/internal/equipo/chat/projects.go b/internal/equipo/chat/projects.go
index acad61e0..5572d9b6 100644
--- a/internal/equipo/chat/projects.go
+++ b/internal/equipo/chat/projects.go
@@ -276,6 +276,13 @@ func (t *txn) cardView(c cardRecord) (wire.Card, error) {
}
v.Inventory = iv
}
+ if c.Kind == wire.CardAdvice {
+ av, err := t.cardAdvice(c)
+ if err != nil {
+ return v, err
+ }
+ v.Advice = av
+ }
if c.Kind == wire.CardTask {
k, err := t.loadTask(c.TaskID)
if err != nil {
@@ -598,6 +605,11 @@ func (s *Store) Answer(ctx context.Context, person, id string, in wire.AnswerCar
out.Card, current = card, cur
return e
}
+ if c.Kind == wire.CardAdvice {
+ card, cur, e := t.answerAdvice(person, c, in)
+ out.Card, current = card, cur
+ return e
+ }
if c.Kind == wire.CardHeld {
card, cur, e := t.answerHeld(person, c, in)
out.Card, current = card, cur
diff --git a/internal/equipo/chat/research.go b/internal/equipo/chat/research.go
index b6545e9d..a1b0bb7f 100644
--- a/internal/equipo/chat/research.go
+++ b/internal/equipo/chat/research.go
@@ -622,7 +622,7 @@ func (t *txn) researchReport(l Lease, k *taskRecord, s *stepRecord, v *wire.Step
s.Family, s.Account, changed = firstSet(v.Family, s.Family), firstSet(v.Account, s.Account), true
}
// The scheduler's hold, as for every step.
- if acceptHold(s, v) {
+ if acceptHold(s, v, t.now()) {
changed = true
}
switch v.State {
diff --git a/internal/equipo/chat/schedule.go b/internal/equipo/chat/schedule.go
index 887aede0..c11799ea 100644
--- a/internal/equipo/chat/schedule.go
+++ b/internal/equipo/chat/schedule.go
@@ -113,11 +113,12 @@ func stepHold(s stepRecord) *wire.StepHold {
}
// acceptHold records a held step's hold from its runner's report, or
-// clears it. A hold the instance cannot read is not kept.
-func acceptHold(s *stepRecord, v *wire.StepReport) bool {
+// clears it. A hold the instance cannot read is not kept. HeldAt is when
+// the hold began (now, for a step not held before); it goes with it.
+func acceptHold(s *stepRecord, v *wire.StepReport, now time.Time) bool {
if v.Hold == nil || wire.StepTerminal(v.State) {
changed := s.Hold != ""
- s.Hold = ""
+ s.Hold, s.HeldAt = "", nil
return changed
}
h := *v.Hold
@@ -126,6 +127,10 @@ func acceptHold(s *stepRecord, v *wire.StepReport) bool {
}
raw := asJSON(h)
changed := raw != s.Hold
+ if s.Hold == "" || s.HeldAt == nil {
+ at := now.UTC()
+ s.HeldAt = &at
+ }
s.Hold = raw
return changed
}
@@ -142,53 +147,62 @@ func (s *Store) SetPriority(ctx context.Context, person, id string, in wire.SetP
if err := s.authority.CurrentPerson(ctx, t.db); err != nil {
return err
}
- if err := t.isOwner(person); err != nil {
- return err
- }
- k, err := t.loadTask(id)
- if err != nil {
- return err
- }
- if k.Creator != person {
- return ErrForbidden
- }
- if wire.FinalStage(k.Stage) || k.CancelRequested {
- return ErrTaskEnded
- }
- if in.Revision != k.Revision {
- return ErrConflict
- }
- var by *time.Time
- if in.By != nil {
- b := in.By.UTC()
- unchanged := k.DueBy != nil && k.DueBy.Equal(b)
- // A deadline newly given must be ahead; the one the task has may
- // have passed (an overdue task can still change priority).
- if !unchanged && (!b.After(t.now()) || b.Sub(t.now()) > wire.MaxByAhead) {
- return ErrInvalid
- }
- by = &b
- }
- k.Priority, k.DueBy, k.PrioritySetBy = in.Priority, by, wire.PrioritySetByPerson
- k.PriorityRevision++
- if err := t.db.Model(&taskRecord{}).Where("id = ?", k.ID).Select("priority", "due_by", "priority_set_by", "priority_revision").Updates(&k).Error; err != nil {
- return err
- }
- if err := t.saveTask(&k); err != nil {
- return err
- }
- if err := t.audit(person, "task.priority", k.ID+"@"+in.Priority); err != nil {
- return err
- }
- if err := t.sendPriority(k); err != nil {
- return err
- }
- out, err = t.taskView(k)
+ out, err = t.setPriority(person, id, in)
return err
})
return out, err
}
+// setPriority is SetPriority in t (advice's Make them low priority and
+// Make them normal act through it, task by task).
+func (t *txn) setPriority(person, id string, in wire.SetPriority) (out wire.Task, err error) {
+ if !wire.ValidPriority(in.Priority) {
+ return out, ErrInvalid
+ }
+ if err := t.isOwner(person); err != nil {
+ return out, err
+ }
+ k, err := t.loadTask(id)
+ if err != nil {
+ return out, err
+ }
+ if k.Creator != person {
+ return out, ErrForbidden
+ }
+ if wire.FinalStage(k.Stage) || k.CancelRequested {
+ return out, ErrTaskEnded
+ }
+ if in.Revision != k.Revision {
+ return out, ErrConflict
+ }
+ var by *time.Time
+ if in.By != nil {
+ b := in.By.UTC()
+ unchanged := k.DueBy != nil && k.DueBy.Equal(b)
+ // A deadline newly given must be ahead; the one the task has may
+ // have passed (an overdue task can still change priority).
+ if !unchanged && (!b.After(t.now()) || b.Sub(t.now()) > wire.MaxByAhead) {
+ return out, ErrInvalid
+ }
+ by = &b
+ }
+ k.Priority, k.DueBy, k.PrioritySetBy = in.Priority, by, wire.PrioritySetByPerson
+ k.PriorityRevision++
+ if err := t.db.Model(&taskRecord{}).Where("id = ?", k.ID).Select("priority", "due_by", "priority_set_by", "priority_revision").Updates(&k).Error; err != nil {
+ return out, err
+ }
+ if err := t.saveTask(&k); err != nil {
+ return out, err
+ }
+ if err := t.audit(person, "task.priority", k.ID+"@"+in.Priority); err != nil {
+ return out, err
+ }
+ if err := t.sendPriority(k); err != nil {
+ return out, err
+ }
+ return t.taskView(k)
+}
+
// sendPriority tells the runner of the task's queued or running step its
// new priority (a runner below the scheduler's protocol never spends,
// and takes the priority with its next dispatch).
diff --git a/internal/equipo/chat/tasks.go b/internal/equipo/chat/tasks.go
index 2d5c44b1..5d680dd0 100644
--- a/internal/equipo/chat/tasks.go
+++ b/internal/equipo/chat/tasks.go
@@ -249,6 +249,9 @@ type stepRecord struct {
// as low and never spends, wherever and whenever it is placed.
Hold string
HousekeepingAttempt int64
+ // HeldAt is when the runner first held the step without a break (nil
+ // while it is not held): advice's "waited a week".
+ HeldAt *time.Time
}
func (stepRecord) TableName() string { return "chat_steps" }
@@ -619,7 +622,7 @@ func (t *txn) writeStep(s *stepRecord) 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", "headline", "family", "account", "verdict", "review_label", "findings", "checks", "gate", "exit_code", "output", "republish", "from_attempt", "askable", "rebase", "from_base", "from_candidate", "merge_sha", "merge_into", "merge_strategy", "without_checks", "switched", "activity", "runner_id", "needs", "placement", "waiting_since", "refused_by", "withdrawn", "termination_kind", "publication", "publication_id", "apple", "checks_sandbox", "change_facts", "decided_by", "merge_source", "merge_parents", "hosted_ci", "kind", "note", "sandbox_runner", "unsandboxed_by", "unsandboxed_at", "unsandboxed_attempt", "unsandboxed_runner", "has_preview", "preview", "boundary", "question", "request_turn", "sources_card", "sources_hash", "research_grant", "research_grant_revision", "hold", "housekeeping_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", "headline", "family", "account", "verdict", "review_label", "findings", "checks", "gate", "exit_code", "output", "republish", "from_attempt", "askable", "rebase", "from_base", "from_candidate", "merge_sha", "merge_into", "merge_strategy", "without_checks", "switched", "activity", "runner_id", "needs", "placement", "waiting_since", "refused_by", "withdrawn", "termination_kind", "publication", "publication_id", "apple", "checks_sandbox", "change_facts", "decided_by", "merge_source", "merge_parents", "hosted_ci", "kind", "note", "sandbox_runner", "unsandboxed_by", "unsandboxed_at", "unsandboxed_attempt", "unsandboxed_runner", "has_preview", "preview", "boundary", "question", "request_turn", "sources_card", "sources_hash", "research_grant", "research_grant_revision", "hold", "housekeeping_attempt", "held_at").Updates(s).Error; err != nil {
return err
}
members, err := t.members()
@@ -1185,7 +1188,7 @@ func (t *txn) stepReport(l Lease, v *wire.StepReport) error {
} else {
// The scheduler's hold: kept while the runner holds the step,
// cleared by any report without it.
- if acceptHold(&s, v) {
+ if acceptHold(&s, v, t.now()) {
changed = true
}
if wire.StepTerminal(v.State) {
diff --git a/internal/equipo/chat/usage.go b/internal/equipo/chat/usage.go
new file mode 100644
index 00000000..d0413c11
--- /dev/null
+++ b/internal/equipo/chat/usage.go
@@ -0,0 +1,242 @@
+package chat
+
+import (
+ "context"
+ "errors"
+ "net/http"
+ "slices"
+ "sort"
+ "time"
+
+ "github.com/go-chi/chi/v5"
+ "gorm.io/gorm"
+
+ "amadan.net/oficina/equipo/internal/equipo/personapi"
+ "amadan.net/oficina/equipo/internal/wire"
+)
+
+// The Usage page's data (Connections rev 3 §6, connectors spec S4): the
+// person's own recorded token use over today, this week or this month
+// in their zone, grouped by connection, role, project or task (four
+// views of one dataset), with the estimate where a price table priced
+// the rows, and the price table each metered connection was last
+// charged by.
+
+// usageFrom is where period starts in loc: today, Monday, or the 1st.
+func usageFrom(period string, now time.Time, loc *time.Location) (time.Time, bool) {
+ l := now.In(loc)
+ day := time.Date(l.Year(), l.Month(), l.Day(), 0, 0, 0, 0, loc)
+ switch period {
+ case wire.UsageDay:
+ return day.UTC(), true
+ case wire.UsageWeek:
+ back := (int(day.Weekday()) + 6) % 7
+ return day.AddDate(0, 0, -back).UTC(), true
+ case wire.UsageMonth:
+ return time.Date(l.Year(), l.Month(), 1, 0, 0, 0, 0, loc).UTC(), true
+ }
+ return time.Time{}, false
+}
+
+// UsageTotals is GET /api/v1/usage?period=&by=: the person's own usage
+// rows for the period, summed per grouping. Rows that overcount are left
+// out and said so.
+func (s *Store) UsageTotals(ctx context.Context, person, period, by string) (out wire.UsageTotals, err error) {
+ if !slices.Contains(wire.UsageGroupings, by) {
+ return out, ErrInvalid
+ }
+ now := s.now()
+ from, ok := usageFrom(period, now, s.Zone(person))
+ if !ok {
+ return out, ErrInvalid
+ }
+ out = wire.UsageTotals{Period: period, By: by, From: from, To: now.UTC(), Rows: []wire.UsageRow{}, Prices: []wire.PriceSource{}}
+ err = s.read(ctx, func(tx *gorm.DB) error {
+ if err := s.authority.CurrentPerson(ctx, tx); err != nil {
+ return err
+ }
+ var conns []connectionRecord
+ if err := tx.Where("person = ?", person).Order("created_at, id").Find(&conns).Error; err != nil {
+ return err
+ }
+ // A usage row names the runner's local id; the page names the
+ // instance's connection.
+ byLocal := map[string]connectionRecord{}
+ for _, c := range conns {
+ if _, seen := byLocal[c.LocalID]; c.LocalID != "" && !seen {
+ byLocal[c.LocalID] = c
+ }
+ }
+ var rows []usageRecord
+ if err := tx.Where("person = ? AND recorded_at >= ?", person, from).Order("recorded_at, id").Find(&rows).Error; err != nil {
+ return err
+ }
+ tasks := map[string]taskRecord{}
+ projects := map[string]projectRecord{}
+ if by == wire.UsageByTask || by == wire.UsageByProject {
+ var ids []string
+ for _, r := range rows {
+ if r.TaskID != "" {
+ ids = append(ids, r.TaskID)
+ }
+ }
+ if len(ids) > 0 {
+ var ks []taskRecord
+ if err := tx.Where("id IN ?", ids).Find(&ks).Error; err != nil {
+ return err
+ }
+ var pids []string
+ for _, k := range ks {
+ tasks[k.ID] = k
+ pids = append(pids, k.ProjectID)
+ }
+ var ps []projectRecord
+ if err := tx.Where("id IN ?", pids).Find(&ps).Error; err != nil {
+ return err
+ }
+ for _, p := range ps {
+ projects[p.ID] = p
+ }
+ }
+ }
+ sums := map[string]*wire.UsageRow{}
+ for _, r := range rows {
+ if r.Overcount {
+ out.LeftOut = true
+ continue
+ }
+ id, label := "", ""
+ switch by {
+ case wire.UsageByConnection:
+ id, label = r.Connection, r.Provider
+ if c, ok := byLocal[r.Connection]; ok {
+ id, label = c.ID, c.Provider
+ }
+ case wire.UsageByRole:
+ id, label = r.Role, r.Role
+ case wire.UsageByTask:
+ if k, ok := tasks[r.TaskID]; ok {
+ id, label = k.ID, k.Title
+ }
+ case wire.UsageByProject:
+ if k, ok := tasks[r.TaskID]; ok {
+ id = k.ProjectID
+ if p, ok := projects[k.ProjectID]; ok {
+ label = ProjectName(p.Repo)
+ }
+ }
+ }
+ row := sums[id]
+ if row == nil {
+ row = &wire.UsageRow{ID: id, Label: label}
+ sums[id] = row
+ }
+ one := rowSpend(r)
+ row.Input += one.Tokens - figure(r.OutputTokens)
+ row.CachedInput += one.Cached
+ row.Output += figure(r.OutputTokens)
+ row.Partial = row.Partial || one.Partial
+ row.Attempts++
+ if r.CostMicros != nil {
+ cost := *r.CostMicros
+ if row.Cost != nil {
+ cost += *row.Cost
+ }
+ row.Cost, row.Currency = &cost, r.Currency
+ }
+ }
+ for _, row := range sums {
+ out.Rows = append(out.Rows, *row)
+ }
+ sort.Slice(out.Rows, func(i, j int) bool {
+ a, b := out.Rows[i], out.Rows[j]
+ if a.Input+a.Output != b.Input+b.Output {
+ return a.Input+a.Output > b.Input+b.Output
+ }
+ return a.ID < b.ID
+ })
+ // The price table each metered connection was last charged by.
+ var priced []usageRecord
+ if err := tx.Where("person = ? AND price_version <> ''", person).Order("recorded_at DESC, id DESC").Find(&priced).Error; err != nil {
+ return err
+ }
+ seen := map[string]bool{}
+ for _, r := range priced {
+ id := r.Connection
+ if c, ok := byLocal[r.Connection]; ok {
+ id = c.ID
+ }
+ if seen[id] {
+ continue
+ }
+ seen[id] = true
+ out.Prices = append(out.Prices, wire.PriceSource{Connection: id, PriceVersion: r.PriceVersion})
+ }
+ return nil
+ })
+ return out, err
+}
+
+// mountUsage adds the Usage resources (§10, Connections rev 3 §6).
+func (h *HTTP) mountUsage(r chi.Router) {
+ r.Get("/usage", h.bearer(h.usage))
+ r.Get("/advice", h.bearer(h.advice))
+ r.Post("/advice/{id}/act", h.bearer(h.actAdvice))
+ r.Post("/advice/{id}/dismiss", h.bearer(h.dismissAdvice))
+}
+
+func (h *HTTP) usage(w http.ResponseWriter, r *http.Request, p personapi.PersonPrincipal) {
+ period, by := r.URL.Query().Get("period"), r.URL.Query().Get("by")
+ if period == "" {
+ period = wire.UsageMonth
+ }
+ if by == "" {
+ by = wire.UsageByConnection
+ }
+ out, err := h.Store.UsageTotals(r.Context(), p.Address, period, by)
+ if err != nil {
+ h.fail(w, r, err)
+ return
+ }
+ writeJSON(w, 200, out)
+}
+
+func (h *HTTP) advice(w http.ResponseWriter, r *http.Request, p personapi.PersonPrincipal) {
+ out, err := h.Store.Advice(r.Context(), p.Address)
+ if err != nil {
+ h.fail(w, r, err)
+ return
+ }
+ writeJSON(w, 200, out)
+}
+
+// actAdvice is POST /api/v1/advice/{id}/act {revision}: 200 with the
+// advice acted on; 409 revision_conflict when it moved, was answered,
+// or its facts no longer hold.
+func (h *HTTP) actAdvice(w http.ResponseWriter, r *http.Request, p personapi.PersonPrincipal) {
+ h.adviceAction(w, r, p, h.Store.ActAdvice)
+}
+
+// dismissAdvice is POST /api/v1/advice/{id}/dismiss {revision}: Not now.
+func (h *HTTP) dismissAdvice(w http.ResponseWriter, r *http.Request, p personapi.PersonPrincipal) {
+ h.adviceAction(w, r, p, h.Store.DismissAdvice)
+}
+
+func (h *HTTP) adviceAction(w http.ResponseWriter, r *http.Request, p personapi.PersonPrincipal, do func(context.Context, string, string, wire.AdviceAction) (wire.Advice, error)) {
+ var in wire.AdviceAction
+ if err := readJSON(r, &in); err != nil {
+ h.fail(w, r, err)
+ return
+ }
+ out, err := do(r.Context(), p.Address, chi.URLParam(r, "id"), in)
+ if errors.Is(err, ErrConflict) {
+ current := out.Revision
+ personapi.WriteError(w, r, http.StatusConflict, "revision_conflict", &current)
+ return
+ }
+ if err != nil {
+ h.fail(w, r, err)
+ return
+ }
+ writeJSON(w, 200, out)
+}
diff --git a/internal/equipo/migrations/0074_thin_advice.sql b/internal/equipo/migrations/0074_thin_advice.sql
new file mode 100644
index 00000000..cb07d43f
--- /dev/null
+++ b/internal/equipo/migrations/0074_thin_advice.sql
@@ -0,0 +1,3 @@
+CREATE TABLE chat_advice (id text PRIMARY KEY, person text, key text, kind text, state text, subject text, facts text, text text, act text, dismiss text, card_id text, revision integer, created_at datetime, updated_at datetime, visible_at datetime, shown_at datetime, dismissed_at datetime);
+CREATE INDEX chat_advice_person ON chat_advice(person, key);
+ALTER TABLE chat_steps ADD COLUMN held_at datetime;
diff --git a/internal/equipo/migrations/schema.sql b/internal/equipo/migrations/schema.sql
index de415f0c..35516625 100644
--- a/internal/equipo/migrations/schema.sql
+++ b/internal/equipo/migrations/schema.sql
@@ -598,7 +598,7 @@ 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, moved_from text, branch_head text, merge_asked text, merged_sha text, merged_into text, merge_strategy text, merged_without_checks numeric, merged_at datetime, ready_sha text, merge_eligible text, done_at datetime, duplicate_of text, folded_into text, folded_stage text, folded_at datetime, engineering_runner text, merge_hold text, merge_verified numeric, revert_of text, revert_sha text, kind text, direction_asked text, built_as text, explored_from text, priority text, due_by datetime, priority_set_by text, priority_revision integer);
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, askable numeric, rebase numeric, from_base text, from_candidate text, merge_sha text, merge_into text, merge_strategy text, without_checks numeric, activity text, switched text, headline text, runner_id text, needs text, placement text, waiting_since datetime, refused_by text, withdrawn numeric, termination_kind text, publication text, publication_id text, apple numeric, checks_sandbox text, recheck_by text, change_facts text, decided_by text, merge_source text, merge_parents text, hosted_ci text, sandbox_runner text, unsandboxed_by text, unsandboxed_at datetime, unsandboxed_attempt integer, unsandboxed_runner text, has_preview numeric, preview text, kind text, note text, boundary text, question text, request_turn text, sources_card text, sources_hash text, research_grant text, research_grant_revision integer, hold text, housekeeping_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, rebase numeric, from_base text, from_candidate text, merge_sha text, merge_into text, merge_strategy text, without_checks numeric, activity text, switched text, headline text, runner_id text, needs text, placement text, waiting_since datetime, refused_by text, withdrawn numeric, termination_kind text, publication text, publication_id text, apple numeric, checks_sandbox text, recheck_by text, change_facts text, decided_by text, merge_source text, merge_parents text, hosted_ci text, sandbox_runner text, unsandboxed_by text, unsandboxed_at datetime, unsandboxed_attempt integer, unsandboxed_runner text, has_preview numeric, preview text, kind text, note text, boundary text, question text, request_turn text, sources_card text, sources_hash text, research_grant text, research_grant_revision integer, hold text, housekeeping_attempt integer, held_at datetime);
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, headline text, folded_from text);
CREATE INDEX chat_entry_task ON chat_task_entries(task_id);
@@ -656,3 +656,5 @@ CREATE TABLE chat_task_file_data (file_id text, idx integer, data blob, PRIMARY
CREATE TABLE chat_releases (id text PRIMARY KEY, task_id text, step_id text, step_revision integer, person text, runner_id text, created_at datetime);
CREATE INDEX chat_release_task ON chat_releases(task_id);
CREATE UNIQUE INDEX chat_release_step ON chat_releases(step_id, step_revision);
+CREATE TABLE chat_advice (id text PRIMARY KEY, person text, key text, kind text, state text, subject text, facts text, text text, act text, dismiss text, card_id text, revision integer, created_at datetime, updated_at datetime, visible_at datetime, shown_at datetime, dismissed_at datetime);
+CREATE INDEX chat_advice_person ON chat_advice(person, key);
diff --git a/internal/plan3test/person_api_contract_test.go b/internal/plan3test/person_api_contract_test.go
index 629f1fdd..32ea92e7 100644
--- a/internal/plan3test/person_api_contract_test.go
+++ b/internal/plan3test/person_api_contract_test.go
@@ -56,7 +56,7 @@ func personAPIContractCoverage(t *testing.T) {
f := newFixture(t)
registered := map[string]bool{}
// Thin v1 conversation routes are contracted by internal/wire fixtures.
- thin := map[string]bool{"GET /messages": true, "POST /messages": true, "GET /turns/{id}": true, "POST /turns/{id}/cancel": true, "GET /snapshot": true, "GET /events": true, "DELETE /projects/{id}": true, "POST /cards/{id}/answer": true, "GET /notebook": true, "POST /notebook/reset": true, "POST /tasks/{id}/retry": true, "POST /tasks/{id}/kind": true, "POST /tasks/{id}/round": true, "POST /tasks/{id}/recover": true, "POST /tasks/{id}/merge": true, "POST /tasks/{id}/duplicate": true, "POST /tasks/{id}/uncombine": true, "POST /tasks/{id}/undo-merge": true, "PUT /tasks/{id}/priority": true, "POST /tasks/{id}/run-now": true, "GET /projects/{id}/merge-policy": true, "PUT /projects/{id}/merge-policy": true, "GET /thinking": true, "PUT /thinking": true, "POST /tasks/{id}/thread": true, "GET /steps/{id}/log": true, "POST /tasks/{id}/questions": true, "POST /questions/{id}/cancel": true, "POST /connections": true, "POST /connections/{id}/cancel": true, "POST /connections/{id}/secret": true, "POST /connections/{id}/forget": true, "POST /connections/{id}/check": true, "POST /connections/{id}/model": true, "PUT /connections/{id}/budget": true, "POST /connections/{id}/resume": true, "GET /connections/preference": true, "PUT /connections/preference": true, "GET /housekeeping": true, "PUT /housekeeping": true, "PUT /housekeeping/detectors/{id}": true, "GET /housekeeping/actions": true, "POST /housekeeping/actions/{id}/undo": true, "POST /attachments": true, "GET /attachments/{id}": true, "GET /attachments/{id}/preview": true, "POST /specialists/{id}/revoke": true, "GET /tasks/{id}/files/{file}": true}
+ thin := map[string]bool{"GET /messages": true, "POST /messages": true, "GET /turns/{id}": true, "POST /turns/{id}/cancel": true, "GET /snapshot": true, "GET /events": true, "DELETE /projects/{id}": true, "POST /cards/{id}/answer": true, "GET /notebook": true, "POST /notebook/reset": true, "POST /tasks/{id}/retry": true, "POST /tasks/{id}/kind": true, "POST /tasks/{id}/round": true, "POST /tasks/{id}/recover": true, "POST /tasks/{id}/merge": true, "POST /tasks/{id}/duplicate": true, "POST /tasks/{id}/uncombine": true, "POST /tasks/{id}/undo-merge": true, "PUT /tasks/{id}/priority": true, "POST /tasks/{id}/run-now": true, "GET /projects/{id}/merge-policy": true, "PUT /projects/{id}/merge-policy": true, "GET /thinking": true, "PUT /thinking": true, "POST /tasks/{id}/thread": true, "GET /steps/{id}/log": true, "POST /tasks/{id}/questions": true, "POST /questions/{id}/cancel": true, "POST /connections": true, "POST /connections/{id}/cancel": true, "POST /connections/{id}/secret": true, "POST /connections/{id}/forget": true, "POST /connections/{id}/check": true, "POST /connections/{id}/model": true, "PUT /connections/{id}/budget": true, "POST /connections/{id}/resume": true, "GET /connections/preference": true, "PUT /connections/preference": true, "GET /housekeeping": true, "PUT /housekeeping": true, "PUT /housekeeping/detectors/{id}": true, "GET /housekeeping/actions": true, "POST /housekeeping/actions/{id}/undo": true, "POST /attachments": true, "GET /attachments/{id}": true, "GET /attachments/{id}/preview": true, "POST /specialists/{id}/revoke": true, "GET /tasks/{id}/files/{file}": true, "GET /usage": true, "GET /advice": true, "POST /advice/{id}/act": true, "POST /advice/{id}/dismiss": true}
must(t, chi.Walk(f.Store.PersonAPIHandler().(chi.Routes), func(method, path string, _ http.Handler, _ ...func(http.Handler) http.Handler) error {
if thin[method+" "+path] {
return nil