package plan3test import ( "amadan.net/oficina/equipo/internal/equipo/notifications" "encoding/json" "errors" "fmt" "gorm.io/gorm" "net/http" "net/http/httptest" "net/url" "reflect" "strings" "testing" "time" "amadan.net/oficina/equipo/internal/equipo" "amadan.net/oficina/equipo/internal/equipo/personapi" ) func notificationSubscription(t *testing.T, f *fixture, d personapi.PersonCredential) equipo.NotificationSubscription { t.Helper() w := deviceRequest(t, f, d.Token, "POST", "/api/v1/notification-subscriptions", fmt.Sprintf(`{"device_id":%q}`, d.ID), "subscribe", "") expectHTTP(t, w, 200) s := apiValue[equipo.NotificationSubscription](t, w) if s.DeviceID != d.ID || s.Cursor == "" || !s.Active || s.Revision != 1 { t.Fatal("invalid subscription", s) } return s } func notificationFeed(t *testing.T, f *fixture, d personapi.PersonCredential, cursor string) personapi.Page[equipo.Notification] { t.Helper() w := deviceRequest(t, f, d.Token, "GET", "/api/v1/notifications?cursor="+url.QueryEscape(cursor), "", "", "") expectHTTP(t, w, 200) if w.Header().Get("Cache-Control") != "no-store" || w.Header().Get("ETag") == "" { t.Fatal("private feed cache headers") } return apiValue[personapi.Page[equipo.Notification]](t, w) } func notificationAck(t *testing.T, f *fixture, d personapi.PersonCredential, s equipo.NotificationSubscription, n, key, rev string) { t.Helper() w := deviceRequest(t, f, d.Token, "POST", "/api/v1/notification-subscriptions/"+s.ID+"/ack", fmt.Sprintf(`{"notification_id":%q}`, n), key, rev) expectHTTP(t, w, 200) } func TestNotificationOutboxAtomic(t *testing.T) { f, x, p, c := claimTools(t) args := map[string]any{"message_id": c.Turn.MessageID, "question": "Private question text", "options": []any{}} q := toolCall(t, x, p, c, "q", "ask_person", args) if f.count(t, "SELECT count(*) FROM notification_outbox WHERE resource_id=? AND recipient=? AND kind='question'", q.ResourceID, owner.Address) != 1 { t.Fatal("question/card/outbox not committed together") } var eventID string must(t, f.DB.Writer().QueryRow("SELECT id FROM notification_outbox WHERE resource_id=?", q.ResourceID).Scan(&eventID)) f.exec(t, "UPDATE coordinator_questions SET state=state WHERE id=?", q.ResourceID) var replayID string must(t, f.DB.Writer().QueryRow("SELECT id FROM notification_outbox WHERE resource_id=?", q.ResourceID).Scan(&replayID)) if replayID != eventID { t.Fatal("duplicate effect changed notification ID") } before := f.count(t, "SELECT count(*) FROM notification_outbox") toolCall(t, x, p, c, "q", "ask_person", args) if f.count(t, "SELECT count(*) FROM notification_outbox") != before { t.Fatal("replay duplicated outbox") } f.exec(t, "CREATE TRIGGER fail_notification BEFORE INSERT ON notification_outbox BEGIN SELECT RAISE(ABORT,'fixture'); END") args["question"] = "A different question" raw, _ := json.Marshal(args) // A different tool request must roll back both its question and card. call := notificationToolCall("rollback", raw) if _, err := x.CallCoordinatorTool(ctx, p, c, call); err == nil { t.Fatal("outbox failure did not roll back effect") } if f.count(t, "SELECT count(*) FROM coordinator_questions") != 1 || f.count(t, "SELECT count(*) FROM notification_outbox") != before { t.Fatal("rollback left notification or question") } f.exec(t, "DROP TRIGGER fail_notification") f.exec(t, "CREATE TRIGGER fail_notification_audit BEFORE INSERT ON audit_events BEGIN SELECT RAISE(ABORT,'fixture'); END") if _, err := x.CallCoordinatorTool(ctx, p, c, call); err == nil { t.Fatal("audit failure ignored") } if f.count(t, "SELECT count(*) FROM notification_outbox") != before { t.Fatal("rollback emitted notification") } f.exec(t, "DROP TRIGGER fail_notification_audit") f = newFixture(t) plan := proposed(t, f) notificationPlanWait(t, f, plan.TaskID) if f.count(t, "SELECT count(*) FROM notification_outbox WHERE resource_id=? AND kind='task_ready'", plan.TaskID) != 1 { t.Fatal("plan card notification missing") } plan.Steps[0].Instructions = "changed" _, err := f.Store.EditPlan(ctx, owner, plan, equipo.Mutation{RequestID: "edit", Revision: 1}) must(t, err) notificationPlanWait(t, f, plan.TaskID) if f.count(t, "SELECT count(*) FROM notification_outbox WHERE resource_id=? AND resource_revision=2", plan.TaskID) != 1 { t.Fatal("plan revision notification missing") } if f.count(t, "SELECT count(*) FROM notification_outbox WHERE resource_id=? AND resource_revision=1 AND state='superseded'", plan.TaskID) != 1 { t.Fatal("old plan notification retained") } } func TestNotificationRecipientIsolation(t *testing.T) { f := newFixture(t) d := approvedDevice(t, f) s := notificationSubscription(t, f, d) p := proposed(t, f) notificationPlanWait(t, f, p.TaskID) own := notificationFeed(t, f, d, s.Cursor) if len(own.Items) != 1 || own.Items[0].ResourceID != p.TaskID { t.Fatal("missing own notification", own) } other, err := f.Store.Notifications(ctx, peer, "", 50) must(t, err) if len(other.Items) != 0 { t.Fatal("recipient scope leaked", other) } if _, err = f.Store.Notifications(ctx, peer, s.Cursor, 50); err == nil { t.Fatal("foreign cursor accepted") } if err = f.Store.AcknowledgeNotification(ctx, peer, s.ID, own.Items[0].ID, equipo.Mutation{RequestID: "foreign", Revision: 1}); err == nil { t.Fatal("foreign acknowledgement accepted") } if f.Store.AllowNotificationSubscription(ctx, peer, s.ID) { t.Fatal("foreign live allowed") } if !f.Store.AllowNotificationSubscription(ctx, owner, s.ID) { t.Fatal("own live denied") } f.exec(t, "UPDATE members SET active=0 WHERE address=?", owner.Address) if _, err = f.Store.Notifications(ctx, owner, s.Cursor, 50); !errors.Is(err, equipo.ErrForbidden) { t.Fatal("removed member read", err) } if f.Store.AllowNotificationSubscription(ctx, owner, s.ID) { t.Fatal("stale live allowed removed member") } if err = f.Store.AcknowledgeNotification(ctx, owner, s.ID, own.Items[0].ID, equipo.Mutation{RequestID: "removed", Revision: 1}); err == nil { t.Fatal("removed member ACK accepted") } if f.count(t, "SELECT count(*) FROM notification_subscriptions WHERE id=? AND active=1", s.ID) != 0 { t.Fatal("roster removal did not disable subscription") } } func TestNotificationReconnect(t *testing.T) { f := newFixture(t) a := approvedDevice(t, f) b := approvedDevice(t, f) sa := notificationSubscription(t, f, a) sb := notificationSubscription(t, f, b) f.task(t, owner, "first") f.exec(t, "UPDATE tasks SET state='proposed',revision=2,plan_revision=1,wait_code='plan.awaiting_approval' WHERE id='first'") f.task(t, owner, "second") f.exec(t, "UPDATE tasks SET state='proposed',revision=2,plan_revision=1,wait_code='plan.awaiting_approval' WHERE id='second'") // No delivery on B means no acknowledgement authority, even for the same person. pa := notificationFeed(t, f, a, sa.Cursor) if len(pa.Items) != 2 { t.Fatal("expected two events", pa) } body := fmt.Sprintf(`{"notification_id":%q}`, pa.Items[0].ID) expectHTTP(t, deviceRequest(t, f, b.Token, "POST", "/api/v1/notification-subscriptions/"+sb.ID+"/ack", body, "undelivered", `"1"`), 404) expectHTTP(t, deviceRequest(t, f, b.Token, "GET", "/api/v1/notifications?cursor="+url.QueryEscape(sa.Cursor), "", "", ""), 404) _ = notificationFeed(t, f, b, sb.Cursor) notificationAck(t, f, a, sa, pa.Items[1].ID, "second", `"1"`) if f.count(t, "SELECT ack_sequence FROM notification_subscriptions WHERE id=?", sa.ID) != 0 { t.Fatal("out-of-order ACK skipped earlier event") } notificationAck(t, f, a, sa, pa.Items[1].ID, "second", `"1"`) if f.count(t, "SELECT revision FROM notification_subscriptions WHERE id=?", sa.ID) != 2 { t.Fatal("lost ACK replay changed revision") } notificationAck(t, f, a, sa, pa.Items[0].ID, "first", `"2"`) if f.count(t, "SELECT ack_sequence FROM notification_subscriptions WHERE id=?", sa.ID) == 0 { t.Fatal("contiguous ACK did not advance") } pb := notificationFeed(t, f, b, sb.Cursor) if len(pb.Items) != 2 || pb.Items[0].State != "unread" || pb.Items[1].State != "unread" { t.Fatal("another device lost unread state", pb) } replay := notificationFeed(t, f, a, sa.Cursor) if len(replay.Items) != 2 || replay.Items[0].ID != pa.Items[0].ID || replay.Items[0].State != "acknowledged" { t.Fatal("reconnect did not preserve delivery IDs", replay) } } func TestNotificationStaleAnswer(t *testing.T) { f, x, p, c := claimTools(t) notificationRouter(t, f, f.Store) q := toolCall(t, x, p, c, "q", "ask_person", map[string]any{"message_id": c.Turn.MessageID, "question": "Secret question", "options": []map[string]string{{"id": "one", "label": "Secret option"}}}) feed, err := f.Store.Notifications(ctx, owner, "", 50) must(t, err) if len(feed.Items) != 1 { t.Fatal("missing question event", feed) } n := feed.Items[0] raw, _ := json.Marshal(n) for _, secret := range []string{"Secret question", "Secret option", "permission", "answer", "token", "recipient"} { if strings.Contains(string(raw), secret) { t.Fatal("notification contains authority/content", string(raw)) } } f.exec(t, "UPDATE coordinator_turns SET state='delivered' WHERE id=?", c.Turn.ID) get := apiRequest(t, f, owner, "GET", "/api/v1/questions/"+q.ResourceID, "", "", "") expectHTTP(t, get, 200) expectHTTP(t, apiRequest(t, f, owner, "POST", "/api/v1/questions/"+q.ResourceID+"/answer", `{"kind":"clarification","option_id":"one","text":""}`, "missing", ""), 428) // Supersede before the answer arrives: the notification's old revision cannot answer. f.exec(t, "UPDATE coordinator_questions SET state='superseded',revision=revision+1 WHERE id=?", q.ResourceID) expectHTTP(t, apiRequest(t, f, owner, "POST", "/api/v1/questions/"+q.ResourceID+"/answer", `{"kind":"clarification","option_id":"one","text":""}`, "stale", get.Header().Get("ETag")), 409) feed, err = f.Store.Notifications(ctx, owner, "", 50) must(t, err) if len(feed.Items) != 1 || feed.Items[0].State != "superseded" { t.Fatal("stale question remains actionable", feed) } } type notificationClock struct{ at time.Time } func (c *notificationClock) Now() time.Time { return c.at } func TestNotificationSubscriptionExpiry(t *testing.T) { f := newFixture(t) d := approvedDevice(t, f) clock := ¬ificationClock{time.Now().UTC()} s := equipo.NewStore(f.DB, equipo.WithRunnerClock(clock)) // The router initializes the instance key; fixture credentials remain offline. notificationRouter(t, f, s) sub := notificationSubscription(t, f, d) if !sub.ExpiresAt.Equal(d.ExpiresAt) { t.Fatal("subscription exceeds credential expiry", sub.ExpiresAt, d.ExpiresAt) } f.task(t, owner, "pending") f.exec(t, "UPDATE tasks SET state='proposed',revision=2,plan_revision=1,wait_code='plan.awaiting_approval' WHERE id='pending'") page := notificationFeed(t, f, d, sub.Cursor) if len(page.Items) != 1 { t.Fatal("pending work absent") } clock.at = sub.ExpiresAt if f.Store.AllowNotificationSubscription(ctx, owner, sub.ID) { t.Fatal("live allowed at deadline") } if _, err := f.Store.Notifications(ctx, owner, sub.Cursor, 50); err == nil { t.Fatal("feed allowed at deadline") } if err := f.Store.AcknowledgeNotification(ctx, owner, sub.ID, page.Items[0].ID, equipo.Mutation{RequestID: "late", Revision: 1}); err == nil { t.Fatal("ACK allowed at deadline") } // A fresh credential is required once the device itself expires. fresh := approvedDevice(t, f) replacement := notificationSubscription(t, f, fresh) unread := notificationFeed(t, f, fresh, replacement.Cursor) if len(unread.Items) != 1 || unread.Items[0].ID != page.Items[0].ID || unread.Items[0].State != "unread" { t.Fatal("replacement lost unread work", unread) } must(t, f.Store.RevokePersonDevice(ctx, owner, fresh.ID, equipo.Mutation{RequestID: "revoke", Revision: 3})) if f.count(t, "SELECT count(*) FROM notification_subscriptions WHERE device_id=? AND active=1", fresh.ID) != 0 { t.Fatal("device revocation not atomic") } expectHTTP(t, deviceRequest(t, f, fresh.Token, "GET", "/api/v1/me", "", "", ""), 401) // Even a stale active flag cannot outlive its revoked credential. f.exec(t, "UPDATE notification_subscriptions SET active=1 WHERE id=?", replacement.ID) if f.Store.AllowNotificationSubscription(ctx, owner, replacement.ID) { t.Fatal("revoked live allowed") } if _, err := f.Store.Notifications(ctx, owner, replacement.Cursor, 50); err == nil { t.Fatal("revoked feed allowed") } } func TestNotificationNoExternalDelivery(t *testing.T) { f := newFixture(t) d := approvedDevice(t, f) for _, extra := range []string{`"recipient":"other@example.com"`, `"callback_url":"https://example.com/push"`, `"provider_token":"secret"`, `"answer":"allow"`} { expectHTTP(t, deviceRequest(t, f, d.Token, "POST", "/api/v1/notification-subscriptions", fmt.Sprintf(`{"device_id":%q,%s}`, d.ID, extra), "invalid", ""), 422) } for _, table := range []string{"notification_outbox", "notification_subscriptions", "notification_deliveries"} { var names []string must(t, f.DB.G.Raw("SELECT name FROM pragma_table_info(?)", table).Scan(&names).Error) if len(names) == 0 { t.Fatal("missing notification table", table) } for _, name := range names { if strings.Contains(name, "token") || strings.Contains(name, "secret") || strings.Contains(name, "callback") { t.Fatal("external delivery field", name) } } } sub := notificationSubscription(t, f, d) raw, _ := json.Marshal(sub) var keys map[string]any must(t, json.Unmarshal(raw, &keys)) expected := []string{"id", "device_id", "cursor", "revision", "active", "expires_at"} if len(keys) != len(expected) { t.Fatal("unexpected subscription payload", string(raw)) } for _, key := range expected { if _, ok := keys[key]; !ok { t.Fatal("missing safe field", key) } } // Store methods return explicit values, not records or credential capabilities. if reflect.TypeOf(sub).Kind() != reflect.Struct { t.Fatal("subscription is not a projection") } } func TestNotificationLiveRechecks(t *testing.T) { f := newFixture(t) d := approvedDevice(t, f) sub := notificationSubscription(t, f, d) topic := notifications.Topic(f.TeamID, owner.Address, sub.ID) allowed := func(r *http.Request, key string) bool { return f.Store.AllowNotificationTopic(r.Context(), owner, key) } writes := 0 next := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if _, err := w.Write([]byte("before")); err != nil { t.Fatal(err) } writes++ must(t, f.Store.RevokePersonDevice(ctx, owner, d.ID, equipo.Mutation{RequestID: "live-revoke", Revision: 3})) if _, err := w.Write([]byte("after")); err == nil { t.Fatal("stale stream wrote after revocation") } writes++ }) w := httptest.NewRecorder() notifications.GuardLive(next, allowed).ServeHTTP(w, httptest.NewRequest("GET", "/live?t="+url.QueryEscape(topic+"@0"), nil)) if writes != 2 || w.Body.String() != "before" { t.Fatal("live guard leaked invalidation", w.Body.String()) } } func TestNotificationRetentionAndCursor(t *testing.T) { f := newFixture(t) d := approvedDevice(t, f) sub := notificationSubscription(t, f, d) clock := ¬ificationClock{time.Now().UTC()} s := equipo.NewStore(f.DB, equipo.WithRunnerClock(clock)) notificationRouter(t, f, s) f.task(t, owner, "retained") f.exec(t, "UPDATE tasks SET state='proposed',revision=2,plan_revision=1,wait_code='plan.awaiting_approval' WHERE id='retained'") page := notificationFeed(t, f, d, sub.Cursor) notificationAck(t, f, d, sub, page.Items[0].ID, "ack", `"1"`) // Cursor remains cryptographically fresh; the retained-history boundary changed. f.exec(t, "UPDATE notification_outbox SET acknowledged_at=?", clock.at.Add(-30*24*time.Hour-time.Second)) // Do not renew the device/subscription while pruning. expectHTTP(t, apiRequest(t, f, owner, "GET", "/api/v1/notifications?cursor="+url.QueryEscape(page.NextCursor), "", "", ""), 410) fresh, err := f.Store.Notifications(ctx, owner, "", 50) must(t, err) if len(fresh.Items) != 0 || f.count(t, "SELECT count(*) FROM notification_outbox") != 0 { t.Fatal("old acknowledged history retained") } // A modified or other-route token is never an accepted continuation. expectHTTP(t, apiRequest(t, f, owner, "GET", "/api/v1/notifications?cursor="+url.QueryEscape(fresh.NextCursor+"x"), "", "", ""), 410) expectHTTP(t, apiRequest(t, f, owner, "GET", "/api/v1/people?cursor="+url.QueryEscape(fresh.NextCursor), "", "", ""), 410) clock.at = clock.at.Add(24 * time.Hour) if _, err = f.Store.Notifications(ctx, owner, fresh.NextCursor, 50); !errors.Is(err, equipo.ErrCursorExpired) { t.Fatal("expired cursor accepted", err) } } func TestNotificationNativeAndReady(t *testing.T) { f, x, principal, request, q := nativeConversationFixture(t) feed, err := f.Store.Notifications(ctx, owner, "", 100) must(t, err) var found bool for _, n := range feed.Items { if n.ResourceID == q.ID { found = true if n.State != "unread" { t.Fatal("current native question superseded", n) } } } if !found { t.Fatal("native question event missing") } device := approvedDevice(t, f) sub := notificationSubscription(t, f, device) delivered := notificationFeed(t, f, device, sub.Cursor) for _, n := range delivered.Items { if n.ResourceID == q.ID { notificationAck(t, f, device, sub, n.ID, "question-ack", `"1"`) } } needs := apiRequest(t, f, owner, "GET", "/api/v1/needs-you", "", "", "") expectHTTP(t, needs, 200) tasks := apiValue[personapi.Page[personapi.Task]](t, needs) pending := false for _, task := range tasks.Items { if task.ID == q.TaskID { pending = true } } if !pending { t.Fatal("acknowledgement hid pending question from Needs you") } before := f.count(t, "SELECT count(*) FROM notification_outbox WHERE resource_id=?", q.ID) request.Question = &q _, err = x.Mutate(ctx, principal, "questions", request) must(t, err) if f.count(t, "SELECT count(*) FROM notification_outbox WHERE resource_id=?", q.ID) != before { t.Fatal("native replay duplicated notification") } f.exec(t, "UPDATE questions SET state='invalid' WHERE id=?", q.ID) feed, err = f.Store.Notifications(ctx, owner, "", 100) must(t, err) for _, n := range feed.Items { if n.ResourceID == q.ID && n.State != "superseded" { t.Fatal("invalid native event remains current") } } // Core completion notifies the requester and an explicit decision owner atomically. var task equipo.Task must(t, f.DB.G.First(&task, "id=?", q.TaskID).Error) f.exec(t, "UPDATE decision_owners SET address=? WHERE project_id=? AND decision='merge'", peer.Address, task.ProjectID) must(t, x.Write(ctx, func(tx *gorm.DB) error { return tx.Exec("UPDATE jobs SET state='succeeded',revision=revision+1 WHERE id=?", task.JobID).Error })) for _, recipient := range []string{owner.Address, peer.Address} { if f.count(t, "SELECT count(*) FROM notification_outbox WHERE event='task_ready.complete' AND resource_id=? AND recipient=?", task.ID, recipient) != 1 { t.Fatal("completion recipient missing", recipient) } } }