feat: add a person-scoped notification outbox
32 files changed,
+2,437
−98
.rastrillo/budgets.txt+1 −1docs/api/equipo-v1.md+11 −1docs/api/equipo-v1.openapi.json+546 −1docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md+72 −0internal/equipo/app.go+3 −2internal/equipo/copy.go+16 −0internal/equipo/live.go+2 −70internal/equipo/migrations/0031_notifications.sql+76 −0internal/equipo/migrations/schema.sql+70 −0internal/equipo/migrations_test.go+43 −15internal/equipo/models.go+2 −1internal/equipo/notifications.go+28 −0internal/equipo/notifications/api.go+353 −0internal/equipo/notifications/budget_test.go+9 −0internal/equipo/notifications/live.go+73 −0internal/equipo/notifications/live_guard.go+47 −0internal/equipo/notifications/models.go+53 −0internal/equipo/notifications/observer.go+105 −0internal/equipo/notifications/outbox.go+91 −0internal/equipo/personapi/conversation.go+10 −0internal/equipo/personapi/handler.go+11 −0internal/equipo/personapi/notifications.go+49 −0internal/equipo/personapi/types.go+1 −0internal/equipo/store.go+2 −0internal/plan3test/coordinator_migration_test.go+2 −2internal/plan3test/migration_test.go+2 −2internal/plan3test/notifications_fixture.go+23 −0internal/plan3test/notifications_lifecycle_test.go+251 −0internal/plan3test/notifications_migration_test.go+66 −0internal/plan3test/notifications_test.go+415 −0internal/plan3test/person_api_contract_test.go+2 −1internal/plan3test/person_api_migration_test.go+2 −2
CI failed — run details
Intent
diff --git a/.rastrillo/budgets.txt b/.rastrillo/budgets.txt| index 0937d332..9f6909e5 100644 |
| --- a/.rastrillo/budgets.txt |
| +++ b/.rastrillo/budgets.txt |
| @@ -28,4 +28,4 @@ time internal/runner/provider/codex 15s Task 11a full branch gate measured 11.65 |
| time internal/directlive 360s Task 5 adds both coordinator policy cases to the fake certification matrix. The targeted 19-case fixture measured 287.275s; 360s leaves 25 percent headroom for namespaces, both adapters, journal, MCP probes and package siblings. Full-package timing is deferred by the targeted-only dispatch. |
| time internal/plan3test 300s Initial cap for combined browser and runner acceptance; measure at both usable stops. |
| -size internal/plan3test - 10000 Task 20 fix round 1 adds invalid-proof isolation, browser revocation, purpose-key, runner scope, migration, decision-owner and API budget-admission regressions in the mandated integration package. Measured 9692 test lines; the final targeted API gate measured 15.826s. The 300s time ceiling is unchanged. |
| +size internal/plan3test - 10500 Task 19 adds notification atomicity, recipient/device isolation, expiry, retention, reconnect, live invalidation and migration regressions in the mandated integration package. Measured 10425 test lines; targeted notification tests measured 10.842s during concurrent validation. The 300s time ceiling is unchanged. |
diff --git a/docs/api/equipo-v1.md b/docs/api/equipo-v1.md| index 6cf74242..0fdb4029 100644 |
| --- a/docs/api/equipo-v1.md |
| +++ b/docs/api/equipo-v1.md |
| @@ -60,4 +60,14 @@ After reconnecting, fetch the conversation, needs-you list and any open task aga |
| Fetch `/questions/{id}` before answering. A clarification accepts `kind: "clarification"` with `option_id` or `text`. A native permission question accepts `kind: "native"`, `behavior`, and only the `updated_input` shape permitted by that question. Post to `/questions/{id}/answer` using its original request revision and current person authentication. A notification action is never authentication. A cancelled, expired or superseded question cannot accept a new answer. |
| -Notification subscriptions are added by Task 19. Clients should treat a future notification as a reason to fetch current state, then use the authenticated question-answer operation. No notification delivery is promised by this task. |
| +Subscribe with `POST /api/v1/notification-subscriptions`, a fresh request key, and `{"device_id":"<your device ID>"}`. Use the returned `cursor` for `GET /api/v1/notifications?cursor=<cursor>`. Each subscription has its own delivery and acknowledgement state. A bearer can use only its bound device. A browser session can manage its own devices. |
| + |
| +Keep polling with `next_cursor`, including after an empty page. Delivery may repeat; deduplicate by notification `id`. A notification contains only its kind, resource ID, resource revision, time, state and instance-relative link. For `question`, fetch `/api/v1/questions/{resource_id}`; for `task_ready`, fetch `/api/v1/tasks/{resource_id}`; for `card`, fetch `/api/v1/cards/{resource_id}`. An `interrupted` event links to the affected task or conversation; fetch that current view before retrying work. `superseded` means the event no longer represents current work. Acknowledgement never answers a question or approves work. |
| + |
| +After receiving an event, post `{"notification_id":"<notification ID>"}` to `/api/v1/notification-subscriptions/{id}/ack` with a request key and the subscription revision in `If-Match`. Save the returned revision. Retry a lost acknowledgement with its original key, body and revision. Only delivered events can be acknowledged. An out-of-order acknowledgement is saved, but the subscription cursor advances only after all earlier recipient events are acknowledged. Another device keeps its unread state. |
| + |
| +Subscriptions expire after thirty days or when their device credential expires, whichever comes first. Polling and acknowledgements do not renew them. Device revocation or roster removal disables them immediately. On `410 subscription_expired`, subscribe explicitly with a current credential and a new request key. On `410 cursor_expired`, fetch notifications without a cursor and check the conversation and Needs you for open questions. Start a replacement subscription to receive those events on a device again. |
| + |
| +Acknowledged history is kept for at least thirty days. Cleanup preserves current questions and entries unread by an active subscription. Notifications without a subscription cursor provide a private snapshot but do not record delivery to a device. To unsubscribe, send an empty JSON object to `DELETE /api/v1/notification-subscriptions/{id}` with its current revision and a request key. |
| + |
| +Web clients can follow the private Rastrillo notification topic through the browser session. Its name is `notifications/` followed by the lowercase SHA-256 hex digest of compact JSON `[team_id,address,subscription_id]`. Pass that topic with `@0` in the existing `/live?t=` protocol. Each stream write checks the current roster, device and subscription deadline. External mobile push delivery is not implemented. |
diff --git a/docs/api/equipo-v1.openapi.json b/docs/api/equipo-v1.openapi.json| index de3aed0e..9a2f4e6a 100644 |
| --- a/docs/api/equipo-v1.openapi.json |
| +++ b/docs/api/equipo-v1.openapi.json |
| @@ -8063,6 +8063,397 @@ |
| } |
| ] |
| } |
| + }, |
| + "/notifications": { |
| + "get": { |
| + "operationId": "get_notifications", |
| + "parameters": [ |
| + { |
| + "name": "cursor", |
| + "in": "query", |
| + "schema": { |
| + "type": "string" |
| + } |
| + }, |
| + { |
| + "name": "limit", |
| + "in": "query", |
| + "schema": { |
| + "type": "integer", |
| + "default": 50, |
| + "minimum": 1, |
| + "maximum": 100 |
| + } |
| + } |
| + ], |
| + "responses": { |
| + "200": { |
| + "description": "OK", |
| + "headers": { |
| + "ETag": { |
| + "schema": { |
| + "type": "string", |
| + "pattern": "^\"(0|[1-9][0-9]*)\"$" |
| + } |
| + }, |
| + "Cache-Control": { |
| + "schema": { |
| + "const": "no-store" |
| + } |
| + } |
| + }, |
| + "content": { |
| + "application/json": { |
| + "schema": { |
| + "$ref": "#/components/schemas/NotificationPage" |
| + } |
| + } |
| + } |
| + }, |
| + "401": { |
| + "$ref": "#/components/responses/unauthenticated" |
| + }, |
| + "403": { |
| + "$ref": "#/components/responses/forbidden" |
| + }, |
| + "404": { |
| + "$ref": "#/components/responses/not_found" |
| + }, |
| + "405": { |
| + "$ref": "#/components/responses/method_not_allowed" |
| + }, |
| + "409": { |
| + "$ref": "#/components/responses/revision_conflict" |
| + }, |
| + "410": { |
| + "description": "cursor_expired or subscription_expired", |
| + "content": { |
| + "application/json": { |
| + "schema": { |
| + "$ref": "#/components/schemas/Error" |
| + } |
| + } |
| + } |
| + }, |
| + "422": { |
| + "$ref": "#/components/responses/invalid_input" |
| + }, |
| + "428": { |
| + "$ref": "#/components/responses/precondition_required" |
| + }, |
| + "503": { |
| + "$ref": "#/components/responses/unavailable" |
| + } |
| + }, |
| + "x-plan-part": "3b" |
| + } |
| + }, |
| + "/notification-subscriptions": { |
| + "post": { |
| + "operationId": "post_notification_subscriptions", |
| + "parameters": [ |
| + { |
| + "name": "Idempotency-Key", |
| + "in": "header", |
| + "required": true, |
| + "schema": { |
| + "type": "string", |
| + "minLength": 1, |
| + "maxLength": 256, |
| + "x-maxBytes": 256 |
| + } |
| + } |
| + ], |
| + "responses": { |
| + "200": { |
| + "description": "OK", |
| + "headers": { |
| + "ETag": { |
| + "schema": { |
| + "type": "string", |
| + "pattern": "^\"(0|[1-9][0-9]*)\"$" |
| + } |
| + }, |
| + "Cache-Control": { |
| + "schema": { |
| + "const": "no-store" |
| + } |
| + } |
| + }, |
| + "content": { |
| + "application/json": { |
| + "schema": { |
| + "$ref": "#/components/schemas/NotificationSubscription" |
| + } |
| + } |
| + } |
| + }, |
| + "401": { |
| + "$ref": "#/components/responses/unauthenticated" |
| + }, |
| + "403": { |
| + "$ref": "#/components/responses/forbidden" |
| + }, |
| + "404": { |
| + "$ref": "#/components/responses/not_found" |
| + }, |
| + "405": { |
| + "$ref": "#/components/responses/method_not_allowed" |
| + }, |
| + "409": { |
| + "$ref": "#/components/responses/revision_conflict" |
| + }, |
| + "410": { |
| + "description": "cursor_expired or subscription_expired", |
| + "content": { |
| + "application/json": { |
| + "schema": { |
| + "$ref": "#/components/schemas/Error" |
| + } |
| + } |
| + } |
| + }, |
| + "422": { |
| + "$ref": "#/components/responses/invalid_input" |
| + }, |
| + "428": { |
| + "$ref": "#/components/responses/precondition_required" |
| + }, |
| + "503": { |
| + "$ref": "#/components/responses/unavailable" |
| + } |
| + }, |
| + "x-plan-part": "3b", |
| + "requestBody": { |
| + "required": true, |
| + "content": { |
| + "application/json": { |
| + "schema": { |
| + "$ref": "#/components/schemas/SubscribeNotificationsInput" |
| + } |
| + } |
| + }, |
| + "x-maxBytes": 65536, |
| + "x-rejectDuplicateKeys": true, |
| + "x-rejectUnknownFields": true |
| + } |
| + } |
| + }, |
| + "/notification-subscriptions/{id}": { |
| + "delete": { |
| + "operationId": "delete_notification_subscriptions_id", |
| + "parameters": [ |
| + { |
| + "name": "id", |
| + "in": "path", |
| + "required": true, |
| + "schema": { |
| + "type": "string" |
| + } |
| + }, |
| + { |
| + "name": "Idempotency-Key", |
| + "in": "header", |
| + "required": true, |
| + "schema": { |
| + "type": "string", |
| + "minLength": 1, |
| + "maxLength": 256, |
| + "x-maxBytes": 256 |
| + } |
| + }, |
| + { |
| + "name": "If-Match", |
| + "in": "header", |
| + "required": true, |
| + "schema": { |
| + "type": "string", |
| + "pattern": "^\"(0|[1-9][0-9]*)\"$" |
| + } |
| + } |
| + ], |
| + "responses": { |
| + "200": { |
| + "description": "OK", |
| + "headers": { |
| + "ETag": { |
| + "schema": { |
| + "type": "string", |
| + "pattern": "^\"(0|[1-9][0-9]*)\"$" |
| + } |
| + }, |
| + "Cache-Control": { |
| + "schema": { |
| + "const": "no-store" |
| + } |
| + } |
| + }, |
| + "content": { |
| + "application/json": { |
| + "schema": { |
| + "$ref": "#/components/schemas/Ack" |
| + } |
| + } |
| + } |
| + }, |
| + "401": { |
| + "$ref": "#/components/responses/unauthenticated" |
| + }, |
| + "403": { |
| + "$ref": "#/components/responses/forbidden" |
| + }, |
| + "404": { |
| + "$ref": "#/components/responses/not_found" |
| + }, |
| + "405": { |
| + "$ref": "#/components/responses/method_not_allowed" |
| + }, |
| + "409": { |
| + "$ref": "#/components/responses/revision_conflict" |
| + }, |
| + "410": { |
| + "description": "cursor_expired or subscription_expired", |
| + "content": { |
| + "application/json": { |
| + "schema": { |
| + "$ref": "#/components/schemas/Error" |
| + } |
| + } |
| + } |
| + }, |
| + "422": { |
| + "$ref": "#/components/responses/invalid_input" |
| + }, |
| + "428": { |
| + "$ref": "#/components/responses/precondition_required" |
| + }, |
| + "503": { |
| + "$ref": "#/components/responses/unavailable" |
| + } |
| + }, |
| + "x-plan-part": "3b", |
| + "requestBody": { |
| + "required": true, |
| + "content": { |
| + "application/json": { |
| + "schema": { |
| + "$ref": "#/components/schemas/Empty" |
| + } |
| + } |
| + }, |
| + "x-maxBytes": 65536, |
| + "x-rejectDuplicateKeys": true, |
| + "x-rejectUnknownFields": true |
| + } |
| + } |
| + }, |
| + "/notification-subscriptions/{id}/ack": { |
| + "post": { |
| + "operationId": "post_notification_subscriptions_id_ack", |
| + "parameters": [ |
| + { |
| + "name": "id", |
| + "in": "path", |
| + "required": true, |
| + "schema": { |
| + "type": "string" |
| + } |
| + }, |
| + { |
| + "name": "Idempotency-Key", |
| + "in": "header", |
| + "required": true, |
| + "schema": { |
| + "type": "string", |
| + "minLength": 1, |
| + "maxLength": 256, |
| + "x-maxBytes": 256 |
| + } |
| + }, |
| + { |
| + "name": "If-Match", |
| + "in": "header", |
| + "required": true, |
| + "schema": { |
| + "type": "string", |
| + "pattern": "^\"(0|[1-9][0-9]*)\"$" |
| + } |
| + } |
| + ], |
| + "responses": { |
| + "200": { |
| + "description": "OK", |
| + "headers": { |
| + "ETag": { |
| + "schema": { |
| + "type": "string", |
| + "pattern": "^\"(0|[1-9][0-9]*)\"$" |
| + } |
| + }, |
| + "Cache-Control": { |
| + "schema": { |
| + "const": "no-store" |
| + } |
| + } |
| + }, |
| + "content": { |
| + "application/json": { |
| + "schema": { |
| + "$ref": "#/components/schemas/Ack" |
| + } |
| + } |
| + } |
| + }, |
| + "401": { |
| + "$ref": "#/components/responses/unauthenticated" |
| + }, |
| + "403": { |
| + "$ref": "#/components/responses/forbidden" |
| + }, |
| + "404": { |
| + "$ref": "#/components/responses/not_found" |
| + }, |
| + "405": { |
| + "$ref": "#/components/responses/method_not_allowed" |
| + }, |
| + "409": { |
| + "$ref": "#/components/responses/revision_conflict" |
| + }, |
| + "410": { |
| + "description": "cursor_expired or subscription_expired", |
| + "content": { |
| + "application/json": { |
| + "schema": { |
| + "$ref": "#/components/schemas/Error" |
| + } |
| + } |
| + } |
| + }, |
| + "422": { |
| + "$ref": "#/components/responses/invalid_input" |
| + }, |
| + "428": { |
| + "$ref": "#/components/responses/precondition_required" |
| + }, |
| + "503": { |
| + "$ref": "#/components/responses/unavailable" |
| + } |
| + }, |
| + "x-plan-part": "3b", |
| + "requestBody": { |
| + "required": true, |
| + "content": { |
| + "application/json": { |
| + "schema": { |
| + "$ref": "#/components/schemas/AcknowledgeNotificationInput" |
| + } |
| + } |
| + }, |
| + "x-maxBytes": 65536, |
| + "x-rejectDuplicateKeys": true, |
| + "x-rejectUnknownFields": true |
| + } |
| + } |
| } |
| }, |
| "components": { |
| @@ -8096,7 +8487,8 @@ |
| "unavailable", |
| "device_expired", |
| "slow_down", |
| - "authorization_pending" |
| + "authorization_pending", |
| + "subscription_expired" |
| ] |
| }, |
| "copy_key": { |
| @@ -11063,6 +11455,142 @@ |
| "$ref": "#/components/schemas/Plan" |
| } |
| ] |
| + }, |
| + "Notification": { |
| + "type": "object", |
| + "additionalProperties": false, |
| + "properties": { |
| + "id": { |
| + "type": "string" |
| + }, |
| + "kind": { |
| + "type": "string", |
| + "enum": [ |
| + "question", |
| + "task_ready", |
| + "interrupted", |
| + "card" |
| + ] |
| + }, |
| + "resource_id": { |
| + "type": "string" |
| + }, |
| + "deep_link": { |
| + "type": "string", |
| + "pattern": "^/[^/]" |
| + }, |
| + "resource_revision": { |
| + "type": "integer", |
| + "format": "int64" |
| + }, |
| + "created_at": { |
| + "type": "string", |
| + "format": "date-time" |
| + }, |
| + "state": { |
| + "type": "string", |
| + "enum": [ |
| + "unread", |
| + "acknowledged", |
| + "superseded" |
| + ] |
| + } |
| + }, |
| + "required": [ |
| + "id", |
| + "kind", |
| + "resource_id", |
| + "deep_link", |
| + "resource_revision", |
| + "created_at", |
| + "state" |
| + ] |
| + }, |
| + "NotificationSubscription": { |
| + "type": "object", |
| + "additionalProperties": false, |
| + "properties": { |
| + "id": { |
| + "type": "string" |
| + }, |
| + "device_id": { |
| + "type": "string" |
| + }, |
| + "cursor": { |
| + "type": "string" |
| + }, |
| + "revision": { |
| + "type": "integer", |
| + "format": "int64" |
| + }, |
| + "active": { |
| + "type": "boolean" |
| + }, |
| + "expires_at": { |
| + "type": "string", |
| + "format": "date-time" |
| + } |
| + }, |
| + "required": [ |
| + "id", |
| + "device_id", |
| + "cursor", |
| + "revision", |
| + "active", |
| + "expires_at" |
| + ] |
| + }, |
| + "NotificationPage": { |
| + "type": "object", |
| + "additionalProperties": false, |
| + "properties": { |
| + "items": { |
| + "type": "array", |
| + "items": { |
| + "$ref": "#/components/schemas/Notification" |
| + } |
| + }, |
| + "next_cursor": { |
| + "type": "string" |
| + }, |
| + "revision": { |
| + "type": "integer", |
| + "format": "int64" |
| + } |
| + }, |
| + "required": [ |
| + "items", |
| + "next_cursor", |
| + "revision" |
| + ] |
| + }, |
| + "SubscribeNotificationsInput": { |
| + "type": "object", |
| + "additionalProperties": false, |
| + "properties": { |
| + "device_id": { |
| + "type": "string", |
| + "minLength": 1, |
| + "maxLength": 128 |
| + } |
| + }, |
| + "required": [ |
| + "device_id" |
| + ] |
| + }, |
| + "AcknowledgeNotificationInput": { |
| + "type": "object", |
| + "additionalProperties": false, |
| + "properties": { |
| + "notification_id": { |
| + "type": "string", |
| + "minLength": 1, |
| + "maxLength": 128 |
| + } |
| + }, |
| + "required": [ |
| + "notification_id" |
| + ] |
| } |
| }, |
| "responses": { |
| @@ -11218,6 +11746,23 @@ |
| } |
| } |
| } |
| + }, |
| + "subscription_expired": { |
| + "description": "subscription_expired", |
| + "headers": { |
| + "Cache-Control": { |
| + "schema": { |
| + "const": "no-store" |
| + } |
| + } |
| + }, |
| + "content": { |
| + "application/json": { |
| + "schema": { |
| + "$ref": "#/components/schemas/Error" |
| + } |
| + } |
| + } |
| } |
| } |
| }, |
diff --git a/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md b/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md| index dbab418f..e7ce0cdb 100644 |
| --- a/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md |
| +++ b/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md |
| @@ -4629,3 +4629,75 @@ The HKDF change intentionally invalidates old cursors. It also invalidates pre-f |
| Copy approval remains a release gate. Review minors 9 and 10 (project-rules web scope and broader OpenAPI response/field coverage) were not requested in this fix round and remain unchanged. Notifications stay with Task 19; inherited live-provider/certification gates remain outside this offline task. |
| No agents, copy-review server, provider runs, sign-ins, live enrolment, full suite, make ci, merge, deployment or push. No server or watcher was started. Scratch stayed under on-disk TMPDIR and is removed before handoff. Go caches remain at their defaults. No `.claude/HANDOFF.md` was created. |
| + |
| + |
| +## Task 19 |
| + |
| +Implemented the durable recipient outbox and device-bound subscriptions with migration 0031, same-transaction source hooks, independent contiguous delivery cursors, expiry/revocation, private live invalidation and all four API routes. No external push adapter. Subject: `feat: add a person-scoped notification outbox`; author: `codex <codex~paul@keymail.dev>`. Full report: `.superpowers/sdd/2026-11-04-equipo-plan-3-coordinator/task-19-report.md`. |
| + |
| +### Verification |
| + |
| +All final checks exited 0. Tests were targeted; no full suite or make ci was run. |
| + |
| +- `CGO_ENABLED=0 go test ./internal/plan3test -run '^TestNotification' -count=1`: PASS, 10.842s in the final concurrent validation run. Covers all six required names plus live reauthorization, retention/cursor failure, native questions, explicit renewal, audit/revocation rollback, pending-question retention, migration, private invalidation, question deadlines, decision owners, lost cursor writes, unknown devices and card resource kinds. |
| +- `CGO_ENABLED=0 go test ./internal/equipo/personapi ./internal/plan3test -run '^TestPersonAPI' -count=1`: PASS, personapi 0.009s and plan3test 18.147s. Includes the Task 10/20 authentication, cursor, replay, contract and device regressions. The final notification/contract rerun after the card kind change passed in 11.154s with `-run '^(TestNotification|TestPersonAPIContractCoverage)'`. |
| +- `CGO_ENABLED=0 go test ./internal/plan3test -run 'Migration' -count=1`: PASS, 8.096s. Existing coordinator, conversation and device upgrade fixtures now defer dependent 0031 until their missing prerequisite migration is applied. |
| +- `CGO_ENABLED=0 go test ./internal/plan3test -run '^(TestConversation(LivePrivacy|LiveAtomic|QuestionRaceNative|ScriptlessSettings)|TestCoordinatorTool(CommitCrash|Clarification|ClarificationInvalidation)|TestPlan(EditClaimRaceAtomic|ProjectCorrection|AuthorityReplay)|TestPreferencesAtomicInvalidation)$' -count=1`: PASS, 7.070s. |
| +- `make migration-check` with CGO disabled: PASS, targeted TestMigrationModels, 0.219s. Final `CGO_ENABLED=0 go test ./internal/equipo -run '^(TestMigrationModels|TestConversationMigrationSnapshot)$' -count=1`: PASS, 3.120s, including table/index and trigger parity. |
| +- `CGO_ENABLED=0 make budget`: PASS, 35 directories within budget. |
| +- `CGO_ENABLED=0 go vet ./internal/equipo ./internal/equipo/notifications ./internal/equipo/personapi ./internal/plan3test`: PASS, no findings. |
| +- `CGO_ENABLED=0 go run honnef.co/go/tools/cmd/staticcheck@v0.7.0 ./internal/equipo ./internal/equipo/notifications ./internal/equipo/personapi ./internal/plan3test`: PASS, no findings. |
| +- `gofmt -l internal/equipo/*.go internal/equipo/notifications/*.go internal/equipo/personapi/*.go internal/plan3test/*.go`: no output. `git diff --check`: PASS. |
| + |
| +### Red evidence and development corrections |
| + |
| +The six named tests were written before implementation. The required command was: |
| + |
| +`CGO_ENABLED=0 go test ./internal/plan3test -run '^TestNotification' -count=1` |
| + |
| +It exited 1 at compilation with undefined `equipo.NotificationSubscription`, `equipo.Notification`, `Store.Notifications`, `Store.AcknowledgeNotification` and `Store.AllowNotificationSubscription`. The same exact command passes after implementation. |
| + |
| +Additional test-first failures, all exit 1: |
| + |
| +- `-run '^TestNotification(LiveRechecks|RetentionAndCursor|NativeAndReady)$'`: undefined `notifications.GuardLive`. The added writer guard rechecks authorization before each stream write, beyond Rastrillo's reconnect-only check. |
| +- `-run '^TestNotification(MigrationUpgrade|PrivateInvalidation|ExplicitRenewal)$'`: `upgrade lost existing actionable task 0`. Added migration backfill for proposed tasks and current pending questions, with ready jobs and explicit human decisions included. |
| +- `-run '^TestNotificationDecisionOwners$'`: `explicit decision owner was not notified`. Added the existing-transaction hook for jobs waiting on approval. |
| +- `-run '^TestNotificationUnknownDevice$'`: HTTP 410 instead of 404. Device lookup now scopes by owner first and preserves the absent/private-resource response. |
| +- `-run '^TestNotificationCardResource$'`: `card event has no fetchable resource kind`. Suggestion-card events now have kind `card`, so clients can fetch `/api/v1/cards/{resource_id}` instead of treating a card ID as a task ID. |
| + |
| +These abbreviated commands use the same `CGO_ENABLED=0 go test ./internal/plan3test ... -count=1` prefix/suffix above. |
| + |
| +Development corrections: the first rollback fixture reused the same question text, which the existing coordinator deliberately deduplicates; the failure probe now uses different text. Coordinator fixtures replace their Store, so the notification fixture recomposes the router to supply the instance cursor key. An invalid historical task fixture returned 404 before another route could validate a cursor; the route-scope test now uses the people list. Initial fixture compilation also exposed an unused import and a mistyped existing live helper name; both were corrected. |
| + |
| +The migration regression run initially failed because older fixtures installed 0031 while excluding its coordinator, conversation or device prerequisite. They now defer 0031 and assert the expanded applied list. The existing snapshot test also exposed Rastrillo's trigger-before-table dump ordering; the test now compares a directly replayed migration database with the executable saved snapshot, including every trigger definition. Early size checks found 10,829 root source lines and later 10,076 integration test lines; observer extraction restored the root ceiling and the measured integration exception was raised to 10,500. |
| + |
| +### Independent guard mutations |
| + |
| +| Guard broken | Exact command | Observed failure | Restored | |
| +| --- | --- | --- | --- | |
| +| commit-audit-rollback | `CGO_ENABLED=0 go test ./internal/plan3test -run ^TestNotificationOutboxAtomic$ -count=1` | Exit 1: notifications_test.go:79: audit failure ignored | Byte-for-byte, yes | |
| +| recipient-scope | `CGO_ENABLED=0 go test ./internal/plan3test -run ^TestNotificationRecipientIsolation$ -count=1` | Exit 1: notifications_test.go:112: recipient scope leaked | Byte-for-byte, yes | |
| +| event-dedup | `CGO_ENABLED=0 go test ./internal/plan3test -run ^TestNotificationOutboxAtomic$ -count=1` | Exit 1: notifications_test.go:58: duplicate effect changed notification ID | Byte-for-byte, yes | |
| +| independent-delivery | `CGO_ENABLED=0 go test ./internal/plan3test -run ^TestNotificationReconnect$ -count=1` | Exit 1: notifications_test.go:173: another device lost unread state | Byte-for-byte, yes | |
| +| contiguous-cursor | `CGO_ENABLED=0 go test ./internal/plan3test -run ^TestNotificationReconnect$ -count=1` | Exit 1: notifications_test.go:161: out-of-order ACK skipped earlier event | Byte-for-byte, yes | |
| +| subscription-expiry | `CGO_ENABLED=0 go test ./internal/plan3test -run ^TestNotificationExplicitRenewal$ -count=1` | Exit 1: notifications_lifecycle_test.go:43: subscription deadline ignored with current device <nil> | Byte-for-byte, yes | |
| +| device-revocation | `CGO_ENABLED=0 go test ./internal/plan3test -run ^TestNotificationSubscriptionExpiry$ -count=1` | Exit 1: notifications_test.go:251: HTTP 200, want 401 | Byte-for-byte, yes | |
| +| delivered-before-ack | `CGO_ENABLED=0 go test ./internal/plan3test -run ^TestNotificationReconnect$ -count=1` | Exit 1: notifications_test.go:156: HTTP 200, want 404 | Byte-for-byte, yes | |
| +| stale-question-expiry | `CGO_ENABLED=0 go test ./internal/plan3test -run ^TestNotificationQuestionDeadline$ -count=1` | Exit 1: notifications_lifecycle_test.go:190: expired question remains current | Byte-for-byte, yes | |
| +| pending-question-retention | `CGO_ENABLED=0 go test ./internal/plan3test -run ^TestNotificationPendingQuestionRetention$ -count=1` | Exit 1: notifications_lifecycle_test.go:93: cleanup removed current question | Byte-for-byte, yes | |
| +| live-write-recheck | `CGO_ENABLED=0 go test ./internal/plan3test -run ^TestNotificationLiveRechecks$ -count=1` | Exit 1: notifications_test.go:312: stale stream wrote after revocation | Byte-for-byte, yes | |
| +| current-decision-owner | `CGO_ENABLED=0 go test ./internal/plan3test -run ^TestNotificationDecisionOwners$ -count=1` | Exit 1: notifications_lifecycle_test.go:218: old decision owner retained current event | Byte-for-byte, yes | |
| +| ack-write-result | `CGO_ENABLED=0 go test ./internal/plan3test -run ^TestNotificationAckLostWrite$ -count=1` | Exit 1: notifications_lifecycle_test.go:230: HTTP 200, want 409 | Byte-for-byte, yes | |
| + |
| +### Copy and release concerns |
| + |
| +- `notifications.question`: A question needs your answer. |
| +- `notifications.task_ready`: A task is ready for you to review. |
| +- `notifications.interrupted`: Work stopped and needs your attention. |
| +- `notifications.superseded`: This item has changed. Fetch its current state. |
| +- `notifications.subscribe`: Receive notifications on this device |
| +- `notifications.unsubscribe`: Stop notifications on this device |
| +- `notifications.cursor_expired`: This notification cursor expired. Fetch notifications without a cursor and check Needs you for open questions. |
| +- `notifications.subscription_expired`: This notification subscription expired. Subscribe again with a current device credential. |
| + |
| +All eight entries have individual `COPY REVIEW REQUIRED` markers. The API guide remains a draft and OpenAPI prose remains pending. The pinned SchemaSQL dumper emits triggers before tables; the committed snapshot uses executable order and the snapshot test now compares replayed schema plus trigger definitions. Root source: 10769/10800; integration tests: 10425/10500 after the measured exception update. No provider runs, sign-ins, enrolment, credential homes, agents, copy-review server, full suite, make ci, push, merge or deployment. Go caches remain unchanged; task scratch is removed before final handoff. |
diff --git a/internal/equipo/app.go b/internal/equipo/app.go| index 226a7894..dc6e97dc 100644 |
| --- a/internal/equipo/app.go |
| +++ b/internal/equipo/app.go |
| @@ -1,6 +1,7 @@ |
| package equipo |
| import ( |
| + "amadan.net/oficina/equipo/internal/equipo/notifications" |
| "context" |
| "errors" |
| "log/slog" |
| @@ -140,7 +141,7 @@ func RouterWithStore(d *db.DB, cfg Config, mailer mail.Sender, logger *slog.Logg |
| } |
| a := &application{installAssets: release.NewInstallAssets(cfg.RunnerReleaseDir, rastrillo.BuildVersion, release.BuildManifest()), executionEnabled: cfg.ExecutionEnabled, Router: chi.NewRouter(), auth: authentication, store: store, logger: logger, nonces: pow.SQLNonces(d.Writer()), origin: cfg.Origin} |
| if cfg.AlwaysOn { |
| - a.live, err = live.New(live.Config{Path: "/live", Topics: map[string]live.Allow{"jobs": a.allowJob, "personal": a.preferenceHandler().Allow, "conversation": a.allowConversation}, Lifetime: 30 * time.Second}) |
| + a.live, err = live.New(live.Config{Path: "/live", Topics: map[string]live.Allow{"jobs": a.allowJob, "personal": a.preferenceHandler().Allow, "conversation": a.allowConversation, "notifications": a.allowNotification}, Lifetime: 30 * time.Second}) |
| if err != nil { |
| return nil, err |
| } |
| @@ -184,7 +185,7 @@ func RouterWithStore(d *db.DB, cfg Config, mailer mail.Sender, logger *slog.Logg |
| r.Get("/auth/devices/{id}", a.deviceBrowser().Page) |
| r.Post("/auth/devices/{id}/approve", a.deviceBrowser().ApproveForm) |
| if a.live != nil { |
| - r.Handle("/live", a.live.Handler()) |
| + r.Handle("/live", notifications.GuardLive(a.live.Handler(), a.allowNotification)) |
| } |
| r.Get("/tasks/new", a.taskForm) |
| r.Get("/tasks/{id}", a.taskDetail) |
diff --git a/internal/equipo/copy.go b/internal/equipo/copy.go| index be621fbc..76515d4a 100644 |
| --- a/internal/equipo/copy.go |
| +++ b/internal/equipo/copy.go |
| @@ -48,6 +48,22 @@ const BootLog = "Equipo could not start." |
| // COPY APPROVED BY DELEGATION (Luna pass, 2026-11-01, house rules). |
| var pageCopy = map[string]string{ |
| + // COPY REVIEW REQUIRED: notifications.question |
| + "notifications.question": "A question needs your answer.", |
| + // COPY REVIEW REQUIRED: notifications.task_ready |
| + "notifications.task_ready": "A task is ready for you to review.", |
| + // COPY REVIEW REQUIRED: notifications.interrupted |
| + "notifications.interrupted": "Work stopped and needs your attention.", |
| + // COPY REVIEW REQUIRED: notifications.superseded |
| + "notifications.superseded": "This item has changed. Fetch its current state.", |
| + // COPY REVIEW REQUIRED: notifications.subscribe |
| + "notifications.subscribe": "Receive notifications on this device", |
| + // COPY REVIEW REQUIRED: notifications.unsubscribe |
| + "notifications.unsubscribe": "Stop notifications on this device", |
| + // COPY REVIEW REQUIRED: notifications.cursor_expired |
| + "notifications.cursor_expired": "This notification cursor expired. Fetch notifications without a cursor and check Needs you for open questions.", |
| + // COPY REVIEW REQUIRED: notifications.subscription_expired |
| + "notifications.subscription_expired": "This notification subscription expired. Subscribe again with a current device credential.", |
| // COPY REVIEW REQUIRED |
| "device.list": "Your devices", |
| // COPY REVIEW REQUIRED |
diff --git a/internal/equipo/live.go b/internal/equipo/live.go| index cbd8adbf..2a3fcf8b 100644 |
| --- a/internal/equipo/live.go |
| +++ b/internal/equipo/live.go |
| @@ -1,10 +1,10 @@ |
| package equipo |
| import ( |
| + "amadan.net/oficina/equipo/internal/equipo/notifications" |
| "context" |
| "database/sql" |
| "net/http" |
| - "sort" |
| "time" |
| "amadan.net/oficina/equipo/internal/equipo/conversation" |
| @@ -64,75 +64,7 @@ func CloseLive(h http.Handler) { |
| type liveState struct{ deadlines map[string][]time.Time } |
| func (s *Store) observeWrite(ctx context.Context, tx *sql.Tx) (team.CommitObserver, error) { |
| - if s.notifier == nil { |
| - return nil, nil |
| - } |
| - if err := conversation.InstallConversationChanges(ctx, tx); err != nil { |
| - return nil, err |
| - } |
| - if err := conversation.InstallPersonalChanges(ctx, tx); err != nil { |
| - return nil, err |
| - } |
| - if err := conversation.InstallJobChanges(ctx, tx); err != nil { |
| - return nil, err |
| - } |
| - return func(ctx context.Context, tx *sql.Tx) (func(), error) { |
| - rows, err := tx.QueryContext(ctx, `SELECT c.team,c.job FROM equipo_live_changes c JOIN teams t ON t.id=c.team WHERE c.job=0 OR EXISTS(SELECT 1 FROM jobs j WHERE j.id=c.job AND j.account=c.team)`) |
| - if err != nil { |
| - return nil, err |
| - } |
| - touched := map[string][]JobID{} |
| - topics := map[string]bool{} |
| - for rows.Next() { |
| - var teamID string |
| - var job JobID |
| - if err = rows.Scan(&teamID, &job); err != nil { |
| - break |
| - } |
| - touched[teamID] = append(touched[teamID], job) |
| - topics[jobTopic(teamID, job)] = true |
| - topics[jobTopic(teamID, 0)] = true |
| - } |
| - if err == nil { |
| - err = rows.Err() |
| - } |
| - rows.Close() |
| - if err != nil { |
| - return nil, err |
| - } |
| - st := liveState{deadlines: map[string][]time.Time{}} |
| - if err := conversation.ConversationDeadlines(ctx, tx, st.deadlines); err != nil { |
| - return nil, err |
| - } |
| - for teamID, ids := range touched { |
| - if err := conversation.JobDeadlines(ctx, tx, st.deadlines, teamID, ids); err != nil { |
| - return nil, err |
| - } |
| - } |
| - private, err := conversation.PersonalChanges(ctx, tx) |
| - if err != nil { |
| - return nil, err |
| - } |
| - conversations, err := conversation.ConversationChanges(ctx, tx) |
| - if err != nil { |
| - return nil, err |
| - } |
| - private = append(private, conversations...) |
| - for _, topic := range private { |
| - topics[topic] = true |
| - } |
| - keys := make([]string, 0, len(topics)) |
| - for topic := range topics { |
| - keys = append(keys, topic) |
| - } |
| - sort.Strings(keys) |
| - return func() { |
| - if len(keys) > 0 { |
| - s.notifier.Notify(keys...) |
| - } |
| - s.scheduleState(st) |
| - }, nil |
| - }, nil |
| + return notifications.ObserveWrite(ctx, tx, s.notifier) |
| } |
| func (s *Store) scheduleState(st liveState) { |
| for topic, dates := range st.deadlines { |
diff --git a/internal/equipo/migrations/0031_notifications.sql b/internal/equipo/migrations/0031_notifications.sql| new file mode 100644 |
| index 00000000..10e56ba5 |
| --- /dev/null |
| +++ b/internal/equipo/migrations/0031_notifications.sql |
| @@ -0,0 +1,76 @@ |
| +CREATE TABLE notification_outbox (sequence integer PRIMARY KEY AUTOINCREMENT, id text NOT NULL, team_id text NOT NULL, recipient text NOT NULL, event text NOT NULL, resource_id text NOT NULL, resource_revision integer NOT NULL, kind text, resource_type text, deep_link text, state text, created_at datetime, acknowledged_at datetime); |
| +CREATE UNIQUE INDEX notification_id ON notification_outbox(id); |
| +CREATE UNIQUE INDEX notification_event ON notification_outbox(team_id,recipient,event,resource_id,resource_revision); |
| +CREATE TABLE notification_subscriptions (id text PRIMARY KEY, team_id text, person text, device_id text, revision integer, ack_sequence integer, active numeric, created_at datetime, expires_at datetime); |
| +CREATE INDEX notification_device ON notification_subscriptions(device_id); |
| +CREATE TABLE notification_deliveries (subscription_id text, sequence integer, delivered_at datetime, acknowledged_at datetime, PRIMARY KEY(subscription_id,sequence)); |
| +CREATE TABLE notification_history (team_id text, person text, pruned_through integer, PRIMARY KEY(team_id,person)); |
| +CREATE TRIGGER notification_clarification_insert AFTER INSERT ON coordinator_questions BEGIN |
| +UPDATE notification_outbox SET state='superseded' WHERE resource_type='clarification' AND resource_id=NEW.id AND state<>'superseded' AND (resource_revision<>NEW.revision OR NEW.state<>'pending'); |
| +INSERT INTO notification_outbox(id,team_id,recipient,event,resource_id,resource_revision,kind,resource_type,deep_link,state,created_at) SELECT lower(hex(randomblob(16))),b.team_id,NEW.person,'question',NEW.id,NEW.revision,'question','clarification','/conversation','unread',strftime('%Y-%m-%d %H:%M:%f','now') FROM coordinator_bindings b WHERE b.id=NEW.binding_id AND NEW.state='pending' AND EXISTS(SELECT 1 FROM members m WHERE m.address=NEW.person AND m.active=1) ON CONFLICT(team_id,recipient,event,resource_id,resource_revision) DO NOTHING; |
| +END; |
| +CREATE TRIGGER notification_question_insert AFTER INSERT ON questions BEGIN |
| +UPDATE notification_outbox SET state='superseded' WHERE resource_type='question' AND resource_id=NEW.id AND state<>'superseded' AND (resource_revision<>NEW.revision OR NEW.state<>'pending'); |
| +INSERT INTO notification_outbox(id,team_id,recipient,event,resource_id,resource_revision,kind,resource_type,deep_link,state,created_at) SELECT lower(hex(randomblob(16))),t.team_id,t.requester,'question',NEW.id,NEW.revision,'question','question','/tasks/'||t.id||'/questions/'||NEW.id,'unread',strftime('%Y-%m-%d %H:%M:%f','now') FROM tasks t WHERE t.id=NEW.task_id AND NEW.state='pending' AND EXISTS(SELECT 1 FROM members m WHERE m.address=t.requester AND m.active=1) ON CONFLICT(team_id,recipient,event,resource_id,resource_revision) DO NOTHING; |
| +END; |
| +CREATE TRIGGER notification_task_insert AFTER INSERT ON tasks BEGIN |
| +UPDATE notification_outbox SET state='superseded' WHERE resource_type='task' AND resource_id=NEW.id AND state<>'superseded' AND (resource_revision<>NEW.revision OR NEW.state IN ('cancelled','cancel_requested','merged','failed')); |
| +INSERT INTO notification_outbox(id,team_id,recipient,event,resource_id,resource_revision,kind,resource_type,deep_link,state,created_at) SELECT lower(hex(randomblob(16))),NEW.team_id,NEW.requester,'task_ready.plan',NEW.id,NEW.revision,'task_ready','task','/tasks/'||NEW.id,'unread',strftime('%Y-%m-%d %H:%M:%f','now') WHERE NEW.state='proposed' AND EXISTS(SELECT 1 FROM members m WHERE m.address=NEW.requester AND m.active=1) ON CONFLICT(team_id,recipient,event,resource_id,resource_revision) DO NOTHING; |
| +END; |
| +CREATE TRIGGER notification_card_insert AFTER INSERT ON conversation_cards BEGIN |
| +UPDATE notification_outbox SET state='superseded' WHERE resource_type='card' AND resource_id=NEW.id AND state<>'superseded' AND resource_revision<>NEW.revision; |
| +INSERT INTO notification_outbox(id,team_id,recipient,event,resource_id,resource_revision,kind,resource_type,deep_link,state,created_at) SELECT lower(hex(randomblob(16))),c.team_id,c.person,'task_ready.plan',NEW.resource_id,NEW.revision,'task_ready','task','/tasks/'||NEW.resource_id,'unread',strftime('%Y-%m-%d %H:%M:%f','now') FROM conversations c WHERE c.id=NEW.stream_id AND NEW.kind='task' AND EXISTS(SELECT 1 FROM members m WHERE m.address=c.person AND m.active=1) ON CONFLICT(team_id,recipient,event,resource_id,resource_revision) DO NOTHING; |
| +INSERT INTO notification_outbox(id,team_id,recipient,event,resource_id,resource_revision,kind,resource_type,deep_link,state,created_at) SELECT lower(hex(randomblob(16))),c.team_id,c.person,'card',NEW.id,NEW.revision,'card','card','/conversation','unread',strftime('%Y-%m-%d %H:%M:%f','now') FROM conversations c WHERE c.id=NEW.stream_id AND NEW.kind LIKE 'suggest_%' AND EXISTS(SELECT 1 FROM members m WHERE m.address=c.person AND m.active=1) ON CONFLICT(team_id,recipient,event,resource_id,resource_revision) DO NOTHING; |
| +END; |
| +CREATE TRIGGER notification_turn_insert AFTER INSERT ON coordinator_turns BEGIN |
| +UPDATE notification_outbox SET state='superseded' WHERE resource_type='coordinator' AND resource_id=NEW.id AND state<>'superseded' AND (resource_revision<>NEW.revision OR NEW.state NOT IN ('uncertain','fenced','context_limit','context_unavailable')); |
| +INSERT INTO notification_outbox(id,team_id,recipient,event,resource_id,resource_revision,kind,resource_type,deep_link,state,created_at) SELECT lower(hex(randomblob(16))),NEW.team_id,NEW.person,'interrupted',NEW.id,NEW.revision,'interrupted','coordinator','/conversation','unread',strftime('%Y-%m-%d %H:%M:%f','now') WHERE NEW.state IN ('uncertain','fenced','context_limit','context_unavailable') AND EXISTS(SELECT 1 FROM members m WHERE m.address=NEW.person AND m.active=1) ON CONFLICT(team_id,recipient,event,resource_id,resource_revision) DO NOTHING; |
| +END; |
| +CREATE TRIGGER notification_clarification_update AFTER UPDATE ON coordinator_questions BEGIN |
| +UPDATE notification_outbox SET state='superseded' WHERE resource_type='clarification' AND resource_id=NEW.id AND state<>'superseded' AND (resource_revision<>NEW.revision OR NEW.state<>'pending'); |
| +INSERT INTO notification_outbox(id,team_id,recipient,event,resource_id,resource_revision,kind,resource_type,deep_link,state,created_at) SELECT lower(hex(randomblob(16))),b.team_id,NEW.person,'question',NEW.id,NEW.revision,'question','clarification','/conversation','unread',strftime('%Y-%m-%d %H:%M:%f','now') FROM coordinator_bindings b WHERE b.id=NEW.binding_id AND NEW.state='pending' AND EXISTS(SELECT 1 FROM members m WHERE m.address=NEW.person AND m.active=1) ON CONFLICT(team_id,recipient,event,resource_id,resource_revision) DO NOTHING; |
| +END; |
| +CREATE TRIGGER notification_question_update AFTER UPDATE ON questions BEGIN |
| +UPDATE notification_outbox SET state='superseded' WHERE resource_type='question' AND resource_id=NEW.id AND state<>'superseded' AND (resource_revision<>NEW.revision OR NEW.state<>'pending'); |
| +INSERT INTO notification_outbox(id,team_id,recipient,event,resource_id,resource_revision,kind,resource_type,deep_link,state,created_at) SELECT lower(hex(randomblob(16))),t.team_id,t.requester,'question',NEW.id,NEW.revision,'question','question','/tasks/'||t.id||'/questions/'||NEW.id,'unread',strftime('%Y-%m-%d %H:%M:%f','now') FROM tasks t WHERE t.id=NEW.task_id AND NEW.state='pending' AND EXISTS(SELECT 1 FROM members m WHERE m.address=t.requester AND m.active=1) ON CONFLICT(team_id,recipient,event,resource_id,resource_revision) DO NOTHING; |
| +END; |
| +CREATE TRIGGER notification_task_update AFTER UPDATE ON tasks BEGIN |
| +UPDATE notification_outbox SET state='superseded' WHERE resource_type='task' AND resource_id=NEW.id AND state<>'superseded' AND (resource_revision<>NEW.revision OR NEW.state IN ('cancelled','cancel_requested','merged','failed')); |
| +INSERT INTO notification_outbox(id,team_id,recipient,event,resource_id,resource_revision,kind,resource_type,deep_link,state,created_at) SELECT lower(hex(randomblob(16))),NEW.team_id,NEW.requester,'task_ready.plan',NEW.id,NEW.revision,'task_ready','task','/tasks/'||NEW.id,'unread',strftime('%Y-%m-%d %H:%M:%f','now') WHERE NEW.state='proposed' AND EXISTS(SELECT 1 FROM members m WHERE m.address=NEW.requester AND m.active=1) ON CONFLICT(team_id,recipient,event,resource_id,resource_revision) DO NOTHING; |
| +END; |
| +CREATE TRIGGER notification_card_update AFTER UPDATE ON conversation_cards BEGIN |
| +UPDATE notification_outbox SET state='superseded' WHERE resource_type='card' AND resource_id=NEW.id AND state<>'superseded' AND resource_revision<>NEW.revision; |
| +INSERT INTO notification_outbox(id,team_id,recipient,event,resource_id,resource_revision,kind,resource_type,deep_link,state,created_at) SELECT lower(hex(randomblob(16))),c.team_id,c.person,'task_ready.plan',NEW.resource_id,NEW.revision,'task_ready','task','/tasks/'||NEW.resource_id,'unread',strftime('%Y-%m-%d %H:%M:%f','now') FROM conversations c WHERE c.id=NEW.stream_id AND NEW.kind='task' AND EXISTS(SELECT 1 FROM members m WHERE m.address=c.person AND m.active=1) ON CONFLICT(team_id,recipient,event,resource_id,resource_revision) DO NOTHING; |
| +INSERT INTO notification_outbox(id,team_id,recipient,event,resource_id,resource_revision,kind,resource_type,deep_link,state,created_at) SELECT lower(hex(randomblob(16))),c.team_id,c.person,'card',NEW.id,NEW.revision,'card','card','/conversation','unread',strftime('%Y-%m-%d %H:%M:%f','now') FROM conversations c WHERE c.id=NEW.stream_id AND NEW.kind LIKE 'suggest_%' AND EXISTS(SELECT 1 FROM members m WHERE m.address=c.person AND m.active=1) ON CONFLICT(team_id,recipient,event,resource_id,resource_revision) DO NOTHING; |
| +END; |
| +CREATE TRIGGER notification_turn_update AFTER UPDATE ON coordinator_turns BEGIN |
| +UPDATE notification_outbox SET state='superseded' WHERE resource_type='coordinator' AND resource_id=NEW.id AND state<>'superseded' AND (resource_revision<>NEW.revision OR NEW.state NOT IN ('uncertain','fenced','context_limit','context_unavailable')); |
| +INSERT INTO notification_outbox(id,team_id,recipient,event,resource_id,resource_revision,kind,resource_type,deep_link,state,created_at) SELECT lower(hex(randomblob(16))),NEW.team_id,NEW.person,'interrupted',NEW.id,NEW.revision,'interrupted','coordinator','/conversation','unread',strftime('%Y-%m-%d %H:%M:%f','now') WHERE NEW.state IN ('uncertain','fenced','context_limit','context_unavailable') AND EXISTS(SELECT 1 FROM members m WHERE m.address=NEW.person AND m.active=1) ON CONFLICT(team_id,recipient,event,resource_id,resource_revision) DO NOTHING; |
| +END; |
| +CREATE TRIGGER notification_job_ready AFTER UPDATE ON jobs WHEN NEW.state='succeeded' AND OLD.state IS NOT NEW.state BEGIN |
| +INSERT INTO notification_outbox(id,team_id,recipient,event,resource_id,resource_revision,kind,resource_type,deep_link,state,created_at) SELECT lower(hex(randomblob(16))),t.team_id,r.person,'task_ready.complete',t.id,t.revision,'task_ready','task','/tasks/'||t.id,'unread',strftime('%Y-%m-%d %H:%M:%f','now') FROM tasks t JOIN (SELECT id AS task_id,requester AS person FROM tasks UNION SELECT t.id,o.address FROM tasks t JOIN decision_owners o ON o.project_id=t.project_id) r ON r.task_id=t.id WHERE t.job_id=NEW.id AND t.team_id=NEW.account AND EXISTS(SELECT 1 FROM members m WHERE m.address=r.person AND m.active=1) ON CONFLICT(team_id,recipient,event,resource_id,resource_revision) DO NOTHING; |
| +END; |
| +CREATE TRIGGER notification_job_decision AFTER UPDATE ON jobs WHEN NEW.wait='approval' AND (OLD.wait IS NOT NEW.wait OR OLD.revision IS NOT NEW.revision) BEGIN |
| +INSERT INTO notification_outbox(id,team_id,recipient,event,resource_id,resource_revision,kind,resource_type,deep_link,state,created_at) SELECT lower(hex(randomblob(16))),t.team_id,r.person,'task_ready.decision.'||NEW.revision,t.id,t.revision,'task_ready','task','/tasks/'||t.id,'unread',strftime('%Y-%m-%d %H:%M:%f','now') FROM tasks t JOIN (SELECT id AS task_id,requester AS person FROM tasks UNION SELECT t.id,o.address FROM tasks t JOIN decision_owners o ON o.project_id=t.project_id) r ON r.task_id=t.id WHERE t.job_id=NEW.id AND t.team_id=NEW.account AND EXISTS(SELECT 1 FROM members m WHERE m.address=r.person AND m.active=1) ON CONFLICT(team_id,recipient,event,resource_id,resource_revision) DO NOTHING; |
| +END; |
| +CREATE TRIGGER notification_job_interrupted AFTER UPDATE ON jobs WHEN NEW.wait IN ('uncertain_external_outcome','runner_unavailable','connection_unavailable') AND OLD.wait IS NOT NEW.wait BEGIN |
| +INSERT INTO notification_outbox(id,team_id,recipient,event,resource_id,resource_revision,kind,resource_type,deep_link,state,created_at) SELECT lower(hex(randomblob(16))),t.team_id,t.requester,'interrupted.job.'||NEW.revision,t.id,t.revision,'interrupted','task','/tasks/'||t.id,'unread',strftime('%Y-%m-%d %H:%M:%f','now') FROM tasks t WHERE t.job_id=NEW.id AND t.team_id=NEW.account AND EXISTS(SELECT 1 FROM members m WHERE m.address=t.requester AND m.active=1) ON CONFLICT(team_id,recipient,event,resource_id,resource_revision) DO NOTHING; |
| +END; |
| +CREATE TRIGGER notification_device_revoke AFTER UPDATE ON person_devices WHEN NEW.revoked_at IS NOT NULL AND OLD.revoked_at IS NULL BEGIN |
| +UPDATE notification_subscriptions SET active=0,revision=revision+1 WHERE device_id=NEW.id AND active=1; |
| +END; |
| +CREATE TRIGGER notification_member_revoke AFTER UPDATE ON members WHEN NEW.active=0 OR NEW.session_epoch<>OLD.session_epoch BEGIN |
| +UPDATE notification_subscriptions SET active=0,revision=revision+1 WHERE person=NEW.address AND active=1; |
| +END; |
| +CREATE TRIGGER notification_binding_generation AFTER UPDATE ON coordinator_bindings WHEN NEW.generation<>OLD.generation BEGIN |
| +UPDATE notification_outbox SET state='superseded' WHERE resource_type IN ('clarification','coordinator') AND resource_id IN (SELECT id FROM coordinator_questions WHERE binding_id=NEW.id UNION SELECT id FROM coordinator_turns WHERE binding_id=NEW.id); |
| +END; |
| + |
| +CREATE INDEX notification_feed ON notification_outbox(team_id,recipient,sequence); |
| + |
| +-- Existing actionable work remains discoverable after upgrade. |
| +INSERT INTO notification_outbox(id,team_id,recipient,event,resource_id,resource_revision,kind,resource_type,deep_link,state,created_at) SELECT lower(hex(randomblob(16))),t.team_id,t.requester,'task_ready.plan',t.id,t.revision,'task_ready','task','/tasks/'||t.id,'unread',strftime('%Y-%m-%d %H:%M:%f','now') FROM tasks t WHERE t.state='proposed' AND EXISTS(SELECT 1 FROM members m WHERE m.address=t.requester AND m.active=1) ON CONFLICT(team_id,recipient,event,resource_id,resource_revision) DO NOTHING; |
| +INSERT INTO notification_outbox(id,team_id,recipient,event,resource_id,resource_revision,kind,resource_type,deep_link,state,created_at) SELECT lower(hex(randomblob(16))),b.team_id,q.person,'question',q.id,q.revision,'question','clarification','/conversation','unread',strftime('%Y-%m-%d %H:%M:%f','now') FROM coordinator_questions q JOIN coordinator_bindings b ON b.id=q.binding_id WHERE q.state='pending' AND q.generation=b.generation AND EXISTS(SELECT 1 FROM members m WHERE m.address=q.person AND m.active=1) ON CONFLICT(team_id,recipient,event,resource_id,resource_revision) DO NOTHING; |
| +INSERT INTO notification_outbox(id,team_id,recipient,event,resource_id,resource_revision,kind,resource_type,deep_link,state,created_at) SELECT lower(hex(randomblob(16))),t.team_id,t.requester,'question',q.id,q.revision,'question','question','/tasks/'||t.id||'/questions/'||q.id,'unread',strftime('%Y-%m-%d %H:%M:%f','now') FROM questions q JOIN tasks t ON t.id=q.task_id WHERE q.state='pending' AND EXISTS(SELECT 1 FROM members m WHERE m.address=t.requester AND m.active=1) ON CONFLICT(team_id,recipient,event,resource_id,resource_revision) DO NOTHING; |
| +INSERT INTO notification_outbox(id,team_id,recipient,event,resource_id,resource_revision,kind,resource_type,deep_link,state,created_at) SELECT lower(hex(randomblob(16))),t.team_id,r.person,'task_ready.complete',t.id,t.revision,'task_ready','task','/tasks/'||t.id,'unread',strftime('%Y-%m-%d %H:%M:%f','now') FROM jobs j JOIN tasks t ON t.job_id=j.id AND t.team_id=j.account JOIN (SELECT id AS task_id,requester AS person FROM tasks UNION SELECT t.id,o.address FROM tasks t JOIN decision_owners o ON o.project_id=t.project_id) r ON r.task_id=t.id WHERE j.state='succeeded' AND t.state NOT IN ('merged','cancelled','cancel_requested','failed') AND EXISTS(SELECT 1 FROM members m WHERE m.address=r.person AND m.active=1) ON CONFLICT(team_id,recipient,event,resource_id,resource_revision) DO NOTHING; |
| +INSERT INTO notification_outbox(id,team_id,recipient,event,resource_id,resource_revision,kind,resource_type,deep_link,state,created_at) SELECT lower(hex(randomblob(16))),t.team_id,r.person,'task_ready.decision.'||j.revision,t.id,t.revision,'task_ready','task','/tasks/'||t.id,'unread',strftime('%Y-%m-%d %H:%M:%f','now') FROM jobs j JOIN tasks t ON t.job_id=j.id AND t.team_id=j.account JOIN (SELECT id AS task_id,requester AS person FROM tasks UNION SELECT t.id,o.address FROM tasks t JOIN decision_owners o ON o.project_id=t.project_id) r ON r.task_id=t.id WHERE j.state='waiting' AND j.wait='approval' AND t.state NOT IN ('merged','cancelled','cancel_requested','failed') AND EXISTS(SELECT 1 FROM members m WHERE m.address=r.person AND m.active=1) ON CONFLICT(team_id,recipient,event,resource_id,resource_revision) DO NOTHING; |
diff --git a/internal/equipo/migrations/schema.sql b/internal/equipo/migrations/schema.sql| index 49bbf246..9de1b892 100644 |
| --- a/internal/equipo/migrations/schema.sql |
| +++ b/internal/equipo/migrations/schema.sql |
| @@ -488,3 +488,73 @@ CREATE TABLE person_device_rates (key text PRIMARY KEY, started_at datetime, cou |
| CREATE TABLE project_rules (project_id integer PRIMARY KEY, text text, revision integer); |
| ALTER TABLE person_devices ADD COLUMN last_used_at datetime; |
| + |
| +CREATE TABLE notification_outbox (sequence integer PRIMARY KEY AUTOINCREMENT, id text NOT NULL, team_id text NOT NULL, recipient text NOT NULL, event text NOT NULL, resource_id text NOT NULL, resource_revision integer NOT NULL, kind text, resource_type text, deep_link text, state text, created_at datetime, acknowledged_at datetime); |
| +CREATE UNIQUE INDEX notification_id ON notification_outbox(id); |
| +CREATE UNIQUE INDEX notification_event ON notification_outbox(team_id,recipient,event,resource_id,resource_revision); |
| +CREATE TABLE notification_subscriptions (id text PRIMARY KEY, team_id text, person text, device_id text, revision integer, ack_sequence integer, active numeric, created_at datetime, expires_at datetime); |
| +CREATE INDEX notification_device ON notification_subscriptions(device_id); |
| +CREATE TABLE notification_deliveries (subscription_id text, sequence integer, delivered_at datetime, acknowledged_at datetime, PRIMARY KEY(subscription_id,sequence)); |
| +CREATE TABLE notification_history (team_id text, person text, pruned_through integer, PRIMARY KEY(team_id,person)); |
| +CREATE TRIGGER notification_clarification_insert AFTER INSERT ON coordinator_questions BEGIN |
| +UPDATE notification_outbox SET state='superseded' WHERE resource_type='clarification' AND resource_id=NEW.id AND state<>'superseded' AND (resource_revision<>NEW.revision OR NEW.state<>'pending'); |
| +INSERT INTO notification_outbox(id,team_id,recipient,event,resource_id,resource_revision,kind,resource_type,deep_link,state,created_at) SELECT lower(hex(randomblob(16))),b.team_id,NEW.person,'question',NEW.id,NEW.revision,'question','clarification','/conversation','unread',strftime('%Y-%m-%d %H:%M:%f','now') FROM coordinator_bindings b WHERE b.id=NEW.binding_id AND NEW.state='pending' AND EXISTS(SELECT 1 FROM members m WHERE m.address=NEW.person AND m.active=1) ON CONFLICT(team_id,recipient,event,resource_id,resource_revision) DO NOTHING; |
| +END; |
| +CREATE TRIGGER notification_question_insert AFTER INSERT ON questions BEGIN |
| +UPDATE notification_outbox SET state='superseded' WHERE resource_type='question' AND resource_id=NEW.id AND state<>'superseded' AND (resource_revision<>NEW.revision OR NEW.state<>'pending'); |
| +INSERT INTO notification_outbox(id,team_id,recipient,event,resource_id,resource_revision,kind,resource_type,deep_link,state,created_at) SELECT lower(hex(randomblob(16))),t.team_id,t.requester,'question',NEW.id,NEW.revision,'question','question','/tasks/'||t.id||'/questions/'||NEW.id,'unread',strftime('%Y-%m-%d %H:%M:%f','now') FROM tasks t WHERE t.id=NEW.task_id AND NEW.state='pending' AND EXISTS(SELECT 1 FROM members m WHERE m.address=t.requester AND m.active=1) ON CONFLICT(team_id,recipient,event,resource_id,resource_revision) DO NOTHING; |
| +END; |
| +CREATE TRIGGER notification_task_insert AFTER INSERT ON tasks BEGIN |
| +UPDATE notification_outbox SET state='superseded' WHERE resource_type='task' AND resource_id=NEW.id AND state<>'superseded' AND (resource_revision<>NEW.revision OR NEW.state IN ('cancelled','cancel_requested','merged','failed')); |
| +INSERT INTO notification_outbox(id,team_id,recipient,event,resource_id,resource_revision,kind,resource_type,deep_link,state,created_at) SELECT lower(hex(randomblob(16))),NEW.team_id,NEW.requester,'task_ready.plan',NEW.id,NEW.revision,'task_ready','task','/tasks/'||NEW.id,'unread',strftime('%Y-%m-%d %H:%M:%f','now') WHERE NEW.state='proposed' AND EXISTS(SELECT 1 FROM members m WHERE m.address=NEW.requester AND m.active=1) ON CONFLICT(team_id,recipient,event,resource_id,resource_revision) DO NOTHING; |
| +END; |
| +CREATE TRIGGER notification_card_insert AFTER INSERT ON conversation_cards BEGIN |
| +UPDATE notification_outbox SET state='superseded' WHERE resource_type='card' AND resource_id=NEW.id AND state<>'superseded' AND resource_revision<>NEW.revision; |
| +INSERT INTO notification_outbox(id,team_id,recipient,event,resource_id,resource_revision,kind,resource_type,deep_link,state,created_at) SELECT lower(hex(randomblob(16))),c.team_id,c.person,'task_ready.plan',NEW.resource_id,NEW.revision,'task_ready','task','/tasks/'||NEW.resource_id,'unread',strftime('%Y-%m-%d %H:%M:%f','now') FROM conversations c WHERE c.id=NEW.stream_id AND NEW.kind='task' AND EXISTS(SELECT 1 FROM members m WHERE m.address=c.person AND m.active=1) ON CONFLICT(team_id,recipient,event,resource_id,resource_revision) DO NOTHING; |
| +INSERT INTO notification_outbox(id,team_id,recipient,event,resource_id,resource_revision,kind,resource_type,deep_link,state,created_at) SELECT lower(hex(randomblob(16))),c.team_id,c.person,'card',NEW.id,NEW.revision,'card','card','/conversation','unread',strftime('%Y-%m-%d %H:%M:%f','now') FROM conversations c WHERE c.id=NEW.stream_id AND NEW.kind LIKE 'suggest_%' AND EXISTS(SELECT 1 FROM members m WHERE m.address=c.person AND m.active=1) ON CONFLICT(team_id,recipient,event,resource_id,resource_revision) DO NOTHING; |
| +END; |
| +CREATE TRIGGER notification_turn_insert AFTER INSERT ON coordinator_turns BEGIN |
| +UPDATE notification_outbox SET state='superseded' WHERE resource_type='coordinator' AND resource_id=NEW.id AND state<>'superseded' AND (resource_revision<>NEW.revision OR NEW.state NOT IN ('uncertain','fenced','context_limit','context_unavailable')); |
| +INSERT INTO notification_outbox(id,team_id,recipient,event,resource_id,resource_revision,kind,resource_type,deep_link,state,created_at) SELECT lower(hex(randomblob(16))),NEW.team_id,NEW.person,'interrupted',NEW.id,NEW.revision,'interrupted','coordinator','/conversation','unread',strftime('%Y-%m-%d %H:%M:%f','now') WHERE NEW.state IN ('uncertain','fenced','context_limit','context_unavailable') AND EXISTS(SELECT 1 FROM members m WHERE m.address=NEW.person AND m.active=1) ON CONFLICT(team_id,recipient,event,resource_id,resource_revision) DO NOTHING; |
| +END; |
| +CREATE TRIGGER notification_clarification_update AFTER UPDATE ON coordinator_questions BEGIN |
| +UPDATE notification_outbox SET state='superseded' WHERE resource_type='clarification' AND resource_id=NEW.id AND state<>'superseded' AND (resource_revision<>NEW.revision OR NEW.state<>'pending'); |
| +INSERT INTO notification_outbox(id,team_id,recipient,event,resource_id,resource_revision,kind,resource_type,deep_link,state,created_at) SELECT lower(hex(randomblob(16))),b.team_id,NEW.person,'question',NEW.id,NEW.revision,'question','clarification','/conversation','unread',strftime('%Y-%m-%d %H:%M:%f','now') FROM coordinator_bindings b WHERE b.id=NEW.binding_id AND NEW.state='pending' AND EXISTS(SELECT 1 FROM members m WHERE m.address=NEW.person AND m.active=1) ON CONFLICT(team_id,recipient,event,resource_id,resource_revision) DO NOTHING; |
| +END; |
| +CREATE TRIGGER notification_question_update AFTER UPDATE ON questions BEGIN |
| +UPDATE notification_outbox SET state='superseded' WHERE resource_type='question' AND resource_id=NEW.id AND state<>'superseded' AND (resource_revision<>NEW.revision OR NEW.state<>'pending'); |
| +INSERT INTO notification_outbox(id,team_id,recipient,event,resource_id,resource_revision,kind,resource_type,deep_link,state,created_at) SELECT lower(hex(randomblob(16))),t.team_id,t.requester,'question',NEW.id,NEW.revision,'question','question','/tasks/'||t.id||'/questions/'||NEW.id,'unread',strftime('%Y-%m-%d %H:%M:%f','now') FROM tasks t WHERE t.id=NEW.task_id AND NEW.state='pending' AND EXISTS(SELECT 1 FROM members m WHERE m.address=t.requester AND m.active=1) ON CONFLICT(team_id,recipient,event,resource_id,resource_revision) DO NOTHING; |
| +END; |
| +CREATE TRIGGER notification_task_update AFTER UPDATE ON tasks BEGIN |
| +UPDATE notification_outbox SET state='superseded' WHERE resource_type='task' AND resource_id=NEW.id AND state<>'superseded' AND (resource_revision<>NEW.revision OR NEW.state IN ('cancelled','cancel_requested','merged','failed')); |
| +INSERT INTO notification_outbox(id,team_id,recipient,event,resource_id,resource_revision,kind,resource_type,deep_link,state,created_at) SELECT lower(hex(randomblob(16))),NEW.team_id,NEW.requester,'task_ready.plan',NEW.id,NEW.revision,'task_ready','task','/tasks/'||NEW.id,'unread',strftime('%Y-%m-%d %H:%M:%f','now') WHERE NEW.state='proposed' AND EXISTS(SELECT 1 FROM members m WHERE m.address=NEW.requester AND m.active=1) ON CONFLICT(team_id,recipient,event,resource_id,resource_revision) DO NOTHING; |
| +END; |
| +CREATE TRIGGER notification_card_update AFTER UPDATE ON conversation_cards BEGIN |
| +UPDATE notification_outbox SET state='superseded' WHERE resource_type='card' AND resource_id=NEW.id AND state<>'superseded' AND resource_revision<>NEW.revision; |
| +INSERT INTO notification_outbox(id,team_id,recipient,event,resource_id,resource_revision,kind,resource_type,deep_link,state,created_at) SELECT lower(hex(randomblob(16))),c.team_id,c.person,'task_ready.plan',NEW.resource_id,NEW.revision,'task_ready','task','/tasks/'||NEW.resource_id,'unread',strftime('%Y-%m-%d %H:%M:%f','now') FROM conversations c WHERE c.id=NEW.stream_id AND NEW.kind='task' AND EXISTS(SELECT 1 FROM members m WHERE m.address=c.person AND m.active=1) ON CONFLICT(team_id,recipient,event,resource_id,resource_revision) DO NOTHING; |
| +INSERT INTO notification_outbox(id,team_id,recipient,event,resource_id,resource_revision,kind,resource_type,deep_link,state,created_at) SELECT lower(hex(randomblob(16))),c.team_id,c.person,'card',NEW.id,NEW.revision,'card','card','/conversation','unread',strftime('%Y-%m-%d %H:%M:%f','now') FROM conversations c WHERE c.id=NEW.stream_id AND NEW.kind LIKE 'suggest_%' AND EXISTS(SELECT 1 FROM members m WHERE m.address=c.person AND m.active=1) ON CONFLICT(team_id,recipient,event,resource_id,resource_revision) DO NOTHING; |
| +END; |
| +CREATE TRIGGER notification_turn_update AFTER UPDATE ON coordinator_turns BEGIN |
| +UPDATE notification_outbox SET state='superseded' WHERE resource_type='coordinator' AND resource_id=NEW.id AND state<>'superseded' AND (resource_revision<>NEW.revision OR NEW.state NOT IN ('uncertain','fenced','context_limit','context_unavailable')); |
| +INSERT INTO notification_outbox(id,team_id,recipient,event,resource_id,resource_revision,kind,resource_type,deep_link,state,created_at) SELECT lower(hex(randomblob(16))),NEW.team_id,NEW.person,'interrupted',NEW.id,NEW.revision,'interrupted','coordinator','/conversation','unread',strftime('%Y-%m-%d %H:%M:%f','now') WHERE NEW.state IN ('uncertain','fenced','context_limit','context_unavailable') AND EXISTS(SELECT 1 FROM members m WHERE m.address=NEW.person AND m.active=1) ON CONFLICT(team_id,recipient,event,resource_id,resource_revision) DO NOTHING; |
| +END; |
| +CREATE TRIGGER notification_job_ready AFTER UPDATE ON jobs WHEN NEW.state='succeeded' AND OLD.state IS NOT NEW.state BEGIN |
| +INSERT INTO notification_outbox(id,team_id,recipient,event,resource_id,resource_revision,kind,resource_type,deep_link,state,created_at) SELECT lower(hex(randomblob(16))),t.team_id,r.person,'task_ready.complete',t.id,t.revision,'task_ready','task','/tasks/'||t.id,'unread',strftime('%Y-%m-%d %H:%M:%f','now') FROM tasks t JOIN (SELECT id AS task_id,requester AS person FROM tasks UNION SELECT t.id,o.address FROM tasks t JOIN decision_owners o ON o.project_id=t.project_id) r ON r.task_id=t.id WHERE t.job_id=NEW.id AND t.team_id=NEW.account AND EXISTS(SELECT 1 FROM members m WHERE m.address=r.person AND m.active=1) ON CONFLICT(team_id,recipient,event,resource_id,resource_revision) DO NOTHING; |
| +END; |
| +CREATE TRIGGER notification_job_decision AFTER UPDATE ON jobs WHEN NEW.wait='approval' AND (OLD.wait IS NOT NEW.wait OR OLD.revision IS NOT NEW.revision) BEGIN |
| +INSERT INTO notification_outbox(id,team_id,recipient,event,resource_id,resource_revision,kind,resource_type,deep_link,state,created_at) SELECT lower(hex(randomblob(16))),t.team_id,r.person,'task_ready.decision.'||NEW.revision,t.id,t.revision,'task_ready','task','/tasks/'||t.id,'unread',strftime('%Y-%m-%d %H:%M:%f','now') FROM tasks t JOIN (SELECT id AS task_id,requester AS person FROM tasks UNION SELECT t.id,o.address FROM tasks t JOIN decision_owners o ON o.project_id=t.project_id) r ON r.task_id=t.id WHERE t.job_id=NEW.id AND t.team_id=NEW.account AND EXISTS(SELECT 1 FROM members m WHERE m.address=r.person AND m.active=1) ON CONFLICT(team_id,recipient,event,resource_id,resource_revision) DO NOTHING; |
| +END; |
| +CREATE TRIGGER notification_job_interrupted AFTER UPDATE ON jobs WHEN NEW.wait IN ('uncertain_external_outcome','runner_unavailable','connection_unavailable') AND OLD.wait IS NOT NEW.wait BEGIN |
| +INSERT INTO notification_outbox(id,team_id,recipient,event,resource_id,resource_revision,kind,resource_type,deep_link,state,created_at) SELECT lower(hex(randomblob(16))),t.team_id,t.requester,'interrupted.job.'||NEW.revision,t.id,t.revision,'interrupted','task','/tasks/'||t.id,'unread',strftime('%Y-%m-%d %H:%M:%f','now') FROM tasks t WHERE t.job_id=NEW.id AND t.team_id=NEW.account AND EXISTS(SELECT 1 FROM members m WHERE m.address=t.requester AND m.active=1) ON CONFLICT(team_id,recipient,event,resource_id,resource_revision) DO NOTHING; |
| +END; |
| +CREATE TRIGGER notification_device_revoke AFTER UPDATE ON person_devices WHEN NEW.revoked_at IS NOT NULL AND OLD.revoked_at IS NULL BEGIN |
| +UPDATE notification_subscriptions SET active=0,revision=revision+1 WHERE device_id=NEW.id AND active=1; |
| +END; |
| +CREATE TRIGGER notification_member_revoke AFTER UPDATE ON members WHEN NEW.active=0 OR NEW.session_epoch<>OLD.session_epoch BEGIN |
| +UPDATE notification_subscriptions SET active=0,revision=revision+1 WHERE person=NEW.address AND active=1; |
| +END; |
| +CREATE TRIGGER notification_binding_generation AFTER UPDATE ON coordinator_bindings WHEN NEW.generation<>OLD.generation BEGIN |
| +UPDATE notification_outbox SET state='superseded' WHERE resource_type IN ('clarification','coordinator') AND resource_id IN (SELECT id FROM coordinator_questions WHERE binding_id=NEW.id UNION SELECT id FROM coordinator_turns WHERE binding_id=NEW.id); |
| +END; |
| + |
| +CREATE INDEX notification_feed ON notification_outbox(team_id,recipient,sequence); |
diff --git a/internal/equipo/migrations_test.go b/internal/equipo/migrations_test.go| index f7a8647a..2770f441 100644 |
| --- a/internal/equipo/migrations_test.go |
| +++ b/internal/equipo/migrations_test.go |
| @@ -6,6 +6,8 @@ import ( |
| "log/slog" |
| "os" |
| "path/filepath" |
| + "reflect" |
| + "strings" |
| "testing" |
| "amadan.net/rastrillo/rastrillo/db" |
| @@ -24,35 +26,61 @@ func TestMigrationModels(t *testing.T) { |
| } |
| func TestConversationMigrationSnapshot(t *testing.T) { |
| - actual, err := migrate.SchemaSQL(context.Background(), Schema.All()) |
| + ctx := context.Background() |
| + // The pinned SchemaSQL dumper sorts triggers before tables. Replay instead |
| + // so this comparison also covers executable triggers and their source tables. |
| + actual, err := migrate.Replay(ctx, Schema.All()) |
| if err != nil { |
| t.Fatal(err) |
| } |
| + defer actual.Close() |
| saved, err := os.ReadFile("migrations/schema.sql") |
| if err != nil { |
| t.Fatal(err) |
| } |
| - read := func(name, sql string) migrate.Snapshot { |
| - d, err := db.Open(filepath.Join(t.TempDir(), name+".db"), slog.New(slog.NewTextHandler(io.Discard, nil))) |
| + d, err := db.Open(filepath.Join(t.TempDir(), "snapshot.db"), slog.New(slog.NewTextHandler(io.Discard, nil))) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + t.Cleanup(func() { |
| + if err := d.Close(); err != nil { |
| + t.Error(err) |
| + } |
| + }) |
| + if _, err = d.Writer().Exec(string(saved)); err != nil { |
| + t.Fatal(err) |
| + } |
| + savedSchema, err := migrate.Read(ctx, d.Writer()) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + migrationSchema, err := migrate.Read(ctx, actual) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if !savedSchema.Equal(migrationSchema) { |
| + t.Fatal("schema snapshot differs from ordered migrations", savedSchema.Diff(migrationSchema)) |
| + } |
| + triggers := func(q migrate.Querier) map[string]string { |
| + rows, err := q.QueryContext(ctx, "SELECT name,sql FROM sqlite_master WHERE type='trigger' ORDER BY name") |
| if err != nil { |
| t.Fatal(err) |
| } |
| - t.Cleanup(func() { |
| - if err := d.Close(); err != nil { |
| - t.Error(err) |
| + defer rows.Close() |
| + out := map[string]string{} |
| + for rows.Next() { |
| + var name, sql string |
| + if err = rows.Scan(&name, &sql); err != nil { |
| + t.Fatal(err) |
| } |
| - }) |
| - if _, err := d.Writer().Exec(sql); err != nil { |
| - t.Fatal(err) |
| + out[name] = strings.TrimSpace(sql) |
| } |
| - snapshot, err := migrate.Read(context.Background(), d.Writer()) |
| - if err != nil { |
| + if err = rows.Err(); err != nil { |
| t.Fatal(err) |
| } |
| - return snapshot |
| + return out |
| } |
| - savedSchema, migrationSchema := read("saved", string(saved)), read("migrations", actual) |
| - if !savedSchema.Equal(migrationSchema) { |
| - t.Fatal("schema snapshot differs from ordered migrations", savedSchema.Diff(migrationSchema)) |
| + if !reflect.DeepEqual(triggers(actual), triggers(d.Writer())) { |
| + t.Fatal("schema snapshot triggers differ from ordered migrations") |
| } |
| } |
diff --git a/internal/equipo/models.go b/internal/equipo/models.go| index c861b6c9..1ca3e0a3 100644 |
| --- a/internal/equipo/models.go |
| +++ b/internal/equipo/models.go |
| @@ -2,6 +2,7 @@ package equipo |
| import ( |
| "amadan.net/oficina/equipo/internal/equipo/library" |
| + "amadan.net/oficina/equipo/internal/equipo/notifications" |
| "time" |
| "amadan.net/oficina/equipo/internal/equipo/conversation" |
| @@ -11,7 +12,7 @@ import ( |
| "amadan.net/oficina/equipo/internal/equipo/setup" |
| ) |
| -var Models = append(append(append(append([]any{&supervisedTrialRecord{}, &questionRecord{}, &runnerEvent{}, &runnerEventID{}, &runnerTimeline{}, &runnerArtifactRequest{}, &artifactBlob{}, &artifactBlobUpload{}, &runnerAssignment{}, &runnerCleanup{}, &runnerObservation{}, &runnerRotation{}, &executionAdmissionTicket{}, &Task{}, &taskOutbox{}, &Team{}, &Member{}, &AuditEvent{}, &Account{}, &Project{}, &DecisionOwner{}, &projectRequest{}, &budgetRecord{}, &runnerRecord{}, &runnerEnrolment{}, &runnerCredentialRecord{}, &runnerRate{}, &connectionRecord{}, &connectionChoiceRecord{}, &isolationAcknowledgementRecord{}, &ConnectionInvalidation{}}, executionModels...), conversation.Models...), planning.Models...), append(append(personapi.Models, library.Models...), setup.Models...)...) |
| +var Models = append(notifications.Models, append(append(append(append([]any{&supervisedTrialRecord{}, &questionRecord{}, &runnerEvent{}, &runnerEventID{}, &runnerTimeline{}, &runnerArtifactRequest{}, &artifactBlob{}, &artifactBlobUpload{}, &runnerAssignment{}, &runnerCleanup{}, &runnerObservation{}, &runnerRotation{}, &executionAdmissionTicket{}, &Task{}, &taskOutbox{}, &Team{}, &Member{}, &AuditEvent{}, &Account{}, &Project{}, &DecisionOwner{}, &projectRequest{}, &budgetRecord{}, &runnerRecord{}, &runnerEnrolment{}, &runnerCredentialRecord{}, &runnerRate{}, &connectionRecord{}, &connectionChoiceRecord{}, &isolationAcknowledgementRecord{}, &ConnectionInvalidation{}}, executionModels...), conversation.Models...), planning.Models...), append(append(personapi.Models, library.Models...), setup.Models...)...)...) |
| type Actor = kernel.Actor |
diff --git a/internal/equipo/notifications.go b/internal/equipo/notifications.go| new file mode 100644 |
| index 00000000..0e10fa86 |
| --- /dev/null |
| +++ b/internal/equipo/notifications.go |
| @@ -0,0 +1,28 @@ |
| +package equipo |
| + |
| +import ( |
| + "amadan.net/oficina/equipo/internal/equipo/notifications" |
| + "amadan.net/oficina/equipo/internal/equipo/personapi" |
| + "gorm.io/gorm" |
| + "net/http" |
| +) |
| + |
| +type Notification = notifications.Notification |
| +type NotificationSubscription = notifications.NotificationSubscription |
| +type NotificationApplication = notifications.Store |
| + |
| +func (s *Store) notificationApplication() *NotificationApplication { |
| + return ¬ifications.Store{Write: s.write, Read: s.invitationRead, Authorize: func(tx *gorm.DB, a Actor) (string, error) { |
| + if _, err := currentRunnerMember(tx, a.Address); err != nil { |
| + return "", err |
| + } |
| + return runnerInstance(tx) |
| + }, Audit: appendAudit, Devices: s.personDevices, Key: func() string { return s.personKey }, Now: s.runnerClock.Now, Invalid: ErrInvalid, Forbidden: ErrForbidden, NotFound: ErrNotFound, Conflict: ErrConflict, CursorExpired: ErrCursorExpired} |
| +} |
| +func (a *application) allowNotification(r *http.Request, key string) bool { |
| + p, err := a.store.personCookie(r) |
| + if err != nil { |
| + return false |
| + } |
| + return a.store.AllowNotificationTopic(personapi.WithVerifiedPrincipal(r.Context(), p), Actor{Address: p.Address}, key) |
| +} |
diff --git a/internal/equipo/notifications/api.go b/internal/equipo/notifications/api.go| new file mode 100644 |
| index 00000000..804ce23e |
| --- /dev/null |
| +++ b/internal/equipo/notifications/api.go |
| @@ -0,0 +1,353 @@ |
| +package notifications |
| + |
| +import ( |
| + "context" |
| + "crypto/rand" |
| + "errors" |
| + "time" |
| + |
| + "amadan.net/oficina/equipo/internal/equipo/kernel" |
| + "amadan.net/oficina/equipo/internal/equipo/personapi" |
| + "gorm.io/gorm" |
| + "gorm.io/gorm/clause" |
| +) |
| + |
| +type Store struct { |
| + Write func(context.Context, func(*gorm.DB) error) error |
| + Read func(context.Context, func(*gorm.DB) error) error |
| + Authorize func(*gorm.DB, kernel.Actor) (string, error) |
| + Audit func(*gorm.DB, kernel.Actor, string, string) error |
| + Devices func() *personapi.DeviceStore |
| + Key func() string |
| + Now func() time.Time |
| + Invalid, Forbidden, NotFound, Conflict, CursorExpired error |
| +} |
| +type position struct { |
| + Subscription string |
| + After int64 |
| + History int64 |
| +} |
| + |
| +func (s *Store) codec() kernel.CursorCodec { return kernel.CursorCodec{Key: s.Key(), Now: s.Now} } |
| +func scope(team, person string) string { return "notifications\x00" + team + "\x00" + person } |
| +func (s *Store) device(tx *gorm.DB, ctx context.Context, a kernel.Actor, id string) (time.Time, error) { |
| + var d struct{ TokenExpiresAt time.Time } |
| + if err := tx.Table("person_devices").Select("token_expires_at").Where("id=? AND person=?", id, a.Address).Take(&d).Error; err != nil { |
| + if errors.Is(err, gorm.ErrRecordNotFound) { |
| + return time.Time{}, s.NotFound |
| + } |
| + return time.Time{}, err |
| + } |
| + if caller, ok := personapi.PrincipalFrom(ctx); ok && caller.CredentialID != "" && caller.CredentialID != id { |
| + return time.Time{}, s.NotFound |
| + } |
| + if _, err := s.Devices().VerifyAt(tx, id, ""); err != nil { |
| + return time.Time{}, personapi.ErrSubscriptionExpired |
| + } |
| + return d.TokenExpiresAt, nil |
| +} |
| +func (s *Store) subscription(tx *gorm.DB, ctx context.Context, a kernel.Actor, team, id string, active bool) (Subscription, error) { |
| + var sub Subscription |
| + if err := tx.Where("id=? AND team_id=? AND person=?", id, team, a.Address).Take(&sub).Error; err != nil { |
| + if errors.Is(err, gorm.ErrRecordNotFound) { |
| + return sub, s.NotFound |
| + } |
| + return sub, err |
| + } |
| + if _, err := s.device(tx, ctx, a, sub.DeviceID); err != nil { |
| + return sub, err |
| + } |
| + if !s.Now().Before(sub.ExpiresAt) || active && !sub.Active { |
| + return sub, personapi.ErrSubscriptionExpired |
| + } |
| + return sub, nil |
| +} |
| +func (s *Store) project(tx *gorm.DB, sub Subscription) (NotificationSubscription, error) { |
| + history, err := historyAt(tx, sub.TeamID, sub.Person) |
| + if err != nil { |
| + return NotificationSubscription{}, err |
| + } |
| + c, err := s.codec().Seal(scope(sub.TeamID, sub.Person), position{Subscription: sub.ID, After: sub.AckSequence, History: history}) |
| + return NotificationSubscription{ID: sub.ID, DeviceID: sub.DeviceID, Cursor: c, Revision: sub.Revision, Active: sub.Active, ExpiresAt: sub.ExpiresAt}, err |
| +} |
| +func (s *Store) SubscribeNotifications(ctx context.Context, a kernel.Actor, device string, m kernel.Mutation) (out NotificationSubscription, err error) { |
| + if !m.Valid() || device == "" || len(device) > 128 { |
| + return out, s.Invalid |
| + } |
| + ctx, err = personapi.ApplicationRequest(ctx, a, "notifications.subscribe", device, struct { |
| + Device string |
| + Revision int64 |
| + }{device, m.Revision}, m) |
| + if err != nil { |
| + return |
| + } |
| + err = s.Write(ctx, func(tx *gorm.DB) error { |
| + team, e := s.authorize(tx, ctx, a) |
| + if e != nil { |
| + return e |
| + } |
| + expiry, e := s.device(tx, ctx, a, device) |
| + if e != nil { |
| + return e |
| + } |
| + if replay, e := personapi.Replay(tx, ctx, &out, s.Conflict); e != nil || replay { |
| + if e != nil { |
| + return e |
| + } |
| + _, e = s.subscription(tx, ctx, a, team, out.ID, true) |
| + return e |
| + } |
| + now := s.Now().UTC() |
| + if max := now.Add(30 * 24 * time.Hour); expiry.After(max) { |
| + expiry = max |
| + } |
| + // One active subscription per device; only an explicit action replaces it. |
| + if e = tx.Model(&Subscription{}).Where("team_id=? AND person=? AND device_id=? AND active=?", team, a.Address, device, true).Select("active", "revision").Updates(map[string]any{"active": false, "revision": gorm.Expr("revision+1")}).Error; e != nil { |
| + return e |
| + } |
| + sub := Subscription{ID: rand.Text(), TeamID: team, Person: a.Address, DeviceID: device, Revision: 1, Active: true, CreatedAt: now, ExpiresAt: expiry} |
| + if e = tx.Create(&sub).Error; e != nil { |
| + return e |
| + } |
| + out, e = s.project(tx, sub) |
| + if e != nil { |
| + return e |
| + } |
| + if e = s.Audit(tx, a, "notifications.subscribe", sub.ID); e != nil { |
| + return e |
| + } |
| + return personapi.SaveResult(tx, ctx, out, s.Conflict) |
| + }) |
| + return |
| +} |
| +func (s *Store) NotificationSubscription(ctx context.Context, a kernel.Actor, id string) (out NotificationSubscription, err error) { |
| + err = s.Read(ctx, func(tx *gorm.DB) error { |
| + team, e := s.authorize(tx, ctx, a) |
| + if e != nil { |
| + return e |
| + } |
| + sub, e := s.subscription(tx, ctx, a, team, id, false) |
| + if e != nil { |
| + return e |
| + } |
| + out, e = s.project(tx, sub) |
| + return e |
| + }) |
| + return |
| +} |
| +func (s *Store) UnsubscribeNotifications(ctx context.Context, a kernel.Actor, id string, m kernel.Mutation) error { |
| + return s.change(ctx, a, id, "", m) |
| +} |
| +func (s *Store) AcknowledgeNotification(ctx context.Context, a kernel.Actor, id, notification string, m kernel.Mutation) error { |
| + if notification == "" || len(notification) > 128 { |
| + return s.Invalid |
| + } |
| + return s.change(ctx, a, id, notification, m) |
| +} |
| +func (s *Store) change(ctx context.Context, a kernel.Actor, id, notification string, m kernel.Mutation) error { |
| + if !m.Valid() { |
| + return s.Invalid |
| + } |
| + op := "notifications.unsubscribe" |
| + if notification != "" { |
| + op = "notifications.ack" |
| + } |
| + ctx, err := personapi.ApplicationRequest(ctx, a, op, id, struct { |
| + ID string |
| + Revision int64 |
| + }{notification, m.Revision}, m) |
| + if err != nil { |
| + return err |
| + } |
| + return s.Write(ctx, func(tx *gorm.DB) error { |
| + team, e := s.authorize(tx, ctx, a) |
| + if e != nil { |
| + return e |
| + } |
| + sub, e := s.subscription(tx, ctx, a, team, id, notification != "") |
| + if e != nil { |
| + return e |
| + } |
| + var ack personapi.Ack |
| + if replay, e := personapi.Replay(tx, ctx, &ack, s.Conflict); e != nil || replay { |
| + return e |
| + } |
| + if sub.Revision != m.Revision { |
| + return s.Conflict |
| + } |
| + if notification == "" { |
| + sub.Active = false |
| + } else { |
| + var n Event |
| + if e = tx.Where("id=? AND team_id=? AND recipient=?", notification, team, a.Address).Take(&n).Error; e != nil { |
| + if errors.Is(e, gorm.ErrRecordNotFound) { |
| + return s.NotFound |
| + } |
| + return e |
| + } |
| + var d Delivery |
| + if e = tx.Where("subscription_id=? AND sequence=?", id, n.Sequence).Take(&d).Error; e != nil { |
| + if errors.Is(e, gorm.ErrRecordNotFound) { |
| + return s.NotFound |
| + } |
| + return e |
| + } |
| + now := s.Now().UTC() |
| + if d.AcknowledgedAt == nil { |
| + if e = tx.Model(&Delivery{}).Where("subscription_id=? AND sequence=?", id, n.Sequence).Select("acknowledged_at").Update("acknowledged_at", now).Error; e != nil { |
| + return e |
| + } |
| + } |
| + // Every recipient event counts, including ones this device has not fetched. |
| + // Numeric gaps belonging to other recipients do not block this cursor. |
| + var first struct{ Sequence int64 } |
| + if e = tx.Table("notification_outbox n").Select("n.sequence").Joins("LEFT JOIN notification_deliveries d ON d.sequence=n.sequence AND d.subscription_id=?", id).Where("n.team_id=? AND n.recipient=? AND n.sequence>? AND d.acknowledged_at IS NULL", team, a.Address, sub.AckSequence).Order("n.sequence").Limit(1).Scan(&first).Error; e != nil { |
| + return e |
| + } |
| + q := tx.Model(&Event{}).Where("team_id=? AND recipient=?", team, a.Address) |
| + if first.Sequence > 0 { |
| + q = q.Where("sequence<?", first.Sequence) |
| + } |
| + var through int64 |
| + if e = q.Select("COALESCE(MAX(sequence),0)").Scan(&through).Error; e != nil { |
| + return e |
| + } |
| + if through > sub.AckSequence { |
| + sub.AckSequence = through |
| + } |
| + // Retention begins once someone acknowledges. Other devices keep their own unread state. |
| + if e = tx.Model(&Event{}).Where("id=? AND acknowledged_at IS NULL", n.ID).Select("acknowledged_at").Update("acknowledged_at", now).Error; e != nil { |
| + return e |
| + } |
| + } |
| + sub.Revision++ |
| + updated := tx.Model(&Subscription{}).Where("id=? AND revision=?", id, m.Revision).Select("active", "ack_sequence", "revision").Updates(&sub) |
| + if updated.Error != nil { |
| + return updated.Error |
| + } |
| + if updated.RowsAffected != 1 { |
| + return s.Conflict |
| + } |
| + if e = s.Audit(tx, a, op, id); e != nil { |
| + return e |
| + } |
| + return personapi.SaveResult(tx, ctx, personapi.Ack{Revision: sub.Revision}, s.Conflict) |
| + }) |
| +} |
| +func (s *Store) Notifications(ctx context.Context, a kernel.Actor, cursor string, limit int) (out personapi.Page[Notification], err error) { |
| + out.Items = []Notification{} |
| + if limit == 0 { |
| + limit = 50 |
| + } |
| + if limit < 1 || limit > 100 { |
| + return out, s.Invalid |
| + } |
| + err = s.Write(personapi.WithoutRequest(ctx), func(tx *gorm.DB) error { |
| + team, e := s.authorize(tx, ctx, a) |
| + if e != nil { |
| + return e |
| + } |
| + var pos position |
| + if cursor != "" && s.codec().Open(scope(team, a.Address), cursor, &pos) != nil { |
| + return s.CursorExpired |
| + } |
| + if pos.After < 0 { |
| + return s.CursorExpired |
| + } |
| + if pos.Subscription != "" { |
| + if _, e = s.subscription(tx, ctx, a, team, pos.Subscription, true); e != nil { |
| + return e |
| + } |
| + } |
| + if e = s.prune(tx, team, a.Address); e != nil { |
| + return e |
| + } |
| + var history History |
| + e = tx.Where("team_id=? AND person=?", team, a.Address).Take(&history).Error |
| + if e != nil && !errors.Is(e, gorm.ErrRecordNotFound) { |
| + return e |
| + } |
| + if cursor != "" && pos.History < history.PrunedThrough { |
| + return s.CursorExpired |
| + } |
| + pos.History = history.PrunedThrough |
| + var rows []Event |
| + if e = tx.Where("team_id=? AND recipient=? AND sequence>?", team, a.Address, pos.After).Order("sequence").Limit(limit).Find(&rows).Error; e != nil { |
| + return e |
| + } |
| + for _, row := range rows { |
| + n := Notification{ID: row.ID, Kind: row.Kind, ResourceID: row.ResourceID, DeepLink: row.DeepLink, ResourceRevision: row.ResourceRevision, CreatedAt: row.CreatedAt.UTC(), State: row.State} |
| + current, e := s.current(tx, row) |
| + if e != nil { |
| + return e |
| + } |
| + if !current { |
| + if row.State != "superseded" { |
| + if e = tx.Model(&Event{}).Where("sequence=?", row.Sequence).Select("state").Update("state", "superseded").Error; e != nil { |
| + return e |
| + } |
| + } |
| + n.State = "superseded" |
| + } |
| + if pos.Subscription != "" { |
| + d := Delivery{SubscriptionID: pos.Subscription, Sequence: row.Sequence, DeliveredAt: s.Now().UTC()} |
| + if e = tx.Clauses(clause.OnConflict{DoNothing: true}).Create(&d).Error; e != nil { |
| + return e |
| + } |
| + if e = tx.Where("subscription_id=? AND sequence=?", pos.Subscription, row.Sequence).Take(&d).Error; e != nil { |
| + return e |
| + } |
| + if d.AcknowledgedAt != nil && n.State != "superseded" { |
| + n.State = "acknowledged" |
| + } |
| + } |
| + out.Items = append(out.Items, n) |
| + pos.After = row.Sequence |
| + } |
| + out.NextCursor, e = s.codec().Seal(scope(team, a.Address), pos) |
| + if e != nil { |
| + return e |
| + } |
| + out.Revision = personapi.Revision(out.Items) |
| + return nil |
| + }) |
| + return |
| +} |
| +func (s *Store) AllowNotificationSubscription(ctx context.Context, a kernel.Actor, id string) bool { |
| + allowed := false |
| + err := s.Read(ctx, func(tx *gorm.DB) error { |
| + team, e := s.authorize(tx, ctx, a) |
| + if e != nil { |
| + return e |
| + } |
| + _, e = s.subscription(tx, ctx, a, team, id, true) |
| + allowed = e == nil |
| + return e |
| + }) |
| + return err == nil && allowed |
| +} |
| + |
| +func (s *Store) authorize(tx *gorm.DB, ctx context.Context, a kernel.Actor) (string, error) { |
| + team, err := s.Authorize(tx, a) |
| + if err != nil { |
| + return "", err |
| + } |
| + if p, ok := personapi.PrincipalFrom(ctx); ok { |
| + if p.Address != a.Address { |
| + return "", s.Forbidden |
| + } |
| + var epoch int64 |
| + if err = tx.Table("members").Select("session_epoch").Where("address=? AND active=1", a.Address).Scan(&epoch).Error; err != nil { |
| + return "", err |
| + } |
| + if p.SessionEpoch < epoch { |
| + return "", s.Forbidden |
| + } |
| + if p.CredentialID != "" { |
| + if _, err = s.Devices().VerifyAt(tx, p.CredentialID, ""); err != nil { |
| + return "", err |
| + } |
| + } |
| + } |
| + return team, nil |
| +} |
diff --git a/internal/equipo/notifications/budget_test.go b/internal/equipo/notifications/budget_test.go| new file mode 100644 |
| index 00000000..9f69af84 |
| --- /dev/null |
| +++ b/internal/equipo/notifications/budget_test.go |
| @@ -0,0 +1,9 @@ |
| +package notifications |
| + |
| +import ( |
| + "amadan.net/rastrillo/rastrillo/budget" |
| + "os" |
| + "testing" |
| +) |
| + |
| +func TestMain(m *testing.M) { os.Exit(budget.Main(m)) } |
diff --git a/internal/equipo/notifications/live.go b/internal/equipo/notifications/live.go| new file mode 100644 |
| index 00000000..f8ded73d |
| --- /dev/null |
| +++ b/internal/equipo/notifications/live.go |
| @@ -0,0 +1,73 @@ |
| +package notifications |
| + |
| +import ( |
| + "context" |
| + "crypto/sha256" |
| + "database/sql" |
| + "encoding/json" |
| + "fmt" |
| + "time" |
| + |
| + "amadan.net/oficina/equipo/internal/equipo/kernel" |
| + "gorm.io/gorm" |
| +) |
| + |
| +func Topic(team, person, id string) string { |
| + raw, _ := json.Marshal([]string{team, person, id}) |
| + return fmt.Sprintf("notifications/%x", sha256.Sum256(raw)) |
| +} |
| +func (s *Store) AllowNotificationTopic(ctx context.Context, a kernel.Actor, key string) bool { |
| + allowed := false |
| + err := s.Read(ctx, func(tx *gorm.DB) error { |
| + team, e := s.authorize(tx, ctx, a) |
| + if e != nil { |
| + return e |
| + } |
| + var subs []Subscription |
| + if e = tx.Where("team_id=? AND person=? AND active=1", team, a.Address).Find(&subs).Error; e != nil { |
| + return e |
| + } |
| + for _, sub := range subs { |
| + if Topic(team, a.Address, sub.ID) == "notifications/"+key { |
| + _, e = s.subscription(tx, ctx, a, team, sub.ID, true) |
| + allowed = e == nil |
| + return e |
| + } |
| + } |
| + return nil |
| + }) |
| + return err == nil && allowed |
| +} |
| +func InstallChanges(ctx context.Context, tx *sql.Tx) error { |
| + for _, stmt := range []string{ |
| + `CREATE TEMP TABLE IF NOT EXISTS equipo_notification_changes(team TEXT,person TEXT,PRIMARY KEY(team,person))`, |
| + `DELETE FROM equipo_notification_changes`, |
| + `CREATE TEMP TRIGGER IF NOT EXISTS equipo_notification_insert AFTER INSERT ON main.notification_outbox BEGIN INSERT OR IGNORE INTO equipo_notification_changes VALUES(NEW.team_id,NEW.recipient); END`, |
| + `CREATE TEMP TRIGGER IF NOT EXISTS equipo_notification_update AFTER UPDATE ON main.notification_outbox BEGIN INSERT OR IGNORE INTO equipo_notification_changes VALUES(NEW.team_id,NEW.recipient); END`, |
| + `CREATE TEMP TRIGGER IF NOT EXISTS equipo_notification_subscription AFTER UPDATE ON main.notification_subscriptions BEGIN INSERT OR IGNORE INTO equipo_notification_changes VALUES(NEW.team_id,NEW.person); END`, |
| + } { |
| + if _, err := tx.ExecContext(ctx, stmt); err != nil { |
| + return err |
| + } |
| + } |
| + return nil |
| +} |
| +func Changes(ctx context.Context, tx *sql.Tx, deadlines map[string][]time.Time) ([]string, error) { |
| + rows, err := tx.QueryContext(ctx, `SELECT s.team_id,s.person,s.id,s.expires_at FROM notification_subscriptions s JOIN equipo_notification_changes c ON c.team=s.team_id AND c.person=s.person`) |
| + if err != nil { |
| + return nil, err |
| + } |
| + defer rows.Close() |
| + var topics []string |
| + for rows.Next() { |
| + var team, person, id string |
| + var expires any |
| + if err = rows.Scan(&team, &person, &id, &expires); err != nil { |
| + return nil, err |
| + } |
| + topic := Topic(team, person, id) |
| + topics = append(topics, topic) |
| + deadlines[topic] = append(deadlines[topic], kernel.ReadTime(expires)) |
| + } |
| + return topics, rows.Err() |
| +} |
diff --git a/internal/equipo/notifications/live_guard.go b/internal/equipo/notifications/live_guard.go| new file mode 100644 |
| index 00000000..02f8681e |
| --- /dev/null |
| +++ b/internal/equipo/notifications/live_guard.go |
| @@ -0,0 +1,47 @@ |
| +package notifications |
| + |
| +import ( |
| + "errors" |
| + "net/http" |
| + "strings" |
| +) |
| + |
| +// Rastrillo reauthorizes on reconnect. Notification streams must also check |
| +// device and subscription expiry before every write on an existing connection. |
| +func GuardLive(next http.Handler, allow func(*http.Request, string) bool) http.Handler { |
| + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + var keys []string |
| + for _, token := range r.URL.Query()["t"] { |
| + topic, _, _ := strings.Cut(token, "@") |
| + if key, ok := strings.CutPrefix(topic, "notifications/"); ok { |
| + keys = append(keys, key) |
| + } |
| + } |
| + if len(keys) == 0 { |
| + next.ServeHTTP(w, r) |
| + return |
| + } |
| + next.ServeHTTP(&guardedWriter{ResponseWriter: w, allowed: func() bool { |
| + for _, key := range keys { |
| + if !allow(r, key) { |
| + return false |
| + } |
| + } |
| + return true |
| + }}, r) |
| + }) |
| +} |
| + |
| +type guardedWriter struct { |
| + http.ResponseWriter |
| + allowed func() bool |
| +} |
| + |
| +func (w *guardedWriter) Write(p []byte) (int, error) { |
| + if !w.allowed() { |
| + return 0, errors.New("notification stream revoked") |
| + } |
| + return w.ResponseWriter.Write(p) |
| +} |
| +func (w *guardedWriter) Flush() { _ = http.NewResponseController(w.ResponseWriter).Flush() } |
| +func (w *guardedWriter) Unwrap() http.ResponseWriter { return w.ResponseWriter } |
diff --git a/internal/equipo/notifications/models.go b/internal/equipo/notifications/models.go| new file mode 100644 |
| index 00000000..096c545d |
| --- /dev/null |
| +++ b/internal/equipo/notifications/models.go |
| @@ -0,0 +1,53 @@ |
| +package notifications |
| + |
| +import ( |
| + "amadan.net/oficina/equipo/internal/equipo/personapi" |
| + "time" |
| +) |
| + |
| +type Notification = personapi.Notification |
| +type NotificationSubscription = personapi.NotificationSubscription |
| + |
| +type Event struct { |
| + Sequence int64 `gorm:"primaryKey;autoIncrement;index:notification_feed,priority:3"` |
| + ID string `gorm:"uniqueIndex:notification_id;not null"` |
| + TeamID string `gorm:"uniqueIndex:notification_event,priority:1;index:notification_feed,priority:1;not null"` |
| + Recipient string `gorm:"uniqueIndex:notification_event,priority:2;index:notification_feed,priority:2;not null"` |
| + Event string `gorm:"uniqueIndex:notification_event,priority:3;not null"` |
| + ResourceID string `gorm:"uniqueIndex:notification_event,priority:4;not null"` |
| + ResourceRevision int64 `gorm:"uniqueIndex:notification_event,priority:5;not null"` |
| + Kind, ResourceType, DeepLink, State string |
| + CreatedAt time.Time |
| + AcknowledgedAt *time.Time |
| +} |
| + |
| +func (Event) TableName() string { return "notification_outbox" } |
| + |
| +type Subscription struct { |
| + ID string `gorm:"primaryKey"` |
| + TeamID, Person string |
| + DeviceID string `gorm:"index:notification_device"` |
| + Revision, AckSequence int64 |
| + Active bool |
| + CreatedAt, ExpiresAt time.Time |
| +} |
| + |
| +func (Subscription) TableName() string { return "notification_subscriptions" } |
| + |
| +type Delivery struct { |
| + SubscriptionID string `gorm:"primaryKey"` |
| + Sequence int64 `gorm:"primaryKey;autoIncrement:false"` |
| + DeliveredAt time.Time |
| + AcknowledgedAt *time.Time |
| +} |
| + |
| +func (Delivery) TableName() string { return "notification_deliveries" } |
| + |
| +type History struct { |
| + TeamID, Person string `gorm:"primaryKey"` |
| + PrunedThrough int64 |
| +} |
| + |
| +func (History) TableName() string { return "notification_history" } |
| + |
| +var Models = []any{&Event{}, &Subscription{}, &Delivery{}, &History{}} |
diff --git a/internal/equipo/notifications/observer.go b/internal/equipo/notifications/observer.go| new file mode 100644 |
| index 00000000..e73bd245 |
| --- /dev/null |
| +++ b/internal/equipo/notifications/observer.go |
| @@ -0,0 +1,105 @@ |
| +package notifications |
| + |
| +import ( |
| + "amadan.net/oficina/equipo/internal/equipo/conversation" |
| + "amadan.net/oficina/equipo/internal/equipo/kernel" |
| + "amadan.net/oficina/equipo/internal/equipo/team" |
| + "context" |
| + "database/sql" |
| + "sort" |
| + "time" |
| +) |
| + |
| +type Notifier interface { |
| + Notify(...string) |
| + NotifyAt(time.Time, ...string) |
| +} |
| + |
| +func ObserveWrite(ctx context.Context, tx *sql.Tx, n Notifier) (team.CommitObserver, error) { |
| + if n == nil { |
| + return nil, nil |
| + } |
| + if err := InstallChanges(ctx, tx); err != nil { |
| + return nil, err |
| + } |
| + if err := conversation.InstallConversationChanges(ctx, tx); err != nil { |
| + return nil, err |
| + } |
| + if err := conversation.InstallPersonalChanges(ctx, tx); err != nil { |
| + return nil, err |
| + } |
| + if err := conversation.InstallJobChanges(ctx, tx); err != nil { |
| + return nil, err |
| + } |
| + return func(ctx context.Context, tx *sql.Tx) (func(), error) { |
| + rows, err := tx.QueryContext(ctx, `SELECT c.team,c.job FROM equipo_live_changes c JOIN teams t ON t.id=c.team WHERE c.job=0 OR EXISTS(SELECT 1 FROM jobs j WHERE j.id=c.job AND j.account=c.team)`) |
| + if err != nil { |
| + return nil, err |
| + } |
| + touched := map[string][]team.JobID{} |
| + topics := map[string]bool{} |
| + for rows.Next() { |
| + var teamID string |
| + var job team.JobID |
| + if err = rows.Scan(&teamID, &job); err != nil { |
| + break |
| + } |
| + touched[teamID] = append(touched[teamID], job) |
| + topics[kernel.JobTopic(teamID, int64(job))] = true |
| + topics[kernel.JobTopic(teamID, 0)] = true |
| + } |
| + if err == nil { |
| + err = rows.Err() |
| + } |
| + rows.Close() |
| + if err != nil { |
| + return nil, err |
| + } |
| + deadlines := map[string][]time.Time{} |
| + if err := conversation.ConversationDeadlines(ctx, tx, deadlines); err != nil { |
| + return nil, err |
| + } |
| + for teamID, ids := range touched { |
| + if err := conversation.JobDeadlines(ctx, tx, deadlines, teamID, ids); err != nil { |
| + return nil, err |
| + } |
| + } |
| + private, err := conversation.PersonalChanges(ctx, tx) |
| + if err != nil { |
| + return nil, err |
| + } |
| + conversations, err := conversation.ConversationChanges(ctx, tx) |
| + if err != nil { |
| + return nil, err |
| + } |
| + notificationTopics, err := Changes(ctx, tx, deadlines) |
| + if err != nil { |
| + return nil, err |
| + } |
| + private = append(private, notificationTopics...) |
| + private = append(private, conversations...) |
| + for _, topic := range private { |
| + topics[topic] = true |
| + } |
| + keys := make([]string, 0, len(topics)) |
| + for topic := range topics { |
| + keys = append(keys, topic) |
| + } |
| + sort.Strings(keys) |
| + return func() { |
| + if len(keys) > 0 { |
| + n.Notify(keys...) |
| + } |
| + Schedule(n, deadlines) |
| + }, nil |
| + }, nil |
| +} |
| +func Schedule(n Notifier, deadlines map[string][]time.Time) { |
| + for topic, dates := range deadlines { |
| + for _, at := range dates { |
| + if at.After(time.Now()) { |
| + n.NotifyAt(at, topic) |
| + } |
| + } |
| + } |
| +} |
diff --git a/internal/equipo/notifications/outbox.go b/internal/equipo/notifications/outbox.go| new file mode 100644 |
| index 00000000..72b52e85 |
| --- /dev/null |
| +++ b/internal/equipo/notifications/outbox.go |
| @@ -0,0 +1,91 @@ |
| +package notifications |
| + |
| +import ( |
| + "errors" |
| + "gorm.io/gorm" |
| + "gorm.io/gorm/clause" |
| + "strings" |
| + "time" |
| +) |
| + |
| +// Re-read authority and resource state. A notification never supplies an answer capability. |
| +func (s *Store) current(tx *gorm.DB, n Event) (bool, error) { |
| + if n.State == "superseded" { |
| + return false, nil |
| + } |
| + var count int64 |
| + var q *gorm.DB |
| + switch n.ResourceType { |
| + case "clarification": |
| + q = tx.Table("coordinator_questions q").Joins("JOIN coordinator_bindings b ON b.id=q.binding_id").Where("q.id=? AND q.person=? AND b.team_id=? AND q.revision=? AND q.state='pending' AND q.generation=b.generation AND julianday(json_extract(q.payload,'$.ExpiresAt'))>julianday(?)", n.ResourceID, n.Recipient, n.TeamID, n.ResourceRevision, s.Now().UTC()) |
| + case "question": |
| + q = tx.Table("questions q").Joins("JOIN tasks t ON t.id=q.task_id").Joins("JOIN runner_assignments a ON a.id=q.assignment_id").Joins("JOIN jobs j ON j.id=t.job_id").Joins("JOIN attempts attempt ON attempt.id=q.attempt").Where("t.state NOT IN ('cancelled','cancel_requested','failed','merged') AND j.state NOT IN ('succeeded','cancelled','failed') AND attempt.state='active' AND attempt.fence=q.fence").Where("q.id=? AND t.team_id=? AND q.revision=? AND q.state='pending' AND julianday(q.expires_at)>julianday(?) AND a.state='claimed' AND a.attempt_id=q.attempt AND a.fence=q.fence AND julianday(a.lease_deadline)>julianday(?) AND (t.requester=? OR EXISTS(SELECT 1 FROM decision_owners o WHERE o.project_id=t.project_id AND o.address=?))", n.ResourceID, n.TeamID, n.ResourceRevision, s.Now().UTC(), s.Now().UTC(), n.Recipient, n.Recipient) |
| + case "task": |
| + q = tx.Table("tasks t").Where("t.id=? AND t.team_id=? AND t.revision=? AND t.state NOT IN ('cancelled','cancel_requested','merged','failed') AND (t.requester=? OR EXISTS(SELECT 1 FROM decision_owners o WHERE o.project_id=t.project_id AND o.address=?))", n.ResourceID, n.TeamID, n.ResourceRevision, n.Recipient, n.Recipient) |
| + if strings.HasPrefix(n.Event, "task_ready.decision.") { |
| + q = q.Where("EXISTS(SELECT 1 FROM jobs j WHERE j.id=t.job_id AND j.state='waiting' AND j.wait='approval' AND 'task_ready.decision.'||j.revision=?)", n.Event) |
| + } |
| + if strings.HasPrefix(n.Event, "interrupted.job.") { |
| + q = q.Where("EXISTS(SELECT 1 FROM jobs j WHERE j.id=t.job_id AND j.state='waiting' AND j.wait IN ('uncertain_external_outcome','runner_unavailable','connection_unavailable'))") |
| + } |
| + case "coordinator": |
| + q = tx.Table("coordinator_turns t").Joins("JOIN coordinator_bindings b ON b.id=t.binding_id").Where("t.id=? AND t.team_id=? AND t.person=? AND t.revision=? AND t.generation=b.generation AND t.state IN ('uncertain','fenced','context_limit','context_unavailable')", n.ResourceID, n.TeamID, n.Recipient, n.ResourceRevision) |
| + case "card": |
| + q = tx.Table("conversation_cards k").Joins("JOIN conversations c ON c.id=k.stream_id").Where("k.id=? AND c.team_id=? AND c.person=? AND k.revision=?", n.ResourceID, n.TeamID, n.Recipient, n.ResourceRevision) |
| + default: |
| + return false, nil |
| + } |
| + err := q.Count(&count).Error |
| + return count == 1, err |
| +} |
| + |
| +// Acknowledged history lasts at least thirty days. Pending questions and unread |
| +// entries on any still-valid subscription survive cleanup. |
| +func (s *Store) prune(tx *gorm.DB, team, person string) error { |
| + var rows []Event |
| + now := s.Now().UTC() |
| + if err := tx.Where("team_id=? AND recipient=? AND acknowledged_at<?", team, person, now.Add(-30*24*time.Hour)).Order("sequence").Limit(100).Find(&rows).Error; err != nil { |
| + return err |
| + } |
| + var through int64 |
| + for _, n := range rows { |
| + if n.Kind == "question" { |
| + current, err := s.current(tx, n) |
| + if err != nil { |
| + return err |
| + } |
| + if current { |
| + continue |
| + } |
| + } |
| + var unread int64 |
| + if err := tx.Table("notification_subscriptions s").Joins("JOIN person_devices p ON p.id=s.device_id").Joins("LEFT JOIN notification_deliveries d ON d.subscription_id=s.id AND d.sequence=?", n.Sequence).Where("s.team_id=? AND s.person=? AND s.active=1 AND s.expires_at>? AND p.revoked_at IS NULL AND p.token_expires_at>? AND d.acknowledged_at IS NULL", team, person, now, now).Count(&unread).Error; err != nil { |
| + return err |
| + } |
| + if unread > 0 { |
| + continue |
| + } |
| + if err := tx.Where("sequence=?", n.Sequence).Delete(&Delivery{}).Error; err != nil { |
| + return err |
| + } |
| + if err := tx.Where("sequence=?", n.Sequence).Delete(&Event{}).Error; err != nil { |
| + return err |
| + } |
| + if n.Sequence > through { |
| + through = n.Sequence |
| + } |
| + } |
| + if through == 0 { |
| + return nil |
| + } |
| + h := History{TeamID: team, Person: person, PrunedThrough: through} |
| + return tx.Clauses(clause.OnConflict{Columns: []clause.Column{{Name: "team_id"}, {Name: "person"}}, DoUpdates: clause.Assignments(map[string]any{"pruned_through": gorm.Expr("MAX(pruned_through,?)", through)})}).Create(&h).Error |
| +} |
| +func historyAt(tx *gorm.DB, team, person string) (int64, error) { |
| + var h History |
| + err := tx.Where("team_id=? AND person=?", team, person).Take(&h).Error |
| + if errors.Is(err, gorm.ErrRecordNotFound) { |
| + err = nil |
| + } |
| + return h.PrunedThrough, err |
| +} |
diff --git a/internal/equipo/personapi/conversation.go b/internal/equipo/personapi/conversation.go| index 95cb73d6..358d7dbf 100644 |
| --- a/internal/equipo/personapi/conversation.go |
| +++ b/internal/equipo/personapi/conversation.go |
| @@ -55,6 +55,9 @@ func ProjectPlan(p taskplan.Plan) Plan { |
| } |
| func (h *Handler) read(ctx context.Context, a kernel.Actor, op, id, cursor string, limit int) (Result, error) { |
| switch op { |
| + case "notifications": |
| + p, err := h.App.Notifications(ctx, a, cursor, limit) |
| + return Result{p, p.Revision}, err |
| case "plan": |
| v, err := h.App.TaskPlan(ctx, a, id) |
| return Result{ProjectPlan(v), v.Revision}, err |
| @@ -81,6 +84,13 @@ func (h *Handler) read(ctx context.Context, a kernel.Actor, op, id, cursor strin |
| } |
| func (h *Handler) mutate(ctx context.Context, a kernel.Actor, op, id string, input any, m kernel.Mutation) (Result, error) { |
| switch op { |
| + case "subscribe_notifications": |
| + v, err := h.App.SubscribeNotifications(ctx, a, input.(*SubscribeNotificationsInput).DeviceID, m) |
| + return Result{v, v.Revision}, err |
| + case "unsubscribe_notifications": |
| + return apiAck(m, h.App.UnsubscribeNotifications(ctx, a, id, m)) |
| + case "ack_notification": |
| + return apiAck(m, h.App.AcknowledgeNotification(ctx, a, id, input.(*AcknowledgeNotificationInput).NotificationID, m)) |
| case "send", "send_thread": |
| v := input.(*MessageInput) |
| thread := "" |
diff --git a/internal/equipo/personapi/handler.go b/internal/equipo/personapi/handler.go| index 3fd4dce9..33aacd4a 100644 |
| --- a/internal/equipo/personapi/handler.go |
| +++ b/internal/equipo/personapi/handler.go |
| @@ -188,6 +188,8 @@ var ErrUnauthenticated = errors.New("api.unauthenticated") |
| func (h *Handler) Failure(w http.ResponseWriter, r *http.Request, err error) { |
| code, status := "unavailable", 503 |
| switch { |
| + case errors.Is(err, ErrSubscriptionExpired): |
| + code, status = "subscription_expired", 410 |
| case errors.Is(err, ErrDeviceExpired): |
| code, status = "device_expired", 410 |
| case errors.Is(err, ErrSlowDown): |
| @@ -218,6 +220,12 @@ func (h *Handler) revisionConflict(err error) bool { |
| } |
| func (h *Handler) currentRevision(ctx context.Context, a kernel.Actor, op, id string, input any) (*int64, error) { |
| switch op { |
| + case "subscribe_notifications": |
| + n := int64(0) |
| + return &n, nil |
| + case "unsubscribe_notifications", "ack_notification": |
| + sub, err := h.App.NotificationSubscription(ctx, a, id) |
| + return &sub.Revision, err |
| case "edit_plan", "approve_plan", "project": |
| op = "plan" |
| case "rendered", "merge", "cancel": |
| @@ -255,6 +263,9 @@ type errorScopeKey struct{} |
| func errorCopyKey(r *http.Request, code string) string { |
| op, _ := r.Context().Value(errorScopeKey{}).(string) |
| + if code == "subscription_expired" || op == "notifications" && code == "cursor_expired" { |
| + return "notifications." + code |
| + } |
| switch code { |
| case "invalid_input", "forbidden", "revision_conflict": |
| switch op { |
diff --git a/internal/equipo/personapi/notifications.go b/internal/equipo/personapi/notifications.go| new file mode 100644 |
| index 00000000..c6896a78 |
| --- /dev/null |
| +++ b/internal/equipo/personapi/notifications.go |
| @@ -0,0 +1,49 @@ |
| +package personapi |
| + |
| +import ( |
| + "amadan.net/oficina/equipo/internal/equipo/kernel" |
| + "context" |
| + "errors" |
| + "time" |
| +) |
| + |
| +var ErrSubscriptionExpired = errors.New("notifications.subscription_expired") |
| + |
| +type Notification struct { |
| + ID string `json:"id"` |
| + Kind string `json:"kind"` |
| + ResourceID string `json:"resource_id"` |
| + DeepLink string `json:"deep_link"` |
| + ResourceRevision int64 `json:"resource_revision"` |
| + CreatedAt time.Time `json:"created_at"` |
| + State string `json:"state"` |
| +} |
| +type NotificationSubscription struct { |
| + ID string `json:"id"` |
| + DeviceID string `json:"device_id"` |
| + Cursor string `json:"cursor"` |
| + Revision int64 `json:"revision"` |
| + Active bool `json:"active"` |
| + ExpiresAt time.Time `json:"expires_at"` |
| +} |
| +type SubscribeNotificationsInput struct { |
| + DeviceID string `json:"device_id"` |
| +} |
| +type AcknowledgeNotificationInput struct { |
| + NotificationID string `json:"notification_id"` |
| +} |
| +type NotificationOperations interface { |
| + Notifications(context.Context, kernel.Actor, string, int) (Page[Notification], error) |
| + SubscribeNotifications(context.Context, kernel.Actor, string, kernel.Mutation) (NotificationSubscription, error) |
| + AcknowledgeNotification(context.Context, kernel.Actor, string, string, kernel.Mutation) error |
| + UnsubscribeNotifications(context.Context, kernel.Actor, string, kernel.Mutation) error |
| + NotificationSubscription(context.Context, kernel.Actor, string) (NotificationSubscription, error) |
| +} |
| + |
| +func init() { |
| + Routes = append(Routes, |
| + Route{"GET", "/notifications", "notifications", false, nil}, |
| + Route{"POST", "/notification-subscriptions", "subscribe_notifications", false, func() any { return &SubscribeNotificationsInput{} }}, |
| + Route{"DELETE", "/notification-subscriptions/{id}", "unsubscribe_notifications", true, func() any { return &struct{}{} }}, |
| + Route{"POST", "/notification-subscriptions/{id}/ack", "ack_notification", true, func() any { return &AcknowledgeNotificationInput{} }}) |
| +} |
diff --git a/internal/equipo/personapi/types.go b/internal/equipo/personapi/types.go| index 140ae41f..a6ecbb33 100644 |
| --- a/internal/equipo/personapi/types.go |
| +++ b/internal/equipo/personapi/types.go |
| @@ -234,6 +234,7 @@ type Plan struct { |
| } |
| type Application interface { |
| + NotificationOperations |
| PersonAPIExtendedMutation(context.Context, kernel.Actor, string, string, any, kernel.Mutation) (Result, error) |
| Conversation(context.Context, kernel.Actor, string, int) (conversation.ConversationPage, error) |
| SendMessage(context.Context, kernel.Actor, string, string, kernel.Mutation) (conversation.Message, error) |
diff --git a/internal/equipo/store.go b/internal/equipo/store.go| index 859c720c..df7a9686 100644 |
| --- a/internal/equipo/store.go |
| +++ b/internal/equipo/store.go |
| @@ -53,6 +53,7 @@ type InvitationApplication = setup.Application |
| // against the current roster and append an AuditEvent in their transaction. |
| type Store struct { |
| + *NotificationApplication |
| *PlanApplication |
| *InvitationApplication |
| *library.Application |
| @@ -83,6 +84,7 @@ func NewStore(d *db.DB, options ...StoreOption) *Store { |
| for _, option := range options { |
| option(s) |
| } |
| + s.NotificationApplication = s.notificationApplication() |
| s.InvitationApplication = &setup.Application{Write: s.write, Read: s.invitationRead, At: s.invitationsAt, Normalize: normalizeAddress, ValidAddress: validAddress, Invalid: ErrInvalid, Unavailable: ErrUnavailable} |
| s.PlanApplication = &planning.Application{Write: s.write, At: s.planningAt, Normalize: normalizeAddress} |
| s.Application = &library.Application{Write: s.write, At: s.libraryAt, Normalize: normalizeAddress, Read: func(ctx context.Context, a Actor, fn func(*gorm.DB) error) error { |
diff --git a/internal/plan3test/coordinator_migration_test.go b/internal/plan3test/coordinator_migration_test.go| index 12d587ba..503a9fe6 100644 |
| --- a/internal/plan3test/coordinator_migration_test.go |
| +++ b/internal/plan3test/coordinator_migration_test.go |
| @@ -18,7 +18,7 @@ func TestCoordinatorMigrationUpgrade(t *testing.T) { |
| t.Cleanup(func() { must(t, d.Close()) }) |
| old := &migrate.Set{} |
| for _, m := range equipo.BootSchema.All() { |
| - if m.ID != "equipo/0021_coordinator" { |
| + if m.ID != "equipo/0021_coordinator" && m.ID != "equipo/0031_notifications" { |
| old.Add(m) |
| } |
| } |
| @@ -30,7 +30,7 @@ func TestCoordinatorMigrationUpgrade(t *testing.T) { |
| must(t, err) |
| result, err := migrate.Apply(ctx, d, equipo.BootSchema) |
| must(t, err) |
| - if len(result.Applied) != 1 || result.Applied[0] != "equipo/0021_coordinator" { |
| + if len(result.Applied) != 2 || result.Applied[0] != "equipo/0021_coordinator" || result.Applied[1] != "equipo/0031_notifications" { |
| t.Fatal("wrong upgrade", result.Applied) |
| } |
| f := &fixture{DB: d, Store: equipo.NewStore(d)} |
diff --git a/internal/plan3test/migration_test.go b/internal/plan3test/migration_test.go| index f8988066..da627499 100644 |
| --- a/internal/plan3test/migration_test.go |
| +++ b/internal/plan3test/migration_test.go |
| @@ -19,7 +19,7 @@ func TestConversationMigrationUpgrade(t *testing.T) { |
| t.Cleanup(func() { must(t, d.Close()) }) |
| old := &migrate.Set{} |
| for _, m := range equipo.BootSchema.All() { |
| - if m.ID != "equipo/0019_conversation" && m.ID != "equipo/0021_coordinator_sources" { |
| + if m.ID != "equipo/0019_conversation" && m.ID != "equipo/0021_coordinator_sources" && m.ID != "equipo/0031_notifications" { |
| old.Add(m) |
| } |
| } |
| @@ -33,7 +33,7 @@ func TestConversationMigrationUpgrade(t *testing.T) { |
| before := f.count(t, "SELECT count(*) FROM audit_events") |
| result, e := migrate.Apply(ctx, d, equipo.BootSchema) |
| must(t, e) |
| - if !reflect.DeepEqual(result.Applied, []string{"equipo/0019_conversation", "equipo/0021_coordinator_sources"}) { |
| + if !reflect.DeepEqual(result.Applied, []string{"equipo/0019_conversation", "equipo/0021_coordinator_sources", "equipo/0031_notifications"}) { |
| t.Fatal("wrong upgrade", result.Applied) |
| } |
| var saved equipo.Task |
diff --git a/internal/plan3test/notifications_fixture.go b/internal/plan3test/notifications_fixture.go| new file mode 100644 |
| index 00000000..e233535c |
| --- /dev/null |
| +++ b/internal/plan3test/notifications_fixture.go |
| @@ -0,0 +1,23 @@ |
| +package plan3test |
| + |
| +import ( |
| + "amadan.net/oficina/equipo/internal/equipo" |
| + "amadan.net/oficina/equipo/internal/runnerproto" |
| + "amadan.net/rastrillo/rastrillo/mail" |
| + "encoding/json" |
| + "io" |
| + "log/slog" |
| + "testing" |
| +) |
| + |
| +func notificationToolCall(id string, body json.RawMessage) runnerproto.CoordinatorToolCall { |
| + return runnerproto.CoordinatorToolCall{RequestID: id, Name: "ask_person", Arguments: body} |
| +} |
| +func notificationRouter(t *testing.T, f *fixture, s *equipo.Store) { |
| + t.Helper() |
| + logger := slog.New(slog.NewTextHandler(io.Discard, nil)) |
| + h, err := equipo.RouterWithStore(f.DB, equipo.Config{Origin: origin, InstanceKey: "plan3-fixture", AllowLoggedMail: true, Owners: []string{owner.Address}}, mail.Logged(logger), logger, s) |
| + must(t, err) |
| + f.Store = s |
| + f.Handler = equipo.Mux(h) |
| +} |
diff --git a/internal/plan3test/notifications_lifecycle_test.go b/internal/plan3test/notifications_lifecycle_test.go| new file mode 100644 |
| index 00000000..b11f3f80 |
| --- /dev/null |
| +++ b/internal/plan3test/notifications_lifecycle_test.go |
| @@ -0,0 +1,251 @@ |
| +package plan3test |
| + |
| +import ( |
| + "amadan.net/oficina/equipo/internal/equipo" |
| + "amadan.net/oficina/equipo/internal/equipo/notifications" |
| + "amadan.net/oficina/equipo/internal/equipo/personapi" |
| + "errors" |
| + "fmt" |
| + "gorm.io/gorm" |
| + "strings" |
| + "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 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 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 TestNotificationPrivateInvalidation(t *testing.T) { |
| + f := newFixture(t) |
| + d := approvedDevice(t, f) |
| + sub := notificationSubscription(t, f, d) |
| + spy := &preferenceNotifications{} |
| + f.Store.SetJobNotifier(spy) |
| + p := proposed(t, f) |
| + topic := notifications.Topic(f.TeamID, owner.Address, sub.ID) |
| + found := false |
| + for _, got := range spy.topics { |
| + if got == topic { |
| + found = true |
| + } |
| + if strings.Contains(got, owner.Address) { |
| + t.Fatal("live topic reveals recipient") |
| + } |
| + } |
| + if !found { |
| + t.Fatal("no private notification invalidation", spy.topics) |
| + } |
| + spy.topics = nil |
| + f.exec(t, "CREATE TRIGGER fail_notification_plan BEFORE INSERT ON audit_events WHEN NEW.kind='plan.edit' BEGIN SELECT RAISE(ABORT,'fixture'); END") |
| + p.Steps[0].Instructions = "rolled back" |
| + if _, err := f.Store.EditPlan(ctx, owner, p, equipo.Mutation{RequestID: "fail", Revision: 1}); err == nil { |
| + t.Fatal("fixture audit failure ignored") |
| + } |
| + if len(spy.topics) != 0 { |
| + t.Fatal("rollback sent live invalidation", spy.topics) |
| + } |
| + // Exercise the registered stream route with the same private topic. |
| + liveFixture(t, f) |
| + if status := watchConversation(t, f, owner, topic); status != 200 { |
| + t.Fatal("own notification live route", status) |
| + } |
| + if status := watchConversation(t, f, peer, topic); status != 403 { |
| + t.Fatal("foreign notification live route", status) |
| + } |
| +} |
| + |
| +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 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) |
| +} |
diff --git a/internal/plan3test/notifications_migration_test.go b/internal/plan3test/notifications_migration_test.go| new file mode 100644 |
| index 00000000..ac59124f |
| --- /dev/null |
| +++ b/internal/plan3test/notifications_migration_test.go |
| @@ -0,0 +1,66 @@ |
| +package plan3test |
| + |
| +import ( |
| + "amadan.net/oficina/equipo/internal/equipo" |
| + "amadan.net/rastrillo/rastrillo/db" |
| + "amadan.net/rastrillo/rastrillo/migrate" |
| + "io" |
| + "log/slog" |
| + "path/filepath" |
| + "testing" |
| +) |
| + |
| +func TestNotificationMigrationUpgrade(t *testing.T) { |
| + path := filepath.Join(t.TempDir(), "notifications.db") |
| + logger := slog.New(slog.NewTextHandler(io.Discard, nil)) |
| + d, err := db.Open(path, logger) |
| + must(t, err) |
| + old := &migrate.Set{} |
| + for _, m := range equipo.BootSchema.All() { |
| + if m.ID != "equipo/0031_notifications" { |
| + old.Add(m) |
| + } |
| + } |
| + _, err = migrate.Apply(ctx, d, old) |
| + must(t, err) |
| + s := equipo.NewStore(d) |
| + must(t, s.Bootstrap(ctx, []string{owner.Address})) |
| + msg, err := s.SendMessage(ctx, owner, "", "historical", equipo.Mutation{RequestID: "old"}) |
| + must(t, err) |
| + var team string |
| + must(t, d.Writer().QueryRow("SELECT id FROM teams").Scan(&team)) |
| + _, err = d.Writer().Exec("INSERT INTO tasks(id,requester,request_id,team_id,revision,state) VALUES('old-task',?,'old-task',?,1,'proposed')", owner.Address, team) |
| + must(t, err) |
| + applied, err := migrate.Apply(ctx, d, equipo.BootSchema) |
| + must(t, err) |
| + if len(applied.Applied) != 1 || applied.Applied[0] != "equipo/0031_notifications" { |
| + t.Fatal(applied) |
| + } |
| + var n int |
| + must(t, d.Writer().QueryRow("SELECT count(*) FROM notification_outbox WHERE resource_id='old-task'").Scan(&n)) |
| + if n != 1 { |
| + t.Fatal("upgrade lost existing actionable task", n) |
| + } |
| + fresh := newFixture(t) |
| + upgraded, err := migrate.Read(ctx, d.Writer()) |
| + must(t, err) |
| + freshSchema, err := migrate.Read(ctx, fresh.DB.Writer()) |
| + must(t, err) |
| + if !upgraded.Equal(freshSchema) { |
| + t.Fatal(upgraded.Diff(freshSchema)) |
| + } |
| + must(t, d.Close()) |
| + d, err = db.Open(path, logger) |
| + must(t, err) |
| + t.Cleanup(func() { must(t, d.Close()) }) |
| + applied, err = migrate.Apply(ctx, d, equipo.BootSchema) |
| + must(t, err) |
| + if len(applied.Applied) != 0 { |
| + t.Fatal("notification migration reapplied") |
| + } |
| + page, err := equipo.NewStore(d).Conversation(ctx, owner, "", 50) |
| + must(t, err) |
| + if len(page.Messages) != 1 || page.Messages[0].ID != msg.ID { |
| + t.Fatal("upgrade lost historical conversation") |
| + } |
| +} |
diff --git a/internal/plan3test/notifications_test.go b/internal/plan3test/notifications_test.go| new file mode 100644 |
| index 00000000..f2073539 |
| --- /dev/null |
| +++ b/internal/plan3test/notifications_test.go |
| @@ -0,0 +1,415 @@ |
| +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) |
| + 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) |
| + 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) |
| + 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 WHERE id='first'") |
| + f.task(t, owner, "second") |
| + f.exec(t, "UPDATE tasks SET state='proposed',revision=2 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 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 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) |
| + } |
| + } |
| +} |
diff --git a/internal/plan3test/person_api_contract_test.go b/internal/plan3test/person_api_contract_test.go| index c8cdedc8..b28e5f44 100644 |
| --- a/internal/plan3test/person_api_contract_test.go |
| +++ b/internal/plan3test/person_api_contract_test.go |
| @@ -44,6 +44,7 @@ func TestPersonAPIContractCoverage(t *testing.T) { |
| "/templates": "GET", "/templates/{id}": "GET", "/templates/{id}/install": "POST", "/specialists/{id}/template-diff": "GET", "/playbooks/{id}/template-diff": "GET", "/specialists/{id}/template-update": "POST", "/playbooks/{id}/template-update": "POST", |
| "/connections": "GET", "/connections/{id}": "GET PATCH DELETE", "/projects/{id}/connections": "PUT", "/tasks/{id}/steps/{key}/selection": "POST", |
| "/runners": "GET", "/runners/{id}": "GET DELETE", "/runners/enrol/approve": "POST", "/onboarding": "GET", "/onboarding/advance": "POST", "/account-setups": "POST", "/account-setups/{id}": "GET DELETE", |
| + "/notifications": "GET", "/notification-subscriptions": "POST", "/notification-subscriptions/{id}": "DELETE", "/notification-subscriptions/{id}/ack": "POST", |
| "/invites": "POST", "/invites/{id}": "GET DELETE", "/invites/{id}/accept": "POST", |
| } { |
| required[path] = methods |
| @@ -92,7 +93,7 @@ func TestPersonAPIContractCoverage(t *testing.T) { |
| t.Fatal("person bearer is undocumented") |
| } |
| codes := document["components"].(map[string]any)["schemas"].(map[string]any)["Error"].(map[string]any)["properties"].(map[string]any)["code"].(map[string]any)["enum"].([]any) |
| - for _, code := range []string{"device_expired", "slow_down", "authorization_pending"} { |
| + for _, code := range []string{"device_expired", "slow_down", "authorization_pending", "subscription_expired"} { |
| found := false |
| for _, value := range codes { |
| if value == code { |
diff --git a/internal/plan3test/person_api_migration_test.go b/internal/plan3test/person_api_migration_test.go| index cbf85906..9f02a792 100644 |
| --- a/internal/plan3test/person_api_migration_test.go |
| +++ b/internal/plan3test/person_api_migration_test.go |
| @@ -80,7 +80,7 @@ func TestPersonAPIDeviceMigrationUpgrade(t *testing.T) { |
| must(t, err) |
| old := &migrate.Set{} |
| for _, m := range equipo.BootSchema.All() { |
| - if m.ID != "equipo/0030_person_devices" && m.ID != "equipo/0030_person_devices_usage" { |
| + if m.ID != "equipo/0030_person_devices" && m.ID != "equipo/0030_person_devices_usage" && m.ID != "equipo/0031_notifications" { |
| old.Add(m) |
| } |
| } |
| @@ -92,7 +92,7 @@ func TestPersonAPIDeviceMigrationUpgrade(t *testing.T) { |
| must(t, err) |
| result, err := migrate.Apply(ctx, d, equipo.BootSchema) |
| must(t, err) |
| - if len(result.Applied) != 2 || result.Applied[0] != "equipo/0030_person_devices" || result.Applied[1] != "equipo/0030_person_devices_usage" { |
| + if len(result.Applied) != 3 || result.Applied[0] != "equipo/0030_person_devices" || result.Applied[1] != "equipo/0030_person_devices_usage" || result.Applied[2] != "equipo/0031_notifications" { |
| t.Fatal(result.Applied) |
| } |
| f := newFixture(t) |