Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
feat(reminders): reminders schema, API, and SQS fan-out dispatch (#5462)
Evan Hutnik6a9162ae6e7c
diff --git a/.github/services-config.json b/.github/services-config.jsonindex dbd1592865..ab5e232bee 100644--- a/.github/services-config.json+++ b/.github/services-config.json@@ -98,6 +98,7 @@"services/document_storage_service/**","crates/call/**","crates/github/**",+ "crates/reminders/**","services/delete_chat_handler/**","services/docx_unzip_handler/**","services/document_upload_finalizer_handler/**"diff --git a/.github/workspace-dep-closures.json b/.github/workspace-dep-closures.jsonindex f6fe14e357..7a56a3687a 100644--- a/.github/workspace-dep-closures.json+++ b/.github/workspace-dep-closures.json@@ -1653,6 +1653,7 @@"crates/properties_service","crates/rate_limit","crates/readonly_pool",+ "crates/reminders","crates/remote_env_var","crates/roles_and_permissions","crates/s3_key",@@ -4841,6 +4842,43 @@"crates/remote_env_var","crates/workspace-hack"],+ "reminders": [+ "crates/agent",+ "crates/ai_toolset",+ "crates/ai_usage",+ "crates/attachment",+ "crates/bot_id",+ "crates/channel_sender",+ "crates/cowlike",+ "crates/document_sub_type",+ "crates/entity_access",+ "crates/invite_email",+ "crates/last_online_tracker",+ "crates/macro_auth",+ "crates/macro_authorization",+ "crates/macro_env",+ "crates/macro_env_var",+ "crates/macro_service_urls",+ "crates/macro_user_id",+ "crates/macro_uuid",+ "crates/mention_utils",+ "crates/model",+ "crates/model-entity",+ "crates/model-error-response",+ "crates/model_file_type",+ "crates/model_notifications",+ "crates/model_user",+ "crates/models_bulk_upload",+ "crates/models_pagination",+ "crates/models_permissions",+ "crates/non_empty",+ "crates/notification",+ "crates/prompt",+ "crates/rate_limit",+ "crates/reminders",+ "crates/remote_env_var",+ "crates/workspace-hack"+ ],"remote_env_var": ["crates/macro_env","crates/macro_env_var",diff --git a/.sqlx/query-054e2fcf72800de203c07120c12c742fc8a991a61bcf7a2195b28443c46b9ae7.json b/.sqlx/query-054e2fcf72800de203c07120c12c742fc8a991a61bcf7a2195b28443c46b9ae7.jsonnew file mode 100644index 0000000000..9bf7a8bf93--- /dev/null+++ b/.sqlx/query-054e2fcf72800de203c07120c12c742fc8a991a61bcf7a2195b28443c46b9ae7.json@@ -0,0 +1,23 @@+{+ "db_name": "PostgreSQL",+ "query": "SELECT EXISTS (\n SELECT 1 FROM reminder WHERE id = $1 AND user_id = $2\n ) AS \"owns!\"",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "owns!",+ "type_info": "Bool"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid",+ "Text"+ ]+ },+ "nullable": [+ null+ ]+ },+ "hash": "054e2fcf72800de203c07120c12c742fc8a991a61bcf7a2195b28443c46b9ae7"+}diff --git a/.sqlx/query-0853eb8aebce758bb70c30b10d78dcedf213799902485db96d42cca7b882b1da.json b/.sqlx/query-0853eb8aebce758bb70c30b10d78dcedf213799902485db96d42cca7b882b1da.jsonnew file mode 100644index 0000000000..72ec1903f6--- /dev/null+++ b/.sqlx/query-0853eb8aebce758bb70c30b10d78dcedf213799902485db96d42cca7b882b1da.json@@ -0,0 +1,25 @@+{+ "db_name": "PostgreSQL",+ "query": "\n INSERT INTO reminder_occurrence (id, reminder_id, scheduled_for)\n VALUES ($1, $2, $3)\n ON CONFLICT (reminder_id, scheduled_for) DO UPDATE\n SET created_at = now()\n WHERE reminder_occurrence.sent_at IS NULL\n AND reminder_occurrence.created_at < $4\n RETURNING id\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "id",+ "type_info": "Uuid"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid",+ "Uuid",+ "Timestamptz",+ "Timestamptz"+ ]+ },+ "nullable": [+ false+ ]+ },+ "hash": "0853eb8aebce758bb70c30b10d78dcedf213799902485db96d42cca7b882b1da"+}diff --git a/.sqlx/query-2ce5bcb25ec45ca0444ca3c78a7f291b93666d073f8b6ea1c8c3e57fe5ca96a6.json b/.sqlx/query-2ce5bcb25ec45ca0444ca3c78a7f291b93666d073f8b6ea1c8c3e57fe5ca96a6.jsonnew file mode 100644index 0000000000..b59ed6fc82--- /dev/null+++ b/.sqlx/query-2ce5bcb25ec45ca0444ca3c78a7f291b93666d073f8b6ea1c8c3e57fe5ca96a6.json@@ -0,0 +1,96 @@+{+ "db_name": "PostgreSQL",+ "query": "\n INSERT INTO reminder (\n id, user_id, description, entity_type, entity_id,\n remind_at, cron, timezone, next_run_at\n )\n VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)\n RETURNING\n id,\n description,\n entity_type,\n entity_id,\n remind_at,\n cron,\n timezone,\n next_run_at,\n enabled,\n completed_at,\n created_at,\n updated_at\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "id",+ "type_info": "Uuid"+ },+ {+ "ordinal": 1,+ "name": "description",+ "type_info": "Text"+ },+ {+ "ordinal": 2,+ "name": "entity_type",+ "type_info": "Text"+ },+ {+ "ordinal": 3,+ "name": "entity_id",+ "type_info": "Uuid"+ },+ {+ "ordinal": 4,+ "name": "remind_at",+ "type_info": "Timestamptz"+ },+ {+ "ordinal": 5,+ "name": "cron",+ "type_info": "Text"+ },+ {+ "ordinal": 6,+ "name": "timezone",+ "type_info": "Text"+ },+ {+ "ordinal": 7,+ "name": "next_run_at",+ "type_info": "Timestamptz"+ },+ {+ "ordinal": 8,+ "name": "enabled",+ "type_info": "Bool"+ },+ {+ "ordinal": 9,+ "name": "completed_at",+ "type_info": "Timestamptz"+ },+ {+ "ordinal": 10,+ "name": "created_at",+ "type_info": "Timestamptz"+ },+ {+ "ordinal": 11,+ "name": "updated_at",+ "type_info": "Timestamptz"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid",+ "Text",+ "Text",+ "Text",+ "Uuid",+ "Timestamptz",+ "Text",+ "Text",+ "Timestamptz"+ ]+ },+ "nullable": [+ false,+ false,+ true,+ true,+ true,+ true,+ true,+ false,+ false,+ true,+ false,+ false+ ]+ },+ "hash": "2ce5bcb25ec45ca0444ca3c78a7f291b93666d073f8b6ea1c8c3e57fe5ca96a6"+}diff --git a/.sqlx/query-3e2b5796094e08296cac6966362f6e832d07813e034839aa042ba7a2b020f1c0.json b/.sqlx/query-3e2b5796094e08296cac6966362f6e832d07813e034839aa042ba7a2b020f1c0.jsonnew file mode 100644index 0000000000..57b13648d2--- /dev/null+++ b/.sqlx/query-3e2b5796094e08296cac6966362f6e832d07813e034839aa042ba7a2b020f1c0.json@@ -0,0 +1,15 @@+{+ "db_name": "PostgreSQL",+ "query": "\n DELETE FROM reminder_occurrence\n WHERE reminder_id = $1\n AND scheduled_for = $2\n AND sent_at IS NULL\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid",+ "Timestamptz"+ ]+ },+ "nullable": []+ },+ "hash": "3e2b5796094e08296cac6966362f6e832d07813e034839aa042ba7a2b020f1c0"+}diff --git a/.sqlx/query-6df28c41347bfe51efffff171c7dc644d23626f411c6fe2275fa6c3dfd2cbce9.json b/.sqlx/query-6df28c41347bfe51efffff171c7dc644d23626f411c6fe2275fa6c3dfd2cbce9.jsonnew file mode 100644index 0000000000..7995983560--- /dev/null+++ b/.sqlx/query-6df28c41347bfe51efffff171c7dc644d23626f411c6fe2275fa6c3dfd2cbce9.json@@ -0,0 +1,15 @@+{+ "db_name": "PostgreSQL",+ "query": "\n UPDATE reminder_occurrence\n SET sent_at = now()\n WHERE reminder_id = $1 AND scheduled_for = $2\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid",+ "Timestamptz"+ ]+ },+ "nullable": []+ },+ "hash": "6df28c41347bfe51efffff171c7dc644d23626f411c6fe2275fa6c3dfd2cbce9"+}diff --git a/.sqlx/query-89436dc59e4e216dc59cd0e24cea0b17573257d6d0f4eb1af11d0c8607fc3a91.json b/.sqlx/query-89436dc59e4e216dc59cd0e24cea0b17573257d6d0f4eb1af11d0c8607fc3a91.jsonnew file mode 100644index 0000000000..8683f2b492--- /dev/null+++ b/.sqlx/query-89436dc59e4e216dc59cd0e24cea0b17573257d6d0f4eb1af11d0c8607fc3a91.json@@ -0,0 +1,15 @@+{+ "db_name": "PostgreSQL",+ "query": "DELETE FROM reminder WHERE id = $1 AND user_id = $2",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid",+ "Text"+ ]+ },+ "nullable": []+ },+ "hash": "89436dc59e4e216dc59cd0e24cea0b17573257d6d0f4eb1af11d0c8607fc3a91"+}diff --git a/.sqlx/query-921e5411094ca64c56d4476eec49206049f771f35699bf36b1beff103fb68bca.json b/.sqlx/query-921e5411094ca64c56d4476eec49206049f771f35699bf36b1beff103fb68bca.jsonnew file mode 100644index 0000000000..659d04207f--- /dev/null+++ b/.sqlx/query-921e5411094ca64c56d4476eec49206049f771f35699bf36b1beff103fb68bca.json@@ -0,0 +1,95 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT\n id,\n user_id,\n description,\n entity_type,\n entity_id,\n remind_at,\n cron,\n timezone,\n next_run_at,\n enabled,\n completed_at,\n created_at,\n updated_at\n FROM reminder\n WHERE id = $1\n AND next_run_at = $2\n AND enabled\n AND completed_at IS NULL\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "id",+ "type_info": "Uuid"+ },+ {+ "ordinal": 1,+ "name": "user_id",+ "type_info": "Text"+ },+ {+ "ordinal": 2,+ "name": "description",+ "type_info": "Text"+ },+ {+ "ordinal": 3,+ "name": "entity_type",+ "type_info": "Text"+ },+ {+ "ordinal": 4,+ "name": "entity_id",+ "type_info": "Uuid"+ },+ {+ "ordinal": 5,+ "name": "remind_at",+ "type_info": "Timestamptz"+ },+ {+ "ordinal": 6,+ "name": "cron",+ "type_info": "Text"+ },+ {+ "ordinal": 7,+ "name": "timezone",+ "type_info": "Text"+ },+ {+ "ordinal": 8,+ "name": "next_run_at",+ "type_info": "Timestamptz"+ },+ {+ "ordinal": 9,+ "name": "enabled",+ "type_info": "Bool"+ },+ {+ "ordinal": 10,+ "name": "completed_at",+ "type_info": "Timestamptz"+ },+ {+ "ordinal": 11,+ "name": "created_at",+ "type_info": "Timestamptz"+ },+ {+ "ordinal": 12,+ "name": "updated_at",+ "type_info": "Timestamptz"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid",+ "Timestamptz"+ ]+ },+ "nullable": [+ false,+ false,+ false,+ true,+ true,+ true,+ true,+ true,+ false,+ false,+ true,+ false,+ false+ ]+ },+ "hash": "921e5411094ca64c56d4476eec49206049f771f35699bf36b1beff103fb68bca"+}diff --git a/.sqlx/query-a7a8fe712c27896d29b2550800fe36f9b684d3c9e2ddb5e6516a5aef593aa052.json b/.sqlx/query-a7a8fe712c27896d29b2550800fe36f9b684d3c9e2ddb5e6516a5aef593aa052.jsonnew file mode 100644index 0000000000..2d0cc4e4c6--- /dev/null+++ b/.sqlx/query-a7a8fe712c27896d29b2550800fe36f9b684d3c9e2ddb5e6516a5aef593aa052.json@@ -0,0 +1,96 @@+{+ "db_name": "PostgreSQL",+ "query": "\n UPDATE reminder\n SET description = COALESCE($3::text, description),\n remind_at = CASE WHEN $4::bool THEN $5::timestamptz ELSE remind_at END,\n cron = CASE WHEN $4::bool THEN $6::text ELSE cron END,\n timezone = CASE WHEN $4::bool THEN $7::text ELSE timezone END,\n next_run_at = COALESCE($8::timestamptz, next_run_at),\n enabled = COALESCE($9::bool, enabled),\n completed_at = CASE WHEN $4::bool THEN NULL ELSE completed_at END,\n updated_at = now()\n WHERE id = $1 AND user_id = $2\n RETURNING\n id,\n description,\n entity_type,\n entity_id,\n remind_at,\n cron,\n timezone,\n next_run_at,\n enabled,\n completed_at,\n created_at,\n updated_at\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "id",+ "type_info": "Uuid"+ },+ {+ "ordinal": 1,+ "name": "description",+ "type_info": "Text"+ },+ {+ "ordinal": 2,+ "name": "entity_type",+ "type_info": "Text"+ },+ {+ "ordinal": 3,+ "name": "entity_id",+ "type_info": "Uuid"+ },+ {+ "ordinal": 4,+ "name": "remind_at",+ "type_info": "Timestamptz"+ },+ {+ "ordinal": 5,+ "name": "cron",+ "type_info": "Text"+ },+ {+ "ordinal": 6,+ "name": "timezone",+ "type_info": "Text"+ },+ {+ "ordinal": 7,+ "name": "next_run_at",+ "type_info": "Timestamptz"+ },+ {+ "ordinal": 8,+ "name": "enabled",+ "type_info": "Bool"+ },+ {+ "ordinal": 9,+ "name": "completed_at",+ "type_info": "Timestamptz"+ },+ {+ "ordinal": 10,+ "name": "created_at",+ "type_info": "Timestamptz"+ },+ {+ "ordinal": 11,+ "name": "updated_at",+ "type_info": "Timestamptz"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid",+ "Text",+ "Text",+ "Bool",+ "Timestamptz",+ "Text",+ "Text",+ "Timestamptz",+ "Bool"+ ]+ },+ "nullable": [+ false,+ false,+ true,+ true,+ true,+ true,+ true,+ false,+ false,+ true,+ false,+ false+ ]+ },+ "hash": "a7a8fe712c27896d29b2550800fe36f9b684d3c9e2ddb5e6516a5aef593aa052"+}diff --git a/.sqlx/query-b3bbc2f4b2ba1ab3a0b0e9c69c8304d70bb5feb515e9f8251cc0e15586576e5e.json b/.sqlx/query-b3bbc2f4b2ba1ab3a0b0e9c69c8304d70bb5feb515e9f8251cc0e15586576e5e.jsonnew file mode 100644index 0000000000..65510c4c3c--- /dev/null+++ b/.sqlx/query-b3bbc2f4b2ba1ab3a0b0e9c69c8304d70bb5feb515e9f8251cc0e15586576e5e.json@@ -0,0 +1,89 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT\n id,\n description,\n entity_type,\n entity_id,\n remind_at,\n cron,\n timezone,\n next_run_at,\n enabled,\n completed_at,\n created_at,\n updated_at\n FROM reminder\n WHERE id = $1 AND user_id = $2\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "id",+ "type_info": "Uuid"+ },+ {+ "ordinal": 1,+ "name": "description",+ "type_info": "Text"+ },+ {+ "ordinal": 2,+ "name": "entity_type",+ "type_info": "Text"+ },+ {+ "ordinal": 3,+ "name": "entity_id",+ "type_info": "Uuid"+ },+ {+ "ordinal": 4,+ "name": "remind_at",+ "type_info": "Timestamptz"+ },+ {+ "ordinal": 5,+ "name": "cron",+ "type_info": "Text"+ },+ {+ "ordinal": 6,+ "name": "timezone",+ "type_info": "Text"+ },+ {+ "ordinal": 7,+ "name": "next_run_at",+ "type_info": "Timestamptz"+ },+ {+ "ordinal": 8,+ "name": "enabled",+ "type_info": "Bool"+ },+ {+ "ordinal": 9,+ "name": "completed_at",+ "type_info": "Timestamptz"+ },+ {+ "ordinal": 10,+ "name": "created_at",+ "type_info": "Timestamptz"+ },+ {+ "ordinal": 11,+ "name": "updated_at",+ "type_info": "Timestamptz"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid",+ "Text"+ ]+ },+ "nullable": [+ false,+ false,+ true,+ true,+ true,+ true,+ true,+ false,+ false,+ true,+ false,+ false+ ]+ },+ "hash": "b3bbc2f4b2ba1ab3a0b0e9c69c8304d70bb5feb515e9f8251cc0e15586576e5e"+}diff --git a/.sqlx/query-d4eb2c260373b3e0443d494e3b5bea07f5a1732e5eab923c148091838d29f83a.json b/.sqlx/query-d4eb2c260373b3e0443d494e3b5bea07f5a1732e5eab923c148091838d29f83a.jsonnew file mode 100644index 0000000000..03e2b466a7--- /dev/null+++ b/.sqlx/query-d4eb2c260373b3e0443d494e3b5bea07f5a1732e5eab923c148091838d29f83a.json@@ -0,0 +1,14 @@+{+ "db_name": "PostgreSQL",+ "query": "\n UPDATE reminder\n SET completed_at = now(), updated_at = now()\n WHERE id = $1\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid"+ ]+ },+ "nullable": []+ },+ "hash": "d4eb2c260373b3e0443d494e3b5bea07f5a1732e5eab923c148091838d29f83a"+}diff --git a/.sqlx/query-e4ef4dc39e836e36f9e85606b1af47108c0a71b1d6248543dd6bb015b4207698.json b/.sqlx/query-e4ef4dc39e836e36f9e85606b1af47108c0a71b1d6248543dd6bb015b4207698.jsonnew file mode 100644index 0000000000..ee8c08ba58--- /dev/null+++ b/.sqlx/query-e4ef4dc39e836e36f9e85606b1af47108c0a71b1d6248543dd6bb015b4207698.json@@ -0,0 +1,95 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT\n id,\n description,\n entity_type,\n entity_id,\n remind_at,\n cron,\n timezone,\n next_run_at,\n enabled,\n completed_at,\n created_at,\n updated_at\n FROM reminder\n WHERE user_id = $1\n AND ($2::text IS NULL OR entity_type = $2)\n AND ($3::uuid IS NULL OR entity_id = $3)\n AND ($4::bool OR completed_at IS NULL)\n -- Keyset: resume strictly after the cursor position in the same\n -- (next_run_at, created_at, id) order the query returns.\n AND (\n $5::timestamptz IS NULL\n OR (next_run_at, created_at, id) > ($5::timestamptz, $6::timestamptz, $7::uuid)\n )\n ORDER BY next_run_at ASC, created_at ASC, id ASC\n LIMIT $8\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "id",+ "type_info": "Uuid"+ },+ {+ "ordinal": 1,+ "name": "description",+ "type_info": "Text"+ },+ {+ "ordinal": 2,+ "name": "entity_type",+ "type_info": "Text"+ },+ {+ "ordinal": 3,+ "name": "entity_id",+ "type_info": "Uuid"+ },+ {+ "ordinal": 4,+ "name": "remind_at",+ "type_info": "Timestamptz"+ },+ {+ "ordinal": 5,+ "name": "cron",+ "type_info": "Text"+ },+ {+ "ordinal": 6,+ "name": "timezone",+ "type_info": "Text"+ },+ {+ "ordinal": 7,+ "name": "next_run_at",+ "type_info": "Timestamptz"+ },+ {+ "ordinal": 8,+ "name": "enabled",+ "type_info": "Bool"+ },+ {+ "ordinal": 9,+ "name": "completed_at",+ "type_info": "Timestamptz"+ },+ {+ "ordinal": 10,+ "name": "created_at",+ "type_info": "Timestamptz"+ },+ {+ "ordinal": 11,+ "name": "updated_at",+ "type_info": "Timestamptz"+ }+ ],+ "parameters": {+ "Left": [+ "Text",+ "Text",+ "Uuid",+ "Bool",+ "Timestamptz",+ "Timestamptz",+ "Uuid",+ "Int8"+ ]+ },+ "nullable": [+ false,+ false,+ true,+ true,+ true,+ true,+ true,+ false,+ false,+ true,+ false,+ false+ ]+ },+ "hash": "e4ef4dc39e836e36f9e85606b1af47108c0a71b1d6248543dd6bb015b4207698"+}diff --git a/.sqlx/query-e92f206e8bc0388e1882ff37f6c160deff421b30e2a790050f0079f629263809.json b/.sqlx/query-e92f206e8bc0388e1882ff37f6c160deff421b30e2a790050f0079f629263809.jsonnew file mode 100644index 0000000000..0042ba681c--- /dev/null+++ b/.sqlx/query-e92f206e8bc0388e1882ff37f6c160deff421b30e2a790050f0079f629263809.json@@ -0,0 +1,28 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT id, next_run_at\n FROM reminder\n WHERE enabled\n AND completed_at IS NULL\n AND cron IS NULL\n AND next_run_at <= $1\n ORDER BY next_run_at\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "id",+ "type_info": "Uuid"+ },+ {+ "ordinal": 1,+ "name": "next_run_at",+ "type_info": "Timestamptz"+ }+ ],+ "parameters": {+ "Left": [+ "Timestamptz"+ ]+ },+ "nullable": [+ false,+ false+ ]+ },+ "hash": "e92f206e8bc0388e1882ff37f6c160deff421b30e2a790050f0079f629263809"+}diff --git a/Cargo.lock b/Cargo.lockindex c7a3d346e8..6d9ea77344 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -4503,6 +4503,7 @@ dependencies = ["readonly_pool","redis","regex",+ "reminders","reqwest 0.13.4","rootcause","s3_key",@@ -12189,6 +12190,40 @@ version = "0.8.10"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "dc897dd8d9e8bd1ed8cdad82b5966c3e0ecae09fb1907d58efaa013543185d0a"+[[package]]+name = "reminders"+version = "0.1.0"+dependencies = [+ "aws-sdk-sqs",+ "axum",+ "chrono",+ "chrono-tz",+ "cron",+ "entity_access",+ "http-body-util",+ "macro_authorization",+ "macro_db_migrator",+ "macro_user_id",+ "macro_uuid",+ "model-entity",+ "model-error-response",+ "model_notifications",+ "model_user",+ "notification",+ "rootcause",+ "serde",+ "serde_json",+ "sqlx",+ "thiserror 2.0.18",+ "tokio",+ "tokio-util",+ "tower 0.5.3",+ "tracing",+ "utoipa",+ "uuid",+ "workspace-hack",+]+[[package]]name = "remote_env_var"version = "0.1.0"@@ -16803,6 +16838,7 @@ dependencies = ["percent-encoding","phf 0.13.1","phf_shared 0.10.0",+ "phf_shared 0.11.3","phf_shared 0.13.1","prettyplease","proc-macro2",@@ -16811,6 +16847,7 @@ dependencies = ["rand 0.10.1","rand 0.8.6","rand 0.9.4",+ "rand_core 0.6.4","redis","regex-automata","regex-syntax",diff --git a/Cargo.toml b/Cargo.tomlindex d33cf816aa..a186314028 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -46,6 +46,7 @@ members = ["crates/onboarding","crates/prompt","crates/properties_service",+ "crates/reminders","crates/search_service","crates/soup_realtime","crates/task_dedup",@@ -133,10 +134,12 @@ base64 = "0.22.1"bebop = "3.1.3"cached = { version = "0.54.0", features = ["async_tokio_rt_multi_thread"] }chrono = { version = "0.4.39", features = ["serde"] }+chrono-tz = { version = "0.10.4", features = ["serde"] }clap = { version = "4.5.20", features = ["derive"] }cloudfront_sign = "0.3.0"constant_time_eq = "0.3.1"cookie = "0.18.1"+cron = "0.16.0"csv = "1"dashmap = "6.1.0"dateparser = "0.2.1"diff --git a/apps/web/src/features/entity/extractors-notification/notification-description-helpers.ts b/apps/web/src/features/entity/extractors-notification/notification-description-helpers.tsindex 776f4a8402..444c874fa9 100644--- a/apps/web/src/features/entity/extractors-notification/notification-description-helpers.ts+++ b/apps/web/src/features/entity/extractors-notification/notification-description-helpers.ts@@ -97,28 +97,32 @@ export function getUniqueGithubLogins(notifications: Notification[]): string[] {* @internal*/export function getActionVerb(type: NotificationType): string {- return match(type)- .with('channel_mention', () => 'mentioned you')- .with('document_mention', () => 'shared with you')- .with('mentioned_in_document_comment', () => 'mentioned you')- .with('replied_to_document_comment_thread', () => 'replied')- .with('commented_on_document', () => 'commented')- .with('channel_message_reply', () => 'replied')- .with('channel_message_send', () => 'sent a message')- .with('ai_response', () => 'AI responded')- .with('new_email', () => 'sent an email')- .with('channel_invite', () => 'invited you')- .with('invite_to_team', () => 'invited you')- .with('task_assigned', () => 'assigned you')- .with('github_pr_status_changed', () => 'updated a pull request')- .with('github_pr_check_run', () => 'completed a check')- .with('github_review_requested', () => 'requested your review')- .with('github_pr_comment', () => 'commented on a pull request')- .with('github_pr_mention', () => 'mentioned you on a pull request')- .with('github_pr_review', () => 'reviewed your pull request')- .with('call_started', () => 'started a call')- .with('inbox_reauth_required', () => 'needs reconnection')- .exhaustive();+ return (+ match(type)+ .with('channel_mention', () => 'mentioned you')+ .with('document_mention', () => 'shared with you')+ .with('mentioned_in_document_comment', () => 'mentioned you')+ .with('replied_to_document_comment_thread', () => 'replied')+ .with('commented_on_document', () => 'commented')+ .with('channel_message_reply', () => 'replied')+ .with('channel_message_send', () => 'sent a message')+ .with('ai_response', () => 'AI responded')+ .with('new_email', () => 'sent an email')+ .with('channel_invite', () => 'invited you')+ .with('invite_to_team', () => 'invited you')+ .with('task_assigned', () => 'assigned you')+ .with('github_pr_status_changed', () => 'updated a pull request')+ .with('github_pr_check_run', () => 'completed a check')+ .with('github_review_requested', () => 'requested your review')+ .with('github_pr_comment', () => 'commented on a pull request')+ .with('github_pr_mention', () => 'mentioned you on a pull request')+ .with('github_pr_review', () => 'reviewed your pull request')+ .with('call_started', () => 'started a call')+ // Reads as a standalone phrase, not an actor's action — nobody sent it.+ .with('reminder', () => 'reminder')+ .with('inbox_reauth_required', () => 'needs reconnection')+ .exhaustive()+ );}/**@@ -156,6 +160,7 @@ export function getTypeNoun(type: NotificationType, count: number): string {.with('github_pr_mention', () => (count === 1 ? 'mention' : 'mentions')).with('github_pr_review', () => (count === 1 ? 'review' : 'reviews')).with('call_started', () => (count === 1 ? 'call' : 'calls'))+ .with('reminder', () => (count === 1 ? 'reminder' : 'reminders')).with('inbox_reauth_required', () => (count === 1 ? 'inbox' : 'inboxes')).exhaustive();}diff --git a/apps/web/src/features/entity/extractors-notification/notification-icon.tsx b/apps/web/src/features/entity/extractors-notification/notification-icon.tsxindex c72ec53d63..8f63acf96d 100644--- a/apps/web/src/features/entity/extractors-notification/notification-icon.tsx+++ b/apps/web/src/features/entity/extractors-notification/notification-icon.tsx@@ -4,6 +4,7 @@ import PhoneIcon from '@icon/wide-call.svg';import type { NotificationStack } from '@notifications';import ArrowBendUpLeftIcon from '@phosphor/arrow-bend-up-left.svg';import AtIcon from '@phosphor/at.svg';+import BellIcon from '@phosphor/bell-simple.svg';import ChatIcon from '@phosphor/chat.svg';import CheckIcon from '@phosphor/check.svg';import EnvelopeIcon from '@phosphor/envelope.svg';@@ -52,6 +53,7 @@ function getNotificationIcon(() => GithubIcon).with('call_started', () => PhoneIcon)+ .with('reminder', () => BellIcon).with('inbox_reauth_required', () => EnvelopeIcon).exhaustive();}diff --git a/apps/web/src/features/entity/utils/notification.ts b/apps/web/src/features/entity/utils/notification.tsindex a22c6d4217..4e08526ada 100644--- a/apps/web/src/features/entity/utils/notification.ts+++ b/apps/web/src/features/entity/utils/notification.ts@@ -137,6 +137,7 @@ export function getNotificationActionText(n: Notification): string {.with('github_pr_mention', () => 'mentioned').with('github_pr_review', () => 'reviewed').with('call_started', () => 'called')+ .with('reminder', () => 'reminder').with('inbox_reauth_required', () => 'needs reconnection').exhaustive();}@@ -198,6 +199,7 @@ export function extractMessageContent(notification: Notification): string {.with({ tag: 'channel_invite' }, () => '').with({ tag: 'invite_to_team' }, () => '').with({ tag: 'call_started' }, (m) => m.content.channel_name ?? '')+ .with({ tag: 'reminder' }, (m) => m.content.description).with({ tag: 'inbox_reauth_required' }, (m) => m.content.emailAddress || '').exhaustive();}diff --git a/apps/web/src/features/next-soup/soup-view/views/inbox/inbox-card-layouts.tsx b/apps/web/src/features/next-soup/soup-view/views/inbox/inbox-card-layouts.tsxindex 5874c7e40c..7af0668506 100644--- a/apps/web/src/features/next-soup/soup-view/views/inbox/inbox-card-layouts.tsx+++ b/apps/web/src/features/next-soup/soup-view/views/inbox/inbox-card-layouts.tsx@@ -29,6 +29,7 @@ import GitMergeIcon from '@phosphor/git-merge.svg';import GitPullRequestIcon from '@phosphor/git-pull-request.svg';import ArrowBendUpLeftIcon from '@phosphor-icons/core/regular/arrow-bend-up-left.svg?component-solid';import AtIcon from '@phosphor-icons/core/regular/at.svg?component-solid';+import BellSimpleIcon from '@phosphor-icons/core/regular/bell-simple.svg?component-solid';import ChatCircleIcon from '@phosphor-icons/core/regular/chat-circle.svg?component-solid';import ChatTextIcon from '@phosphor-icons/core/regular/chat-text.svg?component-solid';import PaperclipIcon from '@phosphor-icons/core/regular/paperclip.svg?component-solid';@@ -245,6 +246,7 @@ const tagBubbleIcon = (tag: NotificationTag) =><UserPlusIcon class="size-4" />)).with('call_started', () => () => <PhoneIcon class="size-4" />)+ .with('reminder', () => () => <BellSimpleIcon class="size-4" />).with('github_pr_status_changed','github_pr_check_run',diff --git a/apps/web/src/features/notifications/notification-metadata.ts b/apps/web/src/features/notifications/notification-metadata.tsindex f665d84418..c7d7250364 100644--- a/apps/web/src/features/notifications/notification-metadata.ts+++ b/apps/web/src/features/notifications/notification-metadata.ts@@ -5,151 +5,174 @@ import type { UnifiedNotification } from './types';// Helper functions for derived notification dataexport function getNotificationAction(n: UnifiedNotification): string {- return match(n.notification_metadata.tag)- .with('channel_mention', () => 'mentioned you in')- .with('document_mention', () => {- const meta = n.notification_metadata;- if (- meta.tag === 'document_mention' &&- meta.content.subType?.type === 'task'- ) {- return 'sent a task';- }+ return (+ match(n.notification_metadata.tag)+ .with('channel_mention', () => 'mentioned you in')+ .with('document_mention', () => {+ const meta = n.notification_metadata;+ if (+ meta.tag === 'document_mention' &&+ meta.content.subType?.type === 'task'+ ) {+ return 'sent a task';+ }- return 'sent a document';- })- .with('mentioned_in_document_comment', () => 'mentioned you in')- .with('replied_to_document_comment_thread', () => 'replied in')- .with('commented_on_document', () => 'commented on')- .with('channel_message_send', () => 'sent a message in')- .with('ai_response', () => 'AI responded')- .with('channel_message_reply', () => 'replied in')- .with('call_started', () => 'started a call')- .with('channel_invite', () => 'invited you to')- .with('new_email', () => 'sent a new email')- .with('invite_to_team', () => 'invited you to')- .with('task_assigned', () => 'assigned you a task')- .with('github_pr_status_changed', () => 'updated a pull request')- .with('github_pr_check_run', () => {- const meta = n.notification_metadata;- if (- meta.tag === 'github_pr_check_run' &&- meta.content.state === 'failed'- ) {- return 'failed a check on';- }+ return 'sent a document';+ })+ .with('mentioned_in_document_comment', () => 'mentioned you in')+ .with('replied_to_document_comment_thread', () => 'replied in')+ .with('commented_on_document', () => 'commented on')+ .with('channel_message_send', () => 'sent a message in')+ .with('ai_response', () => 'AI responded')+ .with('channel_message_reply', () => 'replied in')+ .with('call_started', () => 'started a call')+ .with('channel_invite', () => 'invited you to')+ .with('new_email', () => 'sent a new email')+ .with('invite_to_team', () => 'invited you to')+ .with('task_assigned', () => 'assigned you a task')+ // Self-set, so there is no actor — the sentence reads "Reminder about X"+ // rather than "<someone> reminded you about X".+ .with('reminder', () => 'Reminder')+ .with('github_pr_status_changed', () => 'updated a pull request')+ .with('github_pr_check_run', () => {+ const meta = n.notification_metadata;+ if (+ meta.tag === 'github_pr_check_run' &&+ meta.content.state === 'failed'+ ) {+ return 'failed a check on';+ }- return 'completed a check on';- })- .with('github_review_requested', () => 'requested your review on')- .with('github_pr_comment', () => 'commented on')- .with('github_pr_mention', () => 'mentioned you in')- .with('github_pr_review', () => 'reviewed')- .with('inbox_reauth_required', () => 'needs reconnection')- .exhaustive();+ return 'completed a check on';+ })+ .with('github_review_requested', () => 'requested your review on')+ .with('github_pr_comment', () => 'commented on')+ .with('github_pr_mention', () => 'mentioned you in')+ .with('github_pr_review', () => 'reviewed')+ .with('inbox_reauth_required', () => 'needs reconnection')+ .exhaustive()+ );}export function getNotificationTargetName(n: UnifiedNotification): string | undefined {const m = n.notification_metadata;- return match(m)- .with({ tag: 'channel_invite' }, (m) => m.content.channelName)- .with({ tag: 'document_mention' }, (m) => m.content.documentName)- .with(- { tag: 'mentioned_in_document_comment' },- (m) => m.content.documentName- )- .with(- { tag: 'replied_to_document_comment_thread' },- (m) => m.content.documentName- )- .with({ tag: 'commented_on_document' }, (m) => m.content.documentName)- .with({ tag: 'invite_to_team' }, (m) => m.content.teamName)- .with({ tag: 'task_assigned' }, (m) => m.content.taskName ?? undefined)- .with(- { tag: P.union(...GITHUB_EVENT_TYPES) },- (m) => `${m.content.owner}/${m.content.repo}#${m.content.number}`- )- .with({ tag: 'channel_mention' }, () => undefined)- .with({ tag: 'channel_message_send' }, () => undefined)- .with({ tag: 'ai_response' }, () => undefined)- .with({ tag: 'channel_message_reply' }, () => undefined)- .with({ tag: 'call_started' }, (m) => m.content.channel_name ?? undefined)- .with({ tag: 'new_email' }, () => undefined)- .with({ tag: 'inbox_reauth_required' }, () => undefined)- .exhaustive();+ return (+ match(m)+ .with({ tag: 'channel_invite' }, (m) => m.content.channelName)+ .with({ tag: 'document_mention' }, (m) => m.content.documentName)+ .with(+ { tag: 'mentioned_in_document_comment' },+ (m) => m.content.documentName+ )+ .with(+ { tag: 'replied_to_document_comment_thread' },+ (m) => m.content.documentName+ )+ .with({ tag: 'commented_on_document' }, (m) => m.content.documentName)+ .with({ tag: 'invite_to_team' }, (m) => m.content.teamName)+ .with({ tag: 'task_assigned' }, (m) => m.content.taskName ?? undefined)+ .with(+ { tag: P.union(...GITHUB_EVENT_TYPES) },+ (m) => `${m.content.owner}/${m.content.repo}#${m.content.number}`+ )+ .with({ tag: 'channel_mention' }, () => undefined)+ .with({ tag: 'channel_message_send' }, () => undefined)+ .with({ tag: 'ai_response' }, () => undefined)+ .with({ tag: 'channel_message_reply' }, () => undefined)+ .with({ tag: 'call_started' }, (m) => m.content.channel_name ?? undefined)+ .with({ tag: 'new_email' }, () => undefined)+ // The reminder's entity name is resolved from the notification's entity,+ // not carried in the metadata.+ .with({ tag: 'reminder' }, () => undefined)+ .with({ tag: 'inbox_reauth_required' }, () => undefined)+ .exhaustive()+ );}export function getNotificationContent(n: UnifiedNotification): string | undefined {const m = n.notification_metadata;- return match(m)- .with({ tag: 'channel_mention' }, (m) => m.content.messageContent)- .with({ tag: 'channel_message_send' }, (m) => m.content.messageContent)- .with({ tag: 'ai_response' }, (m) => m.content.summary)- .with({ tag: 'channel_message_reply' }, (m) => m.content.messageContent)- .with({ tag: 'call_started' }, () => undefined)- .with({ tag: 'document_mention' }, (m) => m.content.documentName)- .with({ tag: 'mentioned_in_document_comment' }, (m) => m.content.text)- .with({ tag: 'replied_to_document_comment_thread' }, (m) => m.content.text)- .with({ tag: 'commented_on_document' }, (m) => m.content.text)- .with({ tag: 'new_email' }, (m) => m.content.subject)- .with({ tag: 'task_assigned' }, (m) => m.content.taskName ?? undefined)- .with(- { tag: P.union('github_pr_status_changed', 'github_review_requested') },- (m) => m.content.title || m.content.displayName- )- .with(- { tag: 'github_pr_check_run' },- (m) => m.content.checkName || m.content.title || m.content.displayName- )- .with(- { tag: 'github_pr_comment' },- (m) =>- m.content.commentSnippet || m.content.title || m.content.displayName- )- .with(- { tag: 'github_pr_mention' },- (m) => m.content.textSnippet || m.content.title || m.content.displayName- )- .with(- { tag: 'github_pr_review' },- (m) => m.content.reviewSnippet || m.content.title || m.content.displayName- )- .with({ tag: 'channel_invite' }, () => undefined)- .with({ tag: 'invite_to_team' }, () => undefined)- .with({ tag: 'inbox_reauth_required' }, (m) => m.content.emailAddress)- .exhaustive();+ return (+ match(m)+ .with({ tag: 'channel_mention' }, (m) => m.content.messageContent)+ .with({ tag: 'channel_message_send' }, (m) => m.content.messageContent)+ .with({ tag: 'ai_response' }, (m) => m.content.summary)+ .with({ tag: 'channel_message_reply' }, (m) => m.content.messageContent)+ .with({ tag: 'call_started' }, () => undefined)+ .with({ tag: 'document_mention' }, (m) => m.content.documentName)+ .with({ tag: 'mentioned_in_document_comment' }, (m) => m.content.text)+ .with(+ { tag: 'replied_to_document_comment_thread' },+ (m) => m.content.text+ )+ .with({ tag: 'commented_on_document' }, (m) => m.content.text)+ .with({ tag: 'new_email' }, (m) => m.content.subject)+ .with({ tag: 'task_assigned' }, (m) => m.content.taskName ?? undefined)+ .with(+ { tag: P.union('github_pr_status_changed', 'github_review_requested') },+ (m) => m.content.title || m.content.displayName+ )+ .with(+ { tag: 'github_pr_check_run' },+ (m) => m.content.checkName || m.content.title || m.content.displayName+ )+ .with(+ { tag: 'github_pr_comment' },+ (m) =>+ m.content.commentSnippet || m.content.title || m.content.displayName+ )+ .with(+ { tag: 'github_pr_mention' },+ (m) => m.content.textSnippet || m.content.title || m.content.displayName+ )+ .with(+ { tag: 'github_pr_review' },+ (m) =>+ m.content.reviewSnippet || m.content.title || m.content.displayName+ )+ .with({ tag: 'channel_invite' }, () => undefined)+ .with({ tag: 'invite_to_team' }, () => undefined)+ // The description the user wrote is the whole point of a reminder.+ .with({ tag: 'reminder' }, (m) => m.content.description)+ .with({ tag: 'inbox_reauth_required' }, (m) => m.content.emailAddress)+ .exhaustive()+ );}export function shouldShowNotificationTarget(n: UnifiedNotification): boolean {const m = n.notification_metadata;- return match(m)- .with(- { tag: 'channel_mention' },- (m) => m.content.channelType !== 'directMessage'- )- .with(- { tag: 'channel_message_send' },- (m) => m.content.channelType !== 'directMessage'- )- .with(- { tag: 'channel_message_reply' },- (m) => m.content.channelType !== 'directMessage'- )- .with({ tag: 'ai_response' }, () => false)- .with({ tag: 'call_started' }, () => true)- .with({ tag: 'new_email' }, () => false)- .with({ tag: 'task_assigned' }, () => true)- .with({ tag: P.union(...GITHUB_EVENT_TYPES) }, () => true)- .with({ tag: 'document_mention' }, () => true)- .with({ tag: 'mentioned_in_document_comment' }, () => true)- .with({ tag: 'replied_to_document_comment_thread' }, () => true)- .with({ tag: 'commented_on_document' }, () => true)- .with({ tag: 'channel_invite' }, () => true)- .with({ tag: 'invite_to_team' }, () => true)- .with({ tag: 'inbox_reauth_required' }, () => false)- .exhaustive();+ return (+ match(m)+ .with(+ { tag: 'channel_mention' },+ (m) => m.content.channelType !== 'directMessage'+ )+ .with(+ { tag: 'channel_message_send' },+ (m) => m.content.channelType !== 'directMessage'+ )+ .with(+ { tag: 'channel_message_reply' },+ (m) => m.content.channelType !== 'directMessage'+ )+ .with({ tag: 'ai_response' }, () => false)+ .with({ tag: 'call_started' }, () => true)+ .with({ tag: 'new_email' }, () => false)+ .with({ tag: 'task_assigned' }, () => true)+ .with({ tag: P.union(...GITHUB_EVENT_TYPES) }, () => true)+ .with({ tag: 'document_mention' }, () => true)+ .with({ tag: 'mentioned_in_document_comment' }, () => true)+ .with({ tag: 'replied_to_document_comment_thread' }, () => true)+ .with({ tag: 'commented_on_document' }, () => true)+ .with({ tag: 'channel_invite' }, () => true)+ .with({ tag: 'invite_to_team' }, () => true)+ // Shown so "Reminder" reads as being about something; a standalone+ // reminder resolves to no target name and renders without one anyway.+ .with({ tag: 'reminder' }, () => true)+ .with({ tag: 'inbox_reauth_required' }, () => false)+ .exhaustive()+ );}diff --git a/apps/web/src/features/notifications/notification-navigation.ts b/apps/web/src/features/notifications/notification-navigation.tsindex f197993018..60c56b6009 100644--- a/apps/web/src/features/notifications/notification-navigation.ts+++ b/apps/web/src/features/notifications/notification-navigation.ts@@ -15,13 +15,14 @@ import {resolveBlockAlias,} from '@core/constant/allBlocks';import { USE_MACRO_PR_SUMMARY_BLOCK } from '@core/constant/featureFlags';-import type { NotificationType } from '@core/types';+import type { EntityType, NotificationType } from '@core/types';import { openExternalUrl } from '@core/util/url';import { getNotificationById } from '@queries/notification/user-notifications';import { errAsync, ResultAsync } from 'neverthrow';import { match, P } from 'ts-pattern';import { GITHUB_EVENT_TYPES } from './github-event-types';import { isChannelNotification } from './notification-helpers';+import { DefaultNotificationBlockNameResolver } from './notification-resolvers';import type { NotificationSource } from './notification-source';import { CHANNEL_EVENT_TYPES } from './notification-source';import {@@ -359,6 +360,26 @@ function getSupportedHandler(sourceHandle,});})+ .with('reminder', () => {+ // A reminder carries no entity details of its own — it points at+ // whatever it was set on, and that lives on the notification. A+ // standalone reminder is addressed at the user and has nothing to open.+ const entityType = notification.entity_type as EntityType;+ if (entityType === 'user') return null;++ return async (lm: SplitManager, newSplit: boolean = false) => {+ const blockName = await DefaultNotificationBlockNameResolver(+ notification.entity_id,+ entityType+ );+ if (!blockName) return;++ openSplitIfNotOpen(lm, blockName, notification.entity_id, {+ newSplit,+ sourceHandle,+ });+ };+ }).with('inbox_reauth_required', () => null).exhaustive();}diff --git a/apps/web/src/features/notifications/notification-preview.ts b/apps/web/src/features/notifications/notification-preview.tsindex 8a1b44c1da..20d69f4e9a 100644--- a/apps/web/src/features/notifications/notification-preview.ts+++ b/apps/web/src/features/notifications/notification-preview.ts@@ -20,5 +20,6 @@ export const NOTIFICATION_LABEL_BY_TYPE: Record<NotificationType, string> = {github_pr_mention: 'MENTION',github_pr_review: 'REVIEW',call_started: 'CALL',+ reminder: 'REMINDER',inbox_reauth_required: 'EMAIL',} as const;diff --git a/apps/web/src/lib/core/constant/featureFlags.ts b/apps/web/src/lib/core/constant/featureFlags.tsindex b7b3e7370f..3acac8aa8d 100644--- a/apps/web/src/lib/core/constant/featureFlags.ts+++ b/apps/web/src/lib/core/constant/featureFlags.ts@@ -170,6 +170,40 @@ export function ENABLE_CRM(): boolean {return analytics.posthog.isFeatureEnabled(ENABLE_CRM_FLAG) ?? false;}+// Reminders: the "Remind me about this" entry in the command menu, the soup+// context menu and the block ⋯ menu, its 'h' shortcut, and the composer modal.+// Every surface routes through `makeCreateReminderAction().canExecute`, so this+// is the single gate for all of them. PostHog-gated with a dev-mode default.+export const ENABLE_REMINDERS_FLAG = 'enable-reminders';+// Read statically rather than through `getFeatureFlagOverride`: Vite replaces+// `import.meta.env.VITE_X` by text substitution at build time, so the dynamic+// `import.meta.env[key]` lookup that helper does can come back undefined in a+// production bundle. Same form as VITE_ENABLE_BROWSER_OTEL in observability/.+//+// Written out rather than using `|| undefined` so an explicit+// VITE_ENABLE_REMINDERS=false stays false instead of being coerced to undefined+// and falling through to PostHog.+const REMINDERS_ENV_OVERRIDE = import.meta.env.VITE_ENABLE_REMINDERS;+export const ENABLE_REMINDERS_OVERRIDE: boolean | undefined =+ REMINDERS_ENV_OVERRIDE === 'true'+ ? true+ : REMINDERS_ENV_OVERRIDE === 'false'+ ? false+ : DEV_MODE_ENV+ ? true+ : undefined;++/**+ * Non-reactive check for imperative call sites. For reactive UI, prefer+ * `useFeatureFlag(ENABLE_REMINDERS_FLAG, { enabledOverride: ENABLE_REMINDERS_OVERRIDE })`.+ */+export function ENABLE_REMINDERS(): boolean {+ if (ENABLE_REMINDERS_OVERRIDE !== undefined) {+ return ENABLE_REMINDERS_OVERRIDE;+ }+ return analytics.posthog.isFeatureEnabled(ENABLE_REMINDERS_FLAG) ?? false;+}+export const ENABLE_BLOCK_IN_BLOCK = resolveFeatureFlag('ENABLE_BLOCK_IN_BLOCK',truediff --git a/apps/web/src/lib/queries/notification/user-notifications.ts b/apps/web/src/lib/queries/notification/user-notifications.tsindex dcf4e61534..a36aed9f10 100644--- a/apps/web/src/lib/queries/notification/user-notifications.ts+++ b/apps/web/src/lib/queries/notification/user-notifications.ts@@ -871,7 +871,10 @@ function notificationEntityTypeToSoupTag('static_file','crm_company','crm_contact',- 'calendar_event'+ 'calendar_event',+ // A reminder notification is keyed by the reminder itself, which has+ // no soup entity to map to here.+ 'reminder'),() => null)diff --git a/apps/web/src/lib/queries/reminders/keys.ts b/apps/web/src/lib/queries/reminders/keys.tsnew file mode 100644index 0000000000..d6df233e87--- /dev/null+++ b/apps/web/src/lib/queries/reminders/keys.ts@@ -0,0 +1,5 @@+import { createQueryKeys } from '@lukemorales/query-key-factory';++export const reminderKeys = createQueryKeys('reminders', {+ list: null,+});diff --git a/apps/web/src/lib/queries/reminders/reminders.ts b/apps/web/src/lib/queries/reminders/reminders.tsnew file mode 100644index 0000000000..5540fa3d03--- /dev/null+++ b/apps/web/src/lib/queries/reminders/reminders.ts@@ -0,0 +1,83 @@+import { throwOnErr } from '@core/util/result';+import type { EntityData } from '@entity';+import { storageServiceClient } from '@service-storage/client';+import type { CreateReminderRequest } from '@service-storage/generated/schemas/createReminderRequest';+import type { Reminder } from '@service-storage/generated/schemas/reminder';+import { useMutation } from '@tanstack/solid-query';++import { queryClient } from '../client';+import { type MutationCallbacks, withCallbacks } from '../utils';++import { reminderKeys } from './keys';++/** The entity types a reminder can be attached to, as the API names them. */+export type ReminderEntityType = NonNullable<+ CreateReminderRequest['entityType']+>;++/**+ * Maps a frontend entity to the backend reminder entity type, or undefined for+ * entity kinds a reminder cannot be attached to.+ *+ * Mirrors `favoriteEntityType`: both are gated by what the entity-access layer+ * can resolve an access level for, so the two lists move together.+ */+export function reminderEntityType(+ type: EntityData['type']+): ReminderEntityType | undefined {+ switch (type) {+ case 'document':+ return 'document';+ case 'chat':+ return 'chat';+ case 'project':+ return 'project';+ case 'email':+ return 'email_thread';+ case 'channel':+ return 'channel';+ case 'call':+ return 'call';+ case 'crm_company':+ return 'crm_company';+ case 'crm_contact':+ return 'crm_contact';+ // Channel messages and threads are excluded for the same reason favorites+ // excludes them: their frontend id is a composite `channelId:messageId`+ // that the entity-access layer has no access level for.+ default:+ return undefined;+ }+}++type CreateReminderArgs = CreateReminderRequest;+type CreateReminderCallbacks = MutationCallbacks<+ Reminder,+ Error,+ CreateReminderArgs+>;++/**+ * Create a reminder.+ *+ * Not optimistic: nothing renders a reminder list yet, so there is no cache to+ * update ahead of the server. The list key is invalidated so whatever reads it+ * first sees the new row.+ */+export function useCreateReminderMutation(callbacks?: CreateReminderCallbacks) {+ return useMutation(() => ({+ mutationFn: async (args: CreateReminderArgs) =>+ await throwOnErr(() =>+ storageServiceClient.reminders.createReminder(args)+ ),+ ...withCallbacks<Reminder, Error, CreateReminderArgs>(+ {+ onSettled: () =>+ queryClient.invalidateQueries({+ queryKey: reminderKeys.list.queryKey,+ }),+ },+ callbacks+ ),+ }));+}diff --git a/apps/web/src/lib/service-clients/service-cognition/generated/schemas/entityType.ts b/apps/web/src/lib/service-clients/service-cognition/generated/schemas/entityType.tsindex e156e9c797..9557256b10 100644--- a/apps/web/src/lib/service-clients/service-cognition/generated/schemas/entityType.ts+++ b/apps/web/src/lib/service-clients/service-cognition/generated/schemas/entityType.ts@@ -26,4 +26,5 @@ export const EntityType = {static_file: 'static_file',crm_company: 'crm_company',crm_contact: 'crm_contact',+ reminder: 'reminder',} as const;diff --git a/apps/web/src/lib/service-clients/service-cognition/openapi.json b/apps/web/src/lib/service-clients/service-cognition/openapi.jsonindex b9e70fac6c..917b516d35 100644--- a/apps/web/src/lib/service-clients/service-cognition/openapi.json+++ b/apps/web/src/lib/service-clients/service-cognition/openapi.json@@ -2626,7 +2626,8 @@"foreign_entity","static_file","crm_company",- "crm_contact"+ "crm_contact",+ "reminder"]},"ErrorBody": {diff --git a/apps/web/src/lib/service-clients/service-connection/generated/schemas/entityType.ts b/apps/web/src/lib/service-clients/service-connection/generated/schemas/entityType.tsindex c944885a4d..8c089fb361 100644--- a/apps/web/src/lib/service-clients/service-connection/generated/schemas/entityType.ts+++ b/apps/web/src/lib/service-clients/service-connection/generated/schemas/entityType.ts@@ -26,4 +26,5 @@ export const EntityType = {static_file: 'static_file',crm_company: 'crm_company',crm_contact: 'crm_contact',+ reminder: 'reminder',} as const;diff --git a/apps/web/src/lib/service-clients/service-connection/openapi.json b/apps/web/src/lib/service-clients/service-connection/openapi.jsonindex 7b8df2626d..aef453ef56 100644--- a/apps/web/src/lib/service-clients/service-connection/openapi.json+++ b/apps/web/src/lib/service-clients/service-connection/openapi.json@@ -258,7 +258,8 @@"foreign_entity","static_file","crm_company",- "crm_contact"+ "crm_contact",+ "reminder"]},"GenericErrorResponse": {diff --git a/apps/web/src/lib/service-clients/service-notification/generated/schemas/entityType.ts b/apps/web/src/lib/service-clients/service-notification/generated/schemas/entityType.tsindex 0dcfae3dd0..39669e2fa4 100644--- a/apps/web/src/lib/service-clients/service-notification/generated/schemas/entityType.ts+++ b/apps/web/src/lib/service-clients/service-notification/generated/schemas/entityType.ts@@ -26,4 +26,5 @@ export const EntityType = {static_file: 'static_file',crm_company: 'crm_company',crm_contact: 'crm_contact',+ reminder: 'reminder',} as const;diff --git a/apps/web/src/lib/service-clients/service-notification/generated/schemas/index.ts b/apps/web/src/lib/service-clients/service-notification/generated/schemas/index.tsindex 1c8e597250..f338a9898e 100644--- a/apps/web/src/lib/service-clients/service-notification/generated/schemas/index.ts+++ b/apps/web/src/lib/service-clients/service-notification/generated/schemas/index.ts@@ -117,6 +117,8 @@ export * from './notifEvent';export * from './notifEventOneOf';export * from './notifEventOneOfFive';export * from './notifEventOneOfFiveTag';+export * from './notifEventOneOfFourone';+export * from './notifEventOneOfFouroneTag';export * from './notifEventOneOfNine';export * from './notifEventOneOfNineTag';export * from './notifEventOneOfOnefive';@@ -164,6 +166,7 @@ export * from './notificationServiceApiVersion';export * from './notificationTypeName';export * from './pushNotificationData';export * from './pushNotificationDataSenderProfilePictureUrl';+export * from './reminderMetadata';export * from './repliedToDocumentCommentThreadMetadata';export * from './repliedToDocumentCommentThreadMetadataFileType';export * from './repliedToDocumentCommentThreadMetadataSenderProfilePictureUrl';diff --git a/apps/web/src/lib/service-clients/service-notification/generated/schemas/notifEvent.ts b/apps/web/src/lib/service-clients/service-notification/generated/schemas/notifEvent.tsindex e7fbf0831c..5013fac496 100644--- a/apps/web/src/lib/service-clients/service-notification/generated/schemas/notifEvent.ts+++ b/apps/web/src/lib/service-clients/service-notification/generated/schemas/notifEvent.ts@@ -6,6 +6,7 @@*/import type { NotifEventOneOf } from './notifEventOneOf';import type { NotifEventOneOfFive } from './notifEventOneOfFive';+import type { NotifEventOneOfFourone } from './notifEventOneOfFourone';import type { NotifEventOneOfNine } from './notifEventOneOfNine';import type { NotifEventOneOfOnefive } from './notifEventOneOfOnefive';import type { NotifEventOneOfOnenine } from './notifEventOneOfOnenine';@@ -53,4 +54,5 @@ export type NotifEvent =| NotifEventOneOfThreethree| NotifEventOneOfThreefive| NotifEventOneOfThreeseven- | NotifEventOneOfThreenine;+ | NotifEventOneOfThreenine+ | NotifEventOneOfFourone;diff --git a/apps/web/src/lib/service-clients/service-notification/generated/schemas/notifEventOneOfFourone.ts b/apps/web/src/lib/service-clients/service-notification/generated/schemas/notifEventOneOfFourone.tsnew file mode 100644index 0000000000..8ac2c3e970--- /dev/null+++ b/apps/web/src/lib/service-clients/service-notification/generated/schemas/notifEventOneOfFourone.ts@@ -0,0 +1,17 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * notification_service+ * OpenAPI spec version: 0.1.0+ */+import type { GithubPrReview } from './githubPrReview';+import type { NotifEventOneOfFouroneTag } from './notifEventOneOfFouroneTag';++/**+ * A review was submitted on the user's GitHub pull request.+ */+export type NotifEventOneOfFourone = {+ /** A review was submitted on the user's GitHub pull request. */+ content: GithubPrReview;+ tag: NotifEventOneOfFouroneTag;+};diff --git a/apps/web/src/lib/service-clients/service-notification/generated/schemas/notifEventOneOfFouroneTag.ts b/apps/web/src/lib/service-clients/service-notification/generated/schemas/notifEventOneOfFouroneTag.tsnew file mode 100644index 0000000000..0f462f7fc5--- /dev/null+++ b/apps/web/src/lib/service-clients/service-notification/generated/schemas/notifEventOneOfFouroneTag.ts@@ -0,0 +1,14 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * notification_service+ * OpenAPI spec version: 0.1.0+ */++export type NotifEventOneOfFouroneTag =+ (typeof NotifEventOneOfFouroneTag)[keyof typeof NotifEventOneOfFouroneTag];++// eslint-disable-next-line @typescript-eslint/no-redeclare+export const NotifEventOneOfFouroneTag = {+ github_pr_review: 'github_pr_review',+} as const;diff --git a/apps/web/src/lib/service-clients/service-notification/generated/schemas/notifEventOneOfThreefive.ts b/apps/web/src/lib/service-clients/service-notification/generated/schemas/notifEventOneOfThreefive.tsindex d8a2974a89..2cf39b7de0 100644--- a/apps/web/src/lib/service-clients/service-notification/generated/schemas/notifEventOneOfThreefive.ts+++ b/apps/web/src/lib/service-clients/service-notification/generated/schemas/notifEventOneOfThreefive.ts@@ -4,14 +4,14 @@* notification_service* OpenAPI spec version: 0.1.0*/-import type { GithubPrComment } from './githubPrComment';+import type { GithubReviewRequested } from './githubReviewRequested';import type { NotifEventOneOfThreefiveTag } from './notifEventOneOfThreefiveTag';/**- * A GitHub pull request was commented on.+ * The user's review was requested on a GitHub pull request.*/export type NotifEventOneOfThreefive = {- /** A GitHub pull request was commented on. */- content: GithubPrComment;+ /** The user's review was requested on a GitHub pull request. */+ content: GithubReviewRequested;tag: NotifEventOneOfThreefiveTag;};diff --git a/apps/web/src/lib/service-clients/service-notification/generated/schemas/notifEventOneOfThreefiveTag.ts b/apps/web/src/lib/service-clients/service-notification/generated/schemas/notifEventOneOfThreefiveTag.tsindex c37e9455bb..a32d8970fd 100644--- a/apps/web/src/lib/service-clients/service-notification/generated/schemas/notifEventOneOfThreefiveTag.ts+++ b/apps/web/src/lib/service-clients/service-notification/generated/schemas/notifEventOneOfThreefiveTag.ts@@ -10,5 +10,5 @@ export type NotifEventOneOfThreefiveTag =// eslint-disable-next-line @typescript-eslint/no-redeclareexport const NotifEventOneOfThreefiveTag = {- github_pr_comment: 'github_pr_comment',+ github_review_requested: 'github_review_requested',} as const;diff --git a/apps/web/src/lib/service-clients/service-notification/generated/schemas/notifEventOneOfThreenine.ts b/apps/web/src/lib/service-clients/service-notification/generated/schemas/notifEventOneOfThreenine.tsindex a047607e0e..a50a45a29a 100644--- a/apps/web/src/lib/service-clients/service-notification/generated/schemas/notifEventOneOfThreenine.ts+++ b/apps/web/src/lib/service-clients/service-notification/generated/schemas/notifEventOneOfThreenine.ts@@ -4,14 +4,14 @@* notification_service* OpenAPI spec version: 0.1.0*/-import type { GithubPrReview } from './githubPrReview';+import type { GithubPrMention } from './githubPrMention';import type { NotifEventOneOfThreenineTag } from './notifEventOneOfThreenineTag';/**- * A review was submitted on the user's GitHub pull request.+ * The user was mentioned on a GitHub pull request.*/export type NotifEventOneOfThreenine = {- /** A review was submitted on the user's GitHub pull request. */- content: GithubPrReview;+ /** The user was mentioned on a GitHub pull request. */+ content: GithubPrMention;tag: NotifEventOneOfThreenineTag;};diff --git a/apps/web/src/lib/service-clients/service-notification/generated/schemas/notifEventOneOfThreenineTag.ts b/apps/web/src/lib/service-clients/service-notification/generated/schemas/notifEventOneOfThreenineTag.tsindex 99744b055a..5fecc9bc8a 100644--- a/apps/web/src/lib/service-clients/service-notification/generated/schemas/notifEventOneOfThreenineTag.ts+++ b/apps/web/src/lib/service-clients/service-notification/generated/schemas/notifEventOneOfThreenineTag.ts@@ -10,5 +10,5 @@ export type NotifEventOneOfThreenineTag =// eslint-disable-next-line @typescript-eslint/no-redeclareexport const NotifEventOneOfThreenineTag = {- github_pr_review: 'github_pr_review',+ github_pr_mention: 'github_pr_mention',} as const;diff --git a/apps/web/src/lib/service-clients/service-notification/generated/schemas/notifEventOneOfThreeone.ts b/apps/web/src/lib/service-clients/service-notification/generated/schemas/notifEventOneOfThreeone.tsindex 8f5e3836b5..9c1f5901af 100644--- a/apps/web/src/lib/service-clients/service-notification/generated/schemas/notifEventOneOfThreeone.ts+++ b/apps/web/src/lib/service-clients/service-notification/generated/schemas/notifEventOneOfThreeone.ts@@ -4,14 +4,20 @@* notification_service* OpenAPI spec version: 0.1.0*/-import type { GithubPrCheckRun } from './githubPrCheckRun';+import type { GithubPrStatusChanged } from './githubPrStatusChanged';import type { NotifEventOneOfThreeoneTag } from './notifEventOneOfThreeoneTag';/**- * A GitHub pull request check run completed.+ * A GitHub pull request changed lifecycle state.++The `github_pr_event` alias keeps rows and queue messages persisted+before the rename deserializable.*/export type NotifEventOneOfThreeone = {- /** A GitHub pull request check run completed. */- content: GithubPrCheckRun;+ /** A GitHub pull request changed lifecycle state.++The `github_pr_event` alias keeps rows and queue messages persisted+before the rename deserializable. */+ content: GithubPrStatusChanged;tag: NotifEventOneOfThreeoneTag;};diff --git a/apps/web/src/lib/service-clients/service-notification/generated/schemas/notifEventOneOfThreeoneTag.ts b/apps/web/src/lib/service-clients/service-notification/generated/schemas/notifEventOneOfThreeoneTag.tsindex 770eac2aa1..7b3969fffe 100644--- a/apps/web/src/lib/service-clients/service-notification/generated/schemas/notifEventOneOfThreeoneTag.ts+++ b/apps/web/src/lib/service-clients/service-notification/generated/schemas/notifEventOneOfThreeoneTag.ts@@ -10,5 +10,5 @@ export type NotifEventOneOfThreeoneTag =// eslint-disable-next-line @typescript-eslint/no-redeclareexport const NotifEventOneOfThreeoneTag = {- github_pr_check_run: 'github_pr_check_run',+ github_pr_status_changed: 'github_pr_status_changed',} as const;diff --git a/apps/web/src/lib/service-clients/service-notification/generated/schemas/notifEventOneOfThreeseven.ts b/apps/web/src/lib/service-clients/service-notification/generated/schemas/notifEventOneOfThreeseven.tsindex bd91373448..6cfbc874a1 100644--- a/apps/web/src/lib/service-clients/service-notification/generated/schemas/notifEventOneOfThreeseven.ts+++ b/apps/web/src/lib/service-clients/service-notification/generated/schemas/notifEventOneOfThreeseven.ts@@ -4,14 +4,14 @@* notification_service* OpenAPI spec version: 0.1.0*/-import type { GithubPrMention } from './githubPrMention';+import type { GithubPrComment } from './githubPrComment';import type { NotifEventOneOfThreesevenTag } from './notifEventOneOfThreesevenTag';/**- * The user was mentioned on a GitHub pull request.+ * A GitHub pull request was commented on.*/export type NotifEventOneOfThreeseven = {- /** The user was mentioned on a GitHub pull request. */- content: GithubPrMention;+ /** A GitHub pull request was commented on. */+ content: GithubPrComment;tag: NotifEventOneOfThreesevenTag;};diff --git a/apps/web/src/lib/service-clients/service-notification/generated/schemas/notifEventOneOfThreesevenTag.ts b/apps/web/src/lib/service-clients/service-notification/generated/schemas/notifEventOneOfThreesevenTag.tsindex 6b6310db4c..01d1a0e432 100644--- a/apps/web/src/lib/service-clients/service-notification/generated/schemas/notifEventOneOfThreesevenTag.ts+++ b/apps/web/src/lib/service-clients/service-notification/generated/schemas/notifEventOneOfThreesevenTag.ts@@ -10,5 +10,5 @@ export type NotifEventOneOfThreesevenTag =// eslint-disable-next-line @typescript-eslint/no-redeclareexport const NotifEventOneOfThreesevenTag = {- github_pr_mention: 'github_pr_mention',+ github_pr_comment: 'github_pr_comment',} as const;diff --git a/apps/web/src/lib/service-clients/service-notification/generated/schemas/notifEventOneOfThreethree.ts b/apps/web/src/lib/service-clients/service-notification/generated/schemas/notifEventOneOfThreethree.tsindex e275efc12b..e0bfcdc44d 100644--- a/apps/web/src/lib/service-clients/service-notification/generated/schemas/notifEventOneOfThreethree.ts+++ b/apps/web/src/lib/service-clients/service-notification/generated/schemas/notifEventOneOfThreethree.ts@@ -4,14 +4,14 @@* notification_service* OpenAPI spec version: 0.1.0*/-import type { GithubReviewRequested } from './githubReviewRequested';+import type { GithubPrCheckRun } from './githubPrCheckRun';import type { NotifEventOneOfThreethreeTag } from './notifEventOneOfThreethreeTag';/**- * The user's review was requested on a GitHub pull request.+ * A GitHub pull request check run completed.*/export type NotifEventOneOfThreethree = {- /** The user's review was requested on a GitHub pull request. */- content: GithubReviewRequested;+ /** A GitHub pull request check run completed. */+ content: GithubPrCheckRun;tag: NotifEventOneOfThreethreeTag;};diff --git a/apps/web/src/lib/service-clients/service-notification/generated/schemas/notifEventOneOfThreethreeTag.ts b/apps/web/src/lib/service-clients/service-notification/generated/schemas/notifEventOneOfThreethreeTag.tsindex 56736f6ffe..3b9ab3068f 100644--- a/apps/web/src/lib/service-clients/service-notification/generated/schemas/notifEventOneOfThreethreeTag.ts+++ b/apps/web/src/lib/service-clients/service-notification/generated/schemas/notifEventOneOfThreethreeTag.ts@@ -10,5 +10,5 @@ export type NotifEventOneOfThreethreeTag =// eslint-disable-next-line @typescript-eslint/no-redeclareexport const NotifEventOneOfThreethreeTag = {- github_review_requested: 'github_review_requested',+ github_pr_check_run: 'github_pr_check_run',} as const;diff --git a/apps/web/src/lib/service-clients/service-notification/generated/schemas/notifEventOneOfTwonine.ts b/apps/web/src/lib/service-clients/service-notification/generated/schemas/notifEventOneOfTwonine.tsindex d8689b03a9..6f82bd95a5 100644--- a/apps/web/src/lib/service-clients/service-notification/generated/schemas/notifEventOneOfTwonine.ts+++ b/apps/web/src/lib/service-clients/service-notification/generated/schemas/notifEventOneOfTwonine.ts@@ -4,20 +4,14 @@* notification_service* OpenAPI spec version: 0.1.0*/-import type { GithubPrStatusChanged } from './githubPrStatusChanged';+import type { AiResponseMetadata } from './aiResponseMetadata';import type { NotifEventOneOfTwonineTag } from './notifEventOneOfTwonineTag';/**- * A GitHub pull request changed lifecycle state.--The `github_pr_event` alias keeps rows and queue messages persisted-before the rename deserializable.+ * An AI assistant responded to a chat.*/export type NotifEventOneOfTwonine = {- /** A GitHub pull request changed lifecycle state.--The `github_pr_event` alias keeps rows and queue messages persisted-before the rename deserializable. */- content: GithubPrStatusChanged;+ /** An AI assistant responded to a chat. */+ content: AiResponseMetadata;tag: NotifEventOneOfTwonineTag;};diff --git a/apps/web/src/lib/service-clients/service-notification/generated/schemas/notifEventOneOfTwonineTag.ts b/apps/web/src/lib/service-clients/service-notification/generated/schemas/notifEventOneOfTwonineTag.tsindex de1d24335d..7d2e1a591a 100644--- a/apps/web/src/lib/service-clients/service-notification/generated/schemas/notifEventOneOfTwonineTag.ts+++ b/apps/web/src/lib/service-clients/service-notification/generated/schemas/notifEventOneOfTwonineTag.ts@@ -10,5 +10,5 @@ export type NotifEventOneOfTwonineTag =// eslint-disable-next-line @typescript-eslint/no-redeclareexport const NotifEventOneOfTwonineTag = {- github_pr_status_changed: 'github_pr_status_changed',+ ai_response: 'ai_response',} as const;diff --git a/apps/web/src/lib/service-clients/service-notification/generated/schemas/notifEventOneOfTwoseven.ts b/apps/web/src/lib/service-clients/service-notification/generated/schemas/notifEventOneOfTwoseven.tsindex 572e486a27..ccc2c630e8 100644--- a/apps/web/src/lib/service-clients/service-notification/generated/schemas/notifEventOneOfTwoseven.ts+++ b/apps/web/src/lib/service-clients/service-notification/generated/schemas/notifEventOneOfTwoseven.ts@@ -4,14 +4,15 @@* notification_service* OpenAPI spec version: 0.1.0*/-import type { AiResponseMetadata } from './aiResponseMetadata';+import type { NotifEventOneOfTwosevenTag } from './notifEventOneOfTwosevenTag';+import type { ReminderMetadata } from './reminderMetadata';/**- * An AI assistant responded to a chat.+ * A reminder the user set for themselves came due.*/export type NotifEventOneOfTwoseven = {- /** An AI assistant responded to a chat. */- content: AiResponseMetadata;+ /** A reminder the user set for themselves came due. */+ content: ReminderMetadata;tag: NotifEventOneOfTwosevenTag;};diff --git a/apps/web/src/lib/service-clients/service-notification/generated/schemas/notifEventOneOfTwosevenTag.ts b/apps/web/src/lib/service-clients/service-notification/generated/schemas/notifEventOneOfTwosevenTag.tsindex 8a0edc14dc..e44784f48f 100644--- a/apps/web/src/lib/service-clients/service-notification/generated/schemas/notifEventOneOfTwosevenTag.ts+++ b/apps/web/src/lib/service-clients/service-notification/generated/schemas/notifEventOneOfTwosevenTag.ts@@ -10,5 +10,5 @@ export type NotifEventOneOfTwosevenTag =// eslint-disable-next-line @typescript-eslint/no-redeclareexport const NotifEventOneOfTwosevenTag = {- ai_response: 'ai_response',+ reminder: 'reminder',} as const;diff --git a/apps/web/src/lib/service-clients/service-notification/generated/schemas/reminderMetadata.ts b/apps/web/src/lib/service-clients/service-notification/generated/schemas/reminderMetadata.tsnew file mode 100644index 0000000000..39e3ca50f1--- /dev/null+++ b/apps/web/src/lib/service-clients/service-notification/generated/schemas/reminderMetadata.ts@@ -0,0 +1,25 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * notification_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * Metadata for a reminder the user set for themselves coming due.++There is no sender: a reminder is self-set, so the dispatcher sends it with+`sender_id: None` (a recipient who is also the sender is filtered out of+their own notification). Every formatter here must therefore work without+one.++The associated entity, when there is one, lives on the notification row+rather than in here, and clients resolve its name from that — so the+dispatcher does not have to look up a name across five entity types.+ */+export interface ReminderMetadata {+ /** What the user asked to be reminded about. */+ description: string;+ /** The reminder that fired. */+ reminderId: string;+}diff --git a/apps/web/src/lib/service-clients/service-notification/generated/zod.ts b/apps/web/src/lib/service-clients/service-notification/generated/zod.tsindex 560e260184..bd7311a28f 100644--- a/apps/web/src/lib/service-clients/service-notification/generated/zod.ts+++ b/apps/web/src/lib/service-clients/service-notification/generated/zod.ts@@ -142,6 +142,7 @@ export const listTypedNotificationsResponse = zod'static_file','crm_company','crm_contact',+ 'reminder',]).describe('The type of an entity in Macro'),})@@ -666,6 +667,27 @@ export const listTypedNotificationsResponse = zodtag: zod.enum(['task_assigned']),}).describe('A user was assigned to a task.'),+ zod+ .object({+ content: zod+ .object({+ description: zod+ .string()+ .describe(+ 'What the user asked to be reminded about.'+ ),+ reminderId: zod+ .uuid()+ .describe('The reminder that fired.'),+ })+ .describe(+ 'Metadata for a reminder the user set for themselves coming due.\n\nThere is no sender: a reminder is self-set, so the dispatcher sends it with\n`sender_id: None` (a recipient who is also the sender is filtered out of\ntheir own notification). Every formatter here must therefore work without\none.\n\nThe associated entity, when there is one, lives on the notification row\nrather than in here, and clients resolve its name from that — so the\ndispatcher does not have to look up a name across five entity types.'+ ),+ tag: zod.enum(['reminder']),+ })+ .describe(+ 'A reminder the user set for themselves came due.'+ ),zod.object({content: zod.object({@@ -1404,6 +1426,7 @@ export const bulkGetTypedNotificationsByEventItemIdsResponse = zod'static_file','crm_company','crm_contact',+ 'reminder',]).describe('The type of an entity in Macro'),})@@ -1928,6 +1951,27 @@ export const bulkGetTypedNotificationsByEventItemIdsResponse = zodtag: zod.enum(['task_assigned']),}).describe('A user was assigned to a task.'),+ zod+ .object({+ content: zod+ .object({+ description: zod+ .string()+ .describe(+ 'What the user asked to be reminded about.'+ ),+ reminderId: zod+ .uuid()+ .describe('The reminder that fired.'),+ })+ .describe(+ 'Metadata for a reminder the user set for themselves coming due.\n\nThere is no sender: a reminder is self-set, so the dispatcher sends it with\n`sender_id: None` (a recipient who is also the sender is filtered out of\ntheir own notification). Every formatter here must therefore work without\none.\n\nThe associated entity, when there is one, lives on the notification row\nrather than in here, and clients resolve its name from that — so the\ndispatcher does not have to look up a name across five entity types.'+ ),+ tag: zod.enum(['reminder']),+ })+ .describe(+ 'A reminder the user set for themselves came due.'+ ),zod.object({content: zod.object({@@ -2660,6 +2704,7 @@ export const getTypedNotificationsByEventItemIdResponse = zod'static_file','crm_company','crm_contact',+ 'reminder',]).describe('The type of an entity in Macro'),})@@ -3184,6 +3229,27 @@ export const getTypedNotificationsByEventItemIdResponse = zodtag: zod.enum(['task_assigned']),}).describe('A user was assigned to a task.'),+ zod+ .object({+ content: zod+ .object({+ description: zod+ .string()+ .describe(+ 'What the user asked to be reminded about.'+ ),+ reminderId: zod+ .uuid()+ .describe('The reminder that fired.'),+ })+ .describe(+ 'Metadata for a reminder the user set for themselves coming due.\n\nThere is no sender: a reminder is self-set, so the dispatcher sends it with\n`sender_id: None` (a recipient who is also the sender is filtered out of\ntheir own notification). Every formatter here must therefore work without\none.\n\nThe associated entity, when there is one, lives on the notification row\nrather than in here, and clients resolve its name from that — so the\ndispatcher does not have to look up a name across five entity types.'+ ),+ tag: zod.enum(['reminder']),+ })+ .describe(+ 'A reminder the user set for themselves came due.'+ ),zod.object({content: zod.object({@@ -3927,6 +3993,7 @@ export const getTypedNotificationByIdResponse = zod'static_file','crm_company','crm_contact',+ 'reminder',]).describe('The type of an entity in Macro'),})@@ -4417,6 +4484,21 @@ export const getTypedNotificationByIdResponse = zodtag: zod.enum(['task_assigned']),}).describe('A user was assigned to a task.'),+ zod+ .object({+ content: zod+ .object({+ description: zod+ .string()+ .describe('What the user asked to be reminded about.'),+ reminderId: zod.uuid().describe('The reminder that fired.'),+ })+ .describe(+ 'Metadata for a reminder the user set for themselves coming due.\n\nThere is no sender: a reminder is self-set, so the dispatcher sends it with\n`sender_id: None` (a recipient who is also the sender is filtered out of\ntheir own notification). Every formatter here must therefore work without\none.\n\nThe associated entity, when there is one, lives on the notification row\nrather than in here, and clients resolve its name from that — so the\ndispatcher does not have to look up a name across five entity types.'+ ),+ tag: zod.enum(['reminder']),+ })+ .describe('A reminder the user set for themselves came due.'),zod.object({content: zod.object({diff --git a/apps/web/src/lib/service-clients/service-notification/openapi.json b/apps/web/src/lib/service-clients/service-notification/openapi.jsonindex 36e1e5b54e..4fbfcda375 100644--- a/apps/web/src/lib/service-clients/service-notification/openapi.json+++ b/apps/web/src/lib/service-clients/service-notification/openapi.json@@ -1504,7 +1504,8 @@"foreign_entity","static_file","crm_company",- "crm_contact"+ "crm_contact",+ "reminder"]},"ErrorResponse": {@@ -2221,6 +2222,21 @@}}},+ {+ "type": "object",+ "description": "A reminder the user set for themselves came due.",+ "required": ["content", "tag"],+ "properties": {+ "content": {+ "$ref": "#/components/schemas/ReminderMetadata",+ "description": "A reminder the user set for themselves came due."+ },+ "tag": {+ "type": "string",+ "enum": ["reminder"]+ }+ }+ },{"type": "object","description": "An AI assistant responded to a chat.",@@ -2392,6 +2408,22 @@}}},+ "ReminderMetadata": {+ "type": "object",+ "description": "Metadata for a reminder the user set for themselves coming due.\n\nThere is no sender: a reminder is self-set, so the dispatcher sends it with\n`sender_id: None` (a recipient who is also the sender is filtered out of\ntheir own notification). Every formatter here must therefore work without\none.\n\nThe associated entity, when there is one, lives on the notification row\nrather than in here, and clients resolve its name from that — so the\ndispatcher does not have to look up a name across five entity types.",+ "required": ["reminderId", "description"],+ "properties": {+ "description": {+ "type": "string",+ "description": "What the user asked to be reminded about."+ },+ "reminderId": {+ "type": "string",+ "format": "uuid",+ "description": "The reminder that fired."+ }+ }+ },"RepliedToDocumentCommentThreadMetadata": {"type": "object","description": "Notification sent when someone replies to a document comment thread.",diff --git a/apps/web/src/lib/service-clients/service-storage/client.ts b/apps/web/src/lib/service-clients/service-storage/client.tsindex bf04f2f3ab..1fc36771a4 100644--- a/apps/web/src/lib/service-clients/service-storage/client.ts+++ b/apps/web/src/lib/service-clients/service-storage/client.ts@@ -68,6 +68,7 @@ import type { CreateInstructionsDocumentResponse } from './generated/schemas/creimport type { CreateMarkdownDocumentRequest } from './generated/schemas/createMarkdownDocumentRequest';import type { CreateMarkdownHandler200 } from './generated/schemas/createMarkdownHandler200';import type { CreateProjectResponse } from './generated/schemas/createProjectResponse';+import type { CreateReminderRequest } from './generated/schemas/createReminderRequest';import type { CreateSnippetHandler200 } from './generated/schemas/createSnippetHandler200';import type { CreateSnippetRequest } from './generated/schemas/createSnippetRequest';import type { CreateTaskHandler200 } from './generated/schemas/createTaskHandler200';@@ -132,6 +133,7 @@ import type { PostSoupAstRequest } from './generated/schemas/postSoupAstRequest'import type { PostSoupRequest } from './generated/schemas/postSoupRequest';import type { PostTypingRequest } from './generated/schemas/postTypingRequest';import type { Project } from './generated/schemas/project';+import type { Reminder } from './generated/schemas/reminder';import type { RemoveParticipantsRequest } from './generated/schemas/removeParticipantsRequest';import type { ReorderFavoritesRequest } from './generated/schemas/reorderFavoritesRequest';import type { ReorderPinRequest } from './generated/schemas/reorderPinRequest';@@ -2329,6 +2331,14 @@ export const storageServiceClient = {});},},+ reminders: {+ async createReminder(params: CreateReminderRequest) {+ return await dssFetch<Reminder>('/reminders', {+ method: 'POST',+ body: JSON.stringify(params),+ });+ },+ },async editThread(params) {const { threadId, ...body } = params;diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/addFavoriteRequestEntityType.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/addFavoriteRequestEntityType.tsindex 36a396abf5..1de663095e 100644--- a/apps/web/src/lib/service-clients/service-storage/generated/schemas/addFavoriteRequestEntityType.ts+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/addFavoriteRequestEntityType.ts@@ -22,4 +22,5 @@ export type AddFavoriteRequestEntityType =| 'foreign_entity'| 'static_file'| 'crm_company'- | 'crm_contact';+ | 'crm_contact'+ | 'reminder';diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/createReminderRequest.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/createReminderRequest.tsnew file mode 100644index 0000000000..8b5d0ce7df--- /dev/null+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/createReminderRequest.ts@@ -0,0 +1,23 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */+import type { CreateReminderRequestEntityId } from './createReminderRequestEntityId';+import type { CreateReminderRequestEntityType } from './createReminderRequestEntityType';+import type { ReminderSchedule } from './reminderSchedule';++/**+ * Request body for creating a reminder.+ */+export interface CreateReminderRequest {+ /** What to remind the caller about. */+ description: string;+ /** Id of the entity to attach the reminder to. Requires `entityType`. */+ entityId?: CreateReminderRequestEntityId;+ /** Type of the entity to attach the reminder to. Requires `entityId`. */+ entityType?: CreateReminderRequestEntityType;+ /** When and how often the reminder fires. */+ schedule: ReminderSchedule;+}diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/createReminderRequestEntityId.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/createReminderRequestEntityId.tsnew file mode 100644index 0000000000..801dd9fc2e--- /dev/null+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/createReminderRequestEntityId.ts@@ -0,0 +1,11 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * Id of the entity to attach the reminder to. Requires `entityType`.+ */+export type CreateReminderRequestEntityId = string | null;diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/createReminderRequestEntityType.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/createReminderRequestEntityType.tsnew file mode 100644index 0000000000..9be952da01--- /dev/null+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/createReminderRequestEntityType.ts@@ -0,0 +1,27 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * Type of the entity to attach the reminder to. Requires `entityId`.+ */+export type CreateReminderRequestEntityType =+ | null+ | 'user'+ | 'chat'+ | 'channel'+ | 'channel_message'+ | 'document'+ | 'project'+ | 'email_thread'+ | 'calendar_event'+ | 'team'+ | 'call'+ | 'foreign_entity'+ | 'static_file'+ | 'crm_company'+ | 'crm_contact'+ | 'reminder';diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/favoriteEntityRefEntityType.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/favoriteEntityRefEntityType.tsindex 70436fcc0a..97456cdc19 100644--- a/apps/web/src/lib/service-clients/service-storage/generated/schemas/favoriteEntityRefEntityType.ts+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/favoriteEntityRefEntityType.ts@@ -22,4 +22,5 @@ export type FavoriteEntityRefEntityType =| 'foreign_entity'| 'static_file'| 'crm_company'- | 'crm_contact';+ | 'crm_contact'+ | 'reminder';diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/favoriteEntityType.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/favoriteEntityType.tsindex 4753472e0d..b7ed62fa0b 100644--- a/apps/web/src/lib/service-clients/service-storage/generated/schemas/favoriteEntityType.ts+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/favoriteEntityType.ts@@ -22,4 +22,5 @@ export type FavoriteEntityType =| 'foreign_entity'| 'static_file'| 'crm_company'- | 'crm_contact';+ | 'crm_contact'+ | 'reminder';diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/index.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/index.tsindex 09556711a3..e5befc125e 100644--- a/apps/web/src/lib/service-clients/service-storage/generated/schemas/index.ts+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/index.ts@@ -333,6 +333,9 @@ export * from './createMarkdownHandler200';export * from './createProjectRequest';export * from './createProjectRequestProjectParentId';export * from './createProjectResponse';+export * from './createReminderRequest';+export * from './createReminderRequestEntityId';+export * from './createReminderRequestEntityType';export * from './createSnippetHandler200';export * from './createSnippetRequest';export * from './createSnippetRequestMarkdown';@@ -711,6 +714,8 @@ export * from './latestMessageLatestMessage';export * from './latestMessageLatestNonThreadMessage';export * from './leaveCallResponse';export * from './listOccurrencesParams';+export * from './listRemindersEntityType';+export * from './listRemindersParams';export * from './listWebhooksResponse';export * from './locationResponseData';export * from './locationResponseDataOneOf';@@ -877,6 +882,17 @@ export * from './propertyValueOneOfThreeType';export * from './propertyValueOneOfType';export * from './reactionAction';export * from './recentlyDeletedResponseData';+export * from './reminder';+export * from './reminderCompletedAt';+export * from './reminderEntityId';+export * from './reminderEntityType';+export * from './reminderSchedule';+export * from './reminderScheduleOneOf';+export * from './reminderScheduleOneOfThree';+export * from './reminderScheduleOneOfThreeType';+export * from './reminderScheduleOneOfType';+export * from './remindersList';+export * from './remindersListNextCursor';export * from './removeParticipantsRequest';export * from './reorderFavoritesRequest';export * from './reorderPinRequest';@@ -1094,6 +1110,7 @@ export * from './updateCrmTeamSettingsRequestDeleteRecordsRole';export * from './updateCrmTeamSettingsRequestEditStagesRole';export * from './updateCrmTeamSettingsRequestMoveClosedDealsRole';export * from './updateOperation';+export * from './updateReminderRequest';export * from './updateSharePermissionRequestV2';export * from './updateSharePermissionRequestV2ChannelSharePermissions';export * from './updateSharePermissionRequestV2IsPublic';diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/listRemindersEntityType.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/listRemindersEntityType.tsnew file mode 100644index 0000000000..1e003e1a58--- /dev/null+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/listRemindersEntityType.ts@@ -0,0 +1,28 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */++export type ListRemindersEntityType =+ (typeof ListRemindersEntityType)[keyof typeof ListRemindersEntityType];++// eslint-disable-next-line @typescript-eslint/no-redeclare+export const ListRemindersEntityType = {+ user: 'user',+ chat: 'chat',+ channel: 'channel',+ channel_message: 'channel_message',+ document: 'document',+ project: 'project',+ email_thread: 'email_thread',+ calendar_event: 'calendar_event',+ team: 'team',+ call: 'call',+ foreign_entity: 'foreign_entity',+ static_file: 'static_file',+ crm_company: 'crm_company',+ crm_contact: 'crm_contact',+ reminder: 'reminder',+} as const;diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/listRemindersParams.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/listRemindersParams.tsnew file mode 100644index 0000000000..3a8fe595cc--- /dev/null+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/listRemindersParams.ts@@ -0,0 +1,32 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */+import type { ListRemindersEntityType } from './listRemindersEntityType';++export type ListRemindersParams = {+ /**+ * The type of an entity in Macro+ */+ entityType?: ListRemindersEntityType;+ /**+ * Restrict to reminders attached to this entity id. Requires `entityType`.+ */+ entityId?: string;+ /**+ * Include reminders that have already fired.+ */+ includeCompleted?: boolean;+ /**+ * Page size. Defaults to 100; larger values are capped at 500. A value+that is not a non-negative integer is rejected by the query extractor.+ * @minimum 0+ */+ limit?: number;+ /**+ * `nextCursor` from a previous page.+ */+ cursor?: string;+};diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/reminder.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/reminder.tsnew file mode 100644index 0000000000..4cfed84da3--- /dev/null+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/reminder.ts@@ -0,0 +1,39 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */+import type { ReminderCompletedAt } from './reminderCompletedAt';+import type { ReminderEntityId } from './reminderEntityId';+import type { ReminderEntityType } from './reminderEntityType';+import type { ReminderSchedule } from './reminderSchedule';++/**+ * A reminder belonging to a user.++`user_id` is deliberately absent: a reminder is only ever read by its owner,+so the field would be redundant on the wire.+ */+export interface Reminder {+ /** Set once a one-shot reminder has fired. */+ completedAt?: ReminderCompletedAt;+ /** When the reminder was created. */+ createdAt: string;+ /** What to remind the user about. */+ description: string;+ /** When false, the dispatcher skips this reminder. */+ enabled: boolean;+ /** Id of the associated entity, when the reminder is attached to one. */+ entityId?: ReminderEntityId;+ /** Type of the associated entity, when the reminder is attached to one. */+ entityType?: ReminderEntityType;+ /** Reminder id. */+ id: string;+ /** The next firing, derived from `schedule` on write. */+ nextRunAt: string;+ /** When and how often the reminder fires. */+ schedule: ReminderSchedule;+ /** When the reminder was last modified. */+ updatedAt: string;+}diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/reminderCompletedAt.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/reminderCompletedAt.tsnew file mode 100644index 0000000000..94c975065d--- /dev/null+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/reminderCompletedAt.ts@@ -0,0 +1,11 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * Set once a one-shot reminder has fired.+ */+export type ReminderCompletedAt = string | null;diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/reminderEntityId.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/reminderEntityId.tsnew file mode 100644index 0000000000..5b5af93cfa--- /dev/null+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/reminderEntityId.ts@@ -0,0 +1,11 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * Id of the associated entity, when the reminder is attached to one.+ */+export type ReminderEntityId = string | null;diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/reminderEntityType.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/reminderEntityType.tsnew file mode 100644index 0000000000..e3978086e6--- /dev/null+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/reminderEntityType.ts@@ -0,0 +1,27 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * Type of the associated entity, when the reminder is attached to one.+ */+export type ReminderEntityType =+ | null+ | 'user'+ | 'chat'+ | 'channel'+ | 'channel_message'+ | 'document'+ | 'project'+ | 'email_thread'+ | 'calendar_event'+ | 'team'+ | 'call'+ | 'foreign_entity'+ | 'static_file'+ | 'crm_company'+ | 'crm_contact'+ | 'reminder';diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/reminderSchedule.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/reminderSchedule.tsnew file mode 100644index 0000000000..5d209c9b4e--- /dev/null+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/reminderSchedule.ts@@ -0,0 +1,15 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */+import type { ReminderScheduleOneOf } from './reminderScheduleOneOf';+import type { ReminderScheduleOneOfThree } from './reminderScheduleOneOfThree';++/**+ * When a reminder fires.+ */+export type ReminderSchedule =+ | ReminderScheduleOneOf+ | ReminderScheduleOneOfThree;diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/reminderScheduleOneOf.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/reminderScheduleOneOf.tsnew file mode 100644index 0000000000..f5fa0ecc62--- /dev/null+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/reminderScheduleOneOf.ts@@ -0,0 +1,16 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */+import type { ReminderScheduleOneOfType } from './reminderScheduleOneOfType';++/**+ * Fires once, at a fixed instant.+ */+export type ReminderScheduleOneOf = {+ /** The instant to fire at. */+ remindAt: string;+ type: ReminderScheduleOneOfType;+};diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/reminderScheduleOneOfThree.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/reminderScheduleOneOfThree.tsnew file mode 100644index 0000000000..043dd6cde6--- /dev/null+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/reminderScheduleOneOfThree.ts@@ -0,0 +1,22 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */+import type { ReminderScheduleOneOfThreeType } from './reminderScheduleOneOfThreeType';++/**+ * Fires repeatedly, on a cron schedule evaluated in `timezone`.+ */+export type ReminderScheduleOneOfThree = {+ /** Cron expression, either the conventional 5-field+`min hour dom mon dow` or the 6-/7-field+`sec min hour dom mon dow [year]`. A 5-field expression is stored+normalized to 6 fields with a zero seconds field, so `0 9 * * *` and+`0 0 9 * * *` are the same schedule and both read back as the latter. */+ cron: string;+ /** The timezone the cron expression is evaluated in. */+ timezone: string;+ type: ReminderScheduleOneOfThreeType;+};diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/reminderScheduleOneOfThreeType.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/reminderScheduleOneOfThreeType.tsnew file mode 100644index 0000000000..a32bcdc184--- /dev/null+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/reminderScheduleOneOfThreeType.ts@@ -0,0 +1,14 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */++export type ReminderScheduleOneOfThreeType =+ (typeof ReminderScheduleOneOfThreeType)[keyof typeof ReminderScheduleOneOfThreeType];++// eslint-disable-next-line @typescript-eslint/no-redeclare+export const ReminderScheduleOneOfThreeType = {+ recurring: 'recurring',+} as const;diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/reminderScheduleOneOfType.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/reminderScheduleOneOfType.tsnew file mode 100644index 0000000000..eb944ebab0--- /dev/null+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/reminderScheduleOneOfType.ts@@ -0,0 +1,14 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */++export type ReminderScheduleOneOfType =+ (typeof ReminderScheduleOneOfType)[keyof typeof ReminderScheduleOneOfType];++// eslint-disable-next-line @typescript-eslint/no-redeclare+export const ReminderScheduleOneOfType = {+ once: 'once',+} as const;diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/remindersList.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/remindersList.tsnew file mode 100644index 0000000000..46ac9ac99e--- /dev/null+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/remindersList.ts@@ -0,0 +1,20 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */++import type { Reminder } from './reminder';+import type { RemindersListNextCursor } from './remindersListNextCursor';++/**+ * The caller's reminders, soonest firing first.+ */+export interface RemindersList {+ /** Pass back as `cursor` to fetch the next page. Absent on the last page —+its absence is the only end-of-list signal, since a page can be short. */+ nextCursor?: RemindersListNextCursor;+ /** The reminders. */+ reminders: Reminder[];+}diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/remindersListNextCursor.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/remindersListNextCursor.tsnew file mode 100644index 0000000000..e8d958624c--- /dev/null+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/remindersListNextCursor.ts@@ -0,0 +1,12 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * Pass back as `cursor` to fetch the next page. Absent on the last page —+its absence is the only end-of-list signal, since a page can be short.+ */+export type RemindersListNextCursor = string | null;diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/updateReminderRequest.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/updateReminderRequest.tsnew file mode 100644index 0000000000..e63729603c--- /dev/null+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/updateReminderRequest.ts@@ -0,0 +1,27 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */+import type { ReminderSchedule } from './reminderSchedule';++/**+ * Request body for modifying a reminder. Omitted fields are left unchanged;+the entity association is not modifiable.++Every field is optional but **not** nullable. `Option` here means "absent",+and serde cannot tell an explicit `null` from an omitted key — so a body of+`{"enabled": null}` would deserialize to an empty patch and be rejected as+having no fields to update. `nullable = false` keeps the schema from+advertising a value the API has no meaning for; the deserializer still+tolerates `null` rather than erroring on it.+ */+export interface UpdateReminderRequest {+ /** Replacement description. */+ description?: string;+ /** Whether the reminder should fire at all. */+ enabled?: boolean;+ /** Replacement schedule. */+ schedule?: ReminderSchedule;+}diff --git a/apps/web/src/lib/service-clients/service-storage/generated/zod.ts b/apps/web/src/lib/service-clients/service-storage/generated/zod.tsindex e3f34f2376..997d0da949 100644--- a/apps/web/src/lib/service-clients/service-storage/generated/zod.ts+++ b/apps/web/src/lib/service-clients/service-storage/generated/zod.ts@@ -7339,6 +7339,7 @@ export const listFavoritesResponse = zod'static_file','crm_company','crm_contact',+ 'reminder',]).describe('The type of an entity in Macro').describe('The type of the favorited entity.'),@@ -7382,6 +7383,7 @@ export const addFavoriteBody = zod'static_file','crm_company','crm_contact',+ 'reminder',]).describe('The type of an entity in Macro').describe('The type of the entity to favorite.'),@@ -7426,6 +7428,7 @@ export const addFavoriteResponse = zod'static_file','crm_company','crm_contact',+ 'reminder',]).describe('The type of an entity in Macro').describe('The type of the favorited entity.'),@@ -7467,6 +7470,7 @@ export const reorderFavoritesBody = zod'static_file','crm_company','crm_contact',+ 'reminder',]).describe('The type of an entity in Macro').describe('The type of the favorited entity.'),@@ -7501,6 +7505,7 @@ export const removeFavoriteByEntityParams = zod.object({'static_file','crm_company','crm_contact',+ 'reminder',]).describe('The type of the favorited entity.'),entity_id: zod.string().describe('The id of the favorited entity.'),@@ -24054,6 +24059,448 @@ export const recentlyDeletedResponse = zod.object({error: zod.boolean().describe('Indicates if an error occurred'),});+/**+ * @summary List the caller's reminders, soonest firing first.+ */+export const listRemindersQueryLimitMin = 0;++export const listRemindersQueryParams = zod.object({+ entityType: zod+ .enum([+ 'user',+ 'chat',+ 'channel',+ 'channel_message',+ 'document',+ 'project',+ 'email_thread',+ 'calendar_event',+ 'team',+ 'call',+ 'foreign_entity',+ 'static_file',+ 'crm_company',+ 'crm_contact',+ 'reminder',+ ])+ .optional()+ .describe(+ 'Restrict to reminders attached to this entity type. Requires `entityId`.'+ ),+ entityId: zod+ .string()+ .optional()+ .describe(+ 'Restrict to reminders attached to this entity id. Requires `entityType`.'+ ),+ includeCompleted: zod+ .boolean()+ .optional()+ .describe('Include reminders that have already fired.'),+ limit: zod+ .number()+ .min(listRemindersQueryLimitMin)+ .optional()+ .describe(+ 'Page size. Defaults to 100; larger values are capped at 500. A value\nthat is not a non-negative integer is rejected by the query extractor.'+ ),+ cursor: zod+ .string()+ .optional()+ .describe('`nextCursor` from a previous page.'),+});++export const listRemindersResponse = zod+ .object({+ nextCursor: zod+ .string()+ .nullish()+ .describe(+ 'Pass back as `cursor` to fetch the next page. Absent on the last page —\nits absence is the only end-of-list signal, since a page can be short.'+ ),+ reminders: zod+ .array(+ zod+ .object({+ completedAt: zod.iso+ .datetime({})+ .nullish()+ .describe('Set once a one-shot reminder has fired.'),+ createdAt: zod.iso+ .datetime({})+ .describe('When the reminder was created.'),+ description: zod+ .string()+ .describe('What to remind the user about.'),+ enabled: zod+ .boolean()+ .describe('When false, the dispatcher skips this reminder.'),+ entityId: zod+ .string()+ .nullish()+ .describe(+ 'Id of the associated entity, when the reminder is attached to one.'+ ),+ entityType: zod+ .union([+ zod.null(),+ zod+ .enum([+ 'user',+ 'chat',+ 'channel',+ 'channel_message',+ 'document',+ 'project',+ 'email_thread',+ 'calendar_event',+ 'team',+ 'call',+ 'foreign_entity',+ 'static_file',+ 'crm_company',+ 'crm_contact',+ 'reminder',+ ])+ .describe('The type of an entity in Macro'),+ ])+ .optional()+ .describe(+ 'Type of the associated entity, when the reminder is attached to one.'+ ),+ id: zod.uuid().describe('Reminder id.'),+ nextRunAt: zod.iso+ .datetime({})+ .describe('The next firing, derived from `schedule` on write.'),+ schedule: zod+ .union([+ zod+ .object({+ remindAt: zod.iso+ .datetime({})+ .describe('The instant to fire at.'),+ type: zod.enum(['once']),+ })+ .describe('Fires once, at a fixed instant.'),+ zod+ .object({+ cron: zod+ .string()+ .describe(+ 'Cron expression, either the conventional 5-field\n`min hour dom mon dow` or the 6-\/7-field\n`sec min hour dom mon dow [year]`. A 5-field expression is stored\nnormalized to 6 fields with a zero seconds field, so `0 9 \* \* \*` and\n`0 0 9 \* \* \*` are the same schedule and both read back as the latter.'+ ),+ timezone: zod+ .string()+ .describe(+ 'The timezone the cron expression is evaluated in.'+ ),+ type: zod.enum(['recurring']),+ })+ .describe(+ 'Fires repeatedly, on a cron schedule evaluated in `timezone`.'+ ),+ ])+ .describe('When a reminder fires.'),+ updatedAt: zod.iso+ .datetime({})+ .describe('When the reminder was last modified.'),+ })+ .describe(+ 'A reminder belonging to a user.\n\n`user_id` is deliberately absent: a reminder is only ever read by its owner,\nso the field would be redundant on the wire.'+ )+ )+ .describe('The reminders.'),+ })+ .describe("The caller's reminders, soonest firing first.");++/**+ * @summary Create a reminder, optionally attached to an entity the caller can view.+ */+export const createReminderBody = zod+ .object({+ description: zod.string().describe('What to remind the caller about.'),+ entityId: zod+ .string()+ .nullish()+ .describe(+ 'Id of the entity to attach the reminder to. Requires `entityType`.'+ ),+ entityType: zod+ .union([+ zod.null(),+ zod+ .enum([+ 'user',+ 'chat',+ 'channel',+ 'channel_message',+ 'document',+ 'project',+ 'email_thread',+ 'calendar_event',+ 'team',+ 'call',+ 'foreign_entity',+ 'static_file',+ 'crm_company',+ 'crm_contact',+ 'reminder',+ ])+ .describe('The type of an entity in Macro'),+ ])+ .optional()+ .describe(+ 'Type of the entity to attach the reminder to. Requires `entityId`.'+ ),+ schedule: zod+ .union([+ zod+ .object({+ remindAt: zod.iso.datetime({}).describe('The instant to fire at.'),+ type: zod.enum(['once']),+ })+ .describe('Fires once, at a fixed instant.'),+ zod+ .object({+ cron: zod+ .string()+ .describe(+ 'Cron expression, either the conventional 5-field\n`min hour dom mon dow` or the 6-\/7-field\n`sec min hour dom mon dow [year]`. A 5-field expression is stored\nnormalized to 6 fields with a zero seconds field, so `0 9 \* \* \*` and\n`0 0 9 \* \* \*` are the same schedule and both read back as the latter.'+ ),+ timezone: zod+ .string()+ .describe('The timezone the cron expression is evaluated in.'),+ type: zod.enum(['recurring']),+ })+ .describe(+ 'Fires repeatedly, on a cron schedule evaluated in `timezone`.'+ ),+ ])+ .describe('When a reminder fires.'),+ })+ .describe('Request body for creating a reminder.');++/**+ * @summary Fetch one of the caller's reminders.+ */+export const getReminderParams = zod.object({+ id: zod.uuid().describe('The reminder id.'),+});++export const getReminderResponse = zod+ .object({+ completedAt: zod.iso+ .datetime({})+ .nullish()+ .describe('Set once a one-shot reminder has fired.'),+ createdAt: zod.iso.datetime({}).describe('When the reminder was created.'),+ description: zod.string().describe('What to remind the user about.'),+ enabled: zod+ .boolean()+ .describe('When false, the dispatcher skips this reminder.'),+ entityId: zod+ .string()+ .nullish()+ .describe(+ 'Id of the associated entity, when the reminder is attached to one.'+ ),+ entityType: zod+ .union([+ zod.null(),+ zod+ .enum([+ 'user',+ 'chat',+ 'channel',+ 'channel_message',+ 'document',+ 'project',+ 'email_thread',+ 'calendar_event',+ 'team',+ 'call',+ 'foreign_entity',+ 'static_file',+ 'crm_company',+ 'crm_contact',+ 'reminder',+ ])+ .describe('The type of an entity in Macro'),+ ])+ .optional()+ .describe(+ 'Type of the associated entity, when the reminder is attached to one.'+ ),+ id: zod.uuid().describe('Reminder id.'),+ nextRunAt: zod.iso+ .datetime({})+ .describe('The next firing, derived from `schedule` on write.'),+ schedule: zod+ .union([+ zod+ .object({+ remindAt: zod.iso.datetime({}).describe('The instant to fire at.'),+ type: zod.enum(['once']),+ })+ .describe('Fires once, at a fixed instant.'),+ zod+ .object({+ cron: zod+ .string()+ .describe(+ 'Cron expression, either the conventional 5-field\n`min hour dom mon dow` or the 6-\/7-field\n`sec min hour dom mon dow [year]`. A 5-field expression is stored\nnormalized to 6 fields with a zero seconds field, so `0 9 \* \* \*` and\n`0 0 9 \* \* \*` are the same schedule and both read back as the latter.'+ ),+ timezone: zod+ .string()+ .describe('The timezone the cron expression is evaluated in.'),+ type: zod.enum(['recurring']),+ })+ .describe(+ 'Fires repeatedly, on a cron schedule evaluated in `timezone`.'+ ),+ ])+ .describe('When a reminder fires.'),+ updatedAt: zod.iso+ .datetime({})+ .describe('When the reminder was last modified.'),+ })+ .describe(+ 'A reminder belonging to a user.\n\n`user_id` is deliberately absent: a reminder is only ever read by its owner,\nso the field would be redundant on the wire.'+ );++/**+ * @summary Delete one of the caller's reminders.+ */+export const deleteReminderParams = zod.object({+ id: zod.uuid().describe('The reminder id.'),+});++/**+ * @summary Modify one of the caller's reminders.+ */+export const updateReminderParams = zod.object({+ id: zod.uuid().describe('The reminder id.'),+});++export const updateReminderBody = zod+ .object({+ description: zod.string().optional().describe('Replacement description.'),+ enabled: zod+ .boolean()+ .optional()+ .describe('Whether the reminder should fire at all.'),+ schedule: zod+ .union([+ zod+ .object({+ remindAt: zod.iso.datetime({}).describe('The instant to fire at.'),+ type: zod.enum(['once']),+ })+ .describe('Fires once, at a fixed instant.'),+ zod+ .object({+ cron: zod+ .string()+ .describe(+ 'Cron expression, either the conventional 5-field\n`min hour dom mon dow` or the 6-\/7-field\n`sec min hour dom mon dow [year]`. A 5-field expression is stored\nnormalized to 6 fields with a zero seconds field, so `0 9 \* \* \*` and\n`0 0 9 \* \* \*` are the same schedule and both read back as the latter.'+ ),+ timezone: zod+ .string()+ .describe('The timezone the cron expression is evaluated in.'),+ type: zod.enum(['recurring']),+ })+ .describe(+ 'Fires repeatedly, on a cron schedule evaluated in `timezone`.'+ ),+ ])+ .optional()+ .describe('When a reminder fires.'),+ })+ .describe(+ 'Request body for modifying a reminder. Omitted fields are left unchanged;\nthe entity association is not modifiable.\n\nEvery field is optional but \*\*not\*\* nullable. `Option` here means \"absent\",\nand serde cannot tell an explicit `null` from an omitted key — so a body of\n`{\"enabled\": null}` would deserialize to an empty patch and be rejected as\nhaving no fields to update. `nullable = false` keeps the schema from\nadvertising a value the API has no meaning for; the deserializer still\ntolerates `null` rather than erroring on it.'+ );++export const updateReminderResponse = zod+ .object({+ completedAt: zod.iso+ .datetime({})+ .nullish()+ .describe('Set once a one-shot reminder has fired.'),+ createdAt: zod.iso.datetime({}).describe('When the reminder was created.'),+ description: zod.string().describe('What to remind the user about.'),+ enabled: zod+ .boolean()+ .describe('When false, the dispatcher skips this reminder.'),+ entityId: zod+ .string()+ .nullish()+ .describe(+ 'Id of the associated entity, when the reminder is attached to one.'+ ),+ entityType: zod+ .union([+ zod.null(),+ zod+ .enum([+ 'user',+ 'chat',+ 'channel',+ 'channel_message',+ 'document',+ 'project',+ 'email_thread',+ 'calendar_event',+ 'team',+ 'call',+ 'foreign_entity',+ 'static_file',+ 'crm_company',+ 'crm_contact',+ 'reminder',+ ])+ .describe('The type of an entity in Macro'),+ ])+ .optional()+ .describe(+ 'Type of the associated entity, when the reminder is attached to one.'+ ),+ id: zod.uuid().describe('Reminder id.'),+ nextRunAt: zod.iso+ .datetime({})+ .describe('The next firing, derived from `schedule` on write.'),+ schedule: zod+ .union([+ zod+ .object({+ remindAt: zod.iso.datetime({}).describe('The instant to fire at.'),+ type: zod.enum(['once']),+ })+ .describe('Fires once, at a fixed instant.'),+ zod+ .object({+ cron: zod+ .string()+ .describe(+ 'Cron expression, either the conventional 5-field\n`min hour dom mon dow` or the 6-\/7-field\n`sec min hour dom mon dow [year]`. A 5-field expression is stored\nnormalized to 6 fields with a zero seconds field, so `0 9 \* \* \*` and\n`0 0 9 \* \* \*` are the same schedule and both read back as the latter.'+ ),+ timezone: zod+ .string()+ .describe('The timezone the cron expression is evaluated in.'),+ type: zod.enum(['recurring']),+ })+ .describe(+ 'Fires repeatedly, on a cron schedule evaluated in `timezone`.'+ ),+ ])+ .describe('When a reminder fires.'),+ updatedAt: zod.iso+ .datetime({})+ .describe('When the reminder was last modified.'),+ })+ .describe(+ 'A reminder belonging to a user.\n\n`user_id` is deliberately absent: a reminder is only ever read by its owner,\nso the field would be redundant on the wire.'+ );+export const getViewsHandlerResponse = zod.object({excludedDefaultViews: zod.array(zoddiff --git a/apps/web/src/lib/service-clients/service-storage/openapi.json b/apps/web/src/lib/service-clients/service-storage/openapi.jsonindex 6abf51f2fb..0935ac3794 100644--- a/apps/web/src/lib/service-clients/service-storage/openapi.json+++ b/apps/web/src/lib/service-clients/service-storage/openapi.json@@ -7821,7 +7821,8 @@"foreign_entity","static_file","crm_company",- "crm_contact"+ "crm_contact",+ "reminder"]}},@@ -9596,6 +9597,397 @@}}},+ "/reminders": {+ "get": {+ "tags": ["reminders"],+ "summary": "List the caller's reminders, soonest firing first.",+ "operationId": "list_reminders",+ "parameters": [+ {+ "name": "entityType",+ "in": "query",+ "description": "Restrict to reminders attached to this entity type. Requires `entityId`.",+ "required": false,+ "schema": {+ "type": "string",+ "description": "The type of an entity in Macro",+ "enum": [+ "user",+ "chat",+ "channel",+ "channel_message",+ "document",+ "project",+ "email_thread",+ "calendar_event",+ "team",+ "call",+ "foreign_entity",+ "static_file",+ "crm_company",+ "crm_contact",+ "reminder"+ ]+ }+ },+ {+ "name": "entityId",+ "in": "query",+ "description": "Restrict to reminders attached to this entity id. Requires `entityType`.",+ "required": false,+ "schema": {+ "type": "string"+ }+ },+ {+ "name": "includeCompleted",+ "in": "query",+ "description": "Include reminders that have already fired.",+ "required": false,+ "schema": {+ "type": "boolean"+ }+ },+ {+ "name": "limit",+ "in": "query",+ "description": "Page size. Defaults to 100; larger values are capped at 500. A value\nthat is not a non-negative integer is rejected by the query extractor.",+ "required": false,+ "schema": {+ "type": "integer",+ "format": "int32",+ "minimum": 0+ }+ },+ {+ "name": "cursor",+ "in": "query",+ "description": "`nextCursor` from a previous page.",+ "required": false,+ "schema": {+ "type": "string"+ }+ }+ ],+ "responses": {+ "200": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/RemindersList"+ }+ }+ }+ },+ "400": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "401": {+ "description": "Missing or invalid credentials",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "500": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ }+ }+ },+ "post": {+ "tags": ["reminders"],+ "summary": "Create a reminder, optionally attached to an entity the caller can view.",+ "operationId": "create_reminder",+ "requestBody": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/CreateReminderRequest"+ }+ }+ },+ "required": true+ },+ "responses": {+ "201": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/Reminder"+ }+ }+ }+ },+ "400": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "401": {+ "description": "Missing or invalid credentials",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "403": {+ "description": "No access to the requested entity",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "404": {+ "description": "The requested entity does not exist",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "422": {+ "description": "Malformed request body (plain text)"+ },+ "500": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ }+ }+ }+ },+ "/reminders/{id}": {+ "get": {+ "tags": ["reminders"],+ "summary": "Fetch one of the caller's reminders.",+ "operationId": "get_reminder",+ "parameters": [+ {+ "name": "id",+ "in": "path",+ "description": "The reminder id.",+ "required": true,+ "schema": {+ "type": "string",+ "format": "uuid"+ }+ }+ ],+ "responses": {+ "200": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/Reminder"+ }+ }+ }+ },+ "401": {+ "description": "Missing or invalid credentials",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "404": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "500": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ }+ }+ },+ "delete": {+ "tags": ["reminders"],+ "summary": "Delete one of the caller's reminders.",+ "operationId": "delete_reminder",+ "parameters": [+ {+ "name": "id",+ "in": "path",+ "description": "The reminder id.",+ "required": true,+ "schema": {+ "type": "string",+ "format": "uuid"+ }+ }+ ],+ "responses": {+ "204": {+ "description": "Reminder deleted"+ },+ "401": {+ "description": "Missing or invalid credentials",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "404": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "500": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ }+ }+ },+ "patch": {+ "tags": ["reminders"],+ "summary": "Modify one of the caller's reminders.",+ "operationId": "update_reminder",+ "parameters": [+ {+ "name": "id",+ "in": "path",+ "description": "The reminder id.",+ "required": true,+ "schema": {+ "type": "string",+ "format": "uuid"+ }+ }+ ],+ "requestBody": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/UpdateReminderRequest"+ }+ }+ },+ "required": true+ },+ "responses": {+ "200": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/Reminder"+ }+ }+ }+ },+ "400": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "401": {+ "description": "Missing or invalid credentials",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "404": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "422": {+ "description": "Malformed request body (plain text)"+ },+ "500": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ }+ }+ }+ },"/saved_views": {"get": {"tags": ["saved_views"],@@ -10613,7 +11005,8 @@"foreign_entity","static_file","crm_company",- "crm_contact"+ "crm_contact",+ "reminder"]}],@@ -14647,6 +15040,54 @@}}},+ "CreateReminderRequest": {+ "type": "object",+ "description": "Request body for creating a reminder.",+ "required": ["description", "schedule"],+ "properties": {+ "description": {+ "type": "string",+ "description": "What to remind the caller about."+ },+ "entityId": {+ "type": ["string", "null"],+ "description": "Id of the entity to attach the reminder to. Requires `entityType`."+ },+ "entityType": {+ "oneOf": [+ {+ "type": "null"+ },+ {+ "type": "string",+ "description": "The type of an entity in Macro",+ "enum": [+ "user",+ "chat",+ "channel",+ "channel_message",+ "document",+ "project",+ "email_thread",+ "calendar_event",+ "team",+ "call",+ "foreign_entity",+ "static_file",+ "crm_company",+ "crm_contact",+ "reminder"+ ]+ }+ ],+ "description": "Type of the entity to attach the reminder to. Requires `entityId`."+ },+ "schedule": {+ "$ref": "#/components/schemas/ReminderSchedule",+ "description": "When and how often the reminder fires."+ }+ }+ },"CreateSnippetRequest": {"type": "object","description": "Request body for creating a snippet — a reusable markdown document that can\nbe inserted into any markdown area.",@@ -17164,7 +17605,8 @@"foreign_entity","static_file","crm_company",- "crm_contact"+ "crm_contact",+ "reminder"]}],@@ -17209,7 +17651,8 @@"foreign_entity","static_file","crm_company",- "crm_contact"+ "crm_contact",+ "reminder"]}],@@ -20458,6 +20901,149 @@}}},+ "Reminder": {+ "type": "object",+ "description": "A reminder belonging to a user.\n\n`user_id` is deliberately absent: a reminder is only ever read by its owner,\nso the field would be redundant on the wire.",+ "required": [+ "id",+ "description",+ "schedule",+ "nextRunAt",+ "enabled",+ "createdAt",+ "updatedAt"+ ],+ "properties": {+ "completedAt": {+ "type": ["string", "null"],+ "format": "date-time",+ "description": "Set once a one-shot reminder has fired."+ },+ "createdAt": {+ "type": "string",+ "format": "date-time",+ "description": "When the reminder was created."+ },+ "description": {+ "type": "string",+ "description": "What to remind the user about."+ },+ "enabled": {+ "type": "boolean",+ "description": "When false, the dispatcher skips this reminder."+ },+ "entityId": {+ "type": ["string", "null"],+ "description": "Id of the associated entity, when the reminder is attached to one."+ },+ "entityType": {+ "oneOf": [+ {+ "type": "null"+ },+ {+ "type": "string",+ "description": "The type of an entity in Macro",+ "enum": [+ "user",+ "chat",+ "channel",+ "channel_message",+ "document",+ "project",+ "email_thread",+ "calendar_event",+ "team",+ "call",+ "foreign_entity",+ "static_file",+ "crm_company",+ "crm_contact",+ "reminder"+ ]+ }+ ],+ "description": "Type of the associated entity, when the reminder is attached to one."+ },+ "id": {+ "type": "string",+ "format": "uuid",+ "description": "Reminder id."+ },+ "nextRunAt": {+ "type": "string",+ "format": "date-time",+ "description": "The next firing, derived from `schedule` on write."+ },+ "schedule": {+ "$ref": "#/components/schemas/ReminderSchedule",+ "description": "When and how often the reminder fires."+ },+ "updatedAt": {+ "type": "string",+ "format": "date-time",+ "description": "When the reminder was last modified."+ }+ }+ },+ "ReminderSchedule": {+ "oneOf": [+ {+ "type": "object",+ "description": "Fires once, at a fixed instant.",+ "required": ["remindAt", "type"],+ "properties": {+ "remindAt": {+ "type": "string",+ "format": "date-time",+ "description": "The instant to fire at."+ },+ "type": {+ "type": "string",+ "enum": ["once"]+ }+ }+ },+ {+ "type": "object",+ "description": "Fires repeatedly, on a cron schedule evaluated in `timezone`.",+ "required": ["cron", "timezone", "type"],+ "properties": {+ "cron": {+ "type": "string",+ "description": "Cron expression, either the conventional 5-field\n`min hour dom mon dow` or the 6-/7-field\n`sec min hour dom mon dow [year]`. A 5-field expression is stored\nnormalized to 6 fields with a zero seconds field, so `0 9 * * *` and\n`0 0 9 * * *` are the same schedule and both read back as the latter."+ },+ "timezone": {+ "type": "string",+ "description": "The timezone the cron expression is evaluated in."+ },+ "type": {+ "type": "string",+ "enum": ["recurring"]+ }+ }+ }+ ],+ "description": "When a reminder fires."+ },+ "RemindersList": {+ "type": "object",+ "description": "The caller's reminders, soonest firing first.",+ "required": ["reminders"],+ "properties": {+ "nextCursor": {+ "type": ["string", "null"],+ "description": "Pass back as `cursor` to fetch the next page. Absent on the last page —\nits absence is the only end-of-list signal, since a page can be short."+ },+ "reminders": {+ "type": "array",+ "items": {+ "$ref": "#/components/schemas/Reminder"+ },+ "description": "The reminders."+ }+ }+ },"RemoveParticipantsRequest": {"type": "object","description": "Request to remove participants.",@@ -22712,6 +23298,24 @@"type": "string","enum": ["add", "remove", "replace"]},+ "UpdateReminderRequest": {+ "type": "object",+ "description": "Request body for modifying a reminder. Omitted fields are left unchanged;\nthe entity association is not modifiable.\n\nEvery field is optional but **not** nullable. `Option` here means \"absent\",\nand serde cannot tell an explicit `null` from an omitted key — so a body of\n`{\"enabled\": null}` would deserialize to an empty patch and be rejected as\nhaving no fields to update. `nullable = false` keeps the schema from\nadvertising a value the API has no meaning for; the deserializer still\ntolerates `null` rather than erroring on it.",+ "properties": {+ "description": {+ "type": "string",+ "description": "Replacement description."+ },+ "enabled": {+ "type": "boolean",+ "description": "Whether the reminder should fire at all."+ },+ "schedule": {+ "$ref": "#/components/schemas/ReminderSchedule",+ "description": "Replacement schedule."+ }+ }+ },"UpdateSharePermissionRequestV2": {"type": "object","properties": {diff --git a/apps/web/src/vite-env.d.ts b/apps/web/src/vite-env.d.tsindex 98c7e129bc..ec21d7d642 100644--- a/apps/web/src/vite-env.d.ts+++ b/apps/web/src/vite-env.d.ts@@ -9,6 +9,7 @@ interface ImportMetaEnv {readonly VITE_OTEL_EXPORTER_URL?: string;readonly VITE_OTEL_ENV?: string;readonly VITE_ENABLE_BROWSER_OTEL?: string;+ readonly VITE_ENABLE_REMINDERS?: string;}interface ImportMeta {diff --git a/crates/entity_access/src/domain/ports.rs b/crates/entity_access/src/domain/ports.rsindex fde067619a..33fab129e6 100644--- a/crates/entity_access/src/domain/ports.rs+++ b/crates/entity_access/src/domain/ports.rs@@ -66,6 +66,17 @@ pub trait AccessRepository: Clone + Send + Sync + 'static {user_id: Option<&MacroUserId<Lowercase<'_>>>,) -> impl Future<Output = Result<Option<AccessLevel>, AccessError>> + Send;+ /// Get the access level a user has for a reminder.+ ///+ /// A reminder is never shared, so this is ownership and nothing else:+ /// [`AccessLevel::Owner`] for the user who set it, `None` for everyone+ /// else and for a reminder that does not exist.+ fn get_reminder_access(+ &self,+ reminder_id: &str,+ user_id: Option<&MacroUserId<Lowercase<'_>>>,+ ) -> impl Future<Output = Result<Option<AccessLevel>, AccessError>> + Send;+/// Get the highest access level available to a bot in its owning team's/// scope for a document, chat, project, email thread, or call.///diff --git a/crates/entity_access/src/domain/service.rs b/crates/entity_access/src/domain/service.rsindex eaed39e240..77bf29ffbc 100644--- a/crates/entity_access/src/domain/service.rs+++ b/crates/entity_access/src/domain/service.rs@@ -238,7 +238,9 @@ whereEntityType::User| EntityType::ChannelMessage| EntityType::StaticFile- | EntityType::CalendarEvent => {+ | EntityType::CalendarEvent+ // A reminder belongs to a user, so a team-scoped bot never reaches one.+ | EntityType::Reminder => {Err(AccessError::BadRequest("Unsupported bot entity type"))}}@@ -408,6 +410,7 @@ where.await}EntityType::Channel => self.get_channel_access(entity_id, user_id).await,+ EntityType::Reminder => self.repo.get_reminder_access(entity_id, user_id).await,EntityType::ForeignEntity => self.get_foreign_entity_access(entity_id, user_id).await,EntityType::CrmCompany => Ok(self.get_crm_company_access(entity_id, user_id)diff --git a/crates/entity_access/src/domain/service/test.rs b/crates/entity_access/src/domain/service/test.rsindex 54d7ae7218..df6d44b2d9 100644--- a/crates/entity_access/src/domain/service/test.rs+++ b/crates/entity_access/src/domain/service/test.rs@@ -27,6 +27,7 @@ struct MockRepo {thread_access_calls: Arc<AtomicUsize>,owned_email_thread_ids: Arc<Mutex<Vec<Uuid>>>,call_access: Arc<Mutex<Option<AccessLevel>>>,+ reminder_access: Arc<Mutex<Option<AccessLevel>>>,team_entity_access: Arc<Mutex<Option<AccessLevel>>>,team_entity_access_calls: Arc<AtomicUsize>,team_channel_role: Arc<Mutex<ChannelRoleResult>>,@@ -60,6 +61,7 @@ impl MockRepo {thread_access_calls: Arc::new(AtomicUsize::new(0)),owned_email_thread_ids: Arc::new(Mutex::new(Vec::new())),call_access: Arc::new(Mutex::new(None)),+ reminder_access: Arc::new(Mutex::new(None)),team_entity_access: Arc::new(Mutex::new(None)),team_entity_access_calls: Arc::new(AtomicUsize::new(0)),team_channel_role: Arc::new(Mutex::new(ChannelRoleResult::NotFound)),@@ -281,6 +283,14 @@ impl AccessRepository for MockRepo {Ok(*self.call_access.lock().await)}+ async fn get_reminder_access(+ &self,+ _reminder_id: &str,+ _user_id: Option<&MacroUserId<Lowercase<'_>>>,+ ) -> Result<Option<AccessLevel>, AccessError> {+ Ok(*self.reminder_access.lock().await)+ }+async fn get_team_entity_access(&self,_bot_id: BotId,diff --git a/crates/entity_access/src/inbound/axum_extractors/mod.rs b/crates/entity_access/src/inbound/axum_extractors/mod.rsindex cb9ac5d919..35856559fe 100644--- a/crates/entity_access/src/inbound/axum_extractors/mod.rs+++ b/crates/entity_access/src/inbound/axum_extractors/mod.rs@@ -19,6 +19,7 @@ mod foreign_entity;mod history;mod pin;mod project;+mod reminder;mod team;mod thread;@@ -32,6 +33,7 @@ pub use foreign_entity::ForeignEntityAccessLevelExtractor;pub use history::HistoryAccessExtractor;pub use pin::PinAccessLevelExtractor;pub use project::{ProjectAccessLevelExtractor, ProjectBodyAccessLevelExtractorV2};+pub use reminder::ReminderAccessExtractor;pub use team::{MacroUserTeamExtractorV2, OptionalMacroUserTeamExtractorV2};pub use thread::ThreadAccessLevelExtractor;diff --git a/crates/entity_access/src/inbound/axum_extractors/reminder.rs b/crates/entity_access/src/inbound/axum_extractors/reminder.rsnew file mode 100644index 0000000000..491b98b4bb--- /dev/null+++ b/crates/entity_access/src/inbound/axum_extractors/reminder.rs@@ -0,0 +1,120 @@+//! Reminder access extractor.++use std::marker::PhantomData;+use std::sync::Arc;++use axum::{+ extract::{FromRef, FromRequestParts, Path},+ http::request::Parts,+};+use macro_authorization::{+ AnyPrincipal, MacroAuthorization, MacroAuthorizationService, MacroAuthorizationState,+ OptionalMacroAuthorizationExtractor,+};+use uuid::Uuid;++use super::{ExtractorError, RequiredPermission};+use crate::domain::{+ models::{Entity, EntityAccessAuth, EntityAccessReceipt, EntityPermission, EntityType},+ ports::EntityAccessService,+};++/// Path parameters for reminder routes.+#[derive(serde::Deserialize)]+struct ReminderPathParams {+ /// The id of the reminder.+ id: Uuid,+}++/// Validates that the caller owns the reminder named in the path.+///+/// A reminder is never shared, so the only permission it can carry is+/// [`AccessLevel::Owner`]. Requesting anything less still works — the owner+/// satisfies every requirement — but there is no weaker grant to hand out.+///+/// Bots are deliberately unsupported: a reminder belongs to a person, and a+/// team-scoped bot has no user identity to own one.+#[derive(Debug)]+pub struct ReminderAccessExtractor<T: RequiredPermission, Svc, Auth> {+ /// The entity access receipt.+ pub entity_access_receipt: EntityAccessReceipt<T>,+ _marker: PhantomData<(T, Svc, Auth)>,+}++impl<T, S, Svc, Auth> FromRequestParts<S> for ReminderAccessExtractor<T, Svc, Auth>+where+ T: RequiredPermission,+ Arc<Svc>: FromRef<S>,+ Svc: EntityAccessService,+ MacroAuthorizationState<Auth>: FromRef<S>,+ Auth: MacroAuthorizationService,+ S: Send + Sync + 'static,+{+ type Rejection = ExtractorError;++ #[tracing::instrument(err, skip(parts, state))]+ async fn from_request_parts(parts: &mut Parts, state: &S) -> Result<Self, Self::Rejection> {+ let service = <Arc<Svc>>::from_ref(state);++ let authorization =+ OptionalMacroAuthorizationExtractor::<Auth, AnyPrincipal>::from_request_parts(+ parts, state,+ )+ .await+ .map_err(ExtractorError::from)?;++ let Path(ReminderPathParams { id }) =+ <Path<ReminderPathParams>>::from_request_parts(parts, state)+ .await+ .map_err(|_| {+ ExtractorError::BadRequest("Missing or malformed reminder id in path")+ })?;+ let reminder_id = id.to_string();++ if let Some(MacroAuthorization::Bot(_)) = authorization.authorization.as_ref() {+ return Err(ExtractorError::UnauthorizedWithMessage(+ "bots cannot access reminders",+ ));+ }++ let entity = Entity {+ entity_id: reminder_id.clone(),+ entity_type: EntityType::Reminder,+ };++ // Unlike the other extractors there is no internal-acting-as-nobody+ // bypass: ownership *is* the access model here, so a receipt with no+ // user behind it would name no reminders at all.+ let Some(user_id) = authorization+ .authorization+ .as_ref()+ .and_then(MacroAuthorization::acting_user)+ .map(|user| user.macro_user_id.clone())+ else {+ return Err(ExtractorError::Unauthorized);+ };++ let access_level = service+ .get_access_level(Some(&user_id), &reminder_id, EntityType::Reminder)+ .await+ .map_err(ExtractorError::from)?+ // No row, or somebody else's row. Both are "not yours", and saying+ // which would leak whether the id exists.+ .ok_or(ExtractorError::Unauthorized)?;++ let entity_permission = EntityPermission::AccessLevel { access_level };+ if !entity_permission.satisfies::<T>() {+ return Err(ExtractorError::Unauthorized);+ }++ Ok(Self {+ entity_access_receipt: EntityAccessReceipt {+ entity,+ auth: EntityAccessAuth::Authenticated(user_id),+ entity_permission,+ _marker: PhantomData,+ },+ _marker: PhantomData,+ })+ }+}diff --git a/crates/entity_access/src/outbound/pg_access_repo/mod.rs b/crates/entity_access/src/outbound/pg_access_repo/mod.rsindex cd24a10537..7144d52d9f 100644--- a/crates/entity_access/src/outbound/pg_access_repo/mod.rs+++ b/crates/entity_access/src/outbound/pg_access_repo/mod.rs@@ -202,6 +202,37 @@ impl AccessRepository for PgAccessRepository {Ok(queries::call_access::get_call_access(&self.pool, &call_uuid, &source_ids).await?)}+ // A macro user id embeds the user's email, so it stays out of the span; the+ // reminder id is what identifies the lookup anyway.+ #[tracing::instrument(err, skip(self, user_id))]+ async fn get_reminder_access(+ &self,+ reminder_id: &str,+ user_id: Option<&MacroUserId<Lowercase<'_>>>,+ ) -> Result<Option<AccessLevel>, AccessError> {+ let reminder_uuid = reminder_id+ .parse::<Uuid>()+ .map_err(|_| AccessError::BadRequest("Invalid reminder ID format"))?;+ // An anonymous caller can never own a reminder, so skip the query.+ let Some(user_id) = user_id else {+ return Ok(None);+ };++ let owns = sqlx::query_scalar!(+ r#"SELECT EXISTS (+ SELECT 1 FROM reminder WHERE id = $1 AND user_id = $2+ ) AS "owns!""#,+ reminder_uuid,+ user_id.as_ref(),+ )+ .fetch_one(&self.pool)+ .await+ .map_err(|_| AccessError::Internal)?;++ // Owner or nothing: a reminder has no sharing model to grade.+ Ok(owns.then_some(AccessLevel::Owner))+ }+#[tracing::instrument(err, skip(self))]async fn get_team_entity_access(&self,@@ -250,7 +281,9 @@ impl AccessRepository for PgAccessRepository {| EntityType::ForeignEntity| EntityType::StaticFile| EntityType::CrmCompany- | EntityType::CrmContact => {+ | EntityType::CrmContact+ // Reminders are user-owned, never reachable through a team scope.+ | EntityType::Reminder => {return Err(AccessError::BadRequest("Unsupported entity type for team item access",));diff --git a/crates/entity_access/src/outbound/pg_access_repo/test.rs b/crates/entity_access/src/outbound/pg_access_repo/test.rsindex 9acd9be741..493194add4 100644--- a/crates/entity_access/src/outbound/pg_access_repo/test.rs+++ b/crates/entity_access/src/outbound/pg_access_repo/test.rs@@ -926,3 +926,81 @@ async fn team_item_access_rejects_unsupported_entity_type(pool: PgPool) -> anyho));Ok(())}++const REMINDER_OWNER: &str = "macro|[email protected]";+const REMINDER_STRANGER: &str = "macro|[email protected]";++async fn insert_reminder_user(pool: &PgPool, id: &str) -> anyhow::Result<()> {+ let macro_user_id = Uuid::new_v4();+ sqlx::query!(+ r#"INSERT INTO macro_user (id, username, email, stripe_customer_id)+ VALUES ($1, $2, $2, $2)"#,+ macro_user_id,+ id,+ )+ .execute(pool)+ .await?;+ sqlx::query!(+ r#"INSERT INTO "User" (id, email, macro_user_id) VALUES ($1, $1, $2)"#,+ id,+ macro_user_id,+ )+ .execute(pool)+ .await?;+ Ok(())+}++async fn insert_reminder(pool: &PgPool, owner: &str) -> anyhow::Result<Uuid> {+ let id = Uuid::new_v4();+ sqlx::query!(+ r#"INSERT INTO reminder (id, user_id, description, next_run_at, remind_at)+ VALUES ($1, $2, 'follow up', now(), now())"#,+ id,+ owner,+ )+ .execute(pool)+ .await?;+ Ok(id)+}++/// Reminder access is ownership and nothing else — the boundary+/// `ReminderAccessExtractor` relies on to gate every reminder item route.+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn reminder_access_is_owner_for_the_owner_and_nothing_for_anyone_else(+ pool: PgPool,+) -> anyhow::Result<()> {+ insert_reminder_user(&pool, REMINDER_OWNER).await?;+ insert_reminder_user(&pool, REMINDER_STRANGER).await?;+ let reminder_id = insert_reminder(&pool, REMINDER_OWNER).await?;+ let repo = PgAccessRepository::new(pool);++ let owner = repo+ .get_reminder_access(&reminder_id.to_string(), Some(&user_id(REMINDER_OWNER)))+ .await?;+ assert_eq!(owner, Some(AccessLevel::Owner));++ let stranger = repo+ .get_reminder_access(&reminder_id.to_string(), Some(&user_id(REMINDER_STRANGER)))+ .await?;+ assert_eq!(stranger, None, "a reminder is never shared");++ let anonymous = repo+ .get_reminder_access(&reminder_id.to_string(), None)+ .await?;+ assert_eq!(anonymous, None);++ // A reminder that does not exist is indistinguishable from one that is not+ // yours, which is what keeps the id from leaking.+ let missing = repo+ .get_reminder_access(&Uuid::new_v4().to_string(), Some(&user_id(REMINDER_OWNER)))+ .await?;+ assert_eq!(missing, None);++ let malformed = repo+ .get_reminder_access("not-a-uuid", Some(&user_id(REMINDER_OWNER)))+ .await+ .expect_err("a malformed id is a bad request, not a denial");+ assert!(matches!(malformed, AccessError::BadRequest(_)));++ Ok(())+}diff --git a/crates/entity_access_db_utils/src/lib.rs b/crates/entity_access_db_utils/src/lib.rsindex 49391095f5..34f160a21f 100644--- a/crates/entity_access_db_utils/src/lib.rs+++ b/crates/entity_access_db_utils/src/lib.rs@@ -258,7 +258,9 @@ pub async fn update_entity_access_channel_share_permissions(| EntityType::StaticFile| EntityType::CrmCompany| EntityType::CrmContact- | EntityType::ForeignEntity => {+ | EntityType::ForeignEntity+ // Reminders are never channel-shared: they are private to one user.+ | EntityType::Reminder => {return Err(sqlx::Error::InvalidArgument(format!("received unexpected entity type {entity_type:?}")));@@ -323,7 +325,9 @@ pub async fn update_entity_access_channel_share_permissions(| EntityType::StaticFile| EntityType::CrmCompany| EntityType::CrmContact- | EntityType::ForeignEntity => {+ | EntityType::ForeignEntity+ // Reminders are never channel-shared: they are private to one user.+ | EntityType::Reminder => {return Err(sqlx::Error::InvalidArgument(format!("Received invalid EntityType {entity_type:?}")));diff --git a/crates/graphql_common/src/entity_type.rs b/crates/graphql_common/src/entity_type.rsindex a9bd5a1b01..bbf30bced6 100644--- a/crates/graphql_common/src/entity_type.rs+++ b/crates/graphql_common/src/entity_type.rs@@ -57,6 +57,8 @@ pub enum GraphqlEntityType {StaticFile,/// CRM contact entity.CrmContact,+ /// Reminder entity.+ Reminder,}impl GraphqlSoupEntityType {@@ -120,6 +122,7 @@ impl GraphqlEntityType {EntityType::Team => Self::Team,EntityType::StaticFile => Self::StaticFile,EntityType::CrmContact => Self::CrmContact,+ EntityType::Reminder => Self::Reminder,}}@@ -145,6 +148,7 @@ impl GraphqlEntityType {Self::Team => EntityType::Team,Self::StaticFile => EntityType::StaticFile,Self::CrmContact => EntityType::CrmContact,+ Self::Reminder => EntityType::Reminder,}}}diff --git a/crates/graphql_notification/src/loaders.rs b/crates/graphql_notification/src/loaders.rsindex ec5a580f6a..4eb7b33ef0 100644--- a/crates/graphql_notification/src/loaders.rs+++ b/crates/graphql_notification/src/loaders.rs@@ -33,7 +33,10 @@ fn notification_item_type(entity_type: model_entity::EntityType) -> Option<Notif| EntityType::StaticFile| EntityType::CrmCompany| EntityType::CrmContact- | EntityType::CalendarEvent => None,+ | EntityType::CalendarEvent+ // A reminder's notification is keyed by the reminder's own id, which+ // `NotificationItemType` has no variant for, so it has no edge here.+ | EntityType::Reminder => None,}}diff --git a/crates/graphql_soup/src/loaders.rs b/crates/graphql_soup/src/loaders.rsindex c6de7ff198..e6316c09a3 100644--- a/crates/graphql_soup/src/loaders.rs+++ b/crates/graphql_soup/src/loaders.rs@@ -363,7 +363,9 @@ fn entity_filter_ast(entities: &[Entity<'static>]) -> Result<EntityFilterAst, SoEntityType::User| EntityType::Team| EntityType::StaticFile- | EntityType::CrmContact => {+ | EntityType::CrmContact+ // Reminders are not a Soup entity yet.+ | EntityType::Reminder => {return Err(rootcause::report!("entity type {} is not represented in Soup",entity.entity_typediff --git a/crates/macro_db_client/migrations/20260729145833_create_reminders_tables.sql b/crates/macro_db_client/migrations/20260729145833_create_reminders_tables.sqlnew file mode 100644index 0000000000..8066ead959--- /dev/null+++ b/crates/macro_db_client/migrations/20260729145833_create_reminders_tables.sql@@ -0,0 +1,92 @@+-- Reminders: a user's scheduled nudges, optionally attached to an entity.+--+-- Ids are generated by the application as uuid v7 (macro_uuid), not by the+-- database, so they are time-ordered and known before the insert returns.+CREATE TABLE IF NOT EXISTS reminder+(+ id UUID PRIMARY KEY NOT NULL,+ user_id TEXT NOT NULL REFERENCES "User" (id) ON DELETE CASCADE,+ description TEXT NOT NULL,+ -- Optional, polymorphic entity association. Every reminderable entity is+ -- keyed by a uuid — email_threads, comms_channels, calls, crm_companies+ -- and crm_contacts are uuid columns already, and "Document"/"Chat"/+ -- "Project" hold uuid values in text columns pending their own migration.+ -- Storing uuid here keeps this table correct now instead of inheriting a+ -- conversion later. Polymorphism still rules out an FK; readers filter+ -- dangling rows.+ entity_type TEXT,+ entity_id UUID,+ -- One-shot mode: the single instant to fire at.+ remind_at TIMESTAMPTZ,+ -- Recurring mode: a 6-/7-field cron expression interpreted in `timezone`.+ cron TEXT,+ timezone TEXT,+ -- Next firing, derived from the schedule on write so the dispatcher polls+ -- an index instead of parsing cron, and clients can render "next run".+ next_run_at TIMESTAMPTZ NOT NULL,+ enabled BOOLEAN NOT NULL DEFAULT TRUE,+ -- Set once a reminder has fired and will not fire again. Only the one-shot+ -- mode reaches that state today; the dispatcher will decide what, if+ -- anything, completion means for a recurring reminder, so nothing here+ -- prevents the column being set on one.+ completed_at TIMESTAMPTZ,+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ -- An entity association is both columns or neither.+ CONSTRAINT reminder_entity_both_or_neither+ CHECK ((entity_type IS NULL) = (entity_id IS NULL)),+ -- Exactly one schedule mode, and a cron always carries its timezone.+ CONSTRAINT reminder_schedule_exactly_one+ CHECK (+ num_nonnulls(remind_at, cron) = 1+ AND (cron IS NULL) = (timezone IS NULL)+ ),+ -- The DB is the final guardrail for what the service already validates, so+ -- a direct SQL path cannot leave an unusable row behind. `length()` counts+ -- characters, matching the service's char-based limit.+ CONSTRAINT reminder_description_non_empty+ CHECK (length(btrim(description)) > 0),+ CONSTRAINT reminder_description_max_length+ CHECK (length(btrim(description)) <= 2000),+ -- No non-empty check on entity_id: a uuid cannot be blank.+ CONSTRAINT reminder_entity_type_non_empty+ CHECK (entity_type IS NULL OR length(btrim(entity_type)) > 0)+);++-- The caller's reminders, in firing order. Serves `includeCompleted=true`,+-- which the partial index below cannot.+CREATE INDEX IF NOT EXISTS reminder_user_next_run_idx+ ON reminder (user_id, next_run_at);++-- The default list query excludes completed reminders and pages on+-- (next_run_at, created_at, id), so index exactly that.+CREATE INDEX IF NOT EXISTS reminder_user_active_next_run_idx+ ON reminder (user_id, next_run_at, created_at, id)+ WHERE completed_at IS NULL;++-- Reverse lookup: "what reminders are set on this entity?"+CREATE INDEX IF NOT EXISTS reminder_entity_idx+ ON reminder (entity_type, entity_id)+ WHERE entity_id IS NOT NULL;++-- Dispatcher lookup: reminders that are due and still live.+CREATE INDEX IF NOT EXISTS reminder_due_idx+ ON reminder (next_run_at)+ WHERE enabled AND completed_at IS NULL;++-- One row per firing of a reminder. Written by the dispatcher, which does not+-- exist yet; CRUD leaves this table empty. Ids are application-generated uuid+-- v7, as on `reminder`.+CREATE TABLE IF NOT EXISTS reminder_occurrence+(+ id UUID PRIMARY KEY NOT NULL,+ reminder_id UUID NOT NULL REFERENCES reminder (id) ON DELETE CASCADE,+ scheduled_for TIMESTAMPTZ NOT NULL,+ -- NULL until delivery succeeds.+ sent_at TIMESTAMPTZ,+ created_at TIMESTAMPTZ NOT NULL DEFAULT now()+);++-- Makes delivery idempotent: a firing can only be claimed once.+CREATE UNIQUE INDEX IF NOT EXISTS reminder_occurrence_firing_idx+ ON reminder_occurrence (reminder_id, scheduled_for);diff --git a/crates/macro_db_client/src/item_access/delete.rs b/crates/macro_db_client/src/item_access/delete.rsindex 15bcd227e6..59d8ef6166 100644--- a/crates/macro_db_client/src/item_access/delete.rs+++ b/crates/macro_db_client/src/item_access/delete.rs@@ -41,7 +41,9 @@ pub async fn delete_user_entity_access_bulk(| EntityType::StaticFile| EntityType::CrmCompany| EntityType::CrmContact- | EntityType::ForeignEntity => {+ | EntityType::ForeignEntity+ // Reminders own no entity_access rows to delete.+ | EntityType::Reminder => {anyhow::bail!("invalid entity type")}EntityType::Project => {diff --git a/crates/macro_queues/src/lib.rs b/crates/macro_queues/src/lib.rsindex db30ab6fe0..d70f41faaf 100644--- a/crates/macro_queues/src/lib.rs+++ b/crates/macro_queues/src/lib.rs@@ -609,6 +609,15 @@ queue! {dev: "document-upload-finalizer-queue-dev",prod: "document-upload-finalizer-queue-prod",},+ /// Queue for reminder dispatch.+ ///+ /// Carries both the minutely sweep tick, which an EventBridge rule+ /// publishes directly, and the per-firing messages that sweep fans out.+ pub ReminderDispatchQueue {+ local: "reminder-dispatch-queue",+ dev: "reminder-dispatch-queue-dev",+ prod: "reminder-dispatch-queue-prod",+ },/// Queue for the organization retention handler/// (organization_retention_trigger `ORGANIZATION_RETENTION_QUEUE`).pub OrganizationRetentionQueue {diff --git a/crates/model-entity/src/lib.rs b/crates/model-entity/src/lib.rsindex 3217f639a4..addc17d293 100644--- a/crates/model-entity/src/lib.rs+++ b/crates/model-entity/src/lib.rs@@ -60,6 +60,8 @@ pub enum EntityType {CrmCompany,/// The entity is a CRM contact tracked by a teamCrmContact,+ /// The entity is a reminder set by a user+ Reminder,}impl EntityType {@@ -86,6 +88,10 @@ impl EntityType {// — they aren't rows in the `entity_access` table.EntityType::CrmCompany => false,EntityType::CrmContact => false,+ // A reminder is private to the user who set it. Access resolves+ // from its owner column, not from a row in the `entity_access`+ // table — the same shape as channels and CRM entities.+ EntityType::Reminder => false,}}/// provide an entity string slice to upgrade this type into an [Entity]diff --git a/crates/model_notifications/src/lib.rs b/crates/model_notifications/src/lib.rsindex a2740a6903..65ebb54188 100644--- a/crates/model_notifications/src/lib.rs+++ b/crates/model_notifications/src/lib.rs@@ -17,8 +17,8 @@ pub use metadata::{GithubPrMention, GithubPrMentionLocation, GithubPrNotificationCommon, GithubPrReview,GithubPrReviewState, GithubPrStatusChanged, GithubReviewRequested, InboxReauthRequiredMetadata,InviteToTeamMetadata, ItemSharedMetadata, MentionedInDocumentCommentMetadata, NewEmailMetadata,- NotificationDocumentSubType, NotificationTitle, RepliedToDocumentCommentThreadMetadata,- TaskAssignedMetadata,+ NotificationDocumentSubType, NotificationTitle, ReminderMetadata,+ RepliedToDocumentCommentThreadMetadata, TaskAssignedMetadata,};pub use unsubscribe::UserUnsubscribe;#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]@@ -212,6 +212,9 @@ define_notif_event!(/// A user was assigned to a task.TaskAssigned(TaskAssignedMetadata),+ /// A reminder the user set for themselves came due.+ Reminder(ReminderMetadata),+/// An AI assistant responded to a chat.AiResponse(AiResponseMetadata),@@ -272,6 +275,7 @@ impl NotificationTitle for NotifEvent {NotifEvent::TaskAssigned(task_assigned_metadata) => {task_assigned_metadata.format_title(sender_id)}+ NotifEvent::Reminder(reminder_metadata) => reminder_metadata.format_title(sender_id),NotifEvent::AiResponse(ai_response_metadata) => {ai_response_metadata.format_title(sender_id)}@@ -328,6 +332,7 @@ impl NotificationTitle for NotifEvent {NotifEvent::TaskAssigned(task_assigned_metadata) => {task_assigned_metadata.format_body(sender_id)}+ NotifEvent::Reminder(reminder_metadata) => reminder_metadata.format_body(sender_id),NotifEvent::AiResponse(ai_response_metadata) => {ai_response_metadata.format_body(sender_id)}diff --git a/crates/model_notifications/src/metadata.rs b/crates/model_notifications/src/metadata.rsindex b1ba3651bb..c77c39f1fe 100644--- a/crates/model_notifications/src/metadata.rs+++ b/crates/model_notifications/src/metadata.rs@@ -1331,3 +1331,76 @@ impl NotificationTitle for CallStartedMetadata {Ok(self.channel_name.clone().unwrap_or_default())}}++/// Metadata for a reminder the user set for themselves coming due.+///+/// There is no sender: a reminder is self-set, so the dispatcher sends it with+/// `sender_id: None` (a recipient who is also the sender is filtered out of+/// their own notification). Every formatter here must therefore work without+/// one.+///+/// The associated entity, when there is one, lives on the notification row+/// rather than in here, and clients resolve its name from that — so the+/// dispatcher does not have to look up a name across five entity types.+#[derive(Serialize, Deserialize, Debug, Clone, ToSchema)]+#[serde(rename_all = "camelCase")]+pub struct ReminderMetadata {+ /// The reminder that fired.+ #[schema(value_type = String, format = Uuid)]+ pub reminder_id: Uuid,+ /// What the user asked to be reminded about.+ pub description: String,+}++impl Notification for ReminderMetadata {+ const TYPE_NAME: &'static str = "reminder";+}++impl NotificationTitle for ReminderMetadata {+ fn format_title(+ &self,+ _sender_id: Option<MacroUserIdStr<'_>>,+ ) -> Result<String, rootcause::Report> {+ Ok("Reminder".to_string())+ }++ fn format_body(+ &self,+ _sender_id: Option<MacroUserIdStr<'_>>,+ ) -> Result<String, rootcause::Report> {+ // A description can be 2000 characters, which is 8 KB of UTF-8 at four+ // bytes each — twice Apple's 4 KB push payload limit, and the alert+ // renders only a few lines anyway. Cut on a char boundary.+ Ok(+ match self.description.char_indices().nth(REMINDER_BODY_MAX_CHARS) {+ None => self.description.clone(),+ Some((cut, _)) => format!("{}…", &self.description[..cut]),+ },+ )+ }+}++/// Characters of a reminder description kept in the notification body, chosen+/// so the APNS payload stays well inside Apple's 4 KB limit.+const REMINDER_BODY_MAX_CHARS: usize = 512;++impl NotificationExtIos for ReminderMetadata {+ type NotifData = PushNotificationData;++ fn collapse_key(&self, _entity: &Entity<'_>) -> NotifCollapseKey {+ // Keyed on the reminder rather than the entity: a redelivery of the+ // same firing should replace the alert, but a reminder is not "about"+ // the entity in the way a mention is, so two reminders on one document+ // stay two alerts.+ NotifCollapseKey::new(Self::TYPE_NAME).append(&self.reminder_id.to_string())+ }++ fn as_apns<'a>(+ &self,+ sender_id: Option<MacroUserIdStr<'a>>,+ _entity: &Entity<'_>,+ notification_id: Uuid,+ ) -> Option<APNSPushNotification<Self::NotifData>> {+ alert_apns(self, sender_id, notification_id, None).ok()+ }+}diff --git a/crates/model_notifications/src/metadata/test.rs b/crates/model_notifications/src/metadata/test.rsindex 0b4a912387..85d686ff43 100644--- a/crates/model_notifications/src/metadata/test.rs+++ b/crates/model_notifications/src/metadata/test.rs@@ -706,3 +706,67 @@ fn call_started_deserializes_from_legacy_kebab_case_tag() {};assert_eq!(actual.channel_name.as_deref(), Some("general"));}++#[test]+fn reminder_notif_event_round_trips_and_renders_without_a_sender() {+ let reminder_id = Uuid::parse_str("22222222-2222-4222-8222-222222222222").unwrap();+ let value = serde_json::json!({+ "tag": "reminder",+ "content": { "reminderId": reminder_id, "description": "Follow up on the contract" },+ });++ let event: crate::NotifEvent = serde_json::from_value(value.clone()).unwrap();++ // A reminder is self-set, so the dispatcher passes no sender. Formatting+ // must not depend on one.+ assert_eq!(event.format_title(None).unwrap(), "Reminder");+ assert_eq!(+ event.format_body(None).unwrap(),+ "Follow up on the contract"+ );++ let crate::NotifEvent::Reminder(actual) = event.clone() else {+ panic!("expected reminder variant");+ };+ assert_eq!(actual.reminder_id, reminder_id);+ assert_eq!(actual.description, "Follow up on the contract");++ assert_eq!(serde_json::to_value(&event).unwrap(), value);+}++#[test]+fn reminder_body_is_bounded_for_the_push_payload() {+ // Descriptions are allowed up to 2000 chars. Four-byte chars would make an+ // 8 KB body, over Apple's 4 KB payload limit, so the body is cut on a char+ // boundary rather than passed through whole.+ let metadata = ReminderMetadata {+ reminder_id: Uuid::parse_str("22222222-2222-4222-8222-222222222222").unwrap(),+ description: "🎉".repeat(2_000),+ };++ let body = metadata.format_body(None).unwrap();++ assert_eq!(body.chars().count(), 513, "512 chars plus the ellipsis");+ assert!(body.ends_with('…'));+ assert!(body.len() < 4_096, "must fit inside the APNS payload limit");+}++#[test]+fn reminder_collapse_key_is_per_reminder_not_per_entity() {+ let entity = EntityType::Document.with_entity_str("doc-1");+ let key = |id: &str| {+ ReminderMetadata {+ reminder_id: Uuid::parse_str(id).unwrap(),+ description: "x".to_string(),+ }+ .collapse_key(&entity)+ .into_hashed()+ .into_inner()+ };++ // Two reminders on the same document must not collapse into one alert.+ assert_ne!(+ key("22222222-2222-4222-8222-222222222222"),+ key("33333333-3333-4333-8333-333333333333")+ );+}diff --git a/crates/reminders/Cargo.toml b/crates/reminders/Cargo.tomlnew file mode 100644index 0000000000..cf8348bc92--- /dev/null+++ b/crates/reminders/Cargo.toml@@ -0,0 +1,59 @@+[package]+edition = "2024"+name = "reminders"+publish = false+version = "0.1.0"++[features]+default = []+# The queue worker. Transport-agnostic: it drives the domain through the+# dispatch ports, so it needs an async runtime but no AWS SDK.+dispatch = ["dep:serde_json", "dep:tokio", "dep:tokio-util", "ports"]+# The worker plus the SQS adapter that backs it.+dispatch-sqs = ["dep:aws-sdk-sqs", "dispatch", "outbound"]+inbound = [+ "dep:axum",+ "dep:macro_authorization",+ "dep:model-error-response",+ "dep:utoipa",+ "entity_access/inbound",+ "ports",+]+notify = ["dep:model_notifications", "dep:notification", "outbound"]+outbound = ["ports"]+ports = ["dep:entity_access", "dep:tracing"]+postgres = ["dep:macro_uuid", "dep:sqlx", "outbound"]++[dependencies]+aws-sdk-sqs = { workspace = true, optional = true }+axum = { workspace = true, optional = true }+chrono = { workspace = true, features = ["serde"] }+chrono-tz = { workspace = true }+cron = { workspace = true }+entity_access = { path = "../entity_access", optional = true, default-features = false, features = ["ports"] }+macro_authorization = { path = "../macro_authorization", optional = true, default-features = false, features = ["axum"] }+macro_user_id = { path = "../macro_user_id" }+macro_uuid = { path = "../macro_uuid", optional = true }+model-entity = { path = "../model-entity" }+rootcause = { workspace = true }+model-error-response = { path = "../model-error-response", optional = true }+model_notifications = { path = "../model_notifications", optional = true }+notification = { path = "../notification", optional = true }+serde = { workspace = true }+serde_json = { workspace = true, optional = true }+sqlx = { workspace = true, optional = true }+thiserror = { workspace = true }+tokio = { workspace = true, optional = true, features = ["macros", "time"] }+tokio-util = { workspace = true, optional = true }+tracing = { workspace = true, optional = true }+utoipa = { workspace = true, optional = true }+uuid = { workspace = true }+workspace-hack = { version = "0.1", path = "../workspace-hack" }++[dev-dependencies]+http-body-util = { workspace = true }+macro_db_migrator = { path = "../macro_db_migrator" }+model_user = { path = "../model_user" }+serde_json = { workspace = true }+tokio = { workspace = true, features = ["macros", "rt-multi-thread"] }+tower = { workspace = true }diff --git a/crates/reminders/src/domain.rs b/crates/reminders/src/domain.rsnew file mode 100644index 0000000000..8b08f72863--- /dev/null+++ b/crates/reminders/src/domain.rs@@ -0,0 +1,7 @@+//! Domain layer for reminders.++pub mod models;+#[cfg(feature = "ports")]+pub mod ports;+#[cfg(feature = "ports")]+pub mod service;diff --git a/crates/reminders/src/domain/models.rs b/crates/reminders/src/domain/models.rsnew file mode 100644index 0000000000..b567a705dd--- /dev/null+++ b/crates/reminders/src/domain/models.rs@@ -0,0 +1,536 @@+//! Domain models for reminders.++#[cfg(test)]+mod test;++use std::str::FromStr;++use chrono::{DateTime, Utc};+use chrono_tz::Tz;+use cron::Schedule as CronSchedule;+use macro_user_id::user_id::MacroUserIdStr;+use model_entity::{Entity, EntityType};+use serde::{Deserialize, Deserializer, Serialize};+use uuid::Uuid;++/// Upper bound on a reminder's description in characters, so list payloads+/// stay sane. Mirrored by the `reminder_description_max_length` DB constraint.+pub const MAX_DESCRIPTION_LEN: usize = 2_000;++/// Default number of reminders returned by a list request.+pub const DEFAULT_PAGE_SIZE: u32 = 100;++/// Largest page a client may ask for.+pub const MAX_PAGE_SIZE: u32 = 500;++/// A cron expression the `cron` crate could not parse.+#[derive(Debug, thiserror::Error)]+#[error(+ "invalid cron expression ({0}); expected 5 fields (min hour dom mon dow) \+ or 6-7 fields (sec min hour dom mon dow [year]), e.g. `0 0 9 * * *` for daily at 09:00"+)]+pub struct InvalidCron(String);++/// A cron expression, validated and normalized on construction.+///+/// The `cron` crate requires 6 or 7 fields (`sec min hour dom mon dow [year]`),+/// but the conventional 5-field form is what most clients send, so a 5-field+/// expression is normalized by prepending a zero-seconds field: `0 9 * * *`+/// becomes `0 0 9 * * *`, both meaning daily at 09:00.+#[derive(Debug, Clone, PartialEq, Eq, Serialize)]+#[serde(transparent)]+pub struct ReminderCron(String);++impl ReminderCron {+ /// Validate, normalize, and wrap a cron expression.+ pub fn parse(cron: impl Into<String>) -> Result<Self, InvalidCron> {+ let cron = normalize_cron(cron.into());+ CronSchedule::from_str(&cron).map_err(|e| InvalidCron(e.to_string()))?;+ Ok(Self(cron))+ }++ /// The expression as stored.+ pub fn as_str(&self) -> &str {+ &self.0+ }++ /// The first firing strictly after `after`, evaluated in `timezone` and+ /// returned in UTC. `None` when the expression has no further firing (it+ /// can be year-qualified).+ pub fn next_run_after(&self, after: DateTime<Utc>, timezone: Tz) -> Option<DateTime<Utc>> {+ CronSchedule::from_str(&self.0)+ .expect("cron validated on construction")+ .after(&after.with_timezone(&timezone))+ .next()+ .map(|dt| dt.with_timezone(&Utc))+ }+}++impl<'de> Deserialize<'de> for ReminderCron {+ fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {+ let raw = String::deserialize(deserializer)?;+ ReminderCron::parse(raw).map_err(serde::de::Error::custom)+ }+}++/// Drop any precision finer than a microsecond, matching what a cursor encodes+/// and what Postgres stores.+fn truncate_to_micros(at: DateTime<Utc>) -> DateTime<Utc> {+ DateTime::from_timestamp_micros(at.timestamp_micros()).unwrap_or(at)+}++/// Promote a conventional 5-field cron to the 6-field form the `cron` crate+/// parses. Anything else is passed through for `cron` to accept or reject.+fn normalize_cron(cron: String) -> String {+ if cron.split_whitespace().count() == 5 {+ return format!("0 {}", cron.trim());+ }+ cron+}++/// When a reminder fires.+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]+#[cfg_attr(feature = "inbound", derive(utoipa::ToSchema))]+#[serde(tag = "type", rename_all = "snake_case")]+pub enum ReminderSchedule {+ /// Fires once, at a fixed instant.+ #[serde(rename_all = "camelCase")]+ Once {+ /// The instant to fire at.+ remind_at: DateTime<Utc>,+ },+ /// Fires repeatedly, on a cron schedule evaluated in `timezone`.+ #[serde(rename_all = "camelCase")]+ Recurring {+ /// Cron expression, either the conventional 5-field+ /// `min hour dom mon dow` or the 6-/7-field+ /// `sec min hour dom mon dow [year]`. A 5-field expression is stored+ /// normalized to 6 fields with a zero seconds field, so `0 9 * * *` and+ /// `0 0 9 * * *` are the same schedule and both read back as the latter.+ #[cfg_attr(feature = "inbound", schema(value_type = String))]+ cron: ReminderCron,+ /// The timezone the cron expression is evaluated in.+ #[cfg_attr(feature = "inbound", schema(value_type = String))]+ timezone: Tz,+ },+}++impl ReminderSchedule {+ /// The first firing strictly after `now`, in UTC.+ ///+ /// `None` means the schedule will never fire again: a one-shot whose+ /// instant has passed, or a cron with no upcoming match.+ pub fn next_run_after(&self, now: DateTime<Utc>) -> Option<DateTime<Utc>> {+ match self {+ Self::Once { remind_at } => (*remind_at > now).then_some(*remind_at),+ Self::Recurring { cron, timezone } => cron.next_run_after(now, *timezone),+ }+ }++ /// Whether this schedule fires more than once.+ pub fn repeats(&self) -> bool {+ matches!(self, Self::Recurring { .. })+ }+}++/// A reminder belonging to a user.+///+/// `user_id` is deliberately absent: a reminder is only ever read by its owner,+/// so the field would be redundant on the wire.+#[derive(Debug, Clone, Serialize, Deserialize)]+#[cfg_attr(feature = "inbound", derive(utoipa::ToSchema))]+#[serde(rename_all = "camelCase")]+pub struct Reminder {+ /// Reminder id.+ pub id: Uuid,+ /// What to remind the user about.+ pub description: String,+ /// Type of the associated entity, when the reminder is attached to one.+ // Inlined so the shared `EntityType` component name is not claimed in+ // specs that also expose another `EntityType` enum.+ #[cfg_attr(feature = "inbound", schema(inline))]+ #[serde(skip_serializing_if = "Option::is_none")]+ pub entity_type: Option<EntityType>,+ /// Id of the associated entity, when the reminder is attached to one.+ #[serde(skip_serializing_if = "Option::is_none")]+ pub entity_id: Option<String>,+ /// When and how often the reminder fires.+ pub schedule: ReminderSchedule,+ /// The next firing, derived from `schedule` on write.+ pub next_run_at: DateTime<Utc>,+ /// When false, the dispatcher skips this reminder.+ pub enabled: bool,+ /// Set once a one-shot reminder has fired.+ #[serde(skip_serializing_if = "Option::is_none")]+ pub completed_at: Option<DateTime<Utc>>,+ /// When the reminder was created.+ pub created_at: DateTime<Utc>,+ /// When the reminder was last modified.+ pub updated_at: DateTime<Utc>,+}++impl Reminder {+ /// The associated entity, when the reminder is attached to one.+ pub fn entity(&self) -> Option<Entity<'_>> {+ match (self.entity_type, self.entity_id.as_deref()) {+ (Some(entity_type), Some(entity_id)) => Some(entity_type.with_entity_str(entity_id)),+ _ => None,+ }+ }+}++/// The caller's reminders, soonest firing first.+#[derive(Debug, Clone, Serialize, Deserialize)]+#[cfg_attr(feature = "inbound", derive(utoipa::ToSchema))]+#[serde(rename_all = "camelCase")]+pub struct RemindersList {+ /// The reminders.+ pub reminders: Vec<Reminder>,+ /// Pass back as `cursor` to fetch the next page. Absent on the last page —+ /// its absence is the only end-of-list signal, since a page can be short.+ #[serde(skip_serializing_if = "Option::is_none")]+ pub next_cursor: Option<String>,+}++/// A cursor into the list ordering, `(next_run_at, created_at, id)`.+///+/// Encoded as microsecond timestamps and a uuid joined by `.`, all of which are+/// unreserved in a URI, so the value survives a query string untouched. RFC 3339+/// would carry a `+` that decodes to a space, and `|` is not unreserved.+///+/// Positions compare at microsecond precision, matching Postgres `timestamptz`.+/// Reminders always originate from the repository, so their timestamps are+/// already microsecond-precise; [`ReminderCursor::after`] truncates anything+/// finer rather than silently rounding past a row.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub struct ReminderCursor {+ /// `next_run_at` of the last reminder on the previous page.+ pub next_run_at: DateTime<Utc>,+ /// `created_at` of the last reminder on the previous page.+ pub created_at: DateTime<Utc>,+ /// `id` of the last reminder on the previous page.+ pub id: Uuid,+}++/// A cursor string that could not be decoded.+#[derive(Debug, thiserror::Error)]+#[error("invalid cursor")]+pub struct InvalidCursor;++impl ReminderCursor {+ /// The cursor pointing just past `reminder`.+ ///+ /// Timestamps are truncated to microseconds so the cursor encodes without+ /// loss. A sub-microsecond timestamp (only reachable from a synthetic+ /// reminder, never from the repository) truncates downward, which can+ /// re-return that row rather than skip it.+ pub fn after(reminder: &Reminder) -> Self {+ Self {+ next_run_at: truncate_to_micros(reminder.next_run_at),+ created_at: truncate_to_micros(reminder.created_at),+ id: reminder.id,+ }+ }++ /// Encode for transport.+ pub fn encode(&self) -> String {+ format!(+ "{}.{}.{}",+ self.next_run_at.timestamp_micros(),+ self.created_at.timestamp_micros(),+ self.id+ )+ }++ /// Decode a cursor produced by [`ReminderCursor::encode`].+ pub fn decode(raw: &str) -> Result<Self, InvalidCursor> {+ let mut parts = raw.split('.');+ let next_run_at = parts.next().ok_or(InvalidCursor)?;+ let created_at = parts.next().ok_or(InvalidCursor)?;+ let id = parts.next().ok_or(InvalidCursor)?;+ if parts.next().is_some() {+ return Err(InvalidCursor);+ }++ let micros_to_utc = |raw: &str| {+ raw.parse::<i64>()+ .ok()+ .and_then(DateTime::from_timestamp_micros)+ .ok_or(InvalidCursor)+ };++ Ok(Self {+ next_run_at: micros_to_utc(next_run_at)?,+ created_at: micros_to_utc(created_at)?,+ id: id.parse().map_err(|_| InvalidCursor)?,+ })+ }+}++/// One batch of rows read from storage.+///+/// Rows that could not be decoded are reported rather than dropped silently:+/// the caller needs `last_examined` to advance the cursor past them, otherwise+/// a page made entirely of unreadable rows would end pagination early and hide+/// every readable row behind it.+#[derive(Debug, Clone, Default)]+pub struct ReminderBatch {+ /// The rows that decoded successfully, in `(next_run_at, created_at, id)` order.+ pub reminders: Vec<Reminder>,+ /// How many rows in this batch could not be decoded.+ pub skipped: usize,+ /// Position of the last row examined, decoded or not. `None` for an empty+ /// batch.+ pub last_examined: Option<ReminderCursor>,+}++impl ReminderBatch {+ /// Total rows read, including the ones that could not be decoded.+ pub fn examined(&self) -> usize {+ self.reminders.len() + self.skipped+ }+}++/// One page of reminders.+#[derive(Debug, Clone)]+pub struct ReminderPage {+ /// The reminders on this page, soonest firing first.+ pub reminders: Vec<Reminder>,+ /// Where the next page starts, when there is one.+ pub next_cursor: Option<ReminderCursor>,+}++/// A request to create a reminder, before validation.+#[derive(Debug, Clone)]+pub struct CreateReminder {+ /// What to remind the user about.+ pub description: String,+ /// When and how often the reminder fires.+ ///+ /// The entity to attach to is not named here: it comes from the+ /// [`EntityAccessReceipt`](entity_access::domain::models::EntityAccessReceipt)+ /// passed alongside, so a caller cannot reference an entity without first+ /// proving access to it.+ pub schedule: ReminderSchedule,+}++/// A request to modify a reminder. `None` leaves a field unchanged; the entity+/// association is not modifiable, since changing it would need a fresh access+/// receipt for the new entity.+#[derive(Debug, Clone, Default)]+pub struct ReminderPatch {+ /// Replacement description.+ pub description: Option<String>,+ /// Replacement schedule.+ pub schedule: Option<ReminderSchedule>,+ /// Whether the dispatcher should consider this reminder.+ pub enabled: Option<bool>,+}++impl ReminderPatch {+ /// Whether the patch would change anything.+ pub fn is_empty(&self) -> bool {+ self.description.is_none() && self.schedule.is_none() && self.enabled.is_none()+ }+}++/// Which of a user's reminders to list, and where in the ordering to resume.+#[derive(Debug, Clone, Default)]+pub struct ReminderFilter {+ /// Restrict to reminders attached to this entity.+ pub entity: Option<Entity<'static>>,+ /// Include reminders that have already fired.+ pub include_completed: bool,+ /// Resume after this position in the ordering.+ pub cursor: Option<ReminderCursor>,+ /// Page size requested by the caller. `None` uses [`DEFAULT_PAGE_SIZE`];+ /// anything above [`MAX_PAGE_SIZE`] is clamped down to it.+ pub limit: Option<u32>,+}++impl ReminderFilter {+ /// The effective page size, clamped into range.+ pub fn page_size(&self) -> u32 {+ self.limit+ .unwrap_or(DEFAULT_PAGE_SIZE)+ .clamp(1, MAX_PAGE_SIZE)+ }+}++/// A validated reminder ready to be persisted, with `next_run_at` derived.+#[derive(Debug, Clone)]+pub struct NewReminder {+ /// What to remind the user about.+ pub description: String,+ /// The entity the reminder is attached to, if any.+ pub entity: Option<Entity<'static>>,+ /// When and how often the reminder fires.+ pub schedule: ReminderSchedule,+ /// The first firing, derived from `schedule`.+ pub next_run_at: DateTime<Utc>,+}++/// A new schedule together with the `next_run_at` derived from it.+#[derive(Debug, Clone)]+pub struct ScheduleUpdate {+ /// The replacement schedule.+ pub schedule: ReminderSchedule,+ /// The next firing, derived from `schedule`.+ pub next_run_at: DateTime<Utc>,+}++/// A validated partial update.+#[derive(Debug, Clone, Default)]+pub struct ReminderUpdate {+ /// Replacement description.+ pub description: Option<String>,+ /// Replacement schedule and its derived next firing.+ pub schedule: Option<ScheduleUpdate>,+ /// Replacement enabled flag.+ pub enabled: Option<bool>,+}++/// A reminder that is due to fire, with everything the dispatcher needs to+/// notify its owner.+///+/// Carries `owner_id` because dispatch is the one path that crosses users:+/// [`RemindersRepo`](crate::domain::ports::RemindersRepo) is scoped to a single+/// caller, while the dispatcher sweeps every user's reminders at once.+#[derive(Debug, Clone)]+pub struct DueReminder {+ /// The reminder itself.+ pub reminder: Reminder,+ /// The user the reminder belongs to, and the only recipient of its+ /// notification.+ pub owner_id: MacroUserIdStr<'static>,+ /// The firing being delivered. Also the occurrence's `scheduled_for`, which+ /// is what makes a firing claimable exactly once.+ pub scheduled_for: DateTime<Utc>,+}++/// One firing to deliver: the reminder, and which of its firings this is.+///+/// What a sweep fans out and a delivery resolves back into a [`DueReminder`].+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub struct DueFiring {+ /// The reminder that came due.+ pub reminder_id: Uuid,+ /// The firing, which is also the occurrence's `scheduled_for`.+ pub scheduled_for: DateTime<Utc>,+}++/// A message on the reminder dispatch queue.+///+/// Wrapped in a struct rather than being a bare enum because EventBridge sends+/// the minutely tick as a literal `{"operation":"sweep"}` payload, and that+/// shape has to survive round-tripping through this type.+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct ReminderDispatchMessage {+ /// What the receiving worker should do.+ pub operation: ReminderDispatchOperation,+}++impl ReminderDispatchMessage {+ /// Wrap an operation for publishing.+ pub fn new(operation: ReminderDispatchOperation) -> Self {+ Self { operation }+ }++ /// The message a sweep publishes for one due firing.+ pub fn deliver(firing: DueFiring) -> Self {+ Self::new(ReminderDispatchOperation::Deliver {+ reminder_id: firing.reminder_id,+ scheduled_for: firing.scheduled_for,+ })+ }+}++/// The work one dispatch message asks for.+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub enum ReminderDispatchOperation {+ /// Find everything due and fan out a `Deliver` for each.+ ///+ /// A unit variant so it serializes as the bare string `"sweep"`: this is+ /// the static payload an EventBridge rule puts on the queue every minute,+ /// and a rule can only send a constant.+ Sweep,+ /// Deliver one firing: claim it, notify the owner, complete it.+ Deliver {+ /// The reminder that came due.+ reminder_id: Uuid,+ /// Which firing of it. Stale values are dropped rather than delivered+ /// — see [`DeliveryOutcome::Gone`].+ scheduled_for: DateTime<Utc>,+ },+}++/// What one sweep did, for logging and metrics.+#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]+pub struct SweepSummary {+ /// Firings fanned out onto the queue.+ pub dispatched: usize,+}++/// What became of one `Deliver` message.+///+/// Every variant is a success in the queueing sense — the message is acked.+/// A failure that should be retried surfaces as an `Err` instead.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum DeliveryOutcome {+ /// Notified and completed.+ Delivered,+ /// Another worker holds the claim, or it already sent. Duplicate fan-out+ /// is expected — overlapping sweeps and redelivered sweep messages both+ /// produce it — and this is where it stops being a double-send.+ AlreadyClaimed,+ /// Nothing left to deliver: the reminder was deleted, completed, disabled,+ /// or rescheduled out from under this message between sweep and delivery.+ Gone,+ /// The reminder recurs. Recurring dispatch is not implemented, and firing+ /// one here would deliver it once and complete it forever.+ SkippedRecurring,+}++/// Errors returned by the reminders service.+#[derive(Debug, thiserror::Error)]+pub enum ReminderError {+ /// No such reminder belongs to the caller.+ #[error("reminder not found")]+ NotFound,+ /// The entity the reminder would be attached to does not exist. Distinct+ /// from [`ReminderError::NotFound`] so a failed create does not tell the+ /// caller "reminder not found" about a reminder they were trying to make.+ #[error("entity not found")]+ EntityNotFound,+ /// The request was invalid.+ #[error("{0}")]+ BadRequest(String),+ /// The caller may not attach a reminder to the requested entity. This is an+ /// authorization failure and maps to `403`; authentication failures (`401`)+ /// are produced by the authorization extractor before a handler runs.+ #[error("you do not have access to this entity")]+ EntityAccessDenied,+ /// Any other internal error.+ #[error("internal reminders error: {0:?}")]+ Internal(rootcause::Report),+}++impl From<rootcause::Report> for ReminderError {+ fn from(report: rootcause::Report) -> Self {+ ReminderError::Internal(report)+ }+}++impl From<InvalidCron> for ReminderError {+ fn from(err: InvalidCron) -> Self {+ ReminderError::BadRequest(err.to_string())+ }+}++impl From<InvalidCursor> for ReminderError {+ fn from(err: InvalidCursor) -> Self {+ ReminderError::BadRequest(err.to_string())+ }+}diff --git a/crates/reminders/src/domain/models/test.rs b/crates/reminders/src/domain/models/test.rsnew file mode 100644index 0000000000..01359430f5--- /dev/null+++ b/crates/reminders/src/domain/models/test.rs@@ -0,0 +1,441 @@+use chrono::TimeZone;+use chrono_tz::America::New_York;++use super::*;++/// Daily at 09:00 in the cron crate's 6-field form.+const DAILY_9AM: &str = "0 0 9 * * *";++fn utc(y: i32, m: u32, d: u32, h: u32, min: u32) -> DateTime<Utc> {+ Utc.with_ymd_and_hms(y, m, d, h, min, 0)+ .single()+ .expect("unambiguous instant")+}++#[test]+fn cron_parse_accepts_six_field_expression() {+ let cron = ReminderCron::parse(DAILY_9AM).expect("six-field cron should parse");+ assert_eq!(cron.as_str(), DAILY_9AM);+}++#[test]+fn cron_parse_rejects_garbage() {+ assert!(ReminderCron::parse("not a cron").is_err());+}++#[test]+fn cron_parse_normalizes_conventional_five_field_expression() {+ // The cron crate wants a seconds field, but 5-field is what clients+ // actually send, so it is promoted rather than rejected.+ let cron = ReminderCron::parse("0 9 * * *").expect("five-field cron should normalize");+ assert_eq!(cron.as_str(), DAILY_9AM);++ // The normalized form means the same thing as the explicit one.+ let five = ReminderSchedule::Recurring {+ cron: ReminderCron::parse("0 9 * * *").expect("valid cron"),+ timezone: New_York,+ };+ let six = ReminderSchedule::Recurring {+ cron: ReminderCron::parse(DAILY_9AM).expect("valid cron"),+ timezone: New_York,+ };+ assert_eq!(+ five.next_run_after(utc(2026, 7, 1, 0, 0)),+ six.next_run_after(utc(2026, 7, 1, 0, 0))+ );+}++#[test]+fn cron_parse_rejects_a_field_count_it_cannot_interpret() {+ // Four fields is not a form either convention uses.+ assert!(ReminderCron::parse("9 * * *").is_err());+}++#[test]+fn invalid_cron_error_names_both_accepted_forms() {+ let err = ReminderCron::parse("not a cron").expect_err("garbage should be rejected");+ let message = err.to_string();+ assert!(+ message.contains("5 fields"),+ "unexpected message: {message}"+ );+ assert!(+ message.contains("6-7 fields"),+ "unexpected message: {message}"+ );+ assert!(+ message.contains("0 0 9 * * *"),+ "unexpected message: {message}"+ );+}++#[test]+fn recurring_next_run_is_evaluated_in_the_reminder_timezone() {+ let schedule = ReminderSchedule::Recurring {+ cron: ReminderCron::parse(DAILY_9AM).expect("valid cron"),+ timezone: New_York,+ };++ // July: New York is UTC-4, so 09:00 local is 13:00Z.+ let next = schedule+ .next_run_after(utc(2026, 7, 1, 0, 0))+ .expect("daily cron always has an upcoming firing");+ assert_eq!(next, utc(2026, 7, 1, 13, 0));++ // January: New York is UTC-5, so the same expression lands at 14:00Z.+ let next = schedule+ .next_run_after(utc(2026, 1, 1, 0, 0))+ .expect("daily cron always has an upcoming firing");+ assert_eq!(next, utc(2026, 1, 1, 14, 0));+}++#[test]+fn recurring_next_run_skips_todays_firing_once_it_has_passed() {+ let schedule = ReminderSchedule::Recurring {+ cron: ReminderCron::parse(DAILY_9AM).expect("valid cron"),+ timezone: New_York,+ };++ let next = schedule+ .next_run_after(utc(2026, 7, 1, 13, 0))+ .expect("daily cron always has an upcoming firing");+ assert_eq!(next, utc(2026, 7, 2, 13, 0));+}++#[test]+fn once_next_run_is_the_instant_itself() {+ let remind_at = utc(2026, 7, 1, 13, 0);+ let schedule = ReminderSchedule::Once { remind_at };++ assert_eq!(+ schedule.next_run_after(utc(2026, 7, 1, 12, 0)),+ Some(remind_at)+ );+}++#[test]+fn once_next_run_is_none_once_the_instant_has_passed() {+ let schedule = ReminderSchedule::Once {+ remind_at: utc(2026, 7, 1, 13, 0),+ };++ assert_eq!(schedule.next_run_after(utc(2026, 7, 1, 13, 0)), None);+ assert_eq!(schedule.next_run_after(utc(2026, 7, 1, 14, 0)), None);+}++#[test]+fn repeats_distinguishes_the_two_modes() {+ let once = ReminderSchedule::Once {+ remind_at: utc(2026, 7, 1, 13, 0),+ };+ let recurring = ReminderSchedule::Recurring {+ cron: ReminderCron::parse(DAILY_9AM).expect("valid cron"),+ timezone: New_York,+ };++ assert!(!once.repeats());+ assert!(recurring.repeats());+}++#[test]+fn schedule_round_trips_through_the_wire_format() {+ let once: ReminderSchedule =+ serde_json::from_str(r#"{"type":"once","remindAt":"2026-07-01T13:00:00Z"}"#)+ .expect("one-shot schedule should deserialize");+ assert_eq!(+ once,+ ReminderSchedule::Once {+ remind_at: utc(2026, 7, 1, 13, 0)+ }+ );++ let recurring: ReminderSchedule = serde_json::from_str(+ r#"{"type":"recurring","cron":"0 0 9 * * *","timezone":"America/New_York"}"#,+ )+ .expect("recurring schedule should deserialize");+ assert_eq!(+ recurring,+ ReminderSchedule::Recurring {+ cron: ReminderCron::parse(DAILY_9AM).expect("valid cron"),+ timezone: New_York,+ }+ );++ let json = serde_json::to_value(&recurring).expect("schedule should serialize");+ assert_eq!(json["type"], "recurring");+ assert_eq!(json["cron"], DAILY_9AM);+ assert_eq!(json["timezone"], "America/New_York");+}++#[test]+fn deserializing_an_invalid_cron_fails_at_the_edge() {+ let err = serde_json::from_str::<ReminderSchedule>(+ r#"{"type":"recurring","cron":"every tuesday","timezone":"America/New_York"}"#,+ )+ .expect_err("an uninterpretable cron should be rejected");+ assert!(+ err.to_string().contains("invalid cron expression"),+ "unexpected error: {err}"+ );+}++#[test]+fn entity_is_present_only_when_both_columns_are() {+ let reminder = |entity_type, entity_id| Reminder {+ id: Uuid::nil(),+ description: "ping".to_string(),+ entity_type,+ entity_id,+ schedule: ReminderSchedule::Once {+ remind_at: utc(2026, 7, 1, 13, 0),+ },+ next_run_at: utc(2026, 7, 1, 13, 0),+ enabled: true,+ completed_at: None,+ created_at: utc(2026, 6, 1, 0, 0),+ updated_at: utc(2026, 6, 1, 0, 0),+ };++ let attached = reminder(Some(EntityType::Document), Some("doc-1".to_string()));+ let entity = attached.entity().expect("attached reminder has an entity");+ assert_eq!(entity.entity_type, EntityType::Document);+ assert_eq!(entity.entity_id, "doc-1");++ assert!(reminder(None, None).entity().is_none());+}++#[test]+fn empty_patch_is_detected() {+ assert!(ReminderPatch::default().is_empty());+ assert!(+ !ReminderPatch {+ enabled: Some(false),+ ..Default::default()+ }+ .is_empty()+ );+}++/// 02:30 daily — a local time that does not exist on the spring-forward date.+const DAILY_230AM: &str = "0 30 2 * * *";+/// 01:30 daily — a local time that happens twice on the fall-back date.+const DAILY_130AM: &str = "0 30 1 * * *";++fn ny_recurring(cron: &str) -> ReminderSchedule {+ ReminderSchedule::Recurring {+ cron: ReminderCron::parse(cron).expect("valid cron"),+ timezone: New_York,+ }+}++#[test]+fn a_local_time_skipped_by_spring_forward_does_not_fire_that_day() {+ // New York springs forward 2026-03-08: 02:00 becomes 03:00, so 02:30 never+ // occurs. The firing is skipped rather than shifted into the new offset.+ let schedule = ny_recurring(DAILY_230AM);++ // From late on the 6th, the next firing is the 7th at 02:30 EST (07:30Z).+ assert_eq!(+ schedule.next_run_after(utc(2026, 3, 7, 0, 0)),+ Some(utc(2026, 3, 7, 7, 30))+ );++ // Past the 7th's firing, the next is the 9th at 02:30 EDT (06:30Z) — the+ // 8th is skipped entirely.+ assert_eq!(+ schedule.next_run_after(utc(2026, 3, 8, 0, 0)),+ Some(utc(2026, 3, 9, 6, 30))+ );+}++#[test]+fn a_local_time_repeated_by_fall_back_fires_only_once() {+ // New York falls back 2026-11-01: 02:00 becomes 01:00, so 01:30 occurs+ // twice — once at 05:30Z (EDT) and again at 06:30Z (EST). Only the first+ // fires, so the user is not reminded twice.+ let schedule = ny_recurring(DAILY_130AM);++ assert_eq!(+ schedule.next_run_after(utc(2026, 11, 1, 0, 0)),+ Some(utc(2026, 11, 1, 5, 30))+ );++ // After the first occurrence, the schedule moves to the next day rather+ // than firing the repeated 01:30 an hour later.+ assert_eq!(+ schedule.next_run_after(utc(2026, 11, 1, 5, 45)),+ Some(utc(2026, 11, 2, 6, 30))+ );+}++#[test]+fn a_daily_cron_holds_its_local_time_across_a_dst_boundary() {+ // The product-visible promise: "remind me at 9am daily" stays 9am local,+ // even though the UTC instant shifts by an hour.+ let schedule = ny_recurring(DAILY_9AM);++ // 2026-03-07 (EST): 09:00 local is 14:00Z.+ assert_eq!(+ schedule.next_run_after(utc(2026, 3, 6, 15, 0)),+ Some(utc(2026, 3, 7, 14, 0))+ );+ // 2026-03-08 onward (EDT): 09:00 local is 13:00Z.+ assert_eq!(+ schedule.next_run_after(utc(2026, 3, 7, 15, 0)),+ Some(utc(2026, 3, 8, 13, 0))+ );+ assert_eq!(+ schedule.next_run_after(utc(2026, 3, 8, 15, 0)),+ Some(utc(2026, 3, 9, 13, 0))+ );+}++#[test]+fn cursor_round_trips_through_its_encoding() {+ let reminder = Reminder {+ id: Uuid::from_u128(7),+ description: "ping".to_string(),+ entity_type: None,+ entity_id: None,+ schedule: ReminderSchedule::Once {+ remind_at: utc(2026, 7, 1, 13, 0),+ },+ next_run_at: utc(2026, 7, 1, 13, 0),+ enabled: true,+ completed_at: None,+ created_at: utc(2026, 6, 1, 0, 0),+ updated_at: utc(2026, 6, 1, 0, 0),+ };++ let cursor = ReminderCursor::after(&reminder);+ let encoded = cursor.encode();+ assert_eq!(+ ReminderCursor::decode(&encoded).expect("cursor should decode"),+ cursor+ );++ // Only RFC 3986 unreserved characters, so no client, proxy, or query-string+ // parser has cause to re-encode or mangle it.+ assert!(+ encoded+ .chars()+ .all(|c| c.is_ascii_alphanumeric() || "-._~".contains(c)),+ "cursor is not URL-safe: {encoded}"+ );+ assert!(+ !encoded.contains('|'),+ "the pipe delimiter is not unreserved"+ );+}++#[test]+fn cursor_preserves_sub_second_precision() {+ // Postgres timestamps carry microseconds; a cursor that rounded to seconds+ // would skip or repeat rows sharing a second.+ let precise = DateTime::from_timestamp_micros(1_780_000_000_123_456).expect("valid instant");+ let cursor = ReminderCursor {+ next_run_at: precise,+ created_at: precise,+ id: Uuid::from_u128(1),+ };++ let decoded = ReminderCursor::decode(&cursor.encode()).expect("cursor should decode");+ assert_eq!(decoded.next_run_at, precise);+ assert_eq!(decoded.next_run_at.timestamp_subsec_micros(), 123_456);+}++#[test]+fn a_malformed_cursor_is_rejected() {+ for raw in [+ "",+ "abc",+ // Too few parts, too many, then a bad component in each position.+ "1",+ "1.2",+ "1.2.00000000-0000-0000-0000-000000000001.4",+ "notanumber.2.00000000-0000-0000-0000-000000000001",+ "1.notanumber.00000000-0000-0000-0000-000000000001",+ "1.2.not-a-uuid",+ ] {+ assert!(+ ReminderCursor::decode(raw).is_err(),+ "should have rejected {raw:?}"+ );+ }+}++#[test]+fn page_size_defaults_and_clamps() {+ assert_eq!(ReminderFilter::default().page_size(), DEFAULT_PAGE_SIZE);+ assert_eq!(+ ReminderFilter {+ limit: Some(25),+ ..Default::default()+ }+ .page_size(),+ 25+ );+ assert_eq!(+ ReminderFilter {+ limit: Some(u32::MAX),+ ..Default::default()+ }+ .page_size(),+ MAX_PAGE_SIZE+ );+ assert_eq!(+ ReminderFilter {+ limit: Some(0),+ ..Default::default()+ }+ .page_size(),+ 1+ );+}++/// The literal payload the EventBridge rule is configured to send. A rule can+/// only publish a constant, so this string is the contract: if the enum stops+/// round-tripping it, the minutely tick silently stops working.+const EVENTBRIDGE_SWEEP_PAYLOAD: &str = r#"{"operation":"sweep"}"#;++#[test]+fn the_eventbridge_sweep_payload_round_trips() {+ let parsed: ReminderDispatchMessage =+ serde_json::from_str(EVENTBRIDGE_SWEEP_PAYLOAD).expect("parses");++ assert_eq!(parsed.operation, ReminderDispatchOperation::Sweep);+ assert_eq!(+ serde_json::to_string(&parsed).expect("serializes"),+ EVENTBRIDGE_SWEEP_PAYLOAD+ );+}++#[test]+fn a_deliver_message_round_trips() {+ let firing = DueFiring {+ reminder_id: uuid::Uuid::from_bytes([7; 16]),+ scheduled_for: utc(2026, 7, 1, 12, 0),+ };+ let message = ReminderDispatchMessage::deliver(firing);++ let encoded = serde_json::to_string(&message).expect("serializes");+ let decoded: ReminderDispatchMessage = serde_json::from_str(&encoded).expect("parses");++ assert_eq!(decoded, message);+ assert_eq!(+ decoded.operation,+ ReminderDispatchOperation::Deliver {+ reminder_id: firing.reminder_id,+ scheduled_for: firing.scheduled_for,+ }+ );+}++#[test]+fn an_unknown_operation_is_rejected() {+ // The worker relies on this to discard a message it cannot act on rather+ // than letting it cycle to the dead-letter queue.+ let result = serde_json::from_str::<ReminderDispatchMessage>(r#"{"operation":"explode"}"#);++ assert!(result.is_err());+}diff --git a/crates/reminders/src/domain/ports.rs b/crates/reminders/src/domain/ports.rsnew file mode 100644index 0000000000..7b47dd0f0e--- /dev/null+++ b/crates/reminders/src/domain/ports.rs@@ -0,0 +1,272 @@+//! Ports (trait contracts) for the reminders domain.++use chrono::{DateTime, Utc};+use entity_access::domain::models::{AnyEntityPermission, EntityAccessReceipt, OwnerAccessLevel};+use macro_user_id::user_id::MacroUserIdStr;+use uuid::Uuid;++use crate::domain::models::{+ CreateReminder, DeliveryOutcome, DueFiring, DueReminder, NewReminder, Reminder, ReminderBatch,+ ReminderDispatchMessage, ReminderError, ReminderFilter, ReminderPage, ReminderPatch,+ ReminderUpdate, SweepSummary,+};++/// Source of the current time.+///+/// Injected so schedule boundaries — "exactly now", DST transitions, a cron+/// whose last firing has passed — can be tested deterministically instead of+/// relative to the wall clock.+pub trait Clock: Send + Sync + 'static {+ /// The current instant.+ fn now(&self) -> DateTime<Utc>;+}++/// The real clock.+#[derive(Debug, Clone, Copy, Default)]+pub struct SystemClock;++impl Clock for SystemClock {+ fn now(&self) -> DateTime<Utc> {+ Utc::now()+ }+}++/// Outbound persistence port for reminders.+///+/// Every method is scoped to a user: a reminder is private to its owner, so an+/// id belonging to someone else simply misses rather than erroring.+pub trait RemindersRepo: Send + Sync + 'static {+ /// The error type returned by repository operations.+ type Err: std::error::Error + Send + Sync + 'static;++ /// Insert a reminder for the user.+ fn create_reminder(+ &self,+ user_id: &MacroUserIdStr<'_>,+ new: &NewReminder,+ ) -> impl Future<Output = Result<Reminder, Self::Err>> + Send;++ /// Fetch one of the user's reminders.+ fn get_reminder(+ &self,+ user_id: &MacroUserIdStr<'_>,+ id: Uuid,+ ) -> impl Future<Output = Result<Option<Reminder>, Self::Err>> + Send;++ /// Read at most `limit` of the user's reminders matching `filter`, ordered+ /// by `(next_run_at, created_at, id)` and resuming after `filter.cursor`.+ ///+ /// The caller asks for one more than the page size to discover whether+ /// another page exists, and must use [`ReminderBatch::examined`] — not the+ /// decoded row count — to make that judgement.+ fn list_reminders(+ &self,+ user_id: &MacroUserIdStr<'_>,+ filter: &ReminderFilter,+ limit: i64,+ ) -> impl Future<Output = Result<ReminderBatch, Self::Err>> + Send;++ /// Apply `update` to one of the user's reminders, returning the new state.+ fn update_reminder(+ &self,+ user_id: &MacroUserIdStr<'_>,+ id: Uuid,+ update: &ReminderUpdate,+ ) -> impl Future<Output = Result<Option<Reminder>, Self::Err>> + Send;++ /// Delete one of the user's reminders. Returns `true` when a row was removed.+ fn delete_reminder(+ &self,+ user_id: &MacroUserIdStr<'_>,+ id: Uuid,+ ) -> impl Future<Output = Result<bool, Self::Err>> + Send;+}++/// Outbound persistence port for firing reminders.+///+/// Deliberately separate from [`RemindersRepo`], whose every method is scoped+/// to one user. Dispatch is the only path that reads across users, and folding+/// it in would quietly retire that invariant.+pub trait ReminderDispatchRepo: Send + Sync + 'static {+ /// The error type returned by repository operations.+ type Err: std::error::Error + Send + Sync + 'static;++ /// Every firing due at or before `now`, soonest first.+ ///+ /// Enabled, not yet completed, and not recurring. Returns identifiers+ /// rather than whole reminders because a sweep only fans these out; the+ /// row is read at delivery, by which point it may have changed.+ ///+ /// Deliberately unbounded — a sweep that silently truncated would strand+ /// whatever fell off the end until someone noticed. See the note on the+ /// implementation for where paging goes if a sweep ever grows too large+ /// to fan out inside one message.+ fn due_firings(+ &self,+ now: DateTime<Utc>,+ ) -> impl Future<Output = Result<Vec<DueFiring>, Self::Err>> + Send;++ /// Resolve a fanned-out firing back into the reminder to deliver.+ ///+ /// `None` when the reminder no longer wants this firing — deleted,+ /// completed, disabled, or rescheduled since the sweep listed it. Recurring+ /// reminders are *not* filtered out here; the domain decides what to do+ /// with those so the gap stays visible.+ fn find_due_reminder(+ &self,+ firing: DueFiring,+ ) -> impl Future<Output = Result<Option<DueReminder>, Self::Err>> + Send;++ /// Claim one firing for delivery, returning whether this caller now owns it.+ ///+ /// `false` means the firing already delivered, or another dispatcher holds+ /// it. A claim taken before `retry_before` and never delivered is+ /// reclaimable, so a dispatcher that dies mid-flight does not strand the+ /// reminder forever.+ fn claim_occurrence(+ &self,+ reminder_id: Uuid,+ scheduled_for: DateTime<Utc>,+ retry_before: DateTime<Utc>,+ ) -> impl Future<Output = Result<bool, Self::Err>> + Send;++ /// Give up a claim that was taken but never delivered.+ ///+ /// What makes a failed delivery retryable on the queue's own schedule: the+ /// message is redelivered within the visibility timeout, and without this+ /// the retry would lose the claim race against itself until `retry_before`+ /// finally aged the claim out. A delivered firing is never released.+ fn release_occurrence(+ &self,+ reminder_id: Uuid,+ scheduled_for: DateTime<Utc>,+ ) -> impl Future<Output = Result<(), Self::Err>> + Send;++ /// Record the firing as delivered and complete the reminder, atomically.+ ///+ /// Both halves together: a delivered firing must never leave its reminder+ /// still due, or the next sweep sends it again.+ fn complete_occurrence(+ &self,+ reminder_id: Uuid,+ scheduled_for: DateTime<Utc>,+ ) -> impl Future<Output = Result<(), Self::Err>> + Send;+}++/// A message as it came off the dispatch queue, still unparsed.+///+/// The body stays a string so the worker can ack a message it cannot parse:+/// decoding in the adapter would leave a poison message to be redelivered+/// until the redrive policy dead-lettered it.+#[derive(Debug, Clone, PartialEq, Eq)]+pub struct RawDispatchMessage {+ /// The raw JSON body.+ pub body: String,+ /// Handle used to delete the message once it has been handled.+ pub receipt_handle: String,+}++/// Outbound port for the queue that carries dispatch work.+///+/// One port for both directions because it is one queue: a sweep publishes+/// the `Deliver` messages that the same worker pool then receives.+pub trait ReminderDispatchQueue: Send + Sync + 'static {+ /// The error type returned by queue operations.+ type Err: std::error::Error + Send + Sync + 'static;++ /// Publish messages, batching as the transport allows.+ ///+ /// All-or-nothing per call: a partial failure is an error, and the caller+ /// is expected to let the triggering message be redelivered. Re-fanning a+ /// firing that already went out is harmless — it loses the claim race.+ fn publish_batch(+ &self,+ messages: &[ReminderDispatchMessage],+ ) -> impl Future<Output = Result<(), Self::Err>> + Send;++ /// Receive whatever is waiting, up to the adapter's configured batch size.+ fn receive_messages(+ &self,+ ) -> impl Future<Output = Result<Vec<RawDispatchMessage>, Self::Err>> + Send;++ /// Delete a message that has been handled.+ fn delete_message(+ &self,+ receipt_handle: &str,+ ) -> impl Future<Output = Result<(), Self::Err>> + Send;+}++/// Outbound port for telling a reminder's owner that it fired.+///+/// Takes domain types and returns nothing, so the domain never sees how the+/// notification is built or delivered.+pub trait ReminderNotifier: Send + Sync + 'static {+ /// The error type returned by delivery attempts.+ type Err: std::error::Error + Send + Sync + 'static;++ /// Notify the reminder's owner. Failure leaves the firing undelivered and+ /// retryable.+ fn notify(&self, due: &DueReminder) -> impl Future<Output = Result<(), Self::Err>> + Send;+}++/// Inbound service port: dispatch, driven by the queue worker.+///+/// Two use cases rather than one, because they arrive as two different+/// messages: a scheduled tick fans work out, and each fanned-out message+/// delivers a single firing.+pub trait ReminderDispatch: Send + Sync + 'static {+ /// Fan out every firing that is currently due.+ fn sweep(&self) -> impl Future<Output = Result<SweepSummary, ReminderError>> + Send;++ /// Deliver one fanned-out firing.+ fn deliver(+ &self,+ firing: DueFiring,+ ) -> impl Future<Output = Result<DeliveryOutcome, ReminderError>> + Send;+}++/// Inbound service port: the reminders API used by drivers (HTTP).+pub trait RemindersService: Send + Sync + 'static {+ /// Create a reminder for the user.+ ///+ /// `entity_receipt` must be present whenever `request` names an entity, and+ /// must have been minted for that same entity and user — that is what+ /// proves the caller may attach a reminder to it. Standalone reminders need+ /// no receipt.+ fn create_reminder(+ &self,+ user_id: &MacroUserIdStr<'_>,+ request: CreateReminder,+ entity_receipt: Option<EntityAccessReceipt<AnyEntityPermission>>,+ ) -> impl Future<Output = Result<Reminder, ReminderError>> + Send;++ /// Fetch the reminder the receipt was minted for.+ ///+ /// The receipt carries both the reminder and the caller it was proven for,+ /// so there is no separate id or user to pass — and no way to reach a+ /// reminder without having proven ownership first.+ fn get_reminder(+ &self,+ receipt: EntityAccessReceipt<OwnerAccessLevel>,+ ) -> impl Future<Output = Result<Reminder, ReminderError>> + Send;++ /// List one page of the user's reminders, soonest firing first.+ fn list_reminders(+ &self,+ user_id: &MacroUserIdStr<'_>,+ filter: ReminderFilter,+ ) -> impl Future<Output = Result<ReminderPage, ReminderError>> + Send;++ /// Modify the reminder the receipt was minted for.+ fn update_reminder(+ &self,+ receipt: EntityAccessReceipt<OwnerAccessLevel>,+ patch: ReminderPatch,+ ) -> impl Future<Output = Result<Reminder, ReminderError>> + Send;++ /// Delete the reminder the receipt was minted for.+ fn delete_reminder(+ &self,+ receipt: EntityAccessReceipt<OwnerAccessLevel>,+ ) -> impl Future<Output = Result<(), ReminderError>> + Send;+}diff --git a/crates/reminders/src/domain/service.rs b/crates/reminders/src/domain/service.rsnew file mode 100644index 0000000000..90a5524873--- /dev/null+++ b/crates/reminders/src/domain/service.rs@@ -0,0 +1,326 @@+//! Reminders service implementation.++pub mod dispatch;++#[cfg(test)]+mod test;++use chrono::{DateTime, Utc};+use entity_access::domain::models::{AnyEntityPermission, EntityAccessReceipt, OwnerAccessLevel};+use macro_user_id::user_id::MacroUserIdStr;+use model_entity::Entity;+use uuid::Uuid;++use crate::domain::models::{+ CreateReminder, MAX_DESCRIPTION_LEN, NewReminder, Reminder, ReminderBatch, ReminderCursor,+ ReminderError, ReminderFilter, ReminderPage, ReminderPatch, ReminderSchedule, ReminderUpdate,+ ScheduleUpdate,+};+use crate::domain::ports::{Clock, RemindersRepo, RemindersService, SystemClock};++/// How many storage reads one list request may make while trying to fill a page.+///+/// Only reached when rows cannot be decoded; a normal page costs one read.+const MAX_LIST_BATCHES: usize = 5;++/// Concrete reminders service backed by a [RemindersRepo].+#[derive(Debug, Clone)]+pub struct RemindersServiceImpl<R, C = SystemClock> {+ repo: R,+ clock: C,+}++impl<R> RemindersServiceImpl<R, SystemClock>+where+ R: RemindersRepo,+{+ /// Create a reminders service backed by the provided repository, reading+ /// the current time from the system clock.+ pub fn new(repo: R) -> Self {+ Self {+ repo,+ clock: SystemClock,+ }+ }+}++impl<R, C> RemindersServiceImpl<R, C>+where+ R: RemindersRepo,+ C: Clock,+{+ /// Create a reminders service with an explicit clock.+ pub fn with_clock(repo: R, clock: C) -> Self {+ Self { repo, clock }+ }+}++/// Trim and bounds-check a description.+///+/// The limit counts characters rather than bytes, so a description of emoji is+/// measured the same way a client would count it.+fn validate_description(description: String) -> Result<String, ReminderError> {+ let trimmed = description.trim();+ if trimmed.is_empty() {+ return Err(ReminderError::BadRequest(+ "description must not be empty".to_string(),+ ));+ }+ if trimmed.chars().count() > MAX_DESCRIPTION_LEN {+ return Err(ReminderError::BadRequest(format!(+ "description must be at most {MAX_DESCRIPTION_LEN} characters"+ )));+ }+ Ok(trimmed.to_string())+}++/// Derive the first firing, rejecting schedules that will never fire.+fn derive_next_run_at(+ schedule: &ReminderSchedule,+ now: DateTime<Utc>,+) -> Result<DateTime<Utc>, ReminderError> {+ schedule.next_run_after(now).ok_or_else(|| match schedule {+ ReminderSchedule::Once { .. } => {+ ReminderError::BadRequest("remindAt must be in the future".to_string())+ }+ ReminderSchedule::Recurring { .. } => {+ ReminderError::BadRequest("cron has no upcoming firing".to_string())+ }+ })+}++/// The entity a reminder attaches to, taken from the access receipt.+///+/// The receipt is the only source. A caller cannot name an entity it has not+/// proven access to, because there is nowhere else to put the id — which is+/// the point of taking a receipt rather than an entity: the type makes the+/// access check unskippable instead of merely expected.+fn resolve_entity(+ user_id: &MacroUserIdStr<'_>,+ entity_receipt: Option<EntityAccessReceipt<AnyEntityPermission>>,+) -> Result<Option<Entity<'static>>, ReminderError> {+ let Some(receipt) = entity_receipt else {+ return Ok(None);+ };++ // The receipt proves access for whoever it was minted for; it must be this+ // caller, or one user could attach a reminder using another's receipt.+ let receipt_user = receipt+ .get_authenticated_user()+ .map_err(|_| ReminderError::EntityAccessDenied)?;+ if receipt_user.as_ref() != user_id.as_ref() {+ return Err(ReminderError::EntityAccessDenied);+ }++ let entity = receipt.entity();+ Ok(Some(+ entity+ .entity_type+ .with_entity_string(entity.entity_id.clone()),+ ))+}++/// The owner and reminder id a receipt was minted for.+///+/// Both come off the receipt so a caller cannot address one reminder while+/// holding proof for another. The repo stays user-scoped on top of this: the+/// receipt says who proved what, the `WHERE user_id` says what the query may+/// touch.+fn receipt_owner_and_id(+ receipt: &EntityAccessReceipt<OwnerAccessLevel>,+) -> Result<(MacroUserIdStr<'static>, Uuid), ReminderError> {+ let user_id = receipt+ .get_authenticated_user()+ .map_err(|_| ReminderError::NotFound)?+ .clone();+ let id = receipt+ .entity()+ .entity_id+ .parse::<Uuid>()+ .map_err(|_| ReminderError::NotFound)?;+ Ok((user_id, id))+}++impl<R, C> RemindersService for RemindersServiceImpl<R, C>+where+ R: RemindersRepo,+ C: Clock,+{+ // `user_id` is the auth-provider composite id (it embeds the user's email)+ // and `request`/`patch` carry the user-authored description, so neither is+ // recorded as a span field.+ #[tracing::instrument(err, skip(self, user_id, request, entity_receipt))]+ async fn create_reminder(+ &self,+ user_id: &MacroUserIdStr<'_>,+ request: CreateReminder,+ entity_receipt: Option<EntityAccessReceipt<AnyEntityPermission>>,+ ) -> Result<Reminder, ReminderError> {+ let CreateReminder {+ description,+ schedule,+ } = request;++ let description = validate_description(description)?;+ let entity = resolve_entity(user_id, entity_receipt)?;+ let next_run_at = derive_next_run_at(&schedule, self.clock.now())?;++ let new = NewReminder {+ description,+ entity,+ schedule,+ next_run_at,+ };++ Ok(self+ .repo+ .create_reminder(user_id, &new)+ .await+ .map_err(|e| rootcause::Report::new(e).into_dynamic())?)+ }++ #[tracing::instrument(err, skip(self, receipt))]+ async fn get_reminder(+ &self,+ receipt: EntityAccessReceipt<OwnerAccessLevel>,+ ) -> Result<Reminder, ReminderError> {+ let (user_id, id) = receipt_owner_and_id(&receipt)?;+ self.repo+ .get_reminder(&user_id, id)+ .await+ .map_err(|e| rootcause::Report::new(e).into_dynamic())?+ .ok_or(ReminderError::NotFound)+ }++ #[tracing::instrument(err, skip(self, user_id))]+ async fn list_reminders(+ &self,+ user_id: &MacroUserIdStr<'_>,+ filter: ReminderFilter,+ ) -> Result<ReminderPage, ReminderError> {+ let page_size = filter.page_size() as usize;+ // One extra row answers "is there another page?" without a count query.+ let probe_limit = i64::from(filter.page_size()) + 1;++ let mut reminders: Vec<Reminder> = Vec::new();+ let mut cursor = filter.cursor;+ let mut next_cursor = None;++ // Undecodable rows are skipped, which would otherwise hand the client a+ // short — possibly empty — page even though readable rows remain. Read+ // again from where the last batch stopped so a page is either full or+ // final, and clients can treat "no cursor" as the only end condition.+ // Bounded so a long run of bad rows degrades into a short page rather+ // than an unbounded scan.+ for _ in 0..MAX_LIST_BATCHES {+ let probe = ReminderFilter {+ cursor,+ ..filter.clone()+ };+ let batch = self+ .repo+ .list_reminders(user_id, &probe, probe_limit)+ .await+ .map_err(|e| rootcause::Report::new(e).into_dynamic())?;++ // `examined`, not the decoded count: a batch whose extra row could+ // not be decoded still proves more rows exist.+ let has_more = batch.examined() > page_size;+ let ReminderBatch {+ reminders: decoded,+ last_examined,+ ..+ } = batch;++ let exhausted = !has_more;+ reminders.extend(decoded);++ if reminders.len() > page_size {+ // The probe row is a reminder we are about to drop, so resume+ // from the last row we actually return.+ reminders.truncate(page_size);+ next_cursor = reminders.last().map(ReminderCursor::after);+ break;+ }++ if exhausted {+ // Nothing further matches the filter at all.+ next_cursor = None;+ break;+ }++ // More rows exist. Resume past everything read, including rows that+ // could not be decoded, so they cannot stall pagination.+ cursor = last_examined;+ next_cursor = last_examined;++ if reminders.len() == page_size {+ break;+ }+ }++ Ok(ReminderPage {+ reminders,+ next_cursor,+ })+ }++ #[tracing::instrument(err, skip(self, receipt, patch))]+ async fn update_reminder(+ &self,+ receipt: EntityAccessReceipt<OwnerAccessLevel>,+ patch: ReminderPatch,+ ) -> Result<Reminder, ReminderError> {+ let (user_id, id) = receipt_owner_and_id(&receipt)?;+ if patch.is_empty() {+ return Err(ReminderError::BadRequest("no fields to update".to_string()));+ }++ let ReminderPatch {+ description,+ schedule,+ enabled,+ } = patch;++ let description = description.map(validate_description).transpose()?;+ let schedule = schedule+ .map(|schedule| {+ let next_run_at = derive_next_run_at(&schedule, self.clock.now())?;+ Ok::<_, ReminderError>(ScheduleUpdate {+ schedule,+ next_run_at,+ })+ })+ .transpose()?;++ let update = ReminderUpdate {+ description,+ schedule,+ enabled,+ };++ self.repo+ .update_reminder(&user_id, id, &update)+ .await+ .map_err(|e| rootcause::Report::new(e).into_dynamic())?+ .ok_or(ReminderError::NotFound)+ }++ #[tracing::instrument(err, skip(self, receipt))]+ async fn delete_reminder(+ &self,+ receipt: EntityAccessReceipt<OwnerAccessLevel>,+ ) -> Result<(), ReminderError> {+ let (user_id, id) = receipt_owner_and_id(&receipt)?;+ let deleted = self+ .repo+ .delete_reminder(&user_id, id)+ .await+ .map_err(|e| rootcause::Report::new(e).into_dynamic())?;+ if deleted {+ Ok(())+ } else {+ Err(ReminderError::NotFound)+ }+ }+}diff --git a/crates/reminders/src/domain/service/dispatch.rs b/crates/reminders/src/domain/service/dispatch.rsnew file mode 100644index 0000000000..86c5b473fa--- /dev/null+++ b/crates/reminders/src/domain/service/dispatch.rs@@ -0,0 +1,205 @@+//! Dispatch service: delivers reminders that have come due.+//!+//! Kept apart from [`RemindersServiceImpl`](super::RemindersServiceImpl) — that+//! is the caller-facing CRUD use case, scoped to one user; this one sweeps+//! every user's reminders on a schedule and needs no authorization, because a+//! reminder only ever notifies the owner who was authorized to create it.+//!+//! Two use cases, arriving as two different queue messages. A sweep finds what+//! is due and fans out one message per firing; each of those delivers a single+//! firing. Splitting them is what lets a pool of workers deliver in parallel+//! instead of one process walking a list.++#[cfg(test)]+mod test;++use chrono::{DateTime, Duration, Utc};++use crate::domain::models::{+ DeliveryOutcome, DueFiring, DueReminder, ReminderDispatchMessage, ReminderError, SweepSummary,+};+use crate::domain::ports::{+ Clock, ReminderDispatch, ReminderDispatchQueue, ReminderDispatchRepo, ReminderNotifier,+ SystemClock,+};++/// How long a claimed but undelivered firing is left alone before another+/// worker may take it over.+///+/// Only a crash net now: an ordinary delivery failure releases its own claim,+/// so this covers the case where the process died between claiming and+/// releasing. Long enough that a slow delivery is not raced, short enough that+/// a dead worker does not strand the firing.+const RETRY_AFTER: Duration = Duration::minutes(5);++/// Delivers due reminders to their owners.+#[derive(Debug, Clone)]+pub struct ReminderDispatchService<R, N, Q, C = SystemClock> {+ repo: R,+ notifier: N,+ queue: Q,+ clock: C,+}++impl<R, N, Q> ReminderDispatchService<R, N, Q, SystemClock>+where+ R: ReminderDispatchRepo,+ N: ReminderNotifier,+ Q: ReminderDispatchQueue,+{+ /// Create a dispatch service reading the current time from the system clock.+ pub fn new(repo: R, notifier: N, queue: Q) -> Self {+ Self {+ repo,+ notifier,+ queue,+ clock: SystemClock,+ }+ }+}++impl<R, N, Q, C> ReminderDispatchService<R, N, Q, C>+where+ R: ReminderDispatchRepo,+ N: ReminderNotifier,+ Q: ReminderDispatchQueue,+ C: Clock,+{+ /// Create a dispatch service with an explicit clock.+ pub fn with_clock(repo: R, notifier: N, queue: Q, clock: C) -> Self {+ Self {+ repo,+ notifier,+ queue,+ clock,+ }+ }++ /// Claim, notify, complete — in that order, for one resolved firing.+ ///+ /// Claiming first is what stops two workers double-sending; completing last+ /// is what makes a failed delivery retryable rather than lost.+ async fn deliver_claimed(+ &self,+ due: &DueReminder,+ now: DateTime<Utc>,+ ) -> Result<DeliveryOutcome, ReminderError> {+ let reminder_id = due.reminder.id;+ let scheduled_for = due.scheduled_for;++ let claimed = self+ .repo+ .claim_occurrence(reminder_id, scheduled_for, now - RETRY_AFTER)+ .await+ .map_err(|e| rootcause::Report::new(e).into_dynamic())?;+ if !claimed {+ return Ok(DeliveryOutcome::AlreadyClaimed);+ }++ if let Err(e) = self.notifier.notify(due).await {+ tracing::error!(+ error = ?e,+ reminder_id = %reminder_id,+ "failed to deliver reminder notification; releasing claim for retry",+ );++ // Hand the claim back before the message is redelivered, or the+ // retry would race a claim it owns itself and give up until+ // RETRY_AFTER aged it out. A failure here is not fatal: the claim+ // is stale-reclaimable, it just waits longer.+ if let Err(release_err) = self+ .repo+ .release_occurrence(reminder_id, scheduled_for)+ .await+ {+ tracing::error!(+ error = ?release_err,+ reminder_id = %reminder_id,+ "failed to release reminder claim after a failed delivery",+ );+ }++ return Err(ReminderError::Internal(+ rootcause::Report::new(e).into_dynamic(),+ ));+ }++ self.repo+ .complete_occurrence(reminder_id, scheduled_for)+ .await+ .map_err(|e| rootcause::Report::new(e).into_dynamic())?;++ Ok(DeliveryOutcome::Delivered)+ }+}++impl<R, N, Q, C> ReminderDispatch for ReminderDispatchService<R, N, Q, C>+where+ R: ReminderDispatchRepo,+ N: ReminderNotifier,+ Q: ReminderDispatchQueue,+ C: Clock,+{+ #[tracing::instrument(err, skip(self))]+ async fn sweep(&self) -> Result<SweepSummary, ReminderError> {+ let now = self.clock.now();+ let firings = self+ .repo+ .due_firings(now)+ .await+ .map_err(|e| rootcause::Report::new(e).into_dynamic())?;++ if firings.is_empty() {+ return Ok(SweepSummary::default());+ }++ let messages: Vec<ReminderDispatchMessage> = firings+ .iter()+ .copied()+ .map(ReminderDispatchMessage::deliver)+ .collect();++ // One failed publish fails the whole sweep, so the sweep message is+ // redelivered and the fan-out repeats. Firings that already went out+ // lose the claim race the second time, so the repeat costs messages+ // rather than duplicate notifications.+ self.queue+ .publish_batch(&messages)+ .await+ .map_err(|e| rootcause::Report::new(e).into_dynamic())?;++ Ok(SweepSummary {+ dispatched: messages.len(),+ })+ }++ #[tracing::instrument(err, skip(self))]+ async fn deliver(&self, firing: DueFiring) -> Result<DeliveryOutcome, ReminderError> {+ let now = self.clock.now();++ // Re-read rather than trusting the sweep: between fan-out and here the+ // reminder may have been deleted, completed, disabled or rescheduled,+ // and none of those should still fire.+ let Some(due) = self+ .repo+ .find_due_reminder(firing)+ .await+ .map_err(|e| rootcause::Report::new(e).into_dynamic())?+ else {+ return Ok(DeliveryOutcome::Gone);+ };++ // Recurring reminders are modelled but not dispatched yet. Guarded here+ // rather than in the query because this is the only place that could+ // actually send one — and completing it would retire the series.+ if due.reminder.schedule.repeats() {+ tracing::warn!(+ reminder_id = %due.reminder.id,+ "skipped a due recurring reminder; recurring dispatch is not implemented",+ );+ return Ok(DeliveryOutcome::SkippedRecurring);+ }++ self.deliver_claimed(&due, now).await+ }+}diff --git a/crates/reminders/src/domain/service/dispatch/test.rs b/crates/reminders/src/domain/service/dispatch/test.rsnew file mode 100644index 0000000000..8ab88dfc72--- /dev/null+++ b/crates/reminders/src/domain/service/dispatch/test.rs@@ -0,0 +1,474 @@+use std::sync::{Arc, Mutex};++use chrono::TimeZone;+use chrono_tz::America::New_York;+use macro_user_id::cowlike::CowLike;+use macro_user_id::user_id::MacroUserIdStr;+use model_entity::EntityType;+use uuid::Uuid;++use super::*;+use crate::domain::models::{Reminder, ReminderCron, ReminderSchedule};+use crate::domain::ports::RawDispatchMessage;++const OWNER: &str = "macro|[email protected]";+const DAILY_9AM: &str = "0 0 9 * * *";++fn now() -> DateTime<Utc> {+ Utc.with_ymd_and_hms(2026, 7, 1, 12, 0, 0)+ .single()+ .expect("unambiguous instant")+}++/// A clock frozen at [`now`].+#[derive(Debug, Clone, Copy)]+struct FixedClock(DateTime<Utc>);++impl Clock for FixedClock {+ fn now(&self) -> DateTime<Utc> {+ self.0+ }+}++fn owner() -> MacroUserIdStr<'static> {+ MacroUserIdStr::parse_from_str(OWNER)+ .expect("valid user id")+ .into_owned()+}++fn reminder(id: Uuid, schedule: ReminderSchedule) -> Reminder {+ Reminder {+ id,+ description: "Follow up".to_string(),+ entity_type: Some(EntityType::Document),+ entity_id: Some("doc-1".to_string()),+ next_run_at: now(),+ schedule,+ enabled: true,+ completed_at: None,+ created_at: now(),+ updated_at: now(),+ }+}++fn uuid(n: u8) -> Uuid {+ Uuid::from_bytes([n; 16])+}++fn firing(n: u8) -> DueFiring {+ DueFiring {+ reminder_id: uuid(n),+ scheduled_for: now(),+ }+}++fn due_once(n: u8) -> DueReminder {+ DueReminder {+ reminder: reminder(uuid(n), ReminderSchedule::Once { remind_at: now() }),+ owner_id: owner(),+ scheduled_for: now(),+ }+}++fn due_recurring(n: u8) -> DueReminder {+ let schedule = ReminderSchedule::Recurring {+ cron: ReminderCron::parse(DAILY_9AM).expect("valid cron"),+ timezone: New_York,+ };+ DueReminder {+ reminder: reminder(uuid(n), schedule),+ owner_id: owner(),+ scheduled_for: now(),+ }+}++#[derive(Debug, thiserror::Error)]+#[error("fake failure")]+struct FakeErr;++#[derive(Default)]+struct FakeRepoState {+ due: Vec<DueReminder>,+ /// Reminder ids whose claim should be refused, as if a peer won the race.+ unclaimable: Vec<Uuid>,+ claim_fails: bool,+ list_fails: bool,+ claimed: Vec<Uuid>,+ released: Vec<Uuid>,+ completed: Vec<Uuid>,+}++#[derive(Clone, Default)]+struct FakeRepo(Arc<Mutex<FakeRepoState>>);++impl FakeRepo {+ fn with_due(due: Vec<DueReminder>) -> Self {+ Self(Arc::new(Mutex::new(FakeRepoState {+ due,+ ..Default::default()+ })))+ }++ fn refusing_claim(self, id: Uuid) -> Self {+ self.0.lock().unwrap().unclaimable.push(id);+ self+ }++ fn failing_claim(self) -> Self {+ self.0.lock().unwrap().claim_fails = true;+ self+ }++ fn failing_list(self) -> Self {+ self.0.lock().unwrap().list_fails = true;+ self+ }++ fn claimed(&self) -> Vec<Uuid> {+ self.0.lock().unwrap().claimed.clone()+ }++ fn released(&self) -> Vec<Uuid> {+ self.0.lock().unwrap().released.clone()+ }++ fn completed(&self) -> Vec<Uuid> {+ self.0.lock().unwrap().completed.clone()+ }+}++impl ReminderDispatchRepo for FakeRepo {+ type Err = FakeErr;++ async fn due_firings(&self, _now: DateTime<Utc>) -> Result<Vec<DueFiring>, Self::Err> {+ let state = self.0.lock().unwrap();+ if state.list_fails {+ return Err(FakeErr);+ }+ Ok(state+ .due+ .iter()+ .map(|due| DueFiring {+ reminder_id: due.reminder.id,+ scheduled_for: due.scheduled_for,+ })+ .collect())+ }++ async fn find_due_reminder(&self, firing: DueFiring) -> Result<Option<DueReminder>, Self::Err> {+ Ok(self+ .0+ .lock()+ .unwrap()+ .due+ .iter()+ .find(|due| {+ due.reminder.id == firing.reminder_id && due.scheduled_for == firing.scheduled_for+ })+ .cloned())+ }++ async fn claim_occurrence(+ &self,+ reminder_id: Uuid,+ _scheduled_for: DateTime<Utc>,+ _retry_before: DateTime<Utc>,+ ) -> Result<bool, Self::Err> {+ let mut state = self.0.lock().unwrap();+ if state.claim_fails {+ return Err(FakeErr);+ }+ if state.unclaimable.contains(&reminder_id) {+ return Ok(false);+ }+ state.claimed.push(reminder_id);+ Ok(true)+ }++ async fn release_occurrence(+ &self,+ reminder_id: Uuid,+ _scheduled_for: DateTime<Utc>,+ ) -> Result<(), Self::Err> {+ self.0.lock().unwrap().released.push(reminder_id);+ Ok(())+ }++ async fn complete_occurrence(+ &self,+ reminder_id: Uuid,+ _scheduled_for: DateTime<Utc>,+ ) -> Result<(), Self::Err> {+ self.0.lock().unwrap().completed.push(reminder_id);+ Ok(())+ }+}++#[derive(Clone, Default)]+struct FakeNotifier {+ notified: Arc<Mutex<Vec<Uuid>>>,+ /// Reminder ids whose delivery should fail.+ failing: Arc<Mutex<Vec<Uuid>>>,+}++impl FakeNotifier {+ fn failing_for(id: Uuid) -> Self {+ Self {+ notified: Arc::default(),+ failing: Arc::new(Mutex::new(vec![id])),+ }+ }++ fn notified(&self) -> Vec<Uuid> {+ self.notified.lock().unwrap().clone()+ }+}++impl ReminderNotifier for FakeNotifier {+ type Err = FakeErr;++ async fn notify(&self, due: &DueReminder) -> Result<(), Self::Err> {+ if self.failing.lock().unwrap().contains(&due.reminder.id) {+ return Err(FakeErr);+ }+ self.notified.lock().unwrap().push(due.reminder.id);+ Ok(())+ }+}++#[derive(Clone, Default)]+struct FakeQueue {+ published: Arc<Mutex<Vec<ReminderDispatchMessage>>>,+ publish_fails: Arc<Mutex<bool>>,+}++impl FakeQueue {+ fn failing_publish() -> Self {+ Self {+ published: Arc::default(),+ publish_fails: Arc::new(Mutex::new(true)),+ }+ }++ fn published(&self) -> Vec<ReminderDispatchMessage> {+ self.published.lock().unwrap().clone()+ }+}++impl ReminderDispatchQueue for FakeQueue {+ type Err = FakeErr;++ async fn publish_batch(&self, messages: &[ReminderDispatchMessage]) -> Result<(), Self::Err> {+ if *self.publish_fails.lock().unwrap() {+ return Err(FakeErr);+ }+ self.published.lock().unwrap().extend_from_slice(messages);+ Ok(())+ }++ async fn receive_messages(&self) -> Result<Vec<RawDispatchMessage>, Self::Err> {+ Ok(Vec::new())+ }++ async fn delete_message(&self, _receipt_handle: &str) -> Result<(), Self::Err> {+ Ok(())+ }+}++fn service(+ repo: FakeRepo,+ notifier: FakeNotifier,+ queue: FakeQueue,+) -> ReminderDispatchService<FakeRepo, FakeNotifier, FakeQueue, FixedClock> {+ ReminderDispatchService::with_clock(repo, notifier, queue, FixedClock(now()))+}++// ---------------------------------------------------------------- sweep++#[tokio::test]+async fn a_sweep_fans_out_one_message_per_due_firing() {+ let repo = FakeRepo::with_due(vec![due_once(1), due_once(2), due_once(3)]);+ let queue = FakeQueue::default();++ let summary = service(repo, FakeNotifier::default(), queue.clone())+ .sweep()+ .await+ .expect("sweep succeeds");++ assert_eq!(summary.dispatched, 3);+ assert_eq!(+ queue.published(),+ vec![+ ReminderDispatchMessage::deliver(firing(1)),+ ReminderDispatchMessage::deliver(firing(2)),+ ReminderDispatchMessage::deliver(firing(3)),+ ]+ );+}++#[tokio::test]+async fn a_sweep_fans_out_recurring_reminders_it_is_given() {+ // The exclusion lives in the query, not the sweep: whatever the repo+ // reports as due is fanned out, and `deliver` is what refuses to send it.+ let repo = FakeRepo::with_due(vec![due_recurring(1)]);+ let queue = FakeQueue::default();++ let summary = service(repo, FakeNotifier::default(), queue.clone())+ .sweep()+ .await+ .expect("sweep succeeds");++ assert_eq!(summary.dispatched, 1);+ assert_eq!(queue.published().len(), 1);+}++#[tokio::test]+async fn an_empty_sweep_publishes_nothing() {+ let queue = FakeQueue::default();++ let summary = service(FakeRepo::default(), FakeNotifier::default(), queue.clone())+ .sweep()+ .await+ .expect("sweep succeeds");++ assert_eq!(summary, SweepSummary::default());+ assert!(queue.published().is_empty());+}++#[tokio::test]+async fn a_failed_publish_fails_the_sweep() {+ // The sweep message must not be acked: it is redelivered and the fan-out+ // repeats, which the claim makes harmless.+ let repo = FakeRepo::with_due(vec![due_once(1)]);++ let result = service(repo, FakeNotifier::default(), FakeQueue::failing_publish())+ .sweep()+ .await;++ assert!(matches!(result, Err(ReminderError::Internal(_))));+}++#[tokio::test]+async fn a_failed_listing_fails_the_sweep() {+ let repo = FakeRepo::default().failing_list();++ let result = service(repo, FakeNotifier::default(), FakeQueue::default())+ .sweep()+ .await;++ assert!(matches!(result, Err(ReminderError::Internal(_))));+}++// -------------------------------------------------------------- deliver++#[tokio::test]+async fn delivers_and_completes_a_due_one_shot() {+ let repo = FakeRepo::with_due(vec![due_once(1)]);+ let notifier = FakeNotifier::default();++ let outcome = service(repo.clone(), notifier.clone(), FakeQueue::default())+ .deliver(firing(1))+ .await+ .expect("delivery succeeds");++ assert_eq!(outcome, DeliveryOutcome::Delivered);+ assert_eq!(notifier.notified(), vec![uuid(1)]);+ assert_eq!(repo.claimed(), vec![uuid(1)]);+ assert_eq!(repo.completed(), vec![uuid(1)]);+ assert!(repo.released().is_empty());+}++#[tokio::test]+async fn skips_a_recurring_reminder_without_claiming_it() {+ let repo = FakeRepo::with_due(vec![due_recurring(1)]);+ let notifier = FakeNotifier::default();++ let outcome = service(repo.clone(), notifier.clone(), FakeQueue::default())+ .deliver(firing(1))+ .await+ .expect("delivery succeeds");++ assert_eq!(outcome, DeliveryOutcome::SkippedRecurring);+ // Nothing claimed: a recurring reminder must stay untouched for whenever+ // recurring dispatch lands, not burn its occurrence row.+ assert!(repo.claimed().is_empty());+ assert!(notifier.notified().is_empty());+}++#[tokio::test]+async fn a_firing_that_no_longer_exists_is_acked_not_delivered() {+ let repo = FakeRepo::default();+ let notifier = FakeNotifier::default();++ let outcome = service(repo.clone(), notifier.clone(), FakeQueue::default())+ .deliver(firing(1))+ .await+ .expect("delivery succeeds");++ assert_eq!(outcome, DeliveryOutcome::Gone);+ assert!(repo.claimed().is_empty());+ assert!(notifier.notified().is_empty());+}++#[tokio::test]+async fn a_rescheduled_firing_is_acked_not_delivered() {+ // Same reminder, different firing: the message is stale and must not send.+ let repo = FakeRepo::with_due(vec![due_once(1)]);+ let stale = DueFiring {+ reminder_id: uuid(1),+ scheduled_for: now() - Duration::hours(1),+ };++ let outcome = service(repo.clone(), FakeNotifier::default(), FakeQueue::default())+ .deliver(stale)+ .await+ .expect("delivery succeeds");++ assert_eq!(outcome, DeliveryOutcome::Gone);+ assert!(repo.claimed().is_empty());+}++#[tokio::test]+async fn does_not_notify_a_firing_another_worker_claimed() {+ let repo = FakeRepo::with_due(vec![due_once(1)]).refusing_claim(uuid(1));+ let notifier = FakeNotifier::default();++ let outcome = service(repo.clone(), notifier.clone(), FakeQueue::default())+ .deliver(firing(1))+ .await+ .expect("delivery succeeds");++ assert_eq!(outcome, DeliveryOutcome::AlreadyClaimed);+ assert!(notifier.notified().is_empty());+ assert!(repo.completed().is_empty());+}++#[tokio::test]+async fn releases_the_claim_when_delivery_fails() {+ let repo = FakeRepo::with_due(vec![due_once(1)]);+ let notifier = FakeNotifier::failing_for(uuid(1));++ let result = service(repo.clone(), notifier, FakeQueue::default())+ .deliver(firing(1))+ .await;++ // Errors so the message is redelivered rather than acked, and the claim is+ // handed back so that redelivery can actually take it.+ assert!(matches!(result, Err(ReminderError::Internal(_))));+ assert_eq!(repo.claimed(), vec![uuid(1)]);+ assert_eq!(repo.released(), vec![uuid(1)]);+ assert!(repo.completed().is_empty());+}++#[tokio::test]+async fn a_storage_failure_while_claiming_is_retryable() {+ let repo = FakeRepo::with_due(vec![due_once(1)]).failing_claim();+ let notifier = FakeNotifier::default();++ let result = service(repo, notifier.clone(), FakeQueue::default())+ .deliver(firing(1))+ .await;++ assert!(matches!(result, Err(ReminderError::Internal(_))));+ assert!(notifier.notified().is_empty());+}diff --git a/crates/reminders/src/domain/service/test.rs b/crates/reminders/src/domain/service/test.rsnew file mode 100644index 0000000000..ee8d3125da--- /dev/null+++ b/crates/reminders/src/domain/service/test.rs@@ -0,0 +1,1527 @@+use std::sync::{Arc, Mutex};++use chrono::{Duration, TimeZone};+use chrono_tz::America::New_York;+use entity_access::domain::models::{+ AccessLevel, AnyEntityPermission, Entity as AccessEntity, EntityAccessReceipt,+ EntityPermission, OwnerAccessLevel, ParticipantRole,+};+use model_entity::EntityType;++use super::*;+use crate::domain::models::{MAX_PAGE_SIZE, ReminderCron, RemindersList};++const USER_A: &str = "macro|[email protected]";+const USER_B: &str = "macro|[email protected]";+const DAILY_9AM: &str = "0 0 9 * * *";++fn user(id: &str) -> MacroUserIdStr<'_> {+ MacroUserIdStr::parse_from_str(id).expect("valid user id")+}++/// Fixed "current time" for every service test, so schedule boundaries are+/// deterministic rather than relative to the wall clock.+fn now() -> DateTime<Utc> {+ Utc.with_ymd_and_hms(2026, 7, 1, 12, 0, 0)+ .single()+ .expect("unambiguous instant")+}++fn future() -> DateTime<Utc> {+ now() + Duration::days(1)+}++fn once(remind_at: DateTime<Utc>) -> ReminderSchedule {+ ReminderSchedule::Once { remind_at }+}++fn recurring() -> ReminderSchedule {+ ReminderSchedule::Recurring {+ cron: ReminderCron::parse(DAILY_9AM).expect("valid cron"),+ timezone: New_York,+ }+}++/// A clock frozen at [`now`].+#[derive(Debug, Clone, Copy)]+struct FixedClock(DateTime<Utc>);++impl Clock for FixedClock {+ fn now(&self) -> DateTime<Utc> {+ self.0+ }+}++/// A receipt as the router would mint it: for this user, this entity, carrying+/// an `AccessLevel` permission — the shape documents, chats, projects, email+/// threads, calls and CRM records resolve to.+fn view_receipt(+ user_id: &'static str,+ entity_type: EntityType,+ entity_id: &str,+) -> EntityAccessReceipt<AnyEntityPermission> {+ receipt_with(+ user_id,+ entity_type,+ entity_id,+ EntityPermission::AccessLevel {+ access_level: AccessLevel::View,+ },+ )+}++/// An owner receipt for a reminder, as `ReminderAccessExtractor` mints it.+///+/// Get, update and delete take one of these instead of a user id and an id:+/// the reminder they act on is the one ownership was proven for.+fn owner_receipt(user_id: &'static str, id: Uuid) -> EntityAccessReceipt<OwnerAccessLevel> {+ EntityAccessReceipt::try_new_authenticated_user(+ user(user_id),+ AccessEntity {+ entity_id: id.to_string(),+ entity_type: EntityType::Reminder,+ },+ EntityPermission::AccessLevel {+ access_level: AccessLevel::Owner,+ },+ )+ .expect("owner satisfies an owner requirement")+}++/// A receipt carrying a channel permission.+///+/// Channels never resolve to an `AccessLevel`; they resolve to a participant+/// role or view-only. That is the whole reason the requirement is+/// `AnyEntityPermission` — `ViewAccessLevel` cannot be satisfied by either.+fn channel_receipt(+ user_id: &'static str,+ channel_id: &str,+ permission: EntityPermission,+) -> EntityAccessReceipt<AnyEntityPermission> {+ receipt_with(user_id, EntityType::Channel, channel_id, permission)+}++fn receipt_with(+ user_id: &'static str,+ entity_type: EntityType,+ entity_id: &str,+ permission: EntityPermission,+) -> EntityAccessReceipt<AnyEntityPermission> {+ EntityAccessReceipt::try_new_authenticated_user(+ user(user_id),+ AccessEntity {+ entity_id: entity_id.to_string(),+ entity_type,+ },+ permission,+ )+ .expect("any permission satisfies an any-permission requirement")+}++fn create_request(schedule: ReminderSchedule) -> CreateReminder {+ CreateReminder {+ description: "follow up".to_string(),+ schedule,+ }+}++/// A view receipt for a document, which is where an attached reminder's entity+/// comes from now that `create_reminder` takes a receipt rather than an entity.+fn doc_receipt(entity_id: &str) -> EntityAccessReceipt<AnyEntityPermission> {+ view_receipt(USER_A, EntityType::Document, entity_id)+}++#[derive(Debug, thiserror::Error)]+#[error("fake reminders repository error")]+struct FakeRepoError;++/// In-memory repository. User scoping, ordering, and keyset paging mirror the+/// SQL so the service's page assembly is exercised the same way.+#[derive(Clone, Default)]+struct FakeRemindersRepo {+ rows: Arc<Mutex<Vec<(String, Reminder)>>>,+ next_id: Arc<Mutex<u128>>,+ /// Ids the repository reports as undecodable, standing in for a row whose+ /// stored entity_type or cron no longer parses.+ unreadable: Arc<Mutex<Vec<Uuid>>>,+ /// When set, every method fails, standing in for a database outage.+ failing: Arc<Mutex<bool>>,+}++impl FakeRemindersRepo {+ fn rows(&self) -> Vec<(String, Reminder)> {+ self.rows.lock().expect("rows lock poisoned").clone()+ }++ /// Mark a row unreadable, as a schema drift would.+ fn make_unreadable(&self, id: Uuid) {+ self.unreadable+ .lock()+ .expect("unreadable lock poisoned")+ .push(id);+ }++ /// Make every subsequent call fail.+ fn start_failing(&self) {+ *self.failing.lock().expect("failing lock poisoned") = true;+ }++ fn check_failing(&self) -> Result<(), FakeRepoError> {+ if *self.failing.lock().expect("failing lock poisoned") {+ return Err(FakeRepoError);+ }+ Ok(())+ }++ fn is_unreadable(&self, id: Uuid) -> bool {+ self.unreadable+ .lock()+ .expect("unreadable lock poisoned")+ .contains(&id)+ }++ /// Sequential ids, and `created_at` stamped in insertion order so the+ /// `(next_run_at, created_at, id)` ordering is deterministic.+ fn mint_identity(&self) -> (Uuid, DateTime<Utc>) {+ let mut next = self.next_id.lock().expect("id lock poisoned");+ *next += 1;+ (+ Uuid::from_u128(*next),+ now() + Duration::seconds(*next as i64),+ )+ }+}++fn sort_key(reminder: &Reminder) -> (DateTime<Utc>, DateTime<Utc>, Uuid) {+ (reminder.next_run_at, reminder.created_at, reminder.id)+}++impl RemindersRepo for FakeRemindersRepo {+ type Err = FakeRepoError;++ async fn create_reminder(+ &self,+ user_id: &MacroUserIdStr<'_>,+ new: &NewReminder,+ ) -> Result<Reminder, Self::Err> {+ self.check_failing()?;+ let (id, created_at) = self.mint_identity();+ let reminder = Reminder {+ id,+ description: new.description.clone(),+ entity_type: new.entity.as_ref().map(|entity| entity.entity_type),+ entity_id: new+ .entity+ .as_ref()+ .map(|entity| entity.entity_id.to_string()),+ schedule: new.schedule.clone(),+ next_run_at: new.next_run_at,+ enabled: true,+ completed_at: None,+ created_at,+ updated_at: created_at,+ };+ self.rows+ .lock()+ .expect("rows lock poisoned")+ .push((user_id.as_ref().to_string(), reminder.clone()));+ Ok(reminder)+ }++ async fn get_reminder(+ &self,+ user_id: &MacroUserIdStr<'_>,+ id: Uuid,+ ) -> Result<Option<Reminder>, Self::Err> {+ self.check_failing()?;+ Ok(self+ .rows()+ .into_iter()+ .find(|(owner, reminder)| owner == user_id.as_ref() && reminder.id == id)+ .map(|(_, reminder)| reminder))+ }++ async fn list_reminders(+ &self,+ user_id: &MacroUserIdStr<'_>,+ filter: &ReminderFilter,+ limit: i64,+ ) -> Result<ReminderBatch, Self::Err> {+ self.check_failing()?;+ let mut found: Vec<Reminder> = self+ .rows()+ .into_iter()+ .filter(|(owner, _)| owner == user_id.as_ref())+ .map(|(_, reminder)| reminder)+ .filter(|reminder| filter.include_completed || reminder.completed_at.is_none())+ .filter(|reminder| match &filter.entity {+ Some(entity) => {+ reminder.entity_type == Some(entity.entity_type)+ && reminder.entity_id.as_deref() == Some(entity.entity_id.as_ref())+ }+ None => true,+ })+ .collect();+ found.sort_by_key(sort_key);+ if let Some(cursor) = filter.cursor {+ let cursor_key = (cursor.next_run_at, cursor.created_at, cursor.id);+ found.retain(|reminder| sort_key(reminder) > cursor_key);+ }+ found.truncate(limit.max(0) as usize);++ // Mirrors the SQL adapter: undecodable rows are counted and the last+ // position read is reported, rather than vanishing.+ let last_examined = found.last().map(ReminderCursor::after);+ let mut batch = ReminderBatch {+ reminders: Vec::new(),+ skipped: 0,+ last_examined,+ };+ for reminder in found {+ if self.is_unreadable(reminder.id) {+ batch.skipped += 1;+ } else {+ batch.reminders.push(reminder);+ }+ }+ Ok(batch)+ }++ async fn update_reminder(+ &self,+ user_id: &MacroUserIdStr<'_>,+ id: Uuid,+ update: &ReminderUpdate,+ ) -> Result<Option<Reminder>, Self::Err> {+ self.check_failing()?;+ let mut rows = self.rows.lock().expect("rows lock poisoned");+ let Some((_, reminder)) = rows+ .iter_mut()+ .find(|(owner, reminder)| owner == user_id.as_ref() && reminder.id == id)+ else {+ return Ok(None);+ };++ if let Some(description) = &update.description {+ reminder.description = description.clone();+ }+ if let Some(schedule) = &update.schedule {+ reminder.schedule = schedule.schedule.clone();+ reminder.next_run_at = schedule.next_run_at;+ // Mirrors the SQL: rescheduling revives a completed reminder.+ reminder.completed_at = None;+ }+ if let Some(enabled) = update.enabled {+ reminder.enabled = enabled;+ }+ reminder.updated_at = now();++ Ok(Some(reminder.clone()))+ }++ async fn delete_reminder(+ &self,+ user_id: &MacroUserIdStr<'_>,+ id: Uuid,+ ) -> Result<bool, Self::Err> {+ self.check_failing()?;+ let mut rows = self.rows.lock().expect("rows lock poisoned");+ let before = rows.len();+ rows.retain(|(owner, reminder)| !(owner == user_id.as_ref() && reminder.id == id));+ Ok(rows.len() < before)+ }+}++fn service() -> RemindersServiceImpl<FakeRemindersRepo, FixedClock> {+ RemindersServiceImpl::with_clock(FakeRemindersRepo::default(), FixedClock(now()))+}++/// Mark a reminder completed, standing in for the dispatcher.+fn complete(service: &RemindersServiceImpl<FakeRemindersRepo, FixedClock>, id: Uuid) {+ let mut rows = service.repo.rows.lock().expect("rows lock poisoned");+ let (_, reminder) = rows+ .iter_mut()+ .find(|(_, reminder)| reminder.id == id)+ .expect("reminder exists");+ reminder.completed_at = Some(now());+}++#[tokio::test]+async fn creates_a_standalone_reminder_without_a_receipt() {+ let remind_at = future();+ let reminder = service()+ .create_reminder(&user(USER_A), create_request(once(remind_at)), None)+ .await+ .expect("standalone reminder should be created");++ assert_eq!(reminder.description, "follow up");+ assert!(reminder.entity().is_none());+ assert_eq!(reminder.next_run_at, remind_at);+ assert!(reminder.enabled);+}++#[tokio::test]+async fn creates_an_entity_reminder_with_a_matching_receipt() {+ let reminder = service()+ .create_reminder(+ &user(USER_A),+ create_request(once(future())),+ Some(doc_receipt("doc-1")),+ )+ .await+ .expect("entity reminder should be created");++ let entity = reminder.entity().expect("entity should be persisted");+ assert_eq!(entity.entity_type, EntityType::Document);+ assert_eq!(entity.entity_id, "doc-1");+}++/// Regression: requiring `ViewAccessLevel` made every channel unattachable,+/// because a channel permission is a participant role, never an access level.+/// The failure surfaced as "you do not have access to this entity" on channels+/// the caller was a member of.+#[tokio::test]+async fn creates_a_channel_reminder_for_each_channel_permission_shape() {+ for permission in [+ EntityPermission::ChannelRole {+ role: ParticipantRole::Owner,+ },+ EntityPermission::ChannelRole {+ role: ParticipantRole::Admin,+ },+ EntityPermission::ChannelRole {+ role: ParticipantRole::Member,+ },+ EntityPermission::ChannelViewOnly,+ ] {+ let reminder = service()+ .create_reminder(+ &user(USER_A),+ create_request(once(future())),+ Some(channel_receipt(USER_A, "channel-1", permission.clone())),+ )+ .await+ .expect("a channel permission should allow attaching a reminder");++ let entity = reminder.entity().expect("entity should be persisted");+ assert_eq!(entity.entity_type, EntityType::Channel);+ assert_eq!(entity.entity_id, "channel-1");+ }+}++/// The receipt still has to be for this caller and this channel; loosening the+/// permission requirement must not loosen the identity check.+#[tokio::test]+async fn rejects_a_channel_receipt_minted_for_another_user() {+ let err = service()+ .create_reminder(+ &user(USER_A),+ create_request(once(future())),+ Some(channel_receipt(+ USER_B,+ "channel-1",+ EntityPermission::ChannelRole {+ role: ParticipantRole::Member,+ },+ )),+ )+ .await+ .expect_err("a receipt for another user must not authorize this one");++ assert!(matches!(err, ReminderError::EntityAccessDenied));+}++/// The entity is read off the receipt, so "receipt for a different entity",+/// "entity with no receipt" and "receipt with no entity" are all unrepresentable+/// — there is no second place to name an entity for them to disagree with.+#[tokio::test]+async fn the_attached_entity_comes_from_the_receipt() {+ let reminder = service()+ .create_reminder(+ &user(USER_A),+ create_request(once(future())),+ Some(view_receipt(USER_A, EntityType::Chat, "chat-9")),+ )+ .await+ .expect("entity reminder should be created");++ let entity = reminder.entity().expect("entity should be persisted");+ assert_eq!(entity.entity_type, EntityType::Chat);+ assert_eq!(entity.entity_id, "chat-9");+}++#[tokio::test]+async fn rejects_a_receipt_belonging_to_another_user() {+ let err = service()+ .create_reminder(+ &user(USER_A),+ create_request(once(future())),+ Some(view_receipt(USER_B, EntityType::Document, "doc-1")),+ )+ .await+ .expect_err("receipt user must be the caller");++ assert!(matches!(err, ReminderError::EntityAccessDenied));+}++#[tokio::test]+async fn rejects_a_blank_description() {+ let request = CreateReminder {+ description: " ".to_string(),+ ..create_request(once(future()))+ };++ let err = service()+ .create_reminder(&user(USER_A), request, None)+ .await+ .expect_err("blank description should be rejected");++ assert!(matches!(err, ReminderError::BadRequest(_)));+}++#[tokio::test]+async fn trims_the_description() {+ let request = CreateReminder {+ description: " follow up ".to_string(),+ ..create_request(once(future()))+ };++ let reminder = service()+ .create_reminder(&user(USER_A), request, None)+ .await+ .expect("reminder should be created");++ assert_eq!(reminder.description, "follow up");+}++#[tokio::test]+async fn description_limit_counts_characters_not_bytes() {+ // Each emoji is 4 bytes, so a byte-based limit would reject this at a+ // quarter of the documented length.+ let request = CreateReminder {+ description: "🎉".repeat(MAX_DESCRIPTION_LEN),+ ..create_request(once(future()))+ };++ let reminder = service()+ .create_reminder(&user(USER_A), request, None)+ .await+ .expect("a description of exactly the limit in chars should be accepted");+ assert_eq!(reminder.description.chars().count(), MAX_DESCRIPTION_LEN);++ let too_long = CreateReminder {+ description: "🎉".repeat(MAX_DESCRIPTION_LEN + 1),+ ..create_request(once(future()))+ };+ assert!(matches!(+ service()+ .create_reminder(&user(USER_A), too_long, None)+ .await,+ Err(ReminderError::BadRequest(_))+ ));+}++#[tokio::test]+async fn rejects_a_one_shot_in_the_past() {+ let request = create_request(once(now() - Duration::hours(1)));++ let err = service()+ .create_reminder(&user(USER_A), request, None)+ .await+ .expect_err("a past instant should be rejected");++ assert!(matches!(err, ReminderError::BadRequest(_)));+}++#[tokio::test]+async fn rejects_a_one_shot_at_exactly_now() {+ // The boundary the fixed clock exists to pin: `next_run_after` is strictly+ // after `now`, so an instant equal to now has already passed.+ let err = service()+ .create_reminder(&user(USER_A), create_request(once(now())), None)+ .await+ .expect_err("an instant equal to now should be rejected");++ assert!(matches!(err, ReminderError::BadRequest(_)));+}++#[tokio::test]+async fn accepts_a_one_shot_one_second_from_now() {+ let remind_at = now() + Duration::seconds(1);+ let reminder = service()+ .create_reminder(&user(USER_A), create_request(once(remind_at)), None)+ .await+ .expect("an instant just after now should be accepted");++ assert_eq!(reminder.next_run_at, remind_at);+}++#[tokio::test]+async fn rejects_a_cron_with_no_upcoming_firing() {+ let schedule = ReminderSchedule::Recurring {+ // Year-qualified and long past.+ cron: ReminderCron::parse("0 0 9 * * * 2000").expect("valid cron"),+ timezone: New_York,+ };++ let err = service()+ .create_reminder(&user(USER_A), create_request(schedule), None)+ .await+ .expect_err("a cron with no future firing should be rejected");++ assert!(matches!(err, ReminderError::BadRequest(_)));+}++#[tokio::test]+async fn derives_next_run_at_from_a_recurring_schedule() {+ let reminder = service()+ .create_reminder(&user(USER_A), create_request(recurring()), None)+ .await+ .expect("recurring reminder should be created");++ // Frozen "now" is 2026-07-01T12:00Z, which is 08:00 in New York, so the+ // first firing is 09:00 the same morning — 13:00Z.+ assert_eq!(+ reminder.next_run_at,+ Utc.with_ymd_and_hms(2026, 7, 1, 13, 0, 0)+ .single()+ .expect("unambiguous instant")+ );+ assert!(reminder.schedule.repeats());+}++#[tokio::test]+async fn lists_only_the_callers_reminders_soonest_first() {+ let service = service();+ let soon = now() + Duration::hours(2);+ let later = now() + Duration::days(3);++ service+ .create_reminder(&user(USER_A), create_request(once(later)), None)+ .await+ .expect("created");+ service+ .create_reminder(&user(USER_A), create_request(once(soon)), None)+ .await+ .expect("created");+ service+ .create_reminder(&user(USER_B), create_request(once(soon)), None)+ .await+ .expect("created");++ let page = service+ .list_reminders(&user(USER_A), ReminderFilter::default())+ .await+ .expect("list should succeed");++ assert_eq!(page.reminders.len(), 2);+ assert_eq!(page.reminders[0].next_run_at, soon);+ assert_eq!(page.reminders[1].next_run_at, later);+ assert!(page.next_cursor.is_none(), "one page holds both");++ // The response wrapper is what the router returns.+ let list = RemindersList {+ reminders: page.reminders,+ next_cursor: None,+ };+ assert_eq!(list.reminders.len(), 2);+}++#[tokio::test]+async fn lists_reminders_filtered_by_entity() {+ let service = service();+ service+ .create_reminder(+ &user(USER_A),+ create_request(once(future())),+ Some(doc_receipt("doc-1")),+ )+ .await+ .expect("created");+ service+ .create_reminder(&user(USER_A), create_request(once(future())), None)+ .await+ .expect("created");++ let filter = ReminderFilter {+ entity: Some(EntityType::Document.with_entity_string("doc-1".to_string())),+ ..Default::default()+ };+ let page = service+ .list_reminders(&user(USER_A), filter)+ .await+ .expect("list should succeed");++ assert_eq!(page.reminders.len(), 1);+ assert_eq!(page.reminders[0].entity_id.as_deref(), Some("doc-1"));+}++#[tokio::test]+async fn pages_through_reminders_with_a_cursor() {+ let service = service();+ // Same firing time for all five, so paging depends on the created_at/id+ // tie-breakers rather than next_run_at.+ let remind_at = future();+ for _ in 0..5 {+ service+ .create_reminder(&user(USER_A), create_request(once(remind_at)), None)+ .await+ .expect("created");+ }++ let mut seen = Vec::new();+ let mut cursor = None;+ let mut pages = 0;+ loop {+ let page = service+ .list_reminders(+ &user(USER_A),+ ReminderFilter {+ limit: Some(2),+ cursor,+ ..Default::default()+ },+ )+ .await+ .expect("list should succeed");+ pages += 1;+ assert!(page.reminders.len() <= 2, "page must honour the limit");+ seen.extend(page.reminders.iter().map(|reminder| reminder.id));+ match page.next_cursor {+ Some(next) => cursor = Some(next),+ None => break,+ }+ assert!(pages < 10, "paging should terminate");+ }++ assert_eq!(pages, 3, "5 rows at 2 per page");+ assert_eq!(seen.len(), 5, "every reminder appears exactly once");+ let unique: std::collections::HashSet<_> = seen.iter().collect();+ assert_eq!(unique.len(), 5, "no reminder is returned twice");+}++#[tokio::test]+async fn a_full_final_page_reports_no_further_cursor() {+ let service = service();+ for _ in 0..2 {+ service+ .create_reminder(&user(USER_A), create_request(once(future())), None)+ .await+ .expect("created");+ }++ let page = service+ .list_reminders(+ &user(USER_A),+ ReminderFilter {+ limit: Some(2),+ ..Default::default()+ },+ )+ .await+ .expect("list should succeed");++ assert_eq!(page.reminders.len(), 2);+ assert!(+ page.next_cursor.is_none(),+ "a page that exactly consumes the rows has no next page"+ );+}++#[tokio::test]+async fn an_oversized_limit_is_clamped() {+ let filter = ReminderFilter {+ limit: Some(u32::MAX),+ ..Default::default()+ };+ assert_eq!(filter.page_size(), MAX_PAGE_SIZE);++ // A zero limit would otherwise return an empty page forever.+ let filter = ReminderFilter {+ limit: Some(0),+ ..Default::default()+ };+ assert_eq!(filter.page_size(), 1);++ let service = service();+ service+ .create_reminder(&user(USER_A), create_request(once(future())), None)+ .await+ .expect("created");+ let page = service+ .list_reminders(&user(USER_A), filter)+ .await+ .expect("list should succeed");+ assert_eq!(page.reminders.len(), 1);+}++#[tokio::test]+async fn gets_a_reminder_by_id() {+ let service = service();+ let created = service+ .create_reminder(&user(USER_A), create_request(once(future())), None)+ .await+ .expect("created");++ let found = service+ .get_reminder(owner_receipt(USER_A, created.id))+ .await+ .expect("get should succeed");++ assert_eq!(found.id, created.id);+}++#[tokio::test]+async fn another_users_reminder_is_not_found() {+ let service = service();+ let created = service+ .create_reminder(&user(USER_A), create_request(once(future())), None)+ .await+ .expect("created");++ assert!(matches!(+ service+ .get_reminder(owner_receipt(USER_B, created.id))+ .await,+ Err(ReminderError::NotFound)+ ));+ assert!(matches!(+ service+ .update_reminder(+ owner_receipt(USER_B, created.id),+ ReminderPatch {+ enabled: Some(false),+ ..Default::default()+ },+ )+ .await,+ Err(ReminderError::NotFound)+ ));+ assert!(matches!(+ service+ .delete_reminder(owner_receipt(USER_B, created.id))+ .await,+ Err(ReminderError::NotFound)+ ));++ // ...and USER_A's reminder survived all three attempts.+ assert_eq!(service.repo.rows().len(), 1);+}++#[tokio::test]+async fn updates_description_and_enabled() {+ let service = service();+ let created = service+ .create_reminder(&user(USER_A), create_request(once(future())), None)+ .await+ .expect("created");++ let updated = service+ .update_reminder(+ owner_receipt(USER_A, created.id),+ ReminderPatch {+ description: Some(" new text ".to_string()),+ enabled: Some(false),+ ..Default::default()+ },+ )+ .await+ .expect("update should succeed");++ assert_eq!(updated.description, "new text");+ assert!(!updated.enabled);+ // Untouched fields keep their value.+ assert_eq!(updated.next_run_at, created.next_run_at);+}++#[tokio::test]+async fn updating_the_schedule_recomputes_next_run_at() {+ let service = service();+ let created = service+ .create_reminder(&user(USER_A), create_request(once(future())), None)+ .await+ .expect("created");++ let updated = service+ .update_reminder(+ owner_receipt(USER_A, created.id),+ ReminderPatch {+ schedule: Some(recurring()),+ ..Default::default()+ },+ )+ .await+ .expect("update should succeed");++ assert!(updated.schedule.repeats());+ assert_ne!(updated.next_run_at, created.next_run_at);+ assert!(updated.next_run_at > now());+}++#[tokio::test]+async fn rescheduling_revives_a_completed_reminder() {+ let service = service();+ let created = service+ .create_reminder(&user(USER_A), create_request(once(future())), None)+ .await+ .expect("created");+ complete(&service, created.id);++ let revived = service+ .update_reminder(+ owner_receipt(USER_A, created.id),+ ReminderPatch {+ schedule: Some(once(now() + Duration::days(7))),+ ..Default::default()+ },+ )+ .await+ .expect("update should succeed");++ assert!(+ revived.completed_at.is_none(),+ "a reminder given a new firing must not stay marked completed"+ );+ // ...and it is visible in the default list again.+ let page = service+ .list_reminders(&user(USER_A), ReminderFilter::default())+ .await+ .expect("list should succeed");+ assert_eq!(page.reminders.len(), 1);+}++#[tokio::test]+async fn a_non_schedule_update_leaves_completed_at_alone() {+ let service = service();+ let created = service+ .create_reminder(&user(USER_A), create_request(once(future())), None)+ .await+ .expect("created");+ complete(&service, created.id);++ let updated = service+ .update_reminder(+ owner_receipt(USER_A, created.id),+ ReminderPatch {+ description: Some("still done".to_string()),+ ..Default::default()+ },+ )+ .await+ .expect("update should succeed");++ assert!(updated.completed_at.is_some());+}++#[tokio::test]+async fn rejects_an_update_to_a_past_one_shot() {+ let service = service();+ let created = service+ .create_reminder(&user(USER_A), create_request(recurring()), None)+ .await+ .expect("created");++ let err = service+ .update_reminder(+ owner_receipt(USER_A, created.id),+ ReminderPatch {+ schedule: Some(once(now() - Duration::hours(1))),+ ..Default::default()+ },+ )+ .await+ .expect_err("a past instant should be rejected");++ assert!(matches!(err, ReminderError::BadRequest(_)));+}++#[tokio::test]+async fn rejects_an_empty_patch() {+ let service = service();+ let created = service+ .create_reminder(&user(USER_A), create_request(once(future())), None)+ .await+ .expect("created");++ let err = service+ .update_reminder(owner_receipt(USER_A, created.id), ReminderPatch::default())+ .await+ .expect_err("an empty patch should be rejected");++ assert!(matches!(err, ReminderError::BadRequest(_)));+}++#[tokio::test]+async fn deletes_a_reminder_once() {+ let service = service();+ let created = service+ .create_reminder(&user(USER_A), create_request(once(future())), None)+ .await+ .expect("created");++ service+ .delete_reminder(owner_receipt(USER_A, created.id))+ .await+ .expect("first delete should succeed");++ assert!(matches!(+ service+ .delete_reminder(owner_receipt(USER_A, created.id))+ .await,+ Err(ReminderError::NotFound)+ ));+}++#[tokio::test]+async fn a_completed_reminder_is_hidden_unless_requested() {+ let service = service();+ let created = service+ .create_reminder(&user(USER_A), create_request(once(future())), None)+ .await+ .expect("created");+ complete(&service, created.id);++ let default_list = service+ .list_reminders(&user(USER_A), ReminderFilter::default())+ .await+ .expect("list should succeed");+ assert!(default_list.reminders.is_empty());++ let with_completed = service+ .list_reminders(+ &user(USER_A),+ ReminderFilter {+ include_completed: true,+ ..Default::default()+ },+ )+ .await+ .expect("list should succeed");+ assert_eq!(with_completed.reminders.len(), 1);+}++#[tokio::test]+async fn an_unreadable_row_at_a_page_boundary_does_not_end_pagination() {+ // The failure this guards against: the repo reads page_size + 1 rows, some+ // are undecodable, and a naive `decoded.len() > page_size` check concludes+ // there is no next page — silently truncating the list.+ let service = service();+ let remind_at = future();+ let mut created = Vec::new();+ for _ in 0..5 {+ created.push(+ service+ .create_reminder(&user(USER_A), create_request(once(remind_at)), None)+ .await+ .expect("created"),+ );+ }+ // Break the 3rd row: with page size 2, it is the probe row of page 2.+ service.repo.make_unreadable(created[2].id);++ let mut seen = Vec::new();+ let mut cursor = None;+ let mut pages = 0;+ loop {+ let page = service+ .list_reminders(+ &user(USER_A),+ ReminderFilter {+ limit: Some(2),+ cursor,+ ..Default::default()+ },+ )+ .await+ .expect("list should succeed");+ pages += 1;+ seen.extend(page.reminders.iter().map(|reminder| reminder.id));+ match page.next_cursor {+ Some(next) => cursor = Some(next),+ None => break,+ }+ assert!(pages < 10, "paging should terminate");+ }++ // All four readable reminders are reached; only the broken one is missing.+ assert_eq!(+ seen.len(),+ 4,+ "readable rows after the bad row must be reached"+ );+ assert!(!seen.contains(&created[2].id));+ for (index, reminder) in created.iter().enumerate() {+ if index != 2 {+ assert!(seen.contains(&reminder.id), "missing reminder {index}");+ }+ }+}++#[tokio::test]+async fn a_batch_of_entirely_unreadable_rows_does_not_yield_an_empty_page() {+ // The worst case: every row the first read examines is undecodable. The+ // service reads again from where that batch stopped rather than handing back+ // an empty page, so a client never has to treat "empty but more to come" as+ // a distinct state.+ let service = service();+ let remind_at = future();+ let mut created = Vec::new();+ for _ in 0..4 {+ created.push(+ service+ .create_reminder(&user(USER_A), create_request(once(remind_at)), None)+ .await+ .expect("created"),+ );+ }+ // Page size 2 means each read examines 3 rows; break all three of the first.+ service.repo.make_unreadable(created[0].id);+ service.repo.make_unreadable(created[1].id);+ service.repo.make_unreadable(created[2].id);++ let page = service+ .list_reminders(+ &user(USER_A),+ ReminderFilter {+ limit: Some(2),+ ..Default::default()+ },+ )+ .await+ .expect("list should succeed");++ assert_eq!(+ page.reminders.len(),+ 1,+ "the readable row is returned on the first page, not behind an empty one"+ );+ assert_eq!(page.reminders[0].id, created[3].id);+ assert!(+ page.next_cursor.is_none(),+ "the rows are exhausted, so this is the last page"+ );+}++#[tokio::test]+async fn a_page_is_filled_across_reads_when_rows_are_skipped() {+ // Six readable rows with a broken one wedged in the middle: the page should+ // still come back full rather than short.+ let service = service();+ let remind_at = future();+ let mut created = Vec::new();+ for _ in 0..7 {+ created.push(+ service+ .create_reminder(&user(USER_A), create_request(once(remind_at)), None)+ .await+ .expect("created"),+ );+ }+ service.repo.make_unreadable(created[1].id);++ let page = service+ .list_reminders(+ &user(USER_A),+ ReminderFilter {+ limit: Some(3),+ ..Default::default()+ },+ )+ .await+ .expect("list should succeed");++ assert_eq!(+ page.reminders.len(),+ 3,+ "a skipped row must not shorten the page"+ );+ assert!(!page.reminders.iter().any(|r| r.id == created[1].id));+ assert!(page.next_cursor.is_some(), "rows remain");+}++#[tokio::test]+async fn an_unreadable_run_longer_than_the_scan_cap_degrades_to_a_short_page() {+ // The residual case the cap allows: enough consecutive bad rows that the+ // service gives up filling the page. It still reports a cursor, so the client+ // makes progress on the next call rather than stalling.+ let service = service();+ let remind_at = future();+ let mut created = Vec::new();+ for _ in 0..40 {+ created.push(+ service+ .create_reminder(&user(USER_A), create_request(once(remind_at)), None)+ .await+ .expect("created"),+ );+ }+ // Break the first 30; with page size 2 each read examines 3, so 5 reads+ // cannot get past them.+ for reminder in created.iter().take(30) {+ service.repo.make_unreadable(reminder.id);+ }++ let page = service+ .list_reminders(+ &user(USER_A),+ ReminderFilter {+ limit: Some(2),+ ..Default::default()+ },+ )+ .await+ .expect("list should succeed");++ assert!(page.reminders.is_empty(), "the scan cap was reached");+ assert!(+ page.next_cursor.is_some(),+ "a capped page must still advance, or the client stalls forever"+ );++ // Following the cursor keeps making progress until the readable rows appear.+ let mut cursor = page.next_cursor;+ let mut found = Vec::new();+ for _ in 0..10 {+ let page = service+ .list_reminders(+ &user(USER_A),+ ReminderFilter {+ limit: Some(2),+ cursor,+ ..Default::default()+ },+ )+ .await+ .expect("list should succeed");+ found.extend(page.reminders.iter().map(|r| r.id));+ match page.next_cursor {+ Some(next) => cursor = Some(next),+ None => break,+ }+ }+ assert_eq!(+ found.len(),+ 10,+ "all ten readable rows are eventually reached"+ );+}++#[tokio::test]+async fn a_final_page_with_an_unreadable_row_reports_no_cursor() {+ // Symmetry check: skipped rows must not invent a next page either.+ let service = service();+ let mut created = Vec::new();+ for _ in 0..2 {+ created.push(+ service+ .create_reminder(&user(USER_A), create_request(once(future())), None)+ .await+ .expect("created"),+ );+ }+ service.repo.make_unreadable(created[1].id);++ let page = service+ .list_reminders(+ &user(USER_A),+ ReminderFilter {+ limit: Some(5),+ ..Default::default()+ },+ )+ .await+ .expect("list should succeed");++ assert_eq!(page.reminders.len(), 1);+ assert!(+ page.next_cursor.is_none(),+ "the table is exhausted, so there is no next page"+ );+}++#[tokio::test]+async fn rescheduling_leaves_enabled_alone() {+ // Product decision: `enabled = false` is an explicit "pause this", so+ // rescheduling revives the completion state but does not silently re-enable.+ // A client that wants it active again sends `enabled: true` in the same patch.+ let service = service();+ let created = service+ .create_reminder(&user(USER_A), create_request(once(future())), None)+ .await+ .expect("created");+ let paused = service+ .update_reminder(+ owner_receipt(USER_A, created.id),+ ReminderPatch {+ enabled: Some(false),+ ..Default::default()+ },+ )+ .await+ .expect("update should succeed");+ assert!(!paused.enabled);+ complete(&service, created.id);++ let rescheduled = service+ .update_reminder(+ owner_receipt(USER_A, created.id),+ ReminderPatch {+ schedule: Some(once(now() + Duration::days(7))),+ ..Default::default()+ },+ )+ .await+ .expect("update should succeed");++ assert!(rescheduled.completed_at.is_none(), "completion is cleared");+ assert!(+ !rescheduled.enabled,+ "an explicit pause survives a reschedule"+ );++ // Re-enabling is a separate, explicit field on the same patch.+ let resumed = service+ .update_reminder(+ owner_receipt(USER_A, created.id),+ ReminderPatch {+ schedule: Some(once(now() + Duration::days(8))),+ enabled: Some(true),+ ..Default::default()+ },+ )+ .await+ .expect("update should succeed");+ assert!(resumed.enabled);+}++#[tokio::test]+async fn repository_failures_surface_as_internal_errors() {+ // Every method wraps repo errors with `anyhow::Error::from`, which the router+ // turns into a 500 with the cause logged but not returned. Without this the+ // whole mapping is unexercised.+ let service = service();+ let created = service+ .create_reminder(&user(USER_A), create_request(once(future())), None)+ .await+ .expect("created before the outage");+ service.repo.start_failing();++ assert!(matches!(+ service+ .create_reminder(&user(USER_A), create_request(once(future())), None)+ .await,+ Err(ReminderError::Internal(_))+ ));+ assert!(matches!(+ service+ .get_reminder(owner_receipt(USER_A, created.id))+ .await,+ Err(ReminderError::Internal(_))+ ));+ assert!(matches!(+ service+ .list_reminders(&user(USER_A), ReminderFilter::default())+ .await,+ Err(ReminderError::Internal(_))+ ));+ assert!(matches!(+ service+ .update_reminder(+ owner_receipt(USER_A, created.id),+ ReminderPatch {+ enabled: Some(false),+ ..Default::default()+ },+ )+ .await,+ Err(ReminderError::Internal(_))+ ));+ assert!(matches!(+ service+ .delete_reminder(owner_receipt(USER_A, created.id))+ .await,+ Err(ReminderError::Internal(_))+ ));+}++#[tokio::test]+async fn validation_runs_before_the_repository_is_touched() {+ // With the repo failing, a request that is invalid on its face must still+ // come back as a 400 rather than a 500 — which is only true if validation+ // happens first.+ let service = service();+ service.repo.start_failing();++ let blank = CreateReminder {+ description: " ".to_string(),+ ..create_request(once(future()))+ };+ assert!(matches!(+ service.create_reminder(&user(USER_A), blank, None).await,+ Err(ReminderError::BadRequest(_))+ ));++ assert!(matches!(+ service+ .create_reminder(+ &user(USER_A),+ create_request(once(now() - Duration::hours(1))),+ None+ )+ .await,+ Err(ReminderError::BadRequest(_))+ ));++ // And an empty patch never reaches the repo.+ assert!(matches!(+ service+ .update_reminder(+ owner_receipt(USER_A, Uuid::from_u128(1)),+ ReminderPatch::default()+ )+ .await,+ Err(ReminderError::BadRequest(_))+ ));+}++#[tokio::test]+async fn update_enforces_the_description_limit() {+ // Create and update share `validate_description`, but only create was+ // covered; the DB CHECK would otherwise turn a slip here into a 500.+ let service = service();+ let created = service+ .create_reminder(&user(USER_A), create_request(once(future())), None)+ .await+ .expect("created");++ assert!(matches!(+ service+ .update_reminder(+ owner_receipt(USER_A, created.id),+ ReminderPatch {+ description: Some("🎉".repeat(MAX_DESCRIPTION_LEN + 1)),+ ..Default::default()+ },+ )+ .await,+ Err(ReminderError::BadRequest(_))+ ));++ let at_limit = service+ .update_reminder(+ owner_receipt(USER_A, created.id),+ ReminderPatch {+ description: Some("🎉".repeat(MAX_DESCRIPTION_LEN)),+ ..Default::default()+ },+ )+ .await+ .expect("exactly the limit should be accepted");+ assert_eq!(at_limit.description.chars().count(), MAX_DESCRIPTION_LEN);++ // Blank is rejected on update as well as on create.+ assert!(matches!(+ service+ .update_reminder(+ owner_receipt(USER_A, created.id),+ ReminderPatch {+ description: Some(" ".to_string()),+ ..Default::default()+ },+ )+ .await,+ Err(ReminderError::BadRequest(_))+ ));+}++#[tokio::test]+async fn a_disabled_reminder_is_still_listed() {+ // Deliberate: the default list hides *completed* reminders, not paused ones,+ // so a paused reminder stays visible in the UI. Pinned so a future change to+ // the list predicate has to be a decision rather than an accident.+ let service = service();+ let created = service+ .create_reminder(&user(USER_A), create_request(once(future())), None)+ .await+ .expect("created");+ service+ .update_reminder(+ owner_receipt(USER_A, created.id),+ ReminderPatch {+ enabled: Some(false),+ ..Default::default()+ },+ )+ .await+ .expect("paused");++ let page = service+ .list_reminders(&user(USER_A), ReminderFilter::default())+ .await+ .expect("list should succeed");++ assert_eq!(page.reminders.len(), 1);+ assert!(!page.reminders[0].enabled);+}++#[tokio::test]+async fn pages_within_an_entity_filter() {+ // The entity predicate and the keyset predicate were each covered alone;+ // a paged entity-scoped list applies both at once.+ let service = service();+ let remind_at = future();+ for _ in 0..3 {+ service+ .create_reminder(+ &user(USER_A),+ create_request(once(remind_at)),+ Some(doc_receipt("doc-1")),+ )+ .await+ .expect("created");+ }+ for _ in 0..2 {+ service+ .create_reminder(+ &user(USER_A),+ create_request(once(remind_at)),+ Some(doc_receipt("doc-2")),+ )+ .await+ .expect("created");+ }++ let filter = || ReminderFilter {+ entity: Some(EntityType::Document.with_entity_string("doc-1".to_string())),+ limit: Some(2),+ ..Default::default()+ };++ let mut seen = Vec::new();+ let mut cursor = None;+ let mut pages = 0;+ loop {+ let page = service+ .list_reminders(&user(USER_A), ReminderFilter { cursor, ..filter() })+ .await+ .expect("list should succeed");+ pages += 1;+ for reminder in &page.reminders {+ assert_eq!(+ reminder.entity_id.as_deref(),+ Some("doc-1"),+ "the filter must hold on every page"+ );+ }+ seen.extend(page.reminders.iter().map(|reminder| reminder.id));+ match page.next_cursor {+ Some(next) => cursor = Some(next),+ None => break,+ }+ assert!(pages < 10, "paging should terminate");+ }++ assert_eq!(seen.len(), 3, "all three doc-1 reminders, and only those");+ let unique: std::collections::HashSet<_> = seen.iter().collect();+ assert_eq!(unique.len(), 3);+}diff --git a/crates/reminders/src/inbound.rs b/crates/reminders/src/inbound.rsnew file mode 100644index 0000000000..6c5cfe2b21--- /dev/null+++ b/crates/reminders/src/inbound.rs@@ -0,0 +1,7 @@+//! Inbound (driving) adapters for reminders.++#[cfg(feature = "inbound")]+pub mod axum_router;++#[cfg(feature = "dispatch")]+pub mod dispatch_worker;diff --git a/crates/reminders/src/inbound/axum_router.rs b/crates/reminders/src/inbound/axum_router.rsnew file mode 100644index 0000000000..f9aab5f9e3--- /dev/null+++ b/crates/reminders/src/inbound/axum_router.rs@@ -0,0 +1,492 @@+//! Axum router for reminders endpoints.++#[cfg(test)]+mod test;++use std::sync::Arc;++use axum::{+ Json, Router,+ extract::{FromRef, State},+ http::StatusCode,+ response::IntoResponse,+ routing::{delete, get, patch, post},+};+use entity_access::domain::{+ models::{AccessError, AnyEntityPermission, EntityAccessReceipt, OwnerAccessLevel},+ ports::EntityAccessService,+};+use entity_access::inbound::axum_extractors::ReminderAccessExtractor;+use macro_authorization::{+ MacroAuthorizationExtractor, MacroAuthorizationService, MacroAuthorizationState, UserOrInternal,+};+use macro_user_id::user_id::MacroUserIdStr;+use model_entity::{Entity, EntityType};+use model_error_response::ErrorResponse;+use serde::Deserialize;+use uuid::Uuid;++use crate::domain::{+ models::{+ CreateReminder, Reminder, ReminderCursor, ReminderError, ReminderFilter, ReminderPatch,+ ReminderSchedule, RemindersList,+ },+ ports::RemindersService,+};++/// Router state for reminders endpoints.+pub struct RemindersRouterState<S, Eas, Auth> {+ service: Arc<S>,+ entity_access_service: Arc<Eas>,+ authorization_state: MacroAuthorizationState<Auth>,+}++impl<S, Eas, Auth> Clone for RemindersRouterState<S, Eas, Auth> {+ fn clone(&self) -> Self {+ Self {+ service: self.service.clone(),+ entity_access_service: self.entity_access_service.clone(),+ authorization_state: self.authorization_state.clone(),+ }+ }+}++impl<S, Eas, Auth> RemindersRouterState<S, Eas, Auth>+where+ S: RemindersService,+ Eas: EntityAccessService,+{+ /// Create router state from shared service references and authorization state.+ pub fn new(+ service: Arc<S>,+ entity_access_service: Arc<Eas>,+ authorization_state: MacroAuthorizationState<Auth>,+ ) -> Self {+ Self {+ service,+ entity_access_service,+ authorization_state,+ }+ }+}++impl<S, Eas, Auth> FromRef<RemindersRouterState<S, Eas, Auth>> for Arc<Eas> {+ fn from_ref(state: &RemindersRouterState<S, Eas, Auth>) -> Self {+ state.entity_access_service.clone()+ }+}++impl<S, Eas, Auth> FromRef<RemindersRouterState<S, Eas, Auth>> for MacroAuthorizationState<Auth> {+ fn from_ref(state: &RemindersRouterState<S, Eas, Auth>) -> Self {+ state.authorization_state.clone()+ }+}++/// Build the reminders router.+///+/// Routes:+/// - `GET /` — list the caller's reminders.+/// - `POST /` — create a reminder.+/// - `GET /{id}` — fetch one reminder.+/// - `PATCH /{id}` — modify a reminder.+/// - `DELETE /{id}` — delete a reminder.+pub fn reminders_router<S, Eas, Auth, T>(state: RemindersRouterState<S, Eas, Auth>) -> Router<T>+where+ S: RemindersService,+ Eas: EntityAccessService,+ Auth: MacroAuthorizationService,+ T: Send + Sync + 'static,+{+ Router::new()+ .route("/", get(list_reminders_handler::<S, Eas, Auth>))+ .route("/", post(create_reminder_handler::<S, Eas, Auth>))+ .route("/{id}", get(get_reminder_handler::<S, Eas, Auth>))+ .route("/{id}", patch(update_reminder_handler::<S, Eas, Auth>))+ .route("/{id}", delete(delete_reminder_handler::<S, Eas, Auth>))+ .with_state(state)+}++/// Request body for creating a reminder.+#[derive(Debug, Deserialize, utoipa::ToSchema)]+#[serde(rename_all = "camelCase")]+pub struct CreateReminderRequest {+ /// What to remind the caller about.+ pub description: String,+ /// Type of the entity to attach the reminder to. Requires `entityId`.+ // Inlined to avoid claiming the shared `EntityType` component name (see+ // `Reminder::entity_type`).+ #[schema(inline)]+ pub entity_type: Option<EntityType>,+ /// Id of the entity to attach the reminder to. Requires `entityType`.+ pub entity_id: Option<String>,+ /// When and how often the reminder fires.+ pub schedule: ReminderSchedule,+}++/// Request body for modifying a reminder. Omitted fields are left unchanged;+/// the entity association is not modifiable.+///+/// Every field is optional but **not** nullable. `Option` here means "absent",+/// and serde cannot tell an explicit `null` from an omitted key — so a body of+/// `{"enabled": null}` would deserialize to an empty patch and be rejected as+/// having no fields to update. `nullable = false` keeps the schema from+/// advertising a value the API has no meaning for; the deserializer still+/// tolerates `null` rather than erroring on it.+#[derive(Debug, Deserialize, utoipa::ToSchema)]+#[serde(rename_all = "camelCase")]+pub struct UpdateReminderRequest {+ /// Replacement description.+ #[schema(nullable = false)]+ pub description: Option<String>,+ /// Replacement schedule.+ #[schema(nullable = false)]+ pub schedule: Option<ReminderSchedule>,+ /// Whether the reminder should fire at all.+ #[schema(nullable = false)]+ pub enabled: Option<bool>,+}++/// Query params for listing reminders.+#[derive(Debug, Deserialize, utoipa::IntoParams)]+#[serde(rename_all = "camelCase")]+#[into_params(parameter_in = Query)]+pub struct ListRemindersParams {+ /// Restrict to reminders attached to this entity type. Requires `entityId`.+ #[param(inline)]+ pub entity_type: Option<EntityType>,+ /// Restrict to reminders attached to this entity id. Requires `entityType`.+ pub entity_id: Option<String>,+ /// Include reminders that have already fired.+ #[serde(default)]+ pub include_completed: bool,+ /// Page size. Defaults to 100; larger values are capped at 500. A value+ /// that is not a non-negative integer is rejected by the query extractor.+ pub limit: Option<u32>,+ /// `nextCursor` from a previous page.+ pub cursor: Option<String>,+}++/// Path params for the single-reminder routes.+#[derive(Debug, Deserialize, utoipa::IntoParams)]+#[into_params(parameter_in = Path)]+pub struct ReminderIdParams {+ /// The reminder id.+ pub id: Uuid,+}++/// Pair an optional entity type and id into an entity, rejecting half-supplied+/// associations and blank ids before they reach the domain. Applies to both+/// create and list, so a filter can never carry an empty entity id.+fn build_entity(+ entity_type: Option<EntityType>,+ entity_id: Option<String>,+) -> Result<Option<Entity<'static>>, ReminderError> {+ match (entity_type, entity_id) {+ (Some(entity_type), Some(entity_id)) => {+ // Stored as uuid, so reject a malformed id here rather than let it+ // surface as an opaque repository error.+ let entity_id = entity_id.trim();+ Uuid::parse_str(entity_id)+ .map_err(|_| ReminderError::BadRequest("entityId must be a uuid".to_string()))?;+ Ok(Some(entity_type.with_entity_string(entity_id.to_string())))+ }+ (None, None) => Ok(None),+ _ => Err(ReminderError::BadRequest(+ "entityType and entityId must be provided together".to_string(),+ )),+ }+}++/// Mint the receipt that proves the caller may attach a reminder to `entity`.+/// Access policy itself stays in the domain service, which checks the receipt+/// matches the requested entity and user.+///+/// The requirement is [`AnyEntityPermission`], not `ViewAccessLevel`: entity+/// permissions come in two shapes, and `ViewAccessLevel` only ever matches the+/// `AccessLevel` one. A channel resolves to `ChannelRole`/`ChannelViewOnly`, so+/// requiring `ViewAccessLevel` rejected every channel — including ones the+/// caller owns. `get_entity_permission` already fails closed for an entity the+/// caller cannot reach at all (`AccessLevel` has no "none" variant; no access is+/// an error, not a value), so "holds any permission" is the right bar for+/// attaching a reminder.+async fn mint_entity_receipt<Eas: EntityAccessService>(+ entity_access_service: &Eas,+ user_id: &MacroUserIdStr<'_>,+ user_org_id: Option<i64>,+ entity: &Entity<'_>,+) -> Result<EntityAccessReceipt<AnyEntityPermission>, ReminderError> {+ entity_access_service+ .generate_entity_access_receipt::<AnyEntityPermission>(+ user_id,+ user_org_id,+ entity.entity_id.as_ref(),+ entity.entity_type,+ )+ .await+ // Report what actually went wrong. Collapsing every variant into a 403+ // told a caller with a malformed id or a missing entity that they lacked+ // access, which sent debugging in the wrong direction.+ .map_err(|e| match e {+ AccessError::Unauthorized | AccessError::UnauthorizedWithMessage(_) => {+ ReminderError::EntityAccessDenied+ }+ AccessError::NotFound(_) => ReminderError::EntityNotFound,+ AccessError::BadRequest(msg) => ReminderError::BadRequest(msg.to_string()),+ other => ReminderError::Internal(rootcause::Report::new(other).into_dynamic()),+ })+}++/// List the caller's reminders, soonest firing first.+#[utoipa::path(+ get,+ tag = "reminders",+ operation_id = "list_reminders",+ path = "/reminders",+ params(ListRemindersParams),+ responses(+ (status = 200, body = RemindersList),+ (status = 400, body = ErrorResponse),+ (status = 401, description = "Missing or invalid credentials", body = ErrorResponse),+ (status = 500, body = ErrorResponse),+ )+)]+#[tracing::instrument(err, skip_all)]+pub async fn list_reminders_handler<S, Eas, Auth>(+ State(state): State<RemindersRouterState<S, Eas, Auth>>,+ user: MacroAuthorizationExtractor<Auth, UserOrInternal>,+ axum::extract::Query(params): axum::extract::Query<ListRemindersParams>,+) -> Result<Json<RemindersList>, ReminderError>+where+ S: RemindersService,+ Eas: EntityAccessService,+ Auth: MacroAuthorizationService,+{+ let filter = ReminderFilter {+ entity: build_entity(params.entity_type, params.entity_id)?,+ include_completed: params.include_completed,+ cursor: params+ .cursor+ .as_deref()+ .map(ReminderCursor::decode)+ .transpose()?,+ limit: params.limit,+ };+ let page = state+ .service+ .list_reminders(&user.authorization.user.macro_user_id, filter)+ .await?;+ Ok(Json(RemindersList {+ reminders: page.reminders,+ next_cursor: page.next_cursor.map(|cursor| cursor.encode()),+ }))+}++/// Create a reminder, optionally attached to an entity the caller can view.+#[utoipa::path(+ post,+ tag = "reminders",+ operation_id = "create_reminder",+ path = "/reminders",+ request_body = CreateReminderRequest,+ responses(+ (status = 201, body = Reminder),+ (status = 400, body = ErrorResponse),+ (status = 401, description = "Missing or invalid credentials", body = ErrorResponse),+ (status = 403, description = "No access to the requested entity", body = ErrorResponse),+ (status = 404, description = "The requested entity does not exist", body = ErrorResponse),+ // Body deserialization is rejected by the framework before the handler+ // runs, so this response carries a plain-text body, not `ErrorResponse`.+ (status = 422, description = "Malformed request body (plain text)"),+ (status = 500, body = ErrorResponse),+ )+)]+#[tracing::instrument(err, skip_all)]+pub async fn create_reminder_handler<S, Eas, Auth>(+ State(state): State<RemindersRouterState<S, Eas, Auth>>,+ user: MacroAuthorizationExtractor<Auth, UserOrInternal>,+ Json(req): Json<CreateReminderRequest>,+) -> Result<(StatusCode, Json<Reminder>), ReminderError>+where+ S: RemindersService,+ Eas: EntityAccessService,+ Auth: MacroAuthorizationService,+{+ let CreateReminderRequest {+ description,+ entity_type,+ entity_id,+ schedule,+ } = req;+ let user_id = &user.authorization.user.macro_user_id;+ // Organization channels grant access by matching org, so the org must be+ // carried through or a member of one reads as a non-participant.+ let user_org_id = user+ .authorization+ .user+ .user_context+ .organization_id+ .map(i64::from);++ let entity = build_entity(entity_type, entity_id)?;+ // A standalone reminder points at nothing, so there is no access to check.+ let entity_receipt = match &entity {+ Some(entity) => Some(+ mint_entity_receipt(+ state.entity_access_service.as_ref(),+ user_id,+ user_org_id,+ entity,+ )+ .await?,+ ),+ None => None,+ };++ let reminder = state+ .service+ .create_reminder(+ user_id,+ CreateReminder {+ description,+ schedule,+ },+ entity_receipt,+ )+ .await?;+ // No `Location` header: this router is mounted under a path prefix the+ // service cannot see (clients reach it via `SERVER_HOSTS` + `/dss`, which the+ // proxy strips before forwarding), so any absolute path built here would be+ // wrong for the caller. The created reminder's `id` is in the body.+ Ok((StatusCode::CREATED, Json(reminder)))+}++/// Fetch one of the caller's reminders.+#[utoipa::path(+ get,+ tag = "reminders",+ operation_id = "get_reminder",+ path = "/reminders/{id}",+ params(ReminderIdParams),+ responses(+ (status = 200, body = Reminder),+ (status = 401, description = "Missing or invalid credentials", body = ErrorResponse),+ (status = 404, body = ErrorResponse),+ (status = 500, body = ErrorResponse),+ )+)]+#[tracing::instrument(err, skip_all)]+pub async fn get_reminder_handler<S, Eas, Auth>(+ State(state): State<RemindersRouterState<S, Eas, Auth>>,+ access: ReminderAccessExtractor<OwnerAccessLevel, Eas, Auth>,+) -> Result<Json<Reminder>, ReminderError>+where+ S: RemindersService,+ Eas: EntityAccessService,+ Auth: MacroAuthorizationService,+{+ let reminder = state+ .service+ .get_reminder(access.entity_access_receipt)+ .await?;+ Ok(Json(reminder))+}++/// Modify one of the caller's reminders.+#[utoipa::path(+ patch,+ tag = "reminders",+ operation_id = "update_reminder",+ path = "/reminders/{id}",+ params(ReminderIdParams),+ request_body = UpdateReminderRequest,+ responses(+ (status = 200, body = Reminder),+ (status = 400, body = ErrorResponse),+ (status = 401, description = "Missing or invalid credentials", body = ErrorResponse),+ (status = 404, body = ErrorResponse),+ // As on create: a malformed body is rejected before the handler runs and+ // carries a plain-text body, not `ErrorResponse`.+ (status = 422, description = "Malformed request body (plain text)"),+ (status = 500, body = ErrorResponse),+ )+)]+#[tracing::instrument(err, skip_all)]+pub async fn update_reminder_handler<S, Eas, Auth>(+ State(state): State<RemindersRouterState<S, Eas, Auth>>,+ access: ReminderAccessExtractor<OwnerAccessLevel, Eas, Auth>,+ Json(req): Json<UpdateReminderRequest>,+) -> Result<Json<Reminder>, ReminderError>+where+ S: RemindersService,+ Eas: EntityAccessService,+ Auth: MacroAuthorizationService,+{+ let patch = ReminderPatch {+ description: req.description,+ schedule: req.schedule,+ enabled: req.enabled,+ };+ let reminder = state+ .service+ .update_reminder(access.entity_access_receipt, patch)+ .await?;+ Ok(Json(reminder))+}++/// Delete one of the caller's reminders.+#[utoipa::path(+ delete,+ tag = "reminders",+ operation_id = "delete_reminder",+ path = "/reminders/{id}",+ params(ReminderIdParams),+ responses(+ (status = 204, description = "Reminder deleted"),+ (status = 401, description = "Missing or invalid credentials", body = ErrorResponse),+ (status = 404, body = ErrorResponse),+ (status = 500, body = ErrorResponse),+ )+)]+#[tracing::instrument(err, skip_all)]+pub async fn delete_reminder_handler<S, Eas, Auth>(+ State(state): State<RemindersRouterState<S, Eas, Auth>>,+ access: ReminderAccessExtractor<OwnerAccessLevel, Eas, Auth>,+) -> Result<StatusCode, ReminderError>+where+ S: RemindersService,+ Eas: EntityAccessService,+ Auth: MacroAuthorizationService,+{+ state+ .service+ .delete_reminder(access.entity_access_receipt)+ .await?;+ Ok(StatusCode::NO_CONTENT)+}++impl IntoResponse for ReminderError {+ fn into_response(self) -> axum::response::Response {+ let status_code = match &self {+ ReminderError::NotFound | ReminderError::EntityNotFound => StatusCode::NOT_FOUND,+ ReminderError::BadRequest(_) => StatusCode::BAD_REQUEST,+ ReminderError::EntityAccessDenied => StatusCode::FORBIDDEN,+ ReminderError::Internal(_) => StatusCode::INTERNAL_SERVER_ERROR,+ };++ let message = match &self {+ ReminderError::Internal(_) => {+ tracing::error!(error=?self, "reminders internal server error");+ "internal server error".to_string()+ }+ error => error.to_string(),+ };++ (+ status_code,+ Json(ErrorResponse {+ message: message.into(),+ }),+ )+ .into_response()+ }+}diff --git a/crates/reminders/src/inbound/axum_router/test.rs b/crates/reminders/src/inbound/axum_router/test.rsnew file mode 100644index 0000000000..c53fc6bed4--- /dev/null+++ b/crates/reminders/src/inbound/axum_router/test.rs@@ -0,0 +1,1277 @@+//! HTTP-level tests: status mapping, entity-pair validation, receipt minting,+//! JSON shape, and the pagination round-trip through query params.++use std::sync::{Arc, Mutex};++use axum::http::header;+use chrono::{DateTime, TimeZone, Utc};+use entity_access::domain::models::{+ AccessError, AccessLevel, AnyEntityPermission, BotAccessScope, BotId, CallChannelInfo,+ Entity as AccessEntity, EntityPermission, RequiredPermission, TeamRole, UserTeamInfo,+};+use http_body_util::BodyExt;+use macro_authorization::{+ InternalIdentityClaims, MacroAuthorizationError, MacroAuthorizationService,+};+use macro_user_id::{lowercased::Lowercase, user_id::MacroUserId};+use model_user::UserContext;+use rootcause::Report;+use tower::ServiceExt;+use uuid::Uuid;++use super::*;+use crate::domain::models::{ReminderCursor, ReminderPage};++const USER_ID: &str = "macro|[email protected]";+const VALID_JWT: &str = "valid";+/// The one entity the fake access service grants view access to.+// Entity ids are uuids: `reminder.entity_id` is a uuid column, and the router+// rejects anything that does not parse.+const ACCESSIBLE_DOC: &str = "11111111-1111-4111-8111-111111111111";+const FORBIDDEN_DOC: &str = "22222222-2222-4222-8222-222222222222";++fn instant(day: u32, hour: u32) -> DateTime<Utc> {+ Utc.with_ymd_and_hms(2026, 7, day, hour, 0, 0)+ .single()+ .expect("unambiguous instant")+}++fn user_context() -> UserContext {+ UserContext {+ user_id: USER_ID.to_string(),+ fusion_user_id: "bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb".to_string(),+ permissions: None,+ organization_id: None,+ }+}++#[derive(Clone)]+struct FakeAuthorizationService;++impl MacroAuthorizationService for FakeAuthorizationService {+ async fn authorize(&self, jwt: &str) -> Result<UserContext, Report<MacroAuthorizationError>> {+ if jwt != VALID_JWT {+ return Err(Report::new(MacroAuthorizationError::InvalidCredentials));+ }+ Ok(user_context())+ }++ async fn authorize_internal(+ &self,+ _provided_key: &str,+ _claims: InternalIdentityClaims,+ ) -> Result<Option<UserContext>, Report<MacroAuthorizationError>> {+ Err(Report::new(MacroAuthorizationError::InvalidCredentials))+ }+}++/// Grants view access to [`ACCESSIBLE_DOC`] only. Every other capability errors,+/// since the reminders router never uses them.+#[derive(Clone, Default)]+struct FakeEntityAccessService {+ receipts_minted: Arc<Mutex<Vec<(String, EntityType)>>>,+ /// Error returned for anything other than [`ACCESSIBLE_DOC`]. `None` means+ /// [`AccessError::Unauthorized`], which is the common case.+ denial: Option<fn() -> AccessError>,+ /// When set, the caller owns no reminders, so `ReminderAccessExtractor`+ /// rejects every item route.+ reminder_not_owned: bool,+}++impl FakeEntityAccessService {+ /// The caller owns no reminders.+ fn without_reminder_ownership() -> Self {+ Self {+ reminder_not_owned: true,+ ..Self::default()+ }+ }+}++impl FakeEntityAccessService {+ /// Denies with a specific [`AccessError`], so the router's mapping of each+ /// variant can be exercised.+ fn denying_with(denial: fn() -> AccessError) -> Self {+ Self {+ denial: Some(denial),+ ..Self::default()+ }+ }++ fn minted(&self) -> Vec<(String, EntityType)> {+ self.receipts_minted+ .lock()+ .expect("mint log poisoned")+ .clone()+ }+}++impl EntityAccessService for FakeEntityAccessService {+ async fn generate_entity_access_receipt<T: RequiredPermission>(+ &self,+ user_id: &MacroUserId<Lowercase<'_>>,+ _user_org_id: Option<i64>,+ entity_id: &str,+ entity_type: EntityType,+ ) -> Result<EntityAccessReceipt<T>, AccessError> {+ self.receipts_minted+ .lock()+ .expect("mint log poisoned")+ .push((entity_id.to_string(), entity_type));++ if entity_id != ACCESSIBLE_DOC {+ return Err(self.denial.map_or(AccessError::Unauthorized, |make| make()));+ }++ EntityAccessReceipt::try_new_authenticated_user(+ MacroUserIdStr::parse_from_str(USER_ID)+ .expect("valid user id")+ .clone(),+ AccessEntity {+ entity_id: entity_id.to_string(),+ entity_type,+ },+ EntityPermission::AccessLevel {+ access_level: AccessLevel::View,+ },+ )+ .inspect(|_| debug_assert_eq!(user_id.as_ref(), USER_ID))+ }++ async fn generate_bot_entity_access_receipt<T: RequiredPermission>(+ &self,+ _bot_id: BotId,+ _scope: BotAccessScope,+ _entity_id: &str,+ _entity_type: EntityType,+ ) -> Result<EntityAccessReceipt<T>, AccessError> {+ Err(AccessError::Internal)+ }++ async fn get_access_level(+ &self,+ _user_id: Option<&MacroUserId<Lowercase<'_>>>,+ _entity_id: &str,+ entity_type: EntityType,+ ) -> Result<Option<AccessLevel>, AccessError> {+ // `ReminderAccessExtractor` resolves ownership through this. A reminder+ // grants Owner or nothing; the router never asks about anything else.+ if entity_type == EntityType::Reminder {+ return Ok((!self.reminder_not_owned).then_some(AccessLevel::Owner));+ }+ Err(AccessError::Internal)+ }++ async fn check_access(+ &self,+ _user_id: Option<&MacroUserId<Lowercase<'_>>>,+ _entity_id: &str,+ _entity_type: EntityType,+ _required_level: AccessLevel,+ ) -> Result<AccessLevel, AccessError> {+ Err(AccessError::Internal)+ }++ async fn check_public_access(+ &self,+ _entity_id: &str,+ _entity_type: EntityType,+ _required_level: AccessLevel,+ ) -> Result<AccessLevel, AccessError> {+ Err(AccessError::Internal)+ }++ async fn get_entity_permission(+ &self,+ _user_id: Option<&MacroUserId<Lowercase<'_>>>,+ _entity_id: &str,+ _entity_type: EntityType,+ _user_org_id: Option<i64>,+ ) -> Result<EntityPermission, AccessError> {+ Err(AccessError::Internal)+ }++ async fn get_crm_entity_permission_with_team(+ &self,+ _user_id: Option<&MacroUserId<Lowercase<'_>>>,+ _entity_id: &str,+ _entity_type: EntityType,+ ) -> Result<(EntityPermission, Uuid, TeamRole), AccessError> {+ Err(AccessError::Internal)+ }++ async fn get_users_by_entity(+ &self,+ _entity_id: &str,+ _entity_type: EntityType,+ ) -> Result<Vec<MacroUserIdStr<'static>>, AccessError> {+ Err(AccessError::Internal)+ }++ async fn get_call_channel(+ &self,+ _call_id: &Uuid,+ ) -> Result<Option<CallChannelInfo>, AccessError> {+ Err(AccessError::Internal)+ }++ async fn get_call_channel_by_channel_id(+ &self,+ _channel_id: &Uuid,+ ) -> Result<Option<CallChannelInfo>, AccessError> {+ Err(AccessError::Internal)+ }++ async fn get_user_team(+ &self,+ _user_id: &MacroUserId<Lowercase<'_>>,+ ) -> Result<Option<UserTeamInfo>, AccessError> {+ Err(AccessError::Internal)+ }+}++fn sample_reminder(entity_id: Option<&str>) -> Reminder {+ Reminder {+ id: Uuid::from_u128(1),+ description: "follow up".to_string(),+ entity_type: entity_id.map(|_| EntityType::Document),+ entity_id: entity_id.map(str::to_string),+ schedule: ReminderSchedule::Once {+ remind_at: instant(2, 13),+ },+ next_run_at: instant(2, 13),+ enabled: true,+ completed_at: None,+ created_at: instant(1, 12),+ updated_at: instant(1, 12),+ }+}++/// What the fake service was asked to do, so the router's translation of+/// transport input into domain calls can be asserted.+#[derive(Debug, Clone, PartialEq)]+enum ServiceCall {+ Create {+ description: String,+ entity: Option<(EntityType, String)>,+ has_receipt: bool,+ },+ List {+ entity: Option<(EntityType, String)>,+ include_completed: bool,+ limit: Option<u32>,+ cursor: Option<ReminderCursor>,+ },+ Get(Uuid),+ Update {+ id: Uuid,+ description: Option<String>,+ enabled: Option<bool>,+ has_schedule: bool,+ },+ Delete(Uuid),+}++#[derive(Clone, Default)]+struct FakeRemindersService {+ calls: Arc<Mutex<Vec<ServiceCall>>>,+ /// When set, every method returns this error instead of succeeding.+ error: Option<Arc<dyn Fn() -> ReminderError + Send + Sync>>,+ next_cursor: Option<ReminderCursor>,+}++impl FakeRemindersService {+ fn failing(error: impl Fn() -> ReminderError + Send + Sync + 'static) -> Self {+ Self {+ error: Some(Arc::new(error)),+ ..Default::default()+ }+ }++ fn calls(&self) -> Vec<ServiceCall> {+ self.calls.lock().expect("call log poisoned").clone()+ }++ fn record(&self, call: ServiceCall) {+ self.calls.lock().expect("call log poisoned").push(call);+ }++ fn fail_if_configured(&self) -> Result<(), ReminderError> {+ match &self.error {+ Some(error) => Err(error()),+ None => Ok(()),+ }+ }+}++/// The reminder a receipt was minted for.+fn receipt_id(receipt: &EntityAccessReceipt<OwnerAccessLevel>) -> Uuid {+ receipt+ .entity()+ .entity_id+ .parse()+ .expect("the extractor only mints receipts for a parsed uuid")+}++/// The entity named by a list filter, which is a read filter and so still+/// carries the entity directly.+fn entity_pair(entity: &Option<Entity<'static>>) -> Option<(EntityType, String)> {+ entity+ .as_ref()+ .map(|entity| (entity.entity_type, entity.entity_id.to_string()))+}++/// The entity a create request attaches to, which the receipt carries now that+/// `create_reminder` takes a receipt rather than an entity.+fn receipt_entity_pair(+ receipt: &Option<EntityAccessReceipt<AnyEntityPermission>>,+) -> Option<(EntityType, String)> {+ receipt.as_ref().map(|receipt| {+ let entity = receipt.entity();+ (entity.entity_type, entity.entity_id.clone())+ })+}++impl RemindersService for FakeRemindersService {+ async fn create_reminder(+ &self,+ _user_id: &MacroUserIdStr<'_>,+ request: CreateReminder,+ entity_receipt: Option<EntityAccessReceipt<AnyEntityPermission>>,+ ) -> Result<Reminder, ReminderError> {+ let entity = receipt_entity_pair(&entity_receipt);+ self.record(ServiceCall::Create {+ description: request.description.clone(),+ entity: entity.clone(),+ has_receipt: entity_receipt.is_some(),+ });+ self.fail_if_configured()?;+ Ok(sample_reminder(entity.as_ref().map(|(_, id)| id.as_str())))+ }++ async fn get_reminder(+ &self,+ receipt: EntityAccessReceipt<OwnerAccessLevel>,+ ) -> Result<Reminder, ReminderError> {+ self.record(ServiceCall::Get(receipt_id(&receipt)));+ self.fail_if_configured()?;+ Ok(sample_reminder(None))+ }++ async fn list_reminders(+ &self,+ _user_id: &MacroUserIdStr<'_>,+ filter: ReminderFilter,+ ) -> Result<ReminderPage, ReminderError> {+ self.record(ServiceCall::List {+ entity: entity_pair(&filter.entity),+ include_completed: filter.include_completed,+ limit: filter.limit,+ cursor: filter.cursor,+ });+ self.fail_if_configured()?;+ Ok(ReminderPage {+ reminders: vec![sample_reminder(None)],+ next_cursor: self.next_cursor,+ })+ }++ async fn update_reminder(+ &self,+ receipt: EntityAccessReceipt<OwnerAccessLevel>,+ patch: ReminderPatch,+ ) -> Result<Reminder, ReminderError> {+ self.record(ServiceCall::Update {+ id: receipt_id(&receipt),+ description: patch.description.clone(),+ enabled: patch.enabled,+ has_schedule: patch.schedule.is_some(),+ });+ self.fail_if_configured()?;+ Ok(sample_reminder(None))+ }++ async fn delete_reminder(+ &self,+ receipt: EntityAccessReceipt<OwnerAccessLevel>,+ ) -> Result<(), ReminderError> {+ self.record(ServiceCall::Delete(receipt_id(&receipt)));+ self.fail_if_configured()?;+ Ok(())+ }+}++fn build_router(service: FakeRemindersService, access: FakeEntityAccessService) -> axum::Router {+ reminders_router(RemindersRouterState::new(+ Arc::new(service),+ Arc::new(access),+ MacroAuthorizationState::new(Arc::new(FakeAuthorizationService)),+ ))+}++fn authed(builder: axum::http::request::Builder) -> axum::http::request::Builder {+ builder.header(header::AUTHORIZATION, format!("Bearer {VALID_JWT}"))+}++fn json_body(value: serde_json::Value) -> axum::body::Body {+ axum::body::Body::from(value.to_string())+}++async fn read_json(response: axum::response::Response) -> serde_json::Value {+ let bytes = response+ .into_body()+ .collect()+ .await+ .expect("body should collect")+ .to_bytes();+ if bytes.is_empty() {+ return serde_json::Value::Null;+ }+ serde_json::from_slice(&bytes).expect("body should be json")+}++fn once_schedule() -> serde_json::Value {+ serde_json::json!({"type": "once", "remindAt": "2026-07-02T13:00:00Z"})+}++#[tokio::test]+async fn create_returns_201_with_the_reminder() {+ let service = FakeRemindersService::default();+ let response = build_router(service.clone(), FakeEntityAccessService::default())+ .oneshot(+ authed(axum::http::Request::post("/"))+ .header(header::CONTENT_TYPE, "application/json")+ .body(json_body(serde_json::json!({+ "description": "follow up",+ "schedule": once_schedule(),+ })))+ .expect("request should build"),+ )+ .await+ .expect("router should respond");++ assert_eq!(response.status(), StatusCode::CREATED);+ let body = read_json(response).await;+ assert_eq!(body["description"], "follow up");+ assert_eq!(body["nextRunAt"], "2026-07-02T13:00:00Z");+ assert_eq!(body["schedule"]["type"], "once");+ // Standalone reminders carry no receipt inward.+ assert_eq!(+ service.calls(),+ vec![ServiceCall::Create {+ description: "follow up".to_string(),+ entity: None,+ has_receipt: false,+ }]+ );+}++#[tokio::test]+async fn create_with_an_accessible_entity_mints_a_receipt() {+ let service = FakeRemindersService::default();+ let access = FakeEntityAccessService::default();+ let response = build_router(service.clone(), access.clone())+ .oneshot(+ authed(axum::http::Request::post("/"))+ .header(header::CONTENT_TYPE, "application/json")+ .body(json_body(serde_json::json!({+ "description": "review this",+ "entityType": "document",+ "entityId": ACCESSIBLE_DOC,+ "schedule": once_schedule(),+ })))+ .expect("request should build"),+ )+ .await+ .expect("router should respond");++ assert_eq!(response.status(), StatusCode::CREATED);+ assert_eq!(+ access.minted(),+ vec![(ACCESSIBLE_DOC.to_string(), EntityType::Document)],+ "the receipt must be minted for the entity the client named"+ );+ assert_eq!(+ service.calls(),+ vec![ServiceCall::Create {+ description: "review this".to_string(),+ entity: Some((EntityType::Document, ACCESSIBLE_DOC.to_string())),+ has_receipt: true,+ }]+ );+}++#[tokio::test]+async fn create_with_an_inaccessible_entity_is_403_and_never_reaches_the_service() {+ let service = FakeRemindersService::default();+ let response = build_router(service.clone(), FakeEntityAccessService::default())+ .oneshot(+ authed(axum::http::Request::post("/"))+ .header(header::CONTENT_TYPE, "application/json")+ .body(json_body(serde_json::json!({+ "description": "peek",+ "entityType": "document",+ "entityId": FORBIDDEN_DOC,+ "schedule": once_schedule(),+ })))+ .expect("request should build"),+ )+ .await+ .expect("router should respond");++ assert_eq!(response.status(), StatusCode::FORBIDDEN);+ assert!(+ service.calls().is_empty(),+ "a failed access check must not create anything"+ );+}++#[tokio::test]+async fn a_half_supplied_entity_pair_is_400() {+ for body in [+ serde_json::json!({+ "description": "x", "entityType": "document", "schedule": once_schedule(),+ }),+ serde_json::json!({+ "description": "x", "entityId": ACCESSIBLE_DOC, "schedule": once_schedule(),+ }),+ serde_json::json!({+ "description": "x", "entityType": "document", "entityId": " ",+ "schedule": once_schedule(),+ }),+ ] {+ let service = FakeRemindersService::default();+ let response = build_router(service.clone(), FakeEntityAccessService::default())+ .oneshot(+ authed(axum::http::Request::post("/"))+ .header(header::CONTENT_TYPE, "application/json")+ .body(json_body(body.clone()))+ .expect("request should build"),+ )+ .await+ .expect("router should respond");++ assert_eq!(+ response.status(),+ StatusCode::BAD_REQUEST,+ "expected 400 for {body}"+ );+ assert!(service.calls().is_empty(), "should not reach the service");+ }+}++#[tokio::test]+async fn an_unparseable_cron_is_400_at_the_body() {+ let response = build_router(+ FakeRemindersService::default(),+ FakeEntityAccessService::default(),+ )+ .oneshot(+ authed(axum::http::Request::post("/"))+ .header(header::CONTENT_TYPE, "application/json")+ .body(json_body(serde_json::json!({+ "description": "x",+ "schedule": {"type": "recurring", "cron": "nope", "timezone": "America/New_York"},+ })))+ .expect("request should build"),+ )+ .await+ .expect("router should respond");++ assert_eq!(response.status(), StatusCode::UNPROCESSABLE_ENTITY);+}++#[tokio::test]+async fn a_five_field_cron_is_accepted() {+ let response = build_router(+ FakeRemindersService::default(),+ FakeEntityAccessService::default(),+ )+ .oneshot(+ authed(axum::http::Request::post("/"))+ .header(header::CONTENT_TYPE, "application/json")+ .body(json_body(serde_json::json!({+ "description": "standup",+ "schedule": {+ "type": "recurring", "cron": "0 9 * * *", "timezone": "America/New_York",+ },+ })))+ .expect("request should build"),+ )+ .await+ .expect("router should respond");++ assert_eq!(response.status(), StatusCode::CREATED);+}++#[tokio::test]+async fn missing_credentials_are_401() {+ let response = build_router(+ FakeRemindersService::default(),+ FakeEntityAccessService::default(),+ )+ .oneshot(+ axum::http::Request::get("/")+ .body(axum::body::Body::empty())+ .expect("request should build"),+ )+ .await+ .expect("router should respond");++ assert_eq!(response.status(), StatusCode::UNAUTHORIZED);+}++#[tokio::test]+async fn invalid_credentials_are_401() {+ let response = build_router(+ FakeRemindersService::default(),+ FakeEntityAccessService::default(),+ )+ .oneshot(+ axum::http::Request::get("/")+ .header(header::AUTHORIZATION, "Bearer nope")+ .body(axum::body::Body::empty())+ .expect("request should build"),+ )+ .await+ .expect("router should respond");++ assert_eq!(response.status(), StatusCode::UNAUTHORIZED);+}++#[tokio::test]+async fn list_returns_the_wrapped_collection() {+ let response = build_router(+ FakeRemindersService::default(),+ FakeEntityAccessService::default(),+ )+ .oneshot(+ authed(axum::http::Request::get("/"))+ .body(axum::body::Body::empty())+ .expect("request should build"),+ )+ .await+ .expect("router should respond");++ assert_eq!(response.status(), StatusCode::OK);+ let body = read_json(response).await;+ assert_eq!(body["reminders"].as_array().expect("array").len(), 1);+ assert!(+ body.get("nextCursor").is_none(),+ "a last page omits nextCursor entirely"+ );+}++#[tokio::test]+async fn list_passes_filters_and_paging_through() {+ let service = FakeRemindersService::default();+ let cursor = ReminderCursor {+ next_run_at: instant(2, 13),+ created_at: instant(1, 12),+ id: Uuid::from_u128(9),+ };+ let uri = format!(+ "/?entityType=document&entityId={ACCESSIBLE_DOC}&includeCompleted=true&limit=25&cursor={}",+ cursor.encode()+ );++ let response = build_router(service.clone(), FakeEntityAccessService::default())+ .oneshot(+ authed(axum::http::Request::get(&uri))+ .body(axum::body::Body::empty())+ .expect("request should build"),+ )+ .await+ .expect("router should respond");++ assert_eq!(response.status(), StatusCode::OK);+ assert_eq!(+ service.calls(),+ vec![ServiceCall::List {+ entity: Some((EntityType::Document, ACCESSIBLE_DOC.to_string())),+ include_completed: true,+ limit: Some(25),+ cursor: Some(cursor),+ }],+ "the cursor must survive the query string intact"+ );+}++#[tokio::test]+async fn list_surfaces_the_next_cursor() {+ let cursor = ReminderCursor {+ next_run_at: instant(2, 13),+ created_at: instant(1, 12),+ id: Uuid::from_u128(4),+ };+ let service = FakeRemindersService {+ next_cursor: Some(cursor),+ ..Default::default()+ };++ let response = build_router(service, FakeEntityAccessService::default())+ .oneshot(+ authed(axum::http::Request::get("/"))+ .body(axum::body::Body::empty())+ .expect("request should build"),+ )+ .await+ .expect("router should respond");++ let body = read_json(response).await;+ assert_eq!(body["nextCursor"], cursor.encode());+}++#[tokio::test]+async fn a_malformed_cursor_is_400() {+ let service = FakeRemindersService::default();+ let response = build_router(service.clone(), FakeEntityAccessService::default())+ .oneshot(+ authed(axum::http::Request::get("/?cursor=garbage"))+ .body(axum::body::Body::empty())+ .expect("request should build"),+ )+ .await+ .expect("router should respond");++ assert_eq!(response.status(), StatusCode::BAD_REQUEST);+ assert!(service.calls().is_empty());+}++#[tokio::test]+async fn a_list_filter_with_only_an_entity_type_is_400() {+ let service = FakeRemindersService::default();+ let response = build_router(service.clone(), FakeEntityAccessService::default())+ .oneshot(+ authed(axum::http::Request::get("/?entityType=document"))+ .body(axum::body::Body::empty())+ .expect("request should build"),+ )+ .await+ .expect("router should respond");++ assert_eq!(response.status(), StatusCode::BAD_REQUEST);+ assert!(service.calls().is_empty());+}++#[tokio::test]+async fn get_returns_the_reminder() {+ let service = FakeRemindersService::default();+ let id = Uuid::from_u128(42);+ let response = build_router(service.clone(), FakeEntityAccessService::default())+ .oneshot(+ authed(axum::http::Request::get(format!("/{id}")))+ .body(axum::body::Body::empty())+ .expect("request should build"),+ )+ .await+ .expect("router should respond");++ assert_eq!(response.status(), StatusCode::OK);+ assert_eq!(service.calls(), vec![ServiceCall::Get(id)]);+}++#[tokio::test]+async fn a_non_uuid_id_is_400() {+ let response = build_router(+ FakeRemindersService::default(),+ FakeEntityAccessService::default(),+ )+ .oneshot(+ authed(axum::http::Request::get("/not-a-uuid"))+ .body(axum::body::Body::empty())+ .expect("request should build"),+ )+ .await+ .expect("router should respond");++ assert_eq!(response.status(), StatusCode::BAD_REQUEST);+}++/// The item routes are gated by `ReminderAccessExtractor`, so a reminder the+/// caller does not own is refused before the service is reached. "Not yours"+/// and "does not exist" answer the same way on purpose: distinguishing them+/// would say whether the id is real.+#[tokio::test]+async fn a_reminder_the_caller_does_not_own_never_reaches_the_service() {+ let id = Uuid::from_u128(99);+ for request in [+ authed(axum::http::Request::get(format!("/{id}")))+ .body(axum::body::Body::empty())+ .expect("request should build"),+ authed(axum::http::Request::delete(format!("/{id}")))+ .body(axum::body::Body::empty())+ .expect("request should build"),+ ] {+ let service = FakeRemindersService::default();+ let response = build_router(+ service.clone(),+ FakeEntityAccessService::without_reminder_ownership(),+ )+ .oneshot(request)+ .await+ .expect("router should respond");++ assert_eq!(response.status(), StatusCode::UNAUTHORIZED);+ assert!(+ service.calls().is_empty(),+ "the service must not be reached without an ownership receipt"+ );+ }+}++#[tokio::test]+async fn patch_forwards_only_the_supplied_fields() {+ let service = FakeRemindersService::default();+ let id = Uuid::from_u128(7);+ let response = build_router(service.clone(), FakeEntityAccessService::default())+ .oneshot(+ authed(axum::http::Request::patch(format!("/{id}")))+ .header(header::CONTENT_TYPE, "application/json")+ .body(json_body(serde_json::json!({"enabled": false})))+ .expect("request should build"),+ )+ .await+ .expect("router should respond");++ assert_eq!(response.status(), StatusCode::OK);+ assert_eq!(+ service.calls(),+ vec![ServiceCall::Update {+ id,+ description: None,+ enabled: Some(false),+ has_schedule: false,+ }]+ );+}++#[tokio::test]+async fn delete_returns_204_with_no_body() {+ let service = FakeRemindersService::default();+ let id = Uuid::from_u128(3);+ let response = build_router(service.clone(), FakeEntityAccessService::default())+ .oneshot(+ authed(axum::http::Request::delete(format!("/{id}")))+ .body(axum::body::Body::empty())+ .expect("request should build"),+ )+ .await+ .expect("router should respond");++ assert_eq!(response.status(), StatusCode::NO_CONTENT);+ assert_eq!(service.calls(), vec![ServiceCall::Delete(id)]);+ let bytes = response+ .into_body()+ .collect()+ .await+ .expect("body should collect")+ .to_bytes();+ assert!(bytes.is_empty(), "204 must carry no body");+}++#[tokio::test]+async fn domain_errors_map_to_their_status_codes() {+ let table: Vec<(fn() -> ReminderError, StatusCode, bool)> = vec![+ (|| ReminderError::NotFound, StatusCode::NOT_FOUND, true),+ (+ || ReminderError::EntityNotFound,+ StatusCode::NOT_FOUND,+ true,+ ),+ (+ || ReminderError::BadRequest("nope".to_string()),+ StatusCode::BAD_REQUEST,+ true,+ ),+ (+ || ReminderError::EntityAccessDenied,+ StatusCode::FORBIDDEN,+ true,+ ),+ (+ || ReminderError::Internal(rootcause::report!("boom").into_dynamic()),+ StatusCode::INTERNAL_SERVER_ERROR,+ false,+ ),+ ];++ for (make_error, expected_status, message_is_public) in table {+ let expected_message = make_error().to_string();+ let response = build_router(+ FakeRemindersService::failing(make_error),+ FakeEntityAccessService::default(),+ )+ .oneshot(+ authed(axum::http::Request::get(format!("/{}", Uuid::from_u128(1))))+ .body(axum::body::Body::empty())+ .expect("request should build"),+ )+ .await+ .expect("router should respond");++ assert_eq!(response.status(), expected_status);+ let body = read_json(response).await;+ if message_is_public {+ assert_eq!(body["message"], expected_message);+ } else {+ // Internal errors must not leak their cause.+ assert_eq!(body["message"], "internal server error");+ assert!(!body["message"].to_string().contains("boom"));+ }+ }+}++#[tokio::test]+async fn responses_use_camel_case_field_names() {+ let response = build_router(+ FakeRemindersService::default(),+ FakeEntityAccessService::default(),+ )+ .oneshot(+ authed(axum::http::Request::get(format!("/{}", Uuid::from_u128(1))))+ .body(axum::body::Body::empty())+ .expect("request should build"),+ )+ .await+ .expect("router should respond");++ let body = read_json(response).await;+ let object = body.as_object().expect("reminder object");+ for field in ["nextRunAt", "createdAt", "updatedAt"] {+ assert!(object.contains_key(field), "missing {field}");+ }+ for field in ["next_run_at", "created_at", "updated_at"] {+ assert!(!object.contains_key(field), "unexpected snake_case {field}");+ }+ // Absent optional fields are omitted rather than sent as null.+ assert!(!object.contains_key("completedAt"));+}++#[tokio::test]+async fn create_does_not_claim_a_location() {+ let response = build_router(+ FakeRemindersService::default(),+ FakeEntityAccessService::default(),+ )+ .oneshot(+ authed(axum::http::Request::post("/"))+ .header(header::CONTENT_TYPE, "application/json")+ .body(json_body(serde_json::json!({+ "description": "follow up",+ "schedule": once_schedule(),+ })))+ .expect("request should build"),+ )+ .await+ .expect("router should respond");++ assert_eq!(response.status(), StatusCode::CREATED);+ // Deliberate: the router is mounted under a prefix it cannot see, so an+ // absolute Location would be wrong for the caller. The id is in the body.+ assert!(+ response.headers().get(header::LOCATION).is_none(),+ "Location would be misleading behind the /dss prefix"+ );+ assert_eq!(+ read_json(response).await["id"],+ Uuid::from_u128(1).to_string()+ );+}++#[tokio::test]+async fn an_oversized_limit_clamps_instead_of_failing_to_parse() {+ // With a narrower parameter type this failed at the query extractor with a+ // 400 before the domain's clamp could run.+ let service = FakeRemindersService::default();+ let response = build_router(service.clone(), FakeEntityAccessService::default())+ .oneshot(+ authed(axum::http::Request::get("/?limit=999999"))+ .body(axum::body::Body::empty())+ .expect("request should build"),+ )+ .await+ .expect("router should respond");++ assert_eq!(response.status(), StatusCode::OK);+ assert_eq!(+ service.calls(),+ vec![ServiceCall::List {+ entity: None,+ include_completed: false,+ limit: Some(999_999),+ cursor: None,+ }],+ "the raw value reaches the domain, which clamps it"+ );+}++#[tokio::test]+async fn a_negative_limit_is_rejected_by_the_query_extractor() {+ let service = FakeRemindersService::default();+ let response = build_router(service.clone(), FakeEntityAccessService::default())+ .oneshot(+ authed(axum::http::Request::get("/?limit=-1"))+ .body(axum::body::Body::empty())+ .expect("request should build"),+ )+ .await+ .expect("router should respond");++ assert_eq!(response.status(), StatusCode::BAD_REQUEST);+ assert!(service.calls().is_empty());+}++#[tokio::test]+async fn a_cursor_survives_the_query_string_unencoded() {+ // The delimiter and payload are all RFC 3986 unreserved characters, so the+ // cursor can be pasted straight back into `?cursor=` with no escaping.+ let service = FakeRemindersService::default();+ let cursor = ReminderCursor {+ next_run_at: instant(2, 13),+ created_at: instant(1, 12),+ id: Uuid::from_u128(9),+ };+ let encoded = cursor.encode();+ assert!(!encoded.contains('%'), "cursor should need no escaping");++ let response = build_router(service.clone(), FakeEntityAccessService::default())+ .oneshot(+ authed(axum::http::Request::get(format!("/?cursor={encoded}")))+ .body(axum::body::Body::empty())+ .expect("request should build"),+ )+ .await+ .expect("router should respond");++ assert_eq!(response.status(), StatusCode::OK);+ match service.calls().first() {+ Some(ServiceCall::List { cursor: got, .. }) => assert_eq!(*got, Some(cursor)),+ other => panic!("expected a list call, got {other:?}"),+ }+}++/// Framework-level rejections do not use the `ErrorResponse` envelope that+/// handler errors do. Pinned here so the OpenAPI annotations stay honest: the+/// documented `ErrorResponse` bodies describe handler errors only, and the 422+/// response is documented without a body schema.+#[tokio::test]+async fn extractor_rejections_are_plain_text_not_error_response() {+ let cases = [+ // Malformed body: rejected by the JSON extractor as 422.+ (+ authed(axum::http::Request::post("/"))+ .header(header::CONTENT_TYPE, "application/json")+ .body(json_body(serde_json::json!({"description": "x"})))+ .expect("request should build"),+ StatusCode::UNPROCESSABLE_ENTITY,+ ),+ ];++ for (request, expected_status) in cases {+ let response = build_router(+ FakeRemindersService::default(),+ FakeEntityAccessService::default(),+ )+ .oneshot(request)+ .await+ .expect("router should respond");++ assert_eq!(response.status(), expected_status);+ let content_type = response+ .headers()+ .get(header::CONTENT_TYPE)+ .and_then(|value| value.to_str().ok())+ .unwrap_or_default()+ .to_string();+ assert!(+ content_type.starts_with("text/plain"),+ "expected a plain-text rejection, got {content_type:?}"+ );+ }++ // Handler errors, by contrast, do use the JSON envelope.+ let response = build_router(+ FakeRemindersService::failing(|| ReminderError::NotFound),+ FakeEntityAccessService::default(),+ )+ .oneshot(+ authed(axum::http::Request::get(format!("/{}", Uuid::from_u128(1))))+ .body(axum::body::Body::empty())+ .expect("request should build"),+ )+ .await+ .expect("router should respond");+ assert_eq!(+ response+ .headers()+ .get(header::CONTENT_TYPE)+ .and_then(|value| value.to_str().ok()),+ Some("application/json")+ );+}++#[tokio::test]+async fn an_invalid_cron_message_reaches_the_client() {+ // The 422 body is plain text, but it carries our guidance about accepted+ // cron forms, which is the whole point of the improved error message.+ let response = build_router(+ FakeRemindersService::default(),+ FakeEntityAccessService::default(),+ )+ .oneshot(+ authed(axum::http::Request::post("/"))+ .header(header::CONTENT_TYPE, "application/json")+ .body(json_body(serde_json::json!({+ "description": "x",+ "schedule": {"type": "recurring", "cron": "nope", "timezone": "America/New_York"},+ })))+ .expect("request should build"),+ )+ .await+ .expect("router should respond");++ assert_eq!(response.status(), StatusCode::UNPROCESSABLE_ENTITY);+ let bytes = response+ .into_body()+ .collect()+ .await+ .expect("body should collect")+ .to_bytes();+ let body = String::from_utf8_lossy(&bytes);+ assert!(body.contains("expected 5 fields"), "unhelpful body: {body}");+}++/// The router declares its collection routes at `/` and DSS mounts it with+/// `.nest("/reminders", ..)`, so the paths clients actually call are+/// `/reminders` and `/reminders/{id}` — never the bare `/` every other test in+/// this file exercises. Nesting a `/` route is a known routing footgun (whether+/// the prefix alone matches, or only the prefix with a trailing slash), so pin+/// the mounted shape here rather than inferring it from the nested router.+fn mounted_router(service: FakeRemindersService) -> axum::Router {+ axum::Router::new().nest(+ "/reminders",+ build_router(service, FakeEntityAccessService::default()),+ )+}++#[tokio::test]+async fn list_is_reachable_at_the_mounted_collection_path() {+ let service = FakeRemindersService::default();+ let response = mounted_router(service.clone())+ .oneshot(+ authed(axum::http::Request::get("/reminders"))+ .body(axum::body::Body::empty())+ .expect("request should build"),+ )+ .await+ .expect("router should respond");++ assert_eq!(response.status(), StatusCode::OK);+ assert!(+ service+ .calls()+ .iter()+ .any(|call| matches!(call, ServiceCall::List { .. })),+ "GET /reminders did not reach the handler"+ );+}++/// Axum 0.8 dropped implicit trailing-slash redirects, so the nested `/` route+/// answers `/reminders` and *only* `/reminders`. Documented rather than fixed:+/// every other router DSS nests behaves the same way, the OpenAPI spec and the+/// generated clients all use the unslashed form, and adding a redirect layer+/// for this one router would make it the odd one out.+#[tokio::test]+async fn the_mounted_collection_path_does_not_answer_a_trailing_slash() {+ let response = mounted_router(FakeRemindersService::default())+ .oneshot(+ authed(axum::http::Request::get("/reminders/"))+ .body(axum::body::Body::empty())+ .expect("request should build"),+ )+ .await+ .expect("router should respond");++ assert_eq!(response.status(), StatusCode::NOT_FOUND);+}++#[tokio::test]+async fn create_is_reachable_at_the_mounted_collection_path() {+ let service = FakeRemindersService::default();+ let response = mounted_router(service.clone())+ .oneshot(+ authed(axum::http::Request::post("/reminders"))+ .header(header::CONTENT_TYPE, "application/json")+ .body(json_body(serde_json::json!({+ "description": "follow up",+ "schedule": once_schedule(),+ })))+ .expect("request should build"),+ )+ .await+ .expect("router should respond");++ assert_eq!(response.status(), StatusCode::CREATED);+ assert!(+ service+ .calls()+ .iter()+ .any(|call| matches!(call, ServiceCall::Create { .. })),+ "POST /reminders did not reach the handler"+ );+}++#[tokio::test]+async fn item_routes_are_reachable_at_the_mounted_path() {+ let id = Uuid::now_v7();+ let service = FakeRemindersService::default();+ let response = mounted_router(service.clone())+ .oneshot(+ authed(axum::http::Request::get(format!("/reminders/{id}")))+ .body(axum::body::Body::empty())+ .expect("request should build"),+ )+ .await+ .expect("router should respond");++ assert_eq!(response.status(), StatusCode::OK);+ assert!(+ service.calls().contains(&ServiceCall::Get(id)),+ "GET /reminders/{{id}} did not reach the handler"+ );+}++/// A create naming an entity that does not exist must not answer "reminder not+/// found" — there is no reminder yet, and that wording sends a client looking+/// for the wrong thing. `EntityNotFound` keeps the 404 but says which object is+/// missing.+#[tokio::test]+async fn creating_against_a_missing_entity_says_the_entity_is_missing() {+ let response = build_router(+ FakeRemindersService::default(),+ FakeEntityAccessService::denying_with(|| AccessError::NotFound("doc")),+ )+ .oneshot(+ authed(axum::http::Request::post("/"))+ .header(header::CONTENT_TYPE, "application/json")+ .body(json_body(serde_json::json!({+ "description": "follow up",+ "entityType": "document",+ "entityId": "33333333-3333-4333-8333-333333333333",+ "schedule": once_schedule(),+ })))+ .expect("request should build"),+ )+ .await+ .expect("router should respond");++ assert_eq!(response.status(), StatusCode::NOT_FOUND);+ let body = read_json(response).await;+ let message = body["message"].as_str().unwrap_or_default();+ assert_eq!(message, "entity not found");+ assert!(+ !message.contains("reminder"),+ "create failure should not blame a reminder: {message}"+ );+}diff --git a/crates/reminders/src/inbound/dispatch_worker.rs b/crates/reminders/src/inbound/dispatch_worker.rsnew file mode 100644index 0000000000..05e5223184--- /dev/null+++ b/crates/reminders/src/inbound/dispatch_worker.rs@@ -0,0 +1,159 @@+//! Queue worker driving reminder dispatch.+//!+//! Every message on the dispatch queue is one of two things: the minutely tick+//! an EventBridge rule puts there, or one firing that a tick fanned out. This+//! adapter tells them apart and calls the matching use case — it makes no+//! decisions of its own beyond what to do with the message afterwards.+//!+//! Several of these run at once, one per service task, all on the same queue.+//! That is the point: fan-out only buys parallelism if more than one worker is+//! pulling from the pool.++#[cfg(test)]+mod test;++use std::time::Duration;++use tokio_util::sync::CancellationToken;++use crate::domain::models::{+ DueFiring, ReminderDispatchMessage, ReminderDispatchOperation, SweepSummary,+};+use crate::domain::ports::{RawDispatchMessage, ReminderDispatch, ReminderDispatchQueue};++/// How long to wait after a failed receive before trying again.+///+/// Only covers the queue being unreachable; an idle queue is handled by the+/// adapter's long poll, not by sleeping here.+const RECEIVE_BACKOFF: Duration = Duration::from_secs(1);++/// Polls the dispatch queue and runs what it finds.+pub struct DispatchWorker<S, Q> {+ service: S,+ queue: Q,+}++impl<S, Q> DispatchWorker<S, Q>+where+ S: ReminderDispatch,+ Q: ReminderDispatchQueue,+{+ /// Build a worker over a dispatch service and its queue.+ pub fn new(service: S, queue: Q) -> Self {+ Self { service, queue }+ }++ /// Poll until cancelled.+ ///+ /// A batch already received is finished before shutdown, so a delivery is+ /// never abandoned between claiming and completing.+ pub async fn run(&self, cancellation_token: CancellationToken) {+ loop {+ let received = tokio::select! {+ biased;+ () = cancellation_token.cancelled() => return,+ received = self.queue.receive_messages() => received,+ };++ match received {+ Ok(messages) => {+ for message in messages {+ self.handle_message(message).await;+ }+ }+ Err(e) => {+ tracing::error!(error = ?e, "failed to receive reminder dispatch messages");+ tokio::select! {+ biased;+ () = cancellation_token.cancelled() => return,+ () = tokio::time::sleep(RECEIVE_BACKOFF) => {}+ }+ }+ }+ }+ }++ /// Run one message and decide whether it is done with.+ async fn handle_message(&self, message: RawDispatchMessage) {+ let operation = match serde_json::from_str::<ReminderDispatchMessage>(&message.body) {+ Ok(message) => message.operation,+ Err(e) => {+ // Unparseable is not retryable. Acking beats leaving it to be+ // redelivered until the redrive policy dead-letters it, which+ // would burn a receive a minute and bury the DLQ alarm in+ // noise that no retry could ever clear.+ tracing::error!(+ error = ?e,+ body_length = message.body.len(),+ "discarding an unparseable reminder dispatch message",+ );+ self.delete(&message.receipt_handle).await;+ return;+ }+ };++ let handled = match operation {+ ReminderDispatchOperation::Sweep => self.sweep().await,+ ReminderDispatchOperation::Deliver {+ reminder_id,+ scheduled_for,+ } => {+ let firing = DueFiring {+ reminder_id,+ scheduled_for,+ };+ match self.service.deliver(firing).await {+ Ok(outcome) => {+ tracing::debug!(+ reminder_id = %reminder_id,+ ?outcome,+ "handled a reminder firing",+ );+ true+ }+ Err(e) => {+ tracing::error!(+ error = ?e,+ reminder_id = %reminder_id,+ "failed to deliver a reminder firing; leaving it for redelivery",+ );+ false+ }+ }+ }+ };++ // Only ack work that finished. Anything left is redelivered once the+ // visibility timeout lapses, and dead-lettered if it keeps failing.+ if handled {+ self.delete(&message.receipt_handle).await;+ }+ }++ /// Run a sweep, reporting whether the message can be acked.+ async fn sweep(&self) -> bool {+ match self.service.sweep().await {+ Ok(summary) => {+ // Most ticks find nothing — the schedule fires every minute+ // whether or not anything is due — so only say so when it did.+ if summary != SweepSummary::default() {+ tracing::info!(dispatched = summary.dispatched, "fanned out due reminders");+ }+ true+ }+ Err(e) => {+ tracing::error!(error = ?e, "reminder sweep failed; leaving it for redelivery");+ false+ }+ }+ }++ async fn delete(&self, receipt_handle: &str) {+ if let Err(e) = self.queue.delete_message(receipt_handle).await {+ // The message reappears after the visibility timeout. Delivery is+ // idempotent through the claim, so a repeat is wasted work rather+ // than a duplicate notification.+ tracing::error!(error = ?e, "failed to delete a reminder dispatch message");+ }+ }+}diff --git a/crates/reminders/src/inbound/dispatch_worker/test.rs b/crates/reminders/src/inbound/dispatch_worker/test.rsnew file mode 100644index 0000000000..853fd7c3cc--- /dev/null+++ b/crates/reminders/src/inbound/dispatch_worker/test.rs@@ -0,0 +1,223 @@+use std::sync::{Arc, Mutex};++use chrono::{DateTime, TimeZone, Utc};+use uuid::Uuid;++use super::*;+use crate::domain::models::{DeliveryOutcome, ReminderError};++fn now() -> DateTime<Utc> {+ Utc.with_ymd_and_hms(2026, 7, 1, 12, 0, 0)+ .single()+ .expect("unambiguous instant")+}++fn uuid(n: u8) -> Uuid {+ Uuid::from_bytes([n; 16])+}++fn message(body: &str) -> RawDispatchMessage {+ RawDispatchMessage {+ body: body.to_string(),+ receipt_handle: "receipt-1".to_string(),+ }+}++#[derive(Debug, thiserror::Error)]+#[error("fake failure")]+struct FakeErr;++#[derive(Default)]+struct FakeServiceState {+ swept: usize,+ delivered: Vec<DueFiring>,+ sweep_fails: bool,+ deliver_fails: bool,+}++#[derive(Clone, Default)]+struct FakeService(Arc<Mutex<FakeServiceState>>);++impl FakeService {+ fn failing_sweep() -> Self {+ let service = Self::default();+ service.0.lock().unwrap().sweep_fails = true;+ service+ }++ fn failing_deliver() -> Self {+ let service = Self::default();+ service.0.lock().unwrap().deliver_fails = true;+ service+ }++ fn swept(&self) -> usize {+ self.0.lock().unwrap().swept+ }++ fn delivered(&self) -> Vec<DueFiring> {+ self.0.lock().unwrap().delivered.clone()+ }+}++impl ReminderDispatch for FakeService {+ async fn sweep(&self) -> Result<SweepSummary, ReminderError> {+ let mut state = self.0.lock().unwrap();+ if state.sweep_fails {+ return Err(ReminderError::NotFound);+ }+ state.swept += 1;+ Ok(SweepSummary { dispatched: 2 })+ }++ async fn deliver(&self, firing: DueFiring) -> Result<DeliveryOutcome, ReminderError> {+ let mut state = self.0.lock().unwrap();+ if state.deliver_fails {+ return Err(ReminderError::NotFound);+ }+ state.delivered.push(firing);+ Ok(DeliveryOutcome::Delivered)+ }+}++#[derive(Clone, Default)]+struct FakeQueue {+ deleted: Arc<Mutex<Vec<String>>>,+}++impl FakeQueue {+ fn deleted(&self) -> Vec<String> {+ self.deleted.lock().unwrap().clone()+ }+}++impl ReminderDispatchQueue for FakeQueue {+ type Err = FakeErr;++ async fn publish_batch(&self, _messages: &[ReminderDispatchMessage]) -> Result<(), Self::Err> {+ Ok(())+ }++ async fn receive_messages(&self) -> Result<Vec<RawDispatchMessage>, Self::Err> {+ Ok(Vec::new())+ }++ async fn delete_message(&self, receipt_handle: &str) -> Result<(), Self::Err> {+ self.deleted+ .lock()+ .unwrap()+ .push(receipt_handle.to_string());+ Ok(())+ }+}++fn worker(service: FakeService, queue: FakeQueue) -> DispatchWorker<FakeService, FakeQueue> {+ DispatchWorker::new(service, queue)+}++#[tokio::test]+async fn runs_a_sweep_for_the_eventbridge_payload() {+ // Verbatim what the EventBridge rule is configured to send.+ let service = FakeService::default();+ let queue = FakeQueue::default();++ worker(service.clone(), queue.clone())+ .handle_message(message(r#"{"operation":"sweep"}"#))+ .await;++ assert_eq!(service.swept(), 1);+ assert_eq!(queue.deleted(), vec!["receipt-1"]);+}++#[tokio::test]+async fn delivers_a_fanned_out_firing() {+ let service = FakeService::default();+ let queue = FakeQueue::default();++ let body = serde_json::to_string(&ReminderDispatchMessage::deliver(DueFiring {+ reminder_id: uuid(1),+ scheduled_for: now(),+ }))+ .expect("serializes");++ worker(service.clone(), queue.clone())+ .handle_message(message(&body))+ .await;++ assert_eq!(+ service.delivered(),+ vec![DueFiring {+ reminder_id: uuid(1),+ scheduled_for: now(),+ }]+ );+ assert_eq!(queue.deleted(), vec!["receipt-1"]);+}++#[tokio::test]+async fn discards_an_unparseable_message() {+ let service = FakeService::default();+ let queue = FakeQueue::default();++ worker(service.clone(), queue.clone())+ .handle_message(message("not json"))+ .await;++ assert_eq!(service.swept(), 0);+ assert!(service.delivered().is_empty());+ // Acked: no retry could ever parse it, and leaving it would burn a receive+ // a minute until the redrive policy dead-lettered it.+ assert_eq!(queue.deleted(), vec!["receipt-1"]);+}++#[tokio::test]+async fn discards_a_message_naming_an_unknown_operation() {+ let service = FakeService::default();+ let queue = FakeQueue::default();++ worker(service.clone(), queue.clone())+ .handle_message(message(r#"{"operation":"explode"}"#))+ .await;++ assert_eq!(service.swept(), 0);+ assert_eq!(queue.deleted(), vec!["receipt-1"]);+}++#[tokio::test]+async fn leaves_a_failed_sweep_for_redelivery() {+ let queue = FakeQueue::default();++ worker(FakeService::failing_sweep(), queue.clone())+ .handle_message(message(r#"{"operation":"sweep"}"#))+ .await;++ assert!(queue.deleted().is_empty());+}++#[tokio::test]+async fn leaves_a_failed_delivery_for_redelivery() {+ let queue = FakeQueue::default();++ let body = serde_json::to_string(&ReminderDispatchMessage::deliver(DueFiring {+ reminder_id: uuid(1),+ scheduled_for: now(),+ }))+ .expect("serializes");++ worker(FakeService::failing_deliver(), queue.clone())+ .handle_message(message(&body))+ .await;++ assert!(queue.deleted().is_empty());+}++#[tokio::test]+async fn stops_when_cancelled() {+ let token = CancellationToken::new();+ token.cancel();++ // Returns rather than hanging on the queue's long poll.+ worker(FakeService::default(), FakeQueue::default())+ .run(token)+ .await;+}diff --git a/crates/reminders/src/lib.rs b/crates/reminders/src/lib.rsnew file mode 100644index 0000000000..e508804285--- /dev/null+++ b/crates/reminders/src/lib.rs@@ -0,0 +1,26 @@+#![deny(missing_docs)]+//! Reminders: user-scoped scheduled nudges, optionally attached to an entity,+//! following the hexagonal architecture pattern.+//!+//! A reminder fires either once (`remind_at`) or repeatedly on a cron schedule+//! evaluated in the user's timezone. Attaching a reminder to an entity requires+//! view access to that entity; the reminder itself is private to its owner.+//!+//! # Architecture+//!+//! - **domain**: domain models, ports, and the service implementation.+//! - **inbound**: driving adapters (Axum HTTP router, dispatch queue worker).+//! - **outbound**: driven adapters (Postgres repository, SQS dispatch queue).+//!+//! Delivery lives here too, as a pub/sub fan-out over a single queue: a+//! scheduled tick sweeps for due firings and publishes one message each, and+//! the same pool of workers claims, notifies and completes them in parallel.+//! Recurring schedules are modelled and stored but not yet dispatched.++pub mod domain;++#[cfg(any(feature = "inbound", feature = "dispatch"))]+pub mod inbound;++#[cfg(feature = "outbound")]+pub mod outbound;diff --git a/crates/reminders/src/outbound.rs b/crates/reminders/src/outbound.rsnew file mode 100644index 0000000000..ac0d92701d--- /dev/null+++ b/crates/reminders/src/outbound.rs@@ -0,0 +1,10 @@+//! Outbound (driven) adapters for reminders.++#[cfg(feature = "notify")]+pub mod notification_notifier;++#[cfg(feature = "postgres")]+pub mod pg_reminders_repo;++#[cfg(feature = "dispatch-sqs")]+pub mod sqs_dispatch_queue;diff --git a/crates/reminders/src/outbound/notification_notifier.rs b/crates/reminders/src/outbound/notification_notifier.rsnew file mode 100644index 0000000000..95bce80591--- /dev/null+++ b/crates/reminders/src/outbound/notification_notifier.rs@@ -0,0 +1,81 @@+//! Notification-service implementation of the [`ReminderNotifier`] port.++#[cfg(test)]+mod test;++use std::collections::HashSet;++use macro_user_id::cowlike::CowLike;+use model_entity::EntityType;+use model_notifications::ReminderMetadata;+use notification::domain::models::SendNotificationRequestBuilder;+use notification::domain::service::NotificationIngress;++use crate::domain::models::DueReminder;+use crate::domain::ports::ReminderNotifier;++/// Delivers due reminders by handing them to the notification ingress, which+/// owns everything downstream: recipient filtering, persistence, websocket,+/// push and email digest.+#[derive(Debug, Clone)]+pub struct NotificationReminderNotifier<I> {+ ingress: I,+}++impl<I> NotificationReminderNotifier<I> {+ /// Wrap a notification ingress.+ pub fn new(ingress: I) -> Self {+ Self { ingress }+ }+}++/// A delivery attempt that the notification ingress rejected.+#[derive(Debug, thiserror::Error)]+#[error("failed to send reminder notification")]+pub struct NotifyError;++impl<I: NotificationIngress> ReminderNotifier for NotificationReminderNotifier<I> {+ type Err = NotifyError;++ // `DueReminder` carries both the owner's macro user id — which embeds their+ // email — and the description, which is the user's own note. Only the+ // reminder id is safe to put in a span.+ #[tracing::instrument(err, skip_all, fields(reminder_id = %due.reminder.id))]+ async fn notify(&self, due: &DueReminder) -> Result<(), Self::Err> {+ // A standalone reminder has no entity to hang the notification on, so+ // it is addressed at the user themselves — the same shape+ // `inbox_reauth_required` uses.+ let notification_entity = match due.reminder.entity() {+ Some(entity) => entity,+ None => EntityType::User.with_entity_str(due.owner_id.as_ref()),+ };++ let request = SendNotificationRequestBuilder {+ notification_entity,+ secondary_notification_entity: None,+ notification: ReminderMetadata {+ reminder_id: due.reminder.id,+ description: due.reminder.description.clone(),+ },+ // Must stay None. A recipient who is also the sender is filtered+ // out of their own notification, and a reminder's only recipient is+ // the person who set it — naming them as sender would drop the+ // notification silently.+ sender_id: None,+ recipient_ids: HashSet::from([due.owner_id.copied()]),+ }+ .into_request()+ .with_apns()+ .with_conn_gateway();++ self.ingress+ .send_notification(request)+ .await+ .map_err(|e| {+ tracing::error!(error = ?e, reminder_id = %due.reminder.id, "reminder notification rejected");+ NotifyError+ })?;++ Ok(())+ }+}diff --git a/crates/reminders/src/outbound/notification_notifier/test.rs b/crates/reminders/src/outbound/notification_notifier/test.rsnew file mode 100644index 0000000000..81e008491c--- /dev/null+++ b/crates/reminders/src/outbound/notification_notifier/test.rs@@ -0,0 +1,198 @@+use std::sync::{Arc, Mutex};++use chrono::{DateTime, TimeZone, Utc};+use macro_user_id::user_id::MacroUserIdStr;+use notification::domain::models::request::NotificationResult;+use notification::domain::models::{Notification, SendNotificationRequest};+use notification::domain::service::SendNotificationError;+use rootcause::Report;+use serde::Serialize;+use uuid::Uuid;++use super::*;+use crate::domain::models::{Reminder, ReminderSchedule};++const OWNER: &str = "macro|[email protected]";++fn now() -> DateTime<Utc> {+ Utc.with_ymd_and_hms(2026, 7, 1, 12, 0, 0)+ .single()+ .expect("unambiguous instant")+}++fn owner() -> MacroUserIdStr<'static> {+ MacroUserIdStr::parse_from_str(OWNER)+ .expect("valid user id")+ .into_owned()+}++fn reminder_id() -> Uuid {+ Uuid::from_bytes([7; 16])+}++fn due(entity_type: Option<EntityType>, entity_id: Option<&str>) -> DueReminder {+ DueReminder {+ reminder: Reminder {+ id: reminder_id(),+ description: "Follow up on the contract".to_string(),+ entity_type,+ entity_id: entity_id.map(str::to_string),+ schedule: ReminderSchedule::Once { remind_at: now() },+ next_run_at: now(),+ enabled: true,+ completed_at: None,+ created_at: now(),+ updated_at: now(),+ },+ owner_id: owner(),+ scheduled_for: now(),+ }+}++/// Captures the request as JSON. The request's fields are crate-private to+/// `notification`, but the whole thing is `Serialize` — which is also exactly+/// how it reaches the ingress queue, so asserting on the wire shape checks what+/// actually gets sent.+#[derive(Clone, Default)]+struct CapturingIngress {+ sent: Arc<Mutex<Vec<serde_json::Value>>>,+ fails: bool,+}++impl CapturingIngress {+ fn failing() -> Self {+ Self {+ sent: Arc::default(),+ fails: true,+ }+ }++ fn last(&self) -> serde_json::Value {+ self.sent+ .lock()+ .unwrap()+ .last()+ .cloned()+ .expect("a notification was sent")+ }+}++impl NotificationIngress for CapturingIngress {+ async fn send_notification<+ 'a,+ T: Notification + Clone + 'static,+ U: Serialize + Send + Sync + 'static,+ >(+ &'a self,+ req: SendNotificationRequest<'a, T, U>,+ ) -> Result<Option<NotificationResult<'a>>, Report<SendNotificationError>> {+ if self.fails {+ return Err(rootcause::report!(SendNotificationError::Other));+ }+ self.sent+ .lock()+ .unwrap()+ .push(serde_json::to_value(&req).expect("request serializes"));+ Ok(None)+ }+}++#[tokio::test]+async fn sends_with_no_sender_so_the_owner_is_not_filtered_out() {+ let ingress = CapturingIngress::default();++ NotificationReminderNotifier::new(ingress.clone())+ .notify(&due(Some(EntityType::Document), Some("doc-1")))+ .await+ .expect("notify succeeds");++ let sent = ingress.last();+ // The single most breakable property: a recipient who is also the sender is+ // excluded from their own notification, and a reminder's only recipient is+ // the person who set it.+ assert_eq!(sent["req"]["sender_id"], serde_json::Value::Null);+ assert_eq!(+ sent["req"]["recipient_ids"],+ serde_json::json!([OWNER]),+ "the owner is the only recipient"+ );+}++#[tokio::test]+async fn addresses_the_notification_at_the_reminders_entity() {+ let ingress = CapturingIngress::default();++ NotificationReminderNotifier::new(ingress.clone())+ .notify(&due(Some(EntityType::Channel), Some("channel-1")))+ .await+ .expect("notify succeeds");++ let entity = &ingress.last()["req"]["notification_entity"];+ assert_eq!(entity["entity_type"], "channel");+ assert_eq!(entity["entity_id"], "channel-1");+}++#[tokio::test]+async fn falls_back_to_the_user_when_the_reminder_has_no_entity() {+ let ingress = CapturingIngress::default();++ NotificationReminderNotifier::new(ingress.clone())+ .notify(&due(None, None))+ .await+ .expect("notify succeeds");++ // `event_item_id`/`event_item_type` are NOT NULL, so a standalone reminder+ // still needs an entity; it is addressed at the user, as inbox_reauth does.+ let entity = &ingress.last()["req"]["notification_entity"];+ assert_eq!(entity["entity_type"], "user");+ assert_eq!(entity["entity_id"], OWNER);+}++#[tokio::test]+async fn carries_the_reminder_payload_under_the_reminder_tag() {+ let ingress = CapturingIngress::default();++ NotificationReminderNotifier::new(ingress.clone())+ .notify(&due(Some(EntityType::Document), Some("doc-1")))+ .await+ .expect("notify succeeds");++ let notification = &ingress.last()["req"]["notification"];+ assert_eq!(notification["tag"], ReminderMetadata::TYPE_NAME);+ assert_eq!(+ notification["content"]["reminderId"],+ reminder_id().to_string()+ );+ assert_eq!(+ notification["content"]["description"],+ "Follow up on the contract"+ );+}++#[tokio::test]+async fn requests_push_and_websocket_delivery() {+ let ingress = CapturingIngress::default();++ NotificationReminderNotifier::new(ingress.clone())+ .notify(&due(Some(EntityType::Document), Some("doc-1")))+ .await+ .expect("notify succeeds");++ let sent = ingress.last();+ assert_eq!(sent["send_conn_gateway"], true);+ assert!(+ !sent["build_apns"].is_null(),+ "an APNS payload must be built or mobile gets nothing"+ );+}++#[tokio::test]+async fn surfaces_a_rejected_send_as_an_error() {+ let result = NotificationReminderNotifier::new(CapturingIngress::failing())+ .notify(&due(Some(EntityType::Document), Some("doc-1")))+ .await;++ // The dispatcher relies on this to leave the firing uncompleted and+ // retryable rather than marking it delivered.+ assert!(result.is_err());+}diff --git a/crates/reminders/src/outbound/pg_reminders_repo.rs b/crates/reminders/src/outbound/pg_reminders_repo.rsnew file mode 100644index 0000000000..0b7cec15a8--- /dev/null+++ b/crates/reminders/src/outbound/pg_reminders_repo.rs@@ -0,0 +1,673 @@+//! PostgreSQL implementation of the [`RemindersRepo`] port.++#[cfg(test)]+mod test;++use std::str::FromStr;++use chrono::{DateTime, Utc};+use chrono_tz::Tz;+use macro_user_id::cowlike::CowLike;+use macro_user_id::user_id::MacroUserIdStr;+use model_entity::{Entity, EntityType};+use sqlx::PgPool;+use uuid::Uuid;++use crate::domain::models::{+ DueFiring, DueReminder, InvalidCron, NewReminder, Reminder, ReminderBatch, ReminderCron,+ ReminderCursor, ReminderFilter, ReminderSchedule, ReminderUpdate,+};+use crate::domain::ports::{ReminderDispatchRepo, RemindersRepo};++/// Postgres-backed reminders repository.+#[derive(Debug, Clone)]+pub struct PgRemindersRepo {+ pool: PgPool,+}++impl PgRemindersRepo {+ /// Create a repository backed by the provided pool.+ pub fn new(pool: PgPool) -> Self {+ Self { pool }+ }+}++/// Errors produced by the Postgres reminders repository.+#[derive(Debug, thiserror::Error)]+pub enum RemindersRepoErr {+ /// Underlying database error.+ #[error(transparent)]+ Db(#[from] sqlx::Error),+ /// A stored entity type could not be parsed into [EntityType].+ #[error("invalid entity type {value:?} stored for reminder {reminder_id}")]+ InvalidEntityType {+ /// The reminder carrying the bad value.+ reminder_id: Uuid,+ /// The value that could not be parsed.+ value: String,+ },+ /// A stored timezone is not a known IANA zone.+ #[error("invalid timezone stored for reminder {0}: {1}")]+ InvalidTimezone(Uuid, String),+ /// A stored cron expression no longer parses.+ #[error("invalid cron stored for reminder {0}: {1}")]+ InvalidCron(Uuid, #[source] InvalidCron),+ /// Neither schedule mode is populated, which the table's CHECK constraint+ /// should make impossible.+ #[error("reminder {0} has no schedule")]+ MissingSchedule(Uuid),+ /// An entity id is not a uuid, which the `entity_id` column requires.+ #[error("invalid entity id {value:?} for reminder association")]+ InvalidEntityId {+ /// The value that could not be parsed.+ value: String,+ },+ /// A stored owner is not a parseable macro user id.+ ///+ /// Identified by reminder rather than by the offending value: a macro user+ /// id is `macro|[email protected]`, so echoing it would put an email+ /// address into every log line this error reaches. The row id is enough to+ /// find it.+ #[error("invalid user id stored for reminder {reminder_id}")]+ InvalidUserId {+ /// The reminder carrying the bad value.+ reminder_id: Uuid,+ },+}++/// A `reminder` row, before the schedule columns are folded into a+/// [`ReminderSchedule`].+struct ReminderRow {+ id: Uuid,+ description: String,+ entity_type: Option<String>,+ entity_id: Option<Uuid>,+ remind_at: Option<DateTime<Utc>>,+ cron: Option<String>,+ timezone: Option<String>,+ next_run_at: DateTime<Utc>,+ enabled: bool,+ completed_at: Option<DateTime<Utc>>,+ created_at: DateTime<Utc>,+ updated_at: DateTime<Utc>,+}++impl ReminderRow {+ /// This row's position in the list ordering, readable or not.+ fn position(&self) -> ReminderCursor {+ ReminderCursor {+ next_run_at: self.next_run_at,+ created_at: self.created_at,+ id: self.id,+ }+ }++ fn into_reminder(self) -> Result<Reminder, RemindersRepoErr> {+ let id = self.id;+ let entity_type = self+ .entity_type+ .map(|raw| {+ raw.parse::<EntityType>()+ .map_err(|_| RemindersRepoErr::InvalidEntityType {+ reminder_id: id,+ value: raw,+ })+ })+ .transpose()?;++ let schedule = match (self.remind_at, self.cron, self.timezone) {+ (Some(remind_at), _, _) => ReminderSchedule::Once { remind_at },+ (None, Some(cron), Some(timezone)) => ReminderSchedule::Recurring {+ cron: ReminderCron::parse(cron)+ .map_err(|e| RemindersRepoErr::InvalidCron(self.id, e))?,+ timezone: Tz::from_str(&timezone)+ .map_err(|_| RemindersRepoErr::InvalidTimezone(self.id, timezone))?,+ },+ _ => return Err(RemindersRepoErr::MissingSchedule(self.id)),+ };++ Ok(Reminder {+ id: self.id,+ description: self.description,+ entity_type,+ entity_id: self.entity_id.map(|id| id.to_string()),+ schedule,+ next_run_at: self.next_run_at,+ enabled: self.enabled,+ completed_at: self.completed_at,+ created_at: self.created_at,+ updated_at: self.updated_at,+ })+ }+}++/// A `reminder` row read by the dispatcher, which unlike every other read is+/// not scoped to one user and so has to carry the owner.+struct DueReminderRow {+ id: Uuid,+ user_id: String,+ description: String,+ entity_type: Option<String>,+ entity_id: Option<Uuid>,+ remind_at: Option<DateTime<Utc>>,+ cron: Option<String>,+ timezone: Option<String>,+ next_run_at: DateTime<Utc>,+ enabled: bool,+ completed_at: Option<DateTime<Utc>>,+ created_at: DateTime<Utc>,+ updated_at: DateTime<Utc>,+}++impl DueReminderRow {+ fn into_due(self) -> Result<DueReminder, RemindersRepoErr> {+ let reminder_id = self.id;+ let owner_id = match MacroUserIdStr::parse_from_str(&self.user_id) {+ Ok(owner_id) => owner_id.into_owned(),+ Err(_) => {+ return Err(RemindersRepoErr::InvalidUserId { reminder_id });+ }+ };++ // The firing being delivered is the reminder's current `next_run_at`,+ // which is also what keys the occurrence row.+ let scheduled_for = self.next_run_at;++ let reminder = ReminderRow {+ id: self.id,+ description: self.description,+ entity_type: self.entity_type,+ entity_id: self.entity_id,+ remind_at: self.remind_at,+ cron: self.cron,+ timezone: self.timezone,+ next_run_at: self.next_run_at,+ enabled: self.enabled,+ completed_at: self.completed_at,+ created_at: self.created_at,+ updated_at: self.updated_at,+ }+ .into_reminder()?;++ Ok(DueReminder {+ reminder,+ owner_id,+ scheduled_for,+ })+ }+}++/// The entity id as it is stored: a uuid.+///+/// `Entity` carries the id as a string because it is shared across domains+/// that still key on text, so the conversion happens at this boundary. The+/// router rejects a malformed id first, so reaching the error arm here means+/// a caller bypassed it.+fn entity_uuid(entity: Option<&Entity<'_>>) -> Result<Option<Uuid>, RemindersRepoErr> {+ entity+ .map(|entity| {+ entity.entity_id.as_ref().parse::<Uuid>().map_err(|_| {+ RemindersRepoErr::InvalidEntityId {+ value: entity.entity_id.as_ref().to_string(),+ }+ })+ })+ .transpose()+}++/// The schedule as it is stored: `(remind_at, cron, timezone)`, with exactly+/// one mode populated.+fn schedule_columns(+ schedule: &ReminderSchedule,+) -> (Option<DateTime<Utc>>, Option<&str>, Option<String>) {+ match schedule {+ ReminderSchedule::Once { remind_at } => (Some(*remind_at), None, None),+ ReminderSchedule::Recurring { cron, timezone } => {+ (None, Some(cron.as_str()), Some(timezone.name().to_string()))+ }+ }+}++impl RemindersRepo for PgRemindersRepo {+ type Err = RemindersRepoErr;++ #[tracing::instrument(err, skip(self, user_id, new))]+ async fn create_reminder(+ &self,+ user_id: &MacroUserIdStr<'_>,+ new: &NewReminder,+ ) -> Result<Reminder, Self::Err> {+ let entity_type: Option<&str> = new.entity.as_ref().map(|entity| entity.entity_type.into());+ let entity_id = entity_uuid(new.entity.as_ref())?;+ let (remind_at, cron, timezone) = schedule_columns(&new.schedule);+ // Time-ordered v7 so ids sort by creation, and so the id is known before+ // the insert rather than assigned by the database.+ let id = macro_uuid::generate_uuid_v7();++ let row = sqlx::query_as!(+ ReminderRow,+ r#"+ INSERT INTO reminder (+ id, user_id, description, entity_type, entity_id,+ remind_at, cron, timezone, next_run_at+ )+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)+ RETURNING+ id,+ description,+ entity_type,+ entity_id,+ remind_at,+ cron,+ timezone,+ next_run_at,+ enabled,+ completed_at,+ created_at,+ updated_at+ "#,+ id,+ user_id.as_ref(),+ new.description,+ entity_type,+ entity_id,+ remind_at,+ cron,+ timezone,+ new.next_run_at,+ )+ .fetch_one(&self.pool)+ .await?;++ row.into_reminder()+ }++ #[tracing::instrument(err, skip(self, user_id))]+ async fn get_reminder(+ &self,+ user_id: &MacroUserIdStr<'_>,+ id: Uuid,+ ) -> Result<Option<Reminder>, Self::Err> {+ let row = sqlx::query_as!(+ ReminderRow,+ r#"+ SELECT+ id,+ description,+ entity_type,+ entity_id,+ remind_at,+ cron,+ timezone,+ next_run_at,+ enabled,+ completed_at,+ created_at,+ updated_at+ FROM reminder+ WHERE id = $1 AND user_id = $2+ "#,+ id,+ user_id.as_ref(),+ )+ .fetch_optional(&self.pool)+ .await?;++ row.map(ReminderRow::into_reminder).transpose()+ }++ #[tracing::instrument(err, skip(self, user_id))]+ async fn list_reminders(+ &self,+ user_id: &MacroUserIdStr<'_>,+ filter: &ReminderFilter,+ limit: i64,+ ) -> Result<ReminderBatch, Self::Err> {+ let entity_type: Option<&str> = filter+ .entity+ .as_ref()+ .map(|entity| entity.entity_type.into());+ let entity_id = entity_uuid(filter.entity.as_ref())?;+ let (cursor_next_run_at, cursor_created_at, cursor_id) = match filter.cursor {+ Some(cursor) => (+ Some(cursor.next_run_at),+ Some(cursor.created_at),+ Some(cursor.id),+ ),+ None => (None, None, None),+ };++ let rows = sqlx::query_as!(+ ReminderRow,+ r#"+ SELECT+ id,+ description,+ entity_type,+ entity_id,+ remind_at,+ cron,+ timezone,+ next_run_at,+ enabled,+ completed_at,+ created_at,+ updated_at+ FROM reminder+ WHERE user_id = $1+ AND ($2::text IS NULL OR entity_type = $2)+ AND ($3::uuid IS NULL OR entity_id = $3)+ AND ($4::bool OR completed_at IS NULL)+ -- Keyset: resume strictly after the cursor position in the same+ -- (next_run_at, created_at, id) order the query returns.+ AND (+ $5::timestamptz IS NULL+ OR (next_run_at, created_at, id) > ($5::timestamptz, $6::timestamptz, $7::uuid)+ )+ ORDER BY next_run_at ASC, created_at ASC, id ASC+ LIMIT $8+ "#,+ user_id.as_ref(),+ entity_type,+ entity_id,+ filter.include_completed,+ cursor_next_run_at,+ cursor_created_at,+ cursor_id,+ limit,+ )+ .fetch_all(&self.pool)+ .await?;++ // A row whose stored entity_type or cron no longer parses is skipped+ // rather than failing the page: one unreadable row should not make the+ // caller's whole list unavailable. Single-reminder reads still error.+ //+ // Skipped rows are counted and the last position read is reported, so+ // the domain can still tell whether more rows exist and can advance the+ // cursor past them.+ let last_examined = rows.last().map(ReminderRow::position);+ let mut batch = ReminderBatch {+ reminders: Vec::with_capacity(rows.len()),+ skipped: 0,+ last_examined,+ };+ for row in rows {+ match row.into_reminder() {+ Ok(reminder) => batch.reminders.push(reminder),+ Err(e) => {+ tracing::error!(error=?e, "skipping unreadable reminder");+ batch.skipped += 1;+ }+ }+ }++ Ok(batch)+ }++ #[tracing::instrument(err, skip(self, user_id, update))]+ async fn update_reminder(+ &self,+ user_id: &MacroUserIdStr<'_>,+ id: Uuid,+ update: &ReminderUpdate,+ ) -> Result<Option<Reminder>, Self::Err> {+ // The schedule columns are rewritten as a set, so switching modes can+ // NULL the columns the other mode uses — which `COALESCE` cannot do.+ // Rescheduling also clears `completed_at`: a reminder given a new future+ // firing is live again, and leaving the stamp set would hide it from+ // list results and from the dispatcher's due query.+ let schedule_provided = update.schedule.is_some();+ let (remind_at, cron, timezone) = update+ .schedule+ .as_ref()+ .map(|schedule| schedule_columns(&schedule.schedule))+ .unwrap_or((None, None, None));+ let next_run_at = update+ .schedule+ .as_ref()+ .map(|schedule| schedule.next_run_at);++ let row = sqlx::query_as!(+ ReminderRow,+ r#"+ UPDATE reminder+ SET description = COALESCE($3::text, description),+ remind_at = CASE WHEN $4::bool THEN $5::timestamptz ELSE remind_at END,+ cron = CASE WHEN $4::bool THEN $6::text ELSE cron END,+ timezone = CASE WHEN $4::bool THEN $7::text ELSE timezone END,+ next_run_at = COALESCE($8::timestamptz, next_run_at),+ enabled = COALESCE($9::bool, enabled),+ completed_at = CASE WHEN $4::bool THEN NULL ELSE completed_at END,+ updated_at = now()+ WHERE id = $1 AND user_id = $2+ RETURNING+ id,+ description,+ entity_type,+ entity_id,+ remind_at,+ cron,+ timezone,+ next_run_at,+ enabled,+ completed_at,+ created_at,+ updated_at+ "#,+ id,+ user_id.as_ref(),+ update.description,+ schedule_provided,+ remind_at,+ cron,+ timezone,+ next_run_at,+ update.enabled,+ )+ .fetch_optional(&self.pool)+ .await?;++ row.map(ReminderRow::into_reminder).transpose()+ }++ #[tracing::instrument(err, skip(self, user_id))]+ async fn delete_reminder(+ &self,+ user_id: &MacroUserIdStr<'_>,+ id: Uuid,+ ) -> Result<bool, Self::Err> {+ let result = sqlx::query!(+ r#"DELETE FROM reminder WHERE id = $1 AND user_id = $2"#,+ id,+ user_id.as_ref(),+ )+ .execute(&self.pool)+ .await?;++ Ok(result.rows_affected() > 0)+ }+}++impl ReminderDispatchRepo for PgRemindersRepo {+ type Err = RemindersRepoErr;++ #[tracing::instrument(err, skip(self))]+ async fn due_firings(&self, now: DateTime<Utc>) -> Result<Vec<DueFiring>, Self::Err> {+ // Driven by `reminder_due_idx`: (next_run_at) WHERE enabled AND+ // completed_at IS NULL, with recurring rows filtered out on top.+ //+ // Recurring reminders are excluded here as well as at delivery because+ // one is never completed and never has its next_run_at advanced, so it+ // stays due forever — every sweep would re-fan the same rows and pay+ // for a message each, indefinitely.+ //+ // Unbounded on purpose: a sweep publishes ids, so the cost of a large+ // one is a batch send per ten rows, and the ceiling is the queue's+ // visibility timeout rather than a row count. Should a sweep ever+ // outgrow that, page it with a keyset cursor on (next_run_at, id) and+ // have the handler re-enqueue itself, the way the crm cleanup lister+ // does — a bare LIMIT here would silently strand the overflow.+ let rows = sqlx::query!(+ r#"+ SELECT id, next_run_at+ FROM reminder+ WHERE enabled+ AND completed_at IS NULL+ AND cron IS NULL+ AND next_run_at <= $1+ ORDER BY next_run_at+ "#,+ now,+ )+ .fetch_all(&self.pool)+ .await?;++ Ok(rows+ .into_iter()+ .map(|row| DueFiring {+ reminder_id: row.id,+ scheduled_for: row.next_run_at,+ })+ .collect())+ }++ #[tracing::instrument(err, skip(self))]+ async fn find_due_reminder(&self, firing: DueFiring) -> Result<Option<DueReminder>, Self::Err> {+ // Matching `next_run_at` exactly is what makes a stale message safe: an+ // edit moves the firing, and this then finds nothing rather than+ // delivering the reminder at a time the user cancelled.+ //+ // `cron IS NULL` is deliberately absent — the domain refuses recurring+ // reminders itself so the gap stays visible there.+ let row = sqlx::query_as!(+ DueReminderRow,+ r#"+ SELECT+ id,+ user_id,+ description,+ entity_type,+ entity_id,+ remind_at,+ cron,+ timezone,+ next_run_at,+ enabled,+ completed_at,+ created_at,+ updated_at+ FROM reminder+ WHERE id = $1+ AND next_run_at = $2+ AND enabled+ AND completed_at IS NULL+ "#,+ firing.reminder_id,+ firing.scheduled_for,+ )+ .fetch_optional(&self.pool)+ .await?;++ row.map(DueReminderRow::into_due).transpose()+ }++ #[tracing::instrument(err, skip(self))]+ async fn claim_occurrence(+ &self,+ reminder_id: Uuid,+ scheduled_for: DateTime<Utc>,+ retry_before: DateTime<Utc>,+ ) -> Result<bool, Self::Err> {+ let id = macro_uuid::generate_uuid_v7();++ // One statement covers both a first claim and a retry. The unique index+ // on (reminder_id, scheduled_for) makes the insert the claim; the+ // conflict branch takes over a claim that was made before+ // `retry_before` and never delivered, so a dispatcher that died+ // mid-flight does not strand the firing. A claim that is either already+ // sent or still fresh matches neither and returns no row.+ let claimed = sqlx::query_scalar!(+ r#"+ INSERT INTO reminder_occurrence (id, reminder_id, scheduled_for)+ VALUES ($1, $2, $3)+ ON CONFLICT (reminder_id, scheduled_for) DO UPDATE+ SET created_at = now()+ WHERE reminder_occurrence.sent_at IS NULL+ AND reminder_occurrence.created_at < $4+ RETURNING id+ "#,+ id,+ reminder_id,+ scheduled_for,+ retry_before,+ )+ .fetch_optional(&self.pool)+ .await?;++ Ok(claimed.is_some())+ }++ #[tracing::instrument(err, skip(self))]+ async fn release_occurrence(+ &self,+ reminder_id: Uuid,+ scheduled_for: DateTime<Utc>,+ ) -> Result<(), Self::Err> {+ // `sent_at IS NULL` guards against releasing a firing that did go out:+ // completion and release can only race if the same firing is being+ // handled twice, and the delivered one must win.+ sqlx::query!(+ r#"+ DELETE FROM reminder_occurrence+ WHERE reminder_id = $1+ AND scheduled_for = $2+ AND sent_at IS NULL+ "#,+ reminder_id,+ scheduled_for,+ )+ .execute(&self.pool)+ .await?;++ Ok(())+ }++ #[tracing::instrument(err, skip(self))]+ async fn complete_occurrence(+ &self,+ reminder_id: Uuid,+ scheduled_for: DateTime<Utc>,+ ) -> Result<(), Self::Err> {+ // Both halves in one transaction: a delivered firing whose reminder is+ // still uncompleted would be sent again on the next sweep.+ let mut tx = self.pool.begin().await?;++ sqlx::query!(+ r#"+ UPDATE reminder_occurrence+ SET sent_at = now()+ WHERE reminder_id = $1 AND scheduled_for = $2+ "#,+ reminder_id,+ scheduled_for,+ )+ .execute(&mut *tx)+ .await?;++ sqlx::query!(+ r#"+ UPDATE reminder+ SET completed_at = now(), updated_at = now()+ WHERE id = $1+ "#,+ reminder_id,+ )+ .execute(&mut *tx)+ .await?;++ tx.commit().await?;++ Ok(())+ }+}diff --git a/crates/reminders/src/outbound/pg_reminders_repo/test.rs b/crates/reminders/src/outbound/pg_reminders_repo/test.rsnew file mode 100644index 0000000000..dbc7da44fb--- /dev/null+++ b/crates/reminders/src/outbound/pg_reminders_repo/test.rs@@ -0,0 +1,1395 @@+use chrono::{Duration, TimeZone};+use chrono_tz::America::New_York;+use macro_db_migrator::MACRO_DB_MIGRATIONS;+use macro_user_id::user_id::MacroUserIdStr;+use model_entity::EntityType;+use sqlx::PgPool;++use super::*;+use crate::domain::models::{ReminderCursor, ScheduleUpdate};++const USER_A: &str = "macro|[email protected]";+const USER_B: &str = "macro|[email protected]";+const DAILY_9AM: &str = "0 0 9 * * *";+// `reminder.entity_id` is a uuid column, so associations use uuids.+const DOC_1: &str = "11111111-1111-4111-8111-111111111111";+const DOC_2: &str = "22222222-2222-4222-8222-222222222222";++fn user(id: &str) -> MacroUserIdStr<'_> {+ MacroUserIdStr::parse_from_str(id).expect("valid user id")+}++fn at(y: i32, m: u32, d: u32, h: u32) -> DateTime<Utc> {+ Utc.with_ymd_and_hms(y, m, d, h, 0, 0)+ .single()+ .expect("unambiguous instant")+}++fn once_at(remind_at: DateTime<Utc>) -> ReminderSchedule {+ ReminderSchedule::Once { remind_at }+}++fn recurring() -> ReminderSchedule {+ ReminderSchedule::Recurring {+ cron: ReminderCron::parse(DAILY_9AM).expect("valid cron"),+ timezone: New_York,+ }+}++fn new_reminder(description: &str, schedule: ReminderSchedule) -> NewReminder {+ let next_run_at = schedule+ .next_run_after(at(2026, 1, 1, 0))+ .expect("test schedules always have an upcoming firing");+ NewReminder {+ description: description.to_string(),+ entity: None,+ schedule,+ next_run_at,+ }+}++async fn insert_user(pool: &PgPool, id: &str) {+ let macro_user_id = macro_uuid::generate_uuid_v7();+ sqlx::query(+ r#"INSERT INTO macro_user (id, username, email, stripe_customer_id) VALUES ($1, $2, $2, $2)"#,+ )+ .bind(macro_user_id)+ .bind(id)+ .execute(pool)+ .await+ .expect("macro_user should insert");+ sqlx::query(r#"INSERT INTO "User" (id, email, macro_user_id) VALUES ($1, $1, $2)"#)+ .bind(id)+ .bind(macro_user_id)+ .execute(pool)+ .await+ .expect("user should insert");+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn one_shot_reminder_round_trips(pool: PgPool) {+ insert_user(&pool, USER_A).await;+ let repo = PgRemindersRepo::new(pool);+ let remind_at = at(2026, 8, 1, 14);++ let created = repo+ .create_reminder(+ &user(USER_A),+ &new_reminder("call back", once_at(remind_at)),+ )+ .await+ .expect("reminder should insert");++ assert_eq!(created.description, "call back");+ assert_eq!(created.schedule, once_at(remind_at));+ assert_eq!(created.next_run_at, remind_at);+ assert!(created.enabled);+ assert!(created.completed_at.is_none());+ assert!(created.entity().is_none());++ let fetched = repo+ .get_reminder(&user(USER_A), created.id)+ .await+ .expect("get should succeed")+ .expect("reminder should exist");+ assert_eq!(fetched.id, created.id);+ assert_eq!(fetched.schedule, created.schedule);+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn recurring_reminder_round_trips_with_its_timezone(pool: PgPool) {+ insert_user(&pool, USER_A).await;+ let repo = PgRemindersRepo::new(pool);++ let created = repo+ .create_reminder(&user(USER_A), &new_reminder("standup", recurring()))+ .await+ .expect("reminder should insert");++ let fetched = repo+ .get_reminder(&user(USER_A), created.id)+ .await+ .expect("get should succeed")+ .expect("reminder should exist");++ match fetched.schedule {+ ReminderSchedule::Recurring { cron, timezone } => {+ assert_eq!(cron.as_str(), DAILY_9AM);+ assert_eq!(timezone, New_York);+ }+ other => panic!("expected a recurring schedule, got {other:?}"),+ }+ // 09:00 New York on Jan 1 is 14:00Z.+ assert_eq!(fetched.next_run_at, at(2026, 1, 1, 14));+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn entity_association_round_trips(pool: PgPool) {+ insert_user(&pool, USER_A).await;+ let repo = PgRemindersRepo::new(pool);+ let new = NewReminder {+ entity: Some(EntityType::Document.with_entity_string(DOC_1.to_string())),+ ..new_reminder("review this", once_at(at(2026, 8, 1, 14)))+ };++ let created = repo+ .create_reminder(&user(USER_A), &new)+ .await+ .expect("reminder should insert");++ let entity = created.entity().expect("entity should be persisted");+ assert_eq!(entity.entity_type, EntityType::Document);+ assert_eq!(entity.entity_id, DOC_1);+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn list_returns_only_the_owners_reminders_soonest_first(pool: PgPool) {+ insert_user(&pool, USER_A).await;+ insert_user(&pool, USER_B).await;+ let repo = PgRemindersRepo::new(pool);++ let later = at(2026, 9, 1, 14);+ let soon = at(2026, 8, 1, 14);+ repo.create_reminder(&user(USER_A), &new_reminder("later", once_at(later)))+ .await+ .expect("insert");+ repo.create_reminder(&user(USER_A), &new_reminder("soon", once_at(soon)))+ .await+ .expect("insert");+ repo.create_reminder(&user(USER_B), &new_reminder("theirs", once_at(soon)))+ .await+ .expect("insert");++ let batch = repo+ .list_reminders(&user(USER_A), &ReminderFilter::default(), 100)+ .await+ .expect("list should succeed");++ assert_eq!(batch.reminders.len(), 2);+ assert_eq!(batch.skipped, 0);+ assert_eq!(batch.reminders[0].description, "soon");+ assert_eq!(batch.reminders[1].description, "later");+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn list_filters_by_entity(pool: PgPool) {+ insert_user(&pool, USER_A).await;+ let repo = PgRemindersRepo::new(pool);++ let attached = NewReminder {+ entity: Some(EntityType::Document.with_entity_string(DOC_1.to_string())),+ ..new_reminder("on doc-1", once_at(at(2026, 8, 1, 14)))+ };+ let other = NewReminder {+ entity: Some(EntityType::Document.with_entity_string(DOC_2.to_string())),+ ..new_reminder("on doc-2", once_at(at(2026, 8, 1, 14)))+ };+ repo.create_reminder(&user(USER_A), &attached)+ .await+ .expect("insert");+ repo.create_reminder(&user(USER_A), &other)+ .await+ .expect("insert");+ repo.create_reminder(+ &user(USER_A),+ &new_reminder("standalone", once_at(at(2026, 8, 1, 14))),+ )+ .await+ .expect("insert");++ let filter = ReminderFilter {+ entity: Some(EntityType::Document.with_entity_string(DOC_1.to_string())),+ ..Default::default()+ };+ let batch = repo+ .list_reminders(&user(USER_A), &filter, 100)+ .await+ .expect("list should succeed");++ assert_eq!(batch.reminders.len(), 1);+ assert_eq!(batch.reminders[0].description, "on doc-1");+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn list_hides_completed_reminders_unless_requested(pool: PgPool) {+ insert_user(&pool, USER_A).await;+ let repo = PgRemindersRepo::new(pool.clone());+ let created = repo+ .create_reminder(+ &user(USER_A),+ &new_reminder("fired already", once_at(at(2026, 8, 1, 14))),+ )+ .await+ .expect("insert");++ // Stand in for the dispatcher completing the one-shot.+ sqlx::query(r#"UPDATE reminder SET completed_at = now() WHERE id = $1"#)+ .bind(created.id)+ .execute(&pool)+ .await+ .expect("complete should update");++ let hidden = repo+ .list_reminders(&user(USER_A), &ReminderFilter::default(), 100)+ .await+ .expect("list should succeed");+ assert!(hidden.reminders.is_empty());++ let shown = repo+ .list_reminders(+ &user(USER_A),+ &ReminderFilter {+ include_completed: true,+ ..Default::default()+ },+ 100,+ )+ .await+ .expect("list should succeed");+ assert_eq!(shown.reminders.len(), 1);+ assert!(shown.reminders[0].completed_at.is_some());+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn update_applies_only_the_provided_fields(pool: PgPool) {+ insert_user(&pool, USER_A).await;+ let repo = PgRemindersRepo::new(pool);+ let remind_at = at(2026, 8, 1, 14);+ let created = repo+ .create_reminder(&user(USER_A), &new_reminder("before", once_at(remind_at)))+ .await+ .expect("insert");++ let updated = repo+ .update_reminder(+ &user(USER_A),+ created.id,+ &ReminderUpdate {+ description: Some("after".to_string()),+ enabled: Some(false),+ ..Default::default()+ },+ )+ .await+ .expect("update should succeed")+ .expect("reminder should exist");++ assert_eq!(updated.description, "after");+ assert!(!updated.enabled);+ // Schedule untouched.+ assert_eq!(updated.schedule, once_at(remind_at));+ assert_eq!(updated.next_run_at, remind_at);+ assert!(updated.updated_at >= created.updated_at);+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn update_switching_to_recurring_clears_remind_at(pool: PgPool) {+ insert_user(&pool, USER_A).await;+ let repo = PgRemindersRepo::new(pool);+ let created = repo+ .create_reminder(+ &user(USER_A),+ &new_reminder("one shot", once_at(at(2026, 8, 1, 14))),+ )+ .await+ .expect("insert");++ let next_run_at = at(2026, 1, 1, 14);+ let updated = repo+ .update_reminder(+ &user(USER_A),+ created.id,+ &ReminderUpdate {+ schedule: Some(ScheduleUpdate {+ schedule: recurring(),+ next_run_at,+ }),+ ..Default::default()+ },+ )+ .await+ .expect("update should succeed")+ .expect("reminder should exist");++ assert!(updated.schedule.repeats());+ assert_eq!(updated.next_run_at, next_run_at);+ // Reading it back proves `remind_at` was NULLed: otherwise the row would+ // violate the schedule CHECK, and the mapper would still report `Once`.+ let fetched = repo+ .get_reminder(&user(USER_A), created.id)+ .await+ .expect("get should succeed")+ .expect("reminder should exist");+ assert!(fetched.schedule.repeats());+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn update_switching_to_one_shot_clears_cron_and_timezone(pool: PgPool) {+ insert_user(&pool, USER_A).await;+ let repo = PgRemindersRepo::new(pool);+ let created = repo+ .create_reminder(&user(USER_A), &new_reminder("standup", recurring()))+ .await+ .expect("insert");++ let remind_at = at(2026, 8, 1, 14);+ repo.update_reminder(+ &user(USER_A),+ created.id,+ &ReminderUpdate {+ schedule: Some(ScheduleUpdate {+ schedule: once_at(remind_at),+ next_run_at: remind_at,+ }),+ ..Default::default()+ },+ )+ .await+ .expect("update should succeed")+ .expect("reminder should exist");++ let fetched = repo+ .get_reminder(&user(USER_A), created.id)+ .await+ .expect("get should succeed")+ .expect("reminder should exist");+ assert_eq!(fetched.schedule, once_at(remind_at));+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn reminders_are_scoped_to_their_owner(pool: PgPool) {+ insert_user(&pool, USER_A).await;+ insert_user(&pool, USER_B).await;+ let repo = PgRemindersRepo::new(pool);+ let created = repo+ .create_reminder(+ &user(USER_A),+ &new_reminder("private", once_at(at(2026, 8, 1, 14))),+ )+ .await+ .expect("insert");++ assert!(+ repo.get_reminder(&user(USER_B), created.id)+ .await+ .expect("get should succeed")+ .is_none()+ );+ assert!(+ repo.update_reminder(+ &user(USER_B),+ created.id,+ &ReminderUpdate {+ enabled: Some(false),+ ..Default::default()+ },+ )+ .await+ .expect("update should succeed")+ .is_none()+ );+ assert!(+ !repo+ .delete_reminder(&user(USER_B), created.id)+ .await+ .expect("delete should succeed")+ );+ // Still there, still enabled.+ let survived = repo+ .get_reminder(&user(USER_A), created.id)+ .await+ .expect("get should succeed")+ .expect("reminder should exist");+ assert!(survived.enabled);+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn delete_removes_the_row_once(pool: PgPool) {+ insert_user(&pool, USER_A).await;+ let repo = PgRemindersRepo::new(pool);+ let created = repo+ .create_reminder(+ &user(USER_A),+ &new_reminder("transient", once_at(at(2026, 8, 1, 14))),+ )+ .await+ .expect("insert");++ assert!(+ repo.delete_reminder(&user(USER_A), created.id)+ .await+ .expect("delete should succeed")+ );+ assert!(+ !repo+ .delete_reminder(&user(USER_A), created.id)+ .await+ .expect("second delete should succeed")+ );+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn deleting_the_user_cascades_to_their_reminders(pool: PgPool) {+ insert_user(&pool, USER_A).await;+ let repo = PgRemindersRepo::new(pool.clone());+ repo.create_reminder(+ &user(USER_A),+ &new_reminder("goes away", once_at(at(2026, 8, 1, 14))),+ )+ .await+ .expect("insert");++ sqlx::query(r#"DELETE FROM "User" WHERE id = $1"#)+ .bind(USER_A)+ .execute(&pool)+ .await+ .expect("user delete should succeed");++ let remaining: i64 = sqlx::query_scalar(r#"SELECT COUNT(*) FROM reminder"#)+ .fetch_one(&pool)+ .await+ .expect("count should succeed");+ assert_eq!(remaining, 0);+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn a_half_populated_entity_association_is_rejected(pool: PgPool) {+ insert_user(&pool, USER_A).await;++ let err = sqlx::query(+ r#"+ INSERT INTO reminder (id, user_id, description, entity_type, next_run_at, remind_at)+ VALUES ($1, $2, 'dangling', 'document', now(), now())+ "#,+ )+ .bind(macro_uuid::generate_uuid_v7())+ .bind(USER_A)+ .execute(&pool)+ .await+ .expect_err("entity_type without entity_id should violate the CHECK");++ assert!(+ err.to_string().contains("reminder_entity_both_or_neither"),+ "unexpected error: {err}"+ );+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn both_schedule_modes_at_once_is_rejected(pool: PgPool) {+ insert_user(&pool, USER_A).await;++ let err = sqlx::query(+ r#"+ INSERT INTO reminder (id, user_id, description, next_run_at, remind_at, cron, timezone)+ VALUES ($1, $2, 'confused', now(), now(), '0 0 9 * * *', 'America/New_York')+ "#,+ )+ .bind(macro_uuid::generate_uuid_v7())+ .bind(USER_A)+ .execute(&pool)+ .await+ .expect_err("two schedule modes should violate the CHECK");++ assert!(+ err.to_string().contains("reminder_schedule_exactly_one"),+ "unexpected error: {err}"+ );+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn a_cron_without_a_timezone_is_rejected(pool: PgPool) {+ insert_user(&pool, USER_A).await;++ let err = sqlx::query(+ r#"+ INSERT INTO reminder (id, user_id, description, next_run_at, cron)+ VALUES ($1, $2, 'no zone', now(), '0 0 9 * * *')+ "#,+ )+ .bind(macro_uuid::generate_uuid_v7())+ .bind(USER_A)+ .execute(&pool)+ .await+ .expect_err("a cron without a timezone should violate the CHECK");++ assert!(+ err.to_string().contains("reminder_schedule_exactly_one"),+ "unexpected error: {err}"+ );+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn no_schedule_at_all_is_rejected(pool: PgPool) {+ insert_user(&pool, USER_A).await;++ let err = sqlx::query(+ r#"+ INSERT INTO reminder (id, user_id, description, next_run_at)+ VALUES ($1, $2, 'scheduleless', now())+ "#,+ )+ .bind(macro_uuid::generate_uuid_v7())+ .bind(USER_A)+ .execute(&pool)+ .await+ .expect_err("a reminder with no schedule should violate the CHECK");++ assert!(+ err.to_string().contains("reminder_schedule_exactly_one"),+ "unexpected error: {err}"+ );+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn occurrences_cascade_when_their_reminder_is_deleted(pool: PgPool) {+ insert_user(&pool, USER_A).await;+ let repo = PgRemindersRepo::new(pool.clone());+ let created = repo+ .create_reminder(&user(USER_A), &new_reminder("standup", recurring()))+ .await+ .expect("insert");++ // The dispatcher does not exist yet; write the row it would write.+ sqlx::query(+ r#"INSERT INTO reminder_occurrence (id, reminder_id, scheduled_for, sent_at)+ VALUES ($1, $2, $3, now())"#,+ )+ .bind(macro_uuid::generate_uuid_v7())+ .bind(created.id)+ .bind(created.next_run_at)+ .execute(&pool)+ .await+ .expect("occurrence should insert");++ // The same firing cannot be recorded twice.+ let duplicate = sqlx::query(+ r#"INSERT INTO reminder_occurrence (id, reminder_id, scheduled_for) VALUES ($1, $2, $3)"#,+ )+ .bind(macro_uuid::generate_uuid_v7())+ .bind(created.id)+ .bind(created.next_run_at)+ .execute(&pool)+ .await;+ assert!(duplicate.is_err(), "duplicate firing should be rejected");++ repo.delete_reminder(&user(USER_A), created.id)+ .await+ .expect("delete should succeed");++ let remaining: i64 = sqlx::query_scalar(r#"SELECT COUNT(*) FROM reminder_occurrence"#)+ .fetch_one(&pool)+ .await+ .expect("count should succeed");+ assert_eq!(remaining, 0);+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn a_stored_timezone_that_is_not_a_zone_surfaces_as_an_error(pool: PgPool) {+ insert_user(&pool, USER_A).await;+ let repo = PgRemindersRepo::new(pool.clone());+ let created = repo+ .create_reminder(&user(USER_A), &new_reminder("standup", recurring()))+ .await+ .expect("insert");++ sqlx::query(r#"UPDATE reminder SET timezone = 'Mars/Olympus_Mons' WHERE id = $1"#)+ .bind(created.id)+ .execute(&pool)+ .await+ .expect("update should succeed");++ let err = repo+ .get_reminder(&user(USER_A), created.id)+ .await+ .expect_err("an unknown zone should not silently become UTC");+ assert!(matches!(err, RemindersRepoErr::InvalidTimezone(_, _)));+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn next_run_at_is_indexed_for_the_future_dispatcher(pool: PgPool) {+ insert_user(&pool, USER_A).await;+ let repo = PgRemindersRepo::new(pool.clone());+ repo.create_reminder(&user(USER_A), &new_reminder("due", recurring()))+ .await+ .expect("insert");++ // The dispatcher's query shape, so a schema change that breaks it fails here.+ let due: i64 = sqlx::query_scalar(+ r#"+ SELECT COUNT(*) FROM reminder+ WHERE enabled AND completed_at IS NULL AND next_run_at <= $1+ "#,+ )+ .bind(at(2026, 1, 1, 14) + Duration::seconds(1))+ .fetch_one(&pool)+ .await+ .expect("count should succeed");+ assert_eq!(due, 1);+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn rescheduling_clears_completed_at(pool: PgPool) {+ insert_user(&pool, USER_A).await;+ let repo = PgRemindersRepo::new(pool.clone());+ let created = repo+ .create_reminder(+ &user(USER_A),+ &new_reminder("fired", once_at(at(2026, 8, 1, 14))),+ )+ .await+ .expect("insert");++ sqlx::query(r#"UPDATE reminder SET completed_at = now() WHERE id = $1"#)+ .bind(created.id)+ .execute(&pool)+ .await+ .expect("complete should update");++ let remind_at = at(2026, 9, 1, 14);+ let revived = repo+ .update_reminder(+ &user(USER_A),+ created.id,+ &ReminderUpdate {+ schedule: Some(ScheduleUpdate {+ schedule: once_at(remind_at),+ next_run_at: remind_at,+ }),+ ..Default::default()+ },+ )+ .await+ .expect("update should succeed")+ .expect("reminder should exist");++ assert!(+ revived.completed_at.is_none(),+ "a rescheduled reminder must not stay marked completed"+ );+ // ...so it is back in the default list and in the dispatcher's due query.+ let listed = repo+ .list_reminders(&user(USER_A), &ReminderFilter::default(), 100)+ .await+ .expect("list should succeed");+ assert_eq!(listed.reminders.len(), 1);+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn a_non_schedule_update_leaves_completed_at_alone(pool: PgPool) {+ insert_user(&pool, USER_A).await;+ let repo = PgRemindersRepo::new(pool.clone());+ let created = repo+ .create_reminder(+ &user(USER_A),+ &new_reminder("fired", once_at(at(2026, 8, 1, 14))),+ )+ .await+ .expect("insert");++ sqlx::query(r#"UPDATE reminder SET completed_at = now() WHERE id = $1"#)+ .bind(created.id)+ .execute(&pool)+ .await+ .expect("complete should update");++ let updated = repo+ .update_reminder(+ &user(USER_A),+ created.id,+ &ReminderUpdate {+ description: Some("renamed".to_string()),+ ..Default::default()+ },+ )+ .await+ .expect("update should succeed")+ .expect("reminder should exist");++ assert_eq!(updated.description, "renamed");+ assert!(updated.completed_at.is_some());+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn keyset_paging_walks_every_row_exactly_once(pool: PgPool) {+ insert_user(&pool, USER_A).await;+ let repo = PgRemindersRepo::new(pool);+ // Identical firing times, so paging depends entirely on the created_at/id+ // tie-breakers in both the ORDER BY and the keyset predicate.+ let remind_at = at(2026, 8, 1, 14);+ for index in 0..5 {+ repo.create_reminder(+ &user(USER_A),+ &new_reminder(&format!("reminder-{index}"), once_at(remind_at)),+ )+ .await+ .expect("insert");+ }++ let mut seen = Vec::new();+ let mut cursor = None;+ for _ in 0..5 {+ let page = repo+ .list_reminders(+ &user(USER_A),+ &ReminderFilter {+ cursor,+ ..Default::default()+ },+ 2,+ )+ .await+ .expect("list should succeed");+ if page.reminders.is_empty() {+ break;+ }+ assert!(page.reminders.len() <= 2);+ cursor = page.last_examined;+ seen.extend(page.reminders.into_iter().map(|reminder| reminder.id));+ }++ assert_eq!(seen.len(), 5, "every row is returned");+ let unique: std::collections::HashSet<_> = seen.iter().collect();+ assert_eq!(unique.len(), 5, "no row is returned twice");+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn a_cursor_past_the_end_returns_nothing(pool: PgPool) {+ insert_user(&pool, USER_A).await;+ let repo = PgRemindersRepo::new(pool);+ let created = repo+ .create_reminder(+ &user(USER_A),+ &new_reminder("only", once_at(at(2026, 8, 1, 14))),+ )+ .await+ .expect("insert");++ let page = repo+ .list_reminders(+ &user(USER_A),+ &ReminderFilter {+ cursor: Some(ReminderCursor::after(&created)),+ ..Default::default()+ },+ 100,+ )+ .await+ .expect("list should succeed");++ assert!(page.reminders.is_empty());+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn limit_bounds_the_result_set(pool: PgPool) {+ insert_user(&pool, USER_A).await;+ let repo = PgRemindersRepo::new(pool);+ for index in 0..4 {+ repo.create_reminder(+ &user(USER_A),+ &new_reminder(&format!("r{index}"), once_at(at(2026, 8, 1, 14))),+ )+ .await+ .expect("insert");+ }++ let page = repo+ .list_reminders(&user(USER_A), &ReminderFilter::default(), 2)+ .await+ .expect("list should succeed");+ assert_eq!(page.reminders.len(), 2);+ assert_eq!(page.examined(), 2);+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn an_unreadable_row_is_skipped_rather_than_failing_the_page(pool: PgPool) {+ insert_user(&pool, USER_A).await;+ let repo = PgRemindersRepo::new(pool.clone());+ let broken = repo+ .create_reminder(+ &user(USER_A),+ &NewReminder {+ entity: Some(EntityType::Document.with_entity_string(DOC_1.to_string())),+ ..new_reminder("has a bad entity type", once_at(at(2026, 8, 1, 14)))+ },+ )+ .await+ .expect("insert");+ repo.create_reminder(+ &user(USER_A),+ &new_reminder("fine", once_at(at(2026, 8, 2, 14))),+ )+ .await+ .expect("insert");++ // Only reachable by writing around the service; the CHECK constraints allow+ // it because the value is non-empty text.+ sqlx::query(r#"UPDATE reminder SET entity_type = 'chupacabra' WHERE id = $1"#)+ .bind(broken.id)+ .execute(&pool)+ .await+ .expect("update should succeed");++ let listed = repo+ .list_reminders(&user(USER_A), &ReminderFilter::default(), 100)+ .await+ .expect("one unreadable row must not fail the whole page");+ assert_eq!(listed.reminders.len(), 1);+ assert_eq!(listed.reminders[0].description, "fine");+ // The skipped row is accounted for, and the cursor covers it, so paging+ // cannot stall on it.+ assert_eq!(listed.skipped, 1);+ assert_eq!(listed.examined(), 2);+ assert!(listed.last_examined.is_some());++ // Reading that reminder on its own still surfaces the problem.+ let err = repo+ .get_reminder(&user(USER_A), broken.id)+ .await+ .expect_err("a single-row read should not hide the bad value");+ assert!(matches!(+ err,+ RemindersRepoErr::InvalidEntityType { reminder_id, .. } if reminder_id == broken.id+ ));+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn a_blank_description_is_rejected_by_the_database(pool: PgPool) {+ insert_user(&pool, USER_A).await;++ let err = sqlx::query(+ r#"INSERT INTO reminder (id, user_id, description, next_run_at, remind_at)+ VALUES ($1, $2, ' ', now(), now())"#,+ )+ .bind(macro_uuid::generate_uuid_v7())+ .bind(USER_A)+ .execute(&pool)+ .await+ .expect_err("a whitespace-only description should violate the CHECK");++ assert!(+ err.to_string().contains("reminder_description_non_empty"),+ "unexpected error: {err}"+ );+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn an_over_long_description_is_rejected_by_the_database(pool: PgPool) {+ insert_user(&pool, USER_A).await;++ let err = sqlx::query(+ r#"INSERT INTO reminder (id, user_id, description, next_run_at, remind_at)+ VALUES ($1, $2, repeat('a', 2001), now(), now())"#,+ )+ .bind(macro_uuid::generate_uuid_v7())+ .bind(USER_A)+ .execute(&pool)+ .await+ .expect_err("2001 characters should violate the CHECK");++ assert!(+ err.to_string().contains("reminder_description_max_length"),+ "unexpected error: {err}"+ );++ // The service's limit and the DB's agree on where the boundary is.+ sqlx::query(+ r#"INSERT INTO reminder (id, user_id, description, next_run_at, remind_at)+ VALUES ($1, $2, repeat('a', 2000), now(), now())"#,+ )+ .bind(macro_uuid::generate_uuid_v7())+ .bind(USER_A)+ .execute(&pool)+ .await+ .expect("exactly the limit should be accepted");+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn a_non_uuid_entity_id_is_rejected_by_the_database(pool: PgPool) {+ insert_user(&pool, USER_A).await;++ // The column type is the guardrail now that `entity_id` is a uuid: there is+ // no blank or malformed value to check for, the cast simply fails.+ let err = sqlx::query(+ r#"INSERT INTO reminder (id, user_id, description, entity_type, entity_id, next_run_at, remind_at)+ VALUES ($1, $2, 'x', 'document', 'not-a-uuid', now(), now())"#,+ )+ .bind(macro_uuid::generate_uuid_v7())+ .bind(USER_A)+ .execute(&pool)+ .await+ .expect_err("a non-uuid entity id should not be storable");++ assert!(err.to_string().contains("uuid"), "unexpected error: {err}");+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn the_active_list_index_covers_the_default_query(pool: PgPool) {+ insert_user(&pool, USER_A).await;+ let repo = PgRemindersRepo::new(pool.clone());+ repo.create_reminder(+ &user(USER_A),+ &new_reminder("live", once_at(at(2026, 8, 1, 14))),+ )+ .await+ .expect("insert");++ // Pins that the partial index exists and matches the shape the default list+ // query uses; a rename or predicate change fails here.+ let indexed: bool = sqlx::query_scalar(+ r#"+ SELECT EXISTS (+ SELECT 1 FROM pg_indexes+ WHERE tablename = 'reminder'+ AND indexname = 'reminder_user_active_next_run_idx'+ )+ "#,+ )+ .fetch_one(&pool)+ .await+ .expect("index lookup should succeed");+ assert!(indexed, "the active-list partial index is missing");+}++// ---------------------------------------------------------------------------+// Dispatch+// ---------------------------------------------------------------------------++/// A stale threshold far enough in the past that a claim made "now" is fresh,+/// so a second claim in the same test is refused rather than taken over.+fn no_retry() -> DateTime<Utc> {+ at(2000, 1, 1, 0)+}++async fn create_due(pool: &PgPool, user_id: &str, remind_at: DateTime<Utc>) -> Reminder {+ let repo = PgRemindersRepo::new(pool.clone());+ let new = NewReminder {+ description: "Follow up".to_string(),+ entity: None,+ schedule: once_at(remind_at),+ next_run_at: remind_at,+ };+ repo.create_reminder(&user(user_id), &new)+ .await+ .expect("reminder should insert")+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn due_firings_returns_only_firings_that_have_arrived(pool: PgPool) {+ insert_user(&pool, USER_A).await;+ let now = at(2026, 8, 1, 12);+ let past = create_due(&pool, USER_A, at(2026, 8, 1, 11)).await;+ let _future = create_due(&pool, USER_A, at(2026, 8, 1, 13)).await;+ let repo = PgRemindersRepo::new(pool);++ let due = repo.due_firings(now).await.expect("query succeeds");++ assert_eq!(due.len(), 1);+ assert_eq!(due[0].reminder_id, past.id);+ // The firing being delivered is the reminder's next_run_at, which is what+ // keys the occurrence row.+ assert_eq!(due[0].scheduled_for, past.next_run_at);+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn due_firings_exclude_recurring_reminders(pool: PgPool) {+ // A recurring reminder is never completed and never has its next_run_at+ // advanced, so if the query returned it the row would stay due forever and+ // every sweep would pay for a message that delivery then refuses.+ insert_user(&pool, USER_A).await;+ let repo = PgRemindersRepo::new(pool.clone());+ let now = at(2026, 8, 1, 12);++ repo.create_reminder(&user(USER_A), &new_reminder("standup", recurring()))+ .await+ .expect("recurring reminder should insert");+ let one_shot = create_due(&pool, USER_A, at(2026, 8, 1, 11)).await;++ let due = repo.due_firings(now).await.expect("query succeeds");++ assert_eq!(due.len(), 1);+ assert_eq!(due[0].reminder_id, one_shot.id);+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn due_firings_span_users(pool: PgPool) {+ insert_user(&pool, USER_A).await;+ insert_user(&pool, USER_B).await;+ let now = at(2026, 8, 1, 12);+ create_due(&pool, USER_A, at(2026, 8, 1, 11)).await;+ create_due(&pool, USER_B, at(2026, 8, 1, 10)).await;+ let repo = PgRemindersRepo::new(pool);++ let due = repo.due_firings(now).await.expect("query succeeds");++ // Dispatch is the one read that is not scoped to a single caller.+ let mut owners = Vec::new();+ for firing in &due {+ let resolved = repo+ .find_due_reminder(*firing)+ .await+ .expect("read succeeds")+ .expect("firing resolves");+ owners.push(resolved.owner_id.as_ref().to_string());+ }+ assert_eq!(owners, vec![USER_B, USER_A], "soonest firing first");+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn due_firings_skip_disabled_and_completed(pool: PgPool) {+ insert_user(&pool, USER_A).await;+ let now = at(2026, 8, 1, 12);+ let disabled = create_due(&pool, USER_A, at(2026, 8, 1, 11)).await;+ let completed = create_due(&pool, USER_A, at(2026, 8, 1, 11)).await;+ let repo = PgRemindersRepo::new(pool.clone());++ repo.update_reminder(+ &user(USER_A),+ disabled.id,+ &ReminderUpdate {+ enabled: Some(false),+ ..Default::default()+ },+ )+ .await+ .expect("disable succeeds");+ repo.complete_occurrence(completed.id, completed.next_run_at)+ .await+ .expect("complete succeeds");++ let due = repo.due_firings(now).await.expect("query succeeds");++ assert!(due.is_empty());+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn a_fanned_out_firing_resolves_to_its_reminder_and_owner(pool: PgPool) {+ insert_user(&pool, USER_A).await;+ let reminder = create_due(&pool, USER_A, at(2026, 8, 1, 11)).await;+ let repo = PgRemindersRepo::new(pool);++ let due = repo+ .find_due_reminder(DueFiring {+ reminder_id: reminder.id,+ scheduled_for: reminder.next_run_at,+ })+ .await+ .expect("read succeeds")+ .expect("firing resolves");++ assert_eq!(due.reminder.id, reminder.id);+ assert_eq!(due.owner_id.as_ref(), USER_A);+ assert_eq!(due.scheduled_for, reminder.next_run_at);+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn a_rescheduled_reminder_no_longer_resolves_its_old_firing(pool: PgPool) {+ // The window this closes: a reminder edited between fan-out and delivery+ // must not fire at the time its owner moved it away from.+ insert_user(&pool, USER_A).await;+ let reminder = create_due(&pool, USER_A, at(2026, 8, 1, 11)).await;+ let repo = PgRemindersRepo::new(pool);+ let old_firing = DueFiring {+ reminder_id: reminder.id,+ scheduled_for: reminder.next_run_at,+ };++ repo.update_reminder(+ &user(USER_A),+ reminder.id,+ &ReminderUpdate {+ schedule: Some(ScheduleUpdate {+ schedule: once_at(at(2026, 9, 1, 11)),+ next_run_at: at(2026, 9, 1, 11),+ }),+ ..Default::default()+ },+ )+ .await+ .expect("reschedule succeeds");++ let resolved = repo+ .find_due_reminder(old_firing)+ .await+ .expect("read succeeds");++ assert!(resolved.is_none());+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn a_disabled_or_completed_reminder_does_not_resolve_its_firing(pool: PgPool) {+ insert_user(&pool, USER_A).await;+ let disabled = create_due(&pool, USER_A, at(2026, 8, 1, 11)).await;+ let completed = create_due(&pool, USER_A, at(2026, 8, 1, 11)).await;+ let repo = PgRemindersRepo::new(pool);++ repo.update_reminder(+ &user(USER_A),+ disabled.id,+ &ReminderUpdate {+ enabled: Some(false),+ ..Default::default()+ },+ )+ .await+ .expect("disable succeeds");+ repo.complete_occurrence(completed.id, completed.next_run_at)+ .await+ .expect("complete succeeds");++ for reminder in [&disabled, &completed] {+ let resolved = repo+ .find_due_reminder(DueFiring {+ reminder_id: reminder.id,+ scheduled_for: reminder.next_run_at,+ })+ .await+ .expect("read succeeds");+ assert!(resolved.is_none());+ }+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn a_released_claim_can_be_taken_again_immediately(pool: PgPool) {+ // What makes a failed delivery retry on the queue's schedule rather than+ // waiting out the stale-claim window.+ insert_user(&pool, USER_A).await;+ let reminder = create_due(&pool, USER_A, at(2026, 8, 1, 11)).await;+ let repo = PgRemindersRepo::new(pool);++ assert!(+ repo.claim_occurrence(reminder.id, reminder.next_run_at, no_retry())+ .await+ .expect("first claim succeeds")+ );+ repo.release_occurrence(reminder.id, reminder.next_run_at)+ .await+ .expect("release succeeds");++ // `no_retry()` means nothing stale is reclaimable, so this can only succeed+ // because the release actually removed the claim.+ let retaken = repo+ .claim_occurrence(reminder.id, reminder.next_run_at, no_retry())+ .await+ .expect("second claim succeeds");++ assert!(retaken);+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn releasing_a_delivered_firing_does_not_un_send_it(pool: PgPool) {+ insert_user(&pool, USER_A).await;+ let reminder = create_due(&pool, USER_A, at(2026, 8, 1, 11)).await;+ let repo = PgRemindersRepo::new(pool.clone());++ repo.claim_occurrence(reminder.id, reminder.next_run_at, no_retry())+ .await+ .expect("claim succeeds");+ repo.complete_occurrence(reminder.id, reminder.next_run_at)+ .await+ .expect("complete succeeds");+ repo.release_occurrence(reminder.id, reminder.next_run_at)+ .await+ .expect("release succeeds");++ // The sent row survives, so a redelivered message still loses the claim.+ let remaining: i64 =+ sqlx::query_scalar(r#"SELECT count(*) FROM reminder_occurrence WHERE reminder_id = $1"#)+ .bind(reminder.id)+ .fetch_one(&pool)+ .await+ .expect("count succeeds");+ assert_eq!(remaining, 1);++ let reclaimed = repo+ .claim_occurrence(+ reminder.id,+ reminder.next_run_at,+ Utc::now() + Duration::minutes(1),+ )+ .await+ .expect("claim succeeds");+ assert!(!reclaimed);+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn a_firing_can_only_be_claimed_once(pool: PgPool) {+ insert_user(&pool, USER_A).await;+ let reminder = create_due(&pool, USER_A, at(2026, 8, 1, 11)).await;+ let repo = PgRemindersRepo::new(pool);++ let first = repo+ .claim_occurrence(reminder.id, reminder.next_run_at, no_retry())+ .await+ .expect("first claim succeeds");+ let second = repo+ .claim_occurrence(reminder.id, reminder.next_run_at, no_retry())+ .await+ .expect("second claim succeeds");++ assert!(first, "the first dispatcher takes the firing");+ assert!(!second, "a peer must not take a firing already in flight");+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn a_stale_undelivered_claim_can_be_taken_over(pool: PgPool) {+ insert_user(&pool, USER_A).await;+ let reminder = create_due(&pool, USER_A, at(2026, 8, 1, 11)).await;+ let repo = PgRemindersRepo::new(pool);++ assert!(+ repo.claim_occurrence(reminder.id, reminder.next_run_at, no_retry())+ .await+ .expect("first claim succeeds")+ );++ // A dispatcher that claimed and then died leaves sent_at NULL. Once the+ // claim ages past the retry window another sweep must be able to take it.+ let retaken = repo+ .claim_occurrence(+ reminder.id,+ reminder.next_run_at,+ Utc::now() + Duration::minutes(1),+ )+ .await+ .expect("retry claim succeeds");++ assert!(retaken);+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn a_delivered_firing_is_never_reclaimed(pool: PgPool) {+ insert_user(&pool, USER_A).await;+ let reminder = create_due(&pool, USER_A, at(2026, 8, 1, 11)).await;+ let repo = PgRemindersRepo::new(pool);++ repo.claim_occurrence(reminder.id, reminder.next_run_at, no_retry())+ .await+ .expect("claim succeeds");+ repo.complete_occurrence(reminder.id, reminder.next_run_at)+ .await+ .expect("complete succeeds");++ // Even with a retry window wide enough to reclaim anything unsent, a sent+ // firing must stay sent — this is what stops a duplicate notification.+ let reclaimed = repo+ .claim_occurrence(+ reminder.id,+ reminder.next_run_at,+ Utc::now() + Duration::minutes(1),+ )+ .await+ .expect("claim succeeds");++ assert!(!reclaimed);+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn completing_a_firing_marks_it_sent_and_completes_the_reminder(pool: PgPool) {+ insert_user(&pool, USER_A).await;+ let reminder = create_due(&pool, USER_A, at(2026, 8, 1, 11)).await;+ let repo = PgRemindersRepo::new(pool.clone());++ repo.claim_occurrence(reminder.id, reminder.next_run_at, no_retry())+ .await+ .expect("claim succeeds");+ repo.complete_occurrence(reminder.id, reminder.next_run_at)+ .await+ .expect("complete succeeds");++ let sent_at: Option<DateTime<Utc>> = sqlx::query_scalar(+ r#"SELECT sent_at FROM reminder_occurrence WHERE reminder_id = $1 AND scheduled_for = $2"#,+ )+ .bind(reminder.id)+ .bind(reminder.next_run_at)+ .fetch_one(&pool)+ .await+ .expect("occurrence exists");+ assert!(sent_at.is_some());++ let stored = repo+ .get_reminder(&user(USER_A), reminder.id)+ .await+ .expect("read succeeds")+ .expect("reminder still exists");+ assert!(stored.completed_at.is_some());++ // And it must drop out of the due set, or the next sweep sends it again.+ let due = repo+ .due_firings(at(2026, 8, 1, 12))+ .await+ .expect("query succeeds");+ assert!(due.is_empty());+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn deleting_a_reminder_removes_its_occurrences(pool: PgPool) {+ insert_user(&pool, USER_A).await;+ let reminder = create_due(&pool, USER_A, at(2026, 8, 1, 11)).await;+ let repo = PgRemindersRepo::new(pool.clone());++ repo.claim_occurrence(reminder.id, reminder.next_run_at, no_retry())+ .await+ .expect("claim succeeds");+ repo.delete_reminder(&user(USER_A), reminder.id)+ .await+ .expect("delete succeeds");++ let remaining: i64 =+ sqlx::query_scalar(r#"SELECT count(*) FROM reminder_occurrence WHERE reminder_id = $1"#)+ .bind(reminder.id)+ .fetch_one(&pool)+ .await+ .expect("count succeeds");+ assert_eq!(remaining, 0, "occurrences cascade with the reminder");+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn an_undecodable_row_is_isolated_to_its_own_firing(pool: PgPool) {+ // A sweep reads ids and timestamps only, so nothing it selects can fail to+ // decode: an undecodable row costs its own delivery, which dead-letters and+ // raises the DLQ alarm, and no longer touches anyone else's reminders.+ insert_user(&pool, USER_A).await;+ // Fires first, so a batch-level failure would hide the good one behind it.+ let broken = create_due(&pool, USER_A, at(2026, 8, 1, 10)).await;+ let good = create_due(&pool, USER_A, at(2026, 8, 1, 11)).await;+ let repo = PgRemindersRepo::new(pool.clone());++ // Only reachable by writing around the service: the entity id is a valid+ // uuid, so nothing stops the row landing with an unknown entity type.+ sqlx::query(+ r#"UPDATE reminder SET entity_type = 'chupacabra', entity_id = $2::uuid WHERE id = $1"#,+ )+ .bind(broken.id)+ .bind(DOC_1)+ .execute(&pool)+ .await+ .expect("update should succeed");++ let due = repo+ .due_firings(at(2026, 8, 1, 12))+ .await+ .expect("one bad row must not fail the sweep");++ assert_eq!(due.len(), 2, "the sweep never decodes, so it lists both");++ let broken_firing = DueFiring {+ reminder_id: broken.id,+ scheduled_for: broken.next_run_at,+ };+ assert!(+ repo.find_due_reminder(broken_firing).await.is_err(),+ "the bad row fails its own delivery"+ );++ let good_firing = DueFiring {+ reminder_id: good.id,+ scheduled_for: good.next_run_at,+ };+ assert!(+ repo.find_due_reminder(good_firing)+ .await+ .expect("read succeeds")+ .is_some(),+ "and leaves its neighbour deliverable"+ );+}diff --git a/crates/reminders/src/outbound/sqs_dispatch_queue.rs b/crates/reminders/src/outbound/sqs_dispatch_queue.rsnew file mode 100644index 0000000000..f1d384de5b--- /dev/null+++ b/crates/reminders/src/outbound/sqs_dispatch_queue.rs@@ -0,0 +1,158 @@+//! SQS implementation of the [`ReminderDispatchQueue`] port.+//!+//! The wire format this reads and writes is covered by the+//! `ReminderDispatchMessage` tests in the domain, which is where the shape the+//! EventBridge rule has to produce is pinned down.++use aws_sdk_sqs::Client as SqsClient;+use aws_sdk_sqs::types::SendMessageBatchRequestEntry;++use crate::domain::models::ReminderDispatchMessage;+use crate::domain::ports::{RawDispatchMessage, ReminderDispatchQueue};++/// Most entries SQS accepts in one `SendMessageBatch`.+const MAX_BATCH_SIZE: usize = 10;++/// Most messages one receive returns. Also the SQS maximum.+const MAX_RECEIVE: i32 = 10;++/// Seconds a receive waits for work before returning empty.+///+/// Long polling: the queue is idle for most of every minute, and a short poll+/// would spend that minute issuing empty receives.+const WAIT_TIME_SECONDS: i32 = 20;++/// Reminder dispatch queue backed by SQS.+#[derive(Debug, Clone)]+pub struct SqsDispatchQueue {+ client: SqsClient,+ queue_url: String,+}++impl SqsDispatchQueue {+ /// Point an adapter at a queue.+ pub fn new(client: SqsClient, queue_url: String) -> Self {+ Self { client, queue_url }+ }+}++/// A dispatch queue operation that SQS rejected.+#[derive(Debug, thiserror::Error)]+pub enum DispatchQueueErr {+ /// A message could not be serialized to JSON.+ #[error("failed to serialize a dispatch message")]+ Serialize(#[source] serde_json::Error),+ /// SQS rejected the call outright.+ #[error("dispatch queue request failed")]+ Request(#[source] Box<dyn std::error::Error + Send + Sync>),+ /// The call succeeded but SQS refused some of the batch.+ #[error("{failed} of {total} dispatch messages failed to send")]+ PartialBatch {+ /// Entries SQS refused.+ failed: usize,+ /// Entries in the batch.+ total: usize,+ },+}++impl ReminderDispatchQueue for SqsDispatchQueue {+ type Err = DispatchQueueErr;++ #[tracing::instrument(+ err,+ skip(self, messages),+ fields(message_count = messages.len()),+ )]+ async fn publish_batch(&self, messages: &[ReminderDispatchMessage]) -> Result<(), Self::Err> {+ if messages.is_empty() {+ return Ok(());+ }++ let entries = messages+ .iter()+ .enumerate()+ .map(|(i, message)| {+ let body = serde_json::to_string(message).map_err(DispatchQueueErr::Serialize)?;+ SendMessageBatchRequestEntry::builder()+ // Batch-local, and only has to be unique within the call.+ .id(i.to_string())+ .message_body(body)+ .build()+ .map_err(|e| DispatchQueueErr::Request(Box::new(e)))+ })+ .collect::<Result<Vec<_>, _>>()?;++ for chunk in entries.chunks(MAX_BATCH_SIZE) {+ let result = self+ .client+ .send_message_batch()+ .queue_url(&self.queue_url)+ .set_entries(Some(chunk.to_vec()))+ .send()+ .await+ .map_err(|e| DispatchQueueErr::Request(Box::new(e)))?;++ // A partial failure has to be an error: the caller's contract is+ // all-or-nothing, and silently dropping entries here would strand+ // whatever firings they carried until the next sweep.+ let failed = result.failed().len();+ if failed > 0 {+ return Err(DispatchQueueErr::PartialBatch {+ failed,+ total: chunk.len(),+ });+ }+ }++ Ok(())+ }++ #[tracing::instrument(err, skip(self))]+ async fn receive_messages(&self) -> Result<Vec<RawDispatchMessage>, Self::Err> {+ let result = self+ .client+ .receive_message()+ .queue_url(&self.queue_url)+ .max_number_of_messages(MAX_RECEIVE)+ .wait_time_seconds(WAIT_TIME_SECONDS)+ .send()+ .await+ .map_err(|e| DispatchQueueErr::Request(Box::new(e)))?;++ Ok(result+ .messages+ .unwrap_or_default()+ .into_iter()+ .filter_map(|message| {+ // A message with no body or no receipt handle cannot be handled+ // or acked. Dropping it leaves it to the redrive policy, which+ // is the only thing that can clear it.+ let (Some(body), Some(receipt_handle)) = (message.body, message.receipt_handle)+ else {+ tracing::error!(+ message_id = ?message.message_id,+ "dispatch message missing a body or receipt handle",+ );+ return None;+ };+ Some(RawDispatchMessage {+ body,+ receipt_handle,+ })+ })+ .collect())+ }++ #[tracing::instrument(err, skip(self, receipt_handle))]+ async fn delete_message(&self, receipt_handle: &str) -> Result<(), Self::Err> {+ self.client+ .delete_message()+ .queue_url(&self.queue_url)+ .receipt_handle(receipt_handle)+ .send()+ .await+ .map_err(|e| DispatchQueueErr::Request(Box::new(e)))?;++ Ok(())+ }+}diff --git a/crates/workspace-hack/Cargo.toml b/crates/workspace-hack/Cargo.tomlindex 5f7c2bc155..705fde723f 100644--- a/crates/workspace-hack/Cargo.toml+++ b/crates/workspace-hack/Cargo.toml@@ -86,9 +86,11 @@ percent-encoding = { version = "2" }phf = { version = "0.13", features = ["macros"] }phf_shared-594e8ee84c453af0 = { package = "phf_shared", version = "0.13" }phf_shared-93f6ce9d446188ac = { package = "phf_shared", version = "0.10" }+phf_shared-a6292c17cd707f01 = { package = "phf_shared", version = "0.11" }prost = { version = "0.12", features = ["prost-derive"] }rand-274715c4dabd11b0 = { package = "rand", version = "0.9" }rand-c38e5c1d305a1b54 = { package = "rand", version = "0.8", features = ["small_rng"] }+rand_core = { version = "0.6", default-features = false, features = ["std"] }redis = { version = "1", features = ["cluster-async", "tokio-rustls-comp"] }regex-automata = { version = "0.4", default-features = false, features = ["dfa-build", "dfa-onepass", "hybrid", "meta", "nfa-backtrack", "perf-inline", "perf-literal", "std", "unicode"] }regex-syntax = { version = "0.8" }@@ -211,12 +213,14 @@ percent-encoding = { version = "2" }phf = { version = "0.13", features = ["macros"] }phf_shared-594e8ee84c453af0 = { package = "phf_shared", version = "0.13" }phf_shared-93f6ce9d446188ac = { package = "phf_shared", version = "0.10" }+phf_shared-a6292c17cd707f01 = { package = "phf_shared", version = "0.11" }prettyplease = { version = "0.2", default-features = false, features = ["verbatim"] }proc-macro2 = { version = "1", features = ["span-locations"] }prost = { version = "0.12", features = ["prost-derive"] }quote = { version = "1" }rand-274715c4dabd11b0 = { package = "rand", version = "0.9" }rand-c38e5c1d305a1b54 = { package = "rand", version = "0.8", features = ["small_rng"] }+rand_core = { version = "0.6", default-features = false, features = ["std"] }redis = { version = "1", features = ["cluster-async", "tokio-rustls-comp"] }regex-automata = { version = "0.4", default-features = false, features = ["dfa-build", "dfa-onepass", "hybrid", "meta", "nfa-backtrack", "perf-inline", "perf-literal", "std", "unicode"] }regex-syntax = { version = "0.8" }diff --git a/infra/stacks/cloud-storage-service/index.ts b/infra/stacks/cloud-storage-service/index.tsindex 7a40c3ee91..c2cd1fca9f 100644--- a/infra/stacks/cloud-storage-service/index.ts+++ b/infra/stacks/cloud-storage-service/index.ts@@ -23,6 +23,7 @@ import {DocumentUploadFinalizerLambda,type DocumentUploadFinalizerLambdaEnvVars,} from './document-upload-finalizer-lambda';+import { ReminderDispatchQueue } from './reminder-dispatch-queue';const tags = {environment: stack,@@ -219,6 +220,14 @@ export const deleteChatHandlerLambdaName = deleteChatHandler.lambda.name;export const deleteChatQueueArn = deleteChatHandler.queue.arn;export const deleteChatQueueName = deleteChatHandler.queue.name;+const reminderDispatchQueue = new ReminderDispatchQueue(+ `reminder-dispatch-${stack}`,+ { tags }+);++export const reminderDispatchQueueArn = reminderDispatchQueue.queue.arn;+export const reminderDispatchQueueName = reminderDispatchQueue.queue.name;+const MACRO_API_TOKENS = getMacroApiToken();const GITHUB_WEBHOOK_SECRET_KEY = config.require('github_webhook_secret_key');@@ -266,6 +275,8 @@ const cloudStorageService = new CloudStorageService(contactsQueueArn,emailScheduledQueueArn,gmailOpsQueueArn,+ // Both directions: the sweep publishes onto it and the workers read it.+ reminderDispatchQueue.queue.arn,],vpc: coparse_api_vpc,platform: {diff --git a/infra/stacks/cloud-storage-service/reminder-dispatch-queue.ts b/infra/stacks/cloud-storage-service/reminder-dispatch-queue.tsnew file mode 100644index 0000000000..15f2071456--- /dev/null+++ b/infra/stacks/cloud-storage-service/reminder-dispatch-queue.ts@@ -0,0 +1,102 @@+import * as aws from '@pulumi/aws';+import * as pulumi from '@pulumi/pulumi';+import { Queue } from '../../packages/resources';+import { stack } from '../../packages/shared';++const BASE_NAME = 'reminder-dispatch';++/** The literal payload the rule publishes. Must match `ReminderDispatchOperation::Sweep`. */+const SWEEP_PAYLOAD = JSON.stringify({ operation: 'sweep' });++type Args = {+ tags: { [key: string]: string };+};++/**+ * The queue reminder dispatch runs on, and the schedule that drives it.+ *+ * Every minute EventBridge puts a static sweep payload on the queue. A+ * cloud-storage-service task picks it up, finds every reminder that has come+ * due, and fans one message back onto this same queue per firing — which the+ * whole pool then delivers in parallel. One queue carries both kinds of+ * message; the worker tells them apart by their `operation`.+ *+ * There is no consumer resource here: the workers are the service's own tasks,+ * which reach the queue through the `sqs:*` grant in its role.+ */+export class ReminderDispatchQueue extends pulumi.ComponentResource {+ queue: aws.sqs.Queue;+ dlq: aws.sqs.Queue;+ rule: aws.cloudwatch.EventRule;++ constructor(+ name: string,+ args: Args,+ opts?: pulumi.ComponentResourceOptions+ ) {+ super('my:components:ReminderDispatchQueue', name, {}, opts);+ const { tags } = args;++ const queue = new Queue(+ BASE_NAME,+ {+ tags,+ maxReceiveCount: 5,+ // A delivery is a handful of round trips, and a sweep is one query plus+ // a batch send per ten firings. Generous enough that neither is racing+ // the clock, short enough that a killed task's message comes back fast.+ visibilityTimeoutSeconds: 60,+ },+ { parent: this }+ );++ this.queue = queue.queue;+ this.dlq = queue.dlq;++ this.rule = new aws.cloudwatch.EventRule(+ `${BASE_NAME}-rule`,+ {+ name: `${BASE_NAME}-rule-${stack}`,+ scheduleExpression: 'rate(1 minute)',+ tags,+ },+ { parent: this }+ );++ new aws.cloudwatch.EventTarget(+ `${BASE_NAME}-minutely-target`,+ {+ rule: this.rule.name,+ arn: this.queue.arn,+ input: SWEEP_PAYLOAD,+ },+ { parent: this }+ );++ new aws.sqs.QueuePolicy(+ `${BASE_NAME}-queue-policy`,+ {+ queueUrl: this.queue.url,+ policy: pulumi+ .all([this.queue.arn, this.rule.arn])+ .apply(([queueArn, ruleArn]) =>+ JSON.stringify({+ Version: '2012-10-17',+ Statement: [+ {+ Effect: 'Allow',+ Principal: { Service: 'events.amazonaws.com' },+ Action: 'sqs:SendMessage',+ Resource: queueArn,+ // Scoped to this rule so nothing else in EventBridge can+ // trigger a sweep.+ Condition: { ArnEquals: { 'aws:SourceArn': ruleArn } },+ },+ ],+ })+ ),+ },+ { parent: this }+ );+ }+}diff --git a/packages/sdk/generated/cognition/types.gen.ts b/packages/sdk/generated/cognition/types.gen.tsindex 99e26aee44..3452030a5a 100644--- a/packages/sdk/generated/cognition/types.gen.ts+++ b/packages/sdk/generated/cognition/types.gen.ts@@ -508,7 +508,7 @@ export type Entity = {/*** The type of an entity in Macro*/-export type EntityType = 'user' | 'chat' | 'channel' | 'channel_message' | 'document' | 'project' | 'email_thread' | 'calendar_event' | 'team' | 'call' | 'foreign_entity' | 'static_file' | 'crm_company' | 'crm_contact';+export type EntityType = 'user' | 'chat' | 'channel' | 'channel_message' | 'document' | 'project' | 'email_thread' | 'calendar_event' | 'team' | 'call' | 'foreign_entity' | 'static_file' | 'crm_company' | 'crm_contact' | 'reminder';/*** Error response body.diff --git a/packages/sdk/generated/connection/types.gen.ts b/packages/sdk/generated/connection/types.gen.tsindex ed7960be22..2315ee6f46 100644--- a/packages/sdk/generated/connection/types.gen.ts+++ b/packages/sdk/generated/connection/types.gen.ts@@ -40,7 +40,7 @@ export type Entity = {/*** The type of an entity in Macro*/-export type EntityType = 'user' | 'chat' | 'channel' | 'channel_message' | 'document' | 'project' | 'email_thread' | 'calendar_event' | 'team' | 'call' | 'foreign_entity' | 'static_file' | 'crm_company' | 'crm_contact';+export type EntityType = 'user' | 'chat' | 'channel' | 'channel_message' | 'document' | 'project' | 'email_thread' | 'calendar_event' | 'team' | 'call' | 'foreign_entity' | 'static_file' | 'crm_company' | 'crm_contact' | 'reminder';export type GenericErrorResponse = {/**diff --git a/packages/sdk/generated/notification/index.ts b/packages/sdk/generated/notification/index.tsindex 16ce692de0..7bdad05399 100644--- a/packages/sdk/generated/notification/index.ts+++ b/packages/sdk/generated/notification/index.ts@@ -1,4 +1,4 @@// This file is auto-generated by @hey-api/openapi-tsexport { type Options, Sdk } from './sdk.gen';-export type { AiResponseMetadata, ApiUserNotification, BulkDeleteUserNotificationsV2Data, BulkDeleteUserNotificationsV2Error, BulkDeleteUserNotificationsV2Errors, BulkDeleteUserNotificationsV2Responses, BulkGetByEventItemIdsRequest, BulkGetTypedNotificationsByEventItemIdsData, BulkGetTypedNotificationsByEventItemIdsError, BulkGetTypedNotificationsByEventItemIdsErrors, BulkGetTypedNotificationsByEventItemIdsResponse, BulkGetTypedNotificationsByEventItemIdsResponses, BulkMarkNotificationsDoneData, BulkMarkNotificationsDoneError, BulkMarkNotificationsDoneErrors, BulkMarkNotificationsDoneResponses, BulkMarkNotificationsSeenData, BulkMarkNotificationsSeenError, BulkMarkNotificationsSeenErrors, BulkMarkNotificationsSeenResponses, BulkMarkNotificationsUndoneData, BulkMarkNotificationsUndoneError, BulkMarkNotificationsUndoneErrors, BulkMarkNotificationsUndoneResponses, CallStartedMetadata, ChannelInviteMetadata, ChannelMentionMetadata, ChannelMessageSendMetadata, ChannelReplyMetadata, ChannelType, ClientOptions, CommentedOnDocumentMetadata, CommonChannelMetadata, ConnGatewayInnerNotifValue, ConnGatewayNotificationPayload, CreateNotification, DeleteUserNotificationV2Data, DeleteUserNotificationV2Error, DeleteUserNotificationV2Errors, DeleteUserNotificationV2Responses, DeviceRequest, DeviceType, DisableNotificationTypeData, DisableNotificationTypeError, DisableNotificationTypeErrors, DisableNotificationTypeResponses, DocumentMentionMetadata, EmptyResponse, EnableNotificationTypeData, EnableNotificationTypeError, EnableNotificationTypeErrors, EnableNotificationTypeResponses, Entity, EntityType, ErrorResponse, GetAllUserNotificationsResponse, GetNotificationTypePreferencesData, GetNotificationTypePreferencesError, GetNotificationTypePreferencesErrors, GetNotificationTypePreferencesResponse, GetNotificationTypePreferencesResponse2, GetNotificationTypePreferencesResponses, GetTypedNotificationByIdData, GetTypedNotificationByIdError, GetTypedNotificationByIdErrors, GetTypedNotificationByIdResponse, GetTypedNotificationByIdResponses, GetTypedNotificationsByEventItemIdData, GetTypedNotificationsByEventItemIdError, GetTypedNotificationsByEventItemIdErrors, GetTypedNotificationsByEventItemIdResponse, GetTypedNotificationsByEventItemIdResponses, GetUnsubscribesData, GetUnsubscribesError, GetUnsubscribesErrors, GetUnsubscribesResponse, GetUnsubscribesResponses, GithubPrCheckRun, GithubPrCheckRunState, GithubPrComment, GithubPrCommentKind, GithubPrEventAction, GithubPrEventStatus, GithubPrMention, GithubPrMentionLocation, GithubPrNotificationCommon, GithubPrReview, GithubPrReviewState, GithubPrStatusChanged, GithubReviewRequested, HealthHandlerData, HealthHandlerResponse, HealthHandlerResponses, InboxReauthRequiredMetadata, InviteToTeamMetadata, ItemSharedMetadata, ListTypedNotificationsData, ListTypedNotificationsError, ListTypedNotificationsErrors, ListTypedNotificationsResponse, ListTypedNotificationsResponses, MacroUserIdStr, MentionedInDocumentCommentMetadata, NewEmailMetadata, NotifEvent, NotificationBulkRequest, NotificationDocumentSubType, NotificationServiceApiVersion, NotificationTypeName, PushNotificationData, RemoveUnsubscribeAllData, RemoveUnsubscribeAllError, RemoveUnsubscribeAllErrors, RemoveUnsubscribeAllResponse, RemoveUnsubscribeAllResponses, RemoveUnsubscribeItemData, RemoveUnsubscribeItemError, RemoveUnsubscribeItemErrors, RemoveUnsubscribeItemResponse, RemoveUnsubscribeItemResponses, RepliedToDocumentCommentThreadMetadata, TaggedContentValue, TaskAssignedMetadata, UnsubscribeAllData, UnsubscribeAllError, UnsubscribeAllErrors, UnsubscribeAllResponse, UnsubscribeAllResponses, UnsubscribeEmailData, UnsubscribeEmailError, UnsubscribeEmailErrors, UnsubscribeEmailResponse, UnsubscribeEmailResponses, UnsubscribeItemData, UnsubscribeItemError, UnsubscribeItemErrors, UnsubscribeItemPathParams, UnsubscribeItemResponse, UnsubscribeItemResponses, UserUnsubscribe } from './types.gen';+export type { AiResponseMetadata, ApiUserNotification, BulkDeleteUserNotificationsV2Data, BulkDeleteUserNotificationsV2Error, BulkDeleteUserNotificationsV2Errors, BulkDeleteUserNotificationsV2Responses, BulkGetByEventItemIdsRequest, BulkGetTypedNotificationsByEventItemIdsData, BulkGetTypedNotificationsByEventItemIdsError, BulkGetTypedNotificationsByEventItemIdsErrors, BulkGetTypedNotificationsByEventItemIdsResponse, BulkGetTypedNotificationsByEventItemIdsResponses, BulkMarkNotificationsDoneData, BulkMarkNotificationsDoneError, BulkMarkNotificationsDoneErrors, BulkMarkNotificationsDoneResponses, BulkMarkNotificationsSeenData, BulkMarkNotificationsSeenError, BulkMarkNotificationsSeenErrors, BulkMarkNotificationsSeenResponses, BulkMarkNotificationsUndoneData, BulkMarkNotificationsUndoneError, BulkMarkNotificationsUndoneErrors, BulkMarkNotificationsUndoneResponses, CallStartedMetadata, ChannelInviteMetadata, ChannelMentionMetadata, ChannelMessageSendMetadata, ChannelReplyMetadata, ChannelType, ClientOptions, CommentedOnDocumentMetadata, CommonChannelMetadata, ConnGatewayInnerNotifValue, ConnGatewayNotificationPayload, CreateNotification, DeleteUserNotificationV2Data, DeleteUserNotificationV2Error, DeleteUserNotificationV2Errors, DeleteUserNotificationV2Responses, DeviceRequest, DeviceType, DisableNotificationTypeData, DisableNotificationTypeError, DisableNotificationTypeErrors, DisableNotificationTypeResponses, DocumentMentionMetadata, EmptyResponse, EnableNotificationTypeData, EnableNotificationTypeError, EnableNotificationTypeErrors, EnableNotificationTypeResponses, Entity, EntityType, ErrorResponse, GetAllUserNotificationsResponse, GetNotificationTypePreferencesData, GetNotificationTypePreferencesError, GetNotificationTypePreferencesErrors, GetNotificationTypePreferencesResponse, GetNotificationTypePreferencesResponse2, GetNotificationTypePreferencesResponses, GetTypedNotificationByIdData, GetTypedNotificationByIdError, GetTypedNotificationByIdErrors, GetTypedNotificationByIdResponse, GetTypedNotificationByIdResponses, GetTypedNotificationsByEventItemIdData, GetTypedNotificationsByEventItemIdError, GetTypedNotificationsByEventItemIdErrors, GetTypedNotificationsByEventItemIdResponse, GetTypedNotificationsByEventItemIdResponses, GetUnsubscribesData, GetUnsubscribesError, GetUnsubscribesErrors, GetUnsubscribesResponse, GetUnsubscribesResponses, GithubPrCheckRun, GithubPrCheckRunState, GithubPrComment, GithubPrCommentKind, GithubPrEventAction, GithubPrEventStatus, GithubPrMention, GithubPrMentionLocation, GithubPrNotificationCommon, GithubPrReview, GithubPrReviewState, GithubPrStatusChanged, GithubReviewRequested, HealthHandlerData, HealthHandlerResponse, HealthHandlerResponses, InboxReauthRequiredMetadata, InviteToTeamMetadata, ItemSharedMetadata, ListTypedNotificationsData, ListTypedNotificationsError, ListTypedNotificationsErrors, ListTypedNotificationsResponse, ListTypedNotificationsResponses, MacroUserIdStr, MentionedInDocumentCommentMetadata, NewEmailMetadata, NotifEvent, NotificationBulkRequest, NotificationDocumentSubType, NotificationServiceApiVersion, NotificationTypeName, PushNotificationData, ReminderMetadata, RemoveUnsubscribeAllData, RemoveUnsubscribeAllError, RemoveUnsubscribeAllErrors, RemoveUnsubscribeAllResponse, RemoveUnsubscribeAllResponses, RemoveUnsubscribeItemData, RemoveUnsubscribeItemError, RemoveUnsubscribeItemErrors, RemoveUnsubscribeItemResponse, RemoveUnsubscribeItemResponses, RepliedToDocumentCommentThreadMetadata, TaggedContentValue, TaskAssignedMetadata, UnsubscribeAllData, UnsubscribeAllError, UnsubscribeAllErrors, UnsubscribeAllResponse, UnsubscribeAllResponses, UnsubscribeEmailData, UnsubscribeEmailError, UnsubscribeEmailErrors, UnsubscribeEmailResponse, UnsubscribeEmailResponses, UnsubscribeItemData, UnsubscribeItemError, UnsubscribeItemErrors, UnsubscribeItemPathParams, UnsubscribeItemResponse, UnsubscribeItemResponses, UserUnsubscribe } from './types.gen';diff --git a/packages/sdk/generated/notification/types.gen.ts b/packages/sdk/generated/notification/types.gen.tsindex 09dda0b888..443291b3f7 100644--- a/packages/sdk/generated/notification/types.gen.ts+++ b/packages/sdk/generated/notification/types.gen.ts@@ -350,7 +350,7 @@ export type Entity = {/*** The type of an entity in Macro*/-export type EntityType = 'user' | 'chat' | 'channel' | 'channel_message' | 'document' | 'project' | 'email_thread' | 'calendar_event' | 'team' | 'call' | 'foreign_entity' | 'static_file' | 'crm_company' | 'crm_contact';+export type EntityType = 'user' | 'chat' | 'channel' | 'channel_message' | 'document' | 'project' | 'email_thread' | 'calendar_event' | 'team' | 'call' | 'foreign_entity' | 'static_file' | 'crm_company' | 'crm_contact' | 'reminder';/*** A plain old json error response for use with axum.@@ -815,6 +815,12 @@ export type NotifEvent = {*/content: TaskAssignedMetadata;tag: 'task_assigned';+} | {+ /**+ * A reminder the user set for themselves came due.+ */+ content: ReminderMetadata;+ tag: 'reminder';} | {/*** An AI assistant responded to a chat.@@ -901,6 +907,29 @@ export type PushNotificationData = {senderProfilePictureUrl?: string | null;};+/**+ * Metadata for a reminder the user set for themselves coming due.+ *+ * There is no sender: a reminder is self-set, so the dispatcher sends it with+ * `sender_id: None` (a recipient who is also the sender is filtered out of+ * their own notification). Every formatter here must therefore work without+ * one.+ *+ * The associated entity, when there is one, lives on the notification row+ * rather than in here, and clients resolve its name from that — so the+ * dispatcher does not have to look up a name across five entity types.+ */+export type ReminderMetadata = {+ /**+ * What the user asked to be reminded about.+ */+ description: string;+ /**+ * The reminder that fired.+ */+ reminderId: string;+};+/*** Notification sent when someone replies to a document comment thread.*/diff --git a/packages/sdk/generated/storage/index.ts b/packages/sdk/generated/storage/index.tsindex ff12ca7458..94b5bd30b4 100644--- a/packages/sdk/generated/storage/index.ts+++ b/packages/sdk/generated/storage/index.ts@@ -1,4 +1,4 @@// This file is auto-generated by @hey-api/openapi-tsexport { type Options, Sdk } from './sdk.gen';-export type { AccessLevel, Activity, ActivityType, AddFavoriteData, AddFavoriteError, AddFavoriteErrors, AddFavoriteRequest, AddFavoriteResponse, AddFavoriteResponses, AddParticipantsData, AddParticipantsError, AddParticipantsErrors, AddParticipantsRequest, AddParticipantsResponses, AddPinHandlerData, AddPinHandlerError, AddPinHandlerErrors, AddPinHandlerResponse, AddPinHandlerResponses, AddPinRequest, Anchor, AnchorId, AnchorRequest, AnchorResponse, AnnotationIncrementalUpdate, ApiActivity, ApiAttachmentChannelReference, ApiAttachmentEntityReference, ApiAttachmentGenericReference, ApiChannelAttachment, ApiChannelAttachmentsPage, ApiChannelContextMessage, ApiChannelDetail, ApiChannelListMessage, ApiChannelListPage, ApiChannelListParticipant, ApiChannelListType, ApiChannelMessage, ApiChannelMessageKind, ApiChannelMessagesPage, ApiChannelParticipant, ApiChannelWithLatest, ApiCountedReaction, ApiEntityFilterAst, ApiGroupByField, ApiGroupMeta, ApiMessageAttachment, ApiMessageSender, ApiMessageSenderType, ApiParticipantListRole, ApiParticipantRole, ApiPropertyEntityType, ApiResolvedChannelMessage, ApiThreadInfo, ApiThreadReply, AttendeeResponseStatus, BasicDocument, BasicDocumentSubType, BomPart, Bot, BotChannel, BotChannelType, BotId, BotKind, BotOwner, BotToken, BranchNameResponse, BTreeMap, BulkWakeupRequest, BulkWakeupResponse, BulkWakeupSyncServiceDocumentsData, BulkWakeupSyncServiceDocumentsErrors, BulkWakeupSyncServiceDocumentsResponse, BulkWakeupSyncServiceDocumentsResponses, CalendarAttendee, CalendarEvent, CalendarEventFilters, CalendarOccurrence, CalendarOccurrenceItem, CalendarOccurrenceResponse, CalendarSyncStatus, CallActiveResponse, CallFilters, CallRecord, CallRecordParticipant, CallRecordPreview, CallRecordPreviewData, CallRecordTranscriptSegment, CallStatus, CallTokenResponse, CallWebhookData, CallWebhookError, CallWebhookErrors, CallWebhookResponses, Channel, ChannelCreatedMetadata, ChannelDeletedMetadata, ChannelEventAttachment, ChannelFilters, ChannelJoinCodeResponse, ChannelMentionedMetadata, ChannelMessage, ChannelMessageAttachmentCreatedMetadata, ChannelMessageAttachmentRemovedMetadata, ChannelMessageDeletedMetadata, ChannelMessageFilters, ChannelMessagePatchedMetadata, ChannelMessagePostedMetadata, ChannelParticipant, ChannelParticipantAddedMetadata, ChannelParticipantRemovedMetadata, ChannelPreview, ChannelPreviewData, ChannelSender, ChannelSharePermission, ChannelThreadFilters, ChannelTopicEvent, ChannelType, ChannelUpdatedMetadata, ChannelWebhookRequest, ChannelWebhookResponse, ChannelWithParticipants, Chat, ChatFilters, CheckActiveCallData, CheckActiveCallError, CheckActiveCallErrors, CheckActiveCallResponse, CheckActiveCallResponses, ClientOptions, CloudStorageItemType, Comment, CommentThread, CopyDocumentData, CopyDocumentError, CopyDocumentErrors, CopyDocumentQueryParams, CopyDocumentRequest, CopyDocumentResponse, CopyDocumentResponse2, CopyDocumentResponses, CreateAnchorData, CreateAnchorError, CreateAnchorErrors, CreateAnchorResponse, CreateAnchorResponses, CreateBulkDocumentResponse, CreateBulkDocumentResponseData, CreateChannelData, CreateChannelError, CreateChannelErrors, CreateChannelRequest, CreateChannelResponse, CreateChannelResponse2, CreateChannelResponses, CreateChannelScopedBotData, CreateChannelScopedBotError, CreateChannelScopedBotErrors, CreateChannelScopedBotRequest, CreateChannelScopedBotResponse, CreateChannelScopedBotResponse2, CreateChannelScopedBotResponses, CreateCommentData, CreateCommentError, CreateCommentErrors, CreateCommentRequest, CreateCommentResponse, CreateCommentResponse2, CreateCommentResponses, CreateCrmCommentData, CreateCrmCommentError, CreateCrmCommentErrors, CreateCrmCommentRequest, CreateCrmCommentResponse, CreateCrmCommentResponses, CreateCrmCompanyData, CreateCrmCompanyError, CreateCrmCompanyErrors, CreateCrmCompanyRequest, CreateCrmCompanyResponse, CreateCrmCompanyResponses, CreateCrmContactData, CreateCrmContactError, CreateCrmContactErrors, CreateCrmContactRequest, CreateCrmContactResponse, CreateCrmContactResponses, CreateDocumentData, CreateDocumentError, CreateDocumentErrors, CreateDocumentRequest, CreateDocumentResponse, CreateDocumentResponseData, CreateDocumentResponses, CreateEntityMentionData, CreateEntityMentionError, CreateEntityMentionErrors, CreateEntityMentionRequest, CreateEntityMentionResponse, CreateEntityMentionResponse2, CreateEntityMentionResponses, CreateInstructionsDocumentResponse, CreateInstructionsHandlerData, CreateInstructionsHandlerError, CreateInstructionsHandlerErrors, CreateInstructionsHandlerResponse, CreateInstructionsHandlerResponses, CreateMarkdownDocumentRequest, CreateMarkdownDocumentResponse, CreateMarkdownHandlerData, CreateMarkdownHandlerError, CreateMarkdownHandlerErrors, CreateMarkdownHandlerResponse, CreateMarkdownHandlerResponses, CreateProjectHandlerData, CreateProjectHandlerError, CreateProjectHandlerErrors, CreateProjectHandlerResponse, CreateProjectHandlerResponses, CreateProjectRequest, CreateProjectResponse, CreateSnippetHandlerData, CreateSnippetHandlerError, CreateSnippetHandlerErrors, CreateSnippetHandlerResponse, CreateSnippetHandlerResponses, CreateSnippetRequest, CreateSnippetResponse, CreateTaskHandlerData, CreateTaskHandlerError, CreateTaskHandlerErrors, CreateTaskHandlerResponse, CreateTaskHandlerResponses, CreateTaskRequest, CreateTaskResponse, CreateUnthreadedAnchorRequest, CreateUnthreadedAnchorResponse, CreateUnthreadedPdfAnchorRequest, CreateViewHandlerData, CreateViewHandlerError, CreateViewHandlerErrors, CreateViewHandlerResponse, CreateViewHandlerResponses, CreateViewRequest, CreateWebhookData, CreateWebhookError, CreateWebhookErrors, CreateWebhookRequest, CreateWebhookResponse, CreateWebhookResponse2, CreateWebhookResponses, CrmComment, CrmCommentEntityType, CrmCommentThread, CrmCompanyFilters, CrmCompanyResponse, CrmContactResponse, CrmDomainResponse, CrmPermissionRole, CrmTeamSettingsResponse, CrmThread, CustomSpeakerAssignment, DataType, DeleteAnchorData, DeleteAnchorError, DeleteAnchorErrors, DeleteAnchorInfo, DeleteAnchorResponse, DeleteAnchorResponses, DeleteCallRecordData, DeleteCallRecordError, DeleteCallRecordErrors, DeleteCallRecordResponse, DeleteCallRecordResponses, DeleteChannelData, DeleteChannelError, DeleteChannelErrors, DeleteChannelResponse, DeleteChannelResponses, DeleteCommentData, DeleteCommentError, DeleteCommentErrors, DeleteCommentRequest, DeleteCommentResponse, DeleteCommentResponse2, DeleteCommentResponses, DeleteCrmCommentData, DeleteCrmCommentError, DeleteCrmCommentErrors, DeleteCrmCommentResponse, DeleteCrmCommentResponses, DeleteCrmCommentResult, DeleteDocumentData, DeleteDocumentError, DeleteDocumentErrors, DeleteDocumentResponse, DeleteDocumentResponses, DeleteEntityMentionData, DeleteEntityMentionError, DeleteEntityMentionErrors, DeleteEntityMentionResponse, DeleteEntityMentionResponse2, DeleteEntityMentionResponses, DeleteHistoryHandlerData, DeleteHistoryHandlerError, DeleteHistoryHandlerErrors, DeleteHistoryHandlerResponse, DeleteHistoryHandlerResponses, DeleteMessageData, DeleteMessageError, DeleteMessageErrors, DeleteMessageQuery, DeleteMessageResponse, DeleteMessageResponses, DeleteProjectHandlerData, DeleteProjectHandlerError, DeleteProjectHandlerErrors, DeleteProjectHandlerResponse, DeleteProjectHandlerResponses, DeleteThreadInfo, DeleteUnthreadedAnchorRequest, DeleteUnthreadedAnchorResponse, DeleteUnthreadedPdfAnchorRequest, DeleteUserDocumentViewLocationData, DeleteUserDocumentViewLocationError, DeleteUserDocumentViewLocationErrors, DeleteUserDocumentViewLocationResponse, DeleteUserDocumentViewLocationResponses, DeleteViewHandlerData, DeleteViewHandlerError, DeleteViewHandlerErrors, DeleteViewHandlerResponses, DeleteWebhookData, DeleteWebhookError, DeleteWebhookErrors, DeleteWebhookResponse, DeleteWebhookResponses, DocumentBasic, DocumentContent, DocumentContentLocation, DocumentContentState, DocumentContentUploadedMetadata, DocumentCopiedMetadata, DocumentCreatedMetadata, DocumentDeletedMetadata, DocumentFilters, DocumentInteractionMetadata, DocumentMetadata, DocumentMetadataWithContent, DocumentPermissionsToken, DocumentPermissionsTokenRequest, DocumentPermissionsTokenResponse, DocumentPreview, DocumentPreviewData, DocumentPreviewDataSubType, DocumentPurgedMetadata, DocumentResponse, DocumentResponseMetadata, DocumentResponseMetadataWithContent, DocumentStorageServiceApiVersion, DocumentSubType, DocumentSyncContentUpdatedMetadata, DocumentTeamShareResponse, DocumentTopicEvent, DocumentUpdatedMetadata, EditAnchorData, EditAnchorError, EditAnchorErrors, EditAnchorRequest, EditAnchorResponse, EditAnchorResponse2, EditAnchorResponses, EditCallRecordData, EditCallRecordError, EditCallRecordErrors, EditCallRecordRequest, EditCallRecordResponse, EditCallRecordResponses, EditCallTranscriptData, EditCallTranscriptError, EditCallTranscriptErrors, EditCallTranscriptRequest, EditCallTranscriptResponse, EditCallTranscriptResponses, EditCommentData, EditCommentError, EditCommentErrors, EditCommentRequest, EditCommentResponse, EditCommentResponse2, EditCommentResponses, EditCrmCommentData, EditCrmCommentError, EditCrmCommentErrors, EditCrmCommentRequest, EditCrmCommentResponse, EditCrmCommentResponses, EditDocumentData, EditDocumentError, EditDocumentErrors, EditDocumentResponse, EditDocumentResponse2, EditDocumentResponses, EditDocumentServiceArgs, EditPdfAnchorRequest, EditPdfPlaceableCommentAnchorRequest, EditProjectV2Data, EditProjectV2Error, EditProjectV2Errors, EditProjectV2Response, EditProjectV2Responses, EditThreadV2Data, EditThreadV2Error, EditThreadV2Errors, EditThreadV2Response, EditThreadV2Responses, EmailFilters, EmptyResponse, EntityFilters, EntityPermission, EntityPermissionResponse, EntityReference, EntityType, ErrorResponse, EventStatus, EventTime, EventTransparency, EventVisibility, ExcludedDefaultView, ExcludeDefaultViewHandlerData, ExcludeDefaultViewHandlerError, ExcludeDefaultViewHandlerErrors, ExcludeDefaultViewHandlerResponses, ExcludeDefaultViewRequest, ExportDocumentData, ExportDocumentError, ExportDocumentErrors, ExportDocumentResponse, ExportDocumentResponse2, ExportDocumentResponses, Favorite, FavoriteEntityRef, FavoritesList, FileSystemNodeWithIds, FileType, FileTypeUpdate, FolderItem, ForeignEntity, ForeignEntityFilters, GenericErrorResponse, GenericResponse, GenericSuccessResponse, GetActivitiesResponse, GetActivityData, GetActivityError, GetActivityErrors, GetActivityResponse, GetActivityResponses, GetAttachmentReferencesData, GetAttachmentReferencesError, GetAttachmentReferencesErrors, GetAttachmentReferencesResponse, GetAttachmentReferencesResponse2, GetAttachmentReferencesResponses, GetBatchCallRecordPreviewData, GetBatchCallRecordPreviewError, GetBatchCallRecordPreviewErrors, GetBatchCallRecordPreviewRequest, GetBatchCallRecordPreviewResponse, GetBatchCallRecordPreviewResponse2, GetBatchCallRecordPreviewResponses, GetBatchChannelPreviewData, GetBatchChannelPreviewError, GetBatchChannelPreviewErrors, GetBatchChannelPreviewRequest, GetBatchChannelPreviewResponse, GetBatchChannelPreviewResponse2, GetBatchChannelPreviewResponses, GetBatchPreviewHandlerData, GetBatchPreviewHandlerError, GetBatchPreviewHandlerErrors, GetBatchPreviewHandlerResponse, GetBatchPreviewHandlerResponses, GetBatchPreviewRequest, GetBatchPreviewResponse, GetBatchProjectPreviewData, GetBatchProjectPreviewError, GetBatchProjectPreviewErrors, GetBatchProjectPreviewRequest, GetBatchProjectPreviewResponse, GetBatchProjectPreviewResponse2, GetBatchProjectPreviewResponses, GetCallRecordData, GetCallRecordError, GetCallRecordErrors, GetCallRecordResponse, GetCallRecordResponses, GetChannelAttachmentsData, GetChannelAttachmentsError, GetChannelAttachmentsErrors, GetChannelAttachmentsResponse, GetChannelAttachmentsResponses, GetChannelData, GetChannelError, GetChannelErrors, GetChannelJoinLinkData, GetChannelJoinLinkError, GetChannelJoinLinkErrors, GetChannelJoinLinkResponse, GetChannelJoinLinkResponses, GetChannelMessagesData, GetChannelMessagesError, GetChannelMessagesErrors, GetChannelMessagesResponse, GetChannelMessagesResponses, GetChannelParticipantsData, GetChannelParticipantsError, GetChannelParticipantsErrors, GetChannelParticipantsResponse, GetChannelParticipantsResponses, GetChannelResponse, GetChannelResponses, GetChannelsData, GetChannelsError, GetChannelsErrors, GetChannelsResponse, GetChannelsResponses, GetCompanyData, GetCompanyError, GetCompanyErrors, GetCompanyResponse, GetCompanyResponses, GetContactData, GetContactError, GetContactErrors, GetContactResponse, GetContactResponses, GetCrmTeamSettingsData, GetCrmTeamSettingsError, GetCrmTeamSettingsErrors, GetCrmTeamSettingsResponse, GetCrmTeamSettingsResponses, GetDocumentAnchorsData, GetDocumentAnchorsError, GetDocumentAnchorsErrors, GetDocumentAnchorsResponse, GetDocumentAnchorsResponses, GetDocumentBranchNameData, GetDocumentBranchNameError, GetDocumentBranchNameErrors, GetDocumentBranchNameResponse, GetDocumentBranchNameResponses, GetDocumentByTeamSlugData, GetDocumentByTeamSlugError, GetDocumentByTeamSlugErrors, GetDocumentByTeamSlugResponse, GetDocumentByTeamSlugResponses, GetDocumentCommentsData, GetDocumentCommentsError, GetDocumentCommentsErrors, GetDocumentCommentsResponse, GetDocumentCommentsResponses, GetDocumentData, GetDocumentError, GetDocumentErrors, GetDocumentGithubPullRequestsData, GetDocumentGithubPullRequestsError, GetDocumentGithubPullRequestsErrors, GetDocumentGithubPullRequestsResponse, GetDocumentGithubPullRequestsResponses, GetDocumentKeyResponse, GetDocumentKeyResponseData, GetDocumentListHandlerData, GetDocumentListHandlerError, GetDocumentListHandlerErrors, GetDocumentListHandlerResponse, GetDocumentListHandlerResponses, GetDocumentListResult, GetDocumentLocationV3Data, GetDocumentLocationV3Error, GetDocumentLocationV3Errors, GetDocumentLocationV3Response, GetDocumentLocationV3Responses, GetDocumentPermissionsResponseDataV2, GetDocumentPermissionsTokenData, GetDocumentPermissionsTokenError, GetDocumentPermissionsTokenErrors, GetDocumentPermissionsTokenResponse, GetDocumentPermissionsTokenResponses, GetDocumentPermissionsV2Data, GetDocumentPermissionsV2Error, GetDocumentPermissionsV2Errors, GetDocumentPermissionsV2Response, GetDocumentPermissionsV2Responses, GetDocumentProcessingResult, GetDocumentProcessingResultData, GetDocumentProcessingResultError, GetDocumentProcessingResultErrors, GetDocumentProcessingResultResponse, GetDocumentProcessingResultResponse2, GetDocumentProcessingResultResponses, GetDocumentResponse, GetDocumentResponse2, GetDocumentResponseData, GetDocumentResponses, GetDocumentSearchResponse, GetDocumentShortIdData, GetDocumentShortIdError, GetDocumentShortIdErrors, GetDocumentShortIdResponse, GetDocumentShortIdResponses, GetDocumentsResponse, GetDocumentTeamShareData, GetDocumentTeamShareError, GetDocumentTeamShareErrors, GetDocumentTeamShareResponse, GetDocumentTeamShareResponses, GetDocumentUserAccessLevelResponse, GetDocumentVersionData, GetDocumentVersionError, GetDocumentVersionErrors, GetDocumentVersionResponse, GetDocumentVersionResponses, GetDocumentViewsHandlerData, GetDocumentViewsHandlerError, GetDocumentViewsHandlerErrors, GetDocumentViewsHandlerResponse, GetDocumentViewsHandlerResponses, GetEntityPermissionData, GetEntityPermissionErrors, GetEntityPermissionResponse, GetEntityPermissionResponses, GetForeignEntityData, GetForeignEntityError, GetForeignEntityErrors, GetForeignEntityResponse, GetForeignEntityResponses, GetHistoryHandlerData, GetHistoryHandlerError, GetHistoryHandlerErrors, GetHistoryHandlerResponse, GetHistoryHandlerResponses, GetInstructionsDocumentResponse, GetInstructionsHandlerData, GetInstructionsHandlerError, GetInstructionsHandlerErrors, GetInstructionsHandlerResponse, GetInstructionsHandlerResponses, GetItemsSoupData, GetItemsSoupError, GetItemsSoupErrors, GetItemsSoupResponse, GetItemsSoupResponses, GetLocationHandlerData, GetLocationHandlerError, GetLocationHandlerErrors, GetLocationHandlerResponse, GetLocationHandlerResponses, GetMessageWithContextData, GetMessageWithContextError, GetMessageWithContextErrors, GetMessageWithContextResponse, GetMessageWithContextResponse2, GetMessageWithContextResponses, GetOrCreateAction, GetOrCreateCallData, GetOrCreateCallError, GetOrCreateCallErrors, GetOrCreateCallResponse, GetOrCreateCallResponses, GetOrCreateChannelResponse, GetOrCreateDmData, GetOrCreateDmError, GetOrCreateDmErrors, GetOrCreateDmRequest, GetOrCreateDmResponse, GetOrCreateDmResponses, GetOrCreatePrivateData, GetOrCreatePrivateError, GetOrCreatePrivateErrors, GetOrCreatePrivateRequest, GetOrCreatePrivateResponse, GetOrCreatePrivateResponses, GetPendingProjectsHandlerData, GetPendingProjectsHandlerError, GetPendingProjectsHandlerErrors, GetPendingProjectsHandlerResponse, GetPendingProjectsHandlerResponses, GetPinsHandlerData, GetPinsHandlerError, GetPinsHandlerErrors, GetPinsHandlerResponse, GetPinsHandlerResponses, GetPinsResponse, GetProjectContentHandlerData, GetProjectContentHandlerError, GetProjectContentHandlerErrors, GetProjectContentHandlerResponse, GetProjectContentHandlerResponses, GetProjectContentResponse, GetProjectHandlerData, GetProjectHandlerError, GetProjectHandlerErrors, GetProjectHandlerResponse, GetProjectHandlerResponses, GetProjectPermissionsV2Data, GetProjectPermissionsV2Error, GetProjectPermissionsV2Errors, GetProjectPermissionsV2Response, GetProjectPermissionsV2Responses, GetProjectResponse, GetProjectResponseData, GetProjectsHandlerData, GetProjectsHandlerError, GetProjectsHandlerErrors, GetProjectsHandlerResponse, GetProjectsHandlerResponses, GetProjectsResponse, GetProjectUserAccessLevelData, GetProjectUserAccessLevelError, GetProjectUserAccessLevelErrors, GetProjectUserAccessLevelResponse, GetProjectUserAccessLevelResponses, GetRecentActivityHandlerData, GetRecentActivityHandlerError, GetRecentActivityHandlerErrors, GetRecentActivityHandlerResponse, GetRecentActivityHandlerResponses, GetRingStatusData, GetRingStatusError, GetRingStatusErrors, GetRingStatusResponse, GetRingStatusResponses, GetSelfBotData, GetSelfBotError, GetSelfBotErrors, GetSelfBotResponse, GetSelfBotResponses, GetThreadRepliesData, GetThreadRepliesError, GetThreadRepliesErrors, GetThreadRepliesResponse, GetThreadRepliesResponses, GetUserDocumentsHandlerData, GetUserDocumentsHandlerError, GetUserDocumentsHandlerErrors, GetUserDocumentsHandlerResponse, GetUserDocumentsHandlerResponses, GetUserDocumentViewLocationData, GetUserDocumentViewLocationError, GetUserDocumentViewLocationErrors, GetUserDocumentViewLocationResponse, GetUserDocumentViewLocationResponses, GetUserHistoryResponse, GetViewsHandlerData, GetViewsHandlerError, GetViewsHandlerErrors, GetViewsHandlerResponse, GetViewsHandlerResponses, GetWebhookData, GetWebhookError, GetWebhookErrors, GetWebhookResponse, GetWebhookResponses, GithubPullRequest, GithubPullRequestCheckRun, GithubPullRequestComment, GithubPullRequestsResponse, GroupedInitialParams, GroupedPageParams, GroupedSoupGroupPage, GroupedSoupInitialPage, GroupedSoupPage, GroupedSoupSort, HandlerData, HandlerError, HandlerErrors, HandlerResponse, HandlerResponses, HashMap, HealthHandlerData, HealthHandlerResponse, HealthHandlerResponses, HighlightType, IngestTranscriptData, IngestTranscriptError, IngestTranscriptErrors, IngestTranscriptResponses, InitializeUserDocumentsData, InitializeUserDocumentsError, InitializeUserDocumentsErrors, InitializeUserDocumentsResponse, InitializeUserDocumentsResponses, InstallSyncData, InstallSyncErrors, InteractionReason, Item, ItemWithUserAccessLevel, JobProcessingResultHandlerData, JobProcessingResultHandlerError, JobProcessingResultHandlerErrors, JobProcessingResultHandlerResponse, JobProcessingResultHandlerResponses, JoinChannelByCodeData, JoinChannelByCodeError, JoinChannelByCodeErrors, JoinChannelByCodeResponses, JoinChannelData, JoinChannelError, JoinChannelErrors, JoinChannelResponses, LatestMessage, LeaveCallResponse, LeaveChannelData, LeaveChannelError, LeaveChannelErrors, LeaveChannelResponses, LeaveOrEndCallData, LeaveOrEndCallError, LeaveOrEndCallErrors, LeaveOrEndCallResponse, LeaveOrEndCallResponses, ListBotChannelsData, ListBotChannelsError, ListBotChannelsErrors, ListBotChannelsResponse, ListBotChannelsResponses, ListCompanyContactsData, ListCompanyContactsError, ListCompanyContactsErrors, ListCompanyContactsResponse, ListCompanyContactsResponses, ListCrmCommentsData, ListCrmCommentsError, ListCrmCommentsErrors, ListCrmCommentsResponse, ListCrmCommentsResponses, ListFavoritesData, ListFavoritesError, ListFavoritesErrors, ListFavoritesResponse, ListFavoritesResponses, ListOccurrencesData, ListOccurrencesErrors, ListOccurrencesResponse, ListOccurrencesResponses, ListWebhooksData, ListWebhooksError, ListWebhooksErrors, ListWebhooksResponse, ListWebhooksResponse2, ListWebhooksResponses, LocationResponseData, LocationResponseV3, MacroUserIdStr, Mentions, NewChannelAttachment, NotificationFilters, Params, ParticipantRole, PatchChannelData, PatchChannelError, PatchChannelErrors, PatchChannelRequest, PatchChannelResponse, PatchChannelResponses, PatchMessageData, PatchMessageError, PatchMessageErrors, PatchMessageRequest, PatchMessageResponse, PatchMessageResponses, PatchProjectRequestV2, PatchThreadRequestV2, PatchViewHandlerData, PatchViewHandlerError, PatchViewHandlerErrors, PatchViewHandlerResponses, PatchWebhookData, PatchWebhookError, PatchWebhookErrors, PatchWebhookRequest, PatchWebhookResponse, PatchWebhookResponses, PdfAnchor, PdfAnchorId, PdfAnchorRequest, PdfHighlightAnchor, PdfHighlightAnchorRequest, PdfHighlightRect, PdfHighlightRectAnchorRequest, PdfPlaceableCommentAnchor, PdfPlaceableCommentAnchorRequest, PermanentlyDeleteDocumentData, PermanentlyDeleteDocumentError, PermanentlyDeleteDocumentErrors, PermanentlyDeleteDocumentResponse, PermanentlyDeleteDocumentResponses, PermanentlyDeleteProjectData, PermanentlyDeleteProjectError, PermanentlyDeleteProjectErrors, PermanentlyDeleteProjectResponse, PermanentlyDeleteProjectResponses, PinnedItem, PinRequest, PostActivityData, PostActivityError, PostActivityErrors, PostActivityRequest, PostActivityResponse, PostActivityResponses, PostChannelBotWebhookData, PostChannelBotWebhookError, PostChannelBotWebhookErrors, PostChannelBotWebhookResponse, PostChannelBotWebhookResponses, PostChannelMessagesData, PostChannelMessagesError, PostChannelMessagesErrors, PostChannelMessagesResponse, PostChannelMessagesResponses, PostGroupedSoupAstGroupPageRequest, PostGroupedSoupAstInitialRequest, PostGroupedSoupAstRequest, PostItemsSoupAstData, PostItemsSoupAstError, PostItemsSoupAstErrors, PostItemsSoupAstGroupedData, PostItemsSoupAstGroupedError, PostItemsSoupAstGroupedErrors, PostItemsSoupAstGroupedResponse, PostItemsSoupAstGroupedResponses, PostItemsSoupAstResponse, PostItemsSoupAstResponses, PostItemsSoupData, PostItemsSoupError, PostItemsSoupErrors, PostItemsSoupResponse, PostItemsSoupResponses, PostMessageData, PostMessageError, PostMessageErrors, PostMessageRequest, PostMessageResponse, PostMessageResponse2, PostMessageResponses, PostReactionData, PostReactionError, PostReactionErrors, PostReactionRequest, PostReactionResponse, PostReactionResponses, PostSoupAstRequest, PostSoupRequest, PostTypingData, PostTypingError, PostTypingErrors, PostTypingRequest, PostTypingResponse, PostTypingResponses, PresaveDocumentHandlerData, PresaveDocumentHandlerError, PresaveDocumentHandlerErrors, PresaveDocumentHandlerResponse, PresaveDocumentHandlerResponses, PreSaveDocumentRequest, PreSaveDocumentResponse, PreSaveDocumentResponseData, PresignedUrl, Project, ProjectDeleteResponseData, ProjectDocumentStatus, ProjectFilters, ProjectPreview, ProjectPreviewData, PropertyDefinition, PropertyFilter, PropertyInput, PropertyOwner, PropertyValue, PutCrmTeamSettingsData, PutCrmTeamSettingsError, PutCrmTeamSettingsErrors, PutCrmTeamSettingsResponse, PutCrmTeamSettingsResponses, ReactionAction, RecentlyDeletedData, RecentlyDeletedError, RecentlyDeletedErrors, RecentlyDeletedResponse, RecentlyDeletedResponseData, RecentlyDeletedResponses, RemoveBotFromChannelByBotData, RemoveBotFromChannelByBotError, RemoveBotFromChannelByBotErrors, RemoveBotFromChannelByBotResponse, RemoveBotFromChannelByBotResponses, RemoveFavoriteByEntityData, RemoveFavoriteByEntityError, RemoveFavoriteByEntityErrors, RemoveFavoriteByEntityResponses, RemoveParticipantsData, RemoveParticipantsError, RemoveParticipantsErrors, RemoveParticipantsRequest, RemoveParticipantsResponses, RemovePinHandlerData, RemovePinHandlerError, RemovePinHandlerErrors, RemovePinHandlerResponse, RemovePinHandlerResponses, ReorderFavoritesData, ReorderFavoritesError, ReorderFavoritesErrors, ReorderFavoritesRequest, ReorderFavoritesResponses, ReorderPinRequest, ReorderPinsHandlerData, ReorderPinsHandlerError, ReorderPinsHandlerErrors, ReorderPinsHandlerResponse, ReorderPinsHandlerResponses, ResolveChannelMessageData, ResolveChannelMessageError, ResolveChannelMessageErrors, ResolveChannelMessageResponse, ResolveChannelMessageResponses, RevertDeleteDocumentData, RevertDeleteDocumentError, RevertDeleteDocumentErrors, RevertDeleteDocumentResponse, RevertDeleteDocumentResponses, RevertDeleteProjectData, RevertDeleteProjectError, RevertDeleteProjectErrors, RevertDeleteProjectResponse, RevertDeleteProjectResponses, RingStatus, RingStatusResponse, S3ObjectInfo, SaveBomPart, SaveDocumentHandlerData, SaveDocumentHandlerError, SaveDocumentHandlerErrors, SaveDocumentHandlerResponse, SaveDocumentHandlerResponses, SaveDocumentRequest, SaveDocumentResponse, SaveDocumentResponseData, SetCompanyHiddenData, SetCompanyHiddenError, SetCompanyHiddenErrors, SetCompanyHiddenRequest, SetCompanyHiddenResponse, SetCompanyHiddenResponses, SetCompanyNameRequest, SetContactHiddenData, SetContactHiddenError, SetContactHiddenErrors, SetContactHiddenRequest, SetContactHiddenResponse, SetContactHiddenResponses, SetContactNameRequest, SetCrmCompanyNameData, SetCrmCompanyNameError, SetCrmCompanyNameErrors, SetCrmCompanyNameResponse, SetCrmCompanyNameResponses, SetCrmContactNameData, SetCrmContactNameError, SetCrmContactNameErrors, SetCrmContactNameResponse, SetCrmContactNameResponses, SetDocumentTeamShareData, SetDocumentTeamShareError, SetDocumentTeamShareErrors, SetDocumentTeamShareRequest, SetDocumentTeamShareResponse, SetDocumentTeamShareResponses, SetEmailSyncData, SetEmailSyncError, SetEmailSyncErrors, SetEmailSyncRequest, SetEmailSyncResponse, SetEmailSyncResponses, SetPropertyValue, SharedEmailFilter, SharePermissionV2, ShortIdResponse, SimpleMention, SimpleSaveData, SimpleSaveError, SimpleSaveErrors, SimpleSaveResponse, SimpleSaveResponses, SoupApiItem, SoupApiSort, SoupAttachment, SoupCalendarEventSoupPropertiesField, SoupCalendarEventTime, SoupCallRecordParticipant, SoupCallRecordSoupPropertiesField, SoupChannel, SoupChannelThread, SoupChatSoupPropertiesField, SoupContact, SoupCountedReaction, SoupCrmCompanySoupPropertiesField, SoupCrmDomain, SoupDocumentSoupPropertiesField, SoupDocumentSubType, SoupEmailThreadPreview, SoupEnrichedEmailThreadPreviewSoupPropertiesField, SoupForeignEntity, SoupItem, SoupLabel, SoupLabelListVisibility, SoupLabelType, SoupMessageAttachment, SoupMessageListVisibility, SoupMessageSender, SoupMessageSenderType, SoupPage, SoupProjectSoupPropertiesField, SoupPropertiesField, SoupProperty, SoupThreadInfo, SoupThreadReply, StarterDocumentsResponse, String, SuccessResponse, SyncServiceVersionId, TagFilterMode, TaskFilters, TeamRole, Thread, ThreadResponse, ToggleShareWithTeamData, ToggleShareWithTeamError, ToggleShareWithTeamErrors, ToggleShareWithTeamResponse, ToggleShareWithTeamResponses, TranscriptSegmentRequest, TypedSuccessResponse, TypedSuccessResponseGetDocumentResponseData, TypingAction, UnthreadedPdfUuidRequest, UpdateChannelSharePermission, UpdateCrmTeamSettingsRequest, UpdateOperation, UpdateSharePermissionRequestV2, UploadDocumentStatus, UploadExtractFolderHandlerData, UploadExtractFolderHandlerError, UploadExtractFolderHandlerErrors, UploadExtractFolderHandlerResponse, UploadExtractFolderHandlerResponses, UploadExtractFolderRequest, UploadFolderHandlerData, UploadFolderHandlerError, UploadFolderHandlerErrors, UploadFolderHandlerResponse, UploadFolderHandlerResponses, UploadFolderRequest, UpsertHistoryHandlerData, UpsertHistoryHandlerError, UpsertHistoryHandlerErrors, UpsertHistoryHandlerResponse, UpsertHistoryHandlerResponses, UpsertUserDocumentViewLocationData, UpsertUserDocumentViewLocationError, UpsertUserDocumentViewLocationErrors, UpsertUserDocumentViewLocationRequest, UpsertUserDocumentViewLocationResponse, UpsertUserDocumentViewLocationResponses, UserActivitiesResponse, UserDocumentsResponse, UserDocumentViewLocation, UserDocumentViewLocationResponse, UserPinsResponse, UserViewsResponse, ValidateDocumentPermissionsTokenData, ValidateDocumentPermissionsTokenError, ValidateDocumentPermissionsTokenErrors, ValidateDocumentPermissionsTokenResponse, ValidateDocumentPermissionsTokenResponses, ValidateWebhookData, ValidateWebhookError, ValidateWebhookErrors, ValidateWebhookResponse, ValidateWebhookResponse2, ValidateWebhookResponses, Vec, View, ViewPatch, ViewsResponse, Webhook, WebhookEvent, WebhookFilter, WebhookScope, WebhookStatus, WebhookValidationTestEvent, WithCallId, WithChannelId, WithDocumentId, WithProjectId } from './types.gen';+export type { AccessLevel, Activity, ActivityType, AddFavoriteData, AddFavoriteError, AddFavoriteErrors, AddFavoriteRequest, AddFavoriteResponse, AddFavoriteResponses, AddParticipantsData, AddParticipantsError, AddParticipantsErrors, AddParticipantsRequest, AddParticipantsResponses, AddPinHandlerData, AddPinHandlerError, AddPinHandlerErrors, AddPinHandlerResponse, AddPinHandlerResponses, AddPinRequest, Anchor, AnchorId, AnchorRequest, AnchorResponse, AnnotationIncrementalUpdate, ApiActivity, ApiAttachmentChannelReference, ApiAttachmentEntityReference, ApiAttachmentGenericReference, ApiChannelAttachment, ApiChannelAttachmentsPage, ApiChannelContextMessage, ApiChannelDetail, ApiChannelListMessage, ApiChannelListPage, ApiChannelListParticipant, ApiChannelListType, ApiChannelMessage, ApiChannelMessageKind, ApiChannelMessagesPage, ApiChannelParticipant, ApiChannelWithLatest, ApiCountedReaction, ApiEntityFilterAst, ApiGroupByField, ApiGroupMeta, ApiMessageAttachment, ApiMessageSender, ApiMessageSenderType, ApiParticipantListRole, ApiParticipantRole, ApiPropertyEntityType, ApiResolvedChannelMessage, ApiThreadInfo, ApiThreadReply, AttendeeResponseStatus, BasicDocument, BasicDocumentSubType, BomPart, Bot, BotChannel, BotChannelType, BotId, BotKind, BotOwner, BotToken, BranchNameResponse, BTreeMap, BulkWakeupRequest, BulkWakeupResponse, BulkWakeupSyncServiceDocumentsData, BulkWakeupSyncServiceDocumentsErrors, BulkWakeupSyncServiceDocumentsResponse, BulkWakeupSyncServiceDocumentsResponses, CalendarAttendee, CalendarEvent, CalendarEventFilters, CalendarOccurrence, CalendarOccurrenceItem, CalendarOccurrenceResponse, CalendarSyncStatus, CallActiveResponse, CallFilters, CallRecord, CallRecordParticipant, CallRecordPreview, CallRecordPreviewData, CallRecordTranscriptSegment, CallStatus, CallTokenResponse, CallWebhookData, CallWebhookError, CallWebhookErrors, CallWebhookResponses, Channel, ChannelCreatedMetadata, ChannelDeletedMetadata, ChannelEventAttachment, ChannelFilters, ChannelJoinCodeResponse, ChannelMentionedMetadata, ChannelMessage, ChannelMessageAttachmentCreatedMetadata, ChannelMessageAttachmentRemovedMetadata, ChannelMessageDeletedMetadata, ChannelMessageFilters, ChannelMessagePatchedMetadata, ChannelMessagePostedMetadata, ChannelParticipant, ChannelParticipantAddedMetadata, ChannelParticipantRemovedMetadata, ChannelPreview, ChannelPreviewData, ChannelSender, ChannelSharePermission, ChannelThreadFilters, ChannelTopicEvent, ChannelType, ChannelUpdatedMetadata, ChannelWebhookRequest, ChannelWebhookResponse, ChannelWithParticipants, Chat, ChatFilters, CheckActiveCallData, CheckActiveCallError, CheckActiveCallErrors, CheckActiveCallResponse, CheckActiveCallResponses, ClientOptions, CloudStorageItemType, Comment, CommentThread, CopyDocumentData, CopyDocumentError, CopyDocumentErrors, CopyDocumentQueryParams, CopyDocumentRequest, CopyDocumentResponse, CopyDocumentResponse2, CopyDocumentResponses, CreateAnchorData, CreateAnchorError, CreateAnchorErrors, CreateAnchorResponse, CreateAnchorResponses, CreateBulkDocumentResponse, CreateBulkDocumentResponseData, CreateChannelData, CreateChannelError, CreateChannelErrors, CreateChannelRequest, CreateChannelResponse, CreateChannelResponse2, CreateChannelResponses, CreateChannelScopedBotData, CreateChannelScopedBotError, CreateChannelScopedBotErrors, CreateChannelScopedBotRequest, CreateChannelScopedBotResponse, CreateChannelScopedBotResponse2, CreateChannelScopedBotResponses, CreateCommentData, CreateCommentError, CreateCommentErrors, CreateCommentRequest, CreateCommentResponse, CreateCommentResponse2, CreateCommentResponses, CreateCrmCommentData, CreateCrmCommentError, CreateCrmCommentErrors, CreateCrmCommentRequest, CreateCrmCommentResponse, CreateCrmCommentResponses, CreateCrmCompanyData, CreateCrmCompanyError, CreateCrmCompanyErrors, CreateCrmCompanyRequest, CreateCrmCompanyResponse, CreateCrmCompanyResponses, CreateCrmContactData, CreateCrmContactError, CreateCrmContactErrors, CreateCrmContactRequest, CreateCrmContactResponse, CreateCrmContactResponses, CreateDocumentData, CreateDocumentError, CreateDocumentErrors, CreateDocumentRequest, CreateDocumentResponse, CreateDocumentResponseData, CreateDocumentResponses, CreateEntityMentionData, CreateEntityMentionError, CreateEntityMentionErrors, CreateEntityMentionRequest, CreateEntityMentionResponse, CreateEntityMentionResponse2, CreateEntityMentionResponses, CreateInstructionsDocumentResponse, CreateInstructionsHandlerData, CreateInstructionsHandlerError, CreateInstructionsHandlerErrors, CreateInstructionsHandlerResponse, CreateInstructionsHandlerResponses, CreateMarkdownDocumentRequest, CreateMarkdownDocumentResponse, CreateMarkdownHandlerData, CreateMarkdownHandlerError, CreateMarkdownHandlerErrors, CreateMarkdownHandlerResponse, CreateMarkdownHandlerResponses, CreateProjectHandlerData, CreateProjectHandlerError, CreateProjectHandlerErrors, CreateProjectHandlerResponse, CreateProjectHandlerResponses, CreateProjectRequest, CreateProjectResponse, CreateReminderData, CreateReminderError, CreateReminderErrors, CreateReminderRequest, CreateReminderResponse, CreateReminderResponses, CreateSnippetHandlerData, CreateSnippetHandlerError, CreateSnippetHandlerErrors, CreateSnippetHandlerResponse, CreateSnippetHandlerResponses, CreateSnippetRequest, CreateSnippetResponse, CreateTaskHandlerData, CreateTaskHandlerError, CreateTaskHandlerErrors, CreateTaskHandlerResponse, CreateTaskHandlerResponses, CreateTaskRequest, CreateTaskResponse, CreateUnthreadedAnchorRequest, CreateUnthreadedAnchorResponse, CreateUnthreadedPdfAnchorRequest, CreateViewHandlerData, CreateViewHandlerError, CreateViewHandlerErrors, CreateViewHandlerResponse, CreateViewHandlerResponses, CreateViewRequest, CreateWebhookData, CreateWebhookError, CreateWebhookErrors, CreateWebhookRequest, CreateWebhookResponse, CreateWebhookResponse2, CreateWebhookResponses, CrmComment, CrmCommentEntityType, CrmCommentThread, CrmCompanyFilters, CrmCompanyResponse, CrmContactResponse, CrmDomainResponse, CrmPermissionRole, CrmTeamSettingsResponse, CrmThread, CustomSpeakerAssignment, DataType, DeleteAnchorData, DeleteAnchorError, DeleteAnchorErrors, DeleteAnchorInfo, DeleteAnchorResponse, DeleteAnchorResponses, DeleteCallRecordData, DeleteCallRecordError, DeleteCallRecordErrors, DeleteCallRecordResponse, DeleteCallRecordResponses, DeleteChannelData, DeleteChannelError, DeleteChannelErrors, DeleteChannelResponse, DeleteChannelResponses, DeleteCommentData, DeleteCommentError, DeleteCommentErrors, DeleteCommentRequest, DeleteCommentResponse, DeleteCommentResponse2, DeleteCommentResponses, DeleteCrmCommentData, DeleteCrmCommentError, DeleteCrmCommentErrors, DeleteCrmCommentResponse, DeleteCrmCommentResponses, DeleteCrmCommentResult, DeleteDocumentData, DeleteDocumentError, DeleteDocumentErrors, DeleteDocumentResponse, DeleteDocumentResponses, DeleteEntityMentionData, DeleteEntityMentionError, DeleteEntityMentionErrors, DeleteEntityMentionResponse, DeleteEntityMentionResponse2, DeleteEntityMentionResponses, DeleteHistoryHandlerData, DeleteHistoryHandlerError, DeleteHistoryHandlerErrors, DeleteHistoryHandlerResponse, DeleteHistoryHandlerResponses, DeleteMessageData, DeleteMessageError, DeleteMessageErrors, DeleteMessageQuery, DeleteMessageResponse, DeleteMessageResponses, DeleteProjectHandlerData, DeleteProjectHandlerError, DeleteProjectHandlerErrors, DeleteProjectHandlerResponse, DeleteProjectHandlerResponses, DeleteReminderData, DeleteReminderError, DeleteReminderErrors, DeleteReminderResponse, DeleteReminderResponses, DeleteThreadInfo, DeleteUnthreadedAnchorRequest, DeleteUnthreadedAnchorResponse, DeleteUnthreadedPdfAnchorRequest, DeleteUserDocumentViewLocationData, DeleteUserDocumentViewLocationError, DeleteUserDocumentViewLocationErrors, DeleteUserDocumentViewLocationResponse, DeleteUserDocumentViewLocationResponses, DeleteViewHandlerData, DeleteViewHandlerError, DeleteViewHandlerErrors, DeleteViewHandlerResponses, DeleteWebhookData, DeleteWebhookError, DeleteWebhookErrors, DeleteWebhookResponse, DeleteWebhookResponses, DocumentBasic, DocumentContent, DocumentContentLocation, DocumentContentState, DocumentContentUploadedMetadata, DocumentCopiedMetadata, DocumentCreatedMetadata, DocumentDeletedMetadata, DocumentFilters, DocumentInteractionMetadata, DocumentMetadata, DocumentMetadataWithContent, DocumentPermissionsToken, DocumentPermissionsTokenRequest, DocumentPermissionsTokenResponse, DocumentPreview, DocumentPreviewData, DocumentPreviewDataSubType, DocumentPurgedMetadata, DocumentResponse, DocumentResponseMetadata, DocumentResponseMetadataWithContent, DocumentStorageServiceApiVersion, DocumentSubType, DocumentSyncContentUpdatedMetadata, DocumentTeamShareResponse, DocumentTopicEvent, DocumentUpdatedMetadata, EditAnchorData, EditAnchorError, EditAnchorErrors, EditAnchorRequest, EditAnchorResponse, EditAnchorResponse2, EditAnchorResponses, EditCallRecordData, EditCallRecordError, EditCallRecordErrors, EditCallRecordRequest, EditCallRecordResponse, EditCallRecordResponses, EditCallTranscriptData, EditCallTranscriptError, EditCallTranscriptErrors, EditCallTranscriptRequest, EditCallTranscriptResponse, EditCallTranscriptResponses, EditCommentData, EditCommentError, EditCommentErrors, EditCommentRequest, EditCommentResponse, EditCommentResponse2, EditCommentResponses, EditCrmCommentData, EditCrmCommentError, EditCrmCommentErrors, EditCrmCommentRequest, EditCrmCommentResponse, EditCrmCommentResponses, EditDocumentData, EditDocumentError, EditDocumentErrors, EditDocumentResponse, EditDocumentResponse2, EditDocumentResponses, EditDocumentServiceArgs, EditPdfAnchorRequest, EditPdfPlaceableCommentAnchorRequest, EditProjectV2Data, EditProjectV2Error, EditProjectV2Errors, EditProjectV2Response, EditProjectV2Responses, EditThreadV2Data, EditThreadV2Error, EditThreadV2Errors, EditThreadV2Response, EditThreadV2Responses, EmailFilters, EmptyResponse, EntityFilters, EntityPermission, EntityPermissionResponse, EntityReference, EntityType, ErrorResponse, EventStatus, EventTime, EventTransparency, EventVisibility, ExcludedDefaultView, ExcludeDefaultViewHandlerData, ExcludeDefaultViewHandlerError, ExcludeDefaultViewHandlerErrors, ExcludeDefaultViewHandlerResponses, ExcludeDefaultViewRequest, ExportDocumentData, ExportDocumentError, ExportDocumentErrors, ExportDocumentResponse, ExportDocumentResponse2, ExportDocumentResponses, Favorite, FavoriteEntityRef, FavoritesList, FileSystemNodeWithIds, FileType, FileTypeUpdate, FolderItem, ForeignEntity, ForeignEntityFilters, GenericErrorResponse, GenericResponse, GenericSuccessResponse, GetActivitiesResponse, GetActivityData, GetActivityError, GetActivityErrors, GetActivityResponse, GetActivityResponses, GetAttachmentReferencesData, GetAttachmentReferencesError, GetAttachmentReferencesErrors, GetAttachmentReferencesResponse, GetAttachmentReferencesResponse2, GetAttachmentReferencesResponses, GetBatchCallRecordPreviewData, GetBatchCallRecordPreviewError, GetBatchCallRecordPreviewErrors, GetBatchCallRecordPreviewRequest, GetBatchCallRecordPreviewResponse, GetBatchCallRecordPreviewResponse2, GetBatchCallRecordPreviewResponses, GetBatchChannelPreviewData, GetBatchChannelPreviewError, GetBatchChannelPreviewErrors, GetBatchChannelPreviewRequest, GetBatchChannelPreviewResponse, GetBatchChannelPreviewResponse2, GetBatchChannelPreviewResponses, GetBatchPreviewHandlerData, GetBatchPreviewHandlerError, GetBatchPreviewHandlerErrors, GetBatchPreviewHandlerResponse, GetBatchPreviewHandlerResponses, GetBatchPreviewRequest, GetBatchPreviewResponse, GetBatchProjectPreviewData, GetBatchProjectPreviewError, GetBatchProjectPreviewErrors, GetBatchProjectPreviewRequest, GetBatchProjectPreviewResponse, GetBatchProjectPreviewResponse2, GetBatchProjectPreviewResponses, GetCallRecordData, GetCallRecordError, GetCallRecordErrors, GetCallRecordResponse, GetCallRecordResponses, GetChannelAttachmentsData, GetChannelAttachmentsError, GetChannelAttachmentsErrors, GetChannelAttachmentsResponse, GetChannelAttachmentsResponses, GetChannelData, GetChannelError, GetChannelErrors, GetChannelJoinLinkData, GetChannelJoinLinkError, GetChannelJoinLinkErrors, GetChannelJoinLinkResponse, GetChannelJoinLinkResponses, GetChannelMessagesData, GetChannelMessagesError, GetChannelMessagesErrors, GetChannelMessagesResponse, GetChannelMessagesResponses, GetChannelParticipantsData, GetChannelParticipantsError, GetChannelParticipantsErrors, GetChannelParticipantsResponse, GetChannelParticipantsResponses, GetChannelResponse, GetChannelResponses, GetChannelsData, GetChannelsError, GetChannelsErrors, GetChannelsResponse, GetChannelsResponses, GetCompanyData, GetCompanyError, GetCompanyErrors, GetCompanyResponse, GetCompanyResponses, GetContactData, GetContactError, GetContactErrors, GetContactResponse, GetContactResponses, GetCrmTeamSettingsData, GetCrmTeamSettingsError, GetCrmTeamSettingsErrors, GetCrmTeamSettingsResponse, GetCrmTeamSettingsResponses, GetDocumentAnchorsData, GetDocumentAnchorsError, GetDocumentAnchorsErrors, GetDocumentAnchorsResponse, GetDocumentAnchorsResponses, GetDocumentBranchNameData, GetDocumentBranchNameError, GetDocumentBranchNameErrors, GetDocumentBranchNameResponse, GetDocumentBranchNameResponses, GetDocumentByTeamSlugData, GetDocumentByTeamSlugError, GetDocumentByTeamSlugErrors, GetDocumentByTeamSlugResponse, GetDocumentByTeamSlugResponses, GetDocumentCommentsData, GetDocumentCommentsError, GetDocumentCommentsErrors, GetDocumentCommentsResponse, GetDocumentCommentsResponses, GetDocumentData, GetDocumentError, GetDocumentErrors, GetDocumentGithubPullRequestsData, GetDocumentGithubPullRequestsError, GetDocumentGithubPullRequestsErrors, GetDocumentGithubPullRequestsResponse, GetDocumentGithubPullRequestsResponses, GetDocumentKeyResponse, GetDocumentKeyResponseData, GetDocumentListHandlerData, GetDocumentListHandlerError, GetDocumentListHandlerErrors, GetDocumentListHandlerResponse, GetDocumentListHandlerResponses, GetDocumentListResult, GetDocumentLocationV3Data, GetDocumentLocationV3Error, GetDocumentLocationV3Errors, GetDocumentLocationV3Response, GetDocumentLocationV3Responses, GetDocumentPermissionsResponseDataV2, GetDocumentPermissionsTokenData, GetDocumentPermissionsTokenError, GetDocumentPermissionsTokenErrors, GetDocumentPermissionsTokenResponse, GetDocumentPermissionsTokenResponses, GetDocumentPermissionsV2Data, GetDocumentPermissionsV2Error, GetDocumentPermissionsV2Errors, GetDocumentPermissionsV2Response, GetDocumentPermissionsV2Responses, GetDocumentProcessingResult, GetDocumentProcessingResultData, GetDocumentProcessingResultError, GetDocumentProcessingResultErrors, GetDocumentProcessingResultResponse, GetDocumentProcessingResultResponse2, GetDocumentProcessingResultResponses, GetDocumentResponse, GetDocumentResponse2, GetDocumentResponseData, GetDocumentResponses, GetDocumentSearchResponse, GetDocumentShortIdData, GetDocumentShortIdError, GetDocumentShortIdErrors, GetDocumentShortIdResponse, GetDocumentShortIdResponses, GetDocumentsResponse, GetDocumentTeamShareData, GetDocumentTeamShareError, GetDocumentTeamShareErrors, GetDocumentTeamShareResponse, GetDocumentTeamShareResponses, GetDocumentUserAccessLevelResponse, GetDocumentVersionData, GetDocumentVersionError, GetDocumentVersionErrors, GetDocumentVersionResponse, GetDocumentVersionResponses, GetDocumentViewsHandlerData, GetDocumentViewsHandlerError, GetDocumentViewsHandlerErrors, GetDocumentViewsHandlerResponse, GetDocumentViewsHandlerResponses, GetEntityPermissionData, GetEntityPermissionErrors, GetEntityPermissionResponse, GetEntityPermissionResponses, GetForeignEntityData, GetForeignEntityError, GetForeignEntityErrors, GetForeignEntityResponse, GetForeignEntityResponses, GetHistoryHandlerData, GetHistoryHandlerError, GetHistoryHandlerErrors, GetHistoryHandlerResponse, GetHistoryHandlerResponses, GetInstructionsDocumentResponse, GetInstructionsHandlerData, GetInstructionsHandlerError, GetInstructionsHandlerErrors, GetInstructionsHandlerResponse, GetInstructionsHandlerResponses, GetItemsSoupData, GetItemsSoupError, GetItemsSoupErrors, GetItemsSoupResponse, GetItemsSoupResponses, GetLocationHandlerData, GetLocationHandlerError, GetLocationHandlerErrors, GetLocationHandlerResponse, GetLocationHandlerResponses, GetMessageWithContextData, GetMessageWithContextError, GetMessageWithContextErrors, GetMessageWithContextResponse, GetMessageWithContextResponse2, GetMessageWithContextResponses, GetOrCreateAction, GetOrCreateCallData, GetOrCreateCallError, GetOrCreateCallErrors, GetOrCreateCallResponse, GetOrCreateCallResponses, GetOrCreateChannelResponse, GetOrCreateDmData, GetOrCreateDmError, GetOrCreateDmErrors, GetOrCreateDmRequest, GetOrCreateDmResponse, GetOrCreateDmResponses, GetOrCreatePrivateData, GetOrCreatePrivateError, GetOrCreatePrivateErrors, GetOrCreatePrivateRequest, GetOrCreatePrivateResponse, GetOrCreatePrivateResponses, GetPendingProjectsHandlerData, GetPendingProjectsHandlerError, GetPendingProjectsHandlerErrors, GetPendingProjectsHandlerResponse, GetPendingProjectsHandlerResponses, GetPinsHandlerData, GetPinsHandlerError, GetPinsHandlerErrors, GetPinsHandlerResponse, GetPinsHandlerResponses, GetPinsResponse, GetProjectContentHandlerData, GetProjectContentHandlerError, GetProjectContentHandlerErrors, GetProjectContentHandlerResponse, GetProjectContentHandlerResponses, GetProjectContentResponse, GetProjectHandlerData, GetProjectHandlerError, GetProjectHandlerErrors, GetProjectHandlerResponse, GetProjectHandlerResponses, GetProjectPermissionsV2Data, GetProjectPermissionsV2Error, GetProjectPermissionsV2Errors, GetProjectPermissionsV2Response, GetProjectPermissionsV2Responses, GetProjectResponse, GetProjectResponseData, GetProjectsHandlerData, GetProjectsHandlerError, GetProjectsHandlerErrors, GetProjectsHandlerResponse, GetProjectsHandlerResponses, GetProjectsResponse, GetProjectUserAccessLevelData, GetProjectUserAccessLevelError, GetProjectUserAccessLevelErrors, GetProjectUserAccessLevelResponse, GetProjectUserAccessLevelResponses, GetRecentActivityHandlerData, GetRecentActivityHandlerError, GetRecentActivityHandlerErrors, GetRecentActivityHandlerResponse, GetRecentActivityHandlerResponses, GetReminderData, GetReminderError, GetReminderErrors, GetReminderResponse, GetReminderResponses, GetRingStatusData, GetRingStatusError, GetRingStatusErrors, GetRingStatusResponse, GetRingStatusResponses, GetSelfBotData, GetSelfBotError, GetSelfBotErrors, GetSelfBotResponse, GetSelfBotResponses, GetThreadRepliesData, GetThreadRepliesError, GetThreadRepliesErrors, GetThreadRepliesResponse, GetThreadRepliesResponses, GetUserDocumentsHandlerData, GetUserDocumentsHandlerError, GetUserDocumentsHandlerErrors, GetUserDocumentsHandlerResponse, GetUserDocumentsHandlerResponses, GetUserDocumentViewLocationData, GetUserDocumentViewLocationError, GetUserDocumentViewLocationErrors, GetUserDocumentViewLocationResponse, GetUserDocumentViewLocationResponses, GetUserHistoryResponse, GetViewsHandlerData, GetViewsHandlerError, GetViewsHandlerErrors, GetViewsHandlerResponse, GetViewsHandlerResponses, GetWebhookData, GetWebhookError, GetWebhookErrors, GetWebhookResponse, GetWebhookResponses, GithubPullRequest, GithubPullRequestCheckRun, GithubPullRequestComment, GithubPullRequestsResponse, GroupedInitialParams, GroupedPageParams, GroupedSoupGroupPage, GroupedSoupInitialPage, GroupedSoupPage, GroupedSoupSort, HandlerData, HandlerError, HandlerErrors, HandlerResponse, HandlerResponses, HashMap, HealthHandlerData, HealthHandlerResponse, HealthHandlerResponses, HighlightType, IngestTranscriptData, IngestTranscriptError, IngestTranscriptErrors, IngestTranscriptResponses, InitializeUserDocumentsData, InitializeUserDocumentsError, InitializeUserDocumentsErrors, InitializeUserDocumentsResponse, InitializeUserDocumentsResponses, InstallSyncData, InstallSyncErrors, InteractionReason, Item, ItemWithUserAccessLevel, JobProcessingResultHandlerData, JobProcessingResultHandlerError, JobProcessingResultHandlerErrors, JobProcessingResultHandlerResponse, JobProcessingResultHandlerResponses, JoinChannelByCodeData, JoinChannelByCodeError, JoinChannelByCodeErrors, JoinChannelByCodeResponses, JoinChannelData, JoinChannelError, JoinChannelErrors, JoinChannelResponses, LatestMessage, LeaveCallResponse, LeaveChannelData, LeaveChannelError, LeaveChannelErrors, LeaveChannelResponses, LeaveOrEndCallData, LeaveOrEndCallError, LeaveOrEndCallErrors, LeaveOrEndCallResponse, LeaveOrEndCallResponses, ListBotChannelsData, ListBotChannelsError, ListBotChannelsErrors, ListBotChannelsResponse, ListBotChannelsResponses, ListCompanyContactsData, ListCompanyContactsError, ListCompanyContactsErrors, ListCompanyContactsResponse, ListCompanyContactsResponses, ListCrmCommentsData, ListCrmCommentsError, ListCrmCommentsErrors, ListCrmCommentsResponse, ListCrmCommentsResponses, ListFavoritesData, ListFavoritesError, ListFavoritesErrors, ListFavoritesResponse, ListFavoritesResponses, ListOccurrencesData, ListOccurrencesErrors, ListOccurrencesResponse, ListOccurrencesResponses, ListRemindersData, ListRemindersError, ListRemindersErrors, ListRemindersResponse, ListRemindersResponses, ListWebhooksData, ListWebhooksError, ListWebhooksErrors, ListWebhooksResponse, ListWebhooksResponse2, ListWebhooksResponses, LocationResponseData, LocationResponseV3, MacroUserIdStr, Mentions, NewChannelAttachment, NotificationFilters, Params, ParticipantRole, PatchChannelData, PatchChannelError, PatchChannelErrors, PatchChannelRequest, PatchChannelResponse, PatchChannelResponses, PatchMessageData, PatchMessageError, PatchMessageErrors, PatchMessageRequest, PatchMessageResponse, PatchMessageResponses, PatchProjectRequestV2, PatchThreadRequestV2, PatchViewHandlerData, PatchViewHandlerError, PatchViewHandlerErrors, PatchViewHandlerResponses, PatchWebhookData, PatchWebhookError, PatchWebhookErrors, PatchWebhookRequest, PatchWebhookResponse, PatchWebhookResponses, PdfAnchor, PdfAnchorId, PdfAnchorRequest, PdfHighlightAnchor, PdfHighlightAnchorRequest, PdfHighlightRect, PdfHighlightRectAnchorRequest, PdfPlaceableCommentAnchor, PdfPlaceableCommentAnchorRequest, PermanentlyDeleteDocumentData, PermanentlyDeleteDocumentError, PermanentlyDeleteDocumentErrors, PermanentlyDeleteDocumentResponse, PermanentlyDeleteDocumentResponses, PermanentlyDeleteProjectData, PermanentlyDeleteProjectError, PermanentlyDeleteProjectErrors, PermanentlyDeleteProjectResponse, PermanentlyDeleteProjectResponses, PinnedItem, PinRequest, PostActivityData, PostActivityError, PostActivityErrors, PostActivityRequest, PostActivityResponse, PostActivityResponses, PostChannelBotWebhookData, PostChannelBotWebhookError, PostChannelBotWebhookErrors, PostChannelBotWebhookResponse, PostChannelBotWebhookResponses, PostChannelMessagesData, PostChannelMessagesError, PostChannelMessagesErrors, PostChannelMessagesResponse, PostChannelMessagesResponses, PostGroupedSoupAstGroupPageRequest, PostGroupedSoupAstInitialRequest, PostGroupedSoupAstRequest, PostItemsSoupAstData, PostItemsSoupAstError, PostItemsSoupAstErrors, PostItemsSoupAstGroupedData, PostItemsSoupAstGroupedError, PostItemsSoupAstGroupedErrors, PostItemsSoupAstGroupedResponse, PostItemsSoupAstGroupedResponses, PostItemsSoupAstResponse, PostItemsSoupAstResponses, PostItemsSoupData, PostItemsSoupError, PostItemsSoupErrors, PostItemsSoupResponse, PostItemsSoupResponses, PostMessageData, PostMessageError, PostMessageErrors, PostMessageRequest, PostMessageResponse, PostMessageResponse2, PostMessageResponses, PostReactionData, PostReactionError, PostReactionErrors, PostReactionRequest, PostReactionResponse, PostReactionResponses, PostSoupAstRequest, PostSoupRequest, PostTypingData, PostTypingError, PostTypingErrors, PostTypingRequest, PostTypingResponse, PostTypingResponses, PresaveDocumentHandlerData, PresaveDocumentHandlerError, PresaveDocumentHandlerErrors, PresaveDocumentHandlerResponse, PresaveDocumentHandlerResponses, PreSaveDocumentRequest, PreSaveDocumentResponse, PreSaveDocumentResponseData, PresignedUrl, Project, ProjectDeleteResponseData, ProjectDocumentStatus, ProjectFilters, ProjectPreview, ProjectPreviewData, PropertyDefinition, PropertyFilter, PropertyInput, PropertyOwner, PropertyValue, PutCrmTeamSettingsData, PutCrmTeamSettingsError, PutCrmTeamSettingsErrors, PutCrmTeamSettingsResponse, PutCrmTeamSettingsResponses, ReactionAction, RecentlyDeletedData, RecentlyDeletedError, RecentlyDeletedErrors, RecentlyDeletedResponse, RecentlyDeletedResponseData, RecentlyDeletedResponses, Reminder, ReminderSchedule, RemindersList, RemoveBotFromChannelByBotData, RemoveBotFromChannelByBotError, RemoveBotFromChannelByBotErrors, RemoveBotFromChannelByBotResponse, RemoveBotFromChannelByBotResponses, RemoveFavoriteByEntityData, RemoveFavoriteByEntityError, RemoveFavoriteByEntityErrors, RemoveFavoriteByEntityResponses, RemoveParticipantsData, RemoveParticipantsError, RemoveParticipantsErrors, RemoveParticipantsRequest, RemoveParticipantsResponses, RemovePinHandlerData, RemovePinHandlerError, RemovePinHandlerErrors, RemovePinHandlerResponse, RemovePinHandlerResponses, ReorderFavoritesData, ReorderFavoritesError, ReorderFavoritesErrors, ReorderFavoritesRequest, ReorderFavoritesResponses, ReorderPinRequest, ReorderPinsHandlerData, ReorderPinsHandlerError, ReorderPinsHandlerErrors, ReorderPinsHandlerResponse, ReorderPinsHandlerResponses, ResolveChannelMessageData, ResolveChannelMessageError, ResolveChannelMessageErrors, ResolveChannelMessageResponse, ResolveChannelMessageResponses, RevertDeleteDocumentData, RevertDeleteDocumentError, RevertDeleteDocumentErrors, RevertDeleteDocumentResponse, RevertDeleteDocumentResponses, RevertDeleteProjectData, RevertDeleteProjectError, RevertDeleteProjectErrors, RevertDeleteProjectResponse, RevertDeleteProjectResponses, RingStatus, RingStatusResponse, S3ObjectInfo, SaveBomPart, SaveDocumentHandlerData, SaveDocumentHandlerError, SaveDocumentHandlerErrors, SaveDocumentHandlerResponse, SaveDocumentHandlerResponses, SaveDocumentRequest, SaveDocumentResponse, SaveDocumentResponseData, SetCompanyHiddenData, SetCompanyHiddenError, SetCompanyHiddenErrors, SetCompanyHiddenRequest, SetCompanyHiddenResponse, SetCompanyHiddenResponses, SetCompanyNameRequest, SetContactHiddenData, SetContactHiddenError, SetContactHiddenErrors, SetContactHiddenRequest, SetContactHiddenResponse, SetContactHiddenResponses, SetContactNameRequest, SetCrmCompanyNameData, SetCrmCompanyNameError, SetCrmCompanyNameErrors, SetCrmCompanyNameResponse, SetCrmCompanyNameResponses, SetCrmContactNameData, SetCrmContactNameError, SetCrmContactNameErrors, SetCrmContactNameResponse, SetCrmContactNameResponses, SetDocumentTeamShareData, SetDocumentTeamShareError, SetDocumentTeamShareErrors, SetDocumentTeamShareRequest, SetDocumentTeamShareResponse, SetDocumentTeamShareResponses, SetEmailSyncData, SetEmailSyncError, SetEmailSyncErrors, SetEmailSyncRequest, SetEmailSyncResponse, SetEmailSyncResponses, SetPropertyValue, SharedEmailFilter, SharePermissionV2, ShortIdResponse, SimpleMention, SimpleSaveData, SimpleSaveError, SimpleSaveErrors, SimpleSaveResponse, SimpleSaveResponses, SoupApiItem, SoupApiSort, SoupAttachment, SoupCalendarEventSoupPropertiesField, SoupCalendarEventTime, SoupCallRecordParticipant, SoupCallRecordSoupPropertiesField, SoupChannel, SoupChannelThread, SoupChatSoupPropertiesField, SoupContact, SoupCountedReaction, SoupCrmCompanySoupPropertiesField, SoupCrmDomain, SoupDocumentSoupPropertiesField, SoupDocumentSubType, SoupEmailThreadPreview, SoupEnrichedEmailThreadPreviewSoupPropertiesField, SoupForeignEntity, SoupItem, SoupLabel, SoupLabelListVisibility, SoupLabelType, SoupMessageAttachment, SoupMessageListVisibility, SoupMessageSender, SoupMessageSenderType, SoupPage, SoupProjectSoupPropertiesField, SoupPropertiesField, SoupProperty, SoupThreadInfo, SoupThreadReply, StarterDocumentsResponse, String, SuccessResponse, SyncServiceVersionId, TagFilterMode, TaskFilters, TeamRole, Thread, ThreadResponse, ToggleShareWithTeamData, ToggleShareWithTeamError, ToggleShareWithTeamErrors, ToggleShareWithTeamResponse, ToggleShareWithTeamResponses, TranscriptSegmentRequest, TypedSuccessResponse, TypedSuccessResponseGetDocumentResponseData, TypingAction, UnthreadedPdfUuidRequest, UpdateChannelSharePermission, UpdateCrmTeamSettingsRequest, UpdateOperation, UpdateReminderData, UpdateReminderError, UpdateReminderErrors, UpdateReminderRequest, UpdateReminderResponse, UpdateReminderResponses, UpdateSharePermissionRequestV2, UploadDocumentStatus, UploadExtractFolderHandlerData, UploadExtractFolderHandlerError, UploadExtractFolderHandlerErrors, UploadExtractFolderHandlerResponse, UploadExtractFolderHandlerResponses, UploadExtractFolderRequest, UploadFolderHandlerData, UploadFolderHandlerError, UploadFolderHandlerErrors, UploadFolderHandlerResponse, UploadFolderHandlerResponses, UploadFolderRequest, UpsertHistoryHandlerData, UpsertHistoryHandlerError, UpsertHistoryHandlerErrors, UpsertHistoryHandlerResponse, UpsertHistoryHandlerResponses, UpsertUserDocumentViewLocationData, UpsertUserDocumentViewLocationError, UpsertUserDocumentViewLocationErrors, UpsertUserDocumentViewLocationRequest, UpsertUserDocumentViewLocationResponse, UpsertUserDocumentViewLocationResponses, UserActivitiesResponse, UserDocumentsResponse, UserDocumentViewLocation, UserDocumentViewLocationResponse, UserPinsResponse, UserViewsResponse, ValidateDocumentPermissionsTokenData, ValidateDocumentPermissionsTokenError, ValidateDocumentPermissionsTokenErrors, ValidateDocumentPermissionsTokenResponse, ValidateDocumentPermissionsTokenResponses, ValidateWebhookData, ValidateWebhookError, ValidateWebhookErrors, ValidateWebhookResponse, ValidateWebhookResponse2, ValidateWebhookResponses, Vec, View, ViewPatch, ViewsResponse, Webhook, WebhookEvent, WebhookFilter, WebhookScope, WebhookStatus, WebhookValidationTestEvent, WithCallId, WithChannelId, WithDocumentId, WithProjectId } from './types.gen';diff --git a/packages/sdk/generated/storage/sdk.gen.ts b/packages/sdk/generated/storage/sdk.gen.tsindex 431bd3c741..cf8dee5565 100644--- a/packages/sdk/generated/storage/sdk.gen.ts+++ b/packages/sdk/generated/storage/sdk.gen.ts@@ -2,7 +2,7 @@import type { Client, ClientMeta, Options as Options2, RequestResult, TDataShape } from './client';import { client } from './client.gen';-import type { AddFavoriteData, AddFavoriteErrors, AddFavoriteResponses, AddParticipantsData, AddParticipantsErrors, AddParticipantsResponses, AddPinHandlerData, AddPinHandlerErrors, AddPinHandlerResponses, BulkWakeupSyncServiceDocumentsData, BulkWakeupSyncServiceDocumentsErrors, BulkWakeupSyncServiceDocumentsResponses, CallWebhookData, CallWebhookErrors, CallWebhookResponses, CheckActiveCallData, CheckActiveCallErrors, CheckActiveCallResponses, CopyDocumentData, CopyDocumentErrors, CopyDocumentResponses, CreateAnchorData, CreateAnchorErrors, CreateAnchorResponses, CreateChannelData, CreateChannelErrors, CreateChannelResponses, CreateChannelScopedBotData, CreateChannelScopedBotErrors, CreateChannelScopedBotResponses, CreateCommentData, CreateCommentErrors, CreateCommentResponses, CreateCrmCommentData, CreateCrmCommentErrors, CreateCrmCommentResponses, CreateCrmCompanyData, CreateCrmCompanyErrors, CreateCrmCompanyResponses, CreateCrmContactData, CreateCrmContactErrors, CreateCrmContactResponses, CreateDocumentData, CreateDocumentErrors, CreateDocumentResponses, CreateEntityMentionData, CreateEntityMentionErrors, CreateEntityMentionResponses, CreateInstructionsHandlerData, CreateInstructionsHandlerErrors, CreateInstructionsHandlerResponses, CreateMarkdownHandlerData, CreateMarkdownHandlerErrors, CreateMarkdownHandlerResponses, CreateProjectHandlerData, CreateProjectHandlerErrors, CreateProjectHandlerResponses, CreateSnippetHandlerData, CreateSnippetHandlerErrors, CreateSnippetHandlerResponses, CreateTaskHandlerData, CreateTaskHandlerErrors, CreateTaskHandlerResponses, CreateViewHandlerData, CreateViewHandlerErrors, CreateViewHandlerResponses, CreateWebhookData, CreateWebhookErrors, CreateWebhookResponses, DeleteAnchorData, DeleteAnchorErrors, DeleteAnchorResponses, DeleteCallRecordData, DeleteCallRecordErrors, DeleteCallRecordResponses, DeleteChannelData, DeleteChannelErrors, DeleteChannelResponses, DeleteCommentData, DeleteCommentErrors, DeleteCommentResponses, DeleteCrmCommentData, DeleteCrmCommentErrors, DeleteCrmCommentResponses, DeleteDocumentData, DeleteDocumentErrors, DeleteDocumentResponses, DeleteEntityMentionData, DeleteEntityMentionErrors, DeleteEntityMentionResponses, DeleteHistoryHandlerData, DeleteHistoryHandlerErrors, DeleteHistoryHandlerResponses, DeleteMessageData, DeleteMessageErrors, DeleteMessageResponses, DeleteProjectHandlerData, DeleteProjectHandlerErrors, DeleteProjectHandlerResponses, DeleteUserDocumentViewLocationData, DeleteUserDocumentViewLocationErrors, DeleteUserDocumentViewLocationResponses, DeleteViewHandlerData, DeleteViewHandlerErrors, DeleteViewHandlerResponses, DeleteWebhookData, DeleteWebhookErrors, DeleteWebhookResponses, EditAnchorData, EditAnchorErrors, EditAnchorResponses, EditCallRecordData, EditCallRecordErrors, EditCallRecordResponses, EditCallTranscriptData, EditCallTranscriptErrors, EditCallTranscriptResponses, EditCommentData, EditCommentErrors, EditCommentResponses, EditCrmCommentData, EditCrmCommentErrors, EditCrmCommentResponses, EditDocumentData, EditDocumentErrors, EditDocumentResponses, EditProjectV2Data, EditProjectV2Errors, EditProjectV2Responses, EditThreadV2Data, EditThreadV2Errors, EditThreadV2Responses, ExcludeDefaultViewHandlerData, ExcludeDefaultViewHandlerErrors, ExcludeDefaultViewHandlerResponses, ExportDocumentData, ExportDocumentErrors, ExportDocumentResponses, GetActivityData, GetActivityErrors, GetActivityResponses, GetAttachmentReferencesData, GetAttachmentReferencesErrors, GetAttachmentReferencesResponses, GetBatchCallRecordPreviewData, GetBatchCallRecordPreviewErrors, GetBatchCallRecordPreviewResponses, GetBatchChannelPreviewData, GetBatchChannelPreviewErrors, GetBatchChannelPreviewResponses, GetBatchPreviewHandlerData, GetBatchPreviewHandlerErrors, GetBatchPreviewHandlerResponses, GetBatchProjectPreviewData, GetBatchProjectPreviewErrors, GetBatchProjectPreviewResponses, GetCallRecordData, GetCallRecordErrors, GetCallRecordResponses, GetChannelAttachmentsData, GetChannelAttachmentsErrors, GetChannelAttachmentsResponses, GetChannelData, GetChannelErrors, GetChannelJoinLinkData, GetChannelJoinLinkErrors, GetChannelJoinLinkResponses, GetChannelMessagesData, GetChannelMessagesErrors, GetChannelMessagesResponses, GetChannelParticipantsData, GetChannelParticipantsErrors, GetChannelParticipantsResponses, GetChannelResponses, GetChannelsData, GetChannelsErrors, GetChannelsResponses, GetCompanyData, GetCompanyErrors, GetCompanyResponses, GetContactData, GetContactErrors, GetContactResponses, GetCrmTeamSettingsData, GetCrmTeamSettingsErrors, GetCrmTeamSettingsResponses, GetDocumentAnchorsData, GetDocumentAnchorsErrors, GetDocumentAnchorsResponses, GetDocumentBranchNameData, GetDocumentBranchNameErrors, GetDocumentBranchNameResponses, GetDocumentByTeamSlugData, GetDocumentByTeamSlugErrors, GetDocumentByTeamSlugResponses, GetDocumentCommentsData, GetDocumentCommentsErrors, GetDocumentCommentsResponses, GetDocumentData, GetDocumentErrors, GetDocumentGithubPullRequestsData, GetDocumentGithubPullRequestsErrors, GetDocumentGithubPullRequestsResponses, GetDocumentListHandlerData, GetDocumentListHandlerErrors, GetDocumentListHandlerResponses, GetDocumentLocationV3Data, GetDocumentLocationV3Errors, GetDocumentLocationV3Responses, GetDocumentPermissionsTokenData, GetDocumentPermissionsTokenErrors, GetDocumentPermissionsTokenResponses, GetDocumentPermissionsV2Data, GetDocumentPermissionsV2Errors, GetDocumentPermissionsV2Responses, GetDocumentProcessingResultData, GetDocumentProcessingResultErrors, GetDocumentProcessingResultResponses, GetDocumentResponses, GetDocumentShortIdData, GetDocumentShortIdErrors, GetDocumentShortIdResponses, GetDocumentTeamShareData, GetDocumentTeamShareErrors, GetDocumentTeamShareResponses, GetDocumentVersionData, GetDocumentVersionErrors, GetDocumentVersionResponses, GetDocumentViewsHandlerData, GetDocumentViewsHandlerErrors, GetDocumentViewsHandlerResponses, GetEntityPermissionData, GetEntityPermissionErrors, GetEntityPermissionResponses, GetForeignEntityData, GetForeignEntityErrors, GetForeignEntityResponses, GetHistoryHandlerData, GetHistoryHandlerErrors, GetHistoryHandlerResponses, GetInstructionsHandlerData, GetInstructionsHandlerErrors, GetInstructionsHandlerResponses, GetItemsSoupData, GetItemsSoupErrors, GetItemsSoupResponses, GetLocationHandlerData, GetLocationHandlerErrors, GetLocationHandlerResponses, GetMessageWithContextData, GetMessageWithContextErrors, GetMessageWithContextResponses, GetOrCreateCallData, GetOrCreateCallErrors, GetOrCreateCallResponses, GetOrCreateDmData, GetOrCreateDmErrors, GetOrCreateDmResponses, GetOrCreatePrivateData, GetOrCreatePrivateErrors, GetOrCreatePrivateResponses, GetPendingProjectsHandlerData, GetPendingProjectsHandlerErrors, GetPendingProjectsHandlerResponses, GetPinsHandlerData, GetPinsHandlerErrors, GetPinsHandlerResponses, GetProjectContentHandlerData, GetProjectContentHandlerErrors, GetProjectContentHandlerResponses, GetProjectHandlerData, GetProjectHandlerErrors, GetProjectHandlerResponses, GetProjectPermissionsV2Data, GetProjectPermissionsV2Errors, GetProjectPermissionsV2Responses, GetProjectsHandlerData, GetProjectsHandlerErrors, GetProjectsHandlerResponses, GetProjectUserAccessLevelData, GetProjectUserAccessLevelErrors, GetProjectUserAccessLevelResponses, GetRecentActivityHandlerData, GetRecentActivityHandlerErrors, GetRecentActivityHandlerResponses, GetRingStatusData, GetRingStatusErrors, GetRingStatusResponses, GetSelfBotData, GetSelfBotErrors, GetSelfBotResponses, GetThreadRepliesData, GetThreadRepliesErrors, GetThreadRepliesResponses, GetUserDocumentsHandlerData, GetUserDocumentsHandlerErrors, GetUserDocumentsHandlerResponses, GetUserDocumentViewLocationData, GetUserDocumentViewLocationErrors, GetUserDocumentViewLocationResponses, GetViewsHandlerData, GetViewsHandlerErrors, GetViewsHandlerResponses, GetWebhookData, GetWebhookErrors, GetWebhookResponses, HandlerData, HandlerErrors, HandlerResponses, HealthHandlerData, HealthHandlerResponses, IngestTranscriptData, IngestTranscriptErrors, IngestTranscriptResponses, InitializeUserDocumentsData, InitializeUserDocumentsErrors, InitializeUserDocumentsResponses, InstallSyncData, InstallSyncErrors, JobProcessingResultHandlerData, JobProcessingResultHandlerErrors, JobProcessingResultHandlerResponses, JoinChannelByCodeData, JoinChannelByCodeErrors, JoinChannelByCodeResponses, JoinChannelData, JoinChannelErrors, JoinChannelResponses, LeaveChannelData, LeaveChannelErrors, LeaveChannelResponses, LeaveOrEndCallData, LeaveOrEndCallErrors, LeaveOrEndCallResponses, ListBotChannelsData, ListBotChannelsErrors, ListBotChannelsResponses, ListCompanyContactsData, ListCompanyContactsErrors, ListCompanyContactsResponses, ListCrmCommentsData, ListCrmCommentsErrors, ListCrmCommentsResponses, ListFavoritesData, ListFavoritesErrors, ListFavoritesResponses, ListOccurrencesData, ListOccurrencesErrors, ListOccurrencesResponses, ListWebhooksData, ListWebhooksErrors, ListWebhooksResponses, PatchChannelData, PatchChannelErrors, PatchChannelResponses, PatchMessageData, PatchMessageErrors, PatchMessageResponses, PatchViewHandlerData, PatchViewHandlerErrors, PatchViewHandlerResponses, PatchWebhookData, PatchWebhookErrors, PatchWebhookResponses, PermanentlyDeleteDocumentData, PermanentlyDeleteDocumentErrors, PermanentlyDeleteDocumentResponses, PermanentlyDeleteProjectData, PermanentlyDeleteProjectErrors, PermanentlyDeleteProjectResponses, PostActivityData, PostActivityErrors, PostActivityResponses, PostChannelBotWebhookData, PostChannelBotWebhookErrors, PostChannelBotWebhookResponses, PostChannelMessagesData, PostChannelMessagesErrors, PostChannelMessagesResponses, PostItemsSoupAstData, PostItemsSoupAstErrors, PostItemsSoupAstGroupedData, PostItemsSoupAstGroupedErrors, PostItemsSoupAstGroupedResponses, PostItemsSoupAstResponses, PostItemsSoupData, PostItemsSoupErrors, PostItemsSoupResponses, PostMessageData, PostMessageErrors, PostMessageResponses, PostReactionData, PostReactionErrors, PostReactionResponses, PostTypingData, PostTypingErrors, PostTypingResponses, PresaveDocumentHandlerData, PresaveDocumentHandlerErrors, PresaveDocumentHandlerResponses, PutCrmTeamSettingsData, PutCrmTeamSettingsErrors, PutCrmTeamSettingsResponses, RecentlyDeletedData, RecentlyDeletedErrors, RecentlyDeletedResponses, RemoveBotFromChannelByBotData, RemoveBotFromChannelByBotErrors, RemoveBotFromChannelByBotResponses, RemoveFavoriteByEntityData, RemoveFavoriteByEntityErrors, RemoveFavoriteByEntityResponses, RemoveParticipantsData, RemoveParticipantsErrors, RemoveParticipantsResponses, RemovePinHandlerData, RemovePinHandlerErrors, RemovePinHandlerResponses, ReorderFavoritesData, ReorderFavoritesErrors, ReorderFavoritesResponses, ReorderPinsHandlerData, ReorderPinsHandlerErrors, ReorderPinsHandlerResponses, ResolveChannelMessageData, ResolveChannelMessageErrors, ResolveChannelMessageResponses, RevertDeleteDocumentData, RevertDeleteDocumentErrors, RevertDeleteDocumentResponses, RevertDeleteProjectData, RevertDeleteProjectErrors, RevertDeleteProjectResponses, SaveDocumentHandlerData, SaveDocumentHandlerErrors, SaveDocumentHandlerResponses, SetCompanyHiddenData, SetCompanyHiddenErrors, SetCompanyHiddenResponses, SetContactHiddenData, SetContactHiddenErrors, SetContactHiddenResponses, SetCrmCompanyNameData, SetCrmCompanyNameErrors, SetCrmCompanyNameResponses, SetCrmContactNameData, SetCrmContactNameErrors, SetCrmContactNameResponses, SetDocumentTeamShareData, SetDocumentTeamShareErrors, SetDocumentTeamShareResponses, SetEmailSyncData, SetEmailSyncErrors, SetEmailSyncResponses, SimpleSaveData, SimpleSaveErrors, SimpleSaveResponses, ToggleShareWithTeamData, ToggleShareWithTeamErrors, ToggleShareWithTeamResponses, UploadExtractFolderHandlerData, UploadExtractFolderHandlerErrors, UploadExtractFolderHandlerResponses, UploadFolderHandlerData, UploadFolderHandlerErrors, UploadFolderHandlerResponses, UpsertHistoryHandlerData, UpsertHistoryHandlerErrors, UpsertHistoryHandlerResponses, UpsertUserDocumentViewLocationData, UpsertUserDocumentViewLocationErrors, UpsertUserDocumentViewLocationResponses, ValidateDocumentPermissionsTokenData, ValidateDocumentPermissionsTokenErrors, ValidateDocumentPermissionsTokenResponses, ValidateWebhookData, ValidateWebhookErrors, ValidateWebhookResponses } from './types.gen';+import type { AddFavoriteData, AddFavoriteErrors, AddFavoriteResponses, AddParticipantsData, AddParticipantsErrors, AddParticipantsResponses, AddPinHandlerData, AddPinHandlerErrors, AddPinHandlerResponses, BulkWakeupSyncServiceDocumentsData, BulkWakeupSyncServiceDocumentsErrors, BulkWakeupSyncServiceDocumentsResponses, CallWebhookData, CallWebhookErrors, CallWebhookResponses, CheckActiveCallData, CheckActiveCallErrors, CheckActiveCallResponses, CopyDocumentData, CopyDocumentErrors, CopyDocumentResponses, CreateAnchorData, CreateAnchorErrors, CreateAnchorResponses, CreateChannelData, CreateChannelErrors, CreateChannelResponses, CreateChannelScopedBotData, CreateChannelScopedBotErrors, CreateChannelScopedBotResponses, CreateCommentData, CreateCommentErrors, CreateCommentResponses, CreateCrmCommentData, CreateCrmCommentErrors, CreateCrmCommentResponses, CreateCrmCompanyData, CreateCrmCompanyErrors, CreateCrmCompanyResponses, CreateCrmContactData, CreateCrmContactErrors, CreateCrmContactResponses, CreateDocumentData, CreateDocumentErrors, CreateDocumentResponses, CreateEntityMentionData, CreateEntityMentionErrors, CreateEntityMentionResponses, CreateInstructionsHandlerData, CreateInstructionsHandlerErrors, CreateInstructionsHandlerResponses, CreateMarkdownHandlerData, CreateMarkdownHandlerErrors, CreateMarkdownHandlerResponses, CreateProjectHandlerData, CreateProjectHandlerErrors, CreateProjectHandlerResponses, CreateReminderData, CreateReminderErrors, CreateReminderResponses, CreateSnippetHandlerData, CreateSnippetHandlerErrors, CreateSnippetHandlerResponses, CreateTaskHandlerData, CreateTaskHandlerErrors, CreateTaskHandlerResponses, CreateViewHandlerData, CreateViewHandlerErrors, CreateViewHandlerResponses, CreateWebhookData, CreateWebhookErrors, CreateWebhookResponses, DeleteAnchorData, DeleteAnchorErrors, DeleteAnchorResponses, DeleteCallRecordData, DeleteCallRecordErrors, DeleteCallRecordResponses, DeleteChannelData, DeleteChannelErrors, DeleteChannelResponses, DeleteCommentData, DeleteCommentErrors, DeleteCommentResponses, DeleteCrmCommentData, DeleteCrmCommentErrors, DeleteCrmCommentResponses, DeleteDocumentData, DeleteDocumentErrors, DeleteDocumentResponses, DeleteEntityMentionData, DeleteEntityMentionErrors, DeleteEntityMentionResponses, DeleteHistoryHandlerData, DeleteHistoryHandlerErrors, DeleteHistoryHandlerResponses, DeleteMessageData, DeleteMessageErrors, DeleteMessageResponses, DeleteProjectHandlerData, DeleteProjectHandlerErrors, DeleteProjectHandlerResponses, DeleteReminderData, DeleteReminderErrors, DeleteReminderResponses, DeleteUserDocumentViewLocationData, DeleteUserDocumentViewLocationErrors, DeleteUserDocumentViewLocationResponses, DeleteViewHandlerData, DeleteViewHandlerErrors, DeleteViewHandlerResponses, DeleteWebhookData, DeleteWebhookErrors, DeleteWebhookResponses, EditAnchorData, EditAnchorErrors, EditAnchorResponses, EditCallRecordData, EditCallRecordErrors, EditCallRecordResponses, EditCallTranscriptData, EditCallTranscriptErrors, EditCallTranscriptResponses, EditCommentData, EditCommentErrors, EditCommentResponses, EditCrmCommentData, EditCrmCommentErrors, EditCrmCommentResponses, EditDocumentData, EditDocumentErrors, EditDocumentResponses, EditProjectV2Data, EditProjectV2Errors, EditProjectV2Responses, EditThreadV2Data, EditThreadV2Errors, EditThreadV2Responses, ExcludeDefaultViewHandlerData, ExcludeDefaultViewHandlerErrors, ExcludeDefaultViewHandlerResponses, ExportDocumentData, ExportDocumentErrors, ExportDocumentResponses, GetActivityData, GetActivityErrors, GetActivityResponses, GetAttachmentReferencesData, GetAttachmentReferencesErrors, GetAttachmentReferencesResponses, GetBatchCallRecordPreviewData, GetBatchCallRecordPreviewErrors, GetBatchCallRecordPreviewResponses, GetBatchChannelPreviewData, GetBatchChannelPreviewErrors, GetBatchChannelPreviewResponses, GetBatchPreviewHandlerData, GetBatchPreviewHandlerErrors, GetBatchPreviewHandlerResponses, GetBatchProjectPreviewData, GetBatchProjectPreviewErrors, GetBatchProjectPreviewResponses, GetCallRecordData, GetCallRecordErrors, GetCallRecordResponses, GetChannelAttachmentsData, GetChannelAttachmentsErrors, GetChannelAttachmentsResponses, GetChannelData, GetChannelErrors, GetChannelJoinLinkData, GetChannelJoinLinkErrors, GetChannelJoinLinkResponses, GetChannelMessagesData, GetChannelMessagesErrors, GetChannelMessagesResponses, GetChannelParticipantsData, GetChannelParticipantsErrors, GetChannelParticipantsResponses, GetChannelResponses, GetChannelsData, GetChannelsErrors, GetChannelsResponses, GetCompanyData, GetCompanyErrors, GetCompanyResponses, GetContactData, GetContactErrors, GetContactResponses, GetCrmTeamSettingsData, GetCrmTeamSettingsErrors, GetCrmTeamSettingsResponses, GetDocumentAnchorsData, GetDocumentAnchorsErrors, GetDocumentAnchorsResponses, GetDocumentBranchNameData, GetDocumentBranchNameErrors, GetDocumentBranchNameResponses, GetDocumentByTeamSlugData, GetDocumentByTeamSlugErrors, GetDocumentByTeamSlugResponses, GetDocumentCommentsData, GetDocumentCommentsErrors, GetDocumentCommentsResponses, GetDocumentData, GetDocumentErrors, GetDocumentGithubPullRequestsData, GetDocumentGithubPullRequestsErrors, GetDocumentGithubPullRequestsResponses, GetDocumentListHandlerData, GetDocumentListHandlerErrors, GetDocumentListHandlerResponses, GetDocumentLocationV3Data, GetDocumentLocationV3Errors, GetDocumentLocationV3Responses, GetDocumentPermissionsTokenData, GetDocumentPermissionsTokenErrors, GetDocumentPermissionsTokenResponses, GetDocumentPermissionsV2Data, GetDocumentPermissionsV2Errors, GetDocumentPermissionsV2Responses, GetDocumentProcessingResultData, GetDocumentProcessingResultErrors, GetDocumentProcessingResultResponses, GetDocumentResponses, GetDocumentShortIdData, GetDocumentShortIdErrors, GetDocumentShortIdResponses, GetDocumentTeamShareData, GetDocumentTeamShareErrors, GetDocumentTeamShareResponses, GetDocumentVersionData, GetDocumentVersionErrors, GetDocumentVersionResponses, GetDocumentViewsHandlerData, GetDocumentViewsHandlerErrors, GetDocumentViewsHandlerResponses, GetEntityPermissionData, GetEntityPermissionErrors, GetEntityPermissionResponses, GetForeignEntityData, GetForeignEntityErrors, GetForeignEntityResponses, GetHistoryHandlerData, GetHistoryHandlerErrors, GetHistoryHandlerResponses, GetInstructionsHandlerData, GetInstructionsHandlerErrors, GetInstructionsHandlerResponses, GetItemsSoupData, GetItemsSoupErrors, GetItemsSoupResponses, GetLocationHandlerData, GetLocationHandlerErrors, GetLocationHandlerResponses, GetMessageWithContextData, GetMessageWithContextErrors, GetMessageWithContextResponses, GetOrCreateCallData, GetOrCreateCallErrors, GetOrCreateCallResponses, GetOrCreateDmData, GetOrCreateDmErrors, GetOrCreateDmResponses, GetOrCreatePrivateData, GetOrCreatePrivateErrors, GetOrCreatePrivateResponses, GetPendingProjectsHandlerData, GetPendingProjectsHandlerErrors, GetPendingProjectsHandlerResponses, GetPinsHandlerData, GetPinsHandlerErrors, GetPinsHandlerResponses, GetProjectContentHandlerData, GetProjectContentHandlerErrors, GetProjectContentHandlerResponses, GetProjectHandlerData, GetProjectHandlerErrors, GetProjectHandlerResponses, GetProjectPermissionsV2Data, GetProjectPermissionsV2Errors, GetProjectPermissionsV2Responses, GetProjectsHandlerData, GetProjectsHandlerErrors, GetProjectsHandlerResponses, GetProjectUserAccessLevelData, GetProjectUserAccessLevelErrors, GetProjectUserAccessLevelResponses, GetRecentActivityHandlerData, GetRecentActivityHandlerErrors, GetRecentActivityHandlerResponses, GetReminderData, GetReminderErrors, GetReminderResponses, GetRingStatusData, GetRingStatusErrors, GetRingStatusResponses, GetSelfBotData, GetSelfBotErrors, GetSelfBotResponses, GetThreadRepliesData, GetThreadRepliesErrors, GetThreadRepliesResponses, GetUserDocumentsHandlerData, GetUserDocumentsHandlerErrors, GetUserDocumentsHandlerResponses, GetUserDocumentViewLocationData, GetUserDocumentViewLocationErrors, GetUserDocumentViewLocationResponses, GetViewsHandlerData, GetViewsHandlerErrors, GetViewsHandlerResponses, GetWebhookData, GetWebhookErrors, GetWebhookResponses, HandlerData, HandlerErrors, HandlerResponses, HealthHandlerData, HealthHandlerResponses, IngestTranscriptData, IngestTranscriptErrors, IngestTranscriptResponses, InitializeUserDocumentsData, InitializeUserDocumentsErrors, InitializeUserDocumentsResponses, InstallSyncData, InstallSyncErrors, JobProcessingResultHandlerData, JobProcessingResultHandlerErrors, JobProcessingResultHandlerResponses, JoinChannelByCodeData, JoinChannelByCodeErrors, JoinChannelByCodeResponses, JoinChannelData, JoinChannelErrors, JoinChannelResponses, LeaveChannelData, LeaveChannelErrors, LeaveChannelResponses, LeaveOrEndCallData, LeaveOrEndCallErrors, LeaveOrEndCallResponses, ListBotChannelsData, ListBotChannelsErrors, ListBotChannelsResponses, ListCompanyContactsData, ListCompanyContactsErrors, ListCompanyContactsResponses, ListCrmCommentsData, ListCrmCommentsErrors, ListCrmCommentsResponses, ListFavoritesData, ListFavoritesErrors, ListFavoritesResponses, ListOccurrencesData, ListOccurrencesErrors, ListOccurrencesResponses, ListRemindersData, ListRemindersErrors, ListRemindersResponses, ListWebhooksData, ListWebhooksErrors, ListWebhooksResponses, PatchChannelData, PatchChannelErrors, PatchChannelResponses, PatchMessageData, PatchMessageErrors, PatchMessageResponses, PatchViewHandlerData, PatchViewHandlerErrors, PatchViewHandlerResponses, PatchWebhookData, PatchWebhookErrors, PatchWebhookResponses, PermanentlyDeleteDocumentData, PermanentlyDeleteDocumentErrors, PermanentlyDeleteDocumentResponses, PermanentlyDeleteProjectData, PermanentlyDeleteProjectErrors, PermanentlyDeleteProjectResponses, PostActivityData, PostActivityErrors, PostActivityResponses, PostChannelBotWebhookData, PostChannelBotWebhookErrors, PostChannelBotWebhookResponses, PostChannelMessagesData, PostChannelMessagesErrors, PostChannelMessagesResponses, PostItemsSoupAstData, PostItemsSoupAstErrors, PostItemsSoupAstGroupedData, PostItemsSoupAstGroupedErrors, PostItemsSoupAstGroupedResponses, PostItemsSoupAstResponses, PostItemsSoupData, PostItemsSoupErrors, PostItemsSoupResponses, PostMessageData, PostMessageErrors, PostMessageResponses, PostReactionData, PostReactionErrors, PostReactionResponses, PostTypingData, PostTypingErrors, PostTypingResponses, PresaveDocumentHandlerData, PresaveDocumentHandlerErrors, PresaveDocumentHandlerResponses, PutCrmTeamSettingsData, PutCrmTeamSettingsErrors, PutCrmTeamSettingsResponses, RecentlyDeletedData, RecentlyDeletedErrors, RecentlyDeletedResponses, RemoveBotFromChannelByBotData, RemoveBotFromChannelByBotErrors, RemoveBotFromChannelByBotResponses, RemoveFavoriteByEntityData, RemoveFavoriteByEntityErrors, RemoveFavoriteByEntityResponses, RemoveParticipantsData, RemoveParticipantsErrors, RemoveParticipantsResponses, RemovePinHandlerData, RemovePinHandlerErrors, RemovePinHandlerResponses, ReorderFavoritesData, ReorderFavoritesErrors, ReorderFavoritesResponses, ReorderPinsHandlerData, ReorderPinsHandlerErrors, ReorderPinsHandlerResponses, ResolveChannelMessageData, ResolveChannelMessageErrors, ResolveChannelMessageResponses, RevertDeleteDocumentData, RevertDeleteDocumentErrors, RevertDeleteDocumentResponses, RevertDeleteProjectData, RevertDeleteProjectErrors, RevertDeleteProjectResponses, SaveDocumentHandlerData, SaveDocumentHandlerErrors, SaveDocumentHandlerResponses, SetCompanyHiddenData, SetCompanyHiddenErrors, SetCompanyHiddenResponses, SetContactHiddenData, SetContactHiddenErrors, SetContactHiddenResponses, SetCrmCompanyNameData, SetCrmCompanyNameErrors, SetCrmCompanyNameResponses, SetCrmContactNameData, SetCrmContactNameErrors, SetCrmContactNameResponses, SetDocumentTeamShareData, SetDocumentTeamShareErrors, SetDocumentTeamShareResponses, SetEmailSyncData, SetEmailSyncErrors, SetEmailSyncResponses, SimpleSaveData, SimpleSaveErrors, SimpleSaveResponses, ToggleShareWithTeamData, ToggleShareWithTeamErrors, ToggleShareWithTeamResponses, UpdateReminderData, UpdateReminderErrors, UpdateReminderResponses, UploadExtractFolderHandlerData, UploadExtractFolderHandlerErrors, UploadExtractFolderHandlerResponses, UploadFolderHandlerData, UploadFolderHandlerErrors, UploadFolderHandlerResponses, UpsertHistoryHandlerData, UpsertHistoryHandlerErrors, UpsertHistoryHandlerResponses, UpsertUserDocumentViewLocationData, UpsertUserDocumentViewLocationErrors, UpsertUserDocumentViewLocationResponses, ValidateDocumentPermissionsTokenData, ValidateDocumentPermissionsTokenErrors, ValidateDocumentPermissionsTokenResponses, ValidateWebhookData, ValidateWebhookErrors, ValidateWebhookResponses } from './types.gen';export type Options<TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown> = Options2<TData, ThrowOnError, TResponse> & {/**@@ -1600,6 +1600,55 @@ export class Sdk extends HeyApiClient {return (options?.client ?? this.client).get<RecentlyDeletedResponses, RecentlyDeletedErrors, ThrowOnError>({ url: '/recents/deleted', ...options });}+ /**+ * List the caller's reminders, soonest firing first.+ */+ public listReminders<ThrowOnError extends boolean = false>(options?: Options<ListRemindersData, ThrowOnError>): RequestResult<ListRemindersResponses, ListRemindersErrors, ThrowOnError> {+ return (options?.client ?? this.client).get<ListRemindersResponses, ListRemindersErrors, ThrowOnError>({ url: '/reminders', ...options });+ }++ /**+ * Create a reminder, optionally attached to an entity the caller can view.+ */+ public createReminder<ThrowOnError extends boolean = false>(options: Options<CreateReminderData, ThrowOnError>): RequestResult<CreateReminderResponses, CreateReminderErrors, ThrowOnError> {+ return (options.client ?? this.client).post<CreateReminderResponses, CreateReminderErrors, ThrowOnError>({+ url: '/reminders',+ ...options,+ headers: {+ 'Content-Type': 'application/json',+ ...options.headers+ }+ });+ }++ /**+ * Delete one of the caller's reminders.+ */+ public deleteReminder<ThrowOnError extends boolean = false>(options: Options<DeleteReminderData, ThrowOnError>): RequestResult<DeleteReminderResponses, DeleteReminderErrors, ThrowOnError> {+ return (options.client ?? this.client).delete<DeleteReminderResponses, DeleteReminderErrors, ThrowOnError>({ url: '/reminders/{id}', ...options });+ }++ /**+ * Fetch one of the caller's reminders.+ */+ public getReminder<ThrowOnError extends boolean = false>(options: Options<GetReminderData, ThrowOnError>): RequestResult<GetReminderResponses, GetReminderErrors, ThrowOnError> {+ return (options.client ?? this.client).get<GetReminderResponses, GetReminderErrors, ThrowOnError>({ url: '/reminders/{id}', ...options });+ }++ /**+ * Modify one of the caller's reminders.+ */+ public updateReminder<ThrowOnError extends boolean = false>(options: Options<UpdateReminderData, ThrowOnError>): RequestResult<UpdateReminderResponses, UpdateReminderErrors, ThrowOnError> {+ return (options.client ?? this.client).patch<UpdateReminderResponses, UpdateReminderErrors, ThrowOnError>({+ url: '/reminders/{id}',+ ...options,+ headers: {+ 'Content-Type': 'application/json',+ ...options.headers+ }+ });+ }+public getViewsHandler<ThrowOnError extends boolean = false>(options?: Options<GetViewsHandlerData, ThrowOnError>): RequestResult<GetViewsHandlerResponses, GetViewsHandlerErrors, ThrowOnError> {return (options?.client ?? this.client).get<GetViewsHandlerResponses, GetViewsHandlerErrors, ThrowOnError>({ url: '/saved_views', ...options });}diff --git a/packages/sdk/generated/storage/types.gen.ts b/packages/sdk/generated/storage/types.gen.tsindex a945b295e0..1fad0f8129 100644--- a/packages/sdk/generated/storage/types.gen.ts+++ b/packages/sdk/generated/storage/types.gen.ts@@ -31,7 +31,7 @@ export type AddFavoriteRequest = {/*** The type of the entity to favorite.*/- entityType: 'user' | 'chat' | 'channel' | 'channel_message' | 'document' | 'project' | 'email_thread' | 'calendar_event' | 'team' | 'call' | 'foreign_entity' | 'static_file' | 'crm_company' | 'crm_contact';+ entityType: 'user' | 'chat' | 'channel' | 'channel_message' | 'document' | 'project' | 'email_thread' | 'calendar_event' | 'team' | 'call' | 'foreign_entity' | 'static_file' | 'crm_company' | 'crm_contact' | 'reminder';};/**@@ -2824,6 +2824,28 @@ export type CreateProjectResponse = {error: boolean;};+/**+ * Request body for creating a reminder.+ */+export type CreateReminderRequest = {+ /**+ * What to remind the caller about.+ */+ description: string;+ /**+ * Id of the entity to attach the reminder to. Requires `entityType`.+ */+ entityId?: string | null;+ /**+ * Type of the entity to attach the reminder to. Requires `entityId`.+ */+ entityType?: null | 'user' | 'chat' | 'channel' | 'channel_message' | 'document' | 'project' | 'email_thread' | 'calendar_event' | 'team' | 'call' | 'foreign_entity' | 'static_file' | 'crm_company' | 'crm_contact' | 'reminder';+ /**+ * When and how often the reminder fires.+ */+ schedule: ReminderSchedule;+};+/*** Request body for creating a snippet — a reusable markdown document that can* be inserted into any markdown area.@@ -4454,7 +4476,7 @@ export type Favorite = {/*** The type of the favorited entity.*/- entityType: 'user' | 'chat' | 'channel' | 'channel_message' | 'document' | 'project' | 'email_thread' | 'calendar_event' | 'team' | 'call' | 'foreign_entity' | 'static_file' | 'crm_company' | 'crm_contact';+ entityType: 'user' | 'chat' | 'channel' | 'channel_message' | 'document' | 'project' | 'email_thread' | 'calendar_event' | 'team' | 'call' | 'foreign_entity' | 'static_file' | 'crm_company' | 'crm_contact' | 'reminder';/*** File type of the favorited document, when applicable.*/@@ -4476,7 +4498,7 @@ export type FavoriteEntityRef = {/*** The type of the favorited entity.*/- entityType: 'user' | 'chat' | 'channel' | 'channel_message' | 'document' | 'project' | 'email_thread' | 'calendar_event' | 'team' | 'call' | 'foreign_entity' | 'static_file' | 'crm_company' | 'crm_contact';+ entityType: 'user' | 'chat' | 'channel' | 'channel_message' | 'document' | 'project' | 'email_thread' | 'calendar_event' | 'team' | 'call' | 'foreign_entity' | 'static_file' | 'crm_company' | 'crm_contact' | 'reminder';};/**@@ -6037,6 +6059,95 @@ export type RecentlyDeletedResponseData = {items: Array<Item>;};+/**+ * A reminder belonging to a user.+ *+ * `user_id` is deliberately absent: a reminder is only ever read by its owner,+ * so the field would be redundant on the wire.+ */+export type Reminder = {+ /**+ * Set once a one-shot reminder has fired.+ */+ completedAt?: string | null;+ /**+ * When the reminder was created.+ */+ createdAt: string;+ /**+ * What to remind the user about.+ */+ description: string;+ /**+ * When false, the dispatcher skips this reminder.+ */+ enabled: boolean;+ /**+ * Id of the associated entity, when the reminder is attached to one.+ */+ entityId?: string | null;+ /**+ * Type of the associated entity, when the reminder is attached to one.+ */+ entityType?: null | 'user' | 'chat' | 'channel' | 'channel_message' | 'document' | 'project' | 'email_thread' | 'calendar_event' | 'team' | 'call' | 'foreign_entity' | 'static_file' | 'crm_company' | 'crm_contact' | 'reminder';+ /**+ * Reminder id.+ */+ id: string;+ /**+ * The next firing, derived from `schedule` on write.+ */+ nextRunAt: string;+ /**+ * When and how often the reminder fires.+ */+ schedule: ReminderSchedule;+ /**+ * When the reminder was last modified.+ */+ updatedAt: string;+};++/**+ * When a reminder fires.+ */+export type ReminderSchedule = {+ /**+ * The instant to fire at.+ */+ remindAt: string;+ type: 'once';+} | {+ /**+ * Cron expression, either the conventional 5-field+ * `min hour dom mon dow` or the 6-/7-field+ * `sec min hour dom mon dow [year]`. A 5-field expression is stored+ * normalized to 6 fields with a zero seconds field, so `0 9 * * *` and+ * `0 0 9 * * *` are the same schedule and both read back as the latter.+ */+ cron: string;+ /**+ * The timezone the cron expression is evaluated in.+ */+ timezone: string;+ type: 'recurring';+};++/**+ * The caller's reminders, soonest firing first.+ */+export type RemindersList = {+ /**+ * Pass back as `cursor` to fetch the next page. Absent on the last page —+ * its absence is the only end-of-list signal, since a page can be short.+ */+ nextCursor?: string | null;+ /**+ * The reminders.+ */+ reminders: Array<Reminder>;+};+/*** Request to remove participants.*/@@ -7537,6 +7648,32 @@ export type UpdateCrmTeamSettingsRequest = {export type UpdateOperation = 'add' | 'remove' | 'replace';+/**+ * Request body for modifying a reminder. Omitted fields are left unchanged;+ * the entity association is not modifiable.+ *+ * Every field is optional but **not** nullable. `Option` here means "absent",+ * and serde cannot tell an explicit `null` from an omitted key — so a body of+ * `{"enabled": null}` would deserialize to an empty patch and be rejected as+ * having no fields to update. `nullable = false` keeps the schema from+ * advertising a value the API has no meaning for; the deserializer still+ * tolerates `null` rather than erroring on it.+ */+export type UpdateReminderRequest = {+ /**+ * Replacement description.+ */+ description?: string;+ /**+ * Whether the reminder should fire at all.+ */+ enabled?: boolean;+ /**+ * Replacement schedule.+ */+ schedule?: ReminderSchedule;+};+export type UpdateSharePermissionRequestV2 = {/*** Any channel share permissions to be created/updated/removed@@ -10948,7 +11085,7 @@ export type RemoveFavoriteByEntityData = {/*** The type of an entity in Macro*/- entity_type: 'user' | 'chat' | 'channel' | 'channel_message' | 'document' | 'project' | 'email_thread' | 'calendar_event' | 'team' | 'call' | 'foreign_entity' | 'static_file' | 'crm_company' | 'crm_contact';+ entity_type: 'user' | 'chat' | 'channel' | 'channel_message' | 'document' | 'project' | 'email_thread' | 'calendar_event' | 'team' | 'call' | 'foreign_entity' | 'static_file' | 'crm_company' | 'crm_contact' | 'reminder';/*** The id of the favorited entity.*/@@ -11756,6 +11893,183 @@ export type RecentlyDeletedResponses = {export type RecentlyDeletedResponse = RecentlyDeletedResponses[keyof RecentlyDeletedResponses];+export type ListRemindersData = {+ body?: never;+ path?: never;+ query?: {+ /**+ * The type of an entity in Macro+ */+ entityType?: 'user' | 'chat' | 'channel' | 'channel_message' | 'document' | 'project' | 'email_thread' | 'calendar_event' | 'team' | 'call' | 'foreign_entity' | 'static_file' | 'crm_company' | 'crm_contact' | 'reminder';+ /**+ * Restrict to reminders attached to this entity id. Requires `entityType`.+ */+ entityId?: string;+ /**+ * Include reminders that have already fired.+ */+ includeCompleted?: boolean;+ /**+ * Page size. Defaults to 100; larger values are capped at 500. A value+ * that is not a non-negative integer is rejected by the query extractor.+ */+ limit?: number;+ /**+ * `nextCursor` from a previous page.+ */+ cursor?: string;+ };+ url: '/reminders';+};++export type ListRemindersErrors = {+ 400: ErrorResponse;+ /**+ * Missing or invalid credentials+ */+ 401: ErrorResponse;+ 500: ErrorResponse;+};++export type ListRemindersError = ListRemindersErrors[keyof ListRemindersErrors];++export type ListRemindersResponses = {+ 200: RemindersList;+};++export type ListRemindersResponse = ListRemindersResponses[keyof ListRemindersResponses];++export type CreateReminderData = {+ body: CreateReminderRequest;+ path?: never;+ query?: never;+ url: '/reminders';+};++export type CreateReminderErrors = {+ 400: ErrorResponse;+ /**+ * Missing or invalid credentials+ */+ 401: ErrorResponse;+ /**+ * No access to the requested entity+ */+ 403: ErrorResponse;+ /**+ * The requested entity does not exist+ */+ 404: ErrorResponse;+ /**+ * Malformed request body (plain text)+ */+ 422: unknown;+ 500: ErrorResponse;+};++export type CreateReminderError = CreateReminderErrors[keyof CreateReminderErrors];++export type CreateReminderResponses = {+ 201: Reminder;+};++export type CreateReminderResponse = CreateReminderResponses[keyof CreateReminderResponses];++export type DeleteReminderData = {+ body?: never;+ path: {+ /**+ * The reminder id.+ */+ id: string;+ };+ query?: never;+ url: '/reminders/{id}';+};++export type DeleteReminderErrors = {+ /**+ * Missing or invalid credentials+ */+ 401: ErrorResponse;+ 404: ErrorResponse;+ 500: ErrorResponse;+};++export type DeleteReminderError = DeleteReminderErrors[keyof DeleteReminderErrors];++export type DeleteReminderResponses = {+ /**+ * Reminder deleted+ */+ 204: void;+};++export type DeleteReminderResponse = DeleteReminderResponses[keyof DeleteReminderResponses];++export type GetReminderData = {+ body?: never;+ path: {+ /**+ * The reminder id.+ */+ id: string;+ };+ query?: never;+ url: '/reminders/{id}';+};++export type GetReminderErrors = {+ /**+ * Missing or invalid credentials+ */+ 401: ErrorResponse;+ 404: ErrorResponse;+ 500: ErrorResponse;+};++export type GetReminderError = GetReminderErrors[keyof GetReminderErrors];++export type GetReminderResponses = {+ 200: Reminder;+};++export type GetReminderResponse = GetReminderResponses[keyof GetReminderResponses];++export type UpdateReminderData = {+ body: UpdateReminderRequest;+ path: {+ /**+ * The reminder id.+ */+ id: string;+ };+ query?: never;+ url: '/reminders/{id}';+};++export type UpdateReminderErrors = {+ 400: ErrorResponse;+ /**+ * Missing or invalid credentials+ */+ 401: ErrorResponse;+ 404: ErrorResponse;+ /**+ * Malformed request body (plain text)+ */+ 422: unknown;+ 500: ErrorResponse;+};++export type UpdateReminderError = UpdateReminderErrors[keyof UpdateReminderErrors];++export type UpdateReminderResponses = {+ 200: Reminder;+};++export type UpdateReminderResponse = UpdateReminderResponses[keyof UpdateReminderResponses];+export type GetViewsHandlerData = {body?: never;path?: never;diff --git a/packages/sdk/specs/cognition.json b/packages/sdk/specs/cognition.jsonindex b9e70fac6c..917b516d35 100644--- a/packages/sdk/specs/cognition.json+++ b/packages/sdk/specs/cognition.json@@ -2626,7 +2626,8 @@"foreign_entity","static_file","crm_company",- "crm_contact"+ "crm_contact",+ "reminder"]},"ErrorBody": {diff --git a/packages/sdk/specs/connection.json b/packages/sdk/specs/connection.jsonindex 7b8df2626d..aef453ef56 100644--- a/packages/sdk/specs/connection.json+++ b/packages/sdk/specs/connection.json@@ -258,7 +258,8 @@"foreign_entity","static_file","crm_company",- "crm_contact"+ "crm_contact",+ "reminder"]},"GenericErrorResponse": {diff --git a/packages/sdk/specs/notification.json b/packages/sdk/specs/notification.jsonindex 36e1e5b54e..4fbfcda375 100644--- a/packages/sdk/specs/notification.json+++ b/packages/sdk/specs/notification.json@@ -1504,7 +1504,8 @@"foreign_entity","static_file","crm_company",- "crm_contact"+ "crm_contact",+ "reminder"]},"ErrorResponse": {@@ -2221,6 +2222,21 @@}}},+ {+ "type": "object",+ "description": "A reminder the user set for themselves came due.",+ "required": ["content", "tag"],+ "properties": {+ "content": {+ "$ref": "#/components/schemas/ReminderMetadata",+ "description": "A reminder the user set for themselves came due."+ },+ "tag": {+ "type": "string",+ "enum": ["reminder"]+ }+ }+ },{"type": "object","description": "An AI assistant responded to a chat.",@@ -2392,6 +2408,22 @@}}},+ "ReminderMetadata": {+ "type": "object",+ "description": "Metadata for a reminder the user set for themselves coming due.\n\nThere is no sender: a reminder is self-set, so the dispatcher sends it with\n`sender_id: None` (a recipient who is also the sender is filtered out of\ntheir own notification). Every formatter here must therefore work without\none.\n\nThe associated entity, when there is one, lives on the notification row\nrather than in here, and clients resolve its name from that — so the\ndispatcher does not have to look up a name across five entity types.",+ "required": ["reminderId", "description"],+ "properties": {+ "description": {+ "type": "string",+ "description": "What the user asked to be reminded about."+ },+ "reminderId": {+ "type": "string",+ "format": "uuid",+ "description": "The reminder that fired."+ }+ }+ },"RepliedToDocumentCommentThreadMetadata": {"type": "object","description": "Notification sent when someone replies to a document comment thread.",diff --git a/packages/sdk/specs/storage.json b/packages/sdk/specs/storage.jsonindex 6abf51f2fb..0935ac3794 100644--- a/packages/sdk/specs/storage.json+++ b/packages/sdk/specs/storage.json@@ -7821,7 +7821,8 @@"foreign_entity","static_file","crm_company",- "crm_contact"+ "crm_contact",+ "reminder"]}},@@ -9596,6 +9597,397 @@}}},+ "/reminders": {+ "get": {+ "tags": ["reminders"],+ "summary": "List the caller's reminders, soonest firing first.",+ "operationId": "list_reminders",+ "parameters": [+ {+ "name": "entityType",+ "in": "query",+ "description": "Restrict to reminders attached to this entity type. Requires `entityId`.",+ "required": false,+ "schema": {+ "type": "string",+ "description": "The type of an entity in Macro",+ "enum": [+ "user",+ "chat",+ "channel",+ "channel_message",+ "document",+ "project",+ "email_thread",+ "calendar_event",+ "team",+ "call",+ "foreign_entity",+ "static_file",+ "crm_company",+ "crm_contact",+ "reminder"+ ]+ }+ },+ {+ "name": "entityId",+ "in": "query",+ "description": "Restrict to reminders attached to this entity id. Requires `entityType`.",+ "required": false,+ "schema": {+ "type": "string"+ }+ },+ {+ "name": "includeCompleted",+ "in": "query",+ "description": "Include reminders that have already fired.",+ "required": false,+ "schema": {+ "type": "boolean"+ }+ },+ {+ "name": "limit",+ "in": "query",+ "description": "Page size. Defaults to 100; larger values are capped at 500. A value\nthat is not a non-negative integer is rejected by the query extractor.",+ "required": false,+ "schema": {+ "type": "integer",+ "format": "int32",+ "minimum": 0+ }+ },+ {+ "name": "cursor",+ "in": "query",+ "description": "`nextCursor` from a previous page.",+ "required": false,+ "schema": {+ "type": "string"+ }+ }+ ],+ "responses": {+ "200": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/RemindersList"+ }+ }+ }+ },+ "400": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "401": {+ "description": "Missing or invalid credentials",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "500": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ }+ }+ },+ "post": {+ "tags": ["reminders"],+ "summary": "Create a reminder, optionally attached to an entity the caller can view.",+ "operationId": "create_reminder",+ "requestBody": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/CreateReminderRequest"+ }+ }+ },+ "required": true+ },+ "responses": {+ "201": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/Reminder"+ }+ }+ }+ },+ "400": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "401": {+ "description": "Missing or invalid credentials",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "403": {+ "description": "No access to the requested entity",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "404": {+ "description": "The requested entity does not exist",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "422": {+ "description": "Malformed request body (plain text)"+ },+ "500": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ }+ }+ }+ },+ "/reminders/{id}": {+ "get": {+ "tags": ["reminders"],+ "summary": "Fetch one of the caller's reminders.",+ "operationId": "get_reminder",+ "parameters": [+ {+ "name": "id",+ "in": "path",+ "description": "The reminder id.",+ "required": true,+ "schema": {+ "type": "string",+ "format": "uuid"+ }+ }+ ],+ "responses": {+ "200": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/Reminder"+ }+ }+ }+ },+ "401": {+ "description": "Missing or invalid credentials",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "404": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "500": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ }+ }+ },+ "delete": {+ "tags": ["reminders"],+ "summary": "Delete one of the caller's reminders.",+ "operationId": "delete_reminder",+ "parameters": [+ {+ "name": "id",+ "in": "path",+ "description": "The reminder id.",+ "required": true,+ "schema": {+ "type": "string",+ "format": "uuid"+ }+ }+ ],+ "responses": {+ "204": {+ "description": "Reminder deleted"+ },+ "401": {+ "description": "Missing or invalid credentials",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "404": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "500": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ }+ }+ },+ "patch": {+ "tags": ["reminders"],+ "summary": "Modify one of the caller's reminders.",+ "operationId": "update_reminder",+ "parameters": [+ {+ "name": "id",+ "in": "path",+ "description": "The reminder id.",+ "required": true,+ "schema": {+ "type": "string",+ "format": "uuid"+ }+ }+ ],+ "requestBody": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/UpdateReminderRequest"+ }+ }+ },+ "required": true+ },+ "responses": {+ "200": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/Reminder"+ }+ }+ }+ },+ "400": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "401": {+ "description": "Missing or invalid credentials",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "404": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "422": {+ "description": "Malformed request body (plain text)"+ },+ "500": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ }+ }+ }+ },"/saved_views": {"get": {"tags": ["saved_views"],@@ -10613,7 +11005,8 @@"foreign_entity","static_file","crm_company",- "crm_contact"+ "crm_contact",+ "reminder"]}],@@ -14647,6 +15040,54 @@}}},+ "CreateReminderRequest": {+ "type": "object",+ "description": "Request body for creating a reminder.",+ "required": ["description", "schedule"],+ "properties": {+ "description": {+ "type": "string",+ "description": "What to remind the caller about."+ },+ "entityId": {+ "type": ["string", "null"],+ "description": "Id of the entity to attach the reminder to. Requires `entityType`."+ },+ "entityType": {+ "oneOf": [+ {+ "type": "null"+ },+ {+ "type": "string",+ "description": "The type of an entity in Macro",+ "enum": [+ "user",+ "chat",+ "channel",+ "channel_message",+ "document",+ "project",+ "email_thread",+ "calendar_event",+ "team",+ "call",+ "foreign_entity",+ "static_file",+ "crm_company",+ "crm_contact",+ "reminder"+ ]+ }+ ],+ "description": "Type of the entity to attach the reminder to. Requires `entityId`."+ },+ "schedule": {+ "$ref": "#/components/schemas/ReminderSchedule",+ "description": "When and how often the reminder fires."+ }+ }+ },"CreateSnippetRequest": {"type": "object","description": "Request body for creating a snippet — a reusable markdown document that can\nbe inserted into any markdown area.",@@ -17164,7 +17605,8 @@"foreign_entity","static_file","crm_company",- "crm_contact"+ "crm_contact",+ "reminder"]}],@@ -17209,7 +17651,8 @@"foreign_entity","static_file","crm_company",- "crm_contact"+ "crm_contact",+ "reminder"]}],@@ -20458,6 +20901,149 @@}}},+ "Reminder": {+ "type": "object",+ "description": "A reminder belonging to a user.\n\n`user_id` is deliberately absent: a reminder is only ever read by its owner,\nso the field would be redundant on the wire.",+ "required": [+ "id",+ "description",+ "schedule",+ "nextRunAt",+ "enabled",+ "createdAt",+ "updatedAt"+ ],+ "properties": {+ "completedAt": {+ "type": ["string", "null"],+ "format": "date-time",+ "description": "Set once a one-shot reminder has fired."+ },+ "createdAt": {+ "type": "string",+ "format": "date-time",+ "description": "When the reminder was created."+ },+ "description": {+ "type": "string",+ "description": "What to remind the user about."+ },+ "enabled": {+ "type": "boolean",+ "description": "When false, the dispatcher skips this reminder."+ },+ "entityId": {+ "type": ["string", "null"],+ "description": "Id of the associated entity, when the reminder is attached to one."+ },+ "entityType": {+ "oneOf": [+ {+ "type": "null"+ },+ {+ "type": "string",+ "description": "The type of an entity in Macro",+ "enum": [+ "user",+ "chat",+ "channel",+ "channel_message",+ "document",+ "project",+ "email_thread",+ "calendar_event",+ "team",+ "call",+ "foreign_entity",+ "static_file",+ "crm_company",+ "crm_contact",+ "reminder"+ ]+ }+ ],+ "description": "Type of the associated entity, when the reminder is attached to one."+ },+ "id": {+ "type": "string",+ "format": "uuid",+ "description": "Reminder id."+ },+ "nextRunAt": {+ "type": "string",+ "format": "date-time",+ "description": "The next firing, derived from `schedule` on write."+ },+ "schedule": {+ "$ref": "#/components/schemas/ReminderSchedule",+ "description": "When and how often the reminder fires."+ },+ "updatedAt": {+ "type": "string",+ "format": "date-time",+ "description": "When the reminder was last modified."+ }+ }+ },+ "ReminderSchedule": {+ "oneOf": [+ {+ "type": "object",+ "description": "Fires once, at a fixed instant.",+ "required": ["remindAt", "type"],+ "properties": {+ "remindAt": {+ "type": "string",+ "format": "date-time",+ "description": "The instant to fire at."+ },+ "type": {+ "type": "string",+ "enum": ["once"]+ }+ }+ },+ {+ "type": "object",+ "description": "Fires repeatedly, on a cron schedule evaluated in `timezone`.",+ "required": ["cron", "timezone", "type"],+ "properties": {+ "cron": {+ "type": "string",+ "description": "Cron expression, either the conventional 5-field\n`min hour dom mon dow` or the 6-/7-field\n`sec min hour dom mon dow [year]`. A 5-field expression is stored\nnormalized to 6 fields with a zero seconds field, so `0 9 * * *` and\n`0 0 9 * * *` are the same schedule and both read back as the latter."+ },+ "timezone": {+ "type": "string",+ "description": "The timezone the cron expression is evaluated in."+ },+ "type": {+ "type": "string",+ "enum": ["recurring"]+ }+ }+ }+ ],+ "description": "When a reminder fires."+ },+ "RemindersList": {+ "type": "object",+ "description": "The caller's reminders, soonest firing first.",+ "required": ["reminders"],+ "properties": {+ "nextCursor": {+ "type": ["string", "null"],+ "description": "Pass back as `cursor` to fetch the next page. Absent on the last page —\nits absence is the only end-of-list signal, since a page can be short."+ },+ "reminders": {+ "type": "array",+ "items": {+ "$ref": "#/components/schemas/Reminder"+ },+ "description": "The reminders."+ }+ }+ },"RemoveParticipantsRequest": {"type": "object","description": "Request to remove participants.",@@ -22712,6 +23298,24 @@"type": "string","enum": ["add", "remove", "replace"]},+ "UpdateReminderRequest": {+ "type": "object",+ "description": "Request body for modifying a reminder. Omitted fields are left unchanged;\nthe entity association is not modifiable.\n\nEvery field is optional but **not** nullable. `Option` here means \"absent\",\nand serde cannot tell an explicit `null` from an omitted key — so a body of\n`{\"enabled\": null}` would deserialize to an empty patch and be rejected as\nhaving no fields to update. `nullable = false` keeps the schema from\nadvertising a value the API has no meaning for; the deserializer still\ntolerates `null` rather than erroring on it.",+ "properties": {+ "description": {+ "type": "string",+ "description": "Replacement description."+ },+ "enabled": {+ "type": "boolean",+ "description": "Whether the reminder should fire at all."+ },+ "schedule": {+ "$ref": "#/components/schemas/ReminderSchedule",+ "description": "Replacement schedule."+ }+ }+ },"UpdateSharePermissionRequestV2": {"type": "object","properties": {diff --git a/packages/sdk/src/coverage/skipped.ts b/packages/sdk/src/coverage/skipped.tsindex c9d0aadcff..bd856d295b 100644--- a/packages/sdk/src/coverage/skipped.ts+++ b/packages/sdk/src/coverage/skipped.ts@@ -282,8 +282,10 @@ export const storageBacklog = ['createAnchor','createDocument','createEntityMention',+ 'createReminder','deleteAnchor','deleteEntityMention',+ 'deleteReminder','editAnchor','editCallTranscript','editThreadV2',@@ -297,12 +299,15 @@ export const storageBacklog = ['getProjectPermissionsV2','getProjectUserAccessLevel','getRecentActivityHandler',+ 'getReminder','listOccurrences',+ 'listReminders','postActivity','presaveDocumentHandler','saveDocumentHandler','simpleSave','toggleShareWithTeam',+ 'updateReminder','validateDocumentPermissionsToken',] as const satisfies readonly (keyof StorageSdk)[];diff --git a/services/document_storage_service/Cargo.toml b/services/document_storage_service/Cargo.tomlindex e5c41d300f..4ecacbb7c4 100644--- a/services/document_storage_service/Cargo.toml+++ b/services/document_storage_service/Cargo.toml@@ -164,6 +164,12 @@ redis = { workspace = true, features = ["tokio-rustls-comp",] }regex = { workspace = true }+reminders = { path = "../../crates/reminders", features = [+ "dispatch-sqs",+ "inbound",+ "notify",+ "postgres",+] }reqwest = { workspace = true }rootcause = { workspace = true }s3_key = { path = "../../crates/s3_key" }diff --git a/services/document_storage_service/src/api/context.rs b/services/document_storage_service/src/api/context.rsindex bbf5ec2ed0..a135c4da0a 100644--- a/services/document_storage_service/src/api/context.rs+++ b/services/document_storage_service/src/api/context.rs@@ -93,6 +93,10 @@ use properties::{inbound::axum_router::PropertiesRouterState,};use readonly_pool::ReadOnlyPool;+use reminders::{+ domain::service::RemindersServiceImpl, inbound::axum_router::RemindersRouterState,+ outbound::pg_reminders_repo::PgRemindersRepo,+};use search_service::SearchHandlerState;use soup::{domain::service::SoupImpl, inbound::axum_router::SoupRouterState,@@ -412,6 +416,13 @@ pub(crate) type FavoritesServiceType = FavoritesServiceImpl<PgFavoritesRepo>;pub(crate) type DssFavoritesState =FavoritesRouterState<FavoritesServiceType, EntityAccessService, AuthorizationService>;+/// Type alias for the reminders service.+pub(crate) type RemindersServiceType = RemindersServiceImpl<PgRemindersRepo>;++/// Type alias for the reminders router state.+pub(crate) type DssRemindersState =+ RemindersRouterState<RemindersServiceType, EntityAccessService, AuthorizationService>;+/// Type alias for the foreign entity service.pub(crate) type ForeignEntityServiceType = ForeignEntityServiceImpl<PgForeignEntityRepo>;@@ -461,6 +472,7 @@ pub(crate) struct ApiContext {pub graphql_entity_mutation_service: Arc<DssEntityMutationService>,pub favorites_state: DssFavoritesState,pub favorites_service: Arc<FavoritesServiceType>,+ pub reminders_state: DssRemindersState,pub foreign_entity_state: DssForeignEntityState,pub macro_event_broker: DssEventBroker,pub sqs_client: Arc<sqs_client::SQS>,diff --git a/services/document_storage_service/src/api/mod.rs b/services/document_storage_service/src/api/mod.rsindex fc6852298a..0cfc1fa1d0 100644--- a/services/document_storage_service/src/api/mod.rs+++ b/services/document_storage_service/src/api/mod.rs@@ -224,6 +224,10 @@ fn api_router(state: ApiContext) -> Router {"/favorites",favorites::inbound::axum_router::favorites_router(state.favorites_state.clone()),)+ .nest(+ "/reminders",+ reminders::inbound::axum_router::reminders_router(state.reminders_state.clone()),+ ).nest("/foreign_entity",foreign_entity::inbound::axum_router::foreign_entity_router(diff --git a/services/document_storage_service/src/api/swagger.rs b/services/document_storage_service/src/api/swagger.rsindex 6165fbe17d..09e9b5d954 100644--- a/services/document_storage_service/src/api/swagger.rs+++ b/services/document_storage_service/src/api/swagger.rs@@ -124,6 +124,8 @@ use models_soup::project::SoupProject;use projects_hex::inbound::axum_router::delete_project::{ProjectDeleteResponse, ProjectDeleteResponseData,};+use reminders::domain::models::{Reminder, ReminderSchedule, RemindersList};+use reminders::inbound::axum_router::{CreateReminderRequest, UpdateReminderRequest};use soup::domain::models::{SoupItemWithProperties, SoupPropertiesField};use soup::inbound::axum_router::{ApiGroupByField, ApiGroupMeta, GroupedSoupGroupPage, GroupedSoupInitialPage, GroupedSoupPage,@@ -305,6 +307,13 @@ use utoipa::OpenApi;favorites::inbound::axum_router::remove_favorite_by_entity_handler,favorites::inbound::axum_router::reorder_favorites_handler,+ // reminders+ reminders::inbound::axum_router::list_reminders_handler,+ reminders::inbound::axum_router::create_reminder_handler,+ reminders::inbound::axum_router::get_reminder_handler,+ reminders::inbound::axum_router::update_reminder_handler,+ reminders::inbound::axum_router::delete_reminder_handler,+// foreign_entityforeign_entity::inbound::axum_router::get_foreign_entity_handler,@@ -436,6 +445,11 @@ use utoipa::OpenApi;AddFavoriteRequest,FavoriteEntityRef,ReorderFavoritesRequest,+ Reminder,+ RemindersList,+ ReminderSchedule,+ CreateReminderRequest,+ UpdateReminderRequest,SoupApiSort,SoupPage,SoupEnrichedEmailThreadPreview<SoupPropertiesField>,diff --git a/services/document_storage_service/src/main.rs b/services/document_storage_service/src/main.rsindex 4f6db9540a..54c655df64 100644--- a/services/document_storage_service/src/main.rs+++ b/services/document_storage_service/src/main.rs@@ -105,6 +105,14 @@ use properties::{NotificationServiceImpl, PermissionServiceImpl, PropertiesPgRepo, PropertiesServiceImpl,};use rate_limit::{RateLimitServiceImpl, RedisRateLimitAdapter};+use reminders::{+ domain::service::{RemindersServiceImpl, dispatch::ReminderDispatchService},+ inbound::{axum_router::RemindersRouterState, dispatch_worker::DispatchWorker},+ outbound::{+ notification_notifier::NotificationReminderNotifier, pg_reminders_repo::PgRemindersRepo,+ sqs_dispatch_queue::SqsDispatchQueue,+ },+};use secretsmanager_client::SecretManager;use soup::{domain::service::SoupImpl, inbound::axum_router::SoupRouterState,@@ -223,6 +231,7 @@ async fn main() -> anyhow::Result<()> {let contacts_queue = macro_queues::ContactsQueue::new();let notification_queue = macro_queues::NotificationIngressQueue::new();let gmail_ops_queue = macro_queues::GmailOpsQueue::new();+ let reminder_dispatch_queue = macro_queues::ReminderDispatchQueue::new();let sqs_client = sqs_client::SQS::new(aws_sdk_sqs::Client::new(&aws_config)).search_event_queue(&search_event_queue).document_delete_queue(&document_delete_queue)@@ -997,6 +1006,33 @@ async fn main() -> anyhow::Result<()> {authorization_state.clone(),);+ let reminders_service = Arc::new(RemindersServiceImpl::new(PgRemindersRepo::new(db.clone())));++ // Reminder dispatch. An EventBridge rule drops a sweep tick on this queue+ // every minute; the sweep fans one message out per due firing, onto the+ // same queue, and every task in the pool delivers them in parallel.+ let reminder_dispatch_worker = {+ let queue = SqsDispatchQueue::new(+ aws_sdk_sqs::Client::new(&aws_config),+ reminder_dispatch_queue.to_string(),+ );+ let dispatch_service = ReminderDispatchService::new(+ PgRemindersRepo::new(db.clone()),+ NotificationReminderNotifier::new((*notification_ingress_service).clone()),+ queue.clone(),+ );+ DispatchWorker::new(dispatch_service, queue)+ };++ consumer_tracker.spawn({+ let cancellation_token = consumer_cancellation_token.clone();+ async move {+ tracing::info!("starting reminder dispatch worker");+ reminder_dispatch_worker.run(cancellation_token).await;+ tracing::info!("reminder dispatch worker stopped");+ }+ });+let redis_sha_client = Arc::new(Redis::new(redis_client));let graphql_entity_mutation_service =@@ -1034,6 +1070,11 @@ async fn main() -> anyhow::Result<()> {authorization_state.clone(),),favorites_service,+ reminders_state: RemindersRouterState::new(+ reminders_service,+ entity_access_service.clone(),+ authorization_state.clone(),+ ),graphql_soup_schema: complete_graph::build_schema_from_arcs(soup_service,soup_realtime_service,diff --git a/services/document_storage_service/src/service/entity_mutation.rs b/services/document_storage_service/src/service/entity_mutation.rsindex 45065ed0b3..54b6183108 100644--- a/services/document_storage_service/src/service/entity_mutation.rs+++ b/services/document_storage_service/src/service/entity_mutation.rs@@ -184,7 +184,9 @@ fn favoritable(entity_type: EntityType) -> bool {| EntityType::ChannelMessage| EntityType::StaticFile| EntityType::CrmContact- | EntityType::CalendarEvent => false,+ | EntityType::CalendarEvent+ // Reminders are managed through the reminders API, not favorites.+ | EntityType::Reminder => false,}}@@ -455,7 +457,8 @@ where| EntityType::StaticFile| EntityType::CrmCompany| EntityType::CrmContact- | EntityType::CalendarEvent => {+ | EntityType::CalendarEvent+ | EntityType::Reminder => {return unsupported(requested, "rename");}};@@ -498,7 +501,8 @@ where| EntityType::StaticFile| EntityType::CrmCompany| EntityType::CrmContact- | EntityType::CalendarEvent => {+ | EntityType::CalendarEvent+ | EntityType::Reminder => {return unsupported(requested, "move");}};@@ -543,7 +547,8 @@ where| EntityType::StaticFile| EntityType::CrmCompany| EntityType::CrmContact- | EntityType::CalendarEvent => {+ | EntityType::CalendarEvent+ | EntityType::Reminder => {return unsupported(requested, "share policy updates");}};@@ -591,7 +596,8 @@ where| EntityType::StaticFile| EntityType::CrmCompany| EntityType::CrmContact- | EntityType::CalendarEvent => {+ | EntityType::CalendarEvent+ | EntityType::Reminder => {return unsupported(requested, "trash");}};@@ -618,7 +624,8 @@ where| EntityType::StaticFile| EntityType::CrmCompany| EntityType::CrmContact- | EntityType::CalendarEvent => {+ | EntityType::CalendarEvent+ | EntityType::Reminder => {return unsupported(requested, "restore");}};@@ -665,7 +672,8 @@ where| EntityType::StaticFile| EntityType::CrmCompany| EntityType::CrmContact- | EntityType::CalendarEvent => {+ | EntityType::CalendarEvent+ | EntityType::Reminder => {return unsupported(requested, "permanent deletion");}};@@ -722,7 +730,8 @@ where| EntityType::StaticFile| EntityType::CrmCompany| EntityType::CrmContact- | EntityType::CalendarEvent => {+ | EntityType::CalendarEvent+ | EntityType::Reminder => {return unsupported(requested, "duplication");}};diff --git a/services/scheduled_action/Cargo.toml b/services/scheduled_action/Cargo.tomlindex eff35e6b72..1b871f2a94 100644--- a/services/scheduled_action/Cargo.toml+++ b/services/scheduled_action/Cargo.toml@@ -31,11 +31,11 @@ database_env_vars = { path = "../../crates/database_env_vars" }doppler-config = { workspace = true }sqlx = { workspace = true }macro_user_id = { path = "../../crates/macro_user_id"}-cron = { version = "0.16.0" }+cron = { workspace = true }anyhow = { workspace = true }macro_uuid = { path = "../../crates/macro_uuid"}chrono = { workspace = true}-chrono-tz = { version = "0.10.4", features = ["serde"] }+chrono-tz = { workspace = true }agent = { path = "../../crates/agent" }ai_usage = { path = "../../crates/ai_usage" }tokio = { workspace = true, features = ["signal"] }diff --git a/static_assets/schema.graphql b/static_assets/schema.graphqlindex f7abdeecbc..43ae7995bf 100644--- a/static_assets/schema.graphql+++ b/static_assets/schema.graphql@@ -1397,6 +1397,10 @@ enum GraphqlEntityType {CRM contact entity."""CRM_CONTACT+ """+ Reminder entity.+ """+ REMINDER}"""diff --git a/tooling/just/local_stack.just b/tooling/just/local_stack.justindex ced7b3bec4..e969dc5d2c 100644--- a/tooling/just/local_stack.just+++ b/tooling/just/local_stack.just@@ -49,8 +49,33 @@ create_local_queues:aws --endpoint-url=http://localhost:4566 sqs create-queue --queue-name email-sfs-delete-queue || trueaws --endpoint-url=http://localhost:4566 sqs create-queue --queue-name email-service-sfs-mapper-queue || trueaws --endpoint-url=http://localhost:4566 sqs create-queue --queue-name static-file-s3-event-notification-queue || true+ aws --endpoint-url=http://localhost:4566 sqs create-queue --queue-name reminder-dispatch-queue || true@echo "SQS queues created"+# Fan out every reminder that is currently due, once.+#+# In dev and prod an EventBridge rule puts this same payload on the queue every+# minute. There is no EventBridge locally, so nothing fires until you send it —+# either once with this, or on a loop with `tick_reminder_sweeps`.+poke_reminder_sweep:+ #!/usr/bin/env bash+ set -euo pipefail+ url=$(aws --endpoint-url=http://localhost:4566 sqs get-queue-url \+ --queue-name reminder-dispatch-queue --query QueueUrl --output text)+ aws --endpoint-url=http://localhost:4566 sqs send-message \+ --queue-url "$url" --message-body '{"operation":"sweep"}' >/dev/null+ echo "reminder sweep enqueued"++# Stand in for the EventBridge schedule: sweep once a minute until interrupted.+tick_reminder_sweeps:+ #!/usr/bin/env bash+ set -euo pipefail+ echo "sweeping reminders every 60s; ctrl-c to stop"+ while true; do+ just poke_reminder_sweep+ sleep 60+ done+# Purge all messages from every SQS queue in LocalStackpurge_queues:#!/usr/bin/env bashdiff --git a/tooling/just/rust.just b/tooling/just/rust.justindex 2f444a7018..df653d461c 100644--- a/tooling/just/rust.just+++ b/tooling/just/rust.just@@ -85,6 +85,7 @@ setup_test_envs:echo "DATABASE_URL={{ DATABASE_URL }}" >> ./crates/teams/.envecho "DATABASE_URL={{ DATABASE_URL }}" >> ./crates/frecency/.envecho "DATABASE_URL={{ DATABASE_URL }}" >> ./crates/favorites/.env+ echo "DATABASE_URL={{ DATABASE_URL }}" >> ./crates/reminders/.envecho "DATABASE_URL={{ DATABASE_URL }}" >> ./crates/soup/.envecho "DATABASE_URL={{ DATABASE_URL }}" >> ./crates/email/.envecho "DATABASE_URL={{ DATABASE_URL }}" >> ./crates/system_properties/.envdiff --git a/tooling/xtask/crates/xtask_local/src/local/resources.rs b/tooling/xtask/crates/xtask_local/src/local/resources.rsindex f65b6796c1..e9a4419433 100644--- a/tooling/xtask/crates/xtask_local/src/local/resources.rs+++ b/tooling/xtask/crates/xtask_local/src/local/resources.rs@@ -191,6 +191,20 @@ pub const QUEUES: &[Queue] = &[name: macro_queues::StaticFileServiceS3EventQueueUrl::LOCAL,bindings: &[("STATIC_FILE_SERVICE_S3_EVENT_QUEUE_URL", Url)],},+ Queue {+ // Carries both the reminder sweep tick and the per-firing fan-out it+ // publishes. Consumed by cloud-storage-service's dispatch worker, which+ // tight-loops on receive errors if the queue is not there.+ //+ // No EventBridge locally — LocalStack has `events` disabled — so nothing+ // puts the minutely tick on this queue. `just poke_reminder_sweep` (or+ // `just tick_reminder_sweeps`) stands in for the schedule.+ name: macro_queues::ReminderDispatchQueue::LOCAL,+ bindings: &[(+ macro_queues::ReminderDispatchQueue::OVERRIDE_ENV_VAR_NAME,+ Url,+ )],+ },];/// Every local S3 bucket and the env var that references it.