oficina / equipo Public

Checkpoint notification receipt and retry tests before Mac fixes

Paul Campbell pushed by claude agent, operated by paul@keymail.dev 4dac01115a58c54cd2149c70df91ec976386608d parent 7b909ea
8 files changed, +350 −88
  • internal/equipo/chat/models.go +1 −1
  • internal/equipo/chat/notification_actions.go +134 −0
  • internal/equipo/chat/notification_actions_test.go +84 −0
  • internal/equipo/chat/projects.go +101 −78
  • internal/equipo/chat/store.go +7 −6
  • internal/equipo/migrations/0111_notification_actions.sql +10 −0
  • internal/wire/api.go +4 −3
  • internal/wire/push.go +9 −0
diff --git a/internal/equipo/chat/models.go b/internal/equipo/chat/models.go
index 3b0444a9..0fd04e0f 100644
--- a/internal/equipo/chat/models.go
+++ b/internal/equipo/chat/models.go
@@ -11,7 +11,7 @@ import (
)
// Models are the tables this package owns, for the migration check.
-var Models = append([]any{&projectNameRecord{}, &cardVisibility{}, &cardThreadRecord{}, &copyAttemptRecord{}, &copyReviewRecord{}, &copyFeedbackRecord{}, &turnRecord{}, &messageRecord{}, &eventRecord{}, &commandRecord{}, &inboxRecord{}, &runnerSessionRecord{}, &projectRecord{}, &cardRecord{}, &toolCallRecord{}, &settingRecord{}, &coordinatorRecord{}, &notebookRecord{}, &taskRecord{}, &stepRecord{}, &entryRecord{}, &attachmentRecord{}, &starRecord{}, &questionRecord{}, &connectionRecord{}, &usageRecord{}, &distinctRecord{}, &hkRecord{}, &hkFailureRecord{}, &hkSettingsRecord{}, &fileRecord{}, &fileDataRecord{}, &transferRecord{}, &mergePolicyRecord{}, &mergeAuditRecord{}, &specialistRecord{}, &grantRecord{}, &specialistAuditRecord{}, &researchSourceRecord{}, &researchAddressRecord{}, &researchPrefixRecord{}, &researchInventoryRecord{}, &researchRecord{}, &researchFetchRecord{}, &taskFileRecord{}, &taskFileDataRecord{}, &releaseRecord{}, &adviceRecord{}, &assistantHostRecord{}, &handoffRecord{}, &handoffTurnRecord{}, &handoffTaskRecord{}, &handoffActionRecord{}, &connectTurnRecord{}, &carriedRecord{}, &zoneRecord{}}, push.Models...)
+var Models = append([]any{&notificationReceipt{}, &projectNameRecord{}, &cardVisibility{}, &cardThreadRecord{}, &copyAttemptRecord{}, &copyReviewRecord{}, &copyFeedbackRecord{}, &turnRecord{}, &messageRecord{}, &eventRecord{}, &commandRecord{}, &inboxRecord{}, &runnerSessionRecord{}, &projectRecord{}, &cardRecord{}, &toolCallRecord{}, &settingRecord{}, &coordinatorRecord{}, &notebookRecord{}, &taskRecord{}, &stepRecord{}, &entryRecord{}, &attachmentRecord{}, &starRecord{}, &questionRecord{}, &connectionRecord{}, &usageRecord{}, &distinctRecord{}, &hkRecord{}, &hkFailureRecord{}, &hkSettingsRecord{}, &fileRecord{}, &fileDataRecord{}, &transferRecord{}, &mergePolicyRecord{}, &mergeAuditRecord{}, &specialistRecord{}, &grantRecord{}, &specialistAuditRecord{}, &researchSourceRecord{}, &researchAddressRecord{}, &researchPrefixRecord{}, &researchInventoryRecord{}, &researchRecord{}, &researchFetchRecord{}, &taskFileRecord{}, &taskFileDataRecord{}, &releaseRecord{}, &adviceRecord{}, &assistantHostRecord{}, &handoffRecord{}, &handoffTurnRecord{}, &handoffTaskRecord{}, &handoffActionRecord{}, &connectTurnRecord{}, &carriedRecord{}, &zoneRecord{}}, push.Models...)
type turnRecord struct {
CreateRepo string
diff --git a/internal/equipo/chat/notification_actions.go b/internal/equipo/chat/notification_actions.go
new file mode 100644
index 00000000..2eaca454
--- /dev/null
+++ b/internal/equipo/chat/notification_actions.go
@@ -0,0 +1,134 @@
+package chat
+
+import (
+ "context"
+ "crypto/sha256"
+ "encoding/hex"
+ "encoding/json"
+ "errors"
+ "time"
+
+ "amadan.net/oficina/equipo/internal/wire"
+ "gorm.io/gorm"
+)
+
+// Notification actions remain off until the operator completes device checks.
+func (s *Store) SetNotificationActions(enabled bool) { s.notificationActions.Store(enabled) }
+func (s *Store) NotificationActions() bool { return s.notificationActions.Load() }
+
+type notificationReceipt struct {
+ Person string `gorm:"primaryKey"`
+ Credential string `gorm:"primaryKey"`
+ Operation string `gorm:"primaryKey"`
+ Target string `gorm:"primaryKey"`
+ Key string `gorm:"primaryKey"`
+ Digest string
+ CardID string
+ MessageID string
+ TurnID string
+ Attempt int64
+ ExpiresAt time.Time `gorm:"index:notification_receipt_expiry"`
+}
+
+func (notificationReceipt) TableName() string { return "chat_notification_receipts" }
+
+func (t *txn) actionReceipt(person, credential, operation, target, key string, input any) (*notificationReceipt, bool, error) {
+ if !t.s.NotificationActions() || credential == "" {
+ return nil, false, ErrForbidden
+ }
+ if !validKey(key) {
+ return nil, false, ErrInvalid
+ }
+ if err := t.s.pushCurrent(t.db, person, credential); err != nil {
+ return nil, false, ErrForbidden
+ }
+ raw, err := json.Marshal(input)
+ if err != nil {
+ return nil, false, err
+ }
+ digest := sha256.Sum256(raw)
+ r := notificationReceipt{Person: person, Credential: credential, Operation: operation, Target: target, Key: key, Digest: hex.EncodeToString(digest[:]), ExpiresAt: t.now().Add(7 * 24 * time.Hour)}
+ // A bounded batch, plus this exact expired key, avoids unbounded cleanup.
+ if err = t.db.Exec("DELETE FROM chat_notification_receipts WHERE rowid IN (SELECT rowid FROM chat_notification_receipts WHERE expires_at <= ? LIMIT 100)", t.now()).Error; err != nil {
+ return nil, false, err
+ }
+ query := t.db.Where("person = ? AND credential = ? AND operation = ? AND target = ? AND key = ?", person, credential, operation, target, key)
+ if err = query.Where("expires_at <= ?", t.now()).Delete(&notificationReceipt{}).Error; err != nil {
+ return nil, false, err
+ }
+ var prior notificationReceipt
+ err = t.db.Where("person = ? AND credential = ? AND operation = ? AND target = ? AND key = ?", person, credential, operation, target, key).Take(&prior).Error
+ if errors.Is(err, gorm.ErrRecordNotFound) {
+ return &r, false, nil
+ }
+ if err != nil {
+ return nil, false, err
+ }
+ if prior.Digest != r.Digest {
+ return nil, false, ErrConflict
+ }
+ return &prior, true, nil
+}
+
+func (t *txn) receiptAnswer(r notificationReceipt) (out wire.Answered, err error) {
+ var c cardRecord
+ if err = t.db.Where("id = ? AND person = ?", r.CardID, r.Person).Take(&c).Error; err != nil {
+ return out, err
+ }
+ if out.Card, err = t.cardView(c); err != nil {
+ return out, err
+ }
+ if r.MessageID != "" {
+ var m messageRecord
+ if err = t.db.Where("id = ? AND person = ?", r.MessageID, r.Person).Take(&m).Error; err != nil {
+ return out, err
+ }
+ out.Message = messageView(m)
+ }
+ if r.TurnID != "" {
+ var turn turnRecord
+ if err = t.db.Where("id = ? AND person = ?", r.TurnID, r.Person).Take(&turn).Error; err != nil {
+ return out, err
+ }
+ out.Turn, err = t.turnView(turn)
+ }
+ return out, err
+}
+
+// RetryTaskBound retries exactly the failure seen in the notification.
+func (s *Store) RetryTaskBound(ctx context.Context, person, credential, id string, in wire.RetryTask) (attempt int64, err error) {
+ if in.Revision <= 0 || in.StepRevision <= 0 || in.Attempt <= 0 || in.StepID == "" || in.IdempotencyKey == "" {
+ return 0, ErrInvalid
+ }
+ err = s.tx(ctx, func(t *txn) error {
+ if err := s.authority.CurrentPerson(ctx, t.db); err != nil {
+ return err
+ }
+ r, prior, err := t.actionReceipt(person, credential, "retry", id, in.IdempotencyKey, in)
+ if err != nil {
+ return err
+ }
+ if prior {
+ attempt = r.Attempt
+ return nil
+ }
+ k, err := t.loadTask(id)
+ if err != nil {
+ return err
+ }
+ st, found, err := t.latestStep(id)
+ if err != nil {
+ return err
+ }
+ if k.Revision != in.Revision || !found || st.ID != in.StepID || st.Revision != in.StepRevision || st.Attempt != in.Attempt {
+ return ErrNotRetryable
+ }
+ attempt, err = t.personRetry(person, id, in.StepID, false)
+ if err != nil {
+ return err
+ }
+ r.Attempt = attempt
+ return t.db.Create(r).Error
+ })
+ return attempt, err
+}
diff --git a/internal/equipo/chat/notification_actions_test.go b/internal/equipo/chat/notification_actions_test.go
new file mode 100644
index 00000000..dfef6c15
--- /dev/null
+++ b/internal/equipo/chat/notification_actions_test.go
@@ -0,0 +1,84 @@
+package chat
+
+import (
+ "amadan.net/oficina/equipo/internal/wire"
+ "errors"
+ "testing"
+ "time"
+)
+
+func TestNotificationAnswerReceipt(t *testing.T) {
+ r := newPushRig(t)
+ r.s.SetNotificationActions(true)
+ c := r.card("nc1", wire.CardOpen)
+ in := wire.AnswerCard{Revision: c.Revision, Choice: "main", IdempotencyKey: "notification-answer-1"}
+ a, _, err := r.s.AnswerDevice(r.ctx, hkOwner, "cr_phone", c.ID, in)
+ r.must(err)
+ b, _, err := r.s.AnswerDevice(r.ctx, hkOwner, "cr_phone", c.ID, in)
+ r.must(err)
+ if a.Message.ID == "" || b.Message.ID != a.Message.ID || b.Turn.ID != a.Turn.ID {
+ t.Fatal("retry lost original result", a, b)
+ }
+ if got := r.count("SELECT count(*) FROM chat_messages WHERE idempotency_key = 'card:nc1'"); got != 1 {
+ t.Fatal(got)
+ }
+ in.Choice = "release"
+ if _, _, err = r.s.AnswerDevice(r.ctx, hkOwner, "cr_phone", c.ID, in); !errors.Is(err, ErrConflict) {
+ t.Fatal("changed body", err)
+ }
+ in.Choice = "main"
+ r.revoked["cr_phone"] = true
+ if _, _, err = r.s.AnswerDevice(r.ctx, hkOwner, "cr_phone", c.ID, in); !errors.Is(err, ErrForbidden) {
+ t.Fatal("revoked receipt read", err)
+ }
+ r.revoked["cr_phone"] = false
+ r.now = r.now.Add(8 * 24 * time.Hour)
+ if _, _, err = r.s.AnswerDevice(r.ctx, hkOwner, "cr_phone", c.ID, in); !errors.Is(err, ErrCardConflict) {
+ t.Fatal("expired receipt repeated action", err)
+ }
+}
+
+func TestNotificationRetryBinding(t *testing.T) {
+ for _, mutate := range []string{"task", "step", "revision", "attempt", "creator", "terminated", "none"} {
+ t.Run(mutate, func(t *testing.T) {
+ r := newPushRig(t)
+ r.s.SetNotificationActions(true)
+ k := r.task("tk-notify", "Fix", hkOwner)
+ r.step(&k, "st-notify", wire.SpecialistEngineering, wire.StepFailed)
+ k = r.load(k.ID)
+ in := wire.RetryTask{Revision: k.Revision, StepID: "st-notify", StepRevision: 1, Attempt: 1, IdempotencyKey: "notification-retry-1"}
+ person := hkOwner
+ switch mutate {
+ case "task":
+ in.Revision++
+ case "step":
+ in.StepID = "other"
+ case "revision":
+ in.StepRevision++
+ case "attempt":
+ in.Attempt++
+ case "creator":
+ person = "other@example.com"
+ case "terminated":
+ r.must(r.s.db.G.Model(&stepRecord{}).Where("id = ?", in.StepID).Update("terminated", false).Error)
+ }
+ first, err := r.s.RetryTaskBound(r.ctx, person, "cr_phone", k.ID, in)
+ if mutate != "none" {
+ if err == nil {
+ t.Fatal("accepted changed binding")
+ }
+ return
+ }
+ r.must(err)
+ again, err := r.s.RetryTaskBound(r.ctx, person, "cr_phone", k.ID, in)
+ r.must(err)
+ if first != again || first != 2 {
+ t.Fatal(first, again)
+ }
+ in.Attempt++
+ if _, err = r.s.RetryTaskBound(r.ctx, person, "cr_phone", k.ID, in); !errors.Is(err, ErrConflict) {
+ t.Fatal(err)
+ }
+ })
+ }
+}
diff --git a/internal/equipo/chat/projects.go b/internal/equipo/chat/projects.go
index 5b938ae9..c1d5d621 100644
--- a/internal/equipo/chat/projects.go
+++ b/internal/equipo/chat/projects.go
@@ -674,7 +674,11 @@ func (s *Store) Card(ctx context.Context, person, id string) (out wire.Card, err
// Answer answers a question card. The answer becomes the person's next
// message, so the coordinator reads it in a new turn. A stale revision or
// a card already answered is a conflict carrying the current card.
-func (s *Store) Answer(ctx context.Context, person, id string, in wire.AnswerCard) (out wire.Answered, current wire.Card, err error) {
+func (s *Store) Answer(ctx context.Context, person, id string, in wire.AnswerCard) (wire.Answered, wire.Card, error) {
+ return s.AnswerDevice(ctx, person, "", id, in)
+}
+
+func (s *Store) AnswerDevice(ctx context.Context, person, credential, id string, in wire.AnswerCard) (out wire.Answered, current wire.Card, err error) {
in.Choice = strings.TrimSpace(in.Choice)
if in.Choice == "" || len(in.Choice) > wire.MaxMessageBytes || !utf8.ValidString(in.Choice) || strings.ContainsRune(in.Choice, 0) {
return out, current, ErrInvalid
@@ -683,87 +687,106 @@ func (s *Store) Answer(ctx context.Context, person, id string, in wire.AnswerCar
if err := s.authority.CurrentPerson(ctx, t.db); err != nil {
return err
}
- var c cardRecord
- if err := t.db.Where("id = ? AND person = ? AND "+coordinatorRole, id, person).First(&c).Error; errors.Is(err, gorm.ErrRecordNotFound) {
- return ErrNotFound
- } else if err != nil {
- return err
- }
- if c.Kind == wire.CardHome {
- card, cur, e := t.answerHome(person, c, in)
- out.Card, current = card, cur
- return e
- }
- if c.Kind == wire.CardAccess {
- card, cur, e := t.answerAccess(person, c, in)
- out.Card, current = card, cur
- return e
- }
- if c.Kind == wire.CardCombined {
- card, cur, e := t.answerCombined(person, c, in)
- out.Card, current = card, cur
- return e
- }
- if c.Kind == wire.CardDirection {
- card, cur, e := t.answerDirection(person, c, in)
- out.Card, current = card, cur
- return e
- }
- if c.Kind == wire.CardSpecialist {
- card, cur, e := t.answerSpecialist(person, c, in)
- out.Card, current = card, cur
- return e
- }
- if c.Kind == wire.CardResearchSources {
- card, cur, e := t.answerResearchSources(person, c, in)
- out.Card, current = card, cur
- return e
- }
- if c.Kind == wire.CardResearchInventory {
- card, cur, e := t.answerResearchInventory(person, c, in)
- 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
- return e
- }
- if c.Kind == wire.CardMerge {
- card, cur, e := t.answerMerge(person, c, in)
- out.Card, current = card, cur
- return e
- }
- if c.Kind == wire.CardPublish {
- card, cur, e := t.answerPublish(person, c, in)
- out.Card, current = card, cur
- return e
+ var receipt *notificationReceipt
+ if in.IdempotencyKey != "" {
+ var prior bool
+ receipt, prior, err = t.actionReceipt(person, credential, "answer", id, in.IdempotencyKey, in)
+ if err != nil {
+ return err
+ }
+ if prior {
+ out, err = t.receiptAnswer(*receipt)
+ return err
+ }
}
- if c.Kind == wire.CardMergeShips || c.Kind == wire.CardMergePolicy || c.Kind == wire.CardMergeReceipt {
- var card, cur wire.Card
- var e error
- switch c.Kind {
- case wire.CardMergeShips:
- card, cur, e = t.answerShips(person, c, in)
- case wire.CardMergePolicy:
- card, cur, e = t.answerPolicyCard(person, c, in)
- default:
- card, cur, e = t.answerReceipt(person, c, in)
+ err = func() error {
+ var c cardRecord
+ if err := t.db.Where("id = ? AND person = ? AND "+coordinatorRole, id, person).First(&c).Error; errors.Is(err, gorm.ErrRecordNotFound) {
+ return ErrNotFound
+ } else if err != nil {
+ return err
+ }
+ if c.Kind == wire.CardHome {
+ card, cur, e := t.answerHome(person, c, in)
+ out.Card, current = card, cur
+ return e
+ }
+ if c.Kind == wire.CardAccess {
+ card, cur, e := t.answerAccess(person, c, in)
+ out.Card, current = card, cur
+ return e
+ }
+ if c.Kind == wire.CardCombined {
+ card, cur, e := t.answerCombined(person, c, in)
+ out.Card, current = card, cur
+ return e
+ }
+ if c.Kind == wire.CardDirection {
+ card, cur, e := t.answerDirection(person, c, in)
+ out.Card, current = card, cur
+ return e
}
- out.Card, current = card, cur
+ if c.Kind == wire.CardSpecialist {
+ card, cur, e := t.answerSpecialist(person, c, in)
+ out.Card, current = card, cur
+ return e
+ }
+ if c.Kind == wire.CardResearchSources {
+ card, cur, e := t.answerResearchSources(person, c, in)
+ out.Card, current = card, cur
+ return e
+ }
+ if c.Kind == wire.CardResearchInventory {
+ card, cur, e := t.answerResearchInventory(person, c, in)
+ 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
+ return e
+ }
+ if c.Kind == wire.CardMerge {
+ card, cur, e := t.answerMerge(person, c, in)
+ out.Card, current = card, cur
+ return e
+ }
+ if c.Kind == wire.CardPublish {
+ card, cur, e := t.answerPublish(person, c, in)
+ out.Card, current = card, cur
+ return e
+ }
+ if c.Kind == wire.CardMergeShips || c.Kind == wire.CardMergePolicy || c.Kind == wire.CardMergeReceipt {
+ var card, cur wire.Card
+ var e error
+ switch c.Kind {
+ case wire.CardMergeShips:
+ card, cur, e = t.answerShips(person, c, in)
+ case wire.CardMergePolicy:
+ card, cur, e = t.answerPolicyCard(person, c, in)
+ default:
+ card, cur, e = t.answerReceipt(person, c, in)
+ }
+ out.Card, current = card, cur
+ return e
+ }
+ if c.Kind != wire.CardQuestion && c.Kind != wire.CardProject {
+ return ErrNotFound
+ }
+ var e error
+ out, current, e = t.answerQuestionOrigin(person, c, in, originComposer)
return e
+ }()
+ if err != nil || receipt == nil {
+ return err
}
- if c.Kind != wire.CardQuestion && c.Kind != wire.CardProject {
- return ErrNotFound
- }
- var e error
- out, current, e = t.answerQuestionOrigin(person, c, in, originComposer)
- return e
+ receipt.CardID, receipt.MessageID, receipt.TurnID = out.Card.ID, out.Message.ID, out.Turn.ID
+ return t.db.Create(receipt).Error
})
return out, current, err
}
diff --git a/internal/equipo/chat/store.go b/internal/equipo/chat/store.go
index 7baa640e..8d0148a6 100644
--- a/internal/equipo/chat/store.go
+++ b/internal/equipo/chat/store.go
@@ -95,12 +95,13 @@ type Authority struct {
// Store owns the chat tables.
type Store struct {
- db *db.DB
- authority Authority
- hub *Hub
- now func() time.Time
- process string
- tap atomic.Pointer[func(runner string, raw []byte)]
+ notificationActions atomic.Bool
+ db *db.DB
+ authority Authority
+ hub *Hub
+ now func() time.Time
+ process string
+ tap atomic.Pointer[func(runner string, raw []byte)]
// Housekeeping: the detectors (housekeeping.Default unless a test
// declares others), the team's id once read, and the loop's clock
// (quiet hours, the day's budget, the digest), nil for now.
diff --git a/internal/equipo/migrations/0111_notification_actions.sql b/internal/equipo/migrations/0111_notification_actions.sql
new file mode 100644
index 00000000..34c940fa
--- /dev/null
+++ b/internal/equipo/migrations/0111_notification_actions.sql
@@ -0,0 +1,10 @@
+-- Notification actions are opt-in per device and disabled by default.
+ALTER TABLE push_registrations ADD COLUMN actions_version integer;
+ALTER TABLE push_registrations ADD COLUMN binding_id text;
+CREATE TABLE chat_notification_receipts (
+ person text, credential text, operation text, target text, key text,
+ digest text, card_id text, message_id text, turn_id text, attempt integer,
+ expires_at datetime,
+ PRIMARY KEY (person, credential, operation, target, key)
+);
+CREATE INDEX notification_receipt_expiry ON chat_notification_receipts(expires_at);
diff --git a/internal/wire/api.go b/internal/wire/api.go
index 0f5ebb02..5f5b32a0 100644
--- a/internal/wire/api.go
+++ b/internal/wire/api.go
@@ -401,9 +401,10 @@ type Card struct {
// AnswerCard is the body of POST /api/v1/cards/{id}/answer. Revision must
// be the card's current revision.
type AnswerCard struct {
- RememberName *string `json:"remember_name,omitempty"`
- Choice string `json:"choice"`
- Revision int64 `json:"revision"`
+ IdempotencyKey string `json:"idempotency_key,omitempty"`
+ RememberName *string `json:"remember_name,omitempty"`
+ Choice string `json:"choice"`
+ Revision int64 `json:"revision"`
// Note is the person's words with an answer that takes them (a
// direction card's Try again).
Note string `json:"note,omitempty"`
diff --git a/internal/wire/push.go b/internal/wire/push.go
index cf26f0e3..4355a835 100644
--- a/internal/wire/push.go
+++ b/internal/wire/push.go
@@ -129,3 +129,12 @@ type SetCardVisibility struct {
Aside bool `json:"aside"`
Revision int64 `json:"revision"`
}
+
+// RetryTask binds notification retry to the exact failed attempt shown.
+type RetryTask struct {
+ Revision int64 `json:"revision"`
+ StepID string `json:"step_id"`
+ StepRevision int64 `json:"step_revision"`
+ Attempt int64 `json:"attempt"`
+ IdempotencyKey string `json:"idempotency_key"`
+}