package plan3test import ( "amadan.net/oficina/equipo/internal/equipo" "amadan.net/oficina/equipo/internal/equipo/personapi" "errors" "fmt" "gorm.io/gorm" "testing" "time" ) func TestNotificationExplicitRenewal(t *testing.T) { f := newFixture(t) d := approvedDevice(t, f) clock := ¬ificationClock{time.Now().UTC()} notificationRouter(t, f, equipo.NewStore(f.DB, equipo.WithRunnerClock(clock))) // A fixture credential outlasting the subscription exercises its independent cap. f.exec(t, "UPDATE person_devices SET token_expires_at=? WHERE id=?", clock.at.Add(60*24*time.Hour), d.ID) sub := notificationSubscription(t, f, d) if !sub.ExpiresAt.Equal(clock.at.Add(30 * 24 * time.Hour)) { t.Fatal("subscription lacks independent 30 day cap") } f.task(t, owner, "renew") f.exec(t, "UPDATE tasks SET state='proposed',revision=2,plan_revision=1,wait_code='plan.awaiting_approval' WHERE id='renew'") page := notificationFeed(t, f, d, sub.Cursor) clock.at = clock.at.Add(time.Hour) page = notificationFeed(t, f, d, page.NextCursor) if len(page.Items) != 0 { t.Fatal("poll repeated earlier page") } saved, err := f.Store.NotificationSubscription(ctx, owner, sub.ID) must(t, err) if !saved.ExpiresAt.Equal(sub.ExpiresAt) { t.Fatal("poll renewed subscription") } clock.at = sub.ExpiresAt.Add(-time.Second) saved, err = f.Store.NotificationSubscription(ctx, owner, sub.ID) must(t, err) clock.at = sub.ExpiresAt if _, err = f.Store.Notifications(ctx, owner, saved.Cursor, 50); !errors.Is(err, personapi.ErrSubscriptionExpired) { t.Fatal("subscription deadline ignored with current device", err) } if f.Store.AllowNotificationSubscription(ctx, owner, sub.ID) { t.Fatal("live ignored independent subscription deadline") } var delivered string must(t, f.DB.Writer().QueryRow("SELECT id FROM notification_outbox LIMIT 1").Scan(&delivered)) if err = f.Store.AcknowledgeNotification(ctx, owner, sub.ID, delivered, equipo.Mutation{RequestID: "late", Revision: 1}); !errors.Is(err, personapi.ErrSubscriptionExpired) { t.Fatal("ACK ignored independent subscription deadline", err) } w := apiRequest(t, f, owner, "POST", "/api/v1/notification-subscriptions", fmt.Sprintf(`{"device_id":%q}`, d.ID), "replacement", "") expectHTTP(t, w, 200) replacement := apiValue[equipo.NotificationSubscription](t, w) if replacement.ID == sub.ID || replacement.ExpiresAt.After(clock.at.Add(30*24*time.Hour)) { t.Fatal("replacement reused expired subscription") } if f.count(t, "SELECT count(*) FROM notification_subscriptions WHERE id=? AND active=1", sub.ID) != 0 { t.Fatal("expired subscription still active after replacement") } unread := notificationFeed(t, f, d, replacement.Cursor) if len(unread.Items) != 1 || unread.Items[0].State != "unread" { t.Fatal("replacement lost unread event", unread) } notificationAck(t, f, d, replacement, unread.Items[0].ID, "ack", `"1"`) saved, err = f.Store.NotificationSubscription(ctx, owner, replacement.ID) must(t, err) if !saved.ExpiresAt.Equal(replacement.ExpiresAt) { t.Fatal("ACK renewed subscription") } expectHTTP(t, deviceRequest(t, f, d.Token, "DELETE", "/api/v1/notification-subscriptions/"+replacement.ID, `{}`, "unsubscribe", `"2"`), 200) expectHTTP(t, deviceRequest(t, f, d.Token, "DELETE", "/api/v1/notification-subscriptions/"+replacement.ID, `{}`, "unsubscribe", `"2"`), 200) if f.Store.AllowNotificationSubscription(ctx, owner, replacement.ID) { t.Fatal("unsubscribed live allowed") } } func TestNotificationPendingQuestionRetention(t *testing.T) { f, x, p, c := claimTools(t) notificationRouter(t, f, f.Store) d := approvedDevice(t, f) sub := notificationSubscription(t, f, d) q := toolCall(t, x, p, c, "pending", "ask_person", map[string]any{"message_id": c.Turn.MessageID, "question": "Still needs an answer", "options": []any{}}) page := notificationFeed(t, f, d, sub.Cursor) if len(page.Items) != 1 { t.Fatal("missing pending question", page) } notificationAck(t, f, d, sub, page.Items[0].ID, "ack", `"1"`) f.exec(t, "UPDATE notification_outbox SET acknowledged_at=?", time.Now().UTC().Add(-31*24*time.Hour)) _, err := f.Store.Notifications(ctx, owner, "", 50) must(t, err) if f.count(t, "SELECT count(*) FROM notification_outbox WHERE resource_id=?", q.ResourceID) != 1 { t.Fatal("cleanup removed current question") } expectHTTP(t, apiRequest(t, f, owner, "GET", "/api/v1/questions/"+q.ResourceID, "", "", ""), 200) // A second device sees the same still-open question as unread. other := approvedDevice(t, f) second := notificationSubscription(t, f, other) feed := notificationFeed(t, f, other, second.Cursor) if len(feed.Items) != 1 || feed.Items[0].State != "unread" { t.Fatal("pending question lost on another device", feed) } } func TestNotificationAuditAndRevocationRollback(t *testing.T) { f := newFixture(t) d := approvedDevice(t, f) sub := notificationSubscription(t, f, d) f.task(t, owner, "audit") f.exec(t, "UPDATE tasks SET state='proposed',revision=2,plan_revision=1,wait_code='plan.awaiting_approval' WHERE id='audit'") page := notificationFeed(t, f, d, sub.Cursor) f.exec(t, "CREATE TRIGGER notification_audit_refusal BEFORE INSERT ON audit_events WHEN NEW.kind IN ('notifications.ack','person_device.revoke') BEGIN SELECT RAISE(ABORT,'fixture'); END") if err := f.Store.AcknowledgeNotification(ctx, owner, sub.ID, page.Items[0].ID, equipo.Mutation{RequestID: "fail", Revision: 1}); err == nil { t.Fatal("ACK audit failure ignored") } if f.count(t, "SELECT count(*) FROM notification_deliveries WHERE acknowledged_at IS NOT NULL") != 0 || f.count(t, "SELECT ack_sequence FROM notification_subscriptions WHERE id=?", sub.ID) != 0 { t.Fatal("ACK partially committed") } if err := f.Store.RevokePersonDevice(ctx, owner, d.ID, equipo.Mutation{RequestID: "fail", Revision: 3}); err == nil { t.Fatal("revocation audit failure ignored") } if !f.Store.AllowNotificationSubscription(ctx, owner, sub.ID) { t.Fatal("rolled-back revocation disabled subscription") } f.exec(t, "DROP TRIGGER notification_audit_refusal") notificationAck(t, f, d, sub, page.Items[0].ID, "ack", `"1"`) // Both application replay and HTTP metadata reject changed bodies before revision checking. expectHTTP(t, deviceRequest(t, f, d.Token, "POST", "/api/v1/notification-subscriptions/"+sub.ID+"/ack", `{"notification_id":"different"}`, "ack", `"1"`), 409) f.exec(t, "ALTER TABLE members RENAME TO absent_members") if f.Store.AllowNotificationSubscription(ctx, owner, sub.ID) { t.Fatal("live allowed after roster lookup failure") } if _, err := f.Store.Notifications(ctx, owner, sub.Cursor, 50); err == nil { t.Fatal("feed allowed after roster lookup failure") } } func TestNotificationQuestionDeadline(t *testing.T) { f, x, p, c := claimTools(t) q := toolCall(t, x, p, c, "expiry", "ask_person", map[string]any{"message_id": c.Turn.MessageID, "question": "Expires soon", "options": []any{}}) clock := ¬ificationClock{time.Now().UTC()} notificationRouter(t, f, equipo.NewStore(f.DB, equipo.WithRunnerClock(clock))) page, err := f.Store.Notifications(ctx, owner, "", 50) must(t, err) if len(page.Items) != 1 || page.Items[0].State != "unread" { t.Fatal("current question missing", page) } clock.at = clock.at.Add(25 * time.Hour) page, err = f.Store.Notifications(ctx, owner, "", 50) must(t, err) if len(page.Items) != 1 || page.Items[0].State != "superseded" { t.Fatal("expired question remains current", page) } if f.count(t, "SELECT count(*) FROM notification_outbox WHERE resource_id=? AND state='superseded'", q.ResourceID) != 1 { t.Fatal("expired question not marked obsolete") } } func TestNotificationDecisionOwners(t *testing.T) { f := newFixture(t) p := proposed(t, f) x, task, _ := f.planCore(t, p) f.exec(t, "INSERT INTO decision_owners(project_id,decision,address) VALUES(?,'copy',?)", task.ProjectID, peer.Address) must(t, x.Write(ctx, func(tx *gorm.DB) error { return tx.Exec("UPDATE jobs SET state='waiting',wait='approval',revision=revision+1 WHERE id=?", task.JobID).Error })) if f.count(t, "SELECT count(*) FROM notification_outbox WHERE event LIKE 'task_ready.decision.%' AND recipient=?", peer.Address) != 1 { t.Fatal("explicit decision owner was not notified") } page, err := f.Store.Notifications(ctx, peer, "", 50) must(t, err) if len(page.Items) != 1 || page.Items[0].State != "unread" { t.Fatal("current decision not visible", page) } f.exec(t, "UPDATE decision_owners SET address=? WHERE project_id=? AND decision='copy'", owner.Address, task.ProjectID) page, err = f.Store.Notifications(ctx, peer, "", 50) must(t, err) if len(page.Items) != 1 || page.Items[0].State != "superseded" { t.Fatal("old decision owner retained current event", page) } } func TestNotificationAckLostWrite(t *testing.T) { f := newFixture(t) d := approvedDevice(t, f) sub := notificationSubscription(t, f, d) f.task(t, owner, "lost-write") f.exec(t, "UPDATE tasks SET state='proposed',revision=2,plan_revision=1,wait_code='plan.awaiting_approval' WHERE id='lost-write'") page := notificationFeed(t, f, d, sub.Cursor) f.exec(t, "CREATE TRIGGER skip_notification_update BEFORE UPDATE ON notification_subscriptions BEGIN SELECT RAISE(IGNORE); END") expectHTTP(t, deviceRequest(t, f, d.Token, "POST", "/api/v1/notification-subscriptions/"+sub.ID+"/ack", fmt.Sprintf(`{"notification_id":%q}`, page.Items[0].ID), "lost-write", `"1"`), 409) if f.count(t, "SELECT count(*) FROM notification_deliveries WHERE acknowledged_at IS NOT NULL") != 0 { t.Fatal("unstored cursor committed acknowledgement") } } func TestNotificationUnknownDevice(t *testing.T) { f := newFixture(t) expectHTTP(t, apiRequest(t, f, owner, "POST", "/api/v1/notification-subscriptions", `{"device_id":"absent"}`, "absent", ""), 404) } func TestNotificationCardResource(t *testing.T) { f, x, p, c := claimTools(t) notificationRouter(t, f, f.Store) toolCall(t, x, p, c, "suggestion", "suggest_specialist", map[string]any{"source_message_ids": []string{c.Turn.MessageID}, "draft": map[string]any{"name": "Suggested", "instructions": "Consider this"}}) page, err := f.Store.Notifications(ctx, owner, "", 50) must(t, err) if len(page.Items) != 1 || page.Items[0].Kind != "card" { t.Fatal("card event has no fetchable resource kind", page) } expectHTTP(t, apiRequest(t, f, owner, "GET", "/api/v1/cards/"+page.Items[0].ResourceID, "", "", ""), 200) }